Repository navigation
Expand file tree
/
Copy pathgithub.ts
More file actions
1741 lines (1668 loc) · 68.7 KB
/
Copy pathgithub.ts
File metadata and controls
1741 lines (1668 loc) · 68.7 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
// @ref LLP 0008#github-reporter-identity — the reporter's core problem: which PR comment is ours; identity is proven by author + marker, never marker alone
import { writeFile, mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { resolveTrustedTool, run } from "../core/exec.js";
import { errorMessage } from "../core/util.js";
import { parseUnifiedDiff } from "../core/diff.js";
import {
buildDiffLineIndex,
commentMarker,
inlineStubBody,
parseInlineMarkerFp,
parseReviewState,
renderAggregateMarkdown,
renderInlineCommentBody,
renderMarkdown,
} from "../core/render.js";
import type { LinkContext, ReviewState, ScopeReviewResult } from "../core/render.js";
import { matchReplies } from "../core/responses.js";
import type { ReplyComment } from "../core/responses.js";
import { dropStaleVerdict, feedbackApplied, feedbackNeedsPrAuthor } from "../core/adjudicate.js";
import type { AdjudicationItem } from "../core/adjudicate.js";
import {
applyPins,
collectPins,
fingerprintFinding,
scopedFingerprint,
SEVERITY_RANK,
} from "../core/schema.js";
import type {
CoordinatorOutput,
DismissalRecord,
FeedbackPin,
FeedbackRecord,
Finding,
} from "../core/schema.js";
import type { LoadedConfig } from "../config/schema.js";
import { appendStepSummary } from "../core/step-summary.js";
import type { Reporter } from "./reporter.js";
export interface DismissalResult {
dismissedCount: number;
matched: string[];
unmatched: string[];
}
export interface GitHubReporterOptions {
prNumber: number;
repo: string; // owner/repo
commentTag: string;
breakGlassMarker: string;
cwd?: string;
/**
* Prebuilt link context. When set, linkContextAsync() returns it directly and
* skips the two `gh` calls — the ci fan-out builds ONE context for all scopes.
*/
linkContext?: LinkContext;
/**
* Root-only author-feedback config (see LoadedConfig.feedback). Absent (the
* default for existing callers) or `mode: "off"` disables the whole path, so
* the reporter behaves exactly as before until a caller opts in.
*/
feedback?: LoadedConfig["feedback"];
/**
* Root-only inline-comment config (see LoadedConfig.inline). Absent ⇒ the
* reporter never touches PR review comments at all (zero extra API calls);
* present with `enabled: false` ⇒ no sync, but `clear()` still sweeps this
* tag's inline comments so a comment-mode switch or a disable cleans up.
*/
inline?: LoadedConfig["inline"];
/**
* The head commit this run reviews (the PR's immutable head OID, from the source's
* metadata). Feedback merging binds a stored verdict to the source it judged, so a
* verdict only carries forward while this matches what the record recorded. Absent —
* a caller that runs no review (the `ecr feedback` crawl, a dismissal re-render) or
* a source with no resolvable OID — reads as "unknown source": stored verdicts are
* dropped and re-judged rather than trusted, which costs budget but never hides a
* finding against source the rebuttal no longer fits.
*/
headSha?: string;
/**
* Identity override: treat comments authored by THIS login as the reviewer's
* own, instead of resolving the current `gh` identity. Needed by the
* `ecr feedback` crawl on a developer machine: the reviewer comment was posted
* by CI (`github-actions[bot]` under the default token), so matching the local
* human login would find no comment on any PR. Read-only callers only — a
* posting reporter must keep the real identity or it would edit someone
* else's comments.
*/
ownLogin?: string;
}
const MAINTAINER_ASSOCIATIONS = new Set(["OWNER", "MEMBER", "COLLABORATOR"]);
/**
* PR-author lookups shared across reporter INSTANCES, keyed by the exact PR they
* describe. Routed CI builds one GitHubReporter per scope comment (plus one for the
* aggregate comment), and every one of them would otherwise run its own `gh pr view` for
* the SAME PR. The key carries the checkout, the repo and the PR number, so a lookup can
* never leak across repos or PRs in one process (the `ecr feedback` crawl walks many
* PRs). The in-flight promise is stored, not just the result, so concurrent scopes share
* one call.
*/
const prAuthorByPr = new Map<string, Promise<string | null>>();
/** Cache key for prAuthorByPr. Newline-joined with the free-form part (the checkout
* path) LAST: a PR number is digits and a repo is `owner/name`, neither of which can
* contain a newline, so two different PRs can never collide on one key. Exported for
* tests. */
export function prAuthorCacheKey(repo: string, prNumber: number, cwd?: string): string {
return `${prNumber}\n${repo}\n${cwd ?? ""}`;
}
/**
* Run `resolve` at most once per PR for the lifetime of the process — but cache only a
* SUCCESSFUL answer. A `gh pr view` that fails (rate limit, network blip) resolves to
* null, and caching that null would make one transient error fail-close every later
* scope of the same run: routed CI builds a reporter per scope, all reading this map,
* so every reply would be marked `author: false` and the adjudicated clear path could
* not fire again for the whole process. The entry is therefore removed once the promise
* settles to null (or rejects, which leaves nothing dangling either), so the next scope
* retries. Concurrency is unchanged: the in-flight promise is what's stored, so
* simultaneous scopes still join one call rather than each firing their own. Exported
* for tests (the reporter's own call path needs `gh`).
*/
export function sharedPrAuthor(
key: string,
resolve: () => Promise<string | null>,
): Promise<string | null> {
const cached = prAuthorByPr.get(key);
if (cached) {
return cached;
}
// Only ever forget OUR entry: a later call may already have started a new lookup.
const forget = (settled: Promise<string | null>): void => {
if (prAuthorByPr.get(key) === settled) {
prAuthorByPr.delete(key);
}
};
const pending: Promise<string | null> = resolve().then(
(login) => {
if (login == null) {
forget(pending);
}
return login;
},
(error: unknown) => {
forget(pending);
throw error;
},
);
prAuthorByPr.set(key, pending);
return pending;
}
export interface IssueComment {
id: number;
body?: string;
author_association?: string;
/** The comment's author. GitHub sets this from the authenticated identity; it
* cannot be forged, so it — not the public body marker — is the identity signal. */
user?: { login?: string };
/** Permalink to the comment, used as the reply link on an annotated finding. */
html_url?: string;
}
/** One PR review (inline/diff) comment, as the pulls comments API returns it. */
export interface ReviewCommentApi {
id: number;
body?: string;
path?: string;
line?: number | null;
user?: { login?: string };
html_url?: string;
/** Present on replies; points at the thread's root comment. */
in_reply_to_id?: number;
author_association?: string;
}
/**
* Burst-collapsing cache over the paginated review-comments listing, shared across
* reporter INSTANCES per PR (same motivation and key shape as prAuthorByPr): routed
* single-mode CI builds a fresh reporter per scope for its clear() reconciliation,
* and per-instance caching would re-fetch the identical list once per scope. The
* short TTL and mutation invalidation mirror fetchAllComments.
*/
const reviewCommentsByPr = new Map<string, { at: number; comments: Promise<ReviewCommentApi[]> }>();
/** An existing inline comment of OURS (author + anchored marker), as the planner sees it. */
export interface ExistingInlineComment {
id: number;
fp: string;
body: string;
url?: string;
/** Any listed comment replies to it (`in_reply_to_id` === its id). */
hasReplies: boolean;
}
/** What one inline sync run will do. Bodies are rendered by the executor. */
export interface InlineSyncPlan {
/** Findings to POST a new inline comment for (needs a commit id). */
create: Array<{ fp: string; finding: Finding }>;
/** Live threads whose body converges to the finding's current render. */
patch: Array<{ comment: ExistingInlineComment; finding: Finding }>;
/** No-longer-tracked threads WITH replies: patch to the neutral stub. */
stub: ExistingInlineComment[];
/** No-longer-tracked threads with no replies (and older duplicates): delete. */
remove: ExistingInlineComment[];
}
// @ref LLP 0011#suppression-is-never-silent [constrained-by] — leaving the inline set is
// not resolution: teardown only stubs/deletes when the caller proved the target set is
// complete, and the stub text (see inlineStubBody) never claims resolved/dismissed
/**
* Decide the inline mutations for one sync, purely. `targets` are the ACTIVE,
* diff-anchored findings; `existing` are OUR live inline comments.
*
* The cap is STICKY and deterministic: candidates order by severity rank then fp,
* and fps that already have a live thread fill slots before new ones are admitted —
* a live thread is never evicted (and its replies destroyed) just to create a
* different one, and a tie at the boundary cannot flip membership run to run.
*
* `teardown: false` (a failed/partial/carried run whose target set may be
* incomplete) makes the plan additive-only: no stubs, no deletes of live threads —
* except older DUPLICATES of a kept fp (a crash window between create and list),
* which are ours and redundant whatever the target set says.
*/
export function planInlineSync(opts: {
targets: Array<{ fp: string; finding: Finding }>;
existing: ExistingInlineComment[];
maxComments: number;
teardown: boolean;
}): InlineSyncPlan {
const ordered = [...opts.targets].sort(
(a, b) =>
SEVERITY_RANK[a.finding.severity] - SEVERITY_RANK[b.finding.severity] ||
a.fp.localeCompare(b.fp),
);
// Newest comment per fp is the live thread; older ones are duplicates.
const liveByFp = new Map<string, ExistingInlineComment>();
const duplicates: ExistingInlineComment[] = [];
for (const comment of [...opts.existing].sort((a, b) => a.id - b.id)) {
const previous = liveByFp.get(comment.fp);
if (previous) {
duplicates.push(previous);
}
liveByFp.set(comment.fp, comment);
}
const selected: Array<{ fp: string; finding: Finding }> = [];
for (const entry of ordered) {
if (selected.length >= opts.maxComments) {
break;
}
if (liveByFp.has(entry.fp)) {
selected.push(entry);
}
}
for (const entry of ordered) {
if (selected.length >= opts.maxComments) {
break;
}
if (!liveByFp.has(entry.fp)) {
selected.push(entry);
}
}
const plan: InlineSyncPlan = { create: [], patch: [], stub: [], remove: [] };
const selectedFps = new Set(selected.map((entry) => entry.fp));
for (const entry of selected) {
const live = liveByFp.get(entry.fp);
if (live) {
plan.patch.push({ comment: live, finding: entry.finding });
} else {
plan.create.push(entry);
}
}
for (const [fp, live] of liveByFp) {
if (selectedFps.has(fp)) {
continue;
}
if (!opts.teardown) {
continue;
}
if (live.hasReplies) {
plan.stub.push(live);
} else {
plan.remove.push(live);
}
}
// A duplicate with human replies is still a conversation: stub it like any other
// retired thread rather than deleting what people wrote in.
for (const duplicate of duplicates) {
if (duplicate.hasReplies) {
plan.stub.push(duplicate);
} else {
plan.remove.push(duplicate);
}
}
return plan;
}
/** `\r\n`-insensitive body comparison: the API returns CRLF-normalized bodies. */
export function inlineBodiesEqual(a: string, b: string): boolean {
return a.replace(/\r\n/g, "\n") === b.replace(/\r\n/g, "\n");
}
/** Does a body's UNQUOTED text carry this marker? Quoted (`> `) lines are the
* replier quoting US, which is a genuine reply, not our comment. */
export function hasUnquotedMarker(body: string, marker: string): boolean {
return body.split("\n").some((line) => !/^\s*>/.test(line) && line.includes(marker));
}
/**
* The findings the main comment renders in its ACTIVE list — not dismissed, not
* cleared by an applied reply, not requalified — which is exactly the inline sync's
* target set. Mirrors the isDropped/kept split in renderMarkdown and
* renderAggregateMarkdown (first record per fp wins, like matchedFeedback there).
* Exported for tests.
*/
export function activeFindings(
withFp: Array<{ finding: Finding; fp: string }>,
dismissed: DismissalRecord[],
records: FeedbackRecord[],
): Array<{ finding: Finding; fp: string }> {
const dismissedFps = new Set(dismissed.map((record) => record.fp));
const appliedFps = new Set<string>();
const seen = new Set<string>();
for (const record of records) {
if (!seen.has(record.fp)) {
seen.add(record.fp);
if (record.applied) {
appliedFps.add(record.fp);
}
}
}
return withFp.filter(
({ finding, fp }) => !dismissedFps.has(fp) && !appliedFps.has(fp) && !finding.requalifiedBy,
);
}
/** A per-render COPY of the link context carrying this run's inline thread URLs —
* the routed ci flow shares one LinkContext across reporters, so never mutate it. */
function withInlineUrls(link: LinkContext, inlineUrls: Map<string, string>): LinkContext {
return inlineUrls.size > 0 ? { ...link, inlineUrls } : link;
}
// @ref LLP 0011#suppression-is-never-silent [implements] — a verdict carries only while BOTH the reply and the reviewed source are unchanged
/**
* Carry a decision already recorded in the prior comment state onto the freshly
* matched records. A **verdict** (and the `applied` it justified) is bound to the words
* it judged AND to the source it judged: it carries only while the newest reply is the
* SAME comment it was decided about and `dropStaleVerdict` agrees the head is
* unchanged. A newer reply answers different words; a newer head means the code the
* rebuttal relied on may be gone. Either way the reply is re-judged rather than trusted.
*
* Fresh records own the reply identity (author, comment id, link); the prior state owns
* the decision. A maintainer's `/undismiss` pin is NOT merged here — it belongs to the
* finding, lives in the comment state's own `pins` set, and is stamped back on by
* `applyPins` (which is what keeps it alive through a run that matches no reply at all).
*/
function mergeFeedback(
fresh: FeedbackRecord[],
previous: FeedbackRecord[],
headSha: string | undefined,
): FeedbackRecord[] {
const priorByFp = new Map(previous.map((record) => [record.fp, record]));
return fresh.map((record) => {
const prior = priorByFp.get(record.fp);
if (!prior || prior.commentId !== record.commentId) {
// No prior decision, or different words: nothing decided about the old comment
// carries.
return record;
}
return dropStaleVerdict(
{
...record,
...(prior.verdict !== undefined ? { verdict: prior.verdict } : {}),
...(prior.reason !== undefined ? { reason: prior.reason } : {}),
...(prior.sourceSha !== undefined ? { sourceSha: prior.sourceSha } : {}),
applied: prior.applied,
},
headSha,
);
});
}
// @ref LLP 0011#deterministic-matching [implements] — the pure core of matchAdjudicationItems: no IO, so it is unit-testable; the caller supplies the fetched state/replies
/**
* Pair each matched reply with the finding it answers and its raw reply text, carrying
* any prior verdict forward. Pure: the caller has already fetched `previousFeedback`
* (the comment's stored records) and `replies`. `fpOf` MUST key findings the same way
* that comment stores them (scope-namespaced for an aggregate comment, plain otherwise)
* or a prior verdict can never carry — its fp would not match the fresh record's.
* `headSha` is the source revision being reviewed: a stored verdict carries only when
* it judged that same revision (see mergeFeedback). `pins` is the comment's
* `/undismiss` set: it is stamped onto the matched records so a pinned finding is never
* re-judged and never re-cleared (a v3 comment's record-level flags migrate in through
* collectPins). Exported for tests.
*/
export function buildAdjudicationItems(
review: CoordinatorOutput,
previousFeedback: FeedbackRecord[],
replies: ReplyComment[],
fpOf: (finding: Finding) => string,
match: "quote" | "id" | "both",
headSha?: string,
pins?: FeedbackPin[],
): AdjudicationItem[] {
const withFp = review.findings.map((finding) => ({ finding, fp: fpOf(finding) }));
const { records } = applyPins(
mergeFeedback(matchReplies(replies, withFp, { match }), previousFeedback, headSha),
collectPins(pins, previousFeedback),
);
const findingByFp = new Map(withFp.map((entry) => [entry.fp, entry.finding]));
const bodyById = new Map(replies.map((reply) => [reply.id, reply.body]));
const items: AdjudicationItem[] = [];
for (const record of records) {
const finding = findingByFp.get(record.fp);
if (!finding) {
continue;
}
items.push({ finding, record, replyText: bodyById.get(record.commentId) ?? "" });
}
return items;
}
/**
* The findings a posted comment holds, keyed by the id that comment renders them under:
* scope-namespaced on an aggregate (comment:'single') comment, plain otherwise. This is
* both the valid-id set a `/dismiss` is checked against and the lookup that re-derives
* each feedback record's `applied` under the current config.
*/
function stateFindingsById(state: ReviewState): Map<string, Finding> {
const scopes = state.scopes;
if (scopes && scopes.length > 0) {
return new Map(
scopes.flatMap((scope) =>
scope.review.findings.map(
(finding) =>
[scopedFingerprint(scope.isDefault ? null : scope.scope, finding), finding] as const,
),
),
);
}
return new Map(state.review.findings.map((finding) => [fingerprintFinding(finding), finding]));
}
/** What a `/dismiss` or `/undismiss` turns the comment's state into. */
export interface DismissalStateUpdate {
dismissed: DismissalRecord[];
feedback: FeedbackRecord[];
pins: FeedbackPin[];
matched: string[];
unmatched: string[];
}
// @ref LLP 0011#the-pin-belongs-to-the-finding [implements] — `/undismiss` writes the pin into the state's own pin set (never only onto a reply record), and `/dismiss` is the maintainer action that lifts it
// @ref LLP 0011#hard-floors-in-code [implements] — a re-render is a render: every kept record's `applied` is re-derived from feedbackApplied under the CURRENT config, never carried over as a stored fact
/**
* The pure state transition behind applyDismissal: which findings end up dismissed,
* which are pinned back to the active list, and what each feedback record's `applied`
* flag is under the config in force NOW. Exported for tests (the reporter's own path
* needs `gh`).
*
* Three rules meet here:
* - a `/dismiss` (an fp in `add`) is only recorded for an id this comment actually
* holds, and it LIFTS any pin on that finding — the same trusted hand deciding the
* opposite way;
* - a `/undismiss` (an fp in `remove`) restores a finding a REPLY cleared, not just a
* manual dismissal: it pins the finding so a later re-review recomputing `applied`
* from the still-present reply keeps it active;
* - every record's `applied` is then re-derived with `feedbackApplied` — the same single
* decision function every other render path uses. Passing a record through untouched
* would keep honoring the config of the run that stored it, so a repo that has since
* tightened `dismiss` (or widened `protectedCategories`) would leave an unrelated
* finding hidden until the next full review. A record whose finding is no longer in
* the comment keeps its stored flag, exactly as computeFeedback does.
*/
export function applyDismissalToState(
state: ReviewState,
add: string[],
remove: string[],
config: LoadedConfig["feedback"] | undefined,
by?: string,
reason?: string,
): DismissalStateUpdate {
const findingById = stateFindingsById(state);
const matched = add.filter((fp) => findingById.has(fp));
const unmatched = add.filter((fp) => !findingById.has(fp));
const dismissed: DismissalRecord[] = state.dismissed.filter(
(record) => !remove.includes(record.fp),
);
for (const fp of matched) {
if (!dismissed.some((record) => record.fp === fp)) {
dismissed.push({ fp, by, reason });
}
}
const records = state.feedback ?? [];
const removeSet = new Set(remove);
const addSet = new Set(matched);
const pins = collectPins(state.pins, records).filter((pin) => !addSet.has(pin.fp));
for (const record of records) {
if (removeSet.has(record.fp) && !pins.some((pin) => pin.fp === record.fp)) {
// Pinned against the reply that is current right now: that same reply must not
// lift the pin later, only a maintainer reply posted after it (see applyPins).
pins.push({ fp: record.fp, commentId: record.commentId });
}
}
const stamped = applyPins(records, pins);
const feedback = stamped.records.map((record) => {
const finding = findingById.get(record.fp);
// No feedback config ⇒ the feature is off for this caller, so nothing is applied;
// the record itself (who replied, any verdict) is still preserved.
if (!config) {
return { ...record, applied: false };
}
return finding ? { ...record, applied: feedbackApplied(finding, record, config) } : record;
});
return { dismissed, feedback, pins: stamped.pins, matched, unmatched };
}
/**
* The reviewer's OWN marker comments, oldest-first: carrying the marker AND authored
* by `ownLogin`. The body marker alone is not identity — it defaults to a hardcoded,
* public literal and is readable in the base-branch config, so anyone who can comment
* on the PR (the untrusted PR author included) could post a comment carrying it plus a
* forged embedded review state; a newest-marker-wins lookup would then adopt that
* state and carry its `dismissed` list forward, silently suppressing real findings.
* GitHub sets a comment's author from the authenticated identity and it cannot be
* spoofed, so matching on author closes that. When `ownLogin` is null the author
* cannot be confirmed, so NOTHING is treated as ours (fail closed). Pure; exported for
* tests.
*/
// @ref LLP 0008#github-reporter-identity [constrained-by] — marker-only matching would let a forged comment (from the untrusted PR author) carry forged dismissal state forward; author+marker is what makes identity unspoofable
export function selectOwnComments(
comments: IssueComment[],
marker: string,
ownLogin: string | null,
): IssueComment[] {
if (!ownLogin) {
return [];
}
return comments.filter(
(comment) => comment.body?.includes(marker) && comment.user?.login === ownLogin,
);
}
/**
* Maintains exactly one PR comment, updating it in place across re-reviews (and
* cleaning up duplicates) so the review converges instead of churning. Runs the
* break-glass check first. Comment-only: never calls the review-state APIs.
*/
export class GitHubReporter implements Reporter {
private readonly marker: string;
/** Memoized login of the account this reporter posts as (see resolveOwnLogin). */
private ownLoginResolution?: Promise<string | null>;
constructor(private readonly options: GitHubReporterOptions) {
this.marker = commentMarker(options.commentTag);
}
/**
* The login of the account this reporter comments as, so its own comment is
* recognized by AUTHOR (see selectOwnComments for why the body marker is not enough).
* Resolution: `gh api user` (a user/PAT token), else the scaffolded workflow's default
* GITHUB_TOKEN identity, `github-actions[bot]`, when running under Actions — an
* installation token can't read `/user`. Null when neither is available, which makes
* selectOwnComments treat no comment as ours (fail closed). Memoized: the identity is
* stable for the process, and every reporter method consults it.
*/
private resolveOwnLogin(): Promise<string | null> {
if (this.options.ownLogin) {
return Promise.resolve(this.options.ownLogin);
}
this.ownLoginResolution ??= (async () => {
try {
const gh = await resolveTrustedTool("gh");
const { stdout } = await run(gh, ["api", "user", "--jq", ".login"], {
cwd: this.options.cwd,
});
const login = stdout.trim();
if (login) {
return login;
}
} catch {
// The default GITHUB_TOKEN is an installation token: `/user` returns 403.
}
return process.env.GITHUB_ACTIONS ? "github-actions[bot]" : null;
})();
return this.ownLoginResolution;
}
/**
* The PR author's login, used to mark a reply as coming from the author (see
* replyComments) so the adjudicated clear path can gate on it. Resolved via
* `gh pr view --json author` and fail-soft — a null result marks no reply as the
* author's, so the adjudicated path clears nothing (fail closed), exactly like an
* unresolved own-login. Memoized per PR across reporter INSTANCES (see
* prAuthorByPr), not per instance: routed CI builds one reporter per scope for the
* same PR, and the author's login is a property of the PR, not of the reporter.
*/
private resolvePrAuthor(): Promise<string | null> {
const key = prAuthorCacheKey(this.options.repo, this.options.prNumber, this.options.cwd);
return sharedPrAuthor(key, async () => {
try {
const gh = await resolveTrustedTool("gh");
const { stdout } = await run(
gh,
[
"pr",
"view",
String(this.options.prNumber),
"--repo",
this.options.repo,
"--json",
"author",
"--jq",
".author.login",
],
{ cwd: this.options.cwd },
);
const login = stdout.trim();
return login || null;
} catch {
// No PR author resolvable (missing PR, API error): fail closed — no reply is
// treated as the author's, so nothing clears via the adjudicated path.
return null;
}
});
}
/** This reporter's own marker comments, author-verified (see selectOwnComments). */
private async ownComments(): Promise<IssueComment[]> {
const [comments, ownLogin] = await Promise.all([
this.fetchAllComments(),
this.resolveOwnLogin(),
]);
return selectOwnComments(comments, this.marker, ownLogin);
}
// @ref LLP 0008#comment-lifecycle [constrained-by] — gates on author_association (OWNER/MEMBER/COLLABORATOR), not on posting the marker string, so only a maintainer can skip review
async checkBreakGlass(): Promise<boolean> {
const comments = await this.fetchAllComments();
return comments.some(
(comment) =>
typeof comment.body === "string" &&
comment.body.includes(this.options.breakGlassMarker) &&
MAINTAINER_ASSOCIATIONS.has(comment.author_association ?? ""),
);
}
async postSkipNote(): Promise<void> {
await this.upsertComment(
`${this.marker}\n🤖 AI review skipped via \`${this.options.breakGlassMarker}\`.`,
);
}
/**
* Post/update the single-scope comment. When `feedback` is supplied (the
* adjudication path already matched + judged the replies) it is rendered as-is;
* otherwise the reporter matches live replies to this review's findings itself
* (annotate mode). Either way the feedback path fails soft — it never blocks the
* comment from being posted.
*/
async report(
review: CoordinatorOutput,
feedback?: FeedbackRecord[],
inputHash?: string,
): Promise<void> {
// Carry forward any per-PR dismissals recorded in the existing comment so they
// survive re-reviews (a dismissed finding stays in the collapsed section).
const existing = await this.findExistingComment();
const state = existing ? parseReviewState(existing.body, this.options.commentTag) : null;
const dismissed = state?.dismissed ?? [];
const withFp = review.findings.map((finding) => ({
finding,
fp: fingerprintFinding(finding),
}));
// The `/undismiss` pins carry on every render, whether or not this run matched a
// reply for the pinned finding — the records may come and go, the pin does not.
const priorRecords = state?.feedback ?? [];
const pinsIn = collectPins(state?.pins, priorRecords);
const { records, pins } = feedback
? applyPins(feedback, pinsIn)
: await this.computeFeedback(withFp, priorRecords, pinsIn);
const link = await this.linkContextAsync();
// Inline threads converge to the ACTIVE findings before the body renders, so
// the short form can link each one. A failed run (couldNotComplete) posts an
// empty findings list that proves nothing — additive-only, no teardown.
const inlineUrls = await this.syncInline(activeFindings(withFp, dismissed, records), link, {
teardown: review.couldNotComplete !== true,
});
await this.upsertComment(
renderMarkdown(
review,
this.options.commentTag,
dismissed,
withInlineUrls(link, inlineUrls),
records,
pins,
inputHash,
),
);
}
/**
* Post/update the aggregate multi-scope comment (comment:'single' mode).
* `opts.inlineTeardown: false` marks a run whose result set is NOT the complete
* truth about the PR — a `--scopes` partial run carries the other scopes out of
* (possibly truncated) embedded state — so the inline sync must not stub/delete
* threads it merely cannot see. Any failed scope forces the same, since its
* findings list is empty without being clean.
*/
async reportAggregate(
results: ScopeReviewResult[],
unmatchedFiles: string[],
feedback?: FeedbackRecord[],
opts?: { inlineTeardown?: boolean },
): Promise<void> {
const existing = await this.findExistingComment();
const state = existing ? parseReviewState(existing.body, this.options.commentTag) : null;
const dismissed = state?.dismissed ?? [];
// Feedback is keyed by the SAME scope-namespaced id the aggregate comment
// renders, so a record can never drift across scopes.
const withFp = results.flatMap((result) =>
result.review.findings.map((finding) => ({
finding,
fp: scopedFingerprint(result.isDefault ? null : result.scope, finding),
})),
);
const priorRecords = state?.feedback ?? [];
const pinsIn = collectPins(state?.pins, priorRecords);
const { records, pins } = feedback
? applyPins(feedback, pinsIn)
: await this.computeFeedback(withFp, priorRecords, pinsIn);
const link = await this.linkContextAsync();
const teardown =
(opts?.inlineTeardown ?? true) &&
results.every((result) => result.review.couldNotComplete !== true);
const inlineUrls = await this.syncInline(activeFindings(withFp, dismissed, records), link, {
teardown,
});
await this.upsertComment(
renderAggregateMarkdown(
results,
this.options.commentTag,
dismissed,
withInlineUrls(link, inlineUrls),
{ unmatchedFiles },
records,
pins,
),
);
}
/**
* Pair each matched PR reply with the finding it answers and its raw reply text —
* the input the adjudication step (core/review.ts) judges against the source. Any
* verdict already decided in the prior comment state is carried forward (so a reply
* is not re-judged for the same words). The reply text rides only the transient
* AdjudicationItem: it feeds the adjudicator prompt and is never stored on a record
* or rendered (see FeedbackRecordSchema). Gated on `mode !== "off"`. A fetch/parse
* error THROWS — the caller (runReview's feedback step) catches it and continues
* without records, which lets report() fall back to computeFeedback and preserve
* the previously recorded state; returning `[]` here would wipe it instead.
*
* `fpOf` MUST key findings the same way the comment this review lands in stores its
* feedback: scope-namespaced for the aggregate (comment:'single') comment, plain
* for a single/per-scope one. A mismatch would leave every fresh record keyed
* differently from the prior state, so mergeFeedback would carry no verdict and the
* budget would be re-spent judging the same words each run.
*/
async matchAdjudicationItems(
review: CoordinatorOutput,
fpOf: (finding: Finding) => string = fingerprintFinding,
): Promise<AdjudicationItem[]> {
const config = this.options.feedback;
if (!config || config.mode === "off") {
return [];
}
// Deliberately NOT wrapped in a swallow-all: a fetch error here must propagate so
// runReview's own catch leaves `feedback` undefined — then report() falls back to
// computeFeedback, whose error path preserves the previously recorded state. A
// caught `[]` instead reads downstream as "there are no replies" and would wipe
// prior annotations (and un-hide reply-cleared findings) on a transient API error.
const existing = await this.findExistingComment();
const state = existing ? parseReviewState(existing.body, this.options.commentTag) : null;
const replies = await this.replyComments();
return buildAdjudicationItems(
review,
state?.feedback ?? [],
replies,
fpOf,
config.match,
this.options.headSha,
state?.pins,
);
}
/**
* Read what humans pushed back on for THIS PR from the comment already posted:
* decode its embedded findings, match the non-bot replies, and merge any prior
* verdict. Works retroactively — the bot comment embeds its own findings, so no
* re-review is needed. `ecr feedback` crawls history through this. Fails soft:
* missing/unparseable comment ⇒ empty result, never a throw.
*/
async collectFeedback(): Promise<{
findings: Array<{ finding: Finding; fp: string }>;
records: FeedbackRecord[];
}> {
try {
const existing = await this.findExistingComment();
const state = existing ? parseReviewState(existing.body, this.options.commentTag) : null;
if (!state) {
return { findings: [], records: [] };
}
// An aggregate comment namespaces ids per scope; a single comment does not.
const withFp =
state.scopes && state.scopes.length > 0
? state.scopes.flatMap((scope) =>
scope.review.findings.map((finding) => ({
finding,
fp: scopedFingerprint(scope.isDefault ? null : scope.scope, finding),
})),
)
: state.review.findings.map((finding) => ({ finding, fp: fingerprintFinding(finding) }));
const replies = await this.replyComments();
// The retroactive crawl reports on any recorded pushback regardless of
// `mode`; only the match strategy is honored (default "both"). The crawl reviews
// nothing, so it has no head SHA to compare against: stored verdicts do not carry
// here. That costs the report nothing — it renders who replied and where, never a
// verdict — and keeps "unknown source" uniformly non-carrying.
const { records } = applyPins(
mergeFeedback(
matchReplies(replies, withFp, { match: this.options.feedback?.match ?? "both" }),
state.feedback ?? [],
this.options.headSha,
),
collectPins(state.pins, state.feedback ?? []),
);
return { findings: withFp, records };
} catch {
return { findings: [], records: [] };
}
}
// @ref LLP 0011#deterministic-matching [implements] — replies are matched to findings deterministically; the reporter never lets a model pick which finding a reply answers
/**
* The matched, merged feedback records to render, or none. Gated on
* `mode !== "off"` (the annotate/adjudicate switch) and wrapped so a fetch or
* match error degrades to the records already recorded — a review is never
* blocked by the feedback path.
*/
private async computeFeedback(
withFp: Array<{ finding: Finding; fp: string }>,
previous: FeedbackRecord[],
pinsIn: FeedbackPin[],
): Promise<{ records: FeedbackRecord[]; pins: FeedbackPin[] }> {
const config = this.options.feedback;
// `applied` is a function of the CURRENT config, never a stored fact: a carried
// record's flag was computed under the config of the run that stored it, so a
// repo flipping `dismiss` back to "never" (or `mode` to "off") must un-hide the
// finding on the next render, not keep honoring the old policy.
const findingByFp = new Map(withFp.map((entry) => [entry.fp, entry.finding]));
const reapply = (
records: FeedbackRecord[],
): { records: FeedbackRecord[]; pins: FeedbackPin[] } => {
// Stamp the pins first: `feedbackApplied` reads the pin off the record, and the
// set — not the record — is what says which finding a maintainer restored.
const stamped = applyPins(records, pinsIn);
return {
pins: stamped.pins,
records: stamped.records.map((record) => {
const finding = findingByFp.get(record.fp);
// With no feedback config at all, the feature is disabled, so nothing is
// applied — but the record itself (who replied, any verdict) is preserved.
if (!config) {
return { ...record, applied: false };
}
return finding
? { ...record, applied: feedbackApplied(finding, record, config) }
: record;
}),
};
};
// mode "off" (or no config) preserves the previously recorded records and only
// stops matching NEW replies. Returning [] here would let render's reviewState
// drop the feedback key entirely, permanently losing every recorded reply, verdict
// and reply-dismissal decision — mirror applyDismissal, which keeps feedback on a
// re-render. `applied` is still recomputed (→ false under "off"), so a finding a
// reply had cleared correctly returns to the active list.
if (!config || config.mode === "off") {
return reapply(previous);
}
try {
const replies = await this.replyComments();
return reapply(
mergeFeedback(
matchReplies(replies, withFp, { match: config.match }),
previous,
this.options.headSha,
),
);
} catch {
return reapply(previous);
}
}
// @ref LLP 0008#github-reporter-identity [implements] — a reply is any comment NOT authored by us and NOT carrying our marker; author identity (user.login) is what excludes our own, never the forgeable marker alone
/**
* The PR's human replies, as the matcher consumes them. Excludes comments we
* authored (by unspoofable `user.login`) and any comment carrying our marker, so
* our own footer is never read back as a reply; the `author_association` gives
* the maintainer flag and the PR author's login gives the `author` flag. When our
* login can't be resolved, the marker filter still keeps our own comments out.
*
* The PR-author lookup is an extra `gh` call, so it only runs when the flag can
* actually change an outcome — `dismiss: "adjudicated"` (see feedbackNeedsPrAuthor).
* Skipping it leaves every reply `author: false`, the same fail-closed answer a
* failed lookup gives, and under any other `dismiss` value nothing reads the flag.
*/
private async replyComments(): Promise<ReplyComment[]> {
// Inline replies are read only when the reporter carries an ENABLED inline
// config: the `ecr feedback` crawl and every non-inline repo keep exactly the
// API footprint they had.
const inlineEnabled = this.options.inline?.enabled === true;
const [comments, ownLogin, prAuthor, reviewComments] = await Promise.all([
this.fetchAllComments(),
this.resolveOwnLogin(),
feedbackNeedsPrAuthor(this.options.feedback) ? this.resolvePrAuthor() : null,
inlineEnabled
? this.fetchAllReviewComments().catch(() => [] as ReviewCommentApi[])
: ([] as ReviewCommentApi[]),
]);
const out: ReplyComment[] = [];
for (const comment of comments) {
const login = comment.user?.login;
if (!login || (ownLogin && login === ownLogin)) {
continue;
}
if (comment.body?.includes(this.marker)) {
continue;
}
out.push({
id: comment.id,
body: comment.body ?? "",
login,
maintainer: MAINTAINER_ASSOCIATIONS.has(comment.author_association ?? ""),
// Trusted-for-adjudication identity: the reply is from the PR author. Derived
// from the unspoofable comment author, not the (public) marker or reply text.
author: prAuthor != null && login === prAuthor,
...(comment.html_url ? { url: comment.html_url } : {}),
});
}
if (inlineEnabled && reviewComments.length > 0) {
// fp per OUR top-level inline comment (author + anchored marker), so a reply
// threading to it names its finding structurally.
const fpByRootId = new Map<number, string>();
if (ownLogin) {
for (const comment of reviewComments) {
if (comment.in_reply_to_id != null || comment.user?.login !== ownLogin) {
continue;
}
const fp = parseInlineMarkerFp(comment.body ?? "", this.options.commentTag);
if (fp) {
fpByRootId.set(comment.id, fp);
}
}
}
const byId = new Map(reviewComments.map((comment) => [comment.id, comment]));
// `in_reply_to_id` points at the thread root, but chase a short chain anyway
// so an unexpected reply-to-reply shape still resolves.
const threadFpOf = (comment: ReviewCommentApi): string | undefined => {
let parentId = comment.in_reply_to_id;
for (let hop = 0; parentId != null && hop < 5; hop++) {
const fp = fpByRootId.get(parentId);
if (fp) {
return fp;
}
parentId = byId.get(parentId)?.in_reply_to_id;
}
return undefined;
};
for (const comment of reviewComments) {
const login = comment.user?.login;
if (!login || (ownLogin && login === ownLogin)) {
continue;
}
const body = comment.body ?? "";
// Unquoted-line marker tests only: a GitHub "Quote reply" copies our marker
// behind `> ` and is a genuine human reply that must still be matched.
if (
hasUnquotedMarker(body, this.marker) ||
body.split("\n").some((line) => !/^\s*>/.test(line) && line.includes(":inline:fp="))
) {