@tea-agent/loop-agent 0.52.0-next.9 → 0.53.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/CHANGELOG.md +36 -10
  2. package/dist/build-stamp.json +3 -3
  3. package/dist/executors/dag-pi/plan/finalize-tools.js +13 -0
  4. package/dist/executors/dag-pi/plan/record-tools.js +37 -11
  5. package/dist/executors/dag-pi/sessions/plan-batches.js +1 -1
  6. package/dist/executors/dag-pi/sessions/segmented-plan.js +28 -20
  7. package/dist/executors/dag-pi/tools/plan-decision-tools.js +2 -1
  8. package/dist/executors/dag-pi-executor.js +50 -5
  9. package/dist/executors/pi-executor.js +12 -0
  10. package/dist/executors/pi-sdk-executor.js +2 -2
  11. package/dist/shared/frontend-execution-policy.js +28 -2
  12. package/dist/shared/pi-context-pressure/compaction-policy.js +156 -150
  13. package/dist/shared/pi-context-pressure/extension.js +21 -14
  14. package/dist/shared/pi-context-pressure/index.js +1 -1
  15. package/dist/shared/pi-context-pressure/telemetry.js +10 -0
  16. package/dist/task/config-types.js +2 -2
  17. package/dist/task/source-prepare/prepare.js +1 -1
  18. package/dist/task/source-prepare/semantic-intake.js +2 -2
  19. package/dist/task/source-prepare/source-fidelity-pi.js +2 -1
  20. package/dist/worker/console/chat/assistant-content.js +21 -3
  21. package/dist/worker/console/chat/compaction-errors.js +28 -2
  22. package/dist/worker/console/chat/context-insights.js +4 -4
  23. package/dist/worker/console/chat/context-usage.js +4 -1
  24. package/dist/worker/console/chat/contract-apply-receipt-store.js +37 -25
  25. package/dist/worker/console/chat/pi-runtime.js +55 -119
  26. package/dist/worker/console/chat/routes.js +20 -0
  27. package/dist/worker/console/chat/turn-process.js +2 -0
  28. package/dist/worker/console/mutation-gate-receipt-store.js +38 -29
  29. package/dist/worker/console/pi-compaction-settings.js +72 -34
  30. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-BeB0jyn_.js → abnfDiagram-N423BO3Z-CR1jj_rz.js} +1 -1
  31. package/dist/worker/console/static/assets/{arc-B4E8rogW.js → arc-CjxcQfEu.js} +1 -1
  32. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-CuD5BPrV.js → architectureDiagram-T3A2C74G-D-3u2qFL.js} +1 -1
  33. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-DOR4BrbY.js → blockDiagram-VBNYF7ZC-Bdr7gWVo.js} +1 -1
  34. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-GuWkFUBT.js → c4Diagram-5PPSVZJV-hQHNe5T3.js} +1 -1
  35. package/dist/worker/console/static/assets/channel-CBlJfald.js +1 -0
  36. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-Bvp_6a1j.js → chunk-2GRJ4B5K-BEg_su6q.js} +1 -1
  37. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-zgyCBGFw.js → chunk-2Q5K7J3B-DZnV6VTC.js} +1 -1
  38. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-Bd7_XVhV.js → chunk-5RXB4S5H-Dg0LzAqO.js} +1 -1
  39. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-CO5JbujI.js → chunk-5VM5RSS4-D2vqr52W.js} +1 -1
  40. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-DPb24xsc.js → chunk-6Q2QTUOP-D8We_g6R.js} +1 -1
  41. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-D4OKjlIA.js → chunk-GF5L2VYU-DbEU8drD.js} +1 -1
  42. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-BdtF1gRX.js → chunk-JWPE2WC7-Boi8TJYN.js} +1 -1
  43. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-cSxCzmVA.js → chunk-KBJHAD2P-CjJmKa9f.js} +1 -1
  44. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-De4Oormb.js → chunk-RYQCIY6F-C-KV-ag7.js} +1 -1
  45. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-CMIvrR5C.js → chunk-XXDRQBXY-DZlTonsZ.js} +1 -1
  46. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-mNUYCdDo.js +1 -0
  47. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-mNUYCdDo.js +1 -0
  48. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-9SmHPXIr.js → cose-bilkent-JH36ORCC-BIvFe3yn.js} +1 -1
  49. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-wl-77tI0.js → cynefinDiagram-MW4NZA55-BOBPfv8u.js} +1 -1
  50. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-yqj9yJJQ.js → dagre-VZM6K2ZE-BF54orLO.js} +1 -1
  51. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-D-rMYS98.js → diagram-7IWD3JNH-CxjAP2AP.js} +1 -1
  52. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-CQFAofzl.js → diagram-B4RE2ZJO-BXYkuNGt.js} +1 -1
  53. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-CfUQmVKd.js → diagram-LBJQPF4R-DQTu-2Iy.js} +1 -1
  54. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-BkK1xnZN.js → diagram-Q27KOJAE-DNURuIYc.js} +1 -1
  55. package/dist/worker/console/static/assets/{diagram-UB23O5K3-BQQRT4QA.js → diagram-UB23O5K3-D69uANY8.js} +1 -1
  56. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR--rItMGHc.js → ebnfDiagram-BXEA7PRR-C658EcrV.js} +1 -1
  57. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-YO3gwIVo.js → erDiagram-JOGREHBK-BRccYtAl.js} +1 -1
  58. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-sVlorROr.js → flowDiagram-UKHOOZJN-DnIR4sLs.js} +1 -1
  59. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-DRBbNi-x.js → ganttDiagram-PKOTCBZU-Bo3eWFVC.js} +1 -1
  60. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-D0VaAfPP.js → gitGraphDiagram-DS77QQ5N-EyWDCNU_.js} +1 -1
  61. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-DtHpfgsg.js → infoDiagram-6WML65LV-B0Eld9u0.js} +1 -1
  62. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-Ea8r9FLd.js → ishikawaDiagram-WSZJBQD7-DsJQiJ27.js} +1 -1
  63. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-CVJVcKLc.js → journeyDiagram-NVQOT4AX-fpE0yqjC.js} +1 -1
  64. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-CUdymoGj.js → kanban-definition-27J2QSJJ-Dq9IrDdT.js} +1 -1
  65. package/dist/worker/console/static/assets/{linear-D5880Sph.js → linear-CFV4BDyf.js} +1 -1
  66. package/dist/worker/console/static/assets/main-D-ZQ4gLb.css +1 -0
  67. package/dist/worker/console/static/assets/{main-2IXI34Fw.js → main-Dwhb3ZRq.js} +126 -126
  68. package/dist/worker/console/static/assets/{mermaid.core-D6dkYx5V.js → mermaid.core-BMMXqtrB.js} +4 -4
  69. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-DhZljSlQ.js → mindmap-definition-FAOFIHXS-DurrK_Gi.js} +1 -1
  70. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-2S30TPom.js → pegDiagram-VL7TDLO6-CzZayNy2.js} +1 -1
  71. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-B9y_krb1.js → pieDiagram-7S7Q4E2Y-B1W7Y0cE.js} +1 -1
  72. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-C-XgJLT_.js → quadrantDiagram-CIZ2JOQS-BdbL83CU.js} +1 -1
  73. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-CTeVrhCo.js → railroadDiagram-AXF67PYL-W-bQpd18.js} +1 -1
  74. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-B7K6JWmy.js → requirementDiagram-LRYGKXZP-C9bi4tQJ.js} +1 -1
  75. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-QAlLfn7A.js → sankeyDiagram-W5VNT64P-D4kO56Wd.js} +1 -1
  76. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-BdWZWKdx.js → sequenceDiagram-SI44F4Z6-CIbesK1e.js} +1 -1
  77. package/dist/worker/console/static/assets/{sheet-workbook-BoC0pAy2.js → sheet-workbook-kFN3yUBr.js} +1 -1
  78. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-D6ASD67I.js → sizeCapture-X5ZJPWSS-Dk4XAK7C.js} +1 -1
  79. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-C3MgmUi2.js → stateDiagram-OKZ733FA-Bz9B6UZ7.js} +1 -1
  80. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-BBRlxIq8.js +1 -0
  81. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-Dqrd-WNB.js → swimlanes-SLNWSIFB-qLEds93n.js} +2 -2
  82. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-CRBvOMCQ.js +8 -0
  83. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-lQftYLJh.js → timeline-definition-Z64GVDOM-C9rVFC0h.js} +1 -1
  84. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-WA2DaCGk.js → vennDiagram-T6HMQDX7-CoKJ9hU0.js} +1 -1
  85. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-CFpLw8Jh.js → wardleyDiagram-T6FBY63Y-tHz_S7-L.js} +1 -1
  86. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-zgM9I8sM.js → xychartDiagram-ELKLHX3M-DKzKYnvG.js} +1 -1
  87. package/dist/worker/console/static/index.html +2 -2
  88. package/dist/worker/console/static-src/operator-chat/format-file-size.js +26 -0
  89. package/dist/workflows/dag/checkpoint.js +6 -1
  90. package/dist/workflows/dag/frontend-committed-facts.js +38 -5
  91. package/dist/workflows/dag/frontend-design-policy.js +22 -0
  92. package/dist/workflows/dag/frontend-implementation-contract.js +39 -12
  93. package/dist/workflows/dag/frontend-imported-run-artifacts.js +126 -0
  94. package/dist/workflows/dag/frontend-recovery-run.js +7 -110
  95. package/dist/workflows/dag/frontend-test-framework-adapters.js +14 -0
  96. package/dist/workflows/dag/frontend-verification-trace.js +20 -8
  97. package/dist/workflows/dag/frontend-writer-reuse.js +104 -0
  98. package/dist/workflows/dag/frontend-writer-status.js +0 -4
  99. package/dist/workflows/dag/hybrid/templates/frontend.js +15 -8
  100. package/dist/workflows/dag/init-hybrid.js +1 -1
  101. package/dist/workflows/dag/reconcile-run.js +11 -1
  102. package/dist/workflows/dag/recovery-lease.js +23 -0
  103. package/dist/workflows/dag/rerun-feedback.js +4 -2
  104. package/dist/workflows/dag/rerun-run.js +40 -0
  105. package/dist/workflows/dag/runner.js +11 -0
  106. package/dist/workflows/dag/terminal-status.js +2 -1
  107. package/package.json +3 -3
  108. package/dist/worker/console/static/assets/channel-DFwPpXxz.js +0 -1
  109. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-D9pWfL1L.js +0 -1
  110. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-D9pWfL1L.js +0 -1
  111. package/dist/worker/console/static/assets/main-Ckf7id9T.css +0 -1
  112. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-BEwsMVdO.js +0 -1
  113. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-D9l9u9WV.js +0 -8
@@ -0,0 +1,126 @@
1
+ import { mkdir, mkdtemp, readFile, readdir, realpath, rm, stat, writeFile } from "node:fs/promises";
2
+ import { createHash } from "node:crypto";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { writeFrontendContractReviewArtifacts } from "./frontend-implementation-contract.js";
6
+ import { FRONTEND_WRITER_ADMISSION_RESULT_ARTIFACT } from "./frontend-writer-admission.js";
7
+ const sha256Hex = (bytes) => createHash("sha256").update(bytes).digest("hex");
8
+ /** Imported nodes never execute again. Carry their run-owned outputs as well
9
+ * as their node records, and derive the bounded reader index from verified
10
+ * canonical bytes. Both automatic repair and explicit node reruns use this. */
11
+ async function collectFrontendRunArtifacts(input) {
12
+ const imported = new Set(input.importedNodeIds);
13
+ const nodeArtifacts = [];
14
+ const importedRunArtifacts = [];
15
+ const copy = async (nodeId, relativePath, required = true) => {
16
+ const normalized = relativePath.replace(/\\/g, "/");
17
+ if (path.posix.isAbsolute(normalized) || normalized.split("/").includes("..")) {
18
+ throw new Error(`imported frontend artifact must stay within the run: ${relativePath}`);
19
+ }
20
+ const sourcePath = path.join(input.parentRunDir, normalized);
21
+ try {
22
+ if (!(await stat(sourcePath)).isFile())
23
+ throw new Error(`imported frontend artifact is not a file: ${normalized}`);
24
+ }
25
+ catch (error) {
26
+ if (error.code !== "ENOENT")
27
+ throw error;
28
+ if (!required)
29
+ return undefined;
30
+ throw new Error(`missing imported artifact: ${normalized}`);
31
+ }
32
+ const sourceRoot = await realpath(input.parentRunDir);
33
+ if (!(await realpath(sourcePath)).startsWith(`${sourceRoot}${path.sep}`)) {
34
+ throw new Error(`imported frontend artifact resolves outside parent run: ${normalized}`);
35
+ }
36
+ const sourceBytes = await readFile(sourcePath);
37
+ const expected = sha256Hex(sourceBytes);
38
+ // All selected inputs are JSON facts. Reject corrupt input while still
39
+ // preparing outside the active lifecycle and before acquiring a lease.
40
+ JSON.parse(sourceBytes.toString("utf8"));
41
+ const destinationPath = path.join(input.newRunDir, normalized);
42
+ await mkdir(path.dirname(destinationPath), { recursive: true });
43
+ await writeFile(destinationPath, sourceBytes);
44
+ const actual = sha256Hex(await readFile(destinationPath));
45
+ if (actual !== expected)
46
+ throw new Error(`copy hash mismatch for artifact: ${normalized}`);
47
+ const artifact = { destinationRelativePath: normalized, sha256: actual };
48
+ nodeArtifacts.push({ nodeId, sourceRelativePath: normalized, ...artifact });
49
+ return artifact;
50
+ };
51
+ // The micro contract-import node only checks source freshness. Canonical
52
+ // outputs belong to design-policy and must be regenerated when it resets.
53
+ const policyNodeId = imported.has("frontend-design-policy-shell") ? "frontend-design-policy-shell" : undefined;
54
+ let canonicalContract;
55
+ if (policyNodeId) {
56
+ const policy = input.spec.tasks.find(task => task.shell?.frontendDesignPolicy)?.shell?.frontendDesignPolicy;
57
+ const relativePath = policy
58
+ ? path.posix.join(policy.outputDir, policy.artifactName)
59
+ : "contracts/frontend-implementation-contract.json";
60
+ canonicalContract = await copy(policyNodeId, relativePath);
61
+ const canonicalPath = path.join(input.newRunDir, relativePath);
62
+ const bytes = await readFile(canonicalPath);
63
+ await writeFrontendContractReviewArtifacts({
64
+ runDir: input.newRunDir,
65
+ outputDir: path.posix.dirname(relativePath),
66
+ artifactName: path.posix.basename(relativePath),
67
+ canonical: JSON.parse(bytes.toString("utf8")),
68
+ canonicalArtifact: { path: canonicalPath, sha256: canonicalContract.sha256, bytes: bytes.length },
69
+ });
70
+ // A reset admission node reads this result before capturing its baseline.
71
+ const policyResult = await copy(policyNodeId, "contracts/frontend-design-policy-result.json", !imported.has("frontend-writer-admission-shell"));
72
+ if (policyResult)
73
+ importedRunArtifacts.push({ sourceRelativePath: policyResult.destinationRelativePath, ...policyResult });
74
+ }
75
+ let writerAdmissionResult;
76
+ if (imported.has("frontend-writer-admission-shell")) {
77
+ writerAdmissionResult = await copy("frontend-writer-admission-shell", FRONTEND_WRITER_ADMISSION_RESULT_ARTIFACT);
78
+ for (const [relativePath, required] of [
79
+ ["contracts/frontend-worktree-baseline.json", true],
80
+ ["contracts/frontend-lint-baseline.json", false],
81
+ ]) {
82
+ const artifact = await copy("frontend-writer-admission-shell", relativePath, required);
83
+ if (artifact)
84
+ importedRunArtifacts.push({ sourceRelativePath: relativePath, ...artifact });
85
+ }
86
+ }
87
+ return { canonicalContract, writerAdmissionResult, importedRunArtifacts, nodeArtifacts };
88
+ }
89
+ /** Validate and freeze source bytes and the generated reader surface before
90
+ * reserving a recovery lease or creating an active child. No parent mutation. */
91
+ export async function prepareFrontendRunArtifacts(input) {
92
+ const temporary = await mkdtemp(path.join(os.tmpdir(), "frontend-run-import-"));
93
+ try {
94
+ const manifest = await collectFrontendRunArtifacts({ ...input, newRunDir: temporary });
95
+ const files = [];
96
+ const collect = async (relative = "") => {
97
+ for (const entry of await readdir(path.join(temporary, relative), { withFileTypes: true })) {
98
+ const relativePath = path.posix.join(relative, entry.name);
99
+ if (entry.isDirectory())
100
+ await collect(relativePath);
101
+ else {
102
+ const bytes = await readFile(path.join(temporary, relativePath));
103
+ files.push(Object.freeze({ relativePath, base64: bytes.toString("base64"), sha256: sha256Hex(bytes) }));
104
+ }
105
+ }
106
+ };
107
+ await collect();
108
+ return Object.freeze({ manifest, files: Object.freeze(files) });
109
+ }
110
+ finally {
111
+ await rm(temporary, { recursive: true, force: true });
112
+ }
113
+ }
114
+ export async function importFrontendRunArtifacts(input) {
115
+ const prepared = input.prepared ?? await prepareFrontendRunArtifacts(input);
116
+ for (const file of prepared.files) {
117
+ const bytes = Buffer.from(file.base64, "base64");
118
+ const destination = path.join(input.newRunDir, file.relativePath);
119
+ await mkdir(path.dirname(destination), { recursive: true });
120
+ await writeFile(destination, bytes);
121
+ if (sha256Hex(await readFile(destination)) !== file.sha256) {
122
+ throw new Error(`copy hash mismatch for artifact: ${file.relativePath}`);
123
+ }
124
+ }
125
+ return prepared.manifest;
126
+ }
@@ -2,50 +2,16 @@ import { copyFile, mkdir, readdir, readFile, rm, access } from "node:fs/promises
2
2
  import path from "node:path";
3
3
  import { sha256OfCanonicalJson } from "../../task/contract/hash.js";
4
4
  import { writeJsonAtomic } from "../../infrastructure/harness/atomic-write.js";
5
- import { sha256Hex, writeFrontendContractReviewArtifacts } from "./frontend-implementation-contract.js";
5
+ import { sha256Hex } from "./frontend-implementation-contract.js";
6
+ import { importFrontendRunArtifacts } from "./frontend-imported-run-artifacts.js";
6
7
  import { FRONTEND_RECOVERY_IMPORT_MANIFEST_REL_PATH, FRONTEND_RECOVERY_INTENT_REL_DIR, FRONTEND_RECOVERY_STAGING_PREFIX, computeFrontendRecoveryPlan, computeFrontendRecoveryPlanForSource, } from "./frontend-recovery-plan.js";
7
8
  import { dagRunDirExists, getDagRunDir, locateDagRun, readDagRunSpec, readDagRunState, transferDagRunDir, writeDagRunState, } from "./lifecycle.js";
8
9
  import { buildDagRunId } from "./runner.js";
9
10
  import { buildFrontendTopologyBinding } from "./frontend-shape.js";
10
11
  import { FRONTEND_SHAPE_BOUNDARIES, isCanonicalFrontendShapeDag, } from "./frontend-shape-facts.js";
11
12
  import { prepareRunDir, writeNodeRecord } from "./run-store.js";
12
- import { FRONTEND_WRITER_ADMISSION_RESULT_ARTIFACT, readFrontendWriterAdmissionResult, } from "./scheduler.js";
13
+ import { readFrontendWriterAdmissionResult, } from "./scheduler.js";
13
14
  import { topoSortToRanks } from "./topo.js";
14
- /**
15
- * Candidate-continuation child creation kernel (phase 3b).
16
- *
17
- * Parent terminal convergence (phase 3a) has already persisted a recovery
18
- * intent on `DagRunState.frontendRecoveryState`. This module is the single
19
- * writer that stages and commits one reserved child run per requestId, with a
20
- * commit-point handoff: CAS-reserve childRunId → stage files (hash-verified) →
21
- * rename into active/ → activation marker → three-way consistency check → CAS
22
- * phase=child-running. Scheduling/execution of the child is phase 3c and out
23
- * of scope here.
24
- */
25
- /** Canonical contract artifact default location; overridden by the design
26
- * policy shell's configured outputDir/artifactName when present. */
27
- const FRONTEND_CANONICAL_CONTRACT_DEFAULT_REL_PATH = "contracts/frontend-implementation-contract.json";
28
- /**
29
- * Run-owned artifacts a frontend node writes *outside* its own node directory.
30
- *
31
- * An imported node keeps its parent FINISHED record in the child run, so the
32
- * child never executes the body that produced these files. Any downstream node
33
- * that reads them must still find them in the child run directory: smoke r31
34
- * saw a review-triggered recovery die at `frontend-review-context-shell` with
35
- * `ENOENT contracts/frontend-worktree-baseline.json`, because
36
- * `frontend-writer-admission-shell` is imported (its baseline capture is a side
37
- * effect of the node body) while the review context requires that file.
38
- *
39
- * Entries listed as required fail the staging closed when the parent lacks
40
- * them; optional entries (for example the lint baseline, which only exists when
41
- * lint is configured) are copied when present.
42
- */
43
- const FRONTEND_IMPORTED_NODE_RUN_ARTIFACTS = {
44
- "frontend-writer-admission-shell": {
45
- required: ["contracts/frontend-worktree-baseline.json"],
46
- optional: ["contracts/frontend-lint-baseline.json"],
47
- },
48
- };
49
15
  function resolveDeps(deps) {
50
16
  return {
51
17
  readParentState: deps?.readParentState ?? readDagRunState,
@@ -116,15 +82,6 @@ function classifyFrontendFactKind(nodeId) {
116
82
  return "plan";
117
83
  return "plan";
118
84
  }
119
- function resolveCanonicalContractRelPath(spec) {
120
- for (const task of spec.tasks) {
121
- const policy = task.shell?.frontendDesignPolicy;
122
- if (policy) {
123
- return path.posix.join(policy.outputDir, policy.artifactName);
124
- }
125
- }
126
- return FRONTEND_CANONICAL_CONTRACT_DEFAULT_REL_PATH;
127
- }
128
85
  function normalizeRunRelativePath(relPath) {
129
86
  return relPath.replace(/\\/g, "/");
130
87
  }
@@ -410,72 +367,12 @@ async function materializeChildStaging(input) {
410
367
  throw new Error(`node ${task.id} missing from frontend recovery plan partition`);
411
368
  }
412
369
  }
413
- // Canonical contract + writer-admission identity facts are copied alongside
414
- // the per-node facts so reset nodes can re-read them (AC-4).
415
- const canonicalContract = plan.importedNodeIds.some(id => ["frontend-design-policy-shell", "frontend-contract-import-shell"].includes(id)) ? await copyArtifactVerified({
416
- parentRunDir,
417
- newRunDir: stagingDir,
418
- relativePath: resolveCanonicalContractRelPath(childSpec),
419
- }) : undefined;
420
- if (canonicalContract) {
421
- // Imported policy nodes do not execute in the child. Recreate their
422
- // read surface from the verified canonical bytes before activating it;
423
- // otherwise an indexed-reader writer cannot start a repair round.
424
- const relativePath = canonicalContract.destinationRelativePath;
425
- const canonicalPath = path.join(stagingDir, ...relativePath.split("/"));
426
- const bytes = await readFile(canonicalPath);
427
- await writeFrontendContractReviewArtifacts({
428
- runDir: stagingDir,
429
- outputDir: path.posix.dirname(relativePath),
430
- artifactName: path.posix.basename(relativePath),
431
- canonical: JSON.parse(bytes.toString("utf8")),
432
- canonicalArtifact: {
433
- path: canonicalPath,
434
- sha256: canonicalContract.sha256,
435
- bytes: bytes.length,
436
- },
437
- });
438
- }
439
- const writerAdmissionResult = plan.importedNodeIds.includes("frontend-writer-admission-shell") ? await copyArtifactVerified({
370
+ const { canonicalContract, writerAdmissionResult, importedRunArtifacts } = await importFrontendRunArtifacts({
440
371
  parentRunDir,
441
372
  newRunDir: stagingDir,
442
- relativePath: FRONTEND_WRITER_ADMISSION_RESULT_ARTIFACT,
443
- }) : undefined;
444
- // Imported nodes keep their parent FINISHED record, so the run-owned files
445
- // their bodies wrote outside the node directory travel with them (smoke r31:
446
- // a review-triggered recovery reached review-context with no worktree
447
- // baseline and hard-failed on ENOENT).
448
- const importedRunArtifacts = [];
449
- for (const nodeId of plan.importedNodeIds) {
450
- const artifactSpec = FRONTEND_IMPORTED_NODE_RUN_ARTIFACTS[nodeId];
451
- if (!artifactSpec)
452
- continue;
453
- for (const relativePath of artifactSpec.required) {
454
- const copied = await copyArtifactVerified({
455
- parentRunDir,
456
- newRunDir: stagingDir,
457
- relativePath,
458
- });
459
- importedRunArtifacts.push({
460
- sourceRelativePath: relativePath,
461
- ...copied,
462
- });
463
- }
464
- for (const relativePath of artifactSpec.optional) {
465
- const sourcePath = path.join(parentRunDir, ...relativePath.split("/"));
466
- if (!(await fileExists(sourcePath)))
467
- continue;
468
- const copied = await copyArtifactVerified({
469
- parentRunDir,
470
- newRunDir: stagingDir,
471
- relativePath,
472
- });
473
- importedRunArtifacts.push({
474
- sourceRelativePath: relativePath,
475
- ...copied,
476
- });
477
- }
478
- }
373
+ spec: childSpec,
374
+ importedNodeIds: plan.importedNodeIds,
375
+ });
479
376
  // The scheduler gates every shape boundary by its committed fact once the
480
377
  // boundary's source node is FINISHED. Imported nodes stay FINISHED in the
481
378
  // child, so their boundaries must inherit the parent's committed facts or
@@ -81,6 +81,20 @@ export function resolveRunnerArgv(argv) {
81
81
  words.shift();
82
82
  }
83
83
  const head = words[0];
84
+ // Recognize the project-local Jest entrypoint without rewriting the actual
85
+ // command. Only unwrap understood Node flags: eval/loaders/preloads can
86
+ // change execution semantics and must not be guessed away.
87
+ if (head === "node" || head === "node.exe") {
88
+ let entry = 1;
89
+ while (words[entry] === "--experimental-vm-modules")
90
+ entry++;
91
+ if (words[entry] === "--")
92
+ entry++;
93
+ const script = words[entry]?.replace(/\\/g, "/");
94
+ if (script && /^(?:\.\/)?node_modules\/jest\/bin\/jest\.js$/.test(script)) {
95
+ return ["jest", ...words.slice(entry + 1)];
96
+ }
97
+ }
84
98
  if (head === "npx" || head === "pnpx" || head === "bunx") {
85
99
  words.shift();
86
100
  // `npx --no-install vitest run` / `npx -y vitest run`
@@ -246,22 +246,34 @@ function frozenCheckFailureCategory(mode) {
246
246
  }
247
247
  /**
248
248
  * Normalize a failed frozen check into a bounded, model-independent detail.
249
- * Only the command id, exit status and a short output tail are kept: the model
250
- * is never trusted, and the repair prompt must stay small.
249
+ * Prefer diagnostic lines over reporter footers. This is advisory output,
250
+ * never authority for changing a command, write boundary or verdict.
251
251
  */
252
- function describeFrozenCheckFailure(result) {
252
+ export function describeFrozenCheckFailure(result) {
253
253
  const status = result.command.trim().length === 0
254
254
  ? "has no frozen command text (nothing was run)"
255
255
  : result.exitCode === null
256
256
  ? `did not complete (${result.failureCategory})`
257
257
  : `exited ${result.exitCode}`;
258
- const tail = `${result.stdout}\n${result.stderr}`
258
+ const lines = `${result.stdout}\n${result.stderr}`
259
259
  .split("\n")
260
260
  .map((line) => line.trim())
261
- .filter(Boolean)
262
- .slice(-3)
263
- .join(" | ");
264
- return `frozen check ${result.commandId} ${status}${tail ? `: ${tail.slice(0, 300)}` : ""}`;
261
+ .filter(Boolean);
262
+ const anchors = lines.flatMap((line, index) => /^(?:●|FAIL\b|AssertionError\b|Error:)|\berror TS\d+:/.test(line) ? [index] : []).slice(0, 8);
263
+ const selected = new Set();
264
+ for (const index of anchors) {
265
+ // Keep each headline even if a previous diagnostic has a long source dump.
266
+ selected.add(index);
267
+ }
268
+ for (const index of anchors) {
269
+ for (let offset = 1; offset < 12 && index + offset < lines.length; offset++)
270
+ selected.add(index + offset);
271
+ }
272
+ const detail = (anchors.length
273
+ ? [...selected].map((index) => (lines[index] ?? "").slice(0, 240))
274
+ : [...lines.slice(0, 3), ...lines.slice(-3)])
275
+ .join(" | ").slice(0, 2400);
276
+ return `frozen check ${result.commandId} ${status}${detail ? `: ${detail}` : ""}`;
265
277
  }
266
278
  /**
267
279
  * Writer-boundary check. It validates declared file existence AND, when the
@@ -0,0 +1,104 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstat, readFile, realpath } from "node:fs/promises";
3
+ import path from "node:path";
4
+ const hash = (value) => createHash("sha256").update(value).digest("hex");
5
+ export async function captureFrontendReuseSnapshot(workspaceRoot, contract) {
6
+ const files = {};
7
+ const root = await realpath(workspaceRoot);
8
+ const targets = [...new Set([
9
+ ...contract.requirements.flatMap(r => r.implementationTargets),
10
+ ...contract.verificationTargets.map(t => t.file),
11
+ ])].sort();
12
+ for (const target of targets) {
13
+ try {
14
+ const resolved = path.resolve(root, target);
15
+ const relative = path.relative(root, await realpath(resolved));
16
+ if (relative.startsWith("..") || path.isAbsolute(relative) || !(await lstat(resolved)).isFile())
17
+ continue;
18
+ files[target] = hash(await readFile(resolved));
19
+ }
20
+ catch { /* Missing/unreadable targets cannot be reused. */ }
21
+ }
22
+ return { contractSha256: hash(JSON.stringify(contract)), files };
23
+ }
24
+ export function deriveFrontendReuseEvidence(input) {
25
+ const { baseline, current, contract } = input;
26
+ if (!baseline || !input.guardOk || !input.checksComplete ||
27
+ baseline.contractSha256 !== current.contractSha256 ||
28
+ current.contractSha256 !== hash(JSON.stringify(contract)))
29
+ return;
30
+ const passes = (checks, id) => {
31
+ const found = (checks ?? []).filter(c => c.commandId === id);
32
+ return found.length === 1 && found[0].exitCode === 0 &&
33
+ found[0].failureCategory === "success" && Boolean(found[0].command.trim());
34
+ };
35
+ const unchanged = (file) => Boolean(baseline.files[file]) &&
36
+ baseline.files[file] === current.files[file] && !input.writtenPaths.includes(file);
37
+ // Keep verification inputs unchanged: changing tests cannot certify baseline reuse.
38
+ for (const target of contract.verificationTargets) {
39
+ if (!unchanged(target.file) || !passes(input.baselineChecks, target.commandId) ||
40
+ !passes(input.currentChecks, target.commandId))
41
+ return;
42
+ const before = input.baselineChecks.find(c => c.commandId === target.commandId);
43
+ const after = input.currentChecks.find(c => c.commandId === target.commandId);
44
+ if (before.command !== after.command)
45
+ return;
46
+ }
47
+ if (!contract.verificationTargets.length)
48
+ return;
49
+ const requirementTargets = [...new Set(contract.requirements.flatMap(r => r.implementationTargets))]
50
+ .filter(file => unchanged(file) && contract.requirements.filter(r => r.implementationTargets.includes(file))
51
+ .every(r => r.verificationTargetIds.length > 0 && r.verificationTargetIds.every(id => contract.verificationTargets.some(t => t.id === id && t.requirementIds.includes(r.id)))))
52
+ .sort();
53
+ if (!requirementTargets.length)
54
+ return;
55
+ const proofSha256 = hash(JSON.stringify({ baseline, current, requirementTargets,
56
+ baselineChecks: input.baselineChecks, currentChecks: input.currentChecks }));
57
+ return { requirementTargets, proofSha256 };
58
+ }
59
+ /**
60
+ * Presence/identity evidence for untouched files during a genuine partial repair.
61
+ * Changed verification inputs are recorded, not used to certify a no-op. This
62
+ * evidence may satisfy slice omissions/dependencies, NEVER alreadySatisfied.
63
+ */
64
+ export function deriveFrontendRetainedTargetEvidence(input) {
65
+ const { baseline, current, contract } = input;
66
+ if (!baseline || !input.guardOk || !input.checksComplete ||
67
+ baseline.contractSha256 !== current.contractSha256 ||
68
+ current.contractSha256 !== hash(JSON.stringify(contract)) ||
69
+ !contract.verificationTargets.length)
70
+ return;
71
+ // Every frozen check must be unambiguous and green, with the same command
72
+ // bytes before/after. Trace preflight is separately included in checksComplete.
73
+ const commandIds = [...new Set(contract.verificationTargets.map(target => target.commandId))];
74
+ for (const id of commandIds) {
75
+ const before = input.baselineChecks?.filter(check => check.commandId === id) ?? [];
76
+ const after = input.currentChecks?.filter(check => check.commandId === id) ?? [];
77
+ if (before.length !== 1 || after.length !== 1)
78
+ return;
79
+ const a = before[0];
80
+ const b = after[0];
81
+ if (!a.command.trim() || a.command !== b.command || a.exitCode !== 0 || b.exitCode !== 0 ||
82
+ a.failureCategory !== "success" || b.failureCategory !== "success")
83
+ return;
84
+ }
85
+ const written = new Set(input.writtenPaths);
86
+ const changed = input.writerChangedPaths.filter(file => written.has(file) &&
87
+ Boolean(current.files[file]) && baseline.files[file] !== current.files[file]);
88
+ // A shell side effect, failed/reverted edit, or model claim is not a repair.
89
+ if (!changed.length)
90
+ return;
91
+ const retainedTargets = [...new Set(contract.requirements.flatMap(r => r.implementationTargets))]
92
+ .filter(file => Boolean(baseline.files[file]) && baseline.files[file] === current.files[file] &&
93
+ !written.has(file) && contract.requirements.filter(r => r.implementationTargets.includes(file))
94
+ .every(r => r.verificationTargetIds.length > 0 && r.verificationTargetIds.every(id => contract.verificationTargets.some(t => t.id === id && t.requirementIds.includes(r.id)))))
95
+ .sort();
96
+ if (!retainedTargets.length)
97
+ return;
98
+ const verificationInputChanges = [...new Set(contract.verificationTargets.map(target => target.file))]
99
+ .filter(file => baseline.files[file] !== current.files[file] || written.has(file)).sort();
100
+ const proofSha256 = hash(JSON.stringify({ baseline, current, retainedTargets, verificationInputChanges,
101
+ writerChangedPaths: changed.sort(), writtenPaths: [...written].sort(),
102
+ baselineChecks: input.baselineChecks, currentChecks: input.currentChecks }));
103
+ return { retainedTargets, verificationInputChanges, proofSha256 };
104
+ }
@@ -115,7 +115,6 @@ export const DEFAULT_FRONTEND_MICRO_LOOP_BUDGET = {
115
115
  maxFocusedCheckRounds: 2,
116
116
  maxWriteAttempts: 5,
117
117
  maxWallTimeMs: 15 * 60 * 1000,
118
- maxTokens: 200_000,
119
118
  maxRepeatedFingerprints: 2,
120
119
  };
121
120
  /**
@@ -151,9 +150,6 @@ export function evaluateMicroLoopContinuation(budget, history, startWallTimeMs,
151
150
  if (last.writeAttempts >= budget.maxWriteAttempts) {
152
151
  return { continue: false, reason: "budget-write-attempts" };
153
152
  }
154
- if (last.tokensUsed >= budget.maxTokens) {
155
- return { continue: false, reason: "budget-tokens" };
156
- }
157
153
  const repeatCount = history.filter((round) => round.fingerprint === last.fingerprint).length;
158
154
  if (repeatCount >= budget.maxRepeatedFingerprints) {
159
155
  return { continue: false, reason: "budget-repeated-fingerprint" };
@@ -337,10 +337,12 @@ export async function buildFrontendHybridDagFromTask(sources) {
337
337
  riskLevel: frontendRisk.selectedRisk,
338
338
  targetFiles: implementPaths.writeSet,
339
339
  });
340
+ const sourceScopeInstruction = "Source expectedOutcome outranks derived state/interaction prose. Keep human resolutions within named operations/ACs; shared retries do not share snapshot semantics. Report scope expansion as a plan gap, never a new implementation requirement.";
340
341
  const frontendContractFieldSummary = [
341
342
  "## Contract field summary (authoritative JSON; no plan prose)",
342
- "frontend-plan-pi records typed facts; frontend-design-policy-shell applies the runtime skeleton, validates, and materializes the canonical full contract JSON supplied here. There is no separate plan prose authority. Review these fields:",
343
+ "Typed Plan facts + runtime skeleton produce the canonical contract JSON. Fields:",
343
344
  "- requirements[]: id, expectedOutcome, implementationTargets, verificationTargetIds, evidenceGap",
345
+ sourceScopeInstruction,
344
346
  "- uiStates[]: name, applicable, expectedBehavior, implementationTargets, verificationTargetIds, notApplicableReason",
345
347
  "- interactions[]: name, trigger, expectedBehavior, implementationTargets, verificationTargetIds",
346
348
  "- targets: routes, publicApiChanges (files are runtime-owned)",
@@ -349,7 +351,7 @@ export async function buildFrontendHybridDagFromTask(sources) {
349
351
  "- designEvidence: source, paths, conflicts; evidenceGaps[] (optional)",
350
352
  "- optional: stylingStrategy, uiComponentChoices[], dependencyPolicy, residualRisks[], realIntegrationGap",
351
353
  "- uiComponentChoices[]: purpose, component, decision (specified|reuse-existing|new), specReference { path, section, line } | null, rationale",
352
- "Do not require or read a separate plan prose section; the contract JSON is the only plan surface.",
354
+ "Only contract JSON is authoritative; no separate plan prose.",
353
355
  ].join("\n");
354
356
  // Do not carry every attachment through the whole frontend pipeline. The
355
357
  // contract node is the sole requirements/materials synthesis point; scout
@@ -805,7 +807,7 @@ export async function buildFrontendHybridDagFromTask(sources) {
805
807
  },
806
808
  outputContract: "Typed decision patch only: map frozen requirements to implementation/verification targets and select the needed component, state, data/Mock, styling, and dependency decisions. Use only the record_* tools needed to express those decisions, then call finalize_plan; correct rejected facts until one successful terminal. Contract owns requirement semantics; Scout owns repository discovery; deterministic runtime owns schema, protected fields, path containment, and command validation. No Markdown narrative or file writes.",
807
809
  subtask_prompt: [
808
- "Plan only the delta between the frozen frontend-contract-pi facts and frontend-scout-pi target surface. Do not reinterpret the task, repeat requirements, or search the repository.",
810
+ "Plan only the delta from frozen Contract facts and Scout targets; no reinterpretation, repeated requirements, or repository search.",
809
811
  "Record only: requirement-to-file/verification coverage; component/styling choices; applicable UI state and interaction behavior; data/Mock strategy; and a dependency policy or genuine evidence gap. Reuse Scout paths. If scope is missing, record a blocking gap instead of inventing a path.",
810
812
  "Use the typed tool schemas as the field contract. Runtime owns schemaVersion, sourceBinding, riskLevel, targets.files, mockApi.productionDefaultOff, aliases, command allowlisting, path containment, and final validation; do not restate those rules or emit a full JSON contract.",
811
813
  `Cover each frozen requirement ID exactly once: ${requirementIds.join(", ") || "(none)"}. Bind every verification target to a frozen commandId from the directory above plus a Scout-confirmed file. Behavior commands prove observable behavior: one target may cover multiple related requirementIds when one test behavior proves them together; do not mechanically create one target per requirement. A behavior target id is the stable machine trace token and its file must be a test file. Static commands are project-wide checks traced by file and command only.`,
@@ -909,6 +911,7 @@ export async function buildFrontendHybridDagFromTask(sources) {
909
911
  subtask_prompt: [
910
912
  "Submit findings individually with record_design_finding and stable IDs; terminal tools aggregate saved findings. Correct rejected calls, stop after a successful terminal. Check execution groups against every member source outcome, including permission, threshold and failure-path differences; shared verification is valid only when it proves each independent AC.",
911
913
  "After the typed design terminal succeeds, stop immediately; do not emit a Markdown recap.",
914
+ sourceScopeInstruction,
912
915
  "Audit the frontend plan before implementation. frontend-plan-pi is emitted to you as canonical full-contract JSON after the runtime applied and validated the planner's editable patch against its protected skeleton; there is no separate plan prose.",
913
916
  "Your authoritative terminal verdict is exactly one committed typed tool call: approve_design or request_design_changes. Call exactly one of them; after calling one, do not call the other.",
914
917
  "request_design_changes must carry a typed issueCategory, at least one evidenceRef, and non-empty findings.",
@@ -986,16 +989,16 @@ export async function buildFrontendHybridDagFromTask(sources) {
986
989
  outputContract: "The implementation status is derived by the executor from mechanical facts (write-tool events, run delta, write guard, requirement coverage, focused-check), not from any IMPLEMENTATION_OUTCOME first line. Deliver a Markdown summary with Contract Ref (path/schema/hash), Changed Files, Requirements Implemented, UI States, Tests Changed, Verification Attempts, Deviations, and Residual Risks. When implementationSlices exist, report work in dependency order with tests/checks kept in each slice. Otherwise report the fixed stages: contract confirm → tests → component/state → API/Mock → focused checks → diff cleanup.",
987
990
  subtask_prompt: [
988
991
  "Implement against the validated run-owned Frontend Implementation Contract materialized by frontend-design-policy-shell (path/schema/hash) and authorized by frontend-writer-admission-shell. Do not rebuild the contract from Markdown alone.",
989
- "WRITER TOOL PROTOCOL (hard): the response text is not delivery. Never paste source code, test code, or full file contents into chat. After reading the canonical contract, make the first implementation change with the structured write/edit tool (one file per call); continue writing through those tools until the writeSet is complete. If a write/edit tool is unavailable, stop and report the blocked capability instead of drafting code in the response.",
992
+ "WRITER TOOL PROTOCOL (hard): the response text is not delivery. Never paste source code, test code, or full file contents into chat. Read the canonical contract and assess its target files before editing. For each necessary change, identify the concrete requirement gap and use the structured write/edit tool (one file per call). If no concrete requirement gap is found, make no edits and report the existing implementation evidence. Never manufacture edits merely to touch every writeSet path. A no-op requires runtime proof: matching pre/post fingerprints, unchanged verification inputs, passing frozen checks before and after the session, and passing guard/trace checks. Formal Verify and final review still decide acceptance. If a necessary edit cannot be made because the write/edit tool is unavailable, report the blocked capability instead of drafting code in the response.",
990
993
  "The canonical contract already contains the approved requirement, target-file, UI-state, verification, design, and Mock/API decisions. Do not re-open task sources, OpenSpec, AI workspace, plan/revision, or design-review prose, and do not repeat broad repository research. Inspect only contract target files and directly related local code needed to implement them.",
991
994
  "When the contract has no implementationSlices, execute and report these fixed stages: (1) Contract confirm, (2) Tests sync, (3) Component/UI state implementation, (4) API/Mock wiring per contract.mockApi, (5) Focused checks behind frozen entrypoints only, (6) Diff cleanup. When slices exist, follow their dependency order and keep each slice's tests/checks with its implementation.",
992
- "SLICE ORDER (when the contract carries implementationSlices): the slices ARE the execution order, not a suggestion. Work one slice at a time in the contract's order (prerequisites first), finish every targetPath of the current slice before starting the next, and keep its tests/checks with its own slice instead of deferring all tests to the end. A slice is complete when its own targetPaths are written and its requirements are covered; then move to the next slice. Do not reorder slices, skip a slice, or widen a slice beyond its own targetPaths. If a slice turns out to be impossible, stop and report which slice and why rather than silently implementing a different order. When the contract has no implementationSlices, keep the fixed stages above.",
995
+ "SLICE ORDER (when the contract carries implementationSlices): the slices ARE the execution order, not a suggestion. Work one slice at a time in the contract's order (prerequisites first), assess every targetPath of the current slice and finish its necessary edits before starting the next, and keep its tests/checks with its own slice instead of deferring all tests to the end. A slice is complete when its requirements are covered and its targetPaths have either successful writes or runtime-verified reuse evidence; then move to the next slice. Do not reorder slices, skip a slice, or widen a slice beyond its own targetPaths. If a slice turns out to be impossible, stop and report which slice and why rather than silently implementing a different order. When the contract has no implementationSlices, keep the fixed stages above.",
993
996
  "Map every requirement id, expectedOutcome, interaction trigger/expectedBehavior, and applicable UI state from the contract to concrete files. Do not invent shell verification commands; only frozen static/behavior entrypoints will run.",
994
997
  "A behavior verification target's target.id is only the contract's identifier for that entry; it does not need to appear in test titles. Never add tests, rename describe/it/test titles, or restructure files just to carry generated ids — reuse affected existing test files and their names. The requirement ↔ verification-target association lives in the contract (requirementIds / verificationTargetIds), not in title strings.",
995
- "Begin implementation after the contract and its target files are confirmed. Do not spend the turn collecting optional context. If the canonical contract lacks behavior needed to edit safely, stop and state the blocking reason in the summary instead of reopening broad discovery.",
998
+ "Begin necessary implementation changes only after the contract, its target files, and concrete requirement gaps are confirmed. Do not spend the turn collecting optional context. If the canonical contract lacks behavior needed to edit safely, stop and state the blocking reason in the summary instead of reopening broad discovery.",
996
999
  "Your implementation status is derived by the executor from mechanical facts (persisted write-tool events, run delta, write guard, requirement coverage, focused-check failures), never from any IMPLEMENTATION_OUTCOME first line. Do not emit an IMPLEMENTATION_OUTCOME first line.",
997
1000
  "After the write session the executor re-runs the frozen trace preflight against the contract AND runs the frozen commands bound to its verification targets from the generation-time command directory, recording each command's id and exit code plus a per-round diff checkpoint (changed files, write guard verdict, failure fingerprint, budget); the write guard stays active for the whole session. A target whose declared file merely exists is not a passing check. Repair only local issues attributable to your current diff (syntax/type/import/format/unit-assert/obvious omission). Never change requirements, design, writeSet, or verification strictness. The full frozen command set remains frontend-verify-shell's authority — a green local check is not proof of behavior.",
998
- "When the contract declares implementationSlices, the executor derives slice progress from the write tools you actually called (order, per-slice completion, omitted targets, out-of-slice paths) and records it as writer-slice-progress.json. Implementing a slice before its declared prerequisite, or never writing a declared slice target, is a local failure that triggers a bounded repair round — the SLICE ORDER constraint above is checked against observed writes, not trusted from your summary.",
1001
+ "When the contract declares implementationSlices, the executor derives slice progress from the write tools you actually called (order, per-slice completion, omitted targets, out-of-slice paths) and records it as writer-slice-progress.json. Implementing a slice before its declared prerequisite, or leaving a declared slice target without successful writes or runtime-verified reuse evidence, is a local failure that triggers a bounded repair round — the SLICE ORDER constraint above is checked against observed writes, not trusted from your summary.",
999
1002
  "Implement only the approved Mock strategy carried by the validated contract. Preserve the real request path as the default, require explicit test/dev activation, and never comment out or replace the real request with inline data.",
1000
1003
  "frontend-design-policy-shell materialized and validated the canonical contract; frontend-writer-admission-shell authorized the writeSet. Stay within writeSet and preserve unrelated files.",
1001
1004
  "For native, browser-intercept, or request-adapter, implement contract-aligned fixtures/states and a dev/test-only activation boundary in this same writer. For not-needed, do not add Mock files or a framework and state the positive reason.",
@@ -1080,6 +1083,8 @@ export async function buildFrontendHybridDagFromTask(sources) {
1080
1083
  "Submit findings individually with record_review_finding and stable IDs; terminal tools aggregate saved findings. Correct rejected calls, stop after a successful terminal. Check execution groups against every member source outcome, including permission, threshold and failure-path differences; shared verification is valid only when it proves each independent AC.",
1081
1084
  "After the typed review terminal succeeds, stop immediately; do not emit a Markdown recap.",
1082
1085
  "Review the frontend implementation and verification evidence.",
1086
+ "Before claiming a missing guard, trace the caller through the state-changing branch; cite a reachable failing path, not an isolated API helper or fixture.",
1087
+ sourceScopeInstruction,
1083
1088
  "Your authoritative terminal verdict is exactly one committed typed tool call: approve_review or request_review_changes. Call it once and do not call the other afterwards.",
1084
1089
  "approve_review means the implementation passes; it must not carry Critical or Important findings. request_review_changes must carry a typed issueCategory, at least one evidenceRef, and non-empty findings.",
1085
1090
  "Do NOT emit an equivalent JSON verdict in the response text: the committed typed terminal fact is the only authority and no branch or gate reads response-text JSON verdicts.",
@@ -1199,7 +1204,9 @@ export async function buildFrontendHybridDagFromTask(sources) {
1199
1204
  const frontendMaxContinuations = sources.taskConfig.frontendRecovery?.maxContinuations ?? 1;
1200
1205
  spec.frontendRecovery = { maxContinuations: frontendMaxContinuations };
1201
1206
  // Configurable execution safety quota, independent of model context/output capacity.
1202
- spec.budget = { schemaVersion: 1, mode: "hard", limits: { maxProviderRequests: sources.taskConfig.frontendRecovery?.maxProviderRequests ?? 1024 } };
1207
+ if (sources.taskConfig.frontendRecovery?.maxProviderRequests !== null) {
1208
+ spec.budget = { schemaVersion: 1, mode: "hard", limits: { maxProviderRequests: sources.taskConfig.frontendRecovery?.maxProviderRequests ?? 1024 } };
1209
+ }
1203
1210
  spec.frontendExecutionPolicy = frontendExecutionPolicySchema.parse(sources.taskConfig.frontendExecutionPolicy ?? {});
1204
1211
  applyDefaultReadOnlyRetryPolicy(spec);
1205
1212
  stampGeneratedArtifactBindings(spec);
@@ -382,7 +382,7 @@ async function buildHybridDagForTemplate(sources, template, options = {}) {
382
382
  spec.runtimeContract = GENERATED_DAG_RUNTIME_CONTRACT;
383
383
  }
384
384
  spec.sourceBinding = buildDagSourceBinding(sources, template === "frontend-implementation" ? "frontend-implementation" : undefined);
385
- if (template === "frontend-implementation" && sources.repoRoot) {
385
+ if (template === "frontend-implementation" && sources.repoRoot && spec.budget?.limits.maxProviderRequests !== undefined) {
386
386
  const ledger = await readTaskSourceProviderBudget({ repoRoot: sources.repoRoot, taskId: sources.taskId, maxProviderRequests: spec.budget.limits.maxProviderRequests });
387
387
  if (ledger)
388
388
  spec.sourceProviderBudget = { ledger, contract: sourceBudgetContractIdentity(taskContractBinding), sourceBindingSha256: sha256OfCanonicalJson(spec.sourceBinding), evidence: await freezeTaskSourceUsage({ repoRoot: sources.repoRoot, taskId: sources.taskId, maxProviderRequests: ledger.maxProviderRequests }, ledger) };
@@ -1,4 +1,5 @@
1
1
  import path from "node:path";
2
+ import { readDeadContinuationOwner } from "./recovery-lease.js";
2
3
  import { writeJsonAtomic } from "../../infrastructure/harness/atomic-write.js";
3
4
  import { assessDagRunLiveness, assessDagRunRecoveryEligibility, assertDagRunTransferTargetAvailable, getDagRunDir, locateDagRun, readDagRunState, transferDagRunDir, writeDagRunState, } from "./lifecycle.js";
4
5
  export function parseDagReconcileRunArgs(args) {
@@ -48,7 +49,14 @@ export async function executeDagReconcileRun(repoRoot, rawArgs) {
48
49
  if (!located)
49
50
  throw new Error(`dag run not found: ${parsed.runId}`);
50
51
  const state = await readDagRunState(located.runDir);
51
- const liveness = assessDagRunLiveness({ state });
52
+ const continuation = state.continuation;
53
+ const neverStarted = !state.runner && state.status === "running" &&
54
+ continuation?.kind === "rerun-from-node" && Object.values(state.nodes).every((node) => (node.status === "FINISHED" && node.origin?.kind === "imported" && node.origin.parentRunId === continuation.parentRunId) ||
55
+ (node.status === "PENDING" && !node.startedAt && !node.attempts?.length));
56
+ const recoveryOwnerEvidence = neverStarted && continuation
57
+ ? await readDeadContinuationOwner({ cwd: repoRoot, parentRunId: continuation.parentRunId, runId: state.runId, requestId: continuation.requestId })
58
+ : undefined;
59
+ const liveness = recoveryOwnerEvidence ? { status: "orphaned" } : assessDagRunLiveness({ state });
52
60
  const eligibility = assessDagRunRecoveryEligibility({
53
61
  lifecycle: located.lifecycle,
54
62
  state,
@@ -62,6 +70,7 @@ export async function executeDagReconcileRun(repoRoot, rawArgs) {
62
70
  status: state.status,
63
71
  liveness: liveness.status,
64
72
  eligibility,
73
+ ...(recoveryOwnerEvidence ? { recoveryOwnerEvidence } : {}),
65
74
  nextRecommendedAction: eligibility.canReconcile
66
75
  ? "Re-run with --action supersede|abandon and --reason <text>."
67
76
  : "Do not reconcile this run; inspect runner and lifecycle evidence first.",
@@ -86,6 +95,7 @@ export async function executeDagReconcileRun(repoRoot, rawArgs) {
86
95
  previousStatus: state.status,
87
96
  liveness: liveness.status,
88
97
  originalState: state,
98
+ ...(recoveryOwnerEvidence ? { recoveryOwnerEvidence } : {}),
89
99
  });
90
100
  const previousStatus = state.status;
91
101
  for (const node of Object.values(state.nodes)) {