ultra-builder-pro-cli 0.25.1 → 0.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (243) hide show
  1. package/.ultra-template/changes/abandoned/.gitkeep +0 -0
  2. package/.ultra-template/contexts/TEMPLATE.md +94 -0
  3. package/.ultra-template/decisions/.gitkeep +1 -0
  4. package/.ultra-template/evidence/.gitkeep +1 -0
  5. package/.ultra-template/north-star.md +46 -0
  6. package/.ultra-template/research/.gitkeep +1 -0
  7. package/.ultra-template/specs/discovery.md +2 -2
  8. package/.ultra-template/tasks.json +3 -0
  9. package/.ultra-template/test-report.json +27 -0
  10. package/CHANGELOG.md +107 -1
  11. package/README.md +217 -579
  12. package/adapters/_shared/delegate-profiles/kimi-read-only.md +15 -0
  13. package/adapters/_shared/delegate-profiles/kimi-write.md +17 -0
  14. package/adapters/_shared/file-ops.cjs +76 -2
  15. package/adapters/_shared/host-profile.cjs +97 -0
  16. package/adapters/_shared/plugin-core.cjs +204 -0
  17. package/adapters/_shared/runtime-assets.cjs +31 -96
  18. package/adapters/claude.js +92 -291
  19. package/adapters/codex.js +309 -842
  20. package/adapters/grok.js +143 -1469
  21. package/adapters/kimi.js +124 -1053
  22. package/adapters/opencode.js +230 -742
  23. package/bin/delegate-worker.cjs +328 -0
  24. package/bin/delegate.cjs +463 -0
  25. package/bin/install.js +38 -11
  26. package/docs/ARCHITECTURE.md +125 -216
  27. package/docs/ARTIFACT-AUTHORITY.md +90 -268
  28. package/docs/DECISIONS.md +77 -87
  29. package/docs/PHILOSOPHY.md +208 -0
  30. package/docs/PLUGIN-ISOLATION-CONTRACT.md +65 -39
  31. package/docs/RUNTIME-COMPAT-MATRIX.md +140 -155
  32. package/docs/SKILL-AUTHORING.md +94 -73
  33. package/docs/WORKFLOW-LIFECYCLE.md +97 -189
  34. package/hooks/README.md +19 -37
  35. package/hooks/_common.py +113 -0
  36. package/hooks/adapters/codex.py +9 -16
  37. package/hooks/adapters/grok.py +5 -5
  38. package/hooks/adapters/kimi.py +8 -14
  39. package/hooks/block_dangerous_commands.py +201 -0
  40. package/hooks/compact_context.py +65 -0
  41. package/hooks/mid_workflow_recall.py +25 -0
  42. package/hooks/post_edit_guard.py +105 -0
  43. package/hooks/session_context.py +30 -0
  44. package/package.json +17 -52
  45. package/skills/ultra-change/SKILL.md +115 -50
  46. package/skills/ultra-change/references/change-contract.md +68 -3
  47. package/skills/ultra-delegate/SKILL.md +89 -0
  48. package/skills/ultra-delegate/references/delegation-contract.md +59 -0
  49. package/skills/ultra-delegate/scripts/delegate_wait.py +86 -0
  50. package/skills/ultra-deliver/SKILL.md +98 -42
  51. package/skills/ultra-deliver/references/baseline-reconciliation.md +39 -20
  52. package/skills/ultra-dev/SKILL.md +115 -62
  53. package/skills/ultra-dev/references/debugging.md +22 -0
  54. package/skills/ultra-domain-modeling/SKILL.md +79 -0
  55. package/skills/ultra-grilling/SKILL.md +118 -0
  56. package/skills/ultra-grilling/references/reframing.md +72 -0
  57. package/skills/ultra-init/SKILL.md +102 -37
  58. package/skills/ultra-init/references/brownfield-adoption.md +33 -83
  59. package/skills/ultra-init/scripts/init_project.cjs +84 -0
  60. package/skills/ultra-plan/SKILL.md +101 -68
  61. package/skills/ultra-research/SKILL.md +68 -48
  62. package/skills/ultra-research/references/00-problem-validation.md +5 -5
  63. package/skills/ultra-research/references/01-opportunity-discovery.md +3 -3
  64. package/skills/ultra-research/references/02-market-assessment.md +5 -4
  65. package/skills/ultra-research/references/03-competitive-landscape.md +3 -3
  66. package/skills/ultra-research/references/04-product-strategy.md +3 -3
  67. package/skills/ultra-research/references/05-assumptions-validation.md +5 -5
  68. package/skills/ultra-research/references/10-user-personas.md +3 -2
  69. package/skills/ultra-research/references/11-user-scenarios.md +3 -3
  70. package/skills/ultra-research/references/20-user-stories.md +4 -3
  71. package/skills/ultra-research/references/21-features-scope.md +3 -2
  72. package/skills/ultra-research/references/22-success-metrics.md +3 -3
  73. package/skills/ultra-research/references/30-architecture-context.md +3 -3
  74. package/skills/ultra-research/references/31-solution-strategy.md +3 -3
  75. package/skills/ultra-research/references/32-building-blocks.md +3 -3
  76. package/skills/ultra-research/references/40-deployment.md +3 -3
  77. package/skills/ultra-research/references/41-quality-risks.md +3 -3
  78. package/skills/ultra-research/references/99-synthesis.md +7 -7
  79. package/skills/ultra-review/SKILL.md +84 -32
  80. package/skills/ultra-review/references/code.md +17 -0
  81. package/skills/ultra-review/references/comments.md +12 -0
  82. package/skills/ultra-review/references/design.md +12 -0
  83. package/skills/ultra-review/references/errors.md +13 -0
  84. package/skills/ultra-review/references/spec.md +13 -0
  85. package/skills/ultra-review/references/tests.md +12 -0
  86. package/skills/ultra-review/references/worker-packet.md +40 -0
  87. package/skills/ultra-review/scripts/review_wait.py +26 -15
  88. package/skills/ultra-status/SKILL.md +61 -36
  89. package/skills/ultra-tdd/SKILL.md +81 -0
  90. package/skills/ultra-tdd/references/templates/README.md +20 -0
  91. package/skills/ultra-tdd/references/templates/feature-flag-default-audit.sh +79 -0
  92. package/skills/ultra-tdd/references/templates/persistence-real.ts +78 -0
  93. package/skills/ultra-tdd/references/templates/testcontainer-postgres.py +78 -0
  94. package/skills/ultra-tdd/references/templates/testcontainer-postgres.ts +73 -0
  95. package/skills/ultra-tdd/references/templates/vertical-slice.ts +66 -0
  96. package/skills/ultra-tdd/references/test-execution.md +18 -0
  97. package/skills/ultra-test/SKILL.md +75 -30
  98. package/skills/ultra-test/references/export-syntax.md +18 -0
  99. package/skills/ultra-test/scripts/worktree_digest.cjs +54 -0
  100. package/skills/ultra-think/SKILL.md +49 -27
  101. package/skills/ultra-think/references/autonomy-boundary.md +48 -0
  102. package/skills/ultra-think/references/interaction-boundary.md +18 -33
  103. package/.ultra-template/docs/research/README.md +0 -55
  104. package/.ultra-template/reports/templates/delivery-report.json +0 -17
  105. package/.ultra-template/reports/templates/test-report.json +0 -18
  106. package/.ultra-template/tasks/tasks.json +0 -15
  107. package/.ultra-template/templates/task-context.md +0 -19
  108. package/adapters/_shared/codex-assets.cjs +0 -725
  109. package/adapters/_shared/codex-ultra-tools-entry.cjs +0 -11
  110. package/adapters/_shared/interaction-contract.cjs +0 -129
  111. package/adapters/_shared/path-rewrite.cjs +0 -79
  112. package/adapters/_shared/runtime-native.cjs +0 -132
  113. package/adapters/_shared/settings-merge.cjs +0 -76
  114. package/agents/code-reviewer.md +0 -42
  115. package/agents/debugger.md +0 -40
  116. package/agents/review-code.md +0 -49
  117. package/agents/review-comments.md +0 -38
  118. package/agents/review-coordinator.md +0 -56
  119. package/agents/review-design.md +0 -40
  120. package/agents/review-errors.md +0 -43
  121. package/agents/review-spec.md +0 -39
  122. package/agents/review-tests.md +0 -40
  123. package/agents/tdd-runner.md +0 -38
  124. package/bin/orchestrator.js +0 -383
  125. package/commands/ultra-change.md +0 -10
  126. package/commands/ultra-deliver.md +0 -10
  127. package/commands/ultra-dev.md +0 -10
  128. package/commands/ultra-doctor.md +0 -10
  129. package/commands/ultra-init.md +0 -10
  130. package/commands/ultra-plan.md +0 -10
  131. package/commands/ultra-research.md +0 -10
  132. package/commands/ultra-review.md +0 -10
  133. package/commands/ultra-status.md +0 -10
  134. package/commands/ultra-test.md +0 -10
  135. package/commands/ultra-think.md +0 -10
  136. package/docs/AGENT-CONTEXT.md +0 -191
  137. package/docs/COMMIT-HASH-BACKFILL.md +0 -51
  138. package/docs/LEGACY-CLI-CROSSWALK.md +0 -175
  139. package/docs/ROADMAP.md +0 -101
  140. package/docs/STATE-DB-ACCESS-POLICY.md +0 -161
  141. package/hooks/active_task_context.py +0 -152
  142. package/hooks/context_envelope.py +0 -100
  143. package/hooks/health_check.py +0 -196
  144. package/hooks/pre_stop_check.py +0 -66
  145. package/hooks/runtime_paths.py +0 -396
  146. package/hooks/subagent_tracker.py +0 -88
  147. package/hooks/workflow_checkpoint.py +0 -76
  148. package/hooks/workflow_context.py +0 -48
  149. package/hooks/workflow_resume.py +0 -84
  150. package/mcp-server/hook-context.cjs +0 -38
  151. package/mcp-server/hook-event.cjs +0 -34
  152. package/mcp-server/lib/archive-journal.cjs +0 -1119
  153. package/mcp-server/lib/archive-mutation-worker.py +0 -365
  154. package/mcp-server/lib/artifact-registry.cjs +0 -1232
  155. package/mcp-server/lib/baseline-workflow.cjs +0 -1193
  156. package/mcp-server/lib/canonical-json.cjs +0 -19
  157. package/mcp-server/lib/change-authority.cjs +0 -26
  158. package/mcp-server/lib/change-packet.cjs +0 -790
  159. package/mcp-server/lib/change-workflow.cjs +0 -65
  160. package/mcp-server/lib/context-envelope.cjs +0 -581
  161. package/mcp-server/lib/context-paths.cjs +0 -142
  162. package/mcp-server/lib/decision-records.cjs +0 -423
  163. package/mcp-server/lib/delivery-transaction.cjs +0 -471
  164. package/mcp-server/lib/doctor-backup-worker.cjs +0 -328
  165. package/mcp-server/lib/doctor.cjs +0 -627
  166. package/mcp-server/lib/git-bootstrap.cjs +0 -651
  167. package/mcp-server/lib/init-project.cjs +0 -1021
  168. package/mcp-server/lib/kernel-change-workflow.cjs +0 -2029
  169. package/mcp-server/lib/legacy-change-workflow.cjs +0 -3032
  170. package/mcp-server/lib/managed-file-write.cjs +0 -172
  171. package/mcp-server/lib/plan-checkpoint.cjs +0 -177
  172. package/mcp-server/lib/plan-publication-worker.cjs +0 -830
  173. package/mcp-server/lib/plan-store.cjs +0 -794
  174. package/mcp-server/lib/prd-parser.cjs +0 -83
  175. package/mcp-server/lib/pricing.cjs +0 -44
  176. package/mcp-server/lib/project-context.cjs +0 -178
  177. package/mcp-server/lib/projector.cjs +0 -386
  178. package/mcp-server/lib/provider-refs.cjs +0 -42
  179. package/mcp-server/lib/runtime-paths.cjs +0 -1714
  180. package/mcp-server/lib/runtime-state.cjs +0 -222
  181. package/mcp-server/lib/safe-project-file.cjs +0 -385
  182. package/mcp-server/lib/stage-checkpoints.cjs +0 -463
  183. package/mcp-server/lib/state-authority.cjs +0 -95
  184. package/mcp-server/lib/state-db.cjs +0 -1580
  185. package/mcp-server/lib/state-ops.cjs +0 -1428
  186. package/mcp-server/lib/task-contract.cjs +0 -404
  187. package/mcp-server/lib/task-expander.cjs +0 -105
  188. package/mcp-server/lib/task-ledger.cjs +0 -1964
  189. package/mcp-server/lib/telemetry.cjs +0 -85
  190. package/mcp-server/lib/topo.cjs +0 -131
  191. package/mcp-server/lib/ultra-facade.cjs +0 -2684
  192. package/mcp-server/lib/worker-packet.cjs +0 -358
  193. package/mcp-server/server.cjs +0 -437
  194. package/orchestrator/auto-merge.cjs +0 -128
  195. package/orchestrator/daemon.cjs +0 -264
  196. package/orchestrator/dispatch-rules.cjs +0 -78
  197. package/orchestrator/parallel-orchestrator.cjs +0 -903
  198. package/orchestrator/planner/plan-builder.cjs +0 -125
  199. package/orchestrator/recovery.cjs +0 -188
  200. package/orchestrator/session-close-journal-worker.cjs +0 -5
  201. package/orchestrator/session-close-journal.cjs +0 -1014
  202. package/orchestrator/session-runner.cjs +0 -1153
  203. package/orchestrator/worktree-manager.cjs +0 -282
  204. package/settings.json +0 -7
  205. package/skills/cc-collab/SKILL.md +0 -42
  206. package/skills/code-review-expert/SKILL.md +0 -43
  207. package/skills/code-review-expert/references/correctness-reliability.md +0 -30
  208. package/skills/code-review-expert/references/design-boundaries.md +0 -26
  209. package/skills/code-review-expert/references/removal-plan.md +0 -24
  210. package/skills/codex-collab/SKILL.md +0 -49
  211. package/skills/codex-collab/evals/evals.json +0 -35
  212. package/skills/integration-rules/SKILL.md +0 -32
  213. package/skills/security-rules/SKILL.md +0 -38
  214. package/skills/testing-rules/SKILL.md +0 -32
  215. package/skills/ultra-doctor/SKILL.md +0 -41
  216. package/skills/ultra-plan/references/semantic-preflight.md +0 -20
  217. package/skills/ultra-verify/SKILL.md +0 -46
  218. package/skills/ultra-verify/evals/evals.json +0 -46
  219. package/skills/ultra-verify/references/cross-verify-modes.md +0 -28
  220. package/skills/ultra-verify/references/evidence-status.md +0 -21
  221. package/skills/ultra-verify/scripts/verify_wait.py +0 -94
  222. package/spec/cli-protocol.md +0 -102
  223. package/spec/mcp-tools.yaml +0 -312
  224. package/spec/schemas/baseline-reconciliation.v1.schema.json +0 -73
  225. package/spec/schemas/change-delta.v1.schema.json +0 -153
  226. package/spec/schemas/command-manifest.schema.json +0 -29
  227. package/spec/schemas/context-file.v4.5.schema.json +0 -54
  228. package/spec/schemas/delivery-report.v1.schema.json +0 -66
  229. package/spec/schemas/documentation-reconciliation.v1.schema.json +0 -106
  230. package/spec/schemas/mcp-tools.schema.json +0 -136
  231. package/spec/schemas/skill-manifest.schema.json +0 -24
  232. package/spec/schemas/state-db.sql +0 -641
  233. package/spec/schemas/task-ledger.v2.schema.json +0 -296
  234. package/spec/schemas/tasks.v4.5.schema.json +0 -96
  235. package/spec/schemas/test-report.v1.schema.json +0 -225
  236. package/ultra-tools/cli.cjs +0 -129
  237. package/ultra-tools/commands/db.cjs +0 -226
  238. package/ultra-tools/commands/legacy-memory.cjs +0 -159
  239. package/ultra-tools/commands/migrate.cjs +0 -1386
  240. package/ultra-tools/commands/session.cjs +0 -213
  241. package/ultra-tools/commands/status.cjs +0 -559
  242. package/ultra-tools/commands/system.cjs +0 -498
  243. package/ultra-tools/commands/task.cjs +0 -105
@@ -0,0 +1,328 @@
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 PROTECTED_ROOT = '.ultra';
11
+ const MODEL_FIELDS = new Set([
12
+ '$schema', 'status', 'summary', 'changed_files', 'checks', 'evidence',
13
+ 'questions', 'residual_risks',
14
+ ]);
15
+
16
+ function writeAtomic(file, payload) {
17
+ const temporary = `${file}.tmp-${process.pid}`;
18
+ fs.writeFileSync(temporary, `${JSON.stringify(payload, null, 2)}\n`, { mode: 0o600 });
19
+ fs.renameSync(temporary, file);
20
+ }
21
+
22
+ function sha256(file) {
23
+ try {
24
+ return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+
30
+ function git(cwd, args, { binary = false } = {}) {
31
+ return execFileSync('git', args, {
32
+ cwd,
33
+ encoding: binary ? 'buffer' : 'utf8',
34
+ stdio: ['ignore', 'pipe', 'pipe'],
35
+ });
36
+ }
37
+
38
+ function zeroSeparated(buffer) {
39
+ return buffer.toString('utf8').split('\0').filter(Boolean);
40
+ }
41
+
42
+ function normalizeChangedPath(value) {
43
+ if (typeof value !== 'string' || !value || value.includes('\\') || path.posix.isAbsolute(value)) {
44
+ return null;
45
+ }
46
+ const normalized = path.posix.normalize(value);
47
+ if (normalized !== value || normalized === '.' || normalized === '..' || normalized.startsWith('../')) {
48
+ return null;
49
+ }
50
+ return normalized;
51
+ }
52
+
53
+ function changedFiles(spec) {
54
+ const tracked = zeroSeparated(git(spec.cwd, [
55
+ 'diff', '--name-only', '-z', spec.base_head, '--',
56
+ ], { binary: true }));
57
+ const untracked = zeroSeparated(git(spec.cwd, [
58
+ 'ls-files', '--others', '--exclude-standard', '-z',
59
+ ], { binary: true }));
60
+ return [...new Set([...tracked, ...untracked]
61
+ .map((item) => item.split(path.sep).join('/')))]
62
+ .sort();
63
+ }
64
+
65
+ function parseJson(value) {
66
+ if (typeof value !== 'string') return null;
67
+ let text = value.trim();
68
+ const fence = text.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);
69
+ if (fence) text = fence[1];
70
+ try { return JSON.parse(text); } catch { return null; }
71
+ }
72
+
73
+ function collectResultCandidates(value, candidates, depth = 0) {
74
+ if (depth > 12 || value === null || value === undefined) return;
75
+ if (typeof value === 'string') {
76
+ const parsed = parseJson(value);
77
+ if (parsed !== null) collectResultCandidates(parsed, candidates, depth + 1);
78
+ return;
79
+ }
80
+ if (Array.isArray(value)) {
81
+ for (const item of value) collectResultCandidates(item, candidates, depth + 1);
82
+ return;
83
+ }
84
+ if (typeof value !== 'object') return;
85
+ if (value.$schema === RESULT_SCHEMA) candidates.push(value);
86
+ for (const nested of Object.values(value)) {
87
+ collectResultCandidates(nested, candidates, depth + 1);
88
+ }
89
+ }
90
+
91
+ function extractModelResult(spec) {
92
+ const candidates = [];
93
+ for (const file of [spec.host_output, spec.stdout]) {
94
+ if (!file || !fs.existsSync(file) || fs.statSync(file).size === 0) continue;
95
+ const text = fs.readFileSync(file, 'utf8');
96
+ const full = parseJson(text);
97
+ if (full !== null) collectResultCandidates(full, candidates);
98
+ for (const line of text.split('\n')) {
99
+ const parsed = parseJson(line);
100
+ if (parsed !== null) collectResultCandidates(parsed, candidates);
101
+ }
102
+ }
103
+ return candidates.at(-1) || null;
104
+ }
105
+
106
+ function validateModelResult(payload) {
107
+ if (!payload || Array.isArray(payload) || typeof payload !== 'object') {
108
+ return 'result must be a JSON object';
109
+ }
110
+ const extra = Object.keys(payload).filter((key) => !MODEL_FIELDS.has(key));
111
+ const missing = [...MODEL_FIELDS].filter((key) => !(key in payload));
112
+ if (extra.length || missing.length) {
113
+ return `result fields must be exact; missing=${missing.join(',') || 'none'} extra=${extra.join(',') || 'none'}`;
114
+ }
115
+ if (payload.$schema !== RESULT_SCHEMA) return `$schema must be ${RESULT_SCHEMA}`;
116
+ if (!['finished', 'blocked', 'failed'].includes(payload.status)) {
117
+ return 'status must be finished, blocked, or failed';
118
+ }
119
+ if (typeof payload.summary !== 'string' || !payload.summary.trim()) {
120
+ return 'summary must be a non-empty string';
121
+ }
122
+ if (!Array.isArray(payload.changed_files)) return 'changed_files must be an array';
123
+ const normalized = payload.changed_files.map(normalizeChangedPath);
124
+ if (normalized.some((item) => item === null) || new Set(normalized).size !== normalized.length) {
125
+ return 'changed_files must contain unique normalized repository-relative paths';
126
+ }
127
+ if (!Array.isArray(payload.checks)) return 'checks must be an array';
128
+ for (const check of payload.checks) {
129
+ if (!check || Array.isArray(check) || typeof check !== 'object') return 'checks items must be objects';
130
+ const keys = Object.keys(check);
131
+ if (!keys.every((key) => ['command', 'status', 'output_ref'].includes(key))) {
132
+ return 'checks items contain an unknown field';
133
+ }
134
+ if (typeof check.command !== 'string' || !check.command.trim()) return 'checks.command must be non-empty';
135
+ if (!['passed', 'failed', 'not_run'].includes(check.status)) return 'checks.status is invalid';
136
+ if (check.output_ref !== undefined && (typeof check.output_ref !== 'string' || !check.output_ref.trim())) {
137
+ return 'checks.output_ref must be a non-empty string when present';
138
+ }
139
+ }
140
+ for (const field of ['evidence', 'questions', 'residual_risks']) {
141
+ if (!Array.isArray(payload[field]) || !payload[field].every(
142
+ (item) => typeof item === 'string' && item.trim(),
143
+ )) return `${field} must be an array of non-empty strings`;
144
+ }
145
+ if (payload.status === 'blocked' && payload.questions.length === 0) {
146
+ return 'blocked results require at least one question';
147
+ }
148
+ payload.changed_files = [...normalized].sort();
149
+ return null;
150
+ }
151
+
152
+ // The project's memory has exactly one writer: the primary host. A worker that edits
153
+ // `.ultra` in its own worktree collides in the files every later session reads to
154
+ // resume, so no permission grants it — not even `writable_roots: ["."]`.
155
+ function authorized(spec, file) {
156
+ if (file === PROTECTED_ROOT || file.startsWith(`${PROTECTED_ROOT}/`)) return false;
157
+ return spec.writable_roots.some((root) => (
158
+ root === '.' || file === root || file.startsWith(`${root}/`)
159
+ ));
160
+ }
161
+
162
+ function finalHead(spec) {
163
+ try { return git(spec.cwd, ['rev-parse', 'HEAD']).trim(); } catch { return null; }
164
+ }
165
+
166
+ function mechanical(spec, exitCode, signal) {
167
+ return {
168
+ delegation_id: spec.delegation_id,
169
+ host: spec.host,
170
+ instruction_digest: spec.instruction_digest,
171
+ permission_digest: spec.permission_digest,
172
+ output_schema_digest: spec.output_schema_digest,
173
+ read_only: spec.read_only,
174
+ base_head: spec.base_head,
175
+ final_head: finalHead(spec),
176
+ started_at: spec.started_at,
177
+ finished_at: new Date().toISOString(),
178
+ exit_code: Number.isInteger(exitCode) ? exitCode : null,
179
+ signal: signal || null,
180
+ };
181
+ }
182
+
183
+ function failure(spec, type, summary, exitCode = null, signal = null, files = []) {
184
+ return {
185
+ $schema: RESULT_SCHEMA,
186
+ status: 'failed',
187
+ summary,
188
+ changed_files: files,
189
+ checks: [],
190
+ evidence: [],
191
+ questions: [],
192
+ residual_risks: [],
193
+ failure_type: type,
194
+ ...mechanical(spec, exitCode, signal),
195
+ };
196
+ }
197
+
198
+ function terminate(child, signal = 'SIGTERM') {
199
+ if (!child || child.exitCode !== null || child.signalCode !== null) return;
200
+ try {
201
+ if (process.platform === 'win32') child.kill(signal);
202
+ else process.kill(-child.pid, signal);
203
+ } catch {}
204
+ }
205
+
206
+ function runChild(spec) {
207
+ return new Promise((resolve) => {
208
+ const stdoutFd = fs.openSync(spec.stdout, 'a');
209
+ const stderrFd = fs.openSync(spec.stderr, 'a');
210
+ let termination = null;
211
+ let spawnError = null;
212
+ let closed = false;
213
+ let hardKill = null;
214
+ const child = spawn(spec.command, spec.args, {
215
+ cwd: spec.cwd,
216
+ env: { ...process.env, ...spec.env },
217
+ detached: process.platform !== 'win32',
218
+ stdio: ['ignore', stdoutFd, stderrFd],
219
+ });
220
+ const finish = (code, signal) => {
221
+ if (closed) return;
222
+ closed = true;
223
+ clearInterval(cancelPoll);
224
+ clearTimeout(timeout);
225
+ if (hardKill) clearTimeout(hardKill);
226
+ fs.closeSync(stdoutFd);
227
+ fs.closeSync(stderrFd);
228
+ resolve({ code, signal, termination, spawnError });
229
+ };
230
+ child.on('error', (error) => { spawnError = error; });
231
+ child.on('close', finish);
232
+ const requestTermination = (reason) => {
233
+ if (termination) return;
234
+ termination = reason;
235
+ terminate(child);
236
+ hardKill = setTimeout(() => terminate(child, 'SIGKILL'), 1500);
237
+ hardKill.unref();
238
+ };
239
+ const cancelPoll = setInterval(() => {
240
+ if (fs.existsSync(spec.cancel)) requestTermination('cancelled');
241
+ }, 100);
242
+ const timeout = setTimeout(() => requestTermination('timeout'), spec.timeout_ms);
243
+ cancelPoll.unref();
244
+ timeout.unref();
245
+ });
246
+ }
247
+
248
+ async function main() {
249
+ const specFile = process.argv[2];
250
+ const expectedSpecDigest = process.argv[3];
251
+ if (!specFile || !/^[0-9a-f]{64}$/.test(expectedSpecDigest || '')) {
252
+ throw new Error('worker requires a spec path and digest');
253
+ }
254
+ if (sha256(specFile) !== expectedSpecDigest) throw new Error('worker spec digest mismatch before launch');
255
+ const spec = JSON.parse(fs.readFileSync(specFile, 'utf8'));
256
+ let terminal;
257
+ try {
258
+ if (sha256(spec.instruction) !== spec.instruction_digest) {
259
+ terminal = failure(spec, 'instruction_changed', 'Instruction digest changed before delegation started.');
260
+ } else if (sha256(spec.permission) !== spec.permission_digest) {
261
+ terminal = failure(spec, 'permission_changed', 'Permission digest changed before delegation started.');
262
+ } else if (sha256(spec.output_schema) !== spec.output_schema_digest) {
263
+ terminal = failure(spec, 'output_schema_changed', 'Output schema digest changed before delegation started.');
264
+ } else if (fs.existsSync(spec.cancel)) {
265
+ terminal = failure(spec, 'cancelled', 'Delegation was cancelled before the host process started.');
266
+ } else {
267
+ const processResult = await runChild(spec);
268
+ let files = [];
269
+ try { files = changedFiles(spec); } catch {}
270
+ if (processResult.termination === 'cancelled') {
271
+ terminal = failure(spec, 'cancelled', 'Delegation cancelled by request.', processResult.code, processResult.signal, files);
272
+ } else if (processResult.termination === 'timeout') {
273
+ terminal = failure(spec, 'timeout', 'Delegation timed out and the host process was terminated.', processResult.code, processResult.signal, files);
274
+ } else if (sha256(specFile) !== expectedSpecDigest) {
275
+ terminal = failure(spec, 'worker_spec_changed', 'Worker specification changed during delegation.', processResult.code, processResult.signal, files);
276
+ } else if (sha256(spec.instruction) !== spec.instruction_digest) {
277
+ terminal = failure(spec, 'instruction_changed', 'Instruction digest changed during delegation.', processResult.code, processResult.signal, files);
278
+ } else if (sha256(spec.permission) !== spec.permission_digest) {
279
+ terminal = failure(spec, 'permission_changed', 'Permission digest changed during delegation.', processResult.code, processResult.signal, files);
280
+ } else if (sha256(spec.output_schema) !== spec.output_schema_digest) {
281
+ terminal = failure(spec, 'output_schema_changed', 'Output schema digest changed during delegation.', processResult.code, processResult.signal, files);
282
+ } else if (processResult.spawnError) {
283
+ terminal = failure(spec, 'spawn_error', `Host process failed to start: ${processResult.spawnError.message}`, null, null, files);
284
+ } else if (processResult.code !== 0) {
285
+ terminal = failure(spec, 'process_exit', `Host process exited with code ${processResult.code}.`, processResult.code, processResult.signal, files);
286
+ } else {
287
+ const payload = extractModelResult(spec);
288
+ if (!payload) {
289
+ terminal = failure(
290
+ spec, 'missing_result',
291
+ 'Host process exited without a structured Ultra delegation result.',
292
+ processResult.code, processResult.signal, files,
293
+ );
294
+ } else {
295
+ const validation = validateModelResult(payload);
296
+ if (validation) {
297
+ terminal = failure(spec, 'invalid_result', validation, processResult.code, processResult.signal, files);
298
+ } else {
299
+ const unauthorized = files.filter((file) => !authorized(spec, file));
300
+ if (unauthorized.length) {
301
+ terminal = failure(
302
+ spec, 'unauthorized_write',
303
+ `Actual Git diff escaped writable_roots: ${unauthorized.join(', ')}`,
304
+ processResult.code, processResult.signal, files,
305
+ );
306
+ } else if (JSON.stringify(payload.changed_files) !== JSON.stringify(files)) {
307
+ terminal = failure(
308
+ spec, 'changed_files_mismatch',
309
+ `Declared changed_files do not match actual Git diff: ${files.join(', ') || 'none'}`,
310
+ processResult.code, processResult.signal, files,
311
+ );
312
+ } else {
313
+ terminal = { ...payload, ...mechanical(spec, processResult.code, processResult.signal) };
314
+ }
315
+ }
316
+ }
317
+ }
318
+ }
319
+ if (!fs.existsSync(spec.result)) writeAtomic(spec.result, terminal);
320
+ } finally {
321
+ try { fs.unlinkSync(spec.lock); } catch (error) { if (error.code !== 'ENOENT') throw error; }
322
+ }
323
+ }
324
+
325
+ main().catch((error) => {
326
+ process.stderr.write(`${error.stack || error.message}\n`);
327
+ process.exitCode = 1;
328
+ });