crysk 0.0.0 → 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 +609 -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/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 +81 -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,595 @@
1
+ // The size gate: "this diff is too big — skip it". Pure, offline-testable,
2
+ // and deliberately dumb — it counts lines and files and compares them to two
3
+ // numbers.
4
+ //
5
+ // WHY this exists, stated exactly and no wider: it is a COST AND
6
+ // PREDICTABILITY gate, NOT a quality gate. Measured on our own runs, small
7
+ // trees bill $1.9–$4.8, while the 45-file / +2775 −1237 bench tree billed
8
+ // $6.58–$17.92 across 18 iterations — the cost roughly triples AND its spread
9
+ // widens to ~2.7x, so a big tree is both expensive and unbudgetable.
10
+ //
11
+ // What this gate does NOT claim, because we measured it and it is not true:
12
+ // that a bigger diff reviews WORSE. Attention dilution was tested and
13
+ // falsified in fixtures/scale-probe.ts, and the one measured Greptile-only
14
+ // miss came from a 7-file PR. Nothing here — comment, message or flag help —
15
+ // may imply otherwise.
16
+
17
+ import {
18
+ BUILTIN_IGNORE_RULES,
19
+ compileIgnoreRules,
20
+ type IgnoreRule,
21
+ } from "../ignore-file";
22
+ import type { IgnoreFileReadResult } from "../ignore-read";
23
+ import type { NumstatDiffStat, NumstatFile } from "./preflight";
24
+
25
+ export interface SizeGateConfig {
26
+ // <= 0 disables the limit. Both knobs, independently.
27
+ maxChangedLines: number;
28
+ maxChangedFiles: number;
29
+ excludeRules: IgnoreRule[];
30
+ }
31
+
32
+ // The shipped defaults. 4000 lines sits above the everyday PR; 150 files is
33
+ // the "this is a mechanical sweep, not a review" ceiling.
34
+ //
35
+ // The line default has a history, and the arc matters because the middle of
36
+ // it was a wrong diagnosis. 1500 shipped first, extrapolated from
37
+ // "everything measured cheap was under 830 lines". Then this repo's own PR
38
+ // #1 (1603 lines) printed `size gate: SKIP` and a $3.18-6.86 cost band in the
39
+ // same breath — the gate refusing, on cost grounds, a diff whose cost was
40
+ // ordinary. The conclusion drawn at the time was "the limit is too tight",
41
+ // and it was raised to 2500.
42
+ //
43
+ // That was treating the symptom. The real cause was that the gate was
44
+ // counting lines it was not actually filtering out of the bill:
45
+ // - F001 — the exclusion list shrank the GATE's count but not the diff
46
+ // handed to the hunters, so an excluded lockfile was still paid for in
47
+ // full. The count and the bill were two different numbers.
48
+ // - whitespace — a formatter sweep consumed budget it costs nothing to
49
+ // review, because the count was taken from a plain `--numstat`.
50
+ // With both fixed (the reviewed diff IS the filtered diff, and the gate
51
+ // counts from `git diff -w --ignore-blank-lines`), the number the gate
52
+ // measures is the number that gets paid for, and 1500 was a real 1500. So it
53
+ // stood, and 2500 stayed retired — for a while.
54
+ //
55
+ // The band 830..4000 is still unmeasured. If a diff in it ever bills like the
56
+ // bench tree, this number is the thing to revisit — with a measurement, not
57
+ // another extrapolation.
58
+ //
59
+ // On 2026-09-25 the default moved again, 1500 -> 4000 — NOT a measurement
60
+ // this time, an owner decision: 1500 was skipping too many real PRs outright,
61
+ // and that cost (a review that never runs) was judged worse than the
62
+ // cost/predictability this gate exists to manage. This is the same bench tree
63
+ // cited above: +2775 -1237 across 45 files is ~4000 lines, so the new default
64
+ // sits right AT that tree's size, not "well below" it as the old default did.
65
+ // This says nothing about review quality at 4000 lines — see the file header,
66
+ // this is a COST gate, never a quality one — only that the owner would rather
67
+ // pay/wait for a big review than silently skip it.
68
+ //
69
+ // The default RULES — not a hand-written glob list — are generated-content
70
+ // only: lockfiles, minified bundles and jest-style snapshots are enormous,
71
+ // mechanical, and nothing a hunter can usefully read. Excluding them keeps
72
+ // the gate from firing on a PR whose real change is ten lines beside a
73
+ // regenerated lockfile. `BUILTIN_IGNORE_RULES` (src/ignore-file.ts) parses
74
+ // these same 9 exclusions from plain gitignore LINES through the exact
75
+ // dialect a user's own `.prheroignore` goes through, so the shape here is
76
+ // `IgnoreRule[]`, not `string[]`.
77
+ export const DEFAULT_SIZE_GATE: SizeGateConfig = {
78
+ maxChangedLines: 4000,
79
+ maxChangedFiles: 150,
80
+ excludeRules: BUILTIN_IGNORE_RULES,
81
+ };
82
+
83
+ export type SizeGateVerdict =
84
+ | {
85
+ ok: true;
86
+ effectiveLines: number;
87
+ effectiveFiles: number;
88
+ excludedFiles: number;
89
+ excludedLines: number;
90
+ }
91
+ | {
92
+ ok: false;
93
+ reason: "lines" | "files";
94
+ effectiveLines: number;
95
+ effectiveFiles: number;
96
+ excludedFiles: number;
97
+ excludedLines: number;
98
+ limit: number;
99
+ message: string;
100
+ };
101
+
102
+ // What the shell does with a verdict. Pure so the three callers (local,
103
+ // PR, and the tests) cannot drift on who gets a prompt vs a hard skip.
104
+ //
105
+ // proceed — under the limit, or --force already answered "review anyway".
106
+ // skip — over the limit AND nobody can be asked: --yes (the watcher
107
+ // spawns with it) or a non-TTY stdin. This is the load-bearing
108
+ // unattended path; a prompt here would never fire, which is
109
+ // exactly how the gate used to be bypassed by accident.
110
+ // prompt — over the limit, interactive TTY, no --force. The operator
111
+ // already typed the review command; dying and making them
112
+ // re-run with --force is the same answer with worse UX.
113
+ export type SizeGateDisposition =
114
+ | { action: "proceed" }
115
+ | { action: "skip"; message: string }
116
+ | { action: "prompt" };
117
+
118
+ export function sizeGateDisposition(
119
+ verdict: SizeGateVerdict,
120
+ opts: { force: boolean; yes: boolean; interactive: boolean },
121
+ ): SizeGateDisposition {
122
+ if (verdict.ok || opts.force) return { action: "proceed" };
123
+ if (opts.yes || !opts.interactive) {
124
+ return { action: "skip", message: verdict.message };
125
+ }
126
+ return { action: "prompt" };
127
+ }
128
+
129
+ // Exclusions are applied FIRST and the REMAINDER is what gets compared: the
130
+ // whole point of the list is that a regenerated lockfile must not push a
131
+ // small change over the line. Lines are checked before files, because the
132
+ // line count is what actually drives the bill (files is the coarser
133
+ // backstop).
134
+ export function evaluateSizeGate(
135
+ files: NumstatFile[],
136
+ config: SizeGateConfig,
137
+ ): SizeGateVerdict {
138
+ const matcher = compileIgnoreRules(config.excludeRules);
139
+ let effectiveLines = 0;
140
+ let effectiveFiles = 0;
141
+ let excludedLines = 0;
142
+ let excludedFiles = 0;
143
+ for (const file of files) {
144
+ const lines = file.insertions + file.deletions;
145
+ if (matcher.match(file.path) !== undefined) {
146
+ excludedFiles++;
147
+ excludedLines += lines;
148
+ continue;
149
+ }
150
+ effectiveFiles++;
151
+ effectiveLines += lines;
152
+ }
153
+ const counts = {
154
+ effectiveLines,
155
+ effectiveFiles,
156
+ excludedFiles,
157
+ excludedLines,
158
+ };
159
+ if (config.maxChangedLines > 0 && effectiveLines > config.maxChangedLines) {
160
+ return {
161
+ ok: false,
162
+ reason: "lines",
163
+ ...counts,
164
+ limit: config.maxChangedLines,
165
+ message: gateMessage(
166
+ `${effectiveLines} effective changed line${plural(effectiveLines)} ` +
167
+ `exceeds the ${config.maxChangedLines}-line limit`,
168
+ counts,
169
+ "--max-changed-lines",
170
+ ),
171
+ };
172
+ }
173
+ if (config.maxChangedFiles > 0 && effectiveFiles > config.maxChangedFiles) {
174
+ return {
175
+ ok: false,
176
+ reason: "files",
177
+ ...counts,
178
+ limit: config.maxChangedFiles,
179
+ message: gateMessage(
180
+ `${effectiveFiles} effective changed file${plural(effectiveFiles)} ` +
181
+ `exceeds the ${config.maxChangedFiles}-file limit`,
182
+ counts,
183
+ "--max-changed-files",
184
+ ),
185
+ };
186
+ }
187
+ return { ok: true, ...counts };
188
+ }
189
+
190
+ // THE POINT OF THE EXCLUSION LIST, restated as an invariant: the number the
191
+ // gate measures and the number that gets paid for must be the SAME number.
192
+ // Before this existed, exclusions shrank the gate's count while the hunters
193
+ // were still handed the full unfiltered diff — so a PR with a regenerated
194
+ // 5000-line lockfile passed the gate on a small effective count and then paid
195
+ // to feed that lockfile to every hunter, defeating the gate in exactly the
196
+ // case it was built for.
197
+ //
198
+ // So the excluded files fall out of the REVIEWED DIFF itself: `diff.patch` is
199
+ // this function's output, which makes it literally what the hunters saw, and
200
+ // the cost basis is `effectiveDiffStat` over the SAME rule set — both now
201
+ // share the one matcher this module builds via `compileIgnoreRules`, so they
202
+ // cannot independently drift on what counts as excluded (the "Single Shared
203
+ // Matcher" requirement this consolidation exists to satisfy).
204
+ //
205
+ // Filtering a unified diff by path has to be done on RECORDS, never on lines:
206
+ // a `diff --git ` header at column 0 starts a record and everything up to the
207
+ // next one belongs to it (content lines always carry a ` `/`+`/`-`/`\` prefix,
208
+ // so they can never be mistaken for a header). Whole records are dropped or
209
+ // kept — never individual hunks.
210
+ export interface ExcludedPath {
211
+ path: string;
212
+ // The excluding rule's source line — see IgnoreRule.pattern.
213
+ pattern: string;
214
+ source: "builtin" | "user";
215
+ line?: number;
216
+ }
217
+
218
+ export interface DiffFilterResult {
219
+ // The effective diff: every record whose destination path matched an
220
+ // exclusion rule removed. Byte-identical to the input when nothing matched.
221
+ patch: string;
222
+ // Destination paths of the dropped records, in diff order. Empty means the
223
+ // filter was a no-op — callers use this to decide whether a raw copy of the
224
+ // diff is worth keeping and what to report as provenance.
225
+ droppedPaths: string[];
226
+ // Per-path provenance: which rule (and source) excluded it, in diff order,
227
+ // parallel to droppedPaths.
228
+ exclusions: ExcludedPath[];
229
+ }
230
+
231
+ export function filterDiffByIgnoreRules(
232
+ patch: string,
233
+ rules: readonly IgnoreRule[],
234
+ ): DiffFilterResult {
235
+ const records = splitDiffRecords(patch);
236
+ if (records.length === 0) return { patch, droppedPaths: [], exclusions: [] };
237
+ const matcher = compileIgnoreRules(rules);
238
+ const kept: string[] = [];
239
+ const droppedPaths: string[] = [];
240
+ const exclusions: ExcludedPath[] = [];
241
+ for (const record of records) {
242
+ const target = diffRecordPath(record);
243
+ // A record whose path cannot be resolved is KEPT. Failing open here is
244
+ // the conservative direction: the worst case is paying to review a file
245
+ // that could have been excluded, where failing closed would silently
246
+ // delete real changed code out of the reviewed diff. PRESERVED across
247
+ // this rename/consolidation — see the pin in test/size-gate.test.ts.
248
+ const hit = target !== undefined ? matcher.match(target) : undefined;
249
+ if (target !== undefined && hit !== undefined) {
250
+ droppedPaths.push(target);
251
+ exclusions.push({
252
+ path: target,
253
+ pattern: hit.pattern,
254
+ source: hit.source,
255
+ line: hit.line,
256
+ });
257
+ continue;
258
+ }
259
+ kept.push(record);
260
+ }
261
+ return { patch: kept.join(""), droppedPaths, exclusions };
262
+ }
263
+
264
+ // Split on column-0 `diff --git ` headers, keeping each record's own bytes
265
+ // (including its trailing newline) so a no-op filter reassembles the input
266
+ // exactly. Anything before the first header — git emits nothing there, but a
267
+ // hand-assembled patch might — is carried as a leading record with no path,
268
+ // which the fail-open rule above keeps.
269
+ export function splitDiffRecords(patch: string): string[] {
270
+ const records: string[] = [];
271
+ let start = -1;
272
+ let offset = 0;
273
+ for (const line of patch.split("\n")) {
274
+ const lineLength = line.length + 1;
275
+ if (line.startsWith("diff --git ")) {
276
+ if (start !== -1) records.push(patch.slice(start, offset));
277
+ start = offset;
278
+ } else if (start === -1 && line.length > 0) {
279
+ start = offset;
280
+ }
281
+ offset += lineLength;
282
+ }
283
+ if (start !== -1) records.push(patch.slice(start));
284
+ return records;
285
+ }
286
+
287
+ // The DESTINATION path of a record, resolved the same way and for the same
288
+ // reason as resolveNumstatPath (review/preflight.ts): a rename must be matched on
289
+ // where the file ENDED UP, or a renamed lockfile silently stops being
290
+ // excluded. Preference order runs from the most explicit source to the least:
291
+ //
292
+ // `rename to` / `copy to` — the only unambiguous destination for a rename,
293
+ // and present even when the record is binary and
294
+ // carries no ---/+++ pair at all;
295
+ // `+++ b/<path>` — the ordinary textual case;
296
+ // `--- a/<path>` — a deletion (+++ is /dev/null), where the source
297
+ // path is the only path there is;
298
+ // the header itself — binary adds/deletes, which have neither.
299
+ //
300
+ // git quotes paths with control or non-ASCII characters
301
+ // (`"caf\303\251/bun.lock"`), and this unquotes them. resolveNumstatPath in
302
+ // review/preflight.ts now unquotes too: the asymmetry was NOT harmless — such a file
303
+ // was dropped from diff.patch while its lines stayed in the gate's count, so
304
+ // the gate could refuse a PR whose effective diff was small. Both sides must
305
+ // keep unquoting or that divergence comes straight back.
306
+ export function diffRecordPath(record: string): string | undefined {
307
+ const lines = record.split("\n");
308
+ let minusPath: string | undefined;
309
+ for (const line of lines) {
310
+ if (line.startsWith("rename to ")) return unquotePath(line.slice(10));
311
+ if (line.startsWith("copy to ")) return unquotePath(line.slice(8));
312
+ if (line.startsWith("+++ ")) {
313
+ const target = stripDiffPrefix(line.slice(4));
314
+ if (target !== undefined) return target;
315
+ }
316
+ if (line.startsWith("--- ") && minusPath === undefined) {
317
+ minusPath = stripDiffPrefix(line.slice(4));
318
+ }
319
+ // The header and the ---/+++ pair live in the record's preamble; hunks
320
+ // below can contain any text at all, so stop before reading them as
321
+ // metadata.
322
+ if (line.startsWith("@@")) break;
323
+ }
324
+ if (minusPath !== undefined) return minusPath;
325
+ return headerPath(lines[0] ?? "");
326
+ }
327
+
328
+ // `a/<path>` / `b/<path>`, with /dev/null meaning "this side does not exist".
329
+ function stripDiffPrefix(field: string): string | undefined {
330
+ // The path may be followed by a tab and a timestamp (git does not emit one,
331
+ // other producers do).
332
+ const raw = unquotePath(field.split("\t")[0] ?? "");
333
+ if (raw === "/dev/null") return undefined;
334
+ return raw.startsWith("a/") || raw.startsWith("b/") ? raw.slice(2) : raw;
335
+ }
336
+
337
+ // `diff --git a/<src> b/<dst>`. The separator is ambiguous when a path itself
338
+ // contains " b/", so prefer the split where source and destination agree (the
339
+ // non-rename case, which is nearly all of them) and fall back to the first
340
+ // candidate. Only reached for records that carry no other path evidence.
341
+ function headerPath(header: string): string | undefined {
342
+ if (!header.startsWith("diff --git ")) return undefined;
343
+ const rest = header.slice(11);
344
+ let first: string | undefined;
345
+ for (let i = 0; i < rest.length; i++) {
346
+ if (!rest.startsWith(" b/", i)) continue;
347
+ const source = unquotePath(rest.slice(0, i));
348
+ const destination = unquotePath(rest.slice(i + 1));
349
+ const src = source.startsWith("a/") ? source.slice(2) : source;
350
+ const dst = destination.startsWith("b/")
351
+ ? destination.slice(2)
352
+ : destination;
353
+ if (src === dst) return dst;
354
+ if (first === undefined) first = dst;
355
+ }
356
+ return first;
357
+ }
358
+
359
+ // git's C-style quoting, undone. Only the escapes git actually emits.
360
+ export function unquotePath(field: string): string {
361
+ const raw = field.trim();
362
+ if (!(raw.startsWith('"') && raw.endsWith('"') && raw.length >= 2)) {
363
+ return raw;
364
+ }
365
+ const body = raw.slice(1, -1);
366
+ let out = "";
367
+ const bytes: number[] = [];
368
+ const flush = (): void => {
369
+ if (bytes.length === 0) return;
370
+ out += new TextDecoder().decode(new Uint8Array(bytes));
371
+ bytes.length = 0;
372
+ };
373
+ for (let i = 0; i < body.length; i++) {
374
+ if (body[i] !== "\\") {
375
+ flush();
376
+ out += body[i];
377
+ continue;
378
+ }
379
+ const next = body[i + 1] ?? "";
380
+ const octal = /^[0-7]{3}$/.exec(body.slice(i + 1, i + 4));
381
+ if (octal !== null) {
382
+ bytes.push(Number.parseInt(octal[0], 8));
383
+ i += 3;
384
+ continue;
385
+ }
386
+ flush();
387
+ const simple: Record<string, string> = {
388
+ n: "\n",
389
+ t: "\t",
390
+ r: "\r",
391
+ '"': '"',
392
+ "\\": "\\",
393
+ };
394
+ out += simple[next] ?? next;
395
+ i += 1;
396
+ }
397
+ flush();
398
+ return out;
399
+ }
400
+
401
+ // The cost basis: the same aggregate the plan and the cost band read, but
402
+ // summed over the files that SURVIVE the exclusions. Feeding estimateCost the
403
+ // raw stat would price a lockfile the hunters never see.
404
+ export function effectiveDiffStat(
405
+ files: NumstatFile[],
406
+ rules: readonly IgnoreRule[],
407
+ ): NumstatDiffStat {
408
+ const matcher = compileIgnoreRules(rules);
409
+ let count = 0;
410
+ let insertions = 0;
411
+ let deletions = 0;
412
+ for (const file of files) {
413
+ if (matcher.match(file.path) !== undefined) continue;
414
+ count++;
415
+ insertions += file.insertions;
416
+ deletions += file.deletions;
417
+ }
418
+ return { files: count, insertions, deletions };
419
+ }
420
+
421
+ // The message names the COST reason and the escape hatch, in that order: an
422
+ // operator who hits this must be able to tell in one line that nothing is
423
+ // wrong with their PR and exactly which two levers move the gate.
424
+ //
425
+ // It quotes the MEASUREMENT rather than predicting THIS diff's bill. The
426
+ // limit is configurable, so "this costs $7-18" would be plainly false at a
427
+ // tightened threshold — and a gate that overstates its own evidence is the
428
+ // first step toward the quality claim we do not have.
429
+ function gateMessage(
430
+ headline: string,
431
+ counts: { excludedFiles: number; excludedLines: number },
432
+ limitFlag: string,
433
+ ): string {
434
+ const exclusion =
435
+ counts.excludedFiles > 0
436
+ ? ` (${counts.excludedLines} line${plural(counts.excludedLines)} in ` +
437
+ `${counts.excludedFiles} excluded file${plural(counts.excludedFiles)} ` +
438
+ "were not counted)"
439
+ : "";
440
+ return (
441
+ `${headline}${exclusion}. Cost scales with diff size and gets less ` +
442
+ "predictable as it does (our 45-file bench tree billed $6.58-17.92, a " +
443
+ "~2.7x spread), so Crysk skips past the limit rather than guess at " +
444
+ `the bill. Raise ${limitFlag}, or pass --force to review it anyway.`
445
+ );
446
+ }
447
+
448
+ function plural(n: number): string {
449
+ return n === 1 ? "" : "s";
450
+ }
451
+
452
+ // The same gate against an AGGREGATE (files + insertions + deletions) with
453
+ // no per-file paths — so no exclusion can apply and the answer is an upper
454
+ // bound on the effective size. Used exactly where the per-file data costs a
455
+ // round-trip we have chosen not to pay: the PR dry run (which promises to
456
+ // fetch nothing) and the watcher's free first tier. It can only ever be
457
+ // wrong in the CONSERVATIVE direction — it may say "too large" for a diff
458
+ // whose lockfiles would have rescued it — so every caller must either label
459
+ // it an estimate or escalate to real per-file data before acting.
460
+ //
461
+ // WHY THE GATE IS TWO DIFFERENT INSTRUMENTS, and it is not an oversight:
462
+ // where git is reachable (local mode, PR mode after the fetch) the count
463
+ // comes from `git diff -w --ignore-blank-lines --numstat`, so a formatter
464
+ // sweep counts zero. GitHub's counters — `additions`/`deletions`/
465
+ // `changedFiles` here, and `gh pr view --json files` in the watcher's second
466
+ // tier — carry NO whitespace information at all, and no amount of arithmetic
467
+ // can recover it. Those paths are whitespace-NAIVE and must say so wherever
468
+ // they print, because a reformat can push them over a limit that the real
469
+ // git-side gate would never have fired. Both errors point the same way
470
+ // (overcount, never undercount), which is what makes the asymmetry safe.
471
+ export function evaluateSizeGateAggregate(
472
+ stat: { files: number; insertions: number; deletions: number },
473
+ config: SizeGateConfig,
474
+ ): SizeGateVerdict {
475
+ const counts = {
476
+ effectiveLines: stat.insertions + stat.deletions,
477
+ effectiveFiles: stat.files,
478
+ excludedFiles: 0,
479
+ excludedLines: 0,
480
+ };
481
+ if (
482
+ config.maxChangedLines > 0 &&
483
+ counts.effectiveLines > config.maxChangedLines
484
+ ) {
485
+ return {
486
+ ok: false,
487
+ reason: "lines",
488
+ ...counts,
489
+ limit: config.maxChangedLines,
490
+ message: gateMessage(
491
+ `${counts.effectiveLines} changed line${plural(counts.effectiveLines)} ` +
492
+ `exceeds the ${config.maxChangedLines}-line limit`,
493
+ counts,
494
+ "--max-changed-lines",
495
+ ),
496
+ };
497
+ }
498
+ if (
499
+ config.maxChangedFiles > 0 &&
500
+ counts.effectiveFiles > config.maxChangedFiles
501
+ ) {
502
+ return {
503
+ ok: false,
504
+ reason: "files",
505
+ ...counts,
506
+ limit: config.maxChangedFiles,
507
+ message: gateMessage(
508
+ `${counts.effectiveFiles} changed file${plural(counts.effectiveFiles)} ` +
509
+ `exceeds the ${config.maxChangedFiles}-file limit`,
510
+ counts,
511
+ "--max-changed-files",
512
+ ),
513
+ };
514
+ }
515
+ return { ok: true, ...counts };
516
+ }
517
+
518
+ // The CLI's own knobs on top of the defaults. Undefined means "not asked
519
+ // for", never 0 — 0 is a real value here (it DISABLES the limit), so the
520
+ // two cannot be collapsed.
521
+ //
522
+ // `userRules` is ADDITIVE and optional on purpose: no caller passes it yet
523
+ // (that lands with the local/base-ref `.prheroignore` reads), and omitting
524
+ // it must reproduce today's exact behavior byte-for-byte — that is what
525
+ // keeps `sizeGateConfig({})` equal to `DEFAULT_SIZE_GATE` even after this
526
+ // parameter exists. Builtins are always FIRST, user rules LAST, matching
527
+ // the dialect's own evaluation order (see compileIgnoreRules).
528
+ export function sizeGateConfig(
529
+ overrides: {
530
+ maxChangedLines?: number;
531
+ maxChangedFiles?: number;
532
+ },
533
+ config?: {
534
+ max_changed_lines?: number;
535
+ max_changed_files?: number;
536
+ },
537
+ userRules?: readonly IgnoreRule[],
538
+ ): SizeGateConfig {
539
+ return {
540
+ maxChangedLines:
541
+ overrides.maxChangedLines ??
542
+ config?.max_changed_lines ??
543
+ DEFAULT_SIZE_GATE.maxChangedLines,
544
+ maxChangedFiles:
545
+ overrides.maxChangedFiles ??
546
+ config?.max_changed_files ??
547
+ DEFAULT_SIZE_GATE.maxChangedFiles,
548
+ excludeRules:
549
+ userRules !== undefined
550
+ ? [...BUILTIN_IGNORE_RULES, ...userRules]
551
+ : DEFAULT_SIZE_GATE.excludeRules,
552
+ };
553
+ }
554
+
555
+ // The wiring wrapper both review shells actually call (#177/O-8): the two
556
+ // unexported I/O shells (review(), reviewPr()) each resolve an
557
+ // IgnoreFileReadResult from a DIFFERENT read (working tree / operator root /
558
+ // base ref) and then must thread its `.rules` — never the read result
559
+ // itself, never a dropped default `[]` — into sizeGateConfig's third
560
+ // parameter. Before this wrapper existed that was a plain call to
561
+ // sizeGateConfig with `.rules` picked out ad hoc at each of the three call
562
+ // sites (local review, PR dry run, PR real run), which is exactly the shape
563
+ // that can drift silently: `userRules` is OPTIONAL on sizeGateConfig itself
564
+ // (see its own WHY), so a call that quietly drops the third argument still
565
+ // compiles and produces a config with only the built-in exclusions — a
566
+ // user's `.prheroignore` rule stops applying and nothing fails loud.
567
+ // `ignore` is a REQUIRED parameter here (its VALUE may still be `undefined`,
568
+ // e.g. reviewPr()'s CI dry run has no working-tree read to offer) precisely
569
+ // so a caller cannot drop it by omission the way it could drop
570
+ // sizeGateConfig's own optional third argument.
571
+ export function sizeGateConfigFor(
572
+ overrides: {
573
+ maxChangedLines?: number;
574
+ maxChangedFiles?: number;
575
+ },
576
+ config:
577
+ | { max_changed_lines?: number; max_changed_files?: number }
578
+ | undefined,
579
+ ignore: IgnoreFileReadResult | undefined,
580
+ ): SizeGateConfig {
581
+ return sizeGateConfig(overrides, config, ignore?.rules);
582
+ }
583
+
584
+ // A one-line projection for the plan/dry-run output. Kept here so the local
585
+ // and PR shells (and the watch dry run) cannot drift in how they phrase it.
586
+ export function sizeGateLine(verdict: SizeGateVerdict): string {
587
+ const excluded =
588
+ verdict.excludedFiles > 0
589
+ ? `, ${verdict.excludedFiles} file(s)/${verdict.excludedLines} line(s) excluded`
590
+ : "";
591
+ return verdict.ok
592
+ ? `size gate: pass — ${verdict.effectiveLines} effective line(s) in ` +
593
+ `${verdict.effectiveFiles} file(s)${excluded}`
594
+ : `size gate: SKIP — ${verdict.message}`;
595
+ }