@tea-agent/loop-agent 0.39.0-beta.10 → 0.39.0-beta.11

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 (95) hide show
  1. package/CHANGELOG.md +99 -0
  2. package/dist/build-stamp.json +3 -3
  3. package/dist/executors/dag-pi-executor.js +93 -32
  4. package/dist/executors/pi-executor.js +4 -2
  5. package/dist/executors/pi-sdk-executor.js +46 -1
  6. package/dist/executors/pi-writer-tool-policy.js +57 -1
  7. package/dist/executors/shell-executor.js +10 -1
  8. package/dist/worker/console/chat/chat-event-store.js +13 -1
  9. package/dist/worker/console/chat/pi-runtime.js +70 -5
  10. package/dist/worker/console/chat/routes.js +99 -29
  11. package/dist/worker/console/chat/workspace-landing.js +65 -0
  12. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-BAsjg7ew.js → abnfDiagram-N423BO3Z-CXj_GnSb.js} +1 -1
  13. package/dist/worker/console/static/assets/{arc-CyIlrwZw.js → arc-BZp6JAp7.js} +1 -1
  14. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-Bo4tobhH.js → architectureDiagram-T3A2C74G-DfpcEuYU.js} +1 -1
  15. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-Dfpow9gu.js → blockDiagram-VBNYF7ZC-_Gf0xadb.js} +1 -1
  16. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-DPmzG_B4.js → c4Diagram-5PPSVZJV-Ct2QPCmv.js} +1 -1
  17. package/dist/worker/console/static/assets/channel-3TxJgYaH.js +1 -0
  18. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-pKQpB1UW.js → chunk-2GRJ4B5K-BfklkzKl.js} +1 -1
  19. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-5n9YYquZ.js → chunk-2Q5K7J3B-Dy25vZJV.js} +1 -1
  20. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-DP3CtA2a.js → chunk-5RXB4S5H-BFlCRZep.js} +1 -1
  21. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-DYxMJPUy.js → chunk-5VM5RSS4-op3oVxIE.js} +1 -1
  22. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-CS3D50Io.js → chunk-6Q2QTUOP-C0R7rzF2.js} +1 -1
  23. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-gSdDfo5_.js → chunk-GF5L2VYU-Bt44TCGy.js} +1 -1
  24. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-A48q0ZNt.js → chunk-JWPE2WC7-_uEE_XFx.js} +1 -1
  25. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-ow8Mm3DY.js → chunk-KBJHAD2P-C3TOYGZ9.js} +1 -1
  26. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-CMKfLWYE.js → chunk-RYQCIY6F-Cz60oBPV.js} +1 -1
  27. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-BiTBdQPX.js → chunk-XXDRQBXY-8Bik0qis.js} +1 -1
  28. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-BHIkXpp3.js +1 -0
  29. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-BHIkXpp3.js +1 -0
  30. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-Cm7exRz_.js → cose-bilkent-JH36ORCC-C2QIOA4a.js} +1 -1
  31. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-D9O5qGOu.js → cynefin-VYW2F7L2-CSH_yUUd.js} +1 -1
  32. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-CkvQnako.js → cynefinDiagram-MW4NZA55-BDLw2XFM.js} +1 -1
  33. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-B1rzp7CB.js → dagre-VZM6K2ZE-CcD9ZtF4.js} +1 -1
  34. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-BP07Ipcc.js → diagram-7IWD3JNH-DqwtkBsI.js} +1 -1
  35. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-BlPzweQb.js → diagram-B4RE2ZJO-BWVEcqsC.js} +1 -1
  36. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-CxPa7n0S.js → diagram-LBJQPF4R-M-WAbtQi.js} +1 -1
  37. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-CMTZs53A.js → diagram-Q27KOJAE-DKW7SixP.js} +1 -1
  38. package/dist/worker/console/static/assets/{diagram-UB23O5K3-CxG_X52r.js → diagram-UB23O5K3-PHHPPtrj.js} +1 -1
  39. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-D8axtJM0.js → ebnfDiagram-BXEA7PRR-BQD-B4RX.js} +1 -1
  40. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-DIsGzn7b.js → erDiagram-JOGREHBK-BFvULb51.js} +1 -1
  41. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-CU9zkDG0.js → flowDiagram-UKHOOZJN-Bw-aXTCb.js} +1 -1
  42. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-DCjTmz5P.js → ganttDiagram-PKOTCBZU-BGKw04Qx.js} +1 -1
  43. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-BksdmFzg.js → gitGraphDiagram-DS77QQ5N-RqKaPR-I.js} +1 -1
  44. package/dist/worker/console/static/assets/index-B_D8rbWc.js +407 -0
  45. package/dist/worker/console/static/assets/index-BdNx6fj0.css +1 -0
  46. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-CGzzzJtL.js → infoDiagram-6WML65LV-YO5dnzrJ.js} +1 -1
  47. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-BdseB80N.js → ishikawaDiagram-WSZJBQD7-Bi1VZHMq.js} +1 -1
  48. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-DM9gsgha.js → journeyDiagram-NVQOT4AX-Bszls1DD.js} +1 -1
  49. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-3q-_9R2b.js → kanban-definition-27J2QSJJ-PhzeaZ09.js} +1 -1
  50. package/dist/worker/console/static/assets/{linear-B8N-Mxsd.js → linear-BsjbDoXi.js} +1 -1
  51. package/dist/worker/console/static/assets/{mermaid.core-EPIHUUsu.js → mermaid.core-0B7NnWKk.js} +5 -5
  52. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-CxwO12aa.js → mindmap-definition-FAOFIHXS-BJr4Fj-q.js} +1 -1
  53. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-bPqbVX6Y.js → pegDiagram-VL7TDLO6-moC4fpGB.js} +1 -1
  54. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-KzqIvzeX.js → pieDiagram-7S7Q4E2Y-BEw37-2c.js} +1 -1
  55. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-CyofpWiV.js → quadrantDiagram-CIZ2JOQS-Cq6LyasU.js} +1 -1
  56. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-cTWJvLTP.js → railroadDiagram-AXF67PYL-DUCMcK0D.js} +1 -1
  57. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-BK--q27B.js → requirementDiagram-LRYGKXZP-C3upTZm7.js} +1 -1
  58. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-C0SDOHXK.js → sankeyDiagram-W5VNT64P-BI_gMsCW.js} +1 -1
  59. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-Cong6YIo.js → sequenceDiagram-SI44F4Z6-YFOIRzfN.js} +1 -1
  60. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-DUVkgZx8.js → sizeCapture-X5ZJPWSS-dOnB7UDD.js} +1 -1
  61. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-C7XgxuZg.js → stateDiagram-OKZ733FA-BXUniaIh.js} +1 -1
  62. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Cdi6UhLa.js +1 -0
  63. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-D9Ayvwcy.js → swimlanes-SLNWSIFB-2tA4wTNu.js} +2 -2
  64. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-D-RJBbb0.js +8 -0
  65. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-Byb000cH.js → timeline-definition-Z64GVDOM-DO0HkJXC.js} +1 -1
  66. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-DMLegPt4.js → vennDiagram-T6HMQDX7-DvIOzixv.js} +1 -1
  67. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-ChMMeOsP.js → wardleyDiagram-T6FBY63Y-DXDZ0cTj.js} +1 -1
  68. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-bEMEPisW.js → xychartDiagram-ELKLHX3M-B32Ark0D.js} +1 -1
  69. package/dist/worker/console/static/index.html +2 -2
  70. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +33 -32
  71. package/dist/worker/console/static-src/operator-chat/compaction-message.js +79 -0
  72. package/dist/worker/console/static-src/operator-chat/spatial-overlay.js +1 -2
  73. package/dist/worker/console/static-src/operator-chat/turn-stream-controller.js +25 -0
  74. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +54 -56
  75. package/dist/worker/console/static-src/operator-chat/useChatStream.js +81 -27
  76. package/dist/worker/console/static-src/operator-chat/useChatThread.js +14 -25
  77. package/dist/worker/console/static-src/shell/workspace-route.js +7 -5
  78. package/dist/workflows/dag/backend-test-writer-completeness.js +7 -12
  79. package/dist/workflows/dag/dynamic-runtime/map.js +1 -0
  80. package/dist/workflows/dag/init-hybrid.js +96 -55
  81. package/dist/workflows/dag/node-execution.js +84 -0
  82. package/dist/workflows/dag/types.js +17 -0
  83. package/docs/templates/agent-dag.schema.json +18 -0
  84. package/docs/templates/backend-test-dag.json +265 -237
  85. package/harness.json +3 -3
  86. package/package.json +1 -1
  87. package/dist/worker/console/static/assets/channel-DSrJAn0-.js +0 -1
  88. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DeMmPl0_.js +0 -1
  89. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DeMmPl0_.js +0 -1
  90. package/dist/worker/console/static/assets/index-B-O5ChYq.css +0 -1
  91. package/dist/worker/console/static/assets/index-CfnY8AQx.js +0 -407
  92. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Dzbnd5oX.js +0 -1
  93. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-BY0hHk6G.js +0 -8
  94. package/dist/worker/console/static-src/operator-chat/activity-rail-presentation.js +0 -73
  95. package/dist/worker/console/static-src/operator-chat/useActivityRailTransition.js +0 -59
@@ -2565,7 +2565,7 @@ const frontendComponentConformanceInstruction = [
2565
2565
  "每个 UI 用途必须在契约的 uiComponentChoices[] 中声明组件选型:{ purpose, component, decision, specReference, rationale }。",
2566
2566
  "- decision=specified:前端规范(候选组件/主题桶 + 任务源显式引用)已定义该用途组件 → 必须使用该组件,并给精确 specReference { path, section, line }(path 必须是 openspec/ai_workspace 受支持规范路径)。",
2567
2567
  "- decision=reuse-existing:仅当该组件/惯例**确实已存在于仓库当前代码**(如复用现有 ActiveRunBadge 的 oc- class 惯例)→ specReference 可为 null,rationale 必须指明复用的具体现有组件/文件与依据。",
2568
- "- decision=new:任务源/PRD 要求**新增**该组件(仓库当前不存在该组件文件)→ decision 必须为 new,不得标 reuse-existing;specReference 指向任务源 PRD 中定义该组件的 { path, section, line }(path 为 bound PRD 路径,如 .harness/tasks/<taskId>/source/references/prd.md),rationale 说明新增纯展示组件、复用既有 CSS 命名与主题变量约定;design-review 会复核 specReference 可追溯性。",
2568
+ "- decision=new:任务源/PRD 要求**新增**该组件(仓库当前不存在该组件文件)→ decision 必须为 new,不得标 reuse-existing;调用 record_component_choice 时传 sourceRequirementIds(关联的 frozen requirement ID),runtime 会从 source-fidelity ledger 物化精确的任务源 PRD { path, section, line }。不要读取 PRD 或手填/猜测 specReference;rationale 说明新增纯展示组件、复用既有 CSS 命名与主题变量约定。",
2569
2569
  "不得静默替换规范组件或自创组件而无偏差声明;spec 已定义该用途组件时不得改选其它组件。",
2570
2570
  "prewrite gate 确定性交叉校验:仅 decision=specified 的 specReference 必须是候选 OpenSpec 路径、在 typed decision ledger 中声明且有成功 read 事件;decision=new 的 PRD 引用走任务源可追溯性审查,不得按 OpenSpec 候选拒绝。候选桶非空且契约有 UI 可见工作而 uiComponentChoices 缺失/空 → component-choices-missing。",
2571
2571
  ].join("\n");
@@ -3159,12 +3159,6 @@ async function buildFrontendHybridDagFromTask(sources) {
3159
3159
  complexity: "MED",
3160
3160
  writePolicy: "read-only",
3161
3161
  retryPolicy: FRONTEND_PLAN_LADDER_RETRY_POLICY,
3162
- readBudget: {
3163
- maxFiles: 40,
3164
- maxBytes: 512 * 1024,
3165
- maxOperations: 40,
3166
- onExhaustion: "return-guidance",
3167
- },
3168
3162
  allowedPaths: readOnlyPaths,
3169
3163
  forbiddenPaths,
3170
3164
  skills: FRONTEND_IMPLEMENTATION_SKILLS,
@@ -3181,7 +3175,7 @@ async function buildFrontendHybridDagFromTask(sources) {
3181
3175
  `Cover each frozen requirement ID exactly once: ${requirementIds.join(", ") || "(none)"}. Bind every verification target to a listed frozen command and a Scout-confirmed file. Use static targets for project-wide commands.`,
3182
3176
  ...(requiresOpenspecClassification ? ["When a component choice uses an OpenSpec selection, cite that selection; otherwise do not classify unrelated candidates."] : []),
3183
3177
  "Call finalize_plan exactly once after the necessary typed facts. Return no Markdown narrative.",
3184
- "READ BUDGET: use injected Contract/Scout facts. Do not search or re-read task sources. If an upstream preview is truncated, you may read only its explicitly listed artifact path. You may also read one or more Scout-confirmed target paths when a specific component/state/test decision needs direct evidence. grep/find/ls are unavailable; a non-Scout repository path is denied. After the read cap, stop and finalize from existing facts or record a genuine evidence gap.",
3178
+ "TOOL-ONLY PLAN: Do not read Contract/Scout stdout, task sources, or Scout-confirmed target files. Contract and Scout already own evidence discovery; use the injected upstream facts, record a genuine evidence gap when those facts are insufficient, and start committing record_* facts immediately. For decision=new, pass sourceRequirementIds to record_component_choice; runtime derives the exact PRD citation from the frozen ledger.",
3185
3179
  fixedVerificationContext,
3186
3180
  scopedOpenspecContext,
3187
3181
  mockContextBlock,
@@ -4087,9 +4081,10 @@ export function applyBackendTestLayoutToText(text, layout) {
4087
4081
  /**
4088
4082
  * Builds the `node -e` command for the backend-test module manifest shell.
4089
4083
  * The inline JS mirrors `extractModuleStemsFromReadme` so the map_agent
4090
- * shard set deterministically matches the README index the Completeness
4091
- * Gate trusts: only table-row `testcase/md/<stem>.md` mentions and canonical
4092
- * relative links `[label](./<stem>.md)` count, with the same
4084
+ * shard set deterministically matches the plan index the Completeness
4085
+ * Gate trusts: only `testcase/md/<stem>.md` path mentions and canonical
4086
+ * relative links `[label](./<stem>.md)` count. Adjacent table cells such as
4087
+ * Case Range or pytest assets are never interpreted as module stems. The same
4093
4088
  * `looksLikeValidModuleStem` filter and `normalizeBackendTestModuleStem`
4094
4089
  * normalization. Output is exactly one trailing JSON line `{modules:[{stem}]}`
4095
4090
  * that `parseJsonFromText` accepts after shell command echoes.
@@ -4103,17 +4098,18 @@ function buildBackendTestModuleManifestShellCommand(layout) {
4103
4098
  // mdDir/testPrefix are injected as JSON literals so the same extractor
4104
4099
  // works for any configured backendTest layout (plan A).
4105
4100
  const mdDirLiteral = JSON.stringify(layout.markdownDir);
4106
- const testPrefixLiteral = JSON.stringify(`${layout.scriptDir}/test_`);
4107
4101
  const escOpen = String.fromCharCode(92, 91); // \[
4108
4102
  const escClose = String.fromCharCode(92, 93); // \]
4109
4103
  const escBslash = String.fromCharCode(92, 92); // \\
4110
- const script = `const fs=require('fs');
4104
+ const script = `const fs=require('fs'),path=require('path'),crypto=require('crypto');
4111
4105
  const mdDir=${mdDirLiteral};
4112
- const testPrefix=${testPrefixLiteral};
4113
4106
  const esc=s=>s.replace(/[${escOpen}${escClose}{}()*+?^$|${escBslash}]/g,'${escBslash}$&');
4114
4107
  const rxMdPath=new RegExp(esc(mdDir)+'${escBslash}/([A-Za-z0-9_.-]+)${escBslash}.md','g');
4115
- const rxTableRow=new RegExp('${escBslash}|${escBslash}s*([A-Za-z0-9_.-]+)${escBslash}s*${escBslash}|${escBslash}s*'+esc(testPrefix),'g');
4116
- const readme=fs.existsSync(mdDir+'/README.md')?fs.readFileSync(mdDir+'/README.md','utf8'):'';
4108
+ const runDir=process.env.HARNESS_DAG_RUN_DIR||'';
4109
+ if(!runDir){process.stderr.write('missing HARNESS_DAG_RUN_DIR for backend-test Markdown plan artifact\\n');process.exit(2);}
4110
+ const planPath=path.join(runDir,'generate-backend-md-plan-pi','plan.md');
4111
+ if(!fs.existsSync(planPath)){process.stderr.write('missing backend-test Markdown plan artifact: '+planPath+'\\n');process.exit(2);}
4112
+ const readme=fs.readFileSync(planPath,'utf8');
4117
4113
  const norm=s=>String(s).toLowerCase().replace(/[^a-z0-9]+/g,'_').replace(/^_+|_+$/g,'').replace(/_+/g,'_');
4118
4114
  const bt=String.fromCharCode(96);
4119
4115
  const stripBackticks=s=>s.split(bt).join('');
@@ -4130,15 +4126,17 @@ const lines=section.split('\\n').filter(l=>l.includes('|'));
4130
4126
  for(const line of lines){
4131
4127
  const bare=stripBackticks(line);
4132
4128
  for(const m of bare.matchAll(rxMdPath)){raw.push(m[1]);}
4133
- for(const m of bare.matchAll(rxTableRow)){if(valid(m[1])||invalidReason(m[1])!=='invalid-syntax')raw.push(m[1]);}
4134
4129
  }
4135
4130
  for(const m of section.matchAll(rxRelLink)){raw.push(m[1]);}
4136
4131
  const invalid=[];for(const r of raw){const reason=invalidReason(r);if(reason)invalid.push({stem:norm(r),reason});}
4137
4132
  if(invalid.length){for(const item of invalid)process.stderr.write(item.reason+': '+item.stem+'; use a stable business resource/domain stem\\n');process.exit(2);}
4138
4133
  const seen=new Set();const modules=[];
4139
4134
  for(const r of raw){const st=norm(r);if(valid(r)&&!seen.has(st)){seen.add(st);modules.push({stem:st});}}
4135
+ if(modules.length===0){process.stderr.write('empty-module-index: require at least one stable business module\\n');process.exit(2);}
4140
4136
  if(modules.length>8){process.stderr.write('excessive-module-count: '+modules.length+' > 8; merge by the smallest stable business resource/domain set\\n');process.exit(2);}
4141
- process.stdout.write(JSON.stringify({modules}));
4137
+ const planReadPath=path.relative(process.cwd(),planPath).split(path.sep).join('/');
4138
+ const planSha256=crypto.createHash('sha256').update(readme).digest('hex');
4139
+ process.stdout.write(JSON.stringify({modules:modules.map(item=>({...item,planReadPath})),planReadPath,planSha256}));
4142
4140
  `;
4143
4141
  const encoded = Buffer.from(script, "utf8").toString("base64");
4144
4142
  return `node -e "eval(Buffer.from('${encoded}','base64').toString('utf8'))"`;
@@ -4621,35 +4619,37 @@ async function buildBackendTestHybridDag(sources) {
4621
4619
  const generateMdPlan = {
4622
4620
  id: "generate-backend-md-plan-pi",
4623
4621
  depends_on: [environment.id],
4624
- role: "implementer",
4622
+ role: "planner",
4625
4623
  executor: "pi",
4626
- toolProfile: "write",
4624
+ toolProfile: "read-only",
4627
4625
  complexity: "MED",
4628
- writePolicy: "exclusive",
4629
- writeSet: ["testcase/md/README.md"],
4630
- allowedPaths: ["testcase/md/README.md"],
4626
+ writePolicy: "read-only",
4627
+ allowedPaths: [],
4628
+ readSet: [
4629
+ toDagSourcePath(sources, sources.requirementPath),
4630
+ ...(sources.constraintMarkdown
4631
+ ? [toDagSourcePath(sources, sources.constraintPath)]
4632
+ : []),
4633
+ ...intake.referenceIndex.map((entry) => entry.readPath),
4634
+ ".harness/dag-runs/**/reports/backend-test-environment.md",
4635
+ ],
4631
4636
  forbiddenPaths: forbidden,
4632
- writerOutcomePolicy: {
4633
- type: "implementation-outcome-v1",
4634
- requireChangedFiles: true,
4635
- },
4636
- retryPolicy: BACKEND_TEST_WRITER_COMPLETENESS_RETRY_POLICY,
4637
- outputContract: "Write a Chinese, human-readable testcase/md/README.md as the single Markdown-first entry page with Coverage Scope, Coverage Matrix and a machine-parseable module index. Do not write module case cards here; do not execute pytest or modify production code/config.",
4637
+ outputContract: "Return a Chinese, human-readable Markdown-first plan with Coverage Scope, Coverage Matrix, Scenario Partitions when applicable, and a machine-parseable Module Index. The runtime persists it as a run-owned Harness artifact; do not write testcase/md/README.md, execute pytest, or modify project files.",
4638
4638
  subtask_prompt: [
4639
- "This is a required file-generation node. After reading the bounded inputs, immediately use write tools to create testcase/md/README.md. Do not end after analysis or planning, and do not return before a non-empty bounded diff exists. Write ONLY testcase/md/README.md in this node; module case cards are written by downstream sharded nodes.",
4639
+ "This is a required plan-generation node. Read only the strict read set and return the complete Markdown plan in the assistant response. The runtime persists the response as a run-owned Harness artifact named generate-backend-md-plan-pi/plan.md. Do not write testcase/md/README.md or any project file; module case cards are written by downstream sharded nodes.",
4640
4640
  "Output budget protocol (hard, max output <=16K per turn): Never paste full Matrix, case bodies, or source text into assistant chat. README holds only Scope+Matrix+module index; never inline full case bodies. If a Completeness Gate / OUTPUT_LIMIT_RECOVERY retry is injected, continue only listed target paths.",
4641
- "The first non-empty response line must be exactly IMPLEMENTATION_OUTCOME: changed after the README has been written, or IMPLEMENTATION_OUTCOME: blocked when precise missing evidence prevents safe generation. already-satisfied is not valid for this node.",
4642
- "Read the upstream environment report. Generate the Markdown-first backend test README under testcase/md/README.md.",
4641
+ "Return the complete plan as plain Markdown. Do not emit JSON or code fences. The plan must contain the exact ## Coverage Scope, ## Coverage Matrix and ## Module Index sections required by the downstream manifest.",
4642
+ "Read the upstream environment report only through the strict read set. Generate the Markdown-first backend test plan; it will be persisted under the current DAG run's Harness artifacts, not under testcase/md/.",
4643
4643
  "Write human-readable content in Simplified Chinese by default. Keep English only for machine-readable IDs and technical literals such as Case/AC/REQ/BR IDs, HTTP methods, paths, field names, enum values, commands, filenames, code symbols and exact source citations.",
4644
- "Create testcase/md/README.md as the concise entry page: test objective, target/environment, isolation/cleanup, module summary and a linked case index table with Case ID, Chinese case name, scenario type, endpoint and expected status/result. Avoid repeating every case body in README.",
4645
- "Before the Coverage Matrix, write a mandatory machine-readable `## Coverage Scope` section in README using exactly `| Field | Value |`, immediately followed by the separator row `|---|---|`, and these six unique rows: `Change Classification`, `Coverage Policy`, `Affected Operations`, `Affected Rule Keys`, `Regression Floor`, `Scope Evidence`. Always set `Change Classification` to `new-operation` and `Coverage Policy` to `full-contract`; do NOT reason about whether operations are new or existing. Cover all in-scope rules from the requirement document at full depth; treat the product requirement as the coverage baseline and use API contract evidence (fields/status/enum/boundary/format) to supplement scenario dimensions. Scope is limited to operations/rules the requirement document (or its referenced API contract) explicitly describes; do not expand to unrelated operations that the requirement does not mention. List affected operations exactly as `METHOD /path`, stable rule keys separated by semicolons, and precise source pointers as Scope Evidence.",
4644
+ "Create the concise plan entry page: test objective, target/environment, isolation/cleanup, module summary and a linked case index table with Case ID, Chinese case name, scenario type, endpoint and expected status/result. Avoid repeating every case body in the plan artifact.",
4645
+ "Before the Coverage Matrix, write a mandatory machine-readable `## Coverage Scope` section in the plan artifact using exactly `| Field | Value |`, immediately followed by the separator row `|---|---|`, and these six unique rows: `Change Classification`, `Coverage Policy`, `Affected Operations`, `Affected Rule Keys`, `Regression Floor`, `Scope Evidence`. Always set `Change Classification` to `new-operation` and `Coverage Policy` to `full-contract`; do NOT reason about whether operations are new or existing. Cover all in-scope rules from the requirement document at full depth; treat the product requirement as the coverage baseline and use API contract evidence (fields/status/enum/boundary/format) to supplement scenario dimensions. Scope is limited to operations/rules the requirement document (or its referenced API contract) explicitly describes; do not expand to unrelated operations that the requirement does not mention. List affected operations exactly as `METHOD /path`, stable rule keys separated by semicolons, and precise source pointers as Scope Evidence.",
4646
4646
  "Coverage depth is full over the in-scope rules: fully cover every documented status, request/response field rule, requiredness, enum, boundary, format, auth and business state of each affected operation the requirement describes, but do not re-test unrelated operations the requirement does not mention. Inspect shared validator/helper/DTO/query builder evidence and expand Affected Operations when the same affected path can affect them; unresolved impact stays visible as GAP/CONFLICT.",
4647
- "Before writing cases, build the mandatory machine-readable Coverage Matrix inside `testcase/md/README.md` itself. Its section heading line must be exactly `## Coverage Matrix` with no numeric prefix/suffix; never place the canonical Matrix only in a module file. Use this exact header: `| Rule Key | Priority | Source | Endpoint/Field | Dimension | Rule | Required Test Points | Case IDs | Status |`. Every data row must contain exactly 9 pipe-delimited cells and must never omit `Dimension`; use concise dimensions such as requirement, operation, response-status, requiredness, enum, boundary, format, business-state or error. Use only P0/P1/P2 and COVERED/PARTIAL/GAP/CONFLICT. Use stable `TP-<UPPERCASE-HYPHENATED-ID>` test points separated by semicolons.",
4647
+ "Before writing cases, build the mandatory machine-readable Coverage Matrix inside the plan artifact itself. Its section heading line must be exactly `## Coverage Matrix` with no numeric prefix/suffix; never place the canonical Matrix only in a module file. Use this exact header: `| Rule Key | Priority | Source | Endpoint/Field | Dimension | Rule | Required Test Points | Case IDs | Status |`. Every data row must contain exactly 9 pipe-delimited cells and must never omit `Dimension`; use concise dimensions such as requirement, operation, response-status, requiredness, enum, boundary, format, business-state or error. Use only P0/P1/P2 and COVERED/PARTIAL/GAP/CONFLICT. Use stable `TP-<UPPERCASE-HYPHENATED-ID>` test points separated by semicolons.",
4648
4648
  "Each Rule Key must appear in exactly one Matrix row. Preserve each AC/REQ/BR Rule Key as one row; if one product rule spans multiple dimensions, use a concise composite Dimension in that single row instead of duplicating the key. Derive OpenAPI Rule Keys exactly as the deterministic analyzer does: operation token is `<HTTP-METHOD>-<PATH>` with braces removed and every non-alphanumeric run replaced by a hyphen, uppercase (for example POST `/api/resource-notes` → `POST-API-RESOURCE-NOTES`); response statuses use `API-<OPERATION>-RESPONSE-STATUS`; body/parameter fields use `API-<OPERATION>-<FIELD>-REQUIRED|ENUM|MIN-LENGTH|MAX-LENGTH|MINIMUM|MAXIMUM|PATTERN|FORMAT`. Do not invent aliases such as API-CREATE-FIELDS when a deterministic key applies.",
4649
4649
  "Coverage priority is strict inside the declared scope: P0 product requirements/task hard constraints always remain in scope; P1 exhaustively supplements documented operations, fields, business rules, statuses and errors only for Affected Operations; P2 adds bounded protocol robustness only when it is relevant to the change and does not invent product behavior. Coverage percentages describe the declared affected scope, never whole-API completeness unless every operation is explicitly listed. Conflicts or undefined expectations must stay visible as GAP/CONFLICT with precise source pointers, never guessed.",
4650
4650
  "For uniqueness/lifecycle rules cover absent, active-existing, deleted-existing, create-delete-recreate, restore-then-recreate and documented scope/case-normalization states. For every enum cover every valid value plus bounded invalid equivalence classes (unknown, case variant, whitespace, empty, null/missing and wrong types as applicable). For every length/number rule cover min-1, min, nominal, max and max+1. For format rules cover each allowed class separately plus a valid mixed value, and representative forbidden classes including uppercase, internal/leading/trailing whitespace, tab/newline, unsupported punctuation, slash, emoji or control characters when the source contract supports that expectation.",
4651
- "Mandatory module index: include a `## Module Index` table in README that lists every planned module as a canonical relative link of the exact form `[label](./<stem>.md)` plus a `testcase/md/<stem>.md` path cell, so a downstream deterministic manifest can parse the module list. Group by stable business resource/domain, not by CRUD operation: one resource's list/detail/create/update/delete cases belong in one module such as `resource_notes`; split only when a single module would exceed the per-child 16K output protocol, keep the total module count at the smallest safe value, and never exceed 8 modules. Name each module file with a stable lowercase business stem such as `health` or `resource_notes`. Pure hexadecimal/hash-like opaque stems such as `a401606` or `deadbeef` are forbidden. Do not use priority-only stems `p0`, `p1` or `p2`; Priority belongs only in the Coverage Matrix and never defines module files. Do not use Case-ID-like module filenames such as `BE-HEALTH.md` or `BE-NOTES.md`. The relative link target MUST equal the on-disk filename stem the sharded writer will create. For every automatable case, `自动化映射` must name exactly `testcase/test_<module>.py`, where <module> is that Markdown filename without `.md`, lowercased, with non-alphanumeric characters replaced by underscores. Example: `testcase/md/health.md` → `testcase/test_health.py`; `testcase/md/resource_notes.md` → `testcase/test_resource_notes.py`. Never invent a different pytest path in Markdown than the module stem implies.",
4652
- "Scenario Partitions (query/filter axes): for every affected GET/list operation, declare one row per enum or classification axis used for filtering (query/path parameters such as type/status/category). Add a mandatory machine-readable `## Scenario Partitions` section after the Coverage Matrix using exactly `| Partition ID | Operation | Axis | Domain | Required Slots | Expected by Slot | Bind Rule |` with the separator row. Partition ID is a stable `SP-<OPERATION>-<AXIS>` token; Domain must copy the legal values verbatim from the bound OpenAPI enum or requirement sentence (never guess); Required Slots writes `each-value` plus `omitted` only when the parameter is optional; Expected by Slot states the documented expectation per slot kind (`domain-value`, `default-behavior`, `empty-result`/`excluded-result` when documented, or `GAP` when the source does not document the complement expectation — never invent 空列表/400). POST/PUT body field-validation enums stay in the Coverage Matrix as `TP-<FIELD>-ENUM-*` and MUST NOT get a Scenario Partition row. Do not create partitions for axes without a documented legal-value domain. Only GET/list query or path parameters whose bound source documents a finite enum or classification set may become a Scenario Partition. Do not create partitions for free-form strings, primary keys, required-or-optional-only parameters, or boundary/format-only axes. If an axis has no finite legal-value domain, do not declare a Partition row and do not invent NOT-IN-SET cases. Cross-axis combinations stay as ONE nominal Case; never declare a cross-axis cartesian partition.",
4651
+ "Mandatory module index: include a `## Module Index` table in the plan artifact that lists every planned module as a canonical relative link of the exact form `[label](./<stem>.md)` plus a `testcase/md/<stem>.md` path cell, so a downstream deterministic manifest can parse the module list. Group by stable business resource/domain, not by CRUD operation: one resource's list/detail/create/update/delete cases belong in one module such as `resource_notes`; split only when a single module would exceed the per-child 16K output protocol, keep the total module count at the smallest safe value, and never exceed 8 modules. Name each module file with a stable lowercase business stem such as `health` or `resource_notes`. Pure hexadecimal/hash-like opaque stems such as `a401606` or `deadbeef` are forbidden. Do not use priority-only stems `p0`, `p1` or `p2`; Priority belongs only in the Coverage Matrix and never defines module files. Do not use Case-ID-like module filenames such as `BE-HEALTH.md` or `BE-NOTES.md`. The relative link target MUST equal the on-disk filename stem the sharded writer will create. For every automatable case, `自动化映射` must name exactly `testcase/test_<module>.py`, where <module> is that Markdown filename without `.md`, lowercased, with non-alphanumeric characters replaced by underscores. Example: `testcase/md/health.md` → `testcase/test_health.py`; `testcase/md/resource_notes.md` → `testcase/test_resource_notes.py`. Never invent a different pytest path in Markdown than the module stem implies.",
4652
+ "Scenario Partitions (query/filter axes): for every affected GET/list operation, declare one row per enum or classification axis used for filtering (query/path parameters such as type/status/category). Add a mandatory machine-readable `## Scenario Partitions` section after the Coverage Matrix using exactly `| Partition ID | Operation | Axis | Domain | Required Slots | Expected by Slot | Bind Rule |` with the separator row. Partition ID is a stable `SP-<OPERATION>-<AXIS>` token; Domain must copy the legal values verbatim from the bound OpenAPI enum or requirement sentence (never guess), using bare semicolon-separated identifier values inside the single table cell (for example `ACTIVE; ARCHIVED`, with no Markdown backticks or prose); Required Slots writes `each-value` plus `omitted` only when the parameter is optional; Expected by Slot states the documented expectation per slot kind (`domain-value`, `default-behavior`, `empty-result`/`excluded-result` when documented, or `GAP` when the source does not document the complement expectation — never invent 空列表/400). POST/PUT body field-validation enums stay in the Coverage Matrix as `TP-<FIELD>-ENUM-*` and MUST NOT get a Scenario Partition row. Do not create partitions for axes without a documented legal-value domain. Only GET/list query or path parameters whose bound source documents a finite enum or classification set may become a Scenario Partition. Do not create partitions for free-form strings, primary keys, required-or-optional-only parameters, or boundary/format-only axes. If an axis has no finite legal-value domain, do not declare a Partition row and do not invent NOT-IN-SET cases. Cross-axis combinations stay as ONE nominal Case; never declare a cross-axis cartesian partition.",
4653
4653
  "Before finalizing README, calculate the predicted collected-item count as `sum(max(1, number of variant Test Points in each Case))`. If the task declares an item budget, the prediction must not exceed it. Reduce excess only by removing duplicate execution and converting same-request checkpoints to assertions; never drop required rules, boundaries, enums, operation-specific inputs, or business states. Record the prediction in README. Use only environment-supported fixtures/targets/isolation, record evidence gaps in Chinese, and do not emit JSON, pytest, or execute commands.",
4654
4654
  ...(sharedSetupPrompt ? [sharedSetupPrompt] : []),
4655
4655
  intake.boundedSourceContext,
@@ -4668,8 +4668,8 @@ async function buildBackendTestHybridDag(sources) {
4668
4668
  writePolicy: "read-only",
4669
4669
  allowedPaths: ro,
4670
4670
  forbiddenPaths: forbidden,
4671
- outputContract: "Stdout JSON {modules:[{stem}]} parsed from testcase/md/README.md using the same module-stem extractor as the Completeness Gate, so the map_agent shard set deterministically matches the README module index.",
4672
- subtask_prompt: "Parse testcase/md/README.md and emit exactly one trailing JSON line {modules:[{stem}]} listing every trusted module stem (table-row testcase/md/<stem>.md mentions and canonical [label](./<stem>.md) relative links only). No file writes.",
4671
+ outputContract: "Stdout JSON {modules:[{stem,planReadPath}],planReadPath,planSha256} parsed from the run-owned generate-backend-md-plan-pi/plan.md artifact using the same module-stem extractor as the Completeness Gate.",
4672
+ subtask_prompt: "Parse only $HARNESS_DAG_RUN_DIR/generate-backend-md-plan-pi/plan.md and emit exactly one trailing JSON line {modules:[{stem,planReadPath}],planReadPath,planSha256}. No file writes and no testcase/md/README.md fallback.",
4673
4673
  shell: {
4674
4674
  commands: [buildBackendTestModuleManifestShellCommand(layout)],
4675
4675
  cwd: ".",
@@ -4710,6 +4710,15 @@ async function buildBackendTestHybridDag(sources) {
4710
4710
  allowedPaths: ["testcase/md/{{item.stem}}.md"],
4711
4711
  forbiddenPaths: forbidden,
4712
4712
  writeSet: ["testcase/md/{{item.stem}}.md"],
4713
+ readSet: [
4714
+ "{{item.planReadPath}}",
4715
+ toDagSourcePath(sources, sources.requirementPath),
4716
+ ...(sources.constraintMarkdown
4717
+ ? [toDagSourcePath(sources, sources.constraintPath)]
4718
+ : []),
4719
+ ...intake.referenceIndex.map((entry) => entry.readPath),
4720
+ `${layout.markdownDir}/{{item.stem}}.md`,
4721
+ ],
4713
4722
  writerOutcomePolicy: {
4714
4723
  type: "implementation-outcome-v1",
4715
4724
  requireChangedFiles: true,
@@ -4717,7 +4726,7 @@ async function buildBackendTestHybridDag(sources) {
4717
4726
  retryPolicy: BACKEND_TEST_WRITER_COMPLETENESS_RETRY_POLICY,
4718
4727
  outputContract: "Write exactly one Chinese module Markdown case-card file testcase/md/<stem>.md with BE-<MODULE>-<NNN> cases and the seven required h3 sections; keep machine IDs/literals exact and do not execute pytest or modify production code/config or the README.",
4719
4728
  subtaskPromptTemplate: [
4720
- "This is a required file-generation node for exactly one Markdown module. After reading testcase/md/README.md (Coverage Scope + Coverage Matrix + module index) and the bounded references, immediately use write tools to create the single file testcase/md/{{item.stem}}.md. Do not end after analysis or planning, and do not return before a non-empty bounded diff exists. Do not modify README.md or any other module file.",
4729
+ "This is a required file-generation node for exactly one Markdown module. Read the upstream run-owned Markdown plan artifact at `{{item.planReadPath}}` (Coverage Scope + Coverage Matrix + Module Index) and the bounded references, then immediately use write tools to create the single file testcase/md/{{item.stem}}.md. Do not read or recreate testcase/md/README.md. Do not end after analysis or planning, and do not return before a non-empty bounded diff exists. Do not modify any other module file.",
4721
4730
  "Output budget protocol (hard, max output <=16K per turn): Never paste full Matrix, other modules' case bodies, or source text into assistant chat. Each write/edit tool call touches at most one file (this module). Compact tables/lists are required; omitting required sections or in-scope variants is forbidden. If a Completeness Gate / OUTPUT_LIMIT_RECOVERY retry is injected, continue only listed target paths.",
4722
4731
  "The first non-empty response line must be exactly IMPLEMENTATION_OUTCOME: changed after the module file has been written, or IMPLEMENTATION_OUTCOME: blocked when precise missing evidence prevents safe generation. already-satisfied is not valid for this node.",
4723
4732
  "Write human-readable content in Simplified Chinese by default. Keep English only for machine-readable IDs and technical literals such as Case/AC/REQ/BR IDs, HTTP methods, paths, field names, enum values, commands, filenames, code symbols and exact source citations.",
@@ -4739,28 +4748,37 @@ async function buildBackendTestHybridDag(sources) {
4739
4748
  };
4740
4749
  const reviewCases = {
4741
4750
  id: "review-and-revise-backend-md-cases-pi",
4742
- depends_on: [generateMdCasesMap.id],
4751
+ depends_on: [generateMdCasesMap.id, materializeMdManifest.id],
4743
4752
  role: "implementer",
4744
4753
  executor: "pi",
4745
4754
  toolProfile: "write",
4746
4755
  complexity: "MED",
4747
4756
  writePolicy: "exclusive",
4748
- writeSet: ["testcase/md/**"],
4749
- allowedPaths: Array.from(new Set([...ro, "testcase/md/**"])),
4750
- forbiddenPaths: forbidden,
4757
+ writeSet: [`${layout.markdownDir}/**`],
4758
+ readSet: [
4759
+ ".harness/dag-runs/**/generate-backend-md-plan-pi/plan.md",
4760
+ toDagSourcePath(sources, sources.requirementPath),
4761
+ ...(sources.constraintMarkdown
4762
+ ? [toDagSourcePath(sources, sources.constraintPath)]
4763
+ : []),
4764
+ ...intake.referenceIndex.map((entry) => entry.readPath),
4765
+ `${layout.markdownDir}/*.md`,
4766
+ ],
4767
+ allowedPaths: Array.from(new Set([...ro, `${layout.markdownDir}/**`])),
4768
+ forbiddenPaths: Array.from(new Set([...forbidden, layout.readmePath])),
4751
4769
  writerOutcomePolicy: { type: "implementation-outcome-v1" },
4752
4770
  outputContract: "First non-empty line is IMPLEMENTATION_OUTCOME: changed|already-satisfied|blocked. Perform exactly one bounded incremental synchronization of testcase/md/** against all bound source references; preserve valid Cases and report a concise summary.",
4753
4771
  subtask_prompt: [
4754
- "Perform one gap-targeted synchronization, not a full-suite rewrite or stylistic review. Start from explicit bound source IDs/error codes/DTO fields/normative quoted rules and the README Matrix; open and edit only modules that own a missing or conflicting rule. Preserve unrelated valid modules byte-for-byte and avoid optional wording cleanup.",
4755
- "Output budget protocol: never dump full Matrix/case bodies into assistant chat. Inspect README first, build a concise target list, then read/write only target modules one file per tool call. Do not traverse every module when the Matrix and source token inventory show no gap; return `already-satisfied`. When adding omitted in-scope cases, keep every required section. Do not bulk-delete in-scope cases to save tokens.",
4772
+ "Perform one gap-targeted synchronization, not a full-suite rewrite or stylistic review. Read the immutable run-owned Markdown plan from the direct upstream manifest's planReadPath. Start from explicit bound source IDs/error codes/DTO fields/normative quoted rules and the plan Coverage Matrix; open and edit only modules that own a missing or conflicting rule. Never create or edit testcase/md/README.md and never modify the run-owned plan artifact. Preserve unrelated valid modules byte-for-byte and avoid optional wording cleanup.",
4773
+ "Output budget protocol: never dump full Matrix/case bodies into assistant chat. Inspect the immutable run-owned plan first, build a concise target list from its Matrix and Module Index, then read/write only target modules one file per tool call. Do not traverse every module when the Matrix and source token inventory show no gap; return `already-satisfied`. When adding omitted in-scope cases, keep every required section. Do not bulk-delete in-scope cases to save tokens.",
4756
4774
  "For every variant Test Point, ensure the Markdown scenario intent is machine-checkable and located inside that same Case body/自动化映射, never in a file-level appendix, implementation-details block, or another Case. Use an exact transport target: `场景意图: <TP-ID>; operation=<METHOD /path>; target=<body.field|query.field|path.field|header.field|request>; intent=<empty|missing|null|min-1|min|max|max+1|pattern-invalid|enum-invalid|wrong-type|nominal-operation|custom-literal:V>; bound=<n optional>; example=<optional>; expectedCode=<optional>`. Never use vague targets such as field=resource/health. Keep pytest params aligned to the exact target. For intent=missing/empty/default-omit, pytest may use `_OMIT` or delete the key; for intent=enum-invalid use a concrete invalid enum literal (for example `UNKNOWN_STATUS`), never `_OMIT`/missing-key; for trim/padded samples use `custom-literal:trim` or a real padded string, not a bare token like `filter-active` when the intent is `custom-literal:ACTIVE`.",
4757
4775
  "Treat the requirement document as the coverage baseline; scope is limited to operations/rules it (or its referenced API contract) describes, and API contract evidence supplements scenario dimensions. For every in-scope operation, check applicable lifecycle/uniqueness states (including deleted-existing when in scope), valid enum values, bounded invalid classes, min-1/min/nominal/max/max+1, allowed/forbidden format classes, required/null/missing/wrong-type semantics, status/error codes, auth and state transitions. Inspect shared validator/helper/DTO/query builder evidence and expand Affected Operations when the same affected path can affect them; unresolved impact stays visible as GAP/CONFLICT. Directly add in-scope omissions; reject scope expansion to operations absent from the requirement document; undefined impact remains GAP/CONFLICT rather than invented behavior.",
4758
- "Check AC completeness/meaning, endpoint, fields/shape, status/error codes, rules, states, documented boundaries/auth, positive/negative coverage, executable steps and assertable results. Require the exact `## Coverage Scope` Field/Value table with the `|---|---|` separator row, a valid classification-policy pair, non-empty Affected Operations/Rule Keys/Scope Evidence, and the classification-specific Regression Floor. Require the exact unnumbered `## Coverage Matrix` heading in `testcase/md/README.md`, exact headers, exactly 9 cells in every data row (including a non-empty Dimension), deterministic OpenAPI Rule Keys for every in-scope affected operation, exactly one Matrix row per Rule Key (merge multi-dimension product rows), and bidirectional Matrix Rule/Test Point ↔ Case bindings. Never describe affected-scope coverage as whole-API completeness. Every explicit AC ID must appear in at least one Case `验收标准`; every explicit in-scope AC/REQ/BR Rule Key cited by a Case must have exactly one Coverage Matrix row, and no Case may cite a source Rule Key omitted from the Matrix. Every Matrix Case ID must share at least one of that row's Required Test Points and the Case must cite that Rule Key. Perform an explicit execution-redundancy review: merge checkpoint-only parameter rows, repeated default/read-back assertions, DELETE status/body/follow-up-read checks, response schema/Content-Type checks, PUT full-update/timestamp checks, repeated list setup and identical null/empty inputs when endpoint, input partition, precondition state and expected outcome are the same. Preserve separate POST/PUT, boundary, enum, wrong-type, role/tenant and distinct business-state variants. Directly repair malformed headings/rows/keys and binding modes rather than merely commenting on them. Reject avoidable English prose, duplicated bilingual wording, repeated boilerplate, oversized unstructured sections, a `### 操作步骤` section that contains only a table without any numbered executable line, vague results such as ‘符合预期’, Case-ID-like module filenames (for example `BE-HEALTH.md`), dropped exact `### 操作步骤`/`### 预期结果` headings, and missing or drifted script/function mapping where it can be derived.",
4776
+ "Check AC completeness/meaning, endpoint, fields/shape, status/error codes, rules, states, documented boundaries/auth, positive/negative coverage, executable steps and assertable results. Require the exact `## Coverage Scope` Field/Value table with the `|---|---|` separator row, a valid classification-policy pair, non-empty Affected Operations/Rule Keys/Scope Evidence, and the classification-specific Regression Floor. Require the exact unnumbered `## Coverage Matrix` heading in the immutable run-owned plan artifact, exact headers, exactly 9 cells in every data row (including a non-empty Dimension), deterministic OpenAPI Rule Keys for every in-scope affected operation, exactly one Matrix row per Rule Key (merge multi-dimension product rows), and bidirectional Matrix Rule/Test Point ↔ Case bindings. Never describe affected-scope coverage as whole-API completeness. Every explicit AC ID must appear in at least one Case `验收标准`; every explicit in-scope AC/REQ/BR Rule Key cited by a Case must have exactly one Coverage Matrix row, and no Case may cite a source Rule Key omitted from the Matrix. Every Matrix Case ID must share at least one of that row's Required Test Points and the Case must cite that Rule Key. Perform an explicit execution-redundancy review: merge checkpoint-only parameter rows, repeated default/read-back assertions, DELETE status/body/follow-up-read checks, response schema/Content-Type checks, PUT full-update/timestamp checks, repeated list setup and identical null/empty inputs when endpoint, input partition, precondition state and expected outcome are the same. Preserve separate POST/PUT, boundary, enum, wrong-type, role/tenant and distinct business-state variants. Directly repair malformed headings/rows/keys and binding modes rather than merely commenting on them. Reject avoidable English prose, duplicated bilingual wording, repeated boilerplate, oversized unstructured sections, a `### 操作步骤` section that contains only a table without any numbered executable line, vague results such as ‘符合预期’, Case-ID-like module filenames (for example `BE-HEALTH.md`), dropped exact `### 操作步骤`/`### 预期结果` headings, and missing or drifted script/function mapping where it can be derived.",
4759
4777
  "Correct testcase/md/** directly: add documented omissions, remove unsupported cases, rename module files to stable lowercase stems when needed, normalize every Case ID to hyphen-separated module segments plus exactly three zero-padded digits (`BE-RESOURCE_NOTES-01` → `BE-RESOURCE-NOTES-001`; `BE-RN-011A` must be renumbered or merged) consistently across headings/index/mappings, fix automation mappings so each automatable case points at `testcase/test_<module>.py` derived from that module filename and declares exactly one primary symbol (evidence-only meta cases may keep `脚本/primary symbol=无` with empty variants), assign every Test Point exactly one of `变体测试点`/`场景断言测试点`/`横切证据测试点`, then perform an exact-set check: each Case's `### 测试点` set must equal (not merely contain) the union of those three binding lists; delete stale/legacy aliases and ensure every binding-list Test Point is present, expand every variant parameter row into its own atomic TP ID, make every non-cross-cutting TP Case-specific and owned by exactly one Case, require every primary symbol to start with the canonical Case prefix, ensure every explicit AC ID appears in an applicable Case `验收标准`, merge execution duplicates, improve navigation/tables/Chinese wording, or record gaps in Chinese. Remove every credential/header value, placeholder, fake token and anti-example from Markdown. Sensitive key names may remain only as a plain list; values must be described as runtime-only and omitted, with no colon/value pair or literal example anywhere, including details blocks and explanatory text. Keep Case IDs, AC/REQ/BR IDs, HTTP methods, paths, fields, enum values, filenames, code symbols and source citations as exact machine-readable identifiers; only normalize Case ID separator/sequence formatting as specified above. Recalculate predicted collected items as `sum(max(1, variant count per Case))`; when the task declares a budget, directly merge redundant journeys/reclassify same-request checkpoints until the prediction is within budget, while preserving all required coverage. The validator accepts Chinese and legacy English section aliases; retain or converge to the Chinese human-readable headings without losing structure.",
4760
4778
  "This is the single Markdown incremental synchronization round. Read every authoritative reference index entry whose role hints include acceptance-criteria, api-contract, data-contract or business-rule; do not rely on the derived PRD as a complete inventory. Preserve every explicit AC/REQ/BR ID, every documented HTTP/business error code, every DTO/JSON field, enum value, boundary, format, nested shape, transaction/state/idempotency/uniqueness/auth/tenant/cross-field rule. For each natural-language normative business rule preserved as required scope, include its exact source sentence without paraphrase together with source path and line/heading anchor so the deterministic ledger can verify quote/hash provenance. Ensure every Case declares exactly `Payload Contract: none` or the three labels `Payload Required Paths`, `Payload Allowed Paths`, and `Payload Enum`; every label must occupy its own machine-readable list line, and a Case must never concatenate target/setup operations or multiple `Payload Contract` tokens onto one line, and explanatory prose/details must not repeat any `Payload Contract:` token; never infer missing keys or enum values. A target GET/DELETE operation with no request body must remain `Payload Contract: none` even when its setup journey performs POST/PUT with a DTO; setup payloads never redefine the target Case payload contract. Add only missing Matrix rows/Test Points/Cases/assertions or repair exact drift; do not rewrite already-valid unrelated modules. Work gap-targeted: inspect source anchors and affected modules first, leave unrelated valid modules byte-stable, and return `already-satisfied` without restating the full suite when no gap exists.",
4761
4779
  "For affected API fields, use one valid nominal payload plus atomic required/missing/null/empty/wrong-type, every documented enum value plus bounded invalid classes, documented min-1/min/nominal/max/max+1, formats and nested object/array constraints. Do not generate a Cartesian product or invent undocumented constraints. Do not invent a concrete identifier type when the source only requires presence; for a missing-resource 404 path with unspecified identifier syntax/type, synchronize the Case to a create-delete-derived valid identifier journey rather than an arbitrary UUID/text placeholder.",
4762
- "Scenario Partitions synchronization: when README declares `## Scenario Partitions`, verify each declared partition's slots are fully materialized as variant Test Points with exact `TP-<Partition ID>-...` IDs (each-value per Domain value, OMITTED only for optional axes, exactly one NOT-IN-SET with intent=enum-invalid). Directly add missing slot rows/Cases. You may delete an illegal Partition row that has no source-backed finite domain, together with its derived `TP-SP-*` slots/Cases. Never delete a legal source-backed partition or drop its complement slot to force coverage green. When the bound source does not document the complement expectation, keep the slot with GAP expected instead of guessing. Body-field validation enums (`TP-<FIELD>-ENUM-*`) are NOT partitions — do not add partition rows for them.",
4763
- "Before returning, verify that every explicit source AC/REQ/BR, error code and strong DTO field token appears in README or an applicable module Case. If a fact cannot be safely automated, retain it as GAP/CONFLICT with its exact source pointer instead of dropping it. Return already-satisfied only when no target file needs an incremental edit.",
4780
+ "Scenario Partitions synchronization: when the run-owned plan declares `## Scenario Partitions`, verify each declared partition's slots are fully materialized as variant Test Points with exact `TP-<Partition ID>-...` IDs (each-value per Domain value, OMITTED only for optional axes, exactly one NOT-IN-SET with intent=enum-invalid). Directly add missing slot rows/Cases. Record an illegal plan Partition row that has no source-backed finite domain as GAP/CONFLICT and remove only its derived `TP-SP-*` slots/Cases from target modules; never modify the immutable plan artifact. Never delete a legal source-backed partition or drop its complement slot to force coverage green. When the bound source does not document the complement expectation, keep the slot with GAP expected instead of guessing. Body-field validation enums (`TP-<FIELD>-ENUM-*`) are NOT partitions — do not add partition rows for them.",
4781
+ "Before returning, verify that every explicit source AC/REQ/BR, error code and strong DTO field token appears in the run-owned plan or an applicable module Case. If a fact cannot be safely automated, retain it as GAP/CONFLICT with its exact source pointer instead of dropping it. Return already-satisfied only when no target file needs an incremental edit.",
4764
4782
  "Read only indexed source paths. Do not scan the repository, modify source/**, generate pytest, execute tests, or emit JSON.",
4765
4783
  ...(sharedSetupPrompt ? [sharedSetupPrompt] : []),
4766
4784
  intake.boundedSourceContext,
@@ -4809,8 +4827,8 @@ async function buildBackendTestHybridDag(sources) {
4809
4827
  writePolicy: "read-only",
4810
4828
  allowedPaths: ro,
4811
4829
  forbiddenPaths: forbidden,
4812
- outputContract: "Stdout JSON {modules:[{stem}]} parsed from testcase/md/README.md using the same module-stem extractor as the Completeness Gate, so the map_agent shard set deterministically matches the Markdown module index.",
4813
- subtask_prompt: "Parse testcase/md/README.md and emit exactly one trailing JSON line {modules:[{stem}]} listing every trusted module stem (table-row testcase/md/<stem>.md mentions and canonical [label](./<stem>.md) relative links only). No file writes.",
4830
+ outputContract: "Stdout JSON {modules:[{stem,planReadPath}],planReadPath,planSha256} parsed from the run-owned Markdown plan artifact, so the pytest map shard set and every child planReadPath deterministically match the Markdown map manifest.",
4831
+ subtask_prompt: "Parse only the run-owned generate-backend-md-plan-pi/plan.md artifact and emit exactly one trailing JSON line {modules:[{stem,planReadPath}],planReadPath,planSha256}. Reuse the same plan-derived Module Index contract as the Markdown manifest; do not search for or fall back to testcase/**/README.md. No file writes.",
4814
4832
  shell: {
4815
4833
  commands: [buildBackendTestModuleManifestShellCommand(layout)],
4816
4834
  cwd: ".",
@@ -4865,7 +4883,7 @@ async function buildBackendTestHybridDag(sources) {
4865
4883
  retryPolicy: BACKEND_TEST_WRITER_COMPLETENESS_RETRY_POLICY,
4866
4884
  outputContract: "Write exactly one pytest module file testcase/test_<stem>.py whose actual test function region contains the exact Case ID, preferably in the function name or docstring. testcase/md/<module>.md (excluding README.md) maps one-to-one to testcase/test_<module>.py; never merge or split modules. No JSON and no pytest execution.",
4867
4885
  subtaskPromptTemplate: [
4868
- "Convert the single Markdown module testcase/md/{{item.stem}}.md into one self-contained pytest module. Before writing, also read testcase/md/README.md and use its explicit API target/environment table as the authoritative fallback base URL for every module. A task/Markdown `API_BASE_URL` target takes precedence over project README dev-server URLs; never infer a backend API fallback from a frontend/Vite port such as localhost:3000. After reading the module Markdown, testcase/md/README.md, and the bounded pytest config/conftest, immediately use write tools to create the single file testcase/test_{{item.stem}}.py. Define any bounded HTTP client fixture, request logging/redaction/truncation helper and payload builders needed by this module inside that same file; do not import generated testcase/**/helpers/** or testcase/**/factories/** assets. Do not end after analysis or planning. Do not modify Markdown, conftest, helpers/factories, or any other module's pytest script.",
4886
+ "Convert the single Markdown module testcase/md/{{item.stem}}.md into one self-contained pytest module. Before writing, also read the run-owned Markdown plan artifact at `{{item.planReadPath}}` and use its explicit API target/environment table as the authoritative fallback base URL for every module. A task/Markdown `API_BASE_URL` target takes precedence over project README dev-server URLs; never infer a backend API fallback from a frontend/Vite port such as localhost:3000. After reading the module Markdown, the run-owned plan artifact, and the bounded pytest config/conftest, immediately use write tools to create the single file testcase/test_{{item.stem}}.py. Define any bounded HTTP client fixture, request logging/redaction/truncation helper and payload builders needed by this module inside that same file; do not import generated testcase/**/helpers/** or testcase/**/factories/** assets. Do not end after analysis or planning. Do not modify Markdown, conftest, helpers/factories, or any other module's pytest script.",
4869
4887
  "Output budget protocol (hard, max output <=16K per turn): Write exactly one test_{{item.stem}}.py. Never paste full Python modules into assistant chat. Do not merge or split modules. Do not reduce params/assertions/skips to fit. If OUTPUT_LIMIT_RECOVERY is injected, continue only listed missing/broken scripts.",
4870
4888
  "Align every variant pytest.param payload with the Markdown scenario intent (empty/missing/null/length/pattern/enum/wrong-type/nominal). Prefer literal payloads over Faker for intent-critical fields so pre-execution scenario-param checks can verify them. Hard contract: intent=enum-invalid MUST pass a concrete invalid value literal (string/number/boolean), never `_OMIT`/None/missing key; intent=missing/empty may use `_OMIT` or delete the key; intent=custom-literal:trim|whitespace-padded requires a leading/trailing whitespace string with non-empty trimmed content (all-whitespace belongs to empty/whitespace-only, not trim); intent=custom-literal:ACTIVE|ARCHIVED requires the exact enum string, never descriptive tokens like filter-active; intent=max/min/max+1 should pass a repeated-string length expression, a bare length number N, or a helper named _*_LEN{N} / _*_MAX_LENGTH / _*_OVER_LENGTH — never a bare 1 for oversize. Hard contract: request payload dicts may only contain DTO field keys from Payload Allowed Paths; never put expect/expected/echo_* helper keys inside the JSON body dict. Path/query/header identifiers and scenario-control metadata (including `id`, expected codes, and selector labels) must stay in separate pytest parameters and helper arguments; never merge them into a DTO patch or JSON body unless that exact path is allowed by the Markdown payload contract. Normalize the configured API base URL with `rstrip(\"/\")` (or equivalently join exactly one slash) before appending endpoint paths; generated requests must never contain a `//api/...` path. When the bound source documents a concrete non-secret local API URL, generated clients must use it as the fallback in `os.environ.get(\"API_BASE_URL\", \"<documented-url>\")`; do not require an otherwise-uninjected environment variable or fail setup solely because it is absent. Missing-field helpers must remove keys idempotently with `payload.pop(field, None)`, never `del payload[field]`, because optional fields may already be absent.",
4871
4889
  "For every response contract that requires an object or pagination envelope, first assert that each envelope/data value is a dict and that required keys exist, then index fields and assert values. Never let an incidental KeyError or list/string TypeError stand in for the explicit response-shape contract failure.",
@@ -4881,6 +4899,13 @@ async function buildBackendTestHybridDag(sources) {
4881
4899
  },
4882
4900
  };
4883
4901
  const collectionAssess = shellNode("assess-backend-pytest-collection-shell", [generatePytestCasesMap.id], "markdown-collection-assess", "Resolve final Markdown-mapped scripts before any business test body execution. Run scenario-param assess/at-most-one deterministic repair first, then pytest --collect-only and a no-business-body pytest --setup-plan fixture-resolution preflight. A safe missing mapped script, generated-local syntax/import defect, or generated fixture dependency/plugin-registration defect is REPAIRABLE; dependency, third-party plugin, production-module, environment, safety and unknown failures remain blocked. Materialize hash-bound collection-v3 facts with repairPaths and fixtureResolutionStatus.", "Run-owned reports/backend-test-pytest-collection-initial.md and contracts/backend-test-pytest-collection-initial.json (collection-v3) with bounded collection/fixture diagnostics, repairPaths, asset hashes, collected item IDs and deterministic repair eligibility.", [], 120000);
4902
+ // N10 owns the deterministic scenario-param rewrite that may update mapped
4903
+ // generated test modules before collection. Declare that bounded shell write
4904
+ // authority so filesystem-only workspace control does not misclassify the
4905
+ // intentional repair as an out-of-bounds mutation.
4906
+ collectionAssess.writePolicy = "exclusive";
4907
+ collectionAssess.writeSet = [applyLayout("testcase/**/test_*.py")];
4908
+ collectionAssess.allowedPaths = Array.from(new Set([...ro, ...collectionAssess.writeSet]));
4884
4909
  const repairPytest = {
4885
4910
  id: "repair-backend-pytest-collection-pi",
4886
4911
  depends_on: [collectionAssess.id],
@@ -4890,8 +4915,24 @@ async function buildBackendTestHybridDag(sources) {
4890
4915
  toolProfile: "write",
4891
4916
  complexity: "MED",
4892
4917
  writePolicy: "exclusive",
4893
- writeSet: ["testcase/**/test_*.py"],
4894
- allowedPaths: Array.from(new Set([...ro, "testcase/**"])),
4918
+ writeSet: Array.from(new Set([
4919
+ applyLayout("testcase/**/test_*.py"),
4920
+ `${layout.testRoot}/helpers/**/*.py`,
4921
+ `${layout.testRoot}/factories/**/*.py`,
4922
+ `${layout.testRoot}/__*_helpers.py`,
4923
+ `${layout.scriptDir}/helpers/**/*.py`,
4924
+ `${layout.scriptDir}/factories/**/*.py`,
4925
+ `${layout.scriptDir}/__*_helpers.py`,
4926
+ ])),
4927
+ readSet: [
4928
+ ".harness/dag-runs/**/reports/backend-test-pytest-collection-initial.md",
4929
+ ".harness/dag-runs/**/reports/backend-test-markdown-pytest-correspondence-initial.md",
4930
+ ".harness/dag-runs/**/generate-backend-md-plan-pi/plan.md",
4931
+ `${layout.markdownDir}/**`,
4932
+ `${layout.testRoot}/**/*.py`,
4933
+ ],
4934
+ contextBudget: { maxTurns: 24, maxTokens: 80_000 },
4935
+ allowedPaths: Array.from(new Set([...ro, `${layout.testRoot}/**`])),
4895
4936
  forbiddenPaths: Array.from(new Set([
4896
4937
  ...forbidden,
4897
4938
  "testcase/md/**",
@@ -4904,7 +4945,7 @@ async function buildBackendTestHybridDag(sources) {
4904
4945
  outputContract: "First non-empty line is IMPLEMENTATION_OUTCOME: changed|blocked, followed by a concise repair summary. This node runs only for REPAIRABLE initial facts, so already-satisfied is invalid and a successful outcome requires a non-empty bounded diff. Modify only generated pytest scripts/helpers/factories and preserve every Markdown Case, Test Point, primary symbol and assertion meaning.",
4905
4946
  subtask_prompt: [
4906
4947
  "Repair the generated backend pytest asset as one bounded program using the direct upstream collection assessment. This is the only repair attempt and happens before any business test body execution. Treat any upstream line such as `Repair paths: testcase/test_x.py` as complete authoritative repairPaths evidence. Directly read and edit that testcase path; do not search for separate root-level `contracts/**`, guess a DAG run directory, or require another report artifact. If the read tool successfully returns the testcase file, the path exists—continue the bounded repair and never later claim that file is absent.",
4907
- "Initial status REPAIRABLE means at least one listed finding remains: `already-satisfied` is forbidden, and you must produce a non-empty bounded diff on repairPaths before returning `IMPLEMENTATION_OUTCOME: changed`. Fix only readiness-proven generated testcase-local defects on initial facts repairPaths: create exact safe missing mapped test_*.py paths, repair syntax/import/symbol/decorator/parameterization, close generated fixture dependencies/plugin registration, and repair initial Markdown-to-pytest correspondence findings (missing/multiple primary symbol, script mismatch, parameter ID or assertion binding). Never invent a business pytest symbol for evidence-only Markdown Cases that declare `脚本/primary symbol=无` with empty variants. For fixture defects inspect both provider and importer; fix ScopeMismatch by aligning fixture scopes or inlining request-scoped values so module fixtures never depend on function fixtures; when a shared fixture depends on sibling fixtures, register the whole provider module through an exact pytest_plugins declaration rather than importing only the outer fixture. Do not create unrelated pytest scripts.",
4948
+ "Initial status REPAIRABLE means at least one listed finding remains: `already-satisfied` is forbidden, and you must produce a non-empty bounded diff on repairPaths before returning `IMPLEMENTATION_OUTCOME: changed`. Fix only readiness-proven generated testcase-local defects on initial facts repairPaths: create exact safe missing mapped test_*.py paths, repair syntax/import/symbol/decorator/parameterization, close generated fixture dependencies/plugin registration, and repair initial Markdown-to-pytest correspondence findings. Use this deterministic repair map instead of reading analyzer implementation: findings about `Case-ID`, `Assertion-Test-Points`, or `Cross-Cutting-Test-Points` are fixed by editing the declared primary symbol docstring metadata lines; variant binding findings are fixed in the literal direct `pytest.param(..., id=\"TP-...\")` row; primary-symbol cardinality/name findings are fixed in the function name or duplicate primary symbols; script mismatch is fixed only on the authoritative assessment repairPaths; payload findings are fixed in request payload construction. Do not read controller `src/**` or inspect JS/TS analyzer code. Do not search for `testcase/**/README.md`. Never invent a business pytest symbol for evidence-only Markdown Cases that declare `脚本/primary symbol=无` with empty variants. For fixture defects inspect both provider and importer listed by repairPaths; fix ScopeMismatch by aligning fixture scopes or inlining request-scoped values so module fixtures never depend on function fixtures; when a shared fixture depends on sibling fixtures, register the whole provider module through an exact pytest_plugins declaration rather than importing only the outer fixture. Do not create unrelated pytest scripts.",
4908
4949
  "This is the single pytest incremental synchronization round. The `Findings` in `reports/backend-test-pytest-collection-initial.md` are the mandatory repair checklist: resolve every repairable listed finding on every authoritative `Repair paths` file before considering any other advisory evidence, and never substitute an unrelated scenario-param cleanup for a listed correspondence/collection defect. For every assessment-listed path, compare the effective Markdown Case/Test Points/test data and its `Payload Contract`/`Payload Required Paths`/`Payload Allowed Paths`/`Payload Enum` labels with the generated module. Incrementally add or repair only missing symbols, params, assertions and payload builders. Repair every assessment-listed missing nested path, unexpected key and enum mismatch; preserve exact DTO keys, nested shapes, enum/boundary literals, operation transport and business preconditions; remove guessed replacement keys only when the effective Markdown proves the exact contract. Keep path/query/header identifiers and scenario-control metadata separate from DTO patches and JSON bodies; an `id` used for a path target must be passed to the request path/helper, never inserted into a body patch unless `id` is explicitly listed in Payload Allowed Paths. Flatten every variant into a literal direct `pytest.param(..., id=\"TP-...\")` row; replace `_post_case`/`_put_case` or other parameter-row factories because correspondence and scenario readiness require the actual row values and IDs to be statically visible. Also repair helper call sites to match their defined return signatures; do not tuple-unpack a helper that returns one scalar value.",
4909
4950
  "Preserve final testcase/md/** semantics, every Case ID, Rule/Test Point binding, primary symbol, parameter ID, expected status/body/schema assertion, HTTP logging, redaction and truncation behavior.",
4910
4951
  "Use local edit only on assessment-listed paths; keep summaries short; never rewrite unrelated modules.",
@@ -238,6 +238,85 @@ async function readFrontendPlanCommittedSnapshot(runDir, nodeId) {
238
238
  const hasTerminalFact = committed.some((record) => record.fact.kind === "finalize_plan");
239
239
  return { digest, hasTerminalFact };
240
240
  }
241
+ function planInputRecord(value) {
242
+ return typeof value === "object" && value !== null && !Array.isArray(value);
243
+ }
244
+ function planInputText(value, maxChars = 240) {
245
+ if (typeof value !== "string" || value.trim().length === 0)
246
+ return undefined;
247
+ const normalized = value.trim();
248
+ return normalized.length <= maxChars
249
+ ? normalized
250
+ : `${normalized.slice(0, maxChars - 1)}…`;
251
+ }
252
+ function planInputStrings(value) {
253
+ return Array.isArray(value)
254
+ ? value.filter((item) => typeof item === "string")
255
+ : [];
256
+ }
257
+ /**
258
+ * Render the planner's complete-but-bounded evidence handoff from committed
259
+ * typed facts. It deliberately excludes upstream response prose and artifact
260
+ * paths: Contract and Scout have already established these facts, so Plan
261
+ * should decide and commit rather than spend another model turn reading them.
262
+ */
263
+ export function renderFrontendPlanInputContext(input) {
264
+ const committedFacts = (records) => records.flatMap((record) => record.phase === "committed" && planInputRecord(record.fact)
265
+ ? [record.fact]
266
+ : []);
267
+ const contractFacts = committedFacts(input.contractRecords);
268
+ const scoutFacts = committedFacts(input.scoutRecords);
269
+ const requirements = contractFacts
270
+ .filter((fact) => fact.kind === "requirement" && fact.origin === "contract")
271
+ .map((fact) => ({
272
+ id: planInputText(fact.id, 80),
273
+ text: planInputText(fact.text),
274
+ sourceFragmentIds: planInputStrings(fact.sourceFragmentIds),
275
+ }))
276
+ .filter((fact) => fact.id !== undefined);
277
+ const targetSurface = scoutFacts
278
+ .filter((fact) => fact.kind === "target-surface" && fact.origin === "scout")
279
+ .map((fact) => ({
280
+ completeness: planInputText(fact.completeness, 32),
281
+ entrypoint: planInputText(fact.entrypoint, 240),
282
+ routeOrMount: planInputText(fact.routeOrMount, 240),
283
+ implementationPaths: planInputStrings(fact.implementationPaths),
284
+ testPaths: planInputStrings(fact.testPaths),
285
+ dataSource: planInputText(fact.dataSource),
286
+ allowedPathConflicts: planInputStrings(fact.allowedPathConflicts),
287
+ unresolvedPaths: planInputStrings(fact.unresolvedPaths),
288
+ }));
289
+ const designEvidence = scoutFacts
290
+ .filter((fact) => fact.kind === "design-evidence" && fact.origin === "scout")
291
+ .map((fact) => ({
292
+ source: planInputText(fact.source),
293
+ paths: planInputStrings(fact.paths),
294
+ conflicts: planInputStrings(fact.conflicts),
295
+ }));
296
+ const serialized = JSON.stringify({ requirements, targetSurface, designEvidence });
297
+ const bounded = serialized.length <= 12_000
298
+ ? serialized
299
+ : `${serialized.slice(0, 11_999)}…`;
300
+ return [
301
+ "<frontend_plan_input>",
302
+ "Committed Contract/Scout facts, compiled by the runner. Treat them as the complete planning evidence.",
303
+ bounded,
304
+ "Do not read upstream artifacts, task sources, or repository files. If this input cannot support a decision, record a genuine evidence gap.",
305
+ "</frontend_plan_input>",
306
+ ].join("\n");
307
+ }
308
+ async function buildFrontendPlanInputContext(runDir) {
309
+ try {
310
+ const [contractRecords, scoutRecords] = await Promise.all([
311
+ readTypedEventStoreFromJsonl(path.join(runDir, "frontend-contract-pi", "contract-typed-facts.jsonl")),
312
+ readTypedEventStoreFromJsonl(path.join(runDir, "frontend-scout-pi", "scout-typed-facts.jsonl")),
313
+ ]);
314
+ return renderFrontendPlanInputContext({ contractRecords, scoutRecords });
315
+ }
316
+ catch {
317
+ return "";
318
+ }
319
+ }
241
320
  export function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCategory, previousProtocolReason, recoveryTargetPaths, recoveryDiagnostics, frontendPlanRetryStep) {
242
321
  if (attemptNumber <= 1)
243
322
  return basePrompt;
@@ -938,6 +1017,11 @@ export async function executeDagNode(input) {
938
1017
  await failSkillSnapshot(error);
939
1018
  return;
940
1019
  }
1020
+ if (isFrontendPlanLadderTask(task)) {
1021
+ const planInputContext = await buildFrontendPlanInputContext(runDir);
1022
+ if (planInputContext)
1023
+ prompt = `${prompt}\n\n${planInputContext}`;
1024
+ }
941
1025
  node.resolvedSkills = resolvedSkills;
942
1026
  await writeNodeSkillArtifacts(runDir, nodeId, resolvedSkills);
943
1027
  let model = resolveModelForTask(task, spec.executorModels);
@@ -770,6 +770,8 @@ export const dagDynamicExpansionChildTaskSchema = z.object({
770
770
  allowedPaths: z.array(z.string()).optional().default([]),
771
771
  forbiddenPaths: z.array(z.string()).optional().default([]),
772
772
  writeSet: z.array(z.string()).optional(),
773
+ /** Template-rendered strict repository-relative read allowlist. */
774
+ readSet: z.array(z.string()).optional(),
773
775
  /**
774
776
  * Materialized-child pass-through fields for bounded Pi writer children
775
777
  * (backend-test md/pytest case sharding). All optional so legacy
@@ -970,6 +972,21 @@ export const dagTaskSchema = z.object({ id: z.string().regex(/^[a-z][a-z0-9-]*$/
970
972
  commandPolicy: dagCommandPolicySchema.optional(),
971
973
  writePolicy: dagWritePolicySchema.optional(),
972
974
  writeSet: z.array(z.string()).optional(),
975
+ /** Strict repository-relative read allowlist for bounded Pi nodes. */
976
+ readSet: z.array(z.string()).optional(),
977
+ /**
978
+ * Online per-attempt Pi context guard. Unlike run/map cost budgets, this
979
+ * aborts the active SDK session before an oversized conversation reaches
980
+ * the provider's context rejection boundary.
981
+ */
982
+ contextBudget: z
983
+ .object({
984
+ maxTurns: z.number().int().positive().optional(),
985
+ maxTokens: z.number().int().positive().optional(),
986
+ })
987
+ .strict()
988
+ .refine((value) => value.maxTurns !== undefined || value.maxTokens !== undefined, "contextBudget requires maxTurns or maxTokens")
989
+ .optional(),
973
990
  piStep: z.string().optional(),
974
991
  shell: dagShellConfigSchema.optional(),
975
992
  static: dagStaticConfigSchema.optional(),
@@ -538,6 +538,24 @@
538
538
  "type": "array",
539
539
  "items": { "type": "string", "minLength": 1 }
540
540
  },
541
+ "readSet": {
542
+ "type": "array",
543
+ "items": { "type": "string", "minLength": 1 },
544
+ "description": "Strict repository-relative read allowlist for bounded Pi nodes."
545
+ },
546
+ "contextBudget": {
547
+ "type": "object",
548
+ "additionalProperties": false,
549
+ "description": "Online per-attempt Pi SDK conversation guard. At least one threshold is required; exhaustion aborts the active session with context-budget-exhausted partial evidence.",
550
+ "properties": {
551
+ "maxTurns": { "type": "integer", "minimum": 1 },
552
+ "maxTokens": { "type": "integer", "minimum": 1 }
553
+ },
554
+ "anyOf": [
555
+ { "required": ["maxTurns"] },
556
+ { "required": ["maxTokens"] }
557
+ ]
558
+ },
541
559
  "piStep": {
542
560
  "type": "string",
543
561
  "minLength": 1