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,471 +0,0 @@
1
- 'use strict';
2
-
3
- const crypto = require('node:crypto');
4
- const fs = require('node:fs');
5
- const path = require('node:path');
6
-
7
- const TRANSACTION_ROOT = '.ultra/.runtime/delivery-transactions';
8
- const JOURNAL_FILE = 'transaction.json';
9
- const SCHEMA_VERSION = '1.0';
10
- const ID = /^[a-zA-Z0-9_-]+$/;
11
-
12
- class DeliveryTransactionError extends Error {
13
- constructor(code, message, details = undefined) {
14
- super(message);
15
- this.name = 'DeliveryTransactionError';
16
- this.code = code;
17
- if (details !== undefined) this.details = details;
18
- }
19
- }
20
-
21
- function digestBytes(bytes) {
22
- return crypto.createHash('sha256').update(bytes).digest('hex');
23
- }
24
-
25
- function digestFile(file) {
26
- return digestBytes(fs.readFileSync(file));
27
- }
28
-
29
- function normalizeRelative(value, field) {
30
- if (typeof value !== 'string' || !value.trim()) {
31
- throw new DeliveryTransactionError('DELIVERY_PATH_INVALID', `${field} is required`);
32
- }
33
- const raw = value.trim().replaceAll('\\', '/');
34
- if (path.posix.isAbsolute(raw) || path.win32.isAbsolute(raw)) {
35
- throw new DeliveryTransactionError(
36
- 'DELIVERY_PATH_INVALID', `${field} must be project-relative`,
37
- );
38
- }
39
- const relative = path.posix.normalize(raw).replace(/^\.\//, '');
40
- if (relative === '.' || relative === '..' || relative.startsWith('../')) {
41
- throw new DeliveryTransactionError('DELIVERY_PATH_INVALID', `${field} escapes project root`);
42
- }
43
- return relative;
44
- }
45
-
46
- function projectRoot(rootDir) {
47
- const root = path.resolve(rootDir);
48
- let stat;
49
- try { stat = fs.lstatSync(root); }
50
- catch (error) {
51
- throw new DeliveryTransactionError(
52
- 'DELIVERY_PATH_INVALID', `project root is unavailable: ${error.message}`,
53
- );
54
- }
55
- if (stat.isSymbolicLink() || !stat.isDirectory()) {
56
- throw new DeliveryTransactionError(
57
- 'DELIVERY_PATH_INVALID', 'project root must be a real directory',
58
- );
59
- }
60
- return fs.realpathSync.native(root);
61
- }
62
-
63
- function resolveInside(rootDir, relative, field, { requireFile = false } = {}) {
64
- const root = projectRoot(rootDir);
65
- const normalized = normalizeRelative(relative, field);
66
- const file = path.resolve(root, normalized);
67
- if (!file.startsWith(`${root}${path.sep}`)) {
68
- throw new DeliveryTransactionError('DELIVERY_PATH_INVALID', `${field} escapes project root`);
69
- }
70
- const components = normalized.split('/');
71
- let current = root;
72
- for (let index = 0; index < components.length; index += 1) {
73
- current = path.join(current, components[index]);
74
- let stat;
75
- try { stat = fs.lstatSync(current); }
76
- catch (error) {
77
- if (error.code === 'ENOENT') {
78
- if (requireFile || index < components.length - 1) {
79
- if (index < components.length - 1) continue;
80
- throw new DeliveryTransactionError(
81
- 'DELIVERY_PATH_INVALID', `${field} is missing: ${normalized}`,
82
- );
83
- }
84
- break;
85
- }
86
- throw error;
87
- }
88
- if (stat.isSymbolicLink()) {
89
- throw new DeliveryTransactionError(
90
- 'DELIVERY_PATH_INVALID', `${field} contains a symbolic link: ${normalized}`,
91
- );
92
- }
93
- if (index < components.length - 1 && !stat.isDirectory()) {
94
- throw new DeliveryTransactionError(
95
- 'DELIVERY_PATH_INVALID', `${field} contains a non-directory ancestor: ${normalized}`,
96
- );
97
- }
98
- if (index === components.length - 1 && requireFile && !stat.isFile()) {
99
- throw new DeliveryTransactionError(
100
- 'DELIVERY_PATH_INVALID', `${field} is not a regular file: ${normalized}`,
101
- );
102
- }
103
- }
104
- return { root, relative: normalized, file };
105
- }
106
-
107
- function transactionDirectory(rootDir, changeId) {
108
- if (!ID.test(changeId || '')) {
109
- throw new DeliveryTransactionError(
110
- 'DELIVERY_TRANSACTION_INVALID', `invalid change id: ${changeId || '(missing)'}`,
111
- );
112
- }
113
- return path.join(projectRoot(rootDir), TRANSACTION_ROOT, changeId);
114
- }
115
-
116
- function atomicWrite(file, bytes) {
117
- fs.mkdirSync(path.dirname(file), { recursive: true });
118
- const temporary = `${file}.tmp-${process.pid}-${crypto.randomUUID()}`;
119
- fs.writeFileSync(temporary, bytes, { mode: 0o600 });
120
- fs.renameSync(temporary, file);
121
- }
122
-
123
- function writeJournal(directory, journal) {
124
- journal.updated_at = new Date().toISOString();
125
- atomicWrite(
126
- path.join(directory, JOURNAL_FILE),
127
- `${JSON.stringify(journal, null, 2)}\n`,
128
- );
129
- }
130
-
131
- function readJournal(directory) {
132
- const file = path.join(directory, JOURNAL_FILE);
133
- let value;
134
- try { value = JSON.parse(fs.readFileSync(file, 'utf8')); }
135
- catch (error) {
136
- throw new DeliveryTransactionError(
137
- 'DELIVERY_RECOVERY_REQUIRED',
138
- `delivery transaction journal is unreadable: ${file}`,
139
- { cause: error.message },
140
- );
141
- }
142
- if (value.schema_version !== SCHEMA_VERSION || !ID.test(value.change_id || '')
143
- || !Array.isArray(value.entries)
144
- || !['prepared', 'applied'].includes(value.status)) {
145
- throw new DeliveryTransactionError(
146
- 'DELIVERY_RECOVERY_REQUIRED',
147
- `delivery transaction journal is invalid: ${file}`,
148
- );
149
- }
150
- return value;
151
- }
152
-
153
- function normalizedEntries(entries) {
154
- if (!Array.isArray(entries)) {
155
- throw new DeliveryTransactionError(
156
- 'DELIVERY_TRANSACTION_INVALID', 'delivery entries must be an array',
157
- );
158
- }
159
- const targets = new Set();
160
- return entries.map((entry, index) => {
161
- if (!entry || typeof entry !== 'object' || Array.isArray(entry)
162
- || !ID.test(String(entry.id || ''))
163
- || !['add', 'update'].includes(entry.action)
164
- || !/^[0-9a-f]{64}$/.test(String(entry.after_digest || ''))
165
- || (entry.before_digest !== null
166
- && !/^[0-9a-f]{64}$/.test(String(entry.before_digest || '')))) {
167
- throw new DeliveryTransactionError(
168
- 'DELIVERY_TRANSACTION_INVALID', `delivery entry ${index} is invalid`,
169
- );
170
- }
171
- const targetPath = normalizeRelative(entry.target_path, `entries[${index}].target_path`);
172
- const overlayPath = normalizeRelative(entry.overlay_path, `entries[${index}].overlay_path`);
173
- if (targets.has(targetPath)) {
174
- throw new DeliveryTransactionError(
175
- 'DELIVERY_TRANSACTION_INVALID', `duplicate delivery target: ${targetPath}`,
176
- );
177
- }
178
- targets.add(targetPath);
179
- return {
180
- kind: String(entry.kind || 'artifact'),
181
- id: entry.id,
182
- action: entry.action,
183
- target_path: targetPath,
184
- overlay_path: overlayPath,
185
- before_digest: entry.before_digest,
186
- after_digest: entry.after_digest,
187
- };
188
- });
189
- }
190
-
191
- function canonicalEntries(entries) {
192
- return JSON.stringify(entries.map((entry) => ({
193
- kind: entry.kind,
194
- id: entry.id,
195
- action: entry.action,
196
- target_path: entry.target_path,
197
- overlay_path: entry.overlay_path,
198
- before_digest: entry.before_digest,
199
- after_digest: entry.after_digest,
200
- })));
201
- }
202
-
203
- function preflight(rootDir, entries) {
204
- return entries.map((entry) => {
205
- const target = resolveInside(rootDir, entry.target_path, 'target_path');
206
- const overlay = resolveInside(
207
- rootDir, entry.overlay_path, 'overlay_path', { requireFile: true },
208
- );
209
- const targetExists = fs.existsSync(target.file);
210
- const actualBefore = targetExists ? digestFile(target.file) : null;
211
- if ((entry.action === 'add' && targetExists)
212
- || (entry.action === 'update' && !targetExists)
213
- || actualBefore !== entry.before_digest) {
214
- throw new DeliveryTransactionError(
215
- 'DELIVERY_BASELINE_CONFLICT',
216
- `delivery target changed before convergence: ${entry.target_path}`,
217
- { expected: entry.before_digest, actual: actualBefore },
218
- );
219
- }
220
- const actualAfter = digestFile(overlay.file);
221
- if (actualAfter !== entry.after_digest) {
222
- throw new DeliveryTransactionError(
223
- 'DELIVERY_OVERLAY_STALE',
224
- `delivery overlay changed before convergence: ${entry.overlay_path}`,
225
- { expected: entry.after_digest, actual: actualAfter },
226
- );
227
- }
228
- return { entry, target, overlay, existed: targetExists };
229
- });
230
- }
231
-
232
- function applyEntry(item) {
233
- fs.mkdirSync(path.dirname(item.target.file), { recursive: true });
234
- const temporary = `${item.target.file}.delivery-${process.pid}-${crypto.randomUUID()}`;
235
- fs.copyFileSync(item.overlay.file, temporary);
236
- if (digestFile(temporary) !== item.entry.after_digest) {
237
- fs.rmSync(temporary, { force: true });
238
- throw new DeliveryTransactionError(
239
- 'DELIVERY_OVERLAY_STALE',
240
- `delivery copy changed before publication: ${item.entry.overlay_path}`,
241
- );
242
- }
243
- fs.renameSync(temporary, item.target.file);
244
- }
245
-
246
- function verifyApplied(rootDir, entries) {
247
- for (const entry of entries) {
248
- const target = resolveInside(rootDir, entry.target_path, 'target_path', { requireFile: true });
249
- const actual = digestFile(target.file);
250
- if (actual !== entry.after_digest) {
251
- throw new DeliveryTransactionError(
252
- 'DELIVERY_RECOVERY_REQUIRED',
253
- `applied delivery target is stale: ${entry.target_path}`,
254
- { expected: entry.after_digest, actual },
255
- );
256
- }
257
- }
258
- }
259
-
260
- function restoreJournal(rootDir, journal, directory) {
261
- for (const entry of [...journal.entries].reverse()) {
262
- const target = resolveInside(rootDir, entry.target_path, 'target_path');
263
- if (entry.existed) {
264
- const backup = resolveInside(
265
- rootDir, entry.backup_path, 'backup_path', { requireFile: true },
266
- );
267
- fs.mkdirSync(path.dirname(target.file), { recursive: true });
268
- const temporary = `${target.file}.restore-${process.pid}-${crypto.randomUUID()}`;
269
- fs.copyFileSync(backup.file, temporary);
270
- if (digestFile(temporary) !== entry.before_digest) {
271
- fs.rmSync(temporary, { force: true });
272
- throw new DeliveryTransactionError(
273
- 'DELIVERY_RECOVERY_REQUIRED',
274
- `delivery backup is stale: ${entry.backup_path}`,
275
- );
276
- }
277
- fs.renameSync(temporary, target.file);
278
- } else {
279
- fs.rmSync(target.file, { force: true });
280
- }
281
- }
282
- fs.rmSync(directory, { recursive: true, force: true });
283
- }
284
-
285
- function beginDeliveryTransaction({ rootDir, changeId, entries }) {
286
- const normalized = normalizedEntries(entries);
287
- const directory = transactionDirectory(rootDir, changeId);
288
- if (fs.existsSync(directory)) {
289
- const journal = readJournal(directory);
290
- if (journal.change_id !== changeId
291
- || canonicalEntries(journal.entries) !== canonicalEntries(normalized)) {
292
- throw new DeliveryTransactionError(
293
- 'DELIVERY_TRANSACTION_CONFLICT',
294
- `existing delivery transaction differs for ${changeId}`,
295
- );
296
- }
297
- if (journal.status === 'applied') {
298
- verifyApplied(rootDir, normalized);
299
- return { ...journal, resumed: true };
300
- }
301
- restoreJournal(rootDir, journal, directory);
302
- }
303
-
304
- const inspected = preflight(rootDir, normalized);
305
- const transactionRoot = path.dirname(directory);
306
- fs.mkdirSync(transactionRoot, { recursive: true, mode: 0o700 });
307
- const staging = path.join(
308
- transactionRoot,
309
- `.prepare-${changeId}-${process.pid}-${crypto.randomUUID()}`,
310
- );
311
- const journal = {
312
- schema_version: SCHEMA_VERSION,
313
- transaction_id: crypto.randomUUID(),
314
- change_id: changeId,
315
- status: 'prepared',
316
- entries: [],
317
- created_at: new Date().toISOString(),
318
- updated_at: null,
319
- };
320
- let published = false;
321
- try {
322
- fs.mkdirSync(path.join(staging, 'backups'), { recursive: true, mode: 0o700 });
323
- journal.entries = inspected.map((item, index) => {
324
- const backupPath = `${TRANSACTION_ROOT}/${changeId}/backups/${index + 1}`;
325
- if (item.existed) {
326
- const stagedBackup = path.join(staging, 'backups', String(index + 1));
327
- fs.copyFileSync(item.target.file, stagedBackup);
328
- if (digestFile(stagedBackup) !== item.entry.before_digest) {
329
- throw new DeliveryTransactionError(
330
- 'DELIVERY_RECOVERY_REQUIRED',
331
- `delivery backup could not be verified: ${item.entry.target_path}`,
332
- );
333
- }
334
- }
335
- return {
336
- ...item.entry,
337
- existed: item.existed,
338
- backup_path: item.existed ? backupPath : null,
339
- };
340
- });
341
- writeJournal(staging, journal);
342
- fs.renameSync(staging, directory);
343
- published = true;
344
- for (const item of inspected) applyEntry(item);
345
- verifyApplied(rootDir, normalized);
346
- journal.status = 'applied';
347
- writeJournal(directory, journal);
348
- return { ...journal, resumed: false };
349
- } catch (error) {
350
- if (!published) {
351
- fs.rmSync(staging, { recursive: true, force: true });
352
- } else {
353
- try { restoreJournal(rootDir, journal, directory); }
354
- catch (recoveryError) {
355
- throw new DeliveryTransactionError(
356
- 'DELIVERY_RECOVERY_REQUIRED',
357
- `delivery apply failed and rollback did not complete: ${error.message}`,
358
- { cause: error.code || error.message, rollback: recoveryError.code || recoveryError.message },
359
- );
360
- }
361
- }
362
- throw error;
363
- }
364
- }
365
-
366
- function completeDeliveryTransaction({ rootDir, changeId }) {
367
- const directory = transactionDirectory(rootDir, changeId);
368
- if (!fs.existsSync(directory)) return { completed: true, idempotent: true };
369
- const journal = readJournal(directory);
370
- if (journal.status !== 'applied') {
371
- throw new DeliveryTransactionError(
372
- 'DELIVERY_RECOVERY_REQUIRED',
373
- `delivery transaction ${changeId} is ${journal.status}`,
374
- );
375
- }
376
- verifyApplied(rootDir, journal.entries);
377
- fs.rmSync(directory, { recursive: true, force: true });
378
- return { completed: true, idempotent: false };
379
- }
380
-
381
- function rollbackDeliveryTransaction({ rootDir, changeId }) {
382
- const directory = transactionDirectory(rootDir, changeId);
383
- if (!fs.existsSync(directory)) return { restored: false, idempotent: true };
384
- const journal = readJournal(directory);
385
- restoreJournal(rootDir, journal, directory);
386
- return { restored: true, idempotent: false };
387
- }
388
-
389
- function listDeliveryTransactions(rootDir) {
390
- const root = path.join(projectRoot(rootDir), TRANSACTION_ROOT);
391
- if (!fs.existsSync(root)) return [];
392
- const entries = fs.readdirSync(root, { withFileTypes: true });
393
- const rows = [];
394
- for (const entry of entries) {
395
- if (entry.isDirectory() && entry.name.startsWith('.prepare-')) {
396
- rows.push({
397
- change_id: entry.name,
398
- directory: path.join(root, entry.name),
399
- preparing: true,
400
- });
401
- continue;
402
- }
403
- if (!entry.isDirectory() || !ID.test(entry.name)) {
404
- rows.push({
405
- change_id: entry.name,
406
- error: new DeliveryTransactionError(
407
- 'DELIVERY_RECOVERY_REQUIRED',
408
- `unexpected delivery transaction residue: ${entry.name}`,
409
- ),
410
- });
411
- continue;
412
- }
413
- const directory = path.join(root, entry.name);
414
- try {
415
- rows.push({ change_id: entry.name, directory, journal: readJournal(directory) });
416
- } catch (error) {
417
- rows.push({ change_id: entry.name, directory, error });
418
- }
419
- }
420
- return rows;
421
- }
422
-
423
- function recoverDeliveryTransactions({
424
- rootDir,
425
- archivedChangeIds = new Set(),
426
- } = {}) {
427
- const result = { found: 0, restored: 0, committed: 0, failed: 0, items: [] };
428
- for (const row of listDeliveryTransactions(rootDir)) {
429
- result.found += 1;
430
- if (row.preparing) {
431
- fs.rmSync(row.directory, { recursive: true, force: true });
432
- result.restored += 1;
433
- result.items.push({ change_id: row.change_id, status: 'discarded_preparation' });
434
- continue;
435
- }
436
- if (row.error) {
437
- result.failed += 1;
438
- result.items.push({ change_id: row.change_id, status: 'failed', error: row.error.code });
439
- continue;
440
- }
441
- try {
442
- if (archivedChangeIds.has(row.change_id)) {
443
- completeDeliveryTransaction({ rootDir, changeId: row.change_id });
444
- result.committed += 1;
445
- result.items.push({ change_id: row.change_id, status: 'committed' });
446
- } else {
447
- rollbackDeliveryTransaction({ rootDir, changeId: row.change_id });
448
- result.restored += 1;
449
- result.items.push({ change_id: row.change_id, status: 'restored' });
450
- }
451
- } catch (error) {
452
- result.failed += 1;
453
- result.items.push({
454
- change_id: row.change_id,
455
- status: 'failed',
456
- error: error.code || error.message,
457
- });
458
- }
459
- }
460
- return result;
461
- }
462
-
463
- module.exports = {
464
- DeliveryTransactionError,
465
- TRANSACTION_ROOT,
466
- beginDeliveryTransaction,
467
- completeDeliveryTransaction,
468
- rollbackDeliveryTransaction,
469
- listDeliveryTransactions,
470
- recoverDeliveryTransactions,
471
- };