@tea-agent/loop-agent 0.38.1 → 0.38.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 (127) hide show
  1. package/CHANGELOG.md +109 -13
  2. package/dist/application/dag/generate-task-dag.js +9 -0
  3. package/dist/build-stamp.json +3 -3
  4. package/dist/commands/init.js +2 -14
  5. package/dist/executors/dag-pi-executor.js +41 -4
  6. package/dist/executors/shell-executor.js +269 -15
  7. package/dist/governance/manifest-types.js +0 -2
  8. package/dist/shared/operator/capabilities.js +87 -22
  9. package/dist/task/config-types.js +22 -0
  10. package/dist/worker/console/chat/deferred-turn.js +91 -0
  11. package/dist/worker/console/chat/pi-runtime.js +10 -5
  12. package/dist/worker/console/chat/routes.js +458 -47
  13. package/dist/worker/console/chat/semantic-activity.js +13 -13
  14. package/dist/worker/console/chat/session-store.js +146 -2
  15. package/dist/worker/console/harness-pi-model-matrix.js +2 -11
  16. package/dist/worker/console/operator-actions.js +5 -4
  17. package/dist/worker/console/pi-readiness.js +1 -0
  18. package/dist/worker/console/recovery-cta.js +4 -4
  19. package/dist/worker/console/recovery-error-copy.js +4 -4
  20. package/dist/worker/console/server.js +6 -1
  21. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-Hfsot6rP.js → abnfDiagram-N423BO3Z-C4bmo3iY.js} +1 -1
  22. package/dist/worker/console/static/assets/{arc-YGwEASin.js → arc-SAD7McOS.js} +1 -1
  23. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-CmOM0F92.js → architectureDiagram-T3A2C74G-DAVLUdK1.js} +1 -1
  24. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-DDLuaHC5.js → blockDiagram-VBNYF7ZC-CPPdv4vj.js} +1 -1
  25. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-B0Um43W4.js → c4Diagram-5PPSVZJV-D1GRGZax.js} +1 -1
  26. package/dist/worker/console/static/assets/channel-R6oQIDkw.js +1 -0
  27. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-DvBN4JZc.js → chunk-2GRJ4B5K-D_Bq2ZqK.js} +1 -1
  28. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-B1UVgW4E.js → chunk-2Q5K7J3B-CPLVtamK.js} +1 -1
  29. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-Cf0GgXzX.js → chunk-5RXB4S5H-DnaZWcL3.js} +1 -1
  30. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-DbNA24sj.js → chunk-5VM5RSS4-BRTmFgnq.js} +1 -1
  31. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-Bi_0Be06.js → chunk-6Q2QTUOP-BRlfYZoH.js} +1 -1
  32. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-C8pPGvRd.js → chunk-GF5L2VYU-CjNybD4u.js} +1 -1
  33. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-BitQY8Z-.js → chunk-JWPE2WC7-D3e-74fG.js} +1 -1
  34. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-U67GCiEo.js → chunk-KBJHAD2P-Br3ir6f2.js} +1 -1
  35. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-IoJwXPBA.js → chunk-RYQCIY6F-1NgVuRbh.js} +1 -1
  36. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-YDZ_UHgE.js → chunk-XXDRQBXY-BTYuvuWN.js} +1 -1
  37. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-BPXlmPWI.js +1 -0
  38. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-BPXlmPWI.js +1 -0
  39. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-CUZgsiRC.js → cose-bilkent-JH36ORCC-BC6Bgosf.js} +1 -1
  40. package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-COmCh4pT.js → cynefin-VYW2F7L2-DV-HypfL.js} +1 -1
  41. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-Ta6FSm68.js → cynefinDiagram-MW4NZA55-DhTaddO-.js} +1 -1
  42. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-UdcR-VW9.js → dagre-VZM6K2ZE-BnEcOmiI.js} +1 -1
  43. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-DybcO3Et.js → diagram-7IWD3JNH-xphGRVKp.js} +1 -1
  44. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-wErDFWLw.js → diagram-B4RE2ZJO-CrdD1mRG.js} +1 -1
  45. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-DkVHZWqz.js → diagram-LBJQPF4R-D4YdLsaF.js} +1 -1
  46. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-DdqWs7QN.js → diagram-Q27KOJAE-LCKyGZ5U.js} +1 -1
  47. package/dist/worker/console/static/assets/{diagram-UB23O5K3-C9dMVmDo.js → diagram-UB23O5K3-BeiTe7t0.js} +1 -1
  48. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-B2T2WcBK.js → ebnfDiagram-BXEA7PRR-BO2cq8GS.js} +1 -1
  49. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-Bt9rjDFq.js → erDiagram-JOGREHBK-CmWww3Nt.js} +1 -1
  50. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-U8ic_tvi.js → flowDiagram-UKHOOZJN-C2kkUYg5.js} +1 -1
  51. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-BfQJdQoO.js → ganttDiagram-PKOTCBZU-DY_JZ2iQ.js} +1 -1
  52. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-CpMftH4O.js → gitGraphDiagram-DS77QQ5N-BizhCSw9.js} +1 -1
  53. package/dist/worker/console/static/assets/index-BXN89VPX.js +325 -0
  54. package/dist/worker/console/static/assets/index-CuH5CNFu.css +1 -0
  55. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-DzqWXNO_.js → infoDiagram-6WML65LV-Dlo2eK_d.js} +1 -1
  56. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-CJmGQ5Yp.js → ishikawaDiagram-WSZJBQD7-3EIlIIuZ.js} +1 -1
  57. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-ChPtKFLz.js → journeyDiagram-NVQOT4AX-DiMDe5Yh.js} +1 -1
  58. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-PRe7wB5u.js → kanban-definition-27J2QSJJ-sN553oIN.js} +1 -1
  59. package/dist/worker/console/static/assets/{linear-DpKX6QNp.js → linear-D9Py31Ld.js} +1 -1
  60. package/dist/worker/console/static/assets/{mermaid.core-Dnl76b7Y.js → mermaid.core-D7Occzk_.js} +5 -5
  61. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-S9PCXc3J.js → mindmap-definition-FAOFIHXS-DjDRboiR.js} +1 -1
  62. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-Du8e-FSX.js → pegDiagram-VL7TDLO6-Cgc4qlzp.js} +1 -1
  63. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-CY6OmHTc.js → pieDiagram-7S7Q4E2Y-DxZj8pKd.js} +1 -1
  64. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-C65GPhpj.js → quadrantDiagram-CIZ2JOQS-CJ50MngR.js} +1 -1
  65. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-U6IUiTCL.js → railroadDiagram-AXF67PYL-BY-OD8Tr.js} +1 -1
  66. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-D-I_9Qhi.js → requirementDiagram-LRYGKXZP-CQFButfK.js} +1 -1
  67. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-B57Fhed0.js → sankeyDiagram-W5VNT64P-BB_QUK_b.js} +1 -1
  68. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-CJOtiw21.js → sequenceDiagram-SI44F4Z6-CqhXZjyx.js} +1 -1
  69. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-FyX8zxSh.js → sizeCapture-X5ZJPWSS-2l1U4rgJ.js} +1 -1
  70. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-eF-pbs9t.js → stateDiagram-OKZ733FA-BX1FbrhJ.js} +1 -1
  71. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DJKi0Qel.js +1 -0
  72. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-CcfkA-Dq.js → swimlanes-SLNWSIFB-DOSnT7hb.js} +2 -2
  73. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-YYe7EEm5.js +8 -0
  74. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-DH8FjnOK.js → timeline-definition-Z64GVDOM-DVJQA7AN.js} +1 -1
  75. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-beoTagJg.js → vennDiagram-T6HMQDX7-74uxl9gx.js} +1 -1
  76. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-CQSfw4cK.js → wardleyDiagram-T6FBY63Y-DsBxlcg_.js} +1 -1
  77. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-CQgzQ6jn.js → xychartDiagram-ELKLHX3M-snuW9Mjw.js} +1 -1
  78. package/dist/worker/console/static/index.html +2 -2
  79. package/dist/worker/console/static-src/app/console-types.js +0 -12
  80. package/dist/worker/console/static-src/app/useOperatorActions.js +1 -1
  81. package/dist/worker/console/static-src/app/useRecoveryActions.js +2 -2
  82. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +38 -1
  83. package/dist/worker/console/static-src/operator-chat/turn-stream-controller.js +8 -1
  84. package/dist/worker/console/static-src/operator-chat/turn-submission.js +42 -0
  85. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +3 -0
  86. package/dist/worker/console/static-src/operator-chat/useChatStream.js +204 -11
  87. package/dist/worker/console/static-src/operator-chat/useChatThread.js +23 -1
  88. package/dist/workflows/dag/backend-test-case-coverage-analysis.js +755 -51
  89. package/dist/workflows/dag/backend-test-case-manifest.js +4 -0
  90. package/dist/workflows/dag/backend-test-execution-contract.js +18 -9
  91. package/dist/workflows/dag/backend-test-gap-fill.js +205 -0
  92. package/dist/workflows/dag/backend-test-intake-context.js +32 -0
  93. package/dist/workflows/dag/backend-test-layout.js +133 -0
  94. package/dist/workflows/dag/backend-test-markdown-workflow.js +167 -32
  95. package/dist/workflows/dag/backend-test-module-stem.js +5 -0
  96. package/dist/workflows/dag/backend-test-pytest-collection.js +368 -33
  97. package/dist/workflows/dag/backend-test-result-contract.js +1 -1
  98. package/dist/workflows/dag/backend-test-scenario-param.js +884 -140
  99. package/dist/workflows/dag/backend-test-scenario-partitions.js +249 -0
  100. package/dist/workflows/dag/backend-test-writer-completeness.js +100 -56
  101. package/dist/workflows/dag/contract-validator-registrations.js +2 -1
  102. package/dist/workflows/dag/convergence/controller.js +141 -0
  103. package/dist/workflows/dag/dynamic-runtime/map.js +24 -8
  104. package/dist/workflows/dag/dynamic-runtime/shared.js +1 -1
  105. package/dist/workflows/dag/frontend-implementation-contract.js +236 -8
  106. package/dist/workflows/dag/frontend-prewrite-gate.js +95 -35
  107. package/dist/workflows/dag/init-hybrid.js +652 -87
  108. package/dist/workflows/dag/node-execution.js +45 -18
  109. package/dist/workflows/dag/prompt.js +45 -0
  110. package/dist/workflows/dag/rerun-feedback.js +212 -0
  111. package/dist/workflows/dag/rerun-plan.js +93 -27
  112. package/dist/workflows/dag/rerun-run.js +3 -0
  113. package/dist/workflows/dag/rerun-task.js +61 -2
  114. package/dist/workflows/dag/retry-policy.js +18 -0
  115. package/dist/workflows/dag/types.js +98 -0
  116. package/docs/templates/backend-test-dag.json +60 -35
  117. package/docs/templates/harness.schema.json +0 -8
  118. package/harness.json +1 -8
  119. package/package.json +1 -1
  120. package/skills/frontend-implementation/references/node-contracts.md +2 -2
  121. package/dist/worker/console/static/assets/channel-Dp_2Aqf1.js +0 -1
  122. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL--CODy37j.js +0 -1
  123. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE--CODy37j.js +0 -1
  124. package/dist/worker/console/static/assets/index-BA5-N5ER.css +0 -1
  125. package/dist/worker/console/static/assets/index-DKPXBrdc.js +0 -325
  126. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-B-mvnLEc.js +0 -1
  127. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-JtpBmIv4.js +0 -8
@@ -5,6 +5,7 @@ import path from "node:path";
5
5
  import { writeJsonAtomic } from "../../infrastructure/harness/atomic-write.js";
6
6
  import { assertValidDagSpec } from "./validate.js";
7
7
  import { DAG_AGENT_RUNTIME_PI_ONLY, DAG_REPAIR_WRITER_PROTOCOL_EXPLICIT_NODE_V1, DAG_RUNTIME_CONTRACT_SCHEMA_VERSION, DEFAULT_DAG_OUTPUT_LANGUAGE, DEFAULT_DAG_EXECUTOR_MODELS, parseDagSpec, } from "./types.js";
8
+ import { bindDagRerunFeedback } from "./rerun-feedback.js";
8
9
  import { planMavenVerification, } from "../../verification/maven/index.js";
9
10
  import { pathMatchesPattern } from "../../shared/git-progress.js";
10
11
  import { extractTaskSourceOpenspecPaths } from "../../shared/openspec-spec.js";
@@ -27,12 +28,13 @@ import { DEFAULT_VERIFY_TIMEOUT_MS, resolveVerifyPreset, } from "../../executors
27
28
  import { resolveExecutorModelMatrices } from "../../executors/model-routing.js";
28
29
  import { normalizeTaskRequirementText, resolveTaskDagTemplateSelection, } from "./task-demand-routing.js";
29
30
  import { BACKEND_TEST_EXECUTION_DEFAULT_TEST_ROOT, buildBackendTestExecutionPreflightShellSnippet, } from "./backend-test-execution-contract.js";
31
+ import { resolveBackendTestLayout, } from "./backend-test-layout.js";
30
32
  import { buildBackendTestOutcomeGateShellSnippet } from "./backend-test-result-contract.js";
31
33
  import { buildBackendTestIntakeContext } from "./backend-test-intake-context.js";
32
34
  import { buildFrontendTestOutcomeGateShellSnippet } from "./frontend-test-result-contract.js";
33
35
  import { classifyFrontendRisk, } from "./frontend-risk.js";
34
36
  import { discoverFrontendProjectCapability, } from "./frontend-project-capability.js";
35
- import { FRONTEND_IMPLEMENTATION_CONTRACT_SCHEMA_ID, loadFrontendImplementationContractJsonSchema, } from "./frontend-implementation-contract.js";
37
+ import { buildFrontendImplementationContractSkeleton, FRONTEND_IMPLEMENTATION_CONTRACT_SCHEMA_ID, FRONTEND_IMPLEMENTATION_CONTRACT_PLAN_PATCH_SCHEMA_ID, loadFrontendImplementationContractJsonSchema, } from "./frontend-implementation-contract.js";
36
38
  import { serializeDagTaskSourcePath } from "../../task/dag-source-paths.js";
37
39
  const REQUIREMENT_FILE = "需求.md";
38
40
  const CONSTRAINT_FILE = "执行约束.md";
@@ -2417,33 +2419,21 @@ async function buildFrontendHybridDagFromTask(sources) {
2417
2419
  complexity: taskConfig.complexity,
2418
2420
  });
2419
2421
  const frontendSourceBinding = buildDagSourceBinding(sources);
2422
+ const frontendContractSkeleton = buildFrontendImplementationContractSkeleton({
2423
+ sourceBinding: frontendSourceBinding,
2424
+ riskLevel: frontendRisk.selectedRisk,
2425
+ targetFiles: implementPaths.writeSet,
2426
+ });
2420
2427
  const frontendContractSchemaBlock = (() => {
2421
2428
  const schema = loadFrontendImplementationContractJsonSchema();
2422
- const requirement = frontendSourceBinding.sources.find((source) => source.kind === "requirement");
2423
- if (!requirement) {
2424
- throw new Error("frontend implementation contract context requires a bound requirement source");
2425
- }
2426
- const referencePaths = frontendSourceBinding.sources
2427
- .filter((s) => s.kind === "reference")
2428
- .map((s) => s.path);
2429
- const fixedFields = {
2430
- schemaVersion: 1,
2431
- sourceBinding: {
2432
- taskId: frontendSourceBinding.taskId,
2433
- requirementPath: requirement.path,
2434
- requirementSha256: requirement.sha256,
2435
- referencePaths,
2436
- requirementIds: frontendSourceBinding.requirementIds,
2437
- },
2438
- riskLevel: frontendRisk.selectedRisk,
2439
- targets: { files: implementPaths.writeSet },
2440
- };
2441
2429
  return [
2442
- `## ${FRONTEND_IMPLEMENTATION_CONTRACT_SCHEMA_ID} JSON Schema (authoritative; do not guess fields)`,
2430
+ `## Final ${FRONTEND_IMPLEMENTATION_CONTRACT_SCHEMA_ID} JSON Schema (authoritative after runtime merge)`,
2443
2431
  schema,
2444
2432
  "",
2445
- "## Fixed contract fields (deterministic; copy exactly and do not modify)",
2446
- JSON.stringify(fixedFields),
2433
+ "## Runtime contract skeleton (deterministic and protected)",
2434
+ JSON.stringify(frontendContractSkeleton),
2435
+ "",
2436
+ "The initial planner emits an editable RFC 7386 patch against this skeleton. It MUST omit schemaVersion, sourceBinding, riskLevel, targets.files, and mockApi.productionDefaultOff. The runtime merges and validates the final contract, then replaces the planner output with canonical full-contract JSON for downstream review.",
2447
2437
  "",
2448
2438
  "## Forbidden fields (these are NOT in the schema; do not emit)",
2449
2439
  "- schemaId",
@@ -2795,20 +2785,22 @@ async function buildFrontendHybridDagFromTask(sources) {
2795
2785
  outputMode: "structured-required",
2796
2786
  retryPolicy: STRUCTURED_REQUIRED_PI_RETRY_POLICY,
2797
2787
  structuredContractOutput: {
2798
- schemaId: "frontend-implementation-contract-v1",
2788
+ schemaId: FRONTEND_IMPLEMENTATION_CONTRACT_PLAN_PATCH_SCHEMA_ID,
2799
2789
  retryOnInvalid: true,
2790
+ skeleton: frontendContractSkeleton,
2800
2791
  },
2801
2792
  allowedPaths: readOnlyPaths,
2802
2793
  forbiddenPaths,
2803
2794
  skills: FRONTEND_IMPLEMENTATION_SKILLS,
2804
- outputContract: "One-line lead-in, then exactly ONE fenced json object (```json ... ```) conforming to frontend-implementation-contract-v1. This fenced block is the single authoritative implementation contract the prewrite gate materializes; it must appear exactly once. Immediately after it, append exactly one ```openspec-citations``` fenced citation block. Do NOT emit a Markdown plan explanation or any prose after the contract JSON the output is JSON-only (the gate renders plan.md deterministically). Apart from the contract JSON fenced block and the openspec-citations block, do not emit any other fenced block or raw JSON. No file writes.",
2795
+ outputContract: "JSON-only patch output: one-line lead-in, then exactly ONE fenced json object (```json ... ```) containing only the editable RFC 7386 plan patch for the runtime contract skeleton. Omit protected fields: schemaVersion, sourceBinding, riskLevel, targets.files, and mockApi.productionDefaultOff. Immediately after it, append exactly one ```openspec-citations``` fenced citation block. The runtime applies the patch, validates it, and promotes canonical full-contract JSON for downstream review. Do NOT emit a full contract, Markdown plan explanation, raw JSON, or any other fenced block. No file writes.",
2805
2796
  subtask_prompt: [
2806
- "Based on frontend-contract-pi, frontend-scout-pi, task sources, and the generation-time Mock capability evidence, return a minimal frontend implementation plan.",
2807
- "Select the Mock / API strategy inside the plan and structured contract. Carry endpoint/fixture mapping, explicit activation, production-default-off rule, verification commands, and Real Integration Gap into both outputs.",
2797
+ "Use frontend-contract-pi, frontend-scout-pi, task sources, and the generation-time Mock capability evidence to fill the runtime-owned frontend contract skeleton. Return JSON-only output containing only an editable RFC 7386 plan patch. The runtime already owns schemaVersion, sourceBinding, riskLevel, targets.files, and mockApi.productionDefaultOff; omit those protected paths even when their values look obvious.",
2798
+ "The patch fields become the complete implementation plan after deterministic merge. Do not produce a separate plan document, prose mirror, or full contract.",
2799
+ "Select the Mock / API strategy only in the patch. Encode endpoint/fixture mapping, explicit activation, verification commands, and Real Integration Gap in schema-defined editable fields; productionDefaultOff comes from the protected skeleton and there is no second plan output.",
2808
2800
  "Encode ordered steps (implementationSteps), target files, UI state handling, styling/component strategy (stylingStrategy), interaction notes, Mock/API strategy, dependency policy (dependencyPolicy), deterministic verification entrypoints, Real Integration Gap (realIntegrationGap), and residual risks (residualRisks) into the contract JSON fields. Use only the fixed entrypoints below; implementation may add tests behind them but cannot replace them.",
2809
2801
  "Every target file and verification target must be selected from the current target workspace and task scope. Do not reuse paths or symbols from examples, prior tasks, or loop-agent itself; if the project uses app/, packages/, spec/, __tests__, or another layout, preserve that layout.",
2810
2802
  "Consume the Scout TARGET_SURFACE evidence before selecting files. Preserve the discovered existing entrypoint and data source. If implementationPaths or testPaths are outside task allowedPaths, record a blocking scope conflict; do not substitute a new page or silently broaden the writeSet.",
2811
- "Output in this exact order: (1) exactly one fenced json object conforming to frontend-implementation-contract-v1 — this fenced block is the single authoritative contract the prewrite gate materializes; (2) exactly one openspec-citations citation fenced block appended immediately after it. Do NOT emit a Markdown plan explanation or any prose after the contract JSON the output is JSON-only. Do not emit any raw JSON or JSON objects in prose. Apart from the single contract JSON fenced block and the openspec-citations block, do not emit any other fenced block.",
2803
+ "Output in this exact order: (1) exactly one fenced json object containing the editable plan patch; (2) exactly one openspec-citations citation fenced block appended immediately after it. Do NOT emit protected skeleton fields, a full contract, Markdown plan explanation, raw JSON, or any other fenced block.",
2812
2804
  "Each requirement must state its user-observable or logic-observable expectedOutcome. Each interaction must state its trigger and expectedBehavior. IDs plus file paths are not sufficient behavior semantics.",
2813
2805
  requirementCoverageInstruction,
2814
2806
  "verificationTargets[].commandLabel MUST be one of the frozen command labels listed above. Any other value will be rejected at contract materialization.",
@@ -2836,7 +2828,7 @@ async function buildFrontendHybridDagFromTask(sources) {
2836
2828
  outputProtocol: REVIEW_VERDICT_OUTPUT_PROTOCOL,
2837
2829
  outputContract: "Plain Markdown whose first non-empty line is VERDICT: pass or VERDICT: request-revision, followed by Findings, Required Plan Corrections, and Checked Items. No file writes.",
2838
2830
  subtask_prompt: [
2839
- "Audit the frontend plan before implementation. Consume the contract JSON (the single fenced json block from frontend-plan-pi); there is no separate plan prose.",
2831
+ "Audit the frontend plan before implementation. frontend-plan-pi is emitted to you as canonical full-contract JSON after the runtime applied and validated the planner's editable patch against its protected skeleton; there is no separate plan prose.",
2840
2832
  "First non-empty line must be exactly VERDICT: pass or VERDICT: request-revision.",
2841
2833
  "Request revision when the Mock strategy is MOCK_STRATEGY: blocked, missing, unsupported by repository evidence, inconsistent with the API contract, outside authorized paths/dependencies, unable to prove production-default-off behavior with the fixed production/default-real-path static check, or missing deterministic behavior verification for a declared behavior target or selected Mock strategy. Mock strategies require Mock-backed evidence. A static-only contract is allowed only when every verification target is static and maps to a declared static entrypoint. not-needed otherwise requires applicable real/no-remote behavior evidence unless auto mode explicitly skipped Mock because no project Mock capability exists; in that case the plan must preserve the real request path and record the Real Integration Gap.",
2842
2834
  "Also request revision for missing applicable UI states, unsupported dependency additions, design-system drift without reason, weak interaction coverage, broad scope, inline fake data, schema drift, or missing deterministic verification commands.",
@@ -2869,7 +2861,7 @@ async function buildFrontendHybridDagFromTask(sources) {
2869
2861
  subtask_prompt: [
2870
2862
  "Consume frontend-plan-pi (original contract JSON) and frontend-design-review-pi (first design review findings).",
2871
2863
  "This node runs only when frontend-design-review-pi emitted VERDICT: request-revision. Produce an RFC 7386 merge-patch delta against the original contract JSON that addresses every Required Plan Correction from the design findings.",
2872
- "The patch delta may update any of these contract fields: requirements, implementationSteps, targets, uiStates, interactions, mockApi, dependencyPolicy, stylingStrategy, uiComponentChoices, verificationTargets, evidenceGaps, residualRisks, realIntegrationGap. Only include fields you change; omit unchanged fields (the gate applies the patch on the original contract). null deletes a key; arrays and scalars replace; plain objects merge recursively.",
2864
+ "The patch delta may update editable contract fields such as requirements, implementationSteps, targets.routes/publicApiChanges, uiStates, interactions, mockApi.strategy/activation/endpoints, dependencyPolicy, stylingStrategy, uiComponentChoices, verificationTargets, evidenceGaps, residualRisks, and realIntegrationGap. It must not modify protected schemaVersion, sourceBinding, riskLevel, targets.files, or mockApi.productionDefaultOff. Only include fields you change; omit unchanged fields (the gate applies the patch on the original contract). null deletes a key; arrays and scalars replace; plain objects merge recursively.",
2873
2865
  requirementCoverageInstruction,
2874
2866
  "Do not turn MOCK_STRATEGY: blocked into an implementable strategy without new repository or contract evidence that resolves every blocker.",
2875
2867
  "Read-only: do not modify code, docs, artifacts, or repository files. This node revises the plan only.",
@@ -3592,7 +3584,7 @@ function buildExecuteBackendPytestNode(sources, options = {}) {
3592
3584
  // the current DAG run and moves with active → completed/paused lifecycle.
3593
3585
  // Adapter default testRoot is frozen at DAG generation time (auditable) and
3594
3586
  // cross-checked against the materialized execution contract in preflight.
3595
- const frozenTestRoot = BACKEND_TEST_EXECUTION_DEFAULT_TEST_ROOT;
3587
+ const frozenTestRoot = options.testRoot ?? BACKEND_TEST_EXECUTION_DEFAULT_TEST_ROOT;
3596
3588
  const preflightCommand = buildBackendTestExecutionPreflightShellSnippet({
3597
3589
  expectedTestRoot: frozenTestRoot,
3598
3590
  });
@@ -3794,6 +3786,25 @@ const BACKEND_TEST_DEFAULTS = {
3794
3786
  ...HYBRID_DEFAULTS,
3795
3787
  writePolicy: "read-only",
3796
3788
  };
3789
+ /**
3790
+ * Runtime layout rewriter for backend-test node prompts and contracts (plan A).
3791
+ *
3792
+ * Node prompts and output contracts historically hardcode the default
3793
+ * `testcase/` layout. Instead of duplicating every prompt string as a
3794
+ * template, builders keep the historical literal text and this helper
3795
+ * rewrites it against the resolved layout at DAG compile time. The default
3796
+ * layout maps every token to itself, so the packaged template stays
3797
+ * byte-identical with the historical contract.
3798
+ */
3799
+ export function applyBackendTestLayoutToText(text, layout) {
3800
+ if (layout.isDefault)
3801
+ return text;
3802
+ return text
3803
+ .replaceAll("testcase/md/", `${layout.markdownDir}/`)
3804
+ .replaceAll("testcase/test_", `${layout.scriptDir}/test_`)
3805
+ .replaceAll("testcase/**", `${layout.testRoot}/**`)
3806
+ .replaceAll("testcase/", `${layout.testRoot}/`);
3807
+ }
3797
3808
  /**
3798
3809
  * Builds the `node -e` command for the backend-test module manifest shell.
3799
3810
  * The inline JS mirrors `extractModuleStemsFromReadme` so the map_agent
@@ -3804,34 +3815,50 @@ const BACKEND_TEST_DEFAULTS = {
3804
3815
  * normalization. Output is exactly one trailing JSON line `{modules:[{stem}]}`
3805
3816
  * that `parseJsonFromText` accepts after shell command echoes.
3806
3817
  */
3807
- function buildBackendTestModuleManifestShellCommand() {
3818
+ function buildBackendTestModuleManifestShellCommand(layout) {
3808
3819
  // The extractor is base64-encoded so the shell command is fully opaque to
3809
3820
  // bash: no backticks (command substitution), no regex \/ escaping, no
3810
3821
  // backslash-counting through TS-string -> JSON.stringify -> bash -c -> node -e.
3811
3822
  // Backticks in the README body are stripped at runtime via
3812
3823
  // String.fromCharCode(96), so the extractor source contains no backtick.
3824
+ // mdDir/testPrefix are injected as JSON literals so the same extractor
3825
+ // works for any configured backendTest layout (plan A).
3826
+ const mdDirLiteral = JSON.stringify(layout.markdownDir);
3827
+ const testPrefixLiteral = JSON.stringify(`${layout.scriptDir}/test_`);
3828
+ const escOpen = String.fromCharCode(92, 91); // \[
3829
+ const escClose = String.fromCharCode(92, 93); // \]
3830
+ const escBslash = String.fromCharCode(92, 92); // \\
3813
3831
  const script = `const fs=require('fs');
3814
- const readme=fs.existsSync('testcase/md/README.md')?fs.readFileSync('testcase/md/README.md','utf8'):'';
3832
+ const mdDir=${mdDirLiteral};
3833
+ const testPrefix=${testPrefixLiteral};
3834
+ const esc=s=>s.replace(/[${escOpen}${escClose}{}()*+?^$|${escBslash}]/g,'${escBslash}$&');
3835
+ const rxMdPath=new RegExp(esc(mdDir)+'${escBslash}/([A-Za-z0-9_.-]+)${escBslash}.md','g');
3836
+ const rxTableRow=new RegExp('${escBslash}|${escBslash}s*([A-Za-z0-9_.-]+)${escBslash}s*${escBslash}|${escBslash}s*'+esc(testPrefix),'g');
3837
+ const readme=fs.existsSync(mdDir+'/README.md')?fs.readFileSync(mdDir+'/README.md','utf8'):'';
3815
3838
  const norm=s=>String(s).toLowerCase().replace(/[^a-z0-9]+/g,'_').replace(/^_+|_+$/g,'').replace(/_+/g,'_');
3816
3839
  const bt=String.fromCharCode(96);
3817
3840
  const stripBackticks=s=>s.split(bt).join('');
3818
- const invalidReason=raw=>{const st=norm(raw);if(/^p[0-2]$/.test(st))return 'priority-only-module-stem';if(st==='readme')return 'reserved-module-stem';if(!/^[a-z][a-z0-9_]*$/.test(st))return 'invalid-syntax';if(/^(?:be|tp|ac|req|br)[_-]/i.test(st))return 'case-like-module-stem';return null;};
3841
+ const invalidReason=raw=>{const st=norm(raw);if(/^p[0-2]$/.test(st))return 'priority-only-module-stem';if(/^[a-f][a-f0-9]{6,63}$/.test(st))return 'opaque-hash-module-stem';if(st==='readme')return 'reserved-module-stem';if(!/^[a-z][a-z0-9_]*$/.test(st))return 'invalid-syntax';if(/^(?:be|tp|ac|req|br)[_-]/i.test(st))return 'case-like-module-stem';return null;};
3819
3842
  const valid=raw=>invalidReason(raw)===null;
3820
- const rxMdPath=/testcase\\/md\\/([A-Za-z0-9_.-]+)\\.md/g;
3821
- const rxTableRow=/\\|\\s*([A-Za-z0-9_.-]+)\\s*\\|\\s*testcase\\/test_/g;
3822
3843
  const rxRelLink=/\\[[^\\]]+\\]\\(\\.\\/([A-Za-z0-9_.-]+)\\.md\\)/g;
3844
+ const allLines=readme.replace(/\\r\\n/g,'\\n').replace(/\\r/g,'\\n').split('\\n');
3845
+ const headings=[];for(let i=0;i<allLines.length;i++){if(allLines[i].trim()==='## Module Index')headings.push(i);}
3846
+ if(headings.length!==1){process.stderr.write((headings.length===0?'missing-module-index':'duplicate-module-index')+'; require exactly one exact ## Module Index section\\n');process.exit(2);}
3847
+ const start=headings[0]+1;let end=allLines.length;for(let i=start;i<allLines.length;i++){if(/^##\\s+\\S/.test(allLines[i].trim())){end=i;break;}}
3848
+ const section=allLines.slice(start,end).join('\\n');
3823
3849
  const raw=[];
3824
- const lines=readme.replace(/\\r\\n/g,'\\n').replace(/\\r/g,'\\n').split('\\n').filter(l=>l.includes('|'));
3850
+ const lines=section.split('\\n').filter(l=>l.includes('|'));
3825
3851
  for(const line of lines){
3826
3852
  const bare=stripBackticks(line);
3827
3853
  for(const m of bare.matchAll(rxMdPath)){raw.push(m[1]);}
3828
- for(const m of bare.matchAll(rxTableRow)){if(valid(m[1])||invalidReason(m[1])==='priority-only-module-stem')raw.push(m[1]);}
3854
+ for(const m of bare.matchAll(rxTableRow)){if(valid(m[1])||invalidReason(m[1])!=='invalid-syntax')raw.push(m[1]);}
3829
3855
  }
3830
- for(const m of readme.matchAll(rxRelLink)){raw.push(m[1]);}
3856
+ for(const m of section.matchAll(rxRelLink)){raw.push(m[1]);}
3831
3857
  const invalid=[];for(const r of raw){const reason=invalidReason(r);if(reason)invalid.push({stem:norm(r),reason});}
3832
3858
  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);}
3833
3859
  const seen=new Set();const modules=[];
3834
3860
  for(const r of raw){const st=norm(r);if(valid(r)&&!seen.has(st)){seen.add(st);modules.push({stem:st});}}
3861
+ 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);}
3835
3862
  process.stdout.write(JSON.stringify({modules}));
3836
3863
  `;
3837
3864
  const encoded = Buffer.from(script, "utf8").toString("base64");
@@ -3845,11 +3872,443 @@ const BACKEND_TEST_SKILLS_BY_ROLE = {
3845
3872
  verifier: ["verification-before-completion", "systematic-debugging"],
3846
3873
  closeout: ["loop-agent", "verification-before-completion"],
3847
3874
  };
3875
+ /**
3876
+ * Plan D: gap-fill incremental DAG (mode=gap-fill).
3877
+ *
3878
+ * Re-runs the SAME requirement against a `backend-test-gap-v1` document and
3879
+ * the previous N6 coverage facts. Deterministic ingest plans exact
3880
+ * targetPaths; writers only patch planned files, never renumber Case IDs,
3881
+ * and a satisfied plan short-circuits writers with already-satisfied. The
3882
+ * heavy full-chain nodes (README rewrite, full-source N5 sync, helpers)
3883
+ * are replaced by patch writers whose writeSet equals the planned files.
3884
+ */
3885
+ async function buildBackendTestGapFillDag(sources) {
3886
+ const { taskConfig } = sources;
3887
+ const ro = commonReadOnlyPaths(sources);
3888
+ const forbidden = commonForbiddenPaths(sources);
3889
+ const intake = await buildBackendTestIntakeContext(sources);
3890
+ const layout = resolveBackendTestLayout(taskConfig.backendTest);
3891
+ const sharedSetup = intake.sharedSetup;
3892
+ const gapDocPath = taskConfig.backendTest?.gapDoc?.trim();
3893
+ if (!gapDocPath) {
3894
+ throw new Error("backendTest.mode=gap-fill requires backendTest.gapDoc pointing at the user missing-scenario document");
3895
+ }
3896
+ const envAllowlist = collectBackendTestShellEnvAllowlist(sources);
3897
+ // N1: reuse the full-chain environment validation unchanged.
3898
+ const environment = {
3899
+ id: "validate-backend-test-environment-shell",
3900
+ depends_on: [],
3901
+ role: "verifier",
3902
+ executor: "shell",
3903
+ complexity: "LOW",
3904
+ writePolicy: "read-only",
3905
+ allowedPaths: ro,
3906
+ forbiddenPaths: forbidden,
3907
+ outputContract: "Run-owned reports/backend-test-environment.md with PASS/FAIL runtime, bounded project discovery, fixture and HTML-renderer facts; no secret values.",
3908
+ subtask_prompt: "Fail fast before model work when Python/pytest cannot run in the clean shell. Inspect only bounded common config, conftest, test-root and server-entry candidates; never read .env values or credentials.",
3909
+ shell: {
3910
+ commands: ["python --version", "python -m pytest --version", "python -m pytest --help"],
3911
+ backendTestPipeline: "markdown-environment",
3912
+ cwd: ".",
3913
+ timeoutMs: 60000,
3914
+ envAllowlist,
3915
+ },
3916
+ };
3917
+ // N2': deterministic gap ingest (shell pipeline owns parsing + planning).
3918
+ const ingestGap = {
3919
+ id: "ingest-backend-test-gap-shell",
3920
+ depends_on: [environment.id],
3921
+ role: "verifier",
3922
+ executor: "shell",
3923
+ complexity: "LOW",
3924
+ writePolicy: "read-only",
3925
+ allowedPaths: ro,
3926
+ forbiddenPaths: forbidden,
3927
+ outputContract: "Run-owned contracts/backend-test-gap-plan-v1.json with targetModules, newTestPoints, reuseSetupRefs, conflicts, alreadyPresent and exact targetPaths; identity mismatch (taskId/requirement hash) fails closed before any writer runs.",
3928
+ subtask_prompt: "Parse the bound gap document (backend-test-gap-v1) and union it with previous coverage facts missingSlots; emit the deterministic gap plan. No file writes to testcase assets.",
3929
+ shell: {
3930
+ commands: [],
3931
+ backendTestPipeline: "ingest-backend-test-gap",
3932
+ cwd: ".",
3933
+ timeoutMs: 60000,
3934
+ envAllowlist,
3935
+ },
3936
+ };
3937
+ // N3': patch README Matrix/Partitions for planned slots only.
3938
+ const patchReadme = {
3939
+ id: "patch-backend-readme-matrix-pi",
3940
+ depends_on: [ingestGap.id],
3941
+ role: "implementer",
3942
+ executor: "pi",
3943
+ toolProfile: "write",
3944
+ complexity: "LOW",
3945
+ writePolicy: "exclusive",
3946
+ writeSet: [layout.readmePath],
3947
+ allowedPaths: [layout.readmePath],
3948
+ forbiddenPaths: forbidden,
3949
+ writerOutcomePolicy: {
3950
+ type: "implementation-outcome-v1",
3951
+ requireChangedFiles: false,
3952
+ },
3953
+ retryPolicy: BACKEND_TEST_WRITER_COMPLETENESS_RETRY_POLICY,
3954
+ outputContract: "First non-empty line is IMPLEMENTATION_OUTCOME: changed|already-satisfied|blocked. Patch ONLY the Coverage Matrix rows and Scenario Partitions table entries named by contracts/backend-test-gap-plan-v1.json newTestPoints; never rewrite unrelated README sections, never renumber Cases, never add Module Index modules.",
3955
+ subtask_prompt: [
3956
+ "Read contracts/backend-test-gap-plan-v1.json. For each planned slot in newTestPoints, patch the owning Coverage Matrix row (Required Test Points/Case IDs) and, for TP-SP slots, the Scenario Partitions table so the slot is declared. already-satisfied is valid when every planned slot is already present; changed requires a bounded diff limited to the slot rows.",
3957
+ "When every planned slot is already declared, return already-satisfied without editing. Never expand scope beyond newTestPoints; never touch module Markdown or pytest files here.",
3958
+ intake.boundedSourceContext,
3959
+ ].join("\n\n"),
3960
+ };
3961
+ // N4': patch only the planned module Markdown files (map over targetModules).
3962
+ const patchMdCases = {
3963
+ id: "patch-backend-md-cases-map",
3964
+ depends_on: [patchReadme.id],
3965
+ role: "verifier",
3966
+ executor: "static",
3967
+ complexity: "LOW",
3968
+ writePolicy: "none",
3969
+ allowedPaths: [],
3970
+ forbiddenPaths: forbidden,
3971
+ outputContract: "Serial aggregate of per-module Markdown patch writers; each child writes exactly one planned testcase module file with a bounded append/patch diff.",
3972
+ subtask_prompt: "Expand the gap plan targetModules into one sharded Markdown patch writer child per module and run them serially. Child failures fail-close the map barrier.",
3973
+ static: {
3974
+ resultMarkdown: "Backend-test gap-fill Markdown patch map expansion barrier.",
3975
+ },
3976
+ dynamicExpansion: {
3977
+ type: "map_agent",
3978
+ workflowNodeId: "patch-backend-md-cases-map",
3979
+ itemsFrom: "$.nodes['ingest-backend-test-gap-shell'].json.plan.targetModules",
3980
+ itemName: "item",
3981
+ maxItems: 8,
3982
+ maxExpandedNodes: 8,
3983
+ childIdPrefix: "patch-backend-md-case",
3984
+ tokenBudget: { maxTotalTokens: 1000000 },
3985
+ failOnTokenBudgetExhaustion: true,
3986
+ childTask: {
3987
+ executor: "pi",
3988
+ role: "implementer",
3989
+ skills: BACKEND_TEST_SKILLS_BY_ROLE.implementer,
3990
+ toolProfile: "write",
3991
+ complexity: "LOW",
3992
+ writePolicy: "exclusive",
3993
+ allowedPaths: [`${layout.markdownDir}/{{item.stem}}.md`],
3994
+ forbiddenPaths: forbidden,
3995
+ writeSet: [`${layout.markdownDir}/{{item.stem}}.md`],
3996
+ writerOutcomePolicy: {
3997
+ type: "implementation-outcome-v1",
3998
+ requireChangedFiles: false,
3999
+ },
4000
+ retryPolicy: BACKEND_TEST_WRITER_COMPLETENESS_RETRY_POLICY,
4001
+ outputContract: "Patch exactly one planned module Markdown file: add missing slot Test Points (existing Case variant lists first; new BE-<MODULE>-<max+1> Case only when no Case can own the slot). Case IDs are never renumbered; sections follow the full-chain contract.",
4002
+ subtaskPromptTemplate: [
4003
+ "Read contracts/backend-test-gap-plan-v1.json and patch exactly testcase/md/{{item.stem}}.md. For every planned slot owned by this module: prefer appending the variant to the Case named by the plan (or the most related existing Case); create a new Case only when no existing Case can own it, numbering BE-<MODULE>-<NNN> from the module's current maximum +1. Keep every required h3 section; cite Matrix Rule Keys exactly; TP-SP slots use the exact deterministic slot IDs from the plan.",
4004
+ sharedSetup
4005
+ ? `When the slot needs shared pre-steps defined by the bound user document, reference them with 引用前置: ${sharedSetup.path}#<SS-ID|SS-DEFAULT> instead of duplicating steps.`
4006
+ : "Prepare any needed state locally inside this Case (本地准备); no shared setup document is bound.",
4007
+ "already-satisfied is valid when every planned slot of this module is already covered. Never modify other modules, README, or pytest files.",
4008
+ intake.boundedSourceContext,
4009
+ ].join("\n\n"),
4010
+ },
4011
+ },
4012
+ };
4013
+ // N5': validate patched Markdown with the same N6 pipeline (partition slots fail-closed).
4014
+ const validateMd = {
4015
+ id: "validate-backend-md-cases-shell",
4016
+ depends_on: [patchMdCases.id],
4017
+ role: "verifier",
4018
+ executor: "shell",
4019
+ complexity: "LOW",
4020
+ writePolicy: "read-only",
4021
+ allowedPaths: ro,
4022
+ forbiddenPaths: forbidden,
4023
+ outputContract: "Run-owned reports/backend-md-case-validation.md, coverage analysis and facts v4 with scenarioPartitions; planned slots must be covered (missingSlots for planned entries fail closed).",
4024
+ subtask_prompt: "Record advisory findings for Markdown structure and deterministically analyze the final README Coverage Scope, Coverage Matrix and Scenario Partitions against final Case rule/test-point bindings. Planned gap slots that remain uncovered fail this node closed.",
4025
+ shell: {
4026
+ commands: [],
4027
+ backendTestPipeline: "markdown-cases",
4028
+ cwd: ".",
4029
+ timeoutMs: 60000,
4030
+ envAllowlist,
4031
+ },
4032
+ };
4033
+ // N6': patch only the planned pytest modules (append params/functions).
4034
+ const patchPytest = {
4035
+ id: "patch-backend-pytest-cases-map",
4036
+ depends_on: [validateMd.id],
4037
+ role: "verifier",
4038
+ executor: "static",
4039
+ complexity: "LOW",
4040
+ writePolicy: "none",
4041
+ allowedPaths: [],
4042
+ forbiddenPaths: forbidden,
4043
+ outputContract: "Serial aggregate of per-module pytest patch writers; each child appends to exactly one planned testcase/test_<stem>.py without rewriting the file.",
4044
+ subtask_prompt: "Expand the gap plan targetModules into one sharded pytest patch writer child per module and run them serially. Child failures fail-close the map barrier.",
4045
+ static: {
4046
+ resultMarkdown: "Backend-test gap-fill pytest patch map expansion barrier.",
4047
+ },
4048
+ dynamicExpansion: {
4049
+ type: "map_agent",
4050
+ workflowNodeId: "patch-backend-pytest-cases-map",
4051
+ itemsFrom: "$.nodes['ingest-backend-test-gap-shell'].json.plan.targetModules",
4052
+ itemName: "item",
4053
+ maxItems: 8,
4054
+ maxExpandedNodes: 8,
4055
+ childIdPrefix: "patch-backend-pytest-case",
4056
+ tokenBudget: { maxTotalTokens: 1000000 },
4057
+ failOnTokenBudgetExhaustion: true,
4058
+ childTask: {
4059
+ executor: "pi",
4060
+ role: "implementer",
4061
+ skills: BACKEND_TEST_SKILLS_BY_ROLE.implementer,
4062
+ toolProfile: "write",
4063
+ complexity: "LOW",
4064
+ writePolicy: "exclusive",
4065
+ allowedPaths: [`${layout.scriptDir}/test_{{item.stem}}.py`],
4066
+ forbiddenPaths: Array.from(new Set([
4067
+ ...forbidden,
4068
+ `${layout.markdownDir}/**`,
4069
+ "conftest.py",
4070
+ "pytest.ini",
4071
+ "pyproject.toml",
4072
+ "setup.cfg",
4073
+ ])),
4074
+ writeSet: [`${layout.scriptDir}/test_{{item.stem}}.py`],
4075
+ writerOutcomePolicy: {
4076
+ type: "implementation-outcome-v1",
4077
+ requireChangedFiles: false,
4078
+ },
4079
+ retryPolicy: BACKEND_TEST_WRITER_COMPLETENESS_RETRY_POLICY,
4080
+ outputContract: "Append-only patch of exactly one planned pytest module: add pytest.param rows / test functions for planned slots with exact TP ids; never rewrite or delete existing functions.",
4081
+ subtaskPromptTemplate: [
4082
+ "Read contracts/backend-test-gap-plan-v1.json and the patched module Markdown, then patch only testcase/test_{{item.stem}}.py. For each planned slot owned by this module: append an exact literal pytest.param(..., id=\"<slot-id>\") row to the owning Case's primary symbol, or append a new test function test_BE_<MODULE>_<NNN>_<desc> when a new Case was created. Existing functions, params and assertions must remain byte-stable; append-only edits.",
4083
+ sharedSetup
4084
+ ? "Reuse the module-top user_shared_setup fixture for shared pre-steps; never re-create documented setup steps inside test bodies, and never create or modify conftest.py."
4085
+ : "Keep any needed setup local to the new function; never create or modify conftest.py.",
4086
+ "already-satisfied is valid when every planned slot already has its exact pytest.param id collected. Do not modify Markdown or other modules.",
4087
+ ].join("\n\n"),
4088
+ },
4089
+ },
4090
+ };
4091
+ // N7'-N13': reuse the deterministic collection/repair/gate/trace/manifest chain.
4092
+ const collectionAssess = {
4093
+ id: "assess-backend-pytest-collection-shell",
4094
+ depends_on: [patchPytest.id],
4095
+ role: "verifier",
4096
+ executor: "shell",
4097
+ complexity: "LOW",
4098
+ writePolicy: "read-only",
4099
+ allowedPaths: ro,
4100
+ forbiddenPaths: forbidden,
4101
+ outputContract: "Run-owned collection-v3 facts with repairPaths limited to the gap plan target pytest files.",
4102
+ subtask_prompt: "Resolve final Markdown-mapped scripts; scenario-param assess, pytest --collect-only and no-business-body fixture preflight. Repair eligibility is limited to planned pytest files.",
4103
+ shell: {
4104
+ commands: [],
4105
+ backendTestPipeline: "markdown-collection-assess",
4106
+ cwd: ".",
4107
+ timeoutMs: 120000,
4108
+ envAllowlist,
4109
+ },
4110
+ };
4111
+ const repairPytest = {
4112
+ id: "repair-backend-pytest-collection-pi",
4113
+ depends_on: [collectionAssess.id],
4114
+ runIf: "$.nodes['assess-backend-pytest-collection-shell'].json.repairEligible == true",
4115
+ role: "implementer",
4116
+ executor: "pi",
4117
+ toolProfile: "write",
4118
+ complexity: "MED",
4119
+ writePolicy: "exclusive",
4120
+ writeSet: [`${layout.scriptDir}/test_*.py`],
4121
+ allowedPaths: Array.from(new Set([...ro, layout.scriptDir])),
4122
+ forbiddenPaths: Array.from(new Set([
4123
+ ...forbidden,
4124
+ `${layout.markdownDir}/**`,
4125
+ "conftest.py",
4126
+ "pytest.ini",
4127
+ "pyproject.toml",
4128
+ "setup.cfg",
4129
+ ])),
4130
+ writerOutcomePolicy: { type: "implementation-outcome-v1", requireChangedFiles: true },
4131
+ outputContract: "First non-empty line is IMPLEMENTATION_OUTCOME: changed|blocked. Repair only generated pytest defects on initial facts repairPaths; preserve every Markdown Case, Test Point, primary symbol and assertion meaning.",
4132
+ subtask_prompt: [
4133
+ "Repair the generated backend pytest asset as one bounded program using the direct upstream collection assessment. Treat any upstream `Repair paths:` line as complete authoritative repairPaths evidence. Only planned testcase test_*.py files may change.",
4134
+ "Do not modify Markdown, conftest, pytest config, production code or dependencies. Do not add skip/xfail, remove tests, loosen assertions or replace the real API with mocks.",
4135
+ ].join("\n\n"),
4136
+ };
4137
+ const collectionEffective = {
4138
+ id: "effective-backend-pytest-collection-gate-shell",
4139
+ depends_on: [collectionAssess.id, repairPytest.id],
4140
+ role: "verifier",
4141
+ executor: "shell",
4142
+ complexity: "LOW",
4143
+ writePolicy: "read-only",
4144
+ allowedPaths: ro,
4145
+ forbiddenPaths: forbidden,
4146
+ outputContract: "Canonical backend-test-execution-readiness.json v2 bound to final asset hashes.",
4147
+ subtask_prompt: "Materialize effective collection facts; eligibility excludes non-exact mappings and unsafe payloads as in the full chain.",
4148
+ shell: {
4149
+ commands: [],
4150
+ backendTestPipeline: "markdown-collection-effective",
4151
+ cwd: ".",
4152
+ timeoutMs: 120000,
4153
+ envAllowlist,
4154
+ },
4155
+ };
4156
+ collectionEffective.dependsPolicy = "all-or-condition-skip";
4157
+ const traceability = {
4158
+ id: "backend-test-traceability-gate-shell",
4159
+ depends_on: [collectionEffective.id],
4160
+ role: "verifier",
4161
+ executor: "shell",
4162
+ complexity: "LOW",
4163
+ writePolicy: "read-only",
4164
+ allowedPaths: ro,
4165
+ forbiddenPaths: forbidden,
4166
+ outputContract: "Run-owned traceability and correspondence facts bound after effective collection.",
4167
+ subtask_prompt: "Deterministically scan final readiness-authorized Markdown-mapped pytest scripts; correspondence findings stay advisory.",
4168
+ shell: {
4169
+ commands: [],
4170
+ backendTestPipeline: "markdown-traceability",
4171
+ cwd: ".",
4172
+ timeoutMs: 60000,
4173
+ envAllowlist,
4174
+ },
4175
+ };
4176
+ const manifest = {
4177
+ id: "backend-test-case-manifest-shell",
4178
+ depends_on: [traceability.id],
4179
+ role: "verifier",
4180
+ executor: "shell",
4181
+ complexity: "LOW",
4182
+ writePolicy: "read-only",
4183
+ allowedPaths: ro,
4184
+ forbiddenPaths: forbidden,
4185
+ outputContract: "Run-owned contracts/backend-test-case-manifest.json materialized only from facts; the single machine input for L-5 and closeout.",
4186
+ subtask_prompt: "Materialize the canonical Backend Test Case Manifest only from coverage and correspondence facts; never re-analyze sources.",
4187
+ shell: {
4188
+ commands: [],
4189
+ backendTestPipeline: "markdown-manifest",
4190
+ cwd: ".",
4191
+ timeoutMs: 60000,
4192
+ envAllowlist,
4193
+ },
4194
+ };
4195
+ const execute = {
4196
+ id: "execute-backend-pytest-and-html-report-shell",
4197
+ depends_on: [manifest.id],
4198
+ role: "verifier",
4199
+ executor: "shell",
4200
+ complexity: "LOW",
4201
+ writePolicy: "read-only",
4202
+ allowedPaths: ro,
4203
+ forbiddenPaths: forbidden,
4204
+ outputContract: "One scoped pytest execution over readiness-authorized eligible items producing pytest-html plus the Chinese HTML report and L-5 dashboard; exit 0/1 with valid evidence continues.",
4205
+ subtask_prompt: `Execute readiness-authorized eligible pytest items once${taskConfig.backendTest?.executeScope === "all"
4206
+ ? " (executeScope=all: every eligible item)"
4207
+ : " (executeScope=affected: prefer newly added planned items when readiness marks them; otherwise every eligible item)"}, render the report, and keep evidence run-owned.`,
4208
+ shell: {
4209
+ commands: [],
4210
+ backendTestPipeline: "markdown-execute-html",
4211
+ cwd: ".",
4212
+ timeoutMs: 300000,
4213
+ envAllowlist,
4214
+ },
4215
+ };
4216
+ const report = {
4217
+ id: "backend-test-report-shell",
4218
+ depends_on: [execute.id],
4219
+ role: "verifier",
4220
+ executor: "shell",
4221
+ complexity: "LOW",
4222
+ writePolicy: "read-only",
4223
+ allowedPaths: ro,
4224
+ forbiddenPaths: forbidden,
4225
+ outputContract: "Run-owned backend test Result v1 with pytestExitCode, junit and evidence hashes; failure categories keep product/automation semantics.",
4226
+ subtask_prompt: "Materialize the backend-test Result v1 from the execution evidence; never fabricate metrics.",
4227
+ shell: {
4228
+ commands: [],
4229
+ backendTestPipeline: "markdown-report",
4230
+ cwd: ".",
4231
+ timeoutMs: 60000,
4232
+ envAllowlist,
4233
+ },
4234
+ };
4235
+ const spec = {
4236
+ version: 3,
4237
+ title: `Backend test gap-fill: ${sources.taskId}`,
4238
+ runtimeContract: GENERATED_DAG_RUNTIME_CONTRACT,
4239
+ outputLanguage: sources.outputLanguage ?? DEFAULT_DAG_OUTPUT_LANGUAGE,
4240
+ objective: `Incrementally fill backend-test gap scenarios for task ${sources.taskId} from the bound gap document without renumbering existing Cases.`,
4241
+ successCriteria: [
4242
+ "Every planned gap slot is declared in README (Matrix/Scenario Partitions), covered by a Case test point, and collected as an exact pytest.param id",
4243
+ "Existing Case IDs and unrelated modules remain byte-stable; no conftest.py is created or modified",
4244
+ "A second run over a satisfied plan returns already-satisfied with no asset diff",
4245
+ ],
4246
+ globalConstraints: [
4247
+ ...sources.taskConfig.hardConstraints.filter(Boolean),
4248
+ `backendTestGapDoc=${gapDocPath}`,
4249
+ `backendTestExecuteScope=${taskConfig.backendTest?.executeScope ?? "affected"}`,
4250
+ ],
4251
+ skillsByRole: BACKEND_TEST_SKILLS_BY_ROLE,
4252
+ executorModels: sources.executorModelMatrix ?? DEFAULT_DAG_EXECUTOR_MODELS,
4253
+ verifyStrategy: resolveDagVerifyStrategy(taskConfig),
4254
+ tasks: [
4255
+ environment,
4256
+ ingestGap,
4257
+ patchReadme,
4258
+ patchMdCases,
4259
+ validateMd,
4260
+ patchPytest,
4261
+ collectionAssess,
4262
+ repairPytest,
4263
+ collectionEffective,
4264
+ traceability,
4265
+ manifest,
4266
+ execute,
4267
+ report,
4268
+ ],
4269
+ };
4270
+ spec.backendTestLayout = layout;
4271
+ if (sharedSetup) {
4272
+ spec.backendTestSharedSetup = { ...sharedSetup };
4273
+ }
4274
+ applyDefaultReadOnlyRetryPolicy(spec);
4275
+ parseDagSpec(spec);
4276
+ assertValidDagSpec(spec);
4277
+ return spec;
4278
+ }
3848
4279
  async function buildBackendTestHybridDag(sources) {
3849
4280
  const { taskConfig } = sources;
4281
+ if (taskConfig.backendTest?.mode === "gap-fill") {
4282
+ return buildBackendTestGapFillDag(sources);
4283
+ }
3850
4284
  const ro = commonReadOnlyPaths(sources);
3851
4285
  const forbidden = commonForbiddenPaths(sources);
3852
4286
  const intake = await buildBackendTestIntakeContext(sources);
4287
+ // Plan A: resolve the frozen artifact layout once; every generated path
4288
+ // (README, module Markdown, pytest script, pytest target) derives from it.
4289
+ // Default config resolves to the historical testcase/ layout.
4290
+ const layout = resolveBackendTestLayout(taskConfig.backendTest);
4291
+ const applyLayout = (text) => applyBackendTestLayoutToText(text, layout);
4292
+ // Plan B: when the user binds exactly one shared-setup document, generated
4293
+ // Markdown references it (引用前置/SS-*) and each pytest module hoists the
4294
+ // documented steps into a module-top `user_shared_setup` fixture. Absent the
4295
+ // binding, every prompt below stays byte-identical to the pre-B baseline.
4296
+ const sharedSetup = intake.sharedSetup;
4297
+ const sharedSetupPrompt = sharedSetup
4298
+ ? [
4299
+ "## User shared setup document (bound, read-only)",
4300
+ `A user-provided shared pre-step document is bound at \`${sharedSetup.path}\` (readPath \`${sharedSetup.readPath}\`, sha256 ${sharedSetup.sha256}). Treat it as an authoritative read-only source: never rewrite, split or renumber it, and never invent steps absent from it.`,
4301
+ "When a Case needs a pre-step that this document already defines, the Case MUST reference it instead of duplicating the steps: in `### 前置条件` write `引用前置: <bound-path>#<SS-ID or heading>` lines (plus a `Shared Setup Refs` list of the referenced SS IDs). Extract stable step IDs only from explicit machine IDs (e.g. `SS-1`, `SS-REGISTER-01`); when the document is prose without stable IDs, reference the whole document as `引用前置: <bound-path>#SS-DEFAULT` and do not guess splits. Preparation unique to a Case stays inline but must be labeled `本地准备:`.",
4302
+ "Payload Contract still describes ONLY the target request; setup POST/PUT steps defined by the shared document never redefine the target Case payload contract.",
4303
+ ].join("\n\n")
4304
+ : null;
4305
+ const sharedSetupPytestPrompt = sharedSetup
4306
+ ? [
4307
+ "## User shared setup hoisting (module top)",
4308
+ `The user shared setup document \`${sharedSetup.path}\` (readPath \`${sharedSetup.readPath}\`) defines the common pre-steps. At the TOP of this module file (before any test function), generate exactly one module-scoped fixture named \`user_shared_setup\` implemented by a private helper \`_user_shared_setup()\` that performs the documented shared steps in document order, using the exact resource names/fields from the document. Cases reference these steps via their \`引用前置\` lines; each \`test_BE_*\` body then performs ONLY its target operation and must not repeat documented shared create/setup steps. Generate teardown code only when the user document explicitly documents a cleanup step; never invent a DELETE.`,
4309
+ "Duplication of this prefix across module files is accepted by design: do not extract it into conftest.py, a shared helper module, pytest_plugins, or a `_shared_setup.py`; the module file stays self-contained. NEVER create or modify conftest.py.",
4310
+ ].join("\n\n")
4311
+ : null;
3853
4312
  const shellNode = (id, depends_on, pipeline, prompt, outputContract, commands = [], timeoutMs = 60000) => ({
3854
4313
  id,
3855
4314
  depends_on,
@@ -3909,8 +4368,10 @@ async function buildBackendTestHybridDag(sources) {
3909
4368
  "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.",
3910
4369
  "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.",
3911
4370
  "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.",
3912
- "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 budget, and keep the total module count at the smallest safe value. Name each module file with a stable lowercase business stem such as `health` or `resource_notes`. 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.",
4371
+ "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.",
4372
+ "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. Cross-axis combinations stay as ONE nominal Case; never declare a cross-axis cartesian partition.",
3913
4373
  "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.",
4374
+ ...(sharedSetupPrompt ? [sharedSetupPrompt] : []),
3914
4375
  intake.boundedSourceContext,
3915
4376
  "## Authoritative reference index",
3916
4377
  JSON.stringify(intake.referenceIndex, null, 2),
@@ -3930,7 +4391,7 @@ async function buildBackendTestHybridDag(sources) {
3930
4391
  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.",
3931
4392
  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.",
3932
4393
  shell: {
3933
- commands: [buildBackendTestModuleManifestShellCommand()],
4394
+ commands: [buildBackendTestModuleManifestShellCommand(layout)],
3934
4395
  cwd: ".",
3935
4396
  timeoutMs: 60000,
3936
4397
  },
@@ -3954,10 +4415,11 @@ async function buildBackendTestHybridDag(sources) {
3954
4415
  workflowNodeId: "generate-backend-md-cases-map",
3955
4416
  itemsFrom: "$.nodes['materialize-backend-md-module-manifest-shell'].output.modules",
3956
4417
  itemName: "item",
3957
- maxItems: 64,
3958
- maxExpandedNodes: 64,
4418
+ maxItems: 8,
4419
+ maxExpandedNodes: 8,
3959
4420
  childIdPrefix: "generate-backend-md-case",
3960
- tokenBudget: { maxTokensPerCase: 16384, maxTotalTokens: 600000 },
4421
+ tokenBudget: { maxTotalTokens: 3000000 },
4422
+ failOnTokenBudgetExhaustion: true,
3961
4423
  childTask: {
3962
4424
  executor: "pi",
3963
4425
  role: "implementer",
@@ -3979,10 +4441,13 @@ async function buildBackendTestHybridDag(sources) {
3979
4441
  "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.",
3980
4442
  "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.",
3981
4443
  "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.",
3982
- 'Write the module {{item.stem}} as readable case cards covering every in-scope rule/Test Point the README Coverage Matrix assigns to this module. Every case starts with `## BE-<MODULE>-<NNN>|<中文用例名称>`. `<NNN>` is exactly three zero-padded digits (`001`, `002`, ...), never two digits (`01`), a bare number, or an alphabetic suffix such as `011A`. Every case must include `### 覆盖规则`, `### 测试点`, `### 场景类型`, `### 前置条件`, `### 操作步骤`, `### 预期结果`, and `### 自动化映射` Do not group cases under "## 测试类 ..." (or any h2 grouping) headings that force Cases down to h3; each Case must be a direct h2 (`##`), and its seven sections must be h3 (`###`) children of that Case. If you need to convey a pytest class, state it inside the Case\'s `### 自动化映射` instead. Forbidden: `## 测试类 X` then `### BE-PD-001` and `### 覆盖规则` at the same h3 level. Required: `## BE-PD-001` then `### 覆盖规则`.; `覆盖规则` and `测试点` must reference exact Matrix Rule Keys/Test Points. Add `测试目的`, `验收标准`, `需求依据`, and `测试数据` for readable evidence. The `验收标准` section must list the exact applicable `AC-...` IDs, and every explicit task AC must appear in at least one Case. Every automatable case explicitly names its target pytest script and exactly one primary symbol so traceability scans only that script/symbol.',
3983
- "Name this module file with the stable lowercase business stem `{{item.stem}}` (filename `testcase/md/{{item.stem}}.md`). Priority-only stems `p0`, `p1` and `p2` are forbidden and must never produce `p0.md` or `test_p0.py`. Do not use Case-ID-like module filenames. For every automatable case, `自动化映射` must name exactly `testcase/test_{{item.stem}}.py`, where the module stem is this Markdown filename without `.md`, lowercased, with non-alphanumeric characters replaced by underscores. Example: `health` → `testcase/test_health.py`; `resource_notes` → `testcase/test_resource_notes.py`. Never invent a different pytest path in Markdown than the module stem implies.",
4444
+ 'Write the module {{item.stem}} as readable case cards covering every in-scope rule/Test Point the README Coverage Matrix assigns to this module. Every case starts with `## BE-<MODULE>-<NNN>|<中文用例名称>`. `<NNN>` is exactly three zero-padded digits (`001`, `002`, ...), never two digits (`01`), a bare number, or an alphabetic suffix such as `011A`. Every case must include `### 覆盖规则`, `### 测试点`, `### 场景类型`, `### 前置条件`, `### 操作步骤`, `### 预期结果`, and `### 自动化映射` Do not group cases under "## 测试类 ..." (or any h2 grouping) headings that force Cases down to h3; each Case must be a direct h2 (`##`), and its seven sections must be h3 (`###`) children of that Case. If you need to convey a pytest class, state it inside the Case\'s `### 自动化映射` instead. Forbidden: `## 测试类 X` then `### BE-PD-001` and `### 覆盖规则` at the same h3 level. Required: `## BE-PD-001` then `### 覆盖规则`.; `覆盖规则` and `测试点` must reference exact Matrix Rule Keys/Test Points. Add `测试目的`, `验收标准`, `需求依据`, and `测试数据` for readable evidence. The `验收标准` section must list the exact applicable `AC-...` IDs, and every explicit task AC must appear in at least one Case. Every automatable case explicitly names its target pytest script and exactly one primary symbol so traceability scans only that script/symbol. Evidence-only meta cases that exist solely for non-executable assertion/cross-cutting process evidence may declare `脚本:无` and `primary symbol:无` with empty `变体测试点`, and must not invent a business pytest item.',
4445
+ "Name this module file with the stable lowercase business stem `{{item.stem}}` (filename `testcase/md/{{item.stem}}.md`). Priority-only stems `p0`, `p1` and `p2` are forbidden and must never produce `p0.md` or `test_p0.py`. Pure hexadecimal/hash-like opaque stems such as `a401606` and `deadbeef` are also forbidden. Do not use Case-ID-like module filenames. For every automatable case, `自动化映射` must name exactly `testcase/test_{{item.stem}}.py`, where the module stem is this Markdown filename without `.md`, lowercased, with non-alphanumeric characters replaced by underscores. Example: `health` → `testcase/test_health.py`; `resource_notes` → `testcase/test_resource_notes.py`. Never invent a different pytest path in Markdown than the module stem implies.",
4446
+ "Scenario Partition slots: when README declares `## Scenario Partitions`, every slot of each declared partition MUST appear in this module's Cases as exactly one variant Test Point with the deterministic ID `TP-<Partition ID>-<VALUE-TOKEN>` (each-value), `TP-<Partition ID>-OMITTED` (optional axis only) and exactly one `TP-<Partition ID>-NOT-IN-SET` complement slot with `intent=enum-invalid`. Example: Partition ID `SP-GET-API-RESOURCE-NOTES-STATUS` → `TP-SP-GET-API-RESOURCE-NOTES-STATUS-ACTIVE`. Slot IDs copy the declared Partition ID exactly; never drop the HTTP method, invent, merge, renumber or split slot IDs. Prefer ONE Case per partition with a parameter table over duplicated Cases per value. The not-in-set slot value must be a concrete literal absent from the Domain (e.g. `UNKNOWN_TYPE`) and its expected result must come from the bound source — when Expected by Slot is GAP, the Case states the expectation as GAP evidence, never a guessed 空列表/400. Never create cross-axis combination variants beyond the single documented nominal.",
4447
+ "For every variant Test Point, write its machine-checkable `场景意图: <TP-ID>; operation=...; target=...; intent=...` line inside that same Case body/自动化映射. Never collect Scenario Intent lines in a file-level appendix, implementation-details block, or another Case; local TP ownership is mandatory.",
3984
4448
  "Every Case must keep at least one numbered executable line under `### 操作步骤`; a compact variant/result table may follow but must not replace the numbered action anchor. Keep numbered/bulleted independently assertable results under `### 预期结果`. The exact `### 操作步骤` and `### 预期结果` headings must remain present for every Case, including compact/table-based Cases; never compress later Cases by dropping required headings. Every result must name the observable HTTP status, response field/value, state transition or membership condition, never vague wording such as ‘符合预期’.",
3985
- "In every `自动化映射`, use exactly these machine-readable list labels: `脚本`, `primary symbol`, `变体测试点`, `场景断言测试点`, `横切证据测试点`. Each Test Point from `### 测试点` must appear in exactly one binding list, and every Test Point named in any binding list must also be declared in that Case's `### 测试点`; write `无` for an empty list. A variant Test Point is atomic: one exact endpoint/input/precondition/outcome row equals one exact pytest item and one exact TP ID. If a parameter table has five rows, declare five distinct variant TP IDs in Markdown; never declare one family TP and append row suffixes only in pytest. Classify as `variant` only when endpoint, request input, precondition business state, or expected outcome genuinely changes and therefore needs an independent pytest parameter item. Classify CRUD checkpoints, status/body/header/schema assertions and multiple checks over the same response/journey as `assertion`; classify shared HTTP logging/redaction/truncation evidence as `cross-cutting`. Never create a Test Point merely to parameterize a checkpoint. Every non-cross-cutting TP ID is owned by exactly one Case; when the same response/schema/error assertion is needed in different Cases, use distinct Case-specific TP IDs instead of reusing one assertion TP across Cases. Keep the script path identical to the module one-to-one path and declare exactly one primary symbol named with the canonical Case prefix, for example `BE-RN-003` → `test_BE_RN_003_<description>`; non-Case-prefixed primary symbols are forbidden because parameterized item association must remain deterministic. For redaction scenarios, list sensitive header/field key names only. Never write any header-name-and-value pair, credential placeholder, fake token, anti-example, or other secret-shaped literal in Markdown; state only that a test-only value is supplied at runtime and omitted. Put implementation-only restrictions in a concise `<details>` block rather than dominating the main case flow. Use only environment-supported fixtures/targets/isolation, record evidence gaps in Chinese, and do not emit JSON, pytest, or execute commands.",
4449
+ "In every `自动化映射`, use exactly these machine-readable list labels: `脚本`, `primary symbol`, `变体测试点`, `场景断言测试点`, `横切证据测试点`, plus a deterministic payload contract. For operations without a request body write `Payload Contract: none`. Otherwise write `Payload Required Paths`, `Payload Allowed Paths`, and `Payload Enum` (write `none` when there is no enum); nested fields use dot paths such as `approver.name`. Each Case describes exactly one target request payload contract: put every payload label on its own list line, never concatenate multiple operations or setup POST/PUT contracts into one label line, and never repeat a `Payload Contract:` token inside explanatory prose/details after the machine-readable line. Values must come only from bound API/DTO evidence, never guesses. Each Test Point from `### 测试点` must appear in exactly one binding list, and every Test Point named in any binding list must also be declared in that Case's `### 测试点`; write `无` for an empty list. A variant Test Point is atomic: one exact endpoint/input/precondition/outcome row equals one exact pytest item and one exact TP ID. If a parameter table has five rows, declare five distinct variant TP IDs in Markdown; never declare one family TP and append row suffixes only in pytest. Classify as `variant` only when endpoint, request input, precondition business state, or expected outcome genuinely changes and therefore needs an independent pytest parameter item. Classify CRUD checkpoints, status/body/header/schema assertions and multiple checks over the same response/journey as `assertion`; classify shared HTTP logging/redaction/truncation evidence as `cross-cutting`. Never create a Test Point merely to parameterize a checkpoint. Every non-cross-cutting TP ID is owned by exactly one Case; when the same response/schema/error assertion is needed in different Cases, use distinct Case-specific TP IDs instead of reusing one assertion TP across Cases. Keep the script path identical to the module one-to-one path and declare exactly one primary symbol named with the canonical Case prefix, for example `BE-RN-003` → `test_BE_RN_003_<description>`; non-Case-prefixed primary symbols are forbidden because parameterized item association must remain deterministic. For evidence-only meta Cases with no executable business journey, write `脚本:无` and `primary symbol:无`, keep `变体测试点:无`, and place process evidence only in assertion/cross-cutting lists. If the bound contract only says an identifier is returned/present, do not declare a concrete identifier type. If a 404 Case needs a nonexistent path identifier but its syntax/type is unspecified, define a create-delete-derived valid identifier journey instead of an arbitrary UUID/text placeholder. For redaction scenarios, list sensitive header/field key names only. Never write any header-name-and-value pair, credential placeholder, fake token, anti-example, or other secret-shaped literal in Markdown; state only that a test-only value is supplied at runtime and omitted. Put implementation-only restrictions in a concise `<details>` block rather than dominating the main case flow. Use only environment-supported fixtures/targets/isolation, record evidence gaps in Chinese, and do not emit JSON, pytest, or execute commands.",
4450
+ ...(sharedSetupPrompt ? [sharedSetupPrompt] : []),
3986
4451
  intake.boundedSourceContext,
3987
4452
  "## Authoritative reference index",
3988
4453
  JSON.stringify(intake.referenceIndex, null, 2),
@@ -3995,32 +4460,39 @@ async function buildBackendTestHybridDag(sources) {
3995
4460
  const reviewCases = {
3996
4461
  id: "review-and-revise-backend-md-cases-pi",
3997
4462
  depends_on: [generateMdCasesMap.id],
3998
- role: "reviewer",
3999
- executor: "static",
4000
- complexity: "LOW",
4463
+ role: "implementer",
4464
+ executor: "pi",
4465
+ toolProfile: "write",
4466
+ complexity: "MED",
4001
4467
  writePolicy: "exclusive",
4002
4468
  writeSet: ["testcase/md/**"],
4003
- allowedPaths: ["testcase/md/**"],
4469
+ allowedPaths: Array.from(new Set([...ro, "testcase/md/**"])),
4004
4470
  forbiddenPaths: forbidden,
4005
- outputContract: "Deterministic advisory handoff that reserves testcase/md/** in the approved DAG write set for upstream map children; no model invocation or writes.",
4471
+ writerOutcomePolicy: { type: "implementation-outcome-v1" },
4472
+ 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.",
4006
4473
  subtask_prompt: [
4007
- "Independently review generated Markdown cases against the task requirements and environment evidence. Treat the files as human-facing test documentation: require clear preconditions, executable steps and assertable expected results; improve names, purpose, metadata and automation mapping where useful while preserving exact machine IDs and technical literals.",
4008
- "Output budget protocol: default to local edit per file; never dump full Matrix/case bodies into assistant chat. Review order is README (Scope/Matrix) then one module file per turn. When adding omitted in-scope cases, write one file per tool call and keep every required section. Do not bulk-delete in-scope cases to save tokens.",
4009
- "For every variant Test Point, ensure the Markdown scenario intent is machine-checkable with 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.",
4474
+ "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.",
4475
+ "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.",
4476
+ "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`.",
4010
4477
  "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.",
4011
4478
  "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.",
4012
- "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 case points at `testcase/test_<module>.py` derived from that module filename and declares exactly one primary symbol, assign every Test Point exactly one of `变体测试点`/`场景断言测试点`/`横切证据测试点`, ensure every binding-list Test Point is also present in that Case's `### 测试点`, 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.",
4013
- "Read only precise referenced source paths plus requirement sections needed for uncovered ACs. Do not scan the repository, modify source/**, generate pytest, execute tests, or emit JSON.",
4479
+ "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.",
4480
+ "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.",
4481
+ "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.",
4482
+ "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; never delete a declared 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.",
4483
+ "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.",
4484
+ "Read only indexed source paths. Do not scan the repository, modify source/**, generate pytest, execute tests, or emit JSON.",
4485
+ ...(sharedSetupPrompt ? [sharedSetupPrompt] : []),
4014
4486
  intake.boundedSourceContext,
4015
4487
  "## Authoritative reference index",
4016
4488
  JSON.stringify(intake.referenceIndex, null, 2),
4017
4489
  "For each index entry, use `readPath` for Pi read-tool calls and keep `path` as the exact Markdown Source References citation. Bound files under .harness/tasks/<taskId>/source/** are read-only inputs: reading them is allowed even though writing .harness/** is forbidden. Never resolve `path` relative to the repository root, search for substitutes, or fall back to docs/** when a bound read fails.",
4018
4490
  ].join("\n\n"),
4019
- static: {
4020
- resultMarkdown: "Markdown module writers completed. Deterministic node 6 validation owns advisory structure/coverage findings; no model review or rewrite was invoked.",
4021
- },
4022
4491
  };
4023
- const validateCases = shellNode("validate-backend-md-cases-shell", [reviewCases.id], "markdown-cases", "Record advisory findings for Markdown structure and deterministically analyze the final README Coverage Scope and Coverage Matrix against final Case rule/test-point bindings. Validate the classification-policy pair, affected operations/rules, scope evidence and regression floor; require documented OpenAPI completeness only for declared affected operations, while all explicit AC/REQ/BR remain in scope. Detect missing in-scope product/API rules, enum values, invalid equivalence classes, boundaries, format classes, business lifecycle states, GAP/CONFLICT, bidirectional Matrix/Case drift, non-canonical Case IDs, unclassified Test Points, duplicate binding modes and non-cross-cutting Test Points bound by multiple Cases. Do not validate source-reference existence. Write human and machine evidence from the same facts. Keep quality findings advisory, but fail closed after writing the report when secret-shaped values are detected. Coverage FAIL stays advisory.", "Run-owned reports/backend-md-case-validation.md, reports/backend-test-case-coverage-analysis.md and contracts/backend-test-case-coverage-facts.json v3 with Coverage Scope plus PASS/FAIL/UNAVAILABLE advisory facts; downstream execution continues.");
4492
+ const validateCases = shellNode("validate-backend-md-cases-shell", [reviewCases.id], "markdown-cases", "Record advisory findings for Markdown structure and deterministically analyze the final README Coverage Scope and Coverage Matrix against final Case rule/test-point bindings. Validate the classification-policy pair, affected operations/rules, scope evidence and regression floor; require documented OpenAPI completeness only for declared affected operations, while all explicit AC/REQ/BR remain in scope. Detect missing in-scope product/API rules, enum values, invalid equivalence classes, boundaries, format classes, business lifecycle states, GAP/CONFLICT, bidirectional Matrix/Case drift, non-canonical Case IDs, unclassified Test Points, duplicate binding modes and non-cross-cutting Test Points bound by multiple Cases. Do not validate source-reference existence. Write human and machine evidence from the same facts. Keep quality findings advisory, but fail closed after writing the report when secret-shaped values are detected. Coverage FAIL stays advisory.", "Run-owned reports/backend-md-case-validation.md, reports/backend-test-case-coverage-analysis.md and contracts/backend-test-case-coverage-facts.json v4 with Coverage Scope plus PASS/FAIL/UNAVAILABLE advisory facts; downstream execution continues.");
4493
+ if (sharedSetup) {
4494
+ validateCases.subtask_prompt += ` Deterministically verify shared setup references: every 引用前置 line must cite exactly the bound path ${sharedSetup.path} with a stable SS anchor (or SS-DEFAULT); any other citation, unbound path, invented step ID or 引用前置 line without a bound document is a FAIL finding. Never rewrite the user document.`;
4495
+ }
4024
4496
  // N5 line (sharded): pytest shared-asset plan → manifest shell → map_agent barrier.
4025
4497
  // Shared helpers/factories are written once by the plan node; each module's
4026
4498
  // test_<stem>.py is written by an independent Pi child (own 16K budget).
@@ -4035,9 +4507,9 @@ async function buildBackendTestHybridDag(sources) {
4035
4507
  forbiddenPaths: forbidden,
4036
4508
  outputContract: "Deterministic pytest generation handoff. Per-module map children write self-contained test_<module>.py files with bounded local fixtures, HTTP logging/redaction and payload builders; no model invocation, JSON, shared-asset writes or pytest execution.",
4037
4509
  subtask_prompt: [
4038
- "Convert testcase/md/** into pytest using upstream environment and advisory validation evidence plus only bounded pytest config/conftest. This node writes ONLY the shared pytest support assets (HTTP logging/redaction helper, request factories, shared fixtures); each module's test_<module>.py is written by a downstream sharded node that imports these helpers. A FAIL advisory report does not authorize inventing missing behavior; use the final Markdown facts that are present.",
4039
- "Output budget protocol (hard, max output <=16K per turn): Write helpers/factories one file per write/edit tool call. Never paste full Python modules into assistant chat. Do not reduce params/assertions/skips semantics to fit. If OUTPUT_LIMIT_RECOVERY is injected, continue only listed missing/broken shared files.",
4040
- "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.",
4510
+ "Convert testcase/md/** into pytest using upstream environment and advisory validation evidence plus only bounded pytest config/conftest. This node is a deterministic handoff: NO shared helper/factory/fixture files are generated anywhere in the pipeline; each module's self-contained test_<module>.py (module-local fixtures, HTTP logging/redaction, payload builders) is written by a downstream sharded node. A FAIL advisory report does not authorize inventing missing behavior; use the final Markdown facts that are present.",
4511
+ "Output budget protocol (hard, max output <=16K per turn): downstream module writers write exactly one test_<module>.py per write/edit tool call. Never paste full Python modules into assistant chat. Do not reduce params/assertions/skips semantics to fit.",
4512
+ "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.",
4041
4513
  "Generate a reusable HTTP logging helper (or equivalent client wrapper) and call it for every interface request. The request log must include method, URL/path, and request parameters (query plus JSON/body/payload summary). The response log must include status code and response result (JSON/text/body summary), and both records must be visible in pytest stdout/stderr without changing assertions. If shared pytest fixtures are generated, keep their dependency graph in one provider module and require each downstream test module to register that provider with an exact pytest_plugins tuple; importing only the outer fixture is insufficient and will be rejected by fixture-resolution preflight.",
4042
4514
  "HTTP response header names are case-insensitive. If the helper stores a lower-case normalized header map, every Content-Type or other header assertion must query the lower-case key (for example `content-type`) or use an explicitly case-insensitive accessor; never call a case-sensitive plain dict with `Content-Type` when the stored key is lower-case. Preserve the actual media-type assertion rather than dropping it.",
4043
4515
  "Compare timestamps and other semantically equivalent protocol values by parsed meaning, not byte-for-byte serialization. In particular, normalize valid ISO-8601 instants before equality/order assertions so differences such as omitted trailing fractional seconds do not create TestBug failures; preserve exact-string assertions only when the Markdown explicitly requires representation equality.",
@@ -4060,7 +4532,7 @@ async function buildBackendTestHybridDag(sources) {
4060
4532
  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.",
4061
4533
  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.",
4062
4534
  shell: {
4063
- commands: [buildBackendTestModuleManifestShellCommand()],
4535
+ commands: [buildBackendTestModuleManifestShellCommand(layout)],
4064
4536
  cwd: ".",
4065
4537
  timeoutMs: 60000,
4066
4538
  },
@@ -4084,10 +4556,11 @@ async function buildBackendTestHybridDag(sources) {
4084
4556
  workflowNodeId: "generate-backend-pytest-cases-map",
4085
4557
  itemsFrom: "$.nodes['materialize-backend-pytest-module-manifest-shell'].output.modules",
4086
4558
  itemName: "item",
4087
- maxItems: 64,
4088
- maxExpandedNodes: 64,
4559
+ maxItems: 8,
4560
+ maxExpandedNodes: 8,
4089
4561
  childIdPrefix: "generate-backend-pytest-case",
4090
- tokenBudget: { maxTokensPerCase: 16384, maxTotalTokens: 600000 },
4562
+ tokenBudget: { maxTotalTokens: 3000000 },
4563
+ failOnTokenBudgetExhaustion: true,
4091
4564
  childTask: {
4092
4565
  executor: "pi",
4093
4566
  role: "implementer",
@@ -4112,13 +4585,17 @@ async function buildBackendTestHybridDag(sources) {
4112
4585
  retryPolicy: BACKEND_TEST_WRITER_COMPLETENESS_RETRY_POLICY,
4113
4586
  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.",
4114
4587
  subtaskPromptTemplate: [
4115
- "Convert the single Markdown module testcase/md/{{item.stem}}.md into one self-contained pytest module. After reading the module Markdown 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.",
4588
+ "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.",
4116
4589
  "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.",
4117
- "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.",
4118
- 'Ensure every final Markdown Case ID in this module appears in exactly one primary pytest test function or pytest test class method region, using the exact `primary symbol` declared by Markdown. The symbol must start with `test_BE_<MODULE>_<NNN>_` so every parameterized collected item remains associated with its Case. Module-level functions and class-based pytest methods are both supported. Only `变体测试点` may use stable `pytest.param(..., id="TP-...")` IDs, and every atomic variant ID must appear exactly once with a genuine input/state/outcome change. Use `pytest.param(..., id=...)` for every row; do not use decorator-level `ids=[...]`, generated suffixes, or IDs that extend/shorten the exact Markdown TP. Do not parameterize `场景断言测试点` or `横切证据测试点`; execute all assertion checkpoints within the same business journey/item and use shared helpers for cross-cutting evidence. The primary symbol docstring must contain exact metadata lines `Case-ID: BE-...`, `Assertion-Test-Points: TP-...;TP-...` and `Cross-Cutting-Test-Points: TP-...;TP-...` (use `none` when empty). No Test Point may be invented, renamed, omitted or bound in two modes. The generated pytest collection shape must equal the Markdown prediction `sum(max(1, variant count per Case))`; keep it at or below the task\'s explicit budget by removing duplicate execution, never by collapsing multiple parameter rows under a coarse family TP. Assertions come only from 预期结果 and setup comes only from 前置条件/测试数据/自动化映射.',
4590
+ "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.",
4591
+ "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.",
4592
+ 'Ensure every automatable final Markdown Case ID in this module appears in exactly one primary pytest test function or pytest test class method region, using the exact `primary symbol` declared by Markdown. Skip evidence-only meta Cases that declare `脚本/primary symbol=无` with empty variants; do not invent a business pytest symbol for them. The symbol must start with `test_BE_<MODULE>_<NNN>_` so every parameterized collected item remains associated with its Case. Module-level functions and class-based pytest methods are both supported. Only `变体测试点` may use stable `pytest.param(..., id="TP-...")` IDs, and every atomic variant ID must appear exactly once with a genuine input/state/outcome change. Use a literal direct `pytest.param(..., id=...)` expression for every row; never hide or wrap it behind `_post_case`, `_put_case`, row-factory functions, comprehensions, generators, or dynamically returned parameter lists; do not use decorator-level `ids=[...]`, generated suffixes, or IDs that extend/shorten the exact Markdown TP. Do not parameterize `场景断言测试点` or `横切证据测试点`; execute all assertion checkpoints within the same business journey/item and use shared helpers for cross-cutting evidence. The primary symbol docstring must contain exact metadata lines `Case-ID: BE-...`, `Assertion-Test-Points: TP-...;TP-...` and `Cross-Cutting-Test-Points: TP-...;TP-...` (use `none` when empty). Implement request dictionaries so their direct and nested key paths and enum literals exactly satisfy the Case `Payload Required Paths`, `Payload Allowed Paths`, and `Payload Enum`; for `Payload Contract: none`, do not invent a JSON/body DTO. GET/DELETE setup journeys may create resources, but their setup DTO must not change the target operation\'s no-body payload contract. No Test Point may be invented, renamed, omitted or bound in two modes. The generated pytest collection shape must equal the Markdown prediction `sum(max(1, variant count per Case))`; keep it at or below the task\'s explicit budget by removing duplicate execution, never by collapsing multiple parameter rows under a coarse family TP. Assertions come only from 预期结果 and setup comes only from 前置条件/测试数据/自动化映射.',
4119
4593
  "Name the generated pytest file so it corresponds one-to-one with its source Markdown module file: this module stem `{{item.stem}}` maps to exactly one `testcase/test_{{item.stem}}.py`. The <module> stem is the Markdown filename without the `.md` extension, lowercased and with non-alphanumeric characters replaced by underscores. For example, `resource_notes` → `testcase/test_resource_notes.py`, `health` → `testcase/test_health.py`. If Markdown automation mapping names a different path than this module stem path, still write the module stem path and do not invent prefixes. Never merge multiple Markdown modules into one pytest file, never split one module across several files, and never invent pytest filenames unrelated to the Markdown modules.",
4594
+ "Scenario Partition slots: every `TP-<Partition ID>-...` variant Test Point declared by this module's Markdown MUST become exactly one literal direct `pytest.param(..., id=\"TP-<Partition ID>-...\")` row with the exact slot ID; the not-in-set slot passes a concrete literal absent from the documented Domain (e.g. `UNKNOWN_TYPE`) — never `_OMIT`, never a descriptive token. Never split one slot into multiple params or merge several slots under a family TP id. Slot filtering requests hit the documented list endpoint with the slot value as the query/path filter.",
4120
4595
  "Keep this module self-contained: define module-local fixtures and helpers directly in testcase/test_{{item.stem}}.py, so pytest discovers every fixture dependency without external plugin registration. The request log must include method, URL/path, and request parameters (query plus JSON/body/payload summary). The response log must include status code and response result (JSON/text/body summary), and both records must be visible in pytest stdout/stderr without changing assertions. Recursively redact sensitive values and apply bounded truncation before logging.",
4596
+ "Materialize every automatable Markdown Case exactly once as one canonical primary pytest symbol. Preserve every explicit variant Test Point as a stable pytest.param id and every assertion/cross-cutting binding as declared. Build request payloads from the effective Markdown test data literally: keep all declared DTO keys, nested shapes, enum values, missing/null/boundary variants and business-state preconditions; never substitute guessed convenience fields or rename contract fields. Never assert an identifier's concrete Python/JSON type unless the Markdown or bound contract explicitly declares that type; when only presence is required, accept any non-null scalar identifier and serialize it safely into the path. For a nonexistent-resource 404 Case whose identifier syntax/type is not declared, obtain a syntactically valid identifier from a live create response and delete it before the 404 request; never invent an arbitrary UUID/text identifier that may fail path conversion with 400. Respect every local helper's actual return signature: never tuple-unpack a scalar status/id/helper result, and never treat a tuple response as a scalar.",
4121
4597
  "Do not read source/**, add cases, reassign ACs, modify conftest/config/production code, use skip/xfail, swallow assertions, execute pytest, or emit JSON. For best-effort cleanup, catch only the narrow transport exception actually raised by the selected HTTP client (for example `requests.RequestException` or `urllib.error.URLError`); never use bare `except`, `Exception`, or `BaseException` with `pass`.",
4598
+ ...(sharedSetupPytestPrompt ? [sharedSetupPytestPrompt] : []),
4122
4599
  ].join("\n\n"),
4123
4600
  },
4124
4601
  },
@@ -4131,13 +4608,9 @@ async function buildBackendTestHybridDag(sources) {
4131
4608
  role: "implementer",
4132
4609
  executor: "pi",
4133
4610
  toolProfile: "write",
4134
- complexity: "HIGH",
4611
+ complexity: "MED",
4135
4612
  writePolicy: "exclusive",
4136
- writeSet: [
4137
- "testcase/**/test_*.py",
4138
- "testcase/**/helpers/**",
4139
- "testcase/**/factories/**",
4140
- ],
4613
+ writeSet: ["testcase/**/test_*.py"],
4141
4614
  allowedPaths: Array.from(new Set([...ro, "testcase/**"])),
4142
4615
  forbiddenPaths: Array.from(new Set([
4143
4616
  ...forbidden,
@@ -4147,27 +4620,28 @@ async function buildBackendTestHybridDag(sources) {
4147
4620
  "pyproject.toml",
4148
4621
  "setup.cfg",
4149
4622
  ])),
4150
- writerOutcomePolicy: { type: "implementation-outcome-v1" },
4151
- outputContract: "First non-empty line is IMPLEMENTATION_OUTCOME: changed|already-satisfied|blocked, followed by a concise repair summary. Modify only generated pytest scripts/helpers/factories and preserve every Markdown Case, Test Point, primary symbol and assertion meaning.",
4623
+ writerOutcomePolicy: { type: "implementation-outcome-v1", requireChangedFiles: true },
4624
+ 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.",
4152
4625
  subtask_prompt: [
4153
- "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.",
4154
- "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, or close generated fixture dependencies and plugin registration. For fixture defects inspect both provider and importer; 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.",
4626
+ "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.",
4627
+ "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.",
4628
+ "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.",
4155
4629
  "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.",
4156
4630
  "Use local edit only on assessment-listed paths; keep summaries short; never rewrite unrelated modules.",
4157
- "Do not read task source/** or reinterpret requirements. Do not modify Markdown, conftest, pytest config, production code or dependencies.",
4631
+ "Do not reinterpret requirements beyond the effective Markdown and bounded assessment diagnostics. Do not modify Markdown, conftest, pytest config, production code or dependencies.",
4158
4632
  "Do not add skip/skipif/xfail, remove tests, reduce collected items, loosen assertions, swallow exceptions, use try/except ImportError fallback, mutate sys.path/PYTHONPATH, or replace the real API with mocks.",
4159
4633
  "Do not execute pytest; the deterministic effective collection gate owns the final collection attempt.",
4160
4634
  ].join("\n\n"),
4161
4635
  };
4162
- const collectionEffective = shellNode("effective-backend-pytest-collection-gate-shell", [collectionAssess.id, repairPytest.id], "markdown-collection-effective", "If initial collection+fixture readiness passed, verify unchanged asset hashes and reuse it. If the single repair ran, rerun scenario-param preflight, final collection and no-business-body fixture resolution once. BLOCKED facts, repair failure, residual fixture failure or hash drift prevent business pytest execution. Materialize canonical backend-test-execution-readiness.json.", "Run-owned effective collection-v3 facts plus contracts/backend-test-execution-readiness.json proving exact final assets are collectable, fixture-resolvable and hash-bound; initial PASS is reused, repair path records attempt=1.", [], 120000);
4636
+ const collectionEffective = shellNode("effective-backend-pytest-collection-gate-shell", [collectionAssess.id, repairPytest.id], "markdown-collection-effective", "If initial collection+fixture readiness passed, verify unchanged asset hashes and reuse it. If the single repair ran, rerun scenario-param preflight, final collection and no-business-body fixture resolution once. Recompute effective correspondence/payload shape and materialize Case/symbol/item `ELIGIBLE|NOT_ELIGIBLE` facts; Payload-contract-bound field-target MISMATCH/UNDETERMINED scenario items, non-exact mappings and payload UNSAFE/UNAVAILABLE items are excluded. Generic request-level nominal/health observations remain advisory when payload shape is SAFE and correspondence exact. BLOCKED facts, repair failure, residual fixture failure, zero eligible items or hash drift prevent business pytest execution. Materialize canonical backend-test-execution-readiness.json v2.", "Run-owned effective collection-v3 facts, reports/backend-test-execution-eligibility.md, contracts/backend-test-execution-eligibility.json and contracts/backend-test-execution-readiness.json v2 proving exact final assets are collectable, fixture-resolvable, payload-safe at item level and hash-bound; initial PASS is reused, repair path records attempt=1.", [], 120000);
4163
4637
  collectionEffective.dependsPolicy = "all-or-condition-skip";
4164
- const traceability = shellNode("backend-test-traceability-gate-shell", [collectionEffective.id], "markdown-traceability", "Deterministically scan only final readiness-authorized Markdown-mapped pytest scripts. Produce bidirectional Markdown module/Case/Test Point ↔ pytest file/primary symbol correspondence and logging findings. scenario-param assessment/repair already ran before collection; consume and display its final PASS/PARTIAL/FAIL/UNAVAILABLE facts without modifying pytest assets after readiness was frozen. Correspondence findings remain advisory; Never block pytest solely on correspondence FAIL.", "Run-owned reports/backend-test-traceability.md, reports/backend-test-markdown-pytest-correspondence.md, contracts/backend-test-markdown-pytest-correspondence-facts.json, reports/backend-test-scenario-param-consistency.md and contracts/backend-test-scenario-param-consistency-facts.json (initial+final) with optional repair audit; PASS/FAIL/UNAVAILABLE correspondence facts bound after effective collection.");
4638
+ const traceability = shellNode("backend-test-traceability-gate-shell", [collectionEffective.id], "markdown-traceability", "Deterministically scan only final readiness-authorized Markdown-mapped pytest scripts. Produce bidirectional Markdown module/Case/Test Point ↔ pytest file/primary symbol correspondence, payload-shape safety, per-item execution eligibility and logging findings. scenario-param assessment/repair already ran before collection; consume and display its final PASS/PARTIAL/FAIL/UNAVAILABLE facts without modifying pytest assets after readiness was frozen. Correspondence findings remain advisory; Never block pytest solely on correspondence FAIL.", "Run-owned reports/backend-test-traceability.md, reports/backend-test-markdown-pytest-correspondence.md, contracts/backend-test-markdown-pytest-correspondence-facts.json, reports/backend-test-scenario-param-consistency.md and contracts/backend-test-scenario-param-consistency-facts.json (initial+final) with optional repair audit; PASS/FAIL/UNAVAILABLE correspondence facts bound after effective collection.");
4165
4639
  const manifest = shellNode("backend-test-case-manifest-shell", [traceability.id], "markdown-manifest", "Materialize the canonical Backend Test Case Manifest only from contracts/backend-test-case-coverage-facts.json and contracts/backend-test-markdown-pytest-correspondence-facts.json. Validate schema, task binding, input hashes and freshness; never re-read source semantics, re-analyze Coverage Matrix, rescan pytest symbols or recompute a second set of metrics. Missing/stale/conflicting facts produce partial/unavailable diagnostics rather than fabricated zeros.", "Run-owned contracts/backend-test-case-manifest.json with materializationStatus, sourceFactsIssues, validated coverageScope, coverageSummary, ruleCoverageSummary and correspondenceSummary; this is the single machine input for L-5 and closeout.");
4166
4640
  const pytestCommand = [
4167
4641
  'mkdir -p "${HARNESS_DAG_RUN_DIR}/reports"',
4168
- 'echo "pytest targets are resolved at runtime from final Markdown 自动化映射"',
4642
+ 'echo "pytest targets are resolved at runtime from execution-readiness v2 eligibleItemIds"',
4169
4643
  ].join("; ");
4170
- const execute = shellNode("execute-backend-pytest-and-html-report-shell", [manifest.id], "markdown-execute-html", "Read canonical contracts/backend-test-execution-readiness.json, verify final asset hashes, then resolve the final Markdown Automation Notes/自动化映射 to a unique, safe set of testcase/**/test_*.py targets and execute only those scripts exactly once. Prefer the deterministic module one-to-one path when a mapped script is missing but the module stem file exists. Generate a native pytest-html self-contained report, then render the primary self-contained Chinese HTML report from the same pytest-html plus final Markdown case metadata without rerun. Keep 测试结论 and quality status; make node 6 Markdown validation + case coverage and node 13 traceability + Markdown-to-pytest correspondence expandable to their full escaped details; show each failure overview item with its original pytest message plus deterministic evidence-based reason analysis; list failure/error case cards before the remaining cases while preserving stable order. Each polished per-case result card includes concise scenario, automation test name, result, duration, and redacted bounded HTTP request parameters/response results for both passed and failed cases. Do not render a technical/execution evidence section in HTML; retain auditable paths and hashes in facts.", "One scoped pytest execution over Markdown-mapped scripts producing a valid pytest-html report with per-case captured output, self-contained reports/backend-test.html, reports/backend-test.md, reports/backend-test-facts.md, a deterministic self-contained reports/backend-test-l5-dashboard.html (machine-computed L-5 metrics, no JSON), and an optional contracts/code-coverage-v1.json when jacocoCoverage is configured (JaCoCo TCP dump → jacoco.xml → parsed; failure-safe); exit 0/1 with valid evidence continues.", [pytestCommand], 300000);
4644
+ const execute = shellNode("execute-backend-pytest-and-html-report-shell", [manifest.id], "markdown-execute-html", "Read canonical contracts/backend-test-execution-readiness.json v2, verify final asset and eligibility-input hashes, then execute exactly its `eligibleItemIds` pytest node IDs once. Never execute `excludedItems`; retain each exclusion reason as residual TestBug/automation evidence rather than ProductBug. Prefer the deterministic module one-to-one path when a mapped script is missing but the module stem file exists. Generate a native pytest-html self-contained report, then render the primary self-contained Chinese HTML report from the same pytest-html plus final Markdown case metadata without rerun. Keep 测试结论 and quality status; make node 6 Markdown validation + case coverage and node 13 traceability + Markdown-to-pytest correspondence expandable to their full escaped details; show each failure overview item with its original pytest message plus deterministic evidence-based reason analysis; list failure/error case cards before the remaining cases while preserving stable order. Each polished per-case result card includes concise scenario, automation test name, result, duration, and redacted bounded HTTP request parameters/response results for both passed and failed cases. Do not render a technical/execution evidence section in HTML; retain auditable paths and hashes in facts.", "One scoped pytest execution over readiness-authorized eligible pytest items producing a valid pytest-html report with per-case captured output, self-contained reports/backend-test.html, reports/backend-test.md, reports/backend-test-facts.md, a deterministic self-contained reports/backend-test-l5-dashboard.html (machine-computed L-5 metrics, no JSON), and an optional contracts/code-coverage-v1.json when jacocoCoverage is configured (JaCoCo TCP dump → jacoco.xml → parsed; failure-safe); exit 0/1 with valid evidence continues.", [pytestCommand], 300000);
4171
4645
  if (execute.shell) {
4172
4646
  execute.shell.envAllowlist = collectBackendTestShellEnvAllowlist(sources);
4173
4647
  }
@@ -4245,11 +4719,63 @@ async function buildBackendTestHybridDag(sources) {
4245
4719
  report,
4246
4720
  ],
4247
4721
  };
4722
+ // Plan A: rewrite every backend-test node's layout-dependent strings
4723
+ // (prompts, output contracts, writeSet/allowedPaths, shell commands)
4724
+ // against the resolved layout. The default layout is identity, so the
4725
+ // packaged template stays byte-identical with the historical contract.
4726
+ applyBackendTestLayoutToDagSpec(spec, layout);
4727
+ // Plan B: carry the bound shared-setup document on the spec so runtime
4728
+ // validators (N6 markdown case validation) see the same binding as prompts.
4729
+ if (intake.sharedSetup) {
4730
+ spec.backendTestSharedSetup = { ...intake.sharedSetup };
4731
+ }
4248
4732
  applyDefaultReadOnlyRetryPolicy(spec);
4249
4733
  parseDagSpec(spec);
4250
4734
  assertValidDagSpec(spec);
4251
4735
  return spec;
4252
4736
  }
4737
+ /** Rewrite layout-dependent strings across a compiled backend-test DAG spec (plan A). */
4738
+ function applyBackendTestLayoutToDagSpec(spec, layout) {
4739
+ if (layout.isDefault) {
4740
+ spec.backendTestLayout = layout;
4741
+ return;
4742
+ }
4743
+ const rewrite = (value) => applyBackendTestLayoutToText(value, layout);
4744
+ for (const task of spec.tasks) {
4745
+ task.subtask_prompt = rewrite(task.subtask_prompt);
4746
+ if (task.outputContract)
4747
+ task.outputContract = rewrite(task.outputContract);
4748
+ task.writeSet = task.writeSet?.map(rewrite);
4749
+ task.allowedPaths = task.allowedPaths?.map(rewrite);
4750
+ task.forbiddenPaths = task.forbiddenPaths?.map(rewrite);
4751
+ if (task.dynamicExpansion?.childTask) {
4752
+ const child = task.dynamicExpansion.childTask;
4753
+ if (typeof child.subtaskPromptTemplate === "string") {
4754
+ child.subtaskPromptTemplate = rewrite(child.subtaskPromptTemplate);
4755
+ }
4756
+ if (typeof child.outputContract === "string") {
4757
+ child.outputContract = rewrite(child.outputContract);
4758
+ }
4759
+ if (Array.isArray(child.allowedPaths)) {
4760
+ child.allowedPaths = child.allowedPaths.map(rewrite);
4761
+ }
4762
+ if (Array.isArray(child.writeSet)) {
4763
+ child.writeSet = child.writeSet.map(rewrite);
4764
+ }
4765
+ if (Array.isArray(child.forbiddenPaths)) {
4766
+ child.forbiddenPaths = child.forbiddenPaths.map(rewrite);
4767
+ }
4768
+ }
4769
+ if (task.shell?.commands) {
4770
+ task.shell.commands = task.shell.commands.map(rewrite);
4771
+ }
4772
+ }
4773
+ // Rewrite remaining prose-level constraints and success criteria that
4774
+ // reference the generated asset tree.
4775
+ spec.globalConstraints = spec.globalConstraints?.map(rewrite);
4776
+ spec.successCriteria = spec.successCriteria?.map(rewrite);
4777
+ spec.backendTestLayout = layout;
4778
+ }
4253
4779
  // ---------------------------------------------------------------------------
4254
4780
  // Frontend browser-test RAG DAG template
4255
4781
  // ---------------------------------------------------------------------------
@@ -5928,7 +6454,7 @@ async function resolveTaskContractBindingForGenerate(sources) {
5928
6454
  }
5929
6455
  return synthesizeInMemoryTaskContractBinding(sources);
5930
6456
  }
5931
- async function buildHybridDagForTemplate(sources, template) {
6457
+ async function buildHybridDagForTemplate(sources, template, options = {}) {
5932
6458
  const taskContractBinding = await resolveTaskContractBindingForGenerate(sources);
5933
6459
  let spec;
5934
6460
  if (template === "frontend-implementation") {
@@ -6214,6 +6740,12 @@ function buildGovernanceStandardGateNode(sources) {
6214
6740
  verdictGate: {
6215
6741
  fromNodeId: "verify-pi",
6216
6742
  accept: ["VERDICT: pass"],
6743
+ // A legitimate request-revision is a convergence routing result only
6744
+ // when the task actually has a bounded fix loop. Without that loop the
6745
+ // gate must fail closed instead of letting closeout run.
6746
+ ...((sources.taskConfig.maxFixLoops ?? 0) > 0
6747
+ ? { routingAccept: ["VERDICT: request-revision"] }
6748
+ : {}),
6217
6749
  label: "governance-standard",
6218
6750
  lineMode: "first-verdict-line",
6219
6751
  },
@@ -6239,6 +6771,33 @@ function insertGovernanceStandardGate(spec, sources) {
6239
6771
  spec.tasks.splice(closeoutIndex, 0, gate);
6240
6772
  closeout.depends_on = ["governance-standard-gate-shell"];
6241
6773
  closeout.failureAwareDependsOn = ["governance-standard-gate-shell"];
6774
+ // Governance verify convergence: when the task's bounded-repair budget
6775
+ // allows it, a legitimate verify-pi `request-revision` re-enters a bounded
6776
+ // implement-repair loop (see convergence controller) instead of terminating
6777
+ // the run at the gate. The gate routes `request-revision` as a non-error
6778
+ // result so closeout stays failure-aware rather than cascade-skipped.
6779
+ const maxFixLoops = sources.taskConfig.maxFixLoops ?? 0;
6780
+ if (maxFixLoops > 0) {
6781
+ // verify-shell exists only when the task planned final verify commands;
6782
+ // build the chain from nodes this spec actually contains so
6783
+ // hasConvergenceChain never rejects the governance shape.
6784
+ const governanceChainIds = [
6785
+ "implement-pi",
6786
+ ...(spec.tasks.some((task) => task.id === "verify-shell")
6787
+ ? ["verify-shell"]
6788
+ : []),
6789
+ "verify-pi",
6790
+ "governance-standard-gate-shell",
6791
+ ];
6792
+ spec.convergence = {
6793
+ enabled: true,
6794
+ maxPasses: maxFixLoops + 1,
6795
+ stopOnVerdictPass: true,
6796
+ stopOnHardVerifyPass: true,
6797
+ pauseOnRegression: sources.taskConfig.convergence?.pauseOnRegression ?? true,
6798
+ chainNodeIds: governanceChainIds,
6799
+ };
6800
+ }
6242
6801
  }
6243
6802
  function buildReviewGatedHybridDag(standard, sources) {
6244
6803
  const spec = {
@@ -6789,6 +7348,11 @@ export async function writeHybridDagDraft(sources, outputPath, options = {}) {
6789
7348
  ? await prepareFrontendMockSources(sources, routingProjectCapability)
6790
7349
  : sources;
6791
7350
  const spec = await buildHybridDagForTemplate(preparedSources, template);
7351
+ if (options.rerunFeedback) {
7352
+ spec.rerunFeedback = bindDagRerunFeedback(options.rerunFeedback, spec);
7353
+ parseDagSpec(spec);
7354
+ assertValidDagSpec(spec);
7355
+ }
6792
7356
  if (preparedSources.repoRoot && dagHasWriterExecution(spec)) {
6793
7357
  await requireManagedTaskContractBinding({
6794
7358
  repoRoot: preparedSources.repoRoot,
@@ -6816,5 +7380,6 @@ export async function initHybridDagFromTask(repoRoot, taskId, options = {}) {
6816
7380
  const outputPath = options.outputPath ?? getTaskPaths(repoRoot, taskId).dagDraftPath;
6817
7381
  return writeHybridDagDraft(sources, outputPath, {
6818
7382
  template: options.template,
7383
+ rerunFeedback: options.rerunFeedback,
6819
7384
  });
6820
7385
  }