@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,897 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Production executor for a2h-app-migrate's deterministic DAG runner.
4
+ *
5
+ * Process protocol: read A2H_DAG_REQUEST, write A2H_DAG_RESULT and keep
6
+ * A2H_DAG_ATTEMPT unchanged. Semantic work is never executed by a shell worker:
7
+ * it is returned as waiting_external/waiting_human for the current host.
8
+ *
9
+ * Host callbacks:
10
+ * node dag_production_executor.mjs answer --request <request.json> --answer <answer.json>
11
+ * node dag_production_executor.mjs complete --request <request.json> --outcome <outcome.json>
12
+ * Both write the strict result to request.result_path; the host then calls
13
+ * dag_runner.mjs complete with that result and attempt id.
14
+ */
15
+ import { spawnSync } from "node:child_process";
16
+ import fs from "node:fs";
17
+ import path from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+
20
+ import { evaluateExpression } from "./dag_graph.mjs";
21
+ import { readJson, writeJsonAtomic } from "./json_io.mjs";
22
+
23
+ const SCRIPT_PATH = fileURLToPath(import.meta.url);
24
+ const SCRIPT_DIR = path.dirname(SCRIPT_PATH);
25
+ const SKILLS_ROOT = path.resolve(SCRIPT_DIR, "..", "..");
26
+ const RESULT_STATUSES = new Set(["done", "failed", "waiting_external", "waiting_human"]);
27
+ const PROTECTED_ANSWER_VARS = new Set(["PROFILE", "DAG_RUN_DIR", "DAG_STATE", "WORKFLOW", "LEDGER"]);
28
+
29
+ class ProductionError extends Error {
30
+ constructor(code, message) {
31
+ super(message);
32
+ this.code = code;
33
+ }
34
+ }
35
+
36
+ // Only these are business verdicts (a contract script / audit / gate script said "no"), so they become a
37
+ // strict failed result and follow the node's fail_matrix (soft_continue may carry on). Everything else —
38
+ // protocol errors (STALE_ATTEMPT, cursor conflicts, malformed answers), config errors (INVALID_SKILL,
39
+ // INVALID_SET_VARS) and implementation gaps (UNSUPPORTED_*) — must never be recorded as a soft failure:
40
+ // rethrow so the executor exits non-zero without a result and the Runner blocks.
41
+ const BUSINESS_FAILURE_CODES = new Set(["PRODUCTION_SCRIPT_FAILED", "CAPTURE_AUDIT_FAILED", "HUMAN_GATE_FAILED"]);
42
+
43
+ function businessFailure(request, error) {
44
+ if (!(error instanceof ProductionError) || !BUSINESS_FAILURE_CODES.has(error.code)) throw error;
45
+ return { attempt_id: request.attempt_id, status: "failed", reason: `${error.code}: ${error.message}` };
46
+ }
47
+
48
+ function stamp() {
49
+ return new Date().toISOString();
50
+ }
51
+
52
+ function expand(value, vars) {
53
+ if (typeof value !== "string") return value;
54
+ return value.replace(/\$\{([A-Za-z_$][\w$]*)\}/g, (_match, name) => (
55
+ Object.prototype.hasOwnProperty.call(vars, name) ? String(vars[name] ?? "") : ""
56
+ ));
57
+ }
58
+
59
+ function expandDeep(value, vars) {
60
+ if (typeof value === "string") return expand(value, vars);
61
+ if (Array.isArray(value)) return value.map((item) => expandDeep(item, vars));
62
+ if (value && typeof value === "object") {
63
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, expandDeep(item, vars)]));
64
+ }
65
+ return value;
66
+ }
67
+
68
+ function condition(value, vars) {
69
+ if (value === undefined || value === null || value === "") return true;
70
+ return Boolean(evaluateExpression(String(value), vars));
71
+ }
72
+
73
+ function attemptKey(request) {
74
+ return String(request.attempt?.file_id || request.attempt_id).replace(/[^A-Za-z0-9_.-]/g, "_");
75
+ }
76
+
77
+ function checkpointPath(request) {
78
+ const key = request.attempt?.resume_from_attempt
79
+ ? String(request.attempt.resume_from_attempt).replace(/[^A-Za-z0-9_.-]/g, "_")
80
+ : attemptKey(request);
81
+ return path.join(request.paths.dag_run_dir, "production", `${key}.json`);
82
+ }
83
+
84
+ function initialCheckpoint(request) {
85
+ return {
86
+ schema: "a2h-production-attempt/v1",
87
+ run_id: request.run_id,
88
+ node: request.node,
89
+ attempt_id: request.attempt_id,
90
+ cursor: 0,
91
+ vars: {},
92
+ history: [],
93
+ wait: null,
94
+ phase: "actions",
95
+ preflight_passed: false,
96
+ updated_at: stamp(),
97
+ };
98
+ }
99
+
100
+ function loadCheckpoint(request) {
101
+ const file = checkpointPath(request);
102
+ if (!fs.existsSync(file)) return initialCheckpoint(request);
103
+ const saved = readJson(file);
104
+ if (saved.schema !== "a2h-production-attempt/v1" || saved.run_id !== request.run_id || saved.node !== request.node) {
105
+ throw new ProductionError("PRODUCTION_CURSOR_CONFLICT", `Invalid production action cursor: ${file}`);
106
+ }
107
+ saved.attempt_id = request.attempt_id;
108
+ saved.wait = null;
109
+ return saved;
110
+ }
111
+
112
+ function saveCheckpoint(request, checkpoint) {
113
+ checkpoint.updated_at = stamp();
114
+ writeJsonAtomic(checkpointPath(request), checkpoint);
115
+ }
116
+
117
+ function currentVars(request, checkpoint) {
118
+ return { ...request.vars, ...checkpoint.vars };
119
+ }
120
+
121
+ function setVars(checkpoint, updates) {
122
+ for (const [name, value] of Object.entries(updates || {})) {
123
+ if (!/^[A-Z_][A-Z0-9_]*$/.test(name) || PROTECTED_ANSWER_VARS.has(name)) {
124
+ throw new ProductionError("INVALID_SET_VARS", `Cannot set protected or invalid variable ${name}`);
125
+ }
126
+ if (value !== null && !["string", "number", "boolean"].includes(typeof value)) {
127
+ throw new ProductionError("INVALID_SET_VARS", `${name} must be a scalar value`);
128
+ }
129
+ checkpoint.vars[name] = value;
130
+ }
131
+ }
132
+
133
+ function parseJsonLine(text) {
134
+ const lines = String(text || "").trim().split(/\r?\n/).filter((line) => line.trim());
135
+ for (let index = lines.length - 1; index >= 0; index--) {
136
+ try {
137
+ const value = JSON.parse(lines[index]);
138
+ if (value && typeof value === "object") return value;
139
+ } catch {
140
+ /* try the preceding line */
141
+ }
142
+ }
143
+ return null;
144
+ }
145
+
146
+ function excerpt(value) {
147
+ const text = String(value || "").trim();
148
+ return text.length <= 4096 ? text : `...${text.slice(-4096)}`;
149
+ }
150
+
151
+ function runNode(script, args, { cwd = SCRIPT_DIR } = {}) {
152
+ const outcome = spawnSync(process.execPath, [expand(script, activeVars), ...args], {
153
+ cwd,
154
+ env: process.env,
155
+ shell: false,
156
+ windowsHide: true,
157
+ encoding: "utf8",
158
+ maxBuffer: 16 * 1024 * 1024,
159
+ });
160
+ if (outcome.error) {
161
+ return { code: 2, stdout: "", stderr: outcome.error.message, error: outcome.error };
162
+ }
163
+ return {
164
+ code: outcome.status ?? 2,
165
+ signal: outcome.signal,
166
+ stdout: outcome.stdout || "",
167
+ stderr: outcome.stderr || "",
168
+ };
169
+ }
170
+
171
+ let activeVars = {};
172
+
173
+ function scriptAction(checkpoint, action, args, { allow = [0], cwd } = {}) {
174
+ const script = expand(action.script || action.run, activeVars);
175
+ const rendered = args.map((arg) => String(arg));
176
+ const outcome = runNode(script, rendered, { cwd });
177
+ const record = {
178
+ script,
179
+ args: rendered,
180
+ exit_code: outcome.code,
181
+ stdout: outcome.stdout,
182
+ stderr: outcome.stderr,
183
+ json: parseJsonLine(outcome.stdout),
184
+ };
185
+ if (!allow.includes(outcome.code)) {
186
+ throw new ProductionError(
187
+ "PRODUCTION_SCRIPT_FAILED",
188
+ `${path.basename(script)} exited ${outcome.code}: ${excerpt(outcome.stderr || outcome.stdout)}`,
189
+ );
190
+ }
191
+ return record;
192
+ }
193
+
194
+ function actionName(action) {
195
+ return Object.keys(action || {})[0] || "";
196
+ }
197
+
198
+ function actionBody(action) {
199
+ return action?.[actionName(action)];
200
+ }
201
+
202
+ function resultBase(request, checkpoint) {
203
+ return {
204
+ attempt_id: request.attempt_id,
205
+ ...(Object.keys(checkpoint.vars).length ? { set_vars: checkpoint.vars } : {}),
206
+ };
207
+ }
208
+
209
+ function doneResult(request, checkpoint, evidence = {}) {
210
+ const notices = checkpoint.history
211
+ .filter((entry) => typeof entry.output?.tip === "string" && entry.output.tip.trim())
212
+ .map((entry) => ({ action: entry.action, text: entry.output.tip }));
213
+ return {
214
+ ...resultBase(request, checkpoint),
215
+ status: "done",
216
+ evidence: { ...evidence, ...(notices.length ? { notices } : {}) },
217
+ };
218
+ }
219
+
220
+ function waitingResult(request, checkpoint, status, wait) {
221
+ if (!["waiting_external", "waiting_human"].includes(status)) throw new Error("invalid waiting status");
222
+ checkpoint.wait = { status, wait };
223
+ saveCheckpoint(request, checkpoint);
224
+ return {
225
+ ...resultBase(request, checkpoint),
226
+ status,
227
+ wait: {
228
+ ...wait,
229
+ node: request.node,
230
+ attempt_id: request.attempt_id,
231
+ request_path: request.request_path,
232
+ executor: process.execPath,
233
+ executor_script: SCRIPT_PATH,
234
+ result_path: request.result_path,
235
+ },
236
+ };
237
+ }
238
+
239
+ function hostCallback(request, verb, payloadFlag) {
240
+ return {
241
+ command: process.execPath,
242
+ args: [SCRIPT_PATH, verb, "--request", request.request_path, payloadFlag, `<${payloadFlag.slice(2)}.json>`],
243
+ then: "dag_runner.mjs complete --state <DAG_STATE> --attempt-id <attempt_id> --result-file <result_path>",
244
+ };
245
+ }
246
+
247
+ function probeAllArtifacts(body, vars) {
248
+ const probes = {};
249
+ for (const [id, probe] of Object.entries(body.entries || {})) {
250
+ const files = expandDeep(probe.all || probe.any || [], vars);
251
+ const exists = files.map((file) => {
252
+ try { return fs.statSync(file).isFile(); } catch { return false; }
253
+ });
254
+ let complete = probe.all ? exists.every(Boolean) : exists.some(Boolean);
255
+ let check = null;
256
+ if (complete && probe.check) {
257
+ activeVars = vars;
258
+ const args = String(probe.check.args || "").split(/\s+/).filter(Boolean).map((arg) => expand(arg, vars));
259
+ const outcome = runNode(expand(probe.check.script, vars), args);
260
+ check = { exit_code: outcome.code, json: parseJsonLine(outcome.stdout), stderr: excerpt(outcome.stderr) };
261
+ complete = outcome.code === 0;
262
+ }
263
+ probes[id] = { node: probe.node, complete, files, check };
264
+ }
265
+ return probes;
266
+ }
267
+
268
+ function gateArgs(vars, gate, { writeBy = "", upstreamFailed = false, reason = "" } = {}) {
269
+ const args = ["--gate", gate, "--checkpoint", vars.CHECKPOINT_DIR + path.sep + ({
270
+ arch: "arch-reviewed.ok",
271
+ spec_gen: "spec-gen-reviewed.ok",
272
+ ui_batch: "ui-batch-reviewed.ok",
273
+ }[gate])];
274
+ if (gate === "arch" || gate === "ui_batch") args.push("--hmos", vars.HMOS);
275
+ if (gate === "spec_gen") args.push("--specs-json", path.join(vars.SPEC_DIR, "specs.json"));
276
+ if (gate === "ui_batch") args.push("--ui-info-root", vars.UI_INFO_ROOT);
277
+ if (upstreamFailed) args.push("--upstream-failed", "--reason", reason || "upstream failed");
278
+ if (writeBy) args.push("--write-confirmed", "--confirmed-by", writeBy);
279
+ return args;
280
+ }
281
+
282
+ function isAutoGate(request, vars) {
283
+ if (vars.INTERACTION_MODE === "auto") return true;
284
+ return !String(vars.INTERACTIVE_GATES || "").split(",").map((item) => item.trim()).includes(request.node);
285
+ }
286
+
287
+ function readRunnerState(request) {
288
+ if (!request.paths.state_path) return null;
289
+ try { return readJson(request.paths.state_path); } catch { return null; }
290
+ }
291
+
292
+ function runGate(request, checkpoint) {
293
+ const vars = currentVars(request, checkpoint);
294
+ activeVars = vars;
295
+ const gate = request.runner.gate;
296
+ if (!["arch", "spec_gen", "ui_batch"].includes(gate)) {
297
+ throw new ProductionError("INVALID_PRODUCTION_GATE", `Unsupported gate ${gate}`);
298
+ }
299
+ const state = readRunnerState(request);
300
+ const upstream = gate === "ui_batch" ? state?.nodes?.["ui.batch"] : null;
301
+ let upstreamFailed = gate === "ui_batch" && (checkpoint.gate_upstream_failed || upstream?.status === "failed");
302
+ if (gate === "ui_batch" && !upstreamFailed && !request.confirmation && !checkpoint.capture_audited) {
303
+ const script = path.join(SKILLS_ROOT, "a2h-batch-ui-align", "scripts", "capture_audit.mjs");
304
+ const audit = runNode(script, [vars.UI_INFO_ROOT, "--json", path.join(vars.UI_INFO_ROOT, "capture_audit.json")]);
305
+ checkpoint.history.push({ action: "capture_audit", exit_code: audit.code, stdout: audit.stdout, stderr: audit.stderr });
306
+ if (audit.code !== 0) {
307
+ throw new ProductionError("CAPTURE_AUDIT_FAILED", excerpt(audit.stderr || audit.stdout) || `capture_audit exited ${audit.code}`);
308
+ }
309
+ checkpoint.capture_audited = true;
310
+ saveCheckpoint(request, checkpoint);
311
+ }
312
+
313
+ let reason = upstream?.reason || upstream?.last_failure || "界面转换产物未通过检查";
314
+ const confirmedBy = request.confirmation?.confirmed_by;
315
+ const writeBy = confirmedBy || (isAutoGate(request, vars) ? "auto" : "");
316
+ let outcome = runNode(path.join(SCRIPT_DIR, "human_review_gate.mjs"), gateArgs(vars, gate, {
317
+ writeBy,
318
+ upstreamFailed,
319
+ reason,
320
+ }));
321
+
322
+ // An ordinary UI gate exit 2 is the documented failed-artifact branch, not a
323
+ // review.ui_batch hard failure. Retry it with --upstream-failed.
324
+ if (gate === "ui_batch" && !upstreamFailed && outcome.code === 2) {
325
+ upstreamFailed = true;
326
+ checkpoint.gate_upstream_failed = true;
327
+ reason = excerpt(outcome.stderr || outcome.stdout) || reason;
328
+ saveCheckpoint(request, checkpoint);
329
+ outcome = runNode(path.join(SCRIPT_DIR, "human_review_gate.mjs"), gateArgs(vars, gate, {
330
+ writeBy,
331
+ upstreamFailed: true,
332
+ reason,
333
+ }));
334
+ }
335
+ checkpoint.history.push({ action: `gate:${gate}`, exit_code: outcome.code, stdout: outcome.stdout, stderr: outcome.stderr, upstream_failed: upstreamFailed });
336
+ if (outcome.code === 0) {
337
+ return doneResult(request, checkpoint, {
338
+ gate,
339
+ confirmed_by: writeBy || "existing",
340
+ upstream_failed: upstreamFailed,
341
+ output: excerpt(outcome.stdout),
342
+ });
343
+ }
344
+ if (outcome.code === 1 && !writeBy) {
345
+ const question = upstreamFailed
346
+ ? request.node_definition.user_facing?.ask_failed || request.node_definition.user_facing?.ask
347
+ : request.node_definition.user_facing?.ask;
348
+ return waitingResult(request, checkpoint, "waiting_human", {
349
+ kind: "human_gate",
350
+ gate,
351
+ question,
352
+ upstream_failed: upstreamFailed,
353
+ reason,
354
+ checkpoint: gateArgs(vars, gate)[3],
355
+ confirm: {
356
+ command: process.execPath,
357
+ args: [path.join(SCRIPT_DIR, "dag_runner.mjs"), "confirm", "--state", request.paths.state_path, "--node", request.node],
358
+ },
359
+ rewind: request.runner.rewind_to ? {
360
+ target: request.runner.rewind_to,
361
+ command: process.execPath,
362
+ args: [path.join(SCRIPT_DIR, "dag_runner.mjs"), "rewind", "--state", request.paths.state_path, "--node", request.node],
363
+ } : null,
364
+ output: excerpt(outcome.stdout),
365
+ });
366
+ }
367
+ throw new ProductionError("HUMAN_GATE_FAILED", excerpt(outcome.stderr || outcome.stdout) || `Gate ${gate} exited ${outcome.code}`);
368
+ }
369
+
370
+ function configNeedsAnswer(vars, resume) {
371
+ if (vars.INTERACTION_MODE === "ask") return true;
372
+ if (vars.INTERACTION_MODE === "interactive" && vars.INTERACTIVE_GATES === "ask") return true;
373
+ if (!resume && Object.keys(vars).some((name) => name.startsWith("REUSE_") && vars[name] === "ask")) return true;
374
+ return vars.APK_PATH == null && vars.REUSE_UI_BATCH !== true;
375
+ }
376
+
377
+ function normalizeConfig(request, checkpoint, answer) {
378
+ const body = request.node_definition.actions.map(actionBody).find((value) => value?.interaction && value?.reuse);
379
+ if (!body) throw new ProductionError("INVALID_PRODUCTION_ACTION", "ask_run_config_once is malformed");
380
+ if (answer) {
381
+ const values = answer.set_vars || answer.vars || answer.values || {};
382
+ if (!values || typeof values !== "object" || Array.isArray(values)) {
383
+ throw new ProductionError("INVALID_CONFIG_ANSWER", "Config answer set_vars/vars/values must be an object");
384
+ }
385
+ setVars(checkpoint, values);
386
+ }
387
+ const vars = currentVars(request, checkpoint);
388
+ const resume = vars.PROFILE === "resume" || vars.FROM_NODE !== "bootstrap";
389
+ if (vars.INTERACTION_MODE === "ask") checkpoint.vars.INTERACTION_MODE = body.interaction.prompt_default;
390
+ if (vars.INTERACTION_MODE === "auto") checkpoint.vars.INTERACTIVE_GATES = "";
391
+ else if (vars.INTERACTION_MODE === "interactive" && vars.INTERACTIVE_GATES === "ask") {
392
+ checkpoint.vars.INTERACTIVE_GATES = body.interactive_gates.prompt_default;
393
+ }
394
+ const probes = checkpoint.probes || {};
395
+ if (!resume) {
396
+ const reuseAll = checkpoint.vars.REUSE_ALL || vars.REUSE_ALL;
397
+ for (const [name, ids] of Object.entries(body.reuse.map || {})) {
398
+ let value = checkpoint.vars[name] ?? vars[name];
399
+ if (value === "ask") {
400
+ if (reuseAll === "none") value = false;
401
+ else if (reuseAll === "all") value = ids.every((id) => probes[id]?.complete);
402
+ else value = false;
403
+ }
404
+ if (value === true && !ids.every((id) => probes[id]?.complete)) value = false;
405
+ checkpoint.vars[name] = value;
406
+ }
407
+ }
408
+ }
409
+
410
+ function askRunConfig(request, checkpoint, answer) {
411
+ normalizeConfig(request, checkpoint, answer);
412
+ const vars = currentVars(request, checkpoint);
413
+ const resume = vars.PROFILE === "resume" || vars.FROM_NODE !== "bootstrap";
414
+ if (configNeedsAnswer(currentVars(request, checkpoint), resume)) {
415
+ const body = request.node_definition.actions.map(actionBody).find((value) => value?.interaction && value?.reuse);
416
+ return waitingResult(request, checkpoint, "waiting_external", {
417
+ kind: "config",
418
+ prompt: body.prompt_template,
419
+ interaction: body.interaction,
420
+ interactive_gates: body.interactive_gates,
421
+ reuse: { map: body.reuse.map, mode: vars.REUSE_ALL },
422
+ ask_if_missing: expandDeep(body.ask_if_missing || {}, vars),
423
+ probes: checkpoint.probes || {},
424
+ answer_schema: { attempt_id: request.attempt_id, set_vars: { INTERACTION_MODE: "auto|interactive", INTERACTIVE_GATES: "comma separated", APK_PATH: "absolute path", REUSE_ALL: "all|none", "REUSE_*": true } },
425
+ answer: hostCallback(request, "answer", "--answer"),
426
+ });
427
+ }
428
+ return null;
429
+ }
430
+
431
+ function prepareImageProbe(request, checkpoint) {
432
+ const vars = currentVars(request, checkpoint);
433
+ const probeDir = vars.HMOS_MODE === "existing_project"
434
+ ? path.join(vars.WORK, "image_probe")
435
+ : path.join(vars.ANDROID, ".hometrans-image-probe");
436
+ const script = path.join(SKILLS_ROOT, "a2h-batch-ui-align", "scripts", "image_probe.mjs");
437
+ const prepared = runNode(script, ["prepare", "--dir", probeDir]);
438
+ const data = parseJsonLine(prepared.stdout);
439
+ if (prepared.code !== 0 || !data?.image || !data?.state) {
440
+ runNode(script, ["cleanup", "--dir", probeDir]);
441
+ checkpoint.vars.IMAGE_READ = false;
442
+ checkpoint.history.push({ action: "probe_image_read", error: excerpt(prepared.stderr || prepared.stdout) });
443
+ return null;
444
+ }
445
+ checkpoint.image_probe = { ...data, dir: probeDir, reply_file: path.join(probeDir, "reply.txt") };
446
+ saveCheckpoint(request, checkpoint);
447
+ return waitingResult(request, checkpoint, "waiting_external", {
448
+ kind: "image_read",
449
+ image: data.image,
450
+ state: data.state,
451
+ prompt: data.prompt,
452
+ probe_dir: probeDir,
453
+ reply_file: checkpoint.image_probe.reply_file,
454
+ instructions: "Use one throwaway foreground sub-agent with the prompt verbatim. Do not read the image in primary. Put its raw reply or tool error in answer.reply.",
455
+ answer_schema: { attempt_id: request.attempt_id, reply: "raw sub-agent reply or error" },
456
+ answer: hostCallback(request, "answer", "--answer"),
457
+ });
458
+ }
459
+
460
+ function finishImageProbe(request, checkpoint, answer) {
461
+ const probe = checkpoint.image_probe;
462
+ if (!probe) throw new ProductionError("INVALID_IMAGE_ANSWER", "No pending image probe in this attempt");
463
+ const script = path.join(SKILLS_ROOT, "a2h-batch-ui-align", "scripts", "image_probe.mjs");
464
+ let verdict = { image_read: false, reason: "missing answer" };
465
+ try {
466
+ const reply = typeof answer === "string" ? answer : answer?.reply;
467
+ if (typeof reply !== "string") throw new Error("answer.reply must be a string");
468
+ fs.writeFileSync(probe.reply_file, reply, "utf8");
469
+ const verified = runNode(script, ["verify", "--state", probe.state, "--reply-file", probe.reply_file, "--cleanup"]);
470
+ verdict = parseJsonLine(verified.stdout) || { image_read: false, reason: excerpt(verified.stderr || verified.stdout) };
471
+ } catch (error) {
472
+ verdict = { image_read: false, reason: String(error?.message || error) };
473
+ } finally {
474
+ const cleaned = runNode(script, ["cleanup", "--dir", probe.dir]);
475
+ checkpoint.history.push({ action: "probe_image_read_cleanup", exit_code: cleaned.code, stdout: cleaned.stdout, stderr: cleaned.stderr });
476
+ }
477
+ checkpoint.vars.IMAGE_READ = verdict.image_read === true;
478
+ checkpoint.history.push({ action: "probe_image_read", verdict });
479
+ delete checkpoint.image_probe;
480
+ return null;
481
+ }
482
+
483
+ function runBootstrapAction(request, checkpoint, action, answer) {
484
+ const name = actionName(action);
485
+ const body = actionBody(action);
486
+ const vars = currentVars(request, checkpoint);
487
+ activeVars = vars;
488
+ if (name === "plan_resume") {
489
+ if (!(vars.PROFILE === "resume" || vars.FROM_NODE !== "bootstrap")) return { skipped: true };
490
+ const args = ["--workflow", request.vars.WORKFLOW, "--ledger", request.paths.ledger,
491
+ "--from-node", vars.FROM_NODE, "--engine", vars.SPEC_ENGINE, "--engine-given", String(vars.SPEC_ENGINE_GIVEN === true)];
492
+ if (vars.RESUME_BASE_PROFILE) args.push("--base-profile", vars.RESUME_BASE_PROFILE);
493
+ const record = scriptAction(checkpoint, body, args);
494
+ if (record.json?.spec_engine) setVars(checkpoint, { SPEC_ENGINE: record.json.spec_engine });
495
+ return record;
496
+ }
497
+ if (name === "infer_android_root" || name === "infer_android_root_after_config") {
498
+ const record = scriptAction(checkpoint, body, ["--android", vars.ANDROID, "--apk", vars.APK_PATH == null ? "" : vars.APK_PATH]);
499
+ if (record.json?.replaced && record.json.android) {
500
+ setVars(checkpoint, { ANDROID: record.json.android });
501
+ if (name === "infer_android_root_after_config") {
502
+ checkpoint.probes = probeAllArtifacts(request.node_definition.actions.map(actionBody).find((value) => value?.entries), currentVars(request, checkpoint));
503
+ }
504
+ }
505
+ return record;
506
+ }
507
+ if (name === "resolve_run_dir_show") {
508
+ if (vars.RUN_DIR_GIVEN === true && vars.RUN_DIR) return { skipped: true, reason: "explicit run_dir" };
509
+ const record = scriptAction(checkpoint, body, ["--work", vars.WORK, "--show", "--json", "--engine", vars.SPEC_ENGINE], { allow: [0, 1] });
510
+ if (record.exit_code === 0 && record.json?.run_dir) setVars(checkpoint, { RUN_DIR: record.json.run_dir, SPEC_DIR: record.json.spec_dir });
511
+ return record;
512
+ }
513
+ if (name === "describe_run_dir") {
514
+ if (!(vars.RUN_DIR_GIVEN === true && vars.RUN_DIR)) return { skipped: true };
515
+ const record = scriptAction(checkpoint, body, ["--work", vars.WORK, "--describe", vars.RUN_DIR, "--engine", vars.SPEC_ENGINE]);
516
+ if (record.json?.spec_dir) setVars(checkpoint, { SPEC_DIR: record.json.spec_dir });
517
+ return record;
518
+ }
519
+ if (name === "probe_all_artifacts") {
520
+ checkpoint.probes = probeAllArtifacts(body, vars);
521
+ return { probes: checkpoint.probes };
522
+ }
523
+ if (name === "ask_run_config_once") return askRunConfig(request, checkpoint, answer);
524
+ if (name === "run_env_preflight") {
525
+ const args = Object.entries(body.args || {}).map(([key, value]) => {
526
+ const source = String(value);
527
+ const isExpression = /(?:\bor\b|\band\b|\bnot\b|==|!=|\|\||&&)/.test(source);
528
+ let rendered = isExpression ? evaluateExpression(source, vars) : expand(source, vars);
529
+ if (key === "run_dir" && vars.RUN_DIR_GIVEN !== true && String(rendered).includes("<run-id>")) rendered = "";
530
+ if (key === "specs_json" && vars.SPECS_JSON_IS_DEFAULT === true && String(rendered).includes("<run-id>")) rendered = "";
531
+ return `--${key.replace(/_/g, "-")}=${rendered == null ? "" : String(rendered)}`;
532
+ });
533
+ args.push("--report");
534
+ const record = scriptAction(checkpoint, body, args);
535
+ const line = record.stdout.split(/\r?\n/).filter((item) => item.startsWith("PREFLIGHT_VARS ")).at(-1);
536
+ if (!line) throw new ProductionError("PREFLIGHT_VARS_MISSING", "env_preflight succeeded without PREFLIGHT_VARS");
537
+ let preflight;
538
+ try { preflight = JSON.parse(line.slice("PREFLIGHT_VARS ".length)); } catch (error) {
539
+ throw new ProductionError("PREFLIGHT_VARS_INVALID", error.message);
540
+ }
541
+ checkpoint.preflight_vars = preflight;
542
+ checkpoint.preflight_report = record.stdout.split(/\r?\nPREFLIGHT_VARS /)[0];
543
+ const sharedReport = path.join(request.paths.dag_run_dir, "production", "preflight-report.md");
544
+ writeJsonAtomic(path.join(request.paths.dag_run_dir, "production", "preflight.json"), preflight);
545
+ fs.writeFileSync(sharedReport, checkpoint.preflight_report + "\n", "utf8");
546
+ return record;
547
+ }
548
+ if (name === "set_vars_from_preflight") {
549
+ const source = checkpoint.preflight_vars;
550
+ if (!source) throw new ProductionError("PREFLIGHT_VARS_MISSING", "No committed preflight output in this attempt");
551
+ const updates = {};
552
+ for (const [target, key] of Object.entries(body)) {
553
+ if (["source", "keep_when_empty"].includes(target)) continue;
554
+ // PROFILE is Runner-owned; preflight reports its normalized value but must not write it back.
555
+ if (target === "PROFILE") continue;
556
+ const value = source[key];
557
+ if ((body.keep_when_empty || []).includes(target) && value === "") continue;
558
+ if (value !== undefined) updates[target] = value;
559
+ }
560
+ setVars(checkpoint, updates);
561
+ setVars(checkpoint, { ENV_PREFLIGHT_PASSED: true });
562
+ checkpoint.preflight_passed = true;
563
+ return { applied: updates };
564
+ }
565
+ if (name === "incremental_history") {
566
+ if (!condition(body.when, vars)) return { skipped: true };
567
+ const record = scriptAction(checkpoint, body, ["--hmos", vars.HMOS, "--summary"], { allow: [0, 1, 2] });
568
+ if (record.exit_code !== 0) return { ...record, warning: "migration history unavailable; continuing as first incremental run" };
569
+ if (Array.isArray(record.json?.ui_done)) setVars(checkpoint, { MIGRATED_PAGES: record.json.ui_done.join(",") });
570
+ return record;
571
+ }
572
+ if (name === "incremental_diagnose") {
573
+ if (!condition(body.when, vars)) return { skipped: true };
574
+ const args = ["--hmos", vars.HMOS, "--work", vars.WORK, "--android", vars.ANDROID, "--out", path.join(vars.WORK, "diagnose.json")];
575
+ let record = scriptAction(checkpoint, body, args, { allow: [0, 1, 2] });
576
+ if (record.exit_code !== 0) return { ...record, warning: "incremental diagnosis unavailable; continuing as scenario 3" };
577
+ const ledgerRepair = record.json?.artifacts?.some((entry) => entry.name === "ledger" && ["repair", "rebuild"].includes(entry.action));
578
+ if (ledgerRepair) {
579
+ const rebuild = scriptAction(checkpoint, {
580
+ script: path.join(SKILLS_ROOT, "a2h-app-migrate", "scripts", "migration_manifest.mjs"),
581
+ }, ["--hmos", vars.HMOS, "--rebuild", "--ui-info", vars.UI_INFO_ROOT || ""], { allow: [0, 1, 2] });
582
+ record = { ...scriptAction(checkpoint, body, args, { allow: [0, 1, 2] }), rebuild };
583
+ }
584
+ return record;
585
+ }
586
+ if (name === "probe_image_read") {
587
+ if (condition(body.skip_when, vars)) return { skipped: true };
588
+ if (checkpoint.wait?.wait?.kind === "image_read" || answer) return finishImageProbe(request, checkpoint, answer);
589
+ return prepareImageProbe(request, checkpoint);
590
+ }
591
+ if (name === "tip_image_read_false") {
592
+ if (condition(body.skip_when, vars)) return { skipped: true };
593
+ return { tip: body.tip };
594
+ }
595
+ throw new ProductionError("UNSUPPORTED_PRODUCTION_ACTION", `bootstrap action ${name} has no deterministic implementation`);
596
+ }
597
+
598
+ function runBootstrap(request, checkpoint, answer) {
599
+ const actions = request.node_definition.actions || [];
600
+ while (checkpoint.cursor < actions.length) {
601
+ const index = checkpoint.cursor;
602
+ const name = actionName(actions[index]);
603
+ const output = runBootstrapAction(request, checkpoint, actions[index], checkpoint.cursor === index ? answer : null);
604
+ answer = null;
605
+ if (output?.status && RESULT_STATUSES.has(output.status)) return output;
606
+ checkpoint.history.push({ action: name, index, output });
607
+ checkpoint.cursor = index + 1;
608
+ checkpoint.wait = null;
609
+ saveCheckpoint(request, checkpoint);
610
+ }
611
+ return doneResult(request, checkpoint, { actions: checkpoint.history.length, preflight_passed: checkpoint.preflight_passed });
612
+ }
613
+
614
+ function runWorkspace(request, checkpoint) {
615
+ if (!checkpoint.preflight_passed && request.vars.ENV_PREFLIGHT_PASSED !== true) {
616
+ throw new ProductionError("PREFLIGHT_REQUIRED", "boot.workspace cannot write production paths before env_preflight passes");
617
+ }
618
+ const actions = request.node_definition.actions || [];
619
+ while (checkpoint.cursor < actions.length) {
620
+ const action = actions[checkpoint.cursor];
621
+ const name = actionName(action);
622
+ const body = actionBody(action);
623
+ const vars = currentVars(request, checkpoint);
624
+ activeVars = vars;
625
+ let output;
626
+ if (name === "ensure_dirs") {
627
+ for (const dir of expandDeep(body, vars)) fs.mkdirSync(dir, { recursive: true });
628
+ output = { directories: expandDeep(body, vars) };
629
+ } else if (name === "init_manifest") {
630
+ const target = expand(body, vars);
631
+ const sharedReport = path.join(request.paths.dag_run_dir, "production", "preflight-report.md");
632
+ const report = fs.existsSync(sharedReport) ? fs.readFileSync(sharedReport, "utf8") : "Preflight report unavailable";
633
+ fs.mkdirSync(path.dirname(target), { recursive: true });
634
+ fs.writeFileSync(target, `# a2h-app-migrate manifest\n\n- run_id: ${request.run_id}\n- profile: ${vars.PROFILE}\n- started_at: ${stamp()}\n\n## Environment preflight\n\n${report}\n`, "utf8");
635
+ output = { manifest: target };
636
+ } else if (name === "init_ledger") {
637
+ // run_start is owned and appended by dag_runner after this node's real
638
+ // workspace artifacts pass success validation.
639
+ output = { runner_owned: true };
640
+ } else if (name === "clear_stale_resume_summaries") {
641
+ if (!condition(body.when, vars)) output = { skipped: true };
642
+ else output = scriptAction(checkpoint, body, ["--work", vars.WORK, "--clear-stale"], { allow: [0, 1, 2] });
643
+ } else {
644
+ throw new ProductionError("UNSUPPORTED_PRODUCTION_ACTION", `workspace action ${name} has no deterministic implementation`);
645
+ }
646
+ checkpoint.history.push({ action: name, index: checkpoint.cursor, output });
647
+ checkpoint.cursor++;
648
+ saveCheckpoint(request, checkpoint);
649
+ }
650
+ return doneResult(request, checkpoint, { workspace: true });
651
+ }
652
+
653
+ function runLifecycleScript(checkpoint, body, args, options) {
654
+ return scriptAction(checkpoint, body, args, options);
655
+ }
656
+
657
+ function runSkill(request, checkpoint, outcome) {
658
+ const vars = currentVars(request, checkpoint);
659
+ activeVars = vars;
660
+ if (outcome) {
661
+ if (outcome.attempt_id !== undefined && outcome.attempt_id !== request.attempt_id) {
662
+ throw new ProductionError("STALE_ATTEMPT", `Outcome belongs to ${outcome.attempt_id}, not ${request.attempt_id}`);
663
+ }
664
+ if (outcome.ok === false || outcome.status === "failed") {
665
+ return {
666
+ ...resultBase(request, checkpoint),
667
+ status: "failed",
668
+ reason: String(outcome.reason || outcome.note || "Host reported node failure"),
669
+ details: outcome,
670
+ };
671
+ }
672
+ if (outcome.set_vars) setVars(checkpoint, outcome.set_vars);
673
+ for (const action of request.node_definition.after_run || []) {
674
+ const name = actionName(action);
675
+ const body = actionBody(action);
676
+ if (name !== "refresh_run_dir") throw new ProductionError("UNSUPPORTED_PRODUCTION_ACTION", `after_run ${name} is not implemented`);
677
+ const record = runLifecycleScript(checkpoint, body, ["--work", currentVars(request, checkpoint).WORK, "--show", "--json", "--engine", currentVars(request, checkpoint).SPEC_ENGINE], { allow: [0, 1] });
678
+ if (record.exit_code === 0 && record.json?.run_dir) {
679
+ setVars(checkpoint, { RUN_DIR: record.json.run_dir, SPEC_DIR: record.json.spec_dir });
680
+ } else {
681
+ setVars(checkpoint, { RUN_DIR: "", SPEC_DIR: "" });
682
+ }
683
+ checkpoint.history.push({ action: `after_run:${name}`, output: record });
684
+ }
685
+ saveCheckpoint(request, checkpoint);
686
+ return doneResult(request, checkpoint, { host: outcome });
687
+ }
688
+
689
+ if (!checkpoint.before_run_done) {
690
+ const actions = request.node_definition.before_run || [];
691
+ checkpoint.before_run_cursor ||= 0;
692
+ while (checkpoint.before_run_cursor < actions.length) {
693
+ const action = actions[checkpoint.before_run_cursor];
694
+ const name = actionName(action);
695
+ const body = actionBody(action);
696
+ const live = currentVars(request, checkpoint);
697
+ activeVars = live;
698
+ let record;
699
+ if (name === "clear_gate_checkpoint" || name === "mark_module_docs_start") {
700
+ const args = String(body.args).split(/\s+/).filter(Boolean).map((arg) => expand(arg, live));
701
+ record = runLifecycleScript(checkpoint, body, args);
702
+ } else if (name === "resolve_run_dir") {
703
+ const args = ["--work", live.WORK, "--engine", live.SPEC_ENGINE];
704
+ if (live.RUN_DIR_GIVEN === true && live.RUN_DIR) args.push("--run-dir", live.RUN_DIR);
705
+ if ((request.node_state.generation || 0) > 0 || live.REUSE_ALL === "none") args.push("--fresh");
706
+ record = runLifecycleScript(checkpoint, body, args);
707
+ if (record.json?.run_dir) setVars(checkpoint, { RUN_DIR: record.json.run_dir, SPEC_DIR: record.json.spec_dir, RUN_MODE: record.json.mode });
708
+ } else if (name === "archive_stale_campaign") {
709
+ const args = String(body.args).split(/\s+/).filter(Boolean).map((arg) => expand(arg, live));
710
+ record = runLifecycleScript(checkpoint, body, args, { allow: [0, 1, 2, 3, 4] });
711
+ } else {
712
+ throw new ProductionError("UNSUPPORTED_PRODUCTION_ACTION", `before_run ${name} is not implemented`);
713
+ }
714
+ checkpoint.history.push({ action: `before_run:${name}`, index: checkpoint.before_run_cursor, output: record });
715
+ checkpoint.before_run_cursor++;
716
+ saveCheckpoint(request, checkpoint);
717
+ }
718
+ checkpoint.before_run_done = true;
719
+ saveCheckpoint(request, checkpoint);
720
+ }
721
+ const live = currentVars(request, checkpoint);
722
+ const skill = request.node === "enrich.spec_gen"
723
+ ? request.node_definition.skill_by_engine?.[live.SPEC_ENGINE]
724
+ : request.node_definition.skill;
725
+ if (!skill || skill.includes("${")) throw new ProductionError("INVALID_SKILL", `Unable to resolve skill for ${request.node}`);
726
+ return waitingResult(request, checkpoint, "waiting_external", {
727
+ kind: "skill",
728
+ skill,
729
+ skill_path: path.join(SKILLS_ROOT, skill),
730
+ dispatch: "primary_skill_inline",
731
+ invoke: expand(request.invoke || "", live),
732
+ vars: live,
733
+ paths: request.paths,
734
+ complete: hostCallback(request, "complete", "--outcome"),
735
+ outcome_schema: { attempt_id: request.attempt_id, ok: true, set_vars: {}, note: "on failure use ok:false" },
736
+ });
737
+ }
738
+
739
+ function runGenericActions(request, checkpoint, kind) {
740
+ const node = request.node_definition;
741
+ const vars = currentVars(request, checkpoint);
742
+ activeVars = vars;
743
+ if (node.precondition && !checkpoint.precondition_done) {
744
+ const skip = node.precondition.skip_if && condition(node.precondition.skip_if, vars);
745
+ if (!skip) {
746
+ const args = String(node.precondition.args || "").split(/\s+/).filter(Boolean).map((arg) => expand(arg, vars));
747
+ const record = scriptAction(checkpoint, node.precondition, args);
748
+ checkpoint.history.push({ action: "precondition", output: record });
749
+ }
750
+ checkpoint.precondition_done = true;
751
+ saveCheckpoint(request, checkpoint);
752
+ }
753
+ const actions = node.actions || [];
754
+ while (checkpoint.cursor < actions.length) {
755
+ const action = actions[checkpoint.cursor];
756
+ const name = actionName(action);
757
+ const body = actionBody(action);
758
+ const live = currentVars(request, checkpoint);
759
+ activeVars = live;
760
+ let output;
761
+ if (body && typeof body === "object" && body.script) {
762
+ if (body.when !== undefined && !condition(body.when, live)) output = { skipped: true };
763
+ else if (name === "adopt_batch_specs_json") output = null;
764
+ else {
765
+ const args = String(body.args || "").split(/\s+/).filter(Boolean).map((arg) => expand(arg, live));
766
+ output = scriptAction(checkpoint, body, args);
767
+ }
768
+ }
769
+ if (name === "adopt_batch_specs_json") {
770
+ if (!condition(body.keep_if, live)) setVars(checkpoint, { SPECS_JSON: expand(body.default, live) });
771
+ output = { specs_json: currentVars(request, checkpoint).SPECS_JSON };
772
+ } else if (name === "freeze_order") {
773
+ output = { frozen: true };
774
+ } else if (output === undefined) {
775
+ throw new ProductionError("UNSUPPORTED_PRODUCTION_ACTION", `${kind} action ${name} has no deterministic implementation`);
776
+ }
777
+ checkpoint.history.push({ action: name, index: checkpoint.cursor, output });
778
+ checkpoint.cursor++;
779
+ saveCheckpoint(request, checkpoint);
780
+ }
781
+ return doneResult(request, checkpoint, { kind });
782
+ }
783
+
784
+ function runHostAction(request, checkpoint, outcome) {
785
+ if (!outcome) {
786
+ return waitingResult(request, checkpoint, "waiting_external", {
787
+ kind: "host_action",
788
+ action: request.node,
789
+ invoke: expand(request.invoke || "", currentVars(request, checkpoint)),
790
+ vars: currentVars(request, checkpoint),
791
+ paths: request.paths,
792
+ complete: hostCallback(request, "complete", "--outcome"),
793
+ outcome_schema: { attempt_id: request.attempt_id, ok: true, note: "on failure use ok:false and reason" },
794
+ });
795
+ }
796
+ if (outcome.attempt_id !== undefined && outcome.attempt_id !== request.attempt_id) {
797
+ throw new ProductionError("STALE_ATTEMPT", `Outcome belongs to ${outcome.attempt_id}, not ${request.attempt_id}`);
798
+ }
799
+ if (outcome.ok === false || outcome.status === "failed") {
800
+ return { ...resultBase(request, checkpoint), status: "failed", reason: String(outcome.reason || outcome.note || "Host action failed"), details: outcome };
801
+ }
802
+ if (outcome.set_vars) setVars(checkpoint, outcome.set_vars);
803
+ return doneResult(request, checkpoint, { host: outcome });
804
+ }
805
+
806
+ function executeRequest(request, { answer, outcome } = {}) {
807
+ if (!request || request.runner?.action !== "production") {
808
+ throw new ProductionError("INVALID_REQUEST", "Expected a production DAG request");
809
+ }
810
+ if (!request.attempt_id || !request.result_path || !request.paths?.dag_run_dir) {
811
+ throw new ProductionError("INVALID_REQUEST", "attempt_id, result_path and paths.dag_run_dir are required");
812
+ }
813
+ const checkpoint = loadCheckpoint(request);
814
+ const kind = request.runner.kind;
815
+ if (request.confirmation) {
816
+ if (kind !== "gate") throw new ProductionError("INVALID_CONFIRMATION", "Only gate nodes accept confirmation");
817
+ return runGate(request, checkpoint);
818
+ }
819
+ if (kind === "bootstrap") return runBootstrap(request, checkpoint, answer);
820
+ if (kind === "workspace") return runWorkspace(request, checkpoint);
821
+ if (kind === "script" || kind === "snapshot" || kind === "adopt_specs") return runGenericActions(request, checkpoint, kind);
822
+ if (kind === "skill") return runSkill(request, checkpoint, outcome);
823
+ if (kind === "gate") return runGate(request, checkpoint);
824
+ if (kind === "host_action") return runHostAction(request, checkpoint, outcome);
825
+ throw new ProductionError("UNSUPPORTED_PRODUCTION_KIND", `Unsupported production runner.kind ${kind}`);
826
+ }
827
+
828
+ function writeResult(request, result) {
829
+ if (!RESULT_STATUSES.has(result.status) || result.attempt_id !== request.attempt_id) {
830
+ throw new ProductionError("INVALID_RESULT", "Executor produced an invalid strict result");
831
+ }
832
+ if (result.status === "failed" && !String(result.reason || "").trim()) {
833
+ throw new ProductionError("INVALID_RESULT", "Failed result requires a reason");
834
+ }
835
+ writeJsonAtomic(request.result_path, result);
836
+ }
837
+
838
+ function parseCli(argv) {
839
+ const [command, ...rest] = argv;
840
+ const args = {};
841
+ for (let index = 0; index < rest.length; index++) {
842
+ const token = rest[index];
843
+ if (!token.startsWith("--")) throw new ProductionError("INVALID_ARGUMENTS", `Unexpected argument ${token}`);
844
+ const name = token.slice(2).replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase());
845
+ const value = rest[++index];
846
+ if (value === undefined) throw new ProductionError("INVALID_ARGUMENTS", `Missing value for ${token}`);
847
+ args[name] = value;
848
+ }
849
+ return { command, args };
850
+ }
851
+
852
+ function protocolMain() {
853
+ const request = readJson(process.env.A2H_DAG_REQUEST);
854
+ if (String(request.attempt_id) !== String(process.env.A2H_DAG_ATTEMPT)) {
855
+ throw new ProductionError("STALE_ATTEMPT", "A2H_DAG_ATTEMPT does not match the request");
856
+ }
857
+ request.result_path = process.env.A2H_DAG_RESULT || request.result_path;
858
+ let result;
859
+ try {
860
+ result = executeRequest(request);
861
+ } catch (error) {
862
+ result = businessFailure(request, error);
863
+ }
864
+ writeResult(request, result);
865
+ }
866
+
867
+ function callbackMain(argv) {
868
+ const { command, args } = parseCli(argv);
869
+ if (!["answer", "complete"].includes(command) || !args.request) {
870
+ throw new ProductionError("INVALID_ARGUMENTS", "Usage: answer|complete --request <request.json> --answer|--outcome <json>");
871
+ }
872
+ const request = readJson(args.request);
873
+ const payloadPath = command === "answer" ? args.answer : args.outcome;
874
+ if (!payloadPath) throw new ProductionError("INVALID_ARGUMENTS", `${command} requires --${command === "answer" ? "answer" : "outcome"}`);
875
+ const payload = readJson(payloadPath);
876
+ if (payload?.attempt_id !== undefined && payload.attempt_id !== request.attempt_id) {
877
+ throw new ProductionError("STALE_ATTEMPT", `Callback attempt ${payload.attempt_id} does not match ${request.attempt_id}`);
878
+ }
879
+ let result;
880
+ try {
881
+ result = executeRequest(request, command === "answer" ? { answer: payload } : { outcome: payload });
882
+ } catch (error) {
883
+ // Non-business errors leave result_path untouched (still the waiting result), so the attempt stays
884
+ // waiting and the host can retry with a valid payload; a forced complete never turns into soft failure.
885
+ result = businessFailure(request, error);
886
+ }
887
+ writeResult(request, result);
888
+ process.stdout.write(JSON.stringify({ status: result.status, attempt_id: result.attempt_id, result_path: request.result_path }) + "\n");
889
+ }
890
+
891
+ try {
892
+ if (process.argv[2] === "answer" || process.argv[2] === "complete") callbackMain(process.argv.slice(2));
893
+ else protocolMain();
894
+ } catch (error) {
895
+ process.stderr.write(`${error.code || "PRODUCTION_EXECUTOR_ERROR"}: ${String(error?.message || error)}\n`);
896
+ process.exitCode = 2;
897
+ }