ultra-builder-pro-cli 0.20.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/.ultra-template/docs/research/README.md +26 -5
  2. package/.ultra-template/specs/discovery.md +1 -1
  3. package/.ultra-template/tasks/tasks.json +10 -3
  4. package/.ultra-template/templates/task-context.md +19 -0
  5. package/CHANGELOG.md +106 -0
  6. package/README.md +215 -41
  7. package/adapters/_shared/codex-assets.cjs +69 -11
  8. package/adapters/_shared/interaction-contract.cjs +36 -3
  9. package/adapters/_shared/runtime-assets.cjs +41 -1
  10. package/adapters/claude.js +7 -5
  11. package/adapters/codex.js +1 -1
  12. package/adapters/kimi.js +2 -8
  13. package/adapters/opencode.js +43 -30
  14. package/bin/orchestrator.js +64 -24
  15. package/docs/AGENT-CONTEXT.md +89 -49
  16. package/docs/ARCHITECTURE.md +112 -45
  17. package/docs/ARTIFACT-AUTHORITY.md +274 -0
  18. package/docs/COMMIT-HASH-BACKFILL.md +33 -90
  19. package/docs/DECISIONS.md +14 -6
  20. package/docs/LEGACY-CLI-CROSSWALK.md +16 -6
  21. package/docs/PLUGIN-ISOLATION-CONTRACT.md +6 -4
  22. package/docs/ROADMAP.md +20 -6
  23. package/docs/RUNTIME-COMPAT-MATRIX.md +29 -16
  24. package/docs/STATE-DB-ACCESS-POLICY.md +43 -13
  25. package/docs/WORKFLOW-LIFECYCLE.md +105 -50
  26. package/hooks/README.md +10 -8
  27. package/hooks/active_task_context.py +105 -18
  28. package/hooks/context_spine.py +16 -4
  29. package/hooks/health_check.py +5 -4
  30. package/hooks/pre_stop_check.py +5 -2
  31. package/hooks/runtime_paths.py +396 -0
  32. package/hooks/subagent_tracker.py +5 -2
  33. package/hooks/workflow_checkpoint.py +16 -3
  34. package/hooks/workflow_context.py +11 -3
  35. package/hooks/workflow_resume.py +7 -4
  36. package/mcp-server/breadcrumb.cjs +20 -2
  37. package/mcp-server/lib/archive-journal.cjs +1026 -111
  38. package/mcp-server/lib/archive-mutation-worker.py +365 -0
  39. package/mcp-server/lib/artifact-registry.cjs +1127 -0
  40. package/mcp-server/lib/baseline-workflow.cjs +69 -28
  41. package/mcp-server/lib/change-packet.cjs +818 -0
  42. package/mcp-server/lib/change-workflow.cjs +932 -176
  43. package/mcp-server/lib/context-paths.cjs +142 -0
  44. package/mcp-server/lib/context-spine.cjs +511 -45
  45. package/mcp-server/lib/decision-dialogue.cjs +345 -3
  46. package/mcp-server/lib/delivery-transaction.cjs +471 -0
  47. package/mcp-server/lib/doctor-backup-worker.cjs +328 -0
  48. package/mcp-server/lib/doctor.cjs +401 -11
  49. package/mcp-server/lib/git-bootstrap.cjs +458 -47
  50. package/mcp-server/lib/init-project.cjs +240 -95
  51. package/mcp-server/lib/plan-publication-worker.cjs +830 -0
  52. package/mcp-server/lib/plan-store.cjs +700 -5
  53. package/mcp-server/lib/project-breadcrumb.cjs +23 -4
  54. package/mcp-server/lib/projector.cjs +211 -42
  55. package/mcp-server/lib/runtime-paths.cjs +1687 -0
  56. package/mcp-server/lib/safe-project-file.cjs +385 -0
  57. package/mcp-server/lib/spec-learning.cjs +28 -12
  58. package/mcp-server/lib/state-authority.cjs +19 -3
  59. package/mcp-server/lib/state-db.cjs +263 -9
  60. package/mcp-server/lib/state-ops.cjs +254 -50
  61. package/mcp-server/lib/task-ledger.cjs +1342 -0
  62. package/mcp-server/lib/telemetry.cjs +12 -3
  63. package/mcp-server/lib/workflow-state.cjs +610 -58
  64. package/mcp-server/server.cjs +423 -42
  65. package/orchestrator/daemon.cjs +2 -10
  66. package/orchestrator/parallel-orchestrator.cjs +314 -50
  67. package/orchestrator/planner/plan-builder.cjs +1 -1
  68. package/orchestrator/recovery.cjs +125 -7
  69. package/orchestrator/session-close-journal-worker.cjs +5 -0
  70. package/orchestrator/session-close-journal.cjs +1014 -0
  71. package/orchestrator/session-runner.cjs +679 -69
  72. package/orchestrator/worktree-manager.cjs +186 -35
  73. package/package.json +2 -3
  74. package/skills/cc-collab/SKILL.md +4 -1
  75. package/skills/codex-collab/SKILL.md +5 -2
  76. package/skills/ultra-change/SKILL.md +34 -8
  77. package/skills/ultra-deliver/SKILL.md +26 -11
  78. package/skills/ultra-dev/SKILL.md +52 -10
  79. package/skills/ultra-doctor/SKILL.md +16 -3
  80. package/skills/ultra-init/SKILL.md +22 -11
  81. package/skills/ultra-plan/SKILL.md +58 -18
  82. package/skills/ultra-research/SKILL.md +37 -35
  83. package/skills/ultra-review/SKILL.md +14 -8
  84. package/skills/ultra-status/SKILL.md +18 -9
  85. package/skills/ultra-test/SKILL.md +11 -5
  86. package/skills/ultra-think/SKILL.md +6 -2
  87. package/skills/ultra-think/references/decision-dialogue.md +17 -6
  88. package/skills/ultra-verify/SKILL.md +4 -1
  89. package/spec/cli-protocol.md +21 -7
  90. package/spec/mcp-tools.yaml +629 -44
  91. package/spec/schemas/change-delta.v1.schema.json +153 -0
  92. package/spec/schemas/context-file.v4.5.schema.json +1 -1
  93. package/spec/schemas/documentation-reconciliation.v1.schema.json +106 -0
  94. package/spec/schemas/mcp-tools.schema.json +1 -1
  95. package/spec/schemas/state-db.sql +51 -14
  96. package/spec/schemas/task-ledger.v1.schema.json +217 -0
  97. package/spec/schemas/tasks.v4.5.schema.json +1 -1
  98. package/ultra-tools/cli.cjs +3 -2
  99. package/ultra-tools/commands/db.cjs +76 -25
  100. package/ultra-tools/commands/migrate.cjs +1000 -82
  101. package/ultra-tools/commands/session.cjs +34 -8
  102. package/ultra-tools/commands/status.cjs +32 -6
  103. package/ultra-tools/commands/system.cjs +129 -22
  104. package/.ultra-template/tasks/contexts/TEMPLATE.md +0 -19
  105. package/commands/learn.md +0 -10
  106. package/orchestrator/skill-miner.cjs +0 -133
  107. package/output-styles/coding-vibes.md +0 -67
  108. package/output-styles/structural-thinking.md +0 -61
  109. package/skills/learn/SKILL.md +0 -58
@@ -0,0 +1,830 @@
1
+ 'use strict';
2
+
3
+ // Plan publication needs rename operations relative to a stable directory
4
+ // identity. Node does not expose openat(2)/renameat(2), so the parent launches
5
+ // this bounded helper with cwd set to the verified Change artifact directory.
6
+ // Once the child has chdir'd, ancestor replacement cannot redirect its
7
+ // relative file operations.
8
+
9
+ const fs = require('node:fs');
10
+ const crypto = require('node:crypto');
11
+
12
+ const ACTIONS = new Set([
13
+ 'prepare',
14
+ 'publish',
15
+ 'rollback',
16
+ 'commit',
17
+ 'inspect',
18
+ 'recover',
19
+ 'read',
20
+ ]);
21
+ const TRANSACTION_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
22
+ const JOURNAL_PATTERN = /^\.plan-publish-([0-9a-f-]{36})\.journal\.json$/i;
23
+ const PUBLICATION_ENTRY_PATTERN = /^\.plan-publish-(.+)\.(journal\.json(?:\.next)?|(?:json|md)\.(?:tmp|backup))$/i;
24
+ const KINDS = Object.freeze({
25
+ execution_plan: {
26
+ target: 'plan.json',
27
+ tempSuffix: 'json.tmp',
28
+ backupSuffix: 'json.backup',
29
+ },
30
+ execution_plan_markdown: {
31
+ target: 'plan.md',
32
+ tempSuffix: 'md.tmp',
33
+ backupSuffix: 'md.backup',
34
+ },
35
+ });
36
+ const MAX_CONTENT_BYTES = 16 * 1024 * 1024;
37
+
38
+ class WorkerError extends Error {
39
+ constructor(code, message, details = undefined) {
40
+ super(message);
41
+ this.code = code;
42
+ if (details !== undefined) this.details = details;
43
+ }
44
+ }
45
+
46
+ function digest(value) {
47
+ return crypto.createHash('sha256').update(value).digest('hex');
48
+ }
49
+
50
+ function identityOfCurrentDirectory() {
51
+ const stat = fs.statSync('.', { bigint: true });
52
+ if (!stat.isDirectory()) {
53
+ throw new WorkerError(
54
+ 'PLAN_ARTIFACT_PATH_UNSAFE',
55
+ 'plan publication cwd must be a directory',
56
+ );
57
+ }
58
+ return { dev: String(stat.dev), ino: String(stat.ino) };
59
+ }
60
+
61
+ function validateIdentity(expected) {
62
+ if (!expected || typeof expected !== 'object') {
63
+ throw new WorkerError(
64
+ 'PLAN_ARTIFACT_PATH_UNSAFE',
65
+ 'plan publication directory identity is required',
66
+ );
67
+ }
68
+ const current = identityOfCurrentDirectory();
69
+ if (String(expected.dev) !== current.dev || String(expected.ino) !== current.ino) {
70
+ throw new WorkerError(
71
+ 'PLAN_ARTIFACT_PATH_UNSAFE',
72
+ 'plan artifact directory identity changed',
73
+ { expected, current },
74
+ );
75
+ }
76
+ return current;
77
+ }
78
+
79
+ function validateStoredIdentity(value) {
80
+ if (!value || typeof value !== 'object' || Array.isArray(value)
81
+ || !/^\d+$/.test(String(value.dev || ''))
82
+ || !/^\d+$/.test(String(value.ino || ''))) {
83
+ throw new WorkerError(
84
+ 'PLAN_JOURNAL_INVALID',
85
+ 'plan publication journal directory identity is malformed',
86
+ );
87
+ }
88
+ return { dev: String(value.dev), ino: String(value.ino) };
89
+ }
90
+
91
+ function assertJournalDirectoryIdentity(value) {
92
+ const expected = validateStoredIdentity(value.directory_identity);
93
+ const current = identityOfCurrentDirectory();
94
+ if (expected.dev !== current.dev || expected.ino !== current.ino) {
95
+ throw new WorkerError(
96
+ 'PLAN_ARTIFACT_PATH_UNSAFE',
97
+ 'plan publication journal directory identity does not match cwd',
98
+ { expected, current },
99
+ );
100
+ }
101
+ return current;
102
+ }
103
+
104
+ function normalizeCanonicalPath(value, field) {
105
+ if (typeof value !== 'string' || !value.trim() || value.includes('\\')) {
106
+ throw new WorkerError('PLAN_JOURNAL_INVALID', `${field} must be a canonical project-relative path`);
107
+ }
108
+ const candidate = value.trim();
109
+ if (candidate.startsWith('/') || candidate.split('/').some((segment) => (
110
+ !segment || segment === '.' || segment === '..'
111
+ ))) {
112
+ throw new WorkerError('PLAN_JOURNAL_INVALID', `${field} must be a canonical project-relative path`);
113
+ }
114
+ return candidate;
115
+ }
116
+
117
+ function validateAuthority(value) {
118
+ if (!value || typeof value !== 'object' || Array.isArray(value)
119
+ || value.owner_type !== 'change'
120
+ || typeof value.owner_id !== 'string' || !value.owner_id.trim()
121
+ || !value.paths || typeof value.paths !== 'object' || Array.isArray(value.paths)) {
122
+ throw new WorkerError(
123
+ 'PLAN_JOURNAL_INVALID',
124
+ 'plan publication Change authority is malformed',
125
+ );
126
+ }
127
+ const kinds = Object.keys(KINDS);
128
+ if (Object.keys(value.paths).sort().join(',') !== kinds.sort().join(',')) {
129
+ throw new WorkerError(
130
+ 'PLAN_JOURNAL_INVALID',
131
+ 'plan publication authority path set is incomplete',
132
+ );
133
+ }
134
+ return {
135
+ owner_type: 'change',
136
+ owner_id: value.owner_id.trim(),
137
+ paths: Object.fromEntries(kinds.map((kind) => [
138
+ kind,
139
+ normalizeCanonicalPath(value.paths[kind], `authority.paths.${kind}`),
140
+ ])),
141
+ };
142
+ }
143
+
144
+ function namesFor(kind, transactionId) {
145
+ const definition = KINDS[kind];
146
+ if (!definition) {
147
+ throw new WorkerError('PLAN_JOURNAL_INVALID', `unsupported plan artifact kind: ${kind}`);
148
+ }
149
+ return {
150
+ kind,
151
+ target: definition.target,
152
+ temp: `.plan-publish-${transactionId}.${definition.tempSuffix}`,
153
+ backup: `.plan-publish-${transactionId}.${definition.backupSuffix}`,
154
+ };
155
+ }
156
+
157
+ function journalName(transactionId) {
158
+ return `.plan-publish-${transactionId}.journal.json`;
159
+ }
160
+
161
+ function assertTransactionId(transactionId) {
162
+ if (typeof transactionId !== 'string' || !TRANSACTION_PATTERN.test(transactionId)) {
163
+ throw new WorkerError('PLAN_JOURNAL_INVALID', 'invalid plan publication transaction id');
164
+ }
165
+ return transactionId;
166
+ }
167
+
168
+ function lstat(candidate) {
169
+ try { return fs.lstatSync(candidate); } catch (error) {
170
+ if (error?.code === 'ENOENT') return null;
171
+ throw error;
172
+ }
173
+ }
174
+
175
+ function readRegular(candidate) {
176
+ const before = lstat(candidate);
177
+ if (!before) return null;
178
+ if (!before.isFile() || before.isSymbolicLink()) {
179
+ throw new WorkerError(
180
+ 'PLAN_ARTIFACT_PATH_UNSAFE',
181
+ `plan publication entry must be a regular file: ${candidate}`,
182
+ );
183
+ }
184
+ const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0);
185
+ let fd;
186
+ try {
187
+ fd = fs.openSync(candidate, flags);
188
+ const opened = fs.fstatSync(fd);
189
+ if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino) {
190
+ throw new WorkerError(
191
+ 'PLAN_PUBLISH_CONFLICT',
192
+ `plan publication entry changed while opening: ${candidate}`,
193
+ );
194
+ }
195
+ const bytes = fs.readFileSync(fd);
196
+ return {
197
+ bytes,
198
+ digest: digest(bytes),
199
+ dev: String(opened.dev),
200
+ ino: String(opened.ino),
201
+ };
202
+ } finally {
203
+ if (fd !== undefined) fs.closeSync(fd);
204
+ }
205
+ }
206
+
207
+ function writeExclusive(candidate, content) {
208
+ const flags = fs.constants.O_WRONLY
209
+ | fs.constants.O_CREAT
210
+ | fs.constants.O_EXCL
211
+ | (fs.constants.O_NOFOLLOW || 0);
212
+ const fd = fs.openSync(candidate, flags, 0o600);
213
+ try {
214
+ fs.writeFileSync(fd, content);
215
+ fs.fsyncSync(fd);
216
+ } finally {
217
+ fs.closeSync(fd);
218
+ }
219
+ }
220
+
221
+ function fsyncCurrentDirectory() {
222
+ const fd = fs.openSync('.', fs.constants.O_RDONLY);
223
+ try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
224
+ }
225
+
226
+ function journalNextName(journal) {
227
+ return `${journal}.next`;
228
+ }
229
+
230
+ function discardInterruptedJournalUpdate(journal, transactionId) {
231
+ const next = journalNextName(journal);
232
+ const value = readRegular(next);
233
+ if (!value) return;
234
+ let parsed;
235
+ try { parsed = JSON.parse(value.bytes.toString('utf8')); } catch {
236
+ throw new WorkerError(
237
+ 'PLAN_JOURNAL_INVALID',
238
+ `interrupted journal update is not valid JSON: ${next}`,
239
+ );
240
+ }
241
+ validateJournal(parsed, transactionId);
242
+ fs.unlinkSync(next);
243
+ }
244
+
245
+ function writeJournal(journal, value, { exclusive = false } = {}) {
246
+ const text = `${JSON.stringify(value, null, 2)}\n`;
247
+ if (exclusive) {
248
+ writeExclusive(journal, text);
249
+ fsyncCurrentDirectory();
250
+ return;
251
+ }
252
+ const stat = lstat(journal);
253
+ if (!stat || !stat.isFile() || stat.isSymbolicLink()) {
254
+ throw new WorkerError(
255
+ 'PLAN_JOURNAL_INVALID',
256
+ `plan publication journal is missing or unsafe: ${journal}`,
257
+ );
258
+ }
259
+ discardInterruptedJournalUpdate(journal, value.transaction_id);
260
+ const next = journalNextName(journal);
261
+ writeExclusive(next, text);
262
+ fs.renameSync(next, journal);
263
+ fsyncCurrentDirectory();
264
+ }
265
+
266
+ function validateJournal(value, expectedTransactionId = null) {
267
+ if (!value || typeof value !== 'object' || Array.isArray(value)
268
+ || value.version !== 2
269
+ || !TRANSACTION_PATTERN.test(value.transaction_id || '')
270
+ || !Array.isArray(value.entries)
271
+ || value.entries.length !== 2) {
272
+ throw new WorkerError('PLAN_JOURNAL_INVALID', 'plan publication journal is malformed');
273
+ }
274
+ if (expectedTransactionId && value.transaction_id !== expectedTransactionId) {
275
+ throw new WorkerError('PLAN_JOURNAL_INVALID', 'plan publication journal id mismatch');
276
+ }
277
+ validateStoredIdentity(value.directory_identity);
278
+ const authority = validateAuthority(value.authority);
279
+ const expectedKinds = Object.keys(KINDS);
280
+ const seen = new Set();
281
+ for (const entry of value.entries) {
282
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)
283
+ || !expectedKinds.includes(entry.kind) || seen.has(entry.kind)) {
284
+ throw new WorkerError('PLAN_JOURNAL_INVALID', 'plan publication journal entry is malformed');
285
+ }
286
+ seen.add(entry.kind);
287
+ const names = namesFor(entry.kind, value.transaction_id);
288
+ if (entry.target !== names.target || entry.temp !== names.temp || entry.backup !== names.backup
289
+ || entry.canonical_path !== authority.paths[entry.kind]
290
+ || typeof entry.existed !== 'boolean'
291
+ || (entry.prior_digest !== null && !/^[0-9a-f]{64}$/.test(entry.prior_digest || ''))
292
+ || !/^[0-9a-f]{64}$/.test(entry.digest || '')
293
+ || typeof entry.backed_up !== 'boolean'
294
+ || typeof entry.installed !== 'boolean') {
295
+ throw new WorkerError('PLAN_JOURNAL_INVALID', 'plan publication journal names or digests are invalid');
296
+ }
297
+ }
298
+ if (seen.size !== expectedKinds.length) {
299
+ throw new WorkerError('PLAN_JOURNAL_INVALID', 'plan publication journal entry set is incomplete');
300
+ }
301
+ return value;
302
+ }
303
+
304
+ function readJournal(transactionId) {
305
+ assertTransactionId(transactionId);
306
+ const candidate = journalName(transactionId);
307
+ const read = readRegular(candidate);
308
+ if (!read) return null;
309
+ let parsed;
310
+ try { parsed = JSON.parse(read.bytes.toString('utf8')); } catch (cause) {
311
+ throw new WorkerError('PLAN_JOURNAL_INVALID', `cannot parse ${candidate}: ${cause.message}`);
312
+ }
313
+ const value = validateJournal(parsed, transactionId);
314
+ assertJournalDirectoryIdentity(value);
315
+ return value;
316
+ }
317
+
318
+ function snapshotMatches(entry) {
319
+ const current = readRegular(entry.target);
320
+ if (!entry.existed) return current === null;
321
+ return Boolean(current && current.digest === entry.prior_digest);
322
+ }
323
+
324
+ function cleanup(candidate) {
325
+ const stat = lstat(candidate);
326
+ if (!stat) return;
327
+ if (!stat.isFile() || stat.isSymbolicLink()) {
328
+ throw new WorkerError(
329
+ 'PLAN_ARTIFACT_PATH_UNSAFE',
330
+ `refusing to clean a non-regular plan publication entry: ${candidate}`,
331
+ );
332
+ }
333
+ fs.unlinkSync(candidate);
334
+ }
335
+
336
+ function assertNoPendingPublication(allowedTransactionId = null) {
337
+ const scanned = scanPublicationEntries();
338
+ const otherTransactions = scanned.journals.filter(
339
+ (item) => item.transaction_id !== allowedTransactionId,
340
+ );
341
+ if (otherTransactions.length === 0 && scanned.issues.length === 0) return;
342
+ throw new WorkerError(
343
+ 'PLAN_RECOVERY_REQUIRED',
344
+ 'an earlier plan publication must be inspected or recovered before preparing another one',
345
+ {
346
+ pending_transactions: otherTransactions.map((item) => item.transaction_id),
347
+ issues: scanned.issues,
348
+ },
349
+ );
350
+ }
351
+
352
+ function prepare(payload) {
353
+ const transactionId = assertTransactionId(payload.transaction_id);
354
+ const identity = validateIdentity(payload.identity);
355
+ const authority = validateAuthority(payload.authority);
356
+ assertNoPendingPublication();
357
+ if (!payload.contents || typeof payload.contents !== 'object' || Array.isArray(payload.contents)) {
358
+ throw new WorkerError('PLAN_JOURNAL_INVALID', 'plan publication contents are required');
359
+ }
360
+ const entries = Object.keys(KINDS).map((kind) => {
361
+ const content = payload.contents[kind];
362
+ if (typeof content !== 'string'
363
+ || Buffer.byteLength(content) > MAX_CONTENT_BYTES) {
364
+ throw new WorkerError(
365
+ 'PLAN_JOURNAL_INVALID',
366
+ `plan publication content is invalid or too large: ${kind}`,
367
+ );
368
+ }
369
+ const names = namesFor(kind, transactionId);
370
+ const prior = readRegular(names.target);
371
+ return {
372
+ ...names,
373
+ canonical_path: authority.paths[kind],
374
+ existed: Boolean(prior),
375
+ prior_digest: prior?.digest || null,
376
+ digest: digest(content),
377
+ backed_up: false,
378
+ installed: false,
379
+ content,
380
+ };
381
+ });
382
+ const journal = journalName(transactionId);
383
+ const value = {
384
+ version: 2,
385
+ transaction_id: transactionId,
386
+ phase: 'preparing',
387
+ directory_identity: identity,
388
+ authority,
389
+ created_at: new Date().toISOString(),
390
+ entries: entries.map(({ content, ...entry }) => entry),
391
+ };
392
+ let journalCreated = false;
393
+ try {
394
+ writeJournal(journal, value, { exclusive: true });
395
+ journalCreated = true;
396
+ // Close the race where two publishers both observed an empty directory
397
+ // before either created its journal. Only the first durable journal may
398
+ // proceed to stage bytes.
399
+ assertNoPendingPublication(transactionId);
400
+ for (const entry of entries) writeExclusive(entry.temp, entry.content);
401
+ value.phase = 'prepared';
402
+ writeJournal(journal, value);
403
+ return value;
404
+ } catch (error) {
405
+ if (journalCreated) {
406
+ try { rollbackJournal(value); } catch { /* retained journal is diagnosed later */ }
407
+ } else {
408
+ for (const entry of entries) {
409
+ try { cleanup(entry.temp); } catch { /* retained residue is diagnosed later */ }
410
+ }
411
+ }
412
+ throw error;
413
+ }
414
+ }
415
+
416
+ function publish(payload) {
417
+ validateIdentity(payload.identity);
418
+ const value = readJournal(assertTransactionId(payload.transaction_id));
419
+ if (!value) {
420
+ throw new WorkerError('PLAN_JOURNAL_INVALID', 'plan publication journal is missing');
421
+ }
422
+ if (value.phase === 'published' || value.phase === 'committed') {
423
+ const current = value.entries.every((entry) => readRegular(entry.target)?.digest === entry.digest);
424
+ if (!current) {
425
+ throw new WorkerError('PLAN_PUBLISH_CONFLICT', 'published plan bytes changed');
426
+ }
427
+ return value;
428
+ }
429
+ if (!['preparing', 'prepared'].includes(value.phase)) {
430
+ throw new WorkerError(
431
+ 'PLAN_PUBLISH_CONFLICT',
432
+ `plan publication cannot publish from phase ${value.phase}`,
433
+ );
434
+ }
435
+ const conflict = value.entries.find((entry) => !snapshotMatches(entry));
436
+ if (conflict) {
437
+ throw new WorkerError(
438
+ 'PLAN_PUBLISH_CONFLICT',
439
+ `plan artifact changed after prepare: ${conflict.target}`,
440
+ {
441
+ target: conflict.target,
442
+ expected: conflict.prior_digest,
443
+ actual: readRegular(conflict.target)?.digest || null,
444
+ },
445
+ );
446
+ }
447
+ for (const entry of value.entries) {
448
+ const temp = readRegular(entry.temp);
449
+ if (!temp || temp.digest !== entry.digest) {
450
+ throw new WorkerError(
451
+ 'PLAN_PUBLISH_CONFLICT',
452
+ `staged plan artifact is missing or changed: ${entry.temp}`,
453
+ );
454
+ }
455
+ if (readRegular(entry.backup)) {
456
+ throw new WorkerError(
457
+ 'PLAN_PUBLISH_CONFLICT',
458
+ `plan publication backup already exists: ${entry.backup}`,
459
+ );
460
+ }
461
+ }
462
+ for (const entry of value.entries) {
463
+ if (!entry.existed) continue;
464
+ if (!snapshotMatches(entry) || readRegular(entry.backup)) {
465
+ throw new WorkerError(
466
+ 'PLAN_PUBLISH_CONFLICT',
467
+ `plan artifact changed before backup: ${entry.target}`,
468
+ );
469
+ }
470
+ fs.renameSync(entry.target, entry.backup);
471
+ entry.backed_up = true;
472
+ value.phase = 'backing_up';
473
+ writeJournal(journalName(value.transaction_id), value);
474
+ }
475
+ value.phase = 'backed_up';
476
+ writeJournal(journalName(value.transaction_id), value);
477
+ for (const entry of value.entries) {
478
+ const temp = readRegular(entry.temp);
479
+ if (readRegular(entry.target) || !temp || temp.digest !== entry.digest) {
480
+ throw new WorkerError(
481
+ 'PLAN_PUBLISH_CONFLICT',
482
+ `plan artifact changed before installation: ${entry.target}`,
483
+ );
484
+ }
485
+ fs.renameSync(entry.temp, entry.target);
486
+ entry.installed = true;
487
+ value.phase = 'publishing';
488
+ writeJournal(journalName(value.transaction_id), value);
489
+ }
490
+ value.phase = 'published';
491
+ writeJournal(journalName(value.transaction_id), value);
492
+ return value;
493
+ }
494
+
495
+ function recoveryState(entry) {
496
+ return {
497
+ entry,
498
+ target: readRegular(entry.target),
499
+ backup: readRegular(entry.backup),
500
+ temp: readRegular(entry.temp),
501
+ };
502
+ }
503
+
504
+ function recoveryConflicts(state, journal) {
505
+ const {
506
+ entry, target, backup, temp,
507
+ } = state;
508
+ const conflicts = [];
509
+ const targetIsNew = target?.digest === entry.digest;
510
+ const targetIsPrior = entry.existed && target?.digest === entry.prior_digest;
511
+ if (target && !targetIsNew && !targetIsPrior && backup) {
512
+ conflicts.push(`${entry.target}:target_changed_after_backup`);
513
+ }
514
+ if (backup && (!entry.existed || backup.digest !== entry.prior_digest)) {
515
+ conflicts.push(`${entry.backup}:backup_changed`);
516
+ }
517
+ if (temp && temp.digest !== entry.digest) {
518
+ conflicts.push(`${entry.temp}:temp_changed`);
519
+ }
520
+ const demonstrablyPreBackup = ['preparing', 'prepared'].includes(journal.phase)
521
+ && journal.entries.every((candidate) => (
522
+ candidate.backed_up === false && candidate.installed === false
523
+ ));
524
+ if (entry.existed && !targetIsNew && !targetIsPrior && !backup) {
525
+ conflicts.push(
526
+ `${entry.target}:${target ? 'target_changed' : 'target_missing'}`
527
+ + (demonstrablyPreBackup ? '_before_backup' : '_prior_bytes_unrecoverable'),
528
+ );
529
+ }
530
+ if (entry.existed && targetIsNew
531
+ && (!backup || backup.digest !== entry.prior_digest)) {
532
+ conflicts.push(`${entry.target}:prior_bytes_unrecoverable`);
533
+ }
534
+ return conflicts;
535
+ }
536
+
537
+ function cleanupExpected(candidate, expectedDigest) {
538
+ const current = readRegular(candidate);
539
+ if (!current) return false;
540
+ if (current.digest !== expectedDigest) {
541
+ throw new WorkerError(
542
+ 'PLAN_RECOVERY_CONFLICT',
543
+ `refusing to clean changed plan publication bytes: ${candidate}`,
544
+ );
545
+ }
546
+ fs.unlinkSync(candidate);
547
+ return true;
548
+ }
549
+
550
+ function rollbackJournal(value) {
551
+ assertJournalDirectoryIdentity(value);
552
+ let changed = false;
553
+ const states = [...value.entries].reverse().map(recoveryState);
554
+ const conflicts = states.flatMap((state) => recoveryConflicts(state, value));
555
+ if (conflicts.length > 0) {
556
+ value.phase = 'recovery_blocked';
557
+ writeJournal(journalName(value.transaction_id), value);
558
+ throw new WorkerError(
559
+ 'PLAN_RECOVERY_CONFLICT',
560
+ `plan publication rollback refused changed bytes: ${conflicts.join(', ')}`,
561
+ { conflicts },
562
+ );
563
+ }
564
+ for (const state of states) {
565
+ const { entry, backup } = state;
566
+ const currentTarget = readRegular(entry.target);
567
+ if (currentTarget?.digest === entry.digest) {
568
+ fs.unlinkSync(entry.target);
569
+ changed = true;
570
+ }
571
+ if (entry.existed && backup?.digest === entry.prior_digest
572
+ && !readRegular(entry.target)) {
573
+ fs.renameSync(entry.backup, entry.target);
574
+ changed = true;
575
+ }
576
+ cleanupExpected(entry.temp, entry.digest);
577
+ if (entry.existed) cleanupExpected(entry.backup, entry.prior_digest);
578
+ }
579
+ discardInterruptedJournalUpdate(
580
+ journalName(value.transaction_id),
581
+ value.transaction_id,
582
+ );
583
+ cleanup(journalName(value.transaction_id));
584
+ fsyncCurrentDirectory();
585
+ return { rolled_back: changed };
586
+ }
587
+
588
+ function rollback(payload) {
589
+ validateIdentity(payload.identity);
590
+ const transactionId = assertTransactionId(payload.transaction_id);
591
+ const value = readJournal(transactionId);
592
+ if (!value) return { rolled_back: false };
593
+ return rollbackJournal(value);
594
+ }
595
+
596
+ function finalizeJournal(value) {
597
+ assertJournalDirectoryIdentity(value);
598
+ for (const entry of value.entries) {
599
+ const target = readRegular(entry.target);
600
+ if (!target || target.digest !== entry.digest) {
601
+ throw new WorkerError(
602
+ 'PLAN_PUBLISH_CONFLICT',
603
+ `cannot finalize changed plan bytes: ${entry.target}`,
604
+ );
605
+ }
606
+ const backup = readRegular(entry.backup);
607
+ if (backup && (!entry.existed || backup.digest !== entry.prior_digest)) {
608
+ throw new WorkerError(
609
+ 'PLAN_PUBLISH_CONFLICT',
610
+ `cannot finalize changed plan backup: ${entry.backup}`,
611
+ );
612
+ }
613
+ const temp = readRegular(entry.temp);
614
+ if (temp && temp.digest !== entry.digest) {
615
+ throw new WorkerError(
616
+ 'PLAN_PUBLISH_CONFLICT',
617
+ `cannot finalize changed staged bytes: ${entry.temp}`,
618
+ );
619
+ }
620
+ }
621
+ value.phase = 'committed';
622
+ writeJournal(journalName(value.transaction_id), value);
623
+ for (const entry of value.entries) {
624
+ if (entry.existed) cleanupExpected(entry.backup, entry.prior_digest);
625
+ cleanupExpected(entry.temp, entry.digest);
626
+ }
627
+ discardInterruptedJournalUpdate(
628
+ journalName(value.transaction_id),
629
+ value.transaction_id,
630
+ );
631
+ cleanup(journalName(value.transaction_id));
632
+ fsyncCurrentDirectory();
633
+ return { finalized: true };
634
+ }
635
+
636
+ function commit(payload) {
637
+ validateIdentity(payload.identity);
638
+ const transactionId = assertTransactionId(payload.transaction_id);
639
+ const value = readJournal(transactionId);
640
+ if (!value) return { finalized: false };
641
+ if (!['published', 'committed'].includes(value.phase)) {
642
+ throw new WorkerError(
643
+ 'PLAN_PUBLISH_CONFLICT',
644
+ `plan publication cannot commit from phase ${value.phase}`,
645
+ );
646
+ }
647
+ return finalizeJournal(value);
648
+ }
649
+
650
+ function scanPublicationEntries() {
651
+ const journals = [];
652
+ const issues = [];
653
+ const regularTransactions = new Map();
654
+ for (const entry of fs.readdirSync('.', { withFileTypes: true })) {
655
+ const match = entry.name.match(PUBLICATION_ENTRY_PATTERN);
656
+ if (!match) continue;
657
+ const stat = lstat(entry.name);
658
+ if (!stat || !stat.isFile() || stat.isSymbolicLink()) {
659
+ issues.push({
660
+ code: 'PLAN_ARTIFACT_PATH_UNSAFE',
661
+ journal: entry.name,
662
+ message: `reserved plan publication entry must be a regular file: ${entry.name}`,
663
+ });
664
+ continue;
665
+ }
666
+ const transactionId = match[1];
667
+ if (!TRANSACTION_PATTERN.test(transactionId)) {
668
+ issues.push({
669
+ code: 'PLAN_JOURNAL_INVALID',
670
+ journal: entry.name,
671
+ message: `reserved plan publication entry has an invalid transaction id: ${entry.name}`,
672
+ });
673
+ continue;
674
+ }
675
+ if (!regularTransactions.has(transactionId)) regularTransactions.set(transactionId, []);
676
+ regularTransactions.get(transactionId).push(entry.name);
677
+ if (JOURNAL_PATTERN.test(entry.name)) {
678
+ journals.push({
679
+ name: entry.name,
680
+ mtimeMs: stat.mtimeMs,
681
+ transaction_id: transactionId,
682
+ });
683
+ }
684
+ }
685
+ const journalIds = new Set(journals.map((item) => item.transaction_id));
686
+ for (const [transactionId, names] of regularTransactions) {
687
+ if (journalIds.has(transactionId)) continue;
688
+ for (const name of names) {
689
+ issues.push({
690
+ code: 'PLAN_JOURNAL_INVALID',
691
+ journal: name,
692
+ message: `plan publication sidecar has no journal: ${name}`,
693
+ });
694
+ }
695
+ }
696
+ journals.sort((left, right) => right.mtimeMs - left.mtimeMs);
697
+ return { journals, issues };
698
+ }
699
+
700
+ function inspect(payload) {
701
+ validateIdentity(payload.identity);
702
+ const transactions = [];
703
+ const scanned = scanPublicationEntries();
704
+ const issues = [...scanned.issues];
705
+ for (const candidate of scanned.journals) {
706
+ try {
707
+ const value = readJournal(candidate.transaction_id);
708
+ transactions.push({
709
+ transaction_id: value.transaction_id,
710
+ phase: value.phase,
711
+ created_at: value.created_at || null,
712
+ });
713
+ } catch (error) {
714
+ issues.push({
715
+ code: error.code || 'PLAN_JOURNAL_INVALID',
716
+ journal: candidate.name,
717
+ message: error.message,
718
+ });
719
+ }
720
+ }
721
+ return { pending: transactions.length + issues.length, transactions, issues };
722
+ }
723
+
724
+ function recover(payload) {
725
+ validateIdentity(payload.identity);
726
+ const registry = payload.registry && typeof payload.registry === 'object'
727
+ && !Array.isArray(payload.registry) ? payload.registry : {};
728
+ let recovered = 0;
729
+ let finalized = 0;
730
+ const scanned = scanPublicationEntries();
731
+ const issues = [...scanned.issues];
732
+ if (issues.length > 0) return { recovered, finalized, issues };
733
+ for (const candidate of scanned.journals) {
734
+ try {
735
+ const value = readJournal(candidate.transaction_id);
736
+ const dbHasNewBytes = value.entries.every((entry) => (
737
+ registry[entry.target]?.owner_type === value.authority.owner_type
738
+ && registry[entry.target]?.owner_id === value.authority.owner_id
739
+ && registry[entry.target]?.kind === entry.kind
740
+ && registry[entry.target]?.path === entry.canonical_path
741
+ && registry[entry.target]?.status === 'current'
742
+ && (registry[entry.target]?.managed === true
743
+ || registry[entry.target]?.managed === 1)
744
+ && registry[entry.target]?.digest === entry.digest
745
+ && registry[entry.target]?.provenance?.writer === 'plan.export'
746
+ && registry[entry.target]?.provenance?.publication_transaction_id
747
+ === value.transaction_id
748
+ && readRegular(entry.target)?.digest === entry.digest
749
+ ));
750
+ if (dbHasNewBytes) {
751
+ finalizeJournal(value);
752
+ finalized += 1;
753
+ } else {
754
+ rollbackJournal(value);
755
+ recovered += 1;
756
+ }
757
+ } catch (error) {
758
+ issues.push({
759
+ code: error.code || 'PLAN_RECOVERY_FAILED',
760
+ journal: candidate.name,
761
+ message: error.message,
762
+ details: error.details,
763
+ });
764
+ }
765
+ }
766
+ return { recovered, finalized, issues };
767
+ }
768
+
769
+ function read(payload) {
770
+ validateIdentity(payload.identity);
771
+ if (payload.target !== 'plan.json') {
772
+ throw new WorkerError('PLAN_ARTIFACT_PATH_UNSAFE', 'reader target is not allowlisted');
773
+ }
774
+ const value = readRegular('plan.json');
775
+ return value
776
+ ? { exists: true, digest: value.digest, content: value.bytes.toString('base64') }
777
+ : { exists: false, digest: null, content: null };
778
+ }
779
+
780
+ function execute(action, payload) {
781
+ if (!ACTIONS.has(action)) {
782
+ throw new WorkerError('PLAN_WORKER_PROTOCOL_INVALID', `unsupported worker action: ${action}`);
783
+ }
784
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
785
+ throw new WorkerError('PLAN_WORKER_PROTOCOL_INVALID', 'worker payload must be an object');
786
+ }
787
+ return {
788
+ prepare,
789
+ publish,
790
+ rollback,
791
+ commit,
792
+ inspect,
793
+ recover,
794
+ read,
795
+ }[action](payload);
796
+ }
797
+
798
+ function main() {
799
+ const action = process.argv[2];
800
+ let payload;
801
+ try {
802
+ const input = fs.readFileSync(0, 'utf8');
803
+ if (Buffer.byteLength(input) > 40 * 1024 * 1024) {
804
+ throw new WorkerError('PLAN_WORKER_PROTOCOL_INVALID', 'worker payload is too large');
805
+ }
806
+ payload = JSON.parse(input);
807
+ const result = execute(action, payload);
808
+ process.stdout.write(`${JSON.stringify({ ok: true, result })}\n`);
809
+ } catch (error) {
810
+ process.stdout.write(`${JSON.stringify({
811
+ ok: false,
812
+ error: {
813
+ code: error.code || 'PLAN_WORKER_FAILED',
814
+ message: error.message,
815
+ details: error.details,
816
+ },
817
+ })}\n`);
818
+ process.exitCode = 1;
819
+ }
820
+ }
821
+
822
+ if (require.main === module) main();
823
+
824
+ module.exports = {
825
+ ACTIONS,
826
+ KINDS,
827
+ WorkerError,
828
+ execute,
829
+ identityOfCurrentDirectory,
830
+ };