@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
@@ -11,12 +11,30 @@
11
11
  * (设计档 ENG-TOKEN-BINDING.md §5.1——不经 advisor-async re-export)。
12
12
  */
13
13
 
14
- import { randomUUID } from "node:crypto"
14
+ import { createHash, randomUUID } from "node:crypto"
15
+ import { readFileSync, writeFileSync } from "node:fs"
16
+ import { parse, resolve } from "node:path"
15
17
  import { tokenExpiryMs } from "../token-ttl.mjs"
16
- // 批归属派生(DESIGN-TOKEN-SETTLEMENT §10)——判据与清点面同源(同一个 `lastIndexOf("batches")`)。
18
+ // 评审封印的「被审档」面判:批档面(`docRoot.batches` 之下)排除——判据与 doc-check 的批档面
19
+ // 同源(`batchDirs` 一处),本档不自持第二份「哪个目录算批档」的判定(§10.2 被算集合)。
20
+ import { isBatchFace } from "../doc-check/existence.mjs"
21
+ import { owningProject } from "../manifest-discovery.mjs"
22
+ // 段面读判据单源(骨架档):轮次块计数 ∥ 下一轮 N ∥ 段级状态行 ∥ §3 完成词——结算写块与写入面读同一形态。
23
+ // 裁定行锚(`_V_PRE` / `_V_SUF` / `VERDICT_CHANGES_LINE`)同住骨架档锚块,组合序也只在那一档(`verdictGapOf`):
24
+ // 本档的裁定闸判据、写入面(`append §3` 的打回重置 `statusResetPlan`)与 `§5` 写入门读同一个函数——
25
+ // 锚与序都只此一份,三处不各写一遍。
26
+ import { countRoundBlocks, nextRoundNumber, readSectionStatusWord, STATUS_WORDS, statusPassPlan, statusResetPlan, updateSectionStatusLine, VERDICT_PASS_LINE, verdictGapOf } from "./batch-skeleton.mjs"
27
+ // 段尾追加(`appendLineToSection`)与日期戳(`todayLocal`)单源 = 重开档:结算的轮次块落进 §3 也是
28
+ // 「段尾追加、既有字节零变」那一条判据,块形另有单源(`design-review-record.mjs`)。
29
+ import { appendLineToSection, todayLocal } from "./batch-reopen.mjs"
30
+ // 块文成形单源(叶档、纯函数、零 fs):工具戳 + 结算头 + 本轮结论三件(结论表 → 裁定行 → 计数行),
31
+ // 单源 = `BATCH-RECORD.md` §4.4。
32
+ import { designReviewBlock, verdictLineOf, DISPOSITION_PASS, DISPOSITION_CHANGES_REQUIRED, DISPOSITION_NO_PASS_LINE, DISPOSITION_NO_ECHO } from "./design-review-record.mjs"
33
+ // 批归属派生(DESIGN-TOKEN-SETTLEMENT §10)——两源定序 `batchAbsPathOfRun`:`run.batchDoc` 优先、
34
+ // `docSetKey` 的批档兜底(判据与清点面同源)。
17
35
  // 本档 ⇄ `design-slots.mjs` 为**静态环**(对方取 `effectiveTokenTtlMs`):两侧绑定只在函数体内
18
36
  // 运行时使用,求值期零顶层调用 ⇒ 环安全(与 token-ttl ⇄ session 同构)。
19
- import { batchAbsPath } from "./design-slots.mjs"
37
+ import { batchAbsPathOfRun } from "./design-slots.mjs"
20
38
 
21
39
  /**
22
40
  * F2c/F2e (§29.1 2026-09-07): the engine-generated Approved suffix — ONE builder
@@ -104,82 +122,342 @@ const TRUNCATED_ECHO_MARK = "注:回显被截断(uuid 之后缺失或不符
104
122
  // 裁定行接受本地化等价形(GitHub #32 / #14):评审席用中文回执很常见,
105
123
  // 只认英文会让 pass 落成 no-pass-line、凭证永不签发;判据仍只认整行逐字面,
106
124
  // 不做「句中含『通过』」这类模糊匹配——那样会把「未通过」也放过。
107
- const _V_PRE = "^[ \\t]*[*_`]*[ \\t]*"
108
- const _V_SUF = "[ \\t]*[*_`]*[ \\t]*$"
109
- const VERDICT_PASS_LINE = new RegExp(
110
- _V_PRE + "(?:VERDICT:[ \\t]*(?:pass|通过|通过。)|结论[::][ \\t]*(?:通过|pass))" + _V_SUF, "mi")
111
- const VERDICT_CHANGES_LINE = new RegExp(
112
- _V_PRE + "(?:VERDICT:[ \\t]*(?:changes-required|不通过|需修改)|结论[::][ \\t]*(?:不通过|需修改|changes-required))" + _V_SUF, "mi")
125
+ // 四条锚与两条裁定正则全住骨架档锚块(`batch-skeleton.mjs`),裁定读数单源 = 同档 `verdictGapOf`:
126
+ // 本档、`§5` 写入门与 `append §3` 的通过置位读同一个函数(判定单源,零复制)。
127
+ // pass 锚经本档**原样再导出**——`batch-closeout.mjs` 的 import 面零改。
128
+ export { VERDICT_PASS_LINE }
129
+ /** 裁定闸的拒因(§5.2 #940):对外只两个词,`changes-required` ∥ `no-pass-line`——本批改的是判据来源,
130
+ * 不是这两个词。四格映射(`verdictGapOf` 值域 → 拒因):
131
+ * - `null`(说了 pass)⇒ `null`(签发);
132
+ * - `「VERDICT: changes-required」` ∥ `「两者同携」` ⇒ `changes-required`——同携今天就走这一格
133
+ * (改前打回锚先命中即判打回),组合序挪进函数后这张表照旧;
134
+ * - `「无裁定行」` ⇒ `no-pass-line`。 */
113
135
  export function verdictGateFailure(rawResult) {
114
136
  if (typeof rawResult !== "string") return "no-pass-line"
115
- if (VERDICT_CHANGES_LINE.test(rawResult)) return "changes-required"
116
- return VERDICT_PASS_LINE.test(rawResult) ? null : "no-pass-line"
137
+ const gap = verdictGapOf(rawResult)
138
+ if (gap === null) return null
139
+ return gap === "无裁定行" ? DISPOSITION_NO_PASS_LINE : DISPOSITION_CHANGES_REQUIRED
117
140
  }
118
141
 
119
142
  /** §5.2 rejection mark (verbatim — machine-greppable; reason = no-pass-line | changes-required). */
120
143
  const VERDICT_GATE_MARK = (reason) => `裁定非通过——token 未签发 (review verdict is not pass — no design token was issued; reason: ${reason}; the echoed token was stripped)`
121
144
 
145
+ /** 非签发处置各自的回执尾(逐字——机器可 grep):回显失败、裁定闸两词、宿主不完整族。 */
146
+ function nonIssueMark(disposition) {
147
+ if (disposition === DISPOSITION_NO_ECHO) return NO_VALID_ECHO_MARK
148
+ if (disposition === DISPOSITION_CHANGES_REQUIRED || disposition === DISPOSITION_NO_PASS_LINE) {
149
+ return VERDICT_GATE_MARK(disposition)
150
+ }
151
+ return `评审未完成——token 未签发 (review incomplete — no design token issued; reason: ${disposition})\n以更小范围重跑设计评审(逐档 / 逐节拆分,或拆到两次评审),或调大 agent.advisor.timeoutMs 后重试;补充检查未完成的部分不得按已核处理。`
152
+ }
153
+
154
+ /** §3 记录判据的拒因(ADVISOR-GUARDS.md §1.2——两值;判据 1 的「批档可读」与判据 2 的「写进并回读」,
155
+ * 两者都在任何写之前 ∥ 写坏之后现形)。 */
156
+ const RECORD_STATUS_NOT_PASSED = "status-not-passed"
157
+ const RECORD_BATCH_UNREADABLE = "batch-unreadable"
158
+
159
+ /** §3 记录判据 rejection mark (verbatim — machine-greppable; reason = 上两值之一)。与裁定闸同形:
160
+ * 槽零写、实例不翻 open——标记即回执,不进 `settlementCriterion`(§7 不新增判据值)。
161
+ * **恒定位 = 上方两行逐字不动**;`evidence`(可执行证据 = 当前状态行 ∥ 轮次块数 ∥ 写面通道)
162
+ * 另起一行落在其后——指名当前值,但不把证据塞进那个机器可 grep 的括号里。 */
163
+ const REVIEW_RECORD_MARK = (reason, evidence) => `评审记录不合格——token 未签发 (review record incomplete — no design token was issued; reason: ${reason})\n本轮块与状态行由结算写进该批档 §3:那一笔没落成,整笔已回写到写前(零字节写入,槽零写)。修好该档(可读 ∥ 可写)后重跑设计评审——评审席自己写 §3 的那条通道在工程模式已收回。${evidence ? `\n证据:${evidence}` : ""}`
164
+
165
+ /** §10.2 封印在结算面算不出(被审档读不到)的恒定标记(逐字可 grep):结算拒签、零字节写、可重评。
166
+ * **为什么是返回的拒签而不是 throw**:这是**数据条件**(评审看过的那份档在结算前被移走 / 锁住),
167
+ * 不是接线故障——读回执的人要的是一句话与下一步。throw 会穿过 `settleAdvisorRun` 的
168
+ * `onAccounting` 钩子(那里没有 catch),跳过结算尾(挂起 / 事件 / 唤醒 / 补位),把一个可重评的
169
+ * 拒签变成一次未捕获异常。位置 = 任何写之前(§3 签字与槽都在它之下)。 */
170
+ const SEAL_UNREADABLE_MARK = (path) => `评审封印无法计算——token 未签发 (the review seal cannot be computed — no design token was issued: the reviewed document ${path} cannot be read; restore that file, or re-run the review; nothing was written)`
171
+
172
+ /** 写档字节的**单通道**(模块级引用):初值 = `fs.writeFileSync` 本体,生产路径从不替换。
173
+ * 结算签字与落盘失败后的回退写都经这一个引用 ⇒ 两条写都只有一条路径,单测也能对两笔同时注入失败
174
+ * (「写抛错」∥「只写半截」),不必去动盘上的权限——不可写的地方先不可读,落到的是 `batch-unreadable`。 */
175
+ let recordWriter = writeFileSync
176
+ /** 测试缝(生产路径不调):换掉写通道;传非函数 ⇒ 还原本体(用例 `t.after` 收尾)。 */
177
+ export function __setRecordWriterForTest(fn) {
178
+ recordWriter = typeof fn === "function" ? fn : writeFileSync
179
+ }
180
+
181
+ /** 评审封印的字节口径(DESIGN-TOKEN-SETTLEMENT §10.2,单源——settle 与 spawn 两侧同调本函数):
182
+ * 按 `docs` 数组顺序逐档读**原始字节**,档与档之间放一个 `\n`,路径不进 hash;算法 = sha256。
183
+ * 读不到(缺档 ∥ 权限错)⇒ 抛,`err.sealPath` = 那一份读不到的档的路径(拒文要点它的名)——
184
+ * 「判不了」与「一致」是两件事,闸面按 fail-closed 处置。
185
+ * @param {string[]} docs 被审档绝对路径(顺序 = settle 时记下的顺序)
186
+ * @returns {string} sha256 十六进制 */
187
+ export function designSealHash(docs) {
188
+ const h = createHash("sha256")
189
+ docs.forEach((p, i) => {
190
+ let buf
191
+ try {
192
+ buf = readFileSync(p)
193
+ } catch (e) {
194
+ const err = new Error(`design seal: the reviewed document cannot be read (${p}: ${e?.message ?? e})`)
195
+ err.sealPath = p
196
+ err.cause = e
197
+ throw err
198
+ }
199
+ if (i > 0) h.update("\n")
200
+ h.update(buf)
201
+ })
202
+ return h.digest("hex")
203
+ }
204
+
205
+ /** 逐档 hash(DESIGN-TOKEN-SETTLEMENT §10.2「清单与 hash 一起存进槽」):单档**原始字节**的 sha256,
206
+ * 与 `designSealHash` 同一读取面、同一失败形(读不到 ⇒ 抛,`err.sealPath` = 那一份档的路径)。
207
+ * 它只服务拒文点名:判定值仍是组合 `hash`,这一列不参与任何判定。
208
+ * @param {string} absPath 被审档绝对路径
209
+ * @returns {string} sha256 十六进制 */
210
+ export function designDocHash(absPath) {
211
+ let buf
212
+ try {
213
+ buf = readFileSync(absPath)
214
+ } catch (e) {
215
+ const err = new Error(`design seal: the reviewed document cannot be read (${absPath}: ${e?.message ?? e})`)
216
+ err.sealPath = absPath
217
+ err.cause = e
218
+ throw err
219
+ }
220
+ return createHash("sha256").update(buf).digest("hex")
221
+ }
222
+
223
+ /** 封印行的逐档列(§10.2):按 `docs` 原序逐档各算一次,成形 = `[{ path, hash }]`。
224
+ * @param {string[]} docs 被审档绝对路径(顺序 = settle 时记下的顺序)
225
+ * @returns {{path: string, hash: string}[]} */
226
+ export function designDocHashes(docs) {
227
+ return docs.map((p) => ({ path: p, hash: designDocHash(p) }))
228
+ }
229
+
230
+ /** 该次评审的封印文档集 = 被审文档集里的**非批档**(§10.2「被算集合」):
231
+ * 批档评审通过后还要被写(§5 ∥ §6),把它算进封印就是让每一次正常收口都自毁封印。
232
+ * 「哪一份是批档」的判据不在这里新定义——`isBatchFace` 是 doc-check 那一侧同一个批档面谓词
233
+ * (`docRoot.batches` 一处;显式 `null` = 本面无)。项目根按每份档自己上溯(多仓评审各归各仓)。
234
+ * 清单来源**首选** = 受理面同一把尺解析出的受理绝对路径(`run.docAbs`,`advisor-async.mjs` 起评时落);
235
+ * 只有旧实例 ∥ 手建实例没有它时才退回实例键 `docSetKey`(`normAbs` 的 cwd 拼法——cwd 非项目根时
236
+ * 与受理路径可不同)。顺序与去重:沿用来源的序;同档多种写法按平台大小写归一后去重。 */
237
+ function sealDocSetOf(run) {
238
+ let list = null
239
+ if (Array.isArray(run?.docAbs)) list = run.docAbs
240
+ else { try { list = JSON.parse(run?.docSetKey ?? "null") } catch { return [] } }
241
+ if (!Array.isArray(list)) return []
242
+ const out = []
243
+ const seen = new Set()
244
+ for (const raw of list) {
245
+ if (typeof raw !== "string" || !raw.trim()) continue
246
+ const abs = resolve(raw)
247
+ const key = process.platform === "win32" ? abs.toLowerCase() : abs
248
+ if (seen.has(key)) continue
249
+ seen.add(key)
250
+ const root = owningProject(abs, parse(abs).root)
251
+ if (root && isBatchFace(abs, root)) continue
252
+ out.push(abs)
253
+ }
254
+ return out
255
+ }
256
+
122
257
  /**
123
- * Shared design-review settlement (sync wrapper + async settle): the token echo
124
258
  * IS the verdict — the advisor echoes it only on approval. On echo (full string
125
259
  * OR truncated — uuid present; §5.1①): slot the token under designId (always the
126
260
  * FULL token; + eng-coder gate flag; single-value mirror retired per
127
261
  * DESIGN-TOKEN-SETTLEMENT D3), record its batch attribution (`_engDesignTokenBatches`
128
- * — the reviewed doc-set's `batches/` file, §10 E1; no batch in the set ⇒ no
129
- * attribution) and return the clean output with the
262
+ * — `batchAbsPathOfRun(run)`: the instance's bound `batchDoc`, else the reviewed doc-set's
263
+ * `batches/` file, §10; neither ⇒ no attribution), seal the reviewed documents
264
+ * (`_engDesignTokenSeals` — the non-batch documents' sha256 + their list + the per-document
265
+ * hashes the refusal names, §10.2; an empty set drops the previous seal for this designId)
266
+ * and return the clean output with the
130
267
  * Approved suffix (truncated echo: the M2 marker sits before the suffix); the review
131
268
  * instance CLOSES (a later review of the same doc-set starts a fresh full
132
269
  * review). On non-echo: strip every echo form (single source §5.1③) and return
133
270
  * the findings text + the constant M1 marker — slots stay untouched
134
- * (方案 ②: a failed re-review revokes nothing).
271
+ * (方案 ②: a failed re-review revokes nothing). Whichever way it goes, this round's
272
+ * block lands in the record first (the settlement writes it; the `@remarks` below
273
+ * holds the order of the criteria).
135
274
  * @param {Object} [opts] — 第 11 批(A/F11):`opts.incomplete` = 宿主尾族判定 kind
136
275
  * (单谓词 `advisorIncompleteMarker`——结算方透传)。非空 ⇒ **一律不签发**(无论评审文本
137
276
  * 是否回显 token):剥除全部 token 回显 + 追加未签发提示(原因 + 恢复指引),不写槽、
138
- * 不关实例(可重评)。
139
- * @returns {{passed: boolean, output: string}}
277
+ * 不关实例(可重评);块照旧落(§4.4 该族一段),状态行不动。
278
+ * @remarks §3 记录判据(`ADVISOR-GUARDS.md` §1.2)——本函数**自己写**本轮的轮次块:块形 = 工具戳 +
279
+ * 结算头 + 本轮结论三件(结论表 → 裁定行 → 计数行,`design-review-record.mjs`),N 取 `nextRoundNumber`;
280
+ * 块与状态行进同一个字符串、经同一条写通道一次落盘、一次回读(一笔的顺序与回退 = `docs/core/design/BATCH-RECORD.md` §4.23)。
281
+ * **前置 = 绑了批档**(`run.batchDoc` 非空)——设计评审必携 `batchDoc`(准入门,判据 = 同档 §2 第 6 条)
282
+ * ⇒ 到结算面仍为空只是接线故障,在 `boundBatch` 判定处断言并 throw(程序不变量,早于读档与写槽;
283
+ * 不设对外拒因值,不返回判决)。
284
+ * §1.2 判据按序:① 批档可读——读不到 ⇒ `batch-unreadable`,零字节写;② 本轮块写进 §3 且回读见到它,
285
+ * pass 路径的段级状态行回读为「评审通过」,否则 ⇒ `status-not-passed` 并写回写前原文。
286
+ * 处置四词与宿主不完整族的 kind 词(`pass` ∥ `changes-required` ∥ `no-pass-line` ∥ `no-valid-echo`
287
+ * ∥ 该 kind 词)**都落一块**,凭证结局写进结算头;封印算不出(被审档在结算前变了)不落块、零字节写
288
+ * (§10.2 与 §4.4 KD5)。
289
+ * §10.2 封印算不出 ⇒ `{passed:false, sign:null}` + 恒定标记,且在任何写入之前返回。
290
+ * @returns {{passed: boolean, output: string, sign: {before: string, rollback: () => void}|null}} —— `sign` 非空 =
291
+ * 本笔在该批档上落了本轮的块(+ 按处置改写的状态行):`before` = 写前原文(落盘失败时写回它),
292
+ * `rollback()` = 写回那一笔(写通道单源 = 本模块的 `recordWriter`,故回退走同一个注入点)。
293
+ * 一个字节都没落盘(被任一前置拒)⇒ `sign: null`。
140
294
  */
141
295
  export function settleDesignReview(agent, run, designToken, rawResult, opts = {}) {
142
296
  if (!designToken || typeof rawResult !== "string") {
143
- return { passed: false, output: rawResult ?? "" }
297
+ return { passed: false, output: rawResult ?? "", sign: null }
144
298
  }
145
299
  // A(F11/ADVISOR-GUARDS.md §1 消费点 1):未完成即不签发——判据与 code 完成守卫同源(单谓词)。
146
300
  const incomplete = opts?.incomplete ?? null
147
- if (incomplete) {
148
- const stripped = stripDesignTokenEcho(rawResult, designToken).trim()
149
- return {
150
- passed: false,
151
- output: `${stripped}\n\n评审未完成——token 未签发 (review incomplete — no design token issued; reason: ${incomplete})\n以更小范围重跑设计评审(逐档 / 逐节拆分,或拆到两次评审),或调大 agent.advisor.timeoutMs 后重试;补充检查未完成的部分不得按已核处理。`.trim(),
152
- }
153
- }
154
- // §5.1① 截断容忍:全串匹配 ∨ 截断形(本 token 的 uuid 值出现——空 uuid 不构成「值」)
155
- // ⇒ 认 pass;两者皆无 ⇒ fail + 恒定 M1(含正文为空——N7 零静默)。
301
+ // ── 处置(ADVISOR-GUARDS.md §1.2 + `BATCH-RECORD.md` §4.4):先把处置算完——回显 → 裁定 ──
302
+ // 值域 = 处置四词 + 宿主不完整族的 kind 词:所有处置**都落一块**(判的是当前状态的评审都落一块——
303
+ // 记录不拿凭证结果当过滤条件,凭证结局写在结算头)。不完整族优先占这一格:那一轮的正文可能缺半,
304
+ // 处置词读不出可信的结论;它与裁定闸同走一条落块路,不另开一个早退分支。
305
+ // §5.1① 截断容忍:全串匹配 ∨ 截断形(本 token 的 uuid 值出现——空 uuid 不构成「值」)⇒ 认回显;
306
+ // 两者皆无 ⇒ `no-valid-echo`(含正文为空——N7 零静默)。
156
307
  const uuid = String(designToken).split(":")[0]
157
308
  const fullEcho = makeDesignTokenRegex(designToken).test(rawResult)
158
309
  const truncatedEcho = !fullEcho && uuid.length > 0 && rawResult.includes(uuid)
159
- if (!fullEcho && !truncatedEcho) {
160
- const stripped = stripDesignTokenEcho(rawResult, designToken).trim()
161
- return { passed: false, output: [stripped, NO_VALID_ECHO_MARK].filter(Boolean).join("\n\n") }
310
+ const disposition = incomplete
311
+ ? incomplete
312
+ : (!fullEcho && !truncatedEcho)
313
+ ? DISPOSITION_NO_ECHO
314
+ : (verdictGateFailure(rawResult) ?? DISPOSITION_PASS)
315
+ const issuing = disposition === DISPOSITION_PASS
316
+ // 凭证不落档:块取的是**剥净回显**的评审原文末尾那张结论表(剥除单源 §5.1③);回给父侧的 `output`
317
+ // 仍带剥净回显的全文——原文不丢,只是不进块。
318
+ const stripped = stripDesignTokenEcho(rawResult, designToken).trim()
319
+ // 结算写 `§3` 只在工程模式的**设计轨**(`BATCH-RECORD.md` §4.4 ∥ `ADVISOR-GUARDS.md` §1.2 的第一句):
320
+ // 普通模式没有设计结算进场,`§3` 由绑定评审席位自己写(那一路的写通道保留)——留两个写者就有两块一轮。
321
+ // 判据放在**读档之前**:不进写面就一个字节都不碰,也不做「写了半笔再跳过」。
322
+ const engineering = !!agent?.config?.agent?.engineering
323
+ // 前置 = 绑了批档,**程序不变量、不是拒发分支**:设计评审必携 `batchDoc`(准入门,判据 = 同档 §2 第 6 条)
324
+ // ⇒ 到结算面仍为空只能是「绑定没传到实例」的接线故障 ⇒ 断言并 throw(串点名设计评审实例 + designId),
325
+ // 零槽写、不返回判决、不设对外拒因值。给没发生过的情形配文案就是没有场景的分支;接线 bug 该炸得响,
326
+ // 不该伪装成一条给用户看的拒因(本批 🔴1 裁定)。
327
+ // 位置 = 读档 ∥ 写块 ∥ 写槽之前:落在其后就没拦——token 已在槽里、授权照发。
328
+ // 调用点不得补 catch 后继续——控制流会落回 `set(...)` ⇒ token 照签、零报错、只留一条日志。
329
+ const boundBatch = typeof run?.batchDoc === "string" && run.batchDoc.trim() ? run.batchDoc : null
330
+ if (!boundBatch) {
331
+ throw new Error(`design review settled with no batch-record binding (designId: ${run?.designId ?? "(none)"}) — a design review is launched with \`batchDoc\` required, so settling without it is a wiring fault, not an input to report.`)
162
332
  }
163
- // §5.2 裁定闸(#940):签发 = 回显 ∧ 裁定行——缺 `VERDICT: pass` 行或含 `VERDICT: changes-required` 行
164
- // ⇒ 拒签(与 M1 径同形:剥净回显 + 恒定标记;槽零写 ∥ 实例保持——修后重评)。
165
- const gateFailure = verdictGateFailure(rawResult)
166
- if (gateFailure !== null) {
167
- const stripped = stripDesignTokenEcho(rawResult, designToken).trim()
168
- return { passed: false, output: [stripped, VERDICT_GATE_MARK(gateFailure)].filter(Boolean).join("\n\n") }
333
+ // §10.2(DESIGN-TOKEN-SETTLEMENT)评审封印:**先算,后写**。被审档读不到 ⇒ 结算拒签(恒定标记),
334
+ // 且在任何写入之前返回——它判的那份状态已不在,落了就把作废结论写成结论(§4.4 KD5;陈旧评审在
335
+ // `settleAdvisorRun` 的 stale 支就不进本函数,同一判据的另一半)。两种模式都算:封印是签发的凭据面。
336
+ // 不抛的理由 = 文件头标记注释;被算集合 = 被审文档集里的非批档;口径单源 = `designSealHash`。
337
+ const sealDocs = sealDocSetOf(run)
338
+ let sealHash = null
339
+ let sealDocHashes = []
340
+ if (sealDocs.length > 0) {
341
+ try {
342
+ sealHash = designSealHash(sealDocs)
343
+ // 逐档列与组合值同一个 `try`:两笔都是「读被审档」,读不到时同一条拒签出去(§10.2)。
344
+ sealDocHashes = designDocHashes(sealDocs)
345
+ } catch (e) {
346
+ return { passed: false, output: [stripped, SEAL_UNREADABLE_MARK(e?.sealPath ?? "(unknown)")].filter(Boolean).join("\n\n"), sign: null }
347
+ }
169
348
  }
349
+ // ── 一次写:块与状态行进同一个字符串,经**同一条**写通道(`recordWriter`)一次落盘 ──
350
+ // 只在工程模式的设计轨(上面那一句判);普通模式整段跳过、`sign` 留 `null`——那一路的 `§3` 由绑定评审席位写,
351
+ // 连读都不必(读了也没有要判的对象,把「读不到 ⇒ batch-unreadable」搬到普通模式只是给一个没有写面的路配拒因)。
352
+ let sign = null
353
+ if (engineering) {
354
+ // 判据 1(§1.2 第 1 条):批档可读——读不到 ⇒ `batch-unreadable`,零字节写(块 ∥ 状态行 ∥ 槽都不动)。
355
+ let batchSrc = null
356
+ try {
357
+ batchSrc = readFileSync(boundBatch, "utf8")
358
+ } catch (e) {
359
+ return {
360
+ passed: false,
361
+ output: [stripped, REVIEW_RECORD_MARK(RECORD_BATCH_UNREADABLE, `批档读不到: ${e?.code ?? e?.message ?? "unknown"}`)].filter(Boolean).join("\n\n"),
362
+ sign: null,
363
+ }
364
+ }
365
+ // 块由结算成形(`designReviewBlock`:工具戳 + 结算头 + 本轮结论三件),N 取 `nextRoundNumber`
366
+ // (与 `append §3` 的盖戳同一枚计数),不另立第二套。段尾追加用 `appendLineToSection`(既有字节零变),
367
+ // 状态行仍**只经 `updateSectionStatusLine` 这一个写入函数**改写——零新写路径、零新解析。
368
+ // 裁定行由结算按本轮处置给(不从评审体里挑):块内裁定、结算头与凭证结局三处同源。
369
+ // 状态行按处置写:`pass` 走 `statusPassPlan`(已是完成词则零写,幂等),`changes-required` 走
370
+ // `statusResetPlan`(重置为进行中,块首不再另留痕行——本轮结论由结算头与块内三件承载),其余处置不动它。
371
+ const date = todayLocal()
372
+ const eol = batchSrc.includes("\r\n") ? "\r\n" : "\n"
373
+ const plan = issuing
374
+ ? statusPassPlan(batchSrc, 3, rawResult, "")
375
+ : disposition === DISPOSITION_CHANGES_REQUIRED ? statusResetPlan(batchSrc, 3, rawResult, date) : null
376
+ const block = designReviewBlock({
377
+ roundN: nextRoundNumber(batchSrc, 3),
378
+ signed: issuing,
379
+ reason: disposition,
380
+ date,
381
+ body: stripped,
382
+ verdictLine: verdictLineOf(disposition),
383
+ eol,
384
+ })
385
+ const inserted = appendLineToSection(batchSrc, 3, block)
386
+ const writtenSrc = plan ? updateSectionStatusLine(inserted, 3, plan.statusValue) : inserted
387
+ // 回读的是**盘上字节**,不是刚算出的内存结果——写没落盘、写半截、被别处改回,都在这里现形。
388
+ // 算全文这一步留在 `try` 之外:§3 段头缺失由写面 throw(接线故障该炸得响,不配一条给用户看的拒因
389
+ // ——与 `boundBatch` 同判);只有 `recordWriter` 那一次 fs 写才是「写失败」这一支。
390
+ let failure = ""
391
+ let signedSrc = null
392
+ try {
393
+ recordWriter(boundBatch, writtenSrc, "utf8")
394
+ } catch (e) {
395
+ failure = `写档失败: ${e?.message ?? String(e)}`
396
+ }
397
+ if (!failure) {
398
+ try {
399
+ signedSrc = readFileSync(boundBatch, "utf8")
400
+ } catch (e) {
401
+ failure = `块回读失败: ${e?.message ?? String(e)}`
402
+ }
403
+ }
404
+ if (!failure) {
405
+ // 判据 2(§1.2 第 2 条):本轮块回读见到它;pass 路径的段级状态行回读为「评审通过」。
406
+ const before = countRoundBlocks(batchSrc, 3)
407
+ const after = countRoundBlocks(signedSrc, 3)
408
+ if (after <= before) failure = `回读 §3 轮次块 ${after} 块(写前 ${before} 块)——本轮块不在 §3 里`
409
+ else if (issuing) {
410
+ const back = readSectionStatusWord(signedSrc, 3)
411
+ // 回读不等 ⇒ 盘上可能已是半截档 ⇒ 写回写前原文(验收行要的是「写不进 ⇒ 零字节」,而半截写
412
+ // 恰恰会留半张——截断的批档再没有别的恢复路径)。写回失败不吞:两处并报,token 未签。
413
+ if (back !== STATUS_WORDS[3].done) failure = `回读 §3 状态行 = ${back ?? "(缺)"};须 = ${STATUS_WORDS[3].done}`
414
+ }
415
+ }
416
+ if (failure) {
417
+ // 槽零写、`run.open` 不翻 ⇒ 修好该档后同一实例可重评(与裁定闸同形);拒因不新增值——写失败与
418
+ // 回读不等都落在同一个后置事实上(`status-not-passed` = 结算后那条不是「评审通过」),detail 点名真因。
419
+ try {
420
+ recordWriter(boundBatch, batchSrc, "utf8")
421
+ } catch (e) {
422
+ failure += `;写回写前原文也失败: ${e?.message ?? String(e)}`
423
+ }
424
+ return { passed: false, output: [stripped, REVIEW_RECORD_MARK(RECORD_STATUS_NOT_PASSED, failure)].filter(Boolean).join("\n\n"), sign: null }
425
+ }
426
+ // 块已落:交出去的 `sign` = **写前原文**与写回那一笔——落盘(token)失败时 `settleAdvisorRun` 用它
427
+ // 连同块与状态行一起回退(§4.23:不留有块无凭证的假授权)。回退写经同一个 `recordWriter`
428
+ // ⇒ 写通道只有一条,单测的注入对两笔同时生效。
429
+ sign = { before: batchSrc, rollback: () => recordWriter(boundBatch, batchSrc, "utf8") }
430
+ }
431
+ // 非签发处置到此为止(两种模式同一结论:凭证不发;工程模式那一笔已把块留住,普通模式本轮不写块):
432
+ // 槽零写、`run.open` 不翻 ⇒ 修好后同一实例可重评;拒文按处置各写自己的恒定标记。
433
+ if (!issuing) {
434
+ return { passed: false, output: [stripped, nonIssueMark(disposition)].filter(Boolean).join("\n\n"), sign }
435
+ }
436
+ // §10.2(DESIGN-TOKEN-SETTLEMENT)评审封印:`sealDocs` / `sealHash` 已在裁定闸之后算好
437
+ // (先算后写——被审档读不到时结算已在那一处拒签,没有任何字节落盘)。
170
438
  // Echoed the token → review passed. Issue it to the parent for eng-coder.
171
439
  agent._engDesignTokens ??= new Map()
172
440
  agent._engDesignTokens.set(run.designId, designToken)
173
- // §10 E1(DESIGN-TOKEN-SETTLEMENT):批归属旁列同拍写——派生 = 本评审文档集 `docSetKey` 中
174
- // `batches/` 段档的绝对路径(零新输入)。文档集不含批档 ⇒ 归属 = 无(不猜):**删**该 designId
441
+ // §10 E1(DESIGN-TOKEN-SETTLEMENT):批归属旁列同拍写——派生 = `batchAbsPathOfRun(run)`(两源定序:
442
+ // `run.batchDoc` 优先、文档集里的批档兜底;零新输入)。派生为无 ⇒ 归属 = 无(不猜):**删**该 designId
175
443
  // 的旧行——否则一次改了范围的复评会让新槽继承上一轮的归属,收口时消费掉本不该消费的授权。
176
- const batchAbs = batchAbsPath(run.docSetKey)
444
+ const batchAbs = batchAbsPathOfRun(run)
177
445
  if (batchAbs) {
178
446
  agent._engDesignTokenBatches ??= new Map()
179
447
  agent._engDesignTokenBatches.set(run.designId, batchAbs)
180
448
  } else if (agent._engDesignTokenBatches instanceof Map) {
181
449
  agent._engDesignTokenBatches.delete(run.designId)
182
450
  }
451
+ // §10.2:封印与清单一并存进槽(派单侧只读槽里的 `docs` 复算,不自己推清单)。
452
+ // 空集 ⇒ **删**该 designId 的旧行(与批归属同一分支理由):同一 designId 的复评若只审了批档,
453
+ // 旧封印留着会让下一次派单拿上一轮的版本去比这一轮的档。
454
+ if (sealHash) {
455
+ agent._engDesignTokenSeals ??= new Map()
456
+ // `docHashes` 只服务拒文点名(§10.2「清单与 hash 一起存进槽」):`hash` 仍是判定值,口径零改。
457
+ agent._engDesignTokenSeals.set(run.designId, { hash: sealHash, docs: sealDocs, docHashes: sealDocHashes })
458
+ } else if (agent._engDesignTokenSeals instanceof Map) {
459
+ agent._engDesignTokenSeals.delete(run.designId)
460
+ }
183
461
  // DESIGN-TOKEN-SETTLEMENT D3(2026-09-08):单值镜像 `_engDesignToken` 退役——
184
462
  // 只写多槽 Map(AC3 零镜像写);settle 落盘由调用方(settleAdvisorRun)当场做。
185
463
  // Unlock the dispatch design gate for eng-coder SELF-review (defense-in-depth —
@@ -196,5 +474,6 @@ export function settleDesignReview(agent, run, designToken, rawResult, opts = {}
196
474
  // §5.1② 标记位置不变式:M2 恒居 approvedSuffix 之前、suffix 恒居文末
197
475
  // (stripApprovedSuffix 的精确截断依赖此形——尾部追加改动不得破坏)。
198
476
  output: [clean, truncatedEcho ? TRUNCATED_ECHO_MARK : null, run.approvedSuffix].filter(Boolean).join("\n\n"),
477
+ sign,
199
478
  }
200
479
  }
@@ -1,21 +1,27 @@
1
1
  /**
2
- * agent-tools/doc-check.mjs — `doc_check` 工具:文档纪律机检(产品内建 · 两种问法)。
2
+ * agent-tools/doc-check.mjs — `doc_check` 工具:文档机检(只判三件事)。
3
3
  *
4
- * 设计 = `docs/core/design/DOC-DISCIPLINE.md` §3.20 条目 S(判据 = 锚 ∥ 段判据 · 参数内置常量)。
5
- * 工具形:**无动作枚举**——`mode` = 同一条判据的两种问法(`report` = 报告态 ∥ `gate` = 交付时点的裁定);
6
- * **只读**(零副作用 · 免审批 · 可并行);参数 `target` / `mode` / `docs`
7
- * (`target` 指向多项目工作区 ⇒ 报明候选并要求指名,同 `manifest` 工具面)。
8
- * 判据参数 = 引擎内置常量 `DOC_CHECK_BUILTINS`——不读 manifest、不硬编码本仓路径、不扫目录。
4
+ * 判据句单源 = `docs/core/design/DOC-CHECK.md`:① 一段太长 ∥ ② 拿行号做锚 ∥ ③ 悬空指针。
5
+ * 工具形:**无动作枚举**——`mode` 只是这一笔的意图,而两个 mode 的**判域不同**(单源 = 同档 §6):
6
+ * `report` = 诊断面,判整份;`gate` = 交付判定,只判**本批变更区**。同一句话不许两面各说一套。
7
+ * **时点 = 收口**(§9):它读的是已经在盘的档,与收口同处境——批档面整份不进判域(两个 mode 同此一判)。
8
+ * `gate` 的基线取**绑定给本席的批档**(`ctx.agent._batchDoc`)§1 的记入行:没有绑定 ⇒ 没有「本批」可指
9
+ * ⇒ 没有要判的行,一个档也不判(不猜一份在途批档来当基线)。
10
+ * **`report` 面只读(零副作用 · 免审批 · 可并行)**;**`gate` 面写索引**:判之前对它此行判的那几份档逐个
11
+ * `git add -- <该档>`(按路径限定,不 `git add -A`)——索引外的新档 `git diff` 看不见,那不是「没改」(§6)。
12
+ * 两面都不写档字节、都不问审批。参数 `target` / `mode` / `docs`。
13
+ * `target` = 基根(相对 `docs` 条目按它解析);每份档的项目根沿它自己往上找(单源 = 引擎)。
9
14
  * 判定范围 = 调用方传入的档:`report` 面 `docs` 必填(不给 ⇒ 明确报错,零遍历);
10
15
  * `gate` 面缺省 = 本会话触达记账里的 `.md`(交付面按轮次收窄的唯一来源)。
11
- * `report` 非门禁(硬):输出不得被读作拒执行的理由(用户令 > 机检——§2 总则族);
12
- * `gate` 的强制面住交付协议 + 批次档 §6 前置,工具本体同样不阻断任何动作。
13
16
  * 描述外置:模型可见文本单点 = `tool-docs/doc_check.md`(`DESC` 单一解析面)。
14
17
  * 装配段 = `agent/family-tools.mjs` 三处(depth-0 / eng-coder / eng-designer)——写文档 / 设计档的角色面。
15
18
  */
16
- import { resolve } from "node:path"
19
+ import { isAbsolute, resolve } from "node:path"
17
20
  import { projectRootView } from "../manifest.mjs"
18
- import { runDocCheck } from "../doc-check/index.mjs"
21
+ import { resolvePathTarget } from "../path-resolve.mjs"
22
+ import { runDocCheck, MOMENT } from "../doc-check/index.mjs"
23
+ import { baseShaOf } from "./batch-gate.mjs"
24
+ import { changedRegionsOf, stageDocs } from "./batch-regions.mjs"
19
25
  import { DESC } from "../tools/shared.mjs"
20
26
 
21
27
  export const docCheckTool = {
@@ -24,46 +30,66 @@ export const docCheckTool = {
24
30
  parameters: {
25
31
  type: "object",
26
32
  properties: {
27
- target: { type: "string", description: "Explicit project root to check — defaults to the session anchor; relative paths resolve against it. A workspace target (several projects below it) is reported with the full candidate list — pass the project root you mean." },
28
- mode: { type: "string", enum: ["report", "gate"], description: "How to ask the same two-criteria check. \"report\" (default): a non-gating report over the documents you list in docs. \"gate\": the delivery gate — the documents this round touched (docs, or this session's written documents when docs is omitted), whole-file judged, first line a machine-readable verdict (DOC-CHECK GATE: PASS / REFUSED / ERROR)." },
29
- docs: { type: "array", items: { type: "string" }, description: "The documents to judge, as paths relative to the project root or absolute — each is judged whole; nothing else is read except the targets those documents point at. Required in \"report\" mode (there is no default range: omitting it is refused, not widened). Omitted in \"gate\" mode ⇒ the Markdown documents this session wrote. A path that is not on disk or is not a Markdown document is an error (no document judged) in report mode and a visible skipped line in gate mode." },
33
+ target: { type: "string", description: "The base root for this call: relative `docs` entries resolve against it, and a document that belongs to no project falls back to it. Required — there is no default; the session anchor is the base for relative paths, never a substitute for `target`." },
34
+ mode: { type: "string", enum: ["report", "gate"], description: "What this call is for. \"report\" (default): the diagnostic face — every named document is judged whole. \"gate\": the delivery-time verdict — only this batch's changed region inside each named document is judged (docs, or this session's written documents when docs is omitted). Both judge the same three things and print the same sentences; the first line is DOC-CHECK GATE: PASS or REFUSED." },
35
+ docs: { type: "array", items: { type: "string" }, description: "The documents to judge, as paths relative to `target` or absolute. In \"report\" mode each is judged whole (the diagnostic face); in \"gate\" mode only this batch's changed region inside it is judged, so a pre-existing dangling pointer outside the region is not reported. Required in \"report\" mode (there is no default range: omitting it is refused, not widened). Omitted in \"gate\" mode ⇒ the Markdown documents this session wrote." },
30
36
  },
37
+ required: ["target"],
31
38
  },
32
39
  readonly: true,
33
40
  execute(args, ctx) {
34
- const anchor = ctx?.agent?.cwd ?? ctx?.cwd ?? process.cwd()
35
- const target = args?.target ? resolve(anchor, String(args.target)) : resolve(anchor)
41
+ const anchor = ctx?.agent?.cwd ?? ctx?.cwd
36
42
  const mode = args?.mode === undefined ? "report" : String(args.mode)
37
- if (mode !== "report" && mode !== "gate") return `doc_check: unknown mode "${mode}" — use "report" (a report over the documents you list) or "gate" (this round's documents).`
38
- const explicit = Array.isArray(args?.docs) ? args.docs : null
39
- if (args?.docs !== undefined && !Array.isArray(args.docs)) {
40
- return `doc_check: \`docs\` must be an array of paths (got ${typeof args.docs}) — a bare string is refused rather than read as a whole-domain request; pass ["<path>"].`
43
+ if (mode !== "report" && mode !== "gate") return `doc_check: unknown mode "${mode}" — use "report" (look at the documents you list) or "gate" (this round's documents).`
44
+ const givenTarget = typeof args?.target === "string" && args.target.trim() !== "" ? args.target : undefined
45
+ if (givenTarget === undefined) {
46
+ return "doc_check: `target` is required — pass the base root you mean (an absolute path, or a path relative to the session anchor). There is no default: the session anchor is the base for relative paths, never a substitute for `target`."
41
47
  }
42
- if (explicit && explicit.some((d) => typeof d !== "string")) {
43
- return "doc_check: every `docs` entry must be a path string — a non-string entry is refused rather than coerced (no document was judged)."
48
+ if (!anchor && !isAbsolute(givenTarget)) {
49
+ return "doc_check: no session anchor is available (`ctx.agent.cwd` / `ctx.cwd` both empty) — pass `target` as an absolute path; a relative `target` has no base to resolve against, and this tool will not fall back to `process.cwd()`."
44
50
  }
45
- const view = projectRootView(target)
46
- if (view.state === "workspace") {
51
+ const picked = resolvePathTarget(anchor, givenTarget, { kind: "dir", order: "root-first" })
52
+ if (picked.state === "ambiguous") {
47
53
  if (mode === "gate") {
48
54
  return [
49
55
  "DOC-CHECK GATE: ERROR(多项目工作区:请指名 target)",
50
- `候选:${view.candidates.join(" ∥ ")}`,
56
+ `候选:${picked.candidates.join(" ∥ ")}`,
51
57
  "处置:指名项目根(`target`)后复跑",
52
58
  ].join("\n")
53
59
  }
54
- return `doc_check: ${target} is a workspace holding ${view.candidates.length} projects — pass the project root explicitly via target:\n` +
55
- view.candidates.map((c) => `- ${c}`).join("\n")
60
+ return `doc_check: ${anchor} is a workspace holding ${picked.candidates.length} projects — pass the project root explicitly via target:\n` +
61
+ picked.candidates.map((c) => `- ${c}`).join("\n")
62
+ }
63
+ const target = picked.state === "resolved" ? picked.abs : resolve(anchor, givenTarget)
64
+ const explicit = Array.isArray(args?.docs) ? args.docs : null
65
+ if (args?.docs !== undefined && !Array.isArray(args.docs)) {
66
+ return `doc_check: \`docs\` must be an array of paths (got ${typeof args.docs}) — a bare string is refused rather than read as a whole-domain request; pass ["<path>"].`
56
67
  }
68
+ if (explicit && explicit.some((d) => typeof d !== "string")) {
69
+ return "doc_check: every `docs` entry must be a path string — a non-string entry is refused rather than coerced (no document was judged)."
70
+ }
71
+ const view = projectRootView(target)
57
72
  const root = view.state === "ok" ? view.root : target
58
73
  if (mode === "gate") {
59
74
  const docs = explicit ?? (Array.isArray(ctx?.agent?._touchedFiles) ? ctx.agent._touchedFiles : [])
60
75
  .filter((p) => typeof p === "string" && p.toLowerCase().endsWith(".md"))
61
- return runDocCheck(root, { mode: "gate", docs, docsSource: explicit ? "explicit" : "session" }).report
76
+ if (docs.length === 0) return "DOC-CHECK GATE: ERROR(0 档受检——本轮没有碰过 .md)"
77
+ // 判域只是一部分:先按**收口时点**裁掉批档面(§9),再只判**本批变更区**(§6)——区内照判三件、区外一个字都不出。
78
+ // 基线 = 绑定给本席的批档(谁在判,谁已经知道自己是哪一批):不猜一份在途批档,不去扫发现面。
79
+ // 没有绑定 ⇒ 没有「本批」可指 ⇒ 没有要判的行 ⇒ 一档也不判(空表 = 每一档都没有条目)。
80
+ const bound = typeof ctx?.agent?._batchDoc === "string" && ctx.agent._batchDoc.trim() !== "" ? ctx.agent._batchDoc : null
81
+ const sha = bound ? baseShaOf(bound) : null
82
+ const absDocs = docs.map((d) => resolve(root, d))
83
+ // `gate` 面在判之前会 `git add` 它此行判的那几份档(§6):索引外的新档 `git diff` 看不见,那不是「没改」。
84
+ // 按路径限定、不 `git add -A`。没有绑定的批档 ⇒ 没有基线 ⇒ 没有要取的区,索引也不动。
85
+ if (sha) stageDocs(root, absDocs)
86
+ const regions = sha ? changedRegionsOf(root, sha, absDocs).regions : new Map()
87
+ return runDocCheck(root, { docs, moment: MOMENT.close, regions }).report
62
88
  }
63
- // 报告态:清单是唯一范围来源——不给就是拒绝(不是「全域」)。
64
89
  if (explicit === null) {
65
90
  return "doc_check: `docs` is required in report mode — pass the explicit list of documents to judge (e.g. docs: [\"docs/design/X.md\"]). There is no default range: nothing is scanned unless you name it."
66
91
  }
67
- return runDocCheck(root, { docs: explicit, docsSource: "explicit" }).report
92
+ // `report` = 诊断面:判整份(`regions: null`)。时点不按 mode 分,按**谁在调**分(§9)——批档面两个 mode 都不进判域。
93
+ return runDocCheck(root, { docs: explicit, moment: MOMENT.close, regions: null }).report
68
94
  },
69
95
  }