opencode-agent-orchestration-kit 1.0.27

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 (236) hide show
  1. package/.github/CODEOWNERS +1 -0
  2. package/.github/ISSUE_TEMPLATE/bug_report.yml +65 -0
  3. package/.github/ISSUE_TEMPLATE/config.yml +11 -0
  4. package/.github/ISSUE_TEMPLATE/documentation.yml +22 -0
  5. package/.github/ISSUE_TEMPLATE/feature_request.yml +43 -0
  6. package/.github/PULL_REQUEST_TEMPLATE.md +25 -0
  7. package/.github/workflows/check.yml +47 -0
  8. package/CODE_OF_CONDUCT.md +24 -0
  9. package/CONTRIBUTING.md +52 -0
  10. package/LICENSE +201 -0
  11. package/NOTICE.md +23 -0
  12. package/README.md +806 -0
  13. package/SECURITY.md +17 -0
  14. package/docker/open-design/.env.example +6 -0
  15. package/docker/open-design/Dockerfile +50 -0
  16. package/docker/open-design/docker-compose.yml +18 -0
  17. package/docker/open-design/opencode-od/agents/od-worker.md +22 -0
  18. package/docker/open-design/opencode-od/opencode.json +24 -0
  19. package/docs/agents.md +21 -0
  20. package/docs/commands.md +16 -0
  21. package/docs/configuration.md +30 -0
  22. package/docs/docker-open-design.md +42 -0
  23. package/docs/impeccable.md +18 -0
  24. package/docs/installation.md +176 -0
  25. package/docs/models.md +17 -0
  26. package/docs/open-design.md +25 -0
  27. package/docs/quickstart.md +74 -0
  28. package/docs/releases/v1.0.10.md +46 -0
  29. package/docs/releases/v1.0.14.md +39 -0
  30. package/docs/releases/v1.0.27.md +66 -0
  31. package/docs/security.md +8 -0
  32. package/docs/superpowers/plans/2026-07-20-safe-installation-lifecycle.md +779 -0
  33. package/docs/superpowers/plans/2026-07-20-version-identity-and-releases.md +590 -0
  34. package/docs/superpowers/specs/2026-07-20-safe-installation-lifecycle-design.md +1350 -0
  35. package/docs/superpowers/specs/2026-07-20-version-identity-and-releases-design.md +557 -0
  36. package/docs/superpowers.md +34 -0
  37. package/docs/synology.md +30 -0
  38. package/docs/troubleshooting.md +54 -0
  39. package/docs/workflows.md +44 -0
  40. package/doctor.sh +5 -0
  41. package/env.example +15 -0
  42. package/install.sh +5 -0
  43. package/opencode/AGENTS.md +104 -0
  44. package/opencode/agents/debugger.md +41 -0
  45. package/opencode/agents/designer.md +93 -0
  46. package/opencode/agents/developer.md +180 -0
  47. package/opencode/agents/evaluator.md +35 -0
  48. package/opencode/agents/evolver.md +31 -0
  49. package/opencode/agents/lead.md +251 -0
  50. package/opencode/agents/researcher.md +76 -0
  51. package/opencode/agents/review_api.md +34 -0
  52. package/opencode/agents/review_coordinator.md +111 -0
  53. package/opencode/agents/review_quality.md +35 -0
  54. package/opencode/agents/review_security.md +35 -0
  55. package/opencode/agents/review_tests.md +37 -0
  56. package/opencode/agents/reviewer.md +116 -0
  57. package/opencode/agents/scoper.md +75 -0
  58. package/opencode/agents/specifier.md +116 -0
  59. package/opencode/commands/code-simplify.md +36 -0
  60. package/opencode/commands/design.md +27 -0
  61. package/opencode/commands/evolve.md +165 -0
  62. package/opencode/commands/feature.md +67 -0
  63. package/opencode/commands/implement.md +11 -0
  64. package/opencode/commands/init.md +34 -0
  65. package/opencode/commands/loop.md +145 -0
  66. package/opencode/commands/mvp-spec.md +20 -0
  67. package/opencode/commands/plan.md +74 -0
  68. package/opencode/commands/research.md +12 -0
  69. package/opencode/commands/review-orchestrated.md +47 -0
  70. package/opencode/commands/review-preflight.md +26 -0
  71. package/opencode/commands/review.md +18 -0
  72. package/opencode/commands/scope.md +36 -0
  73. package/opencode/commands/spec.md +12 -0
  74. package/opencode/commands/test.md +40 -0
  75. package/opencode/docs/ai/evolution/README.md +135 -0
  76. package/opencode/docs/ai/evolution/benchmarks/manual-scenarios.md +123 -0
  77. package/opencode/docs/ai/evolution/benchmarks/router-scenarios.jsonl +8 -0
  78. package/opencode/docs/ai/evolution/evolution_history.md +83 -0
  79. package/opencode/docs/ai/evolution/mechanisms.jsonl +7 -0
  80. package/opencode/docs/ai/evolution/rejected_mechanisms.jsonl +2 -0
  81. package/opencode/docs/ai/evolution/runs/README.md +15 -0
  82. package/opencode/docs/ai/evolution/runs/iteration-001-sidecar/analysis/overview.md +12 -0
  83. package/opencode/docs/ai/evolution/runs/iteration-001-sidecar/change_evaluation.json +108 -0
  84. package/opencode/docs/ai/evolution/runs/iteration-001-sidecar/change_manifest.json +52 -0
  85. package/opencode/docs/ai/evolution/runs/iteration-001-sidecar/evaluation.md +19 -0
  86. package/opencode/docs/ai/evolution/runs/iteration-001-sidecar/post_evaluation.md +12 -0
  87. package/opencode/docs/ai/evolution/runs/iteration-002-feature-flow-fix/analysis/overview.md +7 -0
  88. package/opencode/docs/ai/evolution/runs/iteration-002-feature-flow-fix/change_evaluation.json +31 -0
  89. package/opencode/docs/ai/evolution/runs/iteration-002-feature-flow-fix/evaluation.md +19 -0
  90. package/opencode/docs/ai/evolution/runs/iteration-003-agent-readable-harness/analysis/overview.md +13 -0
  91. package/opencode/docs/ai/evolution/runs/iteration-003-agent-readable-harness/change_evaluation.json +66 -0
  92. package/opencode/docs/ai/evolution/runs/iteration-003-agent-readable-harness/change_manifest.json +82 -0
  93. package/opencode/docs/ai/evolution/runs/iteration-003-agent-readable-harness/evaluation.md +20 -0
  94. package/opencode/docs/ai/evolution/runs/iteration-004-orchestration-audit/analysis/detail/ahe-run-lifecycle-validator.md +40 -0
  95. package/opencode/docs/ai/evolution/runs/iteration-004-orchestration-audit/analysis/detail/evolve-evaluation-only-contract.md +15 -0
  96. package/opencode/docs/ai/evolution/runs/iteration-004-orchestration-audit/analysis/detail/open-design-tool-contract.md +14 -0
  97. package/opencode/docs/ai/evolution/runs/iteration-004-orchestration-audit/analysis/detail/slash-command-contract-coverage.md +40 -0
  98. package/opencode/docs/ai/evolution/runs/iteration-004-orchestration-audit/analysis/overview.md +17 -0
  99. package/opencode/docs/ai/evolution/runs/iteration-004-orchestration-audit/analysis/pre_apply_approval.md +15 -0
  100. package/opencode/docs/ai/evolution/runs/iteration-004-orchestration-audit/change_evaluation.json +252 -0
  101. package/opencode/docs/ai/evolution/runs/iteration-004-orchestration-audit/change_manifest.json +210 -0
  102. package/opencode/docs/ai/evolution/runs/iteration-004-orchestration-audit/evaluation.md +25 -0
  103. package/opencode/docs/ai/evolution/runs/iteration-004-orchestration-audit/post_apply_evaluation.md +15 -0
  104. package/opencode/docs/ai/evolution/runs/iteration-004-orchestration-audit/post_manifest_evaluation.md +14 -0
  105. package/opencode/docs/ai/evolution/runs/iteration-004-orchestration-audit/pre_apply_evaluation.md +15 -0
  106. package/opencode/docs/ai/evolution/runs/iteration-005-harness-orchestration-audit/analysis/overview.md +13 -0
  107. package/opencode/docs/ai/evolution/runs/iteration-005-harness-orchestration-audit/change_evaluation.json +14 -0
  108. package/opencode/docs/ai/evolution/runs/iteration-005-harness-orchestration-audit/change_manifest.json +30 -0
  109. package/opencode/docs/ai/evolution/runs/iteration-005-harness-orchestration-audit/evaluation.md +25 -0
  110. package/opencode/docs/ai/evolution/runs/iteration-006-lead-delegation-audit/analysis/overview.md +13 -0
  111. package/opencode/docs/ai/evolution/runs/iteration-006-lead-delegation-audit/change_evaluation.json +14 -0
  112. package/opencode/docs/ai/evolution/runs/iteration-006-lead-delegation-audit/change_manifest.json +29 -0
  113. package/opencode/docs/ai/evolution/runs/iteration-006-lead-delegation-audit/evaluation.md +18 -0
  114. package/opencode/docs/ai/evolution/runs/iteration-007-agent-skills-integration/analysis/overview.md +13 -0
  115. package/opencode/docs/ai/evolution/runs/iteration-007-agent-skills-integration/change_evaluation.json +14 -0
  116. package/opencode/docs/ai/evolution/runs/iteration-007-agent-skills-integration/change_manifest.json +34 -0
  117. package/opencode/docs/ai/evolution/runs/iteration-007-agent-skills-integration/evaluation.md +17 -0
  118. package/opencode/docs/ai/evolution/runs/iteration-008-lead-readonly-shell-permissions/analysis/overview.md +13 -0
  119. package/opencode/docs/ai/evolution/runs/iteration-008-lead-readonly-shell-permissions/change_evaluation.json +12 -0
  120. package/opencode/docs/ai/evolution/runs/iteration-008-lead-readonly-shell-permissions/change_manifest.json +28 -0
  121. package/opencode/docs/ai/evolution/runs/iteration-008-lead-readonly-shell-permissions/evaluation.md +17 -0
  122. package/opencode/docs/ai/evolution/runs/iteration-009-lead-developer-ownership-loop/analysis/overview.md +9 -0
  123. package/opencode/docs/ai/evolution/runs/iteration-009-lead-developer-ownership-loop/change_evaluation.json +14 -0
  124. package/opencode/docs/ai/evolution/runs/iteration-009-lead-developer-ownership-loop/change_manifest.json +31 -0
  125. package/opencode/docs/ai/evolution/runs/iteration-009-lead-developer-ownership-loop/evaluation.md +18 -0
  126. package/opencode/docs/ai/evolution/runs/iteration-010-token-plugin-sidebar-content/analysis/overview.md +12 -0
  127. package/opencode/docs/ai/evolution/runs/iteration-010-token-plugin-sidebar-content/change_evaluation.json +14 -0
  128. package/opencode/docs/ai/evolution/runs/iteration-010-token-plugin-sidebar-content/change_manifest.json +31 -0
  129. package/opencode/docs/ai/evolution/runs/iteration-010-token-plugin-sidebar-content/evaluation.md +17 -0
  130. package/opencode/docs/ai/evolution/runs/iteration-011-lead-cd-which-permissions/analysis/overview.md +10 -0
  131. package/opencode/docs/ai/evolution/runs/iteration-011-lead-cd-which-permissions/change_evaluation.json +14 -0
  132. package/opencode/docs/ai/evolution/runs/iteration-011-lead-cd-which-permissions/change_manifest.json +30 -0
  133. package/opencode/docs/ai/evolution/runs/iteration-011-lead-cd-which-permissions/evaluation.md +17 -0
  134. package/opencode/docs/ai/evolution/runs/iteration-012-lead-shell-allowlist-boundaries/analysis/overview.md +25 -0
  135. package/opencode/docs/ai/evolution/runs/iteration-012-lead-shell-allowlist-boundaries/change_evaluation.json +28 -0
  136. package/opencode/docs/ai/evolution/runs/iteration-012-lead-shell-allowlist-boundaries/change_manifest.json +31 -0
  137. package/opencode/docs/ai/evolution/runs/iteration-012-lead-shell-allowlist-boundaries/evaluation.md +22 -0
  138. package/opencode/docs/ai/evolution/runs/iteration-013-doc-gardening-mechanical-checks/analysis/overview.md +27 -0
  139. package/opencode/docs/ai/evolution/runs/iteration-013-doc-gardening-mechanical-checks/change_evaluation.json +32 -0
  140. package/opencode/docs/ai/evolution/runs/iteration-013-doc-gardening-mechanical-checks/change_manifest.json +49 -0
  141. package/opencode/docs/ai/evolution/runs/iteration-013-doc-gardening-mechanical-checks/evaluation.md +92 -0
  142. package/opencode/docs/ai/evolution/runs/iteration-014-harness-baseline/analysis/detail/token-vs-semantic.md +31 -0
  143. package/opencode/docs/ai/evolution/runs/iteration-014-harness-baseline/analysis/overview.md +14 -0
  144. package/opencode/docs/ai/evolution/runs/iteration-014-harness-baseline/evaluation.md +36 -0
  145. package/opencode/docs/ai/evolution/runs/iteration-015-semantic-checker/analysis/overview.md +13 -0
  146. package/opencode/docs/ai/evolution/runs/iteration-015-semantic-checker/change_evaluation.json +31 -0
  147. package/opencode/docs/ai/evolution/runs/iteration-015-semantic-checker/change_manifest.json +47 -0
  148. package/opencode/docs/ai/evolution/runs/iteration-015-semantic-checker/evaluation.md +27 -0
  149. package/opencode/docs/ai/evolution/runs/iteration-016-contract-prompt-alignment/analysis/overview.md +32 -0
  150. package/opencode/docs/ai/evolution/runs/iteration-016-contract-prompt-alignment/change_evaluation.json +31 -0
  151. package/opencode/docs/ai/evolution/runs/iteration-016-contract-prompt-alignment/change_manifest.json +35 -0
  152. package/opencode/docs/ai/evolution/runs/iteration-016-contract-prompt-alignment/evaluation.md +31 -0
  153. package/opencode/docs/ai/evolution/runs/iteration-017-ahe-cycle/analysis/detail/pattern-1-feature-sidecar-false-positive.md +51 -0
  154. package/opencode/docs/ai/evolution/runs/iteration-017-ahe-cycle/analysis/detail/pattern-2-checker-time-budget.md +52 -0
  155. package/opencode/docs/ai/evolution/runs/iteration-017-ahe-cycle/analysis/overview.md +99 -0
  156. package/opencode/docs/ai/evolution/runs/iteration-017-ahe-cycle/change_evaluation.json +61 -0
  157. package/opencode/docs/ai/evolution/runs/iteration-017-ahe-cycle/change_manifest.json +61 -0
  158. package/opencode/docs/ai/evolution/runs/iteration-017-ahe-cycle/evaluation.md +448 -0
  159. package/opencode/docs/ai/evolution/runs/iteration-018-free-message-routing-audit/analysis/detail/intake-gray-zone.md +65 -0
  160. package/opencode/docs/ai/evolution/runs/iteration-018-free-message-routing-audit/analysis/overview.md +172 -0
  161. package/opencode/docs/ai/evolution/runs/iteration-018-free-message-routing-audit/evaluation.md +226 -0
  162. package/opencode/docs/ai/evolution/runs/iteration-019-handoff-routing-audit/analysis/detail/plan-only-gray-zone.md +62 -0
  163. package/opencode/docs/ai/evolution/runs/iteration-019-handoff-routing-audit/analysis/overview.md +167 -0
  164. package/opencode/docs/ai/evolution/runs/iteration-019-handoff-routing-audit/evaluation.md +163 -0
  165. package/opencode/docs/ai/evolution/runs/iteration-020-loop-engineering-command/analysis/overview.md +42 -0
  166. package/opencode/docs/ai/evolution/runs/iteration-020-loop-engineering-command/change_evaluation.json +46 -0
  167. package/opencode/docs/ai/evolution/runs/iteration-020-loop-engineering-command/change_manifest.json +57 -0
  168. package/opencode/docs/ai/evolution/runs/iteration-020-loop-engineering-command/evaluation.md +48 -0
  169. package/opencode/docs/ai/evolution/runs/iteration-021/analysis/detail/contract-vs-runtime-gap.md +163 -0
  170. package/opencode/docs/ai/evolution/runs/iteration-021/analysis/detail/evidence-collection-blocker.md +134 -0
  171. package/opencode/docs/ai/evolution/runs/iteration-021/analysis/overview.md +111 -0
  172. package/opencode/docs/ai/evolution/runs/iteration-021/change_evaluation.json +52 -0
  173. package/opencode/docs/ai/evolution/runs/iteration-021/change_manifest.json +50 -0
  174. package/opencode/docs/ai/evolution/runs/iteration-021/evaluation.md +46 -0
  175. package/opencode/docs/ai/evolution/runs/iteration-021/manifest-justification.md +48 -0
  176. package/opencode/docs/ai/evolution/session-sources.md +91 -0
  177. package/opencode/docs/ai/harness/README.md +32 -0
  178. package/opencode/docs/ai/harness/agents.md +148 -0
  179. package/opencode/docs/ai/harness/checks.md +119 -0
  180. package/opencode/docs/ai/harness/commands.md +391 -0
  181. package/opencode/docs/ai/harness/evidence.md +85 -0
  182. package/opencode/docs/ai/harness/init-detection-rules.md +160 -0
  183. package/opencode/docs/ai/harness/orchestrated-review.md +131 -0
  184. package/opencode/docs/ai/harness/skill-metadata-schema.md +198 -0
  185. package/opencode/docs/ai/harness/skill-resolution.md +202 -0
  186. package/opencode/docs/ai/harness/skill_registry.json +443 -0
  187. package/opencode/docs/ai/harness/skill_registry.md +43 -0
  188. package/opencode/docs/ai/project-context-template.md +53 -0
  189. package/opencode/opencode.json +38 -0
  190. package/opencode/package-lock.json +1717 -0
  191. package/opencode/package.json +11 -0
  192. package/opencode/plugins/token-tree-usage.tsx +206 -0
  193. package/opencode/references/performance-checklist.md +153 -0
  194. package/opencode/references/security-checklist.md +134 -0
  195. package/opencode/references/testing-patterns.md +236 -0
  196. package/opencode/scripts/check-harness.mjs +1572 -0
  197. package/opencode/scripts/check-harness.test.mjs +820 -0
  198. package/opencode/scripts/collect-session-evidence.mjs +612 -0
  199. package/opencode/scripts/collect-session-evidence.test.mjs +443 -0
  200. package/opencode/scripts/preflight-audit.mjs +497 -0
  201. package/opencode/scripts/preflight-audit.test.mjs +363 -0
  202. package/opencode/scripts/project-capability-snapshot.mjs +407 -0
  203. package/opencode/scripts/project-capability-snapshot.test.mjs +382 -0
  204. package/opencode/scripts/review-orchestrated-prepare.mjs +547 -0
  205. package/opencode/scripts/review-orchestrated-prepare.test.mjs +516 -0
  206. package/opencode/scripts/skill-resolver.mjs +585 -0
  207. package/opencode/scripts/skill-resolver.test.mjs +781 -0
  208. package/opencode/scripts/update-skill-registry.mjs +380 -0
  209. package/opencode/skills/api-and-interface-design/SKILL.md +315 -0
  210. package/opencode/skills/autonomous-loops/SKILL.md +312 -0
  211. package/opencode/skills/code-review-and-quality/SKILL.md +365 -0
  212. package/opencode/skills/code-simplification/SKILL.md +345 -0
  213. package/opencode/skills/context-engineering/SKILL.md +252 -0
  214. package/opencode/skills/debugging-and-error-recovery/SKILL.md +316 -0
  215. package/opencode/skills/documentation-and-adrs/SKILL.md +298 -0
  216. package/opencode/skills/doubt-driven-development/SKILL.md +168 -0
  217. package/opencode/skills/iterative-retrieval/SKILL.md +232 -0
  218. package/opencode/skills/open-design/SKILL.md +123 -0
  219. package/opencode/skills/performance-optimization/SKILL.md +365 -0
  220. package/opencode/skills/security-and-hardening/SKILL.md +369 -0
  221. package/opencode/skills/source-driven-development/SKILL.md +210 -0
  222. package/opencode/skills/test-driven-development/SKILL.md +406 -0
  223. package/opencode/skills/using-agent-skills/SKILL.md +194 -0
  224. package/opencode/skills/verification-loop/SKILL.md +162 -0
  225. package/opencode/tools/open_design.ts +361 -0
  226. package/opencode/tui.json +5 -0
  227. package/package.json +20 -0
  228. package/rollback.sh +5 -0
  229. package/scripts/check.sh +184 -0
  230. package/scripts/install-smoke.sh +111 -0
  231. package/scripts/manage-installation.mjs +1498 -0
  232. package/scripts/manage-installation.test.mjs +1936 -0
  233. package/scripts/version.mjs +197 -0
  234. package/scripts/version.test.mjs +195 -0
  235. package/uninstall.sh +5 -0
  236. package/upgrade.sh +5 -0
@@ -0,0 +1,1498 @@
1
+ #!/usr/bin/env node
2
+
3
+ import path from "node:path";
4
+ import crypto from "node:crypto";
5
+ import fs from "node:fs";
6
+ import { fileURLToPath } from "node:url";
7
+ import { parseStableVersion, readCanonicalVersion, formatVersion, compareStableVersions } from "./version.mjs";
8
+
9
+ export const SCHEMA_VERSION = 1;
10
+ export const PROTECTED_ROOT_FILES = [
11
+ "AGENTS.md",
12
+ "opencode.json",
13
+ "package.json",
14
+ "package-lock.json",
15
+ "tui.json",
16
+ ];
17
+
18
+ const COMMAND_FLAGS = {
19
+ install: new Set(["dryRun", "force", "target", "help"]),
20
+ upgrade: new Set(["dryRun", "target", "help"]),
21
+ doctor: new Set(["acceptPreserved", "target", "help"]),
22
+ uninstall: new Set(["dryRun", "yes", "target", "help"]),
23
+ rollback: new Set(["dryRun", "target", "help"]),
24
+ };
25
+
26
+ const USAGE = {
27
+ install: "Usage: ./install.sh [--dry-run] [--force] [--target PATH]",
28
+ upgrade: "Usage: ./upgrade.sh [--dry-run] [--target PATH]",
29
+ doctor: "Usage: ./doctor.sh [--accept-preserved PATH] [--target PATH]",
30
+ uninstall: "Usage: ./uninstall.sh [--dry-run] [--yes] [--target PATH]",
31
+ rollback: "Usage: ./rollback.sh [--dry-run] [--target PATH]",
32
+ };
33
+
34
+ function invalid(message) {
35
+ const error = new Error(message);
36
+ error.code = "INVALID_INVOCATION";
37
+ return error;
38
+ }
39
+
40
+ export function parseCliArgs(command, argv) {
41
+ const allowed = COMMAND_FLAGS[command];
42
+ if (!allowed) throw invalid(`Unknown command: ${command ?? ""}`);
43
+
44
+ const options = {
45
+ command,
46
+ dryRun: false,
47
+ force: false,
48
+ yes: false,
49
+ help: false,
50
+ target: undefined,
51
+ acceptPreserved: undefined,
52
+ };
53
+
54
+ const flagSpecs = {
55
+ "--dry-run": ["dryRun", false],
56
+ "--force": ["force", false],
57
+ "--yes": ["yes", false],
58
+ "-y": ["yes", false],
59
+ "--help": ["help", false],
60
+ "-h": ["help", false],
61
+ "--target": ["target", true],
62
+ "--accept-preserved": ["acceptPreserved", true],
63
+ };
64
+
65
+ for (let index = 0; index < argv.length; index += 1) {
66
+ const argument = argv[index];
67
+ const spec = flagSpecs[argument];
68
+ if (!spec) throw invalid(`Unknown argument: ${argument}`);
69
+ const [name, takesValue] = spec;
70
+ if (!allowed.has(name)) throw invalid(`${argument} is not valid for ${command}`);
71
+ if (takesValue) {
72
+ if (index + 1 >= argv.length || argv[index + 1].startsWith("--")) {
73
+ throw invalid(`${argument} requires a path`);
74
+ }
75
+ options[name] = argv[index + 1];
76
+ index += 1;
77
+ } else {
78
+ options[name] = true;
79
+ }
80
+ }
81
+
82
+ return options;
83
+ }
84
+
85
+ export function resolveTarget(options, env = process.env) {
86
+ if (options.target !== undefined) {
87
+ if (options.target.length === 0) throw invalid("--target must not be empty");
88
+ return options.target;
89
+ }
90
+ if (Object.hasOwn(env, "OPENCODE_CONFIG_DIR")) {
91
+ if (!env.OPENCODE_CONFIG_DIR) throw invalid("OPENCODE_CONFIG_DIR must not be empty");
92
+ return env.OPENCODE_CONFIG_DIR;
93
+ }
94
+ if (!env.HOME) throw invalid("HOME is required when no target is configured");
95
+ return path.join(env.HOME, ".config", "opencode");
96
+ }
97
+
98
+ function sha256(bytes) {
99
+ return crypto.createHash("sha256").update(bytes).digest("hex");
100
+ }
101
+
102
+ export function normalizeManagedPath(value) {
103
+ if (typeof value !== "string" || value.length === 0) throw invalid("managed path must be non-empty");
104
+ if (/[\0-\x1f\x7f]/.test(value)) throw invalid("managed path contains control characters");
105
+ if (value.includes("\\") || path.posix.isAbsolute(value)) throw invalid("managed path must be relative POSIX syntax");
106
+ const normalized = path.posix.normalize(value);
107
+ if (normalized !== value || value.split("/").some((part) => part === "" || part === "." || part === "..")) {
108
+ throw invalid(`managed path is not normalized: ${value}`);
109
+ }
110
+ if (value === ".oak" || value.startsWith(".oak/")) throw invalid(`managed path uses reserved .oak namespace: ${value}`);
111
+ return value;
112
+ }
113
+
114
+ function canonicalJson(value) {
115
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
116
+ if (value && typeof value === "object") {
117
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
118
+ }
119
+ return JSON.stringify(value);
120
+ }
121
+
122
+ export function inventorySource(sourceRoot, deps = {}) {
123
+ const fsOps = deps.fsOps ?? fs;
124
+ const entries = [];
125
+
126
+ function walk(directory, prefix = "") {
127
+ const names = fsOps.readdirSync(directory).sort();
128
+ for (const name of names) {
129
+ if (prefix === "" && name === "node_modules") continue;
130
+ const relative = prefix ? `${prefix}/${name}` : name;
131
+ if (relative === ".oak" || relative.startsWith(".oak/")) {
132
+ throw invalid(`source payload uses reserved .oak namespace: ${relative}`);
133
+ }
134
+ const fullPath = path.join(directory, name);
135
+ const stat = fsOps.lstatSync(fullPath);
136
+ if (stat.isSymbolicLink()) throw invalid(`source symlink is not allowed: ${relative}`);
137
+ if (stat.isDirectory()) {
138
+ walk(fullPath, relative);
139
+ continue;
140
+ }
141
+ if (!stat.isFile()) throw invalid(`source entry is not a regular file: ${relative}`);
142
+ const managedPath = normalizeManagedPath(relative);
143
+ const bytes = fsOps.readFileSync(fullPath);
144
+ entries.push({ path: managedPath, sha256: sha256(bytes), mode: stat.mode & 0o777 });
145
+ }
146
+ }
147
+
148
+ const rootStat = fsOps.lstatSync(sourceRoot);
149
+ if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) throw invalid("source payload root must be a non-symlink directory");
150
+ walk(sourceRoot);
151
+ entries.sort((left, right) => left.path.localeCompare(right.path));
152
+ return {
153
+ entries,
154
+ payloadSha256: sha256(Buffer.from(`${canonicalJson(entries)}\n`, "utf8")),
155
+ };
156
+ }
157
+
158
+ function isInside(candidate, parent) {
159
+ const relative = path.relative(parent, candidate);
160
+ return relative !== "" && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
161
+ }
162
+
163
+ function resolveExistingComponents(absolutePath, fsOps = fs) {
164
+ let existing = absolutePath;
165
+ const suffix = [];
166
+ while (!lstatIfExists(existing, fsOps)) {
167
+ const parent = path.dirname(existing);
168
+ if (parent === existing) break;
169
+ suffix.unshift(path.basename(existing));
170
+ existing = parent;
171
+ }
172
+ const resolved = fsOps.realpathSync(existing);
173
+ return path.join(resolved, ...suffix);
174
+ }
175
+
176
+ export function assertSafeTarget({ targetRoot, repositoryRoot, sourceRoot, fsOps = fs }) {
177
+ const target = resolveExistingComponents(path.resolve(targetRoot), fsOps);
178
+ const repository = resolveExistingComponents(path.resolve(repositoryRoot), fsOps);
179
+ const source = resolveExistingComponents(path.resolve(sourceRoot), fsOps);
180
+ if (target === path.parse(target).root) throw invalid("target filesystem root is unsafe");
181
+
182
+ if (target === repository || isInside(repository, target)) {
183
+ throw invalid("target must not equal or contain the repository root");
184
+ }
185
+ const targetStat = lstatIfExists(target, fsOps);
186
+ const sourceStat = lstatIfExists(source, fsOps);
187
+ const sameSourceNode = targetStat && sourceStat && targetStat.dev === sourceStat.dev && targetStat.ino === sourceStat.ino;
188
+ if (target === source || sameSourceNode || isInside(target, source) || isInside(source, target)) {
189
+ throw invalid("target must not equal, contain, or be inside the source payload");
190
+ }
191
+ if (isInside(target, repository)) {
192
+ throw invalid("target must not be inside the repository root");
193
+ }
194
+ return target;
195
+ }
196
+
197
+ function assertExactKeys(value, expected, label) {
198
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw invalid(`${label} must be an object`);
199
+ const actual = Object.keys(value).sort();
200
+ const wanted = [...expected].sort();
201
+ const unknown = actual.filter((key) => !wanted.includes(key));
202
+ const missing = wanted.filter((key) => !actual.includes(key));
203
+ if (unknown.length > 0) throw invalid(`${label} has unknown field: ${unknown[0]}`);
204
+ if (missing.length > 0) throw invalid(`${label} is missing field: ${missing[0]}`);
205
+ }
206
+
207
+ function assertHash(value, label) {
208
+ if (typeof value !== "string" || !/^[0-9a-f]{64}$/.test(value)) throw invalid(`${label} must be a lowercase SHA-256 digest`);
209
+ }
210
+
211
+ function assertMode(value, label) {
212
+ if (!Number.isInteger(value) || value < 0 || value > 0o777) throw invalid(`${label} mode must be an integer from 0000 through 0777`);
213
+ }
214
+
215
+ function assertTimestamp(value, label) {
216
+ if (typeof value !== "string" || Number.isNaN(Date.parse(value))) throw invalid(`${label} must be an ISO-8601 timestamp`);
217
+ }
218
+
219
+ const MANIFEST_KEYS = [
220
+ "schema_version", "manager", "kit_version", "payload_sha256", "created_at", "updated_at",
221
+ "last_transaction_id", "owned_files", "preserved_files",
222
+ ];
223
+ const OWNED_KEYS = ["path", "sha256", "mode"];
224
+ const PRESERVED_KEYS = [
225
+ "path", "observed_sha256", "observed_mode", "source_sha256", "source_mode",
226
+ "reason", "merge_acknowledgement",
227
+ ];
228
+ const ACK_KEYS = [
229
+ "target_sha256", "target_mode", "source_sha256", "source_mode", "acknowledged_at",
230
+ ];
231
+
232
+ export function validateManifest(manifest) {
233
+ assertExactKeys(manifest, MANIFEST_KEYS, "manifest");
234
+ if (manifest.schema_version !== SCHEMA_VERSION) throw invalid("manifest schema_version must be 1");
235
+ if (manifest.manager !== "opencode-agent-orchestration-kit") throw invalid("manifest manager is invalid");
236
+ try {
237
+ parseStableVersion(manifest.kit_version);
238
+ } catch (error) {
239
+ throw invalid(`manifest kit_version is invalid: ${error.message}`);
240
+ }
241
+ assertHash(manifest.payload_sha256, "manifest payload_sha256");
242
+ assertTimestamp(manifest.created_at, "manifest created_at");
243
+ assertTimestamp(manifest.updated_at, "manifest updated_at");
244
+ if (typeof manifest.last_transaction_id !== "string" || manifest.last_transaction_id.length === 0) {
245
+ throw invalid("manifest last_transaction_id must be non-empty");
246
+ }
247
+ if (!Array.isArray(manifest.owned_files) || !Array.isArray(manifest.preserved_files)) {
248
+ throw invalid("manifest ownership lists must be arrays");
249
+ }
250
+
251
+ const allPaths = new Set();
252
+ let previousPath = null;
253
+ for (const entry of manifest.owned_files) {
254
+ assertExactKeys(entry, OWNED_KEYS, "owned_files entry");
255
+ normalizeManagedPath(entry.path);
256
+ if (previousPath !== null && previousPath.localeCompare(entry.path) >= 0) {
257
+ throw invalid(previousPath === entry.path ? `duplicate manifest path: ${entry.path}` : "owned_files must be sorted by path");
258
+ }
259
+ previousPath = entry.path;
260
+ allPaths.add(entry.path);
261
+ assertHash(entry.sha256, `owned_files ${entry.path} sha256`);
262
+ assertMode(entry.mode, `owned_files ${entry.path}`);
263
+ }
264
+
265
+ previousPath = null;
266
+ for (const entry of manifest.preserved_files) {
267
+ assertExactKeys(entry, PRESERVED_KEYS, "preserved_files entry");
268
+ normalizeManagedPath(entry.path);
269
+ if (previousPath !== null && previousPath.localeCompare(entry.path) >= 0) {
270
+ throw invalid(previousPath === entry.path ? `duplicate manifest path: ${entry.path}` : "preserved_files must be sorted by path");
271
+ }
272
+ previousPath = entry.path;
273
+ if (allPaths.has(entry.path)) throw invalid(`owned and preserved paths overlap: ${entry.path}`);
274
+ allPaths.add(entry.path);
275
+ assertHash(entry.observed_sha256, `preserved_files ${entry.path} observed_sha256`);
276
+ assertMode(entry.observed_mode, `preserved_files ${entry.path} observed`);
277
+ assertHash(entry.source_sha256, `preserved_files ${entry.path} source_sha256`);
278
+ assertMode(entry.source_mode, `preserved_files ${entry.path} source`);
279
+ if (!["preexisting-user-file", "preexisting-exact-match"].includes(entry.reason)) {
280
+ throw invalid(`preserved_files ${entry.path} reason is invalid`);
281
+ }
282
+ if (entry.merge_acknowledgement !== null) {
283
+ assertExactKeys(entry.merge_acknowledgement, ACK_KEYS, "merge_acknowledgement");
284
+ assertHash(entry.merge_acknowledgement.target_sha256, "merge_acknowledgement target_sha256");
285
+ assertMode(entry.merge_acknowledgement.target_mode, "merge_acknowledgement target");
286
+ assertHash(entry.merge_acknowledgement.source_sha256, "merge_acknowledgement source_sha256");
287
+ assertMode(entry.merge_acknowledgement.source_mode, "merge_acknowledgement source");
288
+ assertTimestamp(entry.merge_acknowledgement.acknowledged_at, "merge_acknowledgement acknowledged_at");
289
+ }
290
+ }
291
+ return manifest;
292
+ }
293
+
294
+ export function canonicalManifestBytes(manifest) {
295
+ validateManifest(manifest);
296
+ return Buffer.from(`${canonicalJson(manifest)}\n`, "utf8");
297
+ }
298
+
299
+ const TRANSACTION_KEYS = [
300
+ "schema_version", "transaction_id", "command", "status", "rollback_origin",
301
+ "created_at", "source_payload_sha256", "previous_manifest", "next_manifest",
302
+ "previous_manifest_sha256", "next_manifest_sha256", "lock", "operations",
303
+ "completed_operation_indexes", "rollback_completed_operation_indexes",
304
+ "manifest_write_completed", "rollback_manifest_write_completed",
305
+ ];
306
+ const LOCK_KEYS = ["transaction_id", "pid", "command", "created_at"];
307
+ const OPERATION_KEYS = [
308
+ "index", "kind", "path", "before_sha256", "before_mode", "after_sha256",
309
+ "after_mode", "backup_path",
310
+ ];
311
+
312
+ function assertNullableStatePair(hash, mode, label) {
313
+ if ((hash === null) !== (mode === null)) throw invalid(`${label} hash and mode must both be null or both be present`);
314
+ if (hash !== null) {
315
+ assertHash(hash, `${label} hash`);
316
+ assertMode(mode, label);
317
+ }
318
+ }
319
+
320
+ function validateManifestPair(transaction, name) {
321
+ const manifest = transaction[`${name}_manifest`];
322
+ const digest = transaction[`${name}_manifest_sha256`];
323
+ if (manifest === null) {
324
+ if (digest !== null) throw invalid(`${name}_manifest_sha256 must be null when ${name}_manifest is null`);
325
+ return false;
326
+ }
327
+ if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)) throw invalid(`${name}_manifest must be null or a complete manifest`);
328
+ try {
329
+ validateManifest(manifest);
330
+ } catch (error) {
331
+ throw invalid(`${name}_manifest is invalid: ${error.message}`);
332
+ }
333
+ assertHash(digest, `${name}_manifest_sha256`);
334
+ if (sha256(canonicalManifestBytes(manifest)) !== digest) throw invalid(`${name}_manifest_sha256 does not match canonical manifest bytes`);
335
+ return true;
336
+ }
337
+
338
+ function validateBackupPath(value, label) {
339
+ if (typeof value !== "string" || !value.startsWith("files/")) throw invalid(`${label} backup must be below files/`);
340
+ normalizeManagedPath(value);
341
+ if (value.split("/").includes(".oak")) throw invalid(`${label} backup uses reserved .oak component`);
342
+ }
343
+
344
+ export function validateTransaction(transaction) {
345
+ assertExactKeys(transaction, TRANSACTION_KEYS, "transaction");
346
+ if (transaction.schema_version !== SCHEMA_VERSION) throw invalid("transaction schema_version must be 1");
347
+ if (typeof transaction.transaction_id !== "string" || transaction.transaction_id.length === 0) throw invalid("transaction_id must be non-empty");
348
+ if (!["install", "upgrade", "accept-preserved", "uninstall"].includes(transaction.command)) throw invalid("transaction command is invalid");
349
+ assertTimestamp(transaction.created_at, "transaction created_at");
350
+ assertHash(transaction.source_payload_sha256, "source_payload_sha256");
351
+
352
+ const statusOrigins = new Set([
353
+ "planned:none", "applying:none", "committed:none",
354
+ "rolling-back:interrupted-forward", "rolled-back:interrupted-forward",
355
+ "rolling-back:committed-operation", "rolled-back:committed-operation",
356
+ ]);
357
+ if (!statusOrigins.has(`${transaction.status}:${transaction.rollback_origin}`)) {
358
+ throw invalid("transaction status and rollback_origin combination is invalid");
359
+ }
360
+
361
+ const hasPrevious = validateManifestPair(transaction, "previous");
362
+ const hasNext = validateManifestPair(transaction, "next");
363
+ const expectedPresence = {
364
+ install: [false, true],
365
+ upgrade: [true, true],
366
+ "accept-preserved": [true, true],
367
+ uninstall: [true, false],
368
+ }[transaction.command];
369
+ if (hasPrevious !== expectedPresence[0] || hasNext !== expectedPresence[1]) {
370
+ throw invalid(`transaction manifest presence pair is invalid for ${transaction.command}`);
371
+ }
372
+
373
+ assertExactKeys(transaction.lock, LOCK_KEYS, "transaction lock");
374
+ if (transaction.lock.transaction_id !== transaction.transaction_id) throw invalid("transaction lock transaction_id mismatch");
375
+ if (!Number.isInteger(transaction.lock.pid) || transaction.lock.pid <= 0) throw invalid("transaction lock pid is invalid");
376
+ if (![transaction.command, "rollback"].includes(transaction.lock.command)) throw invalid("transaction lock command is invalid");
377
+ assertTimestamp(transaction.lock.created_at, "transaction lock created_at");
378
+
379
+ if (!Array.isArray(transaction.operations)) throw invalid("transaction operations must be an array");
380
+ const paths = new Set();
381
+ for (let index = 0; index < transaction.operations.length; index += 1) {
382
+ const operation = transaction.operations[index];
383
+ assertExactKeys(operation, OPERATION_KEYS, "transaction operation");
384
+ if (operation.index !== index) throw invalid("operation indexes must be unique and consecutive");
385
+ if (!["add", "update", "remove"].includes(operation.kind)) throw invalid(`operation kind is invalid: ${operation.kind}`);
386
+ normalizeManagedPath(operation.path);
387
+ if (paths.has(operation.path)) throw invalid(`duplicate operation path: ${operation.path}`);
388
+ paths.add(operation.path);
389
+ assertNullableStatePair(operation.before_sha256, operation.before_mode, `${operation.kind} before-state`);
390
+ assertNullableStatePair(operation.after_sha256, operation.after_mode, `${operation.kind} after-state`);
391
+ if (operation.kind === "add") {
392
+ if (operation.before_sha256 !== null) throw invalid("add before-state must be absent");
393
+ if (operation.after_sha256 === null) throw invalid("add after-state is required");
394
+ if (operation.backup_path !== null) throw invalid("add operation cannot have a backup");
395
+ } else if (operation.kind === "update") {
396
+ if (operation.before_sha256 === null || operation.after_sha256 === null) throw invalid("update before and after states are required");
397
+ if (operation.backup_path === null) throw invalid("update operation requires a backup");
398
+ validateBackupPath(operation.backup_path, "update");
399
+ } else {
400
+ if (operation.before_sha256 === null) throw invalid("remove before-state is required");
401
+ if (operation.after_sha256 !== null) throw invalid("remove after-state must be absent");
402
+ if (operation.backup_path === null) throw invalid("remove operation requires a backup");
403
+ validateBackupPath(operation.backup_path, "remove");
404
+ }
405
+ }
406
+
407
+ const validateIndexes = (values, label) => {
408
+ if (!Array.isArray(values) || values.some((value) => !Number.isInteger(value))) throw invalid(`${label} must be an integer array`);
409
+ if (new Set(values).size !== values.length || values.some((value) => value < 0 || value >= transaction.operations.length)) {
410
+ throw invalid(`${label} contains invalid completed indexes`);
411
+ }
412
+ };
413
+ validateIndexes(transaction.completed_operation_indexes, "completed_operation_indexes");
414
+ validateIndexes(transaction.rollback_completed_operation_indexes, "rollback_completed_operation_indexes");
415
+ if (transaction.rollback_completed_operation_indexes.some((value) => !transaction.completed_operation_indexes.includes(value))) {
416
+ throw invalid("rollback progress may reference only forward-completed operations");
417
+ }
418
+ if (transaction.rollback_completed_operation_indexes.length > 0 && !["rolling-back", "rolled-back"].includes(transaction.status)) {
419
+ throw invalid("rollback progress requires a rolling-back status");
420
+ }
421
+ if (typeof transaction.manifest_write_completed !== "boolean" || typeof transaction.rollback_manifest_write_completed !== "boolean") {
422
+ throw invalid("manifest progress fields must be boolean");
423
+ }
424
+ if (transaction.rollback_manifest_write_completed && (!transaction.manifest_write_completed || !["rolling-back", "rolled-back"].includes(transaction.status))) {
425
+ throw invalid("rollback manifest progress is inconsistent");
426
+ }
427
+ if (transaction.command === "accept-preserved") {
428
+ if (transaction.operations.length !== 0) throw invalid("accept-preserved must be manifest-only");
429
+ if (canonicalJson(transaction.previous_manifest.owned_files) !== canonicalJson(transaction.next_manifest.owned_files)) {
430
+ throw invalid("accept-preserved cannot change owned files");
431
+ }
432
+ const previousByPath = new Map(transaction.previous_manifest.preserved_files.map((entry) => [entry.path, entry]));
433
+ const changed = transaction.next_manifest.preserved_files.filter((entry) => canonicalJson(entry) !== canonicalJson(previousByPath.get(entry.path)));
434
+ if (changed.length !== 1 || transaction.next_manifest.preserved_files.length !== transaction.previous_manifest.preserved_files.length) {
435
+ throw invalid("accept-preserved must change exactly one preserved entry");
436
+ }
437
+ const nextEntry = changed[0];
438
+ const previousEntry = previousByPath.get(nextEntry.path);
439
+ const acknowledgement = nextEntry.merge_acknowledgement;
440
+ if (!previousEntry || nextEntry.reason !== previousEntry.reason || !acknowledgement
441
+ || acknowledgement.target_sha256 !== nextEntry.observed_sha256
442
+ || acknowledgement.target_mode !== nextEntry.observed_mode
443
+ || acknowledgement.source_sha256 !== nextEntry.source_sha256
444
+ || acknowledgement.source_mode !== nextEntry.source_mode) {
445
+ throw invalid("accept-preserved acknowledgement must match next-manifest baselines and preserve reason");
446
+ }
447
+ }
448
+ return transaction;
449
+ }
450
+
451
+ function lstatIfExists(fullPath, fsOps = fs) {
452
+ try {
453
+ return fsOps.lstatSync(fullPath);
454
+ } catch (error) {
455
+ if (error.code === "ENOENT") return null;
456
+ throw error;
457
+ }
458
+ }
459
+
460
+ function inspectTargetPath(targetRoot, relative, fsOps = fs) {
461
+ const parts = relative.split("/");
462
+ let current = targetRoot;
463
+ for (let index = 0; index < parts.length; index += 1) {
464
+ current = path.join(current, parts[index]);
465
+ const stat = lstatIfExists(current, fsOps);
466
+ if (!stat) return { kind: "absent" };
467
+ if (stat.isSymbolicLink()) throw invalid(`target symlink is not allowed: ${relative}`);
468
+ if (index < parts.length - 1) {
469
+ if (!stat.isDirectory()) throw invalid(`target parent is not a directory: ${relative}`);
470
+ continue;
471
+ }
472
+ if (stat.isDirectory()) return { kind: "directory" };
473
+ if (!stat.isFile()) throw invalid(`target entry is not a regular file: ${relative}`);
474
+ const bytes = fsOps.readFileSync(current);
475
+ return { kind: "file", sha256: sha256(bytes), mode: stat.mode & 0o777 };
476
+ }
477
+ return { kind: "absent" };
478
+ }
479
+
480
+ function readManifest(targetRoot, fsOps = fs) {
481
+ const oakPath = path.join(targetRoot, ".oak");
482
+ const oakStat = lstatIfExists(oakPath, fsOps);
483
+ if (!oakStat) return null;
484
+ if (oakStat.isSymbolicLink() || !oakStat.isDirectory()) throw invalid("target .oak must be a non-symlink directory");
485
+ const manifestPath = path.join(oakPath, "manifest.json");
486
+ const manifestStat = lstatIfExists(manifestPath, fsOps);
487
+ if (!manifestStat) return null;
488
+ if (manifestStat.isSymbolicLink() || !manifestStat.isFile()) throw invalid("manifest.json must be a non-symlink regular file");
489
+ let manifest;
490
+ try {
491
+ manifest = JSON.parse(fsOps.readFileSync(manifestPath, "utf8"));
492
+ } catch (error) {
493
+ throw invalid(`manifest JSON is corrupt: ${error.message}`);
494
+ }
495
+ validateManifest(manifest);
496
+ return manifest;
497
+ }
498
+
499
+ export function inspectInstallation({ sourceRoot, targetRoot, deps = {} }) {
500
+ const fsOps = deps.fsOps ?? fs;
501
+ const repositoryRoot = deps.repositoryRoot ?? path.dirname(sourceRoot);
502
+ const safeTarget = assertSafeTarget({ targetRoot, repositoryRoot, sourceRoot, fsOps });
503
+ const targetStat = lstatIfExists(safeTarget, fsOps);
504
+ if (targetStat && (targetStat.isSymbolicLink() || !targetStat.isDirectory())) {
505
+ throw invalid("target root must be a non-symlink directory or absent");
506
+ }
507
+ const source = inventorySource(sourceRoot, { fsOps });
508
+ const manifest = targetStat ? readManifest(safeTarget, fsOps) : null;
509
+ const paths = new Set(source.entries.map((entry) => entry.path));
510
+ for (const entry of manifest?.owned_files ?? []) paths.add(entry.path);
511
+ for (const entry of manifest?.preserved_files ?? []) paths.add(entry.path);
512
+ const target = {};
513
+ for (const relative of [...paths].sort()) target[relative] = targetStat ? inspectTargetPath(safeTarget, relative, fsOps) : { kind: "absent" };
514
+ const fingerprint = sha256(Buffer.from(`${canonicalJson({ source, manifest, target })}\n`, "utf8"));
515
+ return { sourceRoot, targetRoot: safeTarget, repositoryRoot, source, manifest, target, fingerprint };
516
+ }
517
+
518
+ function sameState(left, right) {
519
+ return left?.kind === "file" && left.sha256 === right.sha256 && left.mode === right.mode;
520
+ }
521
+
522
+ function manifestEntryState(entry) {
523
+ return { kind: "file", sha256: entry.sha256, mode: entry.mode };
524
+ }
525
+
526
+ function preservedEntry(source, target, reason) {
527
+ return {
528
+ path: source.path,
529
+ observed_sha256: target.sha256,
530
+ observed_mode: target.mode,
531
+ source_sha256: source.sha256,
532
+ source_mode: source.mode,
533
+ reason,
534
+ merge_acknowledgement: null,
535
+ };
536
+ }
537
+
538
+ function makeNextManifest({ inspection, ownedFiles, preservedFiles, options }) {
539
+ const now = (options.clock?.() ?? new Date()).toISOString();
540
+ return {
541
+ schema_version: SCHEMA_VERSION,
542
+ manager: "opencode-agent-orchestration-kit",
543
+ kit_version: parseStableVersion(options.kitVersion).canonical,
544
+ payload_sha256: inspection.source.payloadSha256,
545
+ created_at: inspection.manifest?.created_at ?? now,
546
+ updated_at: now,
547
+ last_transaction_id: options.transactionId ?? "pending",
548
+ owned_files: ownedFiles.sort((left, right) => left.path.localeCompare(right.path)),
549
+ preserved_files: preservedFiles.sort((left, right) => left.path.localeCompare(right.path)),
550
+ };
551
+ }
552
+
553
+ function classifyVersionState(sourceVersion, manifest, sourcePayloadSha256) {
554
+ const source = parseStableVersion(sourceVersion).canonical;
555
+ if (!manifest) return "not-installed";
556
+ const installed = parseStableVersion(manifest.kit_version).canonical;
557
+ const comparison = compareStableVersions(source, installed);
558
+ if (comparison > 0) return "upgrade-available";
559
+ if (comparison < 0) return "source-older";
560
+ return manifest.payload_sha256 === sourcePayloadSha256
561
+ ? "current"
562
+ : "same-version-different-payload";
563
+ }
564
+
565
+ export function buildPlan({ command, inspection, options = {} }) {
566
+ if (!["install", "upgrade", "uninstall", "accept-preserved"].includes(command)) throw invalid(`cannot build plan for ${command}`);
567
+ if (command === "install" && inspection.manifest) throw invalid("install requires absent manifest; use upgrade");
568
+ if (command !== "install" && !inspection.manifest) throw invalid(`${command} requires a valid active manifest`);
569
+
570
+ const sourceByPath = new Map(inspection.source.entries.map((entry) => [entry.path, entry]));
571
+ const ownedByPath = new Map((inspection.manifest?.owned_files ?? []).map((entry) => [entry.path, entry]));
572
+ const preservedByPath = new Map((inspection.manifest?.preserved_files ?? []).map((entry) => [entry.path, entry]));
573
+ const entries = [];
574
+ const blockers = [];
575
+ const warnings = [];
576
+ const nextOwned = [];
577
+ const nextPreserved = [];
578
+ const allPaths = new Set([...sourceByPath.keys(), ...ownedByPath.keys(), ...preservedByPath.keys()]);
579
+ const versionState = command === "upgrade"
580
+ ? classifyVersionState(options.kitVersion, inspection.manifest, inspection.source.payloadSha256)
581
+ : null;
582
+ if (versionState === "source-older" || versionState === "same-version-different-payload") {
583
+ blockers.push({ path: "kit_version", classification: versionState });
584
+ }
585
+
586
+ for (const managedPath of [...allPaths].sort()) {
587
+ const source = sourceByPath.get(managedPath);
588
+ const owned = ownedByPath.get(managedPath);
589
+ const preserved = preservedByPath.get(managedPath);
590
+ const target = inspection.target[managedPath] ?? { kind: "absent" };
591
+
592
+ if (command === "install") {
593
+ if (target.kind === "absent") {
594
+ entries.push({ kind: "add", path: managedPath, before: null, after: source, reason: "new" });
595
+ nextOwned.push(source);
596
+ } else if (target.kind !== "file") {
597
+ blockers.push({ path: managedPath, classification: "unowned-conflict", reason: "structural-collision" });
598
+ } else if (sameState(target, source)) {
599
+ entries.push({ kind: "adopt", path: managedPath, before: target, after: source, reason: "unowned-match" });
600
+ nextOwned.push(source);
601
+ } else if (PROTECTED_ROOT_FILES.includes(managedPath)) {
602
+ if (options.force) {
603
+ entries.push({ kind: "update", path: managedPath, before: target, after: source, reason: "force-authorized" });
604
+ nextOwned.push(source);
605
+ } else {
606
+ entries.push({ kind: "preserve", path: managedPath, before: target, after: target, reason: "preexisting-user-file" });
607
+ nextPreserved.push(preservedEntry(source, target, "preexisting-user-file"));
608
+ warnings.push({ path: managedPath, classification: "preserved-user" });
609
+ }
610
+ } else if (options.force) {
611
+ entries.push({ kind: "update", path: managedPath, before: target, after: source, reason: "force-authorized" });
612
+ nextOwned.push(source);
613
+ } else {
614
+ blockers.push({ path: managedPath, classification: "unowned-conflict" });
615
+ }
616
+ continue;
617
+ }
618
+
619
+ if (command === "uninstall") {
620
+ if (owned) {
621
+ if (sameState(target, manifestEntryState(owned))) {
622
+ entries.push({ kind: "remove", path: managedPath, before: target, after: null, reason: "owned-unchanged" });
623
+ } else {
624
+ warnings.push({ path: managedPath, classification: target.kind === "absent" ? "owned-missing" : "owned-modified" });
625
+ }
626
+ } else if (preserved) {
627
+ warnings.push({ path: managedPath, classification: "preserved-user" });
628
+ }
629
+ continue;
630
+ }
631
+
632
+ if (owned) {
633
+ const installed = manifestEntryState(owned);
634
+ if (!source) {
635
+ if (sameState(target, installed)) {
636
+ entries.push({ kind: "remove", path: managedPath, before: target, after: null, reason: "obsolete-unchanged" });
637
+ } else {
638
+ blockers.push({ path: managedPath, classification: target.kind === "absent" ? "owned-missing" : "obsolete-modified" });
639
+ nextOwned.push(owned);
640
+ }
641
+ } else if (sameState(target, installed)) {
642
+ if (sameState(target, source)) {
643
+ nextOwned.push(source);
644
+ } else {
645
+ entries.push({ kind: "update", path: managedPath, before: target, after: source, reason: "owned-unchanged" });
646
+ nextOwned.push(source);
647
+ }
648
+ } else {
649
+ blockers.push({ path: managedPath, classification: target.kind === "absent" ? "owned-missing" : "owned-modified" });
650
+ nextOwned.push(owned);
651
+ }
652
+ continue;
653
+ }
654
+
655
+ if (preserved) {
656
+ if (!source) {
657
+ entries.push({ kind: "preserve", path: managedPath, before: target, after: target, reason: "source-removed" });
658
+ warnings.push({ path: managedPath, classification: target.kind === "absent" ? "obsolete-preserved-missing" : "obsolete-preserved-present" });
659
+ } else {
660
+ nextPreserved.push(preserved);
661
+ const targetChanged = target.kind !== "file" || target.sha256 !== preserved.observed_sha256 || target.mode !== preserved.observed_mode;
662
+ const sourceChanged = source.sha256 !== preserved.source_sha256 || source.mode !== preserved.source_mode;
663
+ const classification = target.kind === "absent" ? "preserved-missing"
664
+ : sourceChanged ? (targetChanged ? "preserved-both-changed" : "preserved-source-changed")
665
+ : targetChanged ? "preserved-user-changed" : "preserved-stable";
666
+ warnings.push({ path: managedPath, classification });
667
+ }
668
+ continue;
669
+ }
670
+
671
+ if (source) {
672
+ if (target.kind === "absent") {
673
+ entries.push({ kind: "add", path: managedPath, before: null, after: source, reason: "new" });
674
+ nextOwned.push(source);
675
+ } else if (target.kind === "file" && sameState(target, source)) {
676
+ entries.push({ kind: "preserve", path: managedPath, before: target, after: target, reason: "preexisting-exact-match" });
677
+ nextPreserved.push(preservedEntry(source, target, "preexisting-exact-match"));
678
+ warnings.push({ path: managedPath, classification: "preserved-user" });
679
+ } else {
680
+ blockers.push({ path: managedPath, classification: "unowned-conflict" });
681
+ }
682
+ }
683
+ }
684
+
685
+ entries.sort((left, right) => left.path.localeCompare(right.path));
686
+ blockers.sort((left, right) => left.path.localeCompare(right.path));
687
+ warnings.sort((left, right) => left.path.localeCompare(right.path));
688
+ const operations = entries.filter((entry) => ["add", "update", "remove"].includes(entry.kind));
689
+ const nextManifest = command === "uninstall" ? null : makeNextManifest({ inspection, ownedFiles: nextOwned, preservedFiles: nextPreserved, options });
690
+ const hasWork = command !== "upgrade"
691
+ || entries.length > 0
692
+ || inspection.manifest.payload_sha256 !== inspection.source.payloadSha256
693
+ || versionState === "upgrade-available";
694
+ return {
695
+ command,
696
+ entries,
697
+ operations,
698
+ blockers,
699
+ warnings,
700
+ canApply: blockers.length === 0,
701
+ hasWork,
702
+ previousManifest: inspection.manifest,
703
+ nextManifest,
704
+ fingerprint: inspection.fingerprint,
705
+ };
706
+ }
707
+
708
+ function ensureDirectory(fullPath, mode, fsOps = fs) {
709
+ const existing = lstatIfExists(fullPath, fsOps);
710
+ if (existing) {
711
+ if (existing.isSymbolicLink() || !existing.isDirectory()) throw invalid(`directory path is unsafe: ${fullPath}`);
712
+ return;
713
+ }
714
+ fsOps.mkdirSync(fullPath, { recursive: true, mode });
715
+ fsOps.chmodSync(fullPath, mode);
716
+ }
717
+
718
+ function fsyncDirectory(fullPath, fsOps = fs) {
719
+ const descriptor = fsOps.openSync(fullPath, "r");
720
+ try {
721
+ while (true) {
722
+ try {
723
+ fsOps.fsyncSync(descriptor);
724
+ break;
725
+ } catch (error) {
726
+ if (error.code !== "EINTR") throw error;
727
+ }
728
+ }
729
+ } finally {
730
+ fsOps.closeSync(descriptor);
731
+ }
732
+ }
733
+
734
+ function durableUnlink(fullPath, fsOps = fs) {
735
+ fsOps.unlinkSync(fullPath);
736
+ fsyncDirectory(path.dirname(fullPath), fsOps);
737
+ }
738
+
739
+ function durableRmdir(fullPath, fsOps = fs) {
740
+ fsOps.rmdirSync(fullPath);
741
+ fsyncDirectory(path.dirname(fullPath), fsOps);
742
+ }
743
+
744
+ function durableRemoveTree(fullPath, fsOps = fs) {
745
+ const stat = lstatIfExists(fullPath, fsOps);
746
+ if (!stat) return;
747
+ if (stat.isSymbolicLink()) throw invalid(`refusing to remove unsafe state symlink: ${fullPath}`);
748
+ if (!stat.isDirectory()) {
749
+ durableUnlink(fullPath, fsOps);
750
+ return;
751
+ }
752
+ for (const entry of fsOps.readdirSync(fullPath)) durableRemoveTree(path.join(fullPath, entry), fsOps);
753
+ durableRmdir(fullPath, fsOps);
754
+ }
755
+
756
+ function durableRename(from, to, fsOps = fs) {
757
+ fsOps.renameSync(from, to);
758
+ fsyncDirectory(path.dirname(to), fsOps);
759
+ if (path.dirname(from) !== path.dirname(to)) fsyncDirectory(path.dirname(from), fsOps);
760
+ }
761
+
762
+ function atomicWrite(fullPath, bytes, mode, fsOps = fs) {
763
+ const temporary = path.join(path.dirname(fullPath), `.${path.basename(fullPath)}.${process.pid}.${crypto.randomUUID()}.tmp`);
764
+ let descriptor;
765
+ let renamed = false;
766
+ try {
767
+ descriptor = fsOps.openSync(temporary, "wx", mode);
768
+ let offset = 0;
769
+ const buffer = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes);
770
+ while (offset < buffer.length) offset += fsOps.writeSync(descriptor, buffer, offset, buffer.length - offset);
771
+ fsOps.fsyncSync(descriptor);
772
+ fsOps.closeSync(descriptor);
773
+ descriptor = undefined;
774
+ fsOps.chmodSync(temporary, mode);
775
+ fsOps.renameSync(temporary, fullPath);
776
+ renamed = true;
777
+ fsyncDirectory(path.dirname(fullPath), fsOps);
778
+ } catch (error) {
779
+ if (descriptor !== undefined) {
780
+ try { fsOps.closeSync(descriptor); } catch {}
781
+ }
782
+ if (!renamed && lstatIfExists(temporary, fsOps)) {
783
+ try { durableUnlink(temporary, fsOps); } catch {}
784
+ }
785
+ throw error;
786
+ }
787
+ }
788
+
789
+ function writeJsonState(fullPath, value, fsOps = fs) {
790
+ atomicWrite(fullPath, Buffer.from(`${canonicalJson(value)}\n`, "utf8"), 0o600, fsOps);
791
+ }
792
+
793
+ function removeIfExists(fullPath, fsOps = fs) {
794
+ try {
795
+ durableRemoveTree(fullPath, fsOps);
796
+ } catch (error) {
797
+ if (error.code !== "ENOENT") throw error;
798
+ }
799
+ }
800
+
801
+ function removeEmptyManagedParents(targetRoot, relative, fsOps = fs) {
802
+ let current = path.dirname(path.join(targetRoot, relative));
803
+ while (current !== targetRoot && isInside(current, targetRoot)) {
804
+ try {
805
+ durableRmdir(current, fsOps);
806
+ } catch (error) {
807
+ if (!["ENOTEMPTY", "ENOENT"].includes(error.code)) throw error;
808
+ break;
809
+ }
810
+ current = path.dirname(current);
811
+ }
812
+ }
813
+
814
+ function buildJournal({ command, plan, transactionId, lock, createdAt, targetRoot, fsOps }) {
815
+ const operations = plan.operations.map((entry, index) => {
816
+ const backupPath = entry.kind === "add" ? null : `files/${String(index).padStart(6, "0")}`;
817
+ if (backupPath) {
818
+ const sourcePath = path.join(targetRoot, entry.path);
819
+ const backupFullPath = path.join(targetRoot, ".oak", "rollback.next", backupPath);
820
+ ensureDirectory(path.dirname(backupFullPath), 0o700, fsOps);
821
+ atomicWrite(backupFullPath, fsOps.readFileSync(sourcePath), 0o600, fsOps);
822
+ }
823
+ return {
824
+ index,
825
+ kind: entry.kind,
826
+ path: entry.path,
827
+ before_sha256: entry.before?.sha256 ?? null,
828
+ before_mode: entry.before?.mode ?? null,
829
+ after_sha256: entry.after?.sha256 ?? null,
830
+ after_mode: entry.after?.mode ?? null,
831
+ backup_path: backupPath,
832
+ };
833
+ });
834
+ const previous = plan.previousManifest;
835
+ const next = plan.nextManifest;
836
+ return {
837
+ schema_version: SCHEMA_VERSION,
838
+ transaction_id: transactionId,
839
+ command,
840
+ status: "planned",
841
+ rollback_origin: "none",
842
+ created_at: createdAt,
843
+ source_payload_sha256: plan.nextManifest?.payload_sha256 ?? plan.previousManifest.payload_sha256,
844
+ previous_manifest: previous,
845
+ next_manifest: next,
846
+ previous_manifest_sha256: previous ? sha256(canonicalManifestBytes(previous)) : null,
847
+ next_manifest_sha256: next ? sha256(canonicalManifestBytes(next)) : null,
848
+ lock,
849
+ operations,
850
+ completed_operation_indexes: [],
851
+ rollback_completed_operation_indexes: [],
852
+ manifest_write_completed: false,
853
+ rollback_manifest_write_completed: false,
854
+ };
855
+ }
856
+
857
+ function writeManagedFile(targetRoot, sourceRoot, operation, fsOps = fs) {
858
+ const destination = path.join(targetRoot, operation.path);
859
+ const source = path.join(sourceRoot, operation.path);
860
+ ensureDirectory(path.dirname(destination), 0o755, fsOps);
861
+ atomicWrite(destination, fsOps.readFileSync(source), operation.after_mode, fsOps);
862
+ }
863
+
864
+ function applyForwardOperation(targetRoot, sourceRoot, operation, fsOps = fs) {
865
+ if (operation.kind === "add" || operation.kind === "update") {
866
+ writeManagedFile(targetRoot, sourceRoot, operation, fsOps);
867
+ } else {
868
+ durableUnlink(path.join(targetRoot, operation.path), fsOps);
869
+ removeEmptyManagedParents(targetRoot, operation.path, fsOps);
870
+ }
871
+ }
872
+
873
+ function readJsonState(fullPath, label, fsOps = fs) {
874
+ const stat = lstatIfExists(fullPath, fsOps);
875
+ if (!stat || stat.isSymbolicLink() || !stat.isFile()) throw invalid(`${label} is missing or unsafe`);
876
+ try {
877
+ return JSON.parse(fsOps.readFileSync(fullPath, "utf8"));
878
+ } catch (error) {
879
+ throw invalid(`${label} JSON is corrupt: ${error.message}`);
880
+ }
881
+ }
882
+
883
+ function currentManifestDigest(targetRoot, fsOps = fs) {
884
+ const fullPath = path.join(targetRoot, ".oak", "manifest.json");
885
+ if (!lstatIfExists(fullPath, fsOps)) return null;
886
+ const manifest = readJsonState(fullPath, "manifest", fsOps);
887
+ validateManifest(manifest);
888
+ return sha256(canonicalManifestBytes(manifest));
889
+ }
890
+
891
+ export function createInstallationManager(options) {
892
+ const sourceRoot = options.sourceRoot;
893
+ const fsOps = options.fsOps ?? fs;
894
+ const clock = options.clock ?? (() => new Date());
895
+ const newTransactionId = options.transactionId ?? (() => crypto.randomUUID());
896
+ const failpoint = options.failpoint ?? (() => {});
897
+ const pidProbe = options.pidProbe ?? ((lockPid) => {
898
+ process.kill(lockPid, 0);
899
+ return { alive: true };
900
+ });
901
+ const pid = options.pid ?? process.pid;
902
+ const stdin = options.stdin ?? process.stdin;
903
+ const stdout = options.stdout ?? process.stdout;
904
+ const versionProvider = options.versionProvider ?? (() => {
905
+ throw invalid("canonical kit version provider is required");
906
+ });
907
+
908
+ function currentKitVersion() {
909
+ return parseStableVersion(versionProvider()).canonical;
910
+ }
911
+
912
+ function acquireLock(targetRoot, transactionId, command) {
913
+ const oakPath = path.join(targetRoot, ".oak");
914
+ ensureDirectory(oakPath, 0o700, fsOps);
915
+ const lock = { transaction_id: transactionId, pid, command, created_at: clock().toISOString() };
916
+ const lockPath = path.join(oakPath, "lock.json");
917
+ const descriptor = fsOps.openSync(lockPath, "wx", 0o600);
918
+ try {
919
+ fsOps.writeFileSync(descriptor, `${canonicalJson(lock)}\n`);
920
+ fsOps.fsyncSync(descriptor);
921
+ } finally {
922
+ fsOps.closeSync(descriptor);
923
+ }
924
+ fsyncDirectory(oakPath, fsOps);
925
+ return lock;
926
+ }
927
+
928
+ function releaseLock(targetRoot) {
929
+ const lockPath = path.join(targetRoot, ".oak", "lock.json");
930
+ if (lstatIfExists(lockPath, fsOps)) {
931
+ durableUnlink(lockPath, fsOps);
932
+ }
933
+ }
934
+
935
+ function commitForward(command, targetRoot, plan, transactionId) {
936
+ const oakPath = path.join(targetRoot, ".oak");
937
+ const nextPath = path.join(oakPath, "rollback.next");
938
+ const previousPath = path.join(oakPath, "rollback.previous");
939
+ const rollbackPath = path.join(oakPath, "rollback");
940
+ failpoint("before-journal-create");
941
+ removeIfExists(nextPath, fsOps);
942
+ ensureDirectory(path.join(nextPath, "files"), 0o700, fsOps);
943
+ const lock = readJsonState(path.join(oakPath, "lock.json"), "lock", fsOps);
944
+ const journal = buildJournal({
945
+ command, plan, transactionId, lock, targetRoot, fsOps,
946
+ createdAt: clock().toISOString(),
947
+ });
948
+ validateTransaction(journal);
949
+ writeJsonState(path.join(oakPath, "transaction.json"), journal, fsOps);
950
+ failpoint("after-journal-create");
951
+ journal.status = "applying";
952
+ writeJsonState(path.join(oakPath, "transaction.json"), journal, fsOps);
953
+ for (const operation of journal.operations) {
954
+ applyForwardOperation(targetRoot, sourceRoot, operation, fsOps);
955
+ failpoint("after-operation-write-before-progress");
956
+ journal.completed_operation_indexes.push(operation.index);
957
+ writeJsonState(path.join(oakPath, "transaction.json"), journal, fsOps);
958
+ failpoint("after-operation-progress");
959
+ }
960
+ const manifestPath = path.join(oakPath, "manifest.json");
961
+ if (journal.next_manifest) atomicWrite(manifestPath, canonicalManifestBytes(journal.next_manifest), 0o600, fsOps);
962
+ else if (lstatIfExists(manifestPath, fsOps)) durableUnlink(manifestPath, fsOps);
963
+ journal.manifest_write_completed = true;
964
+ writeJsonState(path.join(oakPath, "transaction.json"), journal, fsOps);
965
+
966
+ const committed = { ...journal, status: "committed" };
967
+ writeJsonState(path.join(nextPath, "transaction.json"), committed, fsOps);
968
+ removeIfExists(previousPath, fsOps);
969
+ if (lstatIfExists(rollbackPath, fsOps)) durableRename(rollbackPath, previousPath, fsOps);
970
+ fsOps.cpSync(nextPath, rollbackPath, { recursive: true, errorOnExist: true, force: false });
971
+ fsOps.chmodSync(rollbackPath, 0o700);
972
+ fsOps.chmodSync(path.join(rollbackPath, "files"), 0o700);
973
+ fsOps.chmodSync(path.join(rollbackPath, "transaction.json"), 0o600);
974
+ for (const operation of committed.operations) {
975
+ if (operation.backup_path) fsOps.chmodSync(path.join(rollbackPath, operation.backup_path), 0o600);
976
+ }
977
+ fsyncDirectory(oakPath, fsOps);
978
+ failpoint("after-rollback-publication");
979
+ durableUnlink(path.join(oakPath, "transaction.json"), fsOps);
980
+ failpoint("after-commit-boundary");
981
+ removeIfExists(previousPath, fsOps);
982
+ removeIfExists(nextPath, fsOps);
983
+ releaseLock(targetRoot);
984
+ return committed;
985
+ }
986
+
987
+ function inverseOperation(targetRoot, rollbackRoot, operation) {
988
+ const destination = path.join(targetRoot, operation.path);
989
+ if (operation.kind === "add") {
990
+ durableUnlink(destination, fsOps);
991
+ removeEmptyManagedParents(targetRoot, operation.path, fsOps);
992
+ return;
993
+ }
994
+ const backup = path.join(rollbackRoot, operation.backup_path);
995
+ ensureDirectory(path.dirname(destination), 0o755, fsOps);
996
+ atomicWrite(destination, fsOps.readFileSync(backup), operation.before_mode, fsOps);
997
+ }
998
+
999
+ function rollbackCommitted(targetRoot, dryRun) {
1000
+ const oakPath = path.join(targetRoot, ".oak");
1001
+ const rollbackRoot = path.join(oakPath, "rollback");
1002
+ const committed = readJsonState(path.join(rollbackRoot, "transaction.json"), "rollback transaction", fsOps);
1003
+ validateTransaction(committed);
1004
+ if (committed.status !== "committed") throw invalid("rollback transaction is not committed");
1005
+ const currentDigest = currentManifestDigest(targetRoot, fsOps);
1006
+ if (currentDigest !== committed.next_manifest_sha256) return { exitCode: 1, conflicts: ["manifest"] };
1007
+ for (const operation of committed.operations) {
1008
+ const current = inspectTargetPath(targetRoot, operation.path, fsOps);
1009
+ const expected = operation.after_sha256 === null ? { kind: "absent" } : { kind: "file", sha256: operation.after_sha256, mode: operation.after_mode };
1010
+ if (expected.kind === "absent" ? current.kind !== "absent" : !sameState(current, expected)) {
1011
+ return { exitCode: 1, conflicts: [operation.path] };
1012
+ }
1013
+ }
1014
+ if (dryRun) return { exitCode: 0, transaction: committed };
1015
+ const lock = acquireLock(targetRoot, committed.transaction_id, "rollback");
1016
+ const active = {
1017
+ ...committed,
1018
+ status: "rolling-back",
1019
+ rollback_origin: "committed-operation",
1020
+ lock,
1021
+ rollback_completed_operation_indexes: [],
1022
+ rollback_manifest_write_completed: false,
1023
+ };
1024
+ writeJsonState(path.join(oakPath, "transaction.json"), active, fsOps);
1025
+ failpoint("after-rollback-journal");
1026
+ for (const operation of [...active.operations].reverse()) {
1027
+ inverseOperation(targetRoot, rollbackRoot, operation);
1028
+ failpoint("after-inverse-write-before-progress");
1029
+ active.rollback_completed_operation_indexes.push(operation.index);
1030
+ writeJsonState(path.join(oakPath, "transaction.json"), active, fsOps);
1031
+ }
1032
+ const manifestPath = path.join(oakPath, "manifest.json");
1033
+ if (active.previous_manifest) atomicWrite(manifestPath, canonicalManifestBytes(active.previous_manifest), 0o600, fsOps);
1034
+ else if (lstatIfExists(manifestPath, fsOps)) durableUnlink(manifestPath, fsOps);
1035
+ active.rollback_manifest_write_completed = true;
1036
+ active.status = "rolled-back";
1037
+ writeJsonState(path.join(oakPath, "transaction.json"), active, fsOps);
1038
+ durableUnlink(path.join(oakPath, "transaction.json"), fsOps);
1039
+ removeIfExists(rollbackRoot, fsOps);
1040
+ removeIfExists(path.join(oakPath, "rollback.next"), fsOps);
1041
+ removeIfExists(path.join(oakPath, "rollback.previous"), fsOps);
1042
+ releaseLock(targetRoot);
1043
+ return { exitCode: 0, transaction: active };
1044
+ }
1045
+
1046
+ function lockAppearsAlive(lock) {
1047
+ try {
1048
+ const result = pidProbe(lock.pid);
1049
+ if (result && typeof result === "object" && Object.hasOwn(result, "alive")) return result.alive !== false;
1050
+ return true;
1051
+ } catch (error) {
1052
+ if (error.code === "ESRCH") return false;
1053
+ return true;
1054
+ }
1055
+ }
1056
+
1057
+ function validateLock(lock) {
1058
+ assertExactKeys(lock, LOCK_KEYS, "lock");
1059
+ if (typeof lock.transaction_id !== "string" || lock.transaction_id.length === 0) throw invalid("lock transaction_id is invalid");
1060
+ if (!Number.isInteger(lock.pid) || lock.pid <= 0) throw invalid("lock pid is invalid");
1061
+ if (!["install", "upgrade", "doctor", "accept-preserved", "uninstall", "rollback"].includes(lock.command)) throw invalid("lock command is invalid");
1062
+ assertTimestamp(lock.created_at, "lock created_at");
1063
+ return lock;
1064
+ }
1065
+
1066
+ function operationalState(targetRoot) {
1067
+ const oakPath = path.join(targetRoot, ".oak");
1068
+ const oakStat = lstatIfExists(oakPath, fsOps);
1069
+ if (!oakStat) return { lock: null, transaction: null };
1070
+ if (oakStat.isSymbolicLink() || !oakStat.isDirectory()) throw invalid("target .oak is unsafe");
1071
+ const lockPath = path.join(oakPath, "lock.json");
1072
+ const transactionPath = path.join(oakPath, "transaction.json");
1073
+ const lock = lstatIfExists(lockPath, fsOps) ? validateLock(readJsonState(lockPath, "lock", fsOps)) : null;
1074
+ const transaction = lstatIfExists(transactionPath, fsOps) ? readJsonState(transactionPath, "active transaction", fsOps) : null;
1075
+ if (transaction) validateTransaction(transaction);
1076
+ return { lock, transaction };
1077
+ }
1078
+
1079
+ function classifyExistingLock(lock) {
1080
+ if (!lock) return null;
1081
+ try {
1082
+ const result = pidProbe(lock.pid);
1083
+ if (result && typeof result === "object" && result.alive === false) return "stale";
1084
+ return "live";
1085
+ } catch (error) {
1086
+ if (error.code === "ESRCH") return "stale";
1087
+ if (error.code === "EPERM") return "live";
1088
+ throw invalid(`PID probe failed conservatively: ${error.code ?? error.message}`);
1089
+ }
1090
+ }
1091
+
1092
+ function recoverInterrupted(targetRoot, dryRun) {
1093
+ const oakPath = path.join(targetRoot, ".oak");
1094
+ const activePath = path.join(oakPath, "transaction.json");
1095
+ const active = readJsonState(activePath, "active transaction", fsOps);
1096
+ validateTransaction(active);
1097
+ if (!["planned", "applying", "rolling-back"].includes(active.status)) throw invalid("active transaction is not recoverable");
1098
+ const committedRollback = active.status === "rolling-back" && active.rollback_origin === "committed-operation";
1099
+ if (active.status === "rolling-back" && !["interrupted-forward", "committed-operation"].includes(active.rollback_origin)) throw invalid("active transaction rollback origin is invalid");
1100
+
1101
+ const expectedManifestDigest = active.rollback_manifest_write_completed
1102
+ ? active.previous_manifest_sha256
1103
+ : active.manifest_write_completed || committedRollback
1104
+ ? active.next_manifest_sha256
1105
+ : active.previous_manifest_sha256;
1106
+ if (currentManifestDigest(targetRoot, fsOps) !== expectedManifestDigest) {
1107
+ throw invalid("current manifest presence or digest does not match the recorded recovery phase");
1108
+ }
1109
+
1110
+ if (!committedRollback && active.rollback_origin === "none") {
1111
+ for (const operation of active.operations) {
1112
+ if (active.completed_operation_indexes.includes(operation.index)) continue;
1113
+ const current = inspectTargetPath(targetRoot, operation.path, fsOps);
1114
+ const before = operation.before_sha256 === null ? { kind: "absent" } : { kind: "file", sha256: operation.before_sha256, mode: operation.before_mode };
1115
+ const after = operation.after_sha256 === null ? { kind: "absent" } : { kind: "file", sha256: operation.after_sha256, mode: operation.after_mode };
1116
+ const matches = (state, expected) => expected.kind === "absent" ? state.kind === "absent" : sameState(state, expected);
1117
+ if (matches(current, after)) active.completed_operation_indexes.push(operation.index);
1118
+ else if (!matches(current, before)) throw invalid(`operation state is inconsistent during recovery: ${operation.path}`);
1119
+ }
1120
+ }
1121
+ const staleLock = validateLock(readJsonState(path.join(oakPath, "lock.json"), "lock", fsOps));
1122
+ const exactSnapshot = canonicalJson(staleLock) === canonicalJson(active.lock);
1123
+ const successorSnapshot = !exactSnapshot
1124
+ && staleLock.transaction_id === active.transaction_id
1125
+ && staleLock.command === "rollback";
1126
+ if (!exactSnapshot && !successorSnapshot) throw invalid("stale lock and transaction lock snapshot do not match");
1127
+ if (lockAppearsAlive(staleLock)) return { exitCode: 1, state: "live-lock" };
1128
+ if (dryRun) return { exitCode: 0, transaction: active };
1129
+ if (successorSnapshot) {
1130
+ active.lock = staleLock;
1131
+ writeJsonState(activePath, active, fsOps);
1132
+ }
1133
+ durableUnlink(path.join(oakPath, "lock.json"), fsOps);
1134
+ const replacementLock = acquireLock(targetRoot, active.transaction_id, "rollback");
1135
+ active.lock = replacementLock;
1136
+ active.status = "rolling-back";
1137
+ active.rollback_origin = committedRollback ? "committed-operation" : "interrupted-forward";
1138
+ writeJsonState(activePath, active, fsOps);
1139
+ const backupRoot = path.join(oakPath, committedRollback ? "rollback" : "rollback.next");
1140
+ const completed = [...active.completed_operation_indexes].sort((left, right) => right - left);
1141
+ for (const index of completed) {
1142
+ if (active.rollback_completed_operation_indexes.includes(index)) continue;
1143
+ inverseOperation(targetRoot, backupRoot, active.operations[index]);
1144
+ failpoint("after-inverse-write-before-progress");
1145
+ active.rollback_completed_operation_indexes.push(index);
1146
+ writeJsonState(activePath, active, fsOps);
1147
+ }
1148
+ if (active.manifest_write_completed && !active.rollback_manifest_write_completed) {
1149
+ const manifestPath = path.join(oakPath, "manifest.json");
1150
+ if (active.previous_manifest) atomicWrite(manifestPath, canonicalManifestBytes(active.previous_manifest), 0o600, fsOps);
1151
+ else if (lstatIfExists(manifestPath, fsOps)) durableUnlink(manifestPath, fsOps);
1152
+ active.rollback_manifest_write_completed = true;
1153
+ writeJsonState(activePath, active, fsOps);
1154
+ }
1155
+ active.status = "rolled-back";
1156
+ writeJsonState(activePath, active, fsOps);
1157
+ durableUnlink(activePath, fsOps);
1158
+ const rollback = path.join(oakPath, "rollback");
1159
+ const previous = path.join(oakPath, "rollback.previous");
1160
+ if (committedRollback) {
1161
+ removeIfExists(rollback, fsOps);
1162
+ removeIfExists(previous, fsOps);
1163
+ } else if (lstatIfExists(previous, fsOps)) {
1164
+ removeIfExists(rollback, fsOps);
1165
+ durableRename(previous, rollback, fsOps);
1166
+ } else if (lstatIfExists(rollback, fsOps)) {
1167
+ const candidate = readJsonState(path.join(rollback, "transaction.json"), "rollback candidate", fsOps);
1168
+ if (candidate.transaction_id === active.transaction_id) removeIfExists(rollback, fsOps);
1169
+ }
1170
+ removeIfExists(path.join(oakPath, "rollback.next"), fsOps);
1171
+ releaseLock(targetRoot);
1172
+ return { exitCode: 0, transaction: active };
1173
+ }
1174
+
1175
+ function doctorReport(targetRoot) {
1176
+ const oakPath = path.join(targetRoot, ".oak");
1177
+ const manifestPath = path.join(oakPath, "manifest.json");
1178
+ const manifestPresent = Boolean(lstatIfExists(manifestPath, fsOps));
1179
+ const operation = operationalState(targetRoot);
1180
+ const activeTransaction = operation.transaction;
1181
+ const activeLock = operation.lock;
1182
+ const residue = ["rollback.next", "rollback.previous"].filter((name) => lstatIfExists(path.join(oakPath, name), fsOps));
1183
+ const common = {
1184
+ blockers: [],
1185
+ warnings: [],
1186
+ activeTransaction: Boolean(activeTransaction),
1187
+ activeLock: activeLock ? classifyExistingLock(activeLock) : null,
1188
+ rollbackAvailable: Boolean(lstatIfExists(path.join(oakPath, "rollback", "transaction.json"), fsOps)),
1189
+ cleanupResidue: residue,
1190
+ };
1191
+ let sourceVersion = null;
1192
+ let sourceInvalid = false;
1193
+ try {
1194
+ sourceVersion = parseStableVersion(currentKitVersion()).canonical;
1195
+ } catch (error) {
1196
+ if (error.code !== "INVALID_VERSION") throw error;
1197
+ sourceInvalid = true;
1198
+ }
1199
+ let validatedManifest = null;
1200
+ try {
1201
+ validatedManifest = readManifest(targetRoot, fsOps);
1202
+ } catch (error) {
1203
+ if (!manifestPresent || error.code !== "INVALID_INVOCATION") throw error;
1204
+ return {
1205
+ exitCode: 2,
1206
+ report: {
1207
+ ...common,
1208
+ manifest: "invalid",
1209
+ blockers: [{ path: "kit_version", classification: "invalid-installed-version-state" }],
1210
+ sourceVersion,
1211
+ installedVersion: null,
1212
+ versionState: "invalid-version-state",
1213
+ },
1214
+ };
1215
+ }
1216
+ const installedVersion = validatedManifest?.kit_version ?? null;
1217
+ if (sourceInvalid) return {
1218
+ exitCode: 2,
1219
+ report: {
1220
+ ...common,
1221
+ manifest: validatedManifest ? "valid" : "absent",
1222
+ blockers: [{ path: "package.json", classification: "invalid-source-version-state" }],
1223
+ sourceVersion: null,
1224
+ installedVersion,
1225
+ versionState: "invalid-version-state",
1226
+ },
1227
+ };
1228
+ const inspection = inspectInstallation({ sourceRoot, targetRoot, deps: { fsOps } });
1229
+ if (!inspection.manifest) return {
1230
+ exitCode: 1,
1231
+ report: {
1232
+ ...common,
1233
+ manifest: "absent",
1234
+ sourceVersion,
1235
+ installedVersion: null,
1236
+ versionState: "not-installed",
1237
+ },
1238
+ };
1239
+ const versionState = classifyVersionState(sourceVersion, inspection.manifest, inspection.source.payloadSha256);
1240
+ const plan = buildPlan({ command: "upgrade", inspection, options: { clock, transactionId: "doctor-read-only", kitVersion: sourceVersion } });
1241
+ const actionableWarnings = new Set([
1242
+ "preserved-source-changed", "preserved-both-changed", "preserved-missing",
1243
+ "obsolete-preserved-present", "obsolete-preserved-missing",
1244
+ ]);
1245
+ const actionable = versionState !== "current"
1246
+ || plan.blockers.length > 0
1247
+ || plan.warnings.some((warning) => actionableWarnings.has(warning.classification))
1248
+ || activeTransaction || activeLock || residue.length > 0;
1249
+ return {
1250
+ exitCode: actionable ? 1 : 0,
1251
+ report: {
1252
+ manifest: "valid",
1253
+ blockers: plan.blockers,
1254
+ warnings: plan.warnings,
1255
+ activeTransaction: Boolean(activeTransaction),
1256
+ activeLock: activeLock ? classifyExistingLock(activeLock) : null,
1257
+ rollbackAvailable: Boolean(lstatIfExists(path.join(oakPath, "rollback", "transaction.json"), fsOps)),
1258
+ cleanupResidue: residue,
1259
+ sourceVersion,
1260
+ installedVersion,
1261
+ versionState,
1262
+ },
1263
+ };
1264
+ }
1265
+
1266
+ async function readAuthorizationLine() {
1267
+ let collected = "";
1268
+ for await (const chunk of stdin) {
1269
+ collected += chunk.toString();
1270
+ const newline = collected.indexOf("\n");
1271
+ if (newline !== -1) return collected.slice(0, newline);
1272
+ }
1273
+ return collected.length === 0 ? null : collected;
1274
+ }
1275
+
1276
+ async function acceptPreserved(targetRoot, preservedPath) {
1277
+ normalizeManagedPath(preservedPath);
1278
+ const transactionId = newTransactionId();
1279
+ const inspection = inspectInstallation({ sourceRoot, targetRoot, deps: { fsOps } });
1280
+ if (!inspection.manifest) throw invalid("accept-preserved requires a valid manifest");
1281
+ const versionState = classifyVersionState(currentKitVersion(), inspection.manifest, inspection.source.payloadSha256);
1282
+ if (versionState !== "current") return { exitCode: 1, versionState };
1283
+ const preserved = inspection.manifest.preserved_files.find((entry) => entry.path === preservedPath);
1284
+ if (!preserved) throw invalid("accept-preserved path is not preserved");
1285
+ const source = inspection.source.entries.find((entry) => entry.path === preservedPath);
1286
+ const target = inspection.target[preservedPath];
1287
+ if (!source || target?.kind !== "file") throw invalid("accept-preserved requires current regular target and source files");
1288
+ const mode = (value) => value.toString(8).padStart(4, "0");
1289
+ const authorization = `ACK-PRESERVED ${preservedPath} ${target.sha256} ${mode(target.mode)} ${source.sha256} ${mode(source.mode)}`;
1290
+ stdout.write(`${authorization}\n`);
1291
+ const supplied = await readAuthorizationLine();
1292
+ if (supplied !== authorization) return { exitCode: 1, authorization };
1293
+ failpoint("after-ack-confirmation");
1294
+ const globalPlan = buildPlan({ command: "upgrade", inspection, options: { clock, transactionId, kitVersion: currentKitVersion() } });
1295
+ if (!globalPlan.canApply) return { exitCode: 1, plan: globalPlan, authorization };
1296
+ acquireLock(targetRoot, transactionId, "accept-preserved");
1297
+ try {
1298
+ const lockedInspection = inspectInstallation({ sourceRoot, targetRoot, deps: { fsOps } });
1299
+ const lockedSource = lockedInspection.source.entries.find((entry) => entry.path === preservedPath);
1300
+ const lockedTarget = lockedInspection.target[preservedPath];
1301
+ if (lockedInspection.fingerprint !== inspection.fingerprint
1302
+ || !sameState(lockedTarget, target)
1303
+ || lockedSource.sha256 !== source.sha256 || lockedSource.mode !== source.mode) {
1304
+ releaseLock(targetRoot);
1305
+ return { exitCode: 1, authorization };
1306
+ }
1307
+ const nextManifest = structuredClone(lockedInspection.manifest);
1308
+ const nextEntry = nextManifest.preserved_files.find((entry) => entry.path === preservedPath);
1309
+ nextEntry.observed_sha256 = lockedTarget.sha256;
1310
+ nextEntry.observed_mode = lockedTarget.mode;
1311
+ nextEntry.source_sha256 = lockedSource.sha256;
1312
+ nextEntry.source_mode = lockedSource.mode;
1313
+ nextEntry.merge_acknowledgement = {
1314
+ target_sha256: lockedTarget.sha256,
1315
+ target_mode: lockedTarget.mode,
1316
+ source_sha256: lockedSource.sha256,
1317
+ source_mode: lockedSource.mode,
1318
+ acknowledged_at: clock().toISOString(),
1319
+ };
1320
+ nextManifest.payload_sha256 = lockedInspection.source.payloadSha256;
1321
+ nextManifest.updated_at = clock().toISOString();
1322
+ nextManifest.last_transaction_id = transactionId;
1323
+ validateManifest(nextManifest);
1324
+ const plan = {
1325
+ command: "accept-preserved",
1326
+ entries: [{ kind: "preserve", path: preservedPath, before: target, after: target, reason: "manual-merge-acknowledged" }],
1327
+ operations: [],
1328
+ blockers: [],
1329
+ warnings: globalPlan.warnings,
1330
+ canApply: true,
1331
+ previousManifest: lockedInspection.manifest,
1332
+ nextManifest,
1333
+ fingerprint: lockedInspection.fingerprint,
1334
+ };
1335
+ const transaction = commitForward("accept-preserved", targetRoot, plan, transactionId);
1336
+ return { exitCode: 0, plan, transaction, authorization };
1337
+ } catch (error) {
1338
+ const transactionPath = path.join(targetRoot, ".oak", "transaction.json");
1339
+ if (!lstatIfExists(transactionPath, fsOps)) {
1340
+ removeIfExists(path.join(targetRoot, ".oak", "rollback.next"), fsOps);
1341
+ releaseLock(targetRoot);
1342
+ }
1343
+ throw error;
1344
+ }
1345
+ }
1346
+
1347
+ async function run(command, runOptions) {
1348
+ const targetRoot = runOptions.targetRoot;
1349
+ const targetExisted = Boolean(lstatIfExists(targetRoot, fsOps));
1350
+ const oakPath = path.join(targetRoot, ".oak");
1351
+ const oakExisted = Boolean(lstatIfExists(oakPath, fsOps));
1352
+ let invocationLockOwned = false;
1353
+ try {
1354
+ if (command === "doctor") {
1355
+ return runOptions.acceptPreserved
1356
+ ? await acceptPreserved(targetRoot, runOptions.acceptPreserved)
1357
+ : doctorReport(targetRoot);
1358
+ }
1359
+ if (command === "rollback") {
1360
+ const activePath = path.join(targetRoot, ".oak", "transaction.json");
1361
+ return lstatIfExists(activePath, fsOps)
1362
+ ? recoverInterrupted(targetRoot, runOptions.dryRun === true)
1363
+ : rollbackCommitted(targetRoot, runOptions.dryRun === true);
1364
+ }
1365
+ const state = operationalState(targetRoot);
1366
+ if (state.lock || state.transaction) {
1367
+ return { exitCode: 1, state: state.lock ? classifyExistingLock(state.lock) : "interrupted-transaction" };
1368
+ }
1369
+ const transactionId = newTransactionId();
1370
+ const inspection = inspectInstallation({ sourceRoot, targetRoot, deps: { fsOps } });
1371
+ const kitVersion = currentKitVersion();
1372
+ const plan = buildPlan({ command, inspection, options: { ...runOptions, clock, transactionId, kitVersion } });
1373
+ if (!plan.canApply) return { exitCode: 1, plan };
1374
+ if (runOptions.dryRun) return { exitCode: 0, plan };
1375
+ if (command === "upgrade" && !plan.hasWork) return { exitCode: 0, plan };
1376
+ ensureDirectory(targetRoot, 0o755, fsOps);
1377
+ acquireLock(targetRoot, transactionId, command);
1378
+ invocationLockOwned = true;
1379
+ const lockedInspection = inspectInstallation({ sourceRoot, targetRoot, deps: { fsOps } });
1380
+ const lockedPlan = buildPlan({ command, inspection: lockedInspection, options: { ...runOptions, clock, transactionId, kitVersion } });
1381
+ if (lockedPlan.fingerprint !== plan.fingerprint || !lockedPlan.canApply) {
1382
+ releaseLock(targetRoot);
1383
+ return { exitCode: 1, plan: lockedPlan };
1384
+ }
1385
+ const transaction = commitForward(command, targetRoot, lockedPlan, transactionId);
1386
+ invocationLockOwned = false;
1387
+ return { exitCode: 0, plan: lockedPlan, transaction };
1388
+ } catch (error) {
1389
+ try {
1390
+ const transactionPath = path.join(oakPath, "transaction.json");
1391
+ if (invocationLockOwned && lstatIfExists(oakPath, fsOps) && !lstatIfExists(transactionPath, fsOps)) {
1392
+ const rollbackNext = path.join(oakPath, "rollback.next");
1393
+ if (!lstatIfExists(path.join(rollbackNext, "transaction.json"), fsOps)) removeIfExists(rollbackNext, fsOps);
1394
+ releaseLock(targetRoot);
1395
+ if (!oakExisted && fsOps.readdirSync(oakPath).length === 0) {
1396
+ durableRmdir(oakPath, fsOps);
1397
+ try { failpoint("after-bootstrap-oak-rmdir"); } catch {}
1398
+ }
1399
+ if (!targetExisted && lstatIfExists(targetRoot, fsOps) && fsOps.readdirSync(targetRoot).length === 0) {
1400
+ durableRmdir(targetRoot, fsOps);
1401
+ try { failpoint("after-bootstrap-target-rmdir"); } catch {}
1402
+ }
1403
+ }
1404
+ } catch {
1405
+ // Preserve the original failure and any state needed for diagnosis.
1406
+ }
1407
+ return { exitCode: error.code === "INVALID_INVOCATION" ? 2 : 2, error };
1408
+ }
1409
+ }
1410
+
1411
+ return { run };
1412
+ }
1413
+
1414
+ export async function main(argv, options = {}) {
1415
+ const stdout = options.stdout ?? process.stdout;
1416
+ const stderr = options.stderr ?? process.stderr;
1417
+ const input = options.stdin ?? process.stdin;
1418
+ try {
1419
+ const directVersion = argv[0] === "--version";
1420
+ const wrapperVersion = Object.hasOwn(USAGE, argv[0]) && argv[1] === "--version";
1421
+ if (directVersion || wrapperVersion) {
1422
+ const expectedLength = directVersion ? 1 : 2;
1423
+ if (argv.length !== expectedLength) throw invalid("--version must be used alone");
1424
+ const repositoryRoot = options.sourceRoot
1425
+ ? path.dirname(options.sourceRoot)
1426
+ : path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
1427
+ const version = options.versionProvider?.() ?? readCanonicalVersion(repositoryRoot);
1428
+ stdout.write(`${formatVersion(version)}\n`);
1429
+ return 0;
1430
+ }
1431
+ const [command, ...arguments_] = argv;
1432
+ const parsed = parseCliArgs(command, arguments_);
1433
+ if (parsed.help) {
1434
+ stdout.write(`${USAGE[command]}\n`);
1435
+ return 0;
1436
+ }
1437
+ const targetRoot = resolveTarget(parsed, options.env ?? process.env);
1438
+ const sourceRoot = options.sourceRoot ?? path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "opencode");
1439
+ const repositoryRoot = path.dirname(sourceRoot);
1440
+ const manager = createInstallationManager({
1441
+ sourceRoot,
1442
+ versionProvider: options.versionProvider ?? (() => readCanonicalVersion(repositoryRoot)),
1443
+ clock: options.clock,
1444
+ transactionId: options.transactionId,
1445
+ pidProbe: options.pidProbe,
1446
+ failpoint: options.failpoint,
1447
+ fsOps: options.fsOps,
1448
+ stdin: input,
1449
+ stdout,
1450
+ stderr,
1451
+ });
1452
+ if (command === "uninstall" && !parsed.yes && !parsed.dryRun) {
1453
+ const preview = await manager.run(command, { ...parsed, targetRoot, dryRun: true });
1454
+ if (preview.exitCode !== 0) return preview.exitCode;
1455
+ stdout.write(`This will remove unchanged kit-owned files from: ${targetRoot}\nContinue? [y/N] `);
1456
+ let answer = "";
1457
+ for await (const chunk of input) {
1458
+ answer += chunk.toString();
1459
+ if (answer.includes("\n")) break;
1460
+ }
1461
+ answer = answer.split("\n", 1)[0];
1462
+ if (!new Set(["y", "Y", "yes", "YES"]).has(answer)) {
1463
+ stdout.write("Aborted.\n");
1464
+ return 0;
1465
+ }
1466
+ parsed.yes = true;
1467
+ }
1468
+ const result = await manager.run(command, { ...parsed, targetRoot });
1469
+ if (result.error) stderr.write(`${result.error.message}\n`);
1470
+ else if (result.exitCode === 1 && result.plan?.blockers?.length) {
1471
+ for (const blocker of result.plan.blockers) stderr.write(`Conflict: ${blocker.path} (${blocker.classification})\n`);
1472
+ } else if (command === "doctor" && !parsed.acceptPreserved && result.report) {
1473
+ const actions = {
1474
+ "not-installed": "run install --dry-run",
1475
+ current: "none",
1476
+ "upgrade-available": "run upgrade --dry-run",
1477
+ "source-older": "use a source checkout at least as new as the installation",
1478
+ "same-version-different-payload": "fix the release identity mismatch",
1479
+ "invalid-version-state": "repair the invalid version state",
1480
+ };
1481
+ stdout.write(`doctor: ${result.report.versionState}; source=${result.report.sourceVersion ?? "invalid"}; installed=${result.report.installedVersion ?? "none"}; action=${actions[result.report.versionState]}\n`);
1482
+ } else if (command !== "doctor" || !parsed.acceptPreserved) {
1483
+ const changes = result.plan?.entries?.length ?? 0;
1484
+ stdout.write(`${command}: ${result.exitCode === 0 ? "ok" : "action required"}${result.plan ? ` (${changes} planned changes)` : ""}\n`);
1485
+ }
1486
+ return result.exitCode;
1487
+ } catch (error) {
1488
+ stderr.write(`${error.message}\n`);
1489
+ return error.code === "INVALID_INVOCATION" ? 2 : 2;
1490
+ }
1491
+ }
1492
+
1493
+ const isEntrypoint = process.argv[1]
1494
+ && fileURLToPath(import.meta.url) === path.resolve(process.argv[1]);
1495
+
1496
+ if (isEntrypoint) {
1497
+ process.exitCode = await main(process.argv.slice(2));
1498
+ }