@thincoder/core 0.11.1 → 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 (333) hide show
  1. package/CHANGELOG.md +46 -2
  2. package/advisor/convergence.mjs +34 -3
  3. package/advisor/loop.mjs +42 -10
  4. package/advisor/messages.mjs +42 -25
  5. package/advisor/project-context.mjs +171 -42
  6. package/advisor/run.mjs +7 -4
  7. package/advisor.mjs +29 -43
  8. package/agent/batch-attribution.mjs +87 -0
  9. package/agent/batch-changed-surface.mjs +129 -0
  10. package/agent/completion.mjs +44 -3
  11. package/agent/dispatch-gates.mjs +6 -0
  12. package/agent/dispatch.mjs +8 -3
  13. package/agent/family-tools.mjs +27 -12
  14. package/agent/helpers.mjs +122 -1
  15. package/agent/offload.mjs +25 -29
  16. package/agent/post-turn.mjs +24 -10
  17. package/agent/record-results.mjs +18 -1
  18. package/agent/run-stages.mjs +77 -32
  19. package/agent/run-start.mjs +37 -0
  20. package/agent/setup-reminders.mjs +9 -2
  21. package/agent/setup.mjs +24 -11
  22. package/agent/spawn-child.mjs +38 -1
  23. package/agent/timers.mjs +5 -3
  24. package/agent/turn-loop.mjs +30 -5
  25. package/agent/turn-projection.mjs +386 -0
  26. package/agent/turn-task-state.mjs +274 -0
  27. package/agent/turn-tool-process.mjs +168 -0
  28. package/agent/write-gate-ledger.mjs +569 -0
  29. package/agent/write-gate.mjs +29 -352
  30. package/agent-tools/advisor-async.mjs +29 -169
  31. package/agent-tools/advisor-launch.mjs +178 -0
  32. package/agent-tools/advisor-settle.mjs +28 -1
  33. package/agent-tools/advisor.mjs +36 -47
  34. package/agent-tools/audit-block.mjs +6 -6
  35. package/agent-tools/batch-closeout.mjs +273 -35
  36. package/agent-tools/batch-gate.mjs +142 -342
  37. package/agent-tools/batch-ledger-bind.mjs +226 -17
  38. package/agent-tools/batch-ledger-view.mjs +109 -0
  39. package/agent-tools/batch-lifecycle.mjs +169 -46
  40. package/agent-tools/batch-paths.mjs +29 -8
  41. package/agent-tools/batch-record-write.mjs +417 -0
  42. package/agent-tools/batch-regions.mjs +215 -0
  43. package/agent-tools/batch-reopen.mjs +23 -11
  44. package/agent-tools/batch-segment-vocab.mjs +379 -0
  45. package/agent-tools/batch-skeleton.mjs +192 -239
  46. package/agent-tools/batch-supersede.mjs +232 -0
  47. package/agent-tools/batch-tier-gate.mjs +297 -0
  48. package/agent-tools/batch.mjs +182 -439
  49. package/agent-tools/consult.mjs +7 -4
  50. package/agent-tools/context.mjs +44 -17
  51. package/agent-tools/design-review-record.mjs +225 -0
  52. package/agent-tools/design-slots.mjs +1 -1
  53. package/agent-tools/design-token.mjs +279 -81
  54. package/agent-tools/doc-check.mjs +43 -33
  55. package/agent-tools/doc-graph.mjs +140 -0
  56. package/agent-tools/eng.mjs +9 -8
  57. package/agent-tools/escalate-async.mjs +2 -2
  58. package/agent-tools/manifest.mjs +34 -18
  59. package/agent-tools/read-history.mjs +112 -11
  60. package/agent-tools/review-facts.mjs +10 -3
  61. package/agent-tools/settings.mjs +23 -2
  62. package/agent-tools/spawn-gates.mjs +9 -8
  63. package/agent-tools/ssh-session.mjs +2 -2
  64. package/agent-tools/ssh-text.mjs +155 -0
  65. package/agent-tools/ssh-transport.mjs +19 -148
  66. package/agent-tools/subagent-actions-query.mjs +10 -6
  67. package/agent-tools/subagent-async.mjs +8 -9
  68. package/agent-tools/subagent-brief.mjs +76 -0
  69. package/agent-tools/subagent-design-token.mjs +168 -0
  70. package/agent-tools/subagent-run.mjs +1 -1
  71. package/agent-tools/subagent-scheduler.mjs +4 -4
  72. package/agent-tools/subagent-spawn.mjs +90 -110
  73. package/agent-tools/subagent.mjs +11 -10
  74. package/agent-tools/taskbook-block.mjs +94 -0
  75. package/agent-tools/timer.mjs +12 -8
  76. package/agent-tools/verify.mjs +13 -4
  77. package/agent-tools.mjs +7 -3
  78. package/agent.mjs +20 -1
  79. package/attachments.mjs +3 -3
  80. package/browser/actions.mjs +9 -3
  81. package/browser/cdp.mjs +45 -17
  82. package/browser/launch.mjs +25 -43
  83. package/browser/pool.mjs +299 -0
  84. package/browser/queue.mjs +2 -0
  85. package/browser/session-state.mjs +450 -0
  86. package/browser/session.mjs +127 -151
  87. package/browser/snapshot.mjs +89 -0
  88. package/client-identity.mjs +1 -1
  89. package/config-defaults.mjs +2 -1
  90. package/config-migrate.mjs +40 -0
  91. package/config-normalize.mjs +28 -2
  92. package/config-reload.mjs +59 -0
  93. package/config.mjs +62 -98
  94. package/context-degrade.mjs +38 -10
  95. package/context-echo.mjs +11 -0
  96. package/context.mjs +149 -83
  97. package/conventions.mjs +11 -9
  98. package/declaration.mjs +31 -5
  99. package/declared-repos.mjs +94 -0
  100. package/doc-check/doc-names.mjs +73 -0
  101. package/doc-check/doc-tokens.mjs +110 -0
  102. package/doc-check/existence.mjs +160 -0
  103. package/doc-check/index.mjs +309 -213
  104. package/doc-check/line-refs.mjs +27 -101
  105. package/doc-check/paragraph.mjs +218 -102
  106. package/doc-graph/anchors.mjs +474 -0
  107. package/doc-graph/doc-batch-face.mjs +59 -0
  108. package/doc-graph/doc-suffix.mjs +27 -0
  109. package/doc-graph/graph-tokens.mjs +160 -0
  110. package/doc-graph.mjs +778 -0
  111. package/explore-distill.mjs +11 -5
  112. package/i18n.mjs +1 -1
  113. package/instance-inbox-watch.mjs +272 -0
  114. package/instance-inbox.mjs +218 -0
  115. package/instance-registry.mjs +179 -0
  116. package/knowledge/README.md +3 -0
  117. package/knowledge/prompt-resources.md +6 -0
  118. package/ledger-close-proof.mjs +100 -49
  119. package/ledger-close.mjs +188 -0
  120. package/ledger-cmd.mjs +47 -91
  121. package/ledger-consistency.mjs +113 -0
  122. package/ledger-db.mjs +47 -15
  123. package/ledger-executors.mjs +1 -1
  124. package/ledger-tools.mjs +78 -19
  125. package/ledger-write-ops.mjs +130 -41
  126. package/ledger.mjs +1 -1
  127. package/manifest-discovery.mjs +3 -1
  128. package/manifest-schema.mjs +27 -5
  129. package/memory/schema.mjs +2 -2
  130. package/package.json +3 -1
  131. package/path-resolve.mjs +338 -57
  132. package/prompt-files.mjs +91 -1
  133. package/prompt-overlays.mjs +9 -6
  134. package/prompts/advisor-design.md +62 -21
  135. package/prompts/advisor-round1.md +34 -1
  136. package/prompts/advisor-round2.md +40 -7
  137. package/prompts/advisor-round3.md +39 -6
  138. package/prompts/common.md +14 -387
  139. package/prompts/consult-base.md +5 -1
  140. package/prompts/discipline-engineering.md +226 -51
  141. package/prompts/discipline-normal.md +4 -255
  142. package/prompts/knowledge/business-gates.md +22 -0
  143. package/prompts/knowledge/decision-quality.md +23 -0
  144. package/prompts/knowledge/doc-lookup.md +35 -0
  145. package/prompts/knowledge/document-writing.md +51 -0
  146. package/prompts/knowledge/documentation-evaluation.md +56 -0
  147. package/prompts/knowledge/evidence-discipline.md +57 -0
  148. package/prompts/knowledge/normal-coding-workflow.md +104 -0
  149. package/prompts/knowledge/normal-delivery-collaboration.md +108 -0
  150. package/prompts/knowledge/normal-work-management.md +57 -0
  151. package/prompts/knowledge/product-security.md +23 -0
  152. package/prompts/knowledge/project-records.md +62 -0
  153. package/prompts/knowledge/tool-advisor.md +29 -0
  154. package/prompts/knowledge/tool-apply-patch.md +18 -0
  155. package/prompts/knowledge/tool-bash.md +39 -0
  156. package/prompts/knowledge/tool-batch-eng-coder.md +12 -0
  157. package/prompts/knowledge/tool-batch-eng-designer.md +12 -0
  158. package/prompts/knowledge/tool-batch-review.md +12 -0
  159. package/prompts/knowledge/tool-batch.md +80 -0
  160. package/prompts/knowledge/tool-browser.md +57 -0
  161. package/prompts/knowledge/tool-code-search.md +4 -0
  162. package/prompts/knowledge/tool-consult-start.md +12 -0
  163. package/prompts/knowledge/tool-consult-stop.md +6 -0
  164. package/prompts/knowledge/tool-context.md +6 -0
  165. package/prompts/knowledge/tool-delete.md +17 -0
  166. package/prompts/knowledge/tool-doc-check.md +70 -0
  167. package/prompts/knowledge/tool-doc-graph-read.md +20 -0
  168. package/prompts/knowledge/tool-doc-graph.md +49 -0
  169. package/prompts/knowledge/tool-doc-search.md +6 -0
  170. package/prompts/knowledge/tool-edit.md +38 -0
  171. package/prompts/knowledge/tool-eng.md +2 -0
  172. package/prompts/knowledge/tool-execute.md +16 -0
  173. package/prompts/knowledge/tool-fetch.md +12 -0
  174. package/prompts/knowledge/tool-file-ops.md +16 -0
  175. package/prompts/knowledge/tool-get-current-time.md +7 -0
  176. package/prompts/knowledge/tool-git-read.md +19 -0
  177. package/prompts/knowledge/tool-git.md +29 -0
  178. package/prompts/knowledge/tool-glob.md +15 -0
  179. package/prompts/knowledge/tool-goal.md +8 -0
  180. package/prompts/knowledge/tool-grep.md +18 -0
  181. package/prompts/knowledge/tool-hashline-edit.md +14 -0
  182. package/prompts/knowledge/tool-insert-after.md +15 -0
  183. package/prompts/knowledge/tool-instance-list.md +6 -0
  184. package/prompts/knowledge/tool-instance-send.md +10 -0
  185. package/prompts/knowledge/tool-knowledge.md +18 -0
  186. package/prompts/knowledge/tool-ledger-read.md +35 -0
  187. package/prompts/knowledge/tool-ledger.md +42 -0
  188. package/prompts/knowledge/tool-lint.md +16 -0
  189. package/prompts/knowledge/tool-ls.md +13 -0
  190. package/prompts/knowledge/tool-lsp.md +11 -0
  191. package/prompts/knowledge/tool-main-history.md +2 -0
  192. package/prompts/knowledge/tool-manifest-read.md +14 -0
  193. package/prompts/knowledge/tool-manifest.md +31 -0
  194. package/prompts/knowledge/tool-memory-read.md +20 -0
  195. package/prompts/knowledge/tool-memory.md +15 -0
  196. package/prompts/knowledge/tool-notify-parent.md +12 -0
  197. package/prompts/knowledge/tool-operations.md +114 -0
  198. package/prompts/knowledge/tool-peer-instances.md +2 -0
  199. package/prompts/knowledge/tool-plan.md +6 -0
  200. package/prompts/knowledge/tool-process-read.md +13 -0
  201. package/prompts/knowledge/tool-process.md +15 -0
  202. package/prompts/knowledge/tool-question.md +16 -0
  203. package/prompts/knowledge/tool-read-history-batch.md +22 -0
  204. package/prompts/knowledge/tool-read-history.md +36 -0
  205. package/prompts/knowledge/tool-read-image.md +11 -0
  206. package/prompts/knowledge/tool-read.md +21 -0
  207. package/prompts/knowledge/tool-recent-changes.md +6 -0
  208. package/prompts/knowledge/tool-repo-outline.md +4 -0
  209. package/prompts/knowledge/tool-settings-read.md +12 -0
  210. package/prompts/knowledge/tool-settings.md +18 -0
  211. package/prompts/knowledge/tool-skill.md +6 -0
  212. package/prompts/knowledge/tool-ssh.md +52 -0
  213. package/prompts/knowledge/tool-subagent.md +59 -0
  214. package/prompts/knowledge/tool-task.md +12 -0
  215. package/prompts/knowledge/tool-team-ledger-read.md +11 -0
  216. package/prompts/knowledge/tool-team-ledger.md +11 -0
  217. package/prompts/knowledge/tool-timer.md +23 -0
  218. package/prompts/knowledge/tool-tree.md +14 -0
  219. package/prompts/knowledge/tool-verify.md +19 -0
  220. package/prompts/knowledge/tool-wait-for.md +25 -0
  221. package/prompts/knowledge/tool-websearch.md +19 -0
  222. package/prompts/knowledge/tool-write.md +9 -0
  223. package/prompts/knowledge/upstream-protocol.md +43 -0
  224. package/prompts/persona-eng-coder.md +21 -3
  225. package/prompts/persona-eng-designer.md +131 -169
  226. package/prompts/persona-engineering.md +142 -84
  227. package/prompts/persona-explore.md +1 -1
  228. package/prompts/persona-plan.md +5 -1
  229. package/prompts/subagent-base.md +2 -0
  230. package/provider/anthropic.mjs +6 -4
  231. package/provider/core.mjs +3 -2
  232. package/provider/errors.mjs +29 -4
  233. package/provider/google.mjs +24 -7
  234. package/provider/responses.mjs +3 -1
  235. package/provider-flows.mjs +2 -2
  236. package/session-index-build.mjs +1 -1
  237. package/session-index-pass.mjs +1 -1
  238. package/session-index-query.mjs +1 -1
  239. package/session-index.mjs +1 -1
  240. package/session-lifecycle.mjs +72 -17
  241. package/session-slot-write.mjs +37 -5
  242. package/session.mjs +24 -8
  243. package/skip-dirs.mjs +2 -2
  244. package/team-ledger.mjs +13 -9
  245. package/token-ttl.mjs +73 -4
  246. package/token-window.mjs +167 -33
  247. package/tool-docs/advisor.md +2 -27
  248. package/tool-docs/apply_patch.md +1 -15
  249. package/tool-docs/bash.md +2 -41
  250. package/tool-docs/batch-eng-coder.md +3 -0
  251. package/tool-docs/batch-eng-designer.md +3 -0
  252. package/tool-docs/batch-review.md +3 -0
  253. package/tool-docs/batch.md +2 -84
  254. package/tool-docs/browser.md +2 -49
  255. package/tool-docs/code_search.md +2 -2
  256. package/tool-docs/consult_start.md +2 -8
  257. package/tool-docs/consult_stop.md +2 -4
  258. package/tool-docs/context.md +1 -5
  259. package/tool-docs/delete.md +2 -17
  260. package/tool-docs/doc_check.md +2 -107
  261. package/tool-docs/doc_graph-read.md +3 -0
  262. package/tool-docs/doc_graph.md +3 -0
  263. package/tool-docs/doc_search.md +2 -4
  264. package/tool-docs/edit.md +1 -38
  265. package/tool-docs/eng.md +3 -1
  266. package/tool-docs/execute.md +2 -18
  267. package/tool-docs/fetch.md +2 -14
  268. package/tool-docs/file_ops.md +2 -18
  269. package/tool-docs/get_current_time.md +1 -6
  270. package/tool-docs/git-read.md +3 -0
  271. package/tool-docs/git.md +2 -35
  272. package/tool-docs/glob.md +2 -10
  273. package/tool-docs/goal.md +1 -6
  274. package/tool-docs/grep.md +2 -18
  275. package/tool-docs/hashline_edit.md +2 -15
  276. package/tool-docs/insert_after.md +2 -16
  277. package/tool-docs/instance_list.md +3 -0
  278. package/tool-docs/instance_send.md +3 -0
  279. package/tool-docs/knowledge.md +3 -0
  280. package/tool-docs/ledger-read.md +3 -0
  281. package/tool-docs/ledger.md +3 -8
  282. package/tool-docs/lint.md +2 -10
  283. package/tool-docs/ls.md +2 -11
  284. package/tool-docs/lsp.md +2 -9
  285. package/tool-docs/main_history.md +3 -1
  286. package/tool-docs/manifest-read.md +2 -8
  287. package/tool-docs/manifest.md +2 -35
  288. package/tool-docs/memory-read.md +3 -0
  289. package/tool-docs/memory.md +2 -20
  290. package/tool-docs/notify_parent.md +2 -13
  291. package/tool-docs/peer_instances.md +3 -1
  292. package/tool-docs/plan.md +1 -5
  293. package/tool-docs/process-read.md +3 -0
  294. package/tool-docs/process.md +2 -13
  295. package/tool-docs/question.md +3 -17
  296. package/tool-docs/read.md +2 -19
  297. package/tool-docs/read_history-batch.md +3 -0
  298. package/tool-docs/read_history.md +2 -18
  299. package/tool-docs/read_image.md +2 -9
  300. package/tool-docs/recent_changes.md +2 -2
  301. package/tool-docs/repo_outline.md +2 -2
  302. package/tool-docs/settings-read.md +3 -0
  303. package/tool-docs/settings.md +1 -12
  304. package/tool-docs/skill.md +2 -6
  305. package/tool-docs/ssh.md +1 -62
  306. package/tool-docs/subagent.md +2 -100
  307. package/tool-docs/task.md +1 -7
  308. package/tool-docs/team_ledger-read.md +3 -0
  309. package/tool-docs/team_ledger.md +3 -9
  310. package/tool-docs/timer.md +2 -19
  311. package/tool-docs/tree.md +2 -13
  312. package/tool-docs/verify.md +2 -12
  313. package/tool-docs/wait_for.md +2 -32
  314. package/tool-docs/websearch.md +2 -19
  315. package/tool-docs/write.md +2 -12
  316. package/tools/browser.mjs +52 -7
  317. package/tools/doc-write-gate.mjs +73 -0
  318. package/tools/edit-batch.mjs +170 -92
  319. package/tools/edit-diff.mjs +78 -62
  320. package/tools/edit-receipt.mjs +39 -0
  321. package/tools/execute.mjs +1 -1
  322. package/tools/file.mjs +16 -8
  323. package/tools/git.mjs +24 -9
  324. package/tools/index.mjs +6 -0
  325. package/tools/knowledge.mjs +143 -0
  326. package/tools/linter.mjs +3 -3
  327. package/tools/ops.mjs +3 -1
  328. package/tools/patch.mjs +123 -43
  329. package/tools/shared.mjs +28 -27
  330. package/tools/write-gate-params.mjs +31 -0
  331. package/tools/write-path.mjs +16 -4
  332. package/window-policy.mjs +203 -0
  333. package/doc-check/anchors.mjs +0 -235
@@ -1,21 +1,26 @@
1
1
  /**
2
- * agent-tools/batch.mjs — 批次档生命周期工具(KD-4 拆分主档:action 分发 + append 迁移面 +
3
- * 路径解析单源 + #84 记账缝)。
2
+ * agent-tools/batch.mjs — 批次档生命周期工具(KD-4 拆分主档:**action 分发 + schema + 路径解析面 +
3
+ * 评审实例绑定 + #84 记账缝**)。
4
4
  *
5
- * 单工具 `batch`,action = create(建档,§4.11)/ append(段写入——原 batch-segment.mjs 语义
6
- * 逐字迁移,§4.1 全表)/ edit(段内就地改——锚定区间替换,§4.19)/ status(段属主状态行流转,
7
- * §4.12)/ close(收口冻结,§4.13)。写入面**按段分权、不按段分处置**:六段各自只有一个作者,
8
- * 作者对本段可 append 加内容 ∥ edit 就地改既有行(§4.19);状态行只有一个写者(status)。
5
+ * 单工具 `batch`,action = create(建档,§4.11)/ attach(给现役档补挂台账行,§4.21.3)/ append(段写入)/ edit
6
+ * (段内就地改,§4.19)/ status(段属主状态行流转,§4.12)/ close(收口冻结,§4.13)/ supersede
7
+ * (被取代的收口,§4.18-D——对象已消失、永不实施、且能点名取代者的批档)。写入面**按段分权、不按段分处置**:
8
+ * 六段各自只有一个作者,作者对本段可 append 加内容 ∥ edit 就地改既有行(§4.19);状态行只有一个写者(status)。
9
9
  * 权威规格 = `docs/core/design/BATCH-RECORD.md` §4(契约/挂载/用例 §4.8/骨架 §4.10/
10
- * 参数面 §4.11–§4.13);骨架与判定字面单源 = `batch-skeleton.mjs`;lifecycle 面 =
11
- * `batch-lifecycle.mjs`。**依赖单向(KD-4):skeleton ← lifecycle ← 主档**。
10
+ * 参数面 §4.11–§4.13 · §4.21)。
11
+ *
12
+ * 2026-11-05 拆档族把**段写入执行面**(append ∥ edit 的执行体、共用助手与八条拒串)搬进
13
+ * `batch-record-write.mjs`——本档只留模型可见的 schema 与分发(改 schema 不该翻过 300 行执行体)。
14
+ * 其余依赖单向:`batch-segment-vocab ← batch-skeleton ← …(gate ∥ closeout ∥ reopen ∥ lifecycle ∥
15
+ * record-write)← 本档`。
12
16
  *
13
17
  * 身份判据(D-BR17/D-BR18/D-BR21):主 agent 调用 ctx 带 `depth === 0`(dispatch 装配);
14
18
  * eng 子代理 `depth > 0`(`agent._role` 定段);评审实例 ctx 无 depth 但工具以 `review: true`
15
- * 绑定。create/close 仅 depth-0 放行;depth-0 的 append/status/close 可选 `path`(D-BR21:
19
+ * 绑定。create/close/attach 仅 depth-0 放行;depth-0 的 append/status/close/attach 可选 `path`(D-BR21:
16
20
  * 缺省 = findInFlightBatch 取唯一在飞批,0/复数 ⇒ throw);子代理/评审传 path ⇒ 拒(目标 =
17
21
  * spawn/实例注入,语法上写不到别处——运行期门拒)。append 段白名单(**模式感知**——§4.16):
18
- * depth-0 → 工程 §1/§4/§6 ∥ 普通 §1/§2/§4/§5/§6 · eng-designer → §2 · 评审 → §3 · eng-coder → §5 ·
22
+ * depth-0 → 工程 §1/§4/§6 ∥ 普通 §1/§2/§4/§5/§6 · eng-designer → §2 · 评审 → §3(**工程设计轨除外**——那一路的
23
+ * `§3` 只由结算写,§4.4)· eng-coder → §5 ·
19
24
  * coder(普通模式分支增表——SEGMENT_BY_ROLE_NORMAL)→ §5;status 写域 = 调用者自己段(模式感知
20
25
  * ——见 batch-lifecycle.mjs)。**edit 的段域 = 同模式 append 白名单**(§4.19「段域」行——一张表两
21
26
  * 个动作,不另立第二张):能 append 哪段就 edit 哪段,两动作只差写法(段尾加内容 ∥ 段内改既有字)。
@@ -23,37 +28,26 @@
23
28
  * "batch_segment:" 前缀**(§4.1 全表锚断言);"batch:" 前缀 = 新增错误面(create/close/status/
24
29
  * edit 锚判据/findInFlight/path 门/dispatch)。
25
30
  *
26
- * 导出面:`batchTool`(主名)· `resolveBatchDocPath` · `batchDocBases` · `batchDocForReview` ·
27
- * `configureBatchSegment` / `resetBatchSegment`(#84 记账缝——契约名不变,AC-11 零改)·
28
- * `MAX_TEXT_CHARS` · `SEGMENT_BY_ROLE`。
31
+ * 导出面(名与形逐字不变——2026-11-05 拆档族后仍由本档出):`batchTool`(主名)· `resolveBatchDocPath` ·
32
+ * `batchDocBases` · `batchDocForReview` · `configureBatchSegment` / `resetBatchSegment`(#84 记账缝——
33
+ * 契约名不变,AC-11 零改)· `MAX_TEXT_CHARS`(经 `batch-record-write.mjs` re-export)· `SEGMENT_BY_ROLE`。
29
34
  *
30
35
  * #84 记账面(CORE-UNIFICATION §2.13.4):写入成功后的记账**按端注入**——核内缺省 no-op = CLI
31
36
  * 语义零行为变;端装配经 `configureBatchSegment({ onWrite })` 覆盖(VSC 侧现形 = `_touchedFiles`
32
- * 记账)。核内零端名分支(契约 5——只认 `onWrite` 函数名)。
37
+ * 记账)。核内零端名分支(契约 5——只认 `onWrite` 函数名)。**缝住本档**:它唯一的读者是下面
38
+ * `batchTool.execute`(取值后经 `onWritten` 形参递给五条 action)——缝与读者同档,执行体侧只收形参。
33
39
  */
34
- import { readFileSync, writeFileSync } from "node:fs"
35
-
36
40
  // 描述面 = `tool-docs/batch.md`(#15 描述外置统一——工厂形描述经 DESC 单一解析面,工厂调用期取值)
37
41
  import { DESC } from "../tools/shared.mjs"
38
- import { SEGMENT_BY_ROLE, SEGMENT_BY_ROLE_NORMAL, DEPTH0_SEGMENTS, readBatchStatusLine, sectionHeaderRe, STATUS_LINE_RE, findPlaceholderResidue, placeholderResidueError, ROUND_HEADING_RE, nextRoundNumber, statusResetPlan, statusPassPlan, updateSectionStatusLine, verdictGapOf } from "./batch-skeleton.mjs"
42
+ import { SEGMENT_BY_ROLE } from "./batch-skeleton.mjs"
39
43
  import { batchDocBases, resolveBatchDocPath } from "./batch-paths.mjs"
40
- import { gateReceiptLine, gateRefusalMessage, runBatchGate } from "./batch-gate.mjs"
41
- import { assertSectionFiveGate } from "./batch-closeout.mjs"
42
- import { createBatchRecord } from "./batch-ledger-bind.mjs"
43
- import { closeBatchRecord, findInFlightBatch, statusBatchRecord } from "./batch-lifecycle.mjs"
44
- // 日期戳单源(`todayLocal`——重开 §1 状态行与本节留痕行同一枚,日期口径只一处)。
45
- import { todayLocal } from "./batch-reopen.mjs"
44
+ import { createBatchRecord, attachBatchRecord } from "./batch-ledger-bind.mjs"
45
+ import { checkBatchRecord, closeBatchRecord, findInFlightBatch, statusBatchRecord } from "./batch-lifecycle.mjs"
46
+ import { supersedeBatchRecord } from "./batch-supersede.mjs"
47
+ import { appendBatchRecord, editBatchRecord } from "./batch-record-write.mjs"
46
48
 
47
49
  export { SEGMENT_BY_ROLE, batchDocBases, resolveBatchDocPath }
48
-
49
- /** text 单次上限(BATCH-RECORD.md §4.1——超出引导分段追加,不承诺"不新盖戳")。append 迁移域私有区常量
50
- * (随执行体自 batch-segment.mjs 迁入——骨架档只住骨架/状态行单源,lifecycle 档头枚举口径)。 */
51
- export const MAX_TEXT_CHARS = 20000
52
- /** 凭证形态(`BATCH-RECORD.md` §4.1——三形):`[DESIGN-TOKEN:…]` 闭括号形 ∥ `designId: …` 键形 ∥ 无标两段
53
- * token 值形 `⟨uuid⟩:⟨epoch⟩`(与单源 `design-token.mjs` 判据对表);裸 uuid 非凭证不剥(KD-7)。两字面勿
54
- * 合并:`CRED_RE` 走 `.replace()` 须 `/g` ∥ `CRED_TEST_RE` 逐行 `.test()` 须非 `/g`(lastIndex 有状态会漏剥)。 */
55
- const CRED_RE = /\[DESIGN-TOKEN:[^\]]*\]|designId\s*:\s*\S+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}:\d{10,16}/g
56
- const CRED_TEST_RE = /\[DESIGN-TOKEN:[^\]]*\]|designId\s*:\s*\S+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}:\d{10,16}/
50
+ export { MAX_TEXT_CHARS } from "./batch-record-write.mjs"
57
51
 
58
52
  // ─── #84 记账面注入缝(「记账面按端注入」,形态参 §2.13.5 注入缝)───────────────
59
53
  /**
@@ -77,429 +71,172 @@ export function resetBatchSegment() { injectedOnWrite = null }
77
71
  */
78
72
 
79
73
  /**
80
- * 设计评审的实例绑定解析(BATCH-RECORD.md §4.2/§4.3——评审实例的唯一路径来源):
81
- * - 同步路径:调用方(advisor 工具)把实例绑定显式放进 callbacks(**带 batchDoc 键**,
82
- * 未绑定即 null)——以此为准,不再回看池条目(防同步/异步混跑时串档);
83
- * - 异步路径:本评审所在**池条目**的 `run.batchDoc`(文档集 = 实例键,各评审各取各条)。
74
+ * 评审侧批次档绑定解析(BATCH-RECORD.md §4.2/§4.3——评审实例的唯一路径来源):
75
+ * 单源 = 调用方把**本笔**绑定显式放进 callbacks(**带 batchDoc 键**,未绑定即 null)——
76
+ * 同步路径来自 advisor 工具,异步路径来自池条目的 `entry.start()`(条目持发起时点的快照)。
77
+ * 缺键 ⇒ null(fail-closed)。
78
+ * 池扫兜底已退役:按文档集去池里认条目是同一判据的第二份、且更弱的表述(只认设计轨);
79
+ * 代码轨 `documents` 为 null ⇒ `[]` 会匹配到无 documents 的条目,等于另开一个错档入口。
80
+ * `agent` / `documents` 形参保留为签名兼容(调用方按位置传参),本函数不再消费。
84
81
  */
85
82
  export function batchDocForReview(agent, documents, callbacks = null) {
86
83
  if (callbacks && "batchDoc" in callbacks) return callbacks.batchDoc ?? null
87
- const key = JSON.stringify([...(documents ?? [])].sort())
88
- for (const e of agent?._asyncAdvisors?.values?.() ?? []) {
89
- if (e.status === "running" && e.reviewType === "design" && JSON.stringify([...(e.documents ?? [])].sort()) === key) {
90
- return e.run?.batchDoc ?? null
91
- }
92
- }
93
84
  return null
94
85
  }
95
86
 
96
- // ─── append 迁移面(原 batch-segment.mjs :129-184 私有区——逐字迁移,错误串逐字保序)───
97
-
98
- /** 段号解析:`§2` / `2` / `§2 批次任务` 均可;无法解析 → null。 */
99
- function segmentNumber(raw) {
100
- const m = /^§?\s*(\d+)/.exec(String(raw ?? "").trim())
101
- return m ? Number(m[1]) : null
102
- }
103
-
104
- /** 身份 → 可写段号;无写权身份 → null。评审实例绑定优先(评审者的身份即"设计评审"。)
105
- * depth-0 的段白名单(append——模式感知,§4.16)由 appendBatchRecord 分支,不经本表;
106
- * 普通模式分支额外合并 coder 增表(`SEGMENT_BY_ROLE_NORMAL`——**合并查只在普通模式分支**)。 */
107
- function allowedSegment(agent, review, engineering) {
108
- if (review) return 3
109
- const role = agent?._role
110
- return SEGMENT_BY_ROLE[role] ?? (engineering ? null : SEGMENT_BY_ROLE_NORMAL[role]) ?? null
111
- }
112
-
113
- /** 无写权身份拒串(`append` 与 `edit` 共用一条——两动作读同一张段白名单,同一件事不各写一份串)。 */
114
- function noSegmentError(engineering) {
115
- return engineering
116
- ? "batch_segment: no segment is writable by this caller — the channel exists for eng-designer (§2), eng-coder (§5) and design reviews bound to a batch record (§3); the parent agent writes §1/§4/§6 through ordinary document writes."
117
- : "batch_segment: no segment is writable by this caller — the channel exists for eng-designer (§2), eng-coder (§5) and design reviews bound to a batch record (§3); in normal mode the parent agent writes §1/§2/§4/§5/§6 through ordinary document writes."
118
- }
119
-
120
87
  /**
121
- * 凭证剥除 + 伪造轮次标题丢弃(BATCH-RECORD.md §4.1 F6/AC30/AC34)。
122
- * 逐行处理:含凭证形态的行 → 剥除该子串,剥后为空则整行丢弃(其余内容逐字保留)。
123
- * `dropStamp`(仅 §3 目标段):调用方自带的 `### 轮次 N(评审子代理)` 行被丢弃——
124
- * 工具生成才是唯一来源戳(否则伪造戳会污染 N 计数)。
88
+ * 身份 profile(TOOLS.md §6.29 ②):depth-0 = 全量六动作;子代理与评审 = 自己那一段的
89
+ * append / edit / status(段域仍由既有身份白名单裁决,本档只裁**动作面与参数面**)。
90
+ * 描述取各自一份档——全量档 `batch.md` 通篇讲六个动作,子代理读到它就是读到做不到的事(B6)。
125
91
  */
126
- function sanitizeText(text, dropStamp) {
127
- const kept = []
128
- for (const line of text.replace(/\r\n?/g, "\n").split("\n")) {
129
- if (dropStamp && ROUND_HEADING_RE.test(line)) continue
130
- if (!CRED_TEST_RE.test(line)) { kept.push(line); continue }
131
- const cleaned = line.replace(CRED_RE, "").replace(/[ \t]+$/, "")
132
- if (cleaned.trim()) kept.push(cleaned)
133
- }
134
- return kept.join("\n")
135
- }
136
-
137
- /** 段尾定位 + 插入(append-only:只在段尾插入,既有字节不变;返回新全文 + 本轮 N)。
138
- * `blockLead`(仅 §3——打回重置的留痕行):落在**工具戳标题之后、评审正文之前**——与
139
- * `### 轮次 N(评审子代理)` 同属工具戳面,append-only 不变。
140
- */
141
- function insertIntoSection(src, seg, text, blockLead = "") {
142
- const hdr = sectionHeaderRe(seg).exec(src)
143
- if (!hdr) throw new Error(missingSectionError(seg))
144
- const nextRe = /^## §\d/gm
145
- nextRe.lastIndex = hdr.index + hdr[0].length
146
- const next = nextRe.exec(src)
147
- const endIdx = next ? next.index : src.length
148
- // 来源戳(仅 §3):工具生成标题 + N——调用方写不进自己的标题(sanitize 已丢弃同名行)。
149
- // N 的单源 = `nextRoundNumber`(= `countRoundBlocks + 1`)——留痕行的「第 N 轮」同取这一枚。
150
- const roundN = seg === 3 ? nextRoundNumber(src, 3) : 0
151
- const stamp = seg === 3 ? `### 轮次 ${roundN}(评审子代理)\n\n` + (blockLead ? `${blockLead}\n\n` : "") : ""
152
- const payload = stamp + text
153
- const before = src.slice(0, endIdx)
154
- const after = src.slice(endIdx)
155
- const eol = src.includes("\r\n") ? "\r\n" : "\n"
156
- const lead = before === "" ? "" : before.endsWith(eol + eol) ? "" : before.endsWith(eol) ? eol : eol + eol
157
- // 尾随 eol 恒加(块自成行);后面还有段标题时再补一个空行(保持模板的空行分隔)。
158
- const written = before + lead + payload.replaceAll("\n", eol) + eol + (after === "" ? "" : eol) + after
159
- return { written, roundN }
160
- }
161
-
162
- /**
163
- * append 执行体(action=append——原 batch_segment execute 迁移 + depth-0 分支):
164
- * - 段白名单(**模式感知**——§4.16):depth-0 工程 → §1/§4/§6(新错误面,"batch:" 前缀)∥
165
- * depth-0 普通 → §1/§2/§4/§5/§6(模式化新串);eng-designer → §2 · 评审 → §3 ·
166
- * eng-coder → §5 · coder(普通模式分支增表)→ §5(迁移错误面,"batch_segment:" 前缀**逐字保持**);
167
- * - 目标定位(D-BR21):depth-0 path 可选(缺省 = findInFlightBatch 唯一在飞批);子代理/评审
168
- * 传 path ⇒ 拒,目标 = spawn/实例绑定;
169
- * - 其余(gate / text 校验 / 剥凭证 / 骨架保护 / **死占位机检(F11-C)** / **文档机检门(§3.20 结构兜底 ①——
170
- * **全部 append 同挂**(含 depth-0 与评审写 §3):本次写入文本的命中 ⇒ 拒写,ERROR ⇒ 写 + 回执明示;
171
- * 批档已落段命中只入回执)** / 插入 / 记账 / 回执)逐字保持原语义。
172
- */
173
- function appendBatchRecord({ args, ctx, review, batchDoc, onWritten }) {
174
- const agent = ctx?.agent ?? {}
175
- const cwd = agent.cwd
176
- const depth0 = ctx?.depth === 0
177
- // 模式位执行期实读(§4.16——同款先例 = task.mjs execute 门;翻转即时生效——D-BR26)
178
- const engineering = !!agent?.config?.agent?.engineering
179
- const seg = allowedSegment(agent, review, engineering)
180
- if (!depth0 && seg === null) throw new Error(noSegmentError(engineering))
181
- const n = segmentNumber(args?.segment)
182
- if (n === null) {
183
- if (depth0) {
184
- throw new Error(engineering
185
- ? `batch: unknown segment ${JSON.stringify(args?.segment ?? null)} — depth-0 append writes §1/§4/§6 of the in-flight record (pass the section number you write, e.g. "§4").`
186
- : `batch: unknown segment ${JSON.stringify(args?.segment ?? null)} — in normal mode depth-0 append writes §1/§2/§4/§5/§6 of the in-flight record (pass the section number you write, e.g. "§4").`)
187
- }
188
- throw new Error(`batch_segment: unknown segment ${JSON.stringify(args?.segment ?? null)} — pass the section number you write (e.g. "§${seg}").`)
189
- }
190
- if (depth0) {
191
- const domain = engineering ? DEPTH0_SEGMENTS.append.engineering : DEPTH0_SEGMENTS.append.normal
192
- if (!domain.includes(n)) {
193
- throw new Error(engineering
194
- ? `batch: §${n} is not yours to write — depth-0 append writes §1/§4/§6 only (一段一作者: §2 = eng-designer, §3 = design review, §5 = eng-coder).`
195
- : `batch: §${n} is not yours to write — in normal mode depth-0 append writes §1/§2/§4/§5/§6 (一段一作者: §3 = design review only). Nothing was written.`)
196
- }
197
- } else if (n !== seg) {
198
- throw new Error(`batch_segment: §${n} is not yours to write — this caller writes §${seg} only (一段一作者: eng-designer → §2, design review → §3, eng-coder → §5).`)
199
- }
200
- // 目标定位(D-BR21)——path 拒面先于绑定解析(与 status 同序:段白名单 → path 门 → 取值)。
201
- const givenPath = typeof args?.path === "string" && args.path.trim() ? args.path : null
202
- let abs
203
- if (givenPath) {
204
- if (!depth0) {
205
- throw new Error("batch: path is a depth-0-only parameter (D-BR21) — your target record arrives via the spawn binding / the review instance key. Nothing was written.")
206
- }
207
- abs = resolveBatchDocPath(cwd, givenPath)
208
- } else if (depth0) {
209
- abs = findInFlightBatch(cwd, batchDocBases(cwd)) // 歧义锚 ⇒ 基底 = 候选并集(#828——唯一在飞批照取 / ≥2 照列)
210
- } else {
211
- if (!batchDoc) {
212
- throw new Error("batch_segment: no batch record is bound to this caller — there is no path parameter by design (the target arrives via the spawn binding / the review instance key). Report the section as not written.")
213
- }
214
- abs = resolveBatchDocPath(cwd, batchDoc)
215
- }
216
- const src = readFileSync(abs, "utf8")
217
- const status = readBatchStatusLine(src)
218
- if (status === "closed") throw new Error(FROZEN_RECORD_ERROR)
219
- if (status === "unknown") throw new Error(UNRESOLVED_STATUS_ERROR)
220
- if (typeof args?.text !== "string") {
221
- throw new Error("batch_segment: text must be a string (the markdown to append).")
222
- }
223
- if (args.text.length > MAX_TEXT_CHARS) {
224
- throw new Error(`batch_segment: text is ${args.text.length} characters — the limit is ${MAX_TEXT_CHARS} per call. Split it into multiple calls: each call becomes its own section and the round number N continues (分段追加——每次调用各成节、N 顺延).`)
225
- }
226
- if (/^## §\d/m.test(args.text)) throw new Error(SKELETON_GUARD_ERROR)
227
- const body = sanitizeText(args.text, n === 3).replace(/^\n+/, "").replace(/\s+$/, "")
228
- if (!body.trim()) {
229
- throw new Error("batch_segment: nothing to append — the text is empty after credential stripping (credential values never reach the record).")
230
- }
231
- // F11-C(挂点:gate / text 校验后 · insertIntoSection 前):档头结构行死占位残留 ⇒ 拒
232
- // (段体引用豁免——判据可辨性收正,`TOOLS.md` §6.20;骨架枚举单源 = skeleton 档 TEMPLATE_PLACEHOLDERS)。
233
- const residues = findPlaceholderResidue(src)
234
- if (residues.length) throw new Error(placeholderResidueError(residues))
235
- // §5 写入门(段序门 · 设计档 §2.6 `R-G2`):实现发生在评审通过之后,序在这里判得出真假;这一门没有旁路
236
- // (`§1` 声明 §3 不适用已随声明机制退役)。
237
- if (n === 5) assertSectionFiveGate(src)
238
- // §3 写入闸(设计档 `BATCH-LEDGER-REVIEW-UNIFY.md` §2.6.1 `R-G3`——裁定行在写的时刻就要在):
239
- // 能写 §3 的只有绑本档的评审实例,它结算后即离场 ⇒ 把错误退回**还有权补那一行的人在场的那一刻**。
240
- // 判定输入 = 净化后正文 `body`(落档的就是它;每笔 §3 自成一块 ⇒ 「写前正文 ≡ 写后末块」只对 body 成立);
241
- // 判据单源 = 骨架档 `verdictGapOf`(与 §5 门判据 2 ∥ 签发面同一个函数)。
242
- // 放行面 = **只拒两格**(`无裁定行` ∥ `两者同携`):判打回的一笔(`VERDICT: changes-required` ∥ `结论:不通过`)
243
- // 照写——§5 门判据 2 与打回重置都靠那一块自带打回裁定;拦它 = 把打回这条业务路堵死。
244
- // 位次 = 既有拒因之后、文档机检门之前(拒 = 零字节落盘、轮次号不消耗——N 在 insertIntoSection 时才取)。
245
- if (n === 3) {
246
- const gap = verdictGapOf(body)
247
- if (gap === "无裁定行" || gap === "两者同携") throw new Error(SECTION3_VERDICT_GAP_ERROR)
248
- }
249
- // 文档机检门(§3.20「结构兜底」①——门位 = 既有拒因全部之后、insertIntoSection / 写盘之前):
250
- // **全部 append 同挂**(§1–§6,含 depth-0 与评审写 §3——规则一条,不按身份分支);
251
- // 强制集 = 本次写入文本 ∪ 写者触达账,批档已落段命中只入回执(不阻本次写)。
252
- // `pending` = 本次段号与正文:门据此落同目录片段档判「你手里这段」,判法与批档本体逐字同源。
253
- // REFUSED ⇒ throw(零字节落盘);PASS ⇒ 照写;ERROR / 门自身异常 ⇒ 写 + 回执明示。
254
- const gate = runBatchGate({ abs, cwd, agent, scope: "writer", pending: { section: n, body } })
255
- if (gate?.state === "refused") throw new Error(gateRefusalMessage(gate, "append"))
256
- // 裁定行 → 状态行(BLRU §2.5——**工具被动写**,两个方向共用同一处判定与同一条写入路径):
257
- // 打回即重置(三合取:本笔写 §3 ∧ 本笔命中打回裁定行 ∧ 写前 §3 状态行 = 评审通过)⇒ 本轮块首留痕行
258
- // (随 `blockLead` 进插入)+ 状态行重置;通过即置位(本笔写 §3 ∧ 本笔命中 pass 裁定行且不命中打回行 ∧
259
- // 写前 §3 状态行 ≠ 评审通过)⇒ 状态行置成评审通过,无留痕行(块本身即记录)。
260
- // 两条靠各自的三合取天然互斥;`??` 的左先右后与签发面 `verdictGateFailure` 同序(先打回、后 pass)。
261
- // 状态行仍**只经 `updateSectionStatusLine` 这一个写入函数**改写(不新开第二条写路径);仍是
262
- // 一次 `writeFileSync`——块与字进的是同一个字符串(无「块已落、字未到」的窗口)。
263
- // 留痕行不经文档机检门——门位在上面(判集 = 本次评审正文 `pending.body`)。
264
- const date = todayLocal()
265
- const plan = statusResetPlan(src, n, body, date) ?? statusPassPlan(src, n, body, date)
266
- const { written: inserted, roundN } = insertIntoSection(src, n, body, plan?.traceLine ?? "")
267
- const written = plan ? updateSectionStatusLine(inserted, 3, plan.statusValue) : inserted
268
- writeFileSync(abs, written)
269
- // #84:记账面按端注入(缺省 no-op = CLI 语义零行为变——端装配经 configureBatchSegment 覆盖)。
270
- onWritten?.(agent, abs)
271
- return `batch_segment: appended ${body.length} characters to §${n} of the batch record${roundN ? ` (### 轮次 ${roundN}(评审子代理))` : ""}.${gateReceiptLine(gate)}`
272
- }
273
-
274
- // ─── 拒串单源(append / edit 共用——两动作只差写法,不差判据)───────────────
275
-
276
- /** 拒串:`§3` 写入闸(`R-G3` 逐字 = `docs/core/design/BATCH-LEDGER-REVIEW-UNIFY.md` §2.6.1)——一笔 `§3` 追加读成
277
- * 「无裁定行」∥「两者同携」⇒ 拒写(零字节落盘、轮次号不消耗)。两个裁定词**内联在同一句里,不各占独立一行**:
278
- * 各占一行时这段拒文自己就读成「两者同携」,把拒文原样引用并另写一行裁定的一笔仍被拒——想解释这道闸的人恰被
279
- * 它挡在门外;缩进 ∥ 列表符同样不取(照抄的行不命中整行锚 ⇒ 补的那行永不生效)。混形反例与「不消耗轮次号」照留。 */
280
- const SECTION3_VERDICT_GAP_ERROR = "batch_segment: §3 append refused — this round block states no readable verdict (块内裁定 = 无裁定行 | 两者同携). A §3 block must carry exactly one verdict as a line of its own; put exactly one of `VERDICT: pass` ∥ `VERDICT: changes-required` on such a line in the text you append — copying this refusal verbatim copies the words, not a verdict line.\n(本地化整行形 `结论:通过` / `结论:不通过` 同认,中文形的尾句号可省可带(`结论:通过。` 同认)。不作独立整行的写法不认——例如 `**结论** = VERDICT: pass`。) Nothing was written — no bytes landed and no round number was consumed: append the same text again with the verdict line added."
281
- /** 拒串:已收口档(§4.9 门 ②——append / edit / status 共用一条,串逐字含「已收口档不回改」)。 */
282
- const FROZEN_RECORD_ERROR = "batch_segment: 已收口档不回改 — the bound batch record's §1 status line contains 「已收口」, so the record is frozen: its body is never written to again (整档冻结;改 = 新批新档). Nothing was written. Report the section as not written."
283
- /** 拒串:§1 状态行不可解析或缺失(fail-closed 视为冻结——与冻结门同一条解析器)。 */
284
- const UNRESOLVED_STATUS_ERROR = "batch_segment: 状态行不可解析或缺失 — the bound batch record has no §1 `**状态行**:` line inside the section header zone whose value contains 已收口 or 进行中 (fail-closed: the write is refused as if frozen). If the record does carry such a line further down — in a round block or in the section body — move it up under `## §1`: a status line outside the header zone is never read. Nothing was written. Do NOT close the record after a refused append — nothing landed, and closing freezes the missing section for good (失败 ⇒ 勿 close)."
285
- /** 拒串:段标题缺失(create 是骨架唯一权威入口,append / edit 都不补骨架)。 */
286
- const missingSectionError = (seg) => `batch_segment: the bound batch record has no "## §${seg}" section header — the six-section skeleton is written by the record's creator before any segment write. Fix: ask the parent/creator to add the "## §${seg} …" heading (with the template's sub-headings) first, then call batch_segment again. Nothing was written.`
287
- /** 拒串:骨架保护(写入文本 ∥ 替换文本含 `## §N` 段头形态 ⇒ 段定位失效——append / edit 共用)。
288
- * 两个动作都不许把段头写进段体:段定位靠 `## §N` 标题,写进去就把定位面改掉(§4.1 fail-closed 行)。 */
289
- const SKELETON_GUARD_ERROR = "batch_segment: the text contains a section header line matching `^## §N` — that would break section location. Rewrite it (escape the heading, or drop the leading `## §N`), then call again (骨架保护). Nothing was written. Do NOT close the record after a refused append — nothing landed, and closing freezes the missing section for good (失败 ⇒ 勿 close)."
290
- /** 拒串:edit 的锚 / 替换触及或引入 `**状态行**:` 行(§4.19 锚判据;逐字 = `TOOLS.md` §6.24 ⑤ E5)。 */
291
- const EDIT_STATUS_LINE_ERROR = "batch: edit would rewrite or introduce a **状态行** line — that line has exactly one writer: status, with a value from the section's word list. Nothing was written."
292
- /** 拒串:edit 空锚(E1——空锚的命中计数不会 ≥2,按「恰一次」会放行并插在段首)。 */
293
- const EDIT_BLANK_ANCHOR_ERROR = "batch: edit needs a non-empty oldText — a blank anchor cannot match exactly once. Nothing was written."
294
- /** 拒串:edit 的 newText 缺参 / 非串(`type: string` 的 fail-closed 面——缺参若当空串处理就是静默删区间)。 */
295
- const EDIT_NO_TEXT_ERROR = "batch: newText must be a string — pass an empty string to delete the anchored range. Nothing was written."
296
-
297
- // ─── edit 面(段内就地改:`BATCH-RECORD.md` §4.19 的代码单源)─────────────────────
298
-
299
- /** 段体**字符区间**(`## §N` 标题行的行尾之后 → 下一 `## §N` 段头之前;段头缺失 ⇒ null)。
300
- * 段定位判据与 `batch-skeleton.mjs` 同源(`sectionHeaderRe` + `/^## §\d/gm`)——本档只取**偏移**。
301
- * 区间函数住这里而不进骨架档:骨架档贴 500 软线,本批不带出助手函数(分批记录 2.4 贴线判)。 */
302
- function sectionBodySpan(src, seg) {
303
- const hdr = sectionHeaderRe(seg).exec(src)
304
- if (!hdr) return null
305
- const nextRe = /^## §\d/gm
306
- nextRe.lastIndex = hdr.index + hdr[0].length
307
- const next = nextRe.exec(src)
308
- const end = next ? next.index : src.length
309
- const nl = src.indexOf("\n", hdr.index) // 段头行余文(`## §N …` 的标题部分)不入段体
310
- return { start: nl < 0 || nl + 1 > end ? end : nl + 1, end }
311
- }
312
-
313
- /** 段体内每条 `**状态行**:` 行的字符区间(相对段体起点)——「状态行只有一个写者」的判定面(E5)。 */
314
- function statusLineSpans(body) {
315
- const out = []
316
- let at = 0
317
- for (const line of body.split("\n")) {
318
- if (STATUS_LINE_RE.test(line)) out.push([at, at + line.length])
319
- at += line.length + 1
92
+ const PROFILE_ACTIONS = ["append", "edit", "status"]
93
+ const PROFILE_SEGMENTS = { "eng-designer": 2, "eng-coder": 5, coder: 5, review: 3 }
94
+ const PROFILE_DOCS = { "eng-designer": "batch-eng-designer", "eng-coder": "batch-eng-coder", coder: "batch-eng-coder", review: "batch-review" }
95
+ /** profile 面保留的参数(其余参数只服务 create / attach / close / path,profile 执行不到 ⇒ 不出现)。 */
96
+ const PROFILE_PROPS = ["segment", "text", "oldText", "newText", "value", "note"]
97
+ /** profile 面的 `segment` 参数(只点名自己那段——全量档那句把六个身份的白名单一起列出来,
98
+ * 子代理读到的是别的身份的写域)。 */
99
+ function profileSegmentProp(profileKey) {
100
+ const seg = PROFILE_SEGMENTS[profileKey]
101
+ return {
102
+ type: "string",
103
+ description: `append/edit/status only — the batch-record section you are writing: §${seg} is your pen on this record (e.g. "§${seg}"). Declares the section number only; the identity bound to this spawn decides what is actually writable.`,
320
104
  }
321
- return out
322
105
  }
323
106
 
324
- /**
325
- * edit 执行体(action=edit——作者对自己那一段的**受认可通道**,不是唯一通道;判据单源 = `docs/core/design/BATCH-RECORD.md` §4.19):
326
- * 锚定区间替换——`oldText` 在**目标段段体**内恰一次命中(逐字节,含行尾)⇒ 换为 `newText`;`newText` 空串 = 删区间。
327
- * 判定与写盘**全部复用既有面**(零新写盘路径):段域 = 同模式 append 白名单(§4.1 一处单源,一张表两个动作)· path 门(D-BR21)·
328
- * 冻结拒写(§4.9 门 ②,串与 append 逐字同)· 剥凭证(同一条 `sanitizeText`;§3 另丢伪造轮次戳——§4.7 不变量 5)· 骨架保护 ·
329
- * 文档机检门(**判集两类**:段长类判 `newText`、锚类判整档——§4.9 门 ④)· `onWrite` 记账 · 一次 `writeFileSync`。
330
- * **不跑 §5 段序门**(§4.19「段序门」行:edit 须有既有锚 ⇒ 写不出原本不存在的内容,造不出「先实施」;
331
- * 反过来在 §3 进行中时拒掉 §5 的旧行,正是本批要消的那种死锁)。
332
- * **不做整段替换**(段体实测两成超 `MAX_TEXT_CHARS`——重发全文 = 静默丢内容)∥ **不做模糊匹配**(一次近似改写 = 一次
333
- * 没人看见的错改;匹配 = 逐字节,`\r\n` 档上的 LF 锚零命中 ⇒ 拒,安全方向)。
334
- * 拒面(全 fail-closed,零字节落盘):空锚 E1 · 零命中 E2 · ≥2 命中(列命中行号)E3 · 锚越段界 E4 · 锚或替换触及 / 引入
335
- * `**状态行**:` 行 E5 · 骨架保护 ∥ 冻结 ∥ 段域 ∥ newText 缺参(E6 族)。
336
- */
337
- function editBatchRecord({ args, ctx, review, batchDoc, onWritten }) {
338
- const agent = ctx?.agent ?? {}
339
- const cwd = agent.cwd
340
- const depth0 = ctx?.depth === 0
341
- const engineering = !!agent?.config?.agent?.engineering
342
- // 段域(§4.19「段域」行):**= 同模式 append 白名单**——能 append 哪段就 edit 哪段,段域一处单源、一张表两个动作。
343
- // 子代理侧取身份段(§4.1:身份 → 段);depth-0 侧取同模式 append 白名单(工程 §1/§4/§6 ∥ 普通 §1/§2/§4/§5/§6,§4.16)。
344
- const own = allowedSegment(agent, review, engineering)
345
- if (!depth0 && own === null) throw new Error(noSegmentError(engineering))
346
- const n = segmentNumber(args?.segment)
347
- if (n === null) {
348
- throw new Error(depth0
349
- ? `batch: unknown segment ${JSON.stringify(args?.segment ?? null)} — depth-0 edit rewrites a section of the in-flight record that you author (${engineering ? "§1/§4/§6" : "§1/§2/§4/§5/§6"} — pass the section number you write, e.g. "§4"). Nothing was written.`
350
- : `batch_segment: unknown segment ${JSON.stringify(args?.segment ?? null)} — pass the section number you write (e.g. "§${own}").`)
351
- }
352
- if (depth0) {
353
- const domain = engineering ? DEPTH0_SEGMENTS.append.engineering : DEPTH0_SEGMENTS.append.normal
354
- if (!domain.includes(n)) {
355
- throw new Error(engineering
356
- ? `batch: §${n} is not yours to write — in engineering mode depth-0 edit rewrites §1/§4/§6 (一段一作者: §2 = eng-designer, §3 = design review, §5 = eng-coder). Nothing was written.`
357
- : `batch: §${n} is not yours to write — in normal mode depth-0 edit rewrites §1/§2/§4/§5/§6 (一段一作者: §3 = design review only). Nothing was written.`)
358
- }
359
- } else if (n !== own) {
360
- throw new Error(`batch_segment: §${n} is not yours to write — this caller writes §${own} only (一段一作者: eng-designer → §2, design review → §3, eng-coder → §5). Nothing was written.`)
361
- }
362
- // 目标定位(D-BR21)——与 append / status 同序:段域 → path 门 → 取值。
363
- const givenPath = typeof args?.path === "string" && args.path.trim() ? args.path : null
364
- let abs
365
- if (givenPath) {
366
- if (!depth0) {
367
- throw new Error("batch: path is a depth-0-only parameter (D-BR21) — your target record arrives via the spawn binding / the review instance key. Nothing was written.")
368
- }
369
- abs = resolveBatchDocPath(cwd, givenPath)
370
- } else if (depth0) {
371
- abs = findInFlightBatch(cwd, batchDocBases(cwd)) // 歧义锚 ⇒ 基底 = 候选并集(#828——唯一在飞批照取 / ≥2 照列)
372
- } else {
373
- if (!batchDoc) {
374
- throw new Error("batch_segment: no batch record is bound to this caller — there is no path parameter by design (the target arrives via the spawn binding / the review instance key). Report the section as not written.")
375
- }
376
- abs = resolveBatchDocPath(cwd, batchDoc)
377
- }
378
- const src = readFileSync(abs, "utf8")
379
- const status = readBatchStatusLine(src)
380
- if (status === "closed") throw new Error(FROZEN_RECORD_ERROR)
381
- if (status === "unknown") throw new Error(UNRESOLVED_STATUS_ERROR)
382
- const oldText = args?.oldText
383
- if (typeof oldText !== "string" || !oldText.trim()) throw new Error(EDIT_BLANK_ANCHOR_ERROR)
384
- if (typeof args?.newText !== "string") throw new Error(EDIT_NO_TEXT_ERROR)
385
- if (/^## §\d/m.test(args.newText)) throw new Error(SKELETON_GUARD_ERROR)
386
- const span = sectionBodySpan(src, n)
387
- if (!span) throw new Error(missingSectionError(n))
388
- const body = src.slice(span.start, span.end)
389
- const hits = []
390
- for (let at = body.indexOf(oldText); at >= 0; at = body.indexOf(oldText, at + 1)) hits.push(at)
391
- if (!hits.length) {
392
- // 零命中 vs 越段界:全档别处有 ⇒ 锚越出目标段段体(E4);全档无 ⇒ 真零命中(E2)。两者都 fail-closed:
393
- // 「删那行作废判据」若零命中放行,会报成功而一字未删——比不做更坏。
394
- throw new Error(src.includes(oldText)
395
- ? `batch: edit anchor crosses the §${n} section boundary — it starts outside the section body or reaches the next §N header, and rewriting across it would break section location. Nothing was written.`
396
- : `batch: edit anchor not found — oldText must match the §${n} body exactly once, byte for byte (line endings included). Nothing was written. Re-read the section and pass its current text verbatim.`)
397
- }
398
- if (hits.length > 1) {
399
- const lines = hits.map((at) => src.slice(0, span.start + at).split("\n").length).join(", ")
400
- throw new Error(`batch: edit anchor is not unique — it matches ${hits.length} places inside §${n} (lines ${lines}). Extend the anchor until it matches once. Nothing was written.`)
107
+ /** 全量参数面(depth-0 六动作):schema 单源——profile 面从它取所需格,见 `PROFILE_PROPS`。 */
108
+ function fullParameters() {
109
+ return {
110
+ type: "object",
111
+ properties: {
112
+ action: {
113
+ type: "string",
114
+ enum: ["create", "attach", "append", "edit", "status", "close", "supersede", "check"],
115
+ description: "Which lifecycle step to run: create (new record) / attach — hang a ledger row on an ALREADY EXISTING in-flight record (depth-0 only: a reopened record taking on a new piece of work; opens a new row, or takes over an unsettled one with ledger:\"#<id>\", and writes its number into the header 台账 line) / append (add text to the END of your section) / edit — replace one anchored range inside YOUR OWN section (§1–§6 alike; your identity decides which section) / status (your section's status line) / close (freeze the record — this settles the batch's ledger rows in the same action) / supersede — freeze a record whose object is gone and will never be implemented, naming what replaced it (supersededBy); it never writes §3/§4/§6, settles the 待核销 rows and returns the unnamed 在途 rows to 待讨论 with trigger 条件 (depth-0 only) / check (depth-0 only, read-only: print this record's half-state readings — §1 open|closed, its ledger rows, and every record↔ledger inconsistency with the way out).",
116
+ },
117
+ path: {
118
+ type: "string",
119
+ description: "depth-0 only (D-BR21) — the batch record to operate on (若传则须可读). Omit it to target the unique in-flight record (0 or ≥2 in flight ⇒ refuse). Sub-agents and design reviews: do NOT pass path — your target record arrives via the spawn binding / the review instance key.",
120
+ },
121
+ segment: {
122
+ type: "string",
123
+ description: "append/edit/status only — the batch-record section you are writing (e.g. \"§4\"). Declares the section number only; your identity decides what is actually writable (main agent: append/edit §1/§4/§6 · status §1 (engineering) / append/edit §1/§2/§4/§5/§6 · status §1/§2/§5 (normal); eng-designer §2; eng-coder §5; normal-mode coder with a batchDoc binding §5; design review §3). edit reads the same whitelist as append — one table, two actions: the section you may append is the section you may rewrite in place.",
124
+ },
125
+ text: {
126
+ type: "string",
127
+ description: "append only — the markdown to append (for a design review §3: the round's conclusion table — one row per finding, its evidence a pointer — plus the VERDICT line and the counts; the report's own text stays out). Limit 20000 characters per call; longer content is refused — split it into multiple calls (each call becomes its own section, N continues). A line that STARTS with the status-line form (`**状态行**:…`) is refused — that line has one writer (`status`); quote it with a leading `> ` instead, or write it as prose.",
128
+ },
129
+ oldText: {
130
+ type: "string",
131
+ description: "edit only — oldText must match exactly once, byte for byte (line endings included), inside the section body; newText replaces that range, and an empty newText deletes it. Refused with nothing written: a blank oldText, zero hits, two or more hits (the matching lines are named), an anchor crossing the section boundary, an anchor touching the section's PROTECTED status line (the first `**状态行**:` line of its header zone — one writer: `status`; deleting a status line elsewhere, e.g. a surplus copy, is allowed), any replacement that introduces a `**状态行**:` line, and any edit that would leave MORE status lines in the header zone than before.",
132
+ },
133
+ newText: {
134
+ type: "string",
135
+ description: "edit only — the replacement text for the anchored range; an empty string deletes the range. Limit 20000 characters per call (same cap as append); longer is refused — split it into several edits of one anchored range each. Credentials are stripped mechanically (same as append); a `## §N` heading line is refused (skeleton protection), and on §3 a `### 轮次 N(评审子代理)` line is dropped (the round stamp is tool-generated only).",
136
+ },
137
+ value: {
138
+ type: "string",
139
+ description: "status only — the new status-line value (single line; exactly one legal keyword of your section's STATUS_WORDS entry: §1 进行中/已收口 · §2 设计完成 · §3 评审通过 · §5 实施完成 — plus decoration only: surrounding symbols / a trailing ISO date / whitespace; prose goes to `note`).",
140
+ },
141
+ note: {
142
+ type: "string",
143
+ description: "status only — prose that lands as a parenthetical on the status line (`**状态行**:进行中(note)`). Single line; must carry no STATUS_WORDS keyword (those go in `value`) and no skeleton placeholders. Omit for a plain value. On the reopen path (a frozen record, §1 → 进行中) `note` is REQUIRED and lands verbatim in the §1 reopen record instead of the status-line parenthetical (it may name the frozen keyword there).",
144
+ },
145
+ completed: {
146
+ type: "array",
147
+ items: { type: "number" },
148
+ description: "close / status writing §1 已收口 / supersede — REQUIRED for close and status: the ledger ids completed by this batch. Every id must be unique, belong to this record, and currently be 在途; every 在途 row must be listed. [] is valid only when the batch has no 在途 rows. On supersede the list is optional: an unnamed 在途 row goes back to 待讨论 with trigger 条件 (the work was not done — that is what this closeout says), so [] or omitting it is the main path there. Other actions do not accept this parameter. Invalid or omitted ids are refused before tokens or the record are written; return unfinished rows to 待讨论 first. Those rows are settled to 已核销 in the same transaction, and this batch's existing 待核销 rows are settled with them — closing leaves zero 在途 and zero 待核销 behind.",
149
+ },
150
+ supersededBy: {
151
+ type: "string",
152
+ description: "supersede only — REQUIRED: who replaced this record. Three forms, each machine-checked: a batch record path (docs/batches/<x>.md, must be on disk) / a document plus a section (docs/<area>/<name>.md §<N>, the section number must hit a heading line) / a commit (40 hex, must be reachable in the version store). A planned or never-done successor does not resolve and is refused — the machine never invents this fact. It lands verbatim in the §1 supersede record line and in the receipt.",
153
+ },
154
+ closeEvidence: {
155
+ type: "string",
156
+ description: "close / supersede / status writing §1 已收口 — REQUIRED on all three: one line of work evidence for this closeout (what this batch actually did). It is written into every settled row's evidence with a `收口 <YYYY-MM-DD>:` prefix, so human evidence and the closeout evidence stay distinguishable on the row. Blank (missing / empty / whitespace) is refused before anything is written — the machine never invents this line, because a machine-written sentence turns the close-proof gate into decoration.",
157
+ },
158
+ topic: {
159
+ type: "string",
160
+ description: "create only — the batch subject word shared by the record header (keep the file name aligned with it).",
161
+ },
162
+ source: {
163
+ type: "string",
164
+ description: "create only — REQUIRED: the record's origin line (来源 = …; single line). It fills the header's 编制 line; without it the skeleton's placeholder would block the record's first append/status (topic-style fail-closed). Nothing is written when it is missing.",
165
+ },
166
+ ledger: {
167
+ type: "string",
168
+ description: "create / attach — optional: an existing ledger entry number to take over (e.g. \"#1830\"; a leading # is optional) — on attach that is how a reopened record takes over an unsettled row. Omit it and the call opens a NEW ledger row in the same call (status 在途 · task_book = this record · trigger 归批; attach needs title for that) — but only when no unsettled row exists on the same face (board); otherwise it is refused and lists the candidates, and you pass either ledger:\"#<id>\" to take one over or newDebt:\"<why this is not one of them>\". Pass an archived / settled / foreign-owned row and it is refused. The row and the record are one action — there is no separate registration step.",
169
+ },
170
+ newDebt: {
171
+ type: "string",
172
+ description: "create / attach — optional: one line saying why this is a NEW debt rather than one of the unsettled rows already on the same face (board). Required only when you omit ledger while that face has unsettled rows; the reason lands in the new row's evidence and is quoted in this record's closeout receipt. Omit both ledger and newDebt while unsettled rows exist ⇒ refused with the candidate list.",
173
+ },
174
+ board: {
175
+ type: "string",
176
+ description: "create / attach — optional: the owning board for the header's 台账 line (e.g. \"core\"). Given, the opened/taken-over row is a requirement and carries this board; omitted, the row is a tech_todo. create writes it into the header 括注 (未给 ⇒ 「—」); attach never rewrites the parenthesis group — it only appends to the number list.",
177
+ },
178
+ title: {
179
+ type: "string",
180
+ description: "attach only — REQUIRED when attach opens a new ledger row (not needed when you take one over with ledger): the row's own subject, i.e. what this new piece of work is. It is the same thing as the ledger row's title (one concept, one name); do not reuse the batch's original subject — a reopened record taking on a new debt is not a second copy of the old one.",
181
+ },
182
+ date: {
183
+ type: "string",
184
+ description: "create only — the record date (YYYY-MM-DD); defaults to today.",
185
+ },
186
+ prev: {
187
+ type: "string",
188
+ description: "create only — the predecessor pointer line (前情); a leading `前情 = ` prefix is stripped automatically (idempotent — repeated prefixes included); defaults to 无(独立批).",
189
+ },
190
+ },
191
+ required: ["action"],
401
192
  }
402
- const hit = hits[0]
403
- // 状态行只有一个写者(status):锚**触及**该行 ∥ 替换**引入**一条 ⇒ 拒(否则一次 edit 就能伪造 status 的生命周期流转)。
404
- const spans = statusLineSpans(body)
405
- if (spans.some(([s, e]) => hit < e && hit + oldText.length > s)) throw new Error(EDIT_STATUS_LINE_ERROR)
406
- if (args.newText.split(/\r?\n/).some((line) => STATUS_LINE_RE.test(line))) throw new Error(EDIT_STATUS_LINE_ERROR)
407
- // 替换文本落盘取目标档的 EOL 形(`sanitizeText` 逐行处理后以 LF 相连;同 append 的 `insertIntoSection` 口径)。
408
- // 来源戳只有工具能盖(§4.7 不变量 5)⇒ `edit §3` 的 `newText` 同 append 丢伪造轮次戳行;其余段无戳可丢。
409
- const eol = src.includes("\r\n") ? "\r\n" : "\n"
410
- const replacement = sanitizeText(args.newText, n === 3).replaceAll("\n", eol)
411
- const newBody = body.slice(0, hit) + replacement + body.slice(hit + oldText.length)
412
- const postEdit = src.slice(0, span.start) + newBody + src.slice(span.end)
413
- // 文档机检门(§4.9 门 ④——**判集按命中类分两套**):**段长类**(段落过长 · 行过长)判本次写入的文本 = `newText`
414
- // (一条早先就在的超长段不再拦本段的无关改动);**锚类**(档缺 · 节缺 · 引缺)判**整档**——引用完整性是档级属性。
415
- // 「整档」= **改写后的**档(`recordView`):#2021 的现场就是「那条死引文被这一次 edit 换掉」,拿改写前的盘上字节判,
416
- // 那一行永远过不去(本批要消的就是那个死锁)。REFUSED ⇒ 拒(零字节落盘)∥ ERROR ⇒ 写 + 回执明示。
417
- const gate = runBatchGate({ abs, cwd, agent, scope: "writer", pending: { section: n, body: replacement, recordView: postEdit } })
418
- if (gate?.state === "refused") throw new Error(gateRefusalMessage(gate, "edit"))
419
- writeFileSync(abs, postEdit)
420
- // #84:记账面按端注入(与 append 同一条缝——缺省 no-op = CLI 语义零行为变)。
421
- onWritten?.(agent, abs)
422
- return `batch: edited §${n} of the batch record — replaced ${oldText.length} characters with ${replacement.length}.${gateReceiptLine(gate)}`
423
193
  }
424
194
 
425
195
  /**
426
- * 批次档生命周期工具工厂(主名 `batch`——单工具五 action)。
196
+ * 批次档生命周期工具工厂(主名 `batch`——**七 action**(+ `check` 只读面):create / attach / append / edit /
197
+ * status / close / supersede)。
427
198
  * @param {string|null} batchDoc — 绑定的目标档(spawn:`child._batchDoc`;评审:实例键;
428
199
  * depth-0 主 agent 挂载时 = null——目标走 D-BR21 可选 path / 在飞扫描)
429
- * @param {{review?: boolean}} [opts] — review=true 表示"设计评审实例"形态(写 §3 + 工具盖戳)
200
+ * @param {{review?: boolean, role?: string|null, reviewType?: string|null}} [opts] —
201
+ * `review=true` 表示评审实例形态(写 `§3` + 工具盖戳);`role` = 装配面的角色身份
202
+ * (`family-tools.mjs` 传;缺省 = depth-0 全量面);`reviewType` = 本评审实例的**评审轨**
203
+ * (`"design"` ∥ `"code"`)——与模式位一起决定 `§3` 写不写得进去(`BATCH-RECORD.md` §4.3 ∥ §4.4:
204
+ * 工程设计轨收回,代码轨与普通模式保留)。两项缺一即判不出,故这里不给默认值。
430
205
  */
431
- export function batchTool(batchDoc = null, { review = false } = {}) {
206
+ export function batchTool(batchDoc = null, { review = false, role = null, reviewType } = {}) {
207
+ const profileKey = review ? "review" : (role && PROFILE_DOCS[role] ? role : null)
208
+ const full = fullParameters()
209
+ const profileParameters = profileKey
210
+ ? {
211
+ type: "object",
212
+ required: ["action"],
213
+ properties: {
214
+ action: {
215
+ type: "string",
216
+ enum: PROFILE_ACTIONS,
217
+ description: `Which step this face carries: ${PROFILE_ACTIONS.join(" / ")} — append (add text to the END of your section) / edit (replace one anchored range inside it) / status (your section's status line).`,
218
+ },
219
+ ...Object.fromEntries(PROFILE_PROPS.map((k) => [k, k === "segment" ? profileSegmentProp(profileKey) : full.properties[k]])),
220
+ },
221
+ }
222
+ : full
432
223
  return {
433
224
  name: "batch",
434
- description: DESC("batch"), // 模型可见文本 = tool-docs/batch.md
435
- parameters: {
436
- type: "object",
437
- properties: {
438
- action: {
439
- type: "string",
440
- enum: ["create", "append", "edit", "status", "close"],
441
- description: "Which lifecycle step to run: create (new record) / append (add text to the END of your section) / edit — replace one anchored range inside YOUR OWN section (§1–§6 alike; your identity decides which section) / status (your section's status line) / close (freeze the record).",
442
- },
443
- path: {
444
- type: "string",
445
- description: "depth-0 only (D-BR21) — the batch record to operate on (若传则须可读). Omit it to target the unique in-flight record (0 or ≥2 in flight ⇒ refuse). Sub-agents and design reviews: do NOT pass path — your target record arrives via the spawn binding / the review instance key.",
446
- },
447
- segment: {
448
- type: "string",
449
- description: "append/edit/status only — the batch-record section you are writing (e.g. \"§4\"). Declares the section number only; your identity decides what is actually writable (main agent: append/edit §1/§4/§6 · status §1 (engineering) / append/edit §1/§2/§4/§5/§6 · status §1/§2/§5 (normal); eng-designer §2; eng-coder §5; normal-mode coder with a batchDoc binding §5; design review §3). edit reads the same whitelist as append — one table, two actions: the section you may append is the section you may rewrite in place.",
450
- },
451
- text: {
452
- type: "string",
453
- description: "append only — the markdown to append (verbatim — findings table + VERDICT + counts for a design review §3). Limit 20000 characters per call; longer content is refused — split it into multiple calls (each call becomes its own section, N continues).",
454
- },
455
- oldText: {
456
- type: "string",
457
- description: "edit only — oldText must match exactly once, byte for byte (line endings included), inside the section body; newText replaces that range, and an empty newText deletes it. Refused with nothing written: a blank oldText, zero hits, two or more hits (the matching lines are named), an anchor crossing the section boundary, and any anchor or replacement that touches or introduces a `**状态行**:` line (the status line has one writer: `status`).",
458
- },
459
- newText: {
460
- type: "string",
461
- description: "edit only — the replacement text for the anchored range; an empty string deletes the range. Credentials are stripped mechanically (same as append); a `## §N` heading line is refused (skeleton protection), and on §3 a `### 轮次 N(评审子代理)` line is dropped (the round stamp is tool-generated only).",
462
- },
463
- value: {
464
- type: "string",
465
- description: "status only — the new status-line value (single line; exactly one legal keyword of your section's STATUS_WORDS entry: §1 进行中/已收口 · §2 设计完成 · §3 评审通过 · §5 实施完成 — plus decoration only: surrounding symbols / a trailing ISO date / whitespace; prose goes to `note`).",
466
- },
467
- note: {
468
- type: "string",
469
- description: "status only — prose that lands as a parenthetical on the status line (`**状态行**:进行中(note)`). Single line; must carry no STATUS_WORDS keyword (those go in `value`) and no skeleton placeholders. Omit for a plain value. On the reopen path (a frozen record, §1 → 进行中) `note` is REQUIRED and lands verbatim in the §1 reopen record instead of the status-line parenthetical (it may name the frozen keyword there).",
470
- },
471
- topic: {
472
- type: "string",
473
- description: "create only — the batch subject word shared by the record header (keep the file name aligned with it).",
474
- },
475
- source: {
476
- type: "string",
477
- description: "create only — REQUIRED: the record's origin line (来源 = …; single line). It fills the header's 编制 line; without it the skeleton's placeholder would block the record's first append/status (topic-style fail-closed). Nothing is written when it is missing.",
478
- },
479
- ledger: {
480
- type: "string",
481
- description: "create only — optional: an existing ledger entry number to take over (e.g. \"#1830\"; a leading # is optional). Omit it and create opens a NEW ledger row in the same call (status 在途 · task_book = this record · trigger 归批) — but only when no unsettled row exists on the same face (board); otherwise create is refused and lists the candidates, and you pass either ledger:\"#<id>\" to take one over or newDebt:\"<why this is not one of them>\". Pass an archived / settled / foreign-owned row and create is refused. create and the ledger row are one action — there is no separate registration step.",
482
- },
483
- newDebt: {
484
- type: "string",
485
- description: "create only — optional: one line saying why this batch is a NEW debt rather than one of the unsettled rows already on the same face (board). Required only when you omit ledger while that face has unsettled rows; the reason lands in the new row's evidence and is quoted in this record's closeout receipt. Omit both ledger and newDebt while unsettled rows exist ⇒ create is refused with the candidate list.",
486
- },
487
- board: {
488
- type: "string",
489
- description: "create only — optional: the owning board for the header's 台账 line (e.g. \"core\"). Given, the opened/taken-over row is a requirement and carries this board; omitted, the row is a tech_todo and the header 括注 shows 「—」.",
490
- },
491
- date: {
492
- type: "string",
493
- description: "create only — the record date (YYYY-MM-DD); defaults to today.",
494
- },
495
- prev: {
496
- type: "string",
497
- description: "create only — the predecessor pointer line (前情); a leading `前情 = ` prefix is stripped automatically (idempotent — repeated prefixes included); defaults to 无(独立批).",
498
- },
499
- },
500
- required: ["action"],
501
- },
225
+ description: profileKey ? DESC(PROFILE_DOCS[profileKey]) : DESC("batch"), // 模型可见文本 = tool-docs/batch*.md
226
+ parameters: profileParameters,
502
227
  async execute(args, ctx) {
228
+ // 第二道门(§6.29 ② · B6):schema 的 enum 只是提示,provider 不保证执行它——profile 面
229
+ // 收到本身份执行不了的动作,必须在任何写盘 / 台账事务之前拒,并点名动作与可用集。
230
+ if (profileKey && !PROFILE_ACTIONS.includes(args?.action)) {
231
+ throw new Error(`batch: action ${JSON.stringify(args?.action ?? null)} is not available to this caller — this face carries ${PROFILE_ACTIONS.join(" / ")} only (its own section of the record). Nothing was written.`)
232
+ }
233
+ const closingCall = args?.action === "close" || args?.action === "supersede" || (args?.action === "status" && typeof args?.value === "string" && args.value.includes("已收口"))
234
+ if (args?.completed !== undefined && !closingCall) {
235
+ throw new Error("batch: completed is accepted only by close, by supersede, or by status writing §1 已收口. Nothing was written.")
236
+ }
237
+ if (args?.closeEvidence !== undefined && !closingCall) {
238
+ throw new Error("batch: closeEvidence is accepted only by close, by supersede, or by status writing §1 已收口. Nothing was written.")
239
+ }
503
240
  const agent = ctx?.agent ?? {}
504
241
  const cwd = agent.cwd
505
242
  const bases = batchDocBases(cwd) // 歧义锚 ⇒ 候选项目基底并集(#828——create / 在飞 / 写门基底集同源)
@@ -521,17 +258,23 @@ export function batchTool(batchDoc = null, { review = false } = {}) {
521
258
  switch (args?.action) {
522
259
  case "create":
523
260
  return createBatchRecord({ args, ctx, review, cwd, bases, onWritten })
261
+ case "attach":
262
+ return attachBatchRecord({ args, ctx, review, cwd, pickTarget, onWritten })
524
263
  case "append":
525
- return appendBatchRecord({ args, ctx, review, batchDoc, onWritten })
264
+ return appendBatchRecord({ args, ctx, review, reviewTrack: reviewType, batchDoc, onWritten })
526
265
  case "edit":
527
- return editBatchRecord({ args, ctx, review, batchDoc, onWritten })
266
+ return editBatchRecord({ args, ctx, review, reviewTrack: reviewType, batchDoc, onWritten })
528
267
  case "status":
529
- return statusBatchRecord({ args, ctx, review, pickTarget, onWritten })
268
+ return statusBatchRecord({ args, ctx, review, reviewTrack: reviewType, pickTarget, onWritten })
530
269
  case "close":
531
270
  return closeBatchRecord({ args, ctx, review, pickTarget, onWritten })
271
+ case "supersede":
272
+ return supersedeBatchRecord({ args, ctx, review, pickTarget, onWritten })
273
+ case "check":
274
+ return checkBatchRecord({ args, ctx, review, pickTarget })
532
275
  default:
533
- throw new Error(`batch: unknown action ${JSON.stringify(args?.action ?? null)} — pass one of create / append / edit / status / close.`)
276
+ throw new Error(`batch: unknown action ${JSON.stringify(args?.action ?? null)} — pass one of create / attach / append / edit / status / close / supersede / check.`)
534
277
  }
535
278
  },
536
279
  }
537
- }
280
+ }