crysk 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +610 -2
  3. package/bin/pr-hero.js +166 -0
  4. package/config/models/anthropic.json +5 -0
  5. package/dist/SKILL-7e3725zn.md +496 -0
  6. package/dist/SKILL-7q35wcaz.md +66 -0
  7. package/dist/SKILL-9at22381.md +74 -0
  8. package/dist/SKILL-ex2hxxh3.md +134 -0
  9. package/dist/adjudicator-dtg2axnh.md +86 -0
  10. package/dist/admission-config.example-a9vqmmad.json +9 -0
  11. package/dist/ci-admission-camfbx2b.md +122 -0
  12. package/dist/cli.js +42292 -0
  13. package/dist/consolidate-ac0mnfyj.md +24 -0
  14. package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
  15. package/dist/deep-review-logic-a6b1gczf.md +156 -0
  16. package/dist/deep-review-parity-0ec904db.md +120 -0
  17. package/dist/deep-review-reliability-qyakbjb9.md +125 -0
  18. package/dist/deep-review-resilience-3tz8y26e.md +118 -0
  19. package/dist/index.js +20190 -0
  20. package/dist/opencode-ci-7b0be64p.md +141 -0
  21. package/dist/review-refuter-j4e9gezy.md +71 -0
  22. package/dist/scout-yvp153q7.md +140 -0
  23. package/dist/summarizer-zca44nxa.md +18 -0
  24. package/dist/workflow-w1g9szna.yml +151 -0
  25. package/package.json +82 -4
  26. package/prompts/consolidate.md +24 -0
  27. package/prompts/default/PROVENANCE.md +18 -0
  28. package/prompts/default/deep-review-lifecycle.md +362 -0
  29. package/prompts/default/deep-review-logic.md +156 -0
  30. package/prompts/default/deep-review-parity.md +120 -0
  31. package/prompts/default/deep-review-reliability.md +125 -0
  32. package/prompts/default/deep-review-resilience.md +118 -0
  33. package/prompts/default/review-refuter.md +71 -0
  34. package/prompts/scout.md +140 -0
  35. package/prompts/summarizer.md +18 -0
  36. package/skills/crysk/SKILL.md +74 -0
  37. package/skills/crysk-ci-setup/SKILL.md +134 -0
  38. package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
  39. package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
  40. package/skills/crysk-ci-setup/references/ci-admission.md +122 -0
  41. package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
  42. package/skills/crysk-loop/SKILL.md +496 -0
  43. package/skills/crysk-loop/adjudicator.md +86 -0
  44. package/skills/crysk-pr/SKILL.md +66 -0
  45. package/src/agent-env.ts +1084 -0
  46. package/src/asset-manifest.ts +83 -0
  47. package/src/assets.d.ts +6 -0
  48. package/src/assets.ts +183 -0
  49. package/src/brand-paths.ts +155 -0
  50. package/src/brand.ts +255 -0
  51. package/src/ci/admission-ledger.ts +350 -0
  52. package/src/ci/classify-error.ts +73 -0
  53. package/src/ci/cli-record.ts +271 -0
  54. package/src/ci/force-comment.ts +39 -0
  55. package/src/ci/gates.ts +923 -0
  56. package/src/ci/outcome.ts +2181 -0
  57. package/src/ci/override.ts +187 -0
  58. package/src/ci/publish.ts +1639 -0
  59. package/src/ci/reporter.ts +626 -0
  60. package/src/ci/review-admission.ts +901 -0
  61. package/src/ci/review-levels.ts +310 -0
  62. package/src/ci/review-policy.ts +18 -0
  63. package/src/ci/review-risk.ts +184 -0
  64. package/src/ci/setup.ts +844 -0
  65. package/src/ci/trigger.ts +1353 -0
  66. package/src/cli.ts +348 -0
  67. package/src/commands/activity.ts +67 -0
  68. package/src/commands/ci-setup-questions.ts +397 -0
  69. package/src/commands/ci-setup.ts +381 -0
  70. package/src/commands/config.ts +99 -0
  71. package/src/commands/doctor.ts +108 -0
  72. package/src/commands/init.ts +139 -0
  73. package/src/commands/mcp.ts +10 -0
  74. package/src/commands/menu.ts +129 -0
  75. package/src/commands/post.ts +302 -0
  76. package/src/commands/skills.ts +83 -0
  77. package/src/commands/status.ts +173 -0
  78. package/src/commands/triage.ts +342 -0
  79. package/src/commands/uninstall.ts +37 -0
  80. package/src/commands/upgrade.ts +214 -0
  81. package/src/commands/usage.ts +98 -0
  82. package/src/compare/compare.ts +28 -0
  83. package/src/compare/floor-test.ts +471 -0
  84. package/src/compare/martian-adapter.ts +80 -0
  85. package/src/config/config.ts +267 -0
  86. package/src/corpus/corpus.ts +1094 -0
  87. package/src/corpus/preflight.ts +1789 -0
  88. package/src/diversity/accounting.ts +90 -0
  89. package/src/diversity/adjudication.ts +145 -0
  90. package/src/diversity/admission.ts +60 -0
  91. package/src/diversity/benchmark.ts +195 -0
  92. package/src/diversity/clustering.ts +285 -0
  93. package/src/diversity/errors.ts +7 -0
  94. package/src/diversity/identity.ts +285 -0
  95. package/src/diversity/index.ts +11 -0
  96. package/src/diversity/pipeline-integration.ts +448 -0
  97. package/src/diversity/projection.ts +57 -0
  98. package/src/diversity/self-contained.ts +68 -0
  99. package/src/diversity/target-validation.ts +179 -0
  100. package/src/doctor-migration.ts +209 -0
  101. package/src/doctor.ts +723 -0
  102. package/src/errors.ts +83 -0
  103. package/src/execution/admission.ts +75 -0
  104. package/src/execution/atomic-write.ts +35 -0
  105. package/src/execution/attempt-evidence.ts +415 -0
  106. package/src/execution/bucket-id.ts +136 -0
  107. package/src/execution/concurrency-limiter.ts +175 -0
  108. package/src/execution/contracts.ts +443 -0
  109. package/src/execution/failure-classification.ts +42 -0
  110. package/src/execution/failure-policy.ts +240 -0
  111. package/src/execution/harness.ts +2548 -0
  112. package/src/execution/settlement.ts +348 -0
  113. package/src/execution/spawned-process.ts +66 -0
  114. package/src/execution/spend-limiter.ts +424 -0
  115. package/src/execution/step-artifacts.ts +55 -0
  116. package/src/execution/usage-normalized.ts +469 -0
  117. package/src/git/git.ts +396 -0
  118. package/src/git/identity.ts +64 -0
  119. package/src/git/refs.ts +140 -0
  120. package/src/home-preflight.ts +443 -0
  121. package/src/home.ts +243 -0
  122. package/src/ignore-file.ts +336 -0
  123. package/src/ignore-read.ts +118 -0
  124. package/src/index.ts +34 -0
  125. package/src/legacy-launchd.ts +29 -0
  126. package/src/mcp/mcp.ts +150 -0
  127. package/src/mcp/preflight.ts +407 -0
  128. package/src/menu-context.ts +192 -0
  129. package/src/model/catalog.ts +251 -0
  130. package/src/model/exec-snapshots.ts +390 -0
  131. package/src/model/free-discovery.ts +302 -0
  132. package/src/model/provider-capabilities.ts +814 -0
  133. package/src/model/routing.ts +600 -0
  134. package/src/pr/admission.ts +847 -0
  135. package/src/pr/ci-admission-gate.ts +665 -0
  136. package/src/pr/ci-publish.ts +76 -0
  137. package/src/pr/discovery.ts +432 -0
  138. package/src/pr/inline.ts +507 -0
  139. package/src/pr/plan.ts +366 -0
  140. package/src/pr/posting.ts +115 -0
  141. package/src/pr/pr-status.ts +787 -0
  142. package/src/pr/pr.ts +3642 -0
  143. package/src/pr/preflight.ts +1031 -0
  144. package/src/pr/publish-outcome.ts +361 -0
  145. package/src/pr/range.ts +119 -0
  146. package/src/pr/reverts-preflight.ts +606 -0
  147. package/src/pr/reverts.ts +377 -0
  148. package/src/pr/review-pr.ts +927 -0
  149. package/src/pr/status.ts +154 -0
  150. package/src/pr/target.ts +388 -0
  151. package/src/pr/teardown.ts +437 -0
  152. package/src/pr/worktree-setup.ts +60 -0
  153. package/src/production-runtime.ts +1877 -0
  154. package/src/progress.ts +487 -0
  155. package/src/rereview/adjudicate.ts +89 -0
  156. package/src/rereview/classify.ts +362 -0
  157. package/src/rereview/identity.ts +211 -0
  158. package/src/rereview/plan.ts +308 -0
  159. package/src/rereview/prepare.ts +1025 -0
  160. package/src/rereview/state.ts +767 -0
  161. package/src/rereview/verify.ts +241 -0
  162. package/src/review/boundary.ts +105 -0
  163. package/src/review/consolidate.ts +246 -0
  164. package/src/review/dedupe.ts +368 -0
  165. package/src/review/drafts.ts +448 -0
  166. package/src/review/findings-conformance.ts +120 -0
  167. package/src/review/findings.ts +714 -0
  168. package/src/review/pipeline.ts +3977 -0
  169. package/src/review/preflight.ts +3575 -0
  170. package/src/review/prompt-set.ts +177 -0
  171. package/src/review/proof-refs.ts +187 -0
  172. package/src/review/report.ts +1821 -0
  173. package/src/review/review.ts +490 -0
  174. package/src/review/root-cause.ts +120 -0
  175. package/src/review/route-preflight.ts +289 -0
  176. package/src/review/run.ts +601 -0
  177. package/src/review/scout.ts +323 -0
  178. package/src/review/size-gate.ts +595 -0
  179. package/src/review/spec.ts +235 -0
  180. package/src/review/step-runner.ts +233 -0
  181. package/src/runner-authority.ts +596 -0
  182. package/src/security/binding-policy.ts +115 -0
  183. package/src/security/credential-broker.ts +773 -0
  184. package/src/security/evidence-redaction.ts +62 -0
  185. package/src/security/execution-authority.ts +27 -0
  186. package/src/security/redact.ts +71 -0
  187. package/src/security/workspace-read-broker.ts +466 -0
  188. package/src/server/client.ts +190 -0
  189. package/src/server/preflight.ts +217 -0
  190. package/src/server/server.ts +327 -0
  191. package/src/signal-handler.ts +50 -0
  192. package/src/store/activity.ts +413 -0
  193. package/src/store/backfill-preflight.ts +49 -0
  194. package/src/store/backfill.ts +141 -0
  195. package/src/store/gc-preflight.ts +206 -0
  196. package/src/store/gc.ts +424 -0
  197. package/src/store/metrics-preflight.ts +229 -0
  198. package/src/store/metrics.ts +236 -0
  199. package/src/store/preflight.ts +748 -0
  200. package/src/store/store.ts +693 -0
  201. package/src/system-tools.ts +355 -0
  202. package/src/transport-registry.ts +1124 -0
  203. package/src/transports/claude-code-cli.ts +1348 -0
  204. package/src/transports/opencode-admission.ts +515 -0
  205. package/src/transports/opencode-client.ts +3328 -0
  206. package/src/transports/opencode-evidence.ts +557 -0
  207. package/src/transports/opencode-mcp.ts +248 -0
  208. package/src/transports/opencode-sdk.ts +2294 -0
  209. package/src/transports/opencode-server.ts +535 -0
  210. package/src/triage/adjudication.ts +113 -0
  211. package/src/triage/reply.ts +125 -0
  212. package/src/triage/triage.ts +255 -0
  213. package/src/ui/activity.ts +173 -0
  214. package/src/ui/config-edit.ts +816 -0
  215. package/src/ui/config.ts +462 -0
  216. package/src/ui/menu.ts +1325 -0
  217. package/src/ui/plan.ts +1039 -0
  218. package/src/ui/primitives.ts +300 -0
  219. package/src/ui/progress.ts +298 -0
  220. package/src/ui/result.ts +552 -0
  221. package/src/ui/review-menu.ts +312 -0
  222. package/src/ui/select.ts +528 -0
  223. package/src/ui/tree.ts +178 -0
  224. package/src/uninstaller.ts +479 -0
  225. package/src/updater.ts +836 -0
  226. package/src/usage.ts +77 -0
  227. package/src/watch/preflight.ts +1389 -0
  228. package/src/watch/watch.ts +1235 -0
  229. package/src/wizard.ts +877 -0
@@ -0,0 +1,507 @@
1
+ // Inline review surface (ROADMAP B6) — pure. Three jobs, chained:
2
+ //
3
+ // 1. classifyAnchorability — will GitHub accept an inline review comment at
4
+ // this finding's path:line? (a PREDICTION — GitHub's 422 is the
5
+ // authority, not this function; see pr/pr.ts's recovery path)
6
+ // 2. matchPostedFindings — does this finding already have a comment from a
7
+ // prior run, so posting it again would duplicate?
8
+ // 3. buildPostPlan — combine both into what to actually post this run.
9
+ //
10
+ // NO I/O. Same contract as review/preflight.ts and pr/preflight.ts: no gh, no
11
+ // git, no network, no filesystem. cli.ts and pr/pr.ts execute what this module
12
+ // plans.
13
+
14
+ import type { PrHeroFindingRef } from "#compare/compare";
15
+ import { extractAnchor } from "#review/root-cause";
16
+ import { diffRecordPath, splitDiffRecords } from "#review/size-gate";
17
+ import { claimFingerprint, type ParsedFindingMarker } from "./preflight";
18
+
19
+ // The comparison ref plus the proof_refs posting needs to re-anchor an
20
+ // off-hunk finding onto a hunter-cited in-diff line (Musive #1727). Optional
21
+ // so existing PrHeroFindingRef[] call sites stay assignable; absent refs
22
+ // mean "this finding's own path:line is the only candidate".
23
+ export type PostableFinding = PrHeroFindingRef & {
24
+ proof_refs?: readonly string[];
25
+ };
26
+
27
+ // ---------------------------------------------------------------------------
28
+ // 1. Anchorability
29
+
30
+ export type Anchorability = "anchorable" | "un-anchorable";
31
+
32
+ // path -> the set of RIGHT-side (head) line numbers any hunk touches.
33
+ export type HunkAnchors = Map<string, Set<number>>;
34
+
35
+ const HUNK_HEADER = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/;
36
+
37
+ // Per-path RIGHT-side line set, built from `@@ -a,b +c,d @@` headers plus the
38
+ // `+`/context lines that follow each one (design D4). Deletion-only lines are
39
+ // LEFT-side and never contribute — a finding always names a HEAD line, so a
40
+ // hunk that only removes code anchors nothing.
41
+ //
42
+ // Reuses splitDiffRecords/diffRecordPath (size-gate.ts) rather than
43
+ // re-parsing `diff --git` headers here: the record boundary and path
44
+ // resolution (rename/copy/C-quoting) logic already exists and any drift
45
+ // between a second implementation and size-gate's would be exactly the class
46
+ // of bug c717fe4 fixed — two places deciding "what is this record's path"
47
+ // and disagreeing. A record whose path cannot be resolved contributes no
48
+ // anchors at all, which is the demote-not-guess direction: every finding in
49
+ // that path falls through to un-anchorable.
50
+ export function parseHunkAnchors(patch: string): HunkAnchors {
51
+ const anchors: HunkAnchors = new Map();
52
+ for (const record of splitDiffRecords(patch)) {
53
+ const target = diffRecordPath(record);
54
+ if (target === undefined) continue;
55
+ const lines = anchorLinesForRecord(record);
56
+ if (lines.size === 0) continue;
57
+ anchors.set(target, lines);
58
+ }
59
+ return anchors;
60
+ }
61
+
62
+ function anchorLinesForRecord(record: string): Set<number> {
63
+ const out = new Set<number>();
64
+ let rightLine = 0;
65
+ let inHunk = false;
66
+ for (const line of record.split("\n")) {
67
+ const header = HUNK_HEADER.exec(line);
68
+ if (header !== null) {
69
+ rightLine = Number.parseInt(header[1] as string, 10);
70
+ inHunk = true;
71
+ continue;
72
+ }
73
+ if (!inHunk) continue;
74
+ if (line.startsWith("+") || line.startsWith(" ")) {
75
+ out.add(rightLine);
76
+ rightLine++;
77
+ continue;
78
+ }
79
+ if (line.startsWith("-")) continue; // left-side only; right counter holds
80
+ // WHY skip, not close: `` is not a tail-only
81
+ // marker. Git emits it immediately after the last `-` line whenever the
82
+ // OLD file lacked a trailing newline, and the hunk continues with more
83
+ // `+` content lines in the SAME hunk when the file's last line is
84
+ // edited (verified against real `git diff` output, not assumed shape).
85
+ // The old code treated ANY non +/-/space line as the hunk's end, so
86
+ // every `+` line after a mid-hunk marker was dropped from the anchor
87
+ // set — classifyAnchorability then reported those lines un-anchorable
88
+ // and buildPostPlan misrouted them to issueComments instead of
89
+ // reviewComments. Closing on a genuine hunk end still works without
90
+ // this branch: the next `@@` header (if any) sets inHunk back to true,
91
+ // and the record simply running out of lines ends the loop regardless.
92
+ if (line.startsWith("\\")) continue;
93
+ // Anything else inside a hunk body closes it — the next header reopens.
94
+ inHunk = false;
95
+ }
96
+ return out;
97
+ }
98
+
99
+ // Un-anchorable is the fail-closed direction on every branch: a path absent
100
+ // from the diff (excluded by the size gate's glob list, or never in the diff
101
+ // at all) and a line the diff never touched both demote rather than guess —
102
+ // see spec "Anchorability classification".
103
+ export function classifyAnchorability(
104
+ finding: { path: string; line: number },
105
+ anchors: HunkAnchors,
106
+ ): Anchorability {
107
+ const lines = anchors.get(finding.path);
108
+ if (lines === undefined) return "un-anchorable";
109
+ return lines.has(finding.line) ? "anchorable" : "un-anchorable";
110
+ }
111
+
112
+ // The line GitHub will be asked to attach an inline comment to. Own line
113
+ // first; if that is off-hunk, the first proof_ref on the SAME path whose
114
+ // cited line (or any line of a `start-end` range) sits in a hunk.
115
+ //
116
+ // This is NOT snapping to the nearest hunk (#17 forbids that: 544 must
117
+ // never become 802 just because 802 is where the hunk starts). A hunter
118
+ // that named 938, and 938 is in the hunk, is using a line the hunter
119
+ // actually cited. No cited in-hunk line → undefined, and the finding
120
+ // stays in the summary Outside Diff bucket.
121
+ export function resolvePostLine(
122
+ finding: PostableFinding,
123
+ anchors: HunkAnchors,
124
+ ): number | undefined {
125
+ const lines = anchors.get(finding.path);
126
+ if (lines === undefined) return undefined;
127
+ if (lines.has(finding.line)) return finding.line;
128
+ if (finding.proof_refs === undefined) return undefined;
129
+ for (const ref of finding.proof_refs) {
130
+ const parsed = parseProofRefLines(ref);
131
+ if (parsed === null || parsed.path !== finding.path) continue;
132
+ for (let n = parsed.start; n <= parsed.end; n++) {
133
+ if (lines.has(n)) return n;
134
+ }
135
+ }
136
+ return undefined;
137
+ }
138
+
139
+ function parseProofRefLines(
140
+ ref: string,
141
+ ): { path: string; start: number; end: number } | null {
142
+ const anchor = extractAnchor([ref]);
143
+ if (anchor === null) return null;
144
+ const colon = anchor.lastIndexOf(":");
145
+ const path = anchor.slice(0, colon);
146
+ const match = /^(\d+)(?:-(\d+))?$/.exec(anchor.slice(colon + 1));
147
+ if (path.length === 0 || match?.[1] === undefined) return null;
148
+ const start = Number(match[1]);
149
+ const end = match[2] === undefined ? start : Number(match[2]);
150
+ if (end < start) return null;
151
+ return { path, start, end };
152
+ }
153
+
154
+ // ---------------------------------------------------------------------------
155
+ // 2. Cross-run matching
156
+
157
+ // FINDING_LINE_WINDOW=5 is a JUDGEMENT CALL, not a measurement — recorded
158
+ // here so nobody later cites it as evidence. It deliberately diverges from
159
+ // compare/compare.ts's DEFAULT_LINE_WINDOW=25: that window is a deliberate OVER-match
160
+ // (show a human a pair they can reject rather than score a real agreement as
161
+ // a miss). This window needs the OPPOSITE bias, because an over-match here
162
+ // silently suppresses a genuinely new finding — an invisible miss, the worst
163
+ // failure a review tool can have. The first live pair of runs is this
164
+ // number's only evidence; widen it only with a measurement, never a
165
+ // extrapolation (size-gate.ts's 1500->2500->1500 arc is the cautionary
166
+ // tale for skipping that step).
167
+ export const FINDING_LINE_WINDOW = 5;
168
+
169
+ // A previously posted per-finding comment, marker-parsed plus whatever
170
+ // GitHub's live projection adds. Review comments carry a live path/line that
171
+ // tracks renames and pushes; issue comments have neither (GitHub does not
172
+ // anchor them to code), so matching an issue comment falls back to the
173
+ // marker's own stored path/line — a known limitation that errs toward a
174
+ // duplicate rather than a silently swallowed finding (design D2).
175
+ export interface PostedFindingComment {
176
+ id: number;
177
+ channel: "review" | "issue";
178
+ marker: ParsedFindingMarker;
179
+ // GitHub's live location for a REVIEW comment. Preferred over the marker's
180
+ // stored path/line because it follows renames and reflects the ACTUAL
181
+ // current position, not the position at post time.
182
+ livePath?: string;
183
+ liveLine?: number;
184
+ // The tier the comment's visible badge states. Absent when the badge is
185
+ // unreadable; absent means unknown, and the matcher then behaves as before.
186
+ tier?: "blocking" | "advisory";
187
+ created_at?: string;
188
+ }
189
+
190
+ export interface FindingMatch {
191
+ finding: PrHeroFindingRef;
192
+ posted: PostedFindingComment;
193
+ }
194
+
195
+ export interface MatchResult {
196
+ // Matched to a prior comment — nothing to post.
197
+ persist: FindingMatch[];
198
+ // No prior comment matched — posts as new.
199
+ fresh: PrHeroFindingRef[];
200
+ // A prior comment with nothing matched to it this run.
201
+ resolved: PostedFindingComment[];
202
+ }
203
+
204
+ interface Candidate {
205
+ posted: PostedFindingComment;
206
+ // 0 for a same-head exact stored-line match; otherwise the window
207
+ // distance computed on the live line. Kept as one number so tie-detection
208
+ // (`resolveWinner`) does not need to know which branch produced it.
209
+ distance: number;
210
+ }
211
+
212
+ // Per-candidate: same head → exact match on the marker's STORED line first,
213
+ // falling back to the ±window on the live line; different head → window
214
+ // only (design D2). WHY the branch exists at all, not just "window on live
215
+ // line" everywhere: GitHub RE-ANCHORS a review comment's live `line`
216
+ // whenever the PR's diff changes — and the diff changes when the BASE
217
+ // branch advances, with no new push to the head. A marker stored at
218
+ // `a.ts:100`, a finding still at `a.ts:100`, and a base-driven live line of
219
+ // `112` is a same-head, zero-drift finding; keying on the live line alone
220
+ // (distance 12 > window 5) misses it and reposts a finding that never
221
+ // moved, which is exactly the daylight spec R11's "an unchanged head MUST
222
+ // NOT repost" exists to close. The live PATH is still preferred in both
223
+ // branches (it follows renames; the marker's path goes stale) — it is only
224
+ // the LINE that must prefer the marker on a same-head comparison.
225
+ function candidatesFor(
226
+ finding: PrHeroFindingRef,
227
+ available: Iterable<PostedFindingComment>,
228
+ window: number,
229
+ headSha: string,
230
+ ): Candidate[] {
231
+ const exact: Candidate[] = [];
232
+ const windowed: Candidate[] = [];
233
+ for (const posted of available) {
234
+ const path = posted.livePath ?? posted.marker.path;
235
+ if (path !== finding.path) continue;
236
+ const sameHead = posted.marker.headSha === headSha;
237
+ // WHY the fingerprint is consulted here too, not just in resolveWinner's
238
+ // tie-break: this branch used to treat same-head path+line alone as
239
+ // sufficient identity, and it is almost always the SOLE candidate (a
240
+ // same-head exact-line hit crowds out any windowed alternative), so the
241
+ // tie-break fingerprint check below never ran for it. Consequence: a
242
+ // genuinely DIFFERENT defect reported at a path:line that already
243
+ // carries an unrelated posted comment was silently classified `persist`
244
+ // and never surfaced — the invisible miss this module's own doc comment
245
+ // (above, "the worst failure mode a review tool can have") warns about,
246
+ // via the one path built to bypass the safeguard meant to prevent it. A
247
+ // fingerprint mismatch means "not established to be the same finding",
248
+ // which resolves to fresh (POST AS NEW) per the demote-not-guess
249
+ // direction: a visible duplicate is self-correcting, an invisible miss
250
+ // is not. The honest cost: claimFingerprint is sha256 over the full
251
+ // trimmed claim text, "nowhere near enough (nor intended) to be a
252
+ // content-addressed identity on its own" (pr/preflight.ts), and LLM
253
+ // claim wording drifts run to run for the SAME defect — so re-reviewing
254
+ // an UNCHANGED head can now post a visible duplicate where it used to
255
+ // silently persist. That trade is deliberate. It is also bounded: this
256
+ // branch only fires on the SAME head, and `post --from` replays the
257
+ // exact same findings.json, so identical claims yield identical
258
+ // fingerprints and that path is unaffected.
259
+ if (sameHead && posted.marker.line === finding.line) {
260
+ if (posted.marker.c === claimFingerprint(finding.claim)) {
261
+ exact.push({ posted, distance: 0 });
262
+ }
263
+ continue;
264
+ }
265
+ const line = posted.liveLine ?? posted.marker.line;
266
+ const distance = Math.abs(line - finding.line);
267
+ if (distance > window) continue;
268
+ windowed.push({ posted, distance });
269
+ }
270
+ // A same-head exact stored-line match always outranks every window
271
+ // candidate for this finding, even one that happens to also sit at
272
+ // distance 0 on the live line — the exact branch is authoritative, not
273
+ // merely a tiebreak, per design D2's ordering ("exact first, THEN window").
274
+ return exact.length > 0 ? exact : windowed;
275
+ }
276
+
277
+ // One-to-one, greedy-nearest, UNDER-match by construction (spec "Match by
278
+ // path and a narrow line window, one-to-one" + "Ambiguous matches post as
279
+ // new, never a forced match"). Findings are matched in input order; each
280
+ // posted comment is consumable at most once, so two findings can never both
281
+ // claim the same prior comment. An ambiguous tie (two candidates at the
282
+ // identical minimum distance) resolves to POST, never to an arbitrary pick —
283
+ // this is the test that would fail if someone later widened the window or
284
+ // made the match many-to-many: widen it and a tie that used to post fresh
285
+ // starts silently forcing a match instead. The one exception is the `c`
286
+ // fingerprint tie-break (design D3): among candidates ALREADY tied at the
287
+ // minimum distance, a fingerprint match picks the winner. It never widens
288
+ // the window and never overrides a strictly nearer candidate — it only
289
+ // resolves a tie that would otherwise post fresh, and a tie where no
290
+ // candidate's fingerprint matches still falls through to post-as-new.
291
+ function resolveWinner(
292
+ finding: PrHeroFindingRef,
293
+ candidates: Candidate[],
294
+ ): PostedFindingComment | undefined {
295
+ if (candidates.length === 0) return undefined;
296
+ const minDistance = Math.min(...candidates.map((c) => c.distance));
297
+ const tied = candidates.filter((c) => c.distance === minDistance);
298
+ if (tied.length === 1) return tied[0]?.posted;
299
+ const fingerprint = claimFingerprint(finding.claim);
300
+ const matching = tied.filter((c) => c.posted.marker.c === fingerprint);
301
+ return matching.length === 1 ? matching[0]?.posted : undefined;
302
+ }
303
+
304
+ export function matchPostedFindings(input: {
305
+ findings: PrHeroFindingRef[];
306
+ posted: PostedFindingComment[];
307
+ headSha: string;
308
+ window?: number;
309
+ }): MatchResult {
310
+ const window = input.window ?? FINDING_LINE_WINDOW;
311
+ const available = new Set(input.posted);
312
+ const persist: FindingMatch[] = [];
313
+ const fresh: PrHeroFindingRef[] = [];
314
+
315
+ for (const finding of input.findings) {
316
+ const candidates = candidatesFor(finding, available, window, input.headSha);
317
+ const winner = resolveWinner(finding, candidates);
318
+ // WHY an advisory comment never matches a blocking finding (tier
319
+ // escalation): the gate counts the blocking finding, so it must be
320
+ // visible. Persisting it onto the old advisory comment would leave the
321
+ // PR showing "advisory" for a finding the gate blocks on, and the triage
322
+ // tooling reads these comments and would never see it. It posts fresh
323
+ // instead; the old comment falls to `resolved`. Every other tier
324
+ // combination, and an unknown tier on either side, matches as before.
325
+ // Except when a fresh comment would carry the very marker the old one
326
+ // carries (path, line, head, claim fingerprint): every marker reader
327
+ // (buildCommentUrlMap, triage reply) takes the first match, the stale
328
+ // advisory one. A same-head tier flip of the same claim on the same line
329
+ // stays a persist, the residual this guard accepts (PR #349 round 1).
330
+ // The guard runs on the WINNER, after resolveWinner, never by filtering
331
+ // the candidates: dropping a candidate first could dissolve a tie that
332
+ // must post fresh and hand the finding to an unrelated comment.
333
+ // The same-head exemption is exactly the duplicate-marker case: same head,
334
+ // same line, same claim fingerprint. A same-head WINDOWED winner sits on
335
+ // another line, so a fresh comment has its own marker and must post
336
+ // (PR #349 round 2).
337
+ const freshWouldDuplicateMarker =
338
+ winner !== undefined &&
339
+ winner.marker.headSha === input.headSha &&
340
+ winner.marker.line === finding.line &&
341
+ winner.marker.c === claimFingerprint(finding.claim);
342
+ if (
343
+ winner !== undefined &&
344
+ !freshWouldDuplicateMarker &&
345
+ finding.tier === "blocking" &&
346
+ winner.tier === "advisory"
347
+ ) {
348
+ fresh.push(finding);
349
+ continue;
350
+ }
351
+ if (winner === undefined) {
352
+ fresh.push(finding);
353
+ continue;
354
+ }
355
+ available.delete(winner);
356
+ persist.push({ finding, posted: winner });
357
+ }
358
+
359
+ const matched = new Set(persist.map((match) => match.posted));
360
+ const resolved = input.posted.filter((posted) => !matched.has(posted));
361
+ return { persist, fresh, resolved };
362
+ }
363
+
364
+ // ---------------------------------------------------------------------------
365
+ // 3. Post plan
366
+
367
+ export interface PostPlan {
368
+ // Anchorable, unmatched findings — go into ONE review submission
369
+ // (`comments[]`), never one review per finding (spec "One review
370
+ // submission for anchorable findings").
371
+ reviewComments: PostableFinding[];
372
+ // Un-anchorable, unmatched findings — go into the summary Outside Diff
373
+ // section (issues #16/#17, Greptile-shaped), not one issue comment each.
374
+ issueComments: PostableFinding[];
375
+ persisting: FindingMatch[];
376
+ resolved: PostedFindingComment[];
377
+ // From the matcher, not a stored count (design D5): persist = matched,
378
+ // new = reviewComments.length + issueComments.length, resolved = prior
379
+ // comments with nothing matched to them.
380
+ delta: { resolved: number; new: number; persist: number };
381
+ }
382
+
383
+ export function buildPostPlan(input: {
384
+ findings: PostableFinding[];
385
+ anchors: HunkAnchors;
386
+ posted: PostedFindingComment[];
387
+ headSha: string;
388
+ window?: number;
389
+ }): PostPlan {
390
+ // Resolve post lines BEFORE matching: a re-anchored finding (544 → 938)
391
+ // has to compare against a prior comment stored at 938, or a re-run on
392
+ // the same head would miss the persist and duplicate. Own-line findings
393
+ // are a no-op here (resolvePostLine returns finding.line).
394
+ const findings = input.findings.map((finding) => {
395
+ const line = resolvePostLine(finding, input.anchors);
396
+ return line === undefined || line === finding.line
397
+ ? finding
398
+ : { ...finding, line };
399
+ });
400
+ const match = matchPostedFindings({
401
+ findings,
402
+ posted: input.posted,
403
+ headSha: input.headSha,
404
+ window: input.window,
405
+ });
406
+ const reviewComments: PostableFinding[] = [];
407
+ const issueComments: PostableFinding[] = [];
408
+ for (const finding of match.fresh) {
409
+ const anchorability = classifyAnchorability(finding, input.anchors);
410
+ if (anchorability === "anchorable") reviewComments.push(finding);
411
+ else issueComments.push(finding);
412
+ }
413
+ return {
414
+ reviewComments,
415
+ issueComments,
416
+ persisting: match.persist,
417
+ resolved: match.resolved,
418
+ delta: {
419
+ resolved: match.resolved.length,
420
+ new: match.fresh.length,
421
+ persist: match.persist.length,
422
+ },
423
+ };
424
+ }
425
+
426
+ // ---------------------------------------------------------------------------
427
+ // Pure decisions and shapes behind pr.ts's postInlineFindings orchestration
428
+ // (ROADMAP B6, WU6, cli-decomp S2 Cluster C): the exit-code rule, the
429
+ // dropped-finding oracle, and the outcome shape both compose. Kept here
430
+ // rather than in pr.ts: postInlineFindings imports these, so keeping them in
431
+ // the pure module (not the shell that consumes them) is the same layering
432
+ // this file's header already states — pr.ts executes what this module plans.
433
+ // ---------------------------------------------------------------------------
434
+
435
+ export interface InlinePostOutcome {
436
+ reviewOutcome: "posted" | "demoted";
437
+ reviewFindingCount: number;
438
+ // Always [] this slice (issues #16/#17): findings no longer POST as
439
+ // standalone issue comments. Kept on the outcome so the receipt's
440
+ // `issue_comment_ids` shape stays unchanged.
441
+ issueCommentIds: number[];
442
+ // Un-anchorable findings plus any 422-demoted review findings that landed
443
+ // in the summary Outside Diff section. Counted separately from
444
+ // issueCommentIds so the posted: log can name the bucket without lying
445
+ // that those findings became issue comments.
446
+ outsideDiffCount: number;
447
+ summary: { action: "created" | "updated"; commentId: number };
448
+ delta: PostPlan["delta"];
449
+ // Finding ids the plan classified as fresh (reviewComments + issueComments)
450
+ // that, after posting completed WITHOUT throwing, reached NEITHER the
451
+ // review NOR the summary Outside Diff bucket — the exact shape of the bug
452
+ // CRIT-1 (verify-report-pr2, #3296) found: a claimed comment swallowing a
453
+ // genuinely new finding. Computed independently of postPrReview's own
454
+ // return value on purpose — this is the caller's OWN check, not a re-read
455
+ // of the primitive's opinion, because trusting the primitive's opinion is
456
+ // exactly what let CRIT-1 through undetected in PR2's own test suite.
457
+ droppedFindingIds: string[];
458
+ // findingId -> the url of the comment that finding now lives at (persisting
459
+ // from a prior run, or posted by this one). Built by buildCommentUrlMap for
460
+ // the summary's index; handed OUT as well so the terminal's result block can
461
+ // link each finding to the thread the reader will reply in rather than to a
462
+ // read-only blob view. Deliberately NOT in post.json: writePostReceipt names
463
+ // its fields one by one, so the receipt's shape is unchanged, and a Map
464
+ // would JSON.stringify to `{}` anyway.
465
+ commentUrls: ReadonlyMap<string, string>;
466
+ // The re-review closing comment's id (postInlineFindings). Absent on a
467
+ // first review, which posts none, and when the closing POST failed.
468
+ closingCommentId?: number;
469
+ // GitHub #39: the PR's head as GitHub reported it immediately before the
470
+ // review submission, when it was NOT the head this run reviewed. Undefined
471
+ // on an unmoved head AND on a re-read that could not be made — the two are
472
+ // deliberately indistinguishable here, because the only thing this field
473
+ // authorizes is a notice, and a notice needs a confirmed mismatch. Handed
474
+ // out so the terminal block can print the same disclosure the summary
475
+ // comment carries, and so the caller can say it in the run log at the
476
+ // moment it happened.
477
+ movedHeadSha: string | undefined;
478
+ }
479
+
480
+ // The exact oracle behind `droppedFindingIds` (design D6's exit-1 rule),
481
+ // pinned as its own pure function — WARN-1 (verify-report-pr3, #3305): under
482
+ // the CRIT-A fix, a genuine drop is no longer REACHABLE through normal
483
+ // execution (every finding the plan classified fresh now ends up in exactly
484
+ // one of `reachedIds` or the demoted-and-matched set), which is the correct
485
+ // outcome but leaves the formula itself untestable through composition
486
+ // alone — the only way to exercise a non-empty result is a hand-built
487
+ // `reached` set, exactly the way `postingExitCode` is already tested against
488
+ // a hand-built literal. Extracted so a future regression in the SET
489
+ // arithmetic (not the posting sequence) is still caught.
490
+ export function computeDroppedFindingIds(
491
+ expectedFresh: PrHeroFindingRef[],
492
+ reached: ReadonlySet<string>,
493
+ ): string[] {
494
+ const expectedIds = new Set(expectedFresh.map((f) => f.id));
495
+ return [...expectedIds].filter((id) => !reached.has(id));
496
+ }
497
+
498
+ // Design D6's exit-code rule, pinned as its own pure function so the rule is
499
+ // testable without a live post: exit 1 ONLY when a finding reached neither
500
+ // channel (the CRIT-1 failure mode); a `null` outcome (sessionFailed, or
501
+ // `--post` never given) is not itself a posting failure — its caller already
502
+ // decides the exit code on its own terms (e.g. reviewPr's sessionFailed
503
+ // early-return above).
504
+ export function postingExitCode(outcome: InlinePostOutcome | null): 0 | 1 {
505
+ if (outcome === null) return 0;
506
+ return outcome.droppedFindingIds.length > 0 ? 1 : 0;
507
+ }