@tea-agent/loop-agent 0.33.6-beta.0 → 0.33.6

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 (64) hide show
  1. package/CHANGELOG.md +29 -4
  2. package/dist/application/task-lifecycle/advance.js +254 -4
  3. package/dist/application/task-lifecycle/gates.js +50 -0
  4. package/dist/application/task-lifecycle/observe.js +11 -2
  5. package/dist/commands/init-upgrade.js +32 -1
  6. package/dist/commands/init.js +94 -3
  7. package/dist/executors/shell-write-guard.js +26 -8
  8. package/dist/shared/operator/capabilities.js +72 -42
  9. package/dist/shared/resilient-git.js +133 -0
  10. package/dist/task/source-prepare/artifact-meta.js +137 -0
  11. package/dist/task/source-prepare/index.js +2 -0
  12. package/dist/task/source-prepare/parse-intent.js +58 -10
  13. package/dist/task/source-prepare/prepare.js +180 -16
  14. package/dist/task/source-prepare/reference-integrity.js +18 -2
  15. package/dist/task/source-prepare/semantic-intake.js +404 -0
  16. package/dist/worker/console/app-data.js +2 -0
  17. package/dist/worker/console/chat/chat-event-store.js +190 -25
  18. package/dist/worker/console/chat/pi-console-config.js +250 -32
  19. package/dist/worker/console/chat/pi-runtime.js +625 -71
  20. package/dist/worker/console/chat/resource-loader.js +5 -4
  21. package/dist/worker/console/chat/routes.js +324 -146
  22. package/dist/worker/console/chat/runtime-context.js +48 -12
  23. package/dist/worker/console/chat/runtime-selection.js +59 -0
  24. package/dist/worker/console/chat/shortcuts.js +1 -0
  25. package/dist/worker/console/chat/tool-adapter.js +9 -3
  26. package/dist/worker/console/chat/tools.js +5 -1
  27. package/dist/worker/console/dag-execution-receipt.js +380 -0
  28. package/dist/worker/console/operator-actions.js +559 -68
  29. package/dist/worker/console/server.js +8 -15
  30. package/dist/worker/console/static/assets/index-BUOLppPr.js +28 -0
  31. package/dist/worker/console/static/assets/index-C1KzazY5.css +1 -0
  32. package/dist/worker/console/static/index.html +2 -2
  33. package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +45 -8
  34. package/dist/worker/console/static-src/operator-chat/refs.js +9 -0
  35. package/dist/worker/console/static-src/operator-chat/runtime-snapshot-store.js +257 -0
  36. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +16 -0
  37. package/dist/worker/console/static-src/operator-chat/useChatStream.js +210 -184
  38. package/dist/worker/console/static-src/operator-chat/useChatThread.js +49 -5
  39. package/dist/worker/console/static-src/operator-chat/useComposer.js +17 -0
  40. package/dist/worker/console/static-src/operator-chat/useRuntimeControls.js +225 -74
  41. package/dist/worker/console/static-src/operator-chat/useRuntimeSnapshot.js +196 -0
  42. package/dist/worker/delivery/final-verification.js +13 -5
  43. package/dist/worker/delivery/package.js +31 -19
  44. package/dist/worker/delivery/verification-bundle.js +6 -4
  45. package/dist/worker/observe/static/operator-chrome.css +5 -2
  46. package/dist/worker/observe/static/operator-chrome.js +6 -1
  47. package/dist/worker/observe/static/styles.css +39 -9
  48. package/dist/workflows/dag/backend-test-case-coverage-analysis.js +2 -27
  49. package/dist/workflows/dag/backend-test-module-stem.js +0 -5
  50. package/dist/workflows/dag/backend-test-writer-completeness.js +16 -47
  51. package/dist/workflows/dag/dynamic-runtime/map.js +8 -24
  52. package/dist/workflows/dag/frontend-worktree-diff.js +12 -27
  53. package/dist/workflows/dag/init-hybrid.js +12 -20
  54. package/dist/workflows/dag/types.js +0 -7
  55. package/dist/workflows/dag/workspace-checkpoint.js +8 -27
  56. package/docs/templates/backend-test-dag.json +10 -10
  57. package/harness.json +1 -1
  58. package/package.json +1 -1
  59. package/skills/loop-agent/references/command-reference.md +3 -1
  60. package/skills/loop-agent/references/source-and-plan-practice.md +13 -0
  61. package/skills/loop-agent/references/task-workflow.md +4 -0
  62. package/dist/worker/console/chat/instruction-skills.js +0 -217
  63. package/dist/worker/console/static/assets/index-CnUXAqxG.css +0 -1
  64. package/dist/worker/console/static/assets/index-CteJFFL2.js +0 -29
@@ -3508,29 +3508,23 @@ const readme=fs.existsSync('testcase/md/README.md')?fs.readFileSync('testcase/md
3508
3508
  const norm=s=>String(s).toLowerCase().replace(/[^a-z0-9]+/g,'_').replace(/^_+|_+$/g,'').replace(/_+/g,'_');
3509
3509
  const bt=String.fromCharCode(96);
3510
3510
  const stripBackticks=s=>s.split(bt).join('');
3511
- 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;};
3511
+ 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;};
3512
3512
  const valid=raw=>invalidReason(raw)===null;
3513
3513
  const rxMdPath=/testcase\\/md\\/([A-Za-z0-9_.-]+)\\.md/g;
3514
3514
  const rxTableRow=/\\|\\s*([A-Za-z0-9_.-]+)\\s*\\|\\s*testcase\\/test_/g;
3515
3515
  const rxRelLink=/\\[[^\\]]+\\]\\(\\.\\/([A-Za-z0-9_.-]+)\\.md\\)/g;
3516
- const allLines=readme.replace(/\\r\\n/g,'\\n').replace(/\\r/g,'\\n').split('\\n');
3517
- const headings=[];for(let i=0;i<allLines.length;i++){if(allLines[i].trim()==='## Module Index')headings.push(i);}
3518
- 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);}
3519
- 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;}}
3520
- const section=allLines.slice(start,end).join('\\n');
3521
3516
  const raw=[];
3522
- const lines=section.split('\\n').filter(l=>l.includes('|'));
3517
+ const lines=readme.replace(/\\r\\n/g,'\\n').replace(/\\r/g,'\\n').split('\\n').filter(l=>l.includes('|'));
3523
3518
  for(const line of lines){
3524
3519
  const bare=stripBackticks(line);
3525
3520
  for(const m of bare.matchAll(rxMdPath)){raw.push(m[1]);}
3526
- for(const m of bare.matchAll(rxTableRow)){if(valid(m[1])||invalidReason(m[1])!=='invalid-syntax')raw.push(m[1]);}
3521
+ for(const m of bare.matchAll(rxTableRow)){if(valid(m[1])||invalidReason(m[1])==='priority-only-module-stem')raw.push(m[1]);}
3527
3522
  }
3528
- for(const m of section.matchAll(rxRelLink)){raw.push(m[1]);}
3523
+ for(const m of readme.matchAll(rxRelLink)){raw.push(m[1]);}
3529
3524
  const invalid=[];for(const r of raw){const reason=invalidReason(r);if(reason)invalid.push({stem:norm(r),reason});}
3530
3525
  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);}
3531
3526
  const seen=new Set();const modules=[];
3532
3527
  for(const r of raw){const st=norm(r);if(valid(r)&&!seen.has(st)){seen.add(st);modules.push({stem:st});}}
3533
- 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);}
3534
3528
  process.stdout.write(JSON.stringify({modules}));
3535
3529
  `;
3536
3530
  const encoded = Buffer.from(script, "utf8").toString("base64");
@@ -3608,7 +3602,7 @@ async function buildBackendTestHybridDag(sources) {
3608
3602
  "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.",
3609
3603
  "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.",
3610
3604
  "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.",
3611
- "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.",
3605
+ "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.",
3612
3606
  "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.",
3613
3607
  intake.boundedSourceContext,
3614
3608
  "## Authoritative reference index",
@@ -3653,11 +3647,10 @@ async function buildBackendTestHybridDag(sources) {
3653
3647
  workflowNodeId: "generate-backend-md-cases-map",
3654
3648
  itemsFrom: "$.nodes['materialize-backend-md-module-manifest-shell'].output.modules",
3655
3649
  itemName: "item",
3656
- maxItems: 8,
3657
- maxExpandedNodes: 8,
3650
+ maxItems: 64,
3651
+ maxExpandedNodes: 64,
3658
3652
  childIdPrefix: "generate-backend-md-case",
3659
- tokenBudget: { maxTotalTokens: 600000 },
3660
- failOnTokenBudgetExhaustion: true,
3653
+ tokenBudget: { maxTokensPerCase: 16384, maxTotalTokens: 600000 },
3661
3654
  childTask: {
3662
3655
  executor: "pi",
3663
3656
  role: "implementer",
@@ -3680,7 +3673,7 @@ async function buildBackendTestHybridDag(sources) {
3680
3673
  "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.",
3681
3674
  "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.",
3682
3675
  '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.',
3683
- "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.",
3676
+ "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.",
3684
3677
  "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 ‘符合预期’.",
3685
3678
  "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.",
3686
3679
  intake.boundedSourceContext,
@@ -3784,11 +3777,10 @@ async function buildBackendTestHybridDag(sources) {
3784
3777
  workflowNodeId: "generate-backend-pytest-cases-map",
3785
3778
  itemsFrom: "$.nodes['materialize-backend-pytest-module-manifest-shell'].output.modules",
3786
3779
  itemName: "item",
3787
- maxItems: 8,
3788
- maxExpandedNodes: 8,
3780
+ maxItems: 64,
3781
+ maxExpandedNodes: 64,
3789
3782
  childIdPrefix: "generate-backend-pytest-case",
3790
- tokenBudget: { maxTotalTokens: 600000 },
3791
- failOnTokenBudgetExhaustion: true,
3783
+ tokenBudget: { maxTokensPerCase: 16384, maxTotalTokens: 600000 },
3792
3784
  childTask: {
3793
3785
  executor: "pi",
3794
3786
  role: "implementer",
@@ -555,13 +555,6 @@ export const dagDynamicExpansionSchema = z.object({
555
555
  maxTotalTokens: z.number().int().positive().optional(),
556
556
  })
557
557
  .optional(),
558
- /**
559
- * When true, any child blocked by the aggregate token budget fails the map
560
- * barrier instead of being retained as a case-level blocked outcome.
561
- * Backend-test enables this because partial Markdown/pytest module sets are
562
- * invalid generation assets; frontend-test keeps the default false.
563
- */
564
- failOnTokenBudgetExhaustion: z.boolean().optional(),
565
558
  /**
566
559
  * When true, map child ERROR/auth/timeout is recorded as case-level
567
560
  * failed/blocked evidence and the map barrier still succeeds (frontend-test).
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
- import { spawn } from "node:child_process";
3
2
  import { lstat, readFile, realpath } from "node:fs/promises";
4
3
  import path from "node:path";
4
+ import { runResilientGitCommand } from "../../shared/resilient-git.js";
5
5
  import { writeJsonAtomic } from "../../infrastructure/harness/atomic-write.js";
6
6
  /**
7
7
  * Workspace checkpoint for DAG continuation safety.
@@ -13,30 +13,10 @@ function sha256Hex(input) {
13
13
  return createHash("sha256").update(input).digest("hex");
14
14
  }
15
15
  async function runGit(cwd, args) {
16
- return new Promise((resolve, reject) => {
17
- const child = spawn("git", args, {
18
- cwd,
19
- stdio: ["ignore", "pipe", "pipe"],
20
- });
21
- let stdout = "";
22
- let stderr = "";
23
- child.stdout.setEncoding("utf-8");
24
- child.stderr.setEncoding("utf-8");
25
- child.stdout.on("data", (chunk) => {
26
- stdout += chunk;
27
- });
28
- child.stderr.on("data", (chunk) => {
29
- stderr += chunk;
30
- });
31
- child.on("error", reject);
32
- child.on("close", (code) => {
33
- if (code === 0) {
34
- resolve(stdout);
35
- return;
36
- }
37
- reject(new Error(`git ${args.join(" ")} failed: ${stderr.trim() || stdout.trim()}`));
38
- });
39
- });
16
+ const result = await runResilientGitCommand({ cwd, args, readOnly: true });
17
+ if (result.code === 0)
18
+ return result.stdout;
19
+ throw new Error(`git ${args.join(" ")} failed: ${result.stderr.trim() || result.stdout.trim() || `exit ${result.code}`}`);
40
20
  }
41
21
  function normalizeGitPath(value) {
42
22
  const target = value.includes(" -> ")
@@ -137,9 +117,10 @@ async function hashStableGovernanceInputs(repoRoot, taskId) {
137
117
  * When `taskId` is provided, fingerprint includes stable ignored Task Contract inputs.
138
118
  */
139
119
  export async function captureWorkspaceCheckpoint(repoRoot, options) {
120
+ const run = options?.dependencies?.runGit ?? runGit;
140
121
  const capturedAt = (options?.now ?? new Date()).toISOString();
141
- const gitHeadSha = (await runGit(repoRoot, ["rev-parse", "HEAD"])).trim();
142
- const porcelain = await runGit(repoRoot, [
122
+ const gitHeadSha = (await run(repoRoot, ["rev-parse", "HEAD"])).trim();
123
+ const porcelain = await run(repoRoot, [
143
124
  "status",
144
125
  "--porcelain=v1",
145
126
  "--untracked-files=all",
@@ -140,7 +140,7 @@
140
140
  ]
141
141
  },
142
142
  "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.",
143
- "subtask_prompt": "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.\n\nOutput 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.\n\nThe 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.\n\nRead the upstream environment report. Generate the Markdown-first backend test README under testcase/md/README.md.\n\nWrite 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.\n\nCreate 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.\n\nBefore 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.\n\nCoverage 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.\n\nBefore 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.\n\nEach 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.\n\nCoverage 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.\n\nFor 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.\n\nMandatory 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.\n\nBefore 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.\n\n## Derived task contract: 需求.md\n\n# Backend test\n- AC-001 proof\n\n## Authoritative reference index\n\n[]\n\nFor each index entry, use `readPath` for Pi read-tool calls and copy `path` exactly into Markdown Source References. 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.\n\nRead only precise indexed references needed for AC/API/field/rule evidence; references remain authoritative over derived text."
143
+ "subtask_prompt": "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.\n\nOutput 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.\n\nThe 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.\n\nRead the upstream environment report. Generate the Markdown-first backend test README under testcase/md/README.md.\n\nWrite 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.\n\nCreate 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.\n\nBefore 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.\n\nCoverage 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.\n\nBefore 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.\n\nEach 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.\n\nCoverage 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.\n\nFor 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.\n\nMandatory 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.\n\nBefore 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.\n\n## Derived task contract: 需求.md\n\n# Backend test\n- AC-001 proof\n\n## Authoritative reference index\n\n[]\n\nFor each index entry, use `readPath` for Pi read-tool calls and copy `path` exactly into Markdown Source References. 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.\n\nRead only precise indexed references needed for AC/API/field/rule evidence; references remain authoritative over derived text."
144
144
  },
145
145
  {
146
146
  "id": "materialize-backend-md-module-manifest-shell",
@@ -164,7 +164,7 @@
164
164
  "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.",
165
165
  "shell": {
166
166
  "commands": [
167
- "node -e \"eval(Buffer.from('Y29uc3QgZnM9cmVxdWlyZSgnZnMnKTsKY29uc3QgcmVhZG1lPWZzLmV4aXN0c1N5bmMoJ3Rlc3RjYXNlL21kL1JFQURNRS5tZCcpP2ZzLnJlYWRGaWxlU3luYygndGVzdGNhc2UvbWQvUkVBRE1FLm1kJywndXRmOCcpOicnOwpjb25zdCBub3JtPXM9PlN0cmluZyhzKS50b0xvd2VyQ2FzZSgpLnJlcGxhY2UoL1teYS16MC05XSsvZywnXycpLnJlcGxhY2UoL15fK3xfKyQvZywnJykucmVwbGFjZSgvXysvZywnXycpOwpjb25zdCBidD1TdHJpbmcuZnJvbUNoYXJDb2RlKDk2KTsKY29uc3Qgc3RyaXBCYWNrdGlja3M9cz0+cy5zcGxpdChidCkuam9pbignJyk7CmNvbnN0IGludmFsaWRSZWFzb249cmF3PT57Y29uc3Qgc3Q9bm9ybShyYXcpO2lmKC9ecFsw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3LnB1c2gobVsxXSk7fQogIGZvcihjb25zdCBtIG9mIGJhcmUubWF0Y2hBbGwocnhUYWJsZVJvdykpe2lmKHZhbGlkKG1bMV0pfHxpbnZhbGlkUmVhc29uKG1bMV0pPT09J3ByaW9yaXR5LW9ubHktbW9kdWxlLXN0ZW0nKXJhdy5wdXNoKG1bMV0pO30KfQpmb3IoY29uc3QgbSBvZiByZWFkbWUubWF0Y2hBbGwocnhSZWxMaW5rKSl7cmF3LnB1c2gobVsxXSk7fQpjb25zdCBpbnZhbGlkPVtdO2Zvcihjb25zdCByIG9mIHJhdyl7Y29uc3QgcmVhc29uPWludmFsaWRSZWFzb24ocik7aWYocmVhc29uKWludmFsaWQucHVzaCh7c3RlbTpub3JtKHIpLHJlYXNvbn0pO30KaWYoaW52YWxpZC5sZW5ndGgpe2Zvcihjb25zdCBpdGVtIG9mIGludmFsaWQpcHJvY2Vzcy5zdGRlcnIud3JpdGUoaXRlbS5yZWFzb24rJzogJytpdGVtLnN0ZW0rJzsgdXNlIGEgc3RhYmxlIGJ1c2luZXNzIHJlc291cmNlL2RvbWFpbiBzdGVtXG4nKTtwcm9jZXNzLmV4aXQoMik7fQpjb25zdCBzZWVuPW5ldyBTZXQoKTtjb25zdCBtb2R1bGVzPVtdOwpmb3IoY29uc3QgciBvZiByYXcpe2NvbnN0IHN0PW5vcm0ocik7aWYodmFsaWQocikmJiFzZWVuLmhhcyhzdCkpe3NlZW4uYWRkKHN0KTttb2R1bGVzLnB1c2goe3N0ZW06c3R9KTt9fQpwcm9jZXNzLnN0ZG91dC53cml0ZShKU09OLnN0cmluZ2lmeSh7bW9kdWxlc30pKTsK','base64').toString('utf8'))\""
168
168
  ],
169
169
  "cwd": ".",
170
170
  "timeoutMs": 60000
@@ -195,13 +195,13 @@
195
195
  "workflowNodeId": "generate-backend-md-cases-map",
196
196
  "itemsFrom": "$.nodes['materialize-backend-md-module-manifest-shell'].output.modules",
197
197
  "itemName": "item",
198
- "maxItems": 8,
199
- "maxExpandedNodes": 8,
198
+ "maxItems": 64,
199
+ "maxExpandedNodes": 64,
200
200
  "childIdPrefix": "generate-backend-md-case",
201
201
  "tokenBudget": {
202
+ "maxTokensPerCase": 16384,
202
203
  "maxTotalTokens": 600000
203
204
  },
204
- "failOnTokenBudgetExhaustion": true,
205
205
  "childTask": {
206
206
  "executor": "pi",
207
207
  "role": "implementer",
@@ -238,7 +238,7 @@
238
238
  ]
239
239
  },
240
240
  "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.",
241
- "subtaskPromptTemplate": "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.\n\nOutput 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.\n\nThe 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.\n\nWrite 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.\n\nWrite 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.\n\nName 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.\n\nEvery 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 ‘符合预期’.\n\nIn 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.\n\n## Derived task contract: 需求.md\n\n# Backend test\n- AC-001 proof\n\n## Authoritative reference index\n\n[]\n\nFor each index entry, use `readPath` for Pi read-tool calls and copy `path` exactly into Markdown Source References. 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.\n\nRead only precise indexed references needed for AC/API/field/rule evidence; references remain authoritative over derived text."
241
+ "subtaskPromptTemplate": "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.\n\nOutput 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.\n\nThe 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.\n\nWrite 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.\n\nWrite 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.\n\nName 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.\n\nEvery 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 ‘符合预期’.\n\nIn 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.\n\n## Derived task contract: 需求.md\n\n# Backend test\n- AC-001 proof\n\n## Authoritative reference index\n\n[]\n\nFor each index entry, use `readPath` for Pi read-tool calls and copy `path` exactly into Markdown Source References. 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.\n\nRead only precise indexed references needed for AC/API/field/rule evidence; references remain authoritative over derived text."
242
242
  }
243
243
  }
244
244
  },
@@ -338,7 +338,7 @@
338
338
  "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.",
339
339
  "shell": {
340
340
  "commands": [
341
- "node -e \"eval(Buffer.from('Y29uc3QgZnM9cmVxdWlyZSgnZnMnKTsKY29uc3QgcmVhZG1lPWZzLmV4aXN0c1N5bmMoJ3Rlc3RjYXNlL21kL1JFQURNRS5tZCcpP2ZzLnJlYWRGaWxlU3luYygndGVzdGNhc2UvbWQvUkVBRE1FLm1kJywndXRmOCcpOicnOwpjb25zdCBub3JtPXM9PlN0cmluZyhzKS50b0xvd2VyQ2FzZSgpLnJlcGxhY2UoL1teYS16MC05XSsvZywnXycpLnJlcGxhY2UoL15fK3xfKyQvZywnJykucmVwbGFjZSgvXysvZywnXycpOwpjb25zdCBidD1TdHJpbmcuZnJvbUNoYXJDb2RlKDk2KTsKY29uc3Qgc3RyaXBCYWNrdGlja3M9cz0+cy5zcGxpdChidCkuam9pbignJyk7CmNvbnN0IGludmFsaWRSZWFzb249cmF3PT57Y29uc3Qgc3Q9bm9ybShyYXcpO2lmKC9ecFswLTJdJC8udGVzdChzdCkpcmV0dXJuICdwcmlvcml0eS1vbmx5LW1vZHVsZS1zdGVtJztpZigvXlthLWZdW2EtZjAtOV17Niw2M30kLy50ZXN0KHN0KSlyZXR1cm4gJ29wYXF1ZS1oYXNoLW1vZHVsZS1zdGVtJztpZihzdD09PSdyZWFkbWUnKXJldHVybiAncmVzZXJ2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pzdH0pO319CnByb2Nlc3Muc3Rkb3V0LndyaXRlKEpTT04uc3RyaW5naWZ5KHttb2R1bGVzfSkpOwo=','base64').toString('utf8'))\""
342
342
  ],
343
343
  "cwd": ".",
344
344
  "timeoutMs": 60000
@@ -369,13 +369,13 @@
369
369
  "workflowNodeId": "generate-backend-pytest-cases-map",
370
370
  "itemsFrom": "$.nodes['materialize-backend-pytest-module-manifest-shell'].output.modules",
371
371
  "itemName": "item",
372
- "maxItems": 8,
373
- "maxExpandedNodes": 8,
372
+ "maxItems": 64,
373
+ "maxExpandedNodes": 64,
374
374
  "childIdPrefix": "generate-backend-pytest-case",
375
375
  "tokenBudget": {
376
+ "maxTokensPerCase": 16384,
376
377
  "maxTotalTokens": 600000
377
378
  },
378
- "failOnTokenBudgetExhaustion": true,
379
379
  "childTask": {
380
380
  "executor": "pi",
381
381
  "role": "implementer",
package/harness.json CHANGED
@@ -81,7 +81,7 @@
81
81
  "pi": {
82
82
  "description": "Pi 负责规划、评审、诊断;当 DAG toolProfile=write 时也可做有界写入。模型按复杂度三档配置,格式为 provider/model 字符串(例:wizard-local/grok-4.5);斜杠前为 Pi provider,后为 modelId,勿只写裸 modelId。",
83
83
  "LOW": "wizard-local/minimax-m3",
84
- "MED": "wizard-local/gpt-5.6-sol",
84
+ "MED": "wizard-local/gpt-5.6-terra",
85
85
  "HIGH": "wizard-local/gpt-5.6-sol"
86
86
  }
87
87
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tea-agent/loop-agent",
3
- "version": "0.33.6-beta.0",
3
+ "version": "0.33.6",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "loop-agent": "bin/loop-agent.js",
@@ -224,7 +224,9 @@ loop-agent task advance <task-id> "标题" \
224
224
  --json
225
225
  ```
226
226
 
227
- 默认无 LLM 写 source;工程边界用 flags 显式给出。不要让 AI 直接改写 `source/references/*`。高级用户仍可手工编辑后 `task advance --from-draft`。
227
+ 默认无 LLM 写 source;工程边界用 flags 显式给出。不要让 AI 直接改写 `source/references/*`。
228
+ Product Requirement V3/V4(`product-requirement.md`)由确定性解析消费;`product-analysis` / `requirement-clarification` 不能单独作为可执行 PRD。
229
+ intake 失败时不要在原 PRD 目录生成兼容 md/json;`--from-draft` **仅**人工 reviewed draft / managed 恢复 / 调试,不是 `EMPTY_ACCEPTANCE` 默认恢复路径。
228
230
 
229
231
  ### Feature-study workflow(参考代码 → 轻量实现)
230
232
 
@@ -41,6 +41,19 @@ Task 目录布局:`task-workflow.md`。
41
41
  - 把用户 PRD **整篇改写**进 `需求.md` 后删掉原文路径。
42
42
  - AI 直接 edit `source/references/*`。
43
43
  - 只把 PRD 路径写在聊天里,不落盘到 task 容器。
44
+ - 把 `product-analysis.md` 当可执行 PRD,或把 analysis/clarification 改写成假 AC 以通过 prepare。
45
+ - intake 失败后在原 PRD 目录生成「兼容格式」Markdown / `reviewed-draft.json`,再用 `--from-draft` 绕过(默认禁止)。
46
+ - 把 `--from-draft` 当作 `EMPTY_ACCEPTANCE` 的自动恢复手段。
47
+
48
+ ### Product Analysis 套件
49
+
50
+ | 文件 | role | 用途 |
51
+ |---|---|---|
52
+ | `product-requirement.md` | `requirement` | **唯一**可执行需求事实源(complete 后才进 DAG) |
53
+ | `product-analysis.md` | `analysis` | 分析证据;**不能**单独作为 requirement |
54
+ | `requirement-clarification.md` | `clarification` | 决策追溯;**不能**单独作为 requirement |
55
+
56
+ `task advance --prd` 可多次传入;未写 `--role` 时按路径/frontmatter 推断。intake 未完成时 lifecycle 为 `intake-incomplete`(PRD 已归档,DAG 未生成)。
44
57
 
45
58
  ### 推荐顺序(有 PRD 时)
46
59
 
@@ -37,6 +37,10 @@ loop-agent task status <task-id> --json
37
37
  ```
38
38
 
39
39
  - 用户原始 PRD 用 `task advance --prd <prd>` 归档到 `source/references/`,禁止 AI 改写。**有文件就归档**。
40
+ - Product Analysis 套件职责:`product-requirement.md` 是唯一可执行需求事实源;`product-analysis.md` / `requirement-clarification.md` 仅引用。未显式 `--role` 时按文件名/frontmatter 推断(analysis / clarification / requirement)。
41
+ - 遇到 `PRODUCT_ANALYSIS_NOT_EXECUTABLE` / `PRODUCT_REQUIREMENT_PENDING` / `EMPTY_ACCEPTANCE`:**禁止**改写原始产物,**禁止**在原 PRD 目录生成兼容 Markdown 或 `reviewed-draft.json` 自救;应换正确 requirement 文档或补真实验收标准后重试。
42
+ - `--from-draft` 仅用于人工 reviewed draft / managed 恢复 / 调试,不是 intake 失败的默认恢复路径。
43
+ - 确定性解析失败且缺口为结构性时,`task advance` 可自动做**一次** Semantic Intake(只读 Pi → `artifacts/intake/semantic-draft.json` → prepare);analysis/pending/真缺决策不会调用。可用 `LOOP_AGENT_SEMANTIC_INTAKE=0` 关闭。禁止在原 PRD 目录写 sidecar。
40
44
  - 默认用 `task advance`(带 `--allowed-path` / `--verify`)投影 `需求.md` / `执行约束.md` 与 managed paths;**不要**默认让 LLM/主会话手写两 source。
41
45
  - 无独立 PRD 的微小任务可用 `task advance --from-text ...` escape hatch(见 `source-and-plan-practice.md`)。
42
46
  - 若 `ai_workspace/loop-agent/` 已有权威 plan/spec/PRD,优先 `task advance --prd` 归档并派生薄契约;避免把长 PRD 直接改写成唯一 source。
@@ -1,217 +0,0 @@
1
- /**
2
- * Operator Chat — instruction skills whitelist (design §7.5 / plan D1).
3
- *
4
- * Hard rules (plan D1):
5
- * - skills are READ-ONLY text context injected into the Chat system prompt;
6
- * - skills are NEVER registered as executable tools;
7
- * - the whitelist is a COMPILE-TIME constant (no runtime dir scan, no env override);
8
- * - arbitrary pi extension / package tool / user-level ~/.pi/agent skill is
9
- * never discovered or loaded (V12);
10
- * - project `.agents/skills/` (init projection) is NOT injected (prevents
11
- * target-repo injecting write instructions).
12
- *
13
- * Only the loop-agent repo's own audited skills are eligible. Workflow-specific
14
- * skills are conditional on taskKind/workflow and loaded on demand (not in MVP
15
- * operator-context default set).
16
- */
17
- import { readFile } from "node:fs/promises";
18
- import path from "node:path";
19
- /**
20
- * Operator-context instruction skills (plan D1, "operator-context 允许").
21
- * These are read-only methodology skills. Loaded as text context for every
22
- * Chat session by default.
23
- *
24
- * MUST stay a compile-time constant. Adding a skill requires an ADR / plan note.
25
- */
26
- export const OPERATOR_CHAT_ALLOWED_INSTRUCTION_SKILLS = Object.freeze([
27
- "grill-me",
28
- "systematic-debugging",
29
- "code-review-core",
30
- "codebase-scout",
31
- "verification-before-completion",
32
- "requesting-code-review",
33
- "analyze-product-requirements",
34
- "analyze-product-dependencies",
35
- "using-git-worktrees",
36
- ]);
37
- /**
38
- * Meta / governance skills that must NEVER be injected into Chat context
39
- * (plan D1 "元 / 治理 skill"). Injecting these would let Chat rewrite its own
40
- * governance. Listed explicitly so accidental allowlist edits are caught.
41
- */
42
- export const OPERATOR_CHAT_DENIED_INSTRUCTION_SKILLS = Object.freeze([
43
- "loop-agent",
44
- "agent-worker",
45
- "init-capability-evolution",
46
- "ai-engineering-context",
47
- "grill-with-docs",
48
- ]);
49
- /**
50
- * Workflow-specific skills (plan D1 "workflow-specific 允许(条件)").
51
- * Only injected when the corresponding taskKind / workflow is active.
52
- * NOT loaded by default in MVP Chat.
53
- */
54
- export const OPERATOR_CHAT_WORKFLOW_CONDITIONAL_SKILLS = Object.freeze([
55
- "frontend-implementation",
56
- "frontend-review",
57
- "frontend-verification",
58
- "frontend-design-review",
59
- "test-driven-development",
60
- "webapp-testing",
61
- "playwright-cli",
62
- "playwright-cli-case-generator",
63
- "browser-tools",
64
- ]);
65
- const ALLOWED = new Set(OPERATOR_CHAT_ALLOWED_INSTRUCTION_SKILLS.map((s) => s.toLowerCase()));
66
- const DENIED = new Set(OPERATOR_CHAT_DENIED_INSTRUCTION_SKILLS.map((s) => s.toLowerCase()));
67
- const CONDITIONAL = new Set(OPERATOR_CHAT_WORKFLOW_CONDITIONAL_SKILLS.map((s) => s.toLowerCase()));
68
- export function isOperatorChatInstructionSkillAllowed(name) {
69
- return ALLOWED.has(name.trim().toLowerCase());
70
- }
71
- export function isOperatorChatInstructionSkillDenied(name) {
72
- return DENIED.has(name.trim().toLowerCase());
73
- }
74
- export function isOperatorChatInstructionSkillConditional(name) {
75
- return CONDITIONAL.has(name.trim().toLowerCase());
76
- }
77
- export function classifyInstructionSkill(name, options) {
78
- const n = name.trim().toLowerCase();
79
- if (DENIED.has(n)) {
80
- return { ok: false, reason: "denied-governance", name };
81
- }
82
- if (ALLOWED.has(n)) {
83
- return { ok: true, kind: "operator-context", name };
84
- }
85
- if (CONDITIONAL.has(n)) {
86
- const active = options?.activeWorkflowSkills ?? [];
87
- const activeLower = new Set(active.map((s) => s.toLowerCase()));
88
- if (activeLower.has(n)) {
89
- // Conditional skill is allowed only when explicitly activated by workflow.
90
- // For MVP, conditional skills are not auto-injected; callers must opt in.
91
- return { ok: false, reason: "conditional-not-active", name };
92
- }
93
- return { ok: false, reason: "conditional-not-active", name };
94
- }
95
- return { ok: false, reason: "unknown", name };
96
- }
97
- /**
98
- * Parse a SKILL.md frontmatter description (first `description:` line) and
99
- * return the body text (frontmatter stripped). Tolerant of missing frontmatter.
100
- */
101
- export function parseSkillFrontmatter(raw) {
102
- let description = "";
103
- let bodyText = raw;
104
- const hasFrontmatter = raw.trimStart().startsWith("---");
105
- if (hasFrontmatter) {
106
- const lines = raw.split(/\r?\n/);
107
- // find closing ---
108
- let closeIdx = -1;
109
- for (let i = 1; i < lines.length; i++) {
110
- if (lines[i].trim() === "---") {
111
- closeIdx = i;
112
- break;
113
- }
114
- }
115
- if (closeIdx > 0) {
116
- const fm = lines.slice(1, closeIdx).join("\n");
117
- bodyText = lines.slice(closeIdx + 1).join("\n").trim();
118
- const descMatch = fm.match(/^description:\s*(.+)$/m);
119
- if (descMatch) {
120
- description = descMatch[1].trim().replace(/^["']|["']$/g, "");
121
- }
122
- }
123
- }
124
- else {
125
- bodyText = raw.trim();
126
- }
127
- return { description, bodyText };
128
- }
129
- /**
130
- * Load the operator-context instruction skills from the loop-agent repo's own
131
- * `skills/` directory and return their text bodies for system-prompt injection.
132
- *
133
- * Security: only names in OPERATOR_CHAT_ALLOWED_INSTRUCTION_SKILLS are read;
134
- * any other path is rejected before filesystem access (safe-side).
135
- *
136
- * @param skillsDir absolute path to the loop-agent repo `skills/` directory
137
- * (source repo / npm pack asset, NOT target project `.agents/skills/`).
138
- * @param names override list (tests); defaults to the full allowlist.
139
- */
140
- export async function loadOperatorChatInstructionSkills(skillsDir, names) {
141
- const selected = names ?? OPERATOR_CHAT_ALLOWED_INSTRUCTION_SKILLS;
142
- const loaded = [];
143
- const failures = [];
144
- const skipped = [];
145
- for (const rawName of selected) {
146
- const name = rawName.trim();
147
- if (!isOperatorChatInstructionSkillAllowed(name)) {
148
- skipped.push(name);
149
- continue;
150
- }
151
- // Defense in depth: reject path traversal / governance skills even if
152
- // an attacker managed to mutate the allowlist at runtime.
153
- if (isOperatorChatInstructionSkillDenied(name)) {
154
- skipped.push(name);
155
- continue;
156
- }
157
- const skillPath = path.join(skillsDir, name, "SKILL.md");
158
- const resolved = path.resolve(skillPath);
159
- const resolvedSkillsDir = path.resolve(skillsDir);
160
- if (!resolved.startsWith(resolvedSkillsDir + path.sep)) {
161
- failures.push({
162
- name,
163
- message: "path escapes skills directory",
164
- });
165
- continue;
166
- }
167
- try {
168
- const raw = await readFile(resolved, "utf8");
169
- const { description, bodyText } = parseSkillFrontmatter(raw);
170
- loaded.push({
171
- name,
172
- description,
173
- bodyText,
174
- charCount: bodyText.length,
175
- });
176
- }
177
- catch (error) {
178
- failures.push({
179
- name,
180
- message: error instanceof Error ? error.message : String(error),
181
- });
182
- }
183
- }
184
- return { loaded, failures, skipped };
185
- }
186
- /** Hard cap on total injected instruction-skill chars (token budget guard). */
187
- export const OPERATOR_CHAT_INSTRUCTION_CHAR_BUDGET = 24_000;
188
- /**
189
- * Compose the system-prompt fragment listing loaded instruction skills.
190
- * Each skill is rendered as a bounded text block. If total chars exceed the
191
- * budget, later skills are truncated (operator-context set is small enough
192
- * that truncation should not trigger in practice, but the cap is enforced).
193
- */
194
- export function composeInstructionSkillsPrompt(skills, budget = OPERATOR_CHAT_INSTRUCTION_CHAR_BUDGET) {
195
- if (skills.length === 0)
196
- return "";
197
- const lines = [
198
- "## Operator methodology context (read-only instruction skills)",
199
- "",
200
- "These skills are READ-ONLY context. You may reference their methodology when reasoning, but you CANNOT execute them. All actions must go through the registered operator tools.",
201
- "",
202
- ];
203
- let used = 0;
204
- for (const skill of skills) {
205
- const header = `\n### ${skill.name}${skill.description ? ` — ${skill.description}` : ""}\n`;
206
- const remaining = budget - used - header.length;
207
- if (remaining <= 0) {
208
- lines.push(`_[${skill.name}: omitted, char budget exhausted]_`);
209
- break;
210
- }
211
- const slice = skill.bodyText.slice(0, Math.max(0, remaining));
212
- lines.push(header);
213
- lines.push(slice);
214
- used += header.length + slice.length;
215
- }
216
- return lines.join("\n");
217
- }