ultra-builder-pro-cli 0.25.1 → 0.26.1

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