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

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 (114) hide show
  1. package/CHANGELOG.md +15 -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/extension.js +24 -0
  13. package/dist/shared/pi-context-pressure/sift-bridge.js +2 -1
  14. package/dist/shared/pi-context-pressure/tool-result-pruner.js +8 -3
  15. package/dist/task/source-prepare/completeness.js +2 -2
  16. package/dist/task/source-prepare/diagnostic.js +76 -0
  17. package/dist/task/source-prepare/ledger-reconciliation.js +65 -9
  18. package/dist/task/source-prepare/ledger-review.js +18 -2
  19. package/dist/task/source-prepare/ledger.js +3 -1
  20. package/dist/task/source-prepare/prepare.js +23 -3
  21. package/dist/task/source-prepare/source-fidelity-pi.js +12 -1
  22. package/dist/task/source-prepare/types.js +1 -1
  23. package/dist/worker/console/chat/chat-event-projection.js +8 -0
  24. package/dist/worker/console/chat/chat-event-store.js +1 -0
  25. package/dist/worker/console/chat/context-insights.js +52 -3
  26. package/dist/worker/console/chat/context-usage.js +54 -0
  27. package/dist/worker/console/chat/pi-runtime/context-edit.js +83 -0
  28. package/dist/worker/console/chat/pi-runtime.js +17 -0
  29. package/dist/worker/console/chat/vcp-prompt.js +20 -13
  30. package/dist/worker/console/recovery-error-copy.js +4 -1
  31. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-DUtUeeEa.js → abnfDiagram-N423BO3Z-BDoJuIJc.js} +1 -1
  32. package/dist/worker/console/static/assets/{arc-Cs0DSwTY.js → arc-BIcO0B1H.js} +1 -1
  33. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-C80FSNgl.js → architectureDiagram-T3A2C74G-DbxnPcOI.js} +1 -1
  34. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-DFgOZUzn.js → blockDiagram-VBNYF7ZC-BG4tXH7C.js} +1 -1
  35. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-CB9nkTjT.js → c4Diagram-5PPSVZJV-BaNxGG9H.js} +1 -1
  36. package/dist/worker/console/static/assets/channel-DigIZ6M1.js +1 -0
  37. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-DbjpoOrh.js → chunk-2GRJ4B5K-BYr2qNac.js} +1 -1
  38. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-BsWVWnWY.js → chunk-2Q5K7J3B-D3q2b9W9.js} +1 -1
  39. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-BwwP_1AG.js → chunk-5RXB4S5H-BFsAsJ8z.js} +1 -1
  40. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-DDEzW9MV.js → chunk-5VM5RSS4-Bnp6GtE7.js} +1 -1
  41. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-D-fLZDni.js → chunk-6Q2QTUOP-CzDChmU1.js} +1 -1
  42. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-DY9q3jMo.js → chunk-GF5L2VYU-kgZTzZlf.js} +1 -1
  43. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-rkUPkzPh.js → chunk-JWPE2WC7-Vnt5nEN_.js} +1 -1
  44. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-Ci9ZksX4.js → chunk-KBJHAD2P-CENlGfou.js} +1 -1
  45. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-DKU-3Ef6.js → chunk-RYQCIY6F-DS1bOotT.js} +1 -1
  46. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-A-xOwXvl.js → chunk-XXDRQBXY-SkFJspnw.js} +1 -1
  47. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-AY-sL87U.js +1 -0
  48. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-AY-sL87U.js +1 -0
  49. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-Bfs1rphL.js → cose-bilkent-JH36ORCC-BE1OAnpP.js} +1 -1
  50. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-BTlXtGR2.js → cynefin-VYW2F7L2-BaTDZwL-.js} +1 -1
  51. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-D8c9vCCr.js → cynefinDiagram-MW4NZA55-BRrIdbbw.js} +1 -1
  52. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-B-e-tfgY.js → dagre-VZM6K2ZE-B4pDil_r.js} +1 -1
  53. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-CG_5dIVJ.js → diagram-7IWD3JNH-DvqFh-9w.js} +1 -1
  54. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-CmP40HmK.js → diagram-B4RE2ZJO-D7me-QwT.js} +1 -1
  55. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-RFt8vi9Y.js → diagram-LBJQPF4R-EahLHu6K.js} +1 -1
  56. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-CM5Sb2jB.js → diagram-Q27KOJAE--S6g2rQZ.js} +1 -1
  57. package/dist/worker/console/static/assets/{diagram-UB23O5K3-Bm4zh0WJ.js → diagram-UB23O5K3-BwqA9gGp.js} +1 -1
  58. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-b3GekSN4.js → ebnfDiagram-BXEA7PRR-Bdj6kj6x.js} +1 -1
  59. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-CFZh4C_o.js → erDiagram-JOGREHBK-_Ii2v364.js} +1 -1
  60. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-CzxniD3z.js → flowDiagram-UKHOOZJN-LM1yby4D.js} +1 -1
  61. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-Czp6xUXj.js → ganttDiagram-PKOTCBZU-_MmByUIz.js} +1 -1
  62. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-B66oX4sn.js → gitGraphDiagram-DS77QQ5N-Be4J6q3D.js} +1 -1
  63. package/dist/worker/console/static/assets/{index-Bq_vMDO3.js → index-CpugPRcA.js} +120 -120
  64. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-rTveEtft.js → infoDiagram-6WML65LV-CFRi5O36.js} +1 -1
  65. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-N2jiPnrD.js → ishikawaDiagram-WSZJBQD7-B2OnsVXe.js} +1 -1
  66. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-DtnLwtAE.js → journeyDiagram-NVQOT4AX-Dnz8Ge36.js} +1 -1
  67. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-t9D_2QMN.js → kanban-definition-27J2QSJJ-DFPGjB3O.js} +1 -1
  68. package/dist/worker/console/static/assets/{linear-BP6ZG0tB.js → linear-DrKFn9ZE.js} +1 -1
  69. package/dist/worker/console/static/assets/{mermaid.core-Cc5_ZtUy.js → mermaid.core-C4__OfPT.js} +5 -5
  70. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-zztwmHj8.js → mindmap-definition-FAOFIHXS-CMEMeYGS.js} +1 -1
  71. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-CmXQOyPH.js → pegDiagram-VL7TDLO6-BDNDtN72.js} +1 -1
  72. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BodwfpEp.js → pieDiagram-7S7Q4E2Y-DX12wRku.js} +1 -1
  73. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-DIgybsTM.js → quadrantDiagram-CIZ2JOQS-DEzotPpD.js} +1 -1
  74. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-CZb_4Cv2.js → railroadDiagram-AXF67PYL-BGbCCVjx.js} +1 -1
  75. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-BvRNauBA.js → requirementDiagram-LRYGKXZP-eClVYdkl.js} +1 -1
  76. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BQ30kRWi.js → sankeyDiagram-W5VNT64P-Hyw3eFyF.js} +1 -1
  77. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-B7sGR3r3.js → sequenceDiagram-SI44F4Z6-DwysyBPq.js} +1 -1
  78. package/dist/worker/console/static/assets/{sheet-workbook-CK8pzw-q.js → sheet-workbook-jLtIaGKt.js} +1 -1
  79. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-1HZrTeyl.js → sizeCapture-X5ZJPWSS-CsA3-7gH.js} +1 -1
  80. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-BKCXlJRS.js → stateDiagram-OKZ733FA-DkUPiKZ8.js} +1 -1
  81. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-BiXtsN97.js +1 -0
  82. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-BhT8u6Vm.js → swimlanes-SLNWSIFB-qfVo6Xay.js} +2 -2
  83. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-ImoXsndy.js +8 -0
  84. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-Dnczuw3j.js → timeline-definition-Z64GVDOM-BRTsFNL5.js} +1 -1
  85. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-PgJCj-16.js → vennDiagram-T6HMQDX7-BI-btTm3.js} +1 -1
  86. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-BjuszbFn.js → wardleyDiagram-T6FBY63Y-BYMVY4Ov.js} +1 -1
  87. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-Dhtjuxrn.js → xychartDiagram-ELKLHX3M-CvK7yNi0.js} +1 -1
  88. package/dist/worker/console/static/index.html +1 -1
  89. package/dist/worker/console/static-src/operator-chat/vcp-fonts.js +1 -6
  90. package/dist/worker/console/workspace-context.js +53 -1
  91. package/dist/worker/observe/static/dag-history-labels.js +2 -0
  92. package/dist/worker/observe/static/views/dag.js +28 -0
  93. package/dist/workflows/dag/frontend-durable-tools.js +5 -2
  94. package/dist/workflows/dag/frontend-implementation-contract.js +19 -6
  95. package/dist/workflows/dag/frontend-recovery-run.js +20 -1
  96. package/dist/workflows/dag/frontend-review-scopes.js +2 -2
  97. package/dist/workflows/dag/frontend-session-budget.js +1 -1
  98. package/dist/workflows/dag/frontend-writer-baseline-guard.js +11 -5
  99. package/dist/workflows/dag/hybrid/templates/frontend.js +35 -5
  100. package/dist/workflows/dag/prompt.js +8 -2
  101. package/dist/workflows/dag/rerun-plan.js +50 -3
  102. package/dist/workflows/dag/rerun-run.js +4 -0
  103. package/dist/workflows/dag/runner.js +11 -0
  104. package/package.json +3 -3
  105. package/dist/worker/console/static/assets/channel-BddnaJc4.js +0 -1
  106. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-CqfGeesl.js +0 -1
  107. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-CqfGeesl.js +0 -1
  108. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DzDcqZJM.js +0 -1
  109. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DgnnY3K8.js +0 -8
  110. package/dist/worker/console/static/vcp/fonts/Lanxi-GreatVibes.woff2 +0 -0
  111. package/dist/worker/console/static/vcp/fonts/Lanxi-MaShanZheng.woff2 +0 -0
  112. package/dist/worker/console/static/vcp/fonts/Lanxi-/347/202/271/351/273/221.woff2 +0 -0
  113. package/dist/worker/console/static/vcp/fonts/Lanxi-/351/235/231/351/273/221/350/266/205/347/273/206.woff2 +0 -0
  114. package/dist/worker/console/static/vcp/fonts/Lanxi-/351/261/274/345/260/276/350/241/214/344/271/246.woff2 +0 -0
package/CHANGELOG.md CHANGED
@@ -8,16 +8,23 @@
8
8
 
9
9
  - 控制台精简内置中文字体包并修复排版引擎的样式覆盖问题,保留常用核心字族,大幅降低安装包体积。
10
10
  - Console 默认采用启动环境中的代理,也可在设置中切换直连或手动代理;保存后新请求立即生效,无需重启,正在输出的回复可继续完成。
11
+ - 前端任务提前检查工作区规模和计划可读性,提交错误可当场修正;运行详情显示重试次数,并可跳转查看自动恢复的前后运行。
12
+ - 普通安全节点续跑可继承剩余硬预算;预算缺失、超限或不一致时会说明原因并停止。前端专用恢复仍使用原恢复入口。
11
13
  - 正式版本的更新说明以「上一正式版本」为对比起点,说明这次升级带来的变化。
12
14
  - 版本页缺少本版本说明时仍可查看历史;新发布版本可直接读取说明,较大的已发布包有更充足的查询时间,失败时会区分超时和内容缺失。预发布版本会保留该构建的待发布变化快照。
13
15
 
14
16
  ### 修复
15
17
 
18
+ - 修复读取较长工具结果时内容反复被压缩、导致任务耗尽请求额度的问题。
19
+
16
20
  - 修复切换对话后停在顶部或回复中间的问题,默认显示最新助手回复末尾;主动上翻后,调整窗口宽度仍保留阅读位置。
17
21
  - 修复浏览器工具在元素引用过期时未提供恢复线索的问题;现在会返回当前可用快照与具体失效原因,避免调用方盲目重试。
18
22
  - 修复因上游依赖包导出变更导致后台服务启动时偶发崩溃的问题。
23
+ - 修复前端任务因验证职责误判、并行检查重名、已有测试命令未识别、工具依赖过多或计划文件过大而无法继续的问题。重试会复用已完成步骤并保留完整计划读取材料,无效入口路径可在检查时修正。
24
+ - 初始化更新会保留有效的项目调度配置,不再因此反复要求合并配置文件。
25
+ - 需求检查失败时保留逐条判定和审核理由,并准确区分未解决条款与背景说明,便于定位阻塞原因。
19
26
 
20
- ## [0.51.0-next.1] - 2026-10-13
27
+ ## [0.51.0-next.2] - 2026-10-14
21
28
 
22
29
  本预发布快照记录构建时已整理的待发布变化,不表示相对上一构建全部新增。
23
30
 
@@ -25,14 +32,21 @@
25
32
 
26
33
  - 控制台精简内置中文字体包并修复排版引擎的样式覆盖问题,保留常用核心字族,大幅降低安装包体积。
27
34
  - Console 默认采用启动环境中的代理,也可在设置中切换直连或手动代理;保存后新请求立即生效,无需重启,正在输出的回复可继续完成。
35
+ - 前端任务提前检查工作区规模和计划可读性,提交错误可当场修正;运行详情显示重试次数,并可跳转查看自动恢复的前后运行。
36
+ - 普通安全节点续跑可继承剩余硬预算;预算缺失、超限或不一致时会说明原因并停止。前端专用恢复仍使用原恢复入口。
28
37
  - 正式版本的更新说明以「上一正式版本」为对比起点,说明这次升级带来的变化。
29
38
  - 版本页缺少本版本说明时仍可查看历史;新发布版本可直接读取说明,较大的已发布包有更充足的查询时间,失败时会区分超时和内容缺失。预发布版本会保留该构建的待发布变化快照。
30
39
 
31
40
  ### 修复
32
41
 
42
+ - 修复读取较长工具结果时内容反复被压缩、导致任务耗尽请求额度的问题。
43
+
33
44
  - 修复切换对话后停在顶部或回复中间的问题,默认显示最新助手回复末尾;主动上翻后,调整窗口宽度仍保留阅读位置。
34
45
  - 修复浏览器工具在元素引用过期时未提供恢复线索的问题;现在会返回当前可用快照与具体失效原因,避免调用方盲目重试。
35
46
  - 修复因上游依赖包导出变更导致后台服务启动时偶发崩溃的问题。
47
+ - 修复前端任务因验证职责误判、并行检查重名、已有测试命令未识别、工具依赖过多或计划文件过大而无法继续的问题。重试会复用已完成步骤并保留完整计划读取材料,无效入口路径可在检查时修正。
48
+ - 初始化更新会保留有效的项目调度配置,不再因此反复要求合并配置文件。
49
+ - 需求检查失败时保留逐条判定和审核理由,并准确区分未解决条款与背景说明,便于定位阻塞原因。
36
50
 
37
51
  ## [0.49.0] - 2026-10-11
38
52
 
@@ -693,6 +693,7 @@ export async function advanceTaskLifecycle(input) {
693
693
  ...(sourceFidelity ? { sourceFidelity } : {}),
694
694
  });
695
695
  if (!prepareResult.ok) {
696
+ warnings.push(...(prepareResult.warnings ?? []).filter((warning) => warning.code === "SOURCE_PREPARE_DIAGNOSTIC_WRITE_FAILED"));
696
697
  const gapCodes = (prepareResult.gaps ?? [])
697
698
  .filter((gap) => gap.level === "blocking")
698
699
  .map((gap) => gap.code);
@@ -799,6 +800,7 @@ export async function advanceTaskLifecycle(input) {
799
800
  continue;
800
801
  }
801
802
  prepareResult = retry;
803
+ warnings.push(...(retry.warnings ?? []).filter((warning) => warning.code === "SOURCE_PREPARE_DIAGNOSTIC_WRITE_FAILED"));
802
804
  // fall through with retry gaps
803
805
  }
804
806
  else {
@@ -873,6 +875,10 @@ export async function advanceTaskLifecycle(input) {
873
875
  gaps: prepareResult.gaps,
874
876
  outcome: prepareResult.outcome,
875
877
  softIntake: softIntakeAfter,
878
+ ...(prepareResult.diagnosticPath ? {
879
+ diagnosticPath: prepareResult.diagnosticPath,
880
+ diagnosticSummary: prepareResult.diagnosticSummary,
881
+ } : {}),
876
882
  },
877
883
  });
878
884
  break;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "version": "0.51.0-next.1",
4
- "gitSha": "85429dabf380106db888fd81e68025f91901287b",
5
- "builtAt": "2026-10-13T15:43:10.422Z"
3
+ "version": "0.51.0-next.2",
4
+ "gitSha": "306c6fab335a5962ff2cee5f528bb934b05468d1",
5
+ "builtAt": "2026-10-14T05:42:40.679Z"
6
6
  }
@@ -6,6 +6,7 @@ import { fileURLToPath } from "node:url";
6
6
  import { GITIGNORE_BLOCK_END, GITIGNORE_BLOCK_START, buildManagedGitignoreBlock, extractGitignoreManagedBlock, mergeGitignoreManagedBlock, } from "../shared/gitignore-managed-block.js";
7
7
  import { isInitRuntimeActive, } from "../shared/runtime-activity.js";
8
8
  import { loadHarnessManifest } from "../governance/harness.js";
9
+ import { workerPolicySchema } from "../governance/manifest-types.js";
9
10
  import { OPENCODE_CONTEXT_OVERFLOW_COMPACT_PLUGIN_PATH, OPENCODE_TRANSIENT_RETRY_PLUGIN_PATH, PI_CONTEXT_OVERFLOW_EXTENSION_PATH, PI_PROJECT_SETTINGS_PATH, applyProjectPiSettingsMerge, buildOpenCodeContextOverflowCompactPluginSource, buildProjectPiSettingsSource, buildOpenCodeTransientRetryPluginSource, buildPiContextOverflowExtensionSource, inspectProjectPiSettings, } from "./client-recovery.js";
10
11
  import { assessInitPiModelReadiness, discoverInitModelCatalog, validateInitModelMatrixAgainstCatalog, } from "./init-model-catalog.js";
11
12
  import { auditLegacyInitSurface, findInitRetirementConsumers, inspectContainedRegularFile, legacyAuditReceipt, removeContainedRegularFileWithSha256Cas, } from "./init-legacy-audit.js";
@@ -1415,14 +1416,22 @@ function isPiModelRoutingPath(path) {
1415
1416
  }
1416
1417
  /**
1417
1418
  * Attribute-set iteration comparison for harness.json: object key shapes must
1418
- * agree at every level, except that the Pi model-routing fields are opaque
1419
- * project-owned configuration. Scalars and array contents may otherwise differ
1420
- * freely unless the key is structurally sensitive.
1419
+ * agree at every level, except for opaque project-owned Pi model routing and
1420
+ * schema-valid optional worker policy. Scalars and array contents may otherwise
1421
+ * differ freely unless the key is structurally sensitive.
1421
1422
  */
1422
1423
  function harnessJsonShapeMatches(current, desired, path = []) {
1423
1424
  if (isRecord(current) || isRecord(desired)) {
1424
1425
  if (!isRecord(current) || !isRecord(desired))
1425
1426
  return false;
1427
+ if (path.length === 0 &&
1428
+ "workerPolicy" in current &&
1429
+ !("workerPolicy" in desired)) {
1430
+ const { workerPolicy, ...managedCurrent } = current;
1431
+ if (!workerPolicySchema.safeParse(workerPolicy).success)
1432
+ return false;
1433
+ return harnessJsonShapeMatches(managedCurrent, desired);
1434
+ }
1426
1435
  const filterKeys = (value) => Object.keys(value)
1427
1436
  .filter((key) => !isPiModelRoutingPath(path) || !PI_MODEL_ROUTING_KEYS.has(key))
1428
1437
  .sort();
@@ -104,6 +104,17 @@ export function collectFrontendPlanMissingFacts(input) {
104
104
  }
105
105
  return missing;
106
106
  }
107
+ /** Reuse only explicit current policy decisions, never a finalize patch snapshot. */
108
+ export function hasCompleteFrontendPlanGlobalPolicy(input) {
109
+ const facts = input.committedFacts.map(committedFactFromPlanRecord).filter((fact) => Boolean(fact && fact.origin === "plan"));
110
+ const route = facts.filter(fact => fact.kind === "target-surface" && !fact.patch).at(-1);
111
+ const dependency = facts.filter(fact => fact.kind === "dependency").at(-1);
112
+ // As in the assembler, singleton policies are latest-wins. A missing or
113
+ // empty current value must not be rescued by an earlier valid decision.
114
+ return planFactStringList(route?.routes).length > 0 &&
115
+ (!input.dependencyPolicyRequired ||
116
+ typeof dependency?.policy === "string" && dependency.policy.trim().length > 0);
117
+ }
107
118
  /** Completeness checks for phases whose facts are committed incrementally. */
108
119
  export function collectFrontendPlanPhaseMissingFacts(input) {
109
120
  const facts = input.committedFacts
@@ -152,12 +163,15 @@ export function collectFrontendPlanPhaseMissingFacts(input) {
152
163
  }
153
164
  return missing;
154
165
  }
155
- const hasMockApi = facts.some((fact) => fact.kind === "mock-api");
166
+ const latestMock = facts.filter(fact => fact.kind === "mock-api").at(-1)?.mockApi;
167
+ const hasMockApi = Boolean(latestMock && typeof latestMock === "object" &&
168
+ !Array.isArray(latestMock) && typeof latestMock.strategy === "string" &&
169
+ String(latestMock.strategy).trim());
156
170
  const allInteractions = collectCanonicalStateFlowNames(input.committedFacts).interactionNames;
157
171
  const liveInteractions = new Set([...collectCanonicalStateFlowNames(facts.filter(f => !planFactStringList(f.scopeRequirementIds).length || planFactScopeIntersects(f, new Set(input.requirementIds)))).interactionNames].filter(name => allInteractions.has(name)));
158
- const coveredInteractions = new Set(facts
159
- .filter((fact) => fact.kind === "data-flow")
160
- .flatMap((fact) => planFactStringList(fact.interactions)));
172
+ // record_data_flow accumulates by default and publishes a replacement
173
+ // snapshot for replace:true. Earlier membership cannot revive a removal.
174
+ const coveredInteractions = new Set(planFactStringList(facts.filter(fact => fact.kind === "data-flow").at(-1)?.interactions));
161
175
  const missing = [];
162
176
  if (!hasMockApi) {
163
177
  missing.push({
@@ -53,7 +53,7 @@ export function buildPlanRecordTools(ctx) {
53
53
  const recordComponentChoiceTool = defineTool({
54
54
  name: "record_component_choice",
55
55
  label: "record_component_choice",
56
- description: "Record ONE component choice (origin=plan component-choice fact). One choice may cover MULTIPLE UI states/interactions via covers: [\"<state-or-interaction name>\", ...]; do not emit one row per interaction. For decision=new, pass sourceRequirementIds containing the frozen requirement ID(s) that mandate the component and sourceFragmentId selecting one frozen citation listed in the plan checklist; the runtime validates the relation and derives the exact PRD specReference. Do not read the PRD or invent a path/line. decision=reuse-existing is only for components that already exist in the repo and REQUIRES evidencePath: a repo-relative path to the existing file that proves the reuse — the runtime verifies the file exists (fresh evidence); a path with no existing file is greenfield and must use decision=new instead. Call up to 5 component choices per assistant message; never more than 5 per message. Optionally include stylingStrategy (set it once, on the first call). Example: {\"choice\": {\"purpose\": \"<interaction or UI state name>\", \"component\": \"<component name>\", \"decision\": \"new\", \"covers\": [\"<other interaction names this component also serves>\"]}, \"sourceRequirementIds\": [\"<AC-XXX mandating this component>\"], \"sourceFragmentId\": \"<REQ-SRC-...>\"} or {\"choice\": {\"purpose\": \"FocusQueuePanel\", \"component\": \"FocusQueuePanel\", \"decision\": \"reuse-existing\", \"evidencePath\": \"src/journal.ts\"}}",
56
+ description: "Record ONE component choice (origin=plan component-choice fact). One choice may cover MULTIPLE UI states/interactions via covers: [\"<state-or-interaction name>\", ...]; do not emit one row per interaction. For decision=specified, provide non-empty specReference.path and section citing the frozen task source, never an implementation file. For decision=new, pass sourceRequirementIds containing the frozen requirement ID(s) that mandate the component and sourceFragmentId selecting one frozen citation listed in the plan checklist; the runtime validates the relation and derives the exact PRD specReference. Do not read the PRD or invent a path/line. decision=reuse-existing is only for components that already exist in the repo and REQUIRES evidencePath: a repo-relative path to the existing file that proves the reuse — the runtime verifies the file exists (fresh evidence); a path with no existing file is greenfield and must use decision=new instead. Call up to 5 component choices per assistant message; never more than 5 per message. Optionally include stylingStrategy (set it once, on the first call). Example: {\"choice\": {\"purpose\": \"<interaction or UI state name>\", \"component\": \"<component name>\", \"decision\": \"new\", \"covers\": [\"<other interaction names this component also serves>\"]}, \"sourceRequirementIds\": [\"<AC-XXX mandating this component>\"], \"sourceFragmentId\": \"<REQ-SRC-...>\"} or {\"choice\": {\"purpose\": \"FocusQueuePanel\", \"component\": \"FocusQueuePanel\", \"decision\": \"reuse-existing\", \"evidencePath\": \"src/journal.ts\"}}",
57
57
  promptSnippet: "Record 1-5 component choices (up to 5 per message).",
58
58
  parameters: Type.Object({
59
59
  choice: uiComponentChoiceSchema,
@@ -104,6 +104,12 @@ export function buildPlanRecordTools(ctx) {
104
104
  ...(citation.line !== undefined ? { line: citation.line } : {}),
105
105
  };
106
106
  }
107
+ const { checkComponentChoiceSourceReferences, deriveFrontendSourceBindingPathsFromRun } = await import("../../../workflows/dag/frontend-implementation-contract.js");
108
+ const citationFindings = checkComponentChoiceSourceReferences({ uiComponentChoices: [choice] }, await deriveFrontendSourceBindingPathsFromRun(input.runDir));
109
+ if (citationFindings.length) {
110
+ return planToolReceipt({ ok: false, kind: "component-choice",
111
+ error: citationFindings.map(finding => finding.message).join("; ") + "; re-submit record_component_choice with the same purpose and a frozen source citation; use reuse-existing with evidencePath only when reusing an existing component." });
112
+ }
107
113
  if (choice.decision === "reuse-existing") {
108
114
  // reuse-existing must cite a file that actually exists NOW (fresh
109
115
  // existence evidence, same semantics as Scout pathEvidence.fresh).
@@ -660,7 +666,7 @@ export function buildPlanRecordTools(ctx) {
660
666
  const recordPlanVerificationTargetTool = defineTool({
661
667
  name: "record_plan_verification_target",
662
668
  label: "record_plan_verification_target",
663
- description: "Commit one plan verification target entry (origin=plan plan-verification-target fact). Reference a frozen verification command by commandId (see the frozen command directory in your prompt: static commands are project-wide checks traced by file and command only; behavior commands bind an existing affected test file; preserve its test names). For behavior targets, call once per distinct behavior, not mechanically once per requirement: one target may cover multiple related requirementIds. For a correction, re-submit the same id with replace=true; the ledger compiles the latest replacement. A target id identifies a contract entry only; never require it in test names. Results bind by frozen command and test file. Entry carries id, commandId, file, requirementIds, and uiStates; optional scope (unit | component | integration) is display-only. Free-form symbol text is not accepted. IMPORTANT: batch up to 4 record_* calls per assistant message; never batch more than 4 — a larger single message risks output truncation under a small output window. Example: {\"entry\": {\"id\": \"VT-DASHBOARD-SHELL\", \"commandId\": \"<frozen behavior command id>\", \"file\": \"<test file>\", \"requirementIds\": [\"AC-001\", \"AC-002\"], \"uiStates\": []}}" +
669
+ description: "Commit one plan verification target entry (origin=plan plan-verification-target fact). Reference a frozen verification command by commandId (see the frozen command directory in your prompt: EVERY static command must have a target, even when behavior tests are already covered; static commands are project-wide checks traced by a planned implementation file and command only; behavior commands bind an existing affected test file; preserve its test names). For behavior targets, call once per distinct behavior, not mechanically once per requirement: one target may cover multiple related requirementIds. For a correction, re-submit the same id with replace=true; the ledger compiles the latest replacement. A target id identifies a contract entry only; never require it in test names. Results bind by frozen command and test file. Entry carries id, commandId, file, requirementIds, and uiStates; optional scope (unit | component | integration) is display-only. Free-form symbol text is not accepted. IMPORTANT: batch up to 4 record_* calls per assistant message; never batch more than 4 — a larger single message risks output truncation under a small output window. Example: {\"entry\": {\"id\": \"VT-DASHBOARD-SHELL\", \"commandId\": \"<frozen behavior command id>\", \"file\": \"<test file>\", \"requirementIds\": [\"AC-001\", \"AC-002\"], \"uiStates\": []}}" +
664
670
  (input.canonicalVerificationTargetIds &&
665
671
  input.canonicalVerificationTargetIds.length > 0
666
672
  ? ` Frozen canonical behavior target ids (use exactly for behavior targets): ${input.canonicalVerificationTargetIds.join(", ")}.`
@@ -784,6 +790,17 @@ export function buildPlanRecordTools(ctx) {
784
790
  // (r7: one full attempt lost to a single unknown UI state name).
785
791
  const committedEvents = readCommittedEvents(session.store, session.attemptId);
786
792
  const declaredUiStateNames = collectCanonicalStateFlowNames(committedEvents).uiStateNames;
793
+ const stateVocabulary = collectCanonicalStateFlowNames(committedEvents);
794
+ if (verifyDirectory.find(command => command.commandId === verificationCommandId)?.mode === "behavior") {
795
+ if (stringList(rawEntry.requirementIds).length === 0) {
796
+ return planToolReceipt({ ok: false, kind: "plan-verification-target",
797
+ error: `behavior verification target ${vtId} must reference at least one requirement; correct entry.requirementIds and resubmit` });
798
+ }
799
+ if (entry.uiStates.length === 0 && (stateVocabulary.uiStateNames.size > 0 || stateVocabulary.interactionNames.size > 0)) {
800
+ return planToolReceipt({ ok: false, kind: "plan-verification-target",
801
+ error: `behavior verification target ${vtId} must reference at least one declared UI state; correct entry.uiStates using [${[...stateVocabulary.uiStateNames].join(", ")}] and resubmit` });
802
+ }
803
+ }
787
804
  const unknownUiStates = entry.uiStates.filter((name) => !declaredUiStateNames.has(name));
788
805
  if (unknownUiStates.length > 0) {
789
806
  return planToolReceipt({
@@ -824,7 +841,21 @@ export function buildPlanRecordTools(ctx) {
824
841
  entry,
825
842
  ...(params?.replace === true ? { replaces: vtId } : {}),
826
843
  });
827
- return planToolReceipt(result);
844
+ const latestTargets = new Map();
845
+ for (const event of readCommittedEvents(session.store, session.attemptId)) {
846
+ const fact = event.fact;
847
+ if (fact.kind === "plan-verification-target" && isRecordObject(fact.entry)
848
+ && typeof fact.entry.id === "string" && typeof fact.entry.commandId === "string") {
849
+ latestTargets.set(fact.entry.id, fact.entry.commandId);
850
+ }
851
+ }
852
+ const coveredCommands = new Set(latestTargets.values());
853
+ const remainingStaticCommandIds = verifyDirectory
854
+ .filter(command => command.mode === "static" && !coveredCommands.has(command.commandId))
855
+ .map(command => command.commandId);
856
+ const receipt = { ...result, remainingStaticCommandIds,
857
+ ...(remainingStaticCommandIds.length ? { nextAction: "Call record_plan_verification_target for each remaining static command, using a planned implementation file; behavior targets do not cover static commands." } : {}) };
858
+ return planToolReceipt(receipt);
828
859
  },
829
860
  });
830
861
  // F1: bounded executable implementation slices. The plan owns the semantic
@@ -2,6 +2,7 @@
2
2
  import path from "node:path";
3
3
  import { observeFrontendSession } from "../../../workflows/dag/frontend-session-budget.js";
4
4
  import { createFrontendScoutEvidenceTools } from "../tools/scout-evidence-tools.js";
5
+ import { readCompleteScoutTargetSurface } from "../../../workflows/dag/frontend-committed-facts.js";
5
6
  export function aggregateParallelPiResults(results) {
6
7
  const first = results[0];
7
8
  const failed = results.find((result) => !result.ok);
@@ -47,7 +48,8 @@ export async function runFrontendScoutParallelSessions(input) {
47
48
  instruction: [
48
49
  "PARALLEL SCOUT SHARD — target surface only.",
49
50
  "Inspect routes, entrypoints, implementation ownership, data source, and existing test entrypoints. Inspect project source/config first; do not recursively explore dependency internals merely to reconfirm standard test-runner behavior. If a concrete required capability cannot be established from project evidence, report the precise gap.",
50
- "Call record_target_surface exactly once with the complete runtime-evidenced surface. Do not call record_design_evidence.",
51
+ "For requested history, trends or aggregates, inspect whether existing storage/API contains the necessary samples. Compare this evidence with forbidden paths and read-only constraints. Report an infeasible required capability as a precise blocked gap; never invent historical samples or silently relax acceptance criteria.",
52
+ "Commit one accepted record_target_surface with the complete runtime-evidenced surface. If rejected, correct the reported errors and resubmit before ending. entrypoint is a single repository-relative path; route/mount relationships belong in routeOrMount. Do not call record_design_evidence.",
51
53
  ].join(" "),
52
54
  },
53
55
  {
@@ -63,8 +65,10 @@ export async function runFrontendScoutParallelSessions(input) {
63
65
  const outcomes = await Promise.all(shards.map(async (shard) => {
64
66
  const cacheKey = JSON.stringify([input.runDir, input.nodeId, shard.id, input.sessionOptions.modelConfig, input.observation?.model, input.observation?.sourceDigest, input.sourceDeclaredPaths]);
65
67
  const cached = input.completedShards?.get(cacheKey);
66
- if (cached)
68
+ if (cached && (shard.id !== "surface" || readCompleteScoutTargetSurface(cached.facts).ok))
67
69
  return { shard, facts: cached.facts, result: { ...cached.result, durationMs: 0, tokensUsed: 0, parsedEvents: 0, attemptedModels: [], fallbackUsed: false } };
70
+ if (cached)
71
+ input.completedShards?.delete(cacheKey);
68
72
  let shardTools;
69
73
  let shardResult;
70
74
  try {
@@ -108,6 +112,11 @@ export async function runFrontendScoutParallelSessions(input) {
108
112
  }));
109
113
  await shardTools.flush();
110
114
  const facts = shardTools.committedFacts();
115
+ if (shard.id === "surface" && shardResult.ok) {
116
+ const check = readCompleteScoutTargetSurface(facts);
117
+ if (!check.ok)
118
+ shardResult = { ...shardResult, ok: false, failureCategory: "invalid-output", stderr: [shardResult.stderr, check.reason].filter(Boolean).join("\n") };
119
+ }
111
120
  const expectedKind = shard.id === "design" ? "design-evidence" : "target-surface";
112
121
  if (shardResult.ok && facts.some(record => { const fact = record.fact; return fact.kind === expectedKind && (shard.id !== "surface" || fact.completeness === "complete"); })) {
113
122
  input.completedShards?.set(cacheKey, { result: structuredClone(shardResult), facts: structuredClone(facts) });
@@ -3,7 +3,7 @@ import { classifyFrontendPlanRecovery } from "../../../workflows/dag/frontend-pl
3
3
  import { collectFrontendExecutionGroups } from "../../../workflows/dag/frontend-execution-groups.js";
4
4
  import { FRONTEND_SCOPE_TARGET_BYTES, packFrontendInputUnits, parseFrontendInputBlock, projectFrontendContractPrompt, projectFrontendInputScope } from "../../../workflows/dag/frontend-input-projection.js";
5
5
  import { observeFrontendFinalization, observeFrontendSession } from "../../../workflows/dag/frontend-session-budget.js";
6
- import { collectFrontendPlanMissingFacts, collectFrontendPlanPhaseMissingFacts, committedFactFromPlanRecord, planFactStringList } from "../plan/facts.js";
6
+ import { collectFrontendPlanMissingFacts, collectFrontendPlanPhaseMissingFacts, hasCompleteFrontendPlanGlobalPolicy, committedFactFromPlanRecord, planFactStringList } from "../plan/facts.js";
7
7
  import { OUTPUT_LIMIT_RETRY_CATEGORY } from "../../../workflows/dag/retry-policy.js";
8
8
  import { FRONTEND_PLAN_BATCH_MAX_SESSIONS, FRONTEND_PLAN_COVERAGE_MAX_RECORD_CALLS, FRONTEND_PLAN_SEGMENTS, buildFrontendPlanWorkload, collectFrontendVerificationCommandFiles } from "./plan-batches.js";
9
9
  import { compactFrontendPlanLedgerContext, compactFrontendPlanPromptForRequirementSlice } from "./plan-prompts.js";
@@ -249,6 +249,84 @@ export async function runFrontendContractSegmentedSessions(input) {
249
249
  input.tools.setActiveRequirementScope(null);
250
250
  }
251
251
  }
252
+ /** A provider may stop normally after receiving a rejected typed-tool receipt.
253
+ * Track that rejection separately from prose/stderr. Only a successful retry
254
+ * of the same fact identity resolves it; unrelated writes cannot hide it. */
255
+ function trackPlanToolFailures(tools) {
256
+ const failures = new Map();
257
+ const callKeys = new Map();
258
+ // Unexecuted truncated arguments cannot reliably identify a fact. A full
259
+ // successful call of that tool clears only this SDK transport condition.
260
+ const truncatedCalls = new Set();
261
+ const executedCalls = new Set();
262
+ const object = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
263
+ const factKey = (name, rawParams) => {
264
+ const params = object(rawParams);
265
+ // A successful bounded read resolves prior pagination/revision guidance,
266
+ // including narrowing an unscoped query to an eventId and field.
267
+ if (name === "read_plan_facts")
268
+ return "read_plan_facts:query";
269
+ const entry = object(params?.entry) ?? object(params?.choice);
270
+ const endpoint = object(params?.endpoint);
271
+ const names = (value) => Array.isArray(value) ? value.map(item => object(item)?.name).filter(item => typeof item === "string").sort() : [];
272
+ const identity = params?.id ?? params?.scopeId ?? entry?.id ?? entry?.purpose ?? entry?.requirementId ?? params?.eventId ?? params?.requirementId ??
273
+ (endpoint ? JSON.stringify([endpoint.method, endpoint.path]) : undefined) ??
274
+ (name === "record_design_input_binding" ? JSON.stringify([entry?.sourcePath, entry?.targetPath]) : undefined) ??
275
+ (name === "record_state_flow" ? JSON.stringify([names(params?.uiStates), names(params?.interactions), planFactStringList(params?.removeUiStateNames).sort(), planFactStringList(params?.removeInteractionNames).sort()]) : undefined);
276
+ const singleton = ["record_dependency", "record_route_selection", "record_state_registry", "record_mock_api", "record_data_flow", "record_design_deviation"].includes(String(name));
277
+ return `${String(name)}:${String(identity ?? (singleton ? "singleton" : JSON.stringify(params)))}`;
278
+ };
279
+ const observeReceipt = (key, result, isError = false, toolName) => {
280
+ const receipt = object(result);
281
+ const details = object(receipt?.details);
282
+ if (isError || receipt?.isError === true || details?.ok === false)
283
+ failures.set(key, String(details?.code ?? details?.error ?? "tool rejected"));
284
+ else if (details?.ok === true) {
285
+ failures.delete(key);
286
+ if (toolName)
287
+ truncatedCalls.delete(toolName);
288
+ }
289
+ };
290
+ const customTools = tools.map(value => {
291
+ const tool = object(value);
292
+ if (!tool || typeof tool.execute !== "function")
293
+ return value;
294
+ const execute = tool.execute;
295
+ return { ...tool, execute: async (...args) => {
296
+ const key = factKey(tool.name, args[1]);
297
+ executedCalls.add(String(args[0]));
298
+ try {
299
+ const result = await execute.apply(tool, args);
300
+ observeReceipt(key, result, false, String(tool.name));
301
+ return result;
302
+ }
303
+ catch (error) {
304
+ failures.set(key, error instanceof Error ? error.message : String(error));
305
+ throw error;
306
+ }
307
+ } };
308
+ });
309
+ // SDK argument validation can reject a call before execute is reached.
310
+ const onSessionEvent = (_line, value) => {
311
+ const event = object(value);
312
+ if (!event || typeof event.toolCallId !== "string")
313
+ return;
314
+ if (event.type === "tool_execution_start")
315
+ callKeys.set(event.toolCallId, factKey(event.toolName, event.args));
316
+ if (event.type === "tool_execution_end") {
317
+ const key = callKeys.get(event.toolCallId) ?? factKey(event.toolName, undefined);
318
+ const content = object(event.result)?.content;
319
+ const truncated = !executedCalls.has(event.toolCallId) && event.isError === true && Array.isArray(content) &&
320
+ content.some(item => object(item)?.text === `Tool call "${String(event.toolName)}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`);
321
+ if (truncated)
322
+ truncatedCalls.add(String(event.toolName));
323
+ else
324
+ observeReceipt(key, event.result, event.isError === true, String(event.toolName));
325
+ callKeys.delete(event.toolCallId);
326
+ }
327
+ };
328
+ return { customTools, failures, onSessionEvent, truncatedCalls };
329
+ }
252
330
  export async function runFrontendPlanSegmentedSessions(input) {
253
331
  const queue = [];
254
332
  const coverageSegment = FRONTEND_PLAN_SEGMENTS.find((segment) => segment.id === "coverage");
@@ -261,12 +339,12 @@ export async function runFrontendPlanSegmentedSessions(input) {
261
339
  ? compactFrontendPlanPromptForRequirementSlice(input.basePrompt, scopeIds, {
262
340
  includeRequirementText: segment.id === "global-mock-data" || segment.id === "finalize",
263
341
  includeVerificationTargets: false,
264
- includeDesignEvidence: segment.id === "global-dependency-deviation" || segment.id === "finalize",
342
+ includeDesignEvidence: segment.id === "global-route" || segment.id === "global-dependency-deviation" || segment.id === "finalize",
265
343
  includeChecklist: false,
266
344
  })
267
345
  : input.basePrompt;
268
346
  const kinds = segment.id === "global-route"
269
- ? ["target-surface"]
347
+ ? ["target-surface", "dependency", "design-deviation"]
270
348
  : segment.id === "global-mock-data"
271
349
  ? ["plan-requirement", "plan-verification-target", "state-flow", "data-flow", "mock-api"]
272
350
  : segment.id === "global-dependency-deviation"
@@ -384,6 +462,7 @@ export async function runFrontendPlanSegmentedSessions(input) {
384
462
  compactFrontendPlanPromptForRequirementSlice(input.basePrompt, allRequirementIds, { includeDesignEvidence: true }),
385
463
  "PLAN PHASE — compact local planning for a small frontend request.",
386
464
  "Review all listed requirements together and record_state_registry first with one global UX vocabulary. Then record every plan-requirement and verification-target fact, followed by component/state-flow facts and the minimal route, Mock/data, dependency, and design-deviation policy facts needed by the observable behavior. Do not read the repository or task source; use only the committed input above. Do not call finalize_plan in this session.",
465
+ "Before ending, cover EVERY frozen static command with record_plan_verification_target (entry.commandId from the directory, entry.file from planned implementation targets, uiStates: []). Behavior tests do not cover build/typecheck commands. Follow remainingStaticCommandIds in tool receipts.",
387
466
  "TOOL-FIRST: your first assistant actions must be record_* tool calls, at most 2-3 facts per message. Do not draft the whole analysis before recording; if a fact is uncertain, record it with an evidence gap instead of reasoning longer.",
388
467
  ledger,
389
468
  ...(missing.length > 0
@@ -610,6 +689,20 @@ export async function runFrontendPlanSegmentedSessions(input) {
610
689
  }
611
690
  }
612
691
  }
692
+ const compactFactsComplete = () => {
693
+ if (!requirementIdsProvided || !input.committedFacts || input.behaviorRequiredRequirementIds === undefined)
694
+ return false;
695
+ const facts = input.committedFacts();
696
+ return collectFrontendPlanMissingFacts({ requirementIds: allRequirementIds, committedFacts: facts }).length === 0 &&
697
+ ["ux-registry", "ux-local", "global-mock-data"].every(phase => collectFrontendPlanPhaseMissingFacts({ phase, requirementIds: allRequirementIds,
698
+ committedFacts: facts, behaviorRequiredRequirementIds: input.behaviorRequiredRequirementIds }).length === 0) &&
699
+ hasCompleteFrontendPlanGlobalPolicy({ committedFacts: facts, dependencyPolicyRequired: dependencyDeviationNeeded });
700
+ };
701
+ const runtimeResult = {
702
+ ok: true, failureCategory: "success", exitCode: 0, stdout: "", stderr: "", assistantText: "",
703
+ command: [], durationMs: 0, modelDisplay: "runtime-finalize", parsedEvents: 0, timedOut: false,
704
+ attemptedModels: [], fallbackUsed: false, tokensUsed: 0,
705
+ };
613
706
  let accumulated;
614
707
  let index = 0;
615
708
  let invocationCount = 0;
@@ -618,6 +711,10 @@ export async function runFrontendPlanSegmentedSessions(input) {
618
711
  const session = queue[index];
619
712
  if (!session)
620
713
  break;
714
+ if (input.attempt > 1 && session.id === "compact-local" && compactFactsComplete()) {
715
+ index += 1;
716
+ continue;
717
+ }
621
718
  if (input.attempt > 1 && input.committedFacts && session.id === "ux-registry" &&
622
719
  collectFrontendPlanPhaseMissingFacts({ phase: "ux-registry", requirementIds: allRequirementIds, committedFacts: input.committedFacts() }).length === 0) {
623
720
  index += 1;
@@ -680,6 +777,16 @@ export async function runFrontendPlanSegmentedSessions(input) {
680
777
  index += 1;
681
778
  continue;
682
779
  }
780
+ if (requirementIdsProvided && input.committedFacts && (session.id === "global-policy" && hasCompleteFrontendPlanGlobalPolicy({
781
+ committedFacts: input.committedFacts(), dependencyPolicyRequired: dependencyDeviationNeeded,
782
+ }) || session.id.startsWith("global-mock-data") &&
783
+ collectFrontendPlanPhaseMissingFacts({
784
+ phase: "global-mock-data", requirementIds: session.requirementSlice ?? allRequirementIds,
785
+ committedFacts: input.committedFacts(),
786
+ }).length === 0)) {
787
+ index += 1;
788
+ continue;
789
+ }
683
790
  let prompt = session.prompt;
684
791
  if (session.coverageOnly && session.coverageSlice) {
685
792
  const promptSlice = [...new Set([...remaining, ...preexistingMissing.flatMap(item => item.requirementIds)])];
@@ -734,14 +841,18 @@ export async function runFrontendPlanSegmentedSessions(input) {
734
841
  "state-registry": "record_state_registry", "component-choice": "record_component_choice",
735
842
  "state-flow": "record_state_flow", "data-flow": "record_data_flow", "mock-api": "record_mock_api",
736
843
  };
737
- const customTools = input.segmentCustomTools(atomicFocus ? new Set([atomicTools[atomicFocus.kind]]) : session.toolNames);
844
+ const originalTools = input.segmentCustomTools(atomicFocus ? new Set([atomicTools[atomicFocus.kind]]) : session.toolNames);
845
+ const { customTools, failures: toolFailures, onSessionEvent: observeToolEvent, truncatedCalls } = trackPlanToolFailures(originalTools);
846
+ let ledgerFlushed = false;
847
+ let ledgerFlushError = "";
738
848
  const result = await observeFrontendSession({
739
849
  ...input.observation, phase: `plan/${session.id}`, dispatchReason: (session.retryCount ?? 0) > 0 || !!session.missingFacts?.length || /capacity|recovery|split/.test(session.id) ? "correction" : "initial", scopeIds: session.requirementSlice ?? session.coverageSlice ?? allRequirementIds,
740
- prompt, userMessage: input.sessionOptions.userMessage, customTools, committedCount: input.committedFactCount, durableCommittedCount: () => lastDurableCount,
850
+ prompt, userMessage: input.sessionOptions.userMessage, customTools: originalTools, committedCount: input.committedFactCount, durableCommittedCount: () => lastDurableCount,
741
851
  artifactPath: input.observation?.artifactPath ? `${input.observation.artifactPath}-${invocationCount}.json` : undefined,
742
852
  }, async (observer) => {
743
853
  const result = await input.piStepFn({
744
854
  ...input.sessionOptions,
855
+ onSessionEvent: (line, event) => { observeToolEvent(line, event); input.sessionOptions.onSessionEvent?.(line, event); },
745
856
  onAttemptObservation: observer,
746
857
  prompt,
747
858
  ...(customTools.length > 0
@@ -756,9 +867,12 @@ export async function runFrontendPlanSegmentedSessions(input) {
756
867
  try {
757
868
  await input.flushLedger();
758
869
  lastDurableCount = input.committedFactCount();
870
+ ledgerFlushed = true;
759
871
  }
760
- catch {
761
- // best-effort: the node-level flush runs again after the attempt
872
+ catch (error) {
873
+ ledgerFlushError = error instanceof Error ? error.message : String(error);
874
+ // The node-level flush can retry persistence, but this session must
875
+ // never claim durable progress or advance to finalization.
762
876
  }
763
877
  return result;
764
878
  });
@@ -766,10 +880,20 @@ export async function runFrontendPlanSegmentedSessions(input) {
766
880
  ? combineSequentialPiResults(accumulated, result)
767
881
  : result;
768
882
  const committedAfter = input.committedFactCount();
769
- const committedFactsOnlySuccess = !(result.assistantText ?? "").trim() &&
770
- !result.stderr.trim() &&
771
- !result.timedOut &&
772
- committedAfter > committedBefore;
883
+ if (classifyFrontendPlanRecovery({ ...result, stopReason: readWriterThinkingExhaustionEvidence(result).stopReason }) === "stop")
884
+ return { ...accumulated, ok: false };
885
+ if (!ledgerFlushed)
886
+ return { ...accumulated, ok: false, failureCategory: "invalid-output",
887
+ stderr: `${accumulated.stderr}\nPLAN_LEDGER_FLUSH_FAILED: ${ledgerFlushError}`.trim() };
888
+ if (truncatedCalls.size > 0 && readWriterThinkingExhaustionEvidence(result).stopReason !== "length" && result.failureCategory !== "output-limit") {
889
+ return { ...accumulated, ok: false, failureCategory: "invalid-output", stderr: `${accumulated.stderr}\nPLAN_TOOL_ERROR: truncated tool calls remain unexecuted`.trim() };
890
+ }
891
+ if (toolFailures.size > 0)
892
+ return { ...accumulated, ok: false, failureCategory: "invalid-output",
893
+ stderr: `${accumulated.stderr}\nPLAN_TOOL_ERROR: ${[...toolFailures.values()].join("; ")}`.trim() };
894
+ const normalEmptyTurn = result.failureCategory === "empty-output" &&
895
+ readWriterThinkingExhaustionEvidence(result).stopReason === "stop" &&
896
+ !(result.assistantText ?? "").trim() && !result.stderr.trim() && !result.timedOut;
773
897
  const missingCoverage = session.coverageOnly && session.coverageSlice && input.committedFacts
774
898
  ? collectFrontendPlanMissingFacts({
775
899
  requirementIds: session.coverageSlice,
@@ -818,6 +942,10 @@ export async function runFrontendPlanSegmentedSessions(input) {
818
942
  })
819
943
  : [];
820
944
  const missingPhaseFacts = [...missingCoverage, ...missingPhase];
945
+ const phaseCompletenessKnown = requirementIdsProvided && Boolean(input.committedFacts) && (Boolean(session.coverageOnly && session.coverageSlice?.length) || isCompactLocalSession && compactFactsComplete() ||
946
+ isUxRegistrySession || isUxLocalSession && input.behaviorRequiredRequirementIds !== undefined ||
947
+ session.id.startsWith("global-mock-data") || session.id === "global-policy" &&
948
+ hasCompleteFrontendPlanGlobalPolicy({ committedFacts: input.committedFacts(), dependencyPolicyRequired: dependencyDeviationNeeded }));
821
949
  // Frozen verification commands must operate on files the planner has
822
950
  // committed verification targets for; otherwise the admission writeSet
823
951
  // cannot authorize the file and verify-shell deterministically fails.
@@ -840,6 +968,7 @@ export async function runFrontendPlanSegmentedSessions(input) {
840
968
  });
841
969
  }
842
970
  }
971
+ const committedFactsOnlySuccess = normalEmptyTurn && (committedAfter > committedBefore || phaseCompletenessKnown && missingPhaseFacts.length === 0);
843
972
  const promptForMissingPhase = (missing) => session.coverageOnly
844
973
  ? buildCoveragePrompt(session.coverageSlice ?? [], missing)
845
974
  : isCompactLocalSession
@@ -960,7 +1089,8 @@ export async function runFrontendPlanSegmentedSessions(input) {
960
1089
  };
961
1090
  }
962
1091
  if (committedFactsOnlySuccess) {
963
- // The session died but banked facts: keep the progress and move on.
1092
+ // Tool-only completion needs no new narrative or duplicate writes.
1093
+ // Durable facts and the final compiler remain the authority.
964
1094
  if (missingPhaseFacts.length > 0 && (session.retryCount ?? 0) < 2) {
965
1095
  queue[index] = {
966
1096
  ...session,
@@ -978,6 +1108,7 @@ export async function runFrontendPlanSegmentedSessions(input) {
978
1108
  failureCategory: "invalid-output",
979
1109
  };
980
1110
  }
1111
+ accumulated = { ...accumulated, ok: true, failureCategory: "success", exitCode: 0 };
981
1112
  index += 1;
982
1113
  continue;
983
1114
  }
@@ -1080,6 +1211,14 @@ export async function runFrontendPlanSegmentedSessions(input) {
1080
1211
  };
1081
1212
  }
1082
1213
  if (!input.parallelCoverageOnly && input.finalizePlan) {
1214
+ try {
1215
+ await input.flushLedger();
1216
+ lastDurableCount = input.committedFactCount();
1217
+ }
1218
+ catch (error) {
1219
+ return { ...(accumulated ?? runtimeResult), ok: false, failureCategory: "invalid-output",
1220
+ stderr: `${accumulated?.stderr ?? ""}\nPLAN_LEDGER_FLUSH_FAILED: ${error instanceof Error ? error.message : String(error)}`.trim() };
1221
+ }
1083
1222
  // Preserve optional closeout context if an earlier correction or future
1084
1223
  // ledger producer committed it. The old model-only finalize session was
1085
1224
  // the only writer of these fields; runtime-owned finalization must not
@@ -1122,17 +1261,20 @@ export async function runFrontendPlanSegmentedSessions(input) {
1122
1261
  input.committedFacts ? compactFrontendPlanLedgerContext({ committedFacts: input.committedFacts(), requirementIds: input.requirementIds ?? [], kinds: ["plan-requirement", "plan-verification-target", "implementation-slice", "state-registry", "component-choice", "state-flow", "data-flow", "mock-api", "design-deviation", "dependency", "target-surface"] }) : "",
1123
1262
  ].filter(Boolean).join("\n\n");
1124
1263
  input.setActiveRequirementScope?.([]);
1125
- const correctionTools = input.segmentCustomTools(null);
1264
+ const originalCorrectionTools = input.segmentCustomTools(null);
1265
+ const { customTools: correctionTools, failures: correctionToolFailures, onSessionEvent: observeCorrectionToolEvent, truncatedCalls: correctionTruncatedCalls } = trackPlanToolFailures(originalCorrectionTools);
1126
1266
  const committedCountBeforeCorrection = input.committedFactCount();
1127
1267
  let correctionFlushed = false;
1268
+ let correctionFlushError = "";
1128
1269
  const correction = await observeFrontendSession({
1129
1270
  ...input.observation, phase: "plan/finalize-correction", dispatchReason: "correction",
1130
1271
  scopeIds: input.requirementIds, prompt: correctionPrompt, userMessage: input.sessionOptions.userMessage,
1131
- customTools: correctionTools, committedCount: input.committedFactCount, durableCommittedCount: () => lastDurableCount,
1272
+ customTools: originalCorrectionTools, committedCount: input.committedFactCount, durableCommittedCount: () => lastDurableCount,
1132
1273
  artifactPath: input.observation?.artifactPath ? `${input.observation.artifactPath}-finalize-correction.json` : undefined,
1133
1274
  }, async (observer) => {
1134
1275
  const result = await input.piStepFn({
1135
1276
  ...input.sessionOptions, onAttemptObservation: observer, prompt: correctionPrompt,
1277
+ onSessionEvent: (line, event) => { observeCorrectionToolEvent(line, event); input.sessionOptions.onSessionEvent?.(line, event); },
1136
1278
  writerToolPolicy: { requireSdk: true, customTools: correctionTools },
1137
1279
  });
1138
1280
  try {
@@ -1140,17 +1282,25 @@ export async function runFrontendPlanSegmentedSessions(input) {
1140
1282
  lastDurableCount = input.committedFactCount();
1141
1283
  correctionFlushed = true;
1142
1284
  }
1143
- catch { /* node-level flush retries below */ }
1285
+ catch (error) {
1286
+ correctionFlushError = error instanceof Error ? error.message : String(error);
1287
+ }
1144
1288
  return result;
1145
1289
  });
1146
1290
  accumulated = accumulated
1147
1291
  ? combineSequentialPiResults(accumulated, correction)
1148
1292
  : correction;
1293
+ const correctionStopReason = readWriterThinkingExhaustionEvidence(correction).stopReason;
1294
+ if (classifyFrontendPlanRecovery({ ...correction, stopReason: correctionStopReason }) === "stop")
1295
+ return { ...accumulated, ok: false };
1296
+ if (!correctionFlushed || correctionToolFailures.size > 0 || correctionTruncatedCalls.size > 0)
1297
+ return { ...accumulated, ok: false, failureCategory: "invalid-output",
1298
+ stderr: `${accumulated.stderr}\n${!correctionFlushed ? `PLAN_LEDGER_FLUSH_FAILED: ${correctionFlushError}` : `PLAN_TOOL_ERROR: ${[...correctionToolFailures.values()].join("; ")}`}`.trim() };
1149
1299
  if (!correction.ok && !["invalid-output", "empty-output", "success"].includes(correction.failureCategory))
1150
1300
  return { ...accumulated, ok: false, failureCategory: correction.failureCategory };
1151
1301
  const durableEmptyCorrection = !correction.ok && correction.failureCategory === "empty-output"
1152
1302
  && !correction.timedOut && !correction.assistantText.trim() && !correction.stderr.trim()
1153
- && !["length", "aborted"].includes(readWriterThinkingExhaustionEvidence(correction).stopReason ?? "")
1303
+ && correctionStopReason === "stop"
1154
1304
  && correctionFlushed && lastDurableCount > committedCountBeforeCorrection;
1155
1305
  if (correction.ok || durableEmptyCorrection) {
1156
1306
  finalizeResult = await finalize();
@@ -1189,6 +1339,10 @@ export async function runFrontendPlanSegmentedSessions(input) {
1189
1339
  failureCategory: "invalid-output",
1190
1340
  };
1191
1341
  }
1342
+ return {
1343
+ ...(accumulated ?? runtimeResult),
1344
+ ok: true, failureCategory: "success", exitCode: 0,
1345
+ };
1192
1346
  }
1193
1347
  return mapPlannerExhaustion(accumulated ?? {
1194
1348
  ok: false,