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,535 @@
1
+ // D1-06: the OpenCode server the SDK client talks to, launched under pr-hero's
2
+ // own threat model instead of the SDK's convenience helper.
3
+ //
4
+ // WHY NOT `createOpencodeServer` from @opencode-ai/sdk. Its implementation is
5
+ // `launch("opencode", args, { env: { ...process.env, ... } })`, and both
6
+ // halves of that are disqualifying here:
7
+ //
8
+ // * it inherits the operator's ENTIRE environment, so the child would see
9
+ // the operator's real HOME and walk straight past the §6.1 credential
10
+ // projection — the projection would exist and protect nothing;
11
+ // * it resolves `opencode` off PATH, while §13 requires preflight and
12
+ // execution to use the same verified absolute binary.
13
+ //
14
+ // It also defaults to port 4096, a fixed port two concurrent reviews would
15
+ // collide on. This module asks for an ephemeral port and reads back the URL
16
+ // the server actually prints.
17
+
18
+ import type { CredentialKind } from "../execution/contracts";
19
+ import {
20
+ ACTIVE_SERVER_CLOSERS,
21
+ type SpawnedProcess,
22
+ serversShuttingDown,
23
+ } from "../execution/spawned-process";
24
+ import type { CredentialBroker } from "../security/credential-broker";
25
+ import { mcpConfigIsEmpty, type OpenCodeMcpConfig } from "./opencode-mcp";
26
+
27
+ // The line the server prints on startup, verified live against
28
+ // opencode 1.18.23: "opencode server listening on http://127.0.0.1:<port>".
29
+ const LISTENING_PREFIX = "opencode server listening";
30
+ const LISTENING_URL = /on\s+(https?:\/\/[^\s]+)/;
31
+
32
+ const DEFAULT_STARTUP_TIMEOUT_MS = 15_000;
33
+ // Same cascade shape as the CLI transport (§5.2): TERM, a bounded grace, then
34
+ // KILL. The numbers are smaller because a server that will not stop is not
35
+ // holding a paid generation — only a port.
36
+ const DEFAULT_TERM_GRACE_MS = 2_000;
37
+ const DEFAULT_KILL_REAP_MS = 2_000;
38
+
39
+ // A piped stream nobody reads is a time bomb: the OS pipe buffer fills at
40
+ // ~64 KiB and the child BLOCKS in write(), stalling the whole server with no
41
+ // signal to the caller. Both pipes therefore keep a reader for the child's
42
+ // entire life, not just for startup.
43
+ async function drainToNowhere(stream: unknown): Promise<void> {
44
+ try {
45
+ for await (const _chunk of stream as AsyncIterable<Uint8Array>) {
46
+ // Discarded on purpose — the point is to keep the pipe empty.
47
+ }
48
+ } catch {
49
+ // A closed or errored pipe needs no draining.
50
+ }
51
+ }
52
+
53
+ export interface OpenCodeServerHandle {
54
+ readonly url: string;
55
+ readonly pid: number;
56
+ // Free-tier gateway fix: the gateway-ask ids this handle's OWN launcher
57
+ // actually wrote into the server's `permission` config (sorted) — see
58
+ // `freeTierGatewayAsk` below and `launchOpenCodeServer`'s config assembly
59
+ // for where it is decided. opencode-client.ts's createSession reads this
60
+ // BACK before it ever deletes a `false` entry off the tools map for a
61
+ // denied id, so the deletion is only ever as safe as this field is honest.
62
+ //
63
+ // Optional, not required, by explicit scope decision: dozens of test
64
+ // fakes across the suite construct a bare `{url, pid, close}` literal for
65
+ // routes that never touch the free-tier gate, and turning every one of
66
+ // them into a required-field update would be unrelated churn far outside
67
+ // this fix. Absence is read as "this launcher attests nothing" by the
68
+ // check in createSession, which fails CLOSED on it — an unattested
69
+ // launcher can never satisfy a non-empty ask requirement, so an absent
70
+ // field is exactly as safe as one that is present and empty.
71
+ readonly gatewayAsk?: readonly string[];
72
+ close(): Promise<void>;
73
+ }
74
+
75
+ export interface LaunchOpenCodeServerOptions {
76
+ // Absolute and already verified by the caller. This module refuses a bare
77
+ // name rather than resolving one itself: resolution is where the binary is
78
+ // hashed, and a launcher that quietly accepted "opencode" would reintroduce
79
+ // exactly the PATH lookup §13 forbids.
80
+ readonly verifiedBinaryPath: string;
81
+ // The COMPLETE environment for the child. Passed through untouched — this
82
+ // module never merges process.env into it, which is the whole point. The ONE
83
+ // documented addition is `mcp` below, and it is a value pr-hero computed
84
+ // rather than one inherited from anywhere.
85
+ readonly env: Readonly<Record<string, string>>;
86
+ // #141: the run's MCP registry, translated from the Claude-shaped mcp.json
87
+ // the binding policy already gates. Delivered as `OPENCODE_CONFIG_CONTENT`
88
+ // at SPAWN, so the servers are connected from the server's first byte —
89
+ // there is then no window between "server up" and "MCP connected" for a
90
+ // prompt to fall into (the #128 race class). An empty registry delivers no
91
+ // config at all: parity with claude-code on a repo with no codegraph index,
92
+ // where the hunters run on read/grep/glob and pr-hero makes no claim about
93
+ // the child's tool channels.
94
+ readonly mcp?: OpenCodeMcpConfig;
95
+ // Free-tier gateway fix (opencode-client.ts's FREE_TIER_GATEWAY_TOOLS):
96
+ // gateway-required ids the calling session does NOT grant. Empty/undefined
97
+ // for every route but `provider_free` — opencode-client.ts's createSession
98
+ // is the only caller that ever populates it, gated on credentialKind, so a
99
+ // metered/OAuth route reaches this launcher exactly as it always has. See
100
+ // the WHY at the config assembly below for what each id gets instead of a
101
+ // tools-map `false`.
102
+ readonly freeTierGatewayAsk?: readonly string[];
103
+ readonly spawnFn?: typeof Bun.spawn;
104
+ // Injectable for offline tests; production signals the child by pid. Same
105
+ // shape as ClaudeCodeCliTransport's, so the two shutdown paths read alike.
106
+ readonly killFn?: (pid: number, signal?: string | number) => unknown;
107
+ readonly startupTimeoutMs?: number;
108
+ readonly termGraceMs?: number;
109
+ readonly killReapMs?: number;
110
+ readonly hostname?: string;
111
+ // Handed the server's own close right after spawn, before the startup wait:
112
+ // a signal in that window (up to startupTimeoutMs) must be able to stop a
113
+ // server that has not announced its URL yet.
114
+ readonly onSpawned?: (close: () => Promise<void>) => void;
115
+ }
116
+
117
+ export function openCodeServerArgv(
118
+ binaryPath: string,
119
+ hostname: string,
120
+ ): string[] {
121
+ return [
122
+ binaryPath,
123
+ "serve",
124
+ // No external plugins. Two reasons, and the second is the one that
125
+ // matters: it drops the plugin.added flood the probe recorded (45 of 71
126
+ // events for one prompt), and it keeps third-party plugin code out of a
127
+ // process holding a projected credential.
128
+ "--pure",
129
+ "--hostname",
130
+ hostname,
131
+ // Ephemeral, always. The URL is read back from stdout.
132
+ "--port",
133
+ "0",
134
+ ];
135
+ }
136
+
137
+ export async function launchOpenCodeServer(
138
+ options: LaunchOpenCodeServerOptions,
139
+ ): Promise<OpenCodeServerHandle> {
140
+ const {
141
+ verifiedBinaryPath,
142
+ env,
143
+ spawnFn = Bun.spawn,
144
+ killFn = process.kill,
145
+ startupTimeoutMs = DEFAULT_STARTUP_TIMEOUT_MS,
146
+ termGraceMs = DEFAULT_TERM_GRACE_MS,
147
+ killReapMs = DEFAULT_KILL_REAP_MS,
148
+ hostname = "127.0.0.1",
149
+ mcp,
150
+ freeTierGatewayAsk,
151
+ onSpawned,
152
+ } = options;
153
+
154
+ if (!verifiedBinaryPath.startsWith("/")) {
155
+ throw new Error(
156
+ `opencode server binary must be an absolute, verified path: ${verifiedBinaryPath}`,
157
+ );
158
+ }
159
+
160
+ // The projection, plus the run's own MCP registry when there is one. The
161
+ // config is READ from `OPENCODE_CONFIG_CONTENT` at startup, which is the
162
+ // mechanism the SDK's own helper uses (dist/server.js:15) and the one
163
+ // measured to work under `--pure` (#141 fact 1). Written here rather than by
164
+ // the caller so the "exactly the projected environment" rule keeps a single
165
+ // enforcement point.
166
+ //
167
+ // #157 (pr-157-8df2fca3-6): a hunter's tool call for a path OUTSIDE the
168
+ // reviewed worktree tripped OpenCode's `permission.asked` for
169
+ // `external_directory` twice in one run, and pr-hero never answers that
170
+ // prompt — the tool call sat blocked until the silence tripwire killed the
171
+ // attempt 150s later at $0. `permission.external_directory: "deny"` is
172
+ // delivered UNCONDITIONALLY (not gated on `mcp`, unlike the block below) so
173
+ // the provider refuses the read/write itself instead of asking and waiting
174
+ // forever. This tightens the §13 isolation threat model (CLAUDE.md rule
175
+ // 4); the client's own reject-on-ask handling (opencode-client.ts's
176
+ // "permission.asked" case) is defense in depth for whatever this config
177
+ // does not cover, never the primary control.
178
+ // Free-tier gateway fix (2026-09-26), scoped to `provider_free` alone by
179
+ // explicit OWNER decision: OpenCode's free catalogue 403s any turn whose
180
+ // tools map denies `bash` or `read` outright (the full observed matrix is
181
+ // on FREE_TIER_GATEWAY_TOOLS in opencode-client.ts). Every other route
182
+ // keeps sending those two `false` in the tools map as it always has, and
183
+ // `freeTierGatewayAsk` stays empty for it, so `gatewayAskPermission` below
184
+ // is `{}` and this object is BYTE IDENTICAL to before this change.
185
+ //
186
+ // For a `provider_free` route, opencode-client.ts's createSession keeps
187
+ // each denied id OFF the tools map's false list instead (the gateway sees
188
+ // a present, non-denied tool and admits the turn) and asks THIS config to
189
+ // mark it "ask" here. That is a real relaxation of the tools-map control,
190
+ // and it is safe only because isolation for these two ids moves entirely
191
+ // to a DIFFERENT control: OpenCode's own permission gate, backed by
192
+ // pr-hero's unconditional auto-reject on every `permission.asked` event
193
+ // (opencode-client.ts's "permission.asked" handler, a few sessions'
194
+ // worth of history below the #157 WHY right above this function). An
195
+ // "ask" that is never answered never executes — OpenCode blocks the tool
196
+ // call until it gets a reply, exactly like the `external_directory` case
197
+ // #157 already describes — so the auto-reject exists NOT to make the call
198
+ // succeed but to make it fail FAST: a rejected call costs one turn, an
199
+ // unanswered one costs the full 150s silence-tripwire stall #157 measured.
200
+ // The owner accepted this trade because the gateway refuses the stronger
201
+ // posture (a denied tool) outright; it is not this module improvising a
202
+ // weaker one on its own judgment.
203
+ const gatewayAskPermission: Record<string, "ask"> = {};
204
+ for (const tool of freeTierGatewayAsk ?? []) {
205
+ gatewayAskPermission[tool] = "ask";
206
+ }
207
+ // The handle's attestation (OpenCodeServerHandle.gatewayAsk): read back
208
+ // from what this function is ABOUT to write into `permission`, not echoed
209
+ // from the `freeTierGatewayAsk` argument — a duplicate in that argument
210
+ // must not inflate the attested set, and the attestation must describe
211
+ // this config, not this call's input.
212
+ const attestedGatewayAsk = Object.keys(gatewayAskPermission).sort();
213
+ const config: {
214
+ mcp?: OpenCodeMcpConfig;
215
+ // Widened to "ask" | "deny" rather than an intersection with
216
+ // Record<string, "ask">: an index signature applies to EVERY key,
217
+ // `external_directory` included, so a plain `Record<string, "ask">`
218
+ // would also demand `external_directory` be "ask" and reject "deny".
219
+ permission: { external_directory: "deny" } & Record<string, "ask" | "deny">;
220
+ } =
221
+ mcp === undefined || mcpConfigIsEmpty(mcp)
222
+ ? {
223
+ permission: {
224
+ external_directory: "deny",
225
+ ...gatewayAskPermission,
226
+ },
227
+ }
228
+ : {
229
+ mcp,
230
+ permission: {
231
+ external_directory: "deny",
232
+ ...gatewayAskPermission,
233
+ },
234
+ };
235
+ const childEnv: Record<string, string> = {
236
+ ...env,
237
+ OPENCODE_CONFIG_CONTENT: JSON.stringify(config),
238
+ };
239
+
240
+ const proc = spawnFn(openCodeServerArgv(verifiedBinaryPath, hostname), {
241
+ // EXACTLY the projected environment. Never `...process.env`.
242
+ env: childEnv,
243
+ stdout: "pipe",
244
+ stderr: "pipe",
245
+ stdin: "ignore",
246
+ }) as SpawnedProcess & { readonly pid: number };
247
+
248
+ // stderr is never parsed, so it is drained from the very first byte. It was
249
+ // piped and then never read at all, which is the same pipe-full stall as
250
+ // stdout with none of the startup logic to disguise it.
251
+ void drainToNowhere(proc.stderr);
252
+
253
+ // Memoized, not a boolean early return: a second caller (the projected
254
+ // wrapper after a startup failure already closed the server) must await the
255
+ // SAME stop, or it destroys the projection while the server is still alive.
256
+ let reaped = false;
257
+ void proc.exited.then(() => {
258
+ reaped = true;
259
+ });
260
+ let stopping: Promise<void> | undefined;
261
+ const close = (): Promise<void> => {
262
+ stopping ??= stop();
263
+ return stopping;
264
+ };
265
+ const stop = async (): Promise<void> => {
266
+ // A reaped pid can be recycled: never signal one.
267
+ if (reaped) return;
268
+ try {
269
+ killFn(proc.pid, "SIGTERM");
270
+ } catch {
271
+ // Already gone; nothing to escalate to.
272
+ }
273
+ const escalated = await Promise.race([
274
+ proc.exited.then(() => "exited" as const),
275
+ new Promise<"grace">((resolve) =>
276
+ setTimeout(() => resolve("grace"), termGraceMs),
277
+ ),
278
+ ]);
279
+ if (escalated === "grace") {
280
+ try {
281
+ killFn(proc.pid, "SIGKILL");
282
+ } catch {
283
+ // Already gone.
284
+ }
285
+ // BOUNDED reap. A child that does not die to SIGKILL is unreapable from
286
+ // here — it is stuck in uninterruptible state or already a zombie whose
287
+ // parent is elsewhere — and waiting on it forever would hang the
288
+ // caller's shutdown on a process nothing can influence. Same reasoning
289
+ // as the CLI transport's reap bound (§5.2).
290
+ await Promise.race([
291
+ proc.exited,
292
+ new Promise<void>((resolve) => setTimeout(resolve, killReapMs)),
293
+ ]);
294
+ }
295
+ };
296
+
297
+ onSpawned?.(close);
298
+
299
+ const url = await new Promise<string>((resolve, reject) => {
300
+ let settled = false;
301
+ const finish = (fn: () => void): void => {
302
+ if (settled) return;
303
+ settled = true;
304
+ clearTimeout(timer);
305
+ fn();
306
+ };
307
+
308
+ const timer = setTimeout(() => {
309
+ finish(() => {
310
+ void close();
311
+ reject(
312
+ new Error(
313
+ `opencode server did not announce a listening URL within ${startupTimeoutMs}ms`,
314
+ ),
315
+ );
316
+ });
317
+ }, startupTimeoutMs);
318
+
319
+ void proc.exited.then((code) => {
320
+ finish(() => {
321
+ reject(
322
+ new Error(`opencode server exited during startup (code ${code})`),
323
+ );
324
+ });
325
+ });
326
+
327
+ void (async () => {
328
+ // Accumulated across chunks on purpose: the announcement arrives split
329
+ // in practice, and a parser that only inspected whole chunks would miss
330
+ // a server that started perfectly well and then time out on it.
331
+ let buffered = "";
332
+ let announced = false;
333
+ const decoder = new TextDecoder();
334
+ try {
335
+ for await (const chunk of proc.stdout as AsyncIterable<Uint8Array>) {
336
+ // Once the URL is out, this loop stops PARSING but keeps READING:
337
+ // the server logs for the rest of its life, and a pipe with no
338
+ // reader fills and blocks the child in write().
339
+ if (announced) continue;
340
+ if (settled) {
341
+ announced = true;
342
+ continue;
343
+ }
344
+ buffered += decoder.decode(chunk, { stream: true });
345
+ // COMPLETE lines only. A partial one can match both the prefix and
346
+ // the URL pattern while the port is still arriving — "…127.0.0.1:6"
347
+ // parses cleanly and points the client at port 6. The trailing
348
+ // fragment stays buffered until its newline lands.
349
+ const lines = buffered.split("\n");
350
+ const complete = lines.slice(0, -1);
351
+ buffered = lines[lines.length - 1] ?? "";
352
+ for (const line of complete) {
353
+ if (!line.startsWith(LISTENING_PREFIX)) continue;
354
+ const match = line.match(LISTENING_URL);
355
+ if (match === null) {
356
+ finish(() => {
357
+ void close();
358
+ reject(
359
+ new Error(
360
+ `opencode server announced a line with no parseable URL: ${line}`,
361
+ ),
362
+ );
363
+ });
364
+ announced = true;
365
+ break;
366
+ }
367
+ finish(() => resolve(match[1]));
368
+ announced = true;
369
+ break;
370
+ }
371
+ }
372
+ } catch {
373
+ finish(() => {
374
+ void close();
375
+ reject(new Error("opencode server stdout ended before startup"));
376
+ });
377
+ }
378
+ })();
379
+ });
380
+
381
+ return { url, pid: proc.pid, gatewayAsk: attestedGatewayAsk, close };
382
+ }
383
+
384
+ // #149: the environment the server may inherit from pr-hero's own process.
385
+ //
386
+ // This list is deliberately NOT the harness's ENV_PASSTHROUGH, and the
387
+ // difference is the whole point. That list serves a claude-code child and
388
+ // carries ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN and CLAUDE_CODE_OAUTH_TOKEN.
389
+ // opencode reads ambient provider keys as credential SOURCES — measured live
390
+ // on 1.18.23: launching with an otherwise-projected env plus a fake
391
+ // ANTHROPIC_API_KEY connected the `anthropic` provider, and plus a fake
392
+ // OPENAI_API_KEY connected `openai`. Composing the server's env from the
393
+ // harness's list would therefore reintroduce, through the fix, the very leak
394
+ // #149 is about.
395
+ //
396
+ // So: operational keys only. Nothing here can name a credential or a home.
397
+ const SERVER_ENV_PASSTHROUGH: readonly string[] = [
398
+ // Not optional: the projection carries no PATH, and the measured-clean
399
+ // configuration included it. `{HOME}` alone was never measured.
400
+ "PATH",
401
+ "LANG",
402
+ "LC_ALL",
403
+ "TERM",
404
+ "HTTP_PROXY",
405
+ "HTTPS_PROXY",
406
+ "NO_PROXY",
407
+ "SSL_CERT_FILE",
408
+ "SSL_CERT_DIR",
409
+ ];
410
+
411
+ export function composeOpenCodeServerEnv(
412
+ base: Readonly<Record<string, string | undefined>>,
413
+ projectionEnv: Readonly<Record<string, string>>,
414
+ ): Record<string, string> {
415
+ const composed: Record<string, string> = {};
416
+ for (const key of SERVER_ENV_PASSTHROUGH) {
417
+ const value = base[key];
418
+ if (value !== undefined) composed[key] = value;
419
+ }
420
+ // Last, and unconditionally: HOME/TMPDIR/XDG_* are the projection's to own.
421
+ // An inherited value surviving here is the defect, not a fallback.
422
+ return { ...composed, ...projectionEnv };
423
+ }
424
+
425
+ export interface LaunchProjectedOpenCodeServerOptions
426
+ extends Omit<LaunchOpenCodeServerOptions, "env"> {
427
+ // The credential authority's broker for this backend. Defaulting one here
428
+ // would be a second source of truth beside runner-authority.ts, so the
429
+ // caller supplies the same instance the binding was resolved with.
430
+ readonly broker: CredentialBroker;
431
+ // #133: REQUIRED, and paired with `broker` above for the same reason it is
432
+ // not defaulted here. The kind is per-ROUTE now — an opencode route on any
433
+ // provider but `openai` runs on a metered API token — so a default in this
434
+ // file would be a second source of truth beside runner-authority.ts, and
435
+ // the wrong half of the pair would only surface at projection time inside a
436
+ // live run. Required drags every caller through tsc instead.
437
+ readonly credentialKind: CredentialKind;
438
+ // pr-hero's own environment, filtered through SERVER_ENV_PASSTHROUGH.
439
+ readonly baseEnv?: Readonly<Record<string, string | undefined>>;
440
+ }
441
+
442
+ // The server's env is its ENTIRE environment, and the server outlives every
443
+ // individual step, so the projection it runs under must outlive them too:
444
+ // one projection per SERVER, destroyed by the handle's close(). Handing the
445
+ // shared server a per-step projection would leave its HOME pointing at a
446
+ // directory deleted when that step settled, while siblings still used it.
447
+ export async function launchProjectedOpenCodeServer(
448
+ options: LaunchProjectedOpenCodeServerOptions,
449
+ ): Promise<OpenCodeServerHandle> {
450
+ const { broker, credentialKind, baseEnv = {}, ...launchOptions } = options;
451
+
452
+ const projection = await broker.project({
453
+ // Three of these four are voided by the OpenCode broker; `kind` is the one
454
+ // it reads. #133: it is no longer a constant. The kind is decided per
455
+ // route by runner-authority.ts's credentialKindForRoute, and this server
456
+ // is handed the one its binding resolved.
457
+ //
458
+ // SCOPE NOTE, not solved here: this server is ONE per backend and
459
+ // outlives every step, so a plan mixing an `openai` OAuth route with a
460
+ // `zai` API-token route needs two credentials behind one server. That
461
+ // case is refused upstream — the metered route has no pricing table yet,
462
+ // so the exact-binding gate blocks it per binding before anything
463
+ // launches (test/production-runtime.test.ts, "a plan mixing an OAuth
464
+ // provider and an API-token provider is refused per binding"). When #137
465
+ // prices those routes, this becomes reachable and needs a server per
466
+ // credential; until then it must fail LOUD, which it does — a broker
467
+ // handed the wrong kind refuses it by name.
468
+ sessionId: "opencode-server",
469
+ credentialRef: "opencode-auth",
470
+ kind: credentialKind,
471
+ verifiedBinaryPath: launchOptions.verifiedBinaryPath,
472
+ });
473
+
474
+ // The signal sweep already ran (during the `broker.project` await above, or
475
+ // before a relaunch): nothing would ever close a server armed now, so it is
476
+ // never launched and the projection does not outlive this call.
477
+ if (serversShuttingDown()) {
478
+ await projection.destroy();
479
+ throw new Error("opencode server launch refused: Crysk is shutting down");
480
+ }
481
+
482
+ // Registered for the signal path (spawned-process.ts closeAllServers)
483
+ // BEFORE the launch, so a signal during startup still stops the spawned
484
+ // server and destroys the projection. One memoized close serves every
485
+ // caller: a signal arriving while a normal close is in flight awaits that
486
+ // same close instead of finding nothing to wait for. It leaves the registry
487
+ // only once the projection is gone.
488
+ let stopServer: (() => Promise<void>) | undefined;
489
+ let closing: Promise<void> | undefined;
490
+ const close = (): Promise<void> => {
491
+ closing ??= (async () => {
492
+ try {
493
+ await stopServer?.();
494
+ } finally {
495
+ try {
496
+ await projection.destroy();
497
+ } finally {
498
+ ACTIVE_SERVER_CLOSERS.delete(close);
499
+ }
500
+ }
501
+ })();
502
+ return closing;
503
+ };
504
+ ACTIVE_SERVER_CLOSERS.add(close);
505
+
506
+ let handle: OpenCodeServerHandle;
507
+ try {
508
+ handle = await launchOpenCodeServer({
509
+ ...launchOptions,
510
+ env: composeOpenCodeServerEnv(baseEnv, projection.env),
511
+ onSpawned: (stop) => {
512
+ stopServer = stop;
513
+ },
514
+ });
515
+ } catch (error) {
516
+ // The client resets its launch promise on failure and will project again,
517
+ // so a projection abandoned here is a credential left on disk per retry.
518
+ await close();
519
+ throw error;
520
+ }
521
+
522
+ return {
523
+ url: handle.url,
524
+ pid: handle.pid,
525
+ // Carried through, not dropped: this function builds a FRESH handle
526
+ // object rather than returning `handle` itself (its `close` has to wrap
527
+ // `projection.destroy()`), and forgetting a field here silently loses
528
+ // it for every production caller — `defaultOpenCodeLaunchServer` and
529
+ // `openCodeLaunchServerFor` both go through this path, so a dropped
530
+ // `gatewayAsk` here would empty the attestation `createSession` reads
531
+ // in the ONE codepath production actually runs.
532
+ gatewayAsk: handle.gatewayAsk,
533
+ close,
534
+ };
535
+ }
@@ -0,0 +1,113 @@
1
+ // T5b: the CI-side adjudicator's record (odd/tasks/agent-first-ci.md, D5).
2
+ //
3
+ // A `/pr-hero recheck` run asks the adjudicator to rule on the author's latest
4
+ // `dismissed` reply to a blocking finding, and posts the ruling as a reply on the
5
+ // finding's thread. That reply is the only CI verdict the gate trusts, and only
6
+ // when all of these hold:
7
+ // - GitHub says the reply's author is CI_ADJUDICATOR_LOGIN. The marker's own
8
+ // text proves nothing, since anyone can type it;
9
+ // - its `reply=` names the comment id of the thread's LATEST triage reply, so a
10
+ // newer dismissal is pending again;
11
+ // - that triage reply is `dismissed`, and the verdict is `upheld` (D5: only a
12
+ // dismissal leaves the count; `deferred` and `misclassified` never do);
13
+ // - its `head=` is the head under review.
14
+ // A run under a token whose login is not CI_ADJUDICATOR_LOGIN posts replies the
15
+ // gate never trusts, so it fails closed: the finding stays counted.
16
+
17
+ import { MARKER_OPEN, matchMarkerPrefix } from "../brand";
18
+
19
+ export const ADJUDICATION_MARKER_PREFIX = `${MARKER_OPEN}adjudication `;
20
+
21
+ // The login GitHub stamps on comments posted with the workflow's GITHUB_TOKEN.
22
+ export const CI_ADJUDICATOR_LOGIN = "github-actions[bot]";
23
+
24
+ // The most adjudicator calls one run makes. A pending dismissal past the cap
25
+ // stays pending, still counted, and the next recheck takes it.
26
+ export const MAX_ADJUDICATIONS_PER_RUN = 5;
27
+
28
+ export type AdjudicationVerdict = "upheld" | "rejected" | "inconclusive";
29
+
30
+ const ADJUDICATION_VERDICTS: ReadonlySet<string> = new Set<AdjudicationVerdict>(
31
+ ["upheld", "rejected", "inconclusive"],
32
+ );
33
+
34
+ const FULL_SHA = /^[0-9a-f]{40}$/;
35
+ const COMMENT_ID = /^[1-9][0-9]{0,19}$/;
36
+
37
+ export interface AdjudicationMarker {
38
+ verdict: AdjudicationVerdict;
39
+ // The comment id of the author's triage reply this verdict rules on.
40
+ reply: number;
41
+ // The head the adjudicator read. A verdict counts only on that head: a push may
42
+ // change the code it ruled on, so a later head needs a new recheck.
43
+ head: string;
44
+ }
45
+
46
+ export function adjudicationMarker(marker: AdjudicationMarker): string {
47
+ return `${ADJUDICATION_MARKER_PREFIX}verdict=${marker.verdict} reply=${marker.reply} head=${marker.head} -->`;
48
+ }
49
+
50
+ // Parses only the first line, and returns null for anything malformed, the same
51
+ // discipline as parseTriageMarker (src/triage/triage.ts).
52
+ export function parseAdjudicationMarker(
53
+ body: string,
54
+ ): AdjudicationMarker | null {
55
+ const prefix = matchMarkerPrefix(body, ADJUDICATION_MARKER_PREFIX);
56
+ if (prefix === undefined) return null;
57
+ const firstLine = body.split("\n", 1)[0] ?? "";
58
+ if (!firstLine.endsWith(" -->")) return null;
59
+ const fields = firstLine.slice(
60
+ prefix.length,
61
+ firstLine.length - " -->".length,
62
+ );
63
+ const parts = new Map<string, string>();
64
+ for (const token of fields.split(" ")) {
65
+ if (token.length === 0) continue;
66
+ const eq = token.indexOf("=");
67
+ if (eq === -1) return null;
68
+ const key = token.slice(0, eq);
69
+ if (parts.has(key)) return null;
70
+ parts.set(key, token.slice(eq + 1));
71
+ }
72
+ if (parts.size !== 3) return null;
73
+ const verdict = parts.get("verdict");
74
+ const reply = parts.get("reply");
75
+ const head = parts.get("head");
76
+ if (verdict === undefined || !ADJUDICATION_VERDICTS.has(verdict)) return null;
77
+ if (reply === undefined || !COMMENT_ID.test(reply)) return null;
78
+ if (head === undefined || !FULL_SHA.test(head)) return null;
79
+ const replyId = Number(reply);
80
+ if (!Number.isSafeInteger(replyId)) return null;
81
+ return {
82
+ verdict: verdict as AdjudicationVerdict,
83
+ reply: replyId,
84
+ head,
85
+ };
86
+ }
87
+
88
+ // One pending dismissal the adjudicator rules on.
89
+ export interface AdjudicationSubject {
90
+ priorId: string;
91
+ // The finding's own review comment: the thread the verdict is posted on.
92
+ threadId: number;
93
+ // The author's `dismissed` reply the verdict names.
94
+ replyId: number;
95
+ sev: string;
96
+ locs: readonly string[];
97
+ claim: string;
98
+ // The author's argument: the triage reply's body below its marker line.
99
+ argument: string;
100
+ }
101
+
102
+ export interface AdjudicationOutcome {
103
+ priorId: string;
104
+ threadId: number;
105
+ replyId: number;
106
+ verdict: AdjudicationVerdict;
107
+ // path:line citations the adjudicator gave. Empty when it failed.
108
+ evidence: string[];
109
+ // Set when no ruling exists: the step failed or timed out, the argument forged
110
+ // the nonce, or no refuter is configured. The verdict is then "inconclusive" and
111
+ // nothing is posted, so the dismissal stays pending and a later recheck rules on it.
112
+ failed?: true;
113
+ }