@buaa_smat/hometrans 26.0.4 → 26.0.5

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 (102) hide show
  1. package/agents/code-reviewer.md +2 -0
  2. package/agents/model-render-worker.md +1 -1
  3. package/i18n/agents/code-reviewer.md +2 -0
  4. package/i18n/agents/model-render-worker.md +1 -1
  5. package/i18n/skills/a2h-app-migrate/SKILL.md +51 -3
  6. package/i18n/skills/a2h-app-migrate/references/workflow.yaml +140 -32
  7. package/i18n/skills/a2h-app-migrate/scripts/dag_graph.mjs +297 -0
  8. package/i18n/skills/a2h-app-migrate/scripts/validate_workflow.mjs +134 -21
  9. package/i18n/skills/a2h-app-migrate/test/test_finalize.mjs +21 -4
  10. package/i18n/skills/a2h-app-migrate/test/test_image_probe.mjs +3 -3
  11. package/i18n/skills/a2h-app-migrate/test/test_resume_plan.mjs +1 -1
  12. package/i18n/skills/a2h-app-migrate/test/test_reuse_static_utg.mjs +1 -1
  13. package/i18n/skills/a2h-app-migrate/test/test_utg_static_done.mjs +12 -5
  14. package/i18n/skills/a2h-arkts-logic-coder/SKILL.md +7 -8
  15. package/i18n/skills/a2h-arkts-logic-coder/references/ISSUES.md +1 -1
  16. package/i18n/skills/a2h-arkts-logic-coder/references/code-generation.md +27 -15
  17. package/i18n/skills/a2h-batch-ui-align/SKILL.md +1 -1
  18. package/i18n/skills/a2h-batch-ui-align/references/cards/widgets.md +4 -0
  19. package/i18n/skills/a2h-batch-ui-align/references/checker-rules.md +36 -0
  20. package/i18n/skills/a2h-batch-ui-align/references/conversion-procedure.md +4 -0
  21. package/i18n/skills/a2h-batch-ui-align/references/mappings/android-to-harmonyOS-ui-layout-mapping-reference.md +4 -0
  22. package/i18n/skills/a2h-batch-ui-align/references/step5-convert.md +3 -3
  23. package/i18n/skills/a2h-batch-ui-align/scripts/static_check/main.ts +8 -0
  24. package/i18n/skills/a2h-batch-ui-align/scripts/static_check/rules/overlay_in_linear.ts +164 -0
  25. package/i18n/skills/a2h-batch-ui-align/scripts/static_check/rules/self_drawn_sheet.ts +105 -0
  26. package/i18n/skills/a2h-batch-ui-align/scripts/static_check/rules/staggered_lanes.ts +127 -0
  27. package/i18n/skills/a2h-batch-ui-align/scripts/static_check/rules/window_size_constant.ts +114 -0
  28. package/i18n/skills/a2h-page-specgen/references/scenario-authoring.md +4 -1
  29. package/i18n/skills/a2h-page-specgen/references/spec-example.md +35 -5
  30. package/i18n/skills/a2h-page-specgen/references/spec-template.md +4 -4
  31. package/i18n/skills/a2h-spec-generate/SKILL.md +3 -1
  32. package/i18n/skills/a2h-spec-generate/references/fusion-task-contract.md +15 -3
  33. package/i18n/skills/a2h-spec-generate/references/review-checklist.md +1 -0
  34. package/i18n/skills/a2h-spec-generate/references/spec-sample-complex.md +16 -0
  35. package/i18n/skills/a2h-spec-generate/references/spec-sample-transfer.md +16 -0
  36. package/i18n/skills/a2h-spec-generate/references/spec-samples.md +5 -1
  37. package/i18n/skills/a2h-spec-generate/references/synthesis-rules.md +21 -1
  38. package/i18n/skills/a2h-spec-generate/references/worker-rules.md +25 -2
  39. package/i18n/skills/a2h-spec-generate/scripts/check_spec.ts +121 -6
  40. package/i18n/skills/a2h-spec-generate/scripts/reqgen/src/fusion/task-contract.ts +2 -1
  41. package/i18n/skills/a2h-spec-generate/scripts/reqgen/test/fusion-behavior-e2e.test.ts +3 -0
  42. package/i18n/skills/a2h-spec-generate/scripts/reqgen/test/fusion-spec.test.ts +16 -2
  43. package/i18n/skills/a2h-spec-generate/test/check-fused-spec.test.mjs +11 -2
  44. package/i18n/skills/a2h-spec-generate/test/check-spec.test.ts +35 -0
  45. package/package.json +1 -1
  46. package/skills/a2h-app-migrate/SKILL.md +53 -5
  47. package/skills/a2h-app-migrate/references/workflow.yaml +140 -32
  48. package/skills/a2h-app-migrate/scripts/assert_dag_complete.mjs +226 -0
  49. package/skills/a2h-app-migrate/scripts/dag_graph.mjs +297 -0
  50. package/skills/a2h-app-migrate/scripts/dag_process_executor.mjs +199 -0
  51. package/skills/a2h-app-migrate/scripts/dag_production_executor.mjs +897 -0
  52. package/skills/a2h-app-migrate/scripts/dag_runner.mjs +1767 -0
  53. package/skills/a2h-app-migrate/scripts/ledger.mjs +15 -2
  54. package/skills/a2h-app-migrate/scripts/lib-yaml-lite.mjs +8 -2
  55. package/skills/a2h-app-migrate/scripts/resume_plan.mjs +3 -8
  56. package/skills/a2h-app-migrate/scripts/validate_workflow.mjs +134 -21
  57. package/skills/a2h-app-migrate/test/test_dag_complete.mjs +222 -0
  58. package/skills/a2h-app-migrate/test/test_dag_production.mjs +670 -0
  59. package/skills/a2h-app-migrate/test/test_dag_runner.mjs +423 -0
  60. package/skills/a2h-app-migrate/test/test_finalize.mjs +21 -4
  61. package/skills/a2h-app-migrate/test/test_image_probe.mjs +1 -1
  62. package/skills/a2h-app-migrate/test/test_resume_plan.mjs +16 -1
  63. package/skills/a2h-app-migrate/test/test_reuse_static_utg.mjs +1 -1
  64. package/skills/a2h-app-migrate/test/test_utg_static_done.mjs +12 -5
  65. package/skills/a2h-arkts-logic-coder/SKILL.md +7 -8
  66. package/skills/a2h-arkts-logic-coder/references/ISSUES.md +1 -1
  67. package/skills/a2h-arkts-logic-coder/references/code-generation.md +27 -15
  68. package/skills/a2h-batch-ui-align/SKILL.md +1 -1
  69. package/skills/a2h-batch-ui-align/references/cards/widgets.md +4 -0
  70. package/skills/a2h-batch-ui-align/references/checker-rules.md +36 -0
  71. package/skills/a2h-batch-ui-align/references/conversion-procedure.md +4 -0
  72. package/skills/a2h-batch-ui-align/references/mappings/android-to-harmonyOS-ui-layout-mapping-reference.md +4 -0
  73. package/skills/a2h-batch-ui-align/references/step5-convert.md +3 -3
  74. package/skills/a2h-batch-ui-align/scripts/group_queue.mjs +49 -3
  75. package/skills/a2h-batch-ui-align/scripts/static_check/core/android.ts +36 -0
  76. package/skills/a2h-batch-ui-align/scripts/static_check/main.ts +8 -0
  77. package/skills/a2h-batch-ui-align/scripts/static_check/registry.ts +8 -0
  78. package/skills/a2h-batch-ui-align/scripts/static_check/rules/overlay_in_linear.ts +164 -0
  79. package/skills/a2h-batch-ui-align/scripts/static_check/rules/self_drawn_sheet.ts +105 -0
  80. package/skills/a2h-batch-ui-align/scripts/static_check/rules/staggered_lanes.ts +127 -0
  81. package/skills/a2h-batch-ui-align/scripts/static_check/rules/window_size_constant.ts +114 -0
  82. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_coolmall_ds1123.test.mjs +433 -0
  83. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_overlay_in_linear.test.mjs +288 -0
  84. package/skills/a2h-batch-ui-align/scripts/tests/group_queue.test.mjs +46 -0
  85. package/skills/a2h-page-specgen/references/scenario-authoring.md +4 -1
  86. package/skills/a2h-page-specgen/references/spec-example.md +35 -5
  87. package/skills/a2h-page-specgen/references/spec-template.md +4 -4
  88. package/skills/a2h-spec-generate/SKILL.md +3 -1
  89. package/skills/a2h-spec-generate/references/fusion-task-contract.md +15 -3
  90. package/skills/a2h-spec-generate/references/review-checklist.md +1 -0
  91. package/skills/a2h-spec-generate/references/spec-sample-complex.md +16 -0
  92. package/skills/a2h-spec-generate/references/spec-sample-transfer.md +16 -0
  93. package/skills/a2h-spec-generate/references/spec-samples.md +5 -1
  94. package/skills/a2h-spec-generate/references/synthesis-rules.md +21 -1
  95. package/skills/a2h-spec-generate/references/worker-rules.md +25 -2
  96. package/skills/a2h-spec-generate/scripts/check-fused-spec.mjs +3 -1
  97. package/skills/a2h-spec-generate/scripts/check_spec.ts +262 -6
  98. package/skills/a2h-spec-generate/scripts/reqgen/src/fusion/task-contract.ts +12 -2
  99. package/skills/a2h-spec-generate/scripts/reqgen/test/fusion-behavior-e2e.test.ts +3 -0
  100. package/skills/a2h-spec-generate/scripts/reqgen/test/fusion-spec.test.ts +16 -2
  101. package/skills/a2h-spec-generate/test/check-fused-spec.test.mjs +54 -3
  102. package/skills/a2h-spec-generate/test/check-spec.test.ts +247 -0
@@ -0,0 +1,1767 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { spawn, spawnSync } from "node:child_process";
5
+ import { createHash, randomUUID } from "node:crypto";
6
+ import { fileURLToPath } from "node:url";
7
+
8
+ import yaml from "./lib-yaml-lite.mjs";
9
+ import { buildGraph, evaluateExpression, readyNodes, resolveParents, rewindAffected } from "./dag_graph.mjs";
10
+ import { ExecutorProtocolError, readExecutorResult, runProcessExecutor } from "./dag_process_executor.mjs";
11
+ import { appendLedger, readLedger, startedFields } from "./ledger.mjs";
12
+ import { evaluateDag } from "./assert_dag_complete.mjs";
13
+ import { planResume } from "./resume_plan.mjs";
14
+
15
+ const SCHEMA = "a2h-dag-run/v1";
16
+ const TERMINAL = new Set(["done", "reused", "skipped", "failed"]);
17
+ const ACTIVE_ATTEMPT = new Set(["running", "waiting_external", "waiting_human"]);
18
+ const UNSUPPORTED_LIFECYCLE = ["precondition", "before_run", "after_run", "hook", "hooks", "actions"];
19
+ const STDERR_LIMIT = 4096;
20
+
21
+ class RunnerError extends Error {
22
+ constructor(code, message, exitCode = 2, cause) {
23
+ super(message, cause === undefined ? undefined : { cause });
24
+ this.name = "RunnerError";
25
+ this.code = code;
26
+ this.exitCode = exitCode;
27
+ }
28
+ }
29
+
30
+ function stamp() {
31
+ return new Date().toISOString();
32
+ }
33
+
34
+ function absolute(value, base = process.cwd()) {
35
+ return path.resolve(base, String(value));
36
+ }
37
+
38
+ function writeJsonAtomic(filePath, value) {
39
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
40
+ const temporary = path.join(
41
+ path.dirname(filePath),
42
+ `.${path.basename(filePath)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,
43
+ );
44
+ try {
45
+ fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf8", flag: "wx" });
46
+ fs.renameSync(temporary, filePath);
47
+ } catch (error) {
48
+ fs.rmSync(temporary, { force: true });
49
+ throw error;
50
+ }
51
+ }
52
+
53
+ function readJson(filePath, code = "INVALID_JSON") {
54
+ let value;
55
+ try {
56
+ value = JSON.parse(fs.readFileSync(filePath, "utf8"));
57
+ } catch (error) {
58
+ throw new RunnerError(code, `Unable to read JSON ${filePath}: ${error.message}`, 2, error);
59
+ }
60
+ return value;
61
+ }
62
+
63
+ function saveState(context) {
64
+ context.state.updated_at = stamp();
65
+ writeJsonAtomic(context.statePath, context.state);
66
+ }
67
+
68
+ function workflowDigest(filePath) {
69
+ return createHash("sha256").update(fs.readFileSync(filePath)).digest("hex");
70
+ }
71
+
72
+ function readWorkflow(filePath) {
73
+ let document;
74
+ try {
75
+ document = yaml.load(fs.readFileSync(filePath, "utf8"));
76
+ } catch (error) {
77
+ throw new RunnerError("INVALID_WORKFLOW", `Unable to load workflow ${filePath}: ${error.message}`, 2, error);
78
+ }
79
+ if (!document || typeof document !== "object" || !Array.isArray(document.nodes)) {
80
+ throw new RunnerError("INVALID_WORKFLOW", "Workflow must contain a nodes array");
81
+ }
82
+ return document;
83
+ }
84
+
85
+ export function loadRunState(statePath) {
86
+ const filePath = absolute(statePath);
87
+ const state = readJson(filePath, "INVALID_RUN_STATE");
88
+ if (
89
+ !state || state.schema !== SCHEMA || typeof state.run_id !== "string" || !state.run_id
90
+ || typeof state.workflow?.path !== "string" || typeof state.workflow?.sha256 !== "string"
91
+ || !state.nodes || typeof state.nodes !== "object" || Array.isArray(state.nodes)
92
+ || !Array.isArray(state.attempts)
93
+ ) {
94
+ throw new RunnerError("INVALID_RUN_STATE", `Not a ${SCHEMA} state file: ${filePath}`);
95
+ }
96
+ return state;
97
+ }
98
+
99
+ function expand(value, vars) {
100
+ if (typeof value !== "string") return value;
101
+ return value.replace(/\$\{([A-Za-z_$][\w$]*)\}/g, (_match, name) => {
102
+ if (Object.prototype.hasOwnProperty.call(vars, name)) return String(vars[name] ?? "");
103
+ return "";
104
+ });
105
+ }
106
+
107
+ function productionWorkflow(document) {
108
+ return document.nodes.some((node) => node.runner?.action === "production");
109
+ }
110
+
111
+ function workflowVars(document, explicit, profile) {
112
+ const values = {};
113
+ for (const [name, definition] of Object.entries(document.vars || {})) {
114
+ values[name] = definition && typeof definition === "object" && !Array.isArray(definition)
115
+ ? definition.default
116
+ : definition;
117
+ }
118
+ Object.assign(values, explicit);
119
+ values.RUN_DIR_GIVEN = Object.prototype.hasOwnProperty.call(explicit, "RUN_DIR");
120
+ if (Object.prototype.hasOwnProperty.call(explicit, "SPEC_ENGINE")) values.SPEC_ENGINE_GIVEN = true;
121
+ if (Object.prototype.hasOwnProperty.call(explicit, "SPECS_JSON")) {
122
+ values.SPECS_JSON_IS_DEFAULT = false;
123
+ values.SKIP_SPEC_GENERATE = true;
124
+ }
125
+ values.PROFILE = profile;
126
+ for (let pass = 0; pass < Object.keys(values).length + 1; pass++) {
127
+ let changed = false;
128
+ for (const [name, value] of Object.entries(values)) {
129
+ if (typeof value !== "string") continue;
130
+ const rendered = expand(value, values);
131
+ if (rendered !== value) {
132
+ values[name] = rendered;
133
+ changed = true;
134
+ }
135
+ }
136
+ if (!changed) break;
137
+ }
138
+ return values;
139
+ }
140
+
141
+ function refreshProductionPaths(context) {
142
+ if (!context.production) return;
143
+ const vars = context.state.vars;
144
+ context.state.paths.production_run_dir = vars.RUN_DIR || "";
145
+ context.state.paths.work = vars.WORK || "";
146
+ context.state.paths.hmos = vars.HMOS || "";
147
+ context.logicReport = absolute(vars.LOGIC_REPORT);
148
+ context.logicState = absolute(vars.LOGIC_STATE);
149
+ context.state.paths.logic_report = context.logicReport;
150
+ context.state.paths.logic_state = context.logicState;
151
+ }
152
+
153
+ function applySetVars(context, result) {
154
+ if (result.set_vars === undefined) return;
155
+ if (!result.set_vars || typeof result.set_vars !== "object" || Array.isArray(result.set_vars)) {
156
+ throw new ExecutorProtocolError("EXECUTOR_INVALID_RESULT", "set_vars must be a JSON object");
157
+ }
158
+ const protectedNames = new Set(["PROFILE", "DAG_RUN_DIR", "DAG_STATE", "WORKFLOW", "LEDGER"]);
159
+ const updates = {};
160
+ for (const [name, value] of Object.entries(result.set_vars)) {
161
+ if (!/^[A-Z_][A-Z0-9_]*$/.test(name) || protectedNames.has(name)) {
162
+ throw new ExecutorProtocolError("EXECUTOR_INVALID_RESULT", `set_vars contains a protected or invalid variable: ${name}`);
163
+ }
164
+ if (value !== null && !["string", "number", "boolean"].includes(typeof value)) {
165
+ throw new ExecutorProtocolError("EXECUTOR_INVALID_RESULT", `set_vars.${name} must be a scalar value`);
166
+ }
167
+ updates[name] = value;
168
+ }
169
+ Object.assign(context.state.vars, updates);
170
+ refreshProductionPaths(context);
171
+ }
172
+
173
+ function splitArgs(value) {
174
+ if (value == null || value === "") return [];
175
+ if (Array.isArray(value)) return value.map((item) => String(item));
176
+ if (typeof value !== "string") {
177
+ throw new RunnerError("UNSUPPORTED_SUCCESS_RULE", "script args must be a string or an array");
178
+ }
179
+ const args = [];
180
+ let token = "";
181
+ let quote = "";
182
+ let started = false;
183
+ for (let index = 0; index < value.length; index++) {
184
+ const char = value[index];
185
+ if (quote) {
186
+ if (char === quote) {
187
+ quote = "";
188
+ } else {
189
+ token += char;
190
+ }
191
+ } else if (char === "'" || char === '"') {
192
+ quote = char;
193
+ started = true;
194
+ } else if (/\s/.test(char)) {
195
+ if (started || token) {
196
+ args.push(token);
197
+ token = "";
198
+ started = false;
199
+ }
200
+ } else {
201
+ token += char;
202
+ started = true;
203
+ }
204
+ }
205
+ if (quote) throw new RunnerError("UNSUPPORTED_SUCCESS_RULE", "Unterminated quote in script args");
206
+ if (started || token) args.push(token);
207
+ return args;
208
+ }
209
+
210
+ function resolveArtifact(value, context) {
211
+ const rendered = expand(value, context.vars || {});
212
+ if (!rendered) return "";
213
+ return absolute(rendered, context.cwd || context.runDir || process.cwd());
214
+ }
215
+
216
+ function globNonempty(pattern, context) {
217
+ const rendered = expand(pattern, context.vars || {});
218
+ if (!rendered || !/[*?]/.test(rendered)) {
219
+ const target = resolveArtifact(rendered, context);
220
+ return Boolean(target && fs.existsSync(target));
221
+ }
222
+ const normalized = absolute(rendered, context.cwd || context.runDir || process.cwd()).replace(/\\/g, "/");
223
+ const root = path.parse(normalized).root.replace(/\\/g, "/");
224
+ const segments = normalized.slice(root.length).split("/").filter(Boolean);
225
+ const segmentRegex = (segment) => {
226
+ let source = "^";
227
+ for (const char of segment) {
228
+ if (char === "*") source += "[^/]*";
229
+ else if (char === "?") source += "[^/]";
230
+ else source += char.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");
231
+ }
232
+ return new RegExp(`${source}$`);
233
+ };
234
+ function visit(directory, index) {
235
+ if (index >= segments.length) return fs.existsSync(directory);
236
+ const segment = segments[index];
237
+ if (segment === "**") {
238
+ if (visit(directory, index + 1)) return true;
239
+ let entries;
240
+ try {
241
+ entries = fs.readdirSync(directory, { withFileTypes: true });
242
+ } catch {
243
+ return false;
244
+ }
245
+ return entries.some((entry) => entry.isDirectory() && visit(path.join(directory, entry.name), index));
246
+ }
247
+ if (!/[*?]/.test(segment)) return visit(path.join(directory, segment), index + 1);
248
+ let entries;
249
+ try {
250
+ entries = fs.readdirSync(directory, { withFileTypes: true });
251
+ } catch {
252
+ return false;
253
+ }
254
+ const regex = segmentRegex(segment);
255
+ return entries.some((entry) => regex.test(entry.name) && visit(path.join(directory, entry.name), index + 1));
256
+ }
257
+ return visit(root, 0);
258
+ }
259
+
260
+ function runSuccessScript(rule, context) {
261
+ if (!rule || typeof rule !== "object" || Array.isArray(rule)) {
262
+ throw new RunnerError("UNSUPPORTED_SUCCESS_RULE", "script_exit_0 requires an object");
263
+ }
264
+ const runner = String(rule.runner || "node").toLowerCase();
265
+ if (runner !== "node" && runner !== "python") {
266
+ throw new RunnerError("UNSUPPORTED_SUCCESS_RULE", `Unsupported success script runner: ${rule.runner}`);
267
+ }
268
+ if (typeof rule.script !== "string" || !rule.script.trim()) {
269
+ throw new RunnerError("UNSUPPORTED_SUCCESS_RULE", "script_exit_0 requires script");
270
+ }
271
+ let args;
272
+ try {
273
+ args = splitArgs(rule.args).map((item) => expand(item, context.vars || {}));
274
+ } catch (error) {
275
+ if (error instanceof RunnerError) throw error;
276
+ throw new RunnerError("UNSUPPORTED_SUCCESS_RULE", error.message, 2, error);
277
+ }
278
+ const script = resolveArtifact(rule.script, context);
279
+ const command = runner === "node" ? process.execPath : "python";
280
+ const commandArgs = runner === "node" ? [script, ...args] : [script, ...args];
281
+ const outcome = spawnSync(command, commandArgs, {
282
+ cwd: rule.cwd ? resolveArtifact(rule.cwd, context) : context.cwd || context.runDir,
283
+ env: process.env,
284
+ shell: false,
285
+ windowsHide: true,
286
+ encoding: "utf8",
287
+ maxBuffer: 1024 * 1024,
288
+ });
289
+ return !outcome.error && outcome.status === 0;
290
+ }
291
+
292
+ function needsTerminal(context) {
293
+ const { state, graph, node } = context;
294
+ if (!state || !node) throw new RunnerError("UNSUPPORTED_SUCCESS_RULE", "all_needs_terminal requires node state");
295
+ const parents = graph ? resolveParents(graph, node, context.vars || {}) : new Set(node.needs || []);
296
+ return [...parents].every((id) => TERMINAL.has(state.nodes[id]?.status));
297
+ }
298
+
299
+ export function evaluateSuccess(rules, context = {}) {
300
+ if (rules == null) return true;
301
+ if (Array.isArray(rules)) return rules.every((rule) => evaluateSuccess(rule, context));
302
+ if (typeof rules === "boolean") return rules;
303
+ if (typeof rules !== "object") {
304
+ throw new RunnerError("UNSUPPORTED_SUCCESS_RULE", `Unsupported success rule: ${JSON.stringify(rules)}`);
305
+ }
306
+
307
+ let conditioned = rules;
308
+ if (Object.prototype.hasOwnProperty.call(rules, "when")) {
309
+ if (!evaluateExpression(String(rules.when ?? ""), context.vars || {})) return false;
310
+ const rest = { ...rules };
311
+ delete rest.when;
312
+ if (Object.keys(rest).length === 0) return true;
313
+ conditioned = rest;
314
+ }
315
+
316
+ return Object.entries(conditioned).every(([predicate, operand]) => {
317
+ switch (predicate) {
318
+ case "all":
319
+ if (!Array.isArray(operand)) throw new RunnerError("UNSUPPORTED_SUCCESS_RULE", "all requires an array");
320
+ return operand.every((rule) => evaluateSuccess(rule, context));
321
+ case "any":
322
+ if (!Array.isArray(operand)) throw new RunnerError("UNSUPPORTED_SUCCESS_RULE", "any requires an array");
323
+ return operand.some((rule) => evaluateSuccess(rule, context));
324
+ case "file_exists": {
325
+ const target = resolveArtifact(operand, context);
326
+ try {
327
+ return Boolean(target && fs.statSync(target).isFile());
328
+ } catch {
329
+ return false;
330
+ }
331
+ }
332
+ case "dir_exists": {
333
+ const target = resolveArtifact(operand, context);
334
+ try {
335
+ return Boolean(target && fs.statSync(target).isDirectory());
336
+ } catch {
337
+ return false;
338
+ }
339
+ }
340
+ case "glob_nonempty":
341
+ return globNonempty(String(operand ?? ""), context);
342
+ case "script_exit_0":
343
+ return runSuccessScript(operand, context);
344
+ case "skipped": {
345
+ const status = context.status || context.nodeState?.status || context.state?.nodes?.[context.node?.id]?.status;
346
+ const skipped = status === "skipped" || status === "reused";
347
+ return skipped === Boolean(operand);
348
+ }
349
+ case "all_needs_terminal":
350
+ return needsTerminal(context) === Boolean(operand);
351
+ default:
352
+ throw new RunnerError("UNSUPPORTED_SUCCESS_RULE", `Unsupported success predicate: ${predicate}`);
353
+ }
354
+ });
355
+ }
356
+
357
+ function pidAlive(pid) {
358
+ if (!Number.isInteger(pid) || pid <= 0) return false;
359
+ try {
360
+ process.kill(pid, 0);
361
+ return true;
362
+ } catch (error) {
363
+ return error?.code === "EPERM";
364
+ }
365
+ }
366
+
367
+ function acquireLock(statePath) {
368
+ const lockPath = `${statePath}.lock`;
369
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });
370
+ for (let attempt = 0; attempt < 3; attempt++) {
371
+ const owner = { pid: process.pid, token: randomUUID(), at: stamp() };
372
+ try {
373
+ const descriptor = fs.openSync(lockPath, "wx");
374
+ try {
375
+ fs.writeFileSync(descriptor, `${JSON.stringify(owner)}\n`, "utf8");
376
+ fs.fsyncSync(descriptor);
377
+ } finally {
378
+ fs.closeSync(descriptor);
379
+ }
380
+ return { lockPath, token: owner.token };
381
+ } catch (error) {
382
+ if (error?.code !== "EEXIST") throw error;
383
+ let existing = null;
384
+ try {
385
+ existing = JSON.parse(fs.readFileSync(lockPath, "utf8"));
386
+ } catch {
387
+ // A lock is created before its owner is written. Retry briefly only if it is still incomplete.
388
+ }
389
+ if (existing && !pidAlive(existing.pid)) {
390
+ const stale = `${lockPath}.${process.pid}.${randomUUID()}.stale`;
391
+ try {
392
+ fs.renameSync(lockPath, stale);
393
+ fs.rmSync(stale, { force: true });
394
+ continue;
395
+ } catch (renameError) {
396
+ if (renameError?.code === "ENOENT") continue;
397
+ throw renameError;
398
+ }
399
+ }
400
+ if (!existing && attempt < 2) {
401
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
402
+ continue;
403
+ }
404
+ throw new RunnerError("RUNNER_LOCKED", `Run state is locked by pid ${existing?.pid || "unknown"}`, 1);
405
+ }
406
+ }
407
+ throw new RunnerError("RUNNER_LOCKED", "Unable to acquire run state lock", 1);
408
+ }
409
+
410
+ function withLock(statePath, operation) {
411
+ const lock = acquireLock(statePath);
412
+ const release = () => {
413
+ try {
414
+ const owner = JSON.parse(fs.readFileSync(lock.lockPath, "utf8"));
415
+ if (owner.token === lock.token) fs.rmSync(lock.lockPath, { force: true });
416
+ } catch {
417
+ // Do not remove a lock whose ownership can no longer be established.
418
+ }
419
+ };
420
+ let result;
421
+ try {
422
+ result = operation();
423
+ } catch (error) {
424
+ release();
425
+ throw error;
426
+ }
427
+ if (result && typeof result.then === "function") return result.finally(release);
428
+ release();
429
+ return result;
430
+ }
431
+
432
+ function normalizeStateOptions(options) {
433
+ return typeof options === "string" ? { state: options } : options || {};
434
+ }
435
+
436
+ function loadContext(rawOptions) {
437
+ const options = normalizeStateOptions(rawOptions);
438
+ const statePath = absolute(options.state || options.statePath || "");
439
+ if (!options.state && !options.statePath) throw new RunnerError("INVALID_ARGUMENTS", "state path is required");
440
+ const state = loadRunState(statePath);
441
+ const workflowPath = absolute(options.workflow || state.workflow.path);
442
+ if (workflowPath !== state.workflow.path) {
443
+ throw new RunnerError("WORKFLOW_CHANGED", "Continue must use the workflow recorded in run state");
444
+ }
445
+ const document = readWorkflow(workflowPath);
446
+ if (workflowDigest(workflowPath) !== state.workflow.sha256) {
447
+ throw new RunnerError("WORKFLOW_CHANGED", `Workflow sha256 does not match run ${state.run_id}`);
448
+ }
449
+ const production = productionWorkflow(document);
450
+ const context = {
451
+ statePath,
452
+ state,
453
+ doc: document,
454
+ production,
455
+ graph: buildGraph(document, { profile: state.profile }),
456
+ ledgerPath: absolute(options.ledger || state.paths.ledger),
457
+ runDir: state.paths.run_dir,
458
+ logicReport: absolute(options.logicReport || state.paths.logic_report),
459
+ logicState: absolute(options.logicState || state.paths.logic_state),
460
+ executorCommand: options.executorCommand !== undefined ? options.executorCommand : state.executor.command,
461
+ executorTimeoutMs: options.executorTimeoutMs !== undefined ? options.executorTimeoutMs : state.executor.timeout_ms,
462
+ };
463
+ state.pending_ledger ||= [];
464
+ state.pending_after_terminal ||= [];
465
+ state.warnings ||= [];
466
+ if (production && options.logicReport === undefined && options.logicState === undefined) refreshProductionPaths(context);
467
+ return context;
468
+ }
469
+
470
+ function currentRunInfo(records, runId, { allowMissing = false } = {}) {
471
+ let start = -1;
472
+ let latestStart = -1;
473
+ for (let index = 0; index < records.length; index++) {
474
+ if (records[index].event === "run_start") {
475
+ latestStart = index;
476
+ if (records[index].run_id === runId) start = index;
477
+ }
478
+ }
479
+ if (start < 0 && allowMissing) return { start: -1, records: [], missing: true };
480
+ if (start < 0) throw new RunnerError("RUN_START_MISSING", `Ledger has no run_start for ${runId}`, 3);
481
+ if (latestStart !== start) throw new RunnerError("RUN_NOT_CURRENT", `Run ${runId} is not the latest ledger run`, 3);
482
+ return { start, records: records.slice(start + 1), missing: false };
483
+ }
484
+
485
+ function attemptFile(context, attempt) {
486
+ return attempt.attempt_path || path.join(context.runDir, "attempts", `${attempt.file_id || attempt.attempt_id.replace(/[^A-Za-z0-9_.-]/g, "_")}.json`);
487
+ }
488
+
489
+ function persistAttempt(context, attempt) {
490
+ attempt.updated_at = stamp();
491
+ writeJsonAtomic(attemptFile(context, attempt), attempt);
492
+ }
493
+
494
+ function findAttempt(state, attemptId) {
495
+ return state.attempts.find((attempt) => attempt.attempt_id === attemptId);
496
+ }
497
+
498
+ function applyTerminal(context, record, attemptId) {
499
+ const node = context.state.nodes[record.node];
500
+ if (!node) throw new RunnerError("LEDGER_STATE_CONFLICT", `Ledger names unknown node ${record.node}`, 3);
501
+ node.status = record.status;
502
+ node.reason = record.reason || "";
503
+ node.completed_at = record.at || stamp();
504
+ if (record.started_at) node.started_at = record.started_at;
505
+ if (record.duration_s !== undefined) node.duration_s = record.duration_s;
506
+ delete node.error;
507
+ if (attemptId) {
508
+ const attempt = findAttempt(context.state, attemptId);
509
+ if (attempt) {
510
+ attempt.status = record.status === "failed" ? "failed" : "done";
511
+ persistAttempt(context, attempt);
512
+ }
513
+ }
514
+ }
515
+
516
+ function runAfterTerminal(context) {
517
+ const pending = context.state.pending_after_terminal || [];
518
+ while (pending.length) {
519
+ const item = pending[0];
520
+ const node = context.graph.byId.get(item.node);
521
+ let warning = "";
522
+ try {
523
+ if (item.action !== "resume_summary") throw new Error(`unsupported after_terminal action: ${item.action}`);
524
+ const script = path.join(path.dirname(fileURLToPath(import.meta.url)), "write_resume_summary.mjs");
525
+ const args = [script, "--work", context.state.vars.WORK, "--node", item.node,
526
+ "--status", item.status, "--ledger", context.ledgerPath];
527
+ if (item.node === "enrich.spec_gen") args.push("--run-dir", context.state.vars.RUN_DIR || "");
528
+ else args.push("--hmos", context.state.vars.HMOS || "");
529
+ const outcome = spawnSync(process.execPath, args, {
530
+ cwd: context.runDir,
531
+ env: process.env,
532
+ shell: false,
533
+ windowsHide: true,
534
+ encoding: "utf8",
535
+ maxBuffer: 1024 * 1024,
536
+ });
537
+ if (outcome.error || outcome.status !== 0) {
538
+ warning = `after_terminal ${item.node}: ${outcome.error?.message || stderrExcerpt(outcome.stderr) || `exit ${outcome.status}`}`;
539
+ }
540
+ } catch (error) {
541
+ warning = `after_terminal ${item.node}: ${String(error?.message || error)}`;
542
+ }
543
+ pending.shift();
544
+ if (warning) context.state.warnings.push({ at: stamp(), node: item.node, message: warning });
545
+ saveState(context);
546
+ }
547
+ }
548
+
549
+ function queueAfterTerminal(context, nodeId, status) {
550
+ const action = context.graph.byId.get(nodeId)?.runner?.after_terminal;
551
+ if (!action) return;
552
+ if (context.state.pending_after_terminal.some((item) => item.node === nodeId && item.status === status && item.action === action)) return;
553
+ context.state.pending_after_terminal.push({ node: nodeId, status, action });
554
+ saveState(context);
555
+ }
556
+
557
+ function runStartRecord(context) {
558
+ return {
559
+ event: "run_start",
560
+ run_id: context.state.run_id,
561
+ profile: context.state.profile,
562
+ from_node: context.state.resume_from || "bootstrap",
563
+ resume: Boolean(context.state.resume),
564
+ ...(context.state.vars.SPEC_ENGINE ? { spec_engine: context.state.vars.SPEC_ENGINE } : {}),
565
+ };
566
+ }
567
+
568
+ function flushPendingLedger(context) {
569
+ if (!context.state.ledger_started) return;
570
+ const records = readLedger(context.ledgerPath);
571
+ const run = currentRunInfo(records, context.state.run_id);
572
+ for (const pending of context.state.pending_ledger) {
573
+ const existing = run.records.filter((record) => record.event === "node" && record.node === pending.node
574
+ && (record.generation || 0) === (pending.generation || 0)).at(-1);
575
+ if (existing) {
576
+ if (existing.status !== pending.status || (existing.reason || "") !== (pending.reason || "")) {
577
+ throw new RunnerError("LEDGER_STATE_CONFLICT", `Ledger already has a different terminal state for ${pending.node}`, 3);
578
+ }
579
+ } else {
580
+ const { after_terminal: _afterTerminal, ...record } = pending;
581
+ appendLedger(context.ledgerPath, { event: "node", ...record });
582
+ }
583
+ if (pending.after_terminal) queueAfterTerminal(context, pending.node, pending.status);
584
+ }
585
+ context.state.pending_ledger = [];
586
+ saveState(context);
587
+ runAfterTerminal(context);
588
+ }
589
+
590
+ function startProductionLedger(context) {
591
+ if (context.state.ledger_started) return;
592
+ appendLedger(context.ledgerPath, runStartRecord(context));
593
+ context.state.ledger_started = true;
594
+ saveState(context);
595
+ flushPendingLedger(context);
596
+ }
597
+
598
+ function commitTerminal(context, nodeId, status, reason = "", attemptId = "") {
599
+ if (!TERMINAL.has(status)) throw new RunnerError("INVALID_NODE_STATUS", `Not a ledger terminal status: ${status}`, 3);
600
+ const current = context.state.nodes[nodeId];
601
+ if (!current) throw new RunnerError("INVALID_NODE", `Unknown node ${nodeId}`);
602
+ if (TERMINAL.has(current.status)) {
603
+ if (current.status === status && (current.reason || "") === (reason || "")) return current;
604
+ throw new RunnerError("LEDGER_STATE_CONFLICT", `${nodeId} is already terminal ${current.status}`, 3);
605
+ }
606
+ if (context.production && nodeId === "boot.workspace" && !context.state.ledger_started) startProductionLedger(context);
607
+ const at = new Date();
608
+ const attempt = attemptId ? findAttempt(context.state, attemptId) : null;
609
+ const timing = startedFields(readLedger(context.ledgerPath), nodeId, attempt?.started_at || "", at);
610
+ const afterTerminal = context.graph.byId.get(nodeId)?.runner?.after_terminal || "";
611
+ const commit = {
612
+ run_id: context.state.run_id,
613
+ node: nodeId,
614
+ status,
615
+ generation: current.generation || 0,
616
+ ...(reason ? { reason } : {}),
617
+ ...(attemptId ? { attempt_id: attemptId } : {}),
618
+ ...timing,
619
+ ...(afterTerminal ? { after_terminal: afterTerminal } : {}),
620
+ };
621
+ if (context.production && !context.state.ledger_started) {
622
+ context.state.pending_ledger.push(commit);
623
+ const terminalRecord = { ...commit, at: at.toISOString() };
624
+ applyTerminal(context, terminalRecord, attemptId);
625
+ saveState(context);
626
+ return terminalRecord;
627
+ }
628
+
629
+ context.state.ledger_commit = commit;
630
+ saveState(context);
631
+ const { after_terminal: _afterTerminal, ...record } = commit;
632
+ appendLedger(context.ledgerPath, { event: "node", ...record }, at);
633
+ const terminalRecord = { ...commit, at: at.toISOString() };
634
+ applyTerminal(context, terminalRecord, attemptId);
635
+ context.state.ledger_commit = null;
636
+ saveState(context);
637
+ if (afterTerminal) queueAfterTerminal(context, nodeId, status);
638
+ runAfterTerminal(context);
639
+ return terminalRecord;
640
+ }
641
+
642
+ function hardFailurePolicy(context, nodeId) {
643
+ return context.doc.fail_matrix?.[nodeId] || context.doc.nodes.find((node) => node.id === nodeId)?.on_fail || "hard_stop";
644
+ }
645
+
646
+ function recoverContext(context) {
647
+ const original = JSON.stringify(context.state);
648
+ let records = readLedger(context.ledgerPath);
649
+ let run = currentRunInfo(records, context.state.run_id, {
650
+ allowMissing: Boolean(context.production && !context.state.ledger_started),
651
+ });
652
+ if (context.production && !run.missing && !context.state.ledger_started) {
653
+ context.state.ledger_started = true;
654
+ saveState(context);
655
+ }
656
+ if (context.production && context.state.ledger_started && context.state.pending_ledger.length) {
657
+ flushPendingLedger(context);
658
+ records = readLedger(context.ledgerPath);
659
+ run = currentRunInfo(records, context.state.run_id);
660
+ }
661
+
662
+ if (context.state.ledger_commit && !run.missing) {
663
+ const commit = context.state.ledger_commit;
664
+ const existing = run.records.filter((record) => record.event === "node" && record.node === commit.node
665
+ && (record.generation || 0) === (commit.generation || 0)).at(-1);
666
+ if (existing) {
667
+ if (existing.status !== commit.status || (existing.reason || "") !== (commit.reason || "")) {
668
+ throw new RunnerError(
669
+ "LEDGER_STATE_CONFLICT",
670
+ `Pending commit for ${commit.node} is ${commit.status}, but ledger already has ${existing.status}`,
671
+ 3,
672
+ );
673
+ }
674
+ applyTerminal(context, existing, commit.attempt_id);
675
+ } else {
676
+ const at = new Date();
677
+ const { after_terminal: _afterTerminal, ...record } = commit;
678
+ appendLedger(context.ledgerPath, { event: "node", ...record }, at);
679
+ applyTerminal(context, { ...commit, at: at.toISOString() }, commit.attempt_id);
680
+ }
681
+ if (commit.after_terminal) queueAfterTerminal(context, commit.node, commit.status);
682
+ context.state.ledger_commit = null;
683
+ records = readLedger(context.ledgerPath);
684
+ run = currentRunInfo(records, context.state.run_id);
685
+ }
686
+
687
+ const latestByNode = new Map();
688
+ for (const record of run.records) {
689
+ if (record.event !== "node" || !record.node) continue;
690
+ const generation = context.state.nodes[record.node]?.generation || 0;
691
+ if ((record.generation || 0) === generation) latestByNode.set(record.node, record);
692
+ }
693
+ for (const [nodeId, nodeState] of Object.entries(context.state.nodes)) {
694
+ const record = latestByNode.get(nodeId);
695
+ if (record) {
696
+ if (nodeState.status !== record.status || (nodeState.reason || "") !== (record.reason || "")) {
697
+ applyTerminal(context, record, nodeState.current_attempt_id);
698
+ }
699
+ } else if (!run.missing && TERMINAL.has(nodeState.status) && !run.records.some((item) => item.event === "run_end")) {
700
+ const at = new Date();
701
+ appendLedger(context.ledgerPath, {
702
+ event: "node",
703
+ run_id: context.state.run_id,
704
+ node: nodeId,
705
+ status: nodeState.status,
706
+ generation: nodeState.generation || 0,
707
+ ...(nodeState.reason ? { reason: nodeState.reason } : {}),
708
+ ...(nodeState.started_at ? { started_at: nodeState.started_at } : {}),
709
+ ...(nodeState.duration_s !== undefined ? { duration_s: nodeState.duration_s } : {}),
710
+ }, at);
711
+ latestByNode.set(nodeId, { node: nodeId, status: nodeState.status, reason: nodeState.reason || "", at: at.toISOString() });
712
+ if (context.graph.byId.get(nodeId)?.runner?.after_terminal) queueAfterTerminal(context, nodeId, nodeState.status);
713
+ }
714
+ }
715
+
716
+ const runEnd = run.records.filter((record) => record.event === "run_end").at(-1);
717
+ if (runEnd) {
718
+ context.state.status = runEnd.status;
719
+ context.state.current_node = null;
720
+ context.state.ledger_commit = null;
721
+ } else {
722
+ for (const [nodeId, record] of latestByNode) {
723
+ if (record.status === "failed" && hardFailurePolicy(context, nodeId) !== "soft_continue") {
724
+ context.state.status = "failed";
725
+ context.state.current_node = nodeId;
726
+ context.state.error = { code: "HARD_STOP", message: record.reason || `${nodeId} failed`, node: nodeId };
727
+ break;
728
+ }
729
+ }
730
+ }
731
+
732
+ if (context.state.status === "running") {
733
+ for (const [nodeId, nodeState] of Object.entries(context.state.nodes)) {
734
+ if (nodeState.status === "running") {
735
+ const attempt = findAttempt(context.state, nodeState.current_attempt_id);
736
+ if (attempt && ACTIVE_ATTEMPT.has(attempt.status) && attempt.result_path && fs.existsSync(attempt.result_path)) {
737
+ const node = context.doc.nodes.find((candidate) => candidate.id === nodeId);
738
+ if (!node) throw new RunnerError("INVALID_ATTEMPT", `Attempt names unknown node ${attempt.node}`);
739
+ try {
740
+ const result = readExecutorResult(attempt.result_path, attempt.attempt_id);
741
+ processResult(context, node, attempt, result);
742
+ } catch (error) {
743
+ block(context, nodeId, error.code || "RUNNER_INTERNAL_ERROR", String(error?.message || error), attempt);
744
+ }
745
+ continue;
746
+ }
747
+ const reason = "Previous runner stopped while this node was running; continue creates a new attempt";
748
+ nodeState.status = "blocked";
749
+ nodeState.error = { code: "RUNNER_INTERRUPTED", message: reason };
750
+ context.state.status = "blocked";
751
+ context.state.current_node = nodeId;
752
+ context.state.error = { code: "RUNNER_INTERRUPTED", message: reason, node: nodeId };
753
+ if (attempt && ACTIVE_ATTEMPT.has(attempt.status)) {
754
+ attempt.status = "blocked";
755
+ attempt.error = nodeState.error;
756
+ persistAttempt(context, attempt);
757
+ }
758
+ break;
759
+ }
760
+ }
761
+ }
762
+ if (context.state.ledger_started && context.state.pending_after_terminal.length) runAfterTerminal(context);
763
+ if (JSON.stringify(context.state) !== original) saveState(context);
764
+ return context.state;
765
+ }
766
+
767
+ export function recover(options) {
768
+ const normalized = normalizeStateOptions(options);
769
+ const statePath = absolute(normalized.state || normalized.statePath || "");
770
+ return withLock(statePath, () => recoverContext(loadContext(normalized)));
771
+ }
772
+
773
+ function block(context, nodeId, code, message, attempt) {
774
+ context.state.status = "blocked";
775
+ context.state.current_node = nodeId || context.state.current_node;
776
+ context.state.error = { code, message, ...(nodeId ? { node: nodeId } : {}) };
777
+ if (nodeId && !TERMINAL.has(context.state.nodes[nodeId]?.status)) {
778
+ context.state.nodes[nodeId].status = "blocked";
779
+ context.state.nodes[nodeId].error = { code, message };
780
+ }
781
+ if (attempt) {
782
+ attempt.status = "blocked";
783
+ attempt.error = { code, message };
784
+ persistAttempt(context, attempt);
785
+ }
786
+ saveState(context);
787
+ return context.state;
788
+ }
789
+
790
+ function retryLimit(node) {
791
+ const retry = node.runner?.retry ?? 0;
792
+ if (!Number.isInteger(retry) || retry < 0) {
793
+ throw new RunnerError("UNSUPPORTED_NODE_ACTION", `runner.retry for ${node.id} must be a non-negative integer`, 3);
794
+ }
795
+ return retry;
796
+ }
797
+
798
+ function logicSkipped(context) {
799
+ if (context.state.vars.SKIP_LOGIC === true) return true;
800
+ if (context.graph.skippedByProfile.has("logic.spec_pipeline")) return true;
801
+ return context.state.nodes["logic.spec_pipeline"]?.status === "skipped";
802
+ }
803
+
804
+ function businessFailure(context, node, attempt, reason) {
805
+ const text = String(reason || "Node failed").trim() || "Node failed";
806
+ if (attempt) {
807
+ attempt.status = "failed";
808
+ attempt.reason = text;
809
+ persistAttempt(context, attempt);
810
+ }
811
+ const nodeState = context.state.nodes[node.id];
812
+ nodeState.last_failure = text;
813
+ const businessFailures = context.state.attempts.filter((candidate) => (
814
+ candidate.node === node.id && candidate.status === "failed"
815
+ )).length;
816
+ const retriesUsed = Math.max(0, businessFailures - 1);
817
+ if (retriesUsed < retryLimit(node)) {
818
+ nodeState.status = "retry_wait";
819
+ context.state.status = "running";
820
+ saveState(context);
821
+ return;
822
+ }
823
+
824
+ const policy = hardFailurePolicy(context, node.id);
825
+ if (node.id === "logic.finalize" && policy === "soft_continue") {
826
+ block(context, node.id, "FINALIZE_FAILED", text, attempt);
827
+ return;
828
+ }
829
+ if (policy === "soft_continue") {
830
+ commitTerminal(context, node.id, "failed", text, attempt?.attempt_id);
831
+ context.state.status = "running";
832
+ } else if (policy === "hard_stop_unless_logic_skipped" && logicSkipped(context)) {
833
+ commitTerminal(context, node.id, "skipped", text, attempt?.attempt_id);
834
+ context.state.status = "running";
835
+ } else if (policy === "hard_stop" || policy === "hard_stop_unless_logic_skipped") {
836
+ commitTerminal(context, node.id, "failed", text, attempt?.attempt_id);
837
+ context.state.status = "failed";
838
+ context.state.error = { code: "HARD_STOP", message: text, node: node.id };
839
+ if (context.production && !context.state.ledger_started) {
840
+ // run_start is only committed by boot.workspace; a hard stop before it (scaffold_new: discover.arch)
841
+ // leaves this run's terminals in pending_ledger only. A failed run cannot be continued, and
842
+ // run --resume-from would plan from an older or empty ledger, so point the host at a fresh run.
843
+ context.state.error.ledger_started = false;
844
+ context.state.error.hint = "本轮在 boot.workspace 提交 run_start 前就 hard_stop,ledger 里没有本轮记录。"
845
+ + "修复原因后用新的 DAG 控制目录重新 run,不要用 run --resume-from(它会按上一轮或空的 ledger 规划续跑)。";
846
+ }
847
+ } else {
848
+ block(context, node.id, "UNSUPPORTED_FAIL_MATRIX", `Unsupported fail_matrix policy: ${policy}`, attempt);
849
+ return;
850
+ }
851
+ saveState(context);
852
+ }
853
+
854
+ function successContext(context, node) {
855
+ return {
856
+ vars: context.state.vars,
857
+ state: context.state,
858
+ graph: context.graph,
859
+ node,
860
+ nodeState: context.state.nodes[node.id],
861
+ status: context.state.nodes[node.id].status,
862
+ runDir: context.runDir,
863
+ cwd: context.runDir,
864
+ };
865
+ }
866
+
867
+ function processResult(context, node, attempt, result) {
868
+ applySetVars(context, result);
869
+ attempt.result = result;
870
+ attempt.result_path = attempt.result_path || path.join(context.runDir, "attempts", `${attempt.file_id}.result.json`);
871
+ const nodeState = context.state.nodes[node.id];
872
+ if (result.status === "waiting_external" || result.status === "waiting_human") {
873
+ attempt.status = result.status;
874
+ nodeState.status = result.status;
875
+ nodeState.wait = result.wait || null;
876
+ context.state.status = result.status;
877
+ context.state.current_node = node.id;
878
+ if (result.wait) {
879
+ attempt.outbox_path = path.join(context.runDir, "outbox", `${attempt.file_id}.json`);
880
+ writeJsonAtomic(attempt.outbox_path, {
881
+ run_id: context.state.run_id,
882
+ node: node.id,
883
+ attempt_id: attempt.attempt_id,
884
+ status: result.status,
885
+ wait: result.wait,
886
+ request_path: attempt.request_path,
887
+ result_path: attempt.result_path,
888
+ });
889
+ }
890
+ persistAttempt(context, attempt);
891
+ saveState(context);
892
+ return;
893
+ }
894
+ if (result.status === "failed") {
895
+ persistAttempt(context, attempt);
896
+ businessFailure(context, node, attempt, result.reason);
897
+ return;
898
+ }
899
+ if (result.status !== "done") {
900
+ throw new ExecutorProtocolError("EXECUTOR_INVALID_RESULT", `Unsupported executor status: ${result.status}`);
901
+ }
902
+
903
+ nodeState.status = "running";
904
+ nodeState.wait = null;
905
+ context.state.status = "running";
906
+ const passed = evaluateSuccess(node.success, successContext(context, node));
907
+ if (!passed) {
908
+ businessFailure(context, node, attempt, "Executor completed but artifact success rules were not satisfied");
909
+ return;
910
+ }
911
+ attempt.status = "done";
912
+ persistAttempt(context, attempt);
913
+ commitTerminal(context, node.id, "done", "", attempt.attempt_id);
914
+ context.state.status = "running";
915
+ saveState(context);
916
+ }
917
+
918
+ function validateNodeAction(node) {
919
+ const action = node.runner?.action || "external";
920
+ if (action !== "production") {
921
+ for (const key of UNSUPPORTED_LIFECYCLE) {
922
+ if (Object.prototype.hasOwnProperty.call(node, key) && node[key] != null) {
923
+ throw new RunnerError("UNSUPPORTED_NODE_ACTION", `${node.id}: ${key} is not supported by the deterministic runner`, 3);
924
+ }
925
+ }
926
+ }
927
+ if (!["external", "script", "production"].includes(action)) {
928
+ throw new RunnerError("UNSUPPORTED_NODE_ACTION", `${node.id}: unsupported runner.action ${action}`, 3);
929
+ }
930
+ if (action === "production" && !node.runner?.kind) {
931
+ throw new RunnerError("UNSUPPORTED_NODE_ACTION", `${node.id}: production runner.kind is required`, 3);
932
+ }
933
+ retryLimit(node);
934
+ return action;
935
+ }
936
+
937
+ function newAttempt(context, node) {
938
+ const nodeState = context.state.nodes[node.id];
939
+ const previous = findAttempt(context.state, nodeState.current_attempt_id);
940
+ const index = nodeState.attempt_count + 1;
941
+ const attemptId = `${context.state.run_id}:${node.id}:${index}`;
942
+ const fileId = `${context.state.run_id.replace(/[^A-Za-z0-9_.-]/g, "_")}-${node.id.replace(/[^A-Za-z0-9_.-]/g, "_")}-${index}`;
943
+ const attempt = {
944
+ attempt_id: attemptId,
945
+ file_id: fileId,
946
+ node: node.id,
947
+ index,
948
+ generation: nodeState.generation || 0,
949
+ status: "running",
950
+ started_at: stamp(),
951
+ request_path: path.join(context.runDir, "attempts", `${fileId}.request.json`),
952
+ result_path: path.join(context.runDir, "attempts", `${fileId}.result.json`),
953
+ };
954
+ attempt.attempt_path = path.join(context.runDir, "attempts", `${fileId}.attempt.json`);
955
+ if (context.production && previous?.error?.code === "RUNNER_INTERRUPTED"
956
+ && (previous.generation || 0) === (nodeState.generation || 0)) {
957
+ attempt.resume_from_attempt = previous.file_id || previous.attempt_id;
958
+ }
959
+ context.state.attempts.push(attempt);
960
+ nodeState.attempt_count = index;
961
+ nodeState.current_attempt_id = attemptId;
962
+ nodeState.status = "running";
963
+ delete nodeState.error;
964
+ delete nodeState.started_at;
965
+ delete nodeState.duration_s;
966
+ context.state.current_node = node.id;
967
+ context.state.status = "running";
968
+ delete context.state.error;
969
+ persistAttempt(context, attempt);
970
+ saveState(context);
971
+ if (context.state.ledger_started) {
972
+ appendLedger(context.ledgerPath, {
973
+ event: "node_start",
974
+ run_id: context.state.run_id,
975
+ node: node.id,
976
+ attempt_id: attemptId,
977
+ generation: attempt.generation,
978
+ }, new Date(attempt.started_at));
979
+ }
980
+ return attempt;
981
+ }
982
+
983
+ function stderrExcerpt(value) {
984
+ const text = String(value || "").trim();
985
+ return text.length <= STDERR_LIMIT ? text : `...${text.slice(-STDERR_LIMIT)}`;
986
+ }
987
+
988
+ function executorRequest(context, node, attempt, extra = {}) {
989
+ return {
990
+ run_id: context.state.run_id,
991
+ node: node.id,
992
+ node_id: node.id,
993
+ node_definition: node,
994
+ node_state: context.state.nodes[node.id],
995
+ runner: node.runner || { action: "external" },
996
+ invoke: node.invoke ?? null,
997
+ vars: context.state.vars,
998
+ paths: {
999
+ dag_run_dir: context.runDir,
1000
+ run_dir: context.state.vars.RUN_DIR || "",
1001
+ work: context.state.vars.WORK || "",
1002
+ hmos: context.state.vars.HMOS || "",
1003
+ ledger: context.ledgerPath,
1004
+ state_path: context.statePath,
1005
+ logic_report: context.logicReport,
1006
+ logic_state: context.logicState,
1007
+ },
1008
+ attempt_id: attempt.attempt_id,
1009
+ attempt,
1010
+ request_path: attempt.request_path,
1011
+ result_path: attempt.result_path,
1012
+ ...extra,
1013
+ };
1014
+ }
1015
+
1016
+ async function runNodeScript(context, node, attempt) {
1017
+ const runner = node.runner;
1018
+ if (!runner?.script || typeof runner.script !== "string") {
1019
+ throw new RunnerError("UNSUPPORTED_NODE_ACTION", `${node.id}: runner.script is required for action=script`, 3);
1020
+ }
1021
+ let args;
1022
+ try {
1023
+ args = splitArgs(runner.args).map((item) => expand(item, context.state.vars));
1024
+ } catch (error) {
1025
+ throw new RunnerError("UNSUPPORTED_NODE_ACTION", `${node.id}: ${error.message}`, 3, error);
1026
+ }
1027
+ const script = resolveArtifact(runner.script, { vars: context.state.vars, runDir: context.runDir });
1028
+ const request = executorRequest(context, node, attempt);
1029
+ writeJsonAtomic(attempt.request_path, request);
1030
+ const outcome = await new Promise((resolve, reject) => {
1031
+ let child;
1032
+ try {
1033
+ child = spawn(process.execPath, [script, ...args], {
1034
+ cwd: runner.cwd ? resolveArtifact(runner.cwd, { vars: context.state.vars, runDir: context.runDir }) : context.runDir,
1035
+ env: process.env,
1036
+ shell: false,
1037
+ windowsHide: true,
1038
+ });
1039
+ } catch (error) {
1040
+ reject(new ExecutorProtocolError("EXECUTOR_SPAWN_FAILED", "Unable to start node script", error));
1041
+ return;
1042
+ }
1043
+ let stdout = "";
1044
+ let stderr = "";
1045
+ let timedOut = false;
1046
+ let timer;
1047
+ child.stdout?.setEncoding("utf8");
1048
+ child.stderr?.setEncoding("utf8");
1049
+ child.stdout?.on("data", (chunk) => { stdout += chunk; });
1050
+ child.stderr?.on("data", (chunk) => { stderr += chunk; });
1051
+ child.once("error", (error) => reject(new ExecutorProtocolError("EXECUTOR_SPAWN_FAILED", "Unable to start node script", error)));
1052
+ child.once("close", (code, signal) => {
1053
+ if (timer) clearTimeout(timer);
1054
+ if (timedOut) reject(new ExecutorProtocolError("EXECUTOR_TIMEOUT", `Node script exceeded timeout of ${context.executorTimeoutMs} ms`));
1055
+ else resolve({ code, signal, stdout, stderr });
1056
+ });
1057
+ if (context.executorTimeoutMs > 0) {
1058
+ timer = setTimeout(() => {
1059
+ timedOut = true;
1060
+ child.kill();
1061
+ }, context.executorTimeoutMs);
1062
+ }
1063
+ });
1064
+ const result = outcome.code === 0
1065
+ ? { status: "done", attempt_id: attempt.attempt_id }
1066
+ : {
1067
+ status: "failed",
1068
+ attempt_id: attempt.attempt_id,
1069
+ reason: `Script exited with ${outcome.signal ? `signal ${outcome.signal}` : `code ${outcome.code}`}${stderrExcerpt(outcome.stderr) ? `: ${stderrExcerpt(outcome.stderr)}` : ""}`,
1070
+ };
1071
+ writeJsonAtomic(attempt.result_path, result);
1072
+ return result;
1073
+ }
1074
+
1075
+ async function executeNode(context, node) {
1076
+ let attempt;
1077
+ try {
1078
+ if (node.skip_if && evaluateExpression(String(node.skip_if), context.state.vars)) {
1079
+ commitTerminal(context, node.id, "skipped", "skip_if");
1080
+ context.state.status = "running";
1081
+ saveState(context);
1082
+ return;
1083
+ }
1084
+ if (node.runner?.reuse_if && evaluateExpression(String(node.runner.reuse_if), context.state.vars)) {
1085
+ commitTerminal(context, node.id, "reused", "runner.reuse_if");
1086
+ context.state.status = "running";
1087
+ saveState(context);
1088
+ return;
1089
+ }
1090
+
1091
+ const action = validateNodeAction(node);
1092
+ attempt = newAttempt(context, node);
1093
+ let result;
1094
+ if (action === "script") {
1095
+ result = await runNodeScript(context, node, attempt);
1096
+ } else if (action === "production" && node.runner.kind === "barrier") {
1097
+ result = { status: "done", attempt_id: attempt.attempt_id, evidence: { all_needs_terminal: true } };
1098
+ writeJsonAtomic(attempt.result_path, result);
1099
+ } else {
1100
+ const request = executorRequest(context, node, attempt);
1101
+ const executed = await runProcessExecutor({
1102
+ command: context.executorCommand,
1103
+ request,
1104
+ requestPath: attempt.request_path,
1105
+ resultPath: attempt.result_path,
1106
+ cwd: context.runDir,
1107
+ timeoutMs: context.executorTimeoutMs,
1108
+ });
1109
+ result = executed.result;
1110
+ attempt.stdout = executed.stdout;
1111
+ attempt.stderr = executed.stderr;
1112
+ }
1113
+ processResult(context, node, attempt, result);
1114
+ } catch (error) {
1115
+ if (error instanceof ExecutorProtocolError) {
1116
+ block(context, node.id, error.code || "EXECUTOR_PROTOCOL_ERROR", error.message, attempt);
1117
+ return;
1118
+ }
1119
+ if (error instanceof RunnerError) {
1120
+ block(context, node.id, error.code || "RUNNER_ERROR", error.message, attempt);
1121
+ return;
1122
+ }
1123
+ block(context, node.id, "RUNNER_INTERNAL_ERROR", String(error?.message || error), attempt);
1124
+ }
1125
+ }
1126
+
1127
+ function evaluationDocument(context) {
1128
+ return {
1129
+ ...context.doc,
1130
+ nodes: context.doc.nodes.map((node) => (
1131
+ node.runner?.reuse_if && !node.skip_if ? { ...node, skip_if: node.runner.reuse_if } : node
1132
+ )),
1133
+ };
1134
+ }
1135
+
1136
+ function finalizeRun(context) {
1137
+ const active = context.doc.nodes.filter((node) => context.graph.activeIds.has(node.id));
1138
+ if (!active.every((node) => TERMINAL.has(context.state.nodes[node.id]?.status))) return false;
1139
+ const evaluated = evaluateDag(evaluationDocument(context), readLedger(context.ledgerPath), {
1140
+ profile: context.state.profile,
1141
+ logicReport: context.logicReport,
1142
+ state: context.logicState,
1143
+ });
1144
+ if (evaluated.code === 0) {
1145
+ if (!evaluated.summary.run_end) {
1146
+ appendLedger(context.ledgerPath, {
1147
+ event: "run_end",
1148
+ run_id: context.state.run_id,
1149
+ status: evaluated.summary.status,
1150
+ failed_nodes: evaluated.summary.failed_soft.map((failure) => failure.node),
1151
+ });
1152
+ }
1153
+ const certified = evaluateDag(evaluationDocument(context), readLedger(context.ledgerPath), {
1154
+ profile: context.state.profile,
1155
+ logicReport: context.logicReport,
1156
+ state: context.logicState,
1157
+ });
1158
+ if (certified.code !== 0 || !certified.summary.run_end) {
1159
+ context.state.status = "blocked";
1160
+ context.state.current_node = "logic.finalize";
1161
+ context.state.error = { code: "INVALID_COMPLETION_EVIDENCE", message: "run_end certification did not pass its idempotent recheck" };
1162
+ saveState(context);
1163
+ return true;
1164
+ }
1165
+ context.state.status = certified.summary.status;
1166
+ context.state.current_node = null;
1167
+ delete context.state.error;
1168
+ saveState(context);
1169
+ return true;
1170
+ }
1171
+ if (evaluated.code === 3) {
1172
+ context.state.status = "failed";
1173
+ context.state.error = { code: "HARD_STOP", message: evaluated.summary.error || "DAG has a hard-stop failure" };
1174
+ } else {
1175
+ const nodeId = context.graph.activeIds.has("logic.finalize") ? "logic.finalize" : context.state.current_node;
1176
+ context.state.status = "blocked";
1177
+ context.state.current_node = nodeId || null;
1178
+ context.state.error = {
1179
+ code: evaluated.code === 2 ? "INVALID_COMPLETION_EVIDENCE" : "DAG_INCOMPLETE",
1180
+ message: evaluated.summary.error || evaluated.summary.reason || "DAG completion evidence is incomplete",
1181
+ ...(nodeId ? { node: nodeId } : {}),
1182
+ };
1183
+ }
1184
+ saveState(context);
1185
+ return true;
1186
+ }
1187
+
1188
+ async function advanceLoop(context) {
1189
+ for (;;) {
1190
+ if (["completed", "completed_with_failures", "failed", "blocked", "waiting_external", "waiting_human"].includes(context.state.status)) {
1191
+ return context.state;
1192
+ }
1193
+ const active = context.doc.nodes.filter((node) => context.graph.activeIds.has(node.id));
1194
+ if (active.every((node) => TERMINAL.has(context.state.nodes[node.id]?.status))) {
1195
+ finalizeRun(context);
1196
+ return context.state;
1197
+ }
1198
+ let candidates;
1199
+ try {
1200
+ candidates = readyNodes(context.graph, context.state.nodes, context.state.vars);
1201
+ } catch (error) {
1202
+ const nodeId = active.find((node) => !TERMINAL.has(context.state.nodes[node.id]?.status))?.id || null;
1203
+ return block(context, nodeId, error.code || "RUNNER_INTERNAL_ERROR", String(error?.message || error));
1204
+ }
1205
+ const next = candidates.find((node) => (
1206
+ ["pending", "retry_wait"].includes(context.state.nodes[node.id]?.status)
1207
+ ));
1208
+ if (!next) {
1209
+ context.state.status = "running";
1210
+ saveState(context);
1211
+ return context.state;
1212
+ }
1213
+ await executeNode(context, next);
1214
+ }
1215
+ }
1216
+
1217
+ function resumeBlocked(context) {
1218
+ if (context.state.status !== "blocked") return;
1219
+ const nodeId = context.state.current_node;
1220
+ if (nodeId && TERMINAL.has(context.state.nodes[nodeId]?.status)) {
1221
+ context.state.status = "running";
1222
+ delete context.state.error;
1223
+ saveState(context);
1224
+ return;
1225
+ }
1226
+ if (nodeId && context.state.nodes[nodeId]?.status === "blocked") {
1227
+ context.state.nodes[nodeId].status = "retry_wait";
1228
+ delete context.state.nodes[nodeId].error;
1229
+ context.state.status = "running";
1230
+ delete context.state.error;
1231
+ saveState(context);
1232
+ }
1233
+ }
1234
+
1235
+ function probeEntries(document) {
1236
+ const bootstrap = document.nodes.find((node) => node.id === "bootstrap");
1237
+ const actions = bootstrap?.actions || [];
1238
+ return actions.map((action) => action.probe_all_artifacts).find(Boolean)?.entries || {};
1239
+ }
1240
+
1241
+ function probeComplete(probe, context) {
1242
+ if (!probe) return false;
1243
+ const files = probe.all || probe.any || [];
1244
+ const fileRules = files.map((file) => ({ file_exists: file }));
1245
+ const filePass = probe.all ? fileRules.every((rule) => evaluateSuccess(rule, context)) : fileRules.some((rule) => evaluateSuccess(rule, context));
1246
+ if (!filePass) return false;
1247
+ return probe.check ? evaluateSuccess({ script_exit_0: probe.check }, context) : true;
1248
+ }
1249
+
1250
+ function applyResumePlan(context, plan) {
1251
+ const probes = probeEntries(context.doc);
1252
+ const probeContext = successContext(context, context.doc.nodes.find((node) => node.id === "bootstrap") || {});
1253
+ for (const [name, value] of Object.entries(plan.reuse || {})) {
1254
+ if (value !== "probe") context.state.vars[name] = value;
1255
+ }
1256
+ for (const [name, value] of Object.entries(plan.reuse || {})) {
1257
+ if (value === "probe") {
1258
+ const wanted = (plan.reuse_if_complete || []).filter((entry) => entry.var === name);
1259
+ context.state.vars[name] = wanted.length > 0 && wanted.every((entry) => probeComplete(probes[entry.probe], probeContext));
1260
+ }
1261
+ }
1262
+ return (plan.require_probes || []).filter((id) => !probeComplete(probes[id], probeContext));
1263
+ }
1264
+
1265
+ export function startRun(rawOptions) {
1266
+ const options = normalizeStateOptions(rawOptions);
1267
+ const runDir = absolute(options.runDir || options.run_dir || "");
1268
+ if (!options.runDir && !options.run_dir) throw new RunnerError("INVALID_ARGUMENTS", "runDir is required");
1269
+ const workflowPath = absolute(options.workflow || "");
1270
+ if (!options.workflow) throw new RunnerError("INVALID_ARGUMENTS", "workflow is required");
1271
+ const statePath = absolute(options.state || path.join(runDir, "dag-run-state.json"));
1272
+ return withLock(statePath, () => {
1273
+ if (fs.existsSync(statePath)) throw new RunnerError("RUN_STATE_EXISTS", `Run state already exists: ${statePath}`);
1274
+ const document = readWorkflow(workflowPath);
1275
+ const vars = options.vars || {};
1276
+ if (!vars || typeof vars !== "object" || Array.isArray(vars)) {
1277
+ throw new RunnerError("INVALID_ARGUMENTS", "vars must be a JSON object");
1278
+ }
1279
+ const production = productionWorkflow(document);
1280
+ let profile = options.profile || vars.PROFILE || "full";
1281
+ const initialVars = production ? workflowVars(document, vars, profile) : vars;
1282
+ const ledgerPath = absolute(options.ledger || (production ? initialVars.LEDGER : path.join(runDir, "stage-ledger.jsonl")));
1283
+ let resumePlan = null;
1284
+ const resumeFrom = options.resumeFrom || options.resume_from || "";
1285
+ if (resumeFrom) {
1286
+ try {
1287
+ resumePlan = planResume(document, readLedger(ledgerPath), {
1288
+ fromNode: resumeFrom,
1289
+ baseProfile: options.baseProfile || options.base_profile || "",
1290
+ engine: vars.SPEC_ENGINE || "",
1291
+ engineGiven: Object.prototype.hasOwnProperty.call(vars, "SPEC_ENGINE"),
1292
+ });
1293
+ } catch (error) {
1294
+ throw new RunnerError("RESUME_PLAN_FAILED", error.message, error.code === 3 ? 3 : 2, error);
1295
+ }
1296
+ profile = resumePlan.base_profile;
1297
+ }
1298
+ if (profile === "resume" || !document.profiles?.[profile]) {
1299
+ throw new RunnerError("INVALID_PROFILE", `Unknown concrete workflow profile: ${profile}`);
1300
+ }
1301
+ const graph = buildGraph(document, { profile });
1302
+ const executorTimeoutMs = Number(options.executorTimeoutMs ?? 0);
1303
+ if (!Number.isInteger(executorTimeoutMs) || executorTimeoutMs < 0) {
1304
+ throw new RunnerError("INVALID_ARGUMENTS", "executor timeout must be a non-negative integer");
1305
+ }
1306
+ const runId = `run-${Date.now()}-${randomUUID()}`;
1307
+ const resolvedVars = production ? workflowVars(document, vars, profile) : { ...vars };
1308
+ const allVars = {
1309
+ ...resolvedVars,
1310
+ PROFILE: profile,
1311
+ DAG_RUN_DIR: runDir,
1312
+ RUN_DIR: production ? resolvedVars.RUN_DIR : (vars.RUN_DIR ?? runDir),
1313
+ LEDGER: ledgerPath,
1314
+ DAG_STATE: statePath,
1315
+ WORKFLOW: workflowPath,
1316
+ LOGIC_REPORT: absolute(options.logicReport || (production ? resolvedVars.LOGIC_REPORT : path.join(runDir, "logic-convert-report.md"))),
1317
+ LOGIC_STATE: absolute(options.logicState || (production
1318
+ ? path.join(resolvedVars.HMOS, ".hometrans", "spec_pipeline_state.json")
1319
+ : path.join(runDir, "spec_pipeline_state.json"))),
1320
+ ...(resumePlan ? { SPEC_ENGINE: resumePlan.spec_engine } : {}),
1321
+ };
1322
+ const nodes = Object.fromEntries(document.nodes.map((node) => [node.id, {
1323
+ status: "pending",
1324
+ attempt_count: 0,
1325
+ current_attempt_id: null,
1326
+ reason: "",
1327
+ generation: 0,
1328
+ }]));
1329
+ const state = {
1330
+ schema: SCHEMA,
1331
+ run_id: runId,
1332
+ workflow: { path: workflowPath, sha256: workflowDigest(workflowPath) },
1333
+ profile,
1334
+ vars: allVars,
1335
+ status: "running",
1336
+ current_node: null,
1337
+ nodes,
1338
+ attempts: [],
1339
+ ledger_commit: null,
1340
+ ledger_started: !production,
1341
+ pending_ledger: [],
1342
+ pending_after_terminal: [],
1343
+ warnings: [],
1344
+ resume: Boolean(resumeFrom),
1345
+ resume_from: resumeFrom || "bootstrap",
1346
+ resume_plan: resumePlan,
1347
+ paths: {
1348
+ run_dir: runDir,
1349
+ production_run_dir: production ? allVars.RUN_DIR : "",
1350
+ work: production ? allVars.WORK || "" : "",
1351
+ hmos: production ? allVars.HMOS || "" : "",
1352
+ ledger: ledgerPath,
1353
+ logic_report: allVars.LOGIC_REPORT,
1354
+ logic_state: allVars.LOGIC_STATE,
1355
+ },
1356
+ executor: {
1357
+ command: options.executorCommand || (production
1358
+ ? `"${process.execPath}" "${path.join(path.dirname(fileURLToPath(import.meta.url)), "dag_production_executor.mjs")}"`
1359
+ : ""),
1360
+ timeout_ms: executorTimeoutMs,
1361
+ },
1362
+ updated_at: stamp(),
1363
+ };
1364
+ const context = {
1365
+ state,
1366
+ statePath,
1367
+ doc: document,
1368
+ production,
1369
+ graph,
1370
+ ledgerPath,
1371
+ runDir,
1372
+ logicReport: allVars.LOGIC_REPORT,
1373
+ logicState: allVars.LOGIC_STATE,
1374
+ executorCommand: state.executor.command,
1375
+ executorTimeoutMs: state.executor.timeout_ms,
1376
+ };
1377
+ fs.mkdirSync(runDir, { recursive: true });
1378
+ if (!production) appendLedger(ledgerPath, runStartRecord(context));
1379
+ saveState(context);
1380
+
1381
+ for (const node of document.nodes) {
1382
+ if (graph.skippedByProfile.has(node.id)) commitTerminal(context, node.id, "skipped", "profile_skip");
1383
+ }
1384
+ if (resumePlan) {
1385
+ for (const inherited of resumePlan.inherited || []) {
1386
+ if (!graph.skippedByProfile.has(inherited.node)) {
1387
+ commitTerminal(context, inherited.node, inherited.status, inherited.reason || "resume inherited");
1388
+ }
1389
+ }
1390
+ const missing = applyResumePlan(context, resumePlan);
1391
+ saveState(context);
1392
+ if (missing.length) {
1393
+ const probe = probesForResume(document)[missing[0]];
1394
+ const nodeId = probe?.node || resumeFrom;
1395
+ const reason = `Required resume artifact probe(s) incomplete: ${missing.join(", ")}`;
1396
+ commitTerminal(context, nodeId, "failed", reason);
1397
+ context.state.status = "failed";
1398
+ context.state.current_node = nodeId;
1399
+ context.state.error = { code: "RESUME_PROBE_INCOMPLETE", message: reason, node: nodeId };
1400
+ saveState(context);
1401
+ }
1402
+ }
1403
+ return context.state;
1404
+ });
1405
+ }
1406
+
1407
+ function probesForResume(document) {
1408
+ return probeEntries(document);
1409
+ }
1410
+
1411
+ export function advance(options) {
1412
+ const normalized = normalizeStateOptions(options);
1413
+ const statePath = absolute(normalized.state || normalized.statePath || "");
1414
+ return withLock(statePath, async () => {
1415
+ const context = loadContext(normalized);
1416
+ recoverContext(context);
1417
+ context.executorCommand = normalized.executorCommand !== undefined ? normalized.executorCommand : context.state.executor.command;
1418
+ context.executorTimeoutMs = normalized.executorTimeoutMs !== undefined ? Number(normalized.executorTimeoutMs) : context.state.executor.timeout_ms;
1419
+ if (!Number.isInteger(context.executorTimeoutMs) || context.executorTimeoutMs < 0) {
1420
+ throw new RunnerError("INVALID_ARGUMENTS", "executor timeout must be a non-negative integer");
1421
+ }
1422
+ context.state.executor = { command: context.executorCommand || "", timeout_ms: context.executorTimeoutMs };
1423
+ resumeBlocked(context);
1424
+ return advanceLoop(context);
1425
+ });
1426
+ }
1427
+
1428
+ export function completeAttempt(rawOptions) {
1429
+ const options = normalizeStateOptions(rawOptions);
1430
+ const statePath = absolute(options.state || options.statePath || "");
1431
+ return withLock(statePath, async () => {
1432
+ const context = loadContext(options);
1433
+ recoverContext(context);
1434
+ const attemptId = options.attemptId || options.attempt_id;
1435
+ const attempt = findAttempt(context.state, attemptId);
1436
+ if (!attempt) throw new RunnerError("INVALID_ATTEMPT", `Unknown attempt_id: ${attemptId}`);
1437
+ const nodeState = context.state.nodes[attempt.node];
1438
+ const isCurrent = nodeState?.current_attempt_id === attemptId;
1439
+ if (!isCurrent) {
1440
+ throw new RunnerError("STALE_ATTEMPT", `Attempt ${attemptId} is no longer current for ${attempt.node}`);
1441
+ }
1442
+ if (!ACTIVE_ATTEMPT.has(attempt.status)) {
1443
+ if (context.state.status === "running") await advanceLoop(context);
1444
+ return context.state;
1445
+ }
1446
+ const node = context.doc.nodes.find((candidate) => candidate.id === attempt.node);
1447
+ if (!node) throw new RunnerError("INVALID_ATTEMPT", `Attempt names unknown node ${attempt.node}`);
1448
+ if (context.production && attempt.status === "waiting_human") {
1449
+ throw new RunnerError("HUMAN_CONFIRM_REQUIRED", `${node.id} requires confirm through the production gate executor`, 3);
1450
+ }
1451
+ attempt.result_path = absolute(options.resultFile || options.result_file || attempt.result_path);
1452
+ let result;
1453
+ try {
1454
+ result = readExecutorResult(attempt.result_path, attemptId);
1455
+ } catch (error) {
1456
+ if (error instanceof ExecutorProtocolError) {
1457
+ return block(context, node.id, error.code || "EXECUTOR_PROTOCOL_ERROR", error.message, attempt);
1458
+ }
1459
+ throw error;
1460
+ }
1461
+ try {
1462
+ processResult(context, node, attempt, result);
1463
+ } catch (error) {
1464
+ return block(context, node.id, error.code || "RUNNER_INTERNAL_ERROR", String(error?.message || error), attempt);
1465
+ }
1466
+ if (context.state.status === "running") await advanceLoop(context);
1467
+ return context.state;
1468
+ });
1469
+ }
1470
+
1471
+ export function confirmGate(rawOptions) {
1472
+ const options = normalizeStateOptions(rawOptions);
1473
+ const statePath = absolute(options.state || options.statePath || "");
1474
+ return withLock(statePath, async () => {
1475
+ const context = loadContext(options);
1476
+ recoverContext(context);
1477
+ const nodeId = options.node || options.nodeId;
1478
+ const nodeState = context.state.nodes[nodeId];
1479
+ if (context.state.status !== "waiting_human" || nodeState?.status !== "waiting_human" || context.state.current_node !== nodeId) {
1480
+ throw new RunnerError("INVALID_GATE_STATE", `${nodeId} is not the current waiting_human node`);
1481
+ }
1482
+ const node = context.doc.nodes.find((candidate) => candidate.id === nodeId);
1483
+ const attempt = findAttempt(context.state, nodeState.current_attempt_id);
1484
+ if (!node || !attempt) throw new RunnerError("INVALID_GATE_STATE", `No current attempt for ${nodeId}`);
1485
+ attempt.confirmed_at = stamp();
1486
+ attempt.confirmed_by = options.confirmedBy || "user";
1487
+ try {
1488
+ let result;
1489
+ if (context.production) {
1490
+ const request = executorRequest(context, node, attempt, {
1491
+ confirmation: { confirmed_by: attempt.confirmed_by, confirmed_at: attempt.confirmed_at },
1492
+ });
1493
+ const executed = await runProcessExecutor({
1494
+ command: context.executorCommand,
1495
+ request,
1496
+ requestPath: attempt.request_path,
1497
+ resultPath: attempt.result_path,
1498
+ cwd: context.runDir,
1499
+ timeoutMs: context.executorTimeoutMs,
1500
+ });
1501
+ result = executed.result;
1502
+ attempt.stdout = executed.stdout;
1503
+ attempt.stderr = executed.stderr;
1504
+ } else {
1505
+ result = {
1506
+ status: "done",
1507
+ attempt_id: attempt.attempt_id,
1508
+ evidence: { confirmed: true, confirmed_by: attempt.confirmed_by },
1509
+ };
1510
+ }
1511
+ processResult(context, node, attempt, result);
1512
+ } catch (error) {
1513
+ return block(context, node.id, error.code || "RUNNER_INTERNAL_ERROR", String(error?.message || error), attempt);
1514
+ }
1515
+ if (context.state.status === "running") await advanceLoop(context);
1516
+ return context.state;
1517
+ });
1518
+ }
1519
+
1520
+ export function rewindGate(rawOptions) {
1521
+ const options = normalizeStateOptions(rawOptions);
1522
+ const statePath = absolute(options.state || options.statePath || "");
1523
+ return withLock(statePath, async () => {
1524
+ const context = loadContext(options);
1525
+ recoverContext(context);
1526
+ const gateId = options.node || options.nodeId;
1527
+ const gate = context.graph.byId.get(gateId);
1528
+ const targetId = gate?.runner?.rewind_to;
1529
+ if (!context.production || gate?.runner?.kind !== "gate" || !targetId || !context.graph.byId.has(targetId)) {
1530
+ throw new RunnerError("INVALID_REWIND", `${gateId} does not declare a production rewind target`, 3);
1531
+ }
1532
+ if (["completed", "completed_with_failures"].includes(context.state.status)
1533
+ || readLedger(context.ledgerPath).some((record) => record.run_id === context.state.run_id && record.event === "run_end")) {
1534
+ throw new RunnerError("INVALID_REWIND", "Cannot rewind after run_end", 3);
1535
+ }
1536
+ if (context.state.status !== "waiting_human" || context.state.current_node !== gateId
1537
+ || context.state.nodes[gateId]?.status !== "waiting_human") {
1538
+ throw new RunnerError("INVALID_REWIND", `${gateId} is not the current waiting_human gate`, 3);
1539
+ }
1540
+ // Data edges only: an ordering-only conditional_needs (boot.workspace -> discover.arch) must not drag
1541
+ // already-finished boot.workspace / discover.utg_static back to pending when the user only redoes arch.
1542
+ const affected = rewindAffected(context.graph, targetId);
1543
+ if (!affected.has(gateId)) throw new RunnerError("INVALID_REWIND", `${targetId} is not upstream of ${gateId}`, 3);
1544
+ const gateAttempt = findAttempt(context.state, context.state.nodes[gateId].current_attempt_id);
1545
+ if (gateAttempt) {
1546
+ gateAttempt.status = "rewound";
1547
+ persistAttempt(context, gateAttempt);
1548
+ }
1549
+ for (const id of affected) {
1550
+ const nodeState = context.state.nodes[id];
1551
+ nodeState.status = "pending";
1552
+ nodeState.reason = "";
1553
+ nodeState.error = undefined;
1554
+ nodeState.wait = null;
1555
+ nodeState.current_attempt_id = null;
1556
+ nodeState.generation = (nodeState.generation || 0) + 1;
1557
+ }
1558
+ for (const name of gate.runner.rewind_clear_vars || []) context.state.vars[name] = false;
1559
+ context.state.status = "running";
1560
+ context.state.current_node = targetId;
1561
+ context.state.rewind_count = (context.state.rewind_count || 0) + 1;
1562
+ delete context.state.error;
1563
+ saveState(context);
1564
+ appendLedger(context.ledgerPath, {
1565
+ event: "rewind",
1566
+ run_id: context.state.run_id,
1567
+ node: gateId,
1568
+ target: targetId,
1569
+ generation: context.state.nodes[targetId].generation,
1570
+ });
1571
+ return advanceLoop(context);
1572
+ });
1573
+ }
1574
+
1575
+ function parseCli(argv) {
1576
+ const [command, ...rest] = argv;
1577
+ const args = {};
1578
+ for (let index = 0; index < rest.length; index++) {
1579
+ const token = rest[index];
1580
+ if (!token.startsWith("--")) throw new RunnerError("INVALID_ARGUMENTS", `Unexpected argument: ${token}`);
1581
+ const equal = token.indexOf("=");
1582
+ const rawName = equal >= 0 ? token.slice(2, equal) : token.slice(2);
1583
+ const name = rawName.replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase());
1584
+ let value;
1585
+ if (equal >= 0) {
1586
+ value = token.slice(equal + 1);
1587
+ } else {
1588
+ value = rest[++index];
1589
+ if (value === undefined || value.startsWith("--")) throw new RunnerError("INVALID_ARGUMENTS", `Missing value for --${rawName}`);
1590
+ }
1591
+ args[name] = value;
1592
+ }
1593
+ return { command, args };
1594
+ }
1595
+
1596
+ function cliOptions(args, runCommand) {
1597
+ const options = { ...args };
1598
+ if (args.vars !== undefined) {
1599
+ try {
1600
+ options.vars = JSON.parse(args.vars);
1601
+ } catch (error) {
1602
+ throw new RunnerError("INVALID_ARGUMENTS", `--vars is not valid JSON: ${error.message}`);
1603
+ }
1604
+ if (!options.vars || typeof options.vars !== "object" || Array.isArray(options.vars)) {
1605
+ throw new RunnerError("INVALID_ARGUMENTS", "--vars must be a JSON object");
1606
+ }
1607
+ }
1608
+ if (args.executorTimeoutMs !== undefined) {
1609
+ options.executorTimeoutMs = Number(args.executorTimeoutMs);
1610
+ if (!Number.isInteger(options.executorTimeoutMs) || options.executorTimeoutMs < 0) {
1611
+ throw new RunnerError("INVALID_ARGUMENTS", "--executor-timeout-ms must be a non-negative integer");
1612
+ }
1613
+ }
1614
+ if (runCommand) {
1615
+ if (!args.runDir) throw new RunnerError("INVALID_ARGUMENTS", "run requires --run-dir");
1616
+ options.state = args.state || path.join(absolute(args.runDir), "dag-run-state.json");
1617
+ if (args.ledger) options.ledger = args.ledger;
1618
+ }
1619
+ return options;
1620
+ }
1621
+
1622
+ function exitForState(state) {
1623
+ if (["completed", "completed_with_failures"].includes(state.status)) return 0;
1624
+ if (["running", "retry_wait", "waiting_external", "waiting_human"].includes(state.status)) return 1;
1625
+ if (state.status === "blocked") return 3;
1626
+ if (state.status === "failed") return 4;
1627
+ return 2;
1628
+ }
1629
+
1630
+ function presentationFacing(node, vars) {
1631
+ return Object.fromEntries(Object.entries(node.user_facing || {}).map(([key, value]) => [
1632
+ key,
1633
+ typeof value === "string" ? expand(value, vars) : value,
1634
+ ]));
1635
+ }
1636
+
1637
+ /**
1638
+ * Host-facing projection of one Runner command. Terminal events are derived
1639
+ * only from committed Runner state; the executor never announces completion.
1640
+ */
1641
+ export function presentationForTransition(before, after, document) {
1642
+ const previousNodes = before?.nodes || {};
1643
+ const previousAttempts = new Map((before?.attempts || []).map((attempt) => [attempt.attempt_id, attempt]));
1644
+ const afterAttempts = new Map((after.attempts || []).map((attempt) => [attempt.attempt_id, attempt]));
1645
+ const byId = new Map(document.nodes.map((node) => [node.id, node]));
1646
+ const order = document.serial_order?.length ? document.serial_order : document.nodes.map((node) => node.id);
1647
+ const events = [];
1648
+
1649
+ for (const id of order) {
1650
+ const node = byId.get(id);
1651
+ const current = after.nodes?.[id];
1652
+ if (!node || !current) continue;
1653
+ const previous = previousNodes[id];
1654
+ const previousStatus = previous?.status || "pending";
1655
+ const currentAttempt = afterAttempts.get(current.current_attempt_id);
1656
+ const started = ACTIVE_ATTEMPT.has(current.status) && (
1657
+ !ACTIVE_ATTEMPT.has(previousStatus) || previous?.current_attempt_id !== current.current_attempt_id
1658
+ );
1659
+ const terminal = TERMINAL.has(current.status) && previousStatus !== current.status;
1660
+ const base = {
1661
+ node: id,
1662
+ user_facing: presentationFacing(node, after.vars || {}),
1663
+ };
1664
+ if (started) events.push({ ...base, kind: "doing", status: current.status, attempt_id: current.current_attempt_id });
1665
+
1666
+ for (const attempt of after.attempts || []) {
1667
+ if (attempt.node !== id) continue;
1668
+ const notices = attempt.result?.evidence?.notices || [];
1669
+ const oldNotices = previousAttempts.get(attempt.attempt_id)?.result?.evidence?.notices || [];
1670
+ if (!notices.length || JSON.stringify(notices) === JSON.stringify(oldNotices)) continue;
1671
+ for (const notice of notices) {
1672
+ events.push({ node: id, kind: "notice", status: current.status, text: expand(notice.text || "", after.vars || {}) });
1673
+ }
1674
+ }
1675
+
1676
+ if (terminal) {
1677
+ events.push({
1678
+ ...base,
1679
+ kind: "terminal",
1680
+ status: current.status,
1681
+ ...(current.reason ? { reason: current.reason } : {}),
1682
+ ...(current.current_attempt_id ? { attempt_id: current.current_attempt_id } : {}),
1683
+ ...(currentAttempt?.result?.evidence ? { evidence: currentAttempt.result.evidence } : {}),
1684
+ });
1685
+ }
1686
+ }
1687
+ return { checklist: document.policy?.progress_checklist || [], events };
1688
+ }
1689
+
1690
+ function summary(state) {
1691
+ return {
1692
+ schema: SCHEMA,
1693
+ run_id: state.run_id,
1694
+ status: state.status,
1695
+ current_node: state.current_node,
1696
+ profile: state.profile,
1697
+ error: state.error || null,
1698
+ nodes: Object.fromEntries(Object.entries(state.nodes).map(([id, node]) => [id, {
1699
+ status: node.status,
1700
+ reason: node.reason || undefined,
1701
+ attempt_count: node.attempt_count,
1702
+ current_attempt_id: node.current_attempt_id,
1703
+ }])),
1704
+ ledger_commit: state.ledger_commit,
1705
+ updated_at: state.updated_at,
1706
+ };
1707
+ }
1708
+
1709
+ function canonicalScriptPath(filePath) {
1710
+ let result;
1711
+ try {
1712
+ result = fs.realpathSync.native(filePath);
1713
+ } catch {
1714
+ result = path.resolve(filePath);
1715
+ }
1716
+ return process.platform === "win32" ? result.toLowerCase() : result;
1717
+ }
1718
+
1719
+ async function main(argv) {
1720
+ const { command, args } = parseCli(argv);
1721
+ if (!command || !["run", "continue", "status", "complete", "confirm", "rewind"].includes(command)) {
1722
+ throw new RunnerError("INVALID_ARGUMENTS", "Usage: dag_runner.mjs run|continue|status|complete|confirm|rewind --state ...");
1723
+ }
1724
+ let state;
1725
+ let previousState = null;
1726
+ if (command === "run") {
1727
+ const options = cliOptions(args, true);
1728
+ state = startRun(options);
1729
+ if (state.status === "running") state = await advance({ state: options.state });
1730
+ } else {
1731
+ if (!args.state) throw new RunnerError("INVALID_ARGUMENTS", `${command} requires --state`);
1732
+ previousState = loadRunState(args.state);
1733
+ const options = cliOptions(args, false);
1734
+ if (command === "status") state = previousState;
1735
+ else if (command === "continue") state = await advance(options);
1736
+ else if (command === "complete") {
1737
+ if (!args.attemptId || !args.resultFile) throw new RunnerError("INVALID_ARGUMENTS", "complete requires --attempt-id and --result-file");
1738
+ state = await completeAttempt(options);
1739
+ } else if (command === "confirm") {
1740
+ if (!args.node) throw new RunnerError("INVALID_ARGUMENTS", "confirm requires --node");
1741
+ state = await confirmGate(options);
1742
+ } else {
1743
+ if (!args.node) throw new RunnerError("INVALID_ARGUMENTS", "rewind requires --node");
1744
+ state = await rewindGate(options);
1745
+ }
1746
+ }
1747
+ const code = exitForState(state);
1748
+ const presentation = command === "status"
1749
+ ? null
1750
+ : presentationForTransition(previousState, state, readWorkflow(state.workflow.path));
1751
+ process.stdout.write(`${JSON.stringify({ ...summary(state), ...(presentation ? { presentation } : {}), exit_code: code })}\n`);
1752
+ return code;
1753
+ }
1754
+
1755
+ const isDirect = process.argv[1] && canonicalScriptPath(process.argv[1]) === canonicalScriptPath(fileURLToPath(import.meta.url));
1756
+ if (isDirect) {
1757
+ try {
1758
+ const code = await main(process.argv.slice(2));
1759
+ process.exitCode = code;
1760
+ } catch (error) {
1761
+ const code = Number.isInteger(error?.exitCode) ? error.exitCode : 2;
1762
+ const payload = { status: code === 3 ? "blocked" : "invalid", error: { code: error?.code || "INVALID", message: String(error?.message || error) } };
1763
+ process.stdout.write(`${JSON.stringify({ ...payload, exit_code: code })}\n`);
1764
+ process.stderr.write(String(error?.message || error) + "\n");
1765
+ process.exitCode = code;
1766
+ }
1767
+ }