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
package/src/updater.ts ADDED
@@ -0,0 +1,836 @@
1
+ import { spawn } from "node:child_process";
2
+ import crypto from "node:crypto";
3
+ import {
4
+ chmodSync,
5
+ copyFileSync,
6
+ existsSync,
7
+ mkdirSync,
8
+ readFileSync,
9
+ renameSync,
10
+ rmSync,
11
+ symlinkSync,
12
+ writeFileSync,
13
+ writeSync,
14
+ } from "node:fs";
15
+ import { open, rm } from "node:fs/promises";
16
+ import os from "node:os";
17
+ import path from "node:path";
18
+ import {
19
+ detectAgentEnvironments,
20
+ registerMcpServer,
21
+ syncSkills,
22
+ } from "./agent-env";
23
+ import { type AssetMode, resolveEngineAssets, selfInvocation } from "./assets";
24
+ import { BIN_NAME, LEGACY_BIN_NAME } from "./brand";
25
+ import { LEGACY_HOME_DIR_NAME, resolveHomeDir } from "./brand-paths";
26
+ import { loadGlobalConfigLayer } from "./config/config";
27
+ import { runDoctor } from "./doctor";
28
+ import { prheroLayout } from "./home-preflight";
29
+ import { type RoutingConfig, routingNeedsOpenCodeSdk } from "./model/routing";
30
+ import {
31
+ readInstalledOpenCodeSdkVersion,
32
+ SUPPORTED_OPENCODE_SDK_VERSION,
33
+ } from "./transport-registry";
34
+
35
+ export const PRHERO_GITHUB_REPO = "cryskai/crysk";
36
+
37
+ export type InstallMethodKind = "standalone" | "package_manager" | "source";
38
+
39
+ export type InstallMethod =
40
+ | { kind: "standalone"; binaryPath: string }
41
+ | { kind: "package_manager"; manager: "npm" | "bun" }
42
+ | { kind: "source" };
43
+
44
+ export interface DetectInstallMethodOptions {
45
+ execPath?: string;
46
+ home?: string;
47
+ version?: string;
48
+ isDev?: boolean;
49
+ exists?: (p: string) => boolean;
50
+ }
51
+
52
+ export function detectInstallMethod(
53
+ options: DetectInstallMethodOptions = {},
54
+ ): InstallMethod {
55
+ const home = options.home ?? os.homedir();
56
+ const execPath = options.execPath ?? process.execPath;
57
+ const version = options.version ?? "0.3.0";
58
+ const exists = options.exists ?? existsSync;
59
+
60
+ const isSource =
61
+ options.isDev !== undefined
62
+ ? options.isDev
63
+ : version === "dev" ||
64
+ (exists("./src/cli.ts") &&
65
+ !execPath.includes(".crysk/bin") &&
66
+ !execPath.includes(".prhero/bin"));
67
+
68
+ if (isSource) {
69
+ return { kind: "source" };
70
+ }
71
+
72
+ // Either home name: a binary installed before the rename lives under
73
+ // ~/.prhero/bin even when a ~/.crysk now exists beside it.
74
+ const standaloneBinDirs = [
75
+ path.join(resolveHomeDir(home, exists), "bin"),
76
+ path.join(home, LEGACY_HOME_DIR_NAME, "bin"),
77
+ ];
78
+ if (
79
+ standaloneBinDirs.some(
80
+ (dir) =>
81
+ execPath.startsWith(dir) ||
82
+ path.resolve(execPath).startsWith(path.resolve(dir)),
83
+ )
84
+ ) {
85
+ return { kind: "standalone", binaryPath: execPath };
86
+ }
87
+
88
+ return {
89
+ kind: "package_manager",
90
+ manager: execPath.includes("bun") ? "bun" : "npm",
91
+ };
92
+ }
93
+
94
+ export interface DetectShadowInstallsOptions {
95
+ currentBinary: string;
96
+ which?: (bin: string) => Promise<string[]> | string[];
97
+ }
98
+
99
+ export async function detectShadowInstalls(
100
+ options: DetectShadowInstallsOptions,
101
+ ): Promise<string[]> {
102
+ const which =
103
+ options.which ??
104
+ (async (bin: string) => {
105
+ const found = Bun.which(bin);
106
+ return found ? [found] : [];
107
+ });
108
+
109
+ // Both names: a crysk upgrade is shadowed by an old pr-hero earlier on PATH
110
+ // just as surely as by another crysk.
111
+ const found = [
112
+ ...(await which(BIN_NAME)),
113
+ ...(await which(LEGACY_BIN_NAME)),
114
+ ].map((p) => path.resolve(p));
115
+
116
+ // The install's own pair (crysk and its pr-hero link, side by side) is one
117
+ // install, not two.
118
+ const currentDir = path.dirname(path.resolve(options.currentBinary));
119
+ const own = new Set([
120
+ path.resolve(options.currentBinary),
121
+ path.join(currentDir, BIN_NAME),
122
+ path.join(currentDir, LEGACY_BIN_NAME),
123
+ ]);
124
+
125
+ return [...new Set(found)].filter((p) => !own.has(p));
126
+ }
127
+
128
+ export interface UpgradeCheckCache {
129
+ checked_at: string;
130
+ current_version: string;
131
+ latest_version: string;
132
+ reconciled_version?: string;
133
+ release_url?: string;
134
+ changelog?: string;
135
+ }
136
+
137
+ export function isCheckCacheFresh(
138
+ cache?: UpgradeCheckCache,
139
+ nowMs = Date.now(),
140
+ ttlMs = 24 * 3600 * 1000,
141
+ ): boolean {
142
+ if (!cache?.checked_at) return false;
143
+ const checkedAtMs = Date.parse(cache.checked_at);
144
+ if (Number.isNaN(checkedAtMs)) return false;
145
+ return nowMs - checkedAtMs < ttlMs;
146
+ }
147
+
148
+ export function readUpgradeCache(
149
+ cachePath: string,
150
+ options: {
151
+ readFile?: (p: string) => string | undefined;
152
+ exists?: (p: string) => boolean;
153
+ } = {},
154
+ ): UpgradeCheckCache | undefined {
155
+ const readFile =
156
+ options.readFile ??
157
+ ((p: string) => {
158
+ try {
159
+ return readFileSync(p, "utf-8");
160
+ } catch {
161
+ return undefined;
162
+ }
163
+ });
164
+ const exists =
165
+ options.exists ??
166
+ (options.readFile ? (p: string) => readFile(p) !== undefined : existsSync);
167
+
168
+ if (!exists(cachePath)) return undefined;
169
+ try {
170
+ const raw = readFile(cachePath);
171
+ if (!raw) return undefined;
172
+ return JSON.parse(raw);
173
+ } catch {
174
+ return undefined;
175
+ }
176
+ }
177
+
178
+ export function writeUpgradeCache(
179
+ cachePath: string,
180
+ cache: UpgradeCheckCache,
181
+ options: {
182
+ writeFile?: (p: string, content: string) => void;
183
+ mkdir?: (p: string, opts?: { recursive?: boolean }) => void;
184
+ } = {},
185
+ ): void {
186
+ const writeFile =
187
+ options.writeFile ??
188
+ ((p: string, c: string) => {
189
+ mkdirSync(path.dirname(p), { recursive: true });
190
+ writeFileSync(p, c, "utf-8");
191
+ });
192
+
193
+ writeFile(cachePath, `${JSON.stringify(cache, null, 2)}\n`);
194
+ }
195
+
196
+ export interface UpgradePlan {
197
+ action:
198
+ | "upgrade_standalone"
199
+ | "upgrade_package_manager"
200
+ | "noop_source"
201
+ | "up_to_date";
202
+ currentVersion: string;
203
+ targetVersion: string;
204
+ targetBinary?: string;
205
+ // The pr-hero name, kept beside targetBinary as a link for one version.
206
+ aliasBinary?: string;
207
+ tempBinary?: string;
208
+ bakBinary?: string;
209
+ downloadUrl?: string;
210
+ // The same bytes under the pre-rename asset name, for a release made before
211
+ // the rename (it has no crysk-<target> asset).
212
+ legacyDownloadUrl?: string;
213
+ checksumsUrl?: string;
214
+ steps: string[];
215
+ message?: string;
216
+ }
217
+
218
+ export interface PlanUpgradeOptions {
219
+ installMethod: InstallMethod;
220
+ currentVersion: string;
221
+ targetVersion: string;
222
+ home?: string;
223
+ platform?: string;
224
+ arch?: string;
225
+ }
226
+
227
+ export async function planUpgrade(
228
+ options: PlanUpgradeOptions,
229
+ ): Promise<UpgradePlan> {
230
+ const { installMethod, currentVersion, targetVersion } = options;
231
+
232
+ if (installMethod.kind === "source") {
233
+ return {
234
+ action: "noop_source",
235
+ currentVersion,
236
+ targetVersion,
237
+ steps: [],
238
+ message:
239
+ "Running from source checkout / development mode. Use git pull to update.",
240
+ };
241
+ }
242
+
243
+ if (currentVersion === targetVersion) {
244
+ return {
245
+ action: "up_to_date",
246
+ currentVersion,
247
+ targetVersion,
248
+ steps: ["reconcile"],
249
+ message: `Crysk is already up to date (v${currentVersion}).`,
250
+ };
251
+ }
252
+
253
+ if (installMethod.kind === "standalone") {
254
+ // Always installed as `crysk` beside whichever name is running: a legacy
255
+ // install (running as pr-hero) gains crysk, and pr-hero becomes its link.
256
+ const binDir = path.dirname(installMethod.binaryPath);
257
+ const targetBinary = path.join(binDir, BIN_NAME);
258
+ const aliasBinary = path.join(binDir, LEGACY_BIN_NAME);
259
+ const rand = crypto.randomBytes(4).toString("hex");
260
+ const tempBinary = path.join(binDir, `${BIN_NAME}.tmp.${rand}`);
261
+ const bakBinary = `${targetBinary}.bak`;
262
+
263
+ const osName =
264
+ (options.platform ?? os.platform()) === "darwin" ? "darwin" : "linux";
265
+ const rawArch = options.arch ?? os.arch();
266
+ const archName =
267
+ rawArch === "arm64" || rawArch === "aarch64" ? "arm64" : "x64";
268
+ const target = `${osName}-${archName}`;
269
+
270
+ const releaseBase = `https://github.com/${PRHERO_GITHUB_REPO}/releases/download/v${targetVersion}`;
271
+ const downloadUrl = `${releaseBase}/${BIN_NAME}-${target}`;
272
+ const legacyDownloadUrl = `${releaseBase}/${LEGACY_BIN_NAME}-${target}`;
273
+ const checksumsUrl = `${releaseBase}/SHA256SUMS`;
274
+
275
+ return {
276
+ action: "upgrade_standalone",
277
+ currentVersion,
278
+ targetVersion,
279
+ targetBinary,
280
+ aliasBinary,
281
+ tempBinary,
282
+ bakBinary,
283
+ downloadUrl,
284
+ legacyDownloadUrl,
285
+ checksumsUrl,
286
+ steps: [
287
+ `Download ${downloadUrl} (or ${legacyDownloadUrl} for a release made before the rename) to ${tempBinary}`,
288
+ `Verify SHA256 against ${checksumsUrl}`,
289
+ `Preserve previous binary as ${bakBinary}`,
290
+ `Atomically replace ${targetBinary}`,
291
+ `Keep ${aliasBinary} working as a link to ${targetBinary}`,
292
+ "Reconcile agent skills, MCP registrations, and SQLite migrations",
293
+ ],
294
+ };
295
+ }
296
+
297
+ return {
298
+ action: "upgrade_package_manager",
299
+ currentVersion,
300
+ targetVersion,
301
+ steps: [
302
+ `Run ${installMethod.manager} install -g crysk@latest`,
303
+ "Reconcile agent skills, MCP registrations, and SQLite migrations",
304
+ ],
305
+ };
306
+ }
307
+
308
+ interface DownloadedBinary {
309
+ bytes: ArrayBuffer;
310
+ // The release asset the bytes came from: the name its SHA256SUMS line carries.
311
+ assetName: string;
312
+ }
313
+
314
+ // Downloads the binary a standalone plan names and verifies it against the
315
+ // SHA256SUMS line of the asset actually fetched. crysk-<target> first; only a
316
+ // 404 falls back to pr-hero-<target> (a release made before the rename). Any
317
+ // other failure is a real failure, not a reason to try another name.
318
+ export async function downloadReleaseBinary(
319
+ plan: UpgradePlan,
320
+ fetchFn: (url: string) => Promise<Response> = fetch,
321
+ ): Promise<DownloadedBinary> {
322
+ const { downloadUrl, legacyDownloadUrl, checksumsUrl } = plan;
323
+ if (!downloadUrl || !legacyDownloadUrl || !checksumsUrl) {
324
+ throw new Error("Incomplete standalone upgrade plan.");
325
+ }
326
+
327
+ let assetUrl = downloadUrl;
328
+ let resp = await fetchFn(assetUrl);
329
+ if (resp.status === 404) {
330
+ assetUrl = legacyDownloadUrl;
331
+ resp = await fetchFn(assetUrl);
332
+ if (resp.status === 404) {
333
+ throw new Error(
334
+ `Failed to download the ${BIN_NAME} binary: neither ${path.basename(downloadUrl)} nor ${path.basename(legacyDownloadUrl)} is on this release.`,
335
+ );
336
+ }
337
+ }
338
+ if (!resp.ok) {
339
+ throw new Error(`Failed to download ${BIN_NAME} binary from ${assetUrl}`);
340
+ }
341
+ const bytes = await resp.arrayBuffer();
342
+
343
+ const sumsResp = await fetchFn(checksumsUrl);
344
+ if (!sumsResp.ok) {
345
+ throw new Error(`Failed to download SHA256SUMS from ${checksumsUrl}`);
346
+ }
347
+ const assetName = path.basename(assetUrl);
348
+ const actualHash = crypto
349
+ .createHash("sha256")
350
+ .update(Buffer.from(bytes))
351
+ .digest("hex");
352
+ // sha256sum's own format: `<hash> <name>`, `*` before the name in binary
353
+ // mode. Matched on the name exactly so one asset's line never vouches for
354
+ // another's bytes.
355
+ const verified = (await sumsResp.text()).split("\n").some((line) => {
356
+ const [hash, name] = line.trim().split(/\s+/);
357
+ return name?.replace(/^\*/, "") === assetName && hash === actualHash;
358
+ });
359
+ if (!verified) {
360
+ throw new Error(`SHA256 checksum verification failed for ${assetName}!`);
361
+ }
362
+ return { bytes, assetName };
363
+ }
364
+
365
+ // A binary that does not answer --help within the limit fails its smoke and is
366
+ // killed: an upgrade must never hang on the binary it is about to install.
367
+ const SMOKE_TIMEOUT_MS = 30_000;
368
+
369
+ async function smokeBinary(
370
+ bin: string,
371
+ timeoutMs = SMOKE_TIMEOUT_MS,
372
+ ): Promise<boolean> {
373
+ try {
374
+ const proc = Bun.spawn([bin, "--help"], {
375
+ stdout: "ignore",
376
+ stderr: "ignore",
377
+ });
378
+ let timer: ReturnType<typeof setTimeout> | undefined;
379
+ const timedOut = new Promise<"timeout">((resolve) => {
380
+ timer = setTimeout(() => resolve("timeout"), timeoutMs);
381
+ });
382
+ const outcome = await Promise.race([proc.exited, timedOut]);
383
+ clearTimeout(timer);
384
+ if (outcome === "timeout") {
385
+ proc.kill("SIGKILL");
386
+ return false;
387
+ }
388
+ return outcome === 0;
389
+ } catch {
390
+ return false;
391
+ }
392
+ }
393
+
394
+ type InstallStandaloneResult =
395
+ | {
396
+ status: "installed";
397
+ alias: "symlink" | "copy" | "failed";
398
+ aliasError?: string;
399
+ }
400
+ | { status: "rolled_back" };
401
+
402
+ // Smoke-tests the verified bytes where they were downloaded, and only then swaps
403
+ // them in as the plan's crysk binary and points pr-hero at it. A failed or hung
404
+ // smoke removes the download and touches nothing installed, so there is never a
405
+ // moment when an unverified binary sits at the installed path.
406
+ export async function installStandaloneBinary(
407
+ plan: UpgradePlan,
408
+ bytes: Uint8Array,
409
+ options: {
410
+ smoke?: (bin: string) => Promise<boolean>;
411
+ smokeTimeoutMs?: number;
412
+ } = {},
413
+ ): Promise<InstallStandaloneResult> {
414
+ const { targetBinary, aliasBinary, tempBinary, bakBinary } = plan;
415
+ if (!targetBinary || !aliasBinary || !tempBinary || !bakBinary) {
416
+ throw new Error("Incomplete standalone upgrade plan.");
417
+ }
418
+ const smoke =
419
+ options.smoke ??
420
+ ((bin: string) => smokeBinary(bin, options.smokeTimeoutMs));
421
+
422
+ // A .bak left by an interrupted upgrade is the last good binary when the
423
+ // target itself is gone: put it back first, so a failed smoke below still
424
+ // leaves a working install. Otherwise the .bak is stale.
425
+ if (!existsSync(targetBinary) && existsSync(bakBinary)) {
426
+ renameSync(bakBinary, targetBinary);
427
+ } else {
428
+ rmSync(bakBinary, { force: true });
429
+ }
430
+
431
+ await Bun.write(tempBinary, bytes);
432
+ chmodSync(tempBinary, 0o755);
433
+ if (!(await smoke(tempBinary))) {
434
+ rmSync(tempBinary, { force: true });
435
+ return { status: "rolled_back" };
436
+ }
437
+
438
+ const hadPrevious = existsSync(targetBinary);
439
+ if (hadPrevious) renameSync(targetBinary, bakBinary);
440
+ renameSync(tempBinary, targetBinary);
441
+ rmSync(bakBinary, { force: true });
442
+
443
+ // crysk is installed and verified; the alias is a convenience on top, so a
444
+ // failure there is reported, never thrown half-way through the upgrade.
445
+ try {
446
+ return { status: "installed", alias: linkAlias(targetBinary, aliasBinary) };
447
+ } catch (err) {
448
+ return {
449
+ status: "installed",
450
+ alias: "failed",
451
+ aliasError: (err as Error).message,
452
+ };
453
+ }
454
+ }
455
+
456
+ // pr-hero -> crysk, replacing whatever pr-hero was (the old binary, on a legacy
457
+ // install). Built beside the alias and renamed over it, so the name never
458
+ // stops resolving mid-swap. A relative link keeps the pair movable together. A
459
+ // filesystem that refuses symlinks gets a copy instead; that copy goes stale on
460
+ // the next upgrade unless this runs again, which it does on every upgrade.
461
+ function linkAlias(target: string, alias: string): "symlink" | "copy" {
462
+ const staged = `${alias}.new.${process.pid}`;
463
+ rmSync(staged, { force: true });
464
+ try {
465
+ symlinkSync(path.basename(target), staged);
466
+ renameSync(staged, alias);
467
+ return "symlink";
468
+ } catch {
469
+ rmSync(staged, { force: true });
470
+ // The copy fallback can fail too (ENOSPC, a dir in the way): the staged file
471
+ // goes either way, so no retry leaves an orphan behind.
472
+ try {
473
+ copyFileSync(target, staged);
474
+ chmodSync(staged, 0o755);
475
+ renameSync(staged, alias);
476
+ return "copy";
477
+ } finally {
478
+ rmSync(staged, { force: true });
479
+ }
480
+ }
481
+ }
482
+
483
+ export interface OpenCodeSdkSpawnResult {
484
+ code: number;
485
+ stderr: string;
486
+ }
487
+
488
+ export interface ReconcileUpgradeOptions {
489
+ home?: string;
490
+ syncSkills?: () => Promise<{ synced: string[]; errors: string[] }>;
491
+ verifyMcp?: () => Promise<{ ok: boolean }>;
492
+ migrateStore?: () => Promise<{ ok: boolean; version?: number }>;
493
+ reloadDaemons?: () => Promise<{ reloaded: string[] }>;
494
+ // Injected so the default installer, which spawns npm or bun, never runs
495
+ // in a test that only cares about the other reconcile steps.
496
+ ensureOpenCodeSdk?: () => Promise<void>;
497
+ runDoctorCheck?: () => Promise<{ overall: string }>;
498
+ readSdkVersion?: () => Promise<string | undefined>;
499
+ // Injected so `bun test` (always `dev`) can exercise the compiled reader.
500
+ // Omitted mode is the only path that calls detectAssetMode().
501
+ assetMode?: AssetMode;
502
+ which?: (bin: string) => string | null;
503
+ spawnInstaller?: (argv: readonly string[]) => Promise<OpenCodeSdkSpawnResult>;
504
+ }
505
+
506
+ // npm when it is on PATH; otherwise bun. Neither is an error, not a spawn.
507
+ // Bun's `add` accepts `--ignore-scripts` (dependency scripts are never run;
508
+ // project lifecycle scripts are skipped) and `--cwd`, so the spec lands in
509
+ // the product home rather than the caller's cwd.
510
+ export function selectOpenCodeSdkInstaller(input: {
511
+ npmPath: string | null;
512
+ bunPath: string | null;
513
+ layoutDir: string;
514
+ }): readonly string[] {
515
+ const spec = `@opencode-ai/sdk@${SUPPORTED_OPENCODE_SDK_VERSION}`;
516
+ if (input.npmPath) {
517
+ return [
518
+ input.npmPath,
519
+ "install",
520
+ "--ignore-scripts",
521
+ "--no-fund",
522
+ "--no-audit",
523
+ "--prefix",
524
+ input.layoutDir,
525
+ spec,
526
+ ];
527
+ }
528
+ if (input.bunPath) {
529
+ return [
530
+ input.bunPath,
531
+ "add",
532
+ "--exact",
533
+ "--ignore-scripts",
534
+ "--cwd",
535
+ input.layoutDir,
536
+ spec,
537
+ ];
538
+ }
539
+ throw new Error(
540
+ "neither npm nor bun is on PATH. Run crysk upgrade --reconcile after installing npm or bun.",
541
+ );
542
+ }
543
+
544
+ function commandOnPath(bin: string | null | undefined): string | null {
545
+ if (typeof bin !== "string" || bin.trim() === "") return null;
546
+ return bin;
547
+ }
548
+
549
+ // Not watch.lock. That file is held for a whole watcher review; this one
550
+ // only covers the install, so a second reconcile cannot npm-install the
551
+ // same prefix while the first is still writing it.
552
+ function openCodeSdkInstallLockPath(home: string): string {
553
+ return path.join(prheroLayout(home).dir, "opencode-sdk.lock");
554
+ }
555
+
556
+ function liveLockPid(lockPath: string): number | null {
557
+ if (!existsSync(lockPath)) return null;
558
+ const pid = Number(readFileSync(lockPath, "utf8").trim());
559
+ if (!Number.isInteger(pid) || pid <= 0) return null;
560
+ try {
561
+ process.kill(pid, 0);
562
+ return pid;
563
+ } catch (error) {
564
+ return (error as NodeJS.ErrnoException).code === "EPERM" ? pid : null;
565
+ }
566
+ }
567
+
568
+ async function withOpenCodeSdkInstallLock(
569
+ home: string,
570
+ work: () => Promise<void>,
571
+ ): Promise<void> {
572
+ const lockPath = openCodeSdkInstallLockPath(home);
573
+ mkdirSync(path.dirname(lockPath), { recursive: true });
574
+ for (let attempt = 0; attempt < 2; attempt++) {
575
+ let handle: Awaited<ReturnType<typeof open>>;
576
+ try {
577
+ handle = await open(lockPath, "wx");
578
+ } catch (error) {
579
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
580
+ const holder = liveLockPid(lockPath);
581
+ if (holder !== null) {
582
+ throw new Error(
583
+ `OpenCode SDK install is already running (pid ${holder}). ` +
584
+ "Run crysk upgrade --reconcile after it finishes.",
585
+ );
586
+ }
587
+ await rm(lockPath, { force: true });
588
+ continue;
589
+ }
590
+ try {
591
+ // Synchronous: an awaited write leaves the file empty, and liveLockPid
592
+ // treats an empty file as a dead holder and deletes it.
593
+ writeSync(handle.fd, `${process.pid}\n`);
594
+ await work();
595
+ return;
596
+ } finally {
597
+ await handle.close();
598
+ await rm(lockPath, { force: true });
599
+ }
600
+ }
601
+ throw new Error(
602
+ "OpenCode SDK install is already running. " +
603
+ "Run crysk upgrade --reconcile after it finishes.",
604
+ );
605
+ }
606
+
607
+ // Same bound as installSystemTool's npm install. A registry fetch can be
608
+ // slow; a child that never exits must not pin reconcile. The message omits
609
+ // argv: `--prefix` carries the product home.
610
+ export const OPENCODE_SDK_INSTALL_TIMEOUT_MS = 300_000;
611
+
612
+ export function spawnOpenCodeSdkInstaller(
613
+ argv: readonly string[],
614
+ timeoutMs = OPENCODE_SDK_INSTALL_TIMEOUT_MS,
615
+ ): Promise<OpenCodeSdkSpawnResult> {
616
+ return new Promise((resolve, reject) => {
617
+ let settled = false;
618
+ const child = spawn(argv[0] ?? "", argv.slice(1), {
619
+ shell: false,
620
+ stdio: ["ignore", "ignore", "pipe"],
621
+ });
622
+ const chunks: Buffer[] = [];
623
+ const timer = setTimeout(() => {
624
+ if (settled) return;
625
+ settled = true;
626
+ child.kill();
627
+ reject(
628
+ new Error(
629
+ `OpenCode SDK install timed out after ${timeoutMs}ms. Run crysk upgrade --reconcile.`,
630
+ ),
631
+ );
632
+ }, timeoutMs);
633
+ const finish = (settle: () => void): void => {
634
+ if (settled) return;
635
+ settled = true;
636
+ clearTimeout(timer);
637
+ settle();
638
+ };
639
+ child.stderr?.on("data", (chunk: Buffer | string) => {
640
+ if (chunks.length >= 8) return;
641
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
642
+ });
643
+ child.on("error", (error) => {
644
+ finish(() => reject(error));
645
+ });
646
+ child.on("close", (code) => {
647
+ finish(() => {
648
+ const stderr = Buffer.concat(chunks)
649
+ .toString("utf8")
650
+ .replaceAll("/$bunfs", "")
651
+ .trim()
652
+ .slice(0, 240);
653
+ resolve({ code: code ?? 1, stderr });
654
+ });
655
+ });
656
+ });
657
+ }
658
+
659
+ async function readReconcileRouting(
660
+ home: string,
661
+ ): Promise<RoutingConfig | undefined> {
662
+ const loaded = await loadGlobalConfigLayer(home);
663
+ return loaded.layer?.routing;
664
+ }
665
+
666
+ async function ensureOpenCodeSdkInstalled(options: {
667
+ home: string;
668
+ assetMode?: AssetMode;
669
+ readSdkVersion?: () => Promise<string | undefined>;
670
+ which?: (bin: string) => string | null;
671
+ spawnInstaller?: (argv: readonly string[]) => Promise<OpenCodeSdkSpawnResult>;
672
+ }): Promise<void> {
673
+ const routing = await readReconcileRouting(options.home);
674
+ if (!routingNeedsOpenCodeSdk(routing)) return;
675
+ // Install and the version check share this home. The no-arg reader uses
676
+ // os.homedir(), which is a different tree whenever reconcile was given one.
677
+ const nodeModulesDir = prheroLayout(options.home).nodeModulesDir;
678
+ const readSdkVersion =
679
+ options.readSdkVersion ??
680
+ (() =>
681
+ readInstalledOpenCodeSdkVersion(
682
+ options.assetMode === undefined
683
+ ? { nodeModulesDir }
684
+ : { mode: options.assetMode, nodeModulesDir },
685
+ ));
686
+ const installed = await readSdkVersion();
687
+ if (installed === SUPPORTED_OPENCODE_SDK_VERSION) return;
688
+ await withOpenCodeSdkInstallLock(options.home, async () => {
689
+ const again = await readSdkVersion();
690
+ if (again === SUPPORTED_OPENCODE_SDK_VERSION) return;
691
+ const which = options.which ?? ((bin: string) => Bun.which(bin));
692
+ const npmPath = commandOnPath(which("npm"));
693
+ const bunPath = npmPath === null ? commandOnPath(which("bun")) : null;
694
+ const argv = selectOpenCodeSdkInstaller({
695
+ npmPath,
696
+ bunPath,
697
+ layoutDir: prheroLayout(options.home).dir,
698
+ });
699
+ const spawnInstaller = options.spawnInstaller ?? spawnOpenCodeSdkInstaller;
700
+ const result = await spawnInstaller(argv);
701
+ if (result.code !== 0) {
702
+ throw new Error(
703
+ `Failed to install @opencode-ai/sdk@${SUPPORTED_OPENCODE_SDK_VERSION} ` +
704
+ `(exit ${result.code}). Run crysk upgrade --reconcile.`,
705
+ );
706
+ }
707
+ const after = await readSdkVersion();
708
+ if (after !== SUPPORTED_OPENCODE_SDK_VERSION) {
709
+ const observed =
710
+ typeof after === "string" && after.trim() !== ""
711
+ ? after.trim()
712
+ : "missing";
713
+ throw new Error(
714
+ `OpenCode SDK version "${observed}" after install; expected ` +
715
+ `"${SUPPORTED_OPENCODE_SDK_VERSION}". Run crysk upgrade --reconcile.`,
716
+ );
717
+ }
718
+ });
719
+ }
720
+
721
+ export async function reconcileUpgrade(
722
+ options: ReconcileUpgradeOptions = {},
723
+ ): Promise<{ ok: boolean; errors: string[] }> {
724
+ const errors: string[] = [];
725
+
726
+ const home = options.home ?? os.homedir();
727
+ const assets = resolveEngineAssets();
728
+ const envs = await detectAgentEnvironments({ home });
729
+ const self = selfInvocation();
730
+
731
+ // 1. Sync skills for all active environments
732
+ if (options.syncSkills) {
733
+ const res = await options.syncSkills();
734
+ if (res.errors.length > 0) errors.push(...res.errors);
735
+ } else {
736
+ for (const env of envs) {
737
+ if (env.skillsDir && (env.status === "active" || env.binaryFound)) {
738
+ const res = await syncSkills(env, assets, { force: true });
739
+ if (res.errors.length > 0) errors.push(...res.errors);
740
+ }
741
+ }
742
+ }
743
+
744
+ // 2. Verify MCP registration
745
+ if (options.verifyMcp) {
746
+ try {
747
+ const res = await options.verifyMcp();
748
+ if (!res.ok) {
749
+ errors.push("MCP verification failed");
750
+ }
751
+ } catch (err) {
752
+ errors.push(`MCP verification failed: ${(err as Error).message}`);
753
+ }
754
+ } else {
755
+ for (const env of envs) {
756
+ if (env.mcpConfigFile && (env.status === "active" || env.binaryFound)) {
757
+ try {
758
+ const res = await registerMcpServer(env, {
759
+ command: self.command,
760
+ args: [...self.args, "mcp"],
761
+ });
762
+ if (!res.registered && res.error) {
763
+ errors.push(`${env.displayName} MCP: ${res.error}`);
764
+ }
765
+ } catch (err) {
766
+ errors.push(`${env.displayName} MCP: ${(err as Error).message}`);
767
+ }
768
+ }
769
+ }
770
+ }
771
+
772
+ // 3. Store migrations
773
+ if (options.migrateStore) {
774
+ try {
775
+ const res = await options.migrateStore();
776
+ if (!res.ok) {
777
+ errors.push("Store migration failed");
778
+ }
779
+ } catch (err) {
780
+ errors.push(`Store migration failed: ${(err as Error).message}`);
781
+ }
782
+ }
783
+
784
+ // 4. Reload daemons on macOS
785
+ if (options.reloadDaemons) {
786
+ try {
787
+ await options.reloadDaemons();
788
+ } catch (err) {
789
+ errors.push(`Daemon reload failed: ${(err as Error).message}`);
790
+ }
791
+ }
792
+
793
+ // 5. OpenCode SDK, after the daemon reload and before doctor, so the
794
+ // doctor step sees the install. A failure is reported and doctor still runs.
795
+ try {
796
+ if (options.ensureOpenCodeSdk) {
797
+ await options.ensureOpenCodeSdk();
798
+ } else {
799
+ await ensureOpenCodeSdkInstalled({
800
+ home,
801
+ assetMode: options.assetMode,
802
+ readSdkVersion: options.readSdkVersion,
803
+ which: options.which,
804
+ spawnInstaller: options.spawnInstaller,
805
+ });
806
+ }
807
+ } catch (err) {
808
+ errors.push(err instanceof Error ? err.message : String(err));
809
+ }
810
+
811
+ // 6. Doctor check
812
+ if (options.runDoctorCheck) {
813
+ try {
814
+ const doc = await options.runDoctorCheck();
815
+ if (doc.overall === "blocking") {
816
+ errors.push("Doctor check found blocking issues");
817
+ }
818
+ } catch (err) {
819
+ errors.push(`Doctor check failed: ${(err as Error).message}`);
820
+ }
821
+ } else {
822
+ try {
823
+ const doc = await runDoctor({ home });
824
+ if (doc.overall === "blocking") {
825
+ errors.push("Doctor check found blocking issues");
826
+ }
827
+ } catch (err) {
828
+ errors.push(`Doctor check error: ${(err as Error).message}`);
829
+ }
830
+ }
831
+
832
+ return {
833
+ ok: errors.length === 0,
834
+ errors,
835
+ };
836
+ }