ultra-builder-pro-cli 0.25.1 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (241) hide show
  1. package/.ultra-template/contexts/TEMPLATE.md +87 -0
  2. package/.ultra-template/decisions/.gitkeep +1 -0
  3. package/.ultra-template/evidence/.gitkeep +1 -0
  4. package/.ultra-template/north-star.md +46 -0
  5. package/.ultra-template/research/.gitkeep +1 -0
  6. package/.ultra-template/specs/discovery.md +2 -2
  7. package/.ultra-template/tasks.json +3 -0
  8. package/.ultra-template/test-report.json +27 -0
  9. package/CHANGELOG.md +40 -0
  10. package/README.md +217 -579
  11. package/adapters/_shared/delegate-profiles/kimi-read-only.md +15 -0
  12. package/adapters/_shared/delegate-profiles/kimi-write.md +17 -0
  13. package/adapters/_shared/file-ops.cjs +76 -2
  14. package/adapters/_shared/host-profile.cjs +97 -0
  15. package/adapters/_shared/plugin-core.cjs +204 -0
  16. package/adapters/_shared/runtime-assets.cjs +31 -96
  17. package/adapters/claude.js +92 -291
  18. package/adapters/codex.js +309 -842
  19. package/adapters/grok.js +143 -1469
  20. package/adapters/kimi.js +124 -1053
  21. package/adapters/opencode.js +230 -742
  22. package/bin/delegate-worker.cjs +323 -0
  23. package/bin/delegate.cjs +456 -0
  24. package/bin/install.js +38 -11
  25. package/docs/ARCHITECTURE.md +122 -216
  26. package/docs/ARTIFACT-AUTHORITY.md +90 -268
  27. package/docs/DECISIONS.md +75 -87
  28. package/docs/PHILOSOPHY.md +177 -0
  29. package/docs/PLUGIN-ISOLATION-CONTRACT.md +62 -39
  30. package/docs/RUNTIME-COMPAT-MATRIX.md +99 -156
  31. package/docs/SKILL-AUTHORING.md +94 -73
  32. package/docs/WORKFLOW-LIFECYCLE.md +93 -189
  33. package/hooks/README.md +17 -37
  34. package/hooks/_common.py +113 -0
  35. package/hooks/adapters/codex.py +9 -16
  36. package/hooks/adapters/grok.py +5 -5
  37. package/hooks/adapters/kimi.py +8 -14
  38. package/hooks/block_dangerous_commands.py +95 -0
  39. package/hooks/compact_context.py +65 -0
  40. package/hooks/mid_workflow_recall.py +25 -0
  41. package/hooks/post_edit_guard.py +105 -0
  42. package/hooks/session_context.py +30 -0
  43. package/package.json +17 -52
  44. package/skills/ultra-change/SKILL.md +97 -50
  45. package/skills/ultra-change/references/change-contract.md +40 -1
  46. package/skills/ultra-delegate/SKILL.md +82 -0
  47. package/skills/ultra-delegate/references/delegation-contract.md +51 -0
  48. package/skills/ultra-delegate/scripts/delegate_wait.py +86 -0
  49. package/skills/ultra-deliver/SKILL.md +61 -42
  50. package/skills/ultra-deliver/references/baseline-reconciliation.md +39 -20
  51. package/skills/ultra-dev/SKILL.md +96 -62
  52. package/skills/ultra-dev/references/debugging.md +22 -0
  53. package/skills/ultra-domain-modeling/SKILL.md +79 -0
  54. package/skills/ultra-grilling/SKILL.md +79 -0
  55. package/skills/ultra-init/SKILL.md +94 -37
  56. package/skills/ultra-init/references/brownfield-adoption.md +33 -83
  57. package/skills/ultra-init/scripts/init_project.cjs +84 -0
  58. package/skills/ultra-plan/SKILL.md +88 -68
  59. package/skills/ultra-research/SKILL.md +62 -48
  60. package/skills/ultra-research/references/00-problem-validation.md +5 -5
  61. package/skills/ultra-research/references/01-opportunity-discovery.md +3 -3
  62. package/skills/ultra-research/references/02-market-assessment.md +5 -4
  63. package/skills/ultra-research/references/03-competitive-landscape.md +3 -3
  64. package/skills/ultra-research/references/04-product-strategy.md +3 -3
  65. package/skills/ultra-research/references/05-assumptions-validation.md +5 -5
  66. package/skills/ultra-research/references/10-user-personas.md +3 -2
  67. package/skills/ultra-research/references/11-user-scenarios.md +3 -3
  68. package/skills/ultra-research/references/20-user-stories.md +4 -3
  69. package/skills/ultra-research/references/21-features-scope.md +3 -2
  70. package/skills/ultra-research/references/22-success-metrics.md +3 -3
  71. package/skills/ultra-research/references/30-architecture-context.md +3 -3
  72. package/skills/ultra-research/references/31-solution-strategy.md +3 -3
  73. package/skills/ultra-research/references/32-building-blocks.md +3 -3
  74. package/skills/ultra-research/references/40-deployment.md +3 -3
  75. package/skills/ultra-research/references/41-quality-risks.md +3 -3
  76. package/skills/ultra-research/references/99-synthesis.md +7 -7
  77. package/skills/ultra-review/SKILL.md +59 -32
  78. package/skills/ultra-review/references/code.md +17 -0
  79. package/skills/ultra-review/references/comments.md +12 -0
  80. package/skills/ultra-review/references/design.md +12 -0
  81. package/skills/ultra-review/references/errors.md +13 -0
  82. package/skills/ultra-review/references/spec.md +13 -0
  83. package/skills/ultra-review/references/tests.md +12 -0
  84. package/skills/ultra-review/references/worker-packet.md +40 -0
  85. package/skills/ultra-review/scripts/review_wait.py +26 -15
  86. package/skills/ultra-status/SKILL.md +61 -36
  87. package/skills/ultra-tdd/SKILL.md +81 -0
  88. package/skills/ultra-tdd/references/templates/README.md +20 -0
  89. package/skills/ultra-tdd/references/templates/feature-flag-default-audit.sh +79 -0
  90. package/skills/ultra-tdd/references/templates/persistence-real.ts +78 -0
  91. package/skills/ultra-tdd/references/templates/testcontainer-postgres.py +78 -0
  92. package/skills/ultra-tdd/references/templates/testcontainer-postgres.ts +73 -0
  93. package/skills/ultra-tdd/references/templates/vertical-slice.ts +66 -0
  94. package/skills/ultra-tdd/references/test-execution.md +18 -0
  95. package/skills/ultra-test/SKILL.md +70 -30
  96. package/skills/ultra-test/references/export-syntax.md +18 -0
  97. package/skills/ultra-test/scripts/worktree_digest.cjs +54 -0
  98. package/skills/ultra-think/SKILL.md +49 -27
  99. package/skills/ultra-think/references/autonomy-boundary.md +48 -0
  100. package/skills/ultra-think/references/interaction-boundary.md +18 -33
  101. package/.ultra-template/docs/research/README.md +0 -55
  102. package/.ultra-template/reports/templates/delivery-report.json +0 -17
  103. package/.ultra-template/reports/templates/test-report.json +0 -18
  104. package/.ultra-template/tasks/tasks.json +0 -15
  105. package/.ultra-template/templates/task-context.md +0 -19
  106. package/adapters/_shared/codex-assets.cjs +0 -725
  107. package/adapters/_shared/codex-ultra-tools-entry.cjs +0 -11
  108. package/adapters/_shared/interaction-contract.cjs +0 -129
  109. package/adapters/_shared/path-rewrite.cjs +0 -79
  110. package/adapters/_shared/runtime-native.cjs +0 -132
  111. package/adapters/_shared/settings-merge.cjs +0 -76
  112. package/agents/code-reviewer.md +0 -42
  113. package/agents/debugger.md +0 -40
  114. package/agents/review-code.md +0 -49
  115. package/agents/review-comments.md +0 -38
  116. package/agents/review-coordinator.md +0 -56
  117. package/agents/review-design.md +0 -40
  118. package/agents/review-errors.md +0 -43
  119. package/agents/review-spec.md +0 -39
  120. package/agents/review-tests.md +0 -40
  121. package/agents/tdd-runner.md +0 -38
  122. package/bin/orchestrator.js +0 -383
  123. package/commands/ultra-change.md +0 -10
  124. package/commands/ultra-deliver.md +0 -10
  125. package/commands/ultra-dev.md +0 -10
  126. package/commands/ultra-doctor.md +0 -10
  127. package/commands/ultra-init.md +0 -10
  128. package/commands/ultra-plan.md +0 -10
  129. package/commands/ultra-research.md +0 -10
  130. package/commands/ultra-review.md +0 -10
  131. package/commands/ultra-status.md +0 -10
  132. package/commands/ultra-test.md +0 -10
  133. package/commands/ultra-think.md +0 -10
  134. package/docs/AGENT-CONTEXT.md +0 -191
  135. package/docs/COMMIT-HASH-BACKFILL.md +0 -51
  136. package/docs/LEGACY-CLI-CROSSWALK.md +0 -175
  137. package/docs/ROADMAP.md +0 -101
  138. package/docs/STATE-DB-ACCESS-POLICY.md +0 -161
  139. package/hooks/active_task_context.py +0 -152
  140. package/hooks/context_envelope.py +0 -100
  141. package/hooks/health_check.py +0 -196
  142. package/hooks/pre_stop_check.py +0 -66
  143. package/hooks/runtime_paths.py +0 -396
  144. package/hooks/subagent_tracker.py +0 -88
  145. package/hooks/workflow_checkpoint.py +0 -76
  146. package/hooks/workflow_context.py +0 -48
  147. package/hooks/workflow_resume.py +0 -84
  148. package/mcp-server/hook-context.cjs +0 -38
  149. package/mcp-server/hook-event.cjs +0 -34
  150. package/mcp-server/lib/archive-journal.cjs +0 -1119
  151. package/mcp-server/lib/archive-mutation-worker.py +0 -365
  152. package/mcp-server/lib/artifact-registry.cjs +0 -1232
  153. package/mcp-server/lib/baseline-workflow.cjs +0 -1193
  154. package/mcp-server/lib/canonical-json.cjs +0 -19
  155. package/mcp-server/lib/change-authority.cjs +0 -26
  156. package/mcp-server/lib/change-packet.cjs +0 -790
  157. package/mcp-server/lib/change-workflow.cjs +0 -65
  158. package/mcp-server/lib/context-envelope.cjs +0 -581
  159. package/mcp-server/lib/context-paths.cjs +0 -142
  160. package/mcp-server/lib/decision-records.cjs +0 -423
  161. package/mcp-server/lib/delivery-transaction.cjs +0 -471
  162. package/mcp-server/lib/doctor-backup-worker.cjs +0 -328
  163. package/mcp-server/lib/doctor.cjs +0 -627
  164. package/mcp-server/lib/git-bootstrap.cjs +0 -651
  165. package/mcp-server/lib/init-project.cjs +0 -1021
  166. package/mcp-server/lib/kernel-change-workflow.cjs +0 -2029
  167. package/mcp-server/lib/legacy-change-workflow.cjs +0 -3032
  168. package/mcp-server/lib/managed-file-write.cjs +0 -172
  169. package/mcp-server/lib/plan-checkpoint.cjs +0 -177
  170. package/mcp-server/lib/plan-publication-worker.cjs +0 -830
  171. package/mcp-server/lib/plan-store.cjs +0 -794
  172. package/mcp-server/lib/prd-parser.cjs +0 -83
  173. package/mcp-server/lib/pricing.cjs +0 -44
  174. package/mcp-server/lib/project-context.cjs +0 -178
  175. package/mcp-server/lib/projector.cjs +0 -386
  176. package/mcp-server/lib/provider-refs.cjs +0 -42
  177. package/mcp-server/lib/runtime-paths.cjs +0 -1714
  178. package/mcp-server/lib/runtime-state.cjs +0 -222
  179. package/mcp-server/lib/safe-project-file.cjs +0 -385
  180. package/mcp-server/lib/stage-checkpoints.cjs +0 -463
  181. package/mcp-server/lib/state-authority.cjs +0 -95
  182. package/mcp-server/lib/state-db.cjs +0 -1580
  183. package/mcp-server/lib/state-ops.cjs +0 -1428
  184. package/mcp-server/lib/task-contract.cjs +0 -404
  185. package/mcp-server/lib/task-expander.cjs +0 -105
  186. package/mcp-server/lib/task-ledger.cjs +0 -1964
  187. package/mcp-server/lib/telemetry.cjs +0 -85
  188. package/mcp-server/lib/topo.cjs +0 -131
  189. package/mcp-server/lib/ultra-facade.cjs +0 -2684
  190. package/mcp-server/lib/worker-packet.cjs +0 -358
  191. package/mcp-server/server.cjs +0 -437
  192. package/orchestrator/auto-merge.cjs +0 -128
  193. package/orchestrator/daemon.cjs +0 -264
  194. package/orchestrator/dispatch-rules.cjs +0 -78
  195. package/orchestrator/parallel-orchestrator.cjs +0 -903
  196. package/orchestrator/planner/plan-builder.cjs +0 -125
  197. package/orchestrator/recovery.cjs +0 -188
  198. package/orchestrator/session-close-journal-worker.cjs +0 -5
  199. package/orchestrator/session-close-journal.cjs +0 -1014
  200. package/orchestrator/session-runner.cjs +0 -1153
  201. package/orchestrator/worktree-manager.cjs +0 -282
  202. package/settings.json +0 -7
  203. package/skills/cc-collab/SKILL.md +0 -42
  204. package/skills/code-review-expert/SKILL.md +0 -43
  205. package/skills/code-review-expert/references/correctness-reliability.md +0 -30
  206. package/skills/code-review-expert/references/design-boundaries.md +0 -26
  207. package/skills/code-review-expert/references/removal-plan.md +0 -24
  208. package/skills/codex-collab/SKILL.md +0 -49
  209. package/skills/codex-collab/evals/evals.json +0 -35
  210. package/skills/integration-rules/SKILL.md +0 -32
  211. package/skills/security-rules/SKILL.md +0 -38
  212. package/skills/testing-rules/SKILL.md +0 -32
  213. package/skills/ultra-doctor/SKILL.md +0 -41
  214. package/skills/ultra-plan/references/semantic-preflight.md +0 -20
  215. package/skills/ultra-verify/SKILL.md +0 -46
  216. package/skills/ultra-verify/evals/evals.json +0 -46
  217. package/skills/ultra-verify/references/cross-verify-modes.md +0 -28
  218. package/skills/ultra-verify/references/evidence-status.md +0 -21
  219. package/skills/ultra-verify/scripts/verify_wait.py +0 -94
  220. package/spec/cli-protocol.md +0 -102
  221. package/spec/mcp-tools.yaml +0 -312
  222. package/spec/schemas/baseline-reconciliation.v1.schema.json +0 -73
  223. package/spec/schemas/change-delta.v1.schema.json +0 -153
  224. package/spec/schemas/command-manifest.schema.json +0 -29
  225. package/spec/schemas/context-file.v4.5.schema.json +0 -54
  226. package/spec/schemas/delivery-report.v1.schema.json +0 -66
  227. package/spec/schemas/documentation-reconciliation.v1.schema.json +0 -106
  228. package/spec/schemas/mcp-tools.schema.json +0 -136
  229. package/spec/schemas/skill-manifest.schema.json +0 -24
  230. package/spec/schemas/state-db.sql +0 -641
  231. package/spec/schemas/task-ledger.v2.schema.json +0 -296
  232. package/spec/schemas/tasks.v4.5.schema.json +0 -96
  233. package/spec/schemas/test-report.v1.schema.json +0 -225
  234. package/ultra-tools/cli.cjs +0 -129
  235. package/ultra-tools/commands/db.cjs +0 -226
  236. package/ultra-tools/commands/legacy-memory.cjs +0 -159
  237. package/ultra-tools/commands/migrate.cjs +0 -1386
  238. package/ultra-tools/commands/session.cjs +0 -213
  239. package/ultra-tools/commands/status.cjs +0 -559
  240. package/ultra-tools/commands/system.cjs +0 -498
  241. package/ultra-tools/commands/task.cjs +0 -105
@@ -1,830 +0,0 @@
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
- };