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
@@ -0,0 +1,323 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const crypto = require('node:crypto');
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+ const { execFileSync, spawn } = require('node:child_process');
8
+
9
+ const RESULT_SCHEMA = 'ultra-delegation-result-v1';
10
+ const MODEL_FIELDS = new Set([
11
+ '$schema', 'status', 'summary', 'changed_files', 'checks', 'evidence',
12
+ 'questions', 'residual_risks',
13
+ ]);
14
+
15
+ function writeAtomic(file, payload) {
16
+ const temporary = `${file}.tmp-${process.pid}`;
17
+ fs.writeFileSync(temporary, `${JSON.stringify(payload, null, 2)}\n`, { mode: 0o600 });
18
+ fs.renameSync(temporary, file);
19
+ }
20
+
21
+ function sha256(file) {
22
+ try {
23
+ return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
28
+
29
+ function git(cwd, args, { binary = false } = {}) {
30
+ return execFileSync('git', args, {
31
+ cwd,
32
+ encoding: binary ? 'buffer' : 'utf8',
33
+ stdio: ['ignore', 'pipe', 'pipe'],
34
+ });
35
+ }
36
+
37
+ function zeroSeparated(buffer) {
38
+ return buffer.toString('utf8').split('\0').filter(Boolean);
39
+ }
40
+
41
+ function normalizeChangedPath(value) {
42
+ if (typeof value !== 'string' || !value || value.includes('\\') || path.posix.isAbsolute(value)) {
43
+ return null;
44
+ }
45
+ const normalized = path.posix.normalize(value);
46
+ if (normalized !== value || normalized === '.' || normalized === '..' || normalized.startsWith('../')) {
47
+ return null;
48
+ }
49
+ return normalized;
50
+ }
51
+
52
+ function changedFiles(spec) {
53
+ const tracked = zeroSeparated(git(spec.cwd, [
54
+ 'diff', '--name-only', '-z', spec.base_head, '--',
55
+ ], { binary: true }));
56
+ const untracked = zeroSeparated(git(spec.cwd, [
57
+ 'ls-files', '--others', '--exclude-standard', '-z',
58
+ ], { binary: true }));
59
+ return [...new Set([...tracked, ...untracked]
60
+ .map((item) => item.split(path.sep).join('/')))]
61
+ .sort();
62
+ }
63
+
64
+ function parseJson(value) {
65
+ if (typeof value !== 'string') return null;
66
+ let text = value.trim();
67
+ const fence = text.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);
68
+ if (fence) text = fence[1];
69
+ try { return JSON.parse(text); } catch { return null; }
70
+ }
71
+
72
+ function collectResultCandidates(value, candidates, depth = 0) {
73
+ if (depth > 12 || value === null || value === undefined) return;
74
+ if (typeof value === 'string') {
75
+ const parsed = parseJson(value);
76
+ if (parsed !== null) collectResultCandidates(parsed, candidates, depth + 1);
77
+ return;
78
+ }
79
+ if (Array.isArray(value)) {
80
+ for (const item of value) collectResultCandidates(item, candidates, depth + 1);
81
+ return;
82
+ }
83
+ if (typeof value !== 'object') return;
84
+ if (value.$schema === RESULT_SCHEMA) candidates.push(value);
85
+ for (const nested of Object.values(value)) {
86
+ collectResultCandidates(nested, candidates, depth + 1);
87
+ }
88
+ }
89
+
90
+ function extractModelResult(spec) {
91
+ const candidates = [];
92
+ for (const file of [spec.host_output, spec.stdout]) {
93
+ if (!file || !fs.existsSync(file) || fs.statSync(file).size === 0) continue;
94
+ const text = fs.readFileSync(file, 'utf8');
95
+ const full = parseJson(text);
96
+ if (full !== null) collectResultCandidates(full, candidates);
97
+ for (const line of text.split('\n')) {
98
+ const parsed = parseJson(line);
99
+ if (parsed !== null) collectResultCandidates(parsed, candidates);
100
+ }
101
+ }
102
+ return candidates.at(-1) || null;
103
+ }
104
+
105
+ function validateModelResult(payload) {
106
+ if (!payload || Array.isArray(payload) || typeof payload !== 'object') {
107
+ return 'result must be a JSON object';
108
+ }
109
+ const extra = Object.keys(payload).filter((key) => !MODEL_FIELDS.has(key));
110
+ const missing = [...MODEL_FIELDS].filter((key) => !(key in payload));
111
+ if (extra.length || missing.length) {
112
+ return `result fields must be exact; missing=${missing.join(',') || 'none'} extra=${extra.join(',') || 'none'}`;
113
+ }
114
+ if (payload.$schema !== RESULT_SCHEMA) return `$schema must be ${RESULT_SCHEMA}`;
115
+ if (!['finished', 'blocked', 'failed'].includes(payload.status)) {
116
+ return 'status must be finished, blocked, or failed';
117
+ }
118
+ if (typeof payload.summary !== 'string' || !payload.summary.trim()) {
119
+ return 'summary must be a non-empty string';
120
+ }
121
+ if (!Array.isArray(payload.changed_files)) return 'changed_files must be an array';
122
+ const normalized = payload.changed_files.map(normalizeChangedPath);
123
+ if (normalized.some((item) => item === null) || new Set(normalized).size !== normalized.length) {
124
+ return 'changed_files must contain unique normalized repository-relative paths';
125
+ }
126
+ if (!Array.isArray(payload.checks)) return 'checks must be an array';
127
+ for (const check of payload.checks) {
128
+ if (!check || Array.isArray(check) || typeof check !== 'object') return 'checks items must be objects';
129
+ const keys = Object.keys(check);
130
+ if (!keys.every((key) => ['command', 'status', 'output_ref'].includes(key))) {
131
+ return 'checks items contain an unknown field';
132
+ }
133
+ if (typeof check.command !== 'string' || !check.command.trim()) return 'checks.command must be non-empty';
134
+ if (!['passed', 'failed', 'not_run'].includes(check.status)) return 'checks.status is invalid';
135
+ if (check.output_ref !== undefined && (typeof check.output_ref !== 'string' || !check.output_ref.trim())) {
136
+ return 'checks.output_ref must be a non-empty string when present';
137
+ }
138
+ }
139
+ for (const field of ['evidence', 'questions', 'residual_risks']) {
140
+ if (!Array.isArray(payload[field]) || !payload[field].every(
141
+ (item) => typeof item === 'string' && item.trim(),
142
+ )) return `${field} must be an array of non-empty strings`;
143
+ }
144
+ if (payload.status === 'blocked' && payload.questions.length === 0) {
145
+ return 'blocked results require at least one question';
146
+ }
147
+ payload.changed_files = [...normalized].sort();
148
+ return null;
149
+ }
150
+
151
+ function authorized(spec, file) {
152
+ return spec.writable_roots.some((root) => (
153
+ root === '.' || file === root || file.startsWith(`${root}/`)
154
+ ));
155
+ }
156
+
157
+ function finalHead(spec) {
158
+ try { return git(spec.cwd, ['rev-parse', 'HEAD']).trim(); } catch { return null; }
159
+ }
160
+
161
+ function mechanical(spec, exitCode, signal) {
162
+ return {
163
+ delegation_id: spec.delegation_id,
164
+ host: spec.host,
165
+ instruction_digest: spec.instruction_digest,
166
+ permission_digest: spec.permission_digest,
167
+ output_schema_digest: spec.output_schema_digest,
168
+ read_only: spec.read_only,
169
+ base_head: spec.base_head,
170
+ final_head: finalHead(spec),
171
+ started_at: spec.started_at,
172
+ finished_at: new Date().toISOString(),
173
+ exit_code: Number.isInteger(exitCode) ? exitCode : null,
174
+ signal: signal || null,
175
+ };
176
+ }
177
+
178
+ function failure(spec, type, summary, exitCode = null, signal = null, files = []) {
179
+ return {
180
+ $schema: RESULT_SCHEMA,
181
+ status: 'failed',
182
+ summary,
183
+ changed_files: files,
184
+ checks: [],
185
+ evidence: [],
186
+ questions: [],
187
+ residual_risks: [],
188
+ failure_type: type,
189
+ ...mechanical(spec, exitCode, signal),
190
+ };
191
+ }
192
+
193
+ function terminate(child, signal = 'SIGTERM') {
194
+ if (!child || child.exitCode !== null || child.signalCode !== null) return;
195
+ try {
196
+ if (process.platform === 'win32') child.kill(signal);
197
+ else process.kill(-child.pid, signal);
198
+ } catch {}
199
+ }
200
+
201
+ function runChild(spec) {
202
+ return new Promise((resolve) => {
203
+ const stdoutFd = fs.openSync(spec.stdout, 'a');
204
+ const stderrFd = fs.openSync(spec.stderr, 'a');
205
+ let termination = null;
206
+ let spawnError = null;
207
+ let closed = false;
208
+ let hardKill = null;
209
+ const child = spawn(spec.command, spec.args, {
210
+ cwd: spec.cwd,
211
+ env: { ...process.env, ...spec.env },
212
+ detached: process.platform !== 'win32',
213
+ stdio: ['ignore', stdoutFd, stderrFd],
214
+ });
215
+ const finish = (code, signal) => {
216
+ if (closed) return;
217
+ closed = true;
218
+ clearInterval(cancelPoll);
219
+ clearTimeout(timeout);
220
+ if (hardKill) clearTimeout(hardKill);
221
+ fs.closeSync(stdoutFd);
222
+ fs.closeSync(stderrFd);
223
+ resolve({ code, signal, termination, spawnError });
224
+ };
225
+ child.on('error', (error) => { spawnError = error; });
226
+ child.on('close', finish);
227
+ const requestTermination = (reason) => {
228
+ if (termination) return;
229
+ termination = reason;
230
+ terminate(child);
231
+ hardKill = setTimeout(() => terminate(child, 'SIGKILL'), 1500);
232
+ hardKill.unref();
233
+ };
234
+ const cancelPoll = setInterval(() => {
235
+ if (fs.existsSync(spec.cancel)) requestTermination('cancelled');
236
+ }, 100);
237
+ const timeout = setTimeout(() => requestTermination('timeout'), spec.timeout_ms);
238
+ cancelPoll.unref();
239
+ timeout.unref();
240
+ });
241
+ }
242
+
243
+ async function main() {
244
+ const specFile = process.argv[2];
245
+ const expectedSpecDigest = process.argv[3];
246
+ if (!specFile || !/^[0-9a-f]{64}$/.test(expectedSpecDigest || '')) {
247
+ throw new Error('worker requires a spec path and digest');
248
+ }
249
+ if (sha256(specFile) !== expectedSpecDigest) throw new Error('worker spec digest mismatch before launch');
250
+ const spec = JSON.parse(fs.readFileSync(specFile, 'utf8'));
251
+ let terminal;
252
+ try {
253
+ if (sha256(spec.instruction) !== spec.instruction_digest) {
254
+ terminal = failure(spec, 'instruction_changed', 'Instruction digest changed before delegation started.');
255
+ } else if (sha256(spec.permission) !== spec.permission_digest) {
256
+ terminal = failure(spec, 'permission_changed', 'Permission digest changed before delegation started.');
257
+ } else if (sha256(spec.output_schema) !== spec.output_schema_digest) {
258
+ terminal = failure(spec, 'output_schema_changed', 'Output schema digest changed before delegation started.');
259
+ } else if (fs.existsSync(spec.cancel)) {
260
+ terminal = failure(spec, 'cancelled', 'Delegation was cancelled before the host process started.');
261
+ } else {
262
+ const processResult = await runChild(spec);
263
+ let files = [];
264
+ try { files = changedFiles(spec); } catch {}
265
+ if (processResult.termination === 'cancelled') {
266
+ terminal = failure(spec, 'cancelled', 'Delegation cancelled by request.', processResult.code, processResult.signal, files);
267
+ } else if (processResult.termination === 'timeout') {
268
+ terminal = failure(spec, 'timeout', 'Delegation timed out and the host process was terminated.', processResult.code, processResult.signal, files);
269
+ } else if (sha256(specFile) !== expectedSpecDigest) {
270
+ terminal = failure(spec, 'worker_spec_changed', 'Worker specification changed during delegation.', processResult.code, processResult.signal, files);
271
+ } else if (sha256(spec.instruction) !== spec.instruction_digest) {
272
+ terminal = failure(spec, 'instruction_changed', 'Instruction digest changed during delegation.', processResult.code, processResult.signal, files);
273
+ } else if (sha256(spec.permission) !== spec.permission_digest) {
274
+ terminal = failure(spec, 'permission_changed', 'Permission digest changed during delegation.', processResult.code, processResult.signal, files);
275
+ } else if (sha256(spec.output_schema) !== spec.output_schema_digest) {
276
+ terminal = failure(spec, 'output_schema_changed', 'Output schema digest changed during delegation.', processResult.code, processResult.signal, files);
277
+ } else if (processResult.spawnError) {
278
+ terminal = failure(spec, 'spawn_error', `Host process failed to start: ${processResult.spawnError.message}`, null, null, files);
279
+ } else if (processResult.code !== 0) {
280
+ terminal = failure(spec, 'process_exit', `Host process exited with code ${processResult.code}.`, processResult.code, processResult.signal, files);
281
+ } else {
282
+ const payload = extractModelResult(spec);
283
+ if (!payload) {
284
+ terminal = failure(
285
+ spec, 'missing_result',
286
+ 'Host process exited without a structured Ultra delegation result.',
287
+ processResult.code, processResult.signal, files,
288
+ );
289
+ } else {
290
+ const validation = validateModelResult(payload);
291
+ if (validation) {
292
+ terminal = failure(spec, 'invalid_result', validation, processResult.code, processResult.signal, files);
293
+ } else {
294
+ const unauthorized = files.filter((file) => !authorized(spec, file));
295
+ if (unauthorized.length) {
296
+ terminal = failure(
297
+ spec, 'unauthorized_write',
298
+ `Actual Git diff escaped writable_roots: ${unauthorized.join(', ')}`,
299
+ processResult.code, processResult.signal, files,
300
+ );
301
+ } else if (JSON.stringify(payload.changed_files) !== JSON.stringify(files)) {
302
+ terminal = failure(
303
+ spec, 'changed_files_mismatch',
304
+ `Declared changed_files do not match actual Git diff: ${files.join(', ') || 'none'}`,
305
+ processResult.code, processResult.signal, files,
306
+ );
307
+ } else {
308
+ terminal = { ...payload, ...mechanical(spec, processResult.code, processResult.signal) };
309
+ }
310
+ }
311
+ }
312
+ }
313
+ }
314
+ if (!fs.existsSync(spec.result)) writeAtomic(spec.result, terminal);
315
+ } finally {
316
+ try { fs.unlinkSync(spec.lock); } catch (error) { if (error.code !== 'ENOENT') throw error; }
317
+ }
318
+ }
319
+
320
+ main().catch((error) => {
321
+ process.stderr.write(`${error.stack || error.message}\n`);
322
+ process.exitCode = 1;
323
+ });