@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
@@ -0,0 +1,444 @@
1
+ /**
2
+ * agent-tools/batch-closeout.mjs — 收口面的四道判据与回执(从 `batch-lifecycle.mjs` 拆出,2026-10-27)。
3
+ *
4
+ * 权威规格 = `docs/core/design/BATCH-LEDGER-REVIEW-UNIFY.md` §2.6(四道门)∥ §2.11(收口前显式处置);
5
+ * 链门的原文契约 = `docs/core/design/BATCH-RECORD.md` §4.18-A。
6
+ *
7
+ * 本档承载三件(都不碰 fs 写、只读与判):
8
+ * ① `assertCloseoutGates` —— 收口两路(`close` ∥ `status` 写 `§1 已收口`)共调的判序:
9
+ * 链完整性门(§2/§3/§4/§6 各段须有内容——`不适用` 声明机制已退役)→ **`§3` 状态词臂**(无条件 = `评审通过`)
10
+ * → 本批批内单测档门(`TESTING.md` §3.5)→ 文档机检门(判据 = `docs/core/design/DOC-CHECK.md` §1–§6;
11
+ * 调用点 = 同档 §7「落点」三处之一「批档写入与收口」)→ **档位臂**
12
+ * (`batch-tier-gate.mjs` 的 `assertTierPlan`——同一臂两节,一条拒文:本批改动面里在盘的码档,§2 必须有
13
+ * 它的行读数且与批起快照一致(判法 ∥ 拒文 = `docs/core/design/DOC-CHECK.md` §8);其中实测越了收口线的
14
+ * 源档,§2 还必须有它的正向形分拆方案。两节判的都是**记录缺件**(越线那一节拿收口时的当前长度当触发物,
15
+ * 判的仍是 §2 那一格);语义单源 = `docs/core/standards/CODE-TIER.md` §2.2,位次 = 本档的判序第 ⑤ 臂)。
16
+ * ② `assertSectionFiveGate` —— §5 写入门(段序门):两条合取——① `§3` 状态行 = `评审通过`;② `§3` 最近一轮
17
+ * 轮次块自己携 pass 裁定行(块 = `lastRoundBlock`;裁定读数 = 骨架档 `verdictGapOf`,`append §3` 写入闸与
18
+ * 签发面读同一个函数)。旧的第一条旁路(`§1` 声明 §3 不适用)已随本批删除:实现只发生在评审之后,没有例外段。
19
+ * ③ `reanchorReceiptLine` —— 收口重锚回执三行(§2.11 逐字)。
20
+ * ④ **全归档补关面**(§4.18-C · `docs/core/design/LEDGER.md` §11.2):拒文 `repairBlockedError`、档面
21
+ * 追记行 `repairTraceLine` 与回执段 `repairReceiptLine`。补关只跳过收口门的 ①②⑤ 三臂,③④ 与写序、
22
+ * 凭证消费、完成清单预检全部保留——「行全归档」不是「环节全免」;分派判据住 `batch-ledger-view.mjs`。
23
+ *
24
+ * 为什么 §3 内容臂留着(不换成只判状态词):内容臂守的是「段里真跑过」,状态词臂守的是「跑的结论是
25
+ * pass」——换掉内容臂 = 门被放宽(一段空着但状态词对就过),那正是本批要堵的洞。所以是**加**一条臂。
26
+ *
27
+ * 依赖单向(KD-4):`skeleton ← closeout ← bind ← reopen ← lifecycle`——本档不 import lifecycle。
28
+ */
29
+ import { execFileSync } from "node:child_process"
30
+ import { readFileSync } from "node:fs"
31
+ import { isAbsolute, relative, resolve } from "node:path"
32
+
33
+ import { owningProject } from "../manifest.mjs"
34
+ import { batchProjectRoot } from "./batch-paths.mjs"
35
+ // 取材面的判据一族(比较键 ∥ 显示式 ∥ 三处判据)——依赖单向:本档 import 它,它不 import 本档。
36
+ import {
37
+ displayRelOf, neighborListClaims, selfAttributedOf, sessionClaimsOf, surfaceKey,
38
+ } from "../agent/batch-changed-surface.mjs"
39
+
40
+ import {
41
+ countRoundBlocks, inapplicableDeclarationError, lastRoundBlock, malformedInapplicableLine, readSectionStatusWord,
42
+ sectionContentState, STATUS_WORDS, verdictGapOf,
43
+ } from "./batch-skeleton.mjs"
44
+ // 裁定读数 = 骨架档 `verdictGapOf` 一个函数(设计档 §2.6.1「判据单源」):`§5` 门判据 2 与签发面判的是同一份
45
+ // 回执文本,组合序各写一遍必然一处变一处不变。本档不再 import 两条裁定锚——锚与序都在那个函数里。
46
+ import { assertUnitTestFilesCleared } from "./batch-unit-test-gate.mjs"
47
+ import { assertTierPlan } from "./batch-tier-gate.mjs"
48
+ import { baseShaOf, gateRefusalMessage, runBatchGate } from "./batch-gate.mjs"
49
+ // 本批提交 diff 腿(现成的改动面——不另造一套登记):`committedDocs` 与本档无依赖方向冲突。
50
+ import { committedDocs } from "./batch-regions.mjs"
51
+
52
+ /** 链判段集(§2/§3/§4/§6——§5 段号豁免恒不判;§1 主 agent 自述段不设前置)。 */
53
+ const CHAIN_SEGMENTS = [2, 3, 4, 6]
54
+
55
+ /** §6 空闸拒句(#422①——空 ⇒ 拒 + 提示先写 §6;防「append 被拒 ⇒ close 照常 ⇒ §6 永久为空」复发)。
56
+ * **§6 为唯一缺段时**拒串取本函数(§4.18-A J2——「非空门」文案逐字零回归);判据本体 = 单源谓词
57
+ * `sectionContentState(src, 6)`。 */
58
+ function emptySectionSixError() {
59
+ return "batch: §6 收口段为空(non-empty gate)— close refuses: the closeout section (§6) has no content, and closing would freeze the record with that section permanently empty. Write the section first (append §6: the closeout / verification summary), then call close again. Nothing was written."
60
+ }
61
+
62
+ /** 链门拒绝句(§4.18-A J1——缺段非仅 §6 时;`missing` = 点名串,
63
+ * 形如 `§2 / §3 / §4`——按段号升序列出)。不再提声明路:机制已退役,提它就等于又给一条可照抄的路。 */
64
+ function closeoutChainError(missing) {
65
+ return "batch: 收口链未跑完(closeout chain gate)— close refuses: the record's closeout chain has not run, and closing would freeze it that way. " +
66
+ `Missing: ${missing}. Each named section must carry its own content — the \`不适用\` declaration is retired (every batch needs its design, its review and its approval). ` +
67
+ "§6 must carry its verification. Nothing was written."
68
+ }
69
+
70
+ /** `§3` 状态词臂拒句(设计档 §2.6 `R-G1` 逐字形):链门已过、只剩评审结论没到时出这一条。
71
+ * `value` = 读到的状态词(缺失 ⇒ `(无状态行)`)。本臂无条件——没有「声明不适用」这条旁路。 */
72
+ function closeoutS3Error(value) {
73
+ return "batch: 收口链未跑完(closeout chain gate)— close refuses: " +
74
+ `§3 状态行 = ${value},须 = 评审通过(评审须真跑过并给 pass)。Missing: §3. Nothing was written.`
75
+ }
76
+
77
+ /**
78
+ * 链完整性门(§4.18-A——**收口前置**):判据 = §2 / §3 / §4 / §6 每段须 `sectionContentState(src, seg) !== "empty"`
79
+ * (有内容);不满足 ⇒ throw 并点名缺段(J1;§6 为唯一缺段时 = J2 旧串逐字)。门不判内容质量、
80
+ * 不做自动修复、不判 §1 / §5。声明行扫描先行(J3——那类行现在一律拒,不静默当作无声明)。
81
+ * @param {string} src — 档全文(写盘前只读)
82
+ */
83
+ export function assertCloseoutChainComplete(src) {
84
+ const badDecl = malformedInapplicableLine(src)
85
+ if (badDecl !== null) throw new Error(inapplicableDeclarationError(badDecl))
86
+ const missing = CHAIN_SEGMENTS.filter((n) => sectionContentState(src, n) === "empty")
87
+ if (missing.length === 0) return
88
+ if (missing.length === 1 && missing[0] === 6) throw new Error(emptySectionSixError()) // J2——零回归
89
+ throw new Error(closeoutChainError(missing.map((n) => `§${n}`).join(" / "))) // J1
90
+ }
91
+
92
+ /**
93
+ * 收口两路共调判序(设计档 §2.4–§2.6 · 2026-10-27 四道门 + 2026-11-11 第 ⑤ 臂):
94
+ * ① 链完整性门(§2 / §3 / §4 / §6 各段须有内容)
95
+ * ② **`§3` 状态词臂**:`§3` 状态行 = `评审通过`(无条件)
96
+ * ③ 本批批内单测档门(仍在盘 ⇒ 拒——零留存的结构兜底)
97
+ * ④ 文档机检门(REFUSED ∥ ERROR ⇒ 拒)
98
+ * ⑤ **档位臂**(`batch-tier-gate.mjs` 的 `assertTierPlan`):两节一趟判完,一条拒文——
99
+ * ① 读数支:本批改动面里在盘的码档,§2 机读清单那一行须带行读数且与**批起快照**一致;
100
+ * ② 越线方案支:其中实测越了收口线的档,§2 须带它的正向形分拆方案。无在盘码档就两节都不启动
101
+ * (**§2 缺块不是拒因**)。
102
+ * 基线内容由本档交进去(`baseTextReaderOf`——门自己不读 git)。
103
+ * 位次 = 既有拒因之后、写盘之前(任一被拒 ⇒ 档字节不变)。返回 `④` 的门结果供回执拼行(`null` = 未跑);
104
+ * `mode === "normal"` 时同一笔把 ⑤ 的取材读数挂上 `changedSurface`,回执行从它取「只报不判」的那一半。
105
+ * @param {{abs:string, cwd:string, agent:object, src:string, action:"close"|"status", mode?:"normal"|"repair"|"supersede"}} o
106
+ * `src` = 调用方已读的写盘前全文(判据与写盘读同一份字节,不二次读盘)。
107
+ * `mode` = **哪一条收口边在跑**(三值闭集;跳过集由这一处决定):
108
+ * `normal` = 正常收口(五臂全跑)∥ `repair` = 全归档补关(§4.18-C)∥ `supersede` = 被取代的收口(§4.18-D)。
109
+ * `repair` ∥ `supersede` 两条都**只跳过 ①②⑤ 三臂**,③④ 照跑——补关与取代按定义没有可判的 §2,
110
+ * 而单测档门与机检门在那两条边上照旧生效;分派判据不在这里
111
+ * (补关住 `batch-ledger-view.mjs` 的一致性预读,取代由 `batch-supersede.mjs` 自己持),本档只承接
112
+ * 「已判定走哪条边」之后的判序。
113
+ * @returns {object|null} 文档机检门结果
114
+ */
115
+ export function assertCloseoutGates({ abs, cwd, agent, src, action = "close", mode = "normal" }) {
116
+ if (mode === "normal") {
117
+ assertCloseoutChainComplete(src) // ① 链门(§2 / §3 / §4 / §6 各段须有内容)
118
+ // ② §3 状态词臂(无条件):评审须真跑过并给 pass。旧旁路「§1 声明 §3 不适用」已随声明机制退役删除。
119
+ const s3 = readSectionStatusWord(src, 3)
120
+ if (s3 !== STATUS_WORDS[3].done) throw new Error(closeoutS3Error(s3 ?? "(无状态行)"))
121
+ }
122
+ assertUnitTestFilesCleared(abs, action) // ③
123
+ const gate = runBatchGate({ abs, cwd, agent, scope: "close" }) // ④
124
+ if (gate.state === "refused" || gate.state === "error") throw new Error(gateRefusalMessage(gate, action))
125
+ // ⑤ 档位臂:与 ①② 同属 `mode === "normal"` 组(`repair` ∥ `supersede` 按定义没有可判的 §2)。
126
+ if (mode === "normal") {
127
+ const root = tierRootOf(abs, cwd)
128
+ const surface = changedSurface(abs, root, agent)
129
+ assertTierPlan(src, root, surface.judged, baseTextReaderOf(abs, root))
130
+ // 只报不判的那一半随门结果交回调用面(同一笔取材,不取第二次——两次取才可能各说各的)。
131
+ gate.changedSurface = surface
132
+ }
133
+ return gate
134
+ }
135
+
136
+ /**
137
+ * 本批 diff 腿读不出的拒文(判据单源 = 设计档 §4.18.1「提交 diff 读不出 ⇒ 拒收口,不静默少一腿」)。
138
+ * 三件必须点在串里:**根**(在哪儿跑)、**批起 sha**(拿什么比)、**下一步**(`git diff --name-only <sha> HEAD`
139
+ * 看 git 报什么),收尾句 = `Nothing was written.`。
140
+ * 为什么必须拒:`committedDocs` 的失败面是 `ok: false` + 空集;空集若被读成「本批没有提交改动」,不经记账工具
141
+ * 写的档(`bash` ∥ `execute` 落盘的、脚本生成的)就一档都判不到,而收口照样把记录冻成历史——业务失败变成功。
142
+ * 只属**本批自己的**这一笔:邻批那几笔读不出不拒(见 `batch-changed-surface.mjs` 的 `neighborListClaims`)。
143
+ * @param {string} root 项目根(拒文点名的那个根)
144
+ * @param {string} baseSha 本批批起 sha(`baseShaOf` 的返回形,此处必非 `null`)
145
+ */
146
+ export function changedSurfaceUnreadableError(root, baseSha) {
147
+ return "batch: 本批改动面读不出(changed surface unreadable)— close refuses: this batch's own commit-diff leg " +
148
+ `could not be read at root ${root} with base sha ${baseSha}, so the changed surface has no diff side left. ` +
149
+ "Closing now would freeze the record while the files written outside the ledger (files dropped by `bash` / `execute` / a script) were never judged — " +
150
+ "an unread diff must not pass for \"this batch committed nothing\". " +
151
+ `下一步:在该根跑 \`git diff --name-only ${baseSha} HEAD\`,看 git 报什么(批起 sha 指向的对象在不在 ∥ 这个目录还在不在仓里),修好后再收口。 ` +
152
+ "Nothing was written."
153
+ }
154
+
155
+ /**
156
+ * 本批改动面(**取材 = 现成两面,按批判**;判据单源 = 设计档 §4.18.1)——交绝对路径,供档位臂量长度。
157
+ *
158
+ * 两腿,**判据一在前**:
159
+ * 判据一 = 写时归属(记账面记下的「这笔写服务哪一批」,取自 `agent._batchAttribution`);
160
+ * 判据二 = 提交 diff,按认领收窄:减去**别的批已认领**的档。认领两源对批档状态的要求不同——观测源
161
+ * (本会话归属表里别的批档)不看那一批收没收口;计划源(盘上批档的 §2 机读清单)**状态可读即收**,
162
+ * 上界随状态定:未收口取 HEAD、已收口取那份批档自己的最后一次提交(取不到就不认领)。
163
+ * 三条合成规则:
164
+ * - 归属表里属本档 ⇒ **判**(一条直接的写记录不被另一个批的计划推翻);
165
+ * - 归属表里没有它、认领成立 ⇒ **不判,只报**(收口回执点名它,请人确认是否本批);
166
+ * - 两腿都不说话 ⇒ **判**(认领不成立就当它是本批的,fail-closed)。
167
+ * 触达账条目本就是绝对路径(写工具记账);提交清单以 **git 仓根**为基,故按 `committedDocs` 回的 `base`
168
+ * 还原成绝对路径——项目根住大仓子目录时也不丢条目。基 sha 未定 ⇒ 只以触达账为准(diff 腿不启动);
169
+ * **基 sha 有了却读不出**(`committed.ok === false`)⇒ 抛拒(`changedSurfaceUnreadableError`),不静默少一腿:
170
+ * 空集若被当成「本批没有提交改动」,不经记账工具写的档就一档都判不到,而收口照样冻记录。
171
+ * 拒收口只属**本批自己的这一笔**:邻批那几笔读不出由 `neighborListClaims` 按「认领不成立」处置。
172
+ * @returns {{root:string, judged:string[], reported:string[]}} `judged` = 交给档位臂判读数的档;
173
+ * `reported` = 认领成立、只进回执行的档(绝对路径)
174
+ */
175
+ export function changedSurface(abs, root, agent) {
176
+ const touched = Array.isArray(agent?._touchedFiles) ? agent._touchedFiles : []
177
+ const baseSha = baseShaOf(abs)
178
+ const diff = []
179
+ if (baseSha !== null) {
180
+ const committed = committedDocs(root, baseSha)
181
+ if (!committed.ok) throw new Error(changedSurfaceUnreadableError(root, baseSha))
182
+ for (const f of committed.files ?? []) diff.push(resolve(committed.base, f))
183
+ }
184
+ // 同一档两腿都会给(触达账记过又提交过):按比较键去重,留首次出现的原形。
185
+ const entries = new Map()
186
+ for (const p of [...touched, ...diff]) {
187
+ if (typeof p !== "string" || p === "") continue
188
+ const key = surfaceKey(p)
189
+ if (!entries.has(key)) entries.set(key, p)
190
+ }
191
+ const mine = selfAttributedOf(agent, abs)
192
+ // 认领只在真有「不属于本档」的条目时才去问(会话归属是内存读,盘上清单那一路每个邻批各两次 git 调用)。
193
+ const claimed = new Set()
194
+ if ([...entries.keys()].some((k) => !mine.has(k))) {
195
+ for (const key of sessionClaimsOf(agent, abs)) claimed.add(key)
196
+ for (const key of neighborListClaims(root, abs).keys()) claimed.add(key)
197
+ }
198
+ const judged = []
199
+ const reported = []
200
+ for (const [key, p] of entries) {
201
+ if (mine.has(key) || !claimed.has(key)) judged.push(p) // 判据一说了算 ∥ 两腿都不说话
202
+ else reported.push(p) // 只报不判
203
+ }
204
+ return { root, judged, reported }
205
+ }
206
+
207
+ /**
208
+ * `[changed surface]` 收口回执段(判据单源 = 设计档 §4.18.1「被别的批认领的档只报不判」):这些档不判读数,
209
+ * 但**点名它们**,请人确认「是否本批」——判据收窄了,这件事仍然看得见。
210
+ * 认领的来源如实写成两源(本会话归属表 ∥ 盘上批档的 §2 清单):观测源不按状态筛;计划源**状态可读即收**、
211
+ * 上界随状态定(未收口取 HEAD、已收口取它自己的收口提交),所以串里不写「在途」那一个限定——回执说的必须是
212
+ * 它真做了的那件事。
213
+ * 承载面 = 收口那一笔返回给调用方的回执文本(与 `[doc-check gate]` ∥ `[ledger reanchor]` 同面);
214
+ * 读者 = 收口这一笔的调用者,他正是决定「这些档算不算本批」的人。不写进批档、不进台账:它不是规范,是一次收口的读数。
215
+ * @param {{root?:string, reported?:string[]}|null} surface — `assertCloseoutGates` 交回的取材读数
216
+ * @returns {string} 以换行起头;没有被认领的档 ⇒ 空串
217
+ */
218
+ export function changedSurfaceReceiptLine(surface) {
219
+ const rows = surface?.reported ?? []
220
+ if (rows.length === 0) return ""
221
+ const items = rows.map((p) => `\n ${displayRelOf(surface.root, p)}`).join("")
222
+ return `\n[changed surface] 只报不判:${rows.length} 档被别的批认领(本会话归属表 ∥ 盘上批档的 §2 清单),本批没判它们的读数——确认是否本批${items}`
223
+ }
224
+
225
+ /** 仓根(§2 机读清单的第一列是仓根相对路径)——解析式与文档机检门同式
226
+ * (`batch-gate.mjs` 的 `evaluate`:`owningProject(批档) ?? batchProjectRoot(cwd)`):
227
+ * 两臂判同一批档、同一套相对路径,根不同就会一处判到档、一处判到空。 */
228
+ function tierRootOf(abs, cwd) {
229
+ const base = resolve(cwd)
230
+ return owningProject(resolve(abs), base) ?? batchProjectRoot(base)
231
+ }
232
+
233
+ // ─── 读数支的基线内容(本档读 git 的唯一一处:门自己不读,内容由这里交进去)──────────────────
234
+
235
+ /** 一次 git 调用(`-C <cwd>`):失败不抛、返 `null`——分流判据在调用方(对象在不在 ∥ 路径在不在)。 */
236
+ function gitRun(cwd, argv) {
237
+ try {
238
+ return execFileSync("git", ["-C", cwd, ...argv], {
239
+ encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 8000,
240
+ })
241
+ } catch {
242
+ return null
243
+ }
244
+ }
245
+
246
+ /** 档在 git 树里的路径:快照的树以 **git 仓根**为基,§2 清单以**项目根**为基——项目根住大仓子目录时
247
+ * 两基不同(解析式与 `committedDocs` 的 `base` 同一条)。 */
248
+ function gitPathOf(top, root, relPath) {
249
+ const abs = isAbsolute(relPath) ? relPath : resolve(root, relPath)
250
+ const rel = relative(top, abs).replace(/\\/g, "/")
251
+ return rel === "" || rel.startsWith("../") || isAbsolute(rel) ? String(relPath).replace(/\\/g, "/") : rel
252
+ }
253
+
254
+ /**
255
+ * 读数支的基线取值函数(判法单源 = `docs/core/design/DOC-CHECK.md` §8「两个失败怎么分开」):
256
+ * `git show <sha>:<档>` 对「快照里没这一档」与「对象读不到」报的错同形,照错文分流会把每个有新建档的批整批拒
257
+ * (`新` 正是那条判据的地基)。故按三步问、各问一件:对象在不在 ⇒ 路径在不在 ⇒ 取内容。
258
+ * **拒绝条件只有一条 = 记入行的 sha 指向的对象读不到**(`undefined`);`refs/thincoder/baseline/<批档名>`
259
+ * 在不在不进判据——ref 只负责让那个对象不被回收,不是取内容的入口。
260
+ * @param {string} abs — 批档绝对路径(记入行 `批起 sha` 的取法单源 = `baseShaOf`)
261
+ * @param {string} root — 项目根(清单第一列的基)
262
+ * @returns {(relPath:string) => string|null|undefined} 串 = 该档在快照里的内容 ∥ `null` = 快照里没有这一档 ∥
263
+ * `undefined` = 基线不可判(门按整批一条拒)
264
+ */
265
+ function baseTextReaderOf(abs, root) {
266
+ const sha = baseShaOf(abs)
267
+ if (sha === null) return () => undefined
268
+ const top = (gitRun(root, ["rev-parse", "--show-toplevel"]) ?? "").trim() || root
269
+ let commitReadable = null // 一次收口只问一遍对象在不在
270
+ return (relPath) => {
271
+ if (commitReadable === null) commitReadable = gitRun(top, ["cat-file", "-e", `${sha}^{commit}`]) !== null
272
+ if (!commitReadable) return undefined
273
+ const gitPath = gitPathOf(top, root, relPath)
274
+ if (gitRun(top, ["cat-file", "-e", `${sha}:${gitPath}`]) === null) return null
275
+ const text = gitRun(top, ["show", `${sha}:${gitPath}`])
276
+ return text === null ? undefined : text // 取不到内容同样按「基线不可判」,不静默读成 `新`
277
+ }
278
+ }
279
+
280
+ /** 读档(本档只读一面——写盘归 lifecycle 与 bind;读错上抛不伪装)。 */
281
+ export function readCloseoutSource(abs) { return readFileSync(abs, "utf8") }
282
+
283
+ // ─── 全归档补关(§4.18-C · `docs/core/design/LEDGER.md` §11.2)────────────────────────────
284
+
285
+ /** 补关被其它半状态拦住(§4.18-C「其它不一致不放行」):全归档但还命中 `header-row-missing` 等任一读形 ⇒
286
+ * 拒,**逐项列出全部半状态**并指回 `check` 按各出路先修——归属错误不得被冻成历史。
287
+ * (无逐字原文;语域照 `batch` 族拒句:点名 + 下一步 + `Nothing was written.`)
288
+ * @param {{name:string, rows:number[]}[]} halfStates — `batchLedgerConsistency` 的 `halfStates`
289
+ */
290
+ export function repairBlockedError(halfStates) {
291
+ const list = halfStates.map((h) => `${h.name}${h.rows?.length ? ` #${h.rows.join(" · #")}` : ""}`).join(";")
292
+ return "batch: 全归档批的补关被拒(ledger repair blocked)— the record's ledger rows are all archived, but the " +
293
+ `consistency read hits more than one half state, so freezing would cement a ledger mismatch as history. Half states: ${list}. ` +
294
+ "Run batch({action:\"check\"}) and follow each exit, then retry close. Nothing was written."
295
+ }
296
+
297
+ /** 补关在档面留的追记行(逐字 = `docs/core/design/LEDGER.md` §11.2;载体 = `appendLineToSection`——只追加
298
+ * 不改写,EOL 取 §1 段头行)。为什么不能只靠瞬时回执:四个段均空、状态行又已收口,不写一行就没有人
299
+ * 看得出这个档为何能冻结。 */
300
+ export const repairTraceLine = (date, rows) => `**补关记录**:${date} · 行集全归档(${rows} 行)· §3/§4/§6 未补写 · 操作者 = 主 agent`
301
+
302
+ /** 补关回执段(§4.13「本档特有面」——补关成功另出 `[ledger repair]`):把「零行改写」说成事实,
303
+ * 不把零行改写报成新结算。`null`(正常收口)⇒ 无该段。
304
+ * @param {{rows:number, date:string}|null} result */
305
+ export function repairReceiptLine(result) {
306
+ if (!result) return ""
307
+ return `\n[ledger repair] 全归档补关:本批 ${result.rows} 行全归档(已核销 / 已废弃)· 台账行零改写 · §3/§4/§6 未补写 · §1 段尾已追加一行 补关记录(${result.date})`
308
+ }
309
+
310
+ /**
311
+ * 判据 2 的块内裁定读数(设计档 §2.6「pass 谓词」):`null` = pass;否则 = 拒文括注里的那一格。
312
+ * 组合序不在本档——一律取骨架档 `verdictGapOf`(判据单源,设计档 §2.6.1):写面、`§5` 门与签发面三处同读
313
+ * 一个函数,锚与顺序都只有那一份。本函数只留名字:拒文(`R-G2b`)与设计档用的就是这个符号,读者按它对账。
314
+ * 块 = `null`(段内无块)⇒ `verdictGapOf(null)` = 「无裁定行」,与改前同值。
315
+ * @param {string|null} block — `lastRoundBlock(src, 3)` 的返回形
316
+ * @returns {string|null} 拒文括注值 ∥ `null`(块自己说了 pass)
317
+ */
318
+ function lastRoundVerdictGap(block) {
319
+ return verdictGapOf(block)
320
+ }
321
+
322
+ /** 判据 2 拒文(设计档 §2.6 `R-G2b` 逐字;`blocks` = 段内轮次块数——无块时取 0)。
323
+ * `gap` = `lastRoundVerdictGap` 的非空返回形,落进括注的裁定格。 */
324
+ function sectionFiveVerdictBlockError(src, gap) {
325
+ const blocks = countRoundBlocks(src, 3)
326
+ return "batch: §5 append refused — the last §3 round block carries no pass verdict " +
327
+ `(§3 最近一轮轮次块 = 第 ${blocks} 轮,块内裁定 = ${gap}). A pass means that block carries a \`VERDICT: pass\` line and no changes-required line — ` +
328
+ "a round that does not state a pass is not a pass: append the verdict line to that block (`VERDICT: pass`),或按裁定行重跑评审。Nothing was written."
329
+ }
330
+
331
+ /**
332
+ * §5 写入门(段序门 · 设计档 §2.6):实现发生在评审通过之后,序在这里才判得出真假。
333
+ * 判据 = 两条合取(**没有第一条的旁路**:`§1` 声明 §3 不适用已随声明机制退役——实现只发生在评审之后),
334
+ * 先判状态词、过了再判块(状态词不过时拒文已足以说明,不必再报块):
335
+ * ① `§3` 状态行 = `评审通过`(拒文 `R-G2`);
336
+ * ② `§3` **最近一轮轮次块自己携 pass 裁定行**(拒文 `R-G2b`)——评审写了一笔 `§3` 却不带任何裁定行时,
337
+ * 上一轮的 `评审通过` 仍是字面字,只判 ① 就会放行。② 只问一个可读的事实「门所依赖的块自己有没有
338
+ * 说结论」,不猜意图(补记 ∥ 隐性打回的处置是同一条);`§3` 无任何轮次块 ⇒ ② 不成立、照拒——
339
+ * 真跑过的 pass 必落本轮块,无块即无 pass 可依。
340
+ * 修正轮在 §3 已 pass 之后追加 §5,末块携 pass 裁定 ⇒ 两判据当场成立。`status` 单写不再足以开 `§5`(只置状态词、不落一块携 pass 裁定的
341
+ * 轮次块 ⇒ 照拒)。
342
+ * @param {string} src — 写盘前的档全文
343
+ */
344
+ export function assertSectionFiveGate(src) {
345
+ const s3 = readSectionStatusWord(src, 3)
346
+ if (s3 !== STATUS_WORDS[3].done) {
347
+ throw new Error("batch: §5 append refused — the implementation section opens only after the design review passed " +
348
+ `(§3 状态行 = ${s3 ?? "(无状态行)"},须 = 评审通过). Nothing was written.`)
349
+ }
350
+ const gap = lastRoundVerdictGap(lastRoundBlock(src, 3))
351
+ if (gap !== null) throw new Error(sectionFiveVerdictBlockError(src, gap))
352
+ }
353
+
354
+ /** 收口重锚回执段(设计档 §2.17 收口步序 7)——**逐行点名每一枚被结清的行,两种起点各一行**:
355
+ * `<#id> 在途 → 待核销 → 已核销` 与 `<#id> 待核销 → 已核销`。后者是「已做完、没结账」的行被静默结清,
356
+ * 不点名就平账了(口径同 `docs/core/design/LEDGER.md` §3.3 安全阀)。
357
+ * 台账失败不再走本段:失败 ⇒ 补偿回滚档 + 抛拒(`closeLedgerFailedError` / `closeHalfStateError`),
358
+ * 收口那次调用根本没有回执。`conditioned` = 本批未动行改挂条件的既有段。
359
+ * @param {{settled?:Array, conditioned?:Array}|null} result — `ledgerReanchorBatch` 返回形
360
+ */
361
+ export function reanchorReceiptLine(result) {
362
+ if (!result) return ""
363
+ const face = (r) => `#${r.id} 「${r.title}」`
364
+ const lines = (result.settled ?? []).map((r) =>
365
+ `\n[ledger reanchor] ${face(r)} ${r.from === "在途" ? "在途 → 待核销 → 已核销" : "待核销 → 已核销"}`)
366
+ const conditioned = result.conditioned ?? []
367
+ if (conditioned.length) {
368
+ lines.push(`\n[ledger reanchor] 本批未动行 → 条件 ${conditioned.length} 行:${conditioned.map(face).join(";")}` +
369
+ " —— 已落 trigger = 条件 + 复启句,由下一批接手")
370
+ }
371
+ return lines.join("")
372
+ }
373
+
374
+ /** 收口台账失败拒文(设计档 §2.17 收口步序 6 第一条串,逐字):档已回滚到写前字节 ⇒ 可原样重试。 */
375
+ export function closeLedgerFailedError(cause) {
376
+ return `batch: close failed — 台账事务未提交(${cause});批档已回滚到写前字节,可原样重试。Ledger: no committed change from this call (it never reached COMMIT).`
377
+ }
378
+
379
+ /** 收口补偿也失败拒文(同节第二条串,逐字——**不得复用第一条**:第一条声称已回滚,此时事实相反):
380
+ * 批档可能仍为已收口;是否半状态由 `check` 按实际行集判,全归档终态不重试,其余残态先修账再重开。 */
381
+ export function closeHalfStateError(abs, cause, rollbackCause) {
382
+ return `batch: close failed — 台账事务未提交(${cause});批档回滚也失败(${rollbackCause})——批档可能仍为已收口。` +
383
+ `Read it with batch({action:"check", path:"${abs}"}); if consistent=false, repair the ledger and reopen before retrying; if consistent=true, the batch is already closed and settled — do not retry.`
384
+ }
385
+
386
+ /** `[ledger consistency]` 行(设计档 §2.17「暴露面两处」第二条):`close` ∥ `reopen` ∥ `status` 回执末尾
387
+ * **恒带一行**——一致 ⇒ `一致(本批 N 行)`;不一致 ⇒ 逐项点名 + 出路。查询面单源 =
388
+ * `batchLedgerConsistency`(本档只格式化,不另判)。 */
389
+ export function consistencyReceiptLine(result) {
390
+ if (!result) return ""
391
+ // 读不出(台账库坏 / 打不开)⇒ 如实点名,**不吞成「一致」**:一条说「一致」却根本没读的读数,
392
+ // 比没有这行更坏——它正是本批要消掉的静默。
393
+ if (result.error) return `\n[ledger consistency] 读不出(${result.error})——半状态面不可用,按批档 §1 与台账行各自的状态自行核对`
394
+ if (result.consistent) return `\n[ledger consistency] 一致(本批 ${result.rows.length} 行)`
395
+ const items = result.halfStates.map((h) =>
396
+ `\n ${h.name}${h.rows.length ? ` #${h.rows.join(" · #")}` : ""}——出路:${h.exit}`)
397
+ return `\n[ledger consistency] 不一致(本批 ${result.rows.length} 行):${items.join("")}`
398
+ }
399
+
400
+ /** `batch({action:"check"})` 回执(设计档 §2.17「暴露面两处」第一条):逐行打印查询面读数——`record`
401
+ * 三态、行集逐行 `{id, status, trigger, title}`、档头号集 `{id, inLedger}`、半状态项与出路、`consistent`。只读动作,零写。 */
402
+ export function checkReceipt(result, abs) {
403
+ const lines = [
404
+ `batch: ledger consistency — ${abs}`,
405
+ ` record = ${result.record} · rows = ${result.rows.length} · consistent = ${result.consistent}`,
406
+ ...result.rows.map((r) => ` #${r.id} ${r.status} 「${r.title}」 · trigger = ${r.trigger ?? "—"}`),
407
+ ...(result.headerRows ?? []).map((h) => ` headerRows #${h.id} inLedger = ${h.inLedger}`),
408
+ ]
409
+ return lines.join("\n") + consistencyReceiptLine(result)
410
+ }
411
+
412
+ /** 新事理由的 `evidence` 前缀(单源 = `docs/core/design/LEDGER.md` §6.3「参数面」;写入侧由
413
+ * `thincoder-core/ledger-write-ops.mjs` 的 `NEW_DEBT_EVIDENCE_PREFIX` 造,本档按同一字面取文)。 */
414
+ const NEW_DEBT_PREFIX = "新事理由:"
415
+ /** `evidence` 追加相接符(追加形 `旧|新` 零空格——§6.3「取文」)。 */
416
+ const EVIDENCE_JOINER = "|"
417
+
418
+ /**
419
+ * 取一行新事理由(设计档 §6.3「取文」):`evidence` 中 `新事理由:` 之后、至首个 `|`(追加相接符)
420
+ * 或串尾的一段。无该前缀 ∥ 取到空串 ⇒ `null`(负向锁:不是本机制写的行不引)。**只读**——不改入参。
421
+ * @param {string|null} evidence — 行 `evidence` 原值
422
+ * @returns {string|null} 理由原文 ∥ `null`
423
+ */
424
+ export function newDebtReasonOf(evidence) {
425
+ const s = String(evidence ?? "")
426
+ const at = s.indexOf(NEW_DEBT_PREFIX)
427
+ if (at < 0) return null
428
+ const rest = s.slice(at + NEW_DEBT_PREFIX.length)
429
+ const cut = rest.indexOf(EVIDENCE_JOINER)
430
+ const value = (cut < 0 ? rest : rest.slice(0, cut)).trim()
431
+ return value === "" ? null : value
432
+ }
433
+
434
+ /**
435
+ * 收口回执的新事理由引文段(逐字 = 设计档 §6.3「理由的读面与时点」:` 新事理由(#<id>):<理由原文>`)。
436
+ * 读者 = 本批收口那一笔的主 agent · 时点 = 本批收口。**零新清单、只引不写**:纯格式化、零库访问、
437
+ * 不改入参;一条理由一行。取不到本批行 ⇒ 入参无该键 ⇒ 不出该段(收口不被否决)。
438
+ * @param {{newDebtReasons?:{id:number, reason:string}[]}|null} result — `reanchorOnClose` 返回形
439
+ * @returns {string} 以换行起头;无引文 ⇒ 空串
440
+ */
441
+ export function newDebtReasonReceiptLine(result) {
442
+ const rows = result?.newDebtReasons ?? []
443
+ return rows.map((r) => `\n 新事理由(#${r.id}):${r.reason}`).join("")
444
+ }