@tea-agent/loop-agent 0.40.0-next.6 → 0.40.0-next.7

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.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  ### 重点更新
6
6
 
7
+ - backend-test Markdown plan 节点收紧为严格 readSet:仅读取绑定任务源、权威 reference 文档和 N1 环境报告,Pi 只暴露受策略包裹的 `read` 工具,禁止全仓库扫描;plan 不再写入 `testcase/md/README.md`,而是保存为 run-owned Harness artifact `generate-backend-md-plan-pi/plan.md`,N3 从该 artifact 提取模块并将 `planReadPath` 传递给下游 map writer。Markdown map child 与唯一 review/sync writer 也增加机器级 strict readSet:动态 child readSet 随 item 模板物化,strict writer 只获得 `read/edit/write`,不能通过 `grep/find/ls/bash` 递归发现仓库;edit 的预读取同样受 readSet 约束,review 机器禁止写 `testcase/md/README.md`。保持 16 节点拓扑不变;backend-test 定向回归通过。
7
8
  - Operator Chat 多次输入排队对齐 DSH Web:运行中的连续输入改为持久化 FIFO 队列,不再用后一条覆盖前一条;单条直接展示,多条默认折叠为数量栏,展开后逐行提供内联编辑、删除和插话发送。队列 Dock 使用与 DSH 一致的外层定位与内层面板结构,标题固定、仅消息列表滚动,并在编辑或请求期间锁定折叠操作。编辑/删除以消息 ID + revision 做并发保护,插话复用 Pi `steer` 注入当前回合,其余消息继续按顺序在回合结束后自动发送;队列通过会话快照与 SSE 权威数组恢复,刷新或 Console 重启不丢失。
8
9
  - Operator Chat 右侧辅助栏统一上下文与调用记录:输入框的上下文环、调用记录入口现在复用文件/DAG 侧栏;「文件」常驻,「上下文 / 调用记录」按入口临时添加并支持独立 `×` 关闭,关闭后回到文件 Tab;点击已选入口可收起侧栏,切换到上下文时同步开启注入状态,收起时仅关闭注入而保留上下文数据。上下文与工具调用内容改为内嵌布局,不再叠加独立弹窗、遮罩、焦点陷阱或重复关闭按钮,并补充 Tab 切换与侧栏开合动画;修复折叠态右侧展开按钮无法恢复侧栏的问题。
9
10
  - Operator Chat 手动 compact 消息流对齐 DSH Web:压缩中在时间线显示状态行,完成后显示默认折叠的 `compact` 摘要边界,点击可展开完整 Markdown 压缩结果;compact 事件通过 SSE 与 session 详情快照双路径恢复,使用事件 ID 去重,刷新/重新进入会话不丢失。Pi compaction 会把摘要写入 session context,后续模型请求继续使用压缩后的上下文。
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "version": "0.40.0-next.6",
4
- "gitSha": "064c2dcbdc7c22f7c52dad6e585645a3f1982b7e",
5
- "builtAt": "2026-08-27T05:20:19.949Z"
3
+ "version": "0.40.0-next.7",
4
+ "gitSha": "59deccb31726ce014324385bd26a5558c5ed7a49",
5
+ "builtAt": "2026-08-27T14:04:40.295Z"
6
6
  }
@@ -4,7 +4,7 @@ import { readFile } from "node:fs/promises";
4
4
  import { writeDagNodeJsonArtifact, writeTextArtifactFile, } from "../infrastructure/harness/artifact-store.js";
5
5
  import { executePiStep, resolvePiBackend, } from "./pi-executor.js";
6
6
  import { resolveDagPiExtensions, } from "./pi-extension-resolver.js";
7
- import { buildPiWriterToolPolicyContext, createPiWriterCustomTools, } from "./pi-writer-tool-policy.js";
7
+ import { buildPiWriterToolPolicyContext, createPiReaderCustomTools, createPiWriterCustomTools, } from "./pi-writer-tool-policy.js";
8
8
  import { cleanupPlaywrightCliDefaultSession, createPlaywrightCliTool, PI_COMMAND_CAPABILITY_REGISTRY, resolveCaseIdFromWriteSet, resolveEvidenceDirFromWriteSet, } from "./pi-playwright-cli-tool.js";
9
9
  import { dagCommandPolicyAllows, resolveDagCommandPolicy, } from "../workflows/dag/types.js";
10
10
  import { redactPromptForLog, truncateOutput, } from "../shared/output-truncation.js";
@@ -182,6 +182,9 @@ export function resolveDagPiStepName(task) {
182
182
  return resolvePiExecutorStep(resolveDagPiPersona(task));
183
183
  }
184
184
  export function resolveDagPiToolNames(task) {
185
+ if ((task.readSet?.length ?? 0) > 0) {
186
+ return isDagPiWriteTask(task) ? ["read", "edit", "write"] : ["read"];
187
+ }
185
188
  if (!isDagPiWriteTask(task))
186
189
  return [...DAG_PI_READONLY_TOOLS];
187
190
  const tools = [...DAG_PI_WRITE_TOOLS];
@@ -238,6 +241,9 @@ export function buildDagPiUserMessage(task, persona, step) {
238
241
  `You are executing hybrid DAG node "${task.id}" (role=${role}, piPersona=${persona}, piStep=${step}, writePolicy=${writePolicy}).`,
239
242
  "The system prompt contains the full DAG envelope: objective, constraints, upstream context, and task.",
240
243
  "Use read-only tools only. Do not edit, write, or commit repository files.",
244
+ (task.readSet?.length ?? 0) > 0
245
+ ? `Strict read set: ${task.readSet.join(", ")}. The read tool rejects every other repository path; do not search for substitutes.`
246
+ : undefined,
241
247
  "Return your conclusion as plain Markdown text suitable for downstream DAG nodes.",
242
248
  "Do not wrap the output in code fences and do not add conversational preamble.",
243
249
  ].join(" ");
@@ -513,9 +519,17 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
513
519
  ok: false, stdout: "", stderr: "pi command capability requires an explicit bounded write tool profile", failureCategory: "tool-policy", durationMs: Date.now() - started,
514
520
  };
515
521
  }
516
- if (isWriteTask || allowsPlaywrightCli) {
522
+ const strictReadSet = (input.task.readSet?.length ?? 0) > 0;
523
+ if (isWriteTask || allowsPlaywrightCli || strictReadSet) {
517
524
  try {
518
525
  const customTools = [];
526
+ if (strictReadSet) {
527
+ const readContext = buildPiWriterToolPolicyContext({
528
+ repoRoot: input.cwd,
529
+ readSet: input.task.readSet,
530
+ });
531
+ customTools.push(...(await createPiReaderCustomTools(readContext)));
532
+ }
519
533
  if (isWriteTask) {
520
534
  const policyContext = buildPiWriterToolPolicyContext({
521
535
  repoRoot: input.cwd,
@@ -523,6 +537,7 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
523
537
  writeSet: input.task.writeSet,
524
538
  forbiddenPaths: input.task.forbiddenPaths,
525
539
  writePolicy: input.task.writePolicy,
540
+ readSet: input.task.readSet,
526
541
  });
527
542
  customTools.push(...(await createPiWriterCustomTools(policyContext)));
528
543
  }
@@ -688,6 +703,9 @@ export async function executeDagPiNode(input, meta, piStepFn = executePiStep, wr
688
703
  persona,
689
704
  step,
690
705
  });
706
+ if (input.task.id === "generate-backend-md-plan-pi" && result.assistantText?.trim()) {
707
+ await writeTextArtifactFile(path.join(meta.runDir, input.task.id, "plan.md"), result.assistantText.trim() + "\n");
708
+ }
691
709
  const mapped = mapPiResultToDagNodeResult(result, input.task.writerOutcomePolicy
692
710
  ? WRITER_OUTCOME_PROTOCOL_LINE
693
711
  : input.task.firstProtocolLine);
@@ -154,6 +154,28 @@ function assertMkdirRelative(relative, ctx) {
154
154
  throw new PiWriterPathDeniedError("forbidden", relative || ".");
155
155
  }
156
156
  }
157
+ export async function assertReadablePath(targetPath, ctx) {
158
+ const raw = String(targetPath ?? "").trim();
159
+ if (!raw)
160
+ throw new PiWriterPathDeniedError("empty-path", targetPath ?? "");
161
+ const repoRoot = path.resolve(ctx.repoRoot);
162
+ const absoluteTarget = path.isAbsolute(raw)
163
+ ? path.resolve(raw)
164
+ : path.resolve(repoRoot, raw);
165
+ if (!isPathInside(repoRoot, absoluteTarget)) {
166
+ throw new PiWriterPathDeniedError("outside-repo", raw);
167
+ }
168
+ const effective = await resolveEffectiveMutationTarget(repoRoot, absoluteTarget);
169
+ const relative = repoRelativePath(repoRoot, absoluteTarget, raw, false);
170
+ const effectiveRelative = repoRelativePath(effective.realRoot, effective.absoluteTarget, raw, false);
171
+ const readSet = ctx.readSet ?? [];
172
+ for (const candidate of [relative, effectiveRelative]) {
173
+ if (readSet.length === 0 || !matchesAnyPattern(candidate, readSet)) {
174
+ throw new PiWriterPathDeniedError("read-outside-read-set", candidate, "path is outside the node readSet");
175
+ }
176
+ }
177
+ return relative;
178
+ }
157
179
  /**
158
180
  * Assert a mutation target is writable under the DAG writer policy.
159
181
  * Returns the normalized lexical repo-relative path on success.
@@ -201,11 +223,30 @@ export async function assertMkdirPath(dirPath, ctx) {
201
223
  assertMkdirRelative(effectiveRelative, ctx);
202
224
  return lexicalRelative;
203
225
  }
226
+ export function createPiReaderFsOperations(ctx) {
227
+ return {
228
+ readFile: async (absolutePath) => {
229
+ await assertReadablePath(absolutePath, ctx);
230
+ return fsReadFile(absolutePath);
231
+ },
232
+ access: async (absolutePath) => {
233
+ await assertReadablePath(absolutePath, ctx);
234
+ await fsAccess(absolutePath);
235
+ },
236
+ };
237
+ }
204
238
  /** Build FS operations that enforce writer policy before mutations. */
205
239
  export function createPiWriterFsOperations(ctx) {
240
+ const strictReadSet = (ctx.readSet?.length ?? 0) > 0;
206
241
  return {
207
- readFile: (absolutePath) => fsReadFile(absolutePath),
242
+ readFile: async (absolutePath) => {
243
+ if (strictReadSet)
244
+ await assertReadablePath(absolutePath, ctx);
245
+ return fsReadFile(absolutePath);
246
+ },
208
247
  access: async (absolutePath) => {
248
+ if (strictReadSet)
249
+ await assertReadablePath(absolutePath, ctx);
209
250
  await fsAccess(absolutePath);
210
251
  },
211
252
  writeFile: async (absolutePath, content) => {
@@ -218,6 +259,20 @@ export function createPiWriterFsOperations(ctx) {
218
259
  },
219
260
  };
220
261
  }
262
+ export async function createPiReaderCustomTools(ctx) {
263
+ const sdk = (await import("@earendil-works/pi-coding-agent"));
264
+ const createReadToolDefinition = sdk.createReadToolDefinition;
265
+ if (typeof createReadToolDefinition !== "function") {
266
+ throw new Error("pi read tool policy unavailable: createReadToolDefinition missing from SDK");
267
+ }
268
+ const read = createReadToolDefinition(path.resolve(ctx.repoRoot), {
269
+ operations: createPiReaderFsOperations(ctx),
270
+ });
271
+ if (read?.name !== "read") {
272
+ throw new Error("pi read tool policy unavailable: SDK tool must be named read");
273
+ }
274
+ return [read];
275
+ }
221
276
  /**
222
277
  * Create same-name custom edit/write tool definitions that override built-ins
223
278
  * via Pi SDK customTools registration. Fails closed when SDK factories are missing.
@@ -262,5 +317,6 @@ export function buildPiWriterToolPolicyContext(input) {
262
317
  writeSet: input.writeSet ?? [],
263
318
  forbiddenPaths: input.forbiddenPaths ?? [],
264
319
  writePolicy: input.writePolicy ?? "exclusive",
320
+ readSet: input.readSet ?? [],
265
321
  };
266
322
  }
@@ -540,13 +540,22 @@ async function executeBackendTestPipeline(input, meta) {
540
540
  const started = Date.now();
541
541
  // Plan A: prefer the frozen layout carried by the compiled spec; fall back
542
542
  // to the historical default for hand-written legacy DAGs.
543
- const backendLayout = resolveBackendTestLayout(meta.spec.backendTestLayout
543
+ const baseBackendLayout = resolveBackendTestLayout(meta.spec.backendTestLayout
544
544
  ? {
545
545
  testRoot: meta.spec.backendTestLayout.testRoot,
546
546
  markdownRel: meta.spec.backendTestLayout.markdownRel,
547
547
  scriptRel: meta.spec.backendTestLayout.scriptRel,
548
548
  }
549
549
  : undefined);
550
+ const markdownPlanArtifact = path.join(meta.runDir, "generate-backend-md-plan-pi", "plan.md");
551
+ const backendLayout = existsSync(markdownPlanArtifact)
552
+ ? {
553
+ ...baseBackendLayout,
554
+ readmePath: path
555
+ .relative(input.cwd, markdownPlanArtifact)
556
+ .replaceAll(path.sep, "/"),
557
+ }
558
+ : baseBackendLayout;
550
559
  try {
551
560
  if (!pipeline)
552
561
  throw new Error("missing backend-test pipeline id");
@@ -26,6 +26,7 @@ export function buildExpandedChildTask(input) {
26
26
  allowedPaths: renderDynamicPatternList(child.allowedPaths, item, index, expansion.itemName) ?? [],
27
27
  forbiddenPaths: renderDynamicPatternList(child.forbiddenPaths, item, index, expansion.itemName) ?? [],
28
28
  writeSet: renderDynamicPatternList(child.writeSet, item, index, expansion.itemName),
29
+ readSet: renderDynamicPatternList(child.readSet, item, index, expansion.itemName),
29
30
  outputContract: child.outputContract,
30
31
  writerOutcomePolicy: child.writerOutcomePolicy,
31
32
  writeGuardPolicy: child.writeGuardPolicy,
@@ -3952,9 +3952,10 @@ export function applyBackendTestLayoutToText(text, layout) {
3952
3952
  /**
3953
3953
  * Builds the `node -e` command for the backend-test module manifest shell.
3954
3954
  * The inline JS mirrors `extractModuleStemsFromReadme` so the map_agent
3955
- * shard set deterministically matches the README index the Completeness
3956
- * Gate trusts: only table-row `testcase/md/<stem>.md` mentions and canonical
3957
- * relative links `[label](./<stem>.md)` count, with the same
3955
+ * shard set deterministically matches the plan index the Completeness
3956
+ * Gate trusts: only `testcase/md/<stem>.md` path mentions and canonical
3957
+ * relative links `[label](./<stem>.md)` count. Adjacent table cells such as
3958
+ * Case Range or pytest assets are never interpreted as module stems. The same
3958
3959
  * `looksLikeValidModuleStem` filter and `normalizeBackendTestModuleStem`
3959
3960
  * normalization. Output is exactly one trailing JSON line `{modules:[{stem}]}`
3960
3961
  * that `parseJsonFromText` accepts after shell command echoes.
@@ -3968,17 +3969,18 @@ function buildBackendTestModuleManifestShellCommand(layout) {
3968
3969
  // mdDir/testPrefix are injected as JSON literals so the same extractor
3969
3970
  // works for any configured backendTest layout (plan A).
3970
3971
  const mdDirLiteral = JSON.stringify(layout.markdownDir);
3971
- const testPrefixLiteral = JSON.stringify(`${layout.scriptDir}/test_`);
3972
3972
  const escOpen = String.fromCharCode(92, 91); // \[
3973
3973
  const escClose = String.fromCharCode(92, 93); // \]
3974
3974
  const escBslash = String.fromCharCode(92, 92); // \\
3975
- const script = `const fs=require('fs');
3975
+ const script = `const fs=require('fs'),path=require('path'),crypto=require('crypto');
3976
3976
  const mdDir=${mdDirLiteral};
3977
- const testPrefix=${testPrefixLiteral};
3978
3977
  const esc=s=>s.replace(/[${escOpen}${escClose}{}()*+?^$|${escBslash}]/g,'${escBslash}$&');
3979
3978
  const rxMdPath=new RegExp(esc(mdDir)+'${escBslash}/([A-Za-z0-9_.-]+)${escBslash}.md','g');
3980
- const rxTableRow=new RegExp('${escBslash}|${escBslash}s*([A-Za-z0-9_.-]+)${escBslash}s*${escBslash}|${escBslash}s*'+esc(testPrefix),'g');
3981
- const readme=fs.existsSync(mdDir+'/README.md')?fs.readFileSync(mdDir+'/README.md','utf8'):'';
3979
+ const runDir=process.env.HARNESS_DAG_RUN_DIR||'';
3980
+ if(!runDir){process.stderr.write('missing HARNESS_DAG_RUN_DIR for backend-test Markdown plan artifact\\n');process.exit(2);}
3981
+ const planPath=path.join(runDir,'generate-backend-md-plan-pi','plan.md');
3982
+ if(!fs.existsSync(planPath)){process.stderr.write('missing backend-test Markdown plan artifact: '+planPath+'\\n');process.exit(2);}
3983
+ const readme=fs.readFileSync(planPath,'utf8');
3982
3984
  const norm=s=>String(s).toLowerCase().replace(/[^a-z0-9]+/g,'_').replace(/^_+|_+$/g,'').replace(/_+/g,'_');
3983
3985
  const bt=String.fromCharCode(96);
3984
3986
  const stripBackticks=s=>s.split(bt).join('');
@@ -3995,15 +3997,17 @@ const lines=section.split('\\n').filter(l=>l.includes('|'));
3995
3997
  for(const line of lines){
3996
3998
  const bare=stripBackticks(line);
3997
3999
  for(const m of bare.matchAll(rxMdPath)){raw.push(m[1]);}
3998
- for(const m of bare.matchAll(rxTableRow)){if(valid(m[1])||invalidReason(m[1])!=='invalid-syntax')raw.push(m[1]);}
3999
4000
  }
4000
4001
  for(const m of section.matchAll(rxRelLink)){raw.push(m[1]);}
4001
4002
  const invalid=[];for(const r of raw){const reason=invalidReason(r);if(reason)invalid.push({stem:norm(r),reason});}
4002
4003
  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);}
4003
4004
  const seen=new Set();const modules=[];
4004
4005
  for(const r of raw){const st=norm(r);if(valid(r)&&!seen.has(st)){seen.add(st);modules.push({stem:st});}}
4006
+ if(modules.length===0){process.stderr.write('empty-module-index: require at least one stable business module\\n');process.exit(2);}
4005
4007
  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);}
4006
- process.stdout.write(JSON.stringify({modules}));
4008
+ const planReadPath=path.relative(process.cwd(),planPath).split(path.sep).join('/');
4009
+ const planSha256=crypto.createHash('sha256').update(readme).digest('hex');
4010
+ process.stdout.write(JSON.stringify({modules:modules.map(item=>({...item,planReadPath})),planReadPath,planSha256}));
4007
4011
  `;
4008
4012
  const encoded = Buffer.from(script, "utf8").toString("base64");
4009
4013
  return `node -e "eval(Buffer.from('${encoded}','base64').toString('utf8'))"`;
@@ -4486,35 +4490,37 @@ async function buildBackendTestHybridDag(sources) {
4486
4490
  const generateMdPlan = {
4487
4491
  id: "generate-backend-md-plan-pi",
4488
4492
  depends_on: [environment.id],
4489
- role: "implementer",
4493
+ role: "planner",
4490
4494
  executor: "pi",
4491
- toolProfile: "write",
4495
+ toolProfile: "read-only",
4492
4496
  complexity: "MED",
4493
- writePolicy: "exclusive",
4494
- writeSet: ["testcase/md/README.md"],
4495
- allowedPaths: ["testcase/md/README.md"],
4497
+ writePolicy: "read-only",
4498
+ allowedPaths: [],
4499
+ readSet: [
4500
+ toDagSourcePath(sources, sources.requirementPath),
4501
+ ...(sources.constraintMarkdown
4502
+ ? [toDagSourcePath(sources, sources.constraintPath)]
4503
+ : []),
4504
+ ...intake.referenceIndex.map((entry) => entry.readPath),
4505
+ ".harness/dag-runs/**/reports/backend-test-environment.md",
4506
+ ],
4496
4507
  forbiddenPaths: forbidden,
4497
- writerOutcomePolicy: {
4498
- type: "implementation-outcome-v1",
4499
- requireChangedFiles: true,
4500
- },
4501
- retryPolicy: BACKEND_TEST_WRITER_COMPLETENESS_RETRY_POLICY,
4502
- outputContract: "Write a Chinese, human-readable testcase/md/README.md as the single Markdown-first entry page with Coverage Scope, Coverage Matrix and a machine-parseable module index. Do not write module case cards here; do not execute pytest or modify production code/config.",
4508
+ outputContract: "Return a Chinese, human-readable Markdown-first plan with Coverage Scope, Coverage Matrix, Scenario Partitions when applicable, and a machine-parseable Module Index. The runtime persists it as a run-owned Harness artifact; do not write testcase/md/README.md, execute pytest, or modify project files.",
4503
4509
  subtask_prompt: [
4504
- "This is a required file-generation node. After reading the bounded inputs, immediately use write tools to create testcase/md/README.md. Do not end after analysis or planning, and do not return before a non-empty bounded diff exists. Write ONLY testcase/md/README.md in this node; module case cards are written by downstream sharded nodes.",
4510
+ "This is a required plan-generation node. Read only the strict read set and return the complete Markdown plan in the assistant response. The runtime persists the response as a run-owned Harness artifact named generate-backend-md-plan-pi/plan.md. Do not write testcase/md/README.md or any project file; module case cards are written by downstream sharded nodes.",
4505
4511
  "Output budget protocol (hard, max output <=16K per turn): Never paste full Matrix, case bodies, or source text into assistant chat. README holds only Scope+Matrix+module index; never inline full case bodies. If a Completeness Gate / OUTPUT_LIMIT_RECOVERY retry is injected, continue only listed target paths.",
4506
- "The first non-empty response line must be exactly IMPLEMENTATION_OUTCOME: changed after the README has been written, or IMPLEMENTATION_OUTCOME: blocked when precise missing evidence prevents safe generation. already-satisfied is not valid for this node.",
4507
- "Read the upstream environment report. Generate the Markdown-first backend test README under testcase/md/README.md.",
4512
+ "Return the complete plan as plain Markdown. Do not emit JSON or code fences. The plan must contain the exact ## Coverage Scope, ## Coverage Matrix and ## Module Index sections required by the downstream manifest.",
4513
+ "Read the upstream environment report only through the strict read set. Generate the Markdown-first backend test plan; it will be persisted under the current DAG run's Harness artifacts, not under testcase/md/.",
4508
4514
  "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.",
4509
- "Create testcase/md/README.md as the concise entry page: test objective, target/environment, isolation/cleanup, module summary and a linked case index table with Case ID, Chinese case name, scenario type, endpoint and expected status/result. Avoid repeating every case body in README.",
4510
- "Before the Coverage Matrix, write a mandatory machine-readable `## Coverage Scope` section in README using exactly `| Field | Value |`, immediately followed by the separator row `|---|---|`, and these six unique rows: `Change Classification`, `Coverage Policy`, `Affected Operations`, `Affected Rule Keys`, `Regression Floor`, `Scope Evidence`. Always set `Change Classification` to `new-operation` and `Coverage Policy` to `full-contract`; do NOT reason about whether operations are new or existing. Cover all in-scope rules from the requirement document at full depth; treat the product requirement as the coverage baseline and use API contract evidence (fields/status/enum/boundary/format) to supplement scenario dimensions. Scope is limited to operations/rules the requirement document (or its referenced API contract) explicitly describes; do not expand to unrelated operations that the requirement does not mention. List affected operations exactly as `METHOD /path`, stable rule keys separated by semicolons, and precise source pointers as Scope Evidence.",
4515
+ "Create the concise plan entry page: test objective, target/environment, isolation/cleanup, module summary and a linked case index table with Case ID, Chinese case name, scenario type, endpoint and expected status/result. Avoid repeating every case body in the plan artifact.",
4516
+ "Before the Coverage Matrix, write a mandatory machine-readable `## Coverage Scope` section in the plan artifact using exactly `| Field | Value |`, immediately followed by the separator row `|---|---|`, and these six unique rows: `Change Classification`, `Coverage Policy`, `Affected Operations`, `Affected Rule Keys`, `Regression Floor`, `Scope Evidence`. Always set `Change Classification` to `new-operation` and `Coverage Policy` to `full-contract`; do NOT reason about whether operations are new or existing. Cover all in-scope rules from the requirement document at full depth; treat the product requirement as the coverage baseline and use API contract evidence (fields/status/enum/boundary/format) to supplement scenario dimensions. Scope is limited to operations/rules the requirement document (or its referenced API contract) explicitly describes; do not expand to unrelated operations that the requirement does not mention. List affected operations exactly as `METHOD /path`, stable rule keys separated by semicolons, and precise source pointers as Scope Evidence.",
4511
4517
  "Coverage depth is full over the in-scope rules: fully cover every documented status, request/response field rule, requiredness, enum, boundary, format, auth and business state of each affected operation the requirement describes, but do not re-test unrelated operations the requirement does not mention. Inspect shared validator/helper/DTO/query builder evidence and expand Affected Operations when the same affected path can affect them; unresolved impact stays visible as GAP/CONFLICT.",
4512
- "Before writing cases, build the mandatory machine-readable Coverage Matrix inside `testcase/md/README.md` itself. Its section heading line must be exactly `## Coverage Matrix` with no numeric prefix/suffix; never place the canonical Matrix only in a module file. Use this exact header: `| Rule Key | Priority | Source | Endpoint/Field | Dimension | Rule | Required Test Points | Case IDs | Status |`. Every data row must contain exactly 9 pipe-delimited cells and must never omit `Dimension`; use concise dimensions such as requirement, operation, response-status, requiredness, enum, boundary, format, business-state or error. Use only P0/P1/P2 and COVERED/PARTIAL/GAP/CONFLICT. Use stable `TP-<UPPERCASE-HYPHENATED-ID>` test points separated by semicolons.",
4518
+ "Before writing cases, build the mandatory machine-readable Coverage Matrix inside the plan artifact itself. Its section heading line must be exactly `## Coverage Matrix` with no numeric prefix/suffix; never place the canonical Matrix only in a module file. Use this exact header: `| Rule Key | Priority | Source | Endpoint/Field | Dimension | Rule | Required Test Points | Case IDs | Status |`. Every data row must contain exactly 9 pipe-delimited cells and must never omit `Dimension`; use concise dimensions such as requirement, operation, response-status, requiredness, enum, boundary, format, business-state or error. Use only P0/P1/P2 and COVERED/PARTIAL/GAP/CONFLICT. Use stable `TP-<UPPERCASE-HYPHENATED-ID>` test points separated by semicolons.",
4513
4519
  "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.",
4514
4520
  "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.",
4515
4521
  "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.",
4516
- "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.",
4517
- "Scenario Partitions (query/filter axes): for every affected GET/list operation, declare one row per enum or classification axis used for filtering (query/path parameters such as type/status/category). Add a mandatory machine-readable `## Scenario Partitions` section after the Coverage Matrix using exactly `| Partition ID | Operation | Axis | Domain | Required Slots | Expected by Slot | Bind Rule |` with the separator row. Partition ID is a stable `SP-<OPERATION>-<AXIS>` token; Domain must copy the legal values verbatim from the bound OpenAPI enum or requirement sentence (never guess); Required Slots writes `each-value` plus `omitted` only when the parameter is optional; Expected by Slot states the documented expectation per slot kind (`domain-value`, `default-behavior`, `empty-result`/`excluded-result` when documented, or `GAP` when the source does not document the complement expectation — never invent 空列表/400). POST/PUT body field-validation enums stay in the Coverage Matrix as `TP-<FIELD>-ENUM-*` and MUST NOT get a Scenario Partition row. Do not create partitions for axes without a documented legal-value domain. Only GET/list query or path parameters whose bound source documents a finite enum or classification set may become a Scenario Partition. Do not create partitions for free-form strings, primary keys, required-or-optional-only parameters, or boundary/format-only axes. If an axis has no finite legal-value domain, do not declare a Partition row and do not invent NOT-IN-SET cases. Cross-axis combinations stay as ONE nominal Case; never declare a cross-axis cartesian partition.",
4522
+ "Mandatory module index: include a `## Module Index` table in the plan artifact that lists every planned module as a canonical relative link of the exact form `[label](./<stem>.md)` plus a `testcase/md/<stem>.md` path cell, so a downstream deterministic manifest can parse the module list. Group by stable business resource/domain, not by CRUD operation: one resource's list/detail/create/update/delete cases belong in one module such as `resource_notes`; split only when a single module would exceed the per-child 16K output protocol, keep the total module count at the smallest safe value, and never exceed 8 modules. Name each module file with a stable lowercase business stem such as `health` or `resource_notes`. Pure hexadecimal/hash-like opaque stems such as `a401606` or `deadbeef` are forbidden. Do not use priority-only stems `p0`, `p1` or `p2`; Priority belongs only in the Coverage Matrix and never defines module files. Do not use Case-ID-like module filenames such as `BE-HEALTH.md` or `BE-NOTES.md`. The relative link target MUST equal the on-disk filename stem the sharded writer will create. For every automatable case, `自动化映射` must name exactly `testcase/test_<module>.py`, where <module> is that Markdown filename without `.md`, lowercased, with non-alphanumeric characters replaced by underscores. Example: `testcase/md/health.md` → `testcase/test_health.py`; `testcase/md/resource_notes.md` → `testcase/test_resource_notes.py`. Never invent a different pytest path in Markdown than the module stem implies.",
4523
+ "Scenario Partitions (query/filter axes): for every affected GET/list operation, declare one row per enum or classification axis used for filtering (query/path parameters such as type/status/category). Add a mandatory machine-readable `## Scenario Partitions` section after the Coverage Matrix using exactly `| Partition ID | Operation | Axis | Domain | Required Slots | Expected by Slot | Bind Rule |` with the separator row. Partition ID is a stable `SP-<OPERATION>-<AXIS>` token; Domain must copy the legal values verbatim from the bound OpenAPI enum or requirement sentence (never guess), using bare semicolon-separated identifier values inside the single table cell (for example `ACTIVE; ARCHIVED`, with no Markdown backticks or prose); Required Slots writes `each-value` plus `omitted` only when the parameter is optional; Expected by Slot states the documented expectation per slot kind (`domain-value`, `default-behavior`, `empty-result`/`excluded-result` when documented, or `GAP` when the source does not document the complement expectation — never invent 空列表/400). POST/PUT body field-validation enums stay in the Coverage Matrix as `TP-<FIELD>-ENUM-*` and MUST NOT get a Scenario Partition row. Do not create partitions for axes without a documented legal-value domain. Only GET/list query or path parameters whose bound source documents a finite enum or classification set may become a Scenario Partition. Do not create partitions for free-form strings, primary keys, required-or-optional-only parameters, or boundary/format-only axes. If an axis has no finite legal-value domain, do not declare a Partition row and do not invent NOT-IN-SET cases. Cross-axis combinations stay as ONE nominal Case; never declare a cross-axis cartesian partition.",
4518
4524
  "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.",
4519
4525
  ...(sharedSetupPrompt ? [sharedSetupPrompt] : []),
4520
4526
  intake.boundedSourceContext,
@@ -4533,8 +4539,8 @@ async function buildBackendTestHybridDag(sources) {
4533
4539
  writePolicy: "read-only",
4534
4540
  allowedPaths: ro,
4535
4541
  forbiddenPaths: forbidden,
4536
- 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.",
4537
- 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.",
4542
+ outputContract: "Stdout JSON {modules:[{stem,planReadPath}],planReadPath,planSha256} parsed from the run-owned generate-backend-md-plan-pi/plan.md artifact using the same module-stem extractor as the Completeness Gate.",
4543
+ subtask_prompt: "Parse only $HARNESS_DAG_RUN_DIR/generate-backend-md-plan-pi/plan.md and emit exactly one trailing JSON line {modules:[{stem,planReadPath}],planReadPath,planSha256}. No file writes and no testcase/md/README.md fallback.",
4538
4544
  shell: {
4539
4545
  commands: [buildBackendTestModuleManifestShellCommand(layout)],
4540
4546
  cwd: ".",
@@ -4575,6 +4581,15 @@ async function buildBackendTestHybridDag(sources) {
4575
4581
  allowedPaths: ["testcase/md/{{item.stem}}.md"],
4576
4582
  forbiddenPaths: forbidden,
4577
4583
  writeSet: ["testcase/md/{{item.stem}}.md"],
4584
+ readSet: [
4585
+ "{{item.planReadPath}}",
4586
+ toDagSourcePath(sources, sources.requirementPath),
4587
+ ...(sources.constraintMarkdown
4588
+ ? [toDagSourcePath(sources, sources.constraintPath)]
4589
+ : []),
4590
+ ...intake.referenceIndex.map((entry) => entry.readPath),
4591
+ `${layout.markdownDir}/{{item.stem}}.md`,
4592
+ ],
4578
4593
  writerOutcomePolicy: {
4579
4594
  type: "implementation-outcome-v1",
4580
4595
  requireChangedFiles: true,
@@ -4582,7 +4597,7 @@ async function buildBackendTestHybridDag(sources) {
4582
4597
  retryPolicy: BACKEND_TEST_WRITER_COMPLETENESS_RETRY_POLICY,
4583
4598
  outputContract: "Write exactly one Chinese module Markdown case-card file testcase/md/<stem>.md with BE-<MODULE>-<NNN> cases and the seven required h3 sections; keep machine IDs/literals exact and do not execute pytest or modify production code/config or the README.",
4584
4599
  subtaskPromptTemplate: [
4585
- "This is a required file-generation node for exactly one Markdown module. After reading testcase/md/README.md (Coverage Scope + Coverage Matrix + module index) and the bounded references, immediately use write tools to create the single file testcase/md/{{item.stem}}.md. Do not end after analysis or planning, and do not return before a non-empty bounded diff exists. Do not modify README.md or any other module file.",
4600
+ "This is a required file-generation node for exactly one Markdown module. Read the upstream run-owned Markdown plan artifact at `{{item.planReadPath}}` (Coverage Scope + Coverage Matrix + Module Index) and the bounded references, then immediately use write tools to create the single file testcase/md/{{item.stem}}.md. Do not read or recreate testcase/md/README.md. Do not end after analysis or planning, and do not return before a non-empty bounded diff exists. Do not modify any other module file.",
4586
4601
  "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.",
4587
4602
  "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.",
4588
4603
  "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.",
@@ -4604,28 +4619,37 @@ async function buildBackendTestHybridDag(sources) {
4604
4619
  };
4605
4620
  const reviewCases = {
4606
4621
  id: "review-and-revise-backend-md-cases-pi",
4607
- depends_on: [generateMdCasesMap.id],
4622
+ depends_on: [generateMdCasesMap.id, materializeMdManifest.id],
4608
4623
  role: "implementer",
4609
4624
  executor: "pi",
4610
4625
  toolProfile: "write",
4611
4626
  complexity: "MED",
4612
4627
  writePolicy: "exclusive",
4613
- writeSet: ["testcase/md/**"],
4614
- allowedPaths: Array.from(new Set([...ro, "testcase/md/**"])),
4615
- forbiddenPaths: forbidden,
4628
+ writeSet: [`${layout.markdownDir}/**`],
4629
+ readSet: [
4630
+ ".harness/dag-runs/**/generate-backend-md-plan-pi/plan.md",
4631
+ toDagSourcePath(sources, sources.requirementPath),
4632
+ ...(sources.constraintMarkdown
4633
+ ? [toDagSourcePath(sources, sources.constraintPath)]
4634
+ : []),
4635
+ ...intake.referenceIndex.map((entry) => entry.readPath),
4636
+ `${layout.markdownDir}/*.md`,
4637
+ ],
4638
+ allowedPaths: Array.from(new Set([...ro, `${layout.markdownDir}/**`])),
4639
+ forbiddenPaths: Array.from(new Set([...forbidden, layout.readmePath])),
4616
4640
  writerOutcomePolicy: { type: "implementation-outcome-v1" },
4617
4641
  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.",
4618
4642
  subtask_prompt: [
4619
- "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.",
4620
- "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.",
4643
+ "Perform one gap-targeted synchronization, not a full-suite rewrite or stylistic review. Read the immutable run-owned Markdown plan from the direct upstream manifest's planReadPath. Start from explicit bound source IDs/error codes/DTO fields/normative quoted rules and the plan Coverage Matrix; open and edit only modules that own a missing or conflicting rule. Never create or edit testcase/md/README.md and never modify the run-owned plan artifact. Preserve unrelated valid modules byte-for-byte and avoid optional wording cleanup.",
4644
+ "Output budget protocol: never dump full Matrix/case bodies into assistant chat. Inspect the immutable run-owned plan first, build a concise target list from its Matrix and Module Index, then read/write only target modules one file per tool call. Do not traverse every module when the Matrix and source token inventory show no gap; return `already-satisfied`. When adding omitted in-scope cases, keep every required section. Do not bulk-delete in-scope cases to save tokens.",
4621
4645
  "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`.",
4622
4646
  "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.",
4623
- "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.",
4647
+ "Check AC completeness/meaning, endpoint, fields/shape, status/error codes, rules, states, documented boundaries/auth, positive/negative coverage, executable steps and assertable results. Require the exact `## Coverage Scope` Field/Value table with the `|---|---|` separator row, a valid classification-policy pair, non-empty Affected Operations/Rule Keys/Scope Evidence, and the classification-specific Regression Floor. Require the exact unnumbered `## Coverage Matrix` heading in the immutable run-owned plan artifact, exact headers, exactly 9 cells in every data row (including a non-empty Dimension), deterministic OpenAPI Rule Keys for every in-scope affected operation, exactly one Matrix row per Rule Key (merge multi-dimension product rows), and bidirectional Matrix Rule/Test Point ↔ Case bindings. Never describe affected-scope coverage as whole-API completeness. Every explicit AC ID must appear in at least one Case `验收标准`; every explicit in-scope AC/REQ/BR Rule Key cited by a Case must have exactly one Coverage Matrix row, and no Case may cite a source Rule Key omitted from the Matrix. Every Matrix Case ID must share at least one of that row's Required Test Points and the Case must cite that Rule Key. Perform an explicit execution-redundancy review: merge checkpoint-only parameter rows, repeated default/read-back assertions, DELETE status/body/follow-up-read checks, response schema/Content-Type checks, PUT full-update/timestamp checks, repeated list setup and identical null/empty inputs when endpoint, input partition, precondition state and expected outcome are the same. Preserve separate POST/PUT, boundary, enum, wrong-type, role/tenant and distinct business-state variants. Directly repair malformed headings/rows/keys and binding modes rather than merely commenting on them. Reject avoidable English prose, duplicated bilingual wording, repeated boilerplate, oversized unstructured sections, a `### 操作步骤` section that contains only a table without any numbered executable line, vague results such as ‘符合预期’, Case-ID-like module filenames (for example `BE-HEALTH.md`), dropped exact `### 操作步骤`/`### 预期结果` headings, and missing or drifted script/function mapping where it can be derived.",
4624
4648
  "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.",
4625
4649
  "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.",
4626
4650
  "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.",
4627
- "Scenario Partitions synchronization: when README declares `## Scenario Partitions`, verify each declared partition's slots are fully materialized as variant Test Points with exact `TP-<Partition ID>-...` IDs (each-value per Domain value, OMITTED only for optional axes, exactly one NOT-IN-SET with intent=enum-invalid). Directly add missing slot rows/Cases. You may delete an illegal Partition row that has no source-backed finite domain, together with its derived `TP-SP-*` slots/Cases. Never delete a legal source-backed partition or drop its complement slot to force coverage green. When the bound source does not document the complement expectation, keep the slot with GAP expected instead of guessing. Body-field validation enums (`TP-<FIELD>-ENUM-*`) are NOT partitions — do not add partition rows for them.",
4628
- "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.",
4651
+ "Scenario Partitions synchronization: when the run-owned plan declares `## Scenario Partitions`, verify each declared partition's slots are fully materialized as variant Test Points with exact `TP-<Partition ID>-...` IDs (each-value per Domain value, OMITTED only for optional axes, exactly one NOT-IN-SET with intent=enum-invalid). Directly add missing slot rows/Cases. Record an illegal plan Partition row that has no source-backed finite domain as GAP/CONFLICT and remove only its derived `TP-SP-*` slots/Cases from target modules; never modify the immutable plan artifact. Never delete a legal source-backed partition or drop its complement slot to force coverage green. When the bound source does not document the complement expectation, keep the slot with GAP expected instead of guessing. Body-field validation enums (`TP-<FIELD>-ENUM-*`) are NOT partitions — do not add partition rows for them.",
4652
+ "Before returning, verify that every explicit source AC/REQ/BR, error code and strong DTO field token appears in the run-owned plan or an applicable module Case. If a fact cannot be safely automated, retain it as GAP/CONFLICT with its exact source pointer instead of dropping it. Return already-satisfied only when no target file needs an incremental edit.",
4629
4653
  "Read only indexed source paths. Do not scan the repository, modify source/**, generate pytest, execute tests, or emit JSON.",
4630
4654
  ...(sharedSetupPrompt ? [sharedSetupPrompt] : []),
4631
4655
  intake.boundedSourceContext,
@@ -4730,7 +4754,7 @@ async function buildBackendTestHybridDag(sources) {
4730
4754
  retryPolicy: BACKEND_TEST_WRITER_COMPLETENESS_RETRY_POLICY,
4731
4755
  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.",
4732
4756
  subtaskPromptTemplate: [
4733
- "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.",
4757
+ "Convert the single Markdown module testcase/md/{{item.stem}}.md into one self-contained pytest module. Before writing, also read the run-owned Markdown plan artifact at `{{item.planReadPath}}` and use its explicit API target/environment table as the authoritative fallback base URL for every module. A task/Markdown `API_BASE_URL` target takes precedence over project README dev-server URLs; never infer a backend API fallback from a frontend/Vite port such as localhost:3000. After reading the module Markdown, the run-owned plan artifact, and the bounded pytest config/conftest, immediately use write tools to create the single file testcase/test_{{item.stem}}.py. Define any bounded HTTP client fixture, request logging/redaction/truncation helper and payload builders needed by this module inside that same file; do not import generated testcase/**/helpers/** or testcase/**/factories/** assets. Do not end after analysis or planning. Do not modify Markdown, conftest, helpers/factories, or any other module's pytest script.",
4734
4758
  "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.",
4735
4759
  "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.",
4736
4760
  "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.",
@@ -589,6 +589,8 @@ export const dagDynamicExpansionChildTaskSchema = z.object({
589
589
  allowedPaths: z.array(z.string()).optional().default([]),
590
590
  forbiddenPaths: z.array(z.string()).optional().default([]),
591
591
  writeSet: z.array(z.string()).optional(),
592
+ /** Template-rendered strict repository-relative read allowlist. */
593
+ readSet: z.array(z.string()).optional(),
592
594
  /**
593
595
  * Materialized-child pass-through fields for bounded Pi writer children
594
596
  * (backend-test md/pytest case sharding). All optional so legacy
@@ -776,6 +778,8 @@ export const dagTaskSchema = z.object({ id: z.string().regex(/^[a-z][a-z0-9-]*$/
776
778
  commandPolicy: dagCommandPolicySchema.optional(),
777
779
  writePolicy: dagWritePolicySchema.optional(),
778
780
  writeSet: z.array(z.string()).optional(),
781
+ /** Strict repository-relative read allowlist for bounded Pi nodes. */
782
+ readSet: z.array(z.string()).optional(),
779
783
  piStep: z.string().optional(),
780
784
  shell: dagShellConfigSchema.optional(),
781
785
  static: dagStaticConfigSchema.optional(),