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,606 @@
1
+ // Revert/hotfix mining decisions (GitHub #41), pure so every classification
2
+ // rule is pinned offline. pr/reverts.ts is the I/O shell: it runs `git log` over
3
+ // the default branch and asks `gh api` for the PR numbers and diff sizes.
4
+ //
5
+ // PURITY CONTRACT, and it is load-bearing rather than stylistic: nothing here
6
+ // reads the filesystem, spawns git or gh, touches the network, or READS A
7
+ // CLOCK. The artifact must be byte-identical across two runs over unchanged
8
+ // history, so `diff` on it means "history changed", never "time passed". An
9
+ // elapsed duration is therefore always the difference of two RECORDED
10
+ // timestamps, never a measurement against now.
11
+ //
12
+ // What this module does NOT do, by the issue's explicit scope: it never runs
13
+ // a review, never scores, and never labels what the defect was. Everything it
14
+ // emits is a CANDIDATE for a human glance.
15
+
16
+ import { CliUsageError } from "../errors";
17
+
18
+ // Two years of default branch history. WHY this number: a revert is only
19
+ // useful as a known-bad case while the surrounding code still resembles the
20
+ // tree a reviewer would see, and a full-history scan on a busy repo spends
21
+ // minutes of `git log` plus one gh call per hit to surface commits nobody
22
+ // would replay. Two years is long enough that a quiet repo still yields a
23
+ // corpus, short enough that a busy one stays a seconds-long read-only scan.
24
+ export const DEFAULT_REVERTS_SINCE = "24 months ago";
25
+
26
+ // The record separators handed to `git log --format`. \x1f (unit separator)
27
+ // and \x1e (record separator) are ASCII control characters that git will not
28
+ // emit from a commit message — which is the entire point: a message that
29
+ // contains newlines, pipes, quotes or the word "commit" still parses, because
30
+ // the delimiter is a byte no author can type into a subject or body.
31
+ export const GIT_LOG_FIELD_SEP = "\x1f";
32
+ export const GIT_LOG_RECORD_SEP = "\x1e";
33
+ export const GIT_LOG_FORMAT = `--format=%H${GIT_LOG_FIELD_SEP}%ct${GIT_LOG_FIELD_SEP}%s${GIT_LOG_FIELD_SEP}%b${GIT_LOG_RECORD_SEP}`;
34
+
35
+ export interface GitLogRecord {
36
+ sha: string;
37
+ // Committer date, unix seconds (%ct). Seconds rather than an ISO string
38
+ // because it is only ever used as a SORT KEY here; the human-facing
39
+ // timestamps in the artifact are the PRs' own merged_at values from gh.
40
+ committedAtSec: number;
41
+ subject: string;
42
+ body: string;
43
+ }
44
+
45
+ const FULL_SHA = /^[0-9a-f]{40}$/;
46
+
47
+ // Splits the `git log GIT_LOG_FORMAT` stream. Fails loud on a chunk that is
48
+ // not four fields with a real sha: a silently dropped commit is a silently
49
+ // missing candidate, and this command's whole value is that the list is
50
+ // complete for the window it claims.
51
+ export function parseGitLogRecords(raw: string): GitLogRecord[] {
52
+ const records: GitLogRecord[] = [];
53
+ for (const chunk of raw.split(GIT_LOG_RECORD_SEP)) {
54
+ // git writes a newline after each record's trailing separator, so every
55
+ // chunk after the first opens with one. Stripping leading newlines only
56
+ // (not a full trim) keeps a body's own leading content intact.
57
+ const cleaned = chunk.replace(/^[\r\n]+/, "");
58
+ if (cleaned.trim().length === 0) continue;
59
+ const fields = cleaned.split(GIT_LOG_FIELD_SEP);
60
+ if (fields.length < 4) {
61
+ throw new CliUsageError(
62
+ `git log record has ${fields.length} field(s), expected 4 ` +
63
+ "(sha, committer date, subject, body)",
64
+ );
65
+ }
66
+ const sha = (fields[0] ?? "").trim();
67
+ if (!FULL_SHA.test(sha)) {
68
+ throw new CliUsageError(`git log record has no full sha, got: ${sha}`);
69
+ }
70
+ const committedAtSec = Number((fields[1] ?? "").trim());
71
+ if (!Number.isInteger(committedAtSec)) {
72
+ throw new CliUsageError(
73
+ `git log record ${sha} has a non-integer committer date: ${fields[1]}`,
74
+ );
75
+ }
76
+ records.push({
77
+ sha,
78
+ committedAtSec,
79
+ subject: fields[2] ?? "",
80
+ // Everything after the third separator is body, separators included —
81
+ // a body cannot contain \x1f, so a rejoin is lossless.
82
+ body: fields.slice(3).join(GIT_LOG_FIELD_SEP).replace(/\s+$/, ""),
83
+ });
84
+ }
85
+ return records;
86
+ }
87
+
88
+ // ---------------------------------------------------------------------------
89
+ // Classification. ANCHORED at position 0, never a substring search.
90
+ //
91
+ // This is the single most important correctness rule in the command. A
92
+ // substring match on revert|rollback|hotfix produces false positives that
93
+ // look entirely plausible — every one of these is real musive history and
94
+ // NONE of them is a revert:
95
+ // docs(mus-638): handle rollback success status
96
+ // test(MUS-518): re-pin the rollback-scan tripwire after the reformat
97
+ // fix(MUS-706): hoist rollback captures so the catch can revert the cover
98
+ // ci: MUS-598 revert temporary Biome probe
99
+ // fix(app): JD2 round-1 corrections — flush-overlap rollback, ...
100
+ // A corpus polluted with those is worse than no corpus: it spends the human
101
+ // glance the whole artifact is trying to make cheap.
102
+
103
+ export type RevertConfidence = "body-linked" | "pattern-only";
104
+
105
+ // git's own machine-written linkage, the highest-confidence signal there is.
106
+ // Case-sensitive and anchored to a line start: git writes exactly this.
107
+ const BODY_LINK = /^This reverts commit ([0-9a-f]{40})\.?/m;
108
+
109
+ // `Revert "…"` is git's generated subject. Case-insensitive because a
110
+ // hand-typed lowercase `revert "…"` means the same thing and the ANCHOR, not
111
+ // the capital R, is what keeps the false positives out.
112
+ const SUBJECT_QUOTED = /^revert\s+"/i;
113
+
114
+ // Conventional-commit revert type at position 0: `revert:` or
115
+ // `revert(scope):`, with the optional `!` breaking-change marker.
116
+ const SUBJECT_CONVENTIONAL = /^revert(\([^)]*\))?!?:/i;
117
+
118
+ // `Merge pull request #<n> from <owner>/<branch>` — GitHub's own merge
119
+ // subject. Only the BRANCH segment is pattern-matched, so a PR that merely
120
+ // mentions a revert in its title cannot qualify.
121
+ const MERGE_SUBJECT = /^Merge pull request #(\d+) from [^/\s]+\/(\S+)/;
122
+
123
+ // A branch whose name starts with hotfix or revert, allowing the separator
124
+ // forms seen in real history: `hotfix/`, `hotfix-prod/`, `revert/`,
125
+ // `revert-`. Anchored and separator-terminated so `revertigo/x` cannot match.
126
+ const REVERT_BRANCH = /^(hotfix|revert)([-/]|$)/i;
127
+
128
+ // GitHub's revert branches carry the reverted PR number for free:
129
+ // `revert-478-feat-username-cannot-change` → 478.
130
+ const BRANCH_PR = /^revert[-/](\d+)(?:[-/]|$)/i;
131
+
132
+ export interface ClassifiedRevert {
133
+ sha: string;
134
+ committedAtSec: number;
135
+ subject: string;
136
+ body: string;
137
+ confidence: RevertConfidence;
138
+ // body-linked only: the sha the body says was reverted.
139
+ revertedSha: string | null;
140
+ // From `Merge pull request #<n>`: the PR that DID the reverting.
141
+ mergePr: number | null;
142
+ // From a `revert-<n>-…` branch: the PR that WAS reverted.
143
+ branchPr: number | null;
144
+ }
145
+
146
+ export function parseRevertedSha(body: string): string | null {
147
+ // First match only. One logical revert can name several shas across several
148
+ // commits; the pair dedupe below is what collapses those, not this.
149
+ const match = BODY_LINK.exec(body);
150
+ return match?.[1] ?? null;
151
+ }
152
+
153
+ export function parseMergeSubject(
154
+ subject: string,
155
+ ): { pr: number; branch: string } | null {
156
+ const match = MERGE_SUBJECT.exec(subject);
157
+ if (match?.[1] === undefined || match[2] === undefined) return null;
158
+ const pr = Number(match[1]);
159
+ if (!Number.isInteger(pr) || pr < 1) return null;
160
+ return { pr, branch: match[2] };
161
+ }
162
+
163
+ export function revertedPrFromBranch(branch: string): number | null {
164
+ const match = BRANCH_PR.exec(branch);
165
+ if (match?.[1] === undefined) return null;
166
+ const pr = Number(match[1]);
167
+ return Number.isInteger(pr) && pr >= 1 ? pr : null;
168
+ }
169
+
170
+ // Returns null for anything that is not a revert. body-linked is tested
171
+ // FIRST and stands on its own: git wrote that line, so it outranks whatever
172
+ // a human typed into the subject.
173
+ export function classifyRevertCommit(
174
+ record: GitLogRecord,
175
+ ): ClassifiedRevert | null {
176
+ const merge = parseMergeSubject(record.subject);
177
+ const base = {
178
+ sha: record.sha,
179
+ committedAtSec: record.committedAtSec,
180
+ subject: record.subject,
181
+ body: record.body,
182
+ mergePr: merge?.pr ?? null,
183
+ branchPr: merge === null ? null : revertedPrFromBranch(merge.branch),
184
+ };
185
+ const revertedSha = parseRevertedSha(record.body);
186
+ if (revertedSha !== null) {
187
+ return { ...base, confidence: "body-linked", revertedSha };
188
+ }
189
+ const subjectMatches =
190
+ SUBJECT_QUOTED.test(record.subject) ||
191
+ SUBJECT_CONVENTIONAL.test(record.subject);
192
+ const branchMatches = merge !== null && REVERT_BRANCH.test(merge.branch);
193
+ if (subjectMatches || branchMatches) {
194
+ return { ...base, confidence: "pattern-only", revertedSha: null };
195
+ }
196
+ return null;
197
+ }
198
+
199
+ // ---------------------------------------------------------------------------
200
+ // Candidates: a classified commit with whatever the gh lookups resolved.
201
+
202
+ export interface RevertCandidate {
203
+ revertCommitSha: string;
204
+ revertCommittedAtSec: number;
205
+ revertSubject: string;
206
+ revertBody: string;
207
+ confidence: RevertConfidence;
208
+ revertingPr: number | null;
209
+ revertingPrMergedAt: string | null;
210
+ revertedPr: number | null;
211
+ revertedPrTitle: string | null;
212
+ revertedPrMergedAt: string | null;
213
+ // The range to replay the reverted PR: base.sha..head.sha.
214
+ revertedBaseSha: string | null;
215
+ revertedHeadSha: string | null;
216
+ additions: number | null;
217
+ deletions: number | null;
218
+ changedFiles: number | null;
219
+ // How many revert commits collapsed into this representative. 1 means it
220
+ // stood alone.
221
+ collapsedCommits: number;
222
+ }
223
+
224
+ // FILTER 1, and it is not optional. A revert whose reverting PR equals the
225
+ // reverted PR never crossed a merge boundary: somebody added a commit and
226
+ // removed it again inside one branch, so nothing ever shipped and there is no
227
+ // regression to catch. Found by probing real data — musive 0f309d0ed resolves
228
+ // to PR 1534 on BOTH sides. Without this the corpus inflates with cases where
229
+ // the "known bad" code was never on the default branch at all.
230
+ export function dropSamePrReverts(
231
+ candidates: RevertCandidate[],
232
+ ): RevertCandidate[] {
233
+ return candidates.filter(
234
+ (candidate) =>
235
+ candidate.revertedPr === null ||
236
+ candidate.revertingPr === null ||
237
+ candidate.revertedPr !== candidate.revertingPr,
238
+ );
239
+ }
240
+
241
+ // FILTER 2, equally not optional. One logical revert is frequently several
242
+ // commits — musive reverted PR 478 via PR 483 in three commits (4ee802e43,
243
+ // 5c8c4fa4e, fea0540a0) across app/web/common. That is ONE case. Counting it
244
+ // three times would triple-weight a single decision in any tally built on
245
+ // this artifact.
246
+ //
247
+ // The representative is the EARLIEST commit of the pair (the one that opened
248
+ // the revert), and the count of what collapsed into it is recorded so the
249
+ // artifact never hides the merge.
250
+ export function dedupeRevertPairs(
251
+ candidates: RevertCandidate[],
252
+ ): RevertCandidate[] {
253
+ const byPair = new Map<string, RevertCandidate>();
254
+ const order: string[] = [];
255
+ for (const candidate of candidates) {
256
+ // When NEITHER side resolved to a PR number there is no pair to dedupe
257
+ // on, and collapsing on a shared "unknown" key would silently merge two
258
+ // unrelated commits. Such a candidate keys on its own sha instead.
259
+ const key =
260
+ candidate.revertedPr === null && candidate.revertingPr === null
261
+ ? `sha:${candidate.revertCommitSha}`
262
+ : `pair:${candidate.revertedPr ?? "?"}:${candidate.revertingPr ?? "?"}`;
263
+ const existing = byPair.get(key);
264
+ if (existing === undefined) {
265
+ byPair.set(key, { ...candidate, collapsedCommits: 1 });
266
+ order.push(key);
267
+ continue;
268
+ }
269
+ const earliest =
270
+ candidate.revertCommittedAtSec < existing.revertCommittedAtSec
271
+ ? candidate
272
+ : existing;
273
+ byPair.set(key, {
274
+ ...earliest,
275
+ collapsedCommits: existing.collapsedCommits + 1,
276
+ });
277
+ }
278
+ return order.map((key) => {
279
+ const candidate = byPair.get(key);
280
+ if (candidate === undefined) {
281
+ throw new CliUsageError(`dedupe lost the candidate keyed ${key}`);
282
+ }
283
+ return candidate;
284
+ });
285
+ }
286
+
287
+ // Both filters plus the artifact's deterministic order: newest reverting
288
+ // commit first, ties broken by sha so two runs over unchanged history cannot
289
+ // disagree about which of two same-second commits comes first.
290
+ export function selectRevertCandidates(
291
+ candidates: RevertCandidate[],
292
+ ): RevertCandidate[] {
293
+ const kept = dedupeRevertPairs(dropSamePrReverts(candidates));
294
+ return [...kept].sort((a, b) =>
295
+ b.revertCommittedAtSec === a.revertCommittedAtSec
296
+ ? a.revertCommitSha.localeCompare(b.revertCommitSha)
297
+ : b.revertCommittedAtSec - a.revertCommittedAtSec,
298
+ );
299
+ }
300
+
301
+ // ---------------------------------------------------------------------------
302
+ // gh payload readers. The pure reader names the FIELD it could not read, and the shell re-wraps adding the
303
+ // endpoint only it knows.
304
+
305
+ export interface CommitPullRef {
306
+ number: number;
307
+ title: string | null;
308
+ mergedAt: string | null;
309
+ }
310
+
311
+ function asRecord(value: unknown, what: string): Record<string, unknown> {
312
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
313
+ throw new CliUsageError(`${what} is not an object`);
314
+ }
315
+ return value as Record<string, unknown>;
316
+ }
317
+
318
+ function optionalString(value: unknown): string | null {
319
+ return typeof value === "string" && value.length > 0 ? value : null;
320
+ }
321
+
322
+ function optionalNumber(value: unknown): number | null {
323
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
324
+ }
325
+
326
+ // `gh api repos/<slug>/commits/<sha>/pulls` → the PRs a commit belongs to.
327
+ // VERIFIED: this endpoint returns additions/deletions/changed_files as NULL,
328
+ // which is why the size fields come from a second /pulls/<n> call and never
329
+ // from here. Anything that is not a merged PR object is skipped rather than
330
+ // fatal — an unmerged or malformed entry is not a case, and one odd row must
331
+ // not kill a scan of hundreds of commits.
332
+ export function parseCommitPulls(raw: string): CommitPullRef[] {
333
+ let parsed: unknown;
334
+ try {
335
+ parsed = JSON.parse(raw);
336
+ } catch {
337
+ throw new CliUsageError("commit pulls response is not JSON");
338
+ }
339
+ if (!Array.isArray(parsed)) {
340
+ throw new CliUsageError("commit pulls response is not an array");
341
+ }
342
+ const refs: CommitPullRef[] = [];
343
+ for (const entry of parsed) {
344
+ if (typeof entry !== "object" || entry === null) continue;
345
+ const record = entry as Record<string, unknown>;
346
+ const number = optionalNumber(record.number);
347
+ if (number === null || !Number.isInteger(number) || number < 1) continue;
348
+ refs.push({
349
+ number,
350
+ title: optionalString(record.title),
351
+ mergedAt: optionalString(record.merged_at),
352
+ });
353
+ }
354
+ return refs;
355
+ }
356
+
357
+ // A commit can belong to more than one PR (a branch merged into a branch).
358
+ // The FIRST is GitHub's own primary association and the one the web UI shows;
359
+ // picking anything else would need a rule this command has no evidence for.
360
+ export function pickCommitPull(refs: CommitPullRef[]): CommitPullRef | null {
361
+ return refs[0] ?? null;
362
+ }
363
+
364
+ export interface PullDetails {
365
+ number: number;
366
+ title: string | null;
367
+ mergedAt: string | null;
368
+ baseSha: string | null;
369
+ headSha: string | null;
370
+ additions: number | null;
371
+ deletions: number | null;
372
+ changedFiles: number | null;
373
+ }
374
+
375
+ // `gh api repos/<slug>/pulls/<n>` → the fields the artifact needs that the
376
+ // commit-pulls endpoint leaves null: the diff size and the base/head shas
377
+ // that make up the replay range.
378
+ export function parsePullDetails(raw: string): PullDetails {
379
+ let parsed: unknown;
380
+ try {
381
+ parsed = JSON.parse(raw);
382
+ } catch {
383
+ throw new CliUsageError("pull details response is not JSON");
384
+ }
385
+ const record = asRecord(parsed, "pull details response");
386
+ const number = optionalNumber(record.number);
387
+ if (number === null || !Number.isInteger(number) || number < 1) {
388
+ throw new CliUsageError("pull details response has no number");
389
+ }
390
+ const base = record.base;
391
+ const head = record.head;
392
+ return {
393
+ number,
394
+ title: optionalString(record.title),
395
+ mergedAt: optionalString(record.merged_at),
396
+ baseSha:
397
+ typeof base === "object" && base !== null
398
+ ? optionalString((base as Record<string, unknown>).sha)
399
+ : null,
400
+ headSha:
401
+ typeof head === "object" && head !== null
402
+ ? optionalString((head as Record<string, unknown>).sha)
403
+ : null,
404
+ additions: optionalNumber(record.additions),
405
+ deletions: optionalNumber(record.deletions),
406
+ changedFiles: optionalNumber(record.changed_files),
407
+ };
408
+ }
409
+
410
+ // `https://github.com/owner/repo` → `owner/repo`, the path segment `gh api
411
+ // repos/<slug>/…` wants. Deliberately built on top of review/preflight.ts's
412
+ // repoWebUrlFromRemote (which already normalises the three remote shapes)
413
+ // rather than parsing a remote again: a second URL parser is a second place
414
+ // for the owner to be wrong.
415
+ export function repoSlugFromWebUrl(webUrl: string): string | null {
416
+ const prefix = "https://github.com/";
417
+ if (!webUrl.startsWith(prefix)) return null;
418
+ const slug = webUrl.slice(prefix.length).replace(/\/+$/, "");
419
+ return /^[^/\s]+\/[^/\s]+$/.test(slug) ? slug : null;
420
+ }
421
+
422
+ // ---------------------------------------------------------------------------
423
+ // The artifact.
424
+
425
+ export interface RevertsArtifact {
426
+ repoSlug: string;
427
+ ref: string;
428
+ since: string;
429
+ scannedCommits: number;
430
+ candidates: RevertCandidate[];
431
+ }
432
+
433
+ const CANDIDATE_WARNING = [
434
+ "> **These are CANDIDATES REQUIRING HUMAN CONFIRMATION, not confirmed",
435
+ "> defects.** A revert is not always a defect: reverts also happen for",
436
+ "> product reasons, merge accidents and dependency rollbacks. Every entry",
437
+ "> below needs a human glance — and its stated reason is recorded here so",
438
+ "> that glance is cheap — before it is treated as a known-bad case.",
439
+ ];
440
+
441
+ const CLASS_ORDER: RevertConfidence[] = ["body-linked", "pattern-only"];
442
+
443
+ const CLASS_NOTE: Record<RevertConfidence, string> = {
444
+ "body-linked":
445
+ "The commit body carries git's own `This reverts commit <sha>.` line — " +
446
+ "machine-written linkage, the highest confidence available.",
447
+ "pattern-only":
448
+ 'No body link. Matched by an anchored subject (`Revert "…"`, ' +
449
+ "`revert:`) or a merge from a `hotfix`/`revert` branch. Lower " +
450
+ "confidence: check what it actually reverted.",
451
+ };
452
+
453
+ export function renderRevertsArtifact(artifact: RevertsArtifact): string {
454
+ const out: string[] = [];
455
+ out.push("# crysk — revert/hotfix candidates");
456
+ out.push("");
457
+ out.push(`- repository: \`${artifact.repoSlug}\``);
458
+ out.push(`- ref: \`${artifact.ref}\``);
459
+ out.push(`- window: \`--since ${artifact.since}\``);
460
+ out.push(
461
+ `- scanned: ${artifact.scannedCommits} commit(s) · ` +
462
+ `${artifact.candidates.length} candidate(s)`,
463
+ );
464
+ for (const confidence of CLASS_ORDER) {
465
+ const count = artifact.candidates.filter(
466
+ (candidate) => candidate.confidence === confidence,
467
+ ).length;
468
+ out.push(`- ${confidence}: ${count}`);
469
+ }
470
+ out.push("");
471
+ out.push(...CANDIDATE_WARNING);
472
+ out.push("");
473
+ for (const confidence of CLASS_ORDER) {
474
+ const group = artifact.candidates.filter(
475
+ (candidate) => candidate.confidence === confidence,
476
+ );
477
+ out.push(`## ${confidence} (${group.length})`);
478
+ out.push("");
479
+ out.push(CLASS_NOTE[confidence]);
480
+ out.push("");
481
+ if (group.length === 0) {
482
+ out.push("_None in this window._");
483
+ out.push("");
484
+ continue;
485
+ }
486
+ for (const candidate of group) {
487
+ out.push(...renderCandidate(candidate));
488
+ }
489
+ }
490
+ return `${out.join("\n").replace(/\n+$/, "")}\n`;
491
+ }
492
+
493
+ function renderCandidate(candidate: RevertCandidate): string[] {
494
+ const out: string[] = [];
495
+ const title = candidate.revertedPrTitle ?? "(title unresolved)";
496
+ out.push(
497
+ candidate.revertedPr === null
498
+ ? `### reverted PR unresolved — ${shortSha(candidate.revertCommitSha)}`
499
+ : `### PR #${candidate.revertedPr} — ${title}`,
500
+ );
501
+ out.push("");
502
+ out.push(
503
+ `- reverted PR: ${prField(candidate.revertedPr)}, merged ` +
504
+ `${stampField(candidate.revertedPrMergedAt)}`,
505
+ );
506
+ out.push(
507
+ `- reverting PR: ${prField(candidate.revertingPr)}, merged ` +
508
+ `${stampField(candidate.revertingPrMergedAt)}`,
509
+ );
510
+ out.push(
511
+ `- elapsed: ${formatMergeToRevertGap(
512
+ candidate.revertedPrMergedAt,
513
+ candidate.revertingPrMergedAt,
514
+ )}`,
515
+ );
516
+ out.push(`- reverting commit: \`${candidate.revertCommitSha}\``);
517
+ out.push(`- replay range: ${replayRange(candidate)}`);
518
+ out.push(`- diff size: ${diffSize(candidate)}`);
519
+ out.push(`- stated reason: ${candidate.revertSubject.trim() || "(none)"}`);
520
+ if (candidate.collapsedCommits > 1) {
521
+ out.push(
522
+ `- collapsed: ${candidate.collapsedCommits} revert commits share this ` +
523
+ "reverted/reverting PR pair; the earliest is shown",
524
+ );
525
+ }
526
+ const reason = revertReasonBody(candidate.revertBody);
527
+ if (reason.length > 0) {
528
+ out.push("");
529
+ for (const line of reason) out.push(`> ${line}`);
530
+ }
531
+ out.push("");
532
+ return out;
533
+ }
534
+
535
+ function shortSha(sha: string): string {
536
+ return sha.slice(0, 12);
537
+ }
538
+
539
+ function prField(pr: number | null): string {
540
+ return pr === null ? "unresolved" : `#${pr}`;
541
+ }
542
+
543
+ function stampField(stamp: string | null): string {
544
+ return stamp ?? "unknown";
545
+ }
546
+
547
+ function replayRange(candidate: RevertCandidate): string {
548
+ if (
549
+ candidate.revertedBaseSha === null ||
550
+ candidate.revertedHeadSha === null
551
+ ) {
552
+ return "unresolved";
553
+ }
554
+ return `\`${candidate.revertedBaseSha}..${candidate.revertedHeadSha}\``;
555
+ }
556
+
557
+ function diffSize(candidate: RevertCandidate): string {
558
+ if (candidate.additions === null || candidate.deletions === null) {
559
+ return "unknown";
560
+ }
561
+ const files =
562
+ candidate.changedFiles === null
563
+ ? "unknown files"
564
+ : `${candidate.changedFiles} file(s)`;
565
+ return `+${candidate.additions}/-${candidate.deletions}, ${files}`;
566
+ }
567
+
568
+ // The body MINUS git's machine-written lines: `This reverts commit …` says
569
+ // nothing a human needs, and the sha is already rendered above. What is left
570
+ // is the author's stated reason, which is the whole point of recording it.
571
+ export function revertReasonBody(body: string): string[] {
572
+ const lines = body
573
+ .split("\n")
574
+ .filter(
575
+ (line) => !/^This reverts commit [0-9a-f]{40}\.?$/.test(line.trim()),
576
+ )
577
+ .map((line) => line.replace(/\s+$/, ""));
578
+ while (lines.length > 0 && (lines[0] ?? "").length === 0) lines.shift();
579
+ while (lines.length > 0 && (lines[lines.length - 1] ?? "").length === 0) {
580
+ lines.pop();
581
+ }
582
+ return lines;
583
+ }
584
+
585
+ // Difference of two RECORDED timestamps. Never a clock read — see the purity
586
+ // contract at the top of this file: an artifact carrying "3 days ago" would
587
+ // change every day on unchanged history and make `diff` meaningless.
588
+ export function formatMergeToRevertGap(
589
+ fromIso: string | null,
590
+ toIso: string | null,
591
+ ): string {
592
+ if (fromIso === null || toIso === null) return "unknown";
593
+ const from = Date.parse(fromIso);
594
+ const to = Date.parse(toIso);
595
+ if (Number.isNaN(from) || Number.isNaN(to)) return "unknown";
596
+ const totalMinutes = Math.round((to - from) / 60_000);
597
+ if (totalMinutes < 0) return "unknown";
598
+ const days = Math.floor(totalMinutes / (60 * 24));
599
+ const hours = Math.floor((totalMinutes % (60 * 24)) / 60);
600
+ const minutes = totalMinutes % 60;
601
+ const parts: string[] = [];
602
+ if (days > 0) parts.push(`${days}d`);
603
+ if (hours > 0) parts.push(`${hours}h`);
604
+ if (minutes > 0 || parts.length === 0) parts.push(`${minutes}m`);
605
+ return `${parts.join(" ")} between merge and revert`;
606
+ }