@thincoder/core 0.10.13 → 0.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (366) hide show
  1. package/CHANGELOG.md +74 -1
  2. package/advisor/convergence.mjs +34 -3
  3. package/advisor/loop.mjs +42 -10
  4. package/advisor/messages.mjs +46 -27
  5. package/advisor/notice.mjs +1 -1
  6. package/advisor/project-context.mjs +253 -14
  7. package/advisor/run.mjs +7 -4
  8. package/advisor.mjs +29 -43
  9. package/agent/batch-attribution.mjs +87 -0
  10. package/agent/batch-changed-surface.mjs +129 -0
  11. package/agent/completion.mjs +57 -4
  12. package/agent/digest-account.mjs +73 -46
  13. package/agent/dispatch-gates.mjs +6 -0
  14. package/agent/dispatch-run.mjs +1 -1
  15. package/agent/dispatch.mjs +35 -22
  16. package/agent/family-tools.mjs +36 -17
  17. package/agent/helpers.mjs +123 -95
  18. package/agent/offload.mjs +84 -0
  19. package/agent/post-turn.mjs +24 -10
  20. package/agent/record-results.mjs +19 -7
  21. package/agent/run-stages.mjs +127 -61
  22. package/agent/run-start.mjs +45 -8
  23. package/agent/setup-reminders.mjs +9 -2
  24. package/agent/setup.mjs +27 -22
  25. package/agent/spawn-child.mjs +38 -1
  26. package/agent/suspension.mjs +1 -1
  27. package/agent/timers.mjs +5 -3
  28. package/agent/turn-loop.mjs +60 -6
  29. package/agent/turn-projection.mjs +386 -0
  30. package/agent/turn-task-state.mjs +274 -0
  31. package/agent/turn-tool-process.mjs +168 -0
  32. package/agent/write-face.mjs +99 -0
  33. package/agent/write-gate-ledger.mjs +569 -0
  34. package/agent/write-gate.mjs +39 -13
  35. package/agent-tools/advisor-async.mjs +29 -169
  36. package/agent-tools/advisor-launch.mjs +178 -0
  37. package/agent-tools/advisor-settle.mjs +28 -1
  38. package/agent-tools/advisor.mjs +136 -31
  39. package/agent-tools/async-settle.mjs +2 -2
  40. package/agent-tools/audit-block.mjs +6 -6
  41. package/agent-tools/bash-async.mjs +8 -2
  42. package/agent-tools/batch-closeout.mjs +444 -0
  43. package/agent-tools/batch-gate.mjs +152 -138
  44. package/agent-tools/batch-ledger-bind.mjs +392 -0
  45. package/agent-tools/batch-ledger-link.mjs +73 -0
  46. package/agent-tools/batch-ledger-view.mjs +109 -0
  47. package/agent-tools/batch-lifecycle.mjs +245 -376
  48. package/agent-tools/batch-paths.mjs +73 -47
  49. package/agent-tools/batch-read.mjs +1 -1
  50. package/agent-tools/batch-record-write.mjs +417 -0
  51. package/agent-tools/batch-regions.mjs +215 -0
  52. package/agent-tools/batch-reopen.mjs +154 -0
  53. package/agent-tools/batch-segment-vocab.mjs +379 -0
  54. package/agent-tools/batch-skeleton.mjs +344 -196
  55. package/agent-tools/batch-supersede.mjs +232 -0
  56. package/agent-tools/batch-tier-gate.mjs +297 -0
  57. package/agent-tools/batch.mjs +189 -253
  58. package/agent-tools/consult.mjs +7 -4
  59. package/agent-tools/context.mjs +47 -17
  60. package/agent-tools/design-review-record.mjs +225 -0
  61. package/agent-tools/design-slots.mjs +24 -24
  62. package/agent-tools/design-token.mjs +318 -39
  63. package/agent-tools/doc-check.mjs +55 -29
  64. package/agent-tools/doc-graph.mjs +140 -0
  65. package/agent-tools/eng.mjs +10 -9
  66. package/agent-tools/escalate-async.mjs +5 -5
  67. package/agent-tools/manifest.mjs +34 -15
  68. package/agent-tools/read-history.mjs +115 -14
  69. package/agent-tools/review-facts.mjs +40 -15
  70. package/agent-tools/settings.mjs +23 -2
  71. package/agent-tools/spawn-gates.mjs +19 -22
  72. package/agent-tools/ssh-session.mjs +120 -111
  73. package/agent-tools/ssh-text.mjs +155 -0
  74. package/agent-tools/ssh-transfer.mjs +210 -0
  75. package/agent-tools/ssh-transport.mjs +183 -81
  76. package/agent-tools/subagent-actions-query.mjs +11 -7
  77. package/agent-tools/subagent-actions.mjs +1 -1
  78. package/agent-tools/subagent-async.mjs +11 -11
  79. package/agent-tools/subagent-brief.mjs +76 -0
  80. package/agent-tools/subagent-design-token.mjs +168 -0
  81. package/agent-tools/subagent-run.mjs +1 -1
  82. package/agent-tools/subagent-scheduler.mjs +45 -11
  83. package/agent-tools/subagent-spawn.mjs +143 -104
  84. package/agent-tools/subagent.mjs +26 -23
  85. package/agent-tools/taskbook-block.mjs +94 -0
  86. package/agent-tools/timer.mjs +12 -8
  87. package/agent-tools/verify.mjs +13 -4
  88. package/agent-tools.mjs +7 -3
  89. package/agent.mjs +20 -1
  90. package/attachments.mjs +3 -3
  91. package/browser/actions.mjs +9 -3
  92. package/browser/cdp.mjs +45 -17
  93. package/browser/launch.mjs +25 -43
  94. package/browser/pool.mjs +299 -0
  95. package/browser/queue.mjs +2 -0
  96. package/browser/session-state.mjs +450 -0
  97. package/browser/session.mjs +127 -151
  98. package/browser/snapshot.mjs +89 -0
  99. package/client-identity.mjs +22 -6
  100. package/config-defaults.mjs +2 -1
  101. package/config-migrate.mjs +40 -0
  102. package/config-normalize.mjs +28 -2
  103. package/config-presets.mjs +5 -3
  104. package/config-reload.mjs +59 -0
  105. package/config.mjs +62 -98
  106. package/context-degrade.mjs +38 -10
  107. package/context-echo.mjs +11 -0
  108. package/context.mjs +165 -68
  109. package/conventions.mjs +11 -9
  110. package/declaration.mjs +33 -7
  111. package/declared-repos.mjs +94 -0
  112. package/doc-check/doc-names.mjs +73 -0
  113. package/doc-check/doc-tokens.mjs +110 -0
  114. package/doc-check/existence.mjs +160 -0
  115. package/doc-check/index.mjs +312 -163
  116. package/doc-check/line-refs.mjs +38 -0
  117. package/doc-check/paragraph.mjs +220 -91
  118. package/doc-graph/anchors.mjs +474 -0
  119. package/doc-graph/doc-batch-face.mjs +59 -0
  120. package/doc-graph/doc-suffix.mjs +27 -0
  121. package/doc-graph/graph-tokens.mjs +160 -0
  122. package/doc-graph.mjs +778 -0
  123. package/explore-distill.mjs +12 -6
  124. package/i18n.mjs +2 -2
  125. package/index-discover.mjs +4 -1
  126. package/instance-inbox-watch.mjs +272 -0
  127. package/instance-inbox.mjs +218 -0
  128. package/instance-registry.mjs +179 -0
  129. package/knowledge/README.md +3 -0
  130. package/knowledge/prompt-resources.md +6 -0
  131. package/ledger-close-proof.mjs +95 -62
  132. package/ledger-close.mjs +188 -0
  133. package/ledger-cmd.mjs +76 -244
  134. package/ledger-consistency.mjs +113 -0
  135. package/ledger-db.mjs +70 -37
  136. package/ledger-executors.mjs +1 -1
  137. package/ledger-migrate.mjs +4 -4
  138. package/ledger-read.mjs +10 -8
  139. package/ledger-surface.mjs +1 -1
  140. package/ledger-tools.mjs +83 -24
  141. package/ledger-variant-notice.mjs +1 -1
  142. package/ledger-write-ops.mjs +462 -0
  143. package/ledger.mjs +2 -2
  144. package/manifest-discovery.mjs +5 -3
  145. package/manifest-schema.mjs +28 -2
  146. package/memory/memory-tool.mjs +5 -2
  147. package/memory/schema.mjs +6 -27
  148. package/package.json +3 -1
  149. package/path-resolve.mjs +498 -0
  150. package/permission.mjs +4 -0
  151. package/prompt-files.mjs +91 -1
  152. package/prompt-overlays.mjs +14 -6
  153. package/prompts/advisor-design.md +66 -22
  154. package/prompts/advisor-round1.md +37 -3
  155. package/prompts/advisor-round2.md +44 -10
  156. package/prompts/advisor-round3.md +43 -9
  157. package/prompts/common.md +15 -375
  158. package/prompts/consult-base.md +6 -1
  159. package/prompts/discipline-engineering.md +251 -95
  160. package/prompts/discipline-normal.md +4 -250
  161. package/prompts/knowledge/business-gates.md +22 -0
  162. package/prompts/knowledge/decision-quality.md +23 -0
  163. package/prompts/knowledge/doc-lookup.md +35 -0
  164. package/prompts/knowledge/document-writing.md +51 -0
  165. package/prompts/knowledge/documentation-evaluation.md +56 -0
  166. package/prompts/knowledge/evidence-discipline.md +57 -0
  167. package/prompts/knowledge/normal-coding-workflow.md +104 -0
  168. package/prompts/knowledge/normal-delivery-collaboration.md +108 -0
  169. package/prompts/knowledge/normal-work-management.md +57 -0
  170. package/prompts/knowledge/product-security.md +23 -0
  171. package/prompts/knowledge/project-records.md +62 -0
  172. package/prompts/knowledge/tool-advisor.md +29 -0
  173. package/prompts/knowledge/tool-apply-patch.md +18 -0
  174. package/prompts/knowledge/tool-bash.md +39 -0
  175. package/prompts/knowledge/tool-batch-eng-coder.md +12 -0
  176. package/prompts/knowledge/tool-batch-eng-designer.md +12 -0
  177. package/prompts/knowledge/tool-batch-review.md +12 -0
  178. package/prompts/knowledge/tool-batch.md +80 -0
  179. package/prompts/knowledge/tool-browser.md +57 -0
  180. package/prompts/knowledge/tool-code-search.md +4 -0
  181. package/prompts/knowledge/tool-consult-start.md +12 -0
  182. package/prompts/knowledge/tool-consult-stop.md +6 -0
  183. package/prompts/knowledge/tool-context.md +6 -0
  184. package/prompts/knowledge/tool-delete.md +17 -0
  185. package/prompts/knowledge/tool-doc-check.md +70 -0
  186. package/prompts/knowledge/tool-doc-graph-read.md +20 -0
  187. package/prompts/knowledge/tool-doc-graph.md +49 -0
  188. package/prompts/knowledge/tool-doc-search.md +6 -0
  189. package/prompts/knowledge/tool-edit.md +38 -0
  190. package/prompts/knowledge/tool-eng.md +2 -0
  191. package/prompts/knowledge/tool-execute.md +16 -0
  192. package/prompts/knowledge/tool-fetch.md +12 -0
  193. package/prompts/knowledge/tool-file-ops.md +16 -0
  194. package/prompts/knowledge/tool-get-current-time.md +7 -0
  195. package/prompts/knowledge/tool-git-read.md +19 -0
  196. package/prompts/knowledge/tool-git.md +29 -0
  197. package/prompts/knowledge/tool-glob.md +15 -0
  198. package/prompts/knowledge/tool-goal.md +8 -0
  199. package/prompts/knowledge/tool-grep.md +18 -0
  200. package/prompts/knowledge/tool-hashline-edit.md +14 -0
  201. package/prompts/knowledge/tool-insert-after.md +15 -0
  202. package/prompts/knowledge/tool-instance-list.md +6 -0
  203. package/prompts/knowledge/tool-instance-send.md +10 -0
  204. package/prompts/knowledge/tool-knowledge.md +18 -0
  205. package/prompts/knowledge/tool-ledger-read.md +35 -0
  206. package/prompts/knowledge/tool-ledger.md +42 -0
  207. package/prompts/knowledge/tool-lint.md +16 -0
  208. package/prompts/knowledge/tool-ls.md +13 -0
  209. package/prompts/knowledge/tool-lsp.md +11 -0
  210. package/prompts/knowledge/tool-main-history.md +2 -0
  211. package/prompts/knowledge/tool-manifest-read.md +14 -0
  212. package/prompts/knowledge/tool-manifest.md +31 -0
  213. package/prompts/knowledge/tool-memory-read.md +20 -0
  214. package/prompts/knowledge/tool-memory.md +15 -0
  215. package/prompts/knowledge/tool-notify-parent.md +12 -0
  216. package/prompts/knowledge/tool-operations.md +114 -0
  217. package/prompts/knowledge/tool-peer-instances.md +2 -0
  218. package/prompts/knowledge/tool-plan.md +6 -0
  219. package/prompts/knowledge/tool-process-read.md +13 -0
  220. package/prompts/knowledge/tool-process.md +15 -0
  221. package/prompts/knowledge/tool-question.md +16 -0
  222. package/prompts/knowledge/tool-read-history-batch.md +22 -0
  223. package/prompts/knowledge/tool-read-history.md +36 -0
  224. package/prompts/knowledge/tool-read-image.md +11 -0
  225. package/prompts/knowledge/tool-read.md +21 -0
  226. package/prompts/knowledge/tool-recent-changes.md +6 -0
  227. package/prompts/knowledge/tool-repo-outline.md +4 -0
  228. package/prompts/knowledge/tool-settings-read.md +12 -0
  229. package/prompts/knowledge/tool-settings.md +18 -0
  230. package/prompts/knowledge/tool-skill.md +6 -0
  231. package/prompts/knowledge/tool-ssh.md +52 -0
  232. package/prompts/knowledge/tool-subagent.md +59 -0
  233. package/prompts/knowledge/tool-task.md +12 -0
  234. package/prompts/knowledge/tool-team-ledger-read.md +11 -0
  235. package/prompts/knowledge/tool-team-ledger.md +11 -0
  236. package/prompts/knowledge/tool-timer.md +23 -0
  237. package/prompts/knowledge/tool-tree.md +14 -0
  238. package/prompts/knowledge/tool-verify.md +19 -0
  239. package/prompts/knowledge/tool-wait-for.md +25 -0
  240. package/prompts/knowledge/tool-websearch.md +19 -0
  241. package/prompts/knowledge/tool-write.md +9 -0
  242. package/prompts/knowledge/upstream-protocol.md +43 -0
  243. package/prompts/persona-eng-coder.md +29 -3
  244. package/prompts/persona-eng-designer.md +131 -159
  245. package/prompts/persona-engineering.md +202 -131
  246. package/prompts/persona-explore.md +1 -1
  247. package/prompts/persona-plan.md +6 -1
  248. package/prompts/persona-tester.md +55 -0
  249. package/prompts/subagent-base.md +2 -0
  250. package/provider/anthropic.mjs +6 -4
  251. package/provider/core.mjs +5 -4
  252. package/provider/errors.mjs +29 -4
  253. package/provider/google.mjs +39 -12
  254. package/provider/rate.mjs +11 -3
  255. package/provider/responses.mjs +3 -1
  256. package/provider/sse.mjs +15 -4
  257. package/provider-flows.mjs +2 -2
  258. package/session-identity.mjs +21 -0
  259. package/session-index-build.mjs +1 -1
  260. package/session-index-pass.mjs +1 -1
  261. package/session-index-query.mjs +1 -1
  262. package/session-index.mjs +1 -1
  263. package/session-lifecycle.mjs +79 -19
  264. package/session-slot-write.mjs +37 -5
  265. package/session-slots.mjs +9 -14
  266. package/session.mjs +29 -8
  267. package/skip-dirs.mjs +48 -0
  268. package/team-ledger.mjs +17 -13
  269. package/text-budget.mjs +4 -0
  270. package/token-ttl.mjs +73 -4
  271. package/token-window.mjs +244 -34
  272. package/tool-docs/advisor.md +2 -27
  273. package/tool-docs/apply_patch.md +1 -13
  274. package/tool-docs/bash.md +2 -37
  275. package/tool-docs/batch-eng-coder.md +3 -0
  276. package/tool-docs/batch-eng-designer.md +3 -0
  277. package/tool-docs/batch-review.md +3 -0
  278. package/tool-docs/batch.md +3 -1
  279. package/tool-docs/browser.md +2 -47
  280. package/tool-docs/code_search.md +3 -1
  281. package/tool-docs/consult_start.md +2 -4
  282. package/tool-docs/consult_stop.md +2 -2
  283. package/tool-docs/context.md +1 -5
  284. package/tool-docs/delete.md +2 -14
  285. package/tool-docs/doc_check.md +2 -72
  286. package/tool-docs/doc_graph-read.md +3 -0
  287. package/tool-docs/doc_graph.md +3 -0
  288. package/tool-docs/doc_search.md +3 -1
  289. package/tool-docs/edit.md +2 -18
  290. package/tool-docs/eng.md +3 -1
  291. package/tool-docs/execute.md +2 -12
  292. package/tool-docs/fetch.md +2 -12
  293. package/tool-docs/file_ops.md +2 -16
  294. package/tool-docs/get_current_time.md +1 -6
  295. package/tool-docs/git-read.md +3 -0
  296. package/tool-docs/git.md +2 -27
  297. package/tool-docs/glob.md +2 -10
  298. package/tool-docs/goal.md +2 -5
  299. package/tool-docs/grep.md +2 -18
  300. package/tool-docs/hashline_edit.md +2 -13
  301. package/tool-docs/insert_after.md +2 -14
  302. package/tool-docs/instance_list.md +3 -0
  303. package/tool-docs/instance_send.md +3 -0
  304. package/tool-docs/knowledge.md +3 -0
  305. package/tool-docs/ledger-read.md +3 -0
  306. package/tool-docs/ledger.md +3 -8
  307. package/tool-docs/lint.md +2 -9
  308. package/tool-docs/ls.md +2 -11
  309. package/tool-docs/lsp.md +2 -9
  310. package/tool-docs/main_history.md +3 -1
  311. package/tool-docs/manifest-read.md +2 -7
  312. package/tool-docs/manifest.md +2 -28
  313. package/tool-docs/memory-read.md +3 -0
  314. package/tool-docs/memory.md +3 -11
  315. package/tool-docs/notify_parent.md +2 -13
  316. package/tool-docs/peer_instances.md +3 -1
  317. package/tool-docs/plan.md +2 -4
  318. package/tool-docs/process-read.md +3 -0
  319. package/tool-docs/process.md +2 -13
  320. package/tool-docs/question.md +3 -17
  321. package/tool-docs/read.md +2 -19
  322. package/tool-docs/read_history-batch.md +3 -0
  323. package/tool-docs/read_history.md +2 -6
  324. package/tool-docs/read_image.md +2 -7
  325. package/tool-docs/recent_changes.md +3 -1
  326. package/tool-docs/repo_outline.md +3 -1
  327. package/tool-docs/settings-read.md +3 -0
  328. package/tool-docs/settings.md +2 -5
  329. package/tool-docs/skill.md +3 -5
  330. package/tool-docs/ssh.md +2 -50
  331. package/tool-docs/subagent.md +2 -63
  332. package/tool-docs/task.md +2 -6
  333. package/tool-docs/team_ledger-read.md +3 -0
  334. package/tool-docs/team_ledger.md +3 -9
  335. package/tool-docs/timer.md +3 -13
  336. package/tool-docs/tree.md +2 -13
  337. package/tool-docs/verify.md +3 -1
  338. package/tool-docs/wait_for.md +2 -32
  339. package/tool-docs/websearch.md +2 -17
  340. package/tool-docs/write.md +2 -10
  341. package/tools/bash.mjs +12 -2
  342. package/tools/browser.mjs +52 -7
  343. package/tools/doc-write-gate.mjs +73 -0
  344. package/tools/edit-batch.mjs +176 -91
  345. package/tools/edit-diff.mjs +129 -45
  346. package/tools/edit-receipt.mjs +39 -0
  347. package/tools/execute.mjs +11 -5
  348. package/tools/file.mjs +32 -34
  349. package/tools/git.mjs +43 -2
  350. package/tools/index.mjs +6 -0
  351. package/tools/knowledge.mjs +143 -0
  352. package/tools/linter.mjs +3 -3
  353. package/tools/ops.mjs +4 -1
  354. package/tools/patch.mjs +127 -38
  355. package/tools/process-doc-mark.mjs +139 -0
  356. package/tools/search.mjs +15 -6
  357. package/tools/shared.mjs +31 -7
  358. package/tools/ssh.mjs +48 -7
  359. package/tools/tree.mjs +4 -1
  360. package/tools/write-gate-params.mjs +31 -0
  361. package/tools/write-path.mjs +79 -6
  362. package/traces/trace-store.mjs +4 -3
  363. package/window-policy.mjs +203 -0
  364. package/agent/light-round.mjs +0 -63
  365. package/agent/unbooked-pen.mjs +0 -62
  366. package/doc-check/anchors.mjs +0 -135
@@ -1,50 +1,72 @@
1
1
  /**
2
2
  * subagent-spawn.mjs — spawn 路径装配(2026-09-05 module-split:subagent.mjs 726
3
- * > 500 硬限——spawn 前置 helpers(effectiveSubagentModel/resolveDesignSlot——审计块
4
- * 构造器 2026-09-22 起另立 ./audit-block.mjs)+ AGENT-LOOP-SUBAGENT.md §6.9 调度参数准入(prepareScheduling)+ child 装配
3
+ * > 500 硬限——spawn 前置 helpers(effectiveSubagentModel)+ AGENT-LOOP-SUBAGENT.md §6.9 调度参数准入(prepareScheduling)+ child 装配
5
4
  * (buildSpawnChild)verbatim 迁入(仅闭包变量参数化),语义零变;executeAsyncSpawn
6
5
  * 另在 subagent-run.mjs。subagent.mjs execute 经本文件 import 调用。
6
+ * **本轮(档位 500 设计器硬线)再切两族**:任务书与 system 固块拼装 → `./subagent-brief.mjs`、
7
+ * 设计令牌门 → `./subagent-design-token.mjs`(落点 = `docs/core/design/PATH-RESOLUTION.md` §3 末条)。
8
+ * **两族的对外面各不相同、各自守住**:设计令牌族**原样再导出**(`subagent.mjs` 的再导出行与用例的 import 行零改);
9
+ * 任务书族由本档直接 import 消费,不对外导出(今天没有任何调用点从本档取它)。
7
10
  * 2026-09-07:executeConsumeDesignAction 消费执行器(token 链终消费制——与 spawn 侧
8
11
  * slot 族同域——ENGINEERING-MODE.md §2.6 F1——removeDesignTokenSlot 自 token-ttl.mjs)。
9
12
  * 2026-09-22(台账 #23 · AGENT-LOOP-SUBAGENT.md §6.26):审计块构造器外提 `./audit-block.mjs`;
10
13
  * spawn 级固定机制性指令改走 system 固块(`child._spawnSystemBlock` 单点绑定——消费点 = 核
11
14
  * `prepareRun`),`input` 只留任务书。2026-10-24(§6.22):工程角色 `input` = 一行机械任务书行
12
- * (批档绝对路径 + §2 指向句),任务书本体由子代理自读 §2。
15
+ * (批档绝对路径 + 按角色的指向句),任务书本体由子代理从批档读(§8.1 切片)。
13
16
  */
14
17
 
18
+ // 2026-11-15(AGENT-LOOP-SUBAGENT.md §8.1):工程角色的任务书正文随 system 固块下发——spawn 当刻读一次
19
+ // 批档并冻结(`readFileSync` 在本档,切段与拼块的本体住 `./taskbook-block.mjs`)。
20
+ import { readFileSync } from "node:fs"
15
21
  import {
16
22
  createAgent,
17
23
  readonlyToolNames, escapeXml, excludeSubagentTools,
18
24
  } from "../agent.mjs"
19
- import { allocRelay, wrapChildCallbacks, relayPrefixOf } from "../agent/spawn-child.mjs"
25
+ import { allocRelay, wrapChildCallbacks, relayPrefixOf, chargeDesignerSurveySpawn, rootAgentOf } from "../agent/spawn-child.mjs"
26
+ // B8(TOOLS.md §6.29 ④):eng 两角色的受限父历史(同名 `read_history`,只在 extraTools 注入)
27
+ import { makeBatchHistoryTool, recordBatchHistoryStart } from "./read-history.mjs"
28
+ // B4(TOOLS.md §6.29 ①):只读角色的 action 级变体派生(构造器单源 = `agent/helpers.mjs`,
29
+ // 判据单源 = `agent/dispatch-gates.mjs` 的 `readonlyActionOf`)。
30
+ import { deriveReadonlyTools } from "../agent/helpers.mjs"
31
+ import { readonlyActionTest } from "../agent/dispatch-gates.mjs"
20
32
  // TUI-OOM-ROOTCAUSE(AGENT-LOOP.md §6.15):子代理人读线窗口常量单源(store 零依赖)。
21
33
  import { RECORD_WINDOW_MESSAGES } from "../session-store.mjs"
22
- import { validateDesignToken } from "./advisor.mjs"
23
- import { tokenExpired, removeDesignTokenSlot, reconcileEngTokensFromSlot } from "../token-ttl.mjs"
34
+ // 设计令牌门(七态拒句 ∥ 槽解析 ∥ 令牌判定)本体落 `./subagent-design-token.mjs`;本档只吃判定。
35
+ import { gateDesignToken } from "./subagent-design-token.mjs"
24
36
  import { resolveChildProvider, buildChildRunOpts, enqueueAsk } from "./subagent-async.mjs"
25
37
  import { nextSubagentId } from "./subagent-scheduler.mjs"
26
38
  import {
27
- normalizeFileList, describeBlockers, assertNoDepCycle, depInfo,
39
+ normalizeFileList, describeBlockers, assertNoDepCycle, depInfo, batchDocInFlight,
28
40
  } from "./subagent-scheduler.mjs"
29
41
  // M5 F2(ENGINEERING-MODE-V2-MODULE-DELEGATION §2.3):任务书 round 枚举 + 五项结构化参数校验/拼装本体落
30
42
  // spawn-gates.mjs(纯谓词零依赖)——本处只加 import 调用。
31
43
  import {
32
- validateRoundParam, validateTaskBookParams, composeTaskBookBrief,
44
+ validateRoundParam, validateTaskBookParams,
33
45
  isEngineeringRole, rejectEngFreeTextParams,
34
46
  } from "./spawn-gates.mjs"
47
+ // 任务书与 system 固块拼装(任务书播报 ∥ 写域行 S4 ∥ 文档坐标行 S5)落 `./subagent-brief.mjs`。
48
+ import { docsCoordinatesBlockOf, filesBlockOf, taskBriefOf } from "./subagent-brief.mjs"
35
49
  // 台账 #23(AGENT-LOOP-SUBAGENT.md §6.26 · D23-3):审计块构造器外提(`buildAuditBlock` 纯函数)
36
50
  // ——spawn 档只做「收集 + 绑定」;块文本逐字搬移(D23-4)。
37
51
  import { buildAuditBlock } from "./audit-block.mjs"
52
+ // 任务书正文块(`AGENT-LOOP-SUBAGENT.md` §8.1 载体 ∥ 切片 ∥ 快照 ∥ 失效即拒)——纯函数外提,同审计块先例。
53
+ import { buildTaskBookBlock, taskBookPointerLine } from "./taskbook-block.mjs"
38
54
  // 批次档路径解析单源(BATCH-RECORD.md §4.15 · 台账 #287):门内解析改经叶档(读面非抛形),
39
55
  // 与 append / create 同源——门判据仍「参数在 + 路径可读」,错误文案逐字零变。
40
- import { resolveBatchReadPath } from "./batch-paths.mjs"
56
+ import { resolveBatchReadPath, resolveBatchReadResult } from "./batch-paths.mjs"
57
+ // `files` 落点单源 = 统一解析层(实调点 = `normalizeFileList`——`thincoder-core/agent-tools/subagent-scheduler.mjs`
58
+ // 的 `const abs = resolvePathTarget(cwd, f, ...)`):本档不再预解析(预解析会让该面的三条门判吃绝对形而漏判)。
59
+ import { danglingSameNameHint } from "../path-resolve.mjs"
41
60
 
42
- /** 任务书播报文本:该角色名集拼装 + 可选 task 自由文本(拼装空 ⇒ 原 task 逐字——旧形零变)。 */
43
- function taskBriefOf(args, role) {
44
- const composed = composeTaskBookBrief(args, role)
45
- if (!composed) return args.task
46
- const extra = typeof args.task === "string" ? args.task.trim() : ""
47
- return extra ? `${composed}\n\n${extra}` : composed
61
+ /** 不可读拒文的追加提示(§2.6:既有文案逐字在前)——同名候选 ∥ 判不出唯一的候选全列;无提示 ⇒ 空串。 */
62
+ function unreadableHint(cwd, given) {
63
+ const r = resolveBatchReadResult(cwd, given)
64
+ if (r.state === "dangling") {
65
+ const hint = danglingSameNameHint(r)
66
+ return hint ? `;${hint}` : ""
67
+ }
68
+ if (r.state === "ambiguous") return `;Candidates: ${r.candidates.join(" ∥ ")}`
69
+ return ""
48
70
  }
49
71
 
50
72
  /** 原 #309 任务书 token 观测(`child:batchdoc-ref`)已废止——2026-10-24 用户裁定
@@ -69,47 +91,6 @@ export function effectiveSubagentModel(parent, role, modelArg) {
69
91
  return cfg.subagentModels?.[role] ?? cfg.subagentModel ?? null
70
92
  }
71
93
 
72
- /**
73
- * Resolve the design-token slot for an eng-coder spawn (2026-09-01 multi-design, FR3):
74
- * - designId given → exact slot lookup (no match = explicit error, never a fuzzy guess)
75
- * - designId omitted → exactly ONE slot must exist (single-design compatibility); with
76
- * multiple slots we refuse rather than pick one (T16: never silently aim the wrong design)
77
- * Returns { token } on success; throws with a parent-actionable message otherwise.
78
- * R16 (2026-09-06): the slot Map is the authority; the format/TTL check itself stays in
79
- * validateDesignToken (2026-09-06: HMAC 防伪层已删——token 为无签名流程凭证——见
80
- * ENGINEERING-MODE.md 2026-09-06 段)。
81
- * DESIGN-TOKEN-SETTLEMENT D2(2026-09-08):内存 Map miss(指定 designId 不在 / 空 Map)
82
- * 时回读槽文件权威台账 reconcile + 判定(reconcileEngTokensFromSlot——与 dispatch 写门
83
- * D3 同源)——覆盖"进程重启后槽有但 Map 未及回填/缓存与槽不一致"(槽文件 = 权威台账)。
84
- * TTL 过滤保留(reconcile 只并入未过期项)。单值镜像 `_engDesignToken` 已随 D3 退役——
85
- * 本门禁不再读镜像(AC3 零命中)。
86
- */
87
- export function resolveDesignSlot(parent, designIdArg) {
88
- let slots = parent._engDesignTokens
89
- const hasSlots = slots instanceof Map && slots.size > 0
90
- // D2:内存 miss(指定 designId 不在 或 空 Map)→ 权威槽回读 reconcile + 判定
91
- if (designIdArg ? !(hasSlots && slots.has(designIdArg)) : !hasSlots) {
92
- const rec = reconcileEngTokensFromSlot(parent)
93
- if (rec && rec !== slots) slots = rec
94
- }
95
- // F2d: both refusal branches carry the HELD id list — after a
96
- // persistence restore the parent has no digest to look the id up in; the error
97
- // list is the only discovery path (ids are not credentials — the token is).
98
- const size = slots instanceof Map ? slots.size : 0
99
- const heldIds = size > 0 ? [...slots.keys()].join(", ") : "(none)"
100
- if (designIdArg) {
101
- if (!(slots instanceof Map) || !slots.has(designIdArg)) {
102
- throw new Error(`designId not found — no approved design review holds this id. Run advisor with type='design' again and pass the designId echoed with the token. (session holds ${size} approved design slot(s); held design ids: ${heldIds})`)
103
- }
104
- return { token: slots.get(designIdArg) }
105
- }
106
- if (size > 1) {
107
- throw new Error(`Multiple approved designs in this session (${size}) — pass the designId parameter (echoed with each token) to choose which design this eng-coder spawn belongs to. Held design ids: ${heldIds}`)
108
- }
109
- if (size === 1) return { token: [...slots.values()][0] }
110
- throw designTokenRefusal("missing")
111
- }
112
-
113
94
  /**
114
95
  * consume-design 动作执行器(2026-09-07 token 链终消费制——ENGINEERING-MODE.md §2.6 F1):
115
96
  * 父侧验收核销时显式调用——读槽值 → removeDesignTokenSlot(移除该 designId 槽)→ 消费后同
@@ -177,7 +158,7 @@ export function prepareScheduling(parent, filesRaw, dependsRaw, wantAsync) {
177
158
  export function buildSpawnChild(parent, ctx, args, role, wantAsync, files, dependsOn, engAuditAttempt) {
178
159
  // Provider/model override: tool `model` arg > subagentModels[role] > subagentModel > parent provider
179
160
  const childProvider = resolveChildProvider(parent, effectiveSubagentModel(parent, role, args.model))
180
- // 工程角色(任务书 = 批次档 §2,零任务书文本参数)——AGENT-LOOP-SUBAGENT.md §6.22.1。
161
+ // 工程角色(任务书 = 绑定批档,按角色切片(§8.1);零任务书文本参数)——AGENT-LOOP-SUBAGENT.md §6.22.1。
181
162
  const engineeringRole = isEngineeringRole(role)
182
163
 
183
164
  // ── batchDoc gate(ENGINEERING-MODE.md §2.12 + §2.15 D1——FR20 #9 机械面)────────
@@ -194,25 +175,44 @@ export function buildSpawnChild(parent, ctx, args, role, wantAsync, files, depen
194
175
  let batchDocAbs = null
195
176
  if (engineeringRole) {
196
177
  const given = typeof args.batchDoc === "string" ? args.batchDoc.trim() : ""
178
+ // 「无果 ⇒ 既有文案 + 追加同名候选」(§2.6——既有拒文逐字在前,层的提示只追加)。
197
179
  const refusal = (suffix = "") => new Error(
198
180
  `batchDoc is required for role='${role}' — pass the batch record path (e.g. <repo>/docs/batches/<batch>-<topic>.md; relative paths resolve against the session cwd first, then candidate project roots — or absolute); spawn refused without it.` + suffix)
199
181
  if (!given) throw refusal()
200
- batchDocAbs = resolveBatchReadPath(parent.cwd ?? process.cwd(), given)
201
- if (!batchDocAbs) throw refusal(" (given path is not a readable file)")
182
+ batchDocAbs = resolveBatchReadPath(parent.cwd, given)
183
+ if (!batchDocAbs) throw refusal(` (given path is not a readable file${unreadableHint(parent.cwd, given)})`)
202
184
  } else if (role === "coder") {
203
185
  const given = typeof args.batchDoc === "string" ? args.batchDoc.trim() : ""
204
186
  if (given) {
205
- batchDocAbs = resolveBatchReadPath(parent.cwd ?? process.cwd(), given)
187
+ batchDocAbs = resolveBatchReadPath(parent.cwd, given)
206
188
  if (!batchDocAbs) {
207
- throw new Error("batchDoc for role='coder' — pass the batch record path (e.g. <repo>/docs/batches/<batch>-<topic>.md; relative paths resolve against the session cwd first, then candidate project roots — or absolute); when provided it must resolve to a readable file (omit batchDoc to spawn without the §5 record-write binding).")
189
+ throw new Error("batchDoc for role='coder' — pass the batch record path (e.g. <repo>/docs/batches/<batch>-<topic>.md; relative paths resolve against the session cwd first, then candidate project roots — or absolute); when provided it must resolve to a readable file (omit batchDoc to spawn without the §5 record-write binding)." + unreadableHint(parent.cwd, given))
208
190
  }
209
191
  }
210
192
  }
211
193
 
194
+ // ── AGENT-LOOP-SUBAGENT.md §6.58 批次档复用护栏(2026-10-28 batchdoc-reuse-guard)──
195
+ // 同一档已有在飞 spawn ⇒ 拒发(2026-10-28 11:34 事故:两席共用一本批档、文件域互不重叠 ⇒
196
+ // 语法坏档 + 一席复原)。判据 = 池内在飞条目的 `_batchDoc` 与本次解析出的绝对路径按 fileKey
197
+ // 相等(谓词单源 = `batchDocInFlight`——池派生事实住 subagent-scheduler.mjs,读法同 `depInfo`)。
198
+ // 只用结构性事实(池 + 路径相等),不做文本匹配(TOOLS.md §6.4)。
199
+ // **不读 `round`**(KD-BG1):修正轮靠「前一轮已 settle ⇒ 不在在飞集」自然放行;前一轮仍
200
+ // 在飞就派修正轮 = 同一种两写者病,照拒。
201
+ // **非对称是判据的一部分,勿「顺手统一」**:被检面只覆盖工程角色(本分支内),占用者是池内
202
+ // 任何带 `_batchDoc` 的条目、不分角色(普通面 coder 携 batchDoc 也算);sync spawn 不入池 ⇒
203
+ // 它不是占用者(§6.58.7 第 7 条)。
204
+ // 拒因文案逐字模板 = §6.58.2(文案单源 = 本处——下游断言逐字对照)。
205
+ if (engineeringRole) {
206
+ const occupant = batchDocInFlight(parent, batchDocAbs)
207
+ if (occupant) {
208
+ throw new Error(`batchDoc is already in flight — spawn refused. Batch record: ${batchDocAbs}. Occupant: ${occupant.role}#${occupant.id} (status: ${occupant.status}). One batch record serves one concurrent spawn: wait for ${occupant.role}#${occupant.id} to settle, or cancel it, then spawn again.`)
209
+ }
210
+ }
211
+
212
212
  // M5 F2 + §6.22(2026-10-24)任务书门——按角色分流:
213
213
  // 工程角色(eng-coder / eng-designer):零任务书文本参数——八个自由文本键命中即拒(键在场即拒)并点名
214
214
  // (值全空白也拒);随后 round 枚举(initial|fix)。
215
- // explore / plan / coder:四项核心 + `scope` 必带(判据三条零改:存在 ∧ string ∧ trim 非空)。
215
+ // explore / plan / coder / tester:四项核心 + `scope` 必带(判据三条零改:存在 ∧ string ∧ trim 非空)。
216
216
  // 落点 = batchDoc 门之后、token 门之前(门序 = AGENT-LOOP-SUBAGENT.md §6.22.1)。
217
217
  if (engineeringRole) {
218
218
  rejectEngFreeTextParams(args, role)
@@ -221,17 +221,67 @@ export function buildSpawnChild(parent, ctx, args, role, wantAsync, files, depen
221
221
  validateTaskBookParams(args, role)
222
222
  }
223
223
 
224
- // eng-coder token gate(TOOLS.md §6.25 ④):判定本体 = gateDesignToken(本档模块尾)——
225
- // missing / mismatch / expired / invalid 四态各出互异拒句;拒绝集合与旧三条件合取全等。
224
+ // AGENT-LOOP-SUBAGENT.md §8.1:任务书**正文**进 system 固块(§8.2 收集序首块)——spawn 当刻读一次批档
225
+ // 并冻结,此后改动不回流(快照语义);切片与块文本住 `./taskbook-block.mjs`,本处只做「读 + 收集」。
226
+ // 失效即拒:段切不出来(无对应段头)⇒ 拒发并点名路径与缺失段(拒文由构造器给出)——
227
+ // 退回只发指向句会让 §8.1 的承诺落空而无人知道。读不到走同一条拒因:batchDoc 门已判过可读,
228
+ // 这里只剩「读的那一刻文件不在了」,那不是可降级情形。
229
+ // 落点 = 任务书参数门之后、token 门之前(门序 §3.3:既有门的先后不变)。
230
+ let taskBookBlock = null
231
+ if (engineeringRole) {
232
+ let recordText
233
+ try {
234
+ recordText = readFileSync(batchDocAbs, "utf8")
235
+ } catch (e) {
236
+ throw new Error(`Task book unavailable — spawn refused: the batch record at ${batchDocAbs} could not be read at spawn time (${e?.message ?? e}); the ${role} task book is cut from it, so this spawn would have no authorized text. Restore the file and spawn again.`)
237
+ }
238
+ taskBookBlock = buildTaskBookBlock({ role, record: { path: batchDocAbs, text: recordText } })
239
+ }
240
+
241
+ // eng-coder token gate(TOOLS.md §6.25 ④⑤⑥):判定本体 = `./subagent-design-token.mjs` 的 `gateDesignToken`——
242
+ // missing / mismatch / expired / invalid / batch-mismatch / seal-mismatch / seal-unreadable 七态各出互异拒句;
243
+ // 前四态的拒绝集合与旧三条件合取全等。第三参 = 本函数上方 batchDoc 门已解析好的绝对路径
244
+ // (§10.1 的比较对象;本门不二次解析 `args.batchDoc`)。
226
245
  // 返回值 = 槽内令牌,必须落回 issuedToken:下方 `child._engDesignId` 回写依赖它。
227
246
  let issuedToken
228
- if (role === "eng-coder") issuedToken = gateDesignToken(parent, args)
247
+ if (role === "eng-coder") issuedToken = gateDesignToken(parent, args, { batchDocAbs })
248
+
249
+ // ── B7(TOOLS.md §6.29 B7):eng-designer 的勘察预算计数 ──────────────────────────
250
+ // 计的是**设计席发起的勘察**(`parent._role === "eng-designer"` 且本 spawn 的 role = explore),
251
+ // 不是设计师自己的被派次数——模型面承诺的是「≤6 explore spawns per batch」。
252
+ // 判据序(设计档原话「先完成角色、同步方式与 batchDoc 准入再计数」):角色/同步两道门在
253
+ // `gateEngCoderSpawn`(调用方,本函数之前已过);本角色的 batchDoc 绑定在设计师自己那一次 spawn
254
+ // 就过完了门(`parent._batchDoc`);任务书门在本函数上方 ⇒ 到此处仍未拒的 spawn 才占额度。
255
+ // 载体 = depth-0 根 agent 的独立 Map(K5:挂一次性 designer child 上会在 fix respawn 归零)。
256
+ if (role === "explore" && parent?._role === "eng-designer" && parent._batchDoc) {
257
+ chargeDesignerSurveySpawn(rootAgentOf(parent), parent._batchDoc)
258
+ }
259
+
260
+ // ── B8(TOOLS.md §6.29 ④):eng 两角色的限量父历史 ────────────────────────────────
261
+ // 绑定的是**父会话**(depth-0 根 agent)与**本批起点**;未绑定角色(explore/plan/coder/tester/consult)
262
+ // 一个新历史工具都拿不到(K7:新工具解决不了「没有 _batchDoc 时范围怎么定」)。
263
+ if (engineeringRole) recordBatchHistoryStart(rootAgentOf(parent), batchDocAbs, Date.now())
229
264
 
230
265
  // Filter tool set by role: explore/plan are read-only (plan is a planning agent, its deliverable is the plan itself)
231
266
  let tools
232
267
  if (role === "explore" || role === "plan") {
268
+ // B4(TOOLS.md §6.29):整把只读集 ∪ action 级只读变体——旧形只认 `t.readonly`,`git` / `memory` /
269
+ // `settings` / `process` 整把不是只读,于是它们的只读动作在只读角色里一起消失(需求 B4 的直接病因)。
270
+ // 判据单源 = 运行期 `readonlyActionOf`(经 `readonlyActionTest` 适配)——不另写一份只读动作名单。
271
+ tools = deriveReadonlyTools(parent.tools, readonlyActionTest)
272
+ } else if (role === "tester") {
273
+ // tester = the THIRD tool face (AGENT-LOOP-SUBAGENT.md §6.59.2 ④): read-only set ∪ {execute, bash},
274
+ // minus {verify, advisor}.
275
+ // · Allowlist form (D-TT1) — a new non-readonly tool stays OUT by default (the write face is fail-closed);
276
+ // a new readonly tool joins automatically through the same formula.
277
+ // · Why subtract `verify` / `advisor`: both produce a VERDICT, not a reading — "I declare this delivery
278
+ // good" and "open a review, produce a judgment". A tester's product is readings (F-TT3: it does not
279
+ // close a judgment on the parent's behalf), and `advisor` is `readonly: true`, so leaving it in would
280
+ // make 「it does not run reviews」 a sentence nobody enforces. Both subtractions are by name, explicit,
281
+ // and do not depend on the tool's `readonly` flag — that flag says "writes nothing", not "concludes nothing".
233
282
  const allowed = readonlyToolNames(parent.tools)
234
- tools = parent.tools.filter((t) => allowed.has(t.name))
283
+ const TRIMMED = new Set(["verify", "advisor"])
284
+ tools = parent.tools.filter((t) => (allowed.has(t.name) && !TRIMMED.has(t.name)) || t.name === "execute" || t.name === "bash")
235
285
  } else {
236
286
  tools = parent.tools
237
287
  }
@@ -274,7 +324,7 @@ export function buildSpawnChild(parent, ctx, args, role, wantAsync, files, depen
274
324
  // 场景映射落到 assemblePrompt("eng-coder"/"eng-designer")(persona-{role} + common +
275
325
  // discipline-engineering);designer 也必须 engineering=true 才能装配工程纪律槽。
276
326
  const childConfig = engineeringRole
277
- ? { ...parent.config, agent: { ...parent.config.agent, engineering: true } }
327
+ ? { ...parent.config, agent: { ...parent.config.agent, mode: "engineering", engineering: true } }
278
328
  : parent.config
279
329
 
280
330
  const child = createAgent({
@@ -321,29 +371,40 @@ export function buildSpawnChild(parent, ctx, args, role, wantAsync, files, depen
321
371
  // 审计/探索("status 里这个文件算不算超清单?")。注入分支整体删除(B 方案
322
372
  // git 只读变体亦随裁定废弃——D-AG5)。顶层主 agent 注入保留(§3 prepareRun——
323
373
  // setup.mjs depth===0——D-AG7 范围边界)。
324
- // §6.22.2 子代理任务输入:工程角色 `input` = 一行机械任务书行(批档绝对路径 + §2 指向句)——
325
- // 任务书本体由子代理自读 §2(KD-SC5:运行时不抽取正文注入,避免过期副本 / 脆标题解析);
374
+ // §6.22.2 子代理任务输入:工程角色 `input` = 一行机械任务书行(批档绝对路径 + 按角色的指向句);
375
+ // 任务书**正文**在 system 固块(§8.1),本行只指路(指向句文本住 `./taskbook-block.mjs`);
326
376
  // 非工程角色 = 既有拼装(context 前缀 + 任务书参数 + 可选 task——零变)。
327
377
  const input = engineeringRole
328
- ? `Task book: §2 of the batch record at ${batchDocAbs} — read it before acting; it is the only task channel for this spawn.`
378
+ ? taskBookPointerLine(role, batchDocAbs)
329
379
  : (args.context ? `Context:\n${args.context}\n\nTask:\n${taskBriefOf(args, role)}` : taskBriefOf(args, role))
330
380
  // 台账 #23(AGENT-LOOP-SUBAGENT.md §6.26 · D23-1):**spawn 级固定机制性指令改走 system 固块**——
331
381
  // 两处(批次档路径行 + 审计模板块)原随 user 首条下发,压缩把首条并入摘要即丢(长任务中后期
332
382
  // 既看不到批次档路径、也看不到审计模板 ⇒ 过度勘察的真病根);固块值在 child 生命周期内恒定
333
383
  // ⇒ run 内 system 前缀逐字节稳定(前缀缓存不破),且不在 `agent.history` 内 ⇒ 压缩结构上吞不掉。
334
- // 收集序 = 原拼接序(批次档行 → 审计块);空数组 ⇒ 不绑定(depth-0 / explore / plan / consult
335
- // 的 system 逐字节同改前——§6.26 缓存契约兼容证明)。
384
+ // 收集序 = 任务书正文(§8.2)→ 批次档行 → 审计块 → 写域行(S4,见下)→ 文档坐标行(S5,见下);
385
+ // 空数组 ⇒ 不绑定(depth-0 不进本函数、system 逐字节同改前——§6.26 缓存契约兼容证明)。
386
+ // S5 与角色无关 ⇒ explore ∥ plan 的子代理也会带上它;它随本项目 manifest 声明而定、与 spawn 参数无关,同一 child 终身不变。
336
387
  const spawnBlocks = []
388
+ // §8.1 任务书正文(§8.2 收集序首块):仅工程角色携带,已按角色切片(eng-coder = §2、eng-designer = §1 + §2)。
389
+ if (taskBookBlock) spawnBlocks.push(taskBookBlock)
337
390
  // §2.11 第 1 点(FR16 载体 + FR17 铁律 #5 的机械面):批次档**绝对路径**下发给工程角色
338
- // (eng-coder 实现 / eng-designer 写稿)——任务书本体 = 本档 §2;本行让子代理"拿到本档路径"。
391
+ // (eng-coder 实现 / eng-designer 写稿)——任务书正文就在上方那块;本行让子代理“拿到本档路径”(改写前回读磁盘用)。
339
392
  // 工程角色恒注入;携绑定 coder(§4.16)随绑定注入(绑定 coder 要能读到本档)。
340
393
  if (batchBound) spawnBlocks.push(`Batch record (batchDoc): ${batchDocAbs}`)
341
394
  // AGENT-LOOP-SUBAGENT.md §6.7.6 D-E2 ③ + §6.22 KD-SC6:审计 spawn 的范围证据 = 机械跟踪的
342
395
  // `_touchedFiles` ∪ 批档 §2(审计子代理自读)——**不是** eng-coder 自述(自述可恰好漏掉应抓的
343
396
  // 越界档)。块文本(含模板逐字)住 `./audit-block.mjs`(D23-3 外提)。
344
397
  if (engAuditAttempt !== null) spawnBlocks.push(buildAuditBlock(ctx))
398
+ // §6.26「写域行(S4)」:`files`(本 spawn 的预期写域,`prepareScheduling` 已归一化)非空 ⇒ 追加
399
+ // 一格——写域此前只有调度器知道,子代理只能猜自己的改动面;空 / 未传 ⇒ 不推块,system 逐字节同改前。
400
+ if (files.length > 0) spawnBlocks.push(filesBlockOf(files))
401
+ // §6.61「子代理文档坐标行(S5)」:本项目声明的三层文档坐标一行随 system 面下发。子代理此前也读得到
402
+ // `docRoot`(`manifestReadTool` 按需主动读),但那得先想到坐标记在 manifest 里、再知道键名——本行把
403
+ // 答案在 spawn 时就放进 system 面,省掉的只是那一趟(出口零新解析)。读不出 ⇒ 不推块。
404
+ const docsBlock = docsCoordinatesBlockOf(parent.cwd)
405
+ if (docsBlock) spawnBlocks.push(docsBlock)
345
406
  // The child's own task input rides the child object: D23-6 —— `_engTaskInput` 语义 = **一行机械
346
- // 任务书行**(批档绝对路径 + §2 指向句;不含固块)。
407
+ // 任务书行**(批档绝对路径 + 按角色的指向句;不含固块——正文在 system 面)。
347
408
  if (engineeringRole) child._engTaskInput = input
348
409
  // spawn 固块单点绑定(sync / async 同点——buildSpawnChild 唯一调用点):此后只读 ⇒ 同一
349
410
  // child 的任意 run(resume 续跑 / 报告追问重跑)逐字节恒定;消费点 = 核 `prepareRun`。
@@ -353,7 +414,7 @@ export function buildSpawnChild(parent, ctx, args, role, wantAsync, files, depen
353
414
  // pipeline (AGENT-LOOP-SUBAGENT.md §6.7.2 D3). Prefix includes a unique id: parallel child agents
354
415
  // with the same role stay independent and don't overwrite each other.
355
416
  // Format: role#id/ → onToken("coder#2/writing..."), onToolCall("coder#2/read", args)
356
- // Async id allocation (AGENT-LOOP-SUBAGENT.md §6.7.3 D-A1): reserve the relay counter at
417
+ // Async id allocation (AGENT-LOOP-SUBAGENT.md §6.7.3): reserve the relay counter at
357
418
  // spawn time — the returned id must be stable while the item sits in the queue.
358
419
  // The [model] token (TUI block creation) is DEFERRED to actual start so queued
359
420
  // children don't paint an empty panel block ("queued 态不显示").
@@ -382,34 +443,12 @@ export function buildSpawnChild(parent, ctx, args, role, wantAsync, files, depen
382
443
  ...wrapChildCallbacks(relayPrefix, ctx.callbacks),
383
444
  }
384
445
  const childRunOpts = buildChildRunOpts(ctx)
446
+ // B8(TOOLS.md §6.29 ④):eng 两角色各挂一枚**本批窗口**的受限 `read_history`(同名工具、
447
+ // 经 extraTools 注入——装配面在 `agent/setup.mjs` 的 `extraTools` 段)。未绑定角色不挂(K7)。
448
+ if (engineeringRole) childRunOpts.extraTools = [makeBatchHistoryTool(rootAgentOf(parent), batchDocAbs)]
385
449
  return { child, input, childOpts, childRunOpts, relayPrefix, childProvider }
386
450
  }
387
-
388
- // ── design-token 门(TOOLS.md §6.25 ③④——四态互异拒句;拒绝集合与旧三条件合取全等) ──
389
-
390
- /** 四态拒句(逐字 = TOOLS.md §6.25 ③):missing / mismatch / expired / invalid。
391
- * mismatch 可携 designId(非凭证);四句均零令牌值回显。 */
392
- export function designTokenRefusal(kind, designId) {
393
- if (kind === "missing") return new Error("designToken missing — the eng-coder spawn is refused: no usable token for an approved design slot came with this spawn. Pass the designToken parameter with the exact value from the subagent action:'design-slots' row (the text after designToken=), copied verbatim; if that list is empty, no design review has been approved in this session yet — run advisor with type='design' first. No token value is echoed here.")
394
- if (kind === "mismatch") return new Error("designToken mismatch — the eng-coder spawn is refused: the value passed does not equal the token held for this design slot. Re-read the subagent action:'design-slots' row and pass the value after designToken= verbatim, unchanged. No token value is echoed here." + (designId ? ` (designId: ${designId})` : ""))
395
- if (kind === "expired") return new Error("designToken expired — the eng-coder spawn is refused: the token matches this design slot but is past its TTL. The expired slot has been removed; run advisor with type='design' again on the current design and pass the newly issued token — an expired authorization cannot be retried. No token value is echoed here.")
396
- return new Error("designToken invalid — the eng-coder spawn is refused: the value passed equals this design slot's stored token, but that stored value is not a well-formed token, so no expiry can be judged and the slot was left in place. Run advisor with type='design' to issue a fresh token for this design; a malformed record never passes the gate. No token value is echoed here.")
397
- }
398
-
399
- /** eng-coder spawn 的令牌门(TOOLS.md §6.25 ④):resolveDesignSlot 的既有两条 designId
400
- * 诊断零改 → 参数在场 → 值相等 → 值有效。槽删除只在 tokenExpired(given) 成立时发生
401
- * (D-R16c ③);mismatch / invalid 不删槽(T-R16d)。返回槽内令牌(调用方回写 designId
402
- * 依赖它);sync / async 两路共经 buildSpawnChild——一处判定双路生效。 */
403
- export function gateDesignToken(parent, args) {
404
- const issuedToken = resolveDesignSlot(parent, args?.designId).token
405
- // 非字符串 ⇒ 空串 ⇒ missing(本意——T9 锁定)
406
- const given = typeof args?.designToken === "string" ? args.designToken : ""
407
- if (!issuedToken || !given.trim()) throw designTokenRefusal("missing")
408
- if (given !== issuedToken) throw designTokenRefusal("mismatch", args?.designId)
409
- if (!validateDesignToken(given)) {
410
- const expired = tokenExpired(given)
411
- if (expired) removeDesignTokenSlot(parent, args?.designId, given)
412
- throw designTokenRefusal(expired ? "expired" : "invalid")
413
- }
414
- return issuedToken
415
- }
451
+ // 设计令牌门(七态拒句 ∥ eng-coder spawn 的令牌判定)已搬 `./subagent-design-token.mjs`(分拆落点 =
452
+ // `docs/core/design/PATH-RESOLUTION.md` §3 末条);本档**原样再导出**其导出面 ⇒ `subagent.mjs` 的再导出行与
453
+ // 用例的 import 行零改。
454
+ export { designTokenRefusal, gateDesignToken, resolveDesignSlot } from "./subagent-design-token.mjs"
@@ -121,7 +121,9 @@ export function buildSyncStoppedReport(role, capturedOutput, designId) {
121
121
  * (suitable for codebase exploration); "coder" — full tool set, self-contained
122
122
  * implementation tasks; "plan" — read-only planning; "eng-coder" —
123
123
  * engineering-mode implementation (design-token gated); "eng-designer" —
124
- * engineering-mode design writing (requirements + design docs, batchDoc gated).
124
+ * engineering-mode design writing (requirements + design docs, batchDoc gated);
125
+ * "tester" — verification runs and readings (read-only set ∪ execute/bash; no write tool in the table —
126
+ * run-only is the role contract, not a sandbox).
125
127
  * - no role specified — invalid by design since the 2026-08-25 fail-closed gate
126
128
  * (role is mandatory; "no role → same tool set as parent" was removed with the
127
129
  * coder-leak fix and the header text above predates it)
@@ -139,28 +141,28 @@ export const subagentTool = {
139
141
  action: { type: "string", enum: ["spawn", "status", "escalate", "cancel", "panel", "consume-design", "observe", "send", "design-slots"], description: "Which action — spawn (default) / status / observe / send / escalate / cancel / panel / consume-design / design-slots; semantics per action in the tool description." },
140
142
  view: { type: "boolean", description: "action:'panel' only: true (default) = the live panel blocks as the user sees them; false without freeze = error. Mutually exclusive with freeze (freeze wins)." },
141
143
  freeze: { type: "string", description: "action:'panel' only: block key of a digested-stuck block — reclaims it into the conversation; refused for running/done/unknown blocks or a still-pending report; works on the CLI TUI panel and on the desktop renderer panel (live readback of the blocks as the user sees them)." },
142
- task: { type: "string", description: "For action:'spawn': normal-mode roles (explore/plan/coder) — OPTIONAL free-text supplement; the brief itself is the four core parameters (goal / knownFacts / acceptance / reportFormat) + scope. Engineering roles (eng-coder / eng-designer) take NO task-book text parameters — their task book is batch record §2 (batchDoc), read by the child itself. For action:'escalate': the brief (goal, constraints, entry files, acceptance criteria)." },
143
- context: { type: "string", description: "Optional background for normal-mode spawns (explore/plan/coder) only; action:'spawn' only." },
144
- role: { type: "string", enum: ["explore", "plan", "coder", "eng-coder", "eng-designer"], description: "The sub-agent role — see the role matrix in the tool description. Exact spelling required. action:'spawn' only (escalate spawns its own expert internally)." },
144
+ task: { type: "string", description: "For action:'spawn': non-engineering roles (explore / plan / coder / tester) — OPTIONAL free-text supplement; the brief itself is the four core parameters (goal / knownFacts / acceptance / reportFormat) + scope. Engineering roles (eng-coder / eng-designer) take NO task-book text parameters — their task book is batch record §2 (batchDoc), read by the child itself. For action:'escalate': the brief (goal, constraints, entry files, acceptance criteria)." },
145
+ context: { type: "string", description: "Optional background for non-engineering spawns (explore / plan / coder / tester) only; action:'spawn' only." },
146
+ role: { type: "string", enum: ["explore", "plan", "coder", "eng-coder", "eng-designer", "tester"], description: "The sub-agent role — see the role matrix in the tool description. Exact spelling required. action:'spawn' only (escalate spawns its own expert internally)." },
145
147
  model: { type: "string", description: "action:'spawn': provider/model override ('provider:model', a provider, or a model name on the parent's provider) — defaults config.agent.subagentModels[role] → config.agent.subagentModel → the parent's provider; \"default\" inherits. action:'escalate': a consult candidate (default = the first)." },
146
148
  designToken: { type: "string", description: "REQUIRED for role='eng-coder': the exact token issued by advisor(type='design') after the review passed — copy it verbatim from the design-slots row (the text after designToken=). missing or mismatched = the spawn is refused; an expired token is refused with expired named. Pass it on every eng-coder spawn, fix rounds included (they reuse the same token)." },
147
149
  designId: { type: "string", description: "role='eng-coder': the designId echoed with the approved token — required to pick between concurrent designs (optional for one). action:'consume-design': the single-slot selector (required to pick between several; the gate refuses to guess); see designIds / expired / olderThanDays for batch consumption. action:'design-slots': filter the inventory to one slot (trimmed exact match; an empty string means no filter; an unknown id is refused with the held id list)." },
148
150
  designIds: { type: "array", items: { type: "string" }, description: "action:'consume-design' (batch): an explicit non-empty list of design ids to close out — pass exactly ONE selector per call (designId / designIds / expired / olderThanDays)." },
149
151
  expired: { type: "boolean", description: "action:'consume-design' (batch): true = close out every expired slot (exactly ONE selector per call)." },
150
152
  olderThanDays: { type: "number", description: "action:'consume-design' (batch): close out every slot older than N days (age > N; exactly ONE selector per call)." },
151
- batchDoc: { type: "string", description: "REQUIRED for role='eng-coder'/'eng-designer': the batch record path (e.g. <repo>/docs/batches/<batch>-<topic>.md; relative paths resolve against the session cwd first, then candidate project roots — or absolute) — the task book this spawn implements/writes. This IS the task book for engineering roles — batch record §2, read by the child itself. Refused when absent or when the path does not resolve to a readable file; the content is never validated. role='coder' (normal mode): optional — binds this spawn's §5 record-write channel (unbound ⇒ the main agent records §5 on its behalf); when provided the path must resolve to a readable file." },
153
+ batchDoc: { type: "string", description: "REQUIRED for role='eng-coder'/'eng-designer': the batch record path (e.g. <repo>/docs/batches/<batch>-<topic>.md; relative paths resolve against the session cwd first, then candidate project roots — or absolute) — the task book this spawn implements/writes. This IS the task book for engineering roles — batch record §2, read by the child itself. Refused when absent, when the path does not resolve to a readable file, or when that record already has an in-flight spawn — one batch record serves one concurrent spawn: wait for the occupant to settle (or cancel it) before spawning again. The content is never validated. role='coder' (normal mode): optional — binds this spawn's §5 record-write channel (unbound ⇒ the main agent records §5 on its behalf); when provided the path must resolve to a readable file." },
152
154
  round: { type: "string", enum: ROUND_VALUES, description: "REQUIRED for role='eng-coder'/'eng-designer': initial (first round for this design) or fix (a correction round reusing the same designId+designToken; docs FIRST). No default — missing = refused." },
153
- goal: { type: "string", description: "REQUIRED for role='explore'/'plan'/'coder' (normal-mode task book): the task book's goal & why — the problem this solves and the cost chain (content only, no label — the runtime composes the labels)." },
154
- knownFacts: { type: "string", description: "REQUIRED for role='explore'/'plan'/'coder' (normal-mode task book): the facts and file paths the parent already verified — the child must not re-explore them." },
155
- scope: { type: "string", description: "REQUIRED for role='explore'/'plan'/'coder' (normal-mode task book, the fifth parameter): scope & forbidden scope — what to read / search and what not to touch." },
156
- acceptance: { type: "string", description: "REQUIRED for role='explore'/'plan'/'coder' (normal-mode task book): acceptance criteria — machine-verifiable (commands / thresholds / assertion counts)." },
157
- reportFormat: { type: "string", description: "REQUIRED for role='explore'/'plan'/'coder' (normal-mode task book): the delivery-report format the child must produce." },
158
- async: { type: "boolean", description: "action:'spawn'/'escalate': default at depth 0 = true (async; the report arrives automatically); depth>0 always sync. async:false forces the blocking flight." },
155
+ goal: { type: "string", description: "REQUIRED for role='explore'/'plan'/'coder'/'tester' (non-engineering task book): the task book's goal & why — the problem this solves and the cost chain (content only, no label — the runtime composes the labels)." },
156
+ knownFacts: { type: "string", description: "REQUIRED for role='explore'/'plan'/'coder'/'tester' (non-engineering task book): the facts and file paths the parent already verified — the child must not re-explore them." },
157
+ scope: { type: "string", description: "REQUIRED for role='explore'/'plan'/'coder'/'tester' (non-engineering task book, the fifth parameter): scope & forbidden scope — what to read / search and what not to touch." },
158
+ acceptance: { type: "string", description: "REQUIRED for role='explore'/'plan'/'coder'/'tester' (non-engineering task book): acceptance criteria — machine-verifiable (commands / thresholds / assertion counts)." },
159
+ reportFormat: { type: "string", description: "REQUIRED for role='explore'/'plan'/'coder'/'tester' (non-engineering task book): the delivery-report format the child must produce." },
160
+ async: { type: "boolean", description: "Required: `true` = async spawn (report via the auto channel); `false` = blocking; omitting it is refused. At depth>0 every spawn is synchronous — an explicit `async: true` there is refused. action:'escalate' keeps its own form: omission there still means the async flight, and `false` asks for the blocking one." },
159
161
  files: { type: "array", items: { type: "string" }, description: "action:'spawn' only: the file write-domain this task declares — file-level paths only (cwd-relative or absolute; directories rejected — they bypass the conflict detector). Overlapping-file tasks serialize automatically. Omit = no conflict detection." },
160
162
  dependsOn: { type: "array", items: { type: "string" }, description: "action:'spawn' only: ids from prior async returns whose outcome this task needs — queues until every dependency settles, then starts. Consumed ids count as satisfied; a cancelled/failed dependency stays queued marked 'dependency cancelled' until you decide (AUTO sessions auto-start). Unknown ids error." },
161
163
  id: { type: "string", description: "action:'status'/'observe'/'send'/'cancel': the subagent id from the spawn return. status: omit = pool overview; observe/send/cancel: REQUIRED." },
162
164
  message: { type: "string", description: "action:'send' only (REQUIRED there): the direction to inject — consumed by the running child at its next turn boundary as an ordinary instruction (non-interrupting)." },
163
- recent: { type: "integer", description: "action:'observe' only (optional, default 5): how many recent-turn summaries (1..20)." },
165
+ recent: { type: "integer", description: "Required for action:'observe': how many recent-turn summaries (1..20)" },
164
166
  },
165
167
  required: [],
166
168
  },
@@ -222,25 +224,26 @@ export const subagentTool = {
222
224
  // schema), so the mechanical check lives here: an absent task would otherwise
223
225
  // flow downstream as `content: undefined` and surface as an obscure error.
224
226
  // 载体判据:**非工程角色** = 结构化参数(拼装后非空)——task 只作补充;两者皆缺 ⇒ 此处先拒。
225
- // 工程角色 = 无任务书文本参数(任务书 = 批次档 §2):此处不判——自由文本键由
227
+ // 工程角色 = 无任务书文本参数(任务书 = 绑定批档,按角色切片(§8.1)):此处不判——自由文本键由
226
228
  // buildSpawnChild 的任务书门键在场即拒并点名(空集拼装不得误报「缺任务书」)。
227
229
  if (!isEngineeringRole(args.role) && !composeTaskBookBrief(args, args.role) && (typeof args.task !== "string" || !args.task.trim())) {
228
- throw new Error("subagent action:'spawn' requires the structured task-book parameters for normal-mode roles (four core: goal / knownFacts / acceptance / reportFormat + scope) — a free-text task alone is not the brief. Engineering roles take no task-book text parameters: their task book is batch record §2.")
230
+ throw new Error("subagent action:'spawn' requires the structured task-book parameters for non-engineering roles (explore / plan / coder / tester) (four core: goal / knownFacts / acceptance / reportFormat + scope) — a free-text task alone is not the brief. Engineering roles take no task-book text parameters: their task book is the bound batch record (batchDoc), sliced per role into the spawn system block.")
229
231
  }
230
- // §18 D-E1a depth-gated async default (2026-09-06 需求池 R12): depth-0 spawns
231
- // default to async for EVERY role (the old role-level default — eng-coder only —
232
- // is superseded); depth>0 spawns default to sync (子代理内部强制同步现状保留).
233
- // async:false remains the explicit escape hatch; async:true at depth>0 is
234
- // refused downstream (executeAsyncSpawn top-level gate).
235
- const wantAsync = args.async ?? ((ctx.depth ?? 0) === 0)
232
+ // §18 D-E1a(必填化——2026-11-07 批 tool-param-zero-defaults):`recent` ∥ `async` 皆必填;
233
+ // depth 不再替调用方选(旧形 `args.async ?? depth === 0` 已撤)。depth>0 无异步——显式
234
+ // `async:true` 下游拒(`async spawn only available at the top level`);`async:false` 仍是阻塞飞行的显式形。
235
+ if (args.async !== true && args.async !== false) {
236
+ throw new Error("subagent: async is required — pass true for an async spawn or false for a blocking flight")
237
+ }
238
+ const wantAsync = args.async
236
239
 
237
240
  // Role normalization + whitelist (2026-08-25, coder-leak fix): exact-string gates let
238
241
  // variant roles ("Coder", " coder") bypass BOTH mode gates and fall through to
239
242
  // full tools / no overlay — a full-write coder without design review. Schema enums are
240
243
  // advisory; providers don't enforce them. Fail closed on unknown roles.
241
- const ROLES = new Set(["explore", "plan", "coder", "eng-coder", "eng-designer"])
244
+ const ROLES = new Set(["explore", "plan", "coder", "eng-coder", "eng-designer", "tester"])
242
245
  if (!ROLES.has(role)) {
243
- throw new Error(`Unknown subagent role: ${JSON.stringify(role)}. Valid roles: explore, plan, coder, eng-coder, eng-designer (exact spelling).`)
246
+ throw new Error(`Unknown subagent role: ${JSON.stringify(role)}. Valid roles: explore, plan, coder, eng-coder, eng-designer, tester (exact spelling).`)
244
247
  }
245
248
  // AGENT-LOOP-SUBAGENT.md §6.7.6 D-E3 internal-spawn gate: an eng-coder sub-agent may only spawn sync
246
249
  // explore (audit) children — non-explore roles and async are refused here
@@ -254,7 +257,7 @@ export const subagentTool = {
254
257
  throw new Error("Engineering mode: role='coder' is disabled — use role='eng-coder' for implementation tasks (or role='eng-designer' for design writing).")
255
258
  }
256
259
  if (parent.config?.agent?.engineering && role === "plan") {
257
- throw new Error("Engineering mode: role='plan' is disabled — the engineering-mode enum is explore / eng-designer / eng-coder (plan is a normal-mode role).")
260
+ throw new Error("Engineering mode: role='plan' is disabled — the engineering-mode enum is explore / eng-designer / eng-coder / tester (plan is a normal-mode role).")
258
261
  }
259
262
  if (!parent.config?.agent?.engineering && role === "eng-coder") {
260
263
  throw new Error("Engineering mode is not active — use role='coder' for implementation tasks.")
@@ -0,0 +1,94 @@
1
+ /**
2
+ * taskbook-block.mjs — 工程角色的任务书正文块构造器(`AGENT-LOOP-SUBAGENT.md` §8.1 载体 ∥ 切片 ∥ 快照)。
3
+ *
4
+ * 为什么另立一档(同 `audit-block.mjs` 的 D23-3 外提先例):块构造是纯函数 ⇒ 判据可直测,
5
+ * 而装配点 `subagent-spawn.mjs` 已接近设计时行数线,不因新增逻辑逼近它。
6
+ *
7
+ * 三件事都在本档定:
8
+ * - **切片**:按角色取段(§8.1)——eng-coder 取 §2,eng-designer 取 §1 + §2。切法 = 段头之间的文本,
9
+ * 段界判据消费批次档段解析的既有实现(`batch-segment-vocab.mjs` 的 `sectionHeaderRe` ∥ `sectionBodyLines`
10
+ * ——段头形态与「下一个 `## §N`」两处判据的唯一住所;`batch-skeleton.mjs` 只再导出其中 `sectionHeaderRe`,
11
+ * 故本档直接消费叶档);不解析标题文字,也不在本档另写一份段界正则。
12
+ * - **快照**:正文由装配点在 spawn 当刻读一次后传进来,此后批档改动不回流——本档零 fs,只做切与拼。
13
+ * - **失效即拒**:该角色的段切不出来(没有对应段头)⇒ 抛错并点名路径与缺失段,不退回「只发指向句」
14
+ * (退回会让 §8.1 的承诺落空而无人知道)。
15
+ *
16
+ * 不截断:截断后的副本仍自称任务书原文,比不给更坏(§8.1)。
17
+ */
18
+
19
+ import { sectionHeaderRe, sectionBodyLines } from "./batch-segment-vocab.mjs"
20
+
21
+ /** 角色 → 进 system 固块的段号(§8.1)。eng-designer 取 §1 + §2:§1 是约束它的裁决、§2 是它自己的笔;
22
+ * §3–§6 不进固块,由该角色按需从磁盘读(改动随时可见)。非工程角色不在此表 ⇒ 不携任务书块。 */
23
+ export const TASK_BOOK_SEGMENTS = Object.freeze({
24
+ "eng-coder": Object.freeze([2]),
25
+ "eng-designer": Object.freeze([1, 2]),
26
+ })
27
+
28
+ /** 块首说明行(§8.1):让子代理知道手里这份是快照,改写/引述之前要回读磁盘。 */
29
+ const SNAPSHOT_NOTE =
30
+ "[Task book — the text below is the batch record verbatim as it stood at spawn time; later edits to the record do not flow into this copy. " +
31
+ "Re-read the record on disk before rewriting or quoting any segment — the batch tool's `edit` anchors only on the current on-disk text.]"
32
+
33
+ /** 段体首尾空行不计(段头之间的空行属版式,不属于该段内容)。 */
34
+ function withoutBlankEdges(lines) {
35
+ let start = 0
36
+ let end = lines.length
37
+ while (start < end && lines[start].trim() === "") start++
38
+ while (end > start && lines[end - 1].trim() === "") end--
39
+ return lines.slice(start, end)
40
+ }
41
+
42
+ /**
43
+ * 任务书正文块(§8.1 / §8.2 收集序首块):纯函数——零 fs、零副作用。
44
+ * @param {{ role: string, record: { path: string, text: string } }} input
45
+ * `role` = 本次 spawn 的角色;`record.path` = 批档绝对路径(拒文点名用);
46
+ * `record.text` = **spawn 当刻**读到的批档全文(快照本体)。
47
+ * @returns {string} 块文本(段之间 `\n\n`;与其它块之间的分隔由装配侧 `join("\n\n")` 施加)
48
+ */
49
+ export function buildTaskBookBlock({ role, record }) {
50
+ const segs = TASK_BOOK_SEGMENTS[role]
51
+ if (!segs) {
52
+ throw new Error(`buildTaskBookBlock: role '${role}' takes no task-book block — only the engineering roles (${Object.keys(TASK_BOOK_SEGMENTS).join(" / ")}) carry one; every other role gets its task book from the structured parameters`)
53
+ }
54
+ const path = record?.path
55
+ const text = record?.text
56
+ if (typeof path !== "string" || path.trim() === "") {
57
+ throw new Error("buildTaskBookBlock: record.path is required (the batch record's absolute path) — the refusal text must name the record it could not cut a segment out of")
58
+ }
59
+ if (typeof text !== "string") {
60
+ throw new Error(`buildTaskBookBlock: record.text is required for ${path} (the batch record's full text as read at spawn time)`)
61
+ }
62
+ const parts = [SNAPSHOT_NOTE]
63
+ for (const seg of segs) {
64
+ const hdr = sectionHeaderRe(seg).exec(text)
65
+ if (!hdr) {
66
+ throw new Error(`Task book unavailable — spawn refused: the batch record at ${path} has no "## §${seg}" section header, so the ${role} task book (§${segs.join(" + §")}) cannot be cut from it. Restore that segment header (create is the batch record skeleton's only authoritative entry), or point batchDoc at the record that carries it.`)
67
+ }
68
+ const nl = text.indexOf("\n", hdr.index)
69
+ const headerLine = (nl < 0 ? text.slice(hdr.index) : text.slice(hdr.index, nl)).replace(/\r$/, "")
70
+ const body = withoutBlankEdges(sectionBodyLines(text, seg) ?? [])
71
+ parts.push([headerLine, ...body].join("\n"))
72
+ }
73
+ return parts.join("\n\n")
74
+ }
75
+
76
+ /**
77
+ * 首条 user 消息的任务书指向句(§3.1「首条 user 消息只留指向句:批档路径 + 其余段自读」)。
78
+ *
79
+ * 两句都不带「only」/「唯一」措辞:「唯一任务通道」只对 eng-coder 的那一段成立,eng-designer 的通道是
80
+ * 整份批档(§1 的裁决对它具约束力),对它声称唯一通道即与 §3.1 互斥。
81
+ * @param {string} role — 本次 spawn 的角色(只有 TASK_BOOK_SEGMENTS 里的角色有指向句)
82
+ * @param {string} recordPath — 批档绝对路径(装配点已解析)
83
+ * @returns {string} 一行机械任务书行
84
+ */
85
+ export function taskBookPointerLine(role, recordPath) {
86
+ const segs = TASK_BOOK_SEGMENTS[role]
87
+ if (!segs) {
88
+ throw new Error(`taskBookPointerLine: role '${role}' has no task-book pointer line — only the engineering roles (${Object.keys(TASK_BOOK_SEGMENTS).join(" / ")}) carry one`)
89
+ }
90
+ if (role === "eng-coder") {
91
+ return `Task book: §2 of the batch record at ${recordPath} — reproduced verbatim in your system prompt as it stood at spawn time. Read the record itself for any other segment; §5 of that record is where you record the implementation.`
92
+ }
93
+ return `Task book: the batch record at ${recordPath} — §1 (the rulings that bind you) and §2 (your own pen) are reproduced verbatim in your system prompt as they stood at spawn time. Read the record itself for §3–§6, and re-read the current §2 text before you edit it.`
94
+ }