-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathnight-watch-pr-reviewer-cron.sh
More file actions
executable file
·1457 lines (1276 loc) · 52.4 KB
/
Copy pathnight-watch-pr-reviewer-cron.sh
File metadata and controls
executable file
·1457 lines (1276 loc) · 52.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
set -euo pipefail
# Night Watch PR Reviewer Cron Runner (project-agnostic)
# Usage: night-watch-pr-reviewer-cron.sh /path/to/project
#
# NOTE: This script expects environment variables to be set by the caller.
# The Node.js CLI will inject config values via environment variables.
# Required env vars (with defaults shown):
# NW_REVIEWER_MAX_RUNTIME=3600 - Maximum runtime in seconds (1 hour)
# NW_PROVIDER_CMD=claude - AI provider CLI to use (claude, codex, etc.)
# NW_DRY_RUN=0 - Set to 1 for dry-run mode (prints diagnostics only)
PROJECT_DIR="${1:?Usage: $0 /path/to/project}"
PROJECT_NAME=$(basename "${PROJECT_DIR}")
LOG_DIR="${PROJECT_DIR}/logs"
LOG_FILE="${LOG_DIR}/reviewer.log"
MAX_RUNTIME="${NW_REVIEWER_MAX_RUNTIME:-3600}" # 1 hour
MAX_LOG_SIZE="524288" # 512 KB
PROVIDER_CMD="${NW_PROVIDER_CMD:-claude}"
PROVIDER_LABEL="${NW_PROVIDER_LABEL:-}"
MIN_REVIEW_SCORE="${NW_MIN_REVIEW_SCORE:-80}"
BRANCH_PATTERNS_RAW="${NW_BRANCH_PATTERNS:-feat/,night-watch/}"
TARGET_PR="${NW_TARGET_PR:-}"
PARALLEL_ENABLED="${NW_REVIEWER_PARALLEL:-1}"
WORKER_MODE="${NW_REVIEWER_WORKER_MODE:-0}"
PRD_DIR_REL="${NW_PRD_DIR:-docs/PRDs/night-watch}"
if [[ "${PRD_DIR_REL}" = /* ]]; then
PRD_DIR="${PRD_DIR_REL}"
else
PRD_DIR="${PROJECT_DIR}/${PRD_DIR_REL}"
fi
# Retry configuration
REVIEWER_MAX_RETRIES="${NW_REVIEWER_MAX_RETRIES:-2}"
REVIEWER_RETRY_DELAY="${NW_REVIEWER_RETRY_DELAY:-30}"
REVIEWER_MAX_PRS_PER_RUN="${NW_REVIEWER_MAX_PRS_PER_RUN:-0}"
SCRIPT_START_TIME=$(date +%s)
# Normalize retry settings to safe numeric ranges
if ! [[ "${REVIEWER_MAX_RETRIES}" =~ ^[0-9]+$ ]]; then
REVIEWER_MAX_RETRIES="2"
fi
if ! [[ "${REVIEWER_RETRY_DELAY}" =~ ^[0-9]+$ ]]; then
REVIEWER_RETRY_DELAY="30"
fi
if ! [[ "${REVIEWER_MAX_PRS_PER_RUN}" =~ ^[0-9]+$ ]]; then
REVIEWER_MAX_PRS_PER_RUN="0"
fi
if [ "${REVIEWER_MAX_RETRIES}" -gt 10 ]; then
REVIEWER_MAX_RETRIES="10"
fi
if [ "${REVIEWER_RETRY_DELAY}" -gt 300 ]; then
REVIEWER_RETRY_DELAY="300"
fi
if [ "${REVIEWER_MAX_PRS_PER_RUN}" -gt 100 ]; then
REVIEWER_MAX_PRS_PER_RUN="100"
fi
mkdir -p "${LOG_DIR}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=night-watch-helpers.sh
source "${SCRIPT_DIR}/night-watch-helpers.sh"
PROJECT_RUNTIME_KEY=$(project_runtime_key "${PROJECT_DIR}")
PROVIDER_MODEL_DISPLAY=$(resolve_provider_model_display "${PROVIDER_CMD}" "${PROVIDER_LABEL}")
GLOBAL_LOCK_FILE="/tmp/night-watch-pr-reviewer-${PROJECT_RUNTIME_KEY}.lock"
if [ "${WORKER_MODE}" = "1" ] && [ -n "${TARGET_PR}" ]; then
LOCK_FILE="/tmp/night-watch-pr-reviewer-${PROJECT_RUNTIME_KEY}-pr-${TARGET_PR}.lock"
else
# NOTE: Lock file path must match reviewerLockPath() in src/utils/status-data.ts
LOCK_FILE="${GLOBAL_LOCK_FILE}"
fi
SCRIPT_TYPE="reviewer"
skip_if_job_paused "${SCRIPT_TYPE}" "${PROJECT_DIR}"
READY_FOR_REVIEW_LABEL="${NW_READY_FOR_REVIEW_LABEL:-ready-for-review}"
READY_FOR_REVIEW_MARKER_NAME="night-watch-ready-for-review"
READY_TO_MERGE_LABEL="${NW_PR_RESOLVER_READY_LABEL:-ready-to-merge}"
emit_result() {
local status="${1:?status required}"
local details="${2:-}"
if [ -n "${details}" ]; then
echo "NIGHT_WATCH_RESULT:${status}|${details}"
else
echo "NIGHT_WATCH_RESULT:${status}"
fi
}
is_pr_open() {
local pr_number="${1:?PR number required}"
local pr_state=""
pr_state=$(gh pr view "${pr_number}" --json state --jq '.state // ""' 2>/dev/null || echo "")
case "${pr_state}" in
OPEN)
return 0
;;
MERGED|CLOSED)
return 1
;;
esac
# Backward-compatible fallback for older gh versions or tests that do not
# support the state field. Treat an unknown/empty state as open only when the
# PR is still viewable by number.
gh pr view "${pr_number}" --json number >/dev/null 2>&1
}
require_provider_on_path() {
if ! ensure_provider_on_path "${PROVIDER_CMD}"; then
echo "ERROR: Provider '${PROVIDER_CMD}' not found in PATH or common installation locations" >&2
exit 127
fi
}
extract_review_score_from_text() {
local review_text="${1:-}"
printf '%s' "${review_text}" \
| grep -oP '(?:Overall\s+)?Score:\*?\*?\s*\d+/100' \
| tail -1 \
| grep -oP '\d+(?=/100)' || echo ""
}
build_ready_for_review_marker() {
local head_sha="${1:-}"
[ -z "${head_sha}" ] && return 1
printf '<!-- %s headRefOid:%s -->' "${READY_FOR_REVIEW_MARKER_NAME}" "${head_sha}"
}
has_ready_for_human_review_marker() {
local comments_text="${1:-}"
local head_sha="${2:-}"
local marker=""
marker=$(build_ready_for_review_marker "${head_sha}" || true)
[ -z "${marker}" ] && return 1
printf '%s\n' "${comments_text}" | grep -Fq "${marker}"
}
get_pr_comments() {
local pr_number="${1:?PR number required}"
{
gh pr view "${pr_number}" --json comments --jq '.comments[].body' 2>/dev/null || true
if [ -n "${REPO:-}" ]; then
gh api "repos/${REPO}/issues/${pr_number}/comments" --jq '.[].body' 2>/dev/null || true
fi
} | awk '!seen[$0]++'
}
get_pr_pending_review_feedback_count() {
local pr_number="${1:?PR number required}"
local review_decision=""
local change_request_count="0"
local unresolved_thread_count="0"
local repo="${REPO:-}"
local owner=""
local name=""
review_decision=$(gh pr view "${pr_number}" --json reviewDecision --jq '.reviewDecision // ""' 2>/dev/null || echo "")
change_request_count=$(gh api "repos/{owner}/{repo}/pulls/${pr_number}/reviews" \
--jq '[.[] | select(.state == "CHANGES_REQUESTED")] | length' 2>/dev/null || echo "0")
if ! [[ "${change_request_count}" =~ ^[0-9]+$ ]]; then
change_request_count="0"
fi
if [ -z "${repo}" ]; then
repo=$(gh repo view --json nameWithOwner --jq '.nameWithOwner' 2>/dev/null || echo "")
fi
if [[ "${repo}" == */* ]]; then
owner="${repo%%/*}"
name="${repo#*/}"
unresolved_thread_count=$(gh api graphql \
-F owner="${owner}" \
-F name="${name}" \
-F number="${pr_number}" \
-f query='
query($owner: String!, $name: String!, $number: Int!) {
repository(owner: $owner, name: $name) {
pullRequest(number: $number) {
reviewThreads(first: 100) {
nodes {
isResolved
}
}
}
}
}
' \
--jq '[.data.repository.pullRequest.reviewThreads.nodes[]? | select(.isResolved == false)] | length' \
2>/dev/null || echo "0")
if ! [[ "${unresolved_thread_count}" =~ ^[0-9]+$ ]]; then
unresolved_thread_count="0"
fi
fi
if [ "${unresolved_thread_count}" -gt 0 ]; then
echo "${unresolved_thread_count}"
return 0
fi
if [ "${change_request_count}" -gt 0 ]; then
echo "${change_request_count}"
return 0
fi
if [ "${review_decision}" = "CHANGES_REQUESTED" ]; then
echo "1"
return 0
fi
echo "0"
}
get_pr_head_ref_oid() {
local pr_number="${1:?PR number required}"
gh pr view "${pr_number}" --json headRefOid --jq '.headRefOid' 2>/dev/null || echo ""
}
clear_ready_for_human_review_label() {
local pr_number="${1:?PR number required}"
gh pr edit "${pr_number}" --remove-label "${READY_FOR_REVIEW_LABEL}" 2>/dev/null || true
}
ensure_ready_for_human_review_comment() {
local pr_number="${1:?PR number required}"
local final_score="${2:-}"
local head_sha="${3:-}"
local comments_text=""
local marker=""
local score_note=""
local short_sha=""
local body=""
[ -z "${head_sha}" ] && return 0
comments_text=$(get_pr_comments "${pr_number}")
if has_ready_for_human_review_marker "${comments_text}" "${head_sha}"; then
gh pr edit "${pr_number}" --add-label "${READY_FOR_REVIEW_LABEL}" 2>/dev/null || true
return 0
fi
marker=$(build_ready_for_review_marker "${head_sha}" || true)
short_sha=$(printf '%s' "${head_sha}" | cut -c1-12)
if [ -n "${final_score}" ]; then
score_note=" (score: ${final_score}/100)"
fi
body="${marker}
## ✅ Ready for Human Review
Night Watch reviewed this PR${score_note} at commit \`${short_sha}\` and found no automated fixes to apply for the current head.
This PR is ready for human review and merge."
gh pr comment "${pr_number}" --body "${body}" 2>/dev/null || true
gh pr edit "${pr_number}" --add-label "${READY_FOR_REVIEW_LABEL}" 2>/dev/null || true
}
# ── Global Job Queue Gate ────────────────────────────────────────────────────
# Atomically claim a DB slot or enqueue for later dispatch — no flock needed.
if [ "${NW_QUEUE_ENABLED:-0}" = "1" ]; then
if [ "${NW_QUEUE_INHERITED_SLOT:-0}" = "1" ]; then
:
elif [ "${NW_QUEUE_DISPATCHED:-0}" = "1" ]; then
arm_global_queue_cleanup
else
claim_or_enqueue "${SCRIPT_TYPE}" "${PROJECT_DIR}"
fi
fi
# ──────────────────────────────────────────────────────────────────────────────
emit_final_status() {
local exit_code="${1:?exit code required}"
local prs_csv="${2:-}"
local auto_merged="${3:-}"
local auto_merge_failed="${4:-}"
local attempts="${5:-1}"
local final_score="${6:-}"
local no_changes="${7:-0}"
local no_changes_prs="${8:-}"
local details=""
local prs_summary=""
local auto_merged_summary=""
local auto_merge_failed_summary=""
local final_score_summary=""
local final_score_line=""
prs_summary="${prs_csv:-none}"
auto_merged_summary="${auto_merged:-none}"
auto_merge_failed_summary="${auto_merge_failed:-none}"
final_score_summary="${final_score:-n/a}"
if [ -n "${final_score}" ]; then
final_score_line="Final score: ${final_score_summary}/100"
else
final_score_line="Final score: n/a"
fi
if [ "${exit_code}" -eq 0 ]; then
details="prs=${prs_csv}|auto_merged=${auto_merged}|auto_merge_failed=${auto_merge_failed}|attempts=${attempts}"
if [ -n "${final_score}" ]; then
details="${details}|final_score=${final_score}"
fi
if [ "${no_changes}" = "1" ]; then
details="${details}|no_changes_needed=1"
fi
if [ -n "${no_changes_prs}" ]; then
details="${details}|no_changes_prs=${no_changes_prs}"
fi
log "DONE: PR reviewer completed successfully"
if [ "${WORKER_MODE}" != "1" ]; then
if [ "${no_changes}" = "1" ]; then
send_telegram_status_message "✅ Night Watch Reviewer: ready for human review" "Project: ${PROJECT_NAME}
Provider (model): ${PROVIDER_MODEL_DISPLAY}
Processed PRs: ${prs_summary}
${final_score_line}
No automated fixes needed — ready for human review & merge."
else
send_telegram_status_message "🔍 Night Watch Reviewer: completed" "Project: ${PROJECT_NAME}
Provider (model): ${PROVIDER_MODEL_DISPLAY}
Processed PRs: ${prs_summary}
Attempts: ${attempts}
${final_score_line}
Auto-merged PRs: ${auto_merged_summary}
Auto-merge failed: ${auto_merge_failed_summary}"
fi
fi
emit_result "success_reviewed" "${details}"
elif [ "${exit_code}" -eq 124 ]; then
details="prs=${prs_csv}|attempts=${attempts}"
if [ -n "${final_score}" ]; then
details="${details}|final_score=${final_score}"
fi
log "TIMEOUT: PR reviewer timed out (runtime budget ${MAX_RUNTIME}s)"
if [ "${WORKER_MODE}" != "1" ]; then
send_telegram_status_message "🔍 Night Watch Reviewer: timeout" "Project: ${PROJECT_NAME}
Provider (model): ${PROVIDER_MODEL_DISPLAY}
Timeout: ${MAX_RUNTIME}s
Processed PRs: ${prs_summary}
Attempts: ${attempts}
${final_score_line}"
fi
emit_result "timeout" "${details}"
else
details="prs=${prs_csv}|attempts=${attempts}"
if [ -n "${final_score}" ]; then
details="${details}|final_score=${final_score}"
fi
log "FAIL: PR reviewer exited with code ${exit_code}"
if [ "${WORKER_MODE}" != "1" ]; then
send_telegram_status_message "🔍 Night Watch Reviewer: failed" "Project: ${PROJECT_NAME}
Provider (model): ${PROVIDER_MODEL_DISPLAY}
Exit code: ${exit_code}
Processed PRs: ${prs_summary}
Attempts: ${attempts}
${final_score_line}"
fi
emit_result "failure" "${details}"
fi
}
append_csv() {
local current="${1:-}"
local incoming="${2:-}"
if [ -z "${incoming}" ]; then
printf "%s" "${current}"
return 0
fi
if [ -z "${current}" ]; then
printf "%s" "${incoming}"
else
printf "%s,%s" "${current}" "${incoming}"
fi
}
provider_output_looks_invalid() {
local from_line="${1:-0}"
if [ ! -f "${LOG_FILE}" ]; then
return 1
fi
tail -n "+$((from_line + 1))" "${LOG_FILE}" 2>/dev/null \
| grep -Eqi \
'Unknown skill:|session is in a broken state|working directory .* no longer exists|Path ".*" does not exist|Please restart this session|failed to start LSP server plugin|spawn .* ENOENT'
}
truncate_for_prompt() {
local text="${1:-}"
local limit="${2:-7000}"
if [ "${#text}" -le "${limit}" ]; then
printf "%s" "${text}"
else
printf '%s\n\n[truncated to %s chars]' "${text:0:${limit}}" "${limit}"
fi
}
extract_linked_issue_numbers() {
local body="${1:-}"
printf '%s\n' "${body}" \
| grep -Eoi '(close[sd]?|fix(e[sd])?|resolve[sd]?)[[:space:]]*:?[[:space:]]*#[0-9]+' \
| grep -Eo '[0-9]+' \
| awk '!seen[$0]++' || true
}
find_prd_file_by_branch() {
local branch_name="${1:-}"
local branch_slug="${branch_name#*/}"
local branch_number=""
local candidate_dirs=()
local candidate=""
local base_name=""
local dir=""
if [ -z "${branch_slug}" ]; then
branch_slug="${branch_name}"
fi
[ -z "${branch_slug}" ] && return 1
if [ -d "${PRD_DIR}" ]; then
candidate_dirs+=("${PRD_DIR}")
fi
if [ -d "${PRD_DIR}/done" ]; then
candidate_dirs+=("${PRD_DIR}/done")
fi
[ "${#candidate_dirs[@]}" -eq 0 ] && return 1
for dir in "${candidate_dirs[@]}"; do
if [ -f "${dir}/${branch_slug}.md" ]; then
printf "%s" "${dir}/${branch_slug}.md"
return 0
fi
done
branch_number=$(printf '%s' "${branch_slug}" | grep -oE '^[0-9]+' || true)
for dir in "${candidate_dirs[@]}"; do
while IFS= read -r candidate; do
[ -z "${candidate}" ] && continue
base_name=$(basename "${candidate}" .md)
if [[ "${base_name}" == "${branch_slug}"* ]] || [[ "${branch_slug}" == "${base_name}"* ]]; then
printf "%s" "${candidate}"
return 0
fi
if [ -n "${branch_number}" ] && [[ "${base_name}" == "${branch_number}-"* ]]; then
printf "%s" "${candidate}"
return 0
fi
done < <(find "${dir}" -maxdepth 1 -type f -name '*.md' 2>/dev/null | sort)
done
return 1
}
build_prd_context_for_pr() {
local pr_number="${1:?PR number required}"
local pr_payload=""
local pr_title=""
local pr_branch=""
local pr_body=""
local pr_url=""
local issue_context=""
local issue_count=0
local issue_number=""
local issue_payload=""
local issue_title=""
local issue_body=""
local issue_excerpt=""
local prd_file=""
local prd_payload=""
local prd_excerpt=""
local prd_rel_path=""
local section=""
pr_payload=$(gh pr view "${pr_number}" --json title,headRefName,body,url 2>/dev/null || true)
pr_title=$(printf '%s' "${pr_payload}" | jq -r '.title // ""' 2>/dev/null || echo "")
pr_branch=$(printf '%s' "${pr_payload}" | jq -r '.headRefName // ""' 2>/dev/null || echo "")
pr_body=$(printf '%s' "${pr_payload}" | jq -r '.body // ""' 2>/dev/null || echo "")
pr_url=$(printf '%s' "${pr_payload}" | jq -r '.url // ""' 2>/dev/null || echo "")
if [ -n "${pr_body}" ]; then
while IFS= read -r issue_number; do
[ -z "${issue_number}" ] && continue
issue_count=$((issue_count + 1))
if [ "${issue_count}" -gt 2 ]; then
break
fi
issue_payload=$(gh issue view "${issue_number}" --json title,body,url 2>/dev/null || true)
issue_title=$(printf '%s' "${issue_payload}" | jq -r '.title // ""' 2>/dev/null || echo "")
issue_body=$(printf '%s' "${issue_payload}" | jq -r '.body // ""' 2>/dev/null || echo "")
[ -z "${issue_body}" ] && continue
issue_excerpt=$(truncate_for_prompt "${issue_body}" 4500)
issue_context="${issue_context}${issue_context:+$'\n\n'}Issue #${issue_number}: ${issue_title}
${issue_excerpt}"
done < <(extract_linked_issue_numbers "${pr_body}")
fi
if [ -z "${issue_context}" ] && [ -n "${pr_branch}" ]; then
prd_file=$(find_prd_file_by_branch "${pr_branch}" || true)
if [ -n "${prd_file}" ] && [ -f "${prd_file}" ]; then
prd_payload=$(cat "${prd_file}" 2>/dev/null || true)
if [ -n "${prd_payload}" ]; then
prd_excerpt=$(truncate_for_prompt "${prd_payload}" 4500)
if [[ "${prd_file}" == "${PROJECT_DIR}/"* ]]; then
prd_rel_path="${prd_file#${PROJECT_DIR}/}"
else
prd_rel_path="${prd_file}"
fi
fi
fi
fi
section="### PR #${pr_number}"
if [ -n "${pr_title}" ]; then
section="${section} — ${pr_title}"
fi
section="${section}
- branch: ${pr_branch:-unknown}"
if [ -n "${pr_url}" ]; then
section="${section}
- url: ${pr_url}"
fi
if [ -n "${issue_context}" ]; then
section="${section}
- context source: linked GitHub issue body
${issue_context}"
elif [ -n "${prd_excerpt}" ]; then
section="${section}
- context source: ${prd_rel_path}
${prd_excerpt}"
else
section="${section}
- context source: not found"
fi
printf "%s" "${section}"
}
build_prd_context_prompt() {
local pr_number=""
local entry=""
local combined=""
for pr_number in "$@"; do
[ -z "${pr_number}" ] && continue
entry=$(build_prd_context_for_pr "${pr_number}")
[ -z "${entry}" ] && continue
combined="${combined}${combined:+$'\n\n'}${entry}"
done
[ -z "${combined}" ] && return 0
printf '\n\n## PRD Context\nUse this product context while reviewing and fixing PRs.\n%s\n' "${combined}"
}
# Extract the latest review score from PR comments
# Returns empty string if no score found
get_pr_score() {
local pr_number="${1:?PR number required}"
local all_comments
all_comments=$(get_pr_comments "${pr_number}")
extract_review_score_from_text "${all_comments}"
}
# Count failed CI checks for a PR.
# Uses JSON fields when available (more reliable across check name/status formats),
# then falls back to text parsing for older/mocked gh outputs.
get_pr_failed_ci_checks() {
local pr_number="${1:?PR number required}"
local failed_count=""
failed_count="$(
gh pr checks "${pr_number}" --json bucket,state,conclusion --jq '
[ .[]
| (.bucket // "" | ascii_downcase) as $bucket
| (.state // "" | ascii_downcase) as $state
| (.conclusion // "" | ascii_downcase) as $conclusion
| select(
$bucket == "fail" or
$bucket == "cancel" or
$state == "failure" or
$state == "error" or
$state == "cancelled" or
$conclusion == "failure" or
$conclusion == "error" or
$conclusion == "cancelled" or
$conclusion == "timed_out" or
$conclusion == "action_required" or
$conclusion == "startup_failure" or
$conclusion == "stale"
)
] | length
' 2>/dev/null || true
)"
if [[ "${failed_count}" =~ ^[0-9]+$ ]]; then
echo "${failed_count}"
return 0
fi
failed_count=$(
gh pr checks "${pr_number}" 2>/dev/null \
| grep -Eci 'fail|error|cancel|timed[_ -]?out|action_required|startup_failure|stale' || true
)
if [[ "${failed_count}" =~ ^[0-9]+$ ]]; then
echo "${failed_count}"
else
echo "0"
fi
}
# Return a semicolon-separated summary of failing CI checks for a PR.
# Format: "<check name> [state=<state>, conclusion=<conclusion>]"
get_pr_failed_ci_summary() {
local pr_number="${1:?PR number required}"
local failed_summary=""
failed_summary="$(
gh pr checks "${pr_number}" --json name,bucket,state,conclusion --jq '
[ .[]
| (.bucket // "" | ascii_downcase) as $bucket
| (.state // "" | ascii_downcase) as $state
| (.conclusion // "" | ascii_downcase) as $conclusion
| select(
$bucket == "fail" or
$bucket == "cancel" or
$state == "failure" or
$state == "error" or
$state == "cancelled" or
$conclusion == "failure" or
$conclusion == "error" or
$conclusion == "cancelled" or
$conclusion == "timed_out" or
$conclusion == "action_required" or
$conclusion == "startup_failure" or
$conclusion == "stale"
)
| "\(.name // "unknown") [state=\(.state // "unknown"), conclusion=\(.conclusion // "unknown")]"
] | join("; ")
' 2>/dev/null || true
)"
if [ -n "${failed_summary}" ]; then
echo "${failed_summary}"
return 0
fi
# Fallback for older/mocked outputs where JSON fields aren't available.
failed_summary=$(
gh pr checks "${pr_number}" 2>/dev/null \
| grep -Ei 'fail|error|cancel|timed[_ -]?out|action_required|startup_failure|stale' \
| sed -e 's/^[[:space:]]*//' -e 's/[[:space:]][[:space:]]*/ /g' \
| paste -sd '; ' - || true
)
echo "${failed_summary}"
}
# Clean up reviewer-managed worktrees.
# - Always removes the caller's runner worktree when runner_scope is provided.
# - Only non-worker/controller processes perform broad cleanup to avoid
# parallel workers deleting each other's active worktrees.
cleanup_reviewer_worktrees() {
local runner_scope="${1:-}"
if [ -n "${runner_scope}" ]; then
cleanup_worktrees "${PROJECT_DIR}" "${runner_scope}"
fi
if [ "${WORKER_MODE}" = "1" ]; then
return 0
fi
# Remove per-PR reviewer worktrees created by prompts from older runs.
cleanup_worktrees "${PROJECT_DIR}" "${PROJECT_NAME}-nw-review-"
# Remove legacy reviewer worktree naming used in some older prompt variants.
local escaped_project_name
escaped_project_name=$(printf '%s\n' "${PROJECT_NAME}" | sed 's/[][(){}.^$*+?|\\/]/\\&/g')
git -C "${PROJECT_DIR}" worktree list --porcelain 2>/dev/null \
| grep '^worktree ' \
| awk '{print $2}' \
| while read -r wt; do
local wt_basename
wt_basename=$(basename "${wt}")
if printf '%s\n' "${wt_basename}" | grep -Eq "^${escaped_project_name}-pr-?[0-9]+$"; then
log "CLEANUP: Removing legacy reviewer worktree ${wt}"
git -C "${PROJECT_DIR}" worktree remove --force "${wt}" 2>/dev/null || true
fi
done || true
}
# Validate provider
if ! validate_provider "${PROVIDER_CMD}"; then
echo "ERROR: Unknown provider: ${PROVIDER_CMD}" >&2
exit 1
fi
rotate_log
log_separator
log "RUN-START: reviewer invoked project=${PROJECT_DIR} provider=${PROVIDER_CMD} worker=${WORKER_MODE} target_pr=${TARGET_PR:-all} parallel=${PARALLEL_ENABLED}"
log "CONFIG: max_runtime=${MAX_RUNTIME}s min_review_score=${MIN_REVIEW_SCORE} branch_patterns=${BRANCH_PATTERNS_RAW}"
if ! acquire_lock "${LOCK_FILE}"; then
emit_result "skip_locked"
exit 0
fi
cd "${PROJECT_DIR}"
if [ "${WORKER_MODE}" != "1" ]; then
send_telegram_status_message "🔍 Night Watch Reviewer: started" "Project: ${PROJECT_NAME}
Provider (model): ${PROVIDER_MODEL_DISPLAY}
Branch patterns: ${BRANCH_PATTERNS_RAW}
Target PR: ${TARGET_PR:-all matching}
Action: scanning open PRs for failing checks or low review scores."
fi
# Convert comma-separated branch prefixes into a regex that matches branch starts.
BRANCH_REGEX=""
IFS=',' read -r -a BRANCH_PATTERNS <<< "${BRANCH_PATTERNS_RAW}"
for pattern in "${BRANCH_PATTERNS[@]}"; do
trimmed_pattern=$(printf '%s' "${pattern}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
if [ -n "${trimmed_pattern}" ]; then
BRANCH_REGEX="${BRANCH_REGEX}${BRANCH_REGEX:+|}^${trimmed_pattern}"
fi
done
if [ -z "${BRANCH_REGEX}" ]; then
BRANCH_REGEX='^(feat/|night-watch/)'
fi
if [ -n "${TARGET_PR}" ]; then
OPEN_PRS=$(
if is_pr_open "${TARGET_PR}"; then
echo "1"
else
echo "0"
fi
)
else
OPEN_PRS=$(
{ gh pr list --state open --json headRefName --jq '.[].headRefName' 2>/dev/null || true; } \
| { grep -E "${BRANCH_REGEX}" || true; } \
| wc -l \
| tr -d '[:space:]'
)
fi
if [ "${OPEN_PRS}" -eq 0 ]; then
log "SKIP: No open PRs matching branch patterns (${BRANCH_PATTERNS_RAW})"
if [ "${WORKER_MODE}" != "1" ]; then
send_telegram_status_message "🔍 Night Watch Reviewer: no matching PRs" "Project: ${PROJECT_NAME}
Provider (model): ${PROVIDER_MODEL_DISPLAY}
Branch patterns: ${BRANCH_PATTERNS_RAW}
Target PR: ${TARGET_PR:-all matching}
Result: 0 open PRs matched."
fi
emit_result "skip_no_open_prs"
exit 0
fi
NEEDS_WORK=0
REPO=$(gh repo view --json nameWithOwner --jq '.nameWithOwner' 2>/dev/null || echo "")
PRS_NEEDING_WORK=""
SKIPPED_ALREADY_REVIEWED_CURRENT_HEAD=0
while IFS=$'\t' read -r pr_number pr_branch pr_labels; do
local_ready_for_review_label_present=0
current_head_sha=""
all_comments=""
latest_score=""
if [ -z "${pr_number}" ] || [ -z "${pr_branch}" ]; then
continue
fi
if [ -n "${TARGET_PR}" ] && [ "${pr_number}" != "${TARGET_PR}" ]; then
continue
fi
if [ -z "${TARGET_PR}" ] && ! printf '%s\n' "${pr_branch}" | grep -Eq "${BRANCH_REGEX}"; then
continue
fi
if csv_has_label "${pr_labels:-}" "${READY_TO_MERGE_LABEL}"; then
log "INFO: PR #${pr_number} (${pr_branch}) is labeled ${READY_TO_MERGE_LABEL}; skipping automated review"
continue
fi
if printf '%s\n' "${pr_labels:-}" | tr ',' '\n' | grep -Fxq 'needs-human-review'; then
log "INFO: PR #${pr_number} (${pr_branch}) is labeled needs-human-review; skipping automated review"
continue
fi
if csv_has_label "${pr_labels:-}" "${NW_EXECUTOR_PARTIAL_LABEL}"; then
log "INFO: PR #${pr_number} (${pr_branch}) is labeled ${NW_EXECUTOR_PARTIAL_LABEL}; waiting for executor to finish"
continue
fi
if csv_has_label "${pr_labels:-}" "${READY_FOR_REVIEW_LABEL}"; then
local_ready_for_review_label_present=1
fi
# Merge-conflict signal: this PR needs action even if CI and score look fine.
MERGE_STATE=$(gh pr view "${pr_number}" --json mergeStateStatus --jq '.mergeStateStatus' 2>/dev/null || echo "")
if [ "${MERGE_STATE}" = "DIRTY" ] || [ "${MERGE_STATE}" = "CONFLICTING" ]; then
if [ "${local_ready_for_review_label_present}" -eq 1 ]; then
log "INFO: PR #${pr_number} (${pr_branch}) is actionable again; removing stale ${READY_FOR_REVIEW_LABEL} label"
clear_ready_for_human_review_label "${pr_number}"
fi
log "INFO: PR #${pr_number} (${pr_branch}) has merge conflicts (${MERGE_STATE})"
NEEDS_WORK=1
PRS_NEEDING_WORK="${PRS_NEEDING_WORK} #${pr_number}"
continue
fi
current_head_sha=$(get_pr_head_ref_oid "${pr_number}")
all_comments=$(get_pr_comments "${pr_number}")
latest_score=$(extract_review_score_from_text "${all_comments}")
if [ -z "${latest_score}" ]; then
if [ "${local_ready_for_review_label_present}" -eq 1 ]; then
log "INFO: PR #${pr_number} (${pr_branch}) needs a fresh review; removing stale ${READY_FOR_REVIEW_LABEL} label"
clear_ready_for_human_review_label "${pr_number}"
fi
log "INFO: PR #${pr_number} (${pr_branch}) has no review score yet — needs initial review"
NEEDS_WORK=1
PRS_NEEDING_WORK="${PRS_NEEDING_WORK} #${pr_number}"
continue
elif [ "${latest_score}" -lt "${MIN_REVIEW_SCORE}" ]; then
if [ "${local_ready_for_review_label_present}" -eq 1 ]; then
log "INFO: PR #${pr_number} (${pr_branch}) fell below review threshold; removing stale ${READY_FOR_REVIEW_LABEL} label"
clear_ready_for_human_review_label "${pr_number}"
fi
log "INFO: PR #${pr_number} (${pr_branch}) has review score ${latest_score}/100 (threshold: ${MIN_REVIEW_SCORE})"
NEEDS_WORK=1
PRS_NEEDING_WORK="${PRS_NEEDING_WORK} #${pr_number}"
continue
fi
PENDING_REVIEW_FEEDBACK_COUNT=$(get_pr_pending_review_feedback_count "${pr_number}")
if [ "${PENDING_REVIEW_FEEDBACK_COUNT}" -gt 0 ]; then
if [ "${local_ready_for_review_label_present}" -eq 1 ]; then
log "INFO: PR #${pr_number} (${pr_branch}) has pending review feedback; removing stale ${READY_FOR_REVIEW_LABEL} label"
clear_ready_for_human_review_label "${pr_number}"
fi
log "INFO: PR #${pr_number} (${pr_branch}) has ${PENDING_REVIEW_FEEDBACK_COUNT} pending review feedback item(s)"
NEEDS_WORK=1
PRS_NEEDING_WORK="${PRS_NEEDING_WORK} #${pr_number}"
continue
fi
if has_ready_for_human_review_marker "${all_comments}" "${current_head_sha}"; then
SKIPPED_ALREADY_REVIEWED_CURRENT_HEAD=1
log "INFO: PR #${pr_number} (${pr_branch}) is already marked ready for human review at head ${current_head_sha:0:12}; skipping repeat automated review"
continue
fi
FAILED_CHECKS=$(get_pr_failed_ci_checks "${pr_number}")
if [ "${FAILED_CHECKS}" -gt 0 ]; then
if [ "${local_ready_for_review_label_present}" -eq 1 ]; then
log "INFO: PR #${pr_number} (${pr_branch}) is actionable again; removing stale ${READY_FOR_REVIEW_LABEL} label"
clear_ready_for_human_review_label "${pr_number}"
fi
FAILED_SUMMARY=$(get_pr_failed_ci_summary "${pr_number}")
if [ -n "${FAILED_SUMMARY}" ]; then
log "INFO: PR #${pr_number} (${pr_branch}) has ${FAILED_CHECKS} failed CI check(s): ${FAILED_SUMMARY}"
else
log "INFO: PR #${pr_number} (${pr_branch}) has ${FAILED_CHECKS} failed CI check(s)"
fi
NEEDS_WORK=1
PRS_NEEDING_WORK="${PRS_NEEDING_WORK} #${pr_number}"
fi
done < <(
gh pr list --state open --json number,headRefName,labels \
--jq '.[] | [.number, .headRefName, ((.labels // []) | map(.name) | join(","))] | @tsv' 2>/dev/null || true
)
if [ "${NEEDS_WORK}" -eq 0 ]; then
if [ "${SKIPPED_ALREADY_REVIEWED_CURRENT_HEAD}" -eq 1 ]; then
log "SKIP: All ${OPEN_PRS} open PR(s) already pass review threshold or have already been reviewed for their current head"
if [ "${WORKER_MODE}" != "1" ]; then
send_telegram_status_message "🔍 Night Watch Reviewer: nothing actionable" "Project: ${PROJECT_NAME}
Provider (model): ${PROVIDER_MODEL_DISPLAY}
Result: all ${OPEN_PRS} matching PRs either already pass review threshold or were already reviewed for their current head."
fi
emit_result "skip_no_actionable_prs"
else
log "SKIP: All ${OPEN_PRS} open PR(s) have passing CI and review score >= ${MIN_REVIEW_SCORE}"
if [ "${WORKER_MODE}" != "1" ]; then
send_telegram_status_message "🔍 Night Watch Reviewer: nothing to do" "Project: ${PROJECT_NAME}
Provider (model): ${PROVIDER_MODEL_DISPLAY}
Result: all ${OPEN_PRS} matching PRs already pass CI and review threshold (${MIN_REVIEW_SCORE})."
fi
emit_result "skip_all_passing"
fi
exit 0
fi
PRS_NEEDING_WORK=$(echo "${PRS_NEEDING_WORK}" \
| sed -e 's/^[[:space:]]*//' -e 's/[[:space:]][[:space:]]*/ /g' -e 's/[[:space:]]*$//')
PRS_NEEDING_WORK_CSV="${PRS_NEEDING_WORK// /,}"
if [ -n "${NW_DEFAULT_BRANCH:-}" ]; then
DEFAULT_BRANCH="${NW_DEFAULT_BRANCH}"
else
DEFAULT_BRANCH=$(detect_default_branch "${PROJECT_DIR}")
fi
log "START: Found PR(s) needing work:${PRS_NEEDING_WORK}"
# Remove stale reviewer worktrees from previous interrupted runs.
# Worker processes skip broad cleanup to avoid parallel interference.
cleanup_reviewer_worktrees
# Convert "#12 #34" into ["12", "34"] for worker fan-out.
PR_NUMBER_ARRAY=()
for pr_token in ${PRS_NEEDING_WORK}; do
PR_NUMBER_ARRAY+=("${pr_token#\#}")
done
if [ "${REVIEWER_MAX_PRS_PER_RUN}" -gt 0 ] && [ "${#PR_NUMBER_ARRAY[@]}" -gt "${REVIEWER_MAX_PRS_PER_RUN}" ]; then
log "LIMIT: Restricting reviewer run to first ${REVIEWER_MAX_PRS_PER_RUN} PR(s) out of ${#PR_NUMBER_ARRAY[@]} needing work"
PR_NUMBER_ARRAY=("${PR_NUMBER_ARRAY[@]:0:${REVIEWER_MAX_PRS_PER_RUN}}")
PRS_NEEDING_WORK=""
for pr_number in "${PR_NUMBER_ARRAY[@]}"; do
PRS_NEEDING_WORK="${PRS_NEEDING_WORK}${PRS_NEEDING_WORK:+ }#${pr_number}"
done
PRS_NEEDING_WORK_CSV="${PRS_NEEDING_WORK// /,}"
fi
if [ -z "${TARGET_PR}" ] && [ "${WORKER_MODE}" != "1" ] && [ "${PARALLEL_ENABLED}" = "1" ] && [ "${#PR_NUMBER_ARRAY[@]}" -gt 1 ]; then
# Dry-run mode: print diagnostics and exit
if [ "${NW_DRY_RUN:-0}" = "1" ]; then
echo "=== Dry Run: PR Reviewer ==="
echo "Provider (model): ${PROVIDER_MODEL_DISPLAY}"
echo "Branch Patterns: ${BRANCH_PATTERNS_RAW}"
echo "Min Review Score: ${MIN_REVIEW_SCORE}"
echo "Max PRs Per Run: ${REVIEWER_MAX_PRS_PER_RUN}"
echo "Open PRs needing work:${PRS_NEEDING_WORK}"
echo "Default Branch: ${DEFAULT_BRANCH}"
echo "Parallel Workers: ${#PR_NUMBER_ARRAY[@]}"
echo "Timeout: ${MAX_RUNTIME}s"
exit 0
fi
require_provider_on_path
log "PARALLEL: Launching ${#PR_NUMBER_ARRAY[@]} reviewer worker(s)"
declare -a WORKER_PIDS=()
declare -a WORKER_PRS=()
declare -a WORKER_OUTPUTS=()
WORKER_IDX=0
WORKER_STAGGER_DELAY="${NW_REVIEWER_WORKER_STAGGER:-60}"
for pr_number in "${PR_NUMBER_ARRAY[@]}"; do
if [ "${WORKER_IDX}" -gt 0 ]; then
log "PARALLEL: Staggering worker launch by ${WORKER_STAGGER_DELAY}s (worker $((WORKER_IDX + 1))/${#PR_NUMBER_ARRAY[@]})"
sleep "${WORKER_STAGGER_DELAY}"
fi
worker_output=$(mktemp "/tmp/night-watch-pr-reviewer-${PROJECT_RUNTIME_KEY}-pr-${pr_number}.XXXXXX")
WORKER_OUTPUTS+=("${worker_output}")
WORKER_PRS+=("${pr_number}")
(
NW_TARGET_PR="${pr_number}" \
NW_REVIEWER_WORKER_MODE="1" \
NW_REVIEWER_PARALLEL="0" \
NW_QUEUE_INHERITED_SLOT="1" \
bash "${SCRIPT_DIR}/night-watch-pr-reviewer-cron.sh" "${PROJECT_DIR}" > "${worker_output}" 2>&1
) &
worker_pid=$!
WORKER_PIDS+=("${worker_pid}")
log "PARALLEL: Worker PID ${worker_pid} started for PR #${pr_number}"
WORKER_IDX=$((WORKER_IDX + 1))
done
EXIT_CODE=0
AUTO_MERGED_PRS=""
AUTO_MERGE_FAILED_PRS=""
ACTUAL_REVIEWED_PRS=""
NO_CHANGES_PRS=""
MAX_WORKER_ATTEMPTS=1
MAX_WORKER_FINAL_SCORE=""
for idx in "${!WORKER_PIDS[@]}"; do
worker_pid="${WORKER_PIDS[$idx]}"