crysk 0.0.0 → 0.3.1

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 (233) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +611 -3
  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/SKILL-y8rv8msh.md +134 -0
  10. package/dist/SKILL-ygka1bs0.md +515 -0
  11. package/dist/adjudicator-dtg2axnh.md +86 -0
  12. package/dist/admission-config.example-a9vqmmad.json +9 -0
  13. package/dist/ci-admission-camfbx2b.md +122 -0
  14. package/dist/ci-admission-qk9r9taq.md +124 -0
  15. package/dist/cli.js +42501 -0
  16. package/dist/consolidate-ac0mnfyj.md +24 -0
  17. package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
  18. package/dist/deep-review-logic-a6b1gczf.md +156 -0
  19. package/dist/deep-review-parity-0ec904db.md +120 -0
  20. package/dist/deep-review-reliability-qyakbjb9.md +125 -0
  21. package/dist/deep-review-resilience-3tz8y26e.md +118 -0
  22. package/dist/index.js +20190 -0
  23. package/dist/opencode-ci-7b0be64p.md +141 -0
  24. package/dist/review-refuter-j4e9gezy.md +71 -0
  25. package/dist/scout-yvp153q7.md +140 -0
  26. package/dist/summarizer-zca44nxa.md +18 -0
  27. package/dist/workflow-w1g9szna.yml +151 -0
  28. package/package.json +81 -4
  29. package/prompts/consolidate.md +24 -0
  30. package/prompts/default/PROVENANCE.md +18 -0
  31. package/prompts/default/deep-review-lifecycle.md +362 -0
  32. package/prompts/default/deep-review-logic.md +156 -0
  33. package/prompts/default/deep-review-parity.md +120 -0
  34. package/prompts/default/deep-review-reliability.md +125 -0
  35. package/prompts/default/deep-review-resilience.md +118 -0
  36. package/prompts/default/review-refuter.md +71 -0
  37. package/prompts/scout.md +140 -0
  38. package/prompts/summarizer.md +18 -0
  39. package/skills/crysk/SKILL.md +74 -0
  40. package/skills/crysk-ci-setup/SKILL.md +134 -0
  41. package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
  42. package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
  43. package/skills/crysk-ci-setup/references/ci-admission.md +124 -0
  44. package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
  45. package/skills/crysk-loop/SKILL.md +515 -0
  46. package/skills/crysk-loop/adjudicator.md +86 -0
  47. package/skills/crysk-pr/SKILL.md +66 -0
  48. package/src/agent-env.ts +1084 -0
  49. package/src/asset-manifest.ts +83 -0
  50. package/src/assets.d.ts +6 -0
  51. package/src/assets.ts +183 -0
  52. package/src/brand-paths.ts +155 -0
  53. package/src/brand.ts +255 -0
  54. package/src/ci/admission-ledger.ts +350 -0
  55. package/src/ci/classify-error.ts +73 -0
  56. package/src/ci/cli-record.ts +271 -0
  57. package/src/ci/force-comment.ts +39 -0
  58. package/src/ci/gates.ts +945 -0
  59. package/src/ci/outcome.ts +2181 -0
  60. package/src/ci/override.ts +187 -0
  61. package/src/ci/publish.ts +1639 -0
  62. package/src/ci/reporter.ts +626 -0
  63. package/src/ci/review-admission.ts +910 -0
  64. package/src/ci/review-levels.ts +310 -0
  65. package/src/ci/review-policy.ts +18 -0
  66. package/src/ci/review-risk.ts +184 -0
  67. package/src/ci/setup.ts +844 -0
  68. package/src/ci/trigger.ts +1353 -0
  69. package/src/cli.ts +348 -0
  70. package/src/commands/activity.ts +67 -0
  71. package/src/commands/ci-setup-questions.ts +397 -0
  72. package/src/commands/ci-setup.ts +381 -0
  73. package/src/commands/config.ts +99 -0
  74. package/src/commands/doctor.ts +108 -0
  75. package/src/commands/init.ts +139 -0
  76. package/src/commands/mcp.ts +10 -0
  77. package/src/commands/menu.ts +129 -0
  78. package/src/commands/post.ts +302 -0
  79. package/src/commands/skills.ts +83 -0
  80. package/src/commands/status.ts +173 -0
  81. package/src/commands/triage.ts +342 -0
  82. package/src/commands/uninstall.ts +37 -0
  83. package/src/commands/upgrade.ts +214 -0
  84. package/src/commands/usage.ts +98 -0
  85. package/src/compare/compare.ts +28 -0
  86. package/src/compare/floor-test.ts +471 -0
  87. package/src/compare/martian-adapter.ts +80 -0
  88. package/src/config/config.ts +267 -0
  89. package/src/corpus/corpus.ts +1094 -0
  90. package/src/corpus/preflight.ts +1789 -0
  91. package/src/diversity/accounting.ts +90 -0
  92. package/src/diversity/adjudication.ts +145 -0
  93. package/src/diversity/admission.ts +60 -0
  94. package/src/diversity/benchmark.ts +195 -0
  95. package/src/diversity/clustering.ts +285 -0
  96. package/src/diversity/errors.ts +7 -0
  97. package/src/diversity/identity.ts +285 -0
  98. package/src/diversity/index.ts +11 -0
  99. package/src/diversity/pipeline-integration.ts +448 -0
  100. package/src/diversity/projection.ts +57 -0
  101. package/src/diversity/self-contained.ts +68 -0
  102. package/src/diversity/target-validation.ts +179 -0
  103. package/src/doctor-migration.ts +209 -0
  104. package/src/doctor.ts +723 -0
  105. package/src/errors.ts +83 -0
  106. package/src/execution/admission.ts +75 -0
  107. package/src/execution/atomic-write.ts +35 -0
  108. package/src/execution/attempt-evidence.ts +415 -0
  109. package/src/execution/bucket-id.ts +136 -0
  110. package/src/execution/concurrency-limiter.ts +175 -0
  111. package/src/execution/contracts.ts +443 -0
  112. package/src/execution/failure-classification.ts +42 -0
  113. package/src/execution/failure-policy.ts +240 -0
  114. package/src/execution/harness.ts +2548 -0
  115. package/src/execution/settlement.ts +348 -0
  116. package/src/execution/spawned-process.ts +66 -0
  117. package/src/execution/spend-limiter.ts +424 -0
  118. package/src/execution/step-artifacts.ts +55 -0
  119. package/src/execution/usage-normalized.ts +469 -0
  120. package/src/git/git.ts +396 -0
  121. package/src/git/identity.ts +64 -0
  122. package/src/git/refs.ts +140 -0
  123. package/src/home-preflight.ts +443 -0
  124. package/src/home.ts +243 -0
  125. package/src/ignore-file.ts +336 -0
  126. package/src/ignore-read.ts +118 -0
  127. package/src/index.ts +34 -0
  128. package/src/legacy-launchd.ts +29 -0
  129. package/src/mcp/mcp.ts +150 -0
  130. package/src/mcp/preflight.ts +407 -0
  131. package/src/menu-context.ts +192 -0
  132. package/src/model/catalog.ts +251 -0
  133. package/src/model/exec-snapshots.ts +390 -0
  134. package/src/model/free-discovery.ts +302 -0
  135. package/src/model/provider-capabilities.ts +814 -0
  136. package/src/model/routing.ts +600 -0
  137. package/src/pr/admission.ts +984 -0
  138. package/src/pr/answered-findings.ts +169 -0
  139. package/src/pr/ci-admission-gate.ts +743 -0
  140. package/src/pr/ci-publish.ts +76 -0
  141. package/src/pr/discovery.ts +432 -0
  142. package/src/pr/inline.ts +507 -0
  143. package/src/pr/plan.ts +366 -0
  144. package/src/pr/posting.ts +115 -0
  145. package/src/pr/pr-status.ts +845 -0
  146. package/src/pr/pr.ts +3642 -0
  147. package/src/pr/preflight.ts +1031 -0
  148. package/src/pr/publish-outcome.ts +361 -0
  149. package/src/pr/range.ts +119 -0
  150. package/src/pr/reverts-preflight.ts +606 -0
  151. package/src/pr/reverts.ts +377 -0
  152. package/src/pr/review-pr.ts +927 -0
  153. package/src/pr/status.ts +154 -0
  154. package/src/pr/target.ts +388 -0
  155. package/src/pr/teardown.ts +437 -0
  156. package/src/pr/worktree-setup.ts +60 -0
  157. package/src/production-runtime.ts +1877 -0
  158. package/src/progress.ts +487 -0
  159. package/src/rereview/adjudicate.ts +89 -0
  160. package/src/rereview/classify.ts +362 -0
  161. package/src/rereview/identity.ts +211 -0
  162. package/src/rereview/plan.ts +308 -0
  163. package/src/rereview/prepare.ts +1025 -0
  164. package/src/rereview/state.ts +767 -0
  165. package/src/rereview/verify.ts +241 -0
  166. package/src/review/boundary.ts +105 -0
  167. package/src/review/consolidate.ts +246 -0
  168. package/src/review/dedupe.ts +368 -0
  169. package/src/review/drafts.ts +448 -0
  170. package/src/review/findings-conformance.ts +120 -0
  171. package/src/review/findings.ts +714 -0
  172. package/src/review/pipeline.ts +3977 -0
  173. package/src/review/preflight.ts +3575 -0
  174. package/src/review/prompt-set.ts +177 -0
  175. package/src/review/proof-refs.ts +187 -0
  176. package/src/review/report.ts +1821 -0
  177. package/src/review/review.ts +490 -0
  178. package/src/review/root-cause.ts +120 -0
  179. package/src/review/route-preflight.ts +289 -0
  180. package/src/review/run.ts +601 -0
  181. package/src/review/scout.ts +323 -0
  182. package/src/review/size-gate.ts +595 -0
  183. package/src/review/spec.ts +235 -0
  184. package/src/review/step-runner.ts +233 -0
  185. package/src/runner-authority.ts +596 -0
  186. package/src/security/binding-policy.ts +115 -0
  187. package/src/security/credential-broker.ts +773 -0
  188. package/src/security/evidence-redaction.ts +62 -0
  189. package/src/security/execution-authority.ts +27 -0
  190. package/src/security/redact.ts +71 -0
  191. package/src/security/workspace-read-broker.ts +466 -0
  192. package/src/server/client.ts +190 -0
  193. package/src/server/preflight.ts +217 -0
  194. package/src/server/server.ts +327 -0
  195. package/src/signal-handler.ts +50 -0
  196. package/src/store/activity.ts +413 -0
  197. package/src/store/backfill-preflight.ts +49 -0
  198. package/src/store/backfill.ts +141 -0
  199. package/src/store/gc-preflight.ts +206 -0
  200. package/src/store/gc.ts +424 -0
  201. package/src/store/metrics-preflight.ts +229 -0
  202. package/src/store/metrics.ts +236 -0
  203. package/src/store/preflight.ts +748 -0
  204. package/src/store/store.ts +693 -0
  205. package/src/system-tools.ts +355 -0
  206. package/src/transport-registry.ts +1124 -0
  207. package/src/transports/claude-code-cli.ts +1348 -0
  208. package/src/transports/opencode-admission.ts +515 -0
  209. package/src/transports/opencode-client.ts +3328 -0
  210. package/src/transports/opencode-evidence.ts +557 -0
  211. package/src/transports/opencode-mcp.ts +248 -0
  212. package/src/transports/opencode-sdk.ts +2294 -0
  213. package/src/transports/opencode-server.ts +535 -0
  214. package/src/triage/adjudication.ts +113 -0
  215. package/src/triage/reply.ts +125 -0
  216. package/src/triage/triage.ts +255 -0
  217. package/src/ui/activity.ts +173 -0
  218. package/src/ui/config-edit.ts +816 -0
  219. package/src/ui/config.ts +462 -0
  220. package/src/ui/menu.ts +1325 -0
  221. package/src/ui/plan.ts +1039 -0
  222. package/src/ui/primitives.ts +300 -0
  223. package/src/ui/progress.ts +298 -0
  224. package/src/ui/result.ts +552 -0
  225. package/src/ui/review-menu.ts +312 -0
  226. package/src/ui/select.ts +528 -0
  227. package/src/ui/tree.ts +178 -0
  228. package/src/uninstaller.ts +479 -0
  229. package/src/updater.ts +836 -0
  230. package/src/usage.ts +77 -0
  231. package/src/watch/preflight.ts +1389 -0
  232. package/src/watch/watch.ts +1235 -0
  233. package/src/wizard.ts +877 -0
@@ -0,0 +1,1025 @@
1
+ // Impure-half orchestration for item 7 discovery (`docs/item7-rereview-design.md`
2
+ // §3.1). Git facts arrive through `RereviewGit` so the CLI owns `cat-file`,
3
+ // `merge-base --is-ancestor`, and `diff --name-only`, and tests inject fakes.
4
+ // The case machine itself stays in rereview/plan.ts.
5
+
6
+ import { normalizePath } from "#compare/compare";
7
+ import { claimFingerprint } from "#pr/preflight";
8
+ import type { Severity } from "#review/findings";
9
+ import { parseFindingCommentBadge } from "#review/report";
10
+ import {
11
+ type AdjudicationSubject,
12
+ CI_ADJUDICATOR_LOGIN,
13
+ MAX_ADJUDICATIONS_PER_RUN,
14
+ parseAdjudicationMarker,
15
+ } from "#triage/adjudication";
16
+ import { parseTriageMarker } from "#triage/triage";
17
+ import {
18
+ classifyPrior,
19
+ isRecoveredSeverity,
20
+ isRecoveredTier,
21
+ type PhaseBResult,
22
+ type PriorRecord,
23
+ type PriorTriage,
24
+ type RecoveredSeverity,
25
+ type RereviewCase,
26
+ SEVERITY_UNRECOVERABLE,
27
+ TIER_UNRECOVERABLE,
28
+ } from "./classify";
29
+ import {
30
+ type FindingIdentity,
31
+ IDENTITY_LINE_WINDOW,
32
+ identityFromLocs,
33
+ } from "./identity";
34
+ import {
35
+ type DiscoveryPlan,
36
+ decideLastHeadDelta,
37
+ decideRereviewCase,
38
+ incompleteLastReviewMessage,
39
+ type LastHeadSource,
40
+ type LastReviewedHead,
41
+ type MarkerHead,
42
+ planDiscovery,
43
+ resolveLastReviewedHead,
44
+ restrictedDiscoveryFiles,
45
+ skippedDiscoveryMessage,
46
+ unreachableLastHeadMessage,
47
+ } from "./plan";
48
+ import type { LiveFinding, StateFinding } from "./state";
49
+ import type { VerifyQueueEntry } from "./verify";
50
+
51
+ // cli.ts reaches the whole re-review surface through this module and never
52
+ // imports rereview/plan.ts directly; these three travel with `prepareDiscovery`'s
53
+ // output, so they ride the same facade. The return type stays unexported here
54
+ // — cli.ts infers it, and nothing names it across this boundary.
55
+ export {
56
+ decideLastHeadDelta,
57
+ incompleteLastReviewMessage,
58
+ skippedDiscoveryMessage,
59
+ unreachableLastHeadMessage,
60
+ };
61
+
62
+ export interface RereviewGit {
63
+ commitExists(sha: string): Promise<boolean>;
64
+ isAncestor(ancestor: string, descendant: string): Promise<boolean>;
65
+ nameOnly(from: string, to: string): Promise<string[]>;
66
+ }
67
+
68
+ export interface PreparedDiscovery {
69
+ last: LastReviewedHead;
70
+ case: RereviewCase;
71
+ plan: DiscoveryPlan;
72
+ // Null: unrestricted B..H (hunters see the full PR range). Empty: skip
73
+ // discovery — no files in the restricted intersection, or case B.
74
+ discoveryPaths: string[] | null;
75
+ discoveryFrom: string;
76
+ discoveryTo: string;
77
+ discoverySkippedEmptyDelta: boolean;
78
+ }
79
+
80
+ export interface RereviewProvenance {
81
+ case: RereviewCase;
82
+ last_reviewed_head: string | null;
83
+ last_head_source: LastHeadSource;
84
+ // Rereview-coverage fix: WHY discovery was forced full without
85
+ // `--full` on the artifact record — "case B, discovery full, no --full"
86
+ // is otherwise unexplained. Mirrors `LastReviewedHead.lastComplete`
87
+ // verbatim. Optional on the TYPE (not just the parser) because it is
88
+ // genuinely absent from every pipeline.json written before this fix —
89
+ // `toRereviewProvenance` always sets a concrete boolean; a reader that
90
+ // wants the definite value defaults it `?? true`, same as
91
+ // `readRereviewProvenance` does below.
92
+ last_review_complete?: boolean;
93
+ discovery_range: string;
94
+ discovery_restricted: boolean;
95
+ discovery_skipped_empty_delta: boolean;
96
+ // pr-hero review #286 finding: `discovery_skipped_empty_delta` alone
97
+ // conflates two different truths — (a) there was genuinely nothing new to
98
+ // discover (case B's same head, or case C's empty restricted intersection:
99
+ // `pr/discovery.ts`'s `skipPlannedDiscovery`), and (b) there WAS a real,
100
+ // non-empty delta, but every file in it was excluded by the size gate /
101
+ // `.prheroignore` rules (`filterDiffByIgnoreRules`'s `droppedPaths`). Only
102
+ // (a) supports "no changes since the last review" wording; (b) requires
103
+ // naming what was excluded, or the summary repeats the exact false claim
104
+ // this field exists to prevent. Optional so an artifact written before this
105
+ // fix still parses (`readRereviewProvenance` below); such an artifact could
106
+ // only ever have reached (a) or (b) through the SAME `discovery_skipped_
107
+ // empty_delta` flag without recording which, so a reader of an old record
108
+ // has no way to tell either — this field is forward-only disambiguation,
109
+ // not a backfillable one.
110
+ discovery_skip_reason?: "no_delta" | "all_excluded";
111
+ // Populated only when `discovery_skip_reason` is `"all_excluded"`.
112
+ discovery_excluded_paths?: string[];
113
+ prior_findings: number;
114
+ settled_deterministically: number;
115
+ verified: number;
116
+ verification_capped: number;
117
+ verification_triggers: {
118
+ applied: number;
119
+ touched: number;
120
+ overlap: number;
121
+ verify_all: number;
122
+ };
123
+ live: LiveFinding[];
124
+ resolved_verified?: number;
125
+ resolved_ids?: string[];
126
+ returned?: number;
127
+ re_tiered?: number;
128
+ worsened?: readonly {
129
+ priorId: string;
130
+ priorSev: RecoveredSeverity;
131
+ discoverySev: Severity;
132
+ }[];
133
+ }
134
+
135
+ export function shouldAbortEmptyDiscovery(
136
+ plan: DiscoveryPlan,
137
+ patch: string,
138
+ ): boolean {
139
+ return plan.emptyDeltaIsError && patch.trim().length === 0;
140
+ }
141
+
142
+ export async function prepareDiscovery(input: {
143
+ B: string;
144
+ H: string;
145
+ full: boolean;
146
+ summaryHead: string | null;
147
+ // Ignored when summaryHead is null. Required so the ONE production caller
148
+ // (cli.ts) must explicitly compute it from the posted marker — see
149
+ // resolveLastReviewedHead's WHY for the "leaves the fix a no-op" trap a
150
+ // silent default would hide.
151
+ summaryComplete: boolean;
152
+ findingMarkers: readonly MarkerHead[];
153
+ git: RereviewGit;
154
+ }): Promise<PreparedDiscovery> {
155
+ const last = resolveLastReviewedHead({
156
+ summaryHead: input.summaryHead,
157
+ summaryComplete: input.summaryComplete,
158
+ findingMarkers: input.findingMarkers,
159
+ });
160
+ let objectExists: boolean | null = null;
161
+ let isAncestor: boolean | null = null;
162
+ if (last.L !== null) {
163
+ objectExists = await input.git.commitExists(last.L);
164
+ if (objectExists) {
165
+ isAncestor = await input.git.isAncestor(last.L, input.H);
166
+ }
167
+ }
168
+ const rereviewCase = decideRereviewCase({
169
+ L: last.L,
170
+ H: input.H,
171
+ objectExists,
172
+ isAncestor,
173
+ });
174
+ const plan = planDiscovery({
175
+ case: rereviewCase,
176
+ full: input.full,
177
+ lastComplete: last.lastComplete,
178
+ });
179
+
180
+ if (plan.skipDiscovery) {
181
+ const from = last.L ?? input.B;
182
+ return {
183
+ last,
184
+ case: rereviewCase,
185
+ plan,
186
+ discoveryPaths: [],
187
+ discoveryFrom: from,
188
+ discoveryTo: input.H,
189
+ discoverySkippedEmptyDelta: true,
190
+ };
191
+ }
192
+
193
+ if (plan.discovery !== "restricted" || last.L === null) {
194
+ return {
195
+ last,
196
+ case: rereviewCase,
197
+ plan,
198
+ discoveryPaths: null,
199
+ discoveryFrom: input.B,
200
+ discoveryTo: input.H,
201
+ discoverySkippedEmptyDelta: false,
202
+ };
203
+ }
204
+
205
+ const [prFiles, deltaFiles] = await Promise.all([
206
+ input.git.nameOnly(input.B, input.H),
207
+ input.git.nameOnly(last.L, input.H),
208
+ ]);
209
+ const discoveryPaths = restrictedDiscoveryFiles(prFiles, deltaFiles);
210
+ return {
211
+ last,
212
+ case: rereviewCase,
213
+ plan,
214
+ discoveryPaths,
215
+ discoveryFrom: last.L,
216
+ discoveryTo: input.H,
217
+ discoverySkippedEmptyDelta: discoveryPaths.length === 0,
218
+ };
219
+ }
220
+
221
+ // First review (case A) carries no block at all (W-prov). Counts that the
222
+ // verify spawn has not filled yet stay zero rather than omitted — an
223
+ // artifact that cannot name its case is unscorable; zeros are still a case.
224
+ export function toRereviewProvenance(
225
+ prepared: PreparedDiscovery,
226
+ priorFindings = 0,
227
+ ): RereviewProvenance | undefined {
228
+ if (prepared.case === "A") return undefined;
229
+ return {
230
+ case: prepared.case,
231
+ last_reviewed_head: prepared.last.L,
232
+ last_head_source: prepared.last.source,
233
+ last_review_complete: prepared.last.lastComplete,
234
+ discovery_range: `${prepared.discoveryFrom}..${prepared.discoveryTo}`,
235
+ discovery_restricted: prepared.plan.discoveryRestricted,
236
+ discovery_skipped_empty_delta: prepared.discoverySkippedEmptyDelta,
237
+ prior_findings: priorFindings,
238
+ settled_deterministically: 0,
239
+ verified: 0,
240
+ verification_capped: 0,
241
+ verification_triggers: {
242
+ applied: 0,
243
+ touched: 0,
244
+ overlap: 0,
245
+ verify_all: 0,
246
+ },
247
+ live: [],
248
+ resolved_verified: 0,
249
+ returned: 0,
250
+ re_tiered: 0,
251
+ };
252
+ }
253
+
254
+ // The read-back half of the block above, for the ONE consumer that has no
255
+ // pipeline in memory: `post --from <run-dir>` (`runPostCommand`). The run's
256
+ // `pipeline.json` is the only place a re-review's case, `live[]` and
257
+ // verified-gone count survive the process that computed them, so the summary
258
+ // `post --from` publishes is truthful exactly when this parse succeeds — and
259
+ // a block that half-parses is worse than none, because the delta it feeds
260
+ // silently falls back to the absence matcher (`MatchResult.resolved`) that
261
+ // item 7 exists to retire. Hence: valid, absent, or LOUD. Pure so the seam is
262
+ // testable without a run directory.
263
+ export type RereviewProvenanceRead =
264
+ | { kind: "absent" }
265
+ | { kind: "ok"; rereview: RereviewProvenance }
266
+ | { kind: "invalid"; problem: string };
267
+
268
+ export function readRereviewProvenance(
269
+ pipeline: unknown,
270
+ ): RereviewProvenanceRead {
271
+ if (!isRecord(pipeline)) return { kind: "invalid", problem: "not an object" };
272
+ const raw = pipeline.rereview;
273
+ if (raw === undefined || raw === null) return { kind: "absent" };
274
+ if (!isRecord(raw)) return { kind: "invalid", problem: "rereview" };
275
+
276
+ const problem = (field: string): RereviewProvenanceRead => ({
277
+ kind: "invalid",
278
+ problem: `rereview.${field}`,
279
+ });
280
+ const rereviewCase = raw.case;
281
+ if (
282
+ rereviewCase !== "A" &&
283
+ rereviewCase !== "B" &&
284
+ rereviewCase !== "C" &&
285
+ rereviewCase !== "D" &&
286
+ rereviewCase !== "E"
287
+ ) {
288
+ return problem("case");
289
+ }
290
+ const lastHead = raw.last_reviewed_head;
291
+ if (lastHead !== null && typeof lastHead !== "string") {
292
+ return problem("last_reviewed_head");
293
+ }
294
+ const source = raw.last_head_source;
295
+ if (
296
+ source !== "summary_marker" &&
297
+ source !== "finding_markers" &&
298
+ source !== "absent"
299
+ ) {
300
+ return problem("last_head_source");
301
+ }
302
+ // Optional (rereview-coverage fix): an artifact written before this fix
303
+ // has no such field at all, and it must still parse — never invalid,
304
+ // defaulting to `true` on read (see the assignment below). The pre-fix
305
+ // world had no notion of a forced-full re-review, so "complete" is the
306
+ // accurate back-compat reading, not a guess.
307
+ if (
308
+ raw.last_review_complete !== undefined &&
309
+ typeof raw.last_review_complete !== "boolean"
310
+ ) {
311
+ return problem("last_review_complete");
312
+ }
313
+ if (typeof raw.discovery_range !== "string") {
314
+ return problem("discovery_range");
315
+ }
316
+ if (typeof raw.discovery_restricted !== "boolean") {
317
+ return problem("discovery_restricted");
318
+ }
319
+ if (typeof raw.discovery_skipped_empty_delta !== "boolean") {
320
+ return problem("discovery_skipped_empty_delta");
321
+ }
322
+ for (const field of [
323
+ "prior_findings",
324
+ "settled_deterministically",
325
+ "verified",
326
+ "verification_capped",
327
+ ] as const) {
328
+ if (!isCount(raw[field])) return problem(field);
329
+ }
330
+ const triggers = raw.verification_triggers;
331
+ if (!isRecord(triggers)) return problem("verification_triggers");
332
+ for (const field of [
333
+ "applied",
334
+ "touched",
335
+ "overlap",
336
+ "verify_all",
337
+ ] as const) {
338
+ if (!isCount(triggers[field])) {
339
+ return problem(`verification_triggers.${field}`);
340
+ }
341
+ }
342
+ if (!Array.isArray(raw.live)) return problem("live");
343
+ const live: LiveFinding[] = [];
344
+ for (const [i, row] of raw.live.entries()) {
345
+ const parsed = asLiveFinding(row);
346
+ if (parsed === null) return problem(`live[${i}]`);
347
+ live.push(parsed);
348
+ }
349
+ for (const field of ["resolved_verified", "returned", "re_tiered"] as const) {
350
+ if (raw[field] !== undefined && !isCount(raw[field])) return problem(field);
351
+ }
352
+ const resolvedIds = raw.resolved_ids;
353
+ if (
354
+ resolvedIds !== undefined &&
355
+ (!Array.isArray(resolvedIds) ||
356
+ !resolvedIds.every((id) => typeof id === "string"))
357
+ ) {
358
+ return problem("resolved_ids");
359
+ }
360
+ // W-worse: `worsened` is what makes the summary name BOTH severities on a
361
+ // prior that came back stronger ("returned R001: WARNING → CRITICAL",
362
+ // `liveFindingLines`). Validated and carried, never quietly dropped — a
363
+ // `post --from` that published the same summary minus those lines would be
364
+ // the silent render this whole seam refuses.
365
+ let worsened: RereviewProvenance["worsened"];
366
+ if (raw.worsened !== undefined) {
367
+ if (!Array.isArray(raw.worsened)) return problem("worsened");
368
+ const rows: {
369
+ priorId: string;
370
+ priorSev: RecoveredSeverity;
371
+ discoverySev: Severity;
372
+ }[] = [];
373
+ for (const [i, row] of raw.worsened.entries()) {
374
+ if (
375
+ !isRecord(row) ||
376
+ typeof row.priorId !== "string" ||
377
+ row.priorId.length === 0 ||
378
+ // `priorSev` may carry the #206 sentinel (a worsening hit computed
379
+ // over an unrecoverable-severity prior, see classify.ts's
380
+ // `isStrictlyHigherSev`); `discoverySev` never does — it is always a
381
+ // fresh finding's real severity.
382
+ !isRecoveredSeverity(row.priorSev) ||
383
+ !isSeverity(row.discoverySev)
384
+ ) {
385
+ return problem(`worsened[${i}]`);
386
+ }
387
+ rows.push({
388
+ priorId: row.priorId,
389
+ priorSev: row.priorSev,
390
+ discoverySev: row.discoverySev,
391
+ });
392
+ }
393
+ worsened = rows;
394
+ }
395
+
396
+ // Optional, same "absent on every pre-fix artifact" reasoning as
397
+ // `last_review_complete` above — see `discovery_skip_reason`'s own WHY on
398
+ // the type. Validated when present so a corrupted value fails loud rather
399
+ // than silently mis-rendering an exclusion claim as a no-delta one.
400
+ const skipReason = raw.discovery_skip_reason;
401
+ if (
402
+ skipReason !== undefined &&
403
+ skipReason !== "no_delta" &&
404
+ skipReason !== "all_excluded"
405
+ ) {
406
+ return problem("discovery_skip_reason");
407
+ }
408
+ const excludedPaths = raw.discovery_excluded_paths;
409
+ if (
410
+ excludedPaths !== undefined &&
411
+ (!Array.isArray(excludedPaths) ||
412
+ !excludedPaths.every((p) => typeof p === "string"))
413
+ ) {
414
+ return problem("discovery_excluded_paths");
415
+ }
416
+
417
+ return {
418
+ kind: "ok",
419
+ rereview: {
420
+ case: rereviewCase,
421
+ last_reviewed_head: lastHead,
422
+ last_head_source: source,
423
+ last_review_complete:
424
+ typeof raw.last_review_complete === "boolean"
425
+ ? raw.last_review_complete
426
+ : true,
427
+ discovery_range: raw.discovery_range,
428
+ discovery_restricted: raw.discovery_restricted,
429
+ discovery_skipped_empty_delta: raw.discovery_skipped_empty_delta,
430
+ ...(skipReason === undefined
431
+ ? {}
432
+ : { discovery_skip_reason: skipReason }),
433
+ ...(excludedPaths === undefined
434
+ ? {}
435
+ : { discovery_excluded_paths: excludedPaths as string[] }),
436
+ prior_findings: raw.prior_findings as number,
437
+ settled_deterministically: raw.settled_deterministically as number,
438
+ verified: raw.verified as number,
439
+ verification_capped: raw.verification_capped as number,
440
+ verification_triggers: {
441
+ applied: triggers.applied as number,
442
+ touched: triggers.touched as number,
443
+ overlap: triggers.overlap as number,
444
+ verify_all: triggers.verify_all as number,
445
+ },
446
+ live,
447
+ resolved_verified: (raw.resolved_verified as number | undefined) ?? 0,
448
+ resolved_ids: (resolvedIds as string[] | undefined) ?? [],
449
+ returned: (raw.returned as number | undefined) ?? 0,
450
+ re_tiered: (raw.re_tiered as number | undefined) ?? 0,
451
+ ...(worsened === undefined ? {} : { worsened }),
452
+ },
453
+ };
454
+ }
455
+
456
+ function isRecord(value: unknown): value is Record<string, unknown> {
457
+ return typeof value === "object" && value !== null && !Array.isArray(value);
458
+ }
459
+
460
+ function isCount(value: unknown): value is number {
461
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
462
+ }
463
+
464
+ function isSeverity(value: unknown): value is Severity {
465
+ return (
466
+ value === "BLOCKER" ||
467
+ value === "CRITICAL" ||
468
+ value === "WARNING" ||
469
+ value === "SUGGESTION"
470
+ );
471
+ }
472
+
473
+ // A `live[]` row, validated to the shape the state block re-renders from —
474
+ // `c` included, because `renderStateBlock` writes it back verbatim and a row
475
+ // missing it produces a block the NEXT run's `parseStateBlock` rejects
476
+ // wholesale, which is how a state block quietly stops existing.
477
+ function asLiveFinding(value: unknown): LiveFinding | null {
478
+ if (!isRecord(value)) return null;
479
+ const { id, sev, tier, channel, status, locs, c, claim } = value;
480
+ if (typeof id !== "string" || id.length === 0) return null;
481
+ // A live row may legitimately carry the #206 sentinel (a prior whose
482
+ // severity/tier could not be recovered when it was built) — see
483
+ // classify.ts's `isRecoveredSeverity`/`isRecoveredTier`.
484
+ if (!isRecoveredSeverity(sev)) return null;
485
+ if (!isRecoveredTier(tier)) return null;
486
+ if (channel !== "inline" && channel !== "outside") return null;
487
+ if (
488
+ status !== "carried" &&
489
+ status !== "unconfirmed" &&
490
+ status !== "suppressed" &&
491
+ status !== "deferred"
492
+ ) {
493
+ return null;
494
+ }
495
+ if (!Array.isArray(locs) || !locs.every((loc) => typeof loc === "string")) {
496
+ return null;
497
+ }
498
+ if (typeof c !== "string" || !/^[0-9a-f]{12}$/.test(c)) return null;
499
+ if (typeof claim !== "string") return null;
500
+ return { id, sev, tier, channel, status, locs: [...locs], c, claim };
501
+ }
502
+
503
+ export interface NameStatus {
504
+ files: string[];
505
+ deleted: string[];
506
+ renameMap: Map<string, string>;
507
+ }
508
+
509
+ // `git diff --name-status` lines. Renames are `R100\told\tnew`. Every path
510
+ // mentioned — including deleted and the old side of a rename — is a touched
511
+ // path: S-revert needs the unrestricted L..H set, not the surviving dest.
512
+ export function parseNameStatus(stdout: string): NameStatus {
513
+ const files = new Set<string>();
514
+ const deleted: string[] = [];
515
+ const renameMap = new Map<string, string>();
516
+ for (const line of stdout.split("\n")) {
517
+ if (line.length === 0) continue;
518
+ const status = line[0];
519
+ const rest = line.slice(1).replace(/^\d*/, "").replace(/^\t/, "");
520
+ const parts = rest.split("\t").filter((p) => p.length > 0);
521
+ if (status === "R" || status === "C") {
522
+ const from = parts[0];
523
+ const to = parts[1];
524
+ if (from === undefined || to === undefined) continue;
525
+ renameMap.set(from, to);
526
+ files.add(from);
527
+ files.add(to);
528
+ continue;
529
+ }
530
+ const path = parts[0];
531
+ if (path === undefined) continue;
532
+ files.add(path);
533
+ if (status === "D") deleted.push(path);
534
+ }
535
+ return {
536
+ files: [...files].sort(),
537
+ deleted: deleted.sort(),
538
+ renameMap,
539
+ };
540
+ }
541
+
542
+ export function buildPhaseBQueue(input: {
543
+ case: RereviewCase;
544
+ priors: readonly PriorRecord[];
545
+ nameStatus: NameStatus;
546
+ summaryUpdatedAt: string | null;
547
+ // Rereview-coverage fix wiring gap: threads `DiscoveryPlan.verifyAll`
548
+ // (rereview/plan.ts) into classifyPrior's ctx — see PhaseBContext's WHY
549
+ // in rereview/classify.ts. Optional/defaulted false so every pre-existing
550
+ // call site (case D/E already force verify_all off `case` alone) keeps
551
+ // its exact behavior untouched.
552
+ verifyAll?: boolean;
553
+ }): {
554
+ queued: VerifyQueueEntry[];
555
+ overlapCandidates: VerifyQueueEntry[];
556
+ settled: PhaseBResult[];
557
+ } {
558
+ const deltaFiles = new Set(input.nameStatus.files);
559
+ const ctx = {
560
+ case: input.case,
561
+ deletedFiles: new Set(input.nameStatus.deleted),
562
+ renameMap: input.nameStatus.renameMap,
563
+ touched: (identity: FindingIdentity) =>
564
+ [...identity.keys()].some((path) => deltaFiles.has(path)),
565
+ summaryUpdatedAt: input.summaryUpdatedAt,
566
+ verifyAll: input.verifyAll ?? false,
567
+ };
568
+ const queued: VerifyQueueEntry[] = [];
569
+ const overlapCandidates: VerifyQueueEntry[] = [];
570
+ const settled: PhaseBResult[] = [];
571
+ for (const prior of input.priors) {
572
+ const result = classifyPrior(prior, ctx);
573
+ settled.push(result);
574
+ const entry = {
575
+ priorId: prior.id,
576
+ sev: prior.sev,
577
+ trigger: result.trigger ?? "touched",
578
+ claim: prior.claim,
579
+ locs: result.locs,
580
+ authorReply: "",
581
+ commentBody: "",
582
+ triageTag: prior.triage?.tag ?? "",
583
+ deltaHunks: "",
584
+ };
585
+ if (result.status === "queued" && result.trigger !== undefined) {
586
+ queued.push({ ...entry, trigger: result.trigger });
587
+ } else if (result.status === "carried") {
588
+ overlapCandidates.push(entry);
589
+ }
590
+ }
591
+ return { queued, overlapCandidates, settled };
592
+ }
593
+
594
+ export function priorsFromStateFindings(
595
+ findings: readonly StateFinding[],
596
+ ): PriorRecord[] {
597
+ return findings.map((finding) => ({
598
+ id: finding.id,
599
+ sev: finding.sev,
600
+ tier: finding.tier,
601
+ channel: finding.channel,
602
+ locs: finding.locs,
603
+ claim: finding.claim,
604
+ triage: null,
605
+ newThreadReply: false,
606
+ }));
607
+ }
608
+
609
+ // #206's fix: the fallback that runs whenever the previous summary's
610
+ // `pr-hero-state` block cannot supply priors — missing, unparseable, or (the
611
+ // ROUTINE case, not a rare one: a FIRST review never writes a state block at
612
+ // all, see `postInlineFindings`'s `framing === undefined` branch in
613
+ // src/pr/pr.ts) simply absent because this is the PR's second review. It
614
+ // used to hardcode `sev: "WARNING"` / `tier: "advisory"` / `claim: ""` for
615
+ // EVERY prior here — silently downgrading a live BLOCKER to a warning on
616
+ // every second review of every PR, and collapsing every claim-less row onto
617
+ // `claimFingerprint("")`'s shared constant.
618
+ //
619
+ // `body` is the posted comment's raw text (the marker line alone carries no
620
+ // sev/tier/claim — `findingMarker` signs only the claim's fingerprint, never
621
+ // the claim itself). `parseFindingCommentBadge` recovers the real values
622
+ // from the SAME renderer that wrote them (`findingBodyLines`,
623
+ // review/report.ts). When it cannot (a foreign/older comment shape, or a
624
+ // truly empty body), the prior gets the explicit UNRECOVERABLE sentinels
625
+ // instead of a guessed real value — see classify.ts's WHY on those types for
626
+ // why every downstream consumer fails toward visibility, never a wrong
627
+ // bucket.
628
+ export function priorsFromPostedMarkers(
629
+ posted: readonly {
630
+ path: string;
631
+ line: number;
632
+ channel: "inline" | "outside";
633
+ body: string;
634
+ }[],
635
+ ): PriorRecord[] {
636
+ return posted.map((item, i) => {
637
+ const recovered = parseFindingCommentBadge(item.body);
638
+ return {
639
+ id: `R${String(i + 1).padStart(3, "0")}`,
640
+ sev: recovered?.sev ?? SEVERITY_UNRECOVERABLE,
641
+ tier: recovered?.tier ?? TIER_UNRECOVERABLE,
642
+ channel: item.channel,
643
+ locs: [`${item.path}:${item.line}`],
644
+ claim: recovered?.claim ?? "",
645
+ triage: null,
646
+ newThreadReply: false,
647
+ };
648
+ });
649
+ }
650
+
651
+ // A previously posted per-finding comment, as much of it as the prior→comment
652
+ // binding needs. Deliberately NOT narrowed to `{ id, marker: { c } }`: that
653
+ // narrowing is what made the two consumers below structurally unable to
654
+ // consult the path and line sitting right there in the marker, so both keyed
655
+ // on `c` alone and neither could ever bind a prior recovered by
656
+ // `priorsFromPostedMarkers` (claim `""`, so a fingerprint no real marker
657
+ // carries). Types are a place bugs hide.
658
+ export interface PostedForPrior {
659
+ id: number;
660
+ marker: { path: string; line: number; c: string };
661
+ // GitHub's live projection of a REVIEW comment. Present only for the
662
+ // review channel, and only a projection — see the two-projection rule in
663
+ // `bindPriorsToPosted`.
664
+ livePath?: string;
665
+ liveLine?: number;
666
+ }
667
+
668
+ // THE PRIOR→COMMENT BINDING, and the one place `c` is allowed to speak here.
669
+ //
670
+ // Three identity regimes now live in this codebase and they are NOT
671
+ // interchangeable. Naming them together because conflating two of them is
672
+ // exactly the defect this function replaces:
673
+ //
674
+ // 1. marker-strict — `matchPostedFindingExact` (`src/triage/reply.ts:63-88`):
675
+ // path + line + headSha + c, live projection ignored ON PURPOSE. It binds
676
+ // a triage reply to the comment a human was looking at, and design §3.5
677
+ // says the marker stays strict there.
678
+ // 2. the §3.5 loc-SET identity — `identitiesMatch`
679
+ // (`src/rereview/identity.ts`): equal-or-contained path sets with
680
+ // overlapping spans. It pairs two FINDINGS across runs. It cannot serve
681
+ // here: a posted comment has ONE anchor while a prior may carry many
682
+ // locs, so `identitiesMatch` would refuse every multi-loc prior its own
683
+ // single-anchor comment.
684
+ // 3. this one — the comment's anchor must land within the window of one of
685
+ // the prior's locs on the same normalized path; `c` breaks a distance
686
+ // TIE and nothing else.
687
+ //
688
+ // WHY the anchor is tested against BOTH the marker's stored path/line and the
689
+ // live projection, taking whichever is nearer: GitHub re-anchors a review
690
+ // comment's live `line` whenever the PR's diff changes, including when the
691
+ // BASE advances with no new push (`src/pr/inline.ts:213-219`). A state-block
692
+ // prior still at `a.ts:100` and its own comment now projected to `a.ts:112`
693
+ // is zero-drift; live-only matching would miss it and silently drop the
694
+ // author's triage — the same class of invisible failure being fixed.
695
+ //
696
+ // WHY `c` is not a requirement even for a lone candidate: a prior recovered
697
+ // from posted markers has no claim at all, and LLM claim wording drifts run
698
+ // to run for the same defect. Requiring `c` would re-elevate the tie-breaker
699
+ // to an identity from the other direction.
700
+ //
701
+ // One-to-one, and the assignment is GLOBAL by distance — never greedy in
702
+ // `priors` array order. That order-dependence was a real defect: with prior A
703
+ // at {X:0, Y:1} and prior B whose only candidate is X at 1, walking the array
704
+ // gave A→X, B→nothing on `[A, B]` and B→X, A→Y on `[B, A]`. Two orderings of
705
+ // the SAME state, two different sets of threads collapsed; and `priors` order
706
+ // is whatever the state block happened to serialise, i.e. arbitrary.
707
+ //
708
+ // The algorithm, and the invariant that makes it order-free:
709
+ // * every (prior, comment) pair inside the window is a candidate, computed
710
+ // once up front;
711
+ // * distances are processed in increasing order, and a level runs
712
+ // synchronous rounds until it quiesces: each round every eligible prior
713
+ // makes at most ONE proposal, then every contested comment is resolved.
714
+ // Nothing inside a round reads array position, so a round's outcome is a
715
+ // function of the state alone.
716
+ // * a round always changes state when it has active pairs (a prior either
717
+ // proposes or is disqualified; a proposal either binds or blocks its
718
+ // comment), so a level cannot quiesce with a nearer pair still live —
719
+ // that is what keeps "nearest first" true, and what terminates the loop.
720
+ //
721
+ // The two ambiguity rules, both "bind NOTHING" as before:
722
+ // * prior side — a prior tied across several comments at its current best
723
+ // distance is resolved by `c`, and disqualified for good when `c` cannot
724
+ // (exactly today's rule, which also never fell through to a farther
725
+ // comment);
726
+ // * comment side — the mirror, which array-order greed used to decide by
727
+ // position: several priors proposing the SAME comment at the same
728
+ // distance are resolved by `c`, and when `c` cannot, that comment is
729
+ // blocked for everyone. The losers of a `c`-resolved contest are NOT
730
+ // disqualified; their comment is simply gone, so they fall to their next
731
+ // distance like any other prior.
732
+ //
733
+ // Direction of error stays under-match — a missed binding costs a dropped
734
+ // triage tag or a thread left open; an over-match puts a "✅ RESOLVED ·
735
+ // verified gone" reply on a still-live finding.
736
+ export function bindPriorsToPosted<T extends PostedForPrior>(
737
+ priors: readonly { id: string; locs: readonly string[]; claim: string }[],
738
+ posted: readonly T[],
739
+ window: number = IDENTITY_LINE_WINDOW,
740
+ ): Map<string, T> {
741
+ interface Pair {
742
+ priorId: string;
743
+ claim: string;
744
+ row: T;
745
+ distance: number;
746
+ }
747
+ const pairs: Pair[] = [];
748
+ for (const prior of priors) {
749
+ const identity = identityFromLocs(prior.locs);
750
+ if (identity.size === 0) continue;
751
+ for (const row of posted) {
752
+ const distance = anchorDistance(identity, row, window);
753
+ if (distance === null) continue;
754
+ pairs.push({ priorId: prior.id, claim: prior.claim, row, distance });
755
+ }
756
+ }
757
+
758
+ const bound = new Map<string, T>();
759
+ // A comment is consumable once (`consumed`), or by nobody at all when an
760
+ // equidistant contest over it could not be resolved (`blocked`). A prior
761
+ // whose own best-distance set was ambiguous binds nothing ever
762
+ // (`disqualified`).
763
+ const consumed = new Set<number>();
764
+ const blocked = new Set<number>();
765
+ const disqualified = new Set<string>();
766
+
767
+ const distances = [...new Set(pairs.map((pair) => pair.distance))].sort(
768
+ (a, b) => a - b,
769
+ );
770
+ for (const distance of distances) {
771
+ for (;;) {
772
+ const active = pairs.filter(
773
+ (pair) =>
774
+ pair.distance === distance &&
775
+ !bound.has(pair.priorId) &&
776
+ !disqualified.has(pair.priorId) &&
777
+ !consumed.has(pair.row.id) &&
778
+ !blocked.has(pair.row.id),
779
+ );
780
+ if (active.length === 0) break;
781
+
782
+ const byPrior = new Map<string, Pair[]>();
783
+ for (const pair of active) {
784
+ const group = byPrior.get(pair.priorId);
785
+ if (group === undefined) byPrior.set(pair.priorId, [pair]);
786
+ else group.push(pair);
787
+ }
788
+ let changed = false;
789
+ const proposals: Pair[] = [];
790
+ for (const [priorId, group] of byPrior) {
791
+ const winner = resolvePriorTie(group, group[0]?.claim ?? "");
792
+ if (winner === undefined) {
793
+ disqualified.add(priorId);
794
+ changed = true;
795
+ continue;
796
+ }
797
+ const proposal = group.find((pair) => pair.row.id === winner.id);
798
+ if (proposal !== undefined) proposals.push(proposal);
799
+ }
800
+
801
+ const byRow = new Map<number, Pair[]>();
802
+ for (const pair of proposals) {
803
+ const group = byRow.get(pair.row.id);
804
+ if (group === undefined) byRow.set(pair.row.id, [pair]);
805
+ else group.push(pair);
806
+ }
807
+ for (const [rowId, group] of byRow) {
808
+ const winner = resolveRowTie(group);
809
+ if (winner === undefined) {
810
+ blocked.add(rowId);
811
+ changed = true;
812
+ continue;
813
+ }
814
+ bound.set(winner.priorId, winner.row);
815
+ consumed.add(rowId);
816
+ changed = true;
817
+ }
818
+ // Unreachable while `active` is non-empty (every branch above changes
819
+ // state); kept because a loop whose termination depends on that
820
+ // reasoning holding forever is one refactor away from hanging a post.
821
+ if (!changed) break;
822
+ }
823
+ }
824
+ return bound;
825
+ }
826
+
827
+ // Nearest approach of the comment's anchor to any of the prior's spans on a
828
+ // shared path, over both projections; null when neither lands within window.
829
+ function anchorDistance(
830
+ identity: FindingIdentity,
831
+ row: PostedForPrior,
832
+ window: number,
833
+ ): number | null {
834
+ const projections: readonly (readonly [string, number])[] = [
835
+ [row.marker.path, row.marker.line],
836
+ [row.livePath ?? row.marker.path, row.liveLine ?? row.marker.line],
837
+ ];
838
+ let best: number | null = null;
839
+ for (const [path, line] of projections) {
840
+ const spans = identity.get(normalizePath(path));
841
+ if (spans === undefined) continue;
842
+ for (const span of spans) {
843
+ const distance =
844
+ line < span.start
845
+ ? span.start - line
846
+ : line > span.end
847
+ ? line - span.end
848
+ : 0;
849
+ if (distance > window) continue;
850
+ if (best === null || distance < best) best = distance;
851
+ }
852
+ }
853
+ return best;
854
+ }
855
+
856
+ function resolvePriorTie<T extends PostedForPrior>(
857
+ tied: readonly { row: T; distance: number }[],
858
+ claim: string,
859
+ ): T | undefined {
860
+ if (tied.length === 1) return tied[0]?.row;
861
+ // No claim, no tie-break: `claimFingerprint("")` is a real constant hash
862
+ // (`e3b0c44298fc`) that every empty-claim prior shares, so consulting it
863
+ // here would hand the whole tied set to whichever row came first.
864
+ if (claim.trim().length === 0) return undefined;
865
+ const fingerprint = claimFingerprint(claim);
866
+ const matching = tied.filter((c) => c.row.marker.c === fingerprint);
867
+ return matching.length === 1 ? matching[0]?.row : undefined;
868
+ }
869
+
870
+ // The mirror of `resolvePriorTie`, for the contest array-order greed used to
871
+ // settle by position: several priors at the SAME distance from one comment.
872
+ // Same rule, read the other way — `c` may break the tie and nothing else, an
873
+ // empty claim cannot vote (`claimFingerprint("")` is a constant every
874
+ // claim-less prior shares), and anything short of exactly one match leaves the
875
+ // comment to nobody.
876
+ function resolveRowTie<T extends PostedForPrior>(
877
+ contenders: readonly { priorId: string; claim: string; row: T }[],
878
+ ): { priorId: string; row: T } | undefined {
879
+ if (contenders.length === 1) return contenders[0];
880
+ const matching = contenders.filter(
881
+ (contender) =>
882
+ contender.claim.trim().length > 0 &&
883
+ contender.row.marker.c === claimFingerprint(contender.claim),
884
+ );
885
+ return matching.length === 1 ? matching[0] : undefined;
886
+ }
887
+
888
+ // T5b: the pending dismissals of blocking priors, at most MAX_ADJUDICATIONS_PER_RUN.
889
+ // WHY advisory priors never cost an adjudicator call: only a blocking prior's
890
+ // dismissal can leave the gate count, so nothing else is worth a ruling.
891
+ // WHY an "inconclusive" ruling stays pending: it counts as not upheld, and a
892
+ // later recheck may retry the same dismissal and get a ruling.
893
+ export function adjudicationQueue(
894
+ priors: readonly PriorRecord[],
895
+ ): AdjudicationSubject[] {
896
+ const subjects: AdjudicationSubject[] = [];
897
+ const retried: AdjudicationSubject[] = [];
898
+ for (const prior of priors) {
899
+ if (prior.tier !== "blocking" && prior.tier !== TIER_UNRECOVERABLE) {
900
+ continue;
901
+ }
902
+ const triage = prior.triage;
903
+ if (
904
+ triage?.tag !== "dismissed" ||
905
+ triage.replyId === undefined ||
906
+ triage.threadId === undefined ||
907
+ (triage.ciVerdict != null && triage.ciVerdict !== "inconclusive")
908
+ ) {
909
+ continue;
910
+ }
911
+ const subject: AdjudicationSubject = {
912
+ priorId: prior.id,
913
+ threadId: triage.threadId,
914
+ replyId: triage.replyId,
915
+ sev: prior.sev,
916
+ locs: prior.locs,
917
+ claim: prior.claim,
918
+ argument: triage.argument ?? "",
919
+ };
920
+ // WHY never-ruled first: an inconclusive ruling is retried, and the model often
921
+ // answers the same way, so retries must not take every slot from a dismissal
922
+ // that was never ruled on.
923
+ if (triage.ciVerdict === "inconclusive") retried.push(subject);
924
+ else subjects.push(subject);
925
+ }
926
+ return [...subjects, ...retried].slice(0, MAX_ADJUDICATIONS_PER_RUN);
927
+ }
928
+
929
+ export function enrichPriorsFromThreads(input: {
930
+ priors: readonly PriorRecord[];
931
+ posted: readonly PostedForPrior[];
932
+ // The head under review. A bot verdict counts only when its `head=` is this
933
+ // head; when it is undefined no bot verdict counts.
934
+ headSha?: string;
935
+ replies: readonly {
936
+ id?: number;
937
+ user?: string;
938
+ in_reply_to_id: number | null;
939
+ body: string;
940
+ created_at?: string;
941
+ }[];
942
+ summaryUpdatedAt: string | null;
943
+ }): PriorRecord[] {
944
+ const bound = bindPriorsToPosted(input.priors, input.posted);
945
+ return input.priors.map((prior) => {
946
+ const parent = bound.get(prior.id);
947
+ if (parent === undefined) return prior;
948
+ const thread = input.replies.filter(
949
+ (reply) => reply.in_reply_to_id === parent.id,
950
+ );
951
+ let triage: PriorTriage | null = prior.triage;
952
+ for (const reply of thread) {
953
+ const marker = parseTriageMarker(reply.body);
954
+ if (marker === null) continue;
955
+ triage = {
956
+ tag: marker.tag,
957
+ verdict: marker.verdict ?? null,
958
+ createdAt: reply.created_at ?? null,
959
+ ...(reply.id === undefined ? {} : { replyId: reply.id }),
960
+ threadId: parent.id,
961
+ argument: reply.body.split("\n").slice(1).join("\n").trim(),
962
+ ciVerdict: null,
963
+ };
964
+ }
965
+ // WHY only GitHub's author field is trusted: the marker text is typed by
966
+ // anyone, so a verdict from any other login is ignored. The LAST match
967
+ // in thread order wins, and only for the latest triage reply.
968
+ // WHY the head must match too: a push may change the code the ruling read,
969
+ // so a verdict on an earlier head is stale and a later head needs a new
970
+ // recheck. With no headSha, no bot verdict can be shown current.
971
+ if (triage?.replyId !== undefined && input.headSha !== undefined) {
972
+ for (const reply of thread) {
973
+ if (reply.user !== CI_ADJUDICATOR_LOGIN) continue;
974
+ const adjudication = parseAdjudicationMarker(reply.body);
975
+ if (
976
+ adjudication === null ||
977
+ adjudication.reply !== triage.replyId ||
978
+ adjudication.head !== input.headSha
979
+ ) {
980
+ continue;
981
+ }
982
+ triage = { ...triage, ciVerdict: adjudication.verdict };
983
+ }
984
+ }
985
+ const newThreadReply = thread.some(
986
+ (reply) =>
987
+ reply.created_at !== undefined &&
988
+ input.summaryUpdatedAt !== null &&
989
+ reply.created_at > input.summaryUpdatedAt,
990
+ );
991
+ return { ...prior, triage, newThreadReply };
992
+ });
993
+ }
994
+
995
+ // WHY the binding runs over EVERY prior and not just the verified-gone ones:
996
+ // one-to-one only means anything when the carried priors get to claim their
997
+ // own comments too. Binding the verified-gone subset alone would let a
998
+ // retired prior take a still-live neighbour's thread, which is the ✅ on a
999
+ // live defect this whole function exists to avoid.
1000
+ export function collapseTargets(input: {
1001
+ verifiedGoneIds: readonly string[];
1002
+ priors: readonly { id: string; claim: string; locs: readonly string[] }[];
1003
+ posted: readonly (PostedForPrior & { channel: "review" | "issue" })[];
1004
+ }): Array<{
1005
+ priorId: string;
1006
+ commentId: number;
1007
+ channel: "review" | "issue";
1008
+ }> {
1009
+ const bound = bindPriorsToPosted(input.priors, input.posted);
1010
+ const out: Array<{
1011
+ priorId: string;
1012
+ commentId: number;
1013
+ channel: "review" | "issue";
1014
+ }> = [];
1015
+ for (const id of input.verifiedGoneIds) {
1016
+ const posted = bound.get(id);
1017
+ if (posted === undefined) continue;
1018
+ out.push({
1019
+ priorId: id,
1020
+ commentId: posted.id,
1021
+ channel: posted.channel,
1022
+ });
1023
+ }
1024
+ return out;
1025
+ }