@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,423 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawnSync } from "node:child_process";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import test from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ import {
10
+ advance,
11
+ completeAttempt,
12
+ confirmGate,
13
+ evaluateSuccess,
14
+ loadRunState,
15
+ recover,
16
+ startRun,
17
+ } from "../scripts/dag_runner.mjs";
18
+ import { buildGraph, evaluateExpression, readyNodes, validateGraph } from "../scripts/dag_graph.mjs";
19
+ import { appendLedger, readLedger } from "../scripts/ledger.mjs";
20
+
21
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
22
+ const RUNNER = path.join(HERE, "..", "scripts", "dag_runner.mjs");
23
+
24
+ function flow(value) {
25
+ if (Array.isArray(value)) return `[${value.map(flow).join(", ")}]`;
26
+ if (value && typeof value === "object") {
27
+ return `{${Object.entries(value).map(([key, item]) => `${JSON.stringify(key)}: ${flow(item)}`).join(", ")}}`;
28
+ }
29
+ return JSON.stringify(value ?? null);
30
+ }
31
+
32
+ function baseDoc(nodes, extra = {}) {
33
+ return { profiles: { full: { include_lanes: "all" } }, nodes, ...extra };
34
+ }
35
+
36
+ function fixture(doc) {
37
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "dag-runner-"));
38
+ const runDir = path.join(root, "run");
39
+ const workflow = path.join(root, "workflow.yaml");
40
+ fs.writeFileSync(workflow, `${Object.entries(doc).map(([key, value]) => `${key}: ${flow(value)}`).join("\n")}\n`);
41
+ return {
42
+ root,
43
+ runDir,
44
+ workflow,
45
+ statePath: path.join(runDir, "dag-run-state.json"),
46
+ ledger: path.join(runDir, "stage-ledger.jsonl"),
47
+ };
48
+ }
49
+
50
+ function makeWorker(root, body) {
51
+ const file = path.join(root, `worker-${fs.readdirSync(root).filter((name) => name.startsWith("worker-")).length}.mjs`);
52
+ fs.writeFileSync(file, `
53
+ import fs from "node:fs";
54
+ const req = JSON.parse(fs.readFileSync(process.env.A2H_DAG_REQUEST, "utf8"));
55
+ const write = (result) => fs.writeFileSync(process.env.A2H_DAG_RESULT, JSON.stringify({ attempt_id: req.attempt_id, ...result }));
56
+ const count = () => {
57
+ let value = 0;
58
+ try { value = JSON.parse(fs.readFileSync(req.vars.COUNT, "utf8")); } catch {}
59
+ value += 1;
60
+ fs.writeFileSync(req.vars.COUNT, JSON.stringify(value));
61
+ return value;
62
+ };
63
+ ${body}
64
+ `);
65
+ return { file, command: `"${process.execPath}" "${file}"` };
66
+ }
67
+
68
+ async function runDoc(doc, options = {}) {
69
+ const f = fixture(doc);
70
+ const initial = startRun({
71
+ workflow: f.workflow,
72
+ runDir: f.runDir,
73
+ state: f.statePath,
74
+ ledger: options.ledger || f.ledger,
75
+ profile: options.profile || "full",
76
+ vars: options.vars || {},
77
+ executorCommand: options.executorCommand || "",
78
+ executorTimeoutMs: options.executorTimeoutMs || 0,
79
+ resumeFrom: options.resumeFrom || "",
80
+ baseProfile: options.baseProfile || "",
81
+ });
82
+ const state = initial.status === "running" ? await advance({ state: f.statePath }) : initial;
83
+ return { ...f, state };
84
+ }
85
+
86
+ const lines = (file) => fs.readFileSync(file, "utf8").trim().split(/\r?\n/).filter(Boolean);
87
+
88
+ test("graph resolves stable topology, conditional/group edges, profile cuts and cycles", () => {
89
+ const doc = baseDoc([
90
+ { id: "a", lane: "one", parallel_group: "g" },
91
+ { id: "b", lane: "two" },
92
+ { id: "c", lane: "one", needs: ["a"], conditional_needs: [{ when: "${USE_B} == true", add: ["b"] }] },
93
+ { id: "d", lane: "one", needs: ["c"], also_needs_group: "g" },
94
+ ]);
95
+ const graph = buildGraph(doc, { profile: "full" });
96
+ assert.deepEqual(readyNodes(graph, {}, {}).map((node) => node.id), ["a", "b"]);
97
+ assert.deepEqual(readyNodes(graph, { a: { status: "done" } }, { USE_B: false }).map((node) => node.id), ["b", "c"]);
98
+ assert.deepEqual(readyNodes(graph, { a: { status: "done" } }, { USE_B: true }).map((node) => node.id), ["b"]);
99
+ assert.ok(graph.parents.d.has("a"), "also_needs_group participates in dependencies");
100
+
101
+ const cut = buildGraph(doc, { profile: "full" });
102
+ cut.activeIds.delete("b");
103
+ assert.deepEqual(readyNodes(cut, { a: { status: "done" } }, { USE_B: true }).map((node) => node.id), ["c"]);
104
+
105
+ const cyclic = baseDoc([{ id: "a", needs: ["b"] }, { id: "b", conditional_needs: [{ when: "true", add: ["a"] }] }]);
106
+ assert.match(validateGraph(cyclic).join("\n"), /cycle/);
107
+ assert.throws(() => buildGraph(cyclic), (error) => error.code === "DAG_GRAPH_INVALID");
108
+ });
109
+
110
+ test("safe expressions support comparisons and reject arbitrary JavaScript", () => {
111
+ assert.equal(evaluateExpression('!(${N} < 2) && (${NAME} === "hm" || false)', { N: 3, NAME: "hm" }), true);
112
+ assert.equal(evaluateExpression("${MISSING} == null", {}), true);
113
+ assert.equal(evaluateExpression("${PROFILE} == incremental", { PROFILE: "incremental" }), true);
114
+ assert.equal(evaluateExpression("${INTERACTION_MODE} == auto", { INTERACTION_MODE: "interactive" }), false);
115
+ for (const source of ["process.exit(0)", "globalThis[\"x\"]", "() => true", "true; false"]) {
116
+ assert.throws(() => evaluateExpression(source, {}), (error) => error.code === "UNSUPPORTED_EXPRESSION");
117
+ }
118
+ });
119
+
120
+ test("all success predicates compose without treating missing artifacts as success", () => {
121
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "dag-success-"));
122
+ fs.writeFileSync(path.join(root, "one.txt"), "1");
123
+ fs.writeFileSync(path.join(root, "two.json"), "{}");
124
+ fs.mkdirSync(path.join(root, "dir"));
125
+ const checker = path.join(root, "check.mjs");
126
+ fs.writeFileSync(checker, "process.exit(0);\n");
127
+ const doc = baseDoc([{ id: "a" }, { id: "b", needs: ["a"] }]);
128
+ const context = {
129
+ vars: { ROOT: root, FLAG: true },
130
+ cwd: root,
131
+ graph: buildGraph(doc),
132
+ node: doc.nodes[1],
133
+ state: { nodes: { a: { status: "done" }, b: { status: "running" } } },
134
+ };
135
+ assert.equal(evaluateSuccess({ all: [
136
+ { file_exists: "${ROOT}/one.txt" },
137
+ { dir_exists: "${ROOT}/dir" },
138
+ { glob_nonempty: "${ROOT}/*.json" },
139
+ { script_exit_0: { runner: "node", script: "${ROOT}/check.mjs" } },
140
+ { any: [{ file_exists: "${ROOT}/missing" }, { when: "${FLAG} == true" }] },
141
+ { all_needs_terminal: true },
142
+ ] }, context), true);
143
+ assert.equal(evaluateSuccess({ skipped: true }, { ...context, status: "skipped" }), true);
144
+ assert.equal(evaluateSuccess({ file_exists: "${ROOT}/missing" }, context), false);
145
+ assert.throws(() => evaluateSuccess({ arbitrary: true }, context), (error) => error.code === "UNSUPPORTED_SUCCESS_RULE");
146
+ });
147
+
148
+ test("runner is serial and owns profile, skip_if and reuse decisions", async () => {
149
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "dag-serial-worker-"));
150
+ const worker = makeWorker(root, `fs.appendFileSync(req.vars.ORDER, req.node + "\\n"); write({ status: "done" });`);
151
+ const order = path.join(root, "order.txt");
152
+ const doc = baseDoc([
153
+ { id: "a", lane: "run" },
154
+ { id: "b", lane: "run" },
155
+ { id: "c", lane: "run", needs: ["a", "b"] },
156
+ { id: "d", lane: "cut" },
157
+ { id: "e", lane: "run", skip_if: "${SKIP_E} == true" },
158
+ { id: "f", lane: "run", runner: { action: "external", reuse_if: "${REUSE_F} == true" } },
159
+ ], { profiles: { full: { include_lanes: ["run"] } } });
160
+ const r = await runDoc(doc, { executorCommand: worker.command, vars: { ORDER: order, SKIP_E: true, REUSE_F: true } });
161
+ assert.equal(r.state.status, "completed", JSON.stringify(r.state.error));
162
+ assert.deepEqual(lines(order), ["a", "b", "c"]);
163
+ assert.equal(r.state.nodes.d.status, "skipped");
164
+ assert.equal(r.state.nodes.e.status, "skipped");
165
+ assert.equal(r.state.nodes.f.status, "reused");
166
+ const ledger = readLedger(r.ledger);
167
+ assert.equal(ledger.filter((record) => record.event === "run_end").length, 1);
168
+ assert.deepEqual(ledger.filter((record) => record.event === "node_start").map((record) => record.node), ["a", "b", "c"]);
169
+ for (const id of ["a", "b", "c"]) {
170
+ const terminal = ledger.find((record) => record.event === "node" && record.node === id);
171
+ assert.ok(Number.isFinite(Date.parse(terminal.started_at)), id);
172
+ assert.ok(Number.isInteger(terminal.duration_s) && terminal.duration_s >= 0, id);
173
+ }
174
+ });
175
+
176
+ test("business fail_matrix policies hard-stop, soft-continue, or skip only when logic is skipped", async () => {
177
+ for (const [policy, skipLogic, expected, downstream] of [
178
+ ["hard_stop", false, "failed", "pending"],
179
+ ["soft_continue", false, "completed_with_failures", "done"],
180
+ ["hard_stop_unless_logic_skipped", true, "completed", "done"],
181
+ ]) {
182
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "dag-policy-worker-"));
183
+ const worker = makeWorker(root, `req.node === "a" ? write({ status: "failed", reason: "bad input" }) : write({ status: "done" });`);
184
+ const doc = baseDoc([{ id: "a", on_fail: policy }, { id: "b", needs: ["a"] }]);
185
+ const r = await runDoc(doc, { executorCommand: worker.command, vars: { SKIP_LOGIC: skipLogic } });
186
+ assert.equal(r.state.status, expected, policy);
187
+ assert.equal(r.state.nodes.a.status, policy === "hard_stop_unless_logic_skipped" ? "skipped" : "failed");
188
+ assert.equal(r.state.nodes.b.status, downstream, policy);
189
+ assert.equal(readLedger(r.ledger).some((record) => record.event === "run_end"), policy !== "hard_stop");
190
+ }
191
+ });
192
+
193
+ test("explicit business retries stop at the configured limit", async () => {
194
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "dag-retry-worker-"));
195
+ const worker = makeWorker(root, `const n = count(); n < 3 ? write({ status: "failed", reason: "try " + n }) : write({ status: "done" });`);
196
+ const count = path.join(root, "count.json");
197
+ const r = await runDoc(baseDoc([{ id: "a", runner: { action: "external", retry: 2 } }]), {
198
+ executorCommand: worker.command,
199
+ vars: { COUNT: count },
200
+ });
201
+ assert.equal(r.state.status, "completed");
202
+ assert.equal(r.state.nodes.a.attempt_count, 3);
203
+ assert.deepEqual(r.state.attempts.map((attempt) => attempt.status), ["failed", "failed", "done"]);
204
+ });
205
+
206
+ test("protocol early-stop recovery does not consume the business retry budget", async () => {
207
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "dag-protocol-retry-worker-"));
208
+ const worker = makeWorker(root, `const n = count(); if (n === 1) {} else if (n === 2) write({ status: "failed", reason: "business" }); else write({ status: "done" });`);
209
+ const count = path.join(root, "count.json");
210
+ const r = await runDoc(baseDoc([{ id: "a", runner: { action: "external", retry: 1 } }]), {
211
+ executorCommand: worker.command,
212
+ vars: { COUNT: count },
213
+ });
214
+ assert.equal(r.state.status, "blocked");
215
+ assert.equal(r.state.error.code, "EXECUTOR_EARLY_STOP");
216
+ const runId = r.state.run_id;
217
+ const recovered = await advance({ state: r.statePath });
218
+ assert.equal(recovered.status, "completed", JSON.stringify(recovered.error));
219
+ assert.equal(recovered.run_id, runId);
220
+ assert.equal(recovered.nodes.a.attempt_count, 3);
221
+ assert.equal(readLedger(r.ledger).filter((record) => record.event === "run_start").length, 1);
222
+ });
223
+
224
+ test("missing executor, unknown action/success and empty results block without soft-continuation", async () => {
225
+ const missing = await runDoc(baseDoc([{ id: "a", on_fail: "soft_continue" }]));
226
+ assert.equal(missing.state.status, "blocked");
227
+ assert.equal(missing.state.error.code, "EXECUTOR_NOT_CONFIGURED");
228
+ assert.equal(readLedger(missing.ledger).some((record) => record.event === "node" && record.node === "a"), false);
229
+
230
+ const unknown = await runDoc(baseDoc([{ id: "a", runner: { action: "mystery" } }]), { executorCommand: "unused" });
231
+ assert.equal(unknown.state.error.code, "UNSUPPORTED_NODE_ACTION");
232
+ assert.equal(unknown.state.attempts.length, 0);
233
+
234
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "dag-empty-worker-"));
235
+ const empty = makeWorker(root, `fs.writeFileSync(process.env.A2H_DAG_RESULT, "");`);
236
+ const emptyResult = await runDoc(baseDoc([{ id: "a", on_fail: "soft_continue" }]), { executorCommand: empty.command });
237
+ assert.equal(emptyResult.state.status, "blocked");
238
+ assert.equal(emptyResult.state.error.code, "EXECUTOR_INVALID_RESULT");
239
+ assert.equal(readLedger(emptyResult.ledger).some((record) => record.event === "node" && record.node === "a"), false);
240
+
241
+ const doneRoot = fs.mkdtempSync(path.join(os.tmpdir(), "dag-unknown-success-worker-"));
242
+ const done = makeWorker(doneRoot, `write({ status: "done" });`);
243
+ const badSuccess = await runDoc(baseDoc([{ id: "a", success: [{ mystery: true }] }]), { executorCommand: done.command });
244
+ assert.equal(badSuccess.state.error.code, "UNSUPPORTED_SUCCESS_RULE");
245
+ assert.equal(readLedger(badSuccess.ledger).some((record) => record.event === "node" && record.node === "a"), false);
246
+ });
247
+
248
+ test("waiting_external completes asynchronously and a current duplicate callback is idempotent", async () => {
249
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "dag-wait-worker-"));
250
+ const worker = makeWorker(root, `req.node === "a" ? write({ status: "waiting_external", wait: { token: "x" } }) : write({ status: "done" });`);
251
+ const r = await runDoc(baseDoc([{ id: "a" }, { id: "b", needs: ["a"] }]), { executorCommand: worker.command });
252
+ assert.equal(r.state.status, "waiting_external");
253
+ assert.equal(r.state.nodes.b.status, "pending");
254
+ const attemptId = r.state.nodes.a.current_attempt_id;
255
+ const result = path.join(root, "async-result.json");
256
+ fs.writeFileSync(result, JSON.stringify({ attempt_id: attemptId, status: "done", evidence: { token: "x" } }));
257
+ const completed = await completeAttempt({ state: r.statePath, attemptId, resultFile: result });
258
+ assert.equal(completed.status, "completed");
259
+ const before = fs.readFileSync(r.ledger, "utf8");
260
+ const duplicate = await completeAttempt({ state: r.statePath, attemptId, resultFile: result });
261
+ assert.equal(duplicate.status, "completed");
262
+ assert.equal(fs.readFileSync(r.ledger, "utf8"), before);
263
+ });
264
+
265
+ test("an old failed attempt cannot complete after a newer attempt is current", async () => {
266
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "dag-stale-worker-"));
267
+ const worker = makeWorker(root, `req.attempt.index === 1 ? write({ status: "waiting_external" }) : write({ status: "done" });`);
268
+ const r = await runDoc(baseDoc([{ id: "a", runner: { action: "external", retry: 1 } }]), { executorCommand: worker.command });
269
+ const attemptId = r.state.nodes.a.current_attempt_id;
270
+ const result = path.join(root, "late.json");
271
+ fs.writeFileSync(result, JSON.stringify({ attempt_id: attemptId, status: "failed", reason: "retry" }));
272
+ const completed = await completeAttempt({ state: r.statePath, attemptId, resultFile: result });
273
+ assert.equal(completed.status, "completed");
274
+ assert.notEqual(completed.nodes.a.current_attempt_id, attemptId);
275
+ await assert.rejects(completeAttempt({ state: r.statePath, attemptId, resultFile: result }), (error) => error.code === "STALE_ATTEMPT");
276
+ });
277
+
278
+ test("waiting_human only advances through the current gate confirmation", async () => {
279
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "dag-human-worker-"));
280
+ const worker = makeWorker(root, `write({ status: "waiting_human" });`);
281
+ const r = await runDoc(baseDoc([{ id: "gate" }]), { executorCommand: worker.command });
282
+ assert.equal(r.state.status, "waiting_human");
283
+ const confirmed = await confirmGate({ state: r.statePath, node: "gate", confirmedBy: "tester" });
284
+ assert.equal(confirmed.status, "completed");
285
+ assert.equal(confirmed.attempts[0].confirmed_by, "tester");
286
+ await assert.rejects(confirmGate({ state: r.statePath, node: "gate" }), (error) => error.code === "INVALID_GATE_STATE");
287
+ });
288
+
289
+ test("ledger_commit recovery covers before/after append and rejects conflicting records", async () => {
290
+ for (const appended of [false, true]) {
291
+ const f = fixture(baseDoc([{ id: "a" }]));
292
+ const started = startRun({ workflow: f.workflow, runDir: f.runDir, state: f.statePath, ledger: f.ledger, profile: "full" });
293
+ if (appended) appendLedger(f.ledger, { event: "node", run_id: started.run_id, node: "a", status: "done" });
294
+ const state = loadRunState(f.statePath);
295
+ state.ledger_commit = { run_id: started.run_id, node: "a", status: "done" };
296
+ fs.writeFileSync(f.statePath, JSON.stringify(state));
297
+ const recovered = recover({ state: f.statePath });
298
+ assert.equal(recovered.nodes.a.status, "done");
299
+ assert.equal(recovered.ledger_commit, null);
300
+ assert.equal(readLedger(f.ledger).filter((record) => record.event === "node" && record.node === "a").length, 1);
301
+ }
302
+
303
+ const f = fixture(baseDoc([{ id: "a" }]));
304
+ const started = startRun({ workflow: f.workflow, runDir: f.runDir, state: f.statePath, ledger: f.ledger, profile: "full" });
305
+ appendLedger(f.ledger, { event: "node", run_id: started.run_id, node: "a", status: "failed", reason: "different" });
306
+ const state = loadRunState(f.statePath);
307
+ state.ledger_commit = { run_id: started.run_id, node: "a", status: "done" };
308
+ fs.writeFileSync(f.statePath, JSON.stringify(state));
309
+ assert.throws(() => recover({ state: f.statePath }), (error) => error.code === "LEDGER_STATE_CONFLICT");
310
+ });
311
+
312
+ test("same-run recovery consumes an already persisted result instead of rerunning it", async () => {
313
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "dag-result-recovery-worker-"));
314
+ const worker = makeWorker(root, `count(); write({ status: "waiting_external" });`);
315
+ const count = path.join(root, "count.json");
316
+ const r = await runDoc(baseDoc([{ id: "a" }]), { executorCommand: worker.command, vars: { COUNT: count } });
317
+ const state = loadRunState(r.statePath);
318
+ state.status = "running";
319
+ state.nodes.a.status = "running";
320
+ state.attempts[0].status = "running";
321
+ fs.writeFileSync(r.statePath, JSON.stringify(state));
322
+ fs.writeFileSync(state.attempts[0].result_path, JSON.stringify({ attempt_id: state.attempts[0].attempt_id, status: "done" }));
323
+ const recovered = await advance({ state: r.statePath });
324
+ assert.equal(recovered.status, "completed", JSON.stringify(recovered.error));
325
+ assert.equal(recovered.run_id, r.state.run_id);
326
+ assert.equal(recovered.attempts.length, 1);
327
+ assert.equal(JSON.parse(fs.readFileSync(count, "utf8")), 1);
328
+ });
329
+
330
+ test("FROM_NODE resume inherits profile artifacts and soft failures, then survives another interruption", async () => {
331
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "dag-resume-worker-"));
332
+ const worker = makeWorker(root, `
333
+ if (req.node === "a") { count(); fs.writeFileSync(req.vars.A_ART, "ok"); write({ status: "done" }); }
334
+ else if (req.node === "b") write({ status: "failed", reason: "known soft failure" });
335
+ else { const n = count(); if (req.vars.RESUME_MODE && n === 3) {} else write({ status: "done" }); }
336
+ `);
337
+ const count = path.join(root, "count.json");
338
+ const artifact = path.join(root, "a.ok");
339
+ const doc = baseDoc([
340
+ { id: "bootstrap", skip_if: "true", actions: [
341
+ { ask_run_config_once: { reuse: { map: { REUSE_A: [1] } } } },
342
+ { probe_all_artifacts: { entries: { 1: { node: "a", all: ["${A_ART}"] } } } },
343
+ ] },
344
+ { id: "a", needs: ["bootstrap"], skip_if: "${REUSE_A} == true" },
345
+ { id: "b", needs: ["a"], on_fail: "soft_continue" },
346
+ { id: "c", needs: ["b"] },
347
+ ]);
348
+ const original = await runDoc(doc, {
349
+ executorCommand: worker.command,
350
+ vars: { COUNT: count, A_ART: artifact, REUSE_A: false, RESUME_MODE: false },
351
+ });
352
+ assert.equal(original.state.status, "completed_with_failures", JSON.stringify(original.state.error));
353
+ const resumedRunDir = path.join(original.root, "resumed-run");
354
+ const resumedState = path.join(resumedRunDir, "dag-run-state.json");
355
+ const started = startRun({
356
+ workflow: original.workflow,
357
+ runDir: resumedRunDir,
358
+ state: resumedState,
359
+ ledger: original.ledger,
360
+ profile: "resume",
361
+ resumeFrom: "c",
362
+ vars: { COUNT: count, A_ART: artifact, RESUME_MODE: true },
363
+ executorCommand: worker.command,
364
+ });
365
+ const interrupted = await advance({ state: resumedState });
366
+ assert.equal(interrupted.status, "blocked");
367
+ assert.equal(interrupted.error.code, "EXECUTOR_EARLY_STOP");
368
+ const resumed = await advance({ state: resumedState });
369
+ assert.equal(resumed.status, "completed_with_failures", JSON.stringify(resumed.error));
370
+ assert.equal(resumed.run_id, started.run_id);
371
+ assert.equal(resumed.nodes.a.status, "skipped");
372
+ assert.equal(resumed.nodes.b.status, "failed");
373
+ assert.equal(resumed.nodes.c.status, "done");
374
+ assert.equal(readLedger(original.ledger).filter((record) => record.event === "run_start").length, 2);
375
+ assert.equal(readLedger(original.ledger).filter((record) => record.event === "node" && record.run_id === started.run_id && record.node === "b").length, 1);
376
+ });
377
+
378
+ test("finalize cannot certify missing evidence, including soft_continue, and run_end stays unique", async () => {
379
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "dag-finalize-worker-"));
380
+ const worker = makeWorker(root, `if (req.vars.WRITE_REPORT) fs.writeFileSync(req.vars.LOGIC_REPORT, "report"); write({ status: "done" });`);
381
+ const bad = await runDoc(baseDoc([{ id: "logic.finalize", on_fail: "soft_continue", success: [{ file_exists: "${LOGIC_REPORT}" }] }]), {
382
+ executorCommand: worker.command,
383
+ vars: { WRITE_REPORT: false },
384
+ });
385
+ assert.equal(bad.state.status, "blocked");
386
+ assert.equal(bad.state.error.code, "FINALIZE_FAILED");
387
+ assert.equal(readLedger(bad.ledger).some((record) => record.event === "run_end"), false);
388
+
389
+ const good = await runDoc(baseDoc([{ id: "logic.finalize", success: [{ file_exists: "${LOGIC_REPORT}" }] }]), {
390
+ executorCommand: worker.command,
391
+ vars: { WRITE_REPORT: true },
392
+ });
393
+ assert.equal(good.state.status, "completed", JSON.stringify(good.state.error));
394
+ const before = fs.readFileSync(good.ledger, "utf8");
395
+ const again = await advance({ state: good.statePath });
396
+ assert.equal(again.status, "completed");
397
+ assert.equal(fs.readFileSync(good.ledger, "utf8"), before);
398
+ assert.equal(readLedger(good.ledger).filter((record) => record.event === "run_end").length, 1);
399
+ });
400
+
401
+ test("real CLI runs, completes an async attempt, and continues without another certificate", async () => {
402
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "dag-cli-worker-"));
403
+ const worker = makeWorker(root, `req.node === "a" ? write({ status: "waiting_external" }) : write({ status: "done" });`);
404
+ const f = fixture(baseDoc([{ id: "a" }, { id: "b", needs: ["a"] }]));
405
+ const invoke = (...args) => spawnSync(process.execPath, [RUNNER, ...args], { encoding: "utf8" });
406
+ const started = invoke("run", "--workflow", f.workflow, "--run-dir", f.runDir, "--state", f.statePath,
407
+ "--ledger", f.ledger, "--profile", "full", "--vars", "{}", "--executor-command", worker.command);
408
+ assert.equal(started.status, 1, started.stderr);
409
+ assert.equal(JSON.parse(started.stdout).status, "waiting_external");
410
+ const state = loadRunState(f.statePath);
411
+ const attemptId = state.nodes.a.current_attempt_id;
412
+ const result = path.join(root, "cli-result.json");
413
+ fs.writeFileSync(result, JSON.stringify({ attempt_id: attemptId, status: "done" }));
414
+ const completed = invoke("complete", "--state", f.statePath, "--attempt-id", attemptId, "--result-file", result);
415
+ assert.equal(completed.status, 0, completed.stderr);
416
+ assert.equal(JSON.parse(completed.stdout).status, "completed");
417
+ const before = fs.readFileSync(f.ledger, "utf8");
418
+ const continued = invoke("continue", "--state", f.statePath);
419
+ assert.equal(continued.status, 0, continued.stderr);
420
+ assert.equal(fs.readFileSync(f.ledger, "utf8"), before);
421
+ const status = invoke("status", "--state", f.statePath);
422
+ assert.equal(JSON.parse(status.stdout).status, "completed");
423
+ });
@@ -90,15 +90,32 @@ test("the page-specgen leaf keeps its gaps out of the app-migrate report", () =>
90
90
  assert.doesNotMatch(finalize, /gaps must go into the final report/);
91
91
  });
92
92
 
93
+ test("logic.finalize leaves terminal recording and DAG certification to the Runner", () => {
94
+ const finalize = byId["logic.finalize"];
95
+ assert.deepEqual(finalize.success, [{ file_exists: "${LOGIC_REPORT}" }]);
96
+ assert.equal(finalize.runner.action, "production");
97
+ assert.equal(finalize.runner.kind, "host_action");
98
+
99
+ const inv = finalize.invoke;
100
+ assert.match(inv, /不要自行追加 logic\.finalize 终态或 run_end/);
101
+ assert.match(inv, /Runner 先核对报告并提交唯一的 logic\.finalize done/);
102
+ assert.match(inv, /写唯一 run_end/);
103
+ assert.doesNotMatch(inv, /--node logic\.finalize --status done/);
104
+ assert.doesNotMatch(inv, /--write-run-end/);
105
+ });
106
+
93
107
  test("review.spec_gen: 重跑 says plainly that it does not refreeze the UTG snapshot (N12)", () => {
94
108
  const inv = byId["review.spec_gen"].invoke;
95
109
  assert.doesNotMatch(inv, /修 Android 侧或 UTG 再生成/);
96
110
  assert.match(inv, /修 UTG 不会因此生效[\s\S]*reuse_discover_utg=false/);
97
111
  });
98
112
 
99
- test("gates: 重跑 first turns off the producer's REUSE_* so its skip_if no longer fires (L5)", () => {
113
+ test("gates: rewind clears the producer's runner.reuse_if instead of conflating reuse with skip_if (L5)", () => {
100
114
  for (const [gate, producer, v] of [["review.arch", "discover.arch", "REUSE_DISCOVER_ARCH"], ["review.spec_gen", "enrich.spec_gen", "REUSE_SPEC_GENERATE"], ["review.ui_batch", "ui.batch", "REUSE_UI_BATCH"]]) {
101
- assert.match(byId[producer].skip_if, new RegExp(v));
115
+ assert.match(byId[producer].runner.reuse_if, new RegExp(v));
116
+ assert.doesNotMatch(String(byId[producer].skip_if || ""), new RegExp(v));
117
+ assert.equal(byId[gate].runner.rewind_to, producer);
118
+ assert.deepEqual(byId[gate].runner.rewind_clear_vars, [v]);
102
119
  const reruns = byId[gate].invoke.split("\n").filter((l) => l.includes("`重跑` →"));
103
120
  assert.ok(reruns.length > 0, gate);
104
121
  for (const l of reruns) assert.match(l, new RegExp(`先置 ${v}=false`), `${gate}: ${l}`);
@@ -111,7 +128,7 @@ test("ui-only keeps logic.finalize so soft_continue failures still get a report
111
128
  assert.ok(!ui.force_skip.includes("finalize") && !ui.force_skip.includes("logic.finalize"));
112
129
  assert.ok(ui.force_skip.includes("logic"), "the logic pipeline itself stays out");
113
130
  const inv = byId["logic.finalize"].invoke;
114
- assert.match(inv, /0\. logic\.spec_pipeline 本轮被 skip[^\n]*\$\{PROFILE\} == ui-only/);
115
- assert.match(inv, /跳过([^\n]*\$\{PROFILE\} == ui-only)→ \*\*不读\*\*/);
131
+ assert.match(inv, /0\. logic\.spec_pipeline 本轮被 skip[^\n]*\$\{PROFILE\} == 'ui-only'/);
132
+ assert.match(inv, /跳过([^\n]*\$\{PROFILE\} == 'ui-only')→ \*\*不读\*\*/);
116
133
  assert.match(inv, /ledger/i);
117
134
  });
@@ -82,7 +82,7 @@ test("bootstrap env-probes image-read; ui.batch re-probes; skip env probe when U
82
82
  assert.equal(tip.skip_when, "${IMAGE_READ} != false or ${REUSE_UI_BATCH} == true");
83
83
  const probe = boot.actions.map((a) => a.probe_image_read).find(Boolean);
84
84
  assert.ok(probe, "bootstrap.probe_image_read is missing");
85
- assert.equal(probe.skip_when, "${IMAGE_READ} != probe or ${REUSE_UI_BATCH} == true");
85
+ assert.equal(probe.skip_when, "${IMAGE_READ} != 'probe' or ${REUSE_UI_BATCH} == true");
86
86
  assert.match(doc.policy.image_read, /REUSE_UI_BATCH == true|不跑 ui\.batch 时跳过/);
87
87
  assert.match(doc.policy.image_read, /再探测一次|互不沿用/);
88
88
  assert.match(doc.policy.image_read, /禁止.*传.*image_read=/);
@@ -109,6 +109,21 @@ test("no ledger: the base profile must be given; switching profile is refused; F
109
109
  assert.throws(() => planResume(doc, [], { fromNode: "ui.batch", baseProfile: "logic-only" }), (e) => e.code === 2 && /logic-only/.test(e.message));
110
110
  });
111
111
 
112
+ test("ledger.mjs --failures lists only nodes whose last record in this run is failed (rewind supersedes)", () => {
113
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ledger-gen-"));
114
+ const L = path.join(dir, "stage-ledger.jsonl");
115
+ appendLedger(L, { event: "run_start", profile: "full", from_node: "bootstrap", resume: false });
116
+ appendLedger(L, { event: "node", node: "ui.batch", status: "failed", reason: "device lost", generation: 0 });
117
+ appendLedger(L, { event: "node", node: "enrich.module_docs", status: "done", generation: 0 });
118
+ appendLedger(L, { event: "rewind", node: "review.ui_batch", target: "ui.batch", generation: 1 });
119
+ appendLedger(L, { event: "node", node: "ui.batch", status: "done", generation: 1 });
120
+ appendLedger(L, { event: "node", node: "enrich.module_docs", status: "failed", reason: "json5", generation: 1 });
121
+ const out = spawnSync(process.execPath, [LEDGER_JS, "--ledger", L, "--failures"], { encoding: "utf8" });
122
+ assert.equal(out.status, 0, out.stderr);
123
+ assert.deepEqual(JSON.parse(out.stdout), [{ node: "enrich.module_docs", reason: "json5" }],
124
+ "ui.batch recovered after the rewind; module_docs failed in its latest generation");
125
+ });
126
+
112
127
  test("ledger.mjs: append-only across runs; --failures reads only the current run", () => {
113
128
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ledger-"));
114
129
  const L = path.join(dir, "stage-ledger.jsonl");
@@ -143,7 +158,7 @@ test("bootstrap runs plan_resume first so the run dirs are resolved from the led
143
158
  // args / when unchanged: still only consumes SKILLS_ROOT / LEDGER / FROM_NODE / RESUME_BASE_PROFILE
144
159
  const plan = boot.actions.map((a) => a.plan_resume).find(Boolean);
145
160
  assert.match(plan.args, /--ledger \$\{LEDGER\} --from-node \$\{FROM_NODE\}/);
146
- assert.match(plan.when, /\$\{PROFILE\} == resume/);
161
+ assert.match(plan.when, /\$\{PROFILE\} == 'resume'/);
147
162
  assert.doesNotMatch(plan.exit_0, /last_engine/, "exit_0 no longer backfills the engine");
148
163
  // The engine carry-over actions are gone: bootstrap has no resolve_last_engine / resolve_case_id
149
164
  assert.equal(at("resolve_last_engine"), -1, names.join(","));
@@ -102,7 +102,7 @@ test("ui.batch reuses discover's workspace only by copying, and only when discov
102
102
  const utg = doc.nodes.find((n) => n.id === "discover.utg_static").invoke;
103
103
  assert.match(ui, /reuse_static_utg\.mjs --from \$\{UTG_DIR\} --to \$\{UI_UTG_DIR\}/);
104
104
  assert.match(ui, /REUSE_DISCOVER_UTG/);
105
- assert.match(ui, /PROFILE\} == ui-only/);
105
+ assert.match(ui, /PROFILE\} == 'ui-only'/);
106
106
  assert.match(ui, /不写回 \$\{UTG_DIR\}/);
107
107
  assert.match(utg, /--lang <locale>/);
108
108
  assert.match(utg, /persist\.sys\.locale/);
@@ -85,8 +85,14 @@ test("workflow: utg_static success, probe and invoke all use the check", () => {
85
85
  test("workflow: utg_static is skipped whenever no spec generation will consume it; snapshot never hard-stops on that", () => {
86
86
  const doc = yaml.load(fs.readFileSync(WORKFLOW, "utf8"));
87
87
  const byId = Object.fromEntries(doc.nodes.map((n) => [n.id, n]));
88
- const noSpec = ["${SKIP_LOGIC}", "${SKIP_SPEC_GENERATE}", "${REUSE_SPEC_GENERATE} == true", "${PROFILE} == ui-only"];
89
- for (const c of noSpec) assert.ok(byId["discover.utg_static"].skip_if.includes(c), `utg_static skip_if lacks ${c}`);
88
+ const skipNoSpec = ["${SKIP_LOGIC}", "${SKIP_SPEC_GENERATE}", "${REUSE_SPEC_GENERATE} == true", "${PROFILE} == 'ui-only'"];
89
+ for (const c of skipNoSpec) assert.ok(byId["discover.utg_static"].skip_if.includes(c), `utg_static skip_if lacks ${c}`);
90
+ // The consumer's reuse (REUSE_SPEC_GENERATE) skips it; its own reuse is owned by runner.reuse_if, not skip_if.
91
+ assert.doesNotMatch(byId["discover.utg_static"].skip_if.replace("${REUSE_SPEC_GENERATE}", ""), /REUSE_/);
92
+ // Same condition as the snapshot it feeds: otherwise utg_static runs (hard_stop on failure) while the snapshot ignores it.
93
+ const ensure = byId["discover.utg_snapshot"].actions.find((a) => a.ensure_utg_snapshot).ensure_utg_snapshot;
94
+ assert.equal(ensure.when, `not (${byId["discover.utg_static"].skip_if})`);
95
+ assert.match(byId["discover.utg_static"].runner.reuse_if, /REUSE_DISCOVER_UTG/);
90
96
  const snap = byId["discover.utg_snapshot"];
91
97
  assert.equal(snap.skip_if, undefined, "snapshot keeps running: its precondition is ui.batch's arch gate");
92
98
  assert.match(JSON.stringify(snap.actions), /"when":"not \(/);
@@ -164,9 +170,10 @@ test("workflow: arch reuse does not hinge on utg_static (which skips legitimatel
164
170
  assert.deepEqual(map.REUSE_DISCOVER_UTG, [1]);
165
171
  assert.ok(!("REUSE_DISCOVER" in map) && !("REUSE_DISCOVER" in doc.vars));
166
172
  const byId = Object.fromEntries(doc.nodes.map((n) => [n.id, n]));
167
- assert.match(byId["discover.arch"].skip_if, /REUSE_DISCOVER_ARCH/);
168
- assert.doesNotMatch(byId["discover.arch"].skip_if, /REUSE_DISCOVER_UTG/);
169
- assert.match(byId["discover.utg_static"].skip_if, /REUSE_DISCOVER_UTG/);
173
+ assert.match(byId["discover.arch"].runner.reuse_if, /REUSE_DISCOVER_ARCH/);
174
+ assert.doesNotMatch(byId["discover.arch"].skip_if, /REUSE_DISCOVER_(ARCH|UTG)/);
175
+ assert.match(byId["discover.utg_static"].runner.reuse_if, /REUSE_DISCOVER_UTG/);
176
+ assert.doesNotMatch(byId["discover.utg_static"].skip_if, /REUSE_DISCOVER_UTG/);
170
177
  for (const v of ["REUSE_DISCOVER_ARCH", "REUSE_DISCOVER_UTG"]) assert.ok(doc.vars[v].from.includes("reuse_discover"), v);
171
178
  });
172
179
 
@@ -146,14 +146,13 @@ extraction to the commit.
146
146
  (unresolved key, lock budget, moved document) takes the same fallback with the key and error
147
147
  recorded. Never guess silently and never block the chunk on the docs.
148
148
 
149
- **Platform API doc gate (soft).** When the chunk calls a platform API whose call shape the
150
- worktree does not already show, run the gate in `references/code-generation.md` Step 2 — it owns
151
- the trigger, the `state_doc.mjs search` / `read-id --section` commands, the
152
- worktree > `.d.ts` > docs precedence, the per-chunk budget and the API-level check. Record the
153
- rows plus `api-docs: available` / `unavailable` / `not-applicable` in the same
154
- `state_docs_used.md`. With `api-docs-mode: unavailable`, skip the wrapper and record
155
- `api-docs: unavailable`; this gate never blocks the chunk and never changes the `state-docs`
156
- verdict.
149
+ **Platform API doc gate (shape: soft; semantics: mandatory).** `references/code-generation.md`
150
+ Step 2 owns the trigger, commands, precedence and record. A working call site may satisfy a shape
151
+ query; a call whose correctness depends on meaning — targets, ordering, capability level, units,
152
+ addressed keys — must read the official page, and its record needs one verbatim sentence from it
153
+ (a `SDK .d.ts` row does not count). Never record `available` without that sentence. A failed read
154
+ is recorded `unavailable` and the chunk continues — the gate never blocks; only the shape half is
155
+ skippable.
157
156
 
158
157
  Do the code generation, its scenario self-check (up to 3 iterations), and its
159
158
  MVVM + px/vp unit hook checks. Do not re-plan or override that workflow.
@@ -7,4 +7,4 @@
7
7
  * 文本测量结果是 px,不是 vp:`MeasureText.measureText` / `measureTextSize`(`@ohos.measure`)和 `getUIContext().getMeasureUtils()` 的同名方法,入参 `fontSize` 是 fp,但返回的宽高都是 **px**(`.d.ts` `@returns`:"both in px")。拿它和 vp 预算比较、或传给 `.width()` 之前,必须先 `this.getUIContext().px2vp(...)` 换算。实测(where-to-study 底部导航):把 `measureTextSize().width`(px)直接与 vp 格宽比较,在 3.5 倍密度下永远判定“放不下”,标签文字在任何设备上都不显示,而评审信了代码注释里“vp 输出”的说法。Canvas 的 `context.measureText()` 默认返回 vp,和它不同,不要混用经验。其他 API 的单位以 `.d.ts` 为准,见 code-generation.md Implementation Principle 6 的单位表;`scripts/check_units.ts` 会拦截这类写法。
8
8
  * 大量列表(歌曲、消息、动态等可能上百条的列表/网格)不要用 `ForEach`:它首次加载就创建全部子节点,条目多时首帧卡顿明显甚至白屏超时。优先 `LazyForEach` + `IDataSource` 按需创建屏幕内节点;注意数据源变更必须经 `notifyDataReload` / `notifyDataAdd` / `notifyDataChange` 等接口通知,整体替换数组而不通知时 UI 不刷新(配合 `@Observed`/`@ObjectLink` 时是已见过的坑)。固定少量选项(菜单、页签)仍用 `ForEach` 即可。
9
9
  * 跨「无类型边界」进入强类型代码的值一律按可空归一,不允许假设有值:反序列化结果、数据库行、本地缓存、跨页传参都算。ArkTS 的类型只是编译期标注,运行时不做校验,`as T` 不会补默认值,`null` 会原样进入实体;映射只判 `=== undefined` 就漏了它——读侧在 `.length`、遍历、方法调用处抛 `TypeError`(闪退),数值比较则把 `null` 静默当 0;写侧被非空约束拒绝而写不进库,或写进 JSON 后读回缺值(对象内的 `null` 仍是 `null`,`undefined` 属性的键直接消失)。规则:归一一律写在做「外部数据→实体」映射的那个函数里,没有就先补一个;字段声明成 `?: T | null`,缺失时用 `??` 取类型默认值(字符串 `''`、数值 `0`、数组 `[]`、对象 `{}`),整体兜住后再逐项、逐字段归一;读库按列的可空声明取值,不要用空串或 0 冒充缺失;兜底只用 `??`,不要 `||` 或 `if (!v)`,它们会把合法的 `0`、`''` 当空值。非空字段上写 `=== null` 不算兜底:漏掉 `undefined`,还会被判为无重叠比较;正解是先把声明改成 `?: T | null`。
10
- * 平台 API 别凭记忆写,也别凭一次搜索结果选页:参数顺序、同步/异步、生命周期(create → use → destroy/off)和返回值单位以本地 `.d.ts` 为准,调用顺序与用法用 `scripts/state_doc.mjs search "<模块或方法>"` + `read-id "<documentId>" --section "<小节标题>" --max-lines 80` 取一段(API 页动辄两三千行,整页读会把正文上下文挤掉;重载会重复同名小节,`--section` 会把几个同名小节全带出来并标 `<!-- section "request" 2/3 -->`,要挑某一个时加 `--occurrence <n>`)。工作区里已有同一 API 的可用调用点时直接照抄,不再查文档;文档与 `.d.ts` 冲突时以 `.d.ts` 为准;小节标题旁的 `phone 12+` 之类标签高于工程 `compatibleSdkVersion` 时改用低版本重载或 `canIUse`。查不到就记 `api-docs: unavailable`,走 `.d.ts` 和本文件,不要静默猜。
10
+ * 平台 API 别凭记忆写,也别凭一次搜索结果选页:参数顺序、同步/异步、生命周期(create → use → destroy/off)和返回值单位以本地 `.d.ts` 为准,调用顺序与用法用 `scripts/state_doc.mjs search "<模块或方法>"` + `read-id "<documentId>" --section "<小节标题>" --max-lines 80` 取一段(API 页动辄两三千行,整页读会把正文上下文挤掉;重载会重复同名小节,`--section` 会把几个同名小节全带出来并标 `<!-- section "request" 2/3 -->`,要挑某一个时加 `--occurrence <n>`)。工作区里已有同一 API 的可用调用点时:**形状**问题(参数顺序、同步/异步、生命周期、返回值单位)可直接照抄、`.d.ts` 优先于文档;**含义**问题(作用目标、执行顺序、权限等级、边界、读写哪个键)即使有调用点也必须读官方页面,并以页面为准,记录里摘一句原文;小节标题旁的 `phone 12+` 之类标签高于工程 `compatibleSdkVersion` 时改用低版本重载或 `canIUse`。查不到就记 `api-docs: unavailable`,走 `.d.ts` 和本文件继续,不要静默猜。