ultra-builder-pro-cli 0.25.0 → 0.26.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 (241) hide show
  1. package/.ultra-template/contexts/TEMPLATE.md +87 -0
  2. package/.ultra-template/decisions/.gitkeep +1 -0
  3. package/.ultra-template/evidence/.gitkeep +1 -0
  4. package/.ultra-template/north-star.md +46 -0
  5. package/.ultra-template/research/.gitkeep +1 -0
  6. package/.ultra-template/specs/discovery.md +2 -2
  7. package/.ultra-template/tasks.json +3 -0
  8. package/.ultra-template/test-report.json +27 -0
  9. package/CHANGELOG.md +49 -0
  10. package/README.md +217 -579
  11. package/adapters/_shared/delegate-profiles/kimi-read-only.md +15 -0
  12. package/adapters/_shared/delegate-profiles/kimi-write.md +17 -0
  13. package/adapters/_shared/file-ops.cjs +76 -2
  14. package/adapters/_shared/host-profile.cjs +97 -0
  15. package/adapters/_shared/plugin-core.cjs +204 -0
  16. package/adapters/_shared/runtime-assets.cjs +31 -96
  17. package/adapters/claude.js +92 -291
  18. package/adapters/codex.js +309 -842
  19. package/adapters/grok.js +143 -1469
  20. package/adapters/kimi.js +124 -1053
  21. package/adapters/opencode.js +230 -742
  22. package/bin/delegate-worker.cjs +323 -0
  23. package/bin/delegate.cjs +456 -0
  24. package/bin/install.js +38 -11
  25. package/docs/ARCHITECTURE.md +122 -216
  26. package/docs/ARTIFACT-AUTHORITY.md +90 -268
  27. package/docs/DECISIONS.md +75 -87
  28. package/docs/PHILOSOPHY.md +177 -0
  29. package/docs/PLUGIN-ISOLATION-CONTRACT.md +62 -39
  30. package/docs/RUNTIME-COMPAT-MATRIX.md +99 -156
  31. package/docs/SKILL-AUTHORING.md +94 -73
  32. package/docs/WORKFLOW-LIFECYCLE.md +93 -189
  33. package/hooks/README.md +17 -37
  34. package/hooks/_common.py +113 -0
  35. package/hooks/adapters/codex.py +9 -16
  36. package/hooks/adapters/grok.py +5 -5
  37. package/hooks/adapters/kimi.py +8 -14
  38. package/hooks/block_dangerous_commands.py +95 -0
  39. package/hooks/compact_context.py +65 -0
  40. package/hooks/mid_workflow_recall.py +25 -0
  41. package/hooks/post_edit_guard.py +105 -0
  42. package/hooks/session_context.py +30 -0
  43. package/package.json +17 -52
  44. package/skills/ultra-change/SKILL.md +97 -50
  45. package/skills/ultra-change/references/change-contract.md +40 -1
  46. package/skills/ultra-delegate/SKILL.md +82 -0
  47. package/skills/ultra-delegate/references/delegation-contract.md +51 -0
  48. package/skills/ultra-delegate/scripts/delegate_wait.py +86 -0
  49. package/skills/ultra-deliver/SKILL.md +61 -42
  50. package/skills/ultra-deliver/references/baseline-reconciliation.md +39 -20
  51. package/skills/ultra-dev/SKILL.md +96 -62
  52. package/skills/ultra-dev/references/debugging.md +22 -0
  53. package/skills/ultra-domain-modeling/SKILL.md +79 -0
  54. package/skills/ultra-grilling/SKILL.md +79 -0
  55. package/skills/ultra-init/SKILL.md +94 -37
  56. package/skills/ultra-init/references/brownfield-adoption.md +33 -83
  57. package/skills/ultra-init/scripts/init_project.cjs +84 -0
  58. package/skills/ultra-plan/SKILL.md +88 -68
  59. package/skills/ultra-research/SKILL.md +62 -48
  60. package/skills/ultra-research/references/00-problem-validation.md +5 -5
  61. package/skills/ultra-research/references/01-opportunity-discovery.md +3 -3
  62. package/skills/ultra-research/references/02-market-assessment.md +5 -4
  63. package/skills/ultra-research/references/03-competitive-landscape.md +3 -3
  64. package/skills/ultra-research/references/04-product-strategy.md +3 -3
  65. package/skills/ultra-research/references/05-assumptions-validation.md +5 -5
  66. package/skills/ultra-research/references/10-user-personas.md +3 -2
  67. package/skills/ultra-research/references/11-user-scenarios.md +3 -3
  68. package/skills/ultra-research/references/20-user-stories.md +4 -3
  69. package/skills/ultra-research/references/21-features-scope.md +3 -2
  70. package/skills/ultra-research/references/22-success-metrics.md +3 -3
  71. package/skills/ultra-research/references/30-architecture-context.md +3 -3
  72. package/skills/ultra-research/references/31-solution-strategy.md +3 -3
  73. package/skills/ultra-research/references/32-building-blocks.md +3 -3
  74. package/skills/ultra-research/references/40-deployment.md +3 -3
  75. package/skills/ultra-research/references/41-quality-risks.md +3 -3
  76. package/skills/ultra-research/references/99-synthesis.md +7 -7
  77. package/skills/ultra-review/SKILL.md +59 -32
  78. package/skills/ultra-review/references/code.md +17 -0
  79. package/skills/ultra-review/references/comments.md +12 -0
  80. package/skills/ultra-review/references/design.md +12 -0
  81. package/skills/ultra-review/references/errors.md +13 -0
  82. package/skills/ultra-review/references/spec.md +13 -0
  83. package/skills/ultra-review/references/tests.md +12 -0
  84. package/skills/ultra-review/references/worker-packet.md +40 -0
  85. package/skills/ultra-review/scripts/review_wait.py +26 -15
  86. package/skills/ultra-status/SKILL.md +61 -36
  87. package/skills/ultra-tdd/SKILL.md +81 -0
  88. package/skills/ultra-tdd/references/templates/README.md +20 -0
  89. package/skills/ultra-tdd/references/templates/feature-flag-default-audit.sh +79 -0
  90. package/skills/ultra-tdd/references/templates/persistence-real.ts +78 -0
  91. package/skills/ultra-tdd/references/templates/testcontainer-postgres.py +78 -0
  92. package/skills/ultra-tdd/references/templates/testcontainer-postgres.ts +73 -0
  93. package/skills/ultra-tdd/references/templates/vertical-slice.ts +66 -0
  94. package/skills/ultra-tdd/references/test-execution.md +18 -0
  95. package/skills/ultra-test/SKILL.md +70 -30
  96. package/skills/ultra-test/references/export-syntax.md +18 -0
  97. package/skills/ultra-test/scripts/worktree_digest.cjs +54 -0
  98. package/skills/ultra-think/SKILL.md +49 -27
  99. package/skills/ultra-think/references/autonomy-boundary.md +48 -0
  100. package/skills/ultra-think/references/interaction-boundary.md +18 -33
  101. package/.ultra-template/docs/research/README.md +0 -55
  102. package/.ultra-template/reports/templates/delivery-report.json +0 -17
  103. package/.ultra-template/reports/templates/test-report.json +0 -18
  104. package/.ultra-template/tasks/tasks.json +0 -15
  105. package/.ultra-template/templates/task-context.md +0 -19
  106. package/adapters/_shared/codex-assets.cjs +0 -725
  107. package/adapters/_shared/codex-ultra-tools-entry.cjs +0 -11
  108. package/adapters/_shared/interaction-contract.cjs +0 -129
  109. package/adapters/_shared/path-rewrite.cjs +0 -79
  110. package/adapters/_shared/runtime-native.cjs +0 -132
  111. package/adapters/_shared/settings-merge.cjs +0 -76
  112. package/agents/code-reviewer.md +0 -42
  113. package/agents/debugger.md +0 -40
  114. package/agents/review-code.md +0 -49
  115. package/agents/review-comments.md +0 -38
  116. package/agents/review-coordinator.md +0 -56
  117. package/agents/review-design.md +0 -40
  118. package/agents/review-errors.md +0 -43
  119. package/agents/review-spec.md +0 -39
  120. package/agents/review-tests.md +0 -40
  121. package/agents/tdd-runner.md +0 -38
  122. package/bin/orchestrator.js +0 -383
  123. package/commands/ultra-change.md +0 -10
  124. package/commands/ultra-deliver.md +0 -10
  125. package/commands/ultra-dev.md +0 -10
  126. package/commands/ultra-doctor.md +0 -10
  127. package/commands/ultra-init.md +0 -10
  128. package/commands/ultra-plan.md +0 -10
  129. package/commands/ultra-research.md +0 -10
  130. package/commands/ultra-review.md +0 -10
  131. package/commands/ultra-status.md +0 -10
  132. package/commands/ultra-test.md +0 -10
  133. package/commands/ultra-think.md +0 -10
  134. package/docs/AGENT-CONTEXT.md +0 -191
  135. package/docs/COMMIT-HASH-BACKFILL.md +0 -51
  136. package/docs/LEGACY-CLI-CROSSWALK.md +0 -175
  137. package/docs/ROADMAP.md +0 -101
  138. package/docs/STATE-DB-ACCESS-POLICY.md +0 -161
  139. package/hooks/active_task_context.py +0 -152
  140. package/hooks/context_envelope.py +0 -100
  141. package/hooks/health_check.py +0 -196
  142. package/hooks/pre_stop_check.py +0 -66
  143. package/hooks/runtime_paths.py +0 -396
  144. package/hooks/subagent_tracker.py +0 -88
  145. package/hooks/workflow_checkpoint.py +0 -76
  146. package/hooks/workflow_context.py +0 -48
  147. package/hooks/workflow_resume.py +0 -84
  148. package/mcp-server/hook-context.cjs +0 -38
  149. package/mcp-server/hook-event.cjs +0 -34
  150. package/mcp-server/lib/archive-journal.cjs +0 -1119
  151. package/mcp-server/lib/archive-mutation-worker.py +0 -365
  152. package/mcp-server/lib/artifact-registry.cjs +0 -1232
  153. package/mcp-server/lib/baseline-workflow.cjs +0 -1193
  154. package/mcp-server/lib/canonical-json.cjs +0 -19
  155. package/mcp-server/lib/change-authority.cjs +0 -26
  156. package/mcp-server/lib/change-packet.cjs +0 -790
  157. package/mcp-server/lib/change-workflow.cjs +0 -65
  158. package/mcp-server/lib/context-envelope.cjs +0 -581
  159. package/mcp-server/lib/context-paths.cjs +0 -142
  160. package/mcp-server/lib/decision-records.cjs +0 -423
  161. package/mcp-server/lib/delivery-transaction.cjs +0 -471
  162. package/mcp-server/lib/doctor-backup-worker.cjs +0 -328
  163. package/mcp-server/lib/doctor.cjs +0 -627
  164. package/mcp-server/lib/git-bootstrap.cjs +0 -651
  165. package/mcp-server/lib/init-project.cjs +0 -1021
  166. package/mcp-server/lib/kernel-change-workflow.cjs +0 -2029
  167. package/mcp-server/lib/legacy-change-workflow.cjs +0 -3032
  168. package/mcp-server/lib/managed-file-write.cjs +0 -172
  169. package/mcp-server/lib/plan-checkpoint.cjs +0 -177
  170. package/mcp-server/lib/plan-publication-worker.cjs +0 -830
  171. package/mcp-server/lib/plan-store.cjs +0 -794
  172. package/mcp-server/lib/prd-parser.cjs +0 -83
  173. package/mcp-server/lib/pricing.cjs +0 -44
  174. package/mcp-server/lib/project-context.cjs +0 -178
  175. package/mcp-server/lib/projector.cjs +0 -386
  176. package/mcp-server/lib/provider-refs.cjs +0 -42
  177. package/mcp-server/lib/runtime-paths.cjs +0 -1687
  178. package/mcp-server/lib/runtime-state.cjs +0 -222
  179. package/mcp-server/lib/safe-project-file.cjs +0 -385
  180. package/mcp-server/lib/stage-checkpoints.cjs +0 -463
  181. package/mcp-server/lib/state-authority.cjs +0 -95
  182. package/mcp-server/lib/state-db.cjs +0 -1580
  183. package/mcp-server/lib/state-ops.cjs +0 -1428
  184. package/mcp-server/lib/task-contract.cjs +0 -404
  185. package/mcp-server/lib/task-expander.cjs +0 -105
  186. package/mcp-server/lib/task-ledger.cjs +0 -1964
  187. package/mcp-server/lib/telemetry.cjs +0 -85
  188. package/mcp-server/lib/topo.cjs +0 -131
  189. package/mcp-server/lib/ultra-facade.cjs +0 -2684
  190. package/mcp-server/lib/worker-packet.cjs +0 -358
  191. package/mcp-server/server.cjs +0 -437
  192. package/orchestrator/auto-merge.cjs +0 -128
  193. package/orchestrator/daemon.cjs +0 -264
  194. package/orchestrator/dispatch-rules.cjs +0 -78
  195. package/orchestrator/parallel-orchestrator.cjs +0 -903
  196. package/orchestrator/planner/plan-builder.cjs +0 -125
  197. package/orchestrator/recovery.cjs +0 -188
  198. package/orchestrator/session-close-journal-worker.cjs +0 -5
  199. package/orchestrator/session-close-journal.cjs +0 -1014
  200. package/orchestrator/session-runner.cjs +0 -1153
  201. package/orchestrator/worktree-manager.cjs +0 -282
  202. package/settings.json +0 -7
  203. package/skills/cc-collab/SKILL.md +0 -42
  204. package/skills/code-review-expert/SKILL.md +0 -43
  205. package/skills/code-review-expert/references/correctness-reliability.md +0 -30
  206. package/skills/code-review-expert/references/design-boundaries.md +0 -26
  207. package/skills/code-review-expert/references/removal-plan.md +0 -24
  208. package/skills/codex-collab/SKILL.md +0 -49
  209. package/skills/codex-collab/evals/evals.json +0 -35
  210. package/skills/integration-rules/SKILL.md +0 -32
  211. package/skills/security-rules/SKILL.md +0 -38
  212. package/skills/testing-rules/SKILL.md +0 -32
  213. package/skills/ultra-doctor/SKILL.md +0 -41
  214. package/skills/ultra-plan/references/semantic-preflight.md +0 -20
  215. package/skills/ultra-verify/SKILL.md +0 -46
  216. package/skills/ultra-verify/evals/evals.json +0 -46
  217. package/skills/ultra-verify/references/cross-verify-modes.md +0 -28
  218. package/skills/ultra-verify/references/evidence-status.md +0 -21
  219. package/skills/ultra-verify/scripts/verify_wait.py +0 -94
  220. package/spec/cli-protocol.md +0 -102
  221. package/spec/mcp-tools.yaml +0 -312
  222. package/spec/schemas/baseline-reconciliation.v1.schema.json +0 -73
  223. package/spec/schemas/change-delta.v1.schema.json +0 -153
  224. package/spec/schemas/command-manifest.schema.json +0 -29
  225. package/spec/schemas/context-file.v4.5.schema.json +0 -54
  226. package/spec/schemas/delivery-report.v1.schema.json +0 -66
  227. package/spec/schemas/documentation-reconciliation.v1.schema.json +0 -106
  228. package/spec/schemas/mcp-tools.schema.json +0 -136
  229. package/spec/schemas/skill-manifest.schema.json +0 -24
  230. package/spec/schemas/state-db.sql +0 -641
  231. package/spec/schemas/task-ledger.v2.schema.json +0 -296
  232. package/spec/schemas/tasks.v4.5.schema.json +0 -96
  233. package/spec/schemas/test-report.v1.schema.json +0 -225
  234. package/ultra-tools/cli.cjs +0 -129
  235. package/ultra-tools/commands/db.cjs +0 -226
  236. package/ultra-tools/commands/legacy-memory.cjs +0 -159
  237. package/ultra-tools/commands/migrate.cjs +0 -1386
  238. package/ultra-tools/commands/session.cjs +0 -213
  239. package/ultra-tools/commands/status.cjs +0 -559
  240. package/ultra-tools/commands/system.cjs +0 -498
  241. package/ultra-tools/commands/task.cjs +0 -105
@@ -1,1687 +0,0 @@
1
- 'use strict';
2
-
3
- const fs = require('node:fs');
4
- const path = require('node:path');
5
- const { createHash, randomUUID } = require('node:crypto');
6
- const { spawnSync } = require('node:child_process');
7
-
8
- const RUNTIME_RELATIVE_DIR = path.join('.ultra', '.runtime');
9
- const STATE_DB_RELATIVE_PATH = path.join(RUNTIME_RELATIVE_DIR, 'state.db');
10
- const LEGACY_STATE_DB_RELATIVE_PATH = path.join('.ultra', 'state.db');
11
- const STATE_SUFFIXES = Object.freeze(['', '-wal', '-shm']);
12
- const STATE_TOMBSTONE_MARKER = 'MIGRATED_TO_RUNTIME.json';
13
- const STATE_TOMBSTONE_KIND = 'ultra-state-migration-tombstone';
14
- const LEGACY_RUNTIME_DIRS = Object.freeze([
15
- ['backups', 'backups'],
16
- ['collab', 'collab'],
17
- ['sessions', 'sessions'],
18
- ['telemetry', 'telemetry'],
19
- ['debug', 'debug'],
20
- ['orchestrator', 'orchestrator'],
21
- ['runtime', '.'],
22
- ]);
23
- const LEGACY_RUNTIME_FILES = Object.freeze([
24
- ['orchestrator.pid', path.join('orchestrator', 'orchestrator.pid')],
25
- ['orchestrator.log', path.join('orchestrator', 'orchestrator.log')],
26
- ]);
27
- const HELD_MIGRATION_GATE = Symbol('held-migration-gate');
28
-
29
- class RuntimePathError extends Error {
30
- constructor(code, message, { cause, details } = {}) {
31
- super(message);
32
- this.name = 'RuntimePathError';
33
- this.code = code;
34
- if (cause) this.cause = cause;
35
- if (details) this.details = details;
36
- }
37
- }
38
-
39
- function lstatOrNull(candidate) {
40
- try {
41
- return fs.lstatSync(candidate);
42
- } catch (error) {
43
- if (error.code === 'ENOENT') return null;
44
- throw error;
45
- }
46
- }
47
-
48
- function isContainedPath(base, candidate) {
49
- const relative = path.relative(base, candidate);
50
- return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..'
51
- && !path.isAbsolute(relative));
52
- }
53
-
54
- function physicalPathCandidate(candidate) {
55
- let existing = path.resolve(candidate);
56
- while (!lstatOrNull(existing)) {
57
- const parent = path.dirname(existing);
58
- if (parent === existing) break;
59
- existing = parent;
60
- }
61
- const physicalExisting = fs.realpathSync(existing);
62
- return path.resolve(physicalExisting, path.relative(existing, path.resolve(candidate)));
63
- }
64
-
65
- function assertSafeRoot(rootDir) {
66
- const root = path.resolve(rootDir || process.cwd());
67
- const stat = lstatOrNull(root);
68
- if (!stat) {
69
- throw new RuntimePathError('RUNTIME_ROOT_INVALID', `project root does not exist: ${root}`);
70
- }
71
- if (stat.isSymbolicLink() || !stat.isDirectory()) {
72
- throw new RuntimePathError(
73
- 'RUNTIME_ROOT_INVALID',
74
- `project root must be a real directory, not a symlink or special entry: ${root}`,
75
- );
76
- }
77
- return root;
78
- }
79
-
80
- function assertRegularFileIfPresent(candidate, label) {
81
- const stat = lstatOrNull(candidate);
82
- if (!stat) return null;
83
- if (stat.isSymbolicLink() || !stat.isFile()) {
84
- throw new RuntimePathError(
85
- 'RUNTIME_PATH_UNSAFE',
86
- `${label} must be a regular file and may not be a symlink: ${candidate}`,
87
- { details: { path: candidate } },
88
- );
89
- }
90
- return stat;
91
- }
92
-
93
- function assertDirectoryIfPresent(candidate, label) {
94
- const stat = lstatOrNull(candidate);
95
- if (!stat) return null;
96
- if (stat.isSymbolicLink() || !stat.isDirectory()) {
97
- throw new RuntimePathError(
98
- 'RUNTIME_PATH_UNSAFE',
99
- `${label} must be a real directory and may not be a symlink: ${candidate}`,
100
- { details: { path: candidate } },
101
- );
102
- }
103
- return stat;
104
- }
105
-
106
- function pathsFor(rootDir) {
107
- const root = path.resolve(rootDir || process.cwd());
108
- const ultraDir = path.join(root, '.ultra');
109
- const runtimeDir = path.join(ultraDir, '.runtime');
110
- return {
111
- rootDir: root,
112
- ultraDir,
113
- runtimeDir,
114
- stateDbPath: path.join(runtimeDir, 'state.db'),
115
- legacyStateDbPath: path.join(ultraDir, 'state.db'),
116
- backupsDir: path.join(runtimeDir, 'backups'),
117
- collabDir: path.join(runtimeDir, 'collab'),
118
- sessionsDir: path.join(runtimeDir, 'sessions'),
119
- worktreesDir: path.join(runtimeDir, 'worktrees'),
120
- telemetryDir: path.join(runtimeDir, 'telemetry'),
121
- debugDir: path.join(runtimeDir, 'debug'),
122
- orchestratorDir: path.join(runtimeDir, 'orchestrator'),
123
- checkpointPath: path.join(runtimeDir, 'checkpoint.json'),
124
- orchestratorPidPath: path.join(runtimeDir, 'orchestrator', 'orchestrator.pid'),
125
- orchestratorLogPath: path.join(runtimeDir, 'orchestrator', 'orchestrator.log'),
126
- };
127
- }
128
-
129
- function explicitStateDbPath(env = process.env) {
130
- const configured = typeof env?.UBP_DB_PATH === 'string' ? env.UBP_DB_PATH.trim() : '';
131
- return configured ? path.resolve(configured) : null;
132
- }
133
-
134
- function managedStateTombstone(mainPath) {
135
- const stat = lstatOrNull(mainPath);
136
- if (!stat || stat.isSymbolicLink()) return null;
137
- let markerPath = mainPath;
138
- if (stat.isDirectory()) {
139
- markerPath = path.join(mainPath, STATE_TOMBSTONE_MARKER);
140
- const entries = fs.readdirSync(mainPath);
141
- const markerStat = lstatOrNull(markerPath);
142
- if (entries.length !== 1
143
- || entries[0] !== STATE_TOMBSTONE_MARKER
144
- || !markerStat?.isFile()
145
- || markerStat.isSymbolicLink()) {
146
- return null;
147
- }
148
- } else if (!stat.isFile()) {
149
- return null;
150
- }
151
- let marker;
152
- try {
153
- marker = JSON.parse(fs.readFileSync(markerPath, 'utf8'));
154
- } catch {
155
- return null;
156
- }
157
- const canonicalPath = path.resolve(path.dirname(mainPath), marker.canonical_state_db || '');
158
- const expected = path.join(path.dirname(mainPath), '.runtime', 'state.db');
159
- if (marker.version !== 1
160
- || marker.kind !== STATE_TOMBSTONE_KIND
161
- || canonicalPath !== expected) {
162
- return null;
163
- }
164
- return { markerPath, canonicalPath, marker };
165
- }
166
-
167
- function isManagedLegacyStateTombstone(mainPath) {
168
- return Boolean(managedStateTombstone(mainPath));
169
- }
170
-
171
- function assertStateSetSafe(mainPath, label, { allowManagedTombstone = false } = {}) {
172
- const mainStat = lstatOrNull(mainPath);
173
- const tombstone = allowManagedTombstone ? managedStateTombstone(mainPath) : null;
174
- let main = null;
175
- if (mainStat && !tombstone) {
176
- main = assertRegularFileIfPresent(mainPath, `${label} state.db`);
177
- }
178
- const wal = assertRegularFileIfPresent(`${mainPath}-wal`, `${label} state.db-wal`);
179
- const shm = assertRegularFileIfPresent(`${mainPath}-shm`, `${label} state.db-shm`);
180
- if ((!main || tombstone) && (wal || shm)) {
181
- throw new RuntimePathError(
182
- 'RUNTIME_ORPHAN_SIDECAR',
183
- `${label} SQLite sidecar exists without its state.db authority`,
184
- {
185
- details: {
186
- state_db_path: mainPath,
187
- wal_path: wal ? `${mainPath}-wal` : null,
188
- shm_path: shm ? `${mainPath}-shm` : null,
189
- },
190
- },
191
- );
192
- }
193
- return { main, wal, shm, tombstone };
194
- }
195
-
196
- function runtimeLinkMatchesConfiguredDb(paths, configuredDbPath) {
197
- const runtimeStat = lstatOrNull(paths.runtimeDir);
198
- if (!runtimeStat?.isSymbolicLink() || !configuredDbPath) return false;
199
- if (path.basename(configuredDbPath) !== 'state.db') return false;
200
- try {
201
- return fs.realpathSync(paths.runtimeDir) === fs.realpathSync(path.dirname(configuredDbPath))
202
- && fs.realpathSync(path.join(paths.runtimeDir, 'state.db'))
203
- === fs.realpathSync(configuredDbPath);
204
- } catch {
205
- return false;
206
- }
207
- }
208
-
209
- function isIntentionalTaskAuthorityLink(paths, candidate, physicalRuntimeDir) {
210
- const relative = path.relative(paths.runtimeDir, candidate);
211
- const parts = relative.split(path.sep);
212
- if (parts.length !== 4
213
- || parts[0] !== 'worktrees'
214
- || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(parts[1])
215
- || parts[2] !== '.ultra'
216
- || parts[3] !== '.runtime') {
217
- return false;
218
- }
219
- try {
220
- return fs.realpathSync(candidate) === physicalRuntimeDir
221
- && fs.realpathSync(path.join(candidate, 'state.db'))
222
- === fs.realpathSync(paths.stateDbPath);
223
- } catch {
224
- return false;
225
- }
226
- }
227
-
228
- function assertRegisteredWorktreeBoundary(paths, candidate, physicalRuntimeDir) {
229
- const sid = path.basename(candidate);
230
- if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(sid)) {
231
- throw new RuntimePathError(
232
- 'RUNTIME_PATH_UNSAFE',
233
- `registered worktree has an unsafe session id: ${candidate}`,
234
- { details: { path: candidate } },
235
- );
236
- }
237
- const authorityLink = path.join(candidate, '.ultra', '.runtime');
238
- const linkStat = lstatOrNull(authorityLink);
239
- if (!linkStat?.isSymbolicLink()
240
- || !isIntentionalTaskAuthorityLink(paths, authorityLink, physicalRuntimeDir)) {
241
- throw new RuntimePathError(
242
- 'RUNTIME_PATH_UNSAFE',
243
- `registered worktree must contain the exact central Ultra authority link: ${authorityLink}`,
244
- { details: { path: candidate, authority_link: authorityLink } },
245
- );
246
- }
247
- }
248
-
249
- function assertRuntimeTreeSafe(paths) {
250
- const runtimeStat = lstatOrNull(paths.runtimeDir);
251
- if (!runtimeStat) return;
252
- let physicalRuntimeDir;
253
- try {
254
- physicalRuntimeDir = fs.realpathSync(paths.runtimeDir);
255
- } catch (error) {
256
- throw new RuntimePathError(
257
- 'RUNTIME_PATH_UNSAFE',
258
- `canonical runtime root cannot be resolved: ${paths.runtimeDir}`,
259
- { cause: error, details: { path: paths.runtimeDir } },
260
- );
261
- }
262
- let registered = null;
263
- const pending = fs.readdirSync(paths.runtimeDir)
264
- .map((entry) => path.join(paths.runtimeDir, entry));
265
- while (pending.length > 0) {
266
- const candidate = pending.pop();
267
- const stat = lstatOrNull(candidate);
268
- if (!stat) continue;
269
- if (stat.isSymbolicLink()) {
270
- if (isIntentionalTaskAuthorityLink(paths, candidate, physicalRuntimeDir)) continue;
271
- throw new RuntimePathError(
272
- 'RUNTIME_PATH_UNSAFE',
273
- `canonical runtime entry may not be a symlink: ${candidate}`,
274
- { details: { path: candidate } },
275
- );
276
- }
277
- if (!stat.isDirectory() && !stat.isFile()) {
278
- throw new RuntimePathError(
279
- 'RUNTIME_PATH_UNSAFE',
280
- `canonical runtime entry must be a regular file or real directory: ${candidate}`,
281
- { details: { path: candidate } },
282
- );
283
- }
284
- let physicalCandidate;
285
- try {
286
- physicalCandidate = fs.realpathSync(candidate);
287
- } catch (error) {
288
- throw new RuntimePathError(
289
- 'RUNTIME_PATH_UNSAFE',
290
- `canonical runtime entry cannot be resolved: ${candidate}`,
291
- { cause: error, details: { path: candidate } },
292
- );
293
- }
294
- if (!isContainedPath(physicalRuntimeDir, physicalCandidate)) {
295
- throw new RuntimePathError(
296
- 'RUNTIME_PATH_UNSAFE',
297
- `canonical runtime entry escapes its physical root: ${candidate}`,
298
- {
299
- details: {
300
- path: candidate,
301
- resolved_path: physicalCandidate,
302
- runtime_root: physicalRuntimeDir,
303
- },
304
- },
305
- );
306
- }
307
- const relative = path.relative(paths.runtimeDir, candidate);
308
- const relativeParts = relative.split(path.sep);
309
- if (stat.isDirectory()
310
- && relativeParts.length === 2
311
- && relativeParts[0] === 'worktrees') {
312
- if (registered === null) registered = registeredWorktrees(paths.rootDir);
313
- if (registered.has(physicalCandidate)) {
314
- assertRegisteredWorktreeBoundary(paths, candidate, physicalRuntimeDir);
315
- // A Git checkout owns its tracked tree. Ultra validates the direct
316
- // managed child and authority link, then leaves repository symlinks
317
- // and other tracked entries to Git instead of treating them as
318
- // runtime artifacts.
319
- continue;
320
- }
321
- }
322
- if (stat.isDirectory()) {
323
- for (const entry of fs.readdirSync(candidate)) {
324
- pending.push(path.join(candidate, entry));
325
- }
326
- }
327
- }
328
- }
329
-
330
- function validateProjectLayout(rootDir, {
331
- env = process.env,
332
- allowConfiguredRuntimeLink = true,
333
- forMutation = false,
334
- validateRuntimeTree = false,
335
- } = {}) {
336
- const root = assertSafeRoot(rootDir);
337
- const paths = pathsFor(root);
338
- assertDirectoryIfPresent(paths.ultraDir, '.ultra');
339
- const configured = explicitStateDbPath(env);
340
- if (configured) assertStateSetSafe(configured, 'configured');
341
- const runtimeStat = lstatOrNull(paths.runtimeDir);
342
- if (runtimeStat?.isSymbolicLink()) {
343
- const allowed = !forMutation
344
- && allowConfiguredRuntimeLink
345
- && runtimeLinkMatchesConfiguredDb(paths, configured);
346
- if (!allowed) {
347
- throw new RuntimePathError(
348
- 'RUNTIME_PATH_UNSAFE',
349
- `.ultra/.runtime may only be a task link to the explicitly configured authority: ${paths.runtimeDir}`,
350
- { details: { path: paths.runtimeDir, configured_state_db_path: configured } },
351
- );
352
- }
353
- } else if (runtimeStat && !runtimeStat.isDirectory()) {
354
- throw new RuntimePathError(
355
- 'RUNTIME_PATH_UNSAFE',
356
- `.ultra/.runtime must be a real directory: ${paths.runtimeDir}`,
357
- { details: { path: paths.runtimeDir } },
358
- );
359
- }
360
- assertStateSetSafe(paths.legacyStateDbPath, 'legacy', { allowManagedTombstone: true });
361
- assertStateSetSafe(paths.stateDbPath, 'runtime');
362
- if (validateRuntimeTree) assertRuntimeTreeSafe(paths);
363
- return { ...paths, configuredStateDbPath: configured, runtimeLinked: runtimeStat?.isSymbolicLink() };
364
- }
365
-
366
- function assertNoCompetingState(paths) {
367
- const legacy = lstatOrNull(paths.legacyStateDbPath);
368
- const runtime = lstatOrNull(paths.stateDbPath);
369
- if (!legacy || !runtime || managedStateTombstone(paths.legacyStateDbPath)) return;
370
- throw new RuntimePathError(
371
- 'RUNTIME_STATE_CONFLICT',
372
- 'both legacy .ultra/state.db and runtime .ultra/.runtime/state.db exist; refusing to choose either authority',
373
- {
374
- details: {
375
- legacy_state_db_path: paths.legacyStateDbPath,
376
- runtime_state_db_path: paths.stateDbPath,
377
- },
378
- },
379
- );
380
- }
381
-
382
- function samePhysicalAuthority(left, right) {
383
- if (path.resolve(left) === path.resolve(right)) return true;
384
- if (!lstatOrNull(left) || !lstatOrNull(right)) return false;
385
- try {
386
- return fs.realpathSync(left) === fs.realpathSync(right);
387
- } catch {
388
- return false;
389
- }
390
- }
391
-
392
- function assertConfiguredAuthorityBinding(paths) {
393
- const configured = paths.configuredStateDbPath;
394
- if (!configured) return;
395
- const active = lstatOrNull(paths.stateDbPath)
396
- ? paths.stateDbPath
397
- : (lstatOrNull(paths.legacyStateDbPath)
398
- && !managedStateTombstone(paths.legacyStateDbPath)
399
- ? paths.legacyStateDbPath
400
- : null);
401
- const allowed = active
402
- ? samePhysicalAuthority(configured, active)
403
- : physicalPathCandidate(configured) === physicalPathCandidate(paths.stateDbPath);
404
- if (allowed && !paths.runtimeLinked) return;
405
- if (allowed && paths.runtimeLinked) {
406
- let authorityRoot;
407
- let authorityPaths;
408
- let physicalTaskRoot;
409
- let physicalWorktreesRoot;
410
- let sid;
411
- try {
412
- authorityRoot = projectRootFromStateDbPath(configured);
413
- authorityPaths = pathsFor(authorityRoot);
414
- if (!samePhysicalAuthority(configured, authorityPaths.stateDbPath)) {
415
- throw new Error('configured DB is not a canonical project runtime authority');
416
- }
417
- physicalTaskRoot = fs.realpathSync(paths.rootDir);
418
- physicalWorktreesRoot = fs.realpathSync(authorityPaths.worktreesDir);
419
- const relative = path.relative(physicalWorktreesRoot, physicalTaskRoot);
420
- const parts = relative.split(path.sep);
421
- if (parts.length !== 1
422
- || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(parts[0])) {
423
- throw new Error('task root is not a direct managed worktree child');
424
- }
425
- [sid] = parts;
426
- const registered = registeredWorktrees(authorityRoot);
427
- if (!registered.has(physicalTaskRoot)) {
428
- throw new Error('task root is not a registered Git worktree');
429
- }
430
- if (!runtimeLinkMatchesConfiguredDb(paths, configured)) {
431
- throw new Error('task authority link does not resolve to the configured DB');
432
- }
433
- // Open read-only only after the complete filesystem and Git binding is
434
- // proven. The row is the durable session-to-worktree ownership record.
435
- // eslint-disable-next-line global-require
436
- const Database = require('better-sqlite3');
437
- const db = new Database(configured, { readonly: true, fileMustExist: true });
438
- try {
439
- const session = db.prepare(
440
- 'SELECT sid, worktree_path FROM sessions WHERE sid = ?',
441
- ).get(sid);
442
- if (!session) throw new Error(`authority has no session binding for ${sid}`);
443
- let recorded;
444
- try { recorded = fs.realpathSync(session.worktree_path); }
445
- catch { recorded = path.resolve(session.worktree_path); }
446
- if (recorded !== physicalTaskRoot) {
447
- throw new Error(`session ${sid} is bound to a different worktree`);
448
- }
449
- } finally {
450
- db.close();
451
- }
452
- return;
453
- } catch (error) {
454
- throw new RuntimePathError(
455
- 'RUNTIME_AUTHORITY_MISMATCH',
456
- `task root is not bound to the configured Ultra authority: ${error.message}`,
457
- {
458
- cause: error,
459
- details: {
460
- project_root: paths.rootDir,
461
- configured_state_db_path: configured,
462
- authority_root: authorityRoot || null,
463
- session_id: sid || null,
464
- },
465
- },
466
- );
467
- }
468
- }
469
- throw new RuntimePathError(
470
- 'RUNTIME_AUTHORITY_MISMATCH',
471
- `UBP_DB_PATH does not name this project's canonical or task-linked authority: ${configured}`,
472
- {
473
- details: {
474
- project_root: paths.rootDir,
475
- configured_state_db_path: configured,
476
- project_state_db_path: active || paths.stateDbPath,
477
- },
478
- },
479
- );
480
- }
481
-
482
- function locateStateDb(rootDir, { env = process.env } = {}) {
483
- const paths = validateProjectLayout(rootDir, { env });
484
- assertNoCompetingState(paths);
485
- assertConfiguredAuthorityBinding(paths);
486
- if (paths.configuredStateDbPath) return paths.configuredStateDbPath;
487
- if (lstatOrNull(paths.stateDbPath)) return paths.stateDbPath;
488
- if (lstatOrNull(paths.legacyStateDbPath)
489
- && !managedStateTombstone(paths.legacyStateDbPath)) {
490
- return paths.legacyStateDbPath;
491
- }
492
- return paths.stateDbPath;
493
- }
494
-
495
- function projectRootFromStateDbPath(dbPath) {
496
- const resolved = path.resolve(dbPath);
497
- if (path.basename(resolved) !== 'state.db') return path.dirname(resolved);
498
- const parent = path.dirname(resolved);
499
- if (path.basename(parent) === '.runtime'
500
- && path.basename(path.dirname(parent)) === '.ultra') {
501
- return path.dirname(path.dirname(parent));
502
- }
503
- if (path.basename(parent) === '.ultra') return path.dirname(parent);
504
- return path.dirname(resolved);
505
- }
506
-
507
- function digestFile(file) {
508
- const hash = createHash('sha256');
509
- hash.update(fs.readFileSync(file));
510
- return hash.digest('hex');
511
- }
512
-
513
- function verifiedCopy(source, target) {
514
- fs.copyFileSync(source, target, fs.constants.COPYFILE_EXCL);
515
- if (fs.statSync(source).size !== fs.statSync(target).size
516
- || digestFile(source) !== digestFile(target)) {
517
- throw new RuntimePathError(
518
- 'RUNTIME_STATE_BACKUP_INVALID',
519
- `backup verification failed for ${source}`,
520
- );
521
- }
522
- }
523
-
524
- function atomicVerifiedCopy(source, target) {
525
- fs.mkdirSync(path.dirname(target), { recursive: true });
526
- const stage = path.join(
527
- path.dirname(target),
528
- `.${path.basename(target)}.stage-${process.pid}-${randomUUID()}`,
529
- );
530
- try {
531
- verifiedCopy(source, stage);
532
- fs.renameSync(stage, target);
533
- } finally {
534
- fs.rmSync(stage, { force: true });
535
- }
536
- }
537
-
538
- function timestampSlug(now) {
539
- return now().toISOString().replace(/[:.]/g, '-');
540
- }
541
-
542
- function createMigrationBackup(paths, now) {
543
- fs.mkdirSync(paths.backupsDir, { recursive: true });
544
- const prefix = `legacy-state-${timestampSlug(now)}`;
545
- let backupPath = path.join(paths.backupsDir, prefix);
546
- let attempt = 0;
547
- while (fs.existsSync(backupPath)) {
548
- attempt += 1;
549
- backupPath = path.join(paths.backupsDir, `${prefix}-${attempt}`);
550
- }
551
- fs.mkdirSync(backupPath, { recursive: false });
552
- try {
553
- for (const suffix of STATE_SUFFIXES) {
554
- const source = `${paths.legacyStateDbPath}${suffix}`;
555
- if (!fs.existsSync(source)) continue;
556
- verifiedCopy(source, path.join(backupPath, `state.db${suffix}`));
557
- }
558
- } catch (error) {
559
- throw error instanceof RuntimePathError ? error : new RuntimePathError(
560
- 'RUNTIME_STATE_BACKUP_FAILED',
561
- `could not back up legacy Ultra state: ${error.message}`,
562
- { cause: error },
563
- );
564
- }
565
- return backupPath;
566
- }
567
-
568
- function isSQLiteDatabase(candidate) {
569
- const descriptor = fs.openSync(candidate, 'r');
570
- try {
571
- const header = Buffer.alloc(16);
572
- return fs.readSync(descriptor, header, 0, header.length, 0) === header.length
573
- && header.equals(Buffer.from('SQLite format 3\0'));
574
- } finally {
575
- fs.closeSync(descriptor);
576
- }
577
- }
578
-
579
- function processStartMarker(pid) {
580
- if (!Number.isInteger(pid) || pid <= 0) return null;
581
- const result = spawnSync('ps', ['-o', 'lstart=', '-p', String(pid)], {
582
- encoding: 'utf8',
583
- stdio: ['ignore', 'pipe', 'ignore'],
584
- });
585
- if (result.status !== 0) return null;
586
- return String(result.stdout || '').trim() || null;
587
- }
588
-
589
- function processIsAlive(pid) {
590
- if (!Number.isInteger(pid) || pid <= 0) return false;
591
- try {
592
- process.kill(pid, 0);
593
- return true;
594
- } catch (error) {
595
- if (error.code === 'ESRCH') return false;
596
- return true;
597
- }
598
- }
599
-
600
- function readMigrationGate(gatePath) {
601
- const stat = lstatOrNull(gatePath);
602
- if (!stat || stat.isSymbolicLink() || !stat.isFile()) return null;
603
- try {
604
- const owner = JSON.parse(fs.readFileSync(gatePath, 'utf8'));
605
- return { owner, stat };
606
- } catch {
607
- return null;
608
- }
609
- }
610
-
611
- function reclaimDeadMigrationGate(gatePath, observed) {
612
- const quarantine = `${gatePath}.stale-${process.pid}-${randomUUID()}`;
613
- fs.renameSync(gatePath, quarantine);
614
- try {
615
- const moved = fs.lstatSync(quarantine);
616
- if (moved.dev !== observed.stat.dev || moved.ino !== observed.stat.ino) {
617
- if (!lstatOrNull(gatePath)) fs.renameSync(quarantine, gatePath);
618
- throw new RuntimePathError(
619
- 'RUNTIME_STATE_NOT_QUIESCENT',
620
- `state migration gate changed while reclaiming a dead owner: ${gatePath}`,
621
- );
622
- }
623
- } finally {
624
- fs.rmSync(quarantine, { force: true });
625
- }
626
- }
627
-
628
- function waitForMigrationGate(ms) {
629
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
630
- }
631
-
632
- function acquireStateMigrationGate(paths, {
633
- timeoutMs = 5000,
634
- retryMs = 25,
635
- } = {}) {
636
- const gatePath = path.join(paths.runtimeDir, 'state-migration.lock');
637
- const token = randomUUID();
638
- const deadline = Date.now() + timeoutMs;
639
- let descriptor;
640
- while (descriptor === undefined) {
641
- try {
642
- descriptor = fs.openSync(gatePath, 'wx', 0o600);
643
- fs.writeFileSync(descriptor, `${JSON.stringify({
644
- version: 2,
645
- pid: process.pid,
646
- owner_started_at: processStartMarker(process.pid),
647
- token,
648
- legacy_state_db: paths.legacyStateDbPath,
649
- runtime_state_db: paths.stateDbPath,
650
- })}\n`);
651
- fs.fsyncSync(descriptor);
652
- break;
653
- } catch (error) {
654
- if (descriptor !== undefined) {
655
- try { fs.closeSync(descriptor); } catch { /* best effort */ }
656
- descriptor = undefined;
657
- }
658
- if (error.code !== 'EEXIST') throw error;
659
- const observed = readMigrationGate(gatePath);
660
- const ownerPid = Number(observed?.owner?.pid);
661
- const live = processIsAlive(ownerPid);
662
- const currentStart = live ? processStartMarker(ownerPid) : null;
663
- const sameOwner = live && (
664
- !observed?.owner?.owner_started_at
665
- || !currentStart
666
- || observed.owner.owner_started_at === currentStart
667
- );
668
- if (!observed) {
669
- throw new RuntimePathError(
670
- 'RUNTIME_STATE_NOT_QUIESCENT',
671
- `the Ultra state migration gate is malformed or unsafe: ${gatePath}`,
672
- { cause: error, details: { gate_path: gatePath, owner_pid: ownerPid || null } },
673
- );
674
- }
675
- if (sameOwner) {
676
- if (ownerPid === process.pid || Date.now() >= deadline) {
677
- throw new RuntimePathError(
678
- 'RUNTIME_STATE_NOT_QUIESCENT',
679
- `another Ultra state migration owns the process gate: ${gatePath}`,
680
- { cause: error, details: { gate_path: gatePath, owner_pid: ownerPid || null } },
681
- );
682
- }
683
- waitForMigrationGate(Math.min(retryMs, Math.max(1, deadline - Date.now())));
684
- continue;
685
- }
686
- reclaimDeadMigrationGate(gatePath, observed);
687
- }
688
- }
689
- return () => {
690
- try {
691
- fs.closeSync(descriptor);
692
- } finally {
693
- const current = readMigrationGate(gatePath);
694
- if (current?.owner?.token === token) fs.rmSync(gatePath, { force: true });
695
- }
696
- };
697
- }
698
-
699
- function createStateTombstone(paths, { beforePublish } = {}) {
700
- const stage = path.join(
701
- paths.ultraDir,
702
- `.state-tombstone-${process.pid}-${randomUUID()}`,
703
- );
704
- fs.writeFileSync(stage, `${JSON.stringify({
705
- version: 1,
706
- kind: STATE_TOMBSTONE_KIND,
707
- canonical_state_db: path.join('.runtime', 'state.db'),
708
- }, null, 2)}\n`, { flag: 'wx', mode: 0o444 });
709
- try {
710
- if (beforePublish) beforePublish({
711
- legacyStateDbPath: paths.legacyStateDbPath,
712
- runtimeStateDbPath: paths.stateDbPath,
713
- });
714
- fs.renameSync(stage, paths.legacyStateDbPath);
715
- if (!managedStateTombstone(paths.legacyStateDbPath)) {
716
- throw new RuntimePathError(
717
- 'RUNTIME_STATE_MIGRATION_FAILED',
718
- `could not verify the managed legacy state tombstone: ${paths.legacyStateDbPath}`,
719
- );
720
- }
721
- } finally {
722
- fs.rmSync(stage, { force: true });
723
- }
724
- }
725
-
726
- function removeStateTombstone(candidate) {
727
- const stat = lstatOrNull(candidate);
728
- if (!stat) return;
729
- if (!managedStateTombstone(candidate)) {
730
- throw new RuntimePathError(
731
- 'RUNTIME_STATE_MIGRATION_FAILED',
732
- `legacy state tombstone changed content during migration: ${candidate}`,
733
- );
734
- }
735
- fs.rmSync(candidate, { recursive: true, force: true });
736
- }
737
-
738
- function migrateLegacyState(rootDir, {
739
- now = () => new Date(),
740
- rename = fs.renameSync,
741
- rollbackRename = fs.renameSync,
742
- beforeTombstonePublish = null,
743
- afterGateAcquired = null,
744
- _migrationGateToken = null,
745
- } = {}) {
746
- let paths = validateProjectLayout(rootDir, { forMutation: true, env: {} });
747
- fs.mkdirSync(paths.runtimeDir, { recursive: true });
748
- const releaseGate = _migrationGateToken === HELD_MIGRATION_GATE
749
- ? () => {}
750
- : acquireStateMigrationGate(paths);
751
- let sqlite = false;
752
- let backupPath = null;
753
- const moved = [];
754
- let tombstone = false;
755
- let db = null;
756
- let exclusive = false;
757
- try {
758
- // The gate owner must classify the complete authority layout again. Any
759
- // observation made before waiting on the gate is stale by definition.
760
- paths = validateProjectLayout(rootDir, { forMutation: true, env: {} });
761
- assertNoCompetingState(paths);
762
- const legacyTombstone = managedStateTombstone(paths.legacyStateDbPath);
763
- const legacyExists = Boolean(lstatOrNull(paths.legacyStateDbPath));
764
- const runtimeExists = Boolean(lstatOrNull(paths.stateDbPath));
765
- if (legacyTombstone && runtimeExists) {
766
- return { ...paths, migrated: false, backupPath: null };
767
- }
768
- if (legacyTombstone && !runtimeExists) {
769
- throw new RuntimePathError(
770
- 'RUNTIME_STATE_MISSING',
771
- `managed legacy state metadata points to a missing runtime authority: ${paths.stateDbPath}`,
772
- );
773
- }
774
- if (!legacyExists) {
775
- return { ...paths, migrated: false, backupPath: null };
776
- }
777
- if (runtimeExists) return { ...paths, migrated: false, backupPath: null };
778
- if (afterGateAcquired) afterGateAcquired({ ...paths });
779
-
780
- sqlite = isSQLiteDatabase(paths.legacyStateDbPath);
781
- if (sqlite) {
782
- // A SQLite-consistent hand-off must first drain WAL, switch away from
783
- // pathname-bound sidecars, then hold an exclusive transaction across
784
- // snapshot, rename, and old-path tombstone publication.
785
- // eslint-disable-next-line global-require
786
- const Database = require('better-sqlite3');
787
- db = new Database(paths.legacyStateDbPath, { fileMustExist: true });
788
- db.pragma('busy_timeout = 0');
789
- const checkpoint = db.pragma('wal_checkpoint(TRUNCATE)');
790
- if (checkpoint.some((row) => Number(row.busy) !== 0)) {
791
- throw new RuntimePathError(
792
- 'RUNTIME_STATE_NOT_QUIESCENT',
793
- 'legacy Ultra state still has a busy WAL writer; migration was not started',
794
- );
795
- }
796
- const journalMode = String(db.pragma('journal_mode = DELETE', { simple: true })).toLowerCase();
797
- if (journalMode !== 'delete') {
798
- throw new RuntimePathError(
799
- 'RUNTIME_STATE_NOT_QUIESCENT',
800
- `legacy Ultra state could not enter rollback-journal mode: ${journalMode}`,
801
- );
802
- }
803
- db.exec('BEGIN EXCLUSIVE');
804
- exclusive = true;
805
- for (const suffix of ['-wal', '-shm']) {
806
- if (lstatOrNull(`${paths.legacyStateDbPath}${suffix}`)) {
807
- throw new RuntimePathError(
808
- 'RUNTIME_STATE_NOT_QUIESCENT',
809
- `legacy SQLite sidecar remained after checkpoint: ${paths.legacyStateDbPath}${suffix}`,
810
- );
811
- }
812
- }
813
- backupPath = createMigrationBackup(paths, now);
814
- atomicVerifiedCopy(paths.legacyStateDbPath, paths.stateDbPath);
815
- moved.push({
816
- kind: 'snapshot',
817
- source: paths.legacyStateDbPath,
818
- target: paths.stateDbPath,
819
- });
820
- createStateTombstone(paths, { beforePublish: beforeTombstonePublish });
821
- tombstone = true;
822
- db.exec('COMMIT');
823
- exclusive = false;
824
- } else {
825
- backupPath = createMigrationBackup(paths, now);
826
- // Non-SQLite legacy fixtures have no live connection semantics. Preserve
827
- // their complete file set byte-for-byte and keep the main file as the
828
- // final completion marker.
829
- for (const suffix of ['-wal', '-shm', '']) {
830
- const source = `${paths.legacyStateDbPath}${suffix}`;
831
- if (!fs.existsSync(source)) continue;
832
- const target = `${paths.stateDbPath}${suffix}`;
833
- rename(source, target);
834
- moved.push({ source, target });
835
- }
836
- }
837
- } catch (error) {
838
- if (exclusive && db) {
839
- try { db.exec('ROLLBACK'); } catch { /* filesystem rollback remains authoritative */ }
840
- exclusive = false;
841
- }
842
- if (db) {
843
- try { db.close(); } catch { /* continue deterministic filesystem rollback */ }
844
- db = null;
845
- }
846
- const rollbackErrors = [];
847
- if (sqlite) {
848
- try {
849
- fs.rmSync(paths.stateDbPath, { force: true });
850
- if (backupPath && managedStateTombstone(paths.legacyStateDbPath)) {
851
- atomicVerifiedCopy(
852
- path.join(backupPath, 'state.db'),
853
- paths.legacyStateDbPath,
854
- );
855
- }
856
- } catch (rollbackError) {
857
- rollbackErrors.push(`${paths.stateDbPath}: ${rollbackError.message}`);
858
- }
859
- } else {
860
- for (const item of moved.reverse()) {
861
- try {
862
- fs.mkdirSync(path.dirname(item.source), { recursive: true });
863
- rollbackRename(item.target, item.source);
864
- } catch (rollbackError) {
865
- rollbackErrors.push(`${item.target}: ${rollbackError.message}`);
866
- }
867
- }
868
- }
869
- if (error instanceof RuntimePathError
870
- && error.code === 'RUNTIME_STATE_NOT_QUIESCENT'
871
- && rollbackErrors.length === 0) {
872
- throw error;
873
- }
874
- throw new RuntimePathError(
875
- 'RUNTIME_STATE_MIGRATION_FAILED',
876
- `could not move legacy Ultra state into .ultra/.runtime: ${error.message}`
877
- + `${rollbackErrors.length ? `; rollback errors: ${rollbackErrors.join('; ')}` : ''}`,
878
- { cause: error, details: { backup_path: backupPath } },
879
- );
880
- } finally {
881
- if (db) {
882
- if (exclusive) {
883
- try { db.exec('ROLLBACK'); } catch { /* best effort */ }
884
- }
885
- try { db.close(); } catch { /* best effort */ }
886
- }
887
- releaseGate();
888
- }
889
- const result = { ...paths, migrated: true, backupPath };
890
- Object.defineProperty(result, '_transaction', {
891
- value: { moved, rollbackRename, tombstone },
892
- });
893
- return result;
894
- }
895
-
896
- function runGitForMigration(rootDir, args, spawnGit) {
897
- return spawnGit('git', args, {
898
- cwd: rootDir,
899
- encoding: 'utf8',
900
- stdio: ['ignore', 'pipe', 'pipe'],
901
- });
902
- }
903
-
904
- function hasGitMetadata(rootDir) {
905
- let current = path.resolve(rootDir);
906
- while (true) {
907
- if (lstatOrNull(path.join(current, '.git'))) return true;
908
- const parent = path.dirname(current);
909
- if (parent === current) return false;
910
- current = parent;
911
- }
912
- }
913
-
914
- function gitProbeFailure(rootDir, result) {
915
- const detail = String(
916
- result?.error?.message || result?.stderr || result?.stdout || 'unknown Git probe failure',
917
- ).trim();
918
- return new RuntimePathError(
919
- 'WORKTREE_DISCOVERY_FAILED',
920
- `cannot classify repository state before legacy worktree migration: ${detail}`,
921
- { cause: result?.error },
922
- );
923
- }
924
-
925
- function registeredWorktrees(rootDir, { spawnGit = spawnSync } = {}) {
926
- let metadataPresent;
927
- try {
928
- metadataPresent = hasGitMetadata(rootDir);
929
- } catch (error) {
930
- throw new RuntimePathError(
931
- 'WORKTREE_DISCOVERY_FAILED',
932
- `cannot inspect Git metadata before legacy worktree migration: ${error.message}`,
933
- { cause: error },
934
- );
935
- }
936
- let repository;
937
- try {
938
- repository = runGitForMigration(
939
- rootDir,
940
- ['rev-parse', '--is-inside-work-tree'],
941
- spawnGit,
942
- );
943
- } catch (error) {
944
- throw gitProbeFailure(rootDir, { error });
945
- }
946
- const probe = String(repository?.stdout || '').trim();
947
- if (repository?.status !== 0 || repository?.error || probe !== 'true') {
948
- const detail = String(repository?.stderr || repository?.stdout || '');
949
- const explicitlyNonGit = !metadataPresent
950
- && repository?.status !== 0
951
- && /not a git repository/i.test(detail);
952
- const explicitlyOutsideWorktree = !metadataPresent
953
- && repository?.status === 0
954
- && probe === 'false';
955
- if (explicitlyNonGit || explicitlyOutsideWorktree) return new Set();
956
- throw gitProbeFailure(rootDir, repository);
957
- }
958
- let result;
959
- try {
960
- result = runGitForMigration(rootDir, ['worktree', 'list', '--porcelain'], spawnGit);
961
- } catch (error) {
962
- throw new RuntimePathError(
963
- 'WORKTREE_DISCOVERY_FAILED',
964
- `cannot inspect registered Git worktrees: ${error.message}`,
965
- { cause: error },
966
- );
967
- }
968
- if (result.status !== 0 || result.error) {
969
- throw new RuntimePathError(
970
- 'WORKTREE_DISCOVERY_FAILED',
971
- `cannot inspect registered Git worktrees: ${
972
- String(result.error?.message || result.stderr || result.stdout || 'unknown error').trim()
973
- }`,
974
- { cause: result.error },
975
- );
976
- }
977
- return new Set(result.stdout
978
- .split(/\r?\n/)
979
- .filter((line) => line.startsWith('worktree '))
980
- .map((line) => {
981
- const candidate = path.resolve(line.slice('worktree '.length));
982
- try { return fs.realpathSync(candidate); }
983
- catch { return candidate; }
984
- }));
985
- }
986
-
987
- function assertTreeEntrySafe(candidate, {
988
- containmentRoot,
989
- registeredWorktree = false,
990
- canonicalRuntimeDir = null,
991
- canonicalUltraDir = null,
992
- } = {}) {
993
- const stat = lstatOrNull(candidate);
994
- if (!stat) return;
995
- if (stat.isSymbolicLink()) {
996
- let resolved;
997
- try {
998
- resolved = fs.realpathSync(candidate);
999
- } catch (error) {
1000
- throw new RuntimePathError(
1001
- 'RUNTIME_PATH_UNSAFE',
1002
- `legacy runtime symlink cannot be resolved safely: ${candidate}`,
1003
- { cause: error, details: { path: candidate } },
1004
- );
1005
- }
1006
- const relative = path.relative(containmentRoot, candidate);
1007
- const isAuthorityLink = registeredWorktree
1008
- && relative === path.join('.ultra', '.runtime')
1009
- && canonicalRuntimeDir
1010
- && resolved === fs.realpathSync(canonicalRuntimeDir);
1011
- const isLegacyWholeUltraLink = registeredWorktree
1012
- && relative === '.ultra'
1013
- && canonicalUltraDir
1014
- && resolved === fs.realpathSync(canonicalUltraDir);
1015
- const containmentReal = fs.realpathSync(containmentRoot);
1016
- if (!isAuthorityLink
1017
- && !isLegacyWholeUltraLink
1018
- && (!registeredWorktree || !isContainedPath(containmentReal, resolved))) {
1019
- throw new RuntimePathError(
1020
- 'RUNTIME_PATH_UNSAFE',
1021
- `legacy runtime symlink escapes its declared authority boundary: ${candidate}`,
1022
- { details: { path: candidate, resolved_path: resolved } },
1023
- );
1024
- }
1025
- return;
1026
- }
1027
- if (stat.isFile()) return;
1028
- if (!stat.isDirectory()) {
1029
- throw new RuntimePathError(
1030
- 'RUNTIME_PATH_UNSAFE',
1031
- `legacy runtime entry must be a regular file or directory: ${candidate}`,
1032
- { details: { path: candidate } },
1033
- );
1034
- }
1035
- for (const entry of fs.readdirSync(candidate)) {
1036
- assertTreeEntrySafe(path.join(candidate, entry), {
1037
- containmentRoot,
1038
- registeredWorktree,
1039
- canonicalRuntimeDir,
1040
- canonicalUltraDir,
1041
- });
1042
- }
1043
- }
1044
-
1045
- function preflightLegacyRuntime(paths, {
1046
- spawnGit = spawnSync,
1047
- } = {}) {
1048
- const legacyWorktrees = path.join(paths.ultraDir, 'worktrees');
1049
- const legacyWorktreesStat = assertDirectoryIfPresent(
1050
- legacyWorktrees,
1051
- 'legacy worktrees runtime root',
1052
- );
1053
- const registered = legacyWorktreesStat
1054
- ? registeredWorktrees(paths.rootDir, { spawnGit })
1055
- : new Set();
1056
- const legacyWholeUltraLinks = new Set();
1057
- const directories = [
1058
- ['worktrees', 'worktrees'],
1059
- ...LEGACY_RUNTIME_DIRS,
1060
- ];
1061
- for (const [legacyName, runtimeName] of directories) {
1062
- const sourceDir = path.join(paths.ultraDir, legacyName);
1063
- const sourceStat = assertDirectoryIfPresent(
1064
- sourceDir,
1065
- `legacy ${legacyName} runtime root`,
1066
- );
1067
- if (!sourceStat) continue;
1068
- const targetDir = runtimeName === '.'
1069
- ? paths.runtimeDir
1070
- : path.join(paths.runtimeDir, runtimeName);
1071
- assertDirectoryIfPresent(targetDir, `runtime ${runtimeName} target`);
1072
- for (const entry of fs.readdirSync(sourceDir)) {
1073
- const source = path.join(sourceDir, entry);
1074
- const target = path.join(targetDir, entry);
1075
- assertVacantTarget(source, target);
1076
- let canonicalSource;
1077
- try { canonicalSource = fs.realpathSync(source); }
1078
- catch { canonicalSource = path.resolve(source); }
1079
- assertTreeEntrySafe(source, {
1080
- containmentRoot: source,
1081
- registeredWorktree: registered.has(canonicalSource),
1082
- canonicalRuntimeDir: paths.runtimeDir,
1083
- canonicalUltraDir: paths.ultraDir,
1084
- });
1085
- const wholeUltra = path.join(source, '.ultra');
1086
- if (registered.has(canonicalSource)
1087
- && lstatOrNull(wholeUltra)?.isSymbolicLink()
1088
- && fs.realpathSync(wholeUltra) === fs.realpathSync(paths.ultraDir)) {
1089
- legacyWholeUltraLinks.add(canonicalSource);
1090
- }
1091
- }
1092
- }
1093
- for (const [legacyName, runtimeRelative] of LEGACY_RUNTIME_FILES) {
1094
- const source = path.join(paths.ultraDir, legacyName);
1095
- const sourceStat = assertRegularFileIfPresent(source, `legacy ${legacyName}`);
1096
- if (!sourceStat) continue;
1097
- assertVacantTarget(source, path.join(paths.runtimeDir, runtimeRelative));
1098
- }
1099
- assertDirectoryIfPresent(paths.backupsDir, 'runtime backups target');
1100
- return { registered, legacyWholeUltraLinks };
1101
- }
1102
-
1103
- function moveRegisteredWorktree(rootDir, source, target) {
1104
- fs.mkdirSync(path.dirname(target), { recursive: true });
1105
- const result = spawnSync('git', ['worktree', 'move', source, target], {
1106
- cwd: rootDir,
1107
- encoding: 'utf8',
1108
- stdio: ['ignore', 'pipe', 'pipe'],
1109
- });
1110
- if (result.status !== 0) {
1111
- throw new Error(
1112
- `git worktree move failed for ${source}: `
1113
- + `${(result.stderr || result.stdout || 'unknown error').trim()}`,
1114
- );
1115
- }
1116
- }
1117
-
1118
- function assertVacantTarget(source, target) {
1119
- if (!fs.existsSync(target) && !fs.lstatSync(target, { throwIfNoEntry: false })) return;
1120
- throw new RuntimePathError(
1121
- 'LEGACY_RUNTIME_CONFLICT',
1122
- `cannot migrate legacy runtime artifact ${source}; target already exists at ${target}`,
1123
- { details: { source, target } },
1124
- );
1125
- }
1126
-
1127
- function restoreTrackedUltraTree(worktreePath) {
1128
- const ultraDir = path.join(worktreePath, '.ultra');
1129
- fs.rmSync(ultraDir, { recursive: true, force: true });
1130
- const listed = spawnSync('git', ['-C', worktreePath, 'ls-files', '-z', '--', '.ultra'], {
1131
- encoding: 'buffer',
1132
- stdio: ['ignore', 'pipe', 'pipe'],
1133
- });
1134
- if (listed.status !== 0) {
1135
- throw new Error(
1136
- `git ls-files failed while restoring tracked Ultra semantics in ${worktreePath}: `
1137
- + `${String(listed.stderr || listed.stdout || 'unknown error').trim()}`,
1138
- );
1139
- }
1140
- if (listed.stdout.length > 0) {
1141
- const restored = spawnSync('git', ['-C', worktreePath, 'checkout', '--', '.ultra'], {
1142
- encoding: 'utf8',
1143
- stdio: ['ignore', 'pipe', 'pipe'],
1144
- });
1145
- if (restored.status !== 0) {
1146
- throw new Error(
1147
- `git checkout failed while restoring tracked Ultra semantics in ${worktreePath}: `
1148
- + `${(restored.stderr || restored.stdout || 'unknown error').trim()}`,
1149
- );
1150
- }
1151
- } else {
1152
- fs.mkdirSync(ultraDir, { recursive: true });
1153
- }
1154
- }
1155
-
1156
- function convertLegacyWholeUltraWorktree(paths, worktreePath) {
1157
- const ultraDir = path.join(worktreePath, '.ultra');
1158
- const stat = lstatOrNull(ultraDir);
1159
- if (!stat?.isSymbolicLink()
1160
- || fs.realpathSync(ultraDir) !== fs.realpathSync(paths.ultraDir)) {
1161
- throw new Error(`legacy whole-.ultra authority link changed before conversion: ${ultraDir}`);
1162
- }
1163
- restoreTrackedUltraTree(worktreePath);
1164
- const runtimeLink = path.join(ultraDir, '.runtime');
1165
- assertVacantTarget(paths.runtimeDir, runtimeLink);
1166
- fs.symlinkSync(path.relative(ultraDir, paths.runtimeDir), runtimeLink, 'dir');
1167
- if (fs.realpathSync(runtimeLink) !== fs.realpathSync(paths.runtimeDir)) {
1168
- throw new Error(`converted worktree authority link does not resolve centrally: ${runtimeLink}`);
1169
- }
1170
- }
1171
-
1172
- function openSessionBindingTransaction(paths) {
1173
- if (!lstatOrNull(paths.stateDbPath) || !isSQLiteDatabase(paths.stateDbPath)) return null;
1174
- // eslint-disable-next-line global-require
1175
- const Database = require('better-sqlite3');
1176
- const db = new Database(paths.stateDbPath, { fileMustExist: true });
1177
- db.pragma('busy_timeout = 0');
1178
- const sessions = db.prepare(
1179
- "SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = 'sessions'",
1180
- ).get();
1181
- if (!sessions) {
1182
- db.close();
1183
- return null;
1184
- }
1185
- db.exec('BEGIN IMMEDIATE');
1186
- return db;
1187
- }
1188
-
1189
- function sessionBindingsForWorktree(db, source) {
1190
- if (!db) return [];
1191
- const canonicalSource = physicalPathCandidate(source);
1192
- return db.prepare('SELECT sid, worktree_path FROM sessions').all()
1193
- .filter((row) => {
1194
- try {
1195
- return physicalPathCandidate(row.worktree_path) === canonicalSource;
1196
- } catch {
1197
- return path.resolve(row.worktree_path) === path.resolve(source);
1198
- }
1199
- });
1200
- }
1201
-
1202
- function moveSessionBindings(db, bindings, source, target) {
1203
- if (!db || bindings.length === 0) return;
1204
- const update = db.prepare(
1205
- 'UPDATE sessions SET worktree_path = ? WHERE sid = ? AND worktree_path = ?',
1206
- );
1207
- for (const binding of bindings) {
1208
- const result = update.run(target, binding.sid, binding.worktree_path);
1209
- if (result.changes !== 1) {
1210
- throw new RuntimePathError(
1211
- 'RUNTIME_SESSION_BINDING_CHANGED',
1212
- `session ${binding.sid} worktree binding changed during migration`,
1213
- {
1214
- details: {
1215
- sid: binding.sid,
1216
- expected_worktree_path: binding.worktree_path,
1217
- target_worktree_path: target,
1218
- },
1219
- },
1220
- );
1221
- }
1222
- }
1223
- }
1224
-
1225
- function restoreCommittedSessionBindings(paths, actions) {
1226
- const worktreeActions = actions.filter(
1227
- (action) => action.kind === 'worktree' && action.sessionBindings?.length,
1228
- );
1229
- if (worktreeActions.length === 0) return;
1230
- const db = openSessionBindingTransaction(paths);
1231
- if (!db) {
1232
- throw new RuntimePathError(
1233
- 'RUNTIME_SESSION_BINDING_MISSING',
1234
- 'cannot restore migrated worktree bindings without canonical state authority',
1235
- );
1236
- }
1237
- try {
1238
- const update = db.prepare(
1239
- 'UPDATE sessions SET worktree_path = ? WHERE sid = ? AND worktree_path = ?',
1240
- );
1241
- for (const action of [...worktreeActions].reverse()) {
1242
- for (const binding of action.sessionBindings) {
1243
- const result = update.run(action.source, binding.sid, action.target);
1244
- if (result.changes !== 1) {
1245
- const current = db.prepare(
1246
- 'SELECT worktree_path FROM sessions WHERE sid = ?',
1247
- ).get(binding.sid);
1248
- if (current?.worktree_path !== action.source) {
1249
- throw new RuntimePathError(
1250
- 'RUNTIME_SESSION_BINDING_CHANGED',
1251
- `session ${binding.sid} cannot restore its legacy worktree binding`,
1252
- );
1253
- }
1254
- }
1255
- }
1256
- }
1257
- db.exec('COMMIT');
1258
- } catch (error) {
1259
- try { db.exec('ROLLBACK'); } catch { /* best effort */ }
1260
- throw error;
1261
- } finally {
1262
- db.close();
1263
- }
1264
- }
1265
-
1266
- function moveLegacyDirectoryContents({
1267
- rootDir,
1268
- sourceDir,
1269
- targetDir,
1270
- registered,
1271
- legacyWholeUltraLinks,
1272
- paths,
1273
- rename,
1274
- actions,
1275
- removedDirs,
1276
- bindingDb,
1277
- }) {
1278
- if (!fs.existsSync(sourceDir)) return;
1279
- fs.mkdirSync(targetDir, { recursive: true });
1280
- for (const entry of fs.readdirSync(sourceDir, { withFileTypes: true })) {
1281
- const source = path.join(sourceDir, entry.name);
1282
- const target = path.join(targetDir, entry.name);
1283
- assertVacantTarget(source, target);
1284
- let canonicalSource;
1285
- try { canonicalSource = fs.realpathSync(source); }
1286
- catch { canonicalSource = path.resolve(source); }
1287
- if (registered.has(canonicalSource)) {
1288
- const sessionBindings = sessionBindingsForWorktree(bindingDb, source);
1289
- const legacyWholeUltraLink = legacyWholeUltraLinks.has(canonicalSource);
1290
- const originalUltraLink = legacyWholeUltraLink
1291
- ? fs.readlinkSync(path.join(source, '.ultra'))
1292
- : null;
1293
- moveRegisteredWorktree(rootDir, source, target);
1294
- actions.push({
1295
- kind: 'worktree',
1296
- source,
1297
- target,
1298
- sessionBindings,
1299
- legacyWholeUltraLink,
1300
- originalUltraLink,
1301
- });
1302
- moveSessionBindings(bindingDb, sessionBindings, source, target);
1303
- if (legacyWholeUltraLink) convertLegacyWholeUltraWorktree(paths, target);
1304
- } else {
1305
- rename(source, target);
1306
- actions.push({ kind: 'rename', source, target });
1307
- }
1308
- }
1309
- if (fs.readdirSync(sourceDir).length === 0) {
1310
- fs.rmdirSync(sourceDir);
1311
- removedDirs.push(sourceDir);
1312
- }
1313
- }
1314
-
1315
- function rollbackLegacyRuntime(rootDir, actions, removedDirs, rollbackRename) {
1316
- const errors = [];
1317
- for (const dir of [...removedDirs].reverse()) {
1318
- try { fs.mkdirSync(dir, { recursive: true }); }
1319
- catch (error) { errors.push(`${dir}: ${error.message}`); }
1320
- }
1321
- for (const action of [...actions].reverse()) {
1322
- try {
1323
- fs.mkdirSync(path.dirname(action.source), { recursive: true });
1324
- if (action.kind === 'worktree') {
1325
- if (action.legacyWholeUltraLink) restoreTrackedUltraTree(action.target);
1326
- moveRegisteredWorktree(rootDir, action.target, action.source);
1327
- if (action.legacyWholeUltraLink) {
1328
- fs.rmSync(path.join(action.source, '.ultra'), { recursive: true, force: true });
1329
- fs.symlinkSync(action.originalUltraLink, path.join(action.source, '.ultra'), 'dir');
1330
- }
1331
- } else {
1332
- rollbackRename(action.target, action.source);
1333
- }
1334
- } catch (error) {
1335
- errors.push(`${action.target}: ${error.message}`);
1336
- }
1337
- }
1338
- if (errors.length === 0) {
1339
- try {
1340
- restoreCommittedSessionBindings(pathsFor(rootDir), actions);
1341
- } catch (error) {
1342
- errors.push(`session worktree bindings: ${error.message}`);
1343
- }
1344
- }
1345
- return errors;
1346
- }
1347
-
1348
- function migrateLegacyRuntime(rootDir, {
1349
- rename = fs.renameSync,
1350
- rollbackRename = fs.renameSync,
1351
- spawnGit = spawnSync,
1352
- _migrationGateToken = null,
1353
- } = {}) {
1354
- let paths = validateProjectLayout(rootDir, { forMutation: true, env: {} });
1355
- fs.mkdirSync(paths.runtimeDir, { recursive: true });
1356
- const releaseGate = _migrationGateToken === HELD_MIGRATION_GATE
1357
- ? () => {}
1358
- : acquireStateMigrationGate(paths);
1359
- let registered;
1360
- let legacyWholeUltraLinks;
1361
- const actions = [];
1362
- const removedDirs = [];
1363
- let bindingDb = null;
1364
- try {
1365
- // The caller may preflight before state migration for all-or-nothing
1366
- // admission, but only this gate-owned re-read is authoritative.
1367
- paths = validateProjectLayout(rootDir, { forMutation: true, env: {} });
1368
- const checked = preflightLegacyRuntime(paths, { spawnGit });
1369
- registered = checked.registered;
1370
- legacyWholeUltraLinks = checked.legacyWholeUltraLinks || new Set();
1371
- bindingDb = openSessionBindingTransaction(paths);
1372
- const legacyWorktrees = path.join(paths.ultraDir, 'worktrees');
1373
- moveLegacyDirectoryContents({
1374
- rootDir,
1375
- sourceDir: legacyWorktrees,
1376
- targetDir: paths.worktreesDir,
1377
- registered,
1378
- legacyWholeUltraLinks,
1379
- paths,
1380
- rename,
1381
- actions,
1382
- removedDirs,
1383
- bindingDb,
1384
- });
1385
- for (const [legacyName, runtimeName] of LEGACY_RUNTIME_DIRS) {
1386
- const sourceDir = path.join(paths.ultraDir, legacyName);
1387
- const targetDir = runtimeName === '.'
1388
- ? paths.runtimeDir
1389
- : path.join(paths.runtimeDir, runtimeName);
1390
- moveLegacyDirectoryContents({
1391
- rootDir,
1392
- sourceDir,
1393
- targetDir,
1394
- registered,
1395
- legacyWholeUltraLinks,
1396
- paths,
1397
- rename,
1398
- actions,
1399
- removedDirs,
1400
- bindingDb,
1401
- });
1402
- }
1403
- for (const [legacyName, runtimeRelative] of LEGACY_RUNTIME_FILES) {
1404
- const source = path.join(paths.ultraDir, legacyName);
1405
- if (!fs.existsSync(source)) continue;
1406
- const target = path.join(paths.runtimeDir, runtimeRelative);
1407
- assertVacantTarget(source, target);
1408
- fs.mkdirSync(path.dirname(target), { recursive: true });
1409
- rename(source, target);
1410
- actions.push({ kind: 'rename', source, target });
1411
- }
1412
- if (bindingDb) bindingDb.exec('COMMIT');
1413
- } catch (error) {
1414
- if (bindingDb) {
1415
- try { bindingDb.exec('ROLLBACK'); } catch { /* best effort */ }
1416
- }
1417
- const rollbackErrors = rollbackLegacyRuntime(
1418
- rootDir,
1419
- actions,
1420
- removedDirs,
1421
- rollbackRename,
1422
- );
1423
- if (error instanceof RuntimePathError && rollbackErrors.length === 0) throw error;
1424
- throw new RuntimePathError(
1425
- 'LEGACY_RUNTIME_MIGRATION_FAILED',
1426
- `could not move legacy Ultra runtime artifacts into .ultra/.runtime: ${error.message}`
1427
- + `${rollbackErrors.length ? `; rollback errors: ${rollbackErrors.join('; ')}` : ''}`,
1428
- { cause: error },
1429
- );
1430
- } finally {
1431
- if (bindingDb) bindingDb.close();
1432
- releaseGate();
1433
- }
1434
- const result = {
1435
- migrated: actions.length > 0,
1436
- moved: actions.map(({ kind, source, target }) => ({ kind, source, target })),
1437
- };
1438
- Object.defineProperty(result, '_transaction', {
1439
- value: { actions, removedDirs, rollbackRename },
1440
- });
1441
- return result;
1442
- }
1443
-
1444
- function restoreStateMigrationImage(state) {
1445
- if (!state?.migrated || !state.backupPath) return;
1446
- for (const suffix of STATE_SUFFIXES) {
1447
- const backup = path.join(state.backupPath, `state.db${suffix}`);
1448
- const runtimeTarget = `${state.stateDbPath}${suffix}`;
1449
- const legacyTarget = `${state.legacyStateDbPath}${suffix}`;
1450
- fs.rmSync(runtimeTarget, { force: true });
1451
- if (!lstatOrNull(backup)) continue;
1452
- assertRegularFileIfPresent(backup, `migration backup state.db${suffix}`);
1453
- atomicVerifiedCopy(backup, legacyTarget);
1454
- }
1455
- if (state._transaction) state._transaction.tombstone = false;
1456
- }
1457
-
1458
- function ensureRuntimeState(rootDir, options = {}) {
1459
- let paths = validateProjectLayout(rootDir, {
1460
- env: options.env || {},
1461
- allowConfiguredRuntimeLink: options.allowConfiguredRuntimeLink === true,
1462
- forMutation: options.allowConfiguredRuntimeLink !== true,
1463
- validateRuntimeTree: true,
1464
- });
1465
- fs.mkdirSync(paths.runtimeDir, { recursive: true });
1466
- const releaseGate = acquireStateMigrationGate(paths);
1467
- let state = null;
1468
- let legacyRuntime = null;
1469
- try {
1470
- // Everything observed before waiting on the outer gate is stale. Re-read
1471
- // the complete authority and keep this token through storage admission or
1472
- // every rollback, so another successful caller can never observe state
1473
- // that a failing predecessor is still allowed to remove.
1474
- paths = validateProjectLayout(rootDir, {
1475
- env: options.env || {},
1476
- allowConfiguredRuntimeLink: options.allowConfiguredRuntimeLink === true,
1477
- forMutation: options.allowConfiguredRuntimeLink !== true,
1478
- validateRuntimeTree: true,
1479
- });
1480
- assertNoCompetingState(paths);
1481
- assertConfiguredAuthorityBinding(paths);
1482
- if (paths.runtimeLinked) {
1483
- const legacyRuntimePresent = [
1484
- ...LEGACY_RUNTIME_DIRS.map(([name]) => path.join(paths.ultraDir, name)),
1485
- ...LEGACY_RUNTIME_FILES.map(([name]) => path.join(paths.ultraDir, name)),
1486
- path.join(paths.ultraDir, 'worktrees'),
1487
- ].some((candidate) => lstatOrNull(candidate));
1488
- if (legacyRuntimePresent) {
1489
- throw new RuntimePathError(
1490
- 'RUNTIME_PATH_UNSAFE',
1491
- 'a task runtime link cannot be used as a migration target for legacy local runtime data',
1492
- );
1493
- }
1494
- const storageBoundary = options.admitStorageBoundary
1495
- ? options.admitStorageBoundary()
1496
- : null;
1497
- return {
1498
- ...paths,
1499
- stateDbPath: paths.configuredStateDbPath,
1500
- migrated: false,
1501
- backupPath: null,
1502
- legacyRuntime: { migrated: false, moved: [] },
1503
- storageBoundary,
1504
- };
1505
- }
1506
-
1507
- // Validate every source and target under the same token that owns the
1508
- // migration, Git boundary callback, and rollback.
1509
- preflightLegacyRuntime(paths, {
1510
- spawnGit: options.spawnGit || spawnSync,
1511
- });
1512
- state = options.migrateState === false
1513
- ? { ...paths, migrated: false, backupPath: null }
1514
- : migrateLegacyState(rootDir, {
1515
- ...options,
1516
- _migrationGateToken: HELD_MIGRATION_GATE,
1517
- });
1518
- legacyRuntime = migrateLegacyRuntime(rootDir, {
1519
- ...options,
1520
- _migrationGateToken: HELD_MIGRATION_GATE,
1521
- });
1522
- const storageBoundary = options.admitStorageBoundary
1523
- ? options.admitStorageBoundary()
1524
- : null;
1525
- return { ...state, legacyRuntime, storageBoundary };
1526
- } catch (error) {
1527
- const rollbackErrors = [];
1528
- if (legacyRuntime?._transaction) {
1529
- rollbackErrors.push(...rollbackLegacyRuntime(
1530
- paths.rootDir,
1531
- legacyRuntime._transaction.actions,
1532
- legacyRuntime._transaction.removedDirs,
1533
- legacyRuntime._transaction.rollbackRename,
1534
- ));
1535
- }
1536
- if (state?._transaction) {
1537
- try {
1538
- restoreStateMigrationImage(state);
1539
- } catch (restoreError) {
1540
- rollbackErrors.push(
1541
- `state migration image restore failed: ${restoreError.message}`,
1542
- );
1543
- }
1544
- }
1545
- if (rollbackErrors.length) {
1546
- throw new RuntimePathError(
1547
- 'RUNTIME_ADMISSION_ROLLBACK_FAILED',
1548
- `${error.message}; rollback errors: ${rollbackErrors.join('; ')}`,
1549
- { cause: error },
1550
- );
1551
- }
1552
- throw error;
1553
- } finally {
1554
- releaseGate();
1555
- }
1556
- }
1557
-
1558
- function resolveConfiguredStateDb(rootDir, {
1559
- env = process.env,
1560
- migrateLegacy = false,
1561
- now,
1562
- } = {}) {
1563
- const projectPaths = validateProjectLayout(rootDir, { env });
1564
- assertNoCompetingState(projectPaths);
1565
- assertConfiguredAuthorityBinding(projectPaths);
1566
- const configured = explicitStateDbPath(env);
1567
- if (configured) {
1568
- if (migrateLegacy && configured === projectPaths.legacyStateDbPath) {
1569
- return {
1570
- ...ensureRuntimeState(rootDir, { ...(now ? { now } : {}) }),
1571
- configured: true,
1572
- };
1573
- }
1574
- return {
1575
- ...projectPaths,
1576
- stateDbPath: configured,
1577
- migrated: false,
1578
- backupPath: null,
1579
- configured: true,
1580
- };
1581
- }
1582
- if (migrateLegacy) {
1583
- return ensureRuntimeState(rootDir, { ...(now ? { now } : {}) });
1584
- }
1585
- return {
1586
- ...pathsFor(rootDir),
1587
- stateDbPath: locateStateDb(rootDir, { env: {} }),
1588
- migrated: false,
1589
- backupPath: null,
1590
- configured: false,
1591
- };
1592
- }
1593
-
1594
- function findProjectRoot(startDir, { env = process.env } = {}) {
1595
- const explicitRoot = typeof env?.UBP_ROOT_DIR === 'string' ? env.UBP_ROOT_DIR.trim() : '';
1596
- if (explicitRoot) {
1597
- const root = assertSafeRoot(explicitRoot);
1598
- const dbPath = locateStateDb(root, { env });
1599
- return fs.existsSync(dbPath) ? root : null;
1600
- }
1601
-
1602
- const requestedStart = path.resolve(startDir || process.cwd());
1603
- let current;
1604
- try {
1605
- current = fs.realpathSync(requestedStart);
1606
- } catch (error) {
1607
- throw new RuntimePathError(
1608
- 'RUNTIME_ROOT_INVALID',
1609
- `project root search start does not exist: ${requestedStart}`,
1610
- { cause: error },
1611
- );
1612
- }
1613
- while (true) {
1614
- const dbPath = locateStateDb(current, { env: {} });
1615
- if (fs.existsSync(dbPath)) return current;
1616
- const parent = path.dirname(current);
1617
- if (parent === current) return null;
1618
- current = parent;
1619
- }
1620
- }
1621
-
1622
- function assertManagedBackupDestination(rootDir, targetPath) {
1623
- const paths = validateProjectLayout(rootDir, {
1624
- env: {},
1625
- validateRuntimeTree: true,
1626
- });
1627
- const target = path.resolve(rootDir, targetPath);
1628
- const physicalBackups = physicalPathCandidate(paths.backupsDir);
1629
- const physicalTarget = physicalPathCandidate(target);
1630
- const relative = path.relative(physicalBackups, physicalTarget);
1631
- if (!relative
1632
- || relative === '..'
1633
- || relative.startsWith(`..${path.sep}`)
1634
- || path.isAbsolute(relative)) {
1635
- throw new RuntimePathError(
1636
- 'RUNTIME_BACKUP_SCOPE_INVALID',
1637
- `backup target must be inside ${paths.backupsDir}: ${target}`,
1638
- { details: { target, backups_root: paths.backupsDir } },
1639
- );
1640
- }
1641
- let current = physicalPathCandidate(paths.runtimeDir);
1642
- for (const part of path.relative(
1643
- physicalPathCandidate(paths.runtimeDir),
1644
- path.dirname(physicalTarget),
1645
- ).split(path.sep)) {
1646
- if (!part || part === '.') continue;
1647
- current = path.join(current, part);
1648
- const stat = lstatOrNull(current);
1649
- if (stat && (stat.isSymbolicLink() || !stat.isDirectory())) {
1650
- throw new RuntimePathError(
1651
- 'RUNTIME_BACKUP_SCOPE_INVALID',
1652
- `backup target parent must be a real managed directory: ${current}`,
1653
- { details: { target, unsafe_parent: current } },
1654
- );
1655
- }
1656
- }
1657
- const targetStat = lstatOrNull(target);
1658
- if (targetStat && (targetStat.isSymbolicLink() || !targetStat.isFile())) {
1659
- throw new RuntimePathError(
1660
- 'RUNTIME_BACKUP_SCOPE_INVALID',
1661
- `backup target must be a regular file: ${target}`,
1662
- { details: { target } },
1663
- );
1664
- }
1665
- return { ...paths, targetPath: target };
1666
- }
1667
-
1668
- module.exports = {
1669
- RuntimePathError,
1670
- RUNTIME_RELATIVE_DIR,
1671
- STATE_DB_RELATIVE_PATH,
1672
- LEGACY_STATE_DB_RELATIVE_PATH,
1673
- pathsFor,
1674
- validateProjectLayout,
1675
- locateStateDb,
1676
- findProjectRoot,
1677
- projectRootFromStateDbPath,
1678
- isManagedLegacyStateTombstone,
1679
- ensureRuntimeState,
1680
- migrateLegacyState,
1681
- migrateLegacyRuntime,
1682
- resolveConfiguredStateDb,
1683
- assertManagedBackupDestination,
1684
- _internal: {
1685
- acquireStateMigrationGate,
1686
- },
1687
- };