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,773 @@
1
+ // D1-05 §6.1: credential projection. The broker copies ONLY the minimum
2
+ // credential record out of a trusted source into an ephemeral 0700 projection
3
+ // with a single 0600 file; every component is lstat-checked so a pre-planted
4
+ // symlink cannot redirect the credential write outside the projection root.
5
+ // Credential values, source paths and file contents never appear in errors,
6
+ // metadata or logs — only the projected file's sha256 is exposed.
7
+
8
+ import { randomUUID } from "node:crypto";
9
+ import {
10
+ existsSync,
11
+ lstatSync,
12
+ mkdirSync,
13
+ rmSync,
14
+ writeFileSync,
15
+ } from "node:fs";
16
+ import { homedir, tmpdir } from "node:os";
17
+ import path from "node:path";
18
+ import type { CredentialKind } from "#model/provider-capabilities";
19
+
20
+ export type CredentialProjectionFile = {
21
+ readonly path: string;
22
+ readonly mode: 0o600;
23
+ readonly sha256: string;
24
+ };
25
+
26
+ // Verbatim shape of docs/multi-runtime-model-diversity-design.md §6.1, plus
27
+ // D1-08 PR3's §9.2 addition: the scope fields `deriveBucketId`
28
+ // (execution/bucket-id.ts) hashes into a rate-limit bucket ID. Populated
29
+ // best-effort per credential kind — today NO broker below sets it, because
30
+ // `claude_subscription_oauth` (the only shipped route) has no
31
+ // account/project/rateLimitGroup to report. That is not a bug: an absent
32
+ // `bucketScope` and an explicit `{}` are handled identically by
33
+ // `deriveBucketId`'s "unknown" sentinel (§9.2 "Bucket Identity Coarsens
34
+ // Unknown Scope"), so every such credential still gets one conservative,
35
+ // coarse bucket rather than an unbounded one (design's Open Question).
36
+ export interface CredentialProjection {
37
+ readonly projectionId: string;
38
+ readonly kind: CredentialKind;
39
+ readonly syntheticHome: string;
40
+ readonly syntheticConfigHome: string;
41
+ readonly syntheticTmp: string;
42
+ readonly env: Readonly<Record<string, string>>;
43
+ readonly files: readonly CredentialProjectionFile[];
44
+ readonly bucketScope?: {
45
+ readonly account?: string;
46
+ readonly project?: string;
47
+ readonly rateLimitGroup?: string;
48
+ };
49
+ destroy(): Promise<void>;
50
+ }
51
+
52
+ // Verbatim shape of docs/multi-runtime-model-diversity-design.md §6.1.
53
+ export interface CredentialBroker {
54
+ project(input: {
55
+ readonly sessionId: string;
56
+ readonly credentialRef: string;
57
+ readonly kind: CredentialKind;
58
+ readonly verifiedBinaryPath: string;
59
+ }): Promise<CredentialProjection>;
60
+ }
61
+
62
+ export const CLAUDE_CREDENTIALS_KEYCHAIN_SERVICE = "Claude Code-credentials";
63
+ const SECURITY_BIN = "/usr/bin/security";
64
+
65
+ export type CredentialProjectionFailureClass =
66
+ | "unsupported_kind"
67
+ | "source_read_failed"
68
+ | "malformed_payload"
69
+ | "missing_subscription_record"
70
+ // #133: the metered kind's own class. `missing_subscription_record` is the
71
+ // wrong NAME for a provider API token — there is no subscription involved —
72
+ // and the wrong BEHAVIOUR: harness.ts degrades that one class to the
73
+ // operator environment (a deliberate 2026-08-26 decision, because Claude's
74
+ // subscription store moved out of the keychain). An absent provider token
75
+ // is not a moved store, and degrading it would run a metered route on
76
+ // whatever provider keys happen to be ambient. It falls into the
77
+ // fail-closed branch there, and must stay there.
78
+ | "missing_provider_record"
79
+ | "projection_layout_invalid";
80
+
81
+ export class CredentialProjectionError extends Error {
82
+ readonly failureClass: CredentialProjectionFailureClass;
83
+
84
+ constructor(failureClass: CredentialProjectionFailureClass) {
85
+ // Message names only the failure class — never source content, paths or
86
+ // keychain output (§6.1 redaction rule).
87
+ super(`Credential projection failed (${failureClass})`);
88
+ this.name = "CredentialProjectionError";
89
+ this.failureClass = failureClass;
90
+ }
91
+ }
92
+
93
+ export interface KeychainCredentialBrokerOptions {
94
+ readonly securityBinPath?: string;
95
+ // Injectable for offline tests; returns the raw JSON payload of the
96
+ // keychain item. Production default shells out to /usr/bin/security.
97
+ readonly readerFn?: (service: string) => Promise<string>;
98
+ }
99
+
100
+ interface ClaudeOauthRecord {
101
+ [key: string]: unknown;
102
+ }
103
+
104
+ export class KeychainCredentialBroker implements CredentialBroker {
105
+ private readonly securityBinPath: string;
106
+ private readonly readerFn: (service: string) => Promise<string>;
107
+
108
+ constructor(options: KeychainCredentialBrokerOptions = {}) {
109
+ this.securityBinPath = options.securityBinPath ?? SECURITY_BIN;
110
+ if (options.readerFn !== undefined) {
111
+ this.readerFn = options.readerFn;
112
+ } else {
113
+ // Fail loud at construction, not at first spawn: a missing pinned
114
+ // helper is an environment defect (§6.1 pins absolute helper paths).
115
+ if (!existsSync(this.securityBinPath)) {
116
+ throw new Error(
117
+ `Pinned security binary not found at ${this.securityBinPath}`,
118
+ );
119
+ }
120
+ this.readerFn = (service) => this.readKeychain(service);
121
+ }
122
+ }
123
+
124
+ async project(input: {
125
+ readonly sessionId: string;
126
+ readonly credentialRef: string;
127
+ readonly kind: CredentialKind;
128
+ readonly verifiedBinaryPath: string;
129
+ }): Promise<CredentialProjection> {
130
+ void input.sessionId;
131
+ void input.credentialRef;
132
+ void input.verifiedBinaryPath;
133
+ if (input.kind !== "claude_subscription_oauth") {
134
+ throw new Error(
135
+ `Unsupported credential kind: ${input.kind} (KeychainCredentialBroker projects only claude_subscription_oauth)`,
136
+ );
137
+ }
138
+
139
+ let raw: string;
140
+ try {
141
+ raw = await this.readerFn(CLAUDE_CREDENTIALS_KEYCHAIN_SERVICE);
142
+ } catch {
143
+ throw new CredentialProjectionError("source_read_failed");
144
+ }
145
+
146
+ let parsed: unknown;
147
+ try {
148
+ parsed = JSON.parse(raw);
149
+ } catch {
150
+ throw new CredentialProjectionError("malformed_payload");
151
+ }
152
+
153
+ if (
154
+ typeof parsed !== "object" ||
155
+ parsed === null ||
156
+ !("claudeAiOauth" in parsed)
157
+ ) {
158
+ throw new CredentialProjectionError("missing_subscription_record");
159
+ }
160
+
161
+ // Carry ONLY the subscription OAuth record: mcpOAuth and any other keys
162
+ // in the store are unrelated secrets and must not leave the source.
163
+ const oauthRecord = (parsed as Record<string, unknown>).claudeAiOauth;
164
+ if (typeof oauthRecord !== "object" || oauthRecord === null) {
165
+ throw new CredentialProjectionError("missing_subscription_record");
166
+ }
167
+
168
+ return this.buildProjection(input.kind, oauthRecord as ClaudeOauthRecord);
169
+ }
170
+
171
+ private buildProjection(
172
+ kind: CredentialKind,
173
+ oauthRecord: ClaudeOauthRecord,
174
+ ): CredentialProjection {
175
+ // Fresh UUID root per projection: no reuse across runs, nothing to collide
176
+ // with (§6.1 ephemeral layout).
177
+ const projectionRoot = path.join(
178
+ tmpdir(),
179
+ "prhero-cred-projections",
180
+ randomUUID(),
181
+ );
182
+ const claudeDir = path.join(projectionRoot, ".claude");
183
+ const syntheticTmp = path.join(projectionRoot, "tmp");
184
+ const credentialsFile = path.join(claudeDir, ".credentials.json");
185
+
186
+ mkdirSync(projectionRoot, { recursive: true, mode: 0o700 });
187
+ mkdirSync(claudeDir, { recursive: true, mode: 0o700 });
188
+ mkdirSync(syntheticTmp, { recursive: true, mode: 0o700 });
189
+
190
+ // Empirically proven live (2026-08-26): the CLI authenticates purely from
191
+ // <syntheticHome>/.claude/.credentials.json containing this exact shape.
192
+ const payload = `${JSON.stringify({ claudeAiOauth: oauthRecord }, null, 2)}\n`;
193
+ writeFileSync(credentialsFile, payload, { mode: 0o600 });
194
+
195
+ // Defense per §6.1: lstat EVERY component after writing — any symlink in
196
+ // the chain means the credential landed outside our control; fail loud.
197
+ for (const component of [
198
+ tmpdir(),
199
+ path.dirname(path.dirname(credentialsFile)),
200
+ path.dirname(credentialsFile),
201
+ credentialsFile,
202
+ ]) {
203
+ const stats = lstatSync(component);
204
+ if (stats.isSymbolicLink()) {
205
+ // Never leave a possibly-redirected credential tree behind.
206
+ rmSync(projectionRoot, { recursive: true, force: true });
207
+ throw new CredentialProjectionError("projection_layout_invalid");
208
+ }
209
+ }
210
+
211
+ const hasher = new Bun.CryptoHasher("sha256");
212
+ hasher.update(new TextEncoder().encode(payload));
213
+ const sha256 = hasher.digest("hex");
214
+
215
+ const projection: CredentialProjection = {
216
+ projectionId: `cred-${randomUUID()}`,
217
+ kind,
218
+ syntheticHome: projectionRoot,
219
+ syntheticConfigHome: claudeDir,
220
+ syntheticTmp,
221
+ env: {
222
+ HOME: projectionRoot,
223
+ TMPDIR: syntheticTmp,
224
+ },
225
+ files: [{ path: credentialsFile, mode: 0o600, sha256 }],
226
+ destroy: async () => {
227
+ rmSync(projectionRoot, { recursive: true, force: true });
228
+ },
229
+ };
230
+ return projection;
231
+ }
232
+
233
+ private async readKeychain(service: string): Promise<string> {
234
+ const proc = Bun.spawn(
235
+ [this.securityBinPath, "find-generic-password", "-s", service, "-w"],
236
+ {
237
+ stdout: "pipe",
238
+ stderr: "ignore",
239
+ stdin: "ignore",
240
+ },
241
+ );
242
+ const stdout = await new Response(proc.stdout).text();
243
+ const exitCode = await proc.exited;
244
+ if (exitCode !== 0) {
245
+ throw new Error("security lookup failed");
246
+ }
247
+ return stdout.trim();
248
+ }
249
+ }
250
+
251
+ // ---------------------------------------------------------------------------
252
+ // D1-06b §6.1: the OpenCode / ChatGPT OAuth route.
253
+ //
254
+ // Ported from KeychainCredentialBroker rather than rewritten — same threat
255
+ // model, same defenses — with three differences the source forces:
256
+ //
257
+ // 1. The source is a FILE, not the macOS keychain, and OpenCode resolves it
258
+ // through XDG_DATA_HOME before falling back to ~/.local/share.
259
+ // 2. auth.json is a SHARED store. Every provider the operator ever logged
260
+ // into lives in it, so carrying it wholesale would hand an OpenAI-routed
261
+ // step unrelated provider keys. Only the `openai` record travels — the
262
+ // same rule that keeps mcpOAuth out of the Claude projection.
263
+ // 3. The projection pins XDG_DATA_HOME/XDG_CONFIG_HOME as well as HOME. The
264
+ // harness env allowlist happens to drop XDG today, but an isolation claim
265
+ // that depends on a passthrough list staying XDG-free is one edit away
266
+ // from being false.
267
+ //
268
+ // Empirically proven live (2026-08-27): `opencode auth list` under a synthetic
269
+ // HOME reads <syntheticHome>/.local/share/opencode/auth.json and reports
270
+ // exactly the one projected OAuth credential, with the sibling provider keys
271
+ // absent.
272
+ // ---------------------------------------------------------------------------
273
+
274
+ export const OPENCODE_AUTH_RELATIVE_PATH = path.join(
275
+ ".local",
276
+ "share",
277
+ "opencode",
278
+ "auth.json",
279
+ );
280
+
281
+ // ONE list, used for both creating the tree and guarding it. The gap this
282
+ // closes was real (pr-hero F001 on PR #80): the create loop had seven entries
283
+ // and the lstat walk had six, so three directories the child is handed as
284
+ // XDG_CONFIG_HOME / syntheticConfigHome / TMPDIR were built and never checked.
285
+ // Two hand-maintained copies of the same paths WILL drift; a shared layout
286
+ // cannot.
287
+ export interface OpenCodeProjectionLayout {
288
+ readonly syntheticHome: string;
289
+ readonly syntheticConfigHome: string;
290
+ readonly syntheticTmp: string;
291
+ readonly xdgDataHome: string;
292
+ readonly xdgConfigHome: string;
293
+ readonly authFile: string;
294
+ readonly directories: readonly string[];
295
+ // Every path lstat must clear before the projection is handed over —
296
+ // the tree itself plus the shared parent it was created under.
297
+ readonly guarded: readonly string[];
298
+ }
299
+
300
+ export function openCodeProjectionLayout(
301
+ projectionRoot: string,
302
+ parentDir: string = tmpdir(),
303
+ ): OpenCodeProjectionLayout {
304
+ const localDir = path.join(projectionRoot, ".local");
305
+ const xdgDataHome = path.join(localDir, "share");
306
+ const xdgConfigHome = path.join(projectionRoot, ".config");
307
+ const opencodeDataDir = path.join(xdgDataHome, "opencode");
308
+ const opencodeConfigDir = path.join(xdgConfigHome, "opencode");
309
+ const syntheticTmp = path.join(projectionRoot, "tmp");
310
+ const authFile = path.join(opencodeDataDir, "auth.json");
311
+ const directories = [
312
+ projectionRoot,
313
+ localDir,
314
+ xdgDataHome,
315
+ opencodeDataDir,
316
+ xdgConfigHome,
317
+ opencodeConfigDir,
318
+ syntheticTmp,
319
+ ];
320
+ return {
321
+ syntheticHome: projectionRoot,
322
+ syntheticConfigHome: opencodeConfigDir,
323
+ syntheticTmp,
324
+ xdgDataHome,
325
+ xdgConfigHome,
326
+ authFile,
327
+ directories,
328
+ guarded: [parentDir, ...directories, authFile],
329
+ };
330
+ }
331
+
332
+ export interface OpenCodeAuthBrokerOptions {
333
+ // Injectable for offline tests; returns the raw auth.json payload.
334
+ readonly readerFn?: () => Promise<string>;
335
+ // Overrides the source lookup; production resolves XDG_DATA_HOME ?? ~/.local/share.
336
+ readonly authFilePath?: string;
337
+ }
338
+
339
+ // One provider's entry in auth.json, whatever shape that provider uses. The
340
+ // broker never interprets it — see buildOpenCodeProjection's "travels WHOLE".
341
+ interface OpenCodeProviderRecord {
342
+ [key: string]: unknown;
343
+ }
344
+
345
+ // The ONE provider OpenCode serves from a subscription rather than a metered
346
+ // API token. Named, because it is the whole reason credentialKindForRoute
347
+ // (runner-authority.ts) is provider-keyed instead of backend-keyed.
348
+ export const OPENCODE_OAUTH_PROVIDER = "openai";
349
+
350
+ export function resolveOpenCodeAuthPath(
351
+ env: Readonly<Record<string, string | undefined>> = process.env,
352
+ homeDir: string = homedir(),
353
+ ): string {
354
+ const dataHome = env.XDG_DATA_HOME;
355
+ const base =
356
+ dataHome !== undefined && dataHome.length > 0
357
+ ? dataHome
358
+ : path.join(homeDir, ".local", "share");
359
+ return path.join(base, "opencode", "auth.json");
360
+ }
361
+
362
+ export class OpenCodeAuthBroker implements CredentialBroker {
363
+ private readonly readerFn: () => Promise<string>;
364
+
365
+ constructor(options: OpenCodeAuthBrokerOptions = {}) {
366
+ if (options.readerFn !== undefined) {
367
+ this.readerFn = options.readerFn;
368
+ } else {
369
+ const authPath = options.authFilePath ?? resolveOpenCodeAuthPath();
370
+ this.readerFn = () => Bun.file(authPath).text();
371
+ }
372
+ }
373
+
374
+ async project(input: {
375
+ readonly sessionId: string;
376
+ readonly credentialRef: string;
377
+ readonly kind: CredentialKind;
378
+ readonly verifiedBinaryPath: string;
379
+ }): Promise<CredentialProjection> {
380
+ void input.sessionId;
381
+ void input.credentialRef;
382
+ void input.verifiedBinaryPath;
383
+ if (input.kind !== "opencode_chatgpt_oauth") {
384
+ throw new Error(
385
+ `Unsupported credential kind: ${input.kind} (OpenCodeAuthBroker projects only opencode_chatgpt_oauth)`,
386
+ );
387
+ }
388
+
389
+ let raw: string;
390
+ try {
391
+ raw = await this.readerFn();
392
+ } catch {
393
+ throw new CredentialProjectionError("source_read_failed");
394
+ }
395
+
396
+ let parsed: unknown;
397
+ try {
398
+ parsed = JSON.parse(raw);
399
+ } catch {
400
+ throw new CredentialProjectionError("malformed_payload");
401
+ }
402
+
403
+ if (typeof parsed !== "object" || parsed === null) {
404
+ throw new CredentialProjectionError("malformed_payload");
405
+ }
406
+
407
+ const record = (parsed as Record<string, unknown>).openai;
408
+ if (typeof record !== "object" || record === null) {
409
+ throw new CredentialProjectionError("missing_subscription_record");
410
+ }
411
+ // This kind promises ChatGPT OAuth specifically. An `openai` entry holding
412
+ // a pay-as-you-go API key is a different credential on different billing,
413
+ // and projecting it here would make the capability report's
414
+ // `billing.mode: "subscription"` a lie rather than a claim.
415
+ //
416
+ // #133 note: this lock is also what makes credentialKindForRoute's
417
+ // provider-keyed decision safe. That function does NOT read the store, so
418
+ // an `openai` entry holding an API key still resolves to this OAuth kind —
419
+ // and lands here, refused, rather than being silently routed metered. A
420
+ // bounded, stated limit, not a bug: the failure is loud and the fix is to
421
+ // name that provider differently in the routing config.
422
+ if ((record as Record<string, unknown>).type !== "oauth") {
423
+ throw new CredentialProjectionError("missing_subscription_record");
424
+ }
425
+
426
+ return buildOpenCodeProjection(
427
+ input.kind,
428
+ OPENCODE_OAUTH_PROVIDER,
429
+ record as OpenCodeProviderRecord,
430
+ );
431
+ }
432
+ }
433
+
434
+ // ONE builder for both OpenCode brokers. A third copy of the create+lstat+hash
435
+ // sequence is exactly the drift `openCodeProjectionLayout` already exists to
436
+ // prevent (pr-hero F001 on PR #80: two hand-maintained path lists, three
437
+ // directories built and never checked). The ONLY thing that differs between
438
+ // the OAuth route and the API-token route is which provider key the payload
439
+ // is written under, so that is the only thing parameterised.
440
+ function buildOpenCodeProjection(
441
+ kind: CredentialKind,
442
+ provider: string,
443
+ record: OpenCodeProviderRecord,
444
+ ): CredentialProjection {
445
+ const parentDir = path.join(tmpdir(), "prhero-cred-projections");
446
+ const layout = openCodeProjectionLayout(
447
+ path.join(parentDir, randomUUID()),
448
+ parentDir,
449
+ );
450
+
451
+ // Every level explicitly at 0700 — `recursive` alone lets an intermediate
452
+ // directory inherit the umask.
453
+ for (const dir of layout.directories) {
454
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
455
+ }
456
+
457
+ // The record travels WHOLE. On the OAuth route its access token expires
458
+ // (~10 days on the observed store) and the child renews it with the refresh
459
+ // token; a projection carrying only `access` would hand the child a
460
+ // credential it cannot rotate, and it would go stale mid-run with no way
461
+ // back. On the API-token route the same rule holds for a different reason:
462
+ // the store's own record shape is what OpenCode reads, and reconstructing a
463
+ // subset of it here would be a second, silently drifting schema.
464
+ const payload = `${JSON.stringify({ [provider]: record }, null, 2)}\n`;
465
+ writeFileSync(layout.authFile, payload, { mode: 0o600 });
466
+
467
+ // §6.1: lstat every guarded path — a pre-planted symlink anywhere in the
468
+ // chain means the credential, or a directory the child writes into,
469
+ // landed outside our control.
470
+ for (const component of layout.guarded) {
471
+ if (lstatSync(component).isSymbolicLink()) {
472
+ rmSync(layout.syntheticHome, { recursive: true, force: true });
473
+ throw new CredentialProjectionError("projection_layout_invalid");
474
+ }
475
+ }
476
+
477
+ const hasher = new Bun.CryptoHasher("sha256");
478
+ hasher.update(new TextEncoder().encode(payload));
479
+ const sha256 = hasher.digest("hex");
480
+
481
+ return {
482
+ projectionId: `cred-${randomUUID()}`,
483
+ kind,
484
+ syntheticHome: layout.syntheticHome,
485
+ syntheticConfigHome: layout.syntheticConfigHome,
486
+ syntheticTmp: layout.syntheticTmp,
487
+ env: {
488
+ HOME: layout.syntheticHome,
489
+ TMPDIR: layout.syntheticTmp,
490
+ // Pinned, not merely absent from the harness allowlist: OpenCode reads
491
+ // XDG_DATA_HOME first, so an inherited value would point the child
492
+ // straight back at the operator's real store.
493
+ XDG_DATA_HOME: layout.xdgDataHome,
494
+ XDG_CONFIG_HOME: layout.xdgConfigHome,
495
+ },
496
+ files: [{ path: layout.authFile, mode: 0o600, sha256 }],
497
+ destroy: async () => {
498
+ rmSync(layout.syntheticHome, { recursive: true, force: true });
499
+ },
500
+ };
501
+ }
502
+
503
+ // ---------------------------------------------------------------------------
504
+ // #133 §6.1: the metered provider API-token route, generic over ANY OpenCode
505
+ // provider. Ported from OpenCodeAuthBroker — same source file, same layout,
506
+ // same lstat defense — with two differences the KIND forces:
507
+ //
508
+ // 1. The provider is a CONSTRUCTOR argument, not a literal. OpenCode's
509
+ // auth.json is keyed by provider name and the operator may hold any
510
+ // number of them; nothing about this broker is zai-shaped.
511
+ // 2. `type === "api"` is required, the exact MIRROR of the OAuth broker's
512
+ // `type === "oauth"` lock. This kind promises a metered API token;
513
+ // projecting an OAuth record under it would make the capability report's
514
+ // `billing.mode: "metered"` wrong in the other direction — a subscription
515
+ // route gated, and charged, as if it spent cash per token.
516
+ //
517
+ // Projection shape proven live (2026-09-01, opencode 1.18.23): a synthetic
518
+ // HOME carrying only `{ <provider>: { type: "api", ... } }` is read as exactly
519
+ // that one credential, with the operator's sibling providers absent, on two
520
+ // different provider keys. Inference under that credential is NOT yet proven —
521
+ // that smoke is blocked on #137's pricing table.
522
+ // ---------------------------------------------------------------------------
523
+
524
+ // The provider name is interpolated into a JSON object key and compared
525
+ // against store keys, so it is constrained to a grammar that cannot be a path
526
+ // traversal, a prototype key, or anything requiring escaping.
527
+ const OPENCODE_PROVIDER_NAME = /^[a-z0-9][a-z0-9_-]*$/;
528
+
529
+ type OpenCodeApiRecordLookup =
530
+ | { readonly ok: true; readonly record: OpenCodeProviderRecord }
531
+ | {
532
+ readonly ok: false;
533
+ readonly failureClass: CredentialProjectionFailureClass;
534
+ };
535
+
536
+ // #280: the read+parse+validate sequence for ONE provider's `type: "api"`
537
+ // entry, shared by OpenCodeApiTokenBroker (below, fails loud on every
538
+ // outcome) and OpenCodeFreeBroker (fails loud on NONE of them — every
539
+ // `ok: false` collapses to the empty tree). Splitting this out is the same
540
+ // move buildOpenCodeProjection's header already made for the create+lstat+
541
+ // hash sequence: a third hand-maintained copy is exactly the drift that
542
+ // comment warns about, and here it would additionally let the two callers'
543
+ // validation silently diverge (e.g. one broker accepting a record shape the
544
+ // other refuses).
545
+ async function lookupOpenCodeApiRecord(
546
+ readerFn: () => Promise<string>,
547
+ provider: string,
548
+ ): Promise<OpenCodeApiRecordLookup> {
549
+ let raw: string;
550
+ try {
551
+ raw = await readerFn();
552
+ } catch {
553
+ return { ok: false, failureClass: "source_read_failed" };
554
+ }
555
+
556
+ let parsed: unknown;
557
+ try {
558
+ parsed = JSON.parse(raw);
559
+ } catch {
560
+ return { ok: false, failureClass: "malformed_payload" };
561
+ }
562
+
563
+ if (typeof parsed !== "object" || parsed === null) {
564
+ return { ok: false, failureClass: "malformed_payload" };
565
+ }
566
+
567
+ // Object.hasOwn, never a bare index — see OpenCodeApiTokenBroker's own note
568
+ // (pr-hero F001 lineage, PR #162): a bare index reaches Object.prototype.
569
+ if (!Object.hasOwn(parsed, provider)) {
570
+ return { ok: false, failureClass: "missing_provider_record" };
571
+ }
572
+ const record = (parsed as Record<string, unknown>)[provider];
573
+ if (typeof record !== "object" || record === null) {
574
+ return { ok: false, failureClass: "missing_provider_record" };
575
+ }
576
+ // The mirror of the OAuth broker's `type !== "oauth"` lock: this lookup
577
+ // promises an API token specifically, never an OAuth record.
578
+ if ((record as Record<string, unknown>).type !== "api") {
579
+ return { ok: false, failureClass: "missing_provider_record" };
580
+ }
581
+
582
+ return { ok: true, record: record as OpenCodeProviderRecord };
583
+ }
584
+
585
+ export class OpenCodeApiTokenBroker implements CredentialBroker {
586
+ private readonly provider: string;
587
+ private readonly readerFn: () => Promise<string>;
588
+
589
+ constructor(provider: string, options: OpenCodeAuthBrokerOptions = {}) {
590
+ // Fail loud at construction, not at first projection: a malformed
591
+ // provider name is a configuration defect, and discovering it mid-run
592
+ // costs a live step.
593
+ if (!OPENCODE_PROVIDER_NAME.test(provider)) {
594
+ throw new Error(
595
+ `Invalid OpenCode provider name: ${JSON.stringify(provider)} (expected ${OPENCODE_PROVIDER_NAME})`,
596
+ );
597
+ }
598
+ this.provider = provider;
599
+ if (options.readerFn !== undefined) {
600
+ this.readerFn = options.readerFn;
601
+ } else {
602
+ const authPath = options.authFilePath ?? resolveOpenCodeAuthPath();
603
+ this.readerFn = () => Bun.file(authPath).text();
604
+ }
605
+ }
606
+
607
+ async project(input: {
608
+ readonly sessionId: string;
609
+ readonly credentialRef: string;
610
+ readonly kind: CredentialKind;
611
+ readonly verifiedBinaryPath: string;
612
+ }): Promise<CredentialProjection> {
613
+ void input.sessionId;
614
+ void input.credentialRef;
615
+ void input.verifiedBinaryPath;
616
+ if (input.kind !== "provider_api_token") {
617
+ throw new Error(
618
+ `Unsupported credential kind: ${input.kind} (OpenCodeApiTokenBroker projects only provider_api_token)`,
619
+ );
620
+ }
621
+
622
+ // HONESTY about the hasOwn guard inside the shared lookup: with
623
+ // OPENCODE_PROVIDER_NAME as it stands, the only Object.prototype key that
624
+ // can even be a provider name is `constructor`, and its value is a
625
+ // FUNCTION — so the `typeof record !== "object"` check already refuses
626
+ // it, and removing the hasOwn guard breaks no test today (verified by
627
+ // mutation, 2026-09-01). It is the second lock, and it is the one that
628
+ // stays correct if the grammar is ever widened or the source stops being
629
+ // JSON.parse output. Keep both; do not read the passing suite as proof
630
+ // that line is exercised.
631
+ const lookup = await lookupOpenCodeApiRecord(this.readerFn, this.provider);
632
+ if (!lookup.ok) {
633
+ throw new CredentialProjectionError(lookup.failureClass);
634
+ }
635
+
636
+ return buildOpenCodeProjection(input.kind, this.provider, lookup.record);
637
+ }
638
+ }
639
+
640
+ // ---------------------------------------------------------------------------
641
+ // #182 → #280: the provider-free route — an OpenCode model the provider
642
+ // itself declares free at runtime (all cost leaves === 0, status active).
643
+ //
644
+ // #182's ORIGINAL invariant was "reads nothing, projects nothing" — sound
645
+ // for a per-token free model, wrong for a flat-fee API-key plan priced at
646
+ // $0 (zai-coding-plan): that provider still REQUIRES its key, so the empty
647
+ // tree left it running keyless against a provider that rejects the request.
648
+ // #280's relaxed invariant, and the reasoning behind each clause:
649
+ //
650
+ // 1. It projects THIS PROVIDER's own `type: "api"` record from auth.json,
651
+ // and ONLY that — never another provider's, never an OAuth record for
652
+ // the same provider name. The read+parse+validate is the exact same
653
+ // `lookupOpenCodeApiRecord` OpenCodeApiTokenBroker uses; the two brokers
654
+ // must never silently diverge on what counts as a usable record.
655
+ // 2. EVERY other outcome of that lookup — the file is absent, unreadable,
656
+ // malformed JSON, has no entry for this provider, or the entry is not
657
+ // `type: "api"` — collapses to the SAME empty 0700 tree #182 always
658
+ // produced (`files: []`, no auth file written at all). Deliberately NOT
659
+ // a fail-closed throw for the read/parse failures: a fresh machine or a
660
+ // Zen-only user has no auth.json for zai-coding-plan at all, and that is
661
+ // the common case this route exists to keep working, not an error to
662
+ // surface. #182's `source_read_failed` header note ("structurally
663
+ // unreachable") no longer holds — this route reads now — but its
664
+ // conclusion does: nothing about a missing or corrupt STORE should stop
665
+ // a free run, only a symlinked LAYOUT should (clause 3).
666
+ // 3. It MUST NEVER throw `missing_subscription_record`. harness.ts degrades
667
+ // exactly that class to the operator environment, and degrading a free
668
+ // route onto ambient credentials would be the failure this issue forbids
669
+ // (a free run silently spending a real token, or now, running under the
670
+ // WRONG provider's ambient key). Only fail-closed class: still
671
+ // `projection_layout_invalid` on a symlinked layout. Nothing else
672
+ // throws — the record lookup above never gets the chance to.
673
+ //
674
+ // Accepted cost (owner decision, #280, 2026-09-24): a model that flips from
675
+ // free to paid mid-run can spend on one attempt before the free-nonzero
676
+ // settlement rule fences the bucket — unchanged from #182, since billing
677
+ // stays keyed on `provider_free`/"free" regardless of what this broker
678
+ // projects. And an OpenCode Zen user with a stored `opencode` api key now
679
+ // runs Zen's free models with that key rather than keyless — accepted
680
+ // because it is strictly an upgrade (a working credential where none
681
+ // existed), never a downgrade.
682
+ // ---------------------------------------------------------------------------
683
+ export class OpenCodeFreeBroker implements CredentialBroker {
684
+ private readonly provider: string;
685
+ private readonly readerFn: () => Promise<string>;
686
+
687
+ constructor(provider: string, options: OpenCodeAuthBrokerOptions = {}) {
688
+ // Same grammar lock as OpenCodeApiTokenBroker, same reason: fail loud at
689
+ // construction, not mid-run, and the provider is interpolated into a
690
+ // JSON key by the shared lookup below.
691
+ if (!OPENCODE_PROVIDER_NAME.test(provider)) {
692
+ throw new Error(
693
+ `Invalid OpenCode provider name: ${JSON.stringify(provider)} (expected ${OPENCODE_PROVIDER_NAME})`,
694
+ );
695
+ }
696
+ this.provider = provider;
697
+ if (options.readerFn !== undefined) {
698
+ this.readerFn = options.readerFn;
699
+ } else {
700
+ const authPath = options.authFilePath ?? resolveOpenCodeAuthPath();
701
+ this.readerFn = () => Bun.file(authPath).text();
702
+ }
703
+ }
704
+
705
+ async project(input: {
706
+ readonly sessionId: string;
707
+ readonly credentialRef: string;
708
+ readonly kind: CredentialKind;
709
+ readonly verifiedBinaryPath: string;
710
+ }): Promise<CredentialProjection> {
711
+ void input.sessionId;
712
+ void input.credentialRef;
713
+ void input.verifiedBinaryPath;
714
+ if (input.kind !== "provider_free") {
715
+ throw new Error(
716
+ `Unsupported credential kind: ${input.kind} (OpenCodeFreeBroker projects only provider_free)`,
717
+ );
718
+ }
719
+
720
+ // Clause 1+2: a usable record projects; every other lookup outcome
721
+ // (including a thrown read/parse error) falls through to the empty tree
722
+ // below rather than propagating — `lookup.failureClass` is deliberately
723
+ // never inspected here.
724
+ const lookup = await lookupOpenCodeApiRecord(this.readerFn, this.provider);
725
+ if (lookup.ok) {
726
+ return buildOpenCodeProjection(input.kind, this.provider, lookup.record);
727
+ }
728
+
729
+ const parentDir = path.join(tmpdir(), "prhero-cred-projections");
730
+ const layout = openCodeProjectionLayout(
731
+ path.join(parentDir, randomUUID()),
732
+ parentDir,
733
+ );
734
+
735
+ // Every level explicitly at 0700 — `recursive` alone lets an intermediate
736
+ // directory inherit the umask. Same rule as buildOpenCodeProjection.
737
+ for (const dir of layout.directories) {
738
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
739
+ }
740
+
741
+ // §6.1: lstat every guarded path EXCEPT the auth file, which does not
742
+ // exist on this route by design. A pre-planted symlink anywhere in the
743
+ // chain means a directory the child writes into landed outside our
744
+ // control.
745
+ for (const component of [parentDir, ...layout.directories]) {
746
+ if (lstatSync(component).isSymbolicLink()) {
747
+ rmSync(layout.syntheticHome, { recursive: true, force: true });
748
+ throw new CredentialProjectionError("projection_layout_invalid");
749
+ }
750
+ }
751
+
752
+ return {
753
+ projectionId: `cred-${randomUUID()}`,
754
+ kind: input.kind,
755
+ syntheticHome: layout.syntheticHome,
756
+ syntheticConfigHome: layout.syntheticConfigHome,
757
+ syntheticTmp: layout.syntheticTmp,
758
+ env: {
759
+ HOME: layout.syntheticHome,
760
+ TMPDIR: layout.syntheticTmp,
761
+ // Pinned, not merely absent from the harness allowlist: OpenCode reads
762
+ // XDG_DATA_HOME first, so an inherited value would point the child
763
+ // straight back at the operator's real store.
764
+ XDG_DATA_HOME: layout.xdgDataHome,
765
+ XDG_CONFIG_HOME: layout.xdgConfigHome,
766
+ },
767
+ files: [],
768
+ destroy: async () => {
769
+ rmSync(layout.syntheticHome, { recursive: true, force: true });
770
+ },
771
+ };
772
+ }
773
+ }