@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
@@ -11,14 +11,25 @@
11
11
  * (设计档 ENG-TOKEN-BINDING.md §5.1——不经 advisor-async re-export)。
12
12
  */
13
13
 
14
- import { randomUUID } from "node:crypto"
15
- import { readFileSync } from "node:fs"
14
+ import { createHash, randomUUID } from "node:crypto"
15
+ import { readFileSync, writeFileSync } from "node:fs"
16
+ import { parse, resolve } from "node:path"
16
17
  import { tokenExpiryMs } from "../token-ttl.mjs"
17
- // 段面读判据单源(骨架档):轮次块计数 ∥ 段级状态行 ∥ §3 完成词——§3 落地门与写入面读同一形态。
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 完成词——结算写块与写入面读同一形态。
18
23
  // 裁定行锚(`_V_PRE` / `_V_SUF` / `VERDICT_CHANGES_LINE`)同住骨架档锚块,组合序也只在那一档(`verdictGapOf`):
19
24
  // 本档的裁定闸判据、写入面(`append §3` 的打回重置 `statusResetPlan`)与 `§5` 写入门读同一个函数——
20
25
  // 锚与序都只此一份,三处不各写一遍。
21
- import { countRoundBlocks, readSectionStatusWord, STATUS_WORDS, VERDICT_PASS_LINE, verdictGapOf } from "./batch-skeleton.mjs"
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"
22
33
  // 批归属派生(DESIGN-TOKEN-SETTLEMENT §10)——两源定序 `batchAbsPathOfRun`:`run.batchDoc` 优先、
23
34
  // `docSetKey` 的批档兜底(判据与清点面同源)。
24
35
  // 本档 ⇄ `design-slots.mjs` 为**静态环**(对方取 `effectiveTokenTtlMs`):两侧绑定只在函数体内
@@ -125,129 +136,305 @@ export function verdictGateFailure(rawResult) {
125
136
  if (typeof rawResult !== "string") return "no-pass-line"
126
137
  const gap = verdictGapOf(rawResult)
127
138
  if (gap === null) return null
128
- return gap === "无裁定行" ? "no-pass-line" : "changes-required"
139
+ return gap === "无裁定行" ? DISPOSITION_NO_PASS_LINE : DISPOSITION_CHANGES_REQUIRED
129
140
  }
130
141
 
131
142
  /** §5.2 rejection mark (verbatim — machine-greppable; reason = no-pass-line | changes-required). */
132
143
  const VERDICT_GATE_MARK = (reason) => `裁定非通过——token 未签发 (review verdict is not pass — no design token was issued; reason: ${reason}; the echoed token was stripped)`
133
144
 
134
- /** §3 落地门拒因(ADVISOR-GUARDS.md §1.1——三值:判据 1 无条件的两个拒形落裁定闸之前 ⇒
135
- * changes-required 轮也会拿到;判据 2 的拒形只在签发路径上)。 */
136
- const RECORD_NO_BLOCK = "no-section3-block"
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
+ * 两者都在任何写之前 ∥ 写坏之后现形)。 */
137
156
  const RECORD_STATUS_NOT_PASSED = "status-not-passed"
138
157
  const RECORD_BATCH_UNREADABLE = "batch-unreadable"
139
158
 
140
- /** §3 落地门 rejection mark (verbatim — machine-greppable; reason = 上三值之一)。与裁定闸同形:
159
+ /** §3 记录判据 rejection mark (verbatim — machine-greppable; reason = 上两值之一)。与裁定闸同形:
141
160
  * 槽零写、实例不翻 open——标记即回执,不进 `settlementCriterion`(§7 不新增判据值)。
142
161
  * **恒定位 = 上方两行逐字不动**;`evidence`(可执行证据 = 当前状态行 ∥ 轮次块数 ∥ 写面通道)
143
162
  * 另起一行落在其后——指名当前值,但不把证据塞进那个机器可 grep 的括号里。 */
144
- const REVIEW_RECORD_MARK = (reason, evidence) => `评审记录不合格——token 未签发 (review record incomplete — no design token was issued; reason: ${reason})\n补写该批档 §3(发现 + VERDICT —— 状态行由工具随块落)后重跑设计评审;未补写不得按已核处理。${evidence ? `\n证据:${evidence}` : ""}`
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
+ }
145
256
 
146
257
  /**
147
- * Shared design-review settlement (sync wrapper + async settle): the token echo
148
258
  * IS the verdict — the advisor echoes it only on approval. On echo (full string
149
259
  * OR truncated — uuid present; §5.1①): slot the token under designId (always the
150
260
  * FULL token; + eng-coder gate flag; single-value mirror retired per
151
261
  * DESIGN-TOKEN-SETTLEMENT D3), record its batch attribution (`_engDesignTokenBatches`
152
262
  * — `batchAbsPathOfRun(run)`: the instance's bound `batchDoc`, else the reviewed doc-set's
153
- * `batches/` file, §10; neither ⇒ no attribution) and return the clean output with the
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
154
267
  * Approved suffix (truncated echo: the M2 marker sits before the suffix); the review
155
268
  * instance CLOSES (a later review of the same doc-set starts a fresh full
156
269
  * review). On non-echo: strip every echo form (single source §5.1③) and return
157
270
  * the findings text + the constant M1 marker — slots stay untouched
158
- * (方案 ②: 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).
159
274
  * @param {Object} [opts] — 第 11 批(A/F11):`opts.incomplete` = 宿主尾族判定 kind
160
275
  * (单谓词 `advisorIncompleteMarker`——结算方透传)。非空 ⇒ **一律不签发**(无论评审文本
161
276
  * 是否回显 token):剥除全部 token 回显 + 追加未签发提示(原因 + 恢复指引),不写槽、
162
- * 不关实例(可重评)。
163
- * @remarks §3 落地门(ADVISOR-GUARDS.md §1.1——同族:未完成即不签发):**前置 = 绑了批档**(`run.batchDoc`
164
- * 非空)——设计评审必携 `batchDoc`(准入门,判据 = 同档 §2 第 6 条)⇒ 到结算面仍为空只是接线故障,
165
- * 在 `boundBatch` 判定处断言并 throw(程序不变量,早于写槽;不设对外拒因值,不返回判决);已过回显闸 ⇒ 两次判:① 轮次块数 > 点火基线
166
- * `run.section3BlocksAtStart`(**无条件**——changes-required 轮同判;嵌在裁定闸之前)② 段级状态行 = `评审通过`
167
- * (只在签发路径上判)。不满足 ⇒ `{passed:false}` + 恒定标记,槽零写、实例不翻 open(补写后同实例可重评)。
168
- * @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`。
169
294
  */
170
295
  export function settleDesignReview(agent, run, designToken, rawResult, opts = {}) {
171
296
  if (!designToken || typeof rawResult !== "string") {
172
- return { passed: false, output: rawResult ?? "" }
297
+ return { passed: false, output: rawResult ?? "", sign: null }
173
298
  }
174
299
  // A(F11/ADVISOR-GUARDS.md §1 消费点 1):未完成即不签发——判据与 code 完成守卫同源(单谓词)。
175
300
  const incomplete = opts?.incomplete ?? null
176
- if (incomplete) {
177
- const stripped = stripDesignTokenEcho(rawResult, designToken).trim()
178
- return {
179
- passed: false,
180
- output: `${stripped}\n\n评审未完成——token 未签发 (review incomplete — no design token issued; reason: ${incomplete})\n以更小范围重跑设计评审(逐档 / 逐节拆分,或拆到两次评审),或调大 agent.advisor.timeoutMs 后重试;补充检查未完成的部分不得按已核处理。`.trim(),
181
- }
182
- }
183
- // §5.1① 截断容忍:全串匹配 ∨ 截断形(本 token 的 uuid 值出现——空 uuid 不构成「值」)
184
- // ⇒ 认 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 零静默)。
185
307
  const uuid = String(designToken).split(":")[0]
186
308
  const fullEcho = makeDesignTokenRegex(designToken).test(rawResult)
187
309
  const truncatedEcho = !fullEcho && uuid.length > 0 && rawResult.includes(uuid)
188
- if (!fullEcho && !truncatedEcho) {
189
- const stripped = stripDesignTokenEcho(rawResult, designToken).trim()
190
- return { passed: false, output: [stripped, NO_VALID_ECHO_MARK].filter(Boolean).join("\n\n") }
191
- }
192
- // §3 落地门判据 1(**无条件**——pass 与 changes-required 都判)—— 嵌在回显闸之后、裁定闸之前。
193
- // 设计单源 = `docs/core/design/ADVISOR-GUARDS.md` §1.1;**一次读档、两次判**(判据 2 复用同一 src)。
194
- // 未回显 ⇒ 已走上面的 M1,记录面零判(连凭据都没有,报「记录不合格」会把真因盖掉)。
195
- //
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
196
323
  // 前置 = 绑了批档,**程序不变量、不是拒发分支**:设计评审必携 `batchDoc`(准入门,判据 = 同档 §2 第 6 条)
197
324
  // ⇒ 到结算面仍为空只能是「绑定没传到实例」的接线故障 ⇒ 断言并 throw(串点名设计评审实例 + designId),
198
325
  // 零槽写、不返回判决、不设对外拒因值。给没发生过的情形配文案就是没有场景的分支;接线 bug 该炸得响,
199
326
  // 不该伪装成一条给用户看的拒因(本批 🔴1 裁定)。
200
- // 位置 = 写槽(`agent._engDesignTokens.set(...)`)之前:落在其后 = 没拦,token 已在槽里、授权照发。
201
- // 调用点不得补 catch 后继续——控制流会落回 `set(...)` ⇒ token 照签、零报错、只留一条日志(同档 §1.1)。
327
+ // 位置 = 读档 ∥ 写块 ∥ 写槽之前:落在其后就没拦——token 已在槽里、授权照发。
328
+ // 调用点不得补 catch 后继续——控制流会落回 `set(...)` ⇒ token 照签、零报错、只留一条日志。
202
329
  const boundBatch = typeof run?.batchDoc === "string" && run.batchDoc.trim() ? run.batchDoc : null
203
330
  if (!boundBatch) {
204
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.`)
205
332
  }
206
- let batchSrc = null
207
- let reason = null
208
- let detail = ""
209
- try {
210
- batchSrc = readFileSync(boundBatch, "utf8")
211
- } catch (e) {
212
- reason = RECORD_BATCH_UNREADABLE
213
- detail = `批档读不到: ${e?.code ?? e?.message ?? "unknown"}`
214
- }
215
- if (reason === null && !Number.isInteger(run.section3BlocksAtStart)) {
216
- // 点火基线 = 评审实例绑定批档时读该档记下的块数(`advisor.mjs`);null / 缺失 = 点火时读不到。
217
- // 判据方向 =「绑了批档却验不了记录」不得当「没有记录要验」。
218
- reason = RECORD_BATCH_UNREADABLE
219
- detail = "点火基线缺失(批档在点火时不可读)"
220
- }
221
- if (reason === null) {
222
- const blocks = countRoundBlocks(batchSrc, 3)
223
- if (blocks <= run.section3BlocksAtStart) {
224
- reason = RECORD_NO_BLOCK
225
- detail = `§3 轮次块 ${blocks} 块、点火基线 ${run.section3BlocksAtStart} 块——本轮未写进 §3`
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 }
226
347
  }
227
348
  }
228
- if (reason !== null) {
229
- // 槽零写、`run.open` 不翻 ⇒ 补写 §3 后同一实例可重评(与裁定闸同形)。
230
- const stripped = stripDesignTokenEcho(rawResult, designToken).trim()
231
- return { passed: false, output: [stripped, REVIEW_RECORD_MARK(reason, detail)].filter(Boolean).join("\n\n") }
232
- }
233
- // §5.2 裁定闸(#940):签发 = 回显 ∧ 裁定行——缺 `VERDICT: pass` 行或含 `VERDICT: changes-required` 行
234
- // ⇒ 拒签(与 M1 径同形:剥净回显 + 恒定标记;槽零写 ∥ 实例保持——修后重评)。
235
- const gateFailure = verdictGateFailure(rawResult)
236
- if (gateFailure !== null) {
237
- const stripped = stripDesignTokenEcho(rawResult, designToken).trim()
238
- return { passed: false, output: [stripped, VERDICT_GATE_MARK(gateFailure)].filter(Boolean).join("\n\n") }
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") }
239
430
  }
240
- // 判据 2(**只在签发路径上判**)——裁定行已判 pass、批档已读到(读不到已在上述判据 1 退场)。
241
- // 段级 = 唯一状态行写面(`batch-skeleton.mjs` `updateSectionStatusLine`)的同一处——写它的是工具:
242
- // `append §3` 那一笔随裁定行置位 ∥ 重置(`statusPassPlan` ∥ `statusResetPlan`),`status` 是同面上的
243
- // 可选手写口——也是下游 `§5` 写入门读的那一处;轮次块只由工具戳标题、块内无状态行落点 ⇒
244
- // 读块内状态行是读一行没人写的字。旧字面 `评审完成` 由 `readSectionStatusWord` 读侧等义。
245
- const word = readSectionStatusWord(batchSrc, 3)
246
- if (word !== STATUS_WORDS[3].done) {
247
- const stripped = stripDesignTokenEcho(rawResult, designToken).trim()
248
- const detail = `§3 状态行 = ${word ?? "(缺)"};须 = ${STATUS_WORDS[3].done}(块落盘时由工具置位)`
249
- return { passed: false, output: [stripped, REVIEW_RECORD_MARK(RECORD_STATUS_NOT_PASSED, detail)].filter(Boolean).join("\n\n") }
431
+ // 非签发处置到此为止(两种模式同一结论:凭证不发;工程模式那一笔已把块留住,普通模式本轮不写块):
432
+ // 槽零写、`run.open` 不翻 ⇒ 修好后同一实例可重评;拒文按处置各写自己的恒定标记。
433
+ if (!issuing) {
434
+ return { passed: false, output: [stripped, nonIssueMark(disposition)].filter(Boolean).join("\n\n"), sign }
250
435
  }
436
+ // §10.2(DESIGN-TOKEN-SETTLEMENT)评审封印:`sealDocs` / `sealHash` 已在裁定闸之后算好
437
+ // (先算后写——被审档读不到时结算已在那一处拒签,没有任何字节落盘)。
251
438
  // Echoed the token → review passed. Issue it to the parent for eng-coder.
252
439
  agent._engDesignTokens ??= new Map()
253
440
  agent._engDesignTokens.set(run.designId, designToken)
@@ -261,6 +448,16 @@ export function settleDesignReview(agent, run, designToken, rawResult, opts = {}
261
448
  } else if (agent._engDesignTokenBatches instanceof Map) {
262
449
  agent._engDesignTokenBatches.delete(run.designId)
263
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
+ }
264
461
  // DESIGN-TOKEN-SETTLEMENT D3(2026-09-08):单值镜像 `_engDesignToken` 退役——
265
462
  // 只写多槽 Map(AC3 零镜像写);settle 落盘由调用方(settleAdvisorRun)当场做。
266
463
  // Unlock the dispatch design gate for eng-coder SELF-review (defense-in-depth —
@@ -277,5 +474,6 @@ export function settleDesignReview(agent, run, designToken, rawResult, opts = {}
277
474
  // §5.1② 标记位置不变式:M2 恒居 approvedSuffix 之前、suffix 恒居文末
278
475
  // (stripApprovedSuffix 的精确截断依赖此形——尾部追加改动不得破坏)。
279
476
  output: [clean, truncatedEcho ? TRUNCATED_ECHO_MARK : null, run.approvedSuffix].filter(Boolean).join("\n\n"),
477
+ sign,
280
478
  }
281
479
  }
@@ -1,22 +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
21
  import { resolvePathTarget } from "../path-resolve.mjs"
19
- import { runDocCheck } from "../doc-check/index.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"
20
25
  import { DESC } from "../tools/shared.mjs"
21
26
 
22
27
  export const docCheckTool = {
@@ -25,20 +30,25 @@ export const docCheckTool = {
25
30
  parameters: {
26
31
  type: "object",
27
32
  properties: {
28
- 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." },
29
- 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)." },
30
- 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." },
31
36
  },
37
+ required: ["target"],
32
38
  },
33
39
  readonly: true,
34
40
  execute(args, ctx) {
35
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
- // `target` 的路径判定经统一解析层(`kind:"dir"` / `order:"root-first"`):判不出唯一根 ⇒ 报明候选(KD-5
39
- // 的形),解析出 ⇒ 用。`dangling` 不阻断本面——本面判据 = 内置常量、不读声明面,任可判目录都能跑
40
- // (受判档由 `docs` 给定),故无项目根时按显式目标 ∥ 会话锚照跑(受理判据归本面)。
41
- const picked = resolvePathTarget(anchor, args?.target, { kind: "dir", order: "root-first" })
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`."
47
+ }
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()`."
50
+ }
51
+ const picked = resolvePathTarget(anchor, givenTarget, { kind: "dir", order: "root-first" })
42
52
  if (picked.state === "ambiguous") {
43
53
  if (mode === "gate") {
44
54
  return [
@@ -50,7 +60,7 @@ export const docCheckTool = {
50
60
  return `doc_check: ${anchor} is a workspace holding ${picked.candidates.length} projects — pass the project root explicitly via target:\n` +
51
61
  picked.candidates.map((c) => `- ${c}`).join("\n")
52
62
  }
53
- const target = picked.state === "resolved" ? picked.abs : resolve(anchor, args?.target ? String(args.target) : "")
63
+ const target = picked.state === "resolved" ? picked.abs : resolve(anchor, givenTarget)
54
64
  const explicit = Array.isArray(args?.docs) ? args.docs : null
55
65
  if (args?.docs !== undefined && !Array.isArray(args.docs)) {
56
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>"].`
@@ -59,27 +69,27 @@ export const docCheckTool = {
59
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)."
60
70
  }
61
71
  const view = projectRootView(target)
62
- if (view.state === "workspace") {
63
- if (mode === "gate") {
64
- return [
65
- "DOC-CHECK GATE: ERROR(多项目工作区:请指名 target)",
66
- `候选:${view.candidates.join(" ∥ ")}`,
67
- "处置:指名项目根(`target`)后复跑",
68
- ].join("\n")
69
- }
70
- return `doc_check: ${target} is a workspace holding ${view.candidates.length} projects — pass the project root explicitly via target:\n` +
71
- view.candidates.map((c) => `- ${c}`).join("\n")
72
- }
73
72
  const root = view.state === "ok" ? view.root : target
74
73
  if (mode === "gate") {
75
74
  const docs = explicit ?? (Array.isArray(ctx?.agent?._touchedFiles) ? ctx.agent._touchedFiles : [])
76
75
  .filter((p) => typeof p === "string" && p.toLowerCase().endsWith(".md"))
77
- 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
78
88
  }
79
- // 报告态:清单是唯一范围来源——不给就是拒绝(不是「全域」)。
80
89
  if (explicit === null) {
81
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."
82
91
  }
83
- 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
84
94
  },
85
95
  }