crysk 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +610 -2
  3. package/bin/pr-hero.js +166 -0
  4. package/config/models/anthropic.json +5 -0
  5. package/dist/SKILL-7e3725zn.md +496 -0
  6. package/dist/SKILL-7q35wcaz.md +66 -0
  7. package/dist/SKILL-9at22381.md +74 -0
  8. package/dist/SKILL-ex2hxxh3.md +134 -0
  9. package/dist/adjudicator-dtg2axnh.md +86 -0
  10. package/dist/admission-config.example-a9vqmmad.json +9 -0
  11. package/dist/ci-admission-camfbx2b.md +122 -0
  12. package/dist/cli.js +42292 -0
  13. package/dist/consolidate-ac0mnfyj.md +24 -0
  14. package/dist/deep-review-lifecycle-m698ybjp.md +362 -0
  15. package/dist/deep-review-logic-a6b1gczf.md +156 -0
  16. package/dist/deep-review-parity-0ec904db.md +120 -0
  17. package/dist/deep-review-reliability-qyakbjb9.md +125 -0
  18. package/dist/deep-review-resilience-3tz8y26e.md +118 -0
  19. package/dist/index.js +20190 -0
  20. package/dist/opencode-ci-7b0be64p.md +141 -0
  21. package/dist/review-refuter-j4e9gezy.md +71 -0
  22. package/dist/scout-yvp153q7.md +140 -0
  23. package/dist/summarizer-zca44nxa.md +18 -0
  24. package/dist/workflow-w1g9szna.yml +151 -0
  25. package/package.json +82 -4
  26. package/prompts/consolidate.md +24 -0
  27. package/prompts/default/PROVENANCE.md +18 -0
  28. package/prompts/default/deep-review-lifecycle.md +362 -0
  29. package/prompts/default/deep-review-logic.md +156 -0
  30. package/prompts/default/deep-review-parity.md +120 -0
  31. package/prompts/default/deep-review-reliability.md +125 -0
  32. package/prompts/default/deep-review-resilience.md +118 -0
  33. package/prompts/default/review-refuter.md +71 -0
  34. package/prompts/scout.md +140 -0
  35. package/prompts/summarizer.md +18 -0
  36. package/skills/crysk/SKILL.md +74 -0
  37. package/skills/crysk-ci-setup/SKILL.md +134 -0
  38. package/skills/crysk-ci-setup/assets/admission-config.example.json +9 -0
  39. package/skills/crysk-ci-setup/assets/workflow.yml +151 -0
  40. package/skills/crysk-ci-setup/references/ci-admission.md +122 -0
  41. package/skills/crysk-ci-setup/references/opencode-ci.md +141 -0
  42. package/skills/crysk-loop/SKILL.md +496 -0
  43. package/skills/crysk-loop/adjudicator.md +86 -0
  44. package/skills/crysk-pr/SKILL.md +66 -0
  45. package/src/agent-env.ts +1084 -0
  46. package/src/asset-manifest.ts +83 -0
  47. package/src/assets.d.ts +6 -0
  48. package/src/assets.ts +183 -0
  49. package/src/brand-paths.ts +155 -0
  50. package/src/brand.ts +255 -0
  51. package/src/ci/admission-ledger.ts +350 -0
  52. package/src/ci/classify-error.ts +73 -0
  53. package/src/ci/cli-record.ts +271 -0
  54. package/src/ci/force-comment.ts +39 -0
  55. package/src/ci/gates.ts +923 -0
  56. package/src/ci/outcome.ts +2181 -0
  57. package/src/ci/override.ts +187 -0
  58. package/src/ci/publish.ts +1639 -0
  59. package/src/ci/reporter.ts +626 -0
  60. package/src/ci/review-admission.ts +901 -0
  61. package/src/ci/review-levels.ts +310 -0
  62. package/src/ci/review-policy.ts +18 -0
  63. package/src/ci/review-risk.ts +184 -0
  64. package/src/ci/setup.ts +844 -0
  65. package/src/ci/trigger.ts +1353 -0
  66. package/src/cli.ts +348 -0
  67. package/src/commands/activity.ts +67 -0
  68. package/src/commands/ci-setup-questions.ts +397 -0
  69. package/src/commands/ci-setup.ts +381 -0
  70. package/src/commands/config.ts +99 -0
  71. package/src/commands/doctor.ts +108 -0
  72. package/src/commands/init.ts +139 -0
  73. package/src/commands/mcp.ts +10 -0
  74. package/src/commands/menu.ts +129 -0
  75. package/src/commands/post.ts +302 -0
  76. package/src/commands/skills.ts +83 -0
  77. package/src/commands/status.ts +173 -0
  78. package/src/commands/triage.ts +342 -0
  79. package/src/commands/uninstall.ts +37 -0
  80. package/src/commands/upgrade.ts +214 -0
  81. package/src/commands/usage.ts +98 -0
  82. package/src/compare/compare.ts +28 -0
  83. package/src/compare/floor-test.ts +471 -0
  84. package/src/compare/martian-adapter.ts +80 -0
  85. package/src/config/config.ts +267 -0
  86. package/src/corpus/corpus.ts +1094 -0
  87. package/src/corpus/preflight.ts +1789 -0
  88. package/src/diversity/accounting.ts +90 -0
  89. package/src/diversity/adjudication.ts +145 -0
  90. package/src/diversity/admission.ts +60 -0
  91. package/src/diversity/benchmark.ts +195 -0
  92. package/src/diversity/clustering.ts +285 -0
  93. package/src/diversity/errors.ts +7 -0
  94. package/src/diversity/identity.ts +285 -0
  95. package/src/diversity/index.ts +11 -0
  96. package/src/diversity/pipeline-integration.ts +448 -0
  97. package/src/diversity/projection.ts +57 -0
  98. package/src/diversity/self-contained.ts +68 -0
  99. package/src/diversity/target-validation.ts +179 -0
  100. package/src/doctor-migration.ts +209 -0
  101. package/src/doctor.ts +723 -0
  102. package/src/errors.ts +83 -0
  103. package/src/execution/admission.ts +75 -0
  104. package/src/execution/atomic-write.ts +35 -0
  105. package/src/execution/attempt-evidence.ts +415 -0
  106. package/src/execution/bucket-id.ts +136 -0
  107. package/src/execution/concurrency-limiter.ts +175 -0
  108. package/src/execution/contracts.ts +443 -0
  109. package/src/execution/failure-classification.ts +42 -0
  110. package/src/execution/failure-policy.ts +240 -0
  111. package/src/execution/harness.ts +2548 -0
  112. package/src/execution/settlement.ts +348 -0
  113. package/src/execution/spawned-process.ts +66 -0
  114. package/src/execution/spend-limiter.ts +424 -0
  115. package/src/execution/step-artifacts.ts +55 -0
  116. package/src/execution/usage-normalized.ts +469 -0
  117. package/src/git/git.ts +396 -0
  118. package/src/git/identity.ts +64 -0
  119. package/src/git/refs.ts +140 -0
  120. package/src/home-preflight.ts +443 -0
  121. package/src/home.ts +243 -0
  122. package/src/ignore-file.ts +336 -0
  123. package/src/ignore-read.ts +118 -0
  124. package/src/index.ts +34 -0
  125. package/src/legacy-launchd.ts +29 -0
  126. package/src/mcp/mcp.ts +150 -0
  127. package/src/mcp/preflight.ts +407 -0
  128. package/src/menu-context.ts +192 -0
  129. package/src/model/catalog.ts +251 -0
  130. package/src/model/exec-snapshots.ts +390 -0
  131. package/src/model/free-discovery.ts +302 -0
  132. package/src/model/provider-capabilities.ts +814 -0
  133. package/src/model/routing.ts +600 -0
  134. package/src/pr/admission.ts +847 -0
  135. package/src/pr/ci-admission-gate.ts +665 -0
  136. package/src/pr/ci-publish.ts +76 -0
  137. package/src/pr/discovery.ts +432 -0
  138. package/src/pr/inline.ts +507 -0
  139. package/src/pr/plan.ts +366 -0
  140. package/src/pr/posting.ts +115 -0
  141. package/src/pr/pr-status.ts +787 -0
  142. package/src/pr/pr.ts +3642 -0
  143. package/src/pr/preflight.ts +1031 -0
  144. package/src/pr/publish-outcome.ts +361 -0
  145. package/src/pr/range.ts +119 -0
  146. package/src/pr/reverts-preflight.ts +606 -0
  147. package/src/pr/reverts.ts +377 -0
  148. package/src/pr/review-pr.ts +927 -0
  149. package/src/pr/status.ts +154 -0
  150. package/src/pr/target.ts +388 -0
  151. package/src/pr/teardown.ts +437 -0
  152. package/src/pr/worktree-setup.ts +60 -0
  153. package/src/production-runtime.ts +1877 -0
  154. package/src/progress.ts +487 -0
  155. package/src/rereview/adjudicate.ts +89 -0
  156. package/src/rereview/classify.ts +362 -0
  157. package/src/rereview/identity.ts +211 -0
  158. package/src/rereview/plan.ts +308 -0
  159. package/src/rereview/prepare.ts +1025 -0
  160. package/src/rereview/state.ts +767 -0
  161. package/src/rereview/verify.ts +241 -0
  162. package/src/review/boundary.ts +105 -0
  163. package/src/review/consolidate.ts +246 -0
  164. package/src/review/dedupe.ts +368 -0
  165. package/src/review/drafts.ts +448 -0
  166. package/src/review/findings-conformance.ts +120 -0
  167. package/src/review/findings.ts +714 -0
  168. package/src/review/pipeline.ts +3977 -0
  169. package/src/review/preflight.ts +3575 -0
  170. package/src/review/prompt-set.ts +177 -0
  171. package/src/review/proof-refs.ts +187 -0
  172. package/src/review/report.ts +1821 -0
  173. package/src/review/review.ts +490 -0
  174. package/src/review/root-cause.ts +120 -0
  175. package/src/review/route-preflight.ts +289 -0
  176. package/src/review/run.ts +601 -0
  177. package/src/review/scout.ts +323 -0
  178. package/src/review/size-gate.ts +595 -0
  179. package/src/review/spec.ts +235 -0
  180. package/src/review/step-runner.ts +233 -0
  181. package/src/runner-authority.ts +596 -0
  182. package/src/security/binding-policy.ts +115 -0
  183. package/src/security/credential-broker.ts +773 -0
  184. package/src/security/evidence-redaction.ts +62 -0
  185. package/src/security/execution-authority.ts +27 -0
  186. package/src/security/redact.ts +71 -0
  187. package/src/security/workspace-read-broker.ts +466 -0
  188. package/src/server/client.ts +190 -0
  189. package/src/server/preflight.ts +217 -0
  190. package/src/server/server.ts +327 -0
  191. package/src/signal-handler.ts +50 -0
  192. package/src/store/activity.ts +413 -0
  193. package/src/store/backfill-preflight.ts +49 -0
  194. package/src/store/backfill.ts +141 -0
  195. package/src/store/gc-preflight.ts +206 -0
  196. package/src/store/gc.ts +424 -0
  197. package/src/store/metrics-preflight.ts +229 -0
  198. package/src/store/metrics.ts +236 -0
  199. package/src/store/preflight.ts +748 -0
  200. package/src/store/store.ts +693 -0
  201. package/src/system-tools.ts +355 -0
  202. package/src/transport-registry.ts +1124 -0
  203. package/src/transports/claude-code-cli.ts +1348 -0
  204. package/src/transports/opencode-admission.ts +515 -0
  205. package/src/transports/opencode-client.ts +3328 -0
  206. package/src/transports/opencode-evidence.ts +557 -0
  207. package/src/transports/opencode-mcp.ts +248 -0
  208. package/src/transports/opencode-sdk.ts +2294 -0
  209. package/src/transports/opencode-server.ts +535 -0
  210. package/src/triage/adjudication.ts +113 -0
  211. package/src/triage/reply.ts +125 -0
  212. package/src/triage/triage.ts +255 -0
  213. package/src/ui/activity.ts +173 -0
  214. package/src/ui/config-edit.ts +816 -0
  215. package/src/ui/config.ts +462 -0
  216. package/src/ui/menu.ts +1325 -0
  217. package/src/ui/plan.ts +1039 -0
  218. package/src/ui/primitives.ts +300 -0
  219. package/src/ui/progress.ts +298 -0
  220. package/src/ui/result.ts +552 -0
  221. package/src/ui/review-menu.ts +312 -0
  222. package/src/ui/select.ts +528 -0
  223. package/src/ui/tree.ts +178 -0
  224. package/src/uninstaller.ts +479 -0
  225. package/src/updater.ts +836 -0
  226. package/src/usage.ts +77 -0
  227. package/src/watch/preflight.ts +1389 -0
  228. package/src/watch/watch.ts +1235 -0
  229. package/src/wizard.ts +877 -0
@@ -0,0 +1,814 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ chmodSync,
4
+ closeSync,
5
+ constants,
6
+ existsSync,
7
+ mkdirSync,
8
+ openSync,
9
+ readFileSync,
10
+ statSync,
11
+ writeSync,
12
+ } from "node:fs";
13
+ import { readFile, realpath } from "node:fs/promises";
14
+ import { homedir } from "node:os";
15
+ import path from "node:path";
16
+ import type { ExactBindingCapabilityReport } from "../execution/contracts";
17
+ import {
18
+ defaultExecSnapshotBase,
19
+ executionSnapshotDirName,
20
+ registerExecutionSnapshot,
21
+ releaseExecutionSnapshot,
22
+ sweepExecutionSnapshotsOpportunistically,
23
+ } from "./exec-snapshots";
24
+
25
+ export type RunnerBackend =
26
+ | "claude-code"
27
+ | "opencode"
28
+ | "antigravity"
29
+ | "codex";
30
+
31
+ export type CredentialKind =
32
+ | "claude_subscription_oauth"
33
+ | "opencode_chatgpt_oauth"
34
+ | "provider_api_token"
35
+ // #182: an OpenCode route whose model the provider itself declares free at
36
+ // runtime (all cost leaves === 0, status active, via `opencode models
37
+ // <provider> --verbose --refresh`). Authenticates with NOTHING — no OAuth
38
+ // record, no API token — so it is refused at credential projection without
39
+ // a kind of its own. Not metered (`credentialKindBillsMetered` is false),
40
+ // so pricing is not_applicable and usage stamps subscription (truthful
41
+ // zero). Additive: every consumer compares with ===/!== or passes through.
42
+ | "provider_free";
43
+
44
+ export type ExecutableDenialCode = "executable_not_approved";
45
+
46
+ export interface ExecutableAllowlistEntry {
47
+ readonly absolutePath: string;
48
+ readonly sha256: string;
49
+ }
50
+
51
+ export interface VerifiedExecutable {
52
+ readonly absolutePath: string;
53
+ readonly sha256: string;
54
+ readonly verifiedExecutionPath: string;
55
+ readonly kind?: "binary" | "script-launcher";
56
+ readonly version?: string;
57
+ }
58
+
59
+ export interface ExecutableVerificationApproved {
60
+ readonly approved: true;
61
+ readonly executable: VerifiedExecutable;
62
+ readonly code?: undefined;
63
+ readonly reason?: undefined;
64
+ }
65
+
66
+ export interface ExecutableVerificationDenied {
67
+ readonly approved: false;
68
+ readonly code: ExecutableDenialCode;
69
+ readonly reason: string;
70
+ readonly executable?: undefined;
71
+ }
72
+
73
+ export type ExecutableVerificationResult =
74
+ | ExecutableVerificationApproved
75
+ | ExecutableVerificationDenied;
76
+
77
+ export interface VerifyExecutableOptions {
78
+ readonly candidatePath: string;
79
+ readonly allowlist?: readonly ExecutableAllowlistEntry[];
80
+ readonly snapshotDir?: string;
81
+ }
82
+
83
+ export interface VerifyExecutableAuthorityDeps {
84
+ readonly realpathFn?: (p: string) => Promise<string>;
85
+ readonly readFileFn?: (p: string) => Promise<Uint8Array>;
86
+ readonly statFn?: (p: string) => { mode: number };
87
+ }
88
+
89
+ interface AllowlistedBytes {
90
+ readonly approved: true;
91
+ readonly canonicalPath: string;
92
+ readonly digest: string;
93
+ readonly content: Buffer;
94
+ }
95
+
96
+ // Steps 1-6: the allowlist and hash verdict, shared by the snapshotting
97
+ // authority below and the verify-only binding check. Writes nothing.
98
+ async function verifyAllowlistedBytes(
99
+ options: Omit<VerifyExecutableOptions, "snapshotDir">,
100
+ deps: VerifyExecutableAuthorityDeps,
101
+ ): Promise<AllowlistedBytes | ExecutableVerificationDenied> {
102
+ const { candidatePath, allowlist = [] } = options;
103
+ const toRealpath = deps.realpathFn ?? realpath;
104
+ const readBytes =
105
+ deps.readFileFn ?? ((p: string) => readFile(p) as Promise<Uint8Array>);
106
+ const statFile = deps.statFn ?? ((p: string) => statSync(p));
107
+
108
+ // 1. Validate allowlist integrity: reject relative paths in allowlist entries
109
+ for (const entry of allowlist) {
110
+ if (!path.isAbsolute(entry.absolutePath)) {
111
+ return {
112
+ approved: false,
113
+ code: "executable_not_approved",
114
+ reason: `Allowlist entry contains relative path: ${entry.absolutePath}`,
115
+ };
116
+ }
117
+ }
118
+
119
+ // 2. Candidate path must be absolute
120
+ if (!path.isAbsolute(candidatePath)) {
121
+ return {
122
+ approved: false,
123
+ code: "executable_not_approved",
124
+ reason: `Relative executable path not allowed: ${candidatePath}`,
125
+ };
126
+ }
127
+
128
+ // 3. Resolve canonical path
129
+ let canonicalPath: string;
130
+ try {
131
+ canonicalPath = await toRealpath(candidatePath);
132
+ } catch (error) {
133
+ return {
134
+ approved: false,
135
+ code: "executable_not_approved",
136
+ reason: `Executable not found or realpath failed: ${(error as Error).message}`,
137
+ };
138
+ }
139
+
140
+ // 4. Check executable mode bit
141
+ try {
142
+ const stats = statFile(canonicalPath);
143
+ const isExecutable = (stats.mode & 0o111) !== 0;
144
+ if (!isExecutable) {
145
+ return {
146
+ approved: false,
147
+ code: "executable_not_approved",
148
+ reason: `Missing executable permissions on: ${canonicalPath}`,
149
+ };
150
+ }
151
+ } catch (error) {
152
+ return {
153
+ approved: false,
154
+ code: "executable_not_approved",
155
+ reason: `Failed to inspect permissions: ${(error as Error).message}`,
156
+ };
157
+ }
158
+
159
+ // 5. Read bytes and compute SHA-256
160
+ let content: Buffer;
161
+ let digest: string;
162
+ try {
163
+ const raw = await readBytes(canonicalPath);
164
+ content = Buffer.from(raw);
165
+ const hasher = new Bun.CryptoHasher("sha256");
166
+ hasher.update(content);
167
+ digest = hasher.digest("hex");
168
+ } catch (error) {
169
+ return {
170
+ approved: false,
171
+ code: "executable_not_approved",
172
+ reason: `Failed to read and hash binary: ${(error as Error).message}`,
173
+ };
174
+ }
175
+
176
+ // 6. Match against allowlist
177
+ const matchingEntry = allowlist.find(
178
+ (entry) =>
179
+ path.resolve(entry.absolutePath) === canonicalPath &&
180
+ entry.sha256.toLowerCase() === digest.toLowerCase(),
181
+ );
182
+
183
+ if (!matchingEntry) {
184
+ return {
185
+ approved: false,
186
+ code: "executable_not_approved",
187
+ reason: `Binary ${canonicalPath} (sha256:${digest}) is not in configured allowlist`,
188
+ };
189
+ }
190
+
191
+ return { approved: true, canonicalPath, digest, content };
192
+ }
193
+
194
+ export interface ExecutableBindingApproved {
195
+ readonly approved: true;
196
+ readonly absolutePath: string;
197
+ readonly sha256: string;
198
+ readonly code?: undefined;
199
+ readonly reason?: undefined;
200
+ }
201
+
202
+ export type ExecutableBindingVerificationResult =
203
+ | ExecutableBindingApproved
204
+ | ExecutableVerificationDenied;
205
+
206
+ // #303: binding resolution (runner-authority.ts) needs the allowlist and hash
207
+ // verdict, never a runnable copy — it used to call verifyExecutableAuthority
208
+ // and discard the snapshot that call had just written, one per route. The
209
+ // approved shape deliberately carries no `verifiedExecutionPath`: nothing can
210
+ // spawn from a verify-only result, so execution still has to go through
211
+ // verifyExecutableAuthority and its TOCTOU snapshot.
212
+ export async function verifyExecutableBinding(
213
+ options: Omit<VerifyExecutableOptions, "snapshotDir">,
214
+ deps: VerifyExecutableAuthorityDeps = {},
215
+ ): Promise<ExecutableBindingVerificationResult> {
216
+ const verified = await verifyAllowlistedBytes(options, deps);
217
+ if (!verified.approved) return verified;
218
+ return {
219
+ approved: true,
220
+ absolutePath: verified.canonicalPath,
221
+ sha256: verified.digest,
222
+ };
223
+ }
224
+
225
+ export async function verifyExecutableAuthority(
226
+ options: VerifyExecutableOptions,
227
+ deps: VerifyExecutableAuthorityDeps = {},
228
+ ): Promise<ExecutableVerificationResult> {
229
+ const verified = await verifyAllowlistedBytes(options, deps);
230
+ if (!verified.approved) return verified;
231
+ const { canonicalPath, digest, content } = verified;
232
+
233
+ // WHY scripts are not snapshotted: a shebang launcher's interpreter resolves
234
+ // relative imports against the script's own location, so a snapshot copy
235
+ // breaks sibling imports. The launcher executes from its canonical path; the
236
+ // residual TOCTOU window on scripts is accepted until credential projection
237
+ // lands.
238
+ if (content.subarray(0, 2).toString("latin1") === "#!") {
239
+ return {
240
+ approved: true,
241
+ executable: {
242
+ absolutePath: canonicalPath,
243
+ sha256: digest,
244
+ verifiedExecutionPath: canonicalPath,
245
+ kind: "script-launcher",
246
+ },
247
+ };
248
+ }
249
+
250
+ // 7. TOCTOU Defense: Create private verified execution snapshot bound to verified bytes
251
+ const snapBase = options.snapshotDir ?? defaultExecSnapshotBase();
252
+ // #303: collect what crashed processes left behind before adding to it.
253
+ // Rate-limited, time-bounded (OPPORTUNISTIC_SWEEP_BUDGET_MS) and
254
+ // best-effort inside, so this step pays at most the budget even on a large
255
+ // backlog; awaited so a test's cleanup never races a sweep still running in
256
+ // the background.
257
+ await sweepExecutionSnapshotsOpportunistically(snapBase);
258
+ // The pid lets a later sweep tell a dead owner's directory from a live one;
259
+ // the per-call uuid stays — it is what defeats a pre-planted path.
260
+ const snapDir = path.join(
261
+ snapBase,
262
+ executionSnapshotDirName(digest, process.pid, randomUUID()),
263
+ );
264
+ try {
265
+ mkdirSync(snapDir, { recursive: true, mode: 0o700 });
266
+ // Registered before the bytes land, so an exit mid-write still removes
267
+ // the partial copy. Every removal below goes through the registry too.
268
+ registerExecutionSnapshot(snapDir);
269
+ chmodSync(snapDir, 0o700);
270
+ const snapBinaryName = path.basename(canonicalPath);
271
+ const snapBinaryPath = path.join(snapDir, snapBinaryName);
272
+ // Exclusive, no-follow create: a symlink planted at this exact path must
273
+ // make the write fail closed rather than redirect the verified bytes.
274
+ const fd = openSync(
275
+ snapBinaryPath,
276
+ constants.O_WRONLY |
277
+ constants.O_CREAT |
278
+ constants.O_EXCL |
279
+ constants.O_NOFOLLOW,
280
+ 0o700,
281
+ );
282
+ try {
283
+ writeSync(fd, content);
284
+ } finally {
285
+ closeSync(fd);
286
+ }
287
+ chmodSync(snapBinaryPath, 0o700);
288
+
289
+ const snapshotBytes = readFileSync(snapBinaryPath);
290
+ const verifyHasher = new Bun.CryptoHasher("sha256");
291
+ verifyHasher.update(snapshotBytes);
292
+ if (verifyHasher.digest("hex") !== digest.toLowerCase()) {
293
+ releaseExecutionSnapshot(snapDir);
294
+ return {
295
+ approved: false,
296
+ code: "executable_not_approved",
297
+ reason: "snapshot verification failed",
298
+ };
299
+ }
300
+
301
+ return {
302
+ approved: true,
303
+ executable: {
304
+ absolutePath: canonicalPath,
305
+ sha256: digest,
306
+ verifiedExecutionPath: snapBinaryPath,
307
+ kind: "binary",
308
+ },
309
+ };
310
+ } catch (error) {
311
+ // Unregistered only when mkdirSync itself failed, and then there is no
312
+ // directory to remove.
313
+ releaseExecutionSnapshot(snapDir);
314
+ return {
315
+ approved: false,
316
+ code: "executable_not_approved",
317
+ reason: `Failed to create verified execution snapshot: ${(error as Error).message}`,
318
+ };
319
+ }
320
+ }
321
+
322
+ export interface ProviderCapabilityReport {
323
+ readonly backend: RunnerBackend;
324
+ readonly status: "ready" | "degraded" | "blocking";
325
+ readonly binary?: { absolutePath: string; sha256: string; version: string };
326
+ readonly auth: {
327
+ kind: CredentialKind;
328
+ projectionReady: boolean;
329
+ probe: "passed" | "failed" | "not_run";
330
+ };
331
+ readonly isolation: {
332
+ syntheticHome: boolean;
333
+ workspaceReadBroker: boolean;
334
+ codegraphPolicy: boolean;
335
+ };
336
+ readonly protocol: {
337
+ terminalProof: boolean;
338
+ boundedEvents: boolean;
339
+ usageMode: "snapshot" | "delta" | "none";
340
+ };
341
+ readonly cancellation: {
342
+ deadlineMs: number;
343
+ conformance: "passed" | "failed" | "not_run";
344
+ };
345
+ readonly billing: {
346
+ mode: "subscription" | "metered" | "unknown";
347
+ pricingReady: boolean;
348
+ };
349
+ readonly rateLimitBucketId?: string;
350
+ readonly issues: readonly {
351
+ code: string;
352
+ message: string;
353
+ blocking: boolean;
354
+ }[];
355
+ }
356
+
357
+ // §13 ("Preflight and execution use the same verified absolute binary"):
358
+ // extracted from resolveRunnerAuthority so the capability-report producer and
359
+ // the execution authority share ONE resolution rule instead of two copies
360
+ // that can drift. Same lookup order, same error strings.
361
+ export interface ClaudeBinaryLookup {
362
+ readonly binaryPath?: string;
363
+ readonly env?: { PATH?: string };
364
+ }
365
+
366
+ export interface ClaudeBinaryResolutionDeps {
367
+ readonly existsFn?: (p: string) => boolean;
368
+ readonly realpathFn?: (p: string) => Promise<string>;
369
+ readonly readFileFn?: (p: string) => Promise<Uint8Array>;
370
+ readonly statFn?: (p: string) => { mode: number };
371
+ }
372
+
373
+ export type ClaudeCanonicalBinary =
374
+ | {
375
+ readonly canonicalPath: string;
376
+ readonly sha256: string;
377
+ readonly error?: undefined;
378
+ }
379
+ | { readonly canonicalPath?: undefined; readonly error: string };
380
+
381
+ const CLAUDE_BINARY_NAME = "claude";
382
+
383
+ export async function resolveClaudeCanonicalBinary(
384
+ lookup: ClaudeBinaryLookup,
385
+ deps: ClaudeBinaryResolutionDeps = {},
386
+ ): Promise<ClaudeCanonicalBinary> {
387
+ const exists = deps.existsFn ?? existsSync;
388
+ const toRealpath = deps.realpathFn ?? realpath;
389
+ const readBytes =
390
+ deps.readFileFn ?? ((p: string) => readFile(p) as Promise<Uint8Array>);
391
+
392
+ let candidate: string;
393
+ if (lookup.binaryPath !== undefined) {
394
+ if (!path.isAbsolute(lookup.binaryPath)) {
395
+ return {
396
+ error: `binary override must be an absolute path: ${lookup.binaryPath}`,
397
+ };
398
+ }
399
+ candidate = lookup.binaryPath;
400
+ } else {
401
+ const searchDirs = (lookup.env?.PATH ?? process.env.PATH ?? "")
402
+ .split(path.delimiter)
403
+ .filter((dir) => dir.length > 0);
404
+ candidate = "";
405
+ for (const dir of searchDirs) {
406
+ const probe = path.join(dir, CLAUDE_BINARY_NAME);
407
+ if (exists(probe)) {
408
+ candidate = probe;
409
+ break;
410
+ }
411
+ }
412
+ if (candidate === "") {
413
+ return { error: "claude binary not found on PATH" };
414
+ }
415
+ }
416
+
417
+ try {
418
+ const canonical = await toRealpath(candidate);
419
+ const bytes = await readBytes(canonical);
420
+ const hasher = new Bun.CryptoHasher("sha256");
421
+ hasher.update(bytes);
422
+ const sha256 = hasher.digest("hex");
423
+ return { canonicalPath: canonical, sha256 };
424
+ } catch (error) {
425
+ return {
426
+ error: `failed to resolve claude binary ${candidate}: ${(error as Error).message}`,
427
+ };
428
+ }
429
+ }
430
+
431
+ // §11/D1-09: fields every claude-code route claims independent of host
432
+ // environment. The transport's capabilities() and the report producer both
433
+ // read these constants, so the two surfaces cannot contradict each other.
434
+ export const CLAUDE_CAPABILITY_STATICS = {
435
+ authKind: "claude_subscription_oauth",
436
+ workspaceReadBroker: true,
437
+ terminalProof: true,
438
+ usageMode: "snapshot",
439
+ cancellationDeadlineMs: 7500,
440
+ cancellationConformance: "passed",
441
+ billingMode: "subscription",
442
+ } as const;
443
+
444
+ // Same predicate runner-authority applies when deciding whether to wire the
445
+ // KeychainCredentialBroker (§6.1): macOS subscription OAuth projects out of
446
+ // the Keychain via /usr/bin/security; elsewhere there is nothing to project.
447
+ export function claudeCredentialProjectionReady(
448
+ options: {
449
+ platform?: NodeJS.Platform;
450
+ existsFn?: (p: string) => boolean;
451
+ } = {},
452
+ ): boolean {
453
+ const platform = options.platform ?? process.platform;
454
+ const exists = options.existsFn ?? existsSync;
455
+ return platform === "darwin" && exists("/usr/bin/security");
456
+ }
457
+
458
+ // Mirrors system-tools' claude auth predicate (env token or on-disk session),
459
+ // extended with the two routes that predicate misses and §6.1's own table
460
+ // names: the macOS Keychain item (the subscription path this project targets
461
+ // — pr-hero found its own gate refusing exactly that machine class) and the
462
+ // Linux-style ~/.claude/.credentials.json. The default probe never spawns
463
+ // claude; the keychain query is metadata-only (no -w), proven non-interactive.
464
+ function defaultKeychainCredentialPresent(): boolean {
465
+ return (
466
+ Bun.spawnSync([
467
+ "/usr/bin/security",
468
+ "find-generic-password",
469
+ "-s",
470
+ "Claude Code-credentials",
471
+ ]).exitCode === 0
472
+ );
473
+ }
474
+
475
+ // The on-disk Claude sessions the default probe accepts, relative to HOME.
476
+ // Exported because src/ci/trigger.ts must reach the same verdict before
477
+ // `bun install` and so keeps its own copy (it may import only builtins); a
478
+ // drift test in test/ci/trigger.test.ts pins that copy to this list.
479
+ export const CLAUDE_SESSION_FILES: readonly string[] = [
480
+ ".claude.json",
481
+ path.join(".claude", "session.json"),
482
+ path.join(".claude", ".credentials.json"),
483
+ ];
484
+
485
+ function defaultClaudeAuthProbe(
486
+ env: Record<string, string | undefined>,
487
+ home: string,
488
+ exists: (p: string) => boolean,
489
+ platform: NodeJS.Platform,
490
+ keychainProbe: () => boolean,
491
+ ): "passed" | "failed" {
492
+ const hasToken =
493
+ Boolean(env.CLAUDE_CODE_OAUTH_TOKEN?.trim()) ||
494
+ Boolean(env.ANTHROPIC_API_KEY?.trim());
495
+ if (hasToken) return "passed";
496
+ const hasSessionFile = CLAUDE_SESSION_FILES.some((file) =>
497
+ exists(path.join(home, file)),
498
+ );
499
+ if (hasSessionFile) return "passed";
500
+ if (platform === "darwin" && exists("/usr/bin/security")) {
501
+ return keychainProbe() ? "passed" : "failed";
502
+ }
503
+ return "failed";
504
+ }
505
+
506
+ export interface ProduceClaudeCapabilityReportOptions {
507
+ readonly binaryPath?: string;
508
+ readonly env?: Record<string, string | undefined>;
509
+ readonly platform?: NodeJS.Platform;
510
+ readonly home?: string;
511
+ readonly existsFn?: (p: string) => boolean;
512
+ readonly realpathFn?: (p: string) => Promise<string>;
513
+ readonly readFileFn?: (p: string) => Promise<Uint8Array>;
514
+ readonly version?: string;
515
+ // Injectable so offline tests never spawn claude (§11).
516
+ readonly authProbe?: () => "passed" | "failed";
517
+ // Injectable keychain presence check backing the default auth probe's
518
+ // macOS subscription route; offline tests stub it.
519
+ readonly keychainProbe?: () => boolean;
520
+ }
521
+
522
+ // §11/D1-09: the REAL claude-code report. Every gap becomes an issue entry;
523
+ // missing binary or failed auth are blocking, everything unproven is claimed
524
+ // false and non-blocking rather than assumed green.
525
+ export async function produceClaudeCapabilityReport(
526
+ options: ProduceClaudeCapabilityReportOptions = {},
527
+ ): Promise<ProviderCapabilityReport> {
528
+ const env = options.env ?? process.env;
529
+ const home = options.home ?? homedir();
530
+ const existsFn = options.existsFn ?? existsSync;
531
+
532
+ const issues: { code: string; message: string; blocking: boolean }[] = [];
533
+
534
+ const resolved = await resolveClaudeCanonicalBinary(
535
+ { binaryPath: options.binaryPath, env },
536
+ {
537
+ existsFn,
538
+ realpathFn: options.realpathFn,
539
+ readFileFn: options.readFileFn,
540
+ },
541
+ );
542
+
543
+ const projectionReady = claudeCredentialProjectionReady({
544
+ platform: options.platform,
545
+ existsFn,
546
+ });
547
+
548
+ const probeResult =
549
+ options.authProbe !== undefined
550
+ ? options.authProbe()
551
+ : defaultClaudeAuthProbe(
552
+ env,
553
+ home,
554
+ existsFn,
555
+ options.platform ?? process.platform,
556
+ options.keychainProbe ?? defaultKeychainCredentialPresent,
557
+ );
558
+ if (probeResult === "failed") {
559
+ issues.push({
560
+ code: "auth_failed",
561
+ message:
562
+ "claude authentication not detected (no OAuth token env var, no session credentials, no keychain entry)",
563
+ blocking: true,
564
+ });
565
+ }
566
+
567
+ if (!projectionReady) {
568
+ issues.push({
569
+ code: "credential_projection_unavailable",
570
+ message:
571
+ "credential projection broker unavailable (needs darwin + /usr/bin/security); child runs with enumerated-passthrough env instead of a synthetic home",
572
+ blocking: false,
573
+ });
574
+ }
575
+
576
+ // Honest until enforced: no codegraph-specific read policy exists in
577
+ // src/security/ today, so the report must not claim one (§11).
578
+ issues.push({
579
+ code: "codegraph_policy_unenforced",
580
+ message:
581
+ "no dedicated codegraph sensitive-file policy is enforced yet; isolation relies on --strict-mcp-config with a codegraph-only mcp.json",
582
+ blocking: false,
583
+ });
584
+
585
+ // The AsyncEventSink contract exists but the pipeline still consumes usage
586
+ // from the CLI's json snapshot, not bounded events (§12 D1-08 residual).
587
+ issues.push({
588
+ code: "bounded_events_sink_missing",
589
+ message:
590
+ "bounded event streaming is not wired: the event sink is currently a no-op and usage arrives as a final snapshot",
591
+ blocking: false,
592
+ });
593
+
594
+ if (resolved.error !== undefined) {
595
+ issues.unshift({
596
+ code: "binary_unresolved",
597
+ message: resolved.error,
598
+ blocking: true,
599
+ });
600
+ }
601
+
602
+ const hasBlocking = issues.some((issue) => issue.blocking);
603
+
604
+ return {
605
+ backend: "claude-code",
606
+ status: hasBlocking ? "blocking" : "degraded",
607
+ ...(resolved.error === undefined
608
+ ? {
609
+ binary: {
610
+ absolutePath: resolved.canonicalPath,
611
+ sha256: resolved.sha256,
612
+ version: options.version ?? "unknown",
613
+ },
614
+ }
615
+ : {}),
616
+ auth: {
617
+ kind: CLAUDE_CAPABILITY_STATICS.authKind,
618
+ projectionReady,
619
+ probe: probeResult,
620
+ },
621
+ isolation: {
622
+ syntheticHome: projectionReady,
623
+ workspaceReadBroker: CLAUDE_CAPABILITY_STATICS.workspaceReadBroker,
624
+ codegraphPolicy: false,
625
+ },
626
+ protocol: {
627
+ terminalProof: CLAUDE_CAPABILITY_STATICS.terminalProof,
628
+ boundedEvents: false,
629
+ usageMode: CLAUDE_CAPABILITY_STATICS.usageMode,
630
+ },
631
+ cancellation: {
632
+ deadlineMs: CLAUDE_CAPABILITY_STATICS.cancellationDeadlineMs,
633
+ conformance: CLAUDE_CAPABILITY_STATICS.cancellationConformance,
634
+ },
635
+ billing: {
636
+ mode: CLAUDE_CAPABILITY_STATICS.billingMode,
637
+ // #197. The old `false` reasoned about a model id: this is a
638
+ // BACKEND-wide report produced before any route resolves, and
639
+ // `tokenPricingAvailableFor` needed a provider AND a model to answer.
640
+ // That function and the tables behind it are deleted, and the flag it
641
+ // fed never meant what the comment assumed — `pricingReady` asserts
642
+ // "will this transport tell you what the attempt cost?", which is a
643
+ // backend-wide fact needing no model. The claude-code CLI reports
644
+ // `total_cost_usd`, so the honest answer here is `true`.
645
+ //
646
+ // Kept IDENTICAL to ClaudeCodeCliTransport.capabilities() on purpose:
647
+ // "the transport contradicts the producer in no environment"
648
+ // (test/model/provider-capabilities.test.ts) is a structural guard, and a
649
+ // producer disagreeing with the transport that actually runs the route
650
+ // is the drift it exists to catch.
651
+ pricingReady: true,
652
+ },
653
+ issues,
654
+ };
655
+ }
656
+
657
+ // §11: "Any blocking issue prevents the route from executing." Pure decision
658
+ // so cli.ts's review paths gate on it without their own issue-parsing logic.
659
+ export interface CapabilityGateDecision {
660
+ readonly ok: boolean;
661
+ readonly reason?: string;
662
+ }
663
+
664
+ export function capabilityGateDecision(
665
+ report: ProviderCapabilityReport,
666
+ ): CapabilityGateDecision {
667
+ const blocking = report.issues.filter((issue) => issue.blocking);
668
+ if (blocking.length === 0) {
669
+ return { ok: true };
670
+ }
671
+ return {
672
+ ok: false,
673
+ reason: blocking
674
+ .map((issue) => `${issue.code}: ${issue.message}`)
675
+ .join("; "),
676
+ };
677
+ }
678
+
679
+ function gateDecisionFromIssues(
680
+ issues: readonly { code: string; message: string; blocking: boolean }[],
681
+ ): CapabilityGateDecision {
682
+ const blocking = issues.filter((issue) => issue.blocking);
683
+ if (blocking.length === 0) {
684
+ return { ok: true };
685
+ }
686
+ return {
687
+ ok: false,
688
+ reason: blocking
689
+ .map((issue) => `${issue.code}: ${issue.message}`)
690
+ .join("; "),
691
+ };
692
+ }
693
+
694
+ // Exact-binding gate (§11 production runtime): subscription routes may pass
695
+ // without token pricing when pricingApplicability is not_applicable; metered
696
+ // routes require tokenPricingAvailable before spend.
697
+ export function exactBindingCapabilityIssues(
698
+ report: ExactBindingCapabilityReport,
699
+ ): readonly { code: string; message: string; blocking: boolean }[] {
700
+ const issues: { code: string; message: string; blocking: boolean }[] = [];
701
+ const label = `${report.backend} (${report.routeKey})`;
702
+
703
+ if (!report.binary.resolved) {
704
+ issues.push({
705
+ code: "binary_unresolved",
706
+ message:
707
+ report.binary.reason ?? `executable not resolved for binding ${label}`,
708
+ blocking: true,
709
+ });
710
+ }
711
+ if (report.auth.probe === "failed") {
712
+ issues.push({
713
+ code: "auth_failed",
714
+ message: `authentication not detected for binding ${label}`,
715
+ blocking: true,
716
+ });
717
+ }
718
+ if (!report.sdk.available) {
719
+ issues.push({
720
+ code: "sdk_unavailable",
721
+ message: `SDK adapter unavailable for binding ${label}`,
722
+ blocking: true,
723
+ });
724
+ }
725
+ if (
726
+ report.billing.pricingApplicability === "required" &&
727
+ !report.billing.tokenPricingAvailable
728
+ ) {
729
+ issues.push({
730
+ code: "pricing_table_missing",
731
+ message: `token pricing required but unavailable for binding ${label}`,
732
+ blocking: true,
733
+ });
734
+ }
735
+ // WHY: this is the enforcement point for the design's "billingMode:
736
+ // 'unknown' is a blocking preflight result"
737
+ // (docs/multi-runtime-model-diversity-design.md:461). The legacy
738
+ // ProviderCapabilityReport has three billing modes and the exact contract
739
+ // has two, so FrozenRuntimeBinding.capabilities() narrows `unknown` into
740
+ // "subscription"; that leaves pricingApplicability at "not_applicable", so
741
+ // the pricing_table_missing gate above structurally CANNOT catch an
742
+ // unknown-billing route. The producer therefore derives
743
+ // cashCostAccountingValid from the THREE-STATE effective mode (#133's
744
+ // `effectiveBillingMode`, which is the transport's own mode for every kind
745
+ // except `provider_api_token`) and reports false for `unknown`, and this
746
+ // branch is what turns that fact into a refusal. It is reachable through
747
+ // the real producer (see test/production-runtime.test.ts "an unknown legacy
748
+ // billing mode blocks the exact-binding gate through the real producer"),
749
+ // and it also holds the pricingApplicability/cashCostAccountingValid field
750
+ // independence (src/execution/contracts.ts:235-237) for any future
751
+ // producer.
752
+ //
753
+ // #133 does not weaken this: the effective mode only ever replaces
754
+ // `unknown` with `metered`, and a metered route without pricing is caught
755
+ // by pricing_table_missing above instead. Nothing reaches "subscription"
756
+ // that did not already, so `unknown` still ends in a blocking refusal on
757
+ // one branch or the other.
758
+ if (
759
+ report.billing.pricingApplicability !== "required" &&
760
+ !report.billing.cashCostAccountingValid
761
+ ) {
762
+ issues.push({
763
+ code: "cash_cost_accounting_invalid",
764
+ message: `cash-cost accounting is not valid for binding ${label}`,
765
+ blocking: true,
766
+ });
767
+ }
768
+ if (!report.isolation.codegraphPolicy) {
769
+ issues.push({
770
+ code: "codegraph_policy_unenforced",
771
+ message:
772
+ "no dedicated codegraph sensitive-file policy is enforced yet; isolation relies on --strict-mcp-config with a codegraph-only mcp.json",
773
+ blocking: false,
774
+ });
775
+ }
776
+ if (!report.protocol.boundedEvents) {
777
+ issues.push({
778
+ code: "bounded_events_sink_missing",
779
+ message:
780
+ "bounded event streaming is not wired: usage arrives as a final snapshot",
781
+ blocking: false,
782
+ });
783
+ }
784
+ if (
785
+ report.auth.projectionReady === false &&
786
+ report.environment.enumeratedPassthrough
787
+ ) {
788
+ issues.push({
789
+ code: "credential_projection_unavailable",
790
+ message:
791
+ "credential projection broker unavailable; child runs with enumerated-passthrough env instead of a synthetic home",
792
+ blocking: false,
793
+ });
794
+ }
795
+ return issues;
796
+ }
797
+
798
+ export function exactBindingCapabilityGate(
799
+ report: ExactBindingCapabilityReport,
800
+ ): CapabilityGateDecision {
801
+ return gateDecisionFromIssues(exactBindingCapabilityIssues(report));
802
+ }
803
+
804
+ export function exactBindingCapabilityStatus(
805
+ issues: readonly { code: string; message: string; blocking: boolean }[],
806
+ ): ProviderCapabilityReport["status"] {
807
+ if (issues.some((issue) => issue.blocking)) {
808
+ return "blocking";
809
+ }
810
+ if (issues.length > 0) {
811
+ return "degraded";
812
+ }
813
+ return "ready";
814
+ }