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,1789 @@
1
+ // Known-bad corpus decisions (GitHub #43), pure so every detector, join and
2
+ // rendering rule is pinned offline. corpus/corpus.ts is the I/O shell: it walks
3
+ // merged PRs through `gh api graphql`, diffs and blames through git, and this
4
+ // module decides what those bytes mean.
5
+ //
6
+ // PURITY CONTRACT, same as pr/reverts-preflight.ts and load-bearing for the same
7
+ // reason: nothing here reads the filesystem, spawns git or gh, touches the
8
+ // network, or READS A CLOCK. The artifact must be byte-identical across two
9
+ // renders of the same data, so `diff` on it means "history changed", never
10
+ // "time passed". Every duration below is the difference of two RECORDED
11
+ // timestamps (git/gh-returned strings), never a measurement against now.
12
+ //
13
+ // Scope, straight from the issue: CANDIDATES for a human glance only. No
14
+ // review runs, nothing is scored, nothing is labelled THE defect. A bug-fix
15
+ // PR proves something was wrong — not that a reviewer should have caught it,
16
+ // and not which change introduced it.
17
+
18
+ // The byte-level git protocol constants live in ONE place: a second copy of
19
+ // "\x1f means field separator" is a second place to be wrong about a delimiter
20
+ // no author can type but every parser here trusts.
21
+ import {
22
+ type CommitPullRef,
23
+ GIT_LOG_FIELD_SEP,
24
+ pickCommitPull,
25
+ } from "#pr/reverts-preflight";
26
+ import { unquotePath } from "#review/size-gate";
27
+ import { CliUsageError } from "../errors";
28
+
29
+ // ---------------------------------------------------------------------------
30
+ // Flag values. Both defaults are spelled as literals inside review/preflight.ts's
31
+ // HELP_TEXT too; that file CANNOT import them from here (this module imports
32
+ // CliUsageError from it, so the reverse edge would be a runtime cycle). The
33
+ // corpus tests pin the two spellings together.
34
+
35
+ export const DEFAULT_PROXIMITY_DAYS = "7";
36
+
37
+ // WHY a cap at all: the proximity join walks every commit in the window
38
+ // against every unresolved fix, and the window is only ever a heuristic — a
39
+ // 365-day "nearby" suspect is numerically indistinguishable from noise while
40
+ // doubling the git-log window it forces. 90 days is the outer edge of "the
41
+ // code still resembles what the fix touched".
42
+ export const MAX_PROXIMITY_DAYS = 90;
43
+
44
+ // The proximity window in days. Validated HERE, not in parseArgs, so the
45
+ // range check is testable offline next to the join that consumes it; the
46
+ // flag's string travels verbatim through parseArgs exactly like --since's.
47
+ export function validateProximityDays(raw: string | undefined): number {
48
+ const value = raw ?? DEFAULT_PROXIMITY_DAYS;
49
+ const parsed = Number(value);
50
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > MAX_PROXIMITY_DAYS) {
51
+ throw new CliUsageError(
52
+ `--proximity-days must be an integer between 1 and ${MAX_PROXIMITY_DAYS}, ` +
53
+ `got: ${value}`,
54
+ );
55
+ }
56
+ return parsed;
57
+ }
58
+
59
+ export const DEFAULT_BUG_LABELS = "bug";
60
+
61
+ // Split, trim, drop empties, dedupe preserving first-seen order. Case is
62
+ // KEPT, never lowercased: GitHub labels are case-sensitive, and "Bug" and
63
+ // "bug" are two distinct labels there — folding them here would silently
64
+ // stop matching a repo that only spells it one way.
65
+ export function splitBugLabels(csv: string | undefined): string[] {
66
+ const value = csv ?? DEFAULT_BUG_LABELS;
67
+ const seen = new Set<string>();
68
+ const labels: string[] = [];
69
+ for (const part of value.split(",")) {
70
+ const label = part.trim();
71
+ if (label.length === 0) continue;
72
+ if (seen.has(label)) continue;
73
+ seen.add(label);
74
+ labels.push(label);
75
+ }
76
+ // An explicitly-passed csv that names nothing ("--bug-labels ,") would
77
+ // silently disable the bug-issue source entirely — the exact "typo'd key
78
+ // reads as no triggers" failure parseLocalConfig guards against.
79
+ if (labels.length === 0) {
80
+ throw new CliUsageError(
81
+ `--bug-labels must name at least one label, got: ${csv}`,
82
+ );
83
+ }
84
+ return labels;
85
+ }
86
+
87
+ // ---------------------------------------------------------------------------
88
+ // The data model.
89
+
90
+ export type CorpusSource =
91
+ | "fix-subject"
92
+ | "bug-issue"
93
+ | "incident-keyword"
94
+ | "proximity"
95
+ | "review-thread";
96
+
97
+ // Tier order in the artifact, descending confidence. These sit BELOW the
98
+ // revert tiers conceptually (body-linked > pattern-only): git's own
99
+ // machine-written linkage outranks anything inferred here. The artifact
100
+ // header says so; the revert candidates themselves live in `pr-hero reverts`.
101
+ export type CorpusConfidence =
102
+ | "issue-linked"
103
+ | "blame-linked"
104
+ | "keyword-only"
105
+ | "proximity"
106
+ | "review-caught";
107
+
108
+ export interface IntroducerInfo {
109
+ pr: number | null;
110
+ title: string | null;
111
+ mergedAt: string | null;
112
+ // The commit git blame named. Always set when the introducer exists at all
113
+ // (a PR was resolved OR it was a direct push) — the sha is the one fact
114
+ // both paths share.
115
+ blamedSha: string;
116
+ // Evidence for the human glance: WHERE blame pointed, in the exact
117
+ // `<file> <start>,<end>` form the `git blame -L` argument used.
118
+ blamedFile: string;
119
+ blamedRange: string;
120
+ }
121
+
122
+ // A fix-shaped candidate: any PR the fixes/incidents/proximity sources
123
+ // produced. Different detectors may all match one PR; `sources` records
124
+ // every one that did.
125
+ export interface CorpusCandidate {
126
+ fixPr: number;
127
+ fixTitle: string;
128
+ fixMergedAt: string | null;
129
+ sources: CorpusSource[];
130
+ // The section the entry renders under — resolved by selectCorpus's ladder,
131
+ // not by whichever detector happened to fire first.
132
+ confidence: CorpusConfidence;
133
+ // Excerpt of the matching line (see excerptLine's rules).
134
+ matchedText: string;
135
+ // bug-issue evidence: every issue ref found in the body with the labels
136
+ // that matched the bug-labels set (empty for a ref that matched none).
137
+ issueRefs: { number: number; matchedLabels: string[] }[];
138
+ // Replay range = the DEFECT SITE: the lines the fix changed are where the
139
+ // bug lived, so base..head of the FIX PR is what a reviewer would replay.
140
+ fixBaseSha: string | null;
141
+ fixHeadSha: string | null;
142
+ additions: number | null;
143
+ deletions: number | null;
144
+ changedFiles: number | null;
145
+ introducer: IntroducerInfo | null;
146
+ alsoBlamedCount: number;
147
+ // Files skipped because the fix renamed them — blame cannot point at a
148
+ // line range that changed path, and hiding the skip would overstate the
149
+ // evidence.
150
+ blameSkippedRenames: number;
151
+ proximitySuspects: {
152
+ pr: number;
153
+ title: string | null;
154
+ mergedAt: string | null;
155
+ sharedFiles: number;
156
+ gapDays: number;
157
+ }[];
158
+ }
159
+
160
+ // A thread-shaped candidate: the review-thread source's own kind. Different
161
+ // in kind from a fix candidate — this is a CAUGHT defect, labeled as such.
162
+ export interface ThreadCandidate {
163
+ pr: number;
164
+ title: string;
165
+ mergedAt: string | null;
166
+ threads: {
167
+ path: string;
168
+ line: number | null;
169
+ firstCommentAt: string;
170
+ excerpt: string;
171
+ pushSha: string;
172
+ }[];
173
+ // True when reviewThreads(first:50) reported more threads than it
174
+ // returned. The cap is a COST decision (a 500-thread PR is not 500 cases);
175
+ // truncation is recorded rather than silent so the count in the artifact
176
+ // can never be read as exhaustive.
177
+ threadsTruncated: boolean;
178
+ // Enrichment (STEP G): the PR's own range and size, exactly like a fix
179
+ // candidate's — the replay range of the PR review caught the bug in.
180
+ baseSha: string | null;
181
+ headSha: string | null;
182
+ additions: number | null;
183
+ deletions: number | null;
184
+ changedFiles: number | null;
185
+ }
186
+
187
+ // The shared evidence-excerpt rules: strip the ASCII control characters git
188
+ // streams carry (\x1f/\x1e would corrupt the markdown), collapse whitespace
189
+ // (matched "lines" come from free text that wraps), truncate. Stripping
190
+ // BEFORE collapsing matters: a control char between two spaces would
191
+ // otherwise leave a double space behind. Spaces are \x20 — not a control
192
+ // character — so they survive by construction. The strip is a char-code
193
+ // filter rather than a regex because the bytes it removes are the same
194
+ // delimiter bytes this repo's git parsers are built to trust.
195
+ function stripControlChars(line: string): string {
196
+ let out = "";
197
+ for (const char of line) {
198
+ const code = char.codePointAt(0) ?? 0;
199
+ if (code > 0x1f && code !== 0x7f) out += char;
200
+ }
201
+ return out;
202
+ }
203
+
204
+ function excerptLine(line: string, max: number): string {
205
+ return stripControlChars(line).replace(/\s+/g, " ").trim().slice(0, max);
206
+ }
207
+
208
+ // The fix-subject evidence is the TITLE itself — the anchored match IS the
209
+ // subject — run through the same excerpt rules as every other evidence line.
210
+ export function evidenceExcerpt(title: string): string {
211
+ return excerptLine(title, 160);
212
+ }
213
+
214
+ // ---------------------------------------------------------------------------
215
+ // Detector 1: fix-shaped subjects.
216
+ //
217
+ // ANCHORED at position 0, never a substring search — the single most
218
+ // important correctness rule in reverts' classifier, ported with it. A
219
+ // substring match on fix|bugfix accepts plausible-looking history that is no
220
+ // fix at all; every one of these is real musive history and NONE of them is
221
+ // a fix PR:
222
+ // docs(mus-638): handle rollback success status
223
+ // test(MUS-518): re-pin the rollback-scan tripwire after the reformat
224
+ // ci: MUS-598 revert temporary Biome probe
225
+ // A corpus polluted with those spends the human glance the whole artifact
226
+ // exists to make cheap.
227
+
228
+ const FIX_SUBJECT = /^(fix|bugfix)(\([^)]*\))?!?:/i;
229
+
230
+ export function isFixSubject(title: string): boolean {
231
+ return FIX_SUBJECT.test(title);
232
+ }
233
+
234
+ // ---------------------------------------------------------------------------
235
+ // Detector 2: closing-keyword issue refs in a PR body.
236
+
237
+ // `#<n>` preceded (same line, ≤40 chars before) by a closing keyword. The
238
+ // 40-char window keeps "fixes #123" and "fixes, a while later, #123" apart
239
+ // without a full grammar. Bare `#123` without a keyword never matches: every
240
+ // PR body mentions numbers.
241
+ const ISSUE_REF =
242
+ /\b(?:closes?|closed|fix|fixes|fixed|resolves?|resolved)\b[^#\n]{0,40}#(\d+)/gi;
243
+
244
+ export function issueRefsFromBody(body: string): number[] {
245
+ const refs: number[] = [];
246
+ for (const match of body.matchAll(ISSUE_REF)) {
247
+ const whole = match[0];
248
+ const number = Number(match[1]);
249
+ // The text between the keyword and the '#': a '/' there means the ref is
250
+ // cross-repo (`owner/repo#123`) and names an issue of ANOTHER repository
251
+ // — this repo's bug labels say nothing about it.
252
+ const hashAt = whole.indexOf("#");
253
+ if (hashAt > 0 && whole.slice(0, hashAt).includes("/")) continue;
254
+ if (!Number.isInteger(number) || number < 1) continue;
255
+ if (!refs.includes(number)) refs.push(number);
256
+ }
257
+ return refs;
258
+ }
259
+
260
+ // ---------------------------------------------------------------------------
261
+ // Detector 3: incident keywords.
262
+ //
263
+ // CRITICAL: bare issue-tracker ids must NEVER be a signal. musive carries
264
+ // `MUS-<n>` in EVERY commit subject; a tracker id says an issue exists, not
265
+ // that the tracked thing is an incident, and matching it would select the
266
+ // entire history. Word boundaries + this exact keyword set are what keep the
267
+ // detector from becoming "every PR that references its own tracker".
268
+ const INCIDENT_KEYWORDS = ["incident", "outage", "sentry", "crashlytics"];
269
+
270
+ function incidentLine(line: string): boolean {
271
+ for (const keyword of INCIDENT_KEYWORDS) {
272
+ if (new RegExp(`\\b${keyword}\\b`, "i").test(line)) return true;
273
+ }
274
+ return false;
275
+ }
276
+
277
+ // Returns the matched line as the evidence excerpt (title wins over body —
278
+ // the title is the PR's own one-line summary of itself), or null when
279
+ // nothing matched.
280
+ export function isIncidentText(title: string, body: string): string | null {
281
+ for (const line of [title, ...body.split("\n")]) {
282
+ if (incidentLine(line)) return excerptLine(line, 160);
283
+ }
284
+ return null;
285
+ }
286
+
287
+ // ---------------------------------------------------------------------------
288
+ // The fix diff → blame plan.
289
+
290
+ // ≤40 files blamed per PR. A fix that touches more is a mega-PR whose blame
291
+ // would cost 40+ git calls to say "lots of people touched lots of lines" —
292
+ // the human glance gets the diff size line and can widen later.
293
+ export const MAX_BLAMED_FILES = 40;
294
+
295
+ // ≤20 merged ranges per file. Same cost logic, one level down: 20 blame
296
+ // calls on ONE file is already a file rewritten wholesale.
297
+ export const MAX_MERGED_RANGES = 20;
298
+
299
+ export interface PreImageRange {
300
+ start: number;
301
+ end: number;
302
+ }
303
+
304
+ export interface DiffFilePlan {
305
+ path: string;
306
+ // Pre-image (`-a,b` side) line ranges: the lines the FIX changed are where
307
+ // the bug lived, so they are what blame is pointed at. Sorted, with
308
+ // overlapping or adjacent (±1 line) ranges merged to fewer blame calls.
309
+ // Empty when the file has hunks but no pre-image lines at all — the fix
310
+ // added code where none was, so there is nothing pre-existing to blame.
311
+ ranges: PreImageRange[];
312
+ }
313
+
314
+ export interface DiffBlamePlan {
315
+ files: DiffFilePlan[];
316
+ // Files the diff showed as renames. Blame is skipped for them: the
317
+ // pre-image of a rename section is not a defect site anyone can point at.
318
+ renamedPaths: string[];
319
+ // Cap accounting, recorded rather than silent: counts of files/ranges
320
+ // dropped beyond MAX_BLAMED_FILES / MAX_MERGED_RANGES.
321
+ droppedFiles: number;
322
+ droppedRanges: number;
323
+ }
324
+
325
+ const HUNK_HEADER = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
326
+
327
+ export function parseDiffHunks(diffText: string): DiffBlamePlan {
328
+ interface Section {
329
+ srcPath: string | null;
330
+ dstPath: string | null;
331
+ renamed: boolean;
332
+ hunks: number;
333
+ ranges: PreImageRange[];
334
+ }
335
+ const sections: Section[] = [];
336
+ let section: Section | null = null;
337
+ for (const line of diffText.split("\n")) {
338
+ if (line.startsWith("diff --git ")) {
339
+ section = {
340
+ srcPath: null,
341
+ dstPath: null,
342
+ renamed: false,
343
+ hunks: 0,
344
+ ranges: [],
345
+ };
346
+ sections.push(section);
347
+ continue;
348
+ }
349
+ if (section === null) continue;
350
+ // The PRE-IMAGE path (`--- a/…`) is the path blame needs: blame runs
351
+ // against the parent commit, where the old path is the only path.
352
+ if (line.startsWith("--- a/")) {
353
+ section.srcPath = unquotePath(line.slice(6));
354
+ continue;
355
+ }
356
+ if (line.startsWith("+++ b/")) {
357
+ section.dstPath = unquotePath(line.slice(6));
358
+ continue;
359
+ }
360
+ if (line.startsWith("rename from ") || line.startsWith("rename to ")) {
361
+ section.renamed = true;
362
+ if (line.startsWith("rename to ")) {
363
+ section.dstPath = unquotePath(line.slice("rename to ".length));
364
+ }
365
+ continue;
366
+ }
367
+ const hunk = HUNK_HEADER.exec(line);
368
+ if (hunk === null) continue;
369
+ section.hunks++;
370
+ const start = Number(hunk[1]);
371
+ const count = hunk[2] === undefined ? 1 : Number(hunk[2]);
372
+ if (!Number.isInteger(start) || !Number.isInteger(count)) continue;
373
+ // count 0 = pure insertion at that position: no pre-image lines exist.
374
+ if (count === 0) continue;
375
+ section.ranges.push({ start, end: start + count - 1 });
376
+ }
377
+
378
+ const plan: DiffBlamePlan = {
379
+ files: [],
380
+ renamedPaths: [],
381
+ droppedFiles: 0,
382
+ droppedRanges: 0,
383
+ };
384
+ for (const section of sections) {
385
+ if (section.renamed) {
386
+ plan.renamedPaths.push(
387
+ section.dstPath ?? section.srcPath ?? "(path unreadable)",
388
+ );
389
+ continue;
390
+ }
391
+ if (section.hunks === 0) continue; // mode change / binary: nothing to blame
392
+ if (plan.files.length >= MAX_BLAMED_FILES) {
393
+ plan.droppedFiles++;
394
+ continue;
395
+ }
396
+ const merged = mergeRanges(section.ranges);
397
+ if (merged.length > MAX_MERGED_RANGES) {
398
+ plan.droppedRanges += merged.length - MAX_MERGED_RANGES;
399
+ merged.length = MAX_MERGED_RANGES;
400
+ }
401
+ plan.files.push({
402
+ path: section.srcPath ?? section.dstPath ?? "(path unreadable)",
403
+ ranges: merged,
404
+ });
405
+ }
406
+ return plan;
407
+ }
408
+
409
+ // Overlapping ranges merge, and so do ADJACENT ones (end + 1 == next start):
410
+ // one blame call over [5,20] beats three over [5,10], [11,15], [16,20], and
411
+ // the answer is identical. A gap of 2+ lines stays split — those untouched
412
+ // lines are not part of the defect site.
413
+ function mergeRanges(ranges: PreImageRange[]): PreImageRange[] {
414
+ const sorted = [...ranges].sort((a, b) => a.start - b.start || a.end - b.end);
415
+ const merged: PreImageRange[] = [];
416
+ for (const range of sorted) {
417
+ const last = merged[merged.length - 1];
418
+ if (last !== undefined && range.start <= last.end + 1) {
419
+ if (range.end > last.end) last.end = range.end;
420
+ continue;
421
+ }
422
+ merged.push({ ...range });
423
+ }
424
+ return merged;
425
+ }
426
+
427
+ // ---------------------------------------------------------------------------
428
+ // Blame reading.
429
+
430
+ // The blame argv, built here so the flags that decide WHICH commit gets named
431
+ // are testable rather than buried in a spawn call.
432
+ //
433
+ // `-w -M -C` are load-bearing, and the measurement that bought them (2026-08-17,
434
+ // MusiveTech/musive): on a pure tabs→spaces reformat, blame WITHOUT them named
435
+ // `feat(backend): files folder system` — a 644-file, 42k-line reformat that did
436
+ // not write a line of the logic; WITH them it named `fix: download song`, the
437
+ // commit an independent forensic pass had separately identified as the true
438
+ // origin. `-w` ignores whitespace-only changes, `-M` follows lines moved inside
439
+ // a file, `-C` follows lines moved or copied in from other files.
440
+ //
441
+ // It is a PARTIAL fix and the tier is still not trustworthy: on a biome REFLOW
442
+ // (a one-line arrow body split across three lines) the same measurement showed
443
+ // the flags change nothing, because those really are new lines and blame is
444
+ // right to say so. `blame-linked` keeps meaning "the last toucher of these
445
+ // lines", which a human still has to check.
446
+ export function blameArgv(
447
+ parentSha: string,
448
+ filePath: string,
449
+ range: PreImageRange,
450
+ ): string[] {
451
+ return [
452
+ "blame",
453
+ "--porcelain",
454
+ "-w",
455
+ "-M",
456
+ "-C",
457
+ "-L",
458
+ `${range.start},${range.end}`,
459
+ parentSha,
460
+ "--",
461
+ filePath,
462
+ ];
463
+ }
464
+
465
+ // `git blame --porcelain`: header lines are exactly
466
+ // `<40-hex sha> <orig-line> <final-line>[ <count>]`; content lines open with
467
+ // a TAB; everything else (author, boundary, previous, filename…) is metadata
468
+ // that never matches the header shape. Distinct shas, first-seen order —
469
+ // deterministic for deterministic input.
470
+ const BLAME_HEADER = /^([0-9a-f]{40}) \d+ \d+(?: \d+)?$/;
471
+
472
+ export function parseBlamePorcelain(raw: string): string[] {
473
+ const shas: string[] = [];
474
+ for (const line of raw.split("\n")) {
475
+ const header = BLAME_HEADER.exec(line);
476
+ const sha = header?.[1];
477
+ if (sha !== undefined && !shas.includes(sha)) shas.push(sha);
478
+ }
479
+ return shas;
480
+ }
481
+
482
+ // `git show -s --format=%H\x1f%ct <shas…>` → sha → committer unix seconds.
483
+ // One batch per PR: the dates exist to pick ONE introducer, and a spawn per
484
+ // sha would bill the same latency this command is trying not to have.
485
+ export function parseCommitDates(raw: string): Map<string, number> {
486
+ const dates = new Map<string, number>();
487
+ for (const line of raw.split("\n")) {
488
+ if (line.trim().length === 0) continue;
489
+ const fields = line.split(GIT_LOG_FIELD_SEP);
490
+ if (fields.length < 2) {
491
+ throw new CliUsageError(
492
+ `commit date record has ${fields.length} field(s), expected 2 (sha, date)`,
493
+ );
494
+ }
495
+ const sha = (fields[0] ?? "").trim();
496
+ if (!/^[0-9a-f]{40}$/.test(sha)) {
497
+ throw new CliUsageError(
498
+ `commit date record has no full sha, got: ${sha}`,
499
+ );
500
+ }
501
+ const seconds = Number((fields[1] ?? "").trim());
502
+ if (!Number.isInteger(seconds)) {
503
+ throw new CliUsageError(
504
+ `commit date record ${sha} has a non-integer date: ${fields[1]}`,
505
+ );
506
+ }
507
+ dates.set(sha, seconds);
508
+ }
509
+ return dates;
510
+ }
511
+
512
+ // `git rev-list --parents -n 1 <sha>` → the parent SHAs, in the order git
513
+ // printed them. First-parent is [0]. A root commit is a legal empty list.
514
+ // Used by the shell to tell merge (2 parents) from squash/rebase (1 parent)
515
+ // without asking GitHub for a merge_method it does not expose after merge.
516
+ export function parseCommitParents(raw: string): string[] {
517
+ const line = raw.trim().split("\n")[0] ?? "";
518
+ const fields = line.split(/\s+/).filter((field) => field.length > 0);
519
+ if (fields.length === 0) {
520
+ throw new CliUsageError("commit parents record is empty");
521
+ }
522
+ const sha = fields[0] ?? "";
523
+ if (!/^[0-9a-f]{40}$/.test(sha)) {
524
+ throw new CliUsageError(
525
+ `commit parents record has no full sha, got: ${sha}`,
526
+ );
527
+ }
528
+ const parents = fields.slice(1);
529
+ for (const parent of parents) {
530
+ if (!/^[0-9a-f]{40}$/.test(parent)) {
531
+ throw new CliUsageError(
532
+ `commit parents record has a non-sha parent: ${parent}`,
533
+ );
534
+ }
535
+ }
536
+ return parents;
537
+ }
538
+
539
+ export interface BlamedSha {
540
+ sha: string;
541
+ committedAtSec: number;
542
+ file: string;
543
+ range: string;
544
+ }
545
+
546
+ export interface IntroducerPick {
547
+ sha: string;
548
+ file: string;
549
+ range: string;
550
+ alsoBlamedCount: number;
551
+ }
552
+
553
+ // The NEWEST commit blame named wins, ties broken by sha ascending so two
554
+ // runs over unchanged history cannot disagree. WHY newest rather than oldest:
555
+ // blame names every commit that ever touched the range, and the most recent
556
+ // toucher is the best single guess at "the code as the fix found it" — an
557
+ // older touch may have been perfectly fine and fixed forward since. The rest
558
+ // are counted, not hidden.
559
+ export function pickIntroducer(blamed: BlamedSha[]): IntroducerPick | null {
560
+ if (blamed.length === 0) return null;
561
+ // The same sha in several ranges is ONE candidate (one commit edited the
562
+ // same broken function twice); its evidence is the first range seen.
563
+ const bySha = new Map<string, BlamedSha>();
564
+ for (const entry of blamed) {
565
+ if (!bySha.has(entry.sha)) bySha.set(entry.sha, entry);
566
+ }
567
+ let winner: BlamedSha | null = null;
568
+ for (const entry of bySha.values()) {
569
+ if (winner === null) {
570
+ winner = entry;
571
+ continue;
572
+ }
573
+ if (entry.committedAtSec > winner.committedAtSec) {
574
+ winner = entry;
575
+ } else if (
576
+ entry.committedAtSec === winner.committedAtSec &&
577
+ entry.sha.localeCompare(winner.sha) < 0
578
+ ) {
579
+ winner = entry;
580
+ }
581
+ }
582
+ if (winner === null) return null;
583
+ return {
584
+ sha: winner.sha,
585
+ file: winner.file,
586
+ range: winner.range,
587
+ alsoBlamedCount: bySha.size - 1,
588
+ };
589
+ }
590
+
591
+ // ---------------------------------------------------------------------------
592
+ // Proximity.
593
+
594
+ // WHY lockfiles are excluded from the overlap: a shared lockfile says nothing
595
+ // about causation and matches nearly every busy-week PR pair — without this,
596
+ // "touched the same files" degenerates into "was open that week".
597
+ export const LOCKFILE_PATHS =
598
+ /(?:^|\/)(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|go\.sum)$|\.(?:lock|lockb)$/;
599
+
600
+ export function isLockfilePath(path: string): boolean {
601
+ return LOCKFILE_PATHS.test(path);
602
+ }
603
+
604
+ export interface CommitIndexEntry {
605
+ sha: string;
606
+ committedAtSec: number;
607
+ files: string[];
608
+ }
609
+
610
+ export interface CommitPrRef {
611
+ pr: number;
612
+ title: string | null;
613
+ mergedAt: string | null;
614
+ }
615
+
616
+ export interface ProximityFix {
617
+ fixPr: number;
618
+ fixMergedAt: string | null;
619
+ // The files blame was pointed at for this fix (the defect site) — the
620
+ // overlap is computed over exactly those.
621
+ files: string[];
622
+ }
623
+
624
+ export interface ProximitySuspect {
625
+ pr: number;
626
+ title: string | null;
627
+ mergedAt: string | null;
628
+ sharedFiles: number;
629
+ gapDays: number;
630
+ }
631
+
632
+ // At most three suspects: the list exists to hand a human a NEXT place to
633
+ // look, and three already-tested places beat an unranked page of them.
634
+ export const MAX_PROXIMITY_SUSPECTS = 3;
635
+
636
+ const DAY_MS = 86_400_000;
637
+
638
+ // The pure join. `fixes` are the unresolved entries only — that gate is the
639
+ // caller's rule (an entry whose introducer resolved has no need of a
640
+ // heuristic), which is why it is not re-tested here. Every duration is the
641
+ // difference of two recorded stamps: fixMergedAt (GitHub) minus the commit's
642
+ // committer seconds (git).
643
+ export function joinProximity(
644
+ fixes: ProximityFix[],
645
+ commitIndex: CommitIndexEntry[],
646
+ proximityDays: number,
647
+ prBySha: Map<string, CommitPrRef>,
648
+ ): Map<number, ProximitySuspect[]> {
649
+ const out = new Map<number, ProximitySuspect[]>();
650
+ const windowMs = proximityDays * DAY_MS;
651
+ for (const fix of fixes) {
652
+ out.set(fix.fixPr, []);
653
+ if (fix.fixMergedAt === null) continue;
654
+ const fixMs = Date.parse(fix.fixMergedAt);
655
+ if (Number.isNaN(fixMs)) continue;
656
+ // Lockfiles drop out of the DEFECT-SIDE set too, so a fix that only
657
+ // touched a lockfile matches nobody — deliberately: it is not a defect
658
+ // site anyone can replay.
659
+ const fixFiles = new Set(fix.files.filter((p) => !isLockfilePath(p)));
660
+ if (fixFiles.size === 0) continue;
661
+ // Group by PR first: one PR with three commits in the window is ONE
662
+ // suspect (the same triple-weighting lesson as reverts' pair dedupe) —
663
+ // union the shared files, keep the SMALLEST gap (its most recent commit).
664
+ const perPr = new Map<
665
+ number,
666
+ { ref: CommitPrRef; shared: Set<string>; gapDays: number }
667
+ >();
668
+ for (const commit of commitIndex) {
669
+ const ref = prBySha.get(commit.sha);
670
+ if (ref === undefined) continue; // direct push, or a PR outside the walk
671
+ if (ref.pr === fix.fixPr) continue; // a PR is never prior to itself
672
+ const gapMs = fixMs - commit.committedAtSec * 1000;
673
+ // 0 < gap ≤ N: strictly before the fix (a commit AT the fix's merge
674
+ // instant is the fix itself), and inside the window — exactly N days
675
+ // is in, N days plus a second is out.
676
+ if (!(gapMs > 0 && gapMs <= windowMs)) continue;
677
+ const shared = commit.files.filter(
678
+ (p) => !isLockfilePath(p) && fixFiles.has(p),
679
+ );
680
+ if (shared.length === 0) continue;
681
+ const gapDays = Math.round((gapMs / DAY_MS) * 10) / 10;
682
+ const existing = perPr.get(ref.pr);
683
+ if (existing === undefined) {
684
+ perPr.set(ref.pr, {
685
+ ref,
686
+ shared: new Set(shared),
687
+ gapDays,
688
+ });
689
+ continue;
690
+ }
691
+ for (const p of shared) existing.shared.add(p);
692
+ if (gapDays < existing.gapDays) existing.gapDays = gapDays;
693
+ }
694
+ const suspects = [...perPr.values()].map((entry) => ({
695
+ pr: entry.ref.pr,
696
+ title: entry.ref.title,
697
+ mergedAt: entry.ref.mergedAt,
698
+ sharedFiles: entry.shared.size,
699
+ gapDays: entry.gapDays,
700
+ }));
701
+ suspects.sort((a, b) => {
702
+ if (a.sharedFiles !== b.sharedFiles) return b.sharedFiles - a.sharedFiles;
703
+ const am = a.mergedAt === null ? Number.NaN : Date.parse(a.mergedAt);
704
+ const bm = b.mergedAt === null ? Number.NaN : Date.parse(b.mergedAt);
705
+ if (!Number.isNaN(am) && !Number.isNaN(bm) && am !== bm) return bm - am;
706
+ if (Number.isNaN(am) !== Number.isNaN(bm)) {
707
+ return Number.isNaN(am) ? 1 : -1;
708
+ }
709
+ return a.pr - b.pr;
710
+ });
711
+ out.set(fix.fixPr, suspects.slice(0, MAX_PROXIMITY_SUSPECTS));
712
+ }
713
+ return out;
714
+ }
715
+
716
+ // ---------------------------------------------------------------------------
717
+ // Review threads.
718
+
719
+ // 50 threads per PR / 50 PRs per graphql batch. Both are COST caps: the
720
+ // thread list beyond the first page and the PRs beyond a batch are capped
721
+ // work a $0 read-only scan cannot grow into. Truncation is recorded
722
+ // (threadsTruncated), never silent.
723
+ export const THREAD_PAGE_SIZE = 50;
724
+ export const THREAD_BATCH_SIZE = 50;
725
+
726
+ // The batch document. PR numbers are integers interpolated into the query
727
+ // text — the ONLY safe interpolation, because they arrived as validated
728
+ // integers from our own walk parser: no quoting context exists for them to
729
+ // break. Everything else travels as graphql variables.
730
+ export function buildThreadBatchQuery(numbers: number[]): string {
731
+ const aliases = numbers
732
+ .map(
733
+ (n, i) =>
734
+ `p${i}: pullRequest(number:${n}){reviewThreads(first:${THREAD_PAGE_SIZE})` +
735
+ "{pageInfo{hasNextPage}nodes{isResolved comments(first:1){nodes{" +
736
+ "path line originalLine createdAt body author{__typename}}}}}}",
737
+ )
738
+ .join(" ");
739
+ return (
740
+ "query($repoOwner:String!,$repoName:String!){repository(owner:$repoOwner," +
741
+ `name:$repoName){${aliases}}}`
742
+ );
743
+ }
744
+
745
+ export interface RawReviewThread {
746
+ isResolved: boolean;
747
+ path: string | null;
748
+ line: number | null;
749
+ firstCommentAt: string | null;
750
+ excerpt: string | null;
751
+ // GraphQL `__typename` of the first comment's author. Measured on musive
752
+ // 2026-08-16: 96 of 109 caught entries were Greptile-bot threads and only
753
+ // 13 had any human thread — #43's source is "HUMAN review comments", so
754
+ // bot-authored threads are excluded by resolvedThreadsWithPath (`Bot`),
755
+ // not by the query.
756
+ authorType: string | null;
757
+ }
758
+
759
+ export interface ThreadBatchEntry {
760
+ threads: RawReviewThread[];
761
+ truncated: boolean;
762
+ }
763
+
764
+ // The batch response, parsed against the numbers that were asked for (alias
765
+ // pN ↔ numbers[N]). Malformed input fails loud naming the query — a silently
766
+ // dropped PR's threads would read as "caught nothing", the plausible wrong
767
+ // answer. A null alias (PR invisible to this token) is an empty entry, not
768
+ // an error: that PR is simply not a candidate.
769
+ export function parseThreadBatch(
770
+ raw: string,
771
+ numbers: number[],
772
+ ): { entries: ThreadBatchEntry[]; nullAliases: number } {
773
+ let parsed: unknown;
774
+ try {
775
+ parsed = JSON.parse(raw);
776
+ } catch {
777
+ throw new CliUsageError(
778
+ "gh api graphql (reviewThreads batch) returned invalid JSON",
779
+ );
780
+ }
781
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
782
+ throw new CliUsageError(
783
+ "gh api graphql (reviewThreads batch) response is not an object",
784
+ );
785
+ }
786
+ const data = (parsed as Record<string, unknown>).data;
787
+ if (typeof data !== "object" || data === null || Array.isArray(data)) {
788
+ throw new CliUsageError(
789
+ "gh api graphql (reviewThreads batch) returned no data",
790
+ );
791
+ }
792
+ // The aliases live under data.repository — the same envelope the merged-PR
793
+ // walk reads — NOT directly under data. Verified against the live response:
794
+ // {"data":{"repository":{"p0":{…}}}}. Reading data.p0 found undefined and
795
+ // failed every batch with "alias p0 is not an object" on the first real run.
796
+ const repository = (data as Record<string, unknown>).repository;
797
+ if (
798
+ typeof repository !== "object" ||
799
+ repository === null ||
800
+ Array.isArray(repository)
801
+ ) {
802
+ throw new CliUsageError(
803
+ "gh api graphql (reviewThreads batch) returned no repository",
804
+ );
805
+ }
806
+ const out: ThreadBatchEntry[] = [];
807
+ let nullAliases = 0;
808
+ for (const [i, number] of numbers.entries()) {
809
+ const node = (repository as Record<string, unknown>)[`p${i}`];
810
+ if (node === null) {
811
+ // A null alias can mean a PR invisible to this token OR a partially
812
+ // executed batch under load; either way the PR contributes no threads
813
+ // here and the caller counts it so a systemic outbreak is visible.
814
+ nullAliases++;
815
+ out.push({ threads: [], truncated: false });
816
+ continue;
817
+ }
818
+ if (typeof node !== "object" || Array.isArray(node)) {
819
+ throw new CliUsageError(
820
+ `gh api graphql (reviewThreads batch) alias p${i} (PR #${number}) is not an object`,
821
+ );
822
+ }
823
+ const connection = (node as Record<string, unknown>).reviewThreads;
824
+ if (
825
+ typeof connection !== "object" ||
826
+ connection === null ||
827
+ !Array.isArray((connection as Record<string, unknown>).nodes)
828
+ ) {
829
+ throw new CliUsageError(
830
+ `gh api graphql (reviewThreads batch) returned no thread list for PR #${number}`,
831
+ );
832
+ }
833
+ const pageInfo = (connection as Record<string, unknown>).pageInfo;
834
+ const truncated =
835
+ typeof pageInfo === "object" &&
836
+ pageInfo !== null &&
837
+ (pageInfo as Record<string, unknown>).hasNextPage === true;
838
+ const threads: RawReviewThread[] = [];
839
+ for (const entry of (connection as Record<string, unknown>)
840
+ .nodes as unknown[]) {
841
+ if (typeof entry !== "object" || entry === null) continue;
842
+ const record = entry as Record<string, unknown>;
843
+ const comments = record.comments;
844
+ const first =
845
+ typeof comments === "object" && comments !== null
846
+ ? (
847
+ (comments as Record<string, unknown>).nodes as
848
+ | unknown[]
849
+ | undefined
850
+ )?.[0]
851
+ : undefined;
852
+ const comment =
853
+ typeof first === "object" && first !== null
854
+ ? (first as Record<string, unknown>)
855
+ : {};
856
+ const line = comment.line;
857
+ const originalLine = comment.originalLine;
858
+ const author =
859
+ typeof comment.author === "object" && comment.author !== null
860
+ ? (comment.author as Record<string, unknown>)
861
+ : {};
862
+ threads.push({
863
+ isResolved: record.isResolved === true,
864
+ path: typeof comment.path === "string" ? comment.path : null,
865
+ line:
866
+ typeof line === "number" && Number.isInteger(line)
867
+ ? line
868
+ : typeof originalLine === "number" && Number.isInteger(originalLine)
869
+ ? originalLine
870
+ : null,
871
+ firstCommentAt:
872
+ typeof comment.createdAt === "string" ? comment.createdAt : null,
873
+ excerpt:
874
+ typeof comment.body === "string"
875
+ ? excerptLine(comment.body, 200)
876
+ : null,
877
+ authorType:
878
+ typeof author.__typename === "string" ? author.__typename : null,
879
+ });
880
+ }
881
+ out.push({ threads, truncated });
882
+ }
883
+ return { entries: out, nullAliases };
884
+ }
885
+
886
+ // Survivors = PRs with ≥1 RESOLVED, PATH-CARRYING, HUMAN-authored thread.
887
+ // Unresolved threads are review in progress (or declined); a thread without a
888
+ // path is an overall-pr comment, which qualifies nothing; and a bot-authored
889
+ // thread is a machine catch, not the "real review findings" source #43 names
890
+ // — on musive that filter is the difference between 109 caught PRs and 13.
891
+ export function resolvedThreadsWithPath(
892
+ threads: RawReviewThread[],
893
+ ): RawReviewThread[] {
894
+ return threads.filter(
895
+ (thread) =>
896
+ thread.isResolved && thread.path !== null && thread.authorType !== "Bot",
897
+ );
898
+ }
899
+
900
+ export interface ThreadRecord {
901
+ path: string;
902
+ line: number | null;
903
+ firstCommentAt: string;
904
+ excerpt: string;
905
+ }
906
+
907
+ export interface QualifiedThread extends ThreadRecord {
908
+ // The commit that plausibly addressed the thread — see the approximation
909
+ // note in the artifact: GitHub's ReviewThread exposes no resolvedAt, so
910
+ // "resolved after a push" is approximated by "a commit landed after the
911
+ // thread's first comment and the thread's path is in the PR's diff; which
912
+ // push touched which line is not distinguishable from these endpoints".
913
+ pushSha: string;
914
+ }
915
+
916
+ // The join over already-fetched data (commits and files from the REST
917
+ // endpoints). A thread qualifies iff (a) SOME commit is strictly later than
918
+ // its first comment — pushSha records the LATEST such commit, ties broken by
919
+ // sha ascending for determinism — AND (b) the thread's path is among the
920
+ // PR's file paths, compared exactly (both sides come from GitHub, so the
921
+ // encodings already agree).
922
+ export function qualifyThreads(
923
+ threads: ThreadRecord[],
924
+ commits: PullCommitRef[],
925
+ filePaths: string[],
926
+ ): QualifiedThread[] {
927
+ const paths = new Set(filePaths);
928
+ const ordered = [...commits]
929
+ .filter(
930
+ (commit) =>
931
+ commit.committedAt !== null &&
932
+ !Number.isNaN(Date.parse(commit.committedAt)),
933
+ )
934
+ .sort((a, b) => {
935
+ const am = Date.parse(a.committedAt ?? "");
936
+ const bm = Date.parse(b.committedAt ?? "");
937
+ return bm === am ? a.sha.localeCompare(b.sha) : bm - am;
938
+ });
939
+ const out: QualifiedThread[] = [];
940
+ for (const thread of threads) {
941
+ const commentMs = Date.parse(thread.firstCommentAt);
942
+ if (Number.isNaN(commentMs)) continue;
943
+ const push = ordered.find(
944
+ (commit) => Date.parse(commit.committedAt ?? "") > commentMs,
945
+ );
946
+ if (push === undefined) continue;
947
+ if (!paths.has(thread.path)) continue;
948
+ out.push({ ...thread, pushSha: push.sha });
949
+ }
950
+ return out;
951
+ }
952
+
953
+ // ---------------------------------------------------------------------------
954
+ // gh/git payload readers for the walk and its satellites.
955
+
956
+ // `git rev-list --max-count=1 --format=%ct --before=<since> <ref>` → the
957
+ // concrete cutoff instant, as unix seconds. Empty output is NOT an error: it
958
+ // means the repo's whole history is inside the window (nothing is older than
959
+ // --since), so the walk has no cutoff and reads everything.
960
+ export function parseCutoffTimestamp(raw: string): number | null {
961
+ const trimmed = raw.trim();
962
+ if (trimmed.length === 0) return null;
963
+ for (const line of trimmed.split("\n")) {
964
+ const candidate = line.trim();
965
+ if (/^\d+$/.test(candidate)) {
966
+ const seconds = Number(candidate);
967
+ if (Number.isInteger(seconds) && seconds > 0) return seconds;
968
+ }
969
+ }
970
+ throw new CliUsageError(
971
+ "rev-list cutoff output has no committer timestamp line",
972
+ );
973
+ }
974
+
975
+ export interface MergedPrNode {
976
+ number: number;
977
+ title: string;
978
+ body: string | null;
979
+ mergedAt: string | null;
980
+ // The walk's SORT KEY. GitHub's pullRequests connection cannot order by
981
+ // mergedAt (IssueOrderField has no MERGED_AT — verified live, the walk
982
+ // failed closed on the first real run), so the walk orders by updatedAt and
983
+ // this field carries that order.
984
+ updatedAt: string | null;
985
+ mergeCommitSha: string | null;
986
+ baseRefName: string;
987
+ }
988
+
989
+ export interface MergedPrPage {
990
+ endCursor: string | null;
991
+ hasNextPage: boolean;
992
+ nodes: MergedPrNode[];
993
+ }
994
+
995
+ // One page of the merged-PR walk. Fails loud naming the query (the parseReviewThreads
996
+ // discipline): a half-parsed page would silently shorten the scan and report
997
+ // "no candidates" with a completely plausible face.
998
+ export function parseMergedPrPage(raw: string): MergedPrPage {
999
+ let parsed: unknown;
1000
+ try {
1001
+ parsed = JSON.parse(raw);
1002
+ } catch {
1003
+ throw new CliUsageError(
1004
+ "gh api graphql (merged PR walk) returned invalid JSON",
1005
+ );
1006
+ }
1007
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1008
+ throw new CliUsageError(
1009
+ "gh api graphql (merged PR walk) response is not an object",
1010
+ );
1011
+ }
1012
+ const repository = (parsed as Record<string, unknown>).data;
1013
+ const connection =
1014
+ typeof repository === "object" && repository !== null
1015
+ ? ((repository as Record<string, unknown>).repository as unknown)
1016
+ : undefined;
1017
+ const pullRequests =
1018
+ typeof connection === "object" && connection !== null
1019
+ ? ((connection as Record<string, unknown>).pullRequests as unknown)
1020
+ : undefined;
1021
+ if (
1022
+ typeof pullRequests !== "object" ||
1023
+ pullRequests === null ||
1024
+ !Array.isArray((pullRequests as Record<string, unknown>).nodes)
1025
+ ) {
1026
+ throw new CliUsageError(
1027
+ "gh api graphql (merged PR walk) returned no pullRequests connection",
1028
+ );
1029
+ }
1030
+ const pageInfo = (pullRequests as Record<string, unknown>).pageInfo;
1031
+ // `typeof null === "object"`, so a null pageInfo used to pass the object
1032
+ // check and then throw a raw TypeError on `.endCursor` — the shell only
1033
+ // remaps CliUsageError, so that reached the operator mid-walk with no
1034
+ // page named. Same shape as parseThreadBatch's pageInfo guard.
1035
+ if (typeof pageInfo !== "object" || pageInfo === null) {
1036
+ throw new CliUsageError(
1037
+ "gh api graphql (merged PR walk) returned no pullRequests connection",
1038
+ );
1039
+ }
1040
+ const record = pullRequests as {
1041
+ nodes: unknown[];
1042
+ pageInfo: Record<string, unknown>;
1043
+ };
1044
+ const hasNextPage = record.pageInfo.hasNextPage === true;
1045
+ const endCursor =
1046
+ typeof record.pageInfo.endCursor === "string"
1047
+ ? record.pageInfo.endCursor
1048
+ : null;
1049
+ // A continuing page without a cursor would loop forever on the same
1050
+ // request. Fail loud rather than hang.
1051
+ if (hasNextPage && endCursor === null) {
1052
+ throw new CliUsageError(
1053
+ "gh api graphql (merged PR walk) hasNextPage is true but endCursor is missing",
1054
+ );
1055
+ }
1056
+ const nodes: MergedPrNode[] = [];
1057
+ for (const [i, entry] of record.nodes.entries()) {
1058
+ if (typeof entry !== "object" || entry === null) {
1059
+ throw new CliUsageError(
1060
+ `gh api graphql (merged PR walk) node ${i} is not an object`,
1061
+ );
1062
+ }
1063
+ const node = entry as Record<string, unknown>;
1064
+ const number = node.number;
1065
+ if (typeof number !== "number" || !Number.isInteger(number) || number < 1) {
1066
+ throw new CliUsageError(
1067
+ `gh api graphql (merged PR walk) node ${i} has no number`,
1068
+ );
1069
+ }
1070
+ if (typeof node.title !== "string") {
1071
+ throw new CliUsageError(
1072
+ `gh api graphql (merged PR walk) PR #${number} has no title`,
1073
+ );
1074
+ }
1075
+ if (typeof node.baseRefName !== "string") {
1076
+ throw new CliUsageError(
1077
+ `gh api graphql (merged PR walk) PR #${number} has no baseRefName`,
1078
+ );
1079
+ }
1080
+ const mergeCommit = node.mergeCommit;
1081
+ const oid =
1082
+ typeof mergeCommit === "object" && mergeCommit !== null
1083
+ ? (mergeCommit as Record<string, unknown>).oid
1084
+ : undefined;
1085
+ nodes.push({
1086
+ number,
1087
+ title: node.title,
1088
+ body: typeof node.body === "string" ? node.body : null,
1089
+ mergedAt: typeof node.mergedAt === "string" ? node.mergedAt : null,
1090
+ updatedAt: typeof node.updatedAt === "string" ? node.updatedAt : null,
1091
+ mergeCommitSha: typeof oid === "string" ? oid : null,
1092
+ baseRefName: node.baseRefName,
1093
+ });
1094
+ }
1095
+ return {
1096
+ endCursor,
1097
+ hasNextPage,
1098
+ nodes,
1099
+ };
1100
+ }
1101
+
1102
+ // The per-page keep filter plus the STOP rule. Kept = merged at/after the
1103
+ // cutoff AND based on the default branch. The stop signal keys on the walk's
1104
+ // ORDER (updatedAt, falling back to mergedAt when the API omitted it): a page
1105
+ // with nothing at/after the cutoff on that order guarantees every later page
1106
+ // is older still. WHY ordering by updatedAt loses nothing: GitHub sets
1107
+ // updatedAt >= mergedAt on every PR, so any PR merged at/after the cutoff
1108
+ // also sorts at/after it and cannot hide below the stop point. The cost is
1109
+ // pages of old-but-recently-commented merged PRs, which the mergedAt filter
1110
+ // discards. Base-branch filtering must NOT trigger the stop — a quiet week on
1111
+ // the default branch is not the end of history, it is just a page of
1112
+ // feature-branch PRs.
1113
+ export function walkPageKept(input: {
1114
+ nodes: MergedPrNode[];
1115
+ cutoffMs: number | null;
1116
+ defaultBranch: string;
1117
+ }): { kept: MergedPrNode[]; olderExhausted: boolean } {
1118
+ const keptByDate: MergedPrNode[] = [];
1119
+ let inDateOnOrder = false;
1120
+ for (const node of input.nodes) {
1121
+ if (node.mergedAt === null) continue; // MERGED without a date: not datable
1122
+ const ms = Date.parse(node.mergedAt);
1123
+ if (Number.isNaN(ms)) continue;
1124
+ if (input.cutoffMs !== null && ms < input.cutoffMs) continue;
1125
+ keptByDate.push(node);
1126
+ }
1127
+ for (const node of input.nodes) {
1128
+ const orderStamp = node.updatedAt ?? node.mergedAt;
1129
+ if (orderStamp === null) continue;
1130
+ const ms = Date.parse(orderStamp);
1131
+ if (Number.isNaN(ms)) continue;
1132
+ if (input.cutoffMs === null || ms >= input.cutoffMs) {
1133
+ inDateOnOrder = true;
1134
+ break;
1135
+ }
1136
+ }
1137
+ return {
1138
+ kept: keptByDate.filter((node) => node.baseRefName === input.defaultBranch),
1139
+ olderExhausted: input.cutoffMs !== null && !inDateOnOrder,
1140
+ };
1141
+ }
1142
+
1143
+ // `git log -m --first-parent --format=%H\x1f%ct --no-renames --numstat` → the
1144
+ // commit/file index the proximity join runs over. Format records carry the
1145
+ // \x1f and are followed by a blank line before the numstat block; numstat
1146
+ // lines are `<added>\t<deleted>\t<path>` where a binary file's counters are
1147
+ // `-` but the PATH still counts (a binary change is still a change to that
1148
+ // file). A merge commit's first-parent numstat is the ONLY numstat the join
1149
+ // can use: it resolves commits to PRs through `mergeCommitSha`, so the
1150
+ // commits a merge absorbed are never in that map and their files would never
1151
+ // arrive. A record with no numstat lines at all is still legal (an empty
1152
+ // commit, or a merge whose first-parent diff is empty) and carries no files.
1153
+ export function parseCommitIndex(raw: string): CommitIndexEntry[] {
1154
+ const out: CommitIndexEntry[] = [];
1155
+ let current: CommitIndexEntry | null = null;
1156
+ for (const line of raw.split("\n")) {
1157
+ if (line.includes(GIT_LOG_FIELD_SEP)) {
1158
+ const fields = line.split(GIT_LOG_FIELD_SEP);
1159
+ if (fields.length < 2) {
1160
+ throw new CliUsageError(
1161
+ `commit index record has ${fields.length} field(s), expected 2 (sha, date)`,
1162
+ );
1163
+ }
1164
+ const sha = (fields[0] ?? "").trim();
1165
+ if (!/^[0-9a-f]{40}$/.test(sha)) {
1166
+ throw new CliUsageError(
1167
+ `commit index record has no full sha, got: ${sha}`,
1168
+ );
1169
+ }
1170
+ const committedAtSec = Number((fields[1] ?? "").trim());
1171
+ if (!Number.isInteger(committedAtSec)) {
1172
+ throw new CliUsageError(
1173
+ `commit index record ${sha} has a non-integer date: ${fields[1]}`,
1174
+ );
1175
+ }
1176
+ current = { sha, committedAtSec, files: [] };
1177
+ out.push(current);
1178
+ continue;
1179
+ }
1180
+ if (current === null) continue;
1181
+ const fields = line.split("\t");
1182
+ if (fields.length < 3) continue;
1183
+ // Tabs inside a path only appear in git's quoted form, which escapes
1184
+ // them; rejoining keeps such a path whole instead of truncating it.
1185
+ current.files.push(unquotePath(fields.slice(2).join("\t")));
1186
+ }
1187
+ return out;
1188
+ }
1189
+
1190
+ export interface IssueLabels {
1191
+ names: string[];
1192
+ // GitHub's issues API returns PRs too; recorded so the caller can tell a
1193
+ // referenced PR from an actual issue.
1194
+ isPull: boolean;
1195
+ }
1196
+
1197
+ // `gh api repos/<slug>/issues/<n>` → the labels + is-it-a-PR. Labels come
1198
+ // back verbatim: matching against the bug-labels set happens case-sensitively
1199
+ // at the caller, because GitHub labels are case-sensitive.
1200
+ export function parseIssueLabels(raw: string): IssueLabels {
1201
+ let parsed: unknown;
1202
+ try {
1203
+ parsed = JSON.parse(raw);
1204
+ } catch {
1205
+ throw new CliUsageError("issue response is not JSON");
1206
+ }
1207
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1208
+ throw new CliUsageError("issue response is not an object");
1209
+ }
1210
+ const record = parsed as Record<string, unknown>;
1211
+ const labels = record.labels;
1212
+ if (labels !== undefined && !Array.isArray(labels)) {
1213
+ throw new CliUsageError("issue response labels is not an array");
1214
+ }
1215
+ const names: string[] = [];
1216
+ for (const entry of (labels ?? []) as unknown[]) {
1217
+ if (typeof entry !== "object" || entry === null) continue;
1218
+ const name = (entry as Record<string, unknown>).name;
1219
+ if (typeof name === "string" && name.length > 0) names.push(name);
1220
+ }
1221
+ return {
1222
+ names,
1223
+ isPull:
1224
+ typeof record.pull_request === "object" && record.pull_request !== null,
1225
+ };
1226
+ }
1227
+
1228
+ export interface BugLabelMatch {
1229
+ // Per referenced number, the bug labels it carries. EVERY ref gets an
1230
+ // entry — a ref that confers nothing is still rendered as evidence the
1231
+ // scan looked at, so it must survive with an empty list, never be dropped.
1232
+ byRef: Map<number, string[]>;
1233
+ anyMatch: boolean;
1234
+ }
1235
+
1236
+ // Which `fixes #N` refs actually confer the `bug-issue` source.
1237
+ //
1238
+ // The `isPull` skip is the whole point. GitHub's issues API answers for pull
1239
+ // requests too, so `fixes #1234` pointing at a PR resolves happily and its
1240
+ // labels look exactly like an issue's. Counting them promoted such a
1241
+ // candidate to `issue-linked`, this artifact's HIGHEST tier, on the strength
1242
+ // of a label somebody put on a pull request — the confusion `parseIssueLabels`
1243
+ // records `isPull` to prevent, which no caller was reading.
1244
+ //
1245
+ // Labels match case-sensitively (`bug` is not `Bug`): GitHub label names are
1246
+ // case-sensitive, so lowercasing would silently widen a set the user spelled
1247
+ // out. Unresolved (404 → null) and never-fetched (undefined) refs both
1248
+ // degrade to no labels rather than throwing; a fact missing about one issue
1249
+ // is not a broken scan.
1250
+ export function matchBugLabels(
1251
+ refs: number[],
1252
+ labelsByRef: Map<number, IssueLabels | null>,
1253
+ bugLabels: Set<string>,
1254
+ ): BugLabelMatch {
1255
+ const byRef = new Map<number, string[]>();
1256
+ let anyMatch = false;
1257
+ for (const number of refs) {
1258
+ const labels = labelsByRef.get(number);
1259
+ const matched =
1260
+ labels === null || labels === undefined || labels.isPull
1261
+ ? []
1262
+ : labels.names.filter((label) => bugLabels.has(label));
1263
+ byRef.set(number, matched);
1264
+ if (matched.length > 0) anyMatch = true;
1265
+ }
1266
+ return { byRef, anyMatch };
1267
+ }
1268
+
1269
+ export interface PullCommitRef {
1270
+ sha: string;
1271
+ committedAt: string | null;
1272
+ }
1273
+
1274
+ // `gh api repos/<slug>/pulls/<n>/commits`. The committer date (not author
1275
+ // date) is taken: it is the instant the commit landed in the PR's history,
1276
+ // which is what "a commit arrived after the comment" is about — an author
1277
+ // date can predate the PR by years.
1278
+ export function parsePullCommits(raw: string): PullCommitRef[] {
1279
+ let parsed: unknown;
1280
+ try {
1281
+ parsed = JSON.parse(raw);
1282
+ } catch {
1283
+ throw new CliUsageError("pull commits response is not JSON");
1284
+ }
1285
+ if (!Array.isArray(parsed)) {
1286
+ throw new CliUsageError("pull commits response is not an array");
1287
+ }
1288
+ const out: PullCommitRef[] = [];
1289
+ for (const entry of parsed) {
1290
+ if (typeof entry !== "object" || entry === null) continue;
1291
+ const record = entry as Record<string, unknown>;
1292
+ if (typeof record.sha !== "string" || record.sha.length === 0) continue;
1293
+ const commit = record.commit;
1294
+ const committer =
1295
+ typeof commit === "object" && commit !== null
1296
+ ? (commit as Record<string, unknown>).committer
1297
+ : undefined;
1298
+ const date =
1299
+ typeof committer === "object" && committer !== null
1300
+ ? (committer as Record<string, unknown>).date
1301
+ : undefined;
1302
+ out.push({
1303
+ sha: record.sha,
1304
+ committedAt: typeof date === "string" ? date : null,
1305
+ });
1306
+ }
1307
+ return out;
1308
+ }
1309
+
1310
+ // `gh api repos/<slug>/pulls/<n>/files` → the paths, for the thread
1311
+ // qualification's path-membership half.
1312
+ export function parsePullFiles(raw: string): string[] {
1313
+ let parsed: unknown;
1314
+ try {
1315
+ parsed = JSON.parse(raw);
1316
+ } catch {
1317
+ throw new CliUsageError("pull files response is not JSON");
1318
+ }
1319
+ if (!Array.isArray(parsed)) {
1320
+ throw new CliUsageError("pull files response is not an array");
1321
+ }
1322
+ const out: string[] = [];
1323
+ for (const entry of parsed) {
1324
+ if (typeof entry !== "object" || entry === null) continue;
1325
+ const filename = (entry as Record<string, unknown>).filename;
1326
+ if (typeof filename === "string" && filename.length > 0) out.push(filename);
1327
+ }
1328
+ return out;
1329
+ }
1330
+
1331
+ // ---------------------------------------------------------------------------
1332
+ // Selection.
1333
+
1334
+ // What the shell knows about one classified PR before tier resolution.
1335
+ // `matchedSources` carries only the DETECTOR matches (fix-subject,
1336
+ // incident-keyword, bug-issue); the proximity source and the confidence tier
1337
+ // are resolved here, once, over the whole set.
1338
+ export interface CorpusWorking {
1339
+ fixPr: number;
1340
+ fixTitle: string;
1341
+ fixMergedAt: string | null;
1342
+ matchedSources: CorpusSource[];
1343
+ matchedText: string;
1344
+ issueRefs: { number: number; matchedLabels: string[] }[];
1345
+ fixBaseSha: string | null;
1346
+ fixHeadSha: string | null;
1347
+ additions: number | null;
1348
+ deletions: number | null;
1349
+ changedFiles: number | null;
1350
+ introducer: IntroducerInfo | null;
1351
+ alsoBlamedCount: number;
1352
+ blameSkippedRenames: number;
1353
+ proximitySuspects: ProximitySuspect[];
1354
+ }
1355
+
1356
+ // Canonical source order for `sources` lines — stable regardless of the
1357
+ // order detectors happened to fire in.
1358
+ const SOURCE_ORDER: CorpusSource[] = [
1359
+ "fix-subject",
1360
+ "incident-keyword",
1361
+ "bug-issue",
1362
+ "proximity",
1363
+ ];
1364
+
1365
+ function stampMs(stamp: string | null): number {
1366
+ if (stamp === null) return Number.NaN;
1367
+ return Date.parse(stamp);
1368
+ }
1369
+
1370
+ // A PR cannot introduce what it itself fixed — circular blame evidence.
1371
+ // Shared by the shell (drop before proximity runs) and selectCorpus
1372
+ // (defense in depth). Direct pushes (`null`) are not self.
1373
+ export function isSelfIntroducer(
1374
+ fixPr: number,
1375
+ introducerPr: number | null,
1376
+ ): boolean {
1377
+ return introducerPr === fixPr;
1378
+ }
1379
+
1380
+ // Rebase-and-merge detection: merge_commit_sha is the last rebased commit,
1381
+ // so its sole parent still belongs to THIS PR. Squash's parent is the
1382
+ // previous default-branch tip (another PR, or none). pickCommitPull is
1383
+ // GitHub's primary association — the same rule blameResolve uses for the
1384
+ // introducer itself.
1385
+ export function parentBelongsToFix(
1386
+ fixPr: number,
1387
+ pulls: CommitPullRef[],
1388
+ ): boolean {
1389
+ const primary = pickCommitPull(pulls);
1390
+ return primary !== null && primary.number === fixPr;
1391
+ }
1392
+
1393
+ // Tier resolution + dedupe + the artifact's deterministic order.
1394
+ export function selectCorpus(entries: CorpusWorking[]): CorpusCandidate[] {
1395
+ // One entry per fix PR, sources merged: the shell keys its map by PR, but
1396
+ // the merge rule lives HERE so a duplicate can never survive to the
1397
+ // artifact even if a future caller builds the list differently.
1398
+ const byPr = new Map<number, CorpusWorking>();
1399
+ for (const entry of entries) {
1400
+ const existing = byPr.get(entry.fixPr);
1401
+ if (existing === undefined) {
1402
+ byPr.set(entry.fixPr, { ...entry });
1403
+ continue;
1404
+ }
1405
+ const sources = new Set([
1406
+ ...existing.matchedSources,
1407
+ ...entry.matchedSources,
1408
+ ]);
1409
+ existing.matchedSources = SOURCE_ORDER.filter((source) =>
1410
+ sources.has(source),
1411
+ );
1412
+ const refs = new Map(existing.issueRefs.map((ref) => [ref.number, ref]));
1413
+ for (const ref of entry.issueRefs) {
1414
+ const seen = refs.get(ref.number);
1415
+ if (seen === undefined) {
1416
+ refs.set(ref.number, ref);
1417
+ continue;
1418
+ }
1419
+ seen.matchedLabels = [
1420
+ ...new Set([...seen.matchedLabels, ...ref.matchedLabels]),
1421
+ ];
1422
+ }
1423
+ existing.issueRefs = [...refs.values()];
1424
+ if (existing.matchedText.length === 0) {
1425
+ existing.matchedText = entry.matchedText;
1426
+ }
1427
+ }
1428
+
1429
+ const candidates: CorpusCandidate[] = [];
1430
+ for (const entry of byPr.values()) {
1431
+ // Defensive filter (dropSamePrReverts' lesson): a PR cannot introduce
1432
+ // what it itself fixed — when blame resolves the introducer to the fix
1433
+ // PR itself, the evidence is circular and the introducer is nulled.
1434
+ const introducer =
1435
+ entry.introducer !== null &&
1436
+ isSelfIntroducer(entry.fixPr, entry.introducer.pr)
1437
+ ? null
1438
+ : entry.introducer;
1439
+ const sources = SOURCE_ORDER.filter((source) =>
1440
+ entry.matchedSources.includes(source),
1441
+ );
1442
+ let confidence: CorpusConfidence;
1443
+ if (sources.includes("bug-issue")) {
1444
+ confidence = "issue-linked";
1445
+ } else if (introducer !== null && introducer.pr !== null) {
1446
+ confidence = "blame-linked";
1447
+ } else if (entry.proximitySuspects.length > 0) {
1448
+ confidence = "proximity";
1449
+ if (!sources.includes("proximity")) sources.push("proximity");
1450
+ } else {
1451
+ confidence = "keyword-only";
1452
+ }
1453
+ candidates.push({
1454
+ fixPr: entry.fixPr,
1455
+ fixTitle: entry.fixTitle,
1456
+ fixMergedAt: entry.fixMergedAt,
1457
+ sources,
1458
+ confidence,
1459
+ matchedText: entry.matchedText,
1460
+ issueRefs: entry.issueRefs,
1461
+ fixBaseSha: entry.fixBaseSha,
1462
+ fixHeadSha: entry.fixHeadSha,
1463
+ additions: entry.additions,
1464
+ deletions: entry.deletions,
1465
+ changedFiles: entry.changedFiles,
1466
+ introducer,
1467
+ alsoBlamedCount: entry.alsoBlamedCount,
1468
+ blameSkippedRenames: entry.blameSkippedRenames,
1469
+ proximitySuspects: entry.proximitySuspects,
1470
+ });
1471
+ }
1472
+
1473
+ // Deterministic order: newest fix first; ties by PR ascending; undatable
1474
+ // entries last rather than interleaved by sort accident.
1475
+ return candidates.sort((a, b) => {
1476
+ const am = stampMs(a.fixMergedAt);
1477
+ const bm = stampMs(b.fixMergedAt);
1478
+ if (!Number.isNaN(am) && !Number.isNaN(bm) && am !== bm) return bm - am;
1479
+ if (Number.isNaN(am) !== Number.isNaN(bm)) {
1480
+ return Number.isNaN(am) ? 1 : -1;
1481
+ }
1482
+ return a.fixPr - b.fixPr;
1483
+ });
1484
+ }
1485
+
1486
+ // ---------------------------------------------------------------------------
1487
+ // The artifact.
1488
+
1489
+ // The lookups that did not answer during the scan, separated by CAUSE because
1490
+ // they mean different things: "GitHub said no" is not "this clone is stale" is
1491
+ // not "git could not blame that range". Each one silently costs a candidate its
1492
+ // evidence — a commit→PR lookup that 404s leaves `introducer.pr = null`, which
1493
+ // the tier ladder reads as a direct push and demotes accordingly. Measured
1494
+ // 2026-08-17: a degraded run reported 12 blame-linked where a clean re-run
1495
+ // reported 428, and the two artifacts were byte-indistinguishable.
1496
+ export interface CorpusLookupFailures {
1497
+ // `repos/<slug>/commits/<sha>/pulls` answered 404. Distinct from the same
1498
+ // call answering 200 with an empty list, which really does mean direct push.
1499
+ commitPrLookup404: number;
1500
+ // The merge commit GitHub named is not in this clone (stale clone or
1501
+ // rewritten history) — the whole PR gets no blame evidence.
1502
+ mergeCommitAbsent: number;
1503
+ // `git blame` failed on one range; that range contributes nothing.
1504
+ blameRangeSkipped: number;
1505
+ }
1506
+
1507
+ export interface CorpusArtifact {
1508
+ repoSlug: string;
1509
+ ref: string;
1510
+ since: string;
1511
+ scannedPrs: number;
1512
+ // Which source flags the run actually had. A count of 0 for a source that
1513
+ // never ran reads exactly like "ran and found nothing", and that ambiguity
1514
+ // is a lie of omission the artifact must not carry.
1515
+ sourcesRun: string[];
1516
+ // Rendered ALWAYS, zeros included, for the reason written on sourcesRun just
1517
+ // above: an omitted count and a count of zero are the same bytes to a reader,
1518
+ // and here that ambiguity is precisely the defect being fixed.
1519
+ lookupFailures: CorpusLookupFailures;
1520
+ candidates: CorpusCandidate[];
1521
+ threadCandidates: ThreadCandidate[];
1522
+ }
1523
+
1524
+ const DEGRADED_WARNING = [
1525
+ "> **This run was DEGRADED — the counts above are not the counts a clean",
1526
+ "> run would produce.** Some lookups never answered, so evidence this scan",
1527
+ "> should have had is simply missing, and candidates may sit in a WEAKER",
1528
+ "> tier than they deserve: an introducer that failed to resolve is recorded",
1529
+ "> exactly like one that resolved to a direct push. Re-run before reading",
1530
+ "> the tier counts, or any absent introducer, as a fact about the code.",
1531
+ ];
1532
+
1533
+ const CANDIDATE_WARNING = [
1534
+ "> **These are CANDIDATES REQUIRING HUMAN CONFIRMATION, not confirmed",
1535
+ "> defects.** A bug-fix PR proves something was wrong, not that a review",
1536
+ "> should have caught it; blame names the LAST toucher of the fixed lines,",
1537
+ "> not necessarily the introducer; proximity is not causation; and the",
1538
+ "> review-caught entries are the OTHER side of the corpus — defects review",
1539
+ "> DID catch. Every entry below needs a human glance before it is treated",
1540
+ "> as a known-bad case.",
1541
+ ];
1542
+
1543
+ // Descending confidence, and it MUST equal the order `selectCorpus`'s ladder
1544
+ // resolves in — the two disagreed: the ladder tries proximity before falling
1545
+ // through to keyword-only (a candidate with suspects has strictly more
1546
+ // evidence than one where nothing resolved), while this list rendered
1547
+ // keyword-only above proximity under a header promising descending
1548
+ // confidence. The renderer was the one lying. Exported so a test can pin the
1549
+ // two together instead of trusting them to drift in step.
1550
+ export const TIER_ORDER: CorpusConfidence[] = [
1551
+ "issue-linked",
1552
+ "blame-linked",
1553
+ "proximity",
1554
+ "keyword-only",
1555
+ "review-caught",
1556
+ ];
1557
+
1558
+ const TIER_NOTE: Record<CorpusConfidence, string> = {
1559
+ "issue-linked":
1560
+ "The fix PR references an issue carrying one of the bug labels — the " +
1561
+ "strongest signal this artifact has.",
1562
+ "blame-linked":
1563
+ "git blame on the fixed lines resolved to a PR. Blame names the LAST " +
1564
+ "toucher, which is not always the introducer — check the blamed range.",
1565
+ "keyword-only":
1566
+ "Matched by an anchored fix subject or an incident keyword alone; " +
1567
+ "nothing else resolved. Lowest confidence: verify before replaying.",
1568
+ proximity:
1569
+ "No introducer resolved; prior PRs touched the same files inside the " +
1570
+ "window. Correlation, not causation — the shared files are the only " +
1571
+ "evidence.",
1572
+ "review-caught":
1573
+ "A resolved review thread that a later push plausibly addressed — the " +
1574
+ "OTHER side of the corpus: defects review DID catch. GitHub exposes no " +
1575
+ "resolvedAt, so 'a commit landed after the first comment and the " +
1576
+ "thread's path is in the diff' is the approximation; which push touched " +
1577
+ "which line is not distinguishable from these endpoints.",
1578
+ };
1579
+
1580
+ export function renderCorpusArtifact(artifact: CorpusArtifact): string {
1581
+ const out: string[] = [];
1582
+ out.push("# crysk — known-bad corpus candidates (beyond reverts)");
1583
+ out.push("");
1584
+ out.push(`- repository: \`${artifact.repoSlug}\``);
1585
+ out.push(`- ref: \`${artifact.ref}\``);
1586
+ out.push(`- window: \`--since ${artifact.since}\``);
1587
+ out.push(`- scanned: ${artifact.scannedPrs} merged PR(s)`);
1588
+ out.push(`- sources run: ${artifact.sourcesRun.join(", ") || "(none)"}`);
1589
+ const failures = artifact.lookupFailures;
1590
+ out.push(`- failed lookups — commit→PR (404): ${failures.commitPrLookup404}`);
1591
+ out.push(
1592
+ "- failed lookups — merge commit absent from this clone (stale clone " +
1593
+ `or rewritten history): ${failures.mergeCommitAbsent}`,
1594
+ );
1595
+ out.push(
1596
+ `- failed lookups — blame range skipped: ${failures.blameRangeSkipped}`,
1597
+ );
1598
+ for (const source of SOURCE_ORDER) {
1599
+ const count = artifact.candidates.filter((candidate) =>
1600
+ candidate.sources.includes(source),
1601
+ ).length;
1602
+ out.push(`- source ${source}: ${count} candidate(s)`);
1603
+ }
1604
+ out.push(
1605
+ `- source review-thread: ${artifact.threadCandidates.length} caught PR(s)`,
1606
+ );
1607
+ for (const tier of TIER_ORDER) {
1608
+ const count =
1609
+ tier === "review-caught"
1610
+ ? artifact.threadCandidates.length
1611
+ : artifact.candidates.filter(
1612
+ (candidate) => candidate.confidence === tier,
1613
+ ).length;
1614
+ out.push(`- tier ${tier}: ${count}`);
1615
+ }
1616
+ out.push("");
1617
+ out.push(
1618
+ "> Tier order below is descending confidence and sits BELOW the revert " +
1619
+ "tiers of `crysk reverts` — git's machine-written body linkage " +
1620
+ "outranks everything inferred here. The revert candidates themselves " +
1621
+ "live in that command's artifact; this one widens the corpus beyond " +
1622
+ "reverts.",
1623
+ );
1624
+ out.push("");
1625
+ if (
1626
+ failures.commitPrLookup404 > 0 ||
1627
+ failures.mergeCommitAbsent > 0 ||
1628
+ failures.blameRangeSkipped > 0
1629
+ ) {
1630
+ out.push(...DEGRADED_WARNING);
1631
+ out.push("");
1632
+ }
1633
+ out.push(...CANDIDATE_WARNING);
1634
+ out.push("");
1635
+ for (const tier of TIER_ORDER) {
1636
+ if (tier === "review-caught") {
1637
+ renderThreadSection(out, artifact.threadCandidates);
1638
+ continue;
1639
+ }
1640
+ const group = artifact.candidates.filter(
1641
+ (candidate) => candidate.confidence === tier,
1642
+ );
1643
+ out.push(`## ${tier} (${group.length})`);
1644
+ out.push("");
1645
+ out.push(TIER_NOTE[tier]);
1646
+ out.push("");
1647
+ if (group.length === 0) {
1648
+ out.push("_None in this window._");
1649
+ out.push("");
1650
+ continue;
1651
+ }
1652
+ for (const candidate of group) {
1653
+ out.push(...renderFixCandidate(candidate));
1654
+ }
1655
+ }
1656
+ return `${out.join("\n").replace(/\n+$/, "")}\n`;
1657
+ }
1658
+
1659
+ function renderFixCandidate(candidate: CorpusCandidate): string[] {
1660
+ const out: string[] = [];
1661
+ out.push(`### fix PR #${candidate.fixPr} — ${candidate.fixTitle}`);
1662
+ out.push("");
1663
+ out.push(`- merged at: ${candidate.fixMergedAt ?? "unknown"}`);
1664
+ out.push(
1665
+ `- replay range (defect site): ${replayRange(candidate.fixBaseSha, candidate.fixHeadSha)}`,
1666
+ );
1667
+ out.push(`- diff size: ${diffSize(candidate)}`);
1668
+ out.push(`- sources: ${candidate.sources.join(", ")}`);
1669
+ out.push(`- evidence: ${candidate.matchedText}`);
1670
+ if (candidate.issueRefs.length > 0) {
1671
+ const refs = candidate.issueRefs
1672
+ .map((ref) =>
1673
+ ref.matchedLabels.length > 0
1674
+ ? `#${ref.number} (${ref.matchedLabels.join(", ")})`
1675
+ : `#${ref.number}`,
1676
+ )
1677
+ .join(", ");
1678
+ out.push(`- issue refs: ${refs}`);
1679
+ }
1680
+ out.push(`- introducer: ${introducerLine(candidate.introducer)}`);
1681
+ if (candidate.alsoBlamedCount > 0) {
1682
+ out.push(`- also blamed: ${candidate.alsoBlamedCount} other commit(s)`);
1683
+ }
1684
+ if (candidate.blameSkippedRenames > 0) {
1685
+ out.push(
1686
+ `- renamed file(s) skipped by blame: ${candidate.blameSkippedRenames}`,
1687
+ );
1688
+ }
1689
+ if (candidate.proximitySuspects.length > 0) {
1690
+ const suspects = candidate.proximitySuspects
1691
+ .map((suspect) => {
1692
+ const title = suspect.title === null ? "" : ` "${suspect.title}"`;
1693
+ return `#${suspect.pr}${title} (${suspect.sharedFiles} shared file(s), ${suspect.gapDays}d before the fix)`;
1694
+ })
1695
+ .join(", ");
1696
+ out.push(`- proximity suspects: ${suspects}`);
1697
+ }
1698
+ out.push("");
1699
+ return out;
1700
+ }
1701
+
1702
+ function renderThreadSection(
1703
+ out: string[],
1704
+ threadCandidates: ThreadCandidate[],
1705
+ ): void {
1706
+ const ordered = [...threadCandidates].sort((a, b) => {
1707
+ const am = stampMs(a.mergedAt);
1708
+ const bm = stampMs(b.mergedAt);
1709
+ if (!Number.isNaN(am) && !Number.isNaN(bm) && am !== bm) return bm - am;
1710
+ if (Number.isNaN(am) !== Number.isNaN(bm)) {
1711
+ return Number.isNaN(am) ? 1 : -1;
1712
+ }
1713
+ return a.pr - b.pr;
1714
+ });
1715
+ out.push(`## review-caught (${ordered.length})`);
1716
+ out.push("");
1717
+ out.push(TIER_NOTE["review-caught"]);
1718
+ out.push("");
1719
+ if (ordered.length === 0) {
1720
+ out.push("_None in this window._");
1721
+ out.push("");
1722
+ return;
1723
+ }
1724
+ for (const candidate of ordered) {
1725
+ out.push(`### PR #${candidate.pr} — ${candidate.title} (caught in review)`);
1726
+ out.push("");
1727
+ out.push(`- merged at: ${candidate.mergedAt ?? "unknown"}`);
1728
+ out.push(
1729
+ `- replay range (defect site): ${replayRange(candidate.baseSha, candidate.headSha)}`,
1730
+ );
1731
+ out.push(
1732
+ `- diff size: ${diffSize({
1733
+ additions: candidate.additions,
1734
+ deletions: candidate.deletions,
1735
+ changedFiles: candidate.changedFiles,
1736
+ })}`,
1737
+ );
1738
+ for (const thread of candidate.threads) {
1739
+ const at =
1740
+ thread.line === null ? thread.path : `${thread.path}:${thread.line}`;
1741
+ out.push(
1742
+ `- thread: \`${at}\` · first comment ${thread.firstCommentAt} · ` +
1743
+ `a commit landed after it: \`${thread.pushSha}\``,
1744
+ );
1745
+ if (thread.excerpt.length > 0) {
1746
+ out.push(` excerpt: ${thread.excerpt}`);
1747
+ }
1748
+ }
1749
+ if (candidate.threadsTruncated) {
1750
+ out.push(
1751
+ `- note: resolved threads truncated at ${THREAD_PAGE_SIZE} — more ` +
1752
+ "exist than are shown",
1753
+ );
1754
+ }
1755
+ out.push("");
1756
+ }
1757
+ }
1758
+
1759
+ function introducerLine(introducer: IntroducerInfo | null): string {
1760
+ if (introducer === null) return "unresolved";
1761
+ const where = `\`${introducer.blamedSha}\` at \`${introducer.blamedFile}:${introducer.blamedRange}\``;
1762
+ if (introducer.pr === null) {
1763
+ return `direct push — blame ${where}`;
1764
+ }
1765
+ const title =
1766
+ introducer.title === null ? "(title unresolved)" : `"${introducer.title}"`;
1767
+ return (
1768
+ `PR #${introducer.pr} ${title}, merged ` +
1769
+ `${introducer.mergedAt ?? "unknown"} — blame ${where}`
1770
+ );
1771
+ }
1772
+
1773
+ function replayRange(base: string | null, head: string | null): string {
1774
+ if (base === null || head === null) return "unresolved";
1775
+ return `\`${base}..${head}\``;
1776
+ }
1777
+
1778
+ function diffSize(size: {
1779
+ additions: number | null;
1780
+ deletions: number | null;
1781
+ changedFiles: number | null;
1782
+ }): string {
1783
+ if (size.additions === null || size.deletions === null) return "unknown";
1784
+ const files =
1785
+ size.changedFiles === null
1786
+ ? "unknown files"
1787
+ : `${size.changedFiles} file(s)`;
1788
+ return `+${size.additions}/-${size.deletions}, ${files}`;
1789
+ }