@tea-agent/loop-agent 0.51.0-next.1 → 0.51.0-next.3

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 (125) hide show
  1. package/CHANGELOG.md +33 -1
  2. package/dist/application/task-lifecycle/advance.js +6 -0
  3. package/dist/build-stamp.json +3 -3
  4. package/dist/commands/init.js +12 -3
  5. package/dist/executors/dag-pi/plan/facts.js +18 -4
  6. package/dist/executors/dag-pi/plan/record-tools.js +34 -3
  7. package/dist/executors/dag-pi/sessions/scout-parallel.js +11 -2
  8. package/dist/executors/dag-pi/sessions/segmented-plan.js +170 -16
  9. package/dist/executors/dag-pi/tools/contract-read-tool.js +34 -0
  10. package/dist/executors/dag-pi/tools/scout-evidence-tools.js +9 -7
  11. package/dist/executors/dag-pi-executor.js +82 -82
  12. package/dist/shared/pi-context-pressure/checkpoint.js +22 -4
  13. package/dist/shared/pi-context-pressure/compaction-policy.js +5 -1
  14. package/dist/shared/pi-context-pressure/extension.js +64 -5
  15. package/dist/shared/pi-context-pressure/sift-bridge.js +2 -1
  16. package/dist/shared/pi-context-pressure/telemetry.js +4 -0
  17. package/dist/shared/pi-context-pressure/tool-result-pruner.js +8 -3
  18. package/dist/task/source-prepare/completeness.js +2 -2
  19. package/dist/task/source-prepare/diagnostic.js +76 -0
  20. package/dist/task/source-prepare/ledger-reconciliation.js +65 -9
  21. package/dist/task/source-prepare/ledger-review.js +18 -2
  22. package/dist/task/source-prepare/ledger.js +3 -1
  23. package/dist/task/source-prepare/prepare.js +23 -3
  24. package/dist/task/source-prepare/source-fidelity-pi.js +12 -1
  25. package/dist/task/source-prepare/types.js +1 -1
  26. package/dist/worker/console/chat/chat-event-projection.js +13 -0
  27. package/dist/worker/console/chat/chat-event-store.js +1 -0
  28. package/dist/worker/console/chat/compaction-errors.js +1 -1
  29. package/dist/worker/console/chat/context-accounting.js +58 -0
  30. package/dist/worker/console/chat/context-insights.js +131 -22
  31. package/dist/worker/console/chat/context-usage.js +57 -1
  32. package/dist/worker/console/chat/pi-runtime/context-edit.js +91 -0
  33. package/dist/worker/console/chat/pi-runtime.js +36 -3
  34. package/dist/worker/console/chat/routes.js +3 -0
  35. package/dist/worker/console/chat/terminal-routes.js +12 -0
  36. package/dist/worker/console/chat/terminal-sessions.js +6 -0
  37. package/dist/worker/console/chat/vcp-prompt.js +28 -15
  38. package/dist/worker/console/recovery-error-copy.js +4 -1
  39. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-DUtUeeEa.js → abnfDiagram-N423BO3Z-GerMJfMU.js} +1 -1
  40. package/dist/worker/console/static/assets/{arc-Cs0DSwTY.js → arc-DHRoAcBA.js} +1 -1
  41. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-C80FSNgl.js → architectureDiagram-T3A2C74G-Bna7kqEi.js} +1 -1
  42. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-DFgOZUzn.js → blockDiagram-VBNYF7ZC-B8yw7WTX.js} +1 -1
  43. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-CB9nkTjT.js → c4Diagram-5PPSVZJV-BaUWiyqi.js} +1 -1
  44. package/dist/worker/console/static/assets/channel-CLhtAowh.js +1 -0
  45. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-DbjpoOrh.js → chunk-2GRJ4B5K-D4iZ2ZNv.js} +1 -1
  46. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-BsWVWnWY.js → chunk-2Q5K7J3B-BtQpibwB.js} +1 -1
  47. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-BwwP_1AG.js → chunk-5RXB4S5H-ez-kfSyS.js} +1 -1
  48. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-DDEzW9MV.js → chunk-5VM5RSS4-6L4-OV-3.js} +1 -1
  49. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-D-fLZDni.js → chunk-6Q2QTUOP-CPUweABC.js} +1 -1
  50. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-DY9q3jMo.js → chunk-GF5L2VYU-6DTw-5Ov.js} +1 -1
  51. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-rkUPkzPh.js → chunk-JWPE2WC7-DFAS-DH8.js} +1 -1
  52. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-Ci9ZksX4.js → chunk-KBJHAD2P-Du7LoER5.js} +1 -1
  53. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-DKU-3Ef6.js → chunk-RYQCIY6F-D9UugPlg.js} +1 -1
  54. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-A-xOwXvl.js → chunk-XXDRQBXY-BLh5yptc.js} +1 -1
  55. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DB7nfjpK.js +1 -0
  56. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DB7nfjpK.js +1 -0
  57. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-Bfs1rphL.js → cose-bilkent-JH36ORCC-DjmHXa8h.js} +1 -1
  58. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-BTlXtGR2.js → cynefin-VYW2F7L2-D5jbf1gi.js} +1 -1
  59. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-D8c9vCCr.js → cynefinDiagram-MW4NZA55-BudjeLTi.js} +1 -1
  60. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-B-e-tfgY.js → dagre-VZM6K2ZE-6YP-wMO0.js} +1 -1
  61. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-CG_5dIVJ.js → diagram-7IWD3JNH-CA3LtUAB.js} +1 -1
  62. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-CmP40HmK.js → diagram-B4RE2ZJO-BAjJeYaD.js} +1 -1
  63. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-RFt8vi9Y.js → diagram-LBJQPF4R-Dh4zb-ds.js} +1 -1
  64. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-CM5Sb2jB.js → diagram-Q27KOJAE-aMKj_Gkp.js} +1 -1
  65. package/dist/worker/console/static/assets/{diagram-UB23O5K3-Bm4zh0WJ.js → diagram-UB23O5K3-D_0_rqQ6.js} +1 -1
  66. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-b3GekSN4.js → ebnfDiagram-BXEA7PRR--C9HfGgB.js} +1 -1
  67. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-CFZh4C_o.js → erDiagram-JOGREHBK-BuqX0vmt.js} +1 -1
  68. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-CzxniD3z.js → flowDiagram-UKHOOZJN-IneEK8zO.js} +1 -1
  69. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-Czp6xUXj.js → ganttDiagram-PKOTCBZU-DK2RiNlb.js} +1 -1
  70. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-B66oX4sn.js → gitGraphDiagram-DS77QQ5N-CuN5z0rP.js} +1 -1
  71. package/dist/worker/console/static/assets/{index-BVMJjujb.css → index-CzfumEW1.css} +1 -1
  72. package/dist/worker/console/static/assets/{index-Bq_vMDO3.js → index-DS6dteCl.js} +159 -147
  73. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-rTveEtft.js → infoDiagram-6WML65LV-B6enpqSl.js} +1 -1
  74. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-N2jiPnrD.js → ishikawaDiagram-WSZJBQD7-DepH_7eq.js} +1 -1
  75. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-DtnLwtAE.js → journeyDiagram-NVQOT4AX-BftlRwcR.js} +1 -1
  76. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-t9D_2QMN.js → kanban-definition-27J2QSJJ-CEIZMo9g.js} +1 -1
  77. package/dist/worker/console/static/assets/{linear-BP6ZG0tB.js → linear-DkgtGbsw.js} +1 -1
  78. package/dist/worker/console/static/assets/{mermaid.core-Cc5_ZtUy.js → mermaid.core-CIMKKPgL.js} +5 -5
  79. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-zztwmHj8.js → mindmap-definition-FAOFIHXS-dzbp1VuW.js} +1 -1
  80. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-CmXQOyPH.js → pegDiagram-VL7TDLO6-C5b5i7KO.js} +1 -1
  81. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BodwfpEp.js → pieDiagram-7S7Q4E2Y-Ugdko1lm.js} +1 -1
  82. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-DIgybsTM.js → quadrantDiagram-CIZ2JOQS-B2s1OZu8.js} +1 -1
  83. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-CZb_4Cv2.js → railroadDiagram-AXF67PYL-BVafp-Z6.js} +1 -1
  84. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-BvRNauBA.js → requirementDiagram-LRYGKXZP-BVxBjdbs.js} +1 -1
  85. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BQ30kRWi.js → sankeyDiagram-W5VNT64P-CorSImxl.js} +1 -1
  86. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-B7sGR3r3.js → sequenceDiagram-SI44F4Z6-eVj3geQV.js} +1 -1
  87. package/dist/worker/console/static/assets/{sheet-workbook-CK8pzw-q.js → sheet-workbook-DNnJDCal.js} +1 -1
  88. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-1HZrTeyl.js → sizeCapture-X5ZJPWSS-OQWfzgrL.js} +1 -1
  89. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-BKCXlJRS.js → stateDiagram-OKZ733FA-DJr_pPmG.js} +1 -1
  90. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Cr-50jJB.js +1 -0
  91. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-BhT8u6Vm.js → swimlanes-SLNWSIFB-CQG0Q9vK.js} +2 -2
  92. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-kZpEmem6.js +8 -0
  93. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-Dnczuw3j.js → timeline-definition-Z64GVDOM-DxWuWIZ5.js} +1 -1
  94. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-PgJCj-16.js → vennDiagram-T6HMQDX7-BJt03ecs.js} +1 -1
  95. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-BjuszbFn.js → wardleyDiagram-T6FBY63Y-BB3rPfNJ.js} +1 -1
  96. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-Dhtjuxrn.js → xychartDiagram-ELKLHX3M-aVR9TCu0.js} +1 -1
  97. package/dist/worker/console/static/index.html +2 -2
  98. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +99 -16
  99. package/dist/worker/console/static-src/operator-chat/useChatThread.js +27 -5
  100. package/dist/worker/console/static-src/operator-chat/vcp-fonts.js +1 -6
  101. package/dist/worker/console/workspace-context.js +56 -1
  102. package/dist/worker/observe/static/dag-history-labels.js +2 -0
  103. package/dist/worker/observe/static/views/dag.js +28 -0
  104. package/dist/workflows/dag/frontend-durable-tools.js +5 -2
  105. package/dist/workflows/dag/frontend-implementation-contract.js +19 -6
  106. package/dist/workflows/dag/frontend-recovery-run.js +20 -1
  107. package/dist/workflows/dag/frontend-review-scopes.js +2 -2
  108. package/dist/workflows/dag/frontend-session-budget.js +1 -1
  109. package/dist/workflows/dag/frontend-writer-baseline-guard.js +11 -5
  110. package/dist/workflows/dag/hybrid/templates/frontend.js +35 -5
  111. package/dist/workflows/dag/prompt.js +8 -2
  112. package/dist/workflows/dag/rerun-plan.js +50 -3
  113. package/dist/workflows/dag/rerun-run.js +4 -0
  114. package/dist/workflows/dag/runner.js +11 -0
  115. package/package.json +6 -3
  116. package/dist/worker/console/static/assets/channel-BddnaJc4.js +0 -1
  117. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-CqfGeesl.js +0 -1
  118. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-CqfGeesl.js +0 -1
  119. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DzDcqZJM.js +0 -1
  120. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DgnnY3K8.js +0 -8
  121. package/dist/worker/console/static/vcp/fonts/Lanxi-GreatVibes.woff2 +0 -0
  122. package/dist/worker/console/static/vcp/fonts/Lanxi-MaShanZheng.woff2 +0 -0
  123. package/dist/worker/console/static/vcp/fonts/Lanxi-/347/202/271/351/273/221.woff2 +0 -0
  124. package/dist/worker/console/static/vcp/fonts/Lanxi-/351/235/231/351/273/221/350/266/205/347/273/206.woff2 +0 -0
  125. package/dist/worker/console/static/vcp/fonts/Lanxi-/351/261/274/345/260/276/350/241/214/344/271/246.woff2 +0 -0
@@ -39,6 +39,7 @@ import {
39
39
  parseRoute,
40
40
  navigate,
41
41
  buildHashPath,
42
+ inspectPathToCanonicalHref,
42
43
  withWorkspaceQuery,
43
44
  } from "../router.js";
44
45
  import {
@@ -398,6 +399,33 @@ export async function renderDagDetail(dagRunId, initial = true) {
398
399
  ["运行编号", dag.dagRunId],
399
400
  ["状态", dagStatusBadge(dag.effectiveStatus ?? dag.status)],
400
401
  ];
402
+ // Child runs persist their own lineage even when the parent's terminal
403
+ // snapshot predates recovery. Include those facts without rewriting history.
404
+ const recoveryChildIds = new Set([
405
+ dag.frontendRecovery?.childRunId,
406
+ ...(snap?.dagRuns ?? [])
407
+ .filter(run => run.frontendRecovery?.parentRunId === dag.dagRunId && run.dagRunId !== dag.dagRunId)
408
+ .map(run => run.dagRunId),
409
+ ].filter(Boolean));
410
+ for (const [label, relatedRunId] of [
411
+ ["来源运行", dag.frontendRecovery?.parentRunId ?? dag.continuation?.parentRunId],
412
+ ...[...recoveryChildIds].sort().map(id => ["自动恢复运行", id]),
413
+ ]) {
414
+ if (!relatedRunId || relatedRunId === dag.dagRunId) continue;
415
+ const link = el("a", null, relatedRunId);
416
+ link.href = inspectPathToCanonicalHref(`/dag/${encodeURIComponent(relatedRunId)}`);
417
+ link.addEventListener("click", event => {
418
+ if (event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
419
+ event.preventDefault();
420
+ navigate(`/dag/${encodeURIComponent(relatedRunId)}`);
421
+ });
422
+ primaryEntries.push([label, link]);
423
+ }
424
+ const retriedNodes = nodes.filter(node => (node.executionSummary?.attempts?.length ?? 0) > 1);
425
+ if (retriedNodes.length) {
426
+ const retries = retriedNodes.reduce((total, node) => total + node.executionSummary.attempts.length - 1, 0);
427
+ primaryEntries.push(["节点重试", `${retriedNodes.length} 个节点,共 ${retries} 次;选择节点查看各次结果`]);
428
+ }
401
429
  if (visibility.showExecutorStatus)
402
430
  primaryEntries.push(["执行器状态", livenessValue]);
403
431
  if (visibility.showConsistencyWarning)
@@ -32,7 +32,10 @@ const ledgerError = (code, message) => Object.assign(new Error(message), { code
32
32
  /** Singleton finalize tools: their committed fact is a run terminal and their
33
33
  * params are an acknowledgement, not domain data (see replay rule below). */
34
34
  const FINALIZE_TERMINAL_TOOLS = new Set(["finalize_contract", "finalize_plan", "finalize_decision"]);
35
- const failure = (code, error) => ({ content: [{ type: "text", text: JSON.stringify({ ok: false, code, error }) }], details: { ok: false, code, error } });
35
+ const failure = (code, error, recovery) => {
36
+ const details = { ok: false, code, error, ...(recovery ? { recovery } : {}) };
37
+ return { content: [{ type: "text", text: JSON.stringify(details) }], details };
38
+ };
36
39
  /** A failed rename must never fall back to copying over a live ledger. */
37
40
  async function persist(file, records) {
38
41
  assertHarnessWriteAllowed(file);
@@ -131,7 +134,7 @@ export async function createDurableFrontendTools(input) {
131
134
  if (FINALIZE_TERMINAL_TOOLS.has(tool.name) && previousFact?.receipt)
132
135
  return replay(previousFact.receipt);
133
136
  if (previousFact && naturalId !== undefined && params?.replace !== true && !["record_evidence_expectation", "record_required_deliverables", "record_data_flow"].includes(tool.name))
134
- return failure("FACT_IDENTITY_CONFLICT", `${identity}: changing a saved fact requires explicit replacement (replace:true)`);
137
+ return failure("FACT_IDENTITY_CONFLICT", `${identity}: changing a saved fact requires explicit replacement (replace:true); resubmit the corrected full payload with the same identity and a fresh call id`, { action: "correct-and-resubmit", tool: tool.name, argumentPatch: { replace: true } });
135
138
  if (input.store.records.some(r => ["contract-finalized", "finalize_plan", "finalize_decision", "approve_review", "request_review_changes", "approve_design", "request_design_changes"].includes(String(r.fact.kind))))
136
139
  return failure("TERMINAL_CONFLICT", "A successful terminal is already durable; only identical acknowledged submissions may be replayed");
137
140
  const draft = structuredClone(input.store);
@@ -481,7 +481,7 @@ async function deriveWriteSetFromRun(runDir) {
481
481
  * task source. Smoke r37/r38: specReference.path pointed at a to-be-implemented
482
482
  * file or an AC id — a demand that only lived in review prose could never be
483
483
  * closed by the plan retry ladder. The allowed set is enumerable here. */
484
- async function deriveFrontendSourceBindingPathsFromRun(runDir) {
484
+ export async function deriveFrontendSourceBindingPathsFromRun(runDir) {
485
485
  const specPath = path.join(runDir, "run.json");
486
486
  let raw;
487
487
  try {
@@ -516,15 +516,23 @@ function stripSourcePathFragment(value) {
516
516
  * path (requirement/constraint), never a to-be-implemented file or a bare
517
517
  * acceptance-criterion id. Absent sourceBinding paths (legacy fixtures) the
518
518
  * check is skipped — generation always freezes them. */
519
- function checkComponentChoiceSourceReferences(canonical, sourcePaths) {
519
+ export function checkComponentChoiceSourceReferences(canonical, sourcePaths) {
520
520
  const findings = [];
521
- if (sourcePaths.length === 0)
522
- return findings;
523
521
  for (const choice of canonical.uiComponentChoices ?? []) {
524
522
  if (choice.decision !== "new" && choice.decision !== "specified") {
525
523
  continue;
526
524
  }
527
- const rawPath = choice.specReference?.path ?? "";
525
+ const reference = choice.specReference && typeof choice.specReference === "object"
526
+ ? choice.specReference : {};
527
+ const rawPath = typeof reference.path === "string" ? reference.path : "";
528
+ if (!rawPath.trim() || typeof reference.section !== "string" || !reference.section.trim()) {
529
+ findings.push({ code: "component-choice-source-reference-invalid",
530
+ message: `component choice "${choice.component}" (decision=${choice.decision}) requires non-empty specReference.path and specReference.section; allowed frozen source paths: [${sourcePaths.join(", ")}]`,
531
+ path: "uiComponentChoices" });
532
+ continue;
533
+ }
534
+ if (sourcePaths.length === 0)
535
+ continue;
528
536
  const normalized = stripSourcePathFragment(rawPath);
529
537
  const traceable = normalized.length > 0 &&
530
538
  sourcePaths.some((source) => stripSourcePathFragment(source) === normalized);
@@ -3228,6 +3236,11 @@ export async function writeFrontendContractReviewArtifacts(input) {
3228
3236
  sections,
3229
3237
  };
3230
3238
  const writtenIndex = await writeCompactDeterministicJsonArtifact(input.runDir, indexRelativePath, indexPayload);
3239
+ // Reuse the reader's deterministic coverage and hash checks before dispatch.
3240
+ // The domain reader returns complete semantic sections; SDK file-read byte
3241
+ // limits must not become an admission limit on valid contract content.
3242
+ const { loadFrontendReviewScopes } = await import("./frontend-review-scopes.js");
3243
+ await loadFrontendReviewScopes(input.runDir, "design", 0, undefined, indexRelativePath);
3231
3244
  // Read budgets for the model-backed frontend review nodes were removed
3232
3245
  // (2026-08-31 one-shot): nodes no longer carry maxFiles/maxBytes, so the
3233
3246
  // capacity diagnostic has no budget basis and emits no consumers.
@@ -3598,7 +3611,7 @@ export async function analyzeFrontendPlanPatchCandidate(input) {
3598
3611
  if (uncovered.length > 0) {
3599
3612
  policyPreFindings.push({
3600
3613
  code: "static-verification-coverage-missing",
3601
- message: `verification targets miss frozen static command(s): [${uncovered.map((entry) => `${entry.commandId} (${entry.label})`).join(", ")}]; the frozen directory offers: [${staticCommands.map((entry) => `${entry.commandId} (${entry.label})`).join(", ")}] — record record_verification_focus for every static commandId`,
3614
+ message: `verification targets miss frozen static command(s): [${uncovered.map((entry) => `${entry.commandId} (${entry.label})`).join(", ")}]; the frozen directory offers: [${staticCommands.map((entry) => `${entry.commandId} (${entry.label})`).join(", ")}] — call record_plan_verification_target with entry {id, commandId, file, requirementIds, uiStates: []} for every missing static commandId; use an existing planned implementation file, and reuse the same target id with replace=true when correcting`,
3602
3615
  path: "verificationTargets",
3603
3616
  });
3604
3617
  }
@@ -2,7 +2,7 @@ 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 } from "./frontend-implementation-contract.js";
5
+ import { sha256Hex, writeFrontendContractReviewArtifacts } from "./frontend-implementation-contract.js";
6
6
  import { FRONTEND_RECOVERY_IMPORT_MANIFEST_REL_PATH, FRONTEND_RECOVERY_INTENT_REL_DIR, FRONTEND_RECOVERY_STAGING_PREFIX, computeFrontendRecoveryPlan, computeFrontendRecoveryPlanForSource, } from "./frontend-recovery-plan.js";
7
7
  import { dagRunDirExists, getDagRunDir, locateDagRun, readDagRunSpec, readDagRunState, transferDagRunDir, writeDagRunState, } from "./lifecycle.js";
8
8
  import { buildDagRunId } from "./runner.js";
@@ -417,6 +417,25 @@ async function materializeChildStaging(input) {
417
417
  newRunDir: stagingDir,
418
418
  relativePath: resolveCanonicalContractRelPath(childSpec),
419
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
+ }
420
439
  const writerAdmissionResult = plan.importedNodeIds.includes("frontend-writer-admission-shell") ? await copyArtifactVerified({
421
440
  parentRunDir,
422
441
  newRunDir: stagingDir,
@@ -14,7 +14,7 @@ const isArtifactReference = (value) => isRecord(value)
14
14
  && typeof value.sha256 === "string" && /^[a-f0-9]{64}$/.test(value.sha256);
15
15
  const hash = (text) => createHash("sha256").update(text).digest("hex");
16
16
  /** The section index is navigation; reconstruct coverage against the canonical source before using it. */
17
- export async function loadFrontendReviewScopes(runDir, phase, targetBytes, workspaceRoot) {
17
+ export async function loadFrontendReviewScopes(runDir, phase, targetBytes, workspaceRoot, indexPath = "contracts/frontend-implementation-contract.index.json") {
18
18
  const root = await realpath(runDir);
19
19
  const files = new Map();
20
20
  const sourceChecks = [];
@@ -31,7 +31,7 @@ export async function loadFrontendReviewScopes(runDir, phase, targetBytes, works
31
31
  }
32
32
  let indexArtifact;
33
33
  try {
34
- indexArtifact = await read("contracts/frontend-implementation-contract.index.json");
34
+ indexArtifact = await read(indexPath);
35
35
  }
36
36
  catch (error) {
37
37
  if (error.code === "ENOENT")
@@ -54,7 +54,7 @@ export function classifyFrontendSessionFailure(result) {
54
54
  : errorCode?.includes("LEDGER") || errorCode === "FRONTEND_COMMIT_FAILED" ? "persistence"
55
55
  : errorCode === "TOOL_SCHEMA_INVALID" ? "schema"
56
56
  : /binding|source|permission|write-guard|tool-policy/.test(category) ? "governance"
57
- : /timeout|rate-limit|provider|transport|network|auth/.test(category) ? "provider"
57
+ : /timeout|rate-limit|provider|transport|network|auth|unavailable/.test(category) ? "provider"
58
58
  : /invalid-output|structured-output/.test(category) ? "protocol-or-coverage"
59
59
  : "unknown";
60
60
  return { failureLayer, errorCode };
@@ -14,8 +14,14 @@ const READ_CHUNK_BYTES = 64 * 1024;
14
14
  // with the same names can contain task output and remain in the snapshot.
15
15
  const EXCLUDED_CACHE_DIRS = new Set([".codegraph"]);
16
16
  const EXCLUDED_TREE_DIRS = new Set([".git", "node_modules", ".harness", "artifacts", ...EXCLUDED_CACHE_DIRS]);
17
- function excludedTreeEntry(entry, isRoot) {
18
- return entry.name === ".git" || (isRoot && entry.isDirectory() && EXCLUDED_TREE_DIRS.has(entry.name));
17
+ function excludedTreeEntry(entry, relDir) {
18
+ // Installed operator dependencies are caches too. Keep the operator source,
19
+ // manifests and all delivery-tree lookalikes in the baseline; never hide a
20
+ // symlink by its name. Use the same boundary during capture and inspection.
21
+ const operatorDependencies = entry.name === "node_modules" &&
22
+ (relDir === ".opencode" || /^\.agents\/skills\/[^/]+$/.test(relDir));
23
+ return entry.name === ".git" || (entry.isDirectory() &&
24
+ ((relDir === "" && EXCLUDED_TREE_DIRS.has(entry.name)) || operatorDependencies));
19
25
  }
20
26
  class BaselineLimitError extends Error {
21
27
  }
@@ -155,7 +161,7 @@ async function collectDeliveryPaths(cwd) {
155
161
  for (const entry of entries) {
156
162
  if (error)
157
163
  return;
158
- if (excludedTreeEntry(entry, relDir === ""))
164
+ if (excludedTreeEntry(entry, relDir))
159
165
  continue;
160
166
  entriesSeen += 1;
161
167
  if (entriesSeen > MAX_ENTRIES) {
@@ -576,8 +582,8 @@ function captureDependencies(maxBytes, cwd) {
576
582
  bytes: () => readBytes,
577
583
  dependencies: {
578
584
  readdir: async (dirPath, options) => {
579
- const isRoot = path.resolve(dirPath) === path.resolve(cwd);
580
- const found = (await readdir(dirPath, options)).filter((entry) => !excludedTreeEntry(entry, isRoot));
585
+ const relDir = path.relative(cwd, dirPath).split(path.sep).join("/");
586
+ const found = (await readdir(dirPath, options)).filter((entry) => !excludedTreeEntry(entry, relDir));
581
587
  entries += found.length;
582
588
  if (entries > MAX_ENTRIES) {
583
589
  throw new BaselineLimitError(`baseline has more than ${MAX_ENTRIES} entries`);
@@ -3,6 +3,7 @@ import path from "node:path";
3
3
  import { inspectFrontendTestCommand } from "../../frontend-test-execution-evidence.js";
4
4
  import { createHash } from "node:crypto";
5
5
  import { frontendExecutionPolicySchema } from "../../../../shared/frontend-execution-policy.js";
6
+ import { redactSecrets, redactSensitivePathsWithFindings } from "../../../../shared/preview.js";
6
7
  import { readFile } from "node:fs/promises";
7
8
  import { fileURLToPath } from "node:url";
8
9
  import { assertValidDagSpec } from "../../validate.js";
@@ -569,9 +570,37 @@ export async function buildFrontendHybridDagFromTask(sources) {
569
570
  }));
570
571
  const fixedVerificationContext = [
571
572
  "## Fixed frontend verification entrypoints",
572
- "These shell entrypoints are fixed at DAG generation and are the only commands the static and behavior shell nodes execute. A strategy or plan may add tests behind an existing entrypoint inside writeSet, but must not invent or replace commands or assume subtask_prompt executes a command.",
573
- "Reference frozen commands ONLY by commandId (record_plan_verification_target entry.commandId). The runtime resolves mode and label; never invent a mode or type.",
574
- ...frontendVerifyDirectory.map((entry) => ` - ${entry.commandId} [${entry.mode}]: ${JSON.stringify(entry.label)}`),
573
+ "Shell entrypoints fixed at DAG generation are the only commands the static and behavior shell nodes execute. Add tests behind them within writeSet; never invent/replace commands. subtask_prompt executes nothing.",
574
+ "Reference frozen commands ONLY by commandId; runtime resolves mode/label. Never invent mode/type.",
575
+ "supported does not prove executable availability, test execution, or passing results. Deferred/unsupported is unresolved; scheme unconfirmed. Labels need not be npm scripts.",
576
+ ...frontendVerifyDirectory.map((entry) => {
577
+ const preflight = behaviorVerifyEvidence.preflight.find((candidate) => candidate.testObservation?.commandId === entry.commandId);
578
+ const preview = (_key, value) => {
579
+ if (typeof value !== "string")
580
+ return value;
581
+ // Do not parse arbitrary env/shell values for display. Only these
582
+ // complete, known non-secret assignments may retain a command preview.
583
+ for (const [assignment] of value.matchAll(/\b[A-Za-z_][A-Za-z0-9_]*=[^\s]*/g)) {
584
+ if (assignment !== "NODE_OPTIONS=--experimental-vm-modules" && assignment !== "HARNESS_ALLOW_ACTIVE_DAG_RUNS=1") {
585
+ return "<redacted-sensitive-preview>";
586
+ }
587
+ }
588
+ if (/--[\w-]*(?:token|password|passwd|secret|api[-_]?key|authorization|credential|cookie|header|user)[\w-]*\b|(?:^|[\s'"])-(?:H|u)\b|\b(?:Authorization|Cookie)\s*:|\b(?:Basic|Bearer)\s+\S+|:\/\/[^/\s]+@/i.test(value)) {
589
+ return "<redacted-sensitive-preview>";
590
+ }
591
+ const relative = value.replaceAll(sources.repoRoot ?? process.cwd(), ".");
592
+ // Keep only this exact non-secret runtime flag visible. All other
593
+ // environment values use the shared redactor; execution is untouched.
594
+ const redacted = relative.split(/(\bNODE_OPTIONS=--experimental-vm-modules)(?=$|[\s'"])/)
595
+ .map((part) => part === "NODE_OPTIONS=--experimental-vm-modules" ? part : redactSecrets(part)).join("");
596
+ return redactSensitivePathsWithFindings(redacted).redacted;
597
+ };
598
+ return ` - ${entry.commandId} [${entry.mode}]: ${JSON.stringify({
599
+ label: entry.label,
600
+ command: entry.command,
601
+ ...(preflight ? { preflightStatus: preflight.status, testObservation: preflight.testObservation } : {}),
602
+ }, preview)}`;
603
+ }),
575
604
  `- Static command source: ${staticVerifyEvidence.commandSource}`,
576
605
  `- Behavior command source: ${behaviorVerifyEvidence.commandSource}`,
577
606
  ].join("\n");
@@ -743,6 +772,7 @@ export async function buildFrontendHybridDagFromTask(sources) {
743
772
  subtask_prompt: [
744
773
  "Inspect frontend code, routing, components, styles, package scripts, and tests.",
745
774
  "Return code and design observations, existing reuse opportunities, and verification entry points.",
775
+ "Check required data availability against existing storage/API and forbidden write paths. Historical/aggregate features need actual samples; report a precise blocking gap if the allowed scope cannot provide them, without inventing data or relaxing requirements.",
746
776
  // Mirrors the design-review node's LARGE-FILE AUDIT rule: locate
747
777
  // first, then read a narrow range. Keeps a capped budget usable
748
778
  // instead of forcing all-or-nothing reads.
@@ -885,10 +915,10 @@ export async function buildFrontendHybridDagFromTask(sources) {
885
915
  "Your verdict is consumed as deterministic data input by frontend-writer-admission-shell. approve_design permits admission; request_design_changes blocks writer admission until a recovery plan incorporates every Critical/Important finding.",
886
916
  "Request design changes when the Mock strategy is blocked, missing, unsupported by repository evidence, inconsistent with the API contract, outside authorized paths/dependencies, unable to prove production-default-off behavior with the fixed production/default-real-path static check, or missing deterministic behavior verification for a declared behavior target or selected Mock strategy. Mock strategies require Mock-backed evidence; a static-only contract is allowed only when every verification target is static and maps to a declared static entrypoint; not-needed requires applicable real/no-remote behavior evidence unless auto mode explicitly skipped Mock because no project Mock capability exists, in which case the plan must preserve the real request path and record the Real Integration Gap.",
887
917
  "Also request design changes for missing applicable UI states, unsupported dependency additions, design-system drift without reason, weak interaction coverage, broad scope, inline fake data, schema drift, or missing deterministic verification commands.",
888
- "Component selection conformance is a hard blocking condition: request_design_changes when the frontend spec (component/theme/rule.components bucket) already defines a component for a purpose but the plan selects another or self-invents one without a declared deviation; when uiComponentChoices is missing/empty for UI-visible work while the frozen component/theme bucket is non-empty; when a decision=specified specReference.path is missing a ledger OpenSpec reference or successful read event; or when a decision=new component lacks a traceable task-source/PRD specReference. A PRD reference for decision=new is not an OpenSpec citation and must not be rejected merely for lacking an OpenSpec read event. For uiComponentChoices, coverage is judged by the covers list: every applicable UI state and interaction must appear in some choice's purpose or covers, and the runtime already pre-checks this deterministically at plan finalize — do not re-litigate it. purpose is a human-readable description of what the choice is for and must NOT be rejected merely for not matching an interaction or uiState name; judge responsibility semantics from the covered ids' expectedBehavior plus the choice rationale.",
918
+ "Component conformance blocks design: request_design_changes for an undeclared departure from a component specified for that purpose; missing/empty uiComponentChoices for UI-visible work with a non-empty component/theme bucket; decision=specified missing either a ledger OpenSpec reference or a successful read of specReference.path; or decision=new without traceable task-source/PRD specReference. PRD references for decision=new need no OpenSpec read event. Runtime already checks every applicable UI state/interaction appears in a choice purpose or covers; do not re-litigate it. purpose is a human-readable description and must NOT be rejected merely for not matching an interaction or uiState name; judge semantics using covered ids' expectedBehavior and the choice rationale.",
889
919
  "You must NOT make authoritative assertions about the execution result of frozen verification commands: command results are deterministically established by frontend-verify-shell. Record a verification-feasibility concern only as a non-blocking finding (severity must not be Critical, and it must never be the sole fatal basis for request_design_changes). Only semantic design defects (component selection, state flow, interaction contract, or conflicts with the specification) may be Critical; a pure command-will-fail prediction must not be classified as contract-requirement-gap.",
890
920
  "Read-only: do not modify repository files.",
891
- "LARGE-FILE AUDIT (avoid full reads): style/theme audit files can be large (e.g. styles.css is often hundreds of KB). Prefer grep to locate the exact rules/variables you must verify (e.g. grep the oc- class, is-* modifier, or --oc- theme variables with their line numbers), then read only the narrow line range when surrounding context is needed. Do not read a large style/test file in full — a single full read can exhaust the read budget and fail the attempt.",
921
+ "LARGE-FILE AUDIT: grep exact style/theme rules or test symbols, then read only the needed line range. Full style/test reads can exhaust the read budget and fail the attempt.",
892
922
  "Canonical contract reading: frontend-design-policy-shell prints absolute paths for Contract, Contract index, and the non-blocking Capacity diagnostic. Read the capacity diagnostic first. When it recommends full-contract, read the exact Contract path. When it recommends indexed-sections, read the Contract index and its hash-bound section files instead of opening the full contract. Never resolve a bare contracts/... path against the repository root or hunt for substitutes. Implementation target files inside the writeSet are created later by the implement node: do not read them and do not treat their absence as a design defect.",
893
923
  fixedVerificationContext,
894
924
  sourceContexts.designReview,
@@ -469,10 +469,16 @@ export function buildDagNodePromptEnvelope(input) {
469
469
  ];
470
470
  if (task.id === "frontend-implement-pi" && runDir) {
471
471
  const contractPath = path.resolve(runDir, "contracts/frontend-implementation-contract.json");
472
+ const indexPath = path.resolve(runDir, "contracts/frontend-implementation-contract.index.json");
472
473
  sections.push([
473
474
  "<canonical_contract_input>",
474
- `Read the canonical contract with the read tool at this absolute path: ${contractPath}`,
475
- "This run-owned artifact is read-only. Do not resolve contracts/frontend-implementation-contract.json from the project root or write under the run directory.",
475
+ `Canonical contract identity: ${contractPath}`,
476
+ `Contract index identity: ${indexPath}`,
477
+ "Call read_frontend_contract with no arguments to list semantic sections, then read each listed sectionId before implementation. The tool returns complete JSON and validates coverage and hashes; reading all sections satisfies the canonical-contract prerequisite. Use its unreadSectionIds to track completion.",
478
+ "Do not split or manually reconstruct JSON, and do not require a full-file SDK read of the compact canonical contract.",
479
+ `Resolve section paths relative to this run directory: ${path.resolve(runDir)}`,
480
+ "For multiple data sources, verify all-missing, each source alone, read failure, and genuine zero values where applicable. Preserve usable sections when another source fails; distinguish unavailable data from zero. Do not fabricate samples or extend storage writes beyond the contract.",
481
+ "The index, sections and canonical artifact are read-only. Do not resolve contracts/... from the project root or write under the run directory. If an indexed section is missing or unreadable, report that exact path as blocked; do not silently omit requirements.",
476
482
  "Source target paths remain relative to the project root.",
477
483
  "</canonical_contract_input>",
478
484
  ].join("\n"));
@@ -1,3 +1,4 @@
1
+ import { validateCumulativeBudgetSuccessor } from "./budget-enforcement.js";
1
2
  import { isCanonicalFrontendShapeDag } from "./frontend-shape-facts.js";
2
3
  import { createHash } from "node:crypto";
3
4
  import { readFile } from "node:fs/promises";
@@ -1280,9 +1281,42 @@ export async function evaluateDagRerunPlan(input) {
1280
1281
  blockedReasons.push("evaluation-rerun-unsupported");
1281
1282
  }
1282
1283
  const budgetMode = input.parentSpec.budget?.mode ?? input.parentState.budget?.mode;
1284
+ let budgetAuthority;
1283
1285
  if (budgetMode === "hard") {
1284
- reasonCodes.push("budget-rerun-unsupported");
1285
- blockedReasons.push("budget-rerun-unsupported");
1286
+ let budgetBlock;
1287
+ // Canonical frontend continuations also need shape capsules and imported
1288
+ // root artifacts; use their dedicated recovery controller until those
1289
+ // invariants are supported by this generic continuation path.
1290
+ if (isCanonicalFrontendShapeDag(new Map(input.parentSpec.tasks.map(task => [task.id, task])))) {
1291
+ budgetBlock = "budget-rerun-unsupported";
1292
+ }
1293
+ else if (!input.parentState.budgetLedger || !input.parentState.budget || !input.parentSpec.budget) {
1294
+ budgetBlock = "budget-lineage-missing";
1295
+ }
1296
+ else if (input.parentState.budgetLedger.status === "breached" || input.parentState.budgetLedger.breaches.length > 0) {
1297
+ budgetBlock = "budget-lineage-breached";
1298
+ }
1299
+ else {
1300
+ const ledger = input.parentState.budgetLedger;
1301
+ const lineage = { parentLedgerSha256: hashCanonicalValue(ledger), inheritedConsumed: structuredClone(ledger.consumed) };
1302
+ try {
1303
+ if (hashCanonicalValue(input.parentSpec.budget) !== hashCanonicalValue(input.parentState.budget))
1304
+ throw new Error("budget drift");
1305
+ validateCumulativeBudgetSuccessor(input.parentState, { ...input.parentState, frontendRecoveryState: {
1306
+ ...input.parentState.frontendRecoveryState, parentRunId: input.parentState.runId, budgetLineage: lineage,
1307
+ }, continuation: undefined });
1308
+ if (workspaceMatched && input.currentWorkspace?.fingerprint) {
1309
+ budgetAuthority = { schemaVersion: 1, workspaceFingerprint: input.currentWorkspace.fingerprint, budget: lineage };
1310
+ }
1311
+ }
1312
+ catch {
1313
+ budgetBlock = "budget-lineage-drift";
1314
+ }
1315
+ }
1316
+ if (budgetBlock) {
1317
+ reasonCodes.push(budgetBlock);
1318
+ blockedReasons.push(budgetBlock);
1319
+ }
1286
1320
  }
1287
1321
  if (!input.parentTerminalWorkspace?.fingerprint) {
1288
1322
  reasonCodes.push("workspace-checkpoint-missing");
@@ -1319,7 +1353,9 @@ export async function evaluateDagRerunPlan(input) {
1319
1353
  ...(task.readSet ?? []),
1320
1354
  ].some((pattern) => pathMatchesWorkspacePattern(driftPath, pattern));
1321
1355
  }));
1322
- if (scopedDrift) {
1356
+ // Hard-budget continuations require a bound V2 authority. Scoped drift
1357
+ // alone cannot authorize a V1 plan that would omit cumulative consumption.
1358
+ if (scopedDrift && budgetMode !== "hard") {
1323
1359
  reasonCodes.push("workspace-drift-scoped");
1324
1360
  }
1325
1361
  else {
@@ -1471,6 +1507,17 @@ export async function evaluateDagRerunPlan(input) {
1471
1507
  }),
1472
1508
  ...(promptOverrideEntries ? { promptOverrides: promptOverrideEntries } : {}),
1473
1509
  };
1510
+ if (budgetAuthority && effectiveFromNodeId) {
1511
+ const plan = {
1512
+ ...planWithoutHash, schemaVersion: 2, trigger: promptOverrideEntries?.length ? "prompt-override" : "node-rerun",
1513
+ highRiskAuthority: budgetAuthority,
1514
+ bindings: { ...bindings, artifactGraphSha256: buildArtifactBindingGraph(input.parentSpec).artifactGraphSha256,
1515
+ parentWorkspaceFingerprint: budgetAuthority.workspaceFingerprint, currentWorkspaceFingerprint: budgetAuthority.workspaceFingerprint,
1516
+ budgetLedgerSha256: budgetAuthority.budget.parentLedgerSha256 },
1517
+ impact: { directConsumerNodeIds: [], effectiveFromNodeId, affectedNodeIds: resetNodeIds, importedNodeIds, blockedNodeIds: blockingNodes },
1518
+ };
1519
+ return dagRerunPlanV2Schema.parse({ ...plan, planHash: computePlanHash(plan) });
1520
+ }
1474
1521
  return {
1475
1522
  ...planWithoutHash,
1476
1523
  planHash: computePlanHash(planWithoutHash),
@@ -1,3 +1,4 @@
1
+ import { validateCumulativeBudgetSuccessor } from "./budget-enforcement.js";
1
2
  import { createHash, timingSafeEqual } from "node:crypto";
2
3
  import { access, copyFile, lstat, mkdir, readdir, readFile, writeFile } from "node:fs/promises";
3
4
  import path from "node:path";
@@ -875,6 +876,7 @@ async function stageContinuationRun(input) {
875
876
  ...(input.parentState.budget
876
877
  ? { budget: structuredClone(input.parentState.budget) }
877
878
  : {}),
879
+ ...(input.parentState.sourceProviderBudget ? { sourceProviderBudget: structuredClone(input.parentState.sourceProviderBudget) } : {}),
878
880
  ...(input.parentState.budgetLedger
879
881
  ? { budgetLedger: structuredClone(input.parentState.budgetLedger) }
880
882
  : {}),
@@ -889,6 +891,8 @@ async function stageContinuationRun(input) {
889
891
  }
890
892
  : {}),
891
893
  };
894
+ if (state.budget?.mode === "hard")
895
+ validateCumulativeBudgetSuccessor(input.parentState, state);
892
896
  if (!input.parentState.skillSnapshotRef) {
893
897
  throw new Error("parent run is missing skill snapshot ref");
894
898
  }
@@ -1,3 +1,4 @@
1
+ import { prepareFrontendFrozenBaselineGuard } from "./frontend-writer-baseline-guard.js";
1
2
  import { assertFrontendPairExecution } from "../../application/evaluation/frontend-pair-registration.js";
2
3
  import { sourceBudgetContractIdentity } from "../../application/evaluation/budget.js";
3
4
  import { summarizeFrozenSourceUsage } from "../../task/source-prepare/source-provider-budget.js";
@@ -20,6 +21,7 @@ import { normalizeDagPromptSources } from "./prompt-source.js";
20
21
  import { createSkillSnapshot, prepareSkillSnapshotForContinuation, writeSkillSnapshot, } from "./skill-snapshot.js";
21
22
  import { captureWorkspaceCheckpoint, WORKSPACE_CHECKPOINT_START_REL, writeWorkspaceCheckpoint, } from "./workspace-checkpoint.js";
22
23
  import { buildNodePrompt, buildNodePromptWithResolvedSkillInstructions, } from "./node-execution.js";
24
+ import { FRONTEND_WRITER_NODE_IDS, } from "./scheduler.js";
23
25
  import { topoSortToRanks } from "./topo.js";
24
26
  import { isCanonicalFrontendShapeDag, } from "./frontend-shape-facts.js";
25
27
  import { assertFrontendTopologyBinding, buildFrontendTopologyBinding, } from "./frontend-shape.js";
@@ -244,6 +246,15 @@ export async function runDag(spec, opts) {
244
246
  ...DAG_CONTROLLER_CAPABILITIES,
245
247
  controllerVersion: runningIdentity.packageVersion,
246
248
  });
249
+ // Check deterministic delivery-tree limits before spending any model budget.
250
+ // This snapshot is discarded: the writer still captures fresh bytes at each
251
+ // frozen check so preflight cannot weaken its CAS protection.
252
+ if (!opts.dryRun && !opts.initOnly && spec.tasks.some(task => FRONTEND_WRITER_NODE_IDS.includes(task.id) && task.executor === "pi" && task.writePolicy === "exclusive")) {
253
+ const baseline = await prepareFrontendFrozenBaselineGuard({ cwd: opts.cwd });
254
+ if (baseline.status !== "ready") {
255
+ throw new Error(`FRONTEND_EXECUTION_PREFLIGHT_FAILED: ${baseline.reason}; fix the workspace before retrying`);
256
+ }
257
+ }
247
258
  const { ranks } = topoSortToRanks(spec);
248
259
  const { maxConcurrent } = resolveEffectiveMaxConcurrent(Math.max(1, opts.maxConcurrent ?? 4), spec.budget);
249
260
  let runId = opts.runId;