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,251 @@
1
+ import anthropicCatalog from "../../config/models/anthropic.json";
2
+ import type { RunnerBackend } from "../execution/contracts";
3
+
4
+ // #175, 2026-09-02. This catalogue holds ALIAS NAMES and nothing else.
5
+ //
6
+ // WHY it used to hold more, and why that was the last version pin in the
7
+ // system: every alias carried `modelFamily`/`modelSnapshot` (`sonnet` ->
8
+ // `claude-sonnet-5`). That pin never decided what RAN — `spawnModelForClaudeCli`
9
+ // sends the bare alias on a `direct` gateway and the Claude CLI resolves it
10
+ // itself (verified live 2026-09-02: `--model sonnet` ran `claude-sonnet-5`).
11
+ // It decided only what we ASSERTED had run, in `ResolvedModelRoute`, the route
12
+ // fingerprint and `pipeline.json`. So the day Anthropic repointed an alias,
13
+ // the CLI would run the new model and our provenance artifact would state the
14
+ // old snapshot — a false statement about what ran, in the artifact whose only
15
+ // job is to say what ran, arrived at silently. And every model release became
16
+ // a release of ours.
17
+ //
18
+ // WHAT SURVIVES, and why it is legitimately ours: the alias LIST. That
19
+ // `sonnet|opus|haiku` are accepted as bare model names is a pr-hero UX
20
+ // convention. What they resolve to is the provider's business, and a wrong
21
+ // name now fails AT THE PROVIDER — an error from the party that knows is more
22
+ // honest than a mapping of ours that pretends to.
23
+ //
24
+ // The operator can still pin: a routing config's `modelSnapshot` is passed
25
+ // through verbatim (model/routing.ts) and reaches `--model` on a `configured`
26
+ // gateway. Pinning is a decision an operator makes per run, not a constant we
27
+ // ship.
28
+ export interface ProviderModelCatalog {
29
+ readonly provider: string;
30
+ readonly defaultBackend?: RunnerBackend;
31
+ readonly aliases: readonly string[];
32
+ }
33
+
34
+ export interface ResolvedCatalogAlias {
35
+ readonly provider: string;
36
+ readonly alias: string;
37
+ readonly canonical: string;
38
+ readonly defaultBackend?: RunnerBackend;
39
+ }
40
+
41
+ function assertNonEmptyString(
42
+ value: unknown,
43
+ label: string,
44
+ ): asserts value is string {
45
+ if (typeof value !== "string" || value.trim().length === 0) {
46
+ throw new Error(`model catalog: ${label} must be a non-empty string`);
47
+ }
48
+ }
49
+
50
+ function normalizeProviderCatalog(raw: unknown): ProviderModelCatalog {
51
+ if (!raw || typeof raw !== "object") {
52
+ throw new Error("model catalog: provider entry must be an object");
53
+ }
54
+ const record = raw as Record<string, unknown>;
55
+ assertNonEmptyString(record.provider, "provider");
56
+ if (
57
+ record.defaultBackend !== undefined &&
58
+ typeof record.defaultBackend !== "string"
59
+ ) {
60
+ throw new Error("model catalog: defaultBackend must be a string");
61
+ }
62
+ // An ARRAY now, where it used to be an object of alias -> model. The shape
63
+ // change is the point: there is no longer a second field per alias for a
64
+ // version to hide in, so no future edit can quietly re-pin one.
65
+ if (!Array.isArray(record.aliases)) {
66
+ throw new Error(
67
+ `model catalog: ${record.provider} aliases must be an array`,
68
+ );
69
+ }
70
+
71
+ const aliases: string[] = [];
72
+ for (const alias of record.aliases) {
73
+ assertNonEmptyString(alias, `${record.provider}.alias`);
74
+ aliases.push(alias);
75
+ }
76
+
77
+ if (aliases.length === 0) {
78
+ throw new Error(`model catalog: ${record.provider} must define aliases`);
79
+ }
80
+
81
+ return {
82
+ provider: record.provider as string,
83
+ ...(record.defaultBackend === undefined
84
+ ? {}
85
+ : { defaultBackend: record.defaultBackend as RunnerBackend }),
86
+ aliases: Object.freeze(aliases),
87
+ };
88
+ }
89
+
90
+ // The logical identity an alias parses to. `provider/alias`, not
91
+ // `provider/version` — the canonical form now names what the operator asked
92
+ // for, which is a fact, instead of a version nobody verified.
93
+ function canonicalIdentity(provider: string, alias: string): string {
94
+ return `${provider}/${alias}`;
95
+ }
96
+
97
+ const PROVIDER_CATALOGS = {
98
+ anthropic: normalizeProviderCatalog(anthropicCatalog),
99
+ } as const satisfies Record<string, ProviderModelCatalog>;
100
+
101
+ export const MODEL_CATALOG = Object.freeze({
102
+ providers: PROVIDER_CATALOGS,
103
+ });
104
+
105
+ const aliasIndex = new Map<string, ResolvedCatalogAlias>();
106
+ const canonicalToAlias = new Map<string, string>();
107
+
108
+ for (const catalog of Object.values(PROVIDER_CATALOGS)) {
109
+ for (const alias of catalog.aliases) {
110
+ if (aliasIndex.has(alias)) {
111
+ throw new Error(`model catalog: duplicate alias "${alias}"`);
112
+ }
113
+ const canonical = canonicalIdentity(catalog.provider, alias);
114
+ // The BIJECTION `reverseAliasForCanonical` depends on, asserted where the
115
+ // map is built rather than inferred from `canonicalIdentity`'s current
116
+ // shape — which is exactly the shape #175 changed.
117
+ //
118
+ // Honest about its reach: while canonical is `provider/alias`, the
119
+ // duplicate-alias guard above already makes a collision unreachable, so
120
+ // this throw cannot fire today. It used to be the load-bearing one —
121
+ // canonical was `provider/modelFamily`, and two aliases pinned to one
122
+ // family (a `sonnet` and a `sonnet-latest` both on `claude-sonnet-5`)
123
+ // would have silently made `reverseAliasForCanonical` return whichever
124
+ // won the loop, so `spawnModelForClaudeCli` would send the other alias's
125
+ // name. It stays because the invariant, not the current key formula, is
126
+ // what the reverse lookup is allowed to rely on.
127
+ if (canonicalToAlias.has(canonical)) {
128
+ throw new Error(`model catalog: duplicate canonical "${canonical}"`);
129
+ }
130
+ aliasIndex.set(alias, {
131
+ provider: catalog.provider,
132
+ alias,
133
+ canonical,
134
+ ...(catalog.defaultBackend === undefined
135
+ ? {}
136
+ : { defaultBackend: catalog.defaultBackend }),
137
+ });
138
+ canonicalToAlias.set(canonical, alias);
139
+ }
140
+ }
141
+
142
+ export type ModelAlias = "sonnet" | "opus" | "haiku";
143
+
144
+ // Unchanged by #175, and the reason it is unchanged is the whole point of the
145
+ // slice: the alias LIST is ours, so a config that drops one still has to fail
146
+ // loud at import. `ModelAlias` is a compile-time union and the JSON is a
147
+ // runtime file; without this loop a deleted alias would typecheck and then
148
+ // throw `unknown alias` deep inside a run.
149
+ const REQUIRED_ALIASES: readonly ModelAlias[] = ["sonnet", "opus", "haiku"];
150
+ for (const alias of REQUIRED_ALIASES) {
151
+ if (!aliasIndex.has(alias)) {
152
+ throw new Error(`model catalog: missing required alias "${alias}"`);
153
+ }
154
+ }
155
+
156
+ export function isModelAlias(value: string): value is ModelAlias {
157
+ return aliasIndex.has(value);
158
+ }
159
+
160
+ export function allModelAliases(): readonly ModelAlias[] {
161
+ return Object.freeze([...aliasIndex.keys()] as ModelAlias[]);
162
+ }
163
+
164
+ export function lookupAlias(alias: ModelAlias): ResolvedCatalogAlias {
165
+ const entry = aliasIndex.get(alias);
166
+ if (entry === undefined) {
167
+ throw new Error(`model catalog: unknown alias "${alias}"`);
168
+ }
169
+ return entry;
170
+ }
171
+
172
+ export function aliasCanonical(alias: ModelAlias): string {
173
+ return lookupAlias(alias).canonical;
174
+ }
175
+
176
+ // `spawnModelForClaudeCli` depends on this: on a `direct` gateway it turns a
177
+ // canonical identity back into the bare alias so the CLI — not us — resolves
178
+ // the version. Sound because of the bijection asserted above.
179
+ export function reverseAliasForCanonical(
180
+ canonical: string,
181
+ ): ModelAlias | undefined {
182
+ const alias = canonicalToAlias.get(canonical);
183
+ return alias === undefined ? undefined : (alias as ModelAlias);
184
+ }
185
+
186
+ // The Claude Code CLI's `--effort` vocabulary, closed. Lives beside
187
+ // `ModelAlias` because the pair is what a step is asked to run as: a model and
188
+ // how hard it works. An unknown level must fail at the frontmatter seam, not
189
+ // reach the CLI, which would reject it (or ignore it) after the run is paid for.
190
+ export const EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"] as const;
191
+ export type Effort = (typeof EFFORT_LEVELS)[number];
192
+
193
+ export function isEffort(value: string): value is Effort {
194
+ return (EFFORT_LEVELS as readonly string[]).includes(value);
195
+ }
196
+
197
+ // Which kind of step is being built. Wider than `AgentSpec.role` on purpose:
198
+ // the summarizer, scout and rereview verifier are steps too, and each needs a
199
+ // resolved level, not an implicit one. `other` is for ad hoc steps (judges,
200
+ // probes) built outside the pipeline.
201
+ export type StepRole =
202
+ | "hunter"
203
+ | "refuter"
204
+ | "summarizer"
205
+ | "scout"
206
+ | "verifier"
207
+ | "other";
208
+
209
+ // THE per-role effort table, and the only place a default is chosen. It is the
210
+ // fallback when a prompt's frontmatter omits `effort:`, so a custom or lab
211
+ // prompt set still runs at an EXPLICIT level.
212
+ //
213
+ // WHY the engine owns this at all (#299, 2026-10-02): pr-hero never passed
214
+ // `--effort`, so every step ran at the CLI's implicit default, which is `high`
215
+ // except on Sonnet 5.5 and Opus 5.5, where it is `medium`
216
+ // (https://code.claude.com/docs/en/model-config). When the `sonnet` alias moved
217
+ // to 5.5 the hunters silently dropped a level and stopped exploring.
218
+ //
219
+ // Measured on musive pr-1858 (Sonnet 5.5, 4 hunters x 2 replicates):
220
+ // medium 0/8 runs with findings (0.5 min), high 6/8 (1.5 min),
221
+ // xhigh 8/8 and all 4 known bugs (4.5 min), max 7/8 (19 min).
222
+ // - hunter xhigh: the cheapest level that found everything.
223
+ // - refuter high: refuter-probe 16/16 at medium was NOT sufficient. On the
224
+ // real pr-1858 xhigh findings the Opus refuter at medium returned
225
+ // `refuted` on the pre-labeled known `updateProject` BLOCKER in 3 of 4
226
+ // verdicts, which deletes it; at high it was `downgraded-latent` (kept, as
227
+ // advisory) in 3 of 4 and refuted in 1 of 4. The other 5 findings got the
228
+ // same verdicts at both levels, and the original Sonnet-5-at-high refuter
229
+ // corroborated that finding. The cost is a refuter leg of ~140s instead of
230
+ // ~90s. The probe plants claims with a known verdict; it cannot see a
231
+ // real finding being talked out of existence, which is what this gate did.
232
+ // - everything else high: unmeasured, so it keeps what every model ran at
233
+ // before the 5.5 family, i.e. the behavior those roles were validated under.
234
+ const ROLE_EFFORT: Readonly<Record<StepRole, Effort>> = Object.freeze({
235
+ hunter: "xhigh",
236
+ refuter: "high",
237
+ summarizer: "high",
238
+ scout: "high",
239
+ verifier: "high",
240
+ other: "high",
241
+ });
242
+
243
+ export function defaultEffortForRole(role: StepRole): Effort {
244
+ return ROLE_EFFORT[role];
245
+ }
246
+
247
+ export function providerCatalog(
248
+ provider: keyof typeof PROVIDER_CATALOGS,
249
+ ): ProviderModelCatalog {
250
+ return PROVIDER_CATALOGS[provider];
251
+ }
@@ -0,0 +1,390 @@
1
+ // Lifecycle of verified execution snapshots (#303).
2
+ //
3
+ // `verifyExecutableAuthority` copies every verified binary into a private
4
+ // `<base>/<digest16>-<pid>-<uuid>/` directory so the bytes that execute are
5
+ // the bytes that were hashed (the TOCTOU defense in provider-capabilities.ts).
6
+ // Nothing ever removed those copies: one per step, one per route at binding
7
+ // resolution, one per test — a real claude binary is >100 MB, and a benchmark
8
+ // machine reached 153 GB across 23,153 directories with its disk at 98%.
9
+ //
10
+ // Three layers, each covering what the previous one cannot:
11
+ // 1. `releaseExecutionSnapshot` — the owner releases its snapshot as soon as
12
+ // the last attempt that spawns from it settles (the harness `finally`).
13
+ // 2. the `process.on("exit")` hook — `process.exit()` (the SIGINT/SIGTERM
14
+ // handlers in cli.ts and mcp.ts end in it) skips every pending `finally`,
15
+ // but it does run exit listeners, synchronously.
16
+ // 3. `sweepStaleExecutionSnapshots` — SIGKILL, a crash, or default-signal
17
+ // death run nothing at all, so the next snapshot-creating process (and
18
+ // `pr-hero gc`) removes directories whose owner pid is dead or that are
19
+ // older than any step can live.
20
+ //
21
+ // Deletion is gated on a process-local registry of the directories THIS
22
+ // process created, never on `VerifiedExecutable.kind` or on
23
+ // `verifiedExecutionPath !== absolutePath`: test fakes and
24
+ // production-runtime.ts's `toVerifiedExecutable` leave `kind` unset, and a
25
+ // path-shape heuristic is one refactor away from unlinking an operator's real
26
+ // binary. A path this process never registered is never deleted by layer 1 or
27
+ // 2, whatever it looks like.
28
+
29
+ import { rmSync, type Stats } from "node:fs";
30
+ import { lstat, readdir, rm } from "node:fs/promises";
31
+ import { tmpdir } from "node:os";
32
+ import path from "node:path";
33
+
34
+ export const EXEC_SNAPSHOT_DIRNAME = "prhero-exec-snapshots";
35
+
36
+ // WHY 6 h: a step attempt defaults to 30 min with 2 attempts and a pipeline
37
+ // caps at 75 min; the in-flight TTL precedent (IN_FLIGHT_TTL_MS) is 90 min.
38
+ // Six hours is several times the longest legitimate lifetime, so an entry
39
+ // this old is garbage even when its pid has been recycled by a live process.
40
+ export const STALE_SNAPSHOT_MAX_AGE_MS = 6 * 60 * 60 * 1000;
41
+
42
+ // WHY once per hour per base: the watcher is a long-lived process that
43
+ // creates a snapshot per step; sweeping before every one of them would re-scan
44
+ // the base for nothing. Stale entries only appear when a process dies, so an
45
+ // hourly pass bounds the directory without measurable cost.
46
+ export const SNAPSHOT_SWEEP_INTERVAL_MS = 60 * 60 * 1000;
47
+
48
+ // WHY a budget at all: the opportunistic pass runs inside the first step's
49
+ // verification, before that step's watchdog starts. A machine carrying the
50
+ // pre-#303 backlog (23k dirs, 147 GB) would otherwise block that step until
51
+ // the whole backlog was deleted. Two seconds per pass bounds what one step
52
+ // pays; an exhausted pass hands the rest to the next verification.
53
+ export const OPPORTUNISTIC_SWEEP_BUDGET_MS = 2000;
54
+
55
+ export function defaultExecSnapshotBase(): string {
56
+ return path.join(tmpdir(), EXEC_SNAPSHOT_DIRNAME);
57
+ }
58
+
59
+ export function executionSnapshotDirName(
60
+ digest: string,
61
+ pid: number,
62
+ uuid: string,
63
+ ): string {
64
+ return `${digest.slice(0, 16)}-${pid}-${uuid}`;
65
+ }
66
+
67
+ const registeredSnapshotDirs = new Set<string>();
68
+ let exitHookInstalled = false;
69
+
70
+ // Registers a snapshot directory this process just created. Call it right
71
+ // after the directory exists and BEFORE the binary is written, so an exit in
72
+ // between still removes the partial copy.
73
+ export function registerExecutionSnapshot(snapshotDir: string): void {
74
+ registeredSnapshotDirs.add(path.resolve(snapshotDir));
75
+ if (!exitHookInstalled) {
76
+ exitHookInstalled = true;
77
+ // Installed lazily so a process that never snapshots adds no listener.
78
+ // Covers `process.exit()` from every entrypoint, including the signal
79
+ // handlers in cli.ts and mcp.ts, which skip pending `finally` blocks.
80
+ // Does NOT cover SIGKILL or death by a signal with no handler: no
81
+ // JavaScript runs then, and `sweepStaleExecutionSnapshots` is the
82
+ // backstop for exactly that.
83
+ process.on("exit", releaseAllExecutionSnapshots);
84
+ }
85
+ }
86
+
87
+ function registeredDirFor(target: string): string | undefined {
88
+ const resolved = path.resolve(target);
89
+ if (registeredSnapshotDirs.has(resolved)) return resolved;
90
+ const parent = path.dirname(resolved);
91
+ if (registeredSnapshotDirs.has(parent)) return parent;
92
+ return undefined;
93
+ }
94
+
95
+ // Best-effort removal of one snapshot dir. Synchronous because it also runs
96
+ // from an exit listener, where nothing asynchronous completes. Never throws:
97
+ // a release failure must not replace a step's real outcome. `force` makes a
98
+ // directory already removed (by a sweep, or by hand) a success. Any other
99
+ // failure — EBUSY on Windows while a killed child still maps the binary —
100
+ // leaves the dir registered so the exit hook tries again.
101
+ function removeRegisteredDir(dir: string): void {
102
+ try {
103
+ rmSync(dir, { recursive: true, force: true });
104
+ registeredSnapshotDirs.delete(dir);
105
+ } catch {
106
+ // Kept registered; the exit hook retries.
107
+ }
108
+ }
109
+
110
+ // Releases the snapshot that `verifiedExecutionPath` (or its directory)
111
+ // points at. A no-op for anything this process did not register: a canonical
112
+ // binary, a `#!` launcher executing in place, a test fake's path.
113
+ export function releaseExecutionSnapshot(target: string): void {
114
+ const dir = registeredDirFor(target);
115
+ if (dir === undefined) return;
116
+ removeRegisteredDir(dir);
117
+ }
118
+
119
+ export function releaseAllExecutionSnapshots(): void {
120
+ for (const dir of [...registeredSnapshotDirs]) {
121
+ removeRegisteredDir(dir);
122
+ }
123
+ }
124
+
125
+ // `<digest16>-<pid>-<uuid>` since #303; `<digest16>-<uuid>` before it. The
126
+ // optional pid group cannot swallow a legacy uuid's first segment: what would
127
+ // remain is not a whole uuid, so the regex backtracks to the legacy form.
128
+ const UUID_PATTERN =
129
+ "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
130
+ const SNAPSHOT_NAME = new RegExp(
131
+ `^[0-9a-f]{16}-(?:([0-9]+)-)?${UUID_PATTERN}$`,
132
+ );
133
+
134
+ export interface SnapshotEntryFacts {
135
+ readonly name: string;
136
+ // From lstat: a symlink is reported as "symlink" and never followed.
137
+ readonly kind: "directory" | "symlink" | "other";
138
+ readonly ownerUid: number;
139
+ readonly mtimeMs: number;
140
+ readonly registeredByThisProcess: boolean;
141
+ }
142
+
143
+ export interface SnapshotSweepPolicy {
144
+ readonly nowMs: number;
145
+ readonly maxAgeMs: number;
146
+ // undefined when the platform has no `process.getuid` (Windows).
147
+ readonly currentUid: number | undefined;
148
+ // undefined when no pid-liveness probe is available.
149
+ readonly pidAlive: ((pid: number) => boolean) | undefined;
150
+ }
151
+
152
+ export type SnapshotSweepDecision =
153
+ | { readonly action: "remove"; readonly reason: "owner-dead" | "stale" }
154
+ | {
155
+ readonly action: "keep";
156
+ readonly reason:
157
+ | "foreign-name"
158
+ | "not-a-directory"
159
+ | "foreign-owner"
160
+ | "in-use"
161
+ | "fresh";
162
+ };
163
+
164
+ export function classifySnapshotEntry(
165
+ entry: SnapshotEntryFacts,
166
+ policy: SnapshotSweepPolicy,
167
+ ): SnapshotSweepDecision {
168
+ const match = SNAPSHOT_NAME.exec(entry.name);
169
+ if (match === null) return { action: "keep", reason: "foreign-name" };
170
+ if (entry.kind !== "directory") {
171
+ return { action: "keep", reason: "not-a-directory" };
172
+ }
173
+ // On Linux the base sits in a shared /tmp: another user's entry is never
174
+ // ours to delete, whatever its age.
175
+ if (policy.currentUid !== undefined && entry.ownerUid !== policy.currentUid) {
176
+ return { action: "keep", reason: "foreign-owner" };
177
+ }
178
+ if (entry.registeredByThisProcess) {
179
+ return { action: "keep", reason: "in-use" };
180
+ }
181
+ // Explicit degradation to age-only: without a uid there is no ownership
182
+ // proof, and without a probe there is no liveness answer, so an entry is
183
+ // only removed once it is older than any step can live. Platforms without
184
+ // `getuid` (Windows) keep the temp dir per user, so age-only stays safe.
185
+ // Legacy names carry no pid and are age-only on every platform.
186
+ const pid = match[1] === undefined ? undefined : Number(match[1]);
187
+ if (
188
+ pid !== undefined &&
189
+ Number.isSafeInteger(pid) &&
190
+ policy.currentUid !== undefined &&
191
+ policy.pidAlive !== undefined &&
192
+ !policy.pidAlive(pid)
193
+ ) {
194
+ return { action: "remove", reason: "owner-dead" };
195
+ }
196
+ // Accepted trade-offs, both failing closed (the step that loses its binary
197
+ // fails with ENOENT on its next spawn; nothing runs unverified bytes):
198
+ // - The age cap applies to a LIVE pid too, deliberately, to bound pid
199
+ // recycling. A host asleep for more than 6 h mid-step can lose the
200
+ // snapshot; that step's watchdog would time it out on wake anyway.
201
+ // - ESRCH is trusted as death. Same-uid containers sharing one /tmp across
202
+ // separate pid namespaces would see each other's live pids as dead; that
203
+ // deployment is out of scope.
204
+ if (policy.nowMs - entry.mtimeMs > policy.maxAgeMs) {
205
+ return { action: "remove", reason: "stale" };
206
+ }
207
+ return { action: "keep", reason: "fresh" };
208
+ }
209
+
210
+ // ESRCH is the only proof of death. EPERM means the pid exists under another
211
+ // user; any other error is not a "dead" answer either, so it keeps the entry.
212
+ function pidAliveByKill(pid: number): boolean {
213
+ try {
214
+ process.kill(pid, 0);
215
+ return true;
216
+ } catch (error) {
217
+ return (error as NodeJS.ErrnoException).code !== "ESRCH";
218
+ }
219
+ }
220
+
221
+ function currentProcessUid(): number | undefined {
222
+ return typeof process.getuid === "function" ? process.getuid() : undefined;
223
+ }
224
+
225
+ export interface SnapshotSweepOptions {
226
+ readonly snapshotBase?: string;
227
+ readonly nowMs?: number;
228
+ readonly maxAgeMs?: number;
229
+ readonly pidAlive?: (pid: number) => boolean;
230
+ readonly currentUid?: number;
231
+ // Classify and count only; remove nothing.
232
+ readonly dryRun?: boolean;
233
+ // Wall-clock budget for the whole pass, checked before each entry; once
234
+ // spent, no new entry is taken. Unset means unbounded (`pr-hero gc`).
235
+ readonly budgetMs?: number;
236
+ // Clock for the budget only (never for ages); injectable for tests.
237
+ readonly clock?: () => number;
238
+ // Size each removed dir (default true). Sizing is a readdir plus an lstat
239
+ // per file; the opportunistic pass skips it, only the gc report needs it.
240
+ readonly countBytes?: boolean;
241
+ }
242
+
243
+ export interface SnapshotSweepReport {
244
+ // In a dry run: what would be removed, and its size.
245
+ readonly removed: number;
246
+ // 0 when `countBytes` is false.
247
+ readonly removedBytes: number;
248
+ readonly kept: number;
249
+ readonly failed: number;
250
+ // Entries left untouched because the budget ran out.
251
+ readonly unprocessed: number;
252
+ }
253
+
254
+ // Best-effort size of a snapshot dir: its regular files, one level, via lstat.
255
+ async function snapshotDirBytes(dir: string): Promise<number> {
256
+ try {
257
+ let total = 0;
258
+ for (const name of await readdir(dir)) {
259
+ const stats = await lstat(path.join(dir, name));
260
+ if (stats.isFile()) total += stats.size;
261
+ }
262
+ return total;
263
+ } catch {
264
+ return 0;
265
+ }
266
+ }
267
+
268
+ export async function sweepStaleExecutionSnapshots(
269
+ options: SnapshotSweepOptions = {},
270
+ ): Promise<SnapshotSweepReport> {
271
+ const base = options.snapshotBase ?? defaultExecSnapshotBase();
272
+ const clock = options.clock ?? (() => performance.now());
273
+ const startedAt = clock();
274
+ const countBytes = options.countBytes ?? true;
275
+ const policy: SnapshotSweepPolicy = {
276
+ nowMs: options.nowMs ?? Date.now(),
277
+ maxAgeMs: options.maxAgeMs ?? STALE_SNAPSHOT_MAX_AGE_MS,
278
+ currentUid: options.currentUid ?? currentProcessUid(),
279
+ pidAlive: options.pidAlive ?? pidAliveByKill,
280
+ };
281
+ let names: string[];
282
+ try {
283
+ names = await readdir(base);
284
+ } catch {
285
+ // No base yet (first run) or unreadable: nothing to sweep.
286
+ return { removed: 0, removedBytes: 0, kept: 0, failed: 0, unprocessed: 0 };
287
+ }
288
+ let removed = 0;
289
+ let removedBytes = 0;
290
+ let kept = 0;
291
+ let failed = 0;
292
+ for (const [index, name] of names.entries()) {
293
+ if (
294
+ options.budgetMs !== undefined &&
295
+ clock() - startedAt >= options.budgetMs
296
+ ) {
297
+ return {
298
+ removed,
299
+ removedBytes,
300
+ kept,
301
+ failed,
302
+ unprocessed: names.length - index,
303
+ };
304
+ }
305
+ const entryPath = path.join(base, name);
306
+ let stats: Stats;
307
+ try {
308
+ stats = await lstat(entryPath);
309
+ } catch {
310
+ // Released by its owner between readdir and lstat: already gone.
311
+ continue;
312
+ }
313
+ const decision = classifySnapshotEntry(
314
+ {
315
+ name,
316
+ kind: stats.isSymbolicLink()
317
+ ? "symlink"
318
+ : stats.isDirectory()
319
+ ? "directory"
320
+ : "other",
321
+ ownerUid: stats.uid,
322
+ mtimeMs: stats.mtimeMs,
323
+ registeredByThisProcess: registeredSnapshotDirs.has(
324
+ path.resolve(entryPath),
325
+ ),
326
+ },
327
+ policy,
328
+ );
329
+ if (decision.action === "keep") {
330
+ kept++;
331
+ continue;
332
+ }
333
+ const bytes = countBytes ? await snapshotDirBytes(entryPath) : 0;
334
+ if (options.dryRun) {
335
+ removed++;
336
+ removedBytes += bytes;
337
+ continue;
338
+ }
339
+ try {
340
+ await rm(entryPath, { recursive: true, force: true });
341
+ removed++;
342
+ removedBytes += bytes;
343
+ } catch {
344
+ failed++;
345
+ }
346
+ }
347
+ return { removed, removedBytes, kept, failed, unprocessed: 0 };
348
+ }
349
+
350
+ const lastSweepAtMsByBase = new Map<string, number>();
351
+
352
+ // The opportunistic trigger `verifyExecutableAuthority` runs before creating a
353
+ // snapshot. Rate-limited per resolved base (production has exactly one, so
354
+ // this is "once per hour per process"); the claim is taken BEFORE the sweep
355
+ // so concurrent verifications in the same process do not all sweep.
356
+ // Time-bounded (OPPORTUNISTIC_SWEEP_BUDGET_MS) and byte-blind: it only has to
357
+ // make progress. A pass that runs out of budget gives the claim back, so the
358
+ // NEXT verification continues the backlog instead of waiting an hour; a pass
359
+ // that finishes keeps the claim. Returns the report, or undefined when the
360
+ // rate limit skipped the pass. Never throws: a sweep problem must not fail or
361
+ // delay-fail verification.
362
+ export async function sweepExecutionSnapshotsOpportunistically(
363
+ snapshotBase: string,
364
+ nowMs: number = Date.now(),
365
+ budget: {
366
+ readonly budgetMs?: number;
367
+ readonly clock?: () => number;
368
+ } = {},
369
+ ): Promise<SnapshotSweepReport | undefined> {
370
+ const key = path.resolve(snapshotBase);
371
+ const last = lastSweepAtMsByBase.get(key);
372
+ if (last !== undefined && nowMs - last < SNAPSHOT_SWEEP_INTERVAL_MS) {
373
+ return undefined;
374
+ }
375
+ lastSweepAtMsByBase.set(key, nowMs);
376
+ try {
377
+ const report = await sweepStaleExecutionSnapshots({
378
+ snapshotBase: key,
379
+ nowMs,
380
+ budgetMs: budget.budgetMs ?? OPPORTUNISTIC_SWEEP_BUDGET_MS,
381
+ clock: budget.clock,
382
+ countBytes: false,
383
+ });
384
+ if (report.unprocessed > 0) lastSweepAtMsByBase.delete(key);
385
+ return report;
386
+ } catch {
387
+ // Best-effort by contract.
388
+ return undefined;
389
+ }
390
+ }