@thincoder/core 0.11.1 → 0.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (333) hide show
  1. package/CHANGELOG.md +46 -2
  2. package/advisor/convergence.mjs +34 -3
  3. package/advisor/loop.mjs +42 -10
  4. package/advisor/messages.mjs +42 -25
  5. package/advisor/project-context.mjs +171 -42
  6. package/advisor/run.mjs +7 -4
  7. package/advisor.mjs +29 -43
  8. package/agent/batch-attribution.mjs +87 -0
  9. package/agent/batch-changed-surface.mjs +129 -0
  10. package/agent/completion.mjs +44 -3
  11. package/agent/dispatch-gates.mjs +6 -0
  12. package/agent/dispatch.mjs +8 -3
  13. package/agent/family-tools.mjs +27 -12
  14. package/agent/helpers.mjs +122 -1
  15. package/agent/offload.mjs +25 -29
  16. package/agent/post-turn.mjs +24 -10
  17. package/agent/record-results.mjs +18 -1
  18. package/agent/run-stages.mjs +77 -32
  19. package/agent/run-start.mjs +37 -0
  20. package/agent/setup-reminders.mjs +9 -2
  21. package/agent/setup.mjs +24 -11
  22. package/agent/spawn-child.mjs +38 -1
  23. package/agent/timers.mjs +5 -3
  24. package/agent/turn-loop.mjs +30 -5
  25. package/agent/turn-projection.mjs +386 -0
  26. package/agent/turn-task-state.mjs +274 -0
  27. package/agent/turn-tool-process.mjs +168 -0
  28. package/agent/write-gate-ledger.mjs +569 -0
  29. package/agent/write-gate.mjs +29 -352
  30. package/agent-tools/advisor-async.mjs +29 -169
  31. package/agent-tools/advisor-launch.mjs +178 -0
  32. package/agent-tools/advisor-settle.mjs +28 -1
  33. package/agent-tools/advisor.mjs +36 -47
  34. package/agent-tools/audit-block.mjs +6 -6
  35. package/agent-tools/batch-closeout.mjs +273 -35
  36. package/agent-tools/batch-gate.mjs +142 -342
  37. package/agent-tools/batch-ledger-bind.mjs +226 -17
  38. package/agent-tools/batch-ledger-view.mjs +109 -0
  39. package/agent-tools/batch-lifecycle.mjs +169 -46
  40. package/agent-tools/batch-paths.mjs +29 -8
  41. package/agent-tools/batch-record-write.mjs +417 -0
  42. package/agent-tools/batch-regions.mjs +215 -0
  43. package/agent-tools/batch-reopen.mjs +23 -11
  44. package/agent-tools/batch-segment-vocab.mjs +379 -0
  45. package/agent-tools/batch-skeleton.mjs +192 -239
  46. package/agent-tools/batch-supersede.mjs +232 -0
  47. package/agent-tools/batch-tier-gate.mjs +297 -0
  48. package/agent-tools/batch.mjs +182 -439
  49. package/agent-tools/consult.mjs +7 -4
  50. package/agent-tools/context.mjs +44 -17
  51. package/agent-tools/design-review-record.mjs +225 -0
  52. package/agent-tools/design-slots.mjs +1 -1
  53. package/agent-tools/design-token.mjs +279 -81
  54. package/agent-tools/doc-check.mjs +43 -33
  55. package/agent-tools/doc-graph.mjs +140 -0
  56. package/agent-tools/eng.mjs +9 -8
  57. package/agent-tools/escalate-async.mjs +2 -2
  58. package/agent-tools/manifest.mjs +34 -18
  59. package/agent-tools/read-history.mjs +112 -11
  60. package/agent-tools/review-facts.mjs +10 -3
  61. package/agent-tools/settings.mjs +23 -2
  62. package/agent-tools/spawn-gates.mjs +9 -8
  63. package/agent-tools/ssh-session.mjs +2 -2
  64. package/agent-tools/ssh-text.mjs +155 -0
  65. package/agent-tools/ssh-transport.mjs +19 -148
  66. package/agent-tools/subagent-actions-query.mjs +10 -6
  67. package/agent-tools/subagent-async.mjs +8 -9
  68. package/agent-tools/subagent-brief.mjs +76 -0
  69. package/agent-tools/subagent-design-token.mjs +168 -0
  70. package/agent-tools/subagent-run.mjs +1 -1
  71. package/agent-tools/subagent-scheduler.mjs +4 -4
  72. package/agent-tools/subagent-spawn.mjs +90 -110
  73. package/agent-tools/subagent.mjs +11 -10
  74. package/agent-tools/taskbook-block.mjs +94 -0
  75. package/agent-tools/timer.mjs +12 -8
  76. package/agent-tools/verify.mjs +13 -4
  77. package/agent-tools.mjs +7 -3
  78. package/agent.mjs +20 -1
  79. package/attachments.mjs +3 -3
  80. package/browser/actions.mjs +9 -3
  81. package/browser/cdp.mjs +45 -17
  82. package/browser/launch.mjs +25 -43
  83. package/browser/pool.mjs +299 -0
  84. package/browser/queue.mjs +2 -0
  85. package/browser/session-state.mjs +450 -0
  86. package/browser/session.mjs +127 -151
  87. package/browser/snapshot.mjs +89 -0
  88. package/client-identity.mjs +1 -1
  89. package/config-defaults.mjs +2 -1
  90. package/config-migrate.mjs +40 -0
  91. package/config-normalize.mjs +28 -2
  92. package/config-reload.mjs +59 -0
  93. package/config.mjs +62 -98
  94. package/context-degrade.mjs +38 -10
  95. package/context-echo.mjs +11 -0
  96. package/context.mjs +149 -83
  97. package/conventions.mjs +11 -9
  98. package/declaration.mjs +31 -5
  99. package/declared-repos.mjs +94 -0
  100. package/doc-check/doc-names.mjs +73 -0
  101. package/doc-check/doc-tokens.mjs +110 -0
  102. package/doc-check/existence.mjs +160 -0
  103. package/doc-check/index.mjs +309 -213
  104. package/doc-check/line-refs.mjs +27 -101
  105. package/doc-check/paragraph.mjs +218 -102
  106. package/doc-graph/anchors.mjs +474 -0
  107. package/doc-graph/doc-batch-face.mjs +59 -0
  108. package/doc-graph/doc-suffix.mjs +27 -0
  109. package/doc-graph/graph-tokens.mjs +160 -0
  110. package/doc-graph.mjs +778 -0
  111. package/explore-distill.mjs +11 -5
  112. package/i18n.mjs +1 -1
  113. package/instance-inbox-watch.mjs +272 -0
  114. package/instance-inbox.mjs +218 -0
  115. package/instance-registry.mjs +179 -0
  116. package/knowledge/README.md +3 -0
  117. package/knowledge/prompt-resources.md +6 -0
  118. package/ledger-close-proof.mjs +100 -49
  119. package/ledger-close.mjs +188 -0
  120. package/ledger-cmd.mjs +47 -91
  121. package/ledger-consistency.mjs +113 -0
  122. package/ledger-db.mjs +47 -15
  123. package/ledger-executors.mjs +1 -1
  124. package/ledger-tools.mjs +78 -19
  125. package/ledger-write-ops.mjs +130 -41
  126. package/ledger.mjs +1 -1
  127. package/manifest-discovery.mjs +3 -1
  128. package/manifest-schema.mjs +27 -5
  129. package/memory/schema.mjs +2 -2
  130. package/package.json +3 -1
  131. package/path-resolve.mjs +338 -57
  132. package/prompt-files.mjs +91 -1
  133. package/prompt-overlays.mjs +9 -6
  134. package/prompts/advisor-design.md +62 -21
  135. package/prompts/advisor-round1.md +34 -1
  136. package/prompts/advisor-round2.md +40 -7
  137. package/prompts/advisor-round3.md +39 -6
  138. package/prompts/common.md +14 -387
  139. package/prompts/consult-base.md +5 -1
  140. package/prompts/discipline-engineering.md +226 -51
  141. package/prompts/discipline-normal.md +4 -255
  142. package/prompts/knowledge/business-gates.md +22 -0
  143. package/prompts/knowledge/decision-quality.md +23 -0
  144. package/prompts/knowledge/doc-lookup.md +35 -0
  145. package/prompts/knowledge/document-writing.md +51 -0
  146. package/prompts/knowledge/documentation-evaluation.md +56 -0
  147. package/prompts/knowledge/evidence-discipline.md +57 -0
  148. package/prompts/knowledge/normal-coding-workflow.md +104 -0
  149. package/prompts/knowledge/normal-delivery-collaboration.md +108 -0
  150. package/prompts/knowledge/normal-work-management.md +57 -0
  151. package/prompts/knowledge/product-security.md +23 -0
  152. package/prompts/knowledge/project-records.md +62 -0
  153. package/prompts/knowledge/tool-advisor.md +29 -0
  154. package/prompts/knowledge/tool-apply-patch.md +18 -0
  155. package/prompts/knowledge/tool-bash.md +39 -0
  156. package/prompts/knowledge/tool-batch-eng-coder.md +12 -0
  157. package/prompts/knowledge/tool-batch-eng-designer.md +12 -0
  158. package/prompts/knowledge/tool-batch-review.md +12 -0
  159. package/prompts/knowledge/tool-batch.md +80 -0
  160. package/prompts/knowledge/tool-browser.md +57 -0
  161. package/prompts/knowledge/tool-code-search.md +4 -0
  162. package/prompts/knowledge/tool-consult-start.md +12 -0
  163. package/prompts/knowledge/tool-consult-stop.md +6 -0
  164. package/prompts/knowledge/tool-context.md +6 -0
  165. package/prompts/knowledge/tool-delete.md +17 -0
  166. package/prompts/knowledge/tool-doc-check.md +70 -0
  167. package/prompts/knowledge/tool-doc-graph-read.md +20 -0
  168. package/prompts/knowledge/tool-doc-graph.md +49 -0
  169. package/prompts/knowledge/tool-doc-search.md +6 -0
  170. package/prompts/knowledge/tool-edit.md +38 -0
  171. package/prompts/knowledge/tool-eng.md +2 -0
  172. package/prompts/knowledge/tool-execute.md +16 -0
  173. package/prompts/knowledge/tool-fetch.md +12 -0
  174. package/prompts/knowledge/tool-file-ops.md +16 -0
  175. package/prompts/knowledge/tool-get-current-time.md +7 -0
  176. package/prompts/knowledge/tool-git-read.md +19 -0
  177. package/prompts/knowledge/tool-git.md +29 -0
  178. package/prompts/knowledge/tool-glob.md +15 -0
  179. package/prompts/knowledge/tool-goal.md +8 -0
  180. package/prompts/knowledge/tool-grep.md +18 -0
  181. package/prompts/knowledge/tool-hashline-edit.md +14 -0
  182. package/prompts/knowledge/tool-insert-after.md +15 -0
  183. package/prompts/knowledge/tool-instance-list.md +6 -0
  184. package/prompts/knowledge/tool-instance-send.md +10 -0
  185. package/prompts/knowledge/tool-knowledge.md +18 -0
  186. package/prompts/knowledge/tool-ledger-read.md +35 -0
  187. package/prompts/knowledge/tool-ledger.md +42 -0
  188. package/prompts/knowledge/tool-lint.md +16 -0
  189. package/prompts/knowledge/tool-ls.md +13 -0
  190. package/prompts/knowledge/tool-lsp.md +11 -0
  191. package/prompts/knowledge/tool-main-history.md +2 -0
  192. package/prompts/knowledge/tool-manifest-read.md +14 -0
  193. package/prompts/knowledge/tool-manifest.md +31 -0
  194. package/prompts/knowledge/tool-memory-read.md +20 -0
  195. package/prompts/knowledge/tool-memory.md +15 -0
  196. package/prompts/knowledge/tool-notify-parent.md +12 -0
  197. package/prompts/knowledge/tool-operations.md +114 -0
  198. package/prompts/knowledge/tool-peer-instances.md +2 -0
  199. package/prompts/knowledge/tool-plan.md +6 -0
  200. package/prompts/knowledge/tool-process-read.md +13 -0
  201. package/prompts/knowledge/tool-process.md +15 -0
  202. package/prompts/knowledge/tool-question.md +16 -0
  203. package/prompts/knowledge/tool-read-history-batch.md +22 -0
  204. package/prompts/knowledge/tool-read-history.md +36 -0
  205. package/prompts/knowledge/tool-read-image.md +11 -0
  206. package/prompts/knowledge/tool-read.md +21 -0
  207. package/prompts/knowledge/tool-recent-changes.md +6 -0
  208. package/prompts/knowledge/tool-repo-outline.md +4 -0
  209. package/prompts/knowledge/tool-settings-read.md +12 -0
  210. package/prompts/knowledge/tool-settings.md +18 -0
  211. package/prompts/knowledge/tool-skill.md +6 -0
  212. package/prompts/knowledge/tool-ssh.md +52 -0
  213. package/prompts/knowledge/tool-subagent.md +59 -0
  214. package/prompts/knowledge/tool-task.md +12 -0
  215. package/prompts/knowledge/tool-team-ledger-read.md +11 -0
  216. package/prompts/knowledge/tool-team-ledger.md +11 -0
  217. package/prompts/knowledge/tool-timer.md +23 -0
  218. package/prompts/knowledge/tool-tree.md +14 -0
  219. package/prompts/knowledge/tool-verify.md +19 -0
  220. package/prompts/knowledge/tool-wait-for.md +25 -0
  221. package/prompts/knowledge/tool-websearch.md +19 -0
  222. package/prompts/knowledge/tool-write.md +9 -0
  223. package/prompts/knowledge/upstream-protocol.md +43 -0
  224. package/prompts/persona-eng-coder.md +21 -3
  225. package/prompts/persona-eng-designer.md +131 -169
  226. package/prompts/persona-engineering.md +142 -84
  227. package/prompts/persona-explore.md +1 -1
  228. package/prompts/persona-plan.md +5 -1
  229. package/prompts/subagent-base.md +2 -0
  230. package/provider/anthropic.mjs +6 -4
  231. package/provider/core.mjs +3 -2
  232. package/provider/errors.mjs +29 -4
  233. package/provider/google.mjs +24 -7
  234. package/provider/responses.mjs +3 -1
  235. package/provider-flows.mjs +2 -2
  236. package/session-index-build.mjs +1 -1
  237. package/session-index-pass.mjs +1 -1
  238. package/session-index-query.mjs +1 -1
  239. package/session-index.mjs +1 -1
  240. package/session-lifecycle.mjs +72 -17
  241. package/session-slot-write.mjs +37 -5
  242. package/session.mjs +24 -8
  243. package/skip-dirs.mjs +2 -2
  244. package/team-ledger.mjs +13 -9
  245. package/token-ttl.mjs +73 -4
  246. package/token-window.mjs +167 -33
  247. package/tool-docs/advisor.md +2 -27
  248. package/tool-docs/apply_patch.md +1 -15
  249. package/tool-docs/bash.md +2 -41
  250. package/tool-docs/batch-eng-coder.md +3 -0
  251. package/tool-docs/batch-eng-designer.md +3 -0
  252. package/tool-docs/batch-review.md +3 -0
  253. package/tool-docs/batch.md +2 -84
  254. package/tool-docs/browser.md +2 -49
  255. package/tool-docs/code_search.md +2 -2
  256. package/tool-docs/consult_start.md +2 -8
  257. package/tool-docs/consult_stop.md +2 -4
  258. package/tool-docs/context.md +1 -5
  259. package/tool-docs/delete.md +2 -17
  260. package/tool-docs/doc_check.md +2 -107
  261. package/tool-docs/doc_graph-read.md +3 -0
  262. package/tool-docs/doc_graph.md +3 -0
  263. package/tool-docs/doc_search.md +2 -4
  264. package/tool-docs/edit.md +1 -38
  265. package/tool-docs/eng.md +3 -1
  266. package/tool-docs/execute.md +2 -18
  267. package/tool-docs/fetch.md +2 -14
  268. package/tool-docs/file_ops.md +2 -18
  269. package/tool-docs/get_current_time.md +1 -6
  270. package/tool-docs/git-read.md +3 -0
  271. package/tool-docs/git.md +2 -35
  272. package/tool-docs/glob.md +2 -10
  273. package/tool-docs/goal.md +1 -6
  274. package/tool-docs/grep.md +2 -18
  275. package/tool-docs/hashline_edit.md +2 -15
  276. package/tool-docs/insert_after.md +2 -16
  277. package/tool-docs/instance_list.md +3 -0
  278. package/tool-docs/instance_send.md +3 -0
  279. package/tool-docs/knowledge.md +3 -0
  280. package/tool-docs/ledger-read.md +3 -0
  281. package/tool-docs/ledger.md +3 -8
  282. package/tool-docs/lint.md +2 -10
  283. package/tool-docs/ls.md +2 -11
  284. package/tool-docs/lsp.md +2 -9
  285. package/tool-docs/main_history.md +3 -1
  286. package/tool-docs/manifest-read.md +2 -8
  287. package/tool-docs/manifest.md +2 -35
  288. package/tool-docs/memory-read.md +3 -0
  289. package/tool-docs/memory.md +2 -20
  290. package/tool-docs/notify_parent.md +2 -13
  291. package/tool-docs/peer_instances.md +3 -1
  292. package/tool-docs/plan.md +1 -5
  293. package/tool-docs/process-read.md +3 -0
  294. package/tool-docs/process.md +2 -13
  295. package/tool-docs/question.md +3 -17
  296. package/tool-docs/read.md +2 -19
  297. package/tool-docs/read_history-batch.md +3 -0
  298. package/tool-docs/read_history.md +2 -18
  299. package/tool-docs/read_image.md +2 -9
  300. package/tool-docs/recent_changes.md +2 -2
  301. package/tool-docs/repo_outline.md +2 -2
  302. package/tool-docs/settings-read.md +3 -0
  303. package/tool-docs/settings.md +1 -12
  304. package/tool-docs/skill.md +2 -6
  305. package/tool-docs/ssh.md +1 -62
  306. package/tool-docs/subagent.md +2 -100
  307. package/tool-docs/task.md +1 -7
  308. package/tool-docs/team_ledger-read.md +3 -0
  309. package/tool-docs/team_ledger.md +3 -9
  310. package/tool-docs/timer.md +2 -19
  311. package/tool-docs/tree.md +2 -13
  312. package/tool-docs/verify.md +2 -12
  313. package/tool-docs/wait_for.md +2 -32
  314. package/tool-docs/websearch.md +2 -19
  315. package/tool-docs/write.md +2 -12
  316. package/tools/browser.mjs +52 -7
  317. package/tools/doc-write-gate.mjs +73 -0
  318. package/tools/edit-batch.mjs +170 -92
  319. package/tools/edit-diff.mjs +78 -62
  320. package/tools/edit-receipt.mjs +39 -0
  321. package/tools/execute.mjs +1 -1
  322. package/tools/file.mjs +16 -8
  323. package/tools/git.mjs +24 -9
  324. package/tools/index.mjs +6 -0
  325. package/tools/knowledge.mjs +143 -0
  326. package/tools/linter.mjs +3 -3
  327. package/tools/ops.mjs +3 -1
  328. package/tools/patch.mjs +123 -43
  329. package/tools/shared.mjs +28 -27
  330. package/tools/write-gate-params.mjs +31 -0
  331. package/tools/write-path.mjs +16 -4
  332. package/window-policy.mjs +203 -0
  333. package/doc-check/anchors.mjs +0 -235
@@ -1,242 +1,338 @@
1
1
  /**
2
- * doc-check/index.mjs — 文档纪律机检 · 引擎入口(两条判据 + 报面行)。
2
+ * doc-check/index.mjs — 文档机检引擎:判三件事,出一份回执。
3
3
  *
4
- * 判据两条(起步 · 闭集——口径单源 = `docs/core/design/DOC-DISCIPLINE.md` §3.20 条目 S):
5
- * ① 锚(档缺 / 节缺 / 引缺)——实现 = `./anchors.mjs`;② 段判据(文字太长,难于阅读 ∥ 行太长)——口径 = §3.18 条目 Q,实现 = `./paragraph.mjs`。
6
- * 判据参数 = **工具内置常量** `DOC_CHECK_BUILTINS`:不读任何项目的声明面,因而没有「缺参数 ⇒ 拒跑」这一层,
7
- * 也没有常量校验面——改判据 = 改代码、走评审。
8
- * 判定范围 = **调用方传入的文件清单**(判定范围 = 解析范围 = 传入的那几档;无目录遍历、无全域兜底):
9
- * 不给清单 ⇒ 明确报错要求显式清单——判了本轮没碰过的档,别轮的存量问题会记到本轮头上。
10
- * 两种问法(§3.20「工具形」——同一条判据):
11
- * `report`(缺省)= 报告态——**零门禁 / 零退出码 / 零阻断**,输出不得被读作拒执行的理由(用户令 > 机检);
12
- * 清单里不可判档(不在盘 ∥ 非 .md)⇒ 报错点名、整次零判定;
13
- * `gate` = 交付时点的裁定——首行给机器可判 verdict;不可判档给跳过行(可见,不静默丢掉)。
14
- * 强制面住交付协议 + 批次档 §6 前置,工具本体不阻断任何动作。
15
- * **`report` 面另有一份只读清点:行号坐标清单**(`./line-refs.mjs` · 口径 = `docs/core/design/DOC-DISCIPLINE.md` §3.23 条目 W)——
16
- * **只报不拦**:不进 `gate`、不计入 `hits`、不阻断写入。判据面仍是上面两条,一字不改。
4
+ * 判据句单源 = `docs/core/design/DOC-CHECK.md`:① 一段太长(`./paragraph.mjs`)∥ ② 拿行号做锚(`./line-refs.mjs`)
5
+ * ∥ ③ 悬空指针(`./existence.mjs`)。**这三件之外不判**——节号、引文、行数、跨仓都不在射程(§1 ∥ §4)。
6
+ * 面别只决定判据 ③:批档面(`docRoot.batches` 之下的档)整份不判悬空(§3)——它的读者不照着 §1–§6 去找档。
7
+ *
8
+ * 判域 = 交给门的那几档里的**本批变更区**(§6):区内照判三件、区外一个字都不出。两个时点取法不同源:收口那一刻
9
+ * 读 `git diff`(`changedRegionsOf`,`agent-tools/batch-regions.mjs`),写时点读**两份文本**——盘上现文与这一笔要写的
10
+ * 改后整份(`changedRegionOf`,本档)。判整份的只有诊断面(`doc_check` 的 `report` mode)与写时点的新档 / 读不到
11
+ * 现文那一支。区间由调用方算好交进来——引擎不读 git。
12
+ *
13
+ * 报面(§5):首行是机器判的,后面每行一句人话;没有命中 ⇒ `PASS` 一行,不再添任何一行。
14
+ * 两个调用点共用这套句子,差别只在拿不拿它挡这一笔写:写盘前 / 批档写入与收口 / `doc_check` 工具面。
15
+ *
16
+ * **判域带时点**(§9):批档只在「写」的那一刻判。写时点 = `batch` 的 `append` ∥ `edit`,加 `.md` 落盘前那道门;
17
+ * 收口时点 = `batch close`,加 `doc_check` 工具面。判域谓词 = 本档的 `judgedDomainDocs`(**一条,三面共用**):
18
+ * 写时点原样交回,收口时点把批档面整份移出判域。判据本体 `judgeText` 不带时点——它对批档面的悬空豁免
19
+ * 正是**写时点**那条规则,两件事各有自己的单源。
20
+ *
21
+ * **判域上挂着两道滤**(「哪些档进来」的加减只在本档这一处发生):第一道认批档面(§9,按**时点**),
22
+ * 第二道认**排除面**(§10,两个时点都认)——项目在 manifest 的 `index.docCheckExcludePaths` 里声明的
23
+ * 路径前缀之下,档一律不进判域。判据仍是三件,排除面只决定「哪些档进来」。
24
+ *
25
+ * 「没判」照实说:不在盘、读不到的那几档各出一行,不当命中也不当干净——删掉它,一个什么都没判的 `PASS`
26
+ * 会被读成「都判过了、都干净」,那是假绿。
17
27
  */
18
- import { statSync } from "node:fs"
19
- import { relative, resolve } from "node:path"
20
- import { checkParagraphs, DOC_CLASS } from "./paragraph.mjs"
21
- import { checkAnchors } from "./anchors.mjs"
22
- import { collectLineRefs, lineRefsBlock } from "./line-refs.mjs"
23
- // 跨仓引用一行读数的文案骨架(单源 = 统一解析层;本档只把它摆进报面)。
24
- import { crossRepoNote } from "../path-resolve.mjs"
28
+ import { existsSync, readFileSync } from "node:fs"
29
+ import { join, relative, resolve } from "node:path"
25
30
 
26
- /** 判据参数(内置常量 · 冻结):阈值 300 字符(一段 ∥ 一行同值——§3.18 ④);两项空列表 = 区带类 / 豁免类默认值且恒空
27
- * ——豁免谓词(表行 / 围栏 / 列表项 / 引文)住代码,没有「登记后放过」的写入口(空列表 ≠ 可登记豁免)。 */
28
- export const DOC_CHECK_BUILTINS = Object.freeze({
29
- paragraphMax: 300,
30
- lineMax: 300,
31
- paragraphExemptZones: Object.freeze([]),
32
- exemptions: Object.freeze([]),
33
- })
31
+ import { readManifest } from "../manifest.mjs"
32
+ import { normalizePathList } from "../declaration.mjs" // 归一的同一把尺(与 `index.excludePaths` 同款)
33
+ import { PARAGRAPH_MAX, isPromptFace, paragraphHits } from "./paragraph.mjs"
34
+ import { lineRefHits } from "./line-refs.mjs"
35
+ import { existenceHits, isBatchFace, pathIndexOf, plannedPathsOf } from "./existence.mjs"
34
36
 
35
- /** 命中类名单源再出口(`./paragraph.mjs` 的 `DOC_CLASS`):`agent-tools/batch-gate.mjs` 要判「处置块何时出」,
36
- * 而它按判据链纪律只 import 本档(引擎 import 只指向 `../doc-check/index.mjs`)⇒ 类名由本档再出口,
37
- * 消费面不抄字面类名——抄一次就是「改报面忘改过滤」那类字面漂移(`paragraph.mjs` 头注记着 2026-10-26 实发过一次)。 */
38
- export { DOC_CLASS }
37
+ /** 命中的类名(报面句子按类各一句;消费面按类取用时也认这三个字面)。 */
38
+ export const HIT_KIND = Object.freeze({ missing: "missing", paragraph: "paragraph", lineRef: "lineRef" })
39
39
 
40
- /** 段命中的处置块(五行 · 逐字单源):口径单源 = `docs/core/design/DOC-DISCIPLINE.md` §3.20「报面(固定句形 · 交付门 gate)」尾行。
41
- * 三处消费面(本档 `gateReport` ∥ `agent-tools/batch-gate.mjs` 的报面组装与拒串 ∥ `scripts/doc-check.mjs` 的段报告段)
42
- * 只 import 本数组、零字面复制——同一句话抄三遍,改一处漏两处是必然。
43
- * **为什么住本档**:报面尾行本来就住这里,`batch-gate.mjs` 已 import 本档 ⇒ 字面随报面同源,不新增第三个 import 面。
44
- * **为什么是五行而不是一句命令口吻的单条出路**:被拒的人当场只读得到这一面——旧句只说「你该怎么改」且只给一条出路;
45
- * 规则面本有三条,且「过机检」与「是处置」是两件事(切段 ∥ 缩短能过计数,读者拿到的还是同一堵墙)。
46
- * **何时出**:只跟「文字太长,难于阅读」类命中走;仅锚 ∥ 仅行命中 ⇒ 零处置块(叫人对段落动手而问题不在此 = 指错方向)。 */
47
- export const PARA_DISPOSE = Object.freeze([
48
- "处置:上面这些段落,读者一口气读不完——不是字符数超了,是这一段装的事太多。",
49
- "出路三条:① 重组结构——无标记的续行逐条添标记、逐条起名,拆成带名的列表项(逐字不改)∥ ② 重写文字——把长句拆成几句短的(意思不变,句子变少)∥ ③ 改写成表格行——内容本是逐条读数 / 映射 / 清单时成立。",
50
- "① ∥ ③ 只对能逐条起名的并列断言成立——一条因果链拆成带名条目还是同一条因果链,读者拿到的只有断点;讲因果的长段走 ②。",
51
- "折行连机检都过不了——句子中间插换行,读者拿到的还是同一堵墙;切段 ∥ 缩短能过机检,但不是处置——机检绿了不等于读者读得动。",
52
- "同轮修正后复跑;不转台账。",
53
- ])
40
+ /** 时点两值(闭集):`writer` = 手上正在写的那段文本 ∥ `close` = 已在盘的记录(§9 那张表)。
41
+ * 字面与 `runBatchGate` 的 `scope` 同一对——一件事一个名字,不另起一套词。 */
42
+ export const MOMENT = Object.freeze({ writer: "writer", close: "close" })
54
43
 
55
- /** 相对路径显示形(正斜杠——跨平台同形)。 */
56
- const rel = (root, p) => relative(root, p).replace(/\\/g, "/")
44
+ /** 项目根:沿这份档往上最近的带 `PROJECT-MANIFEST.json` 的目录;找不到 ⇒ 调用方给的基根。 */
45
+ function projectRootOf(abs, fallback) {
46
+ let dir = resolve(abs, "..")
47
+ for (;;) {
48
+ if (existsSync(join(dir, "PROJECT-MANIFEST.json"))) return dir
49
+ const up = resolve(dir, "..")
50
+ if (up === dir) return fallback
51
+ dir = up
52
+ }
53
+ }
57
54
 
58
- /** 平台路径键(Windows 大小写不敏感——只用于清单去重,非判据面)。 */
59
- const pathKey = (p) => (process.platform === "win32" ? p.toLowerCase() : p)
55
+ /** 相对路径显示形(正斜杠;仓外照原值——不猜)。 */
56
+ export function displayPath(root, abs) {
57
+ const r = relative(root, resolve(abs)).replace(/\\/g, "/")
58
+ return r === "" || r.startsWith("../") ? resolve(abs).replace(/\\/g, "/") : r
59
+ }
60
60
 
61
- /** 不可判档的两因(闭集 · 判序 = 存在性 → 类型):不在盘 ∥ 非 markdown 档(目录归后因)。 */
62
- function undecidableReason(abs) {
63
- let st
64
- try { st = statSync(abs) } catch { return "not on disk" }
65
- if (!st.isFile() || !abs.toLowerCase().endsWith(".md")) return "not a markdown document"
66
- return null
61
+ /**
62
+ * 该档所属项目声明的排除前缀(`index.docCheckExcludePaths`,归一 = `../declaration.mjs` 的 `normalizePathList`)。
63
+ * **读不到 manifest ∥ 键写成非数组 ⇒ 空表 ⇒ 照判**(放行必须有声明,不替项目放行):
64
+ * `readManifest` 对盘上没有的 manifest 返 `{ ok: false, reason: "missing" }`,读数方拿到的默认值就是 schema 里那个空数组。
65
+ * `memo` = 本次调用内按项目根记忆——一次判多档时同一根只读一次盘。
66
+ */
67
+ function exclusionPrefixesOf(root, memo) {
68
+ if (memo.has(root)) return memo.get(root)
69
+ let prefixes = []
70
+ try {
71
+ const read = readManifest(root)
72
+ if (read?.ok) prefixes = normalizePathList(read.manifest?.index?.docCheckExcludePaths)
73
+ } catch { prefixes = [] } // 读面抛错也走「照判」那一侧:宁多判一份档,不替项目放行
74
+ memo.set(root, prefixes)
75
+ return prefixes
67
76
  }
68
77
 
69
- /** 清单 → 可判集(去重保序)+ 不可判档两类(`missing` ∥ `notMarkdown`)+ 非法条目下标(非字符串 / 空白)。 */
70
- function resolveRange(base, docs) {
71
- const seen = new Set()
72
- const check = []
73
- const undecidable = []
74
- const missing = []
75
- const notMarkdown = []
76
- const invalid = []
77
- docs.forEach((d, i) => {
78
- if (typeof d !== "string" || d.trim() === "") { invalid.push(i); return }
79
- const abs = resolve(base, d)
80
- const key = pathKey(abs)
81
- const reason = undecidableReason(abs)
82
- if (reason === null) { if (!seen.has(key)) { seen.add(key); check.push(abs) } return }
83
- undecidable.push({ abs, reason })
84
- if (reason === "not on disk") missing.push(abs)
85
- else notMarkdown.push(abs)
86
- })
87
- return { check: check.sort(), undecidable, missing, notMarkdown, invalid }
78
+ /** 该档是否落在排除面上:**项目根相对路径**恰好等于某前缀,或以「前缀 + `/`」起头。
79
+ * 裸前缀不比——声明 `docs/_arch` 不吞 `docs/_archive-x` 之下的档(那不是声明的意思)。
80
+ * 比对按**字面**取(与 `normalizePathList` 同一把尺,不折大小写):声明写什么就比什么。
81
+ * 大小写不敏感是 `batch-paths.mjs` 的 `baseContaining` 那一族的判据(它比的是盘上同一个根),不是这一条。 */
82
+ function isExcludedDoc(abs, root, memo) {
83
+ const rel = relative(root, abs).replace(/\\/g, "/")
84
+ return exclusionPrefixesOf(root, memo).some((p) => rel === p || rel.startsWith(`${p}/`))
88
85
  }
89
86
 
90
- /** 段判据命中行(报面单源——两类命中同形,按 `clazz` 分词)。**不报字符数**:用户 2026-10-26 11:16「不能表述成超长多少个字符,要表述成为文字太长难于阅读」。 */
91
- const paragraphHitLine = (base, h) => `✗ ${h.clazz} ${rel(base, h.file)}:${h.line}`
87
+ /**
88
+ * 判域谓词(**一条,三个调用面共用**):批档面这道滤只在收口时点生效(写时点原样交回);排除面那道两个时点都认。
89
+ * 判据句单源 = `docs/core/design/DOC-CHECK.md` §9——写的那一刻量的是手上正在产生的文本,量得出缺陷;
90
+ * 收口那一刻量的是几小时前的记录、现态已经变了,量得出的是时间差。
91
+ *
92
+ * 面别判据不新造:批档面 = `existence.mjs` 的 `isBatchFace`(与 §3 第二条例外同一个谓词)。
93
+ * 时点按**谁在调**判,不按批档 §1 状态行判——状态行是记录自己的属性,时点是调用者的位置。
94
+ *
95
+ * **第二道滤 = 排除面**(§10):按每份档自己的项目根读声明,两个时点都认——一个档要么在门里、要么不在,
96
+ * 不按调用面分家。判据仍是三件,排除面只决定「哪些档进来」。
97
+ *
98
+ * @param {string[]} docs 候选档清单(绝对路径,或相对 `root` 的路径;交回的条目保持原形,不改写成绝对路径):
99
+ * 非数组一律抛——不许读成「空判域」,那会印出一个什么都没判过的 `PASS`
100
+ * @param {{moment:'writer'|'close', root?:string}} o `moment` = 这一刻谁在调(**必填**:它决定批档判不判,
101
+ * 缺省值等于替调用者决定一件事);`root` = 项目根(`isBatchFace` 与排除面读声明的基准;缺省按每份档自己往上找)
102
+ * @returns {string[]} 判域内的档(原顺序)
103
+ */
104
+ export function judgedDomainDocs(docs, { moment, root } = {}) {
105
+ if (!Array.isArray(docs)) {
106
+ throw new Error(`doc_check: \`docs\` must be an array of paths (got ${typeof docs}) — a non-array is refused rather than read as an empty domain, which would print a PASS over nothing judged.`)
107
+ }
108
+ if (moment !== MOMENT.writer && moment !== MOMENT.close) {
109
+ throw new Error(`doc_check: unknown moment ${JSON.stringify(moment)} — take "${MOMENT.writer}" (text still being written) or "${MOMENT.close}" (a record already on disk). Which moment it is decides whether batch records are judged, so it is never defaulted.`)
110
+ }
111
+ const base = typeof root === "string" && root.trim() !== "" ? resolve(root) : null
112
+ const prefixesByRoot = new Map()
113
+ return docs.filter((d) => {
114
+ const abs = base === null ? resolve(String(d)) : resolve(base, String(d))
115
+ const docRoot = projectRootOf(abs, base ?? resolve(abs, ".."))
116
+ // 两道滤的顺序跟本节的说法走(先批档面、再排除面);两条谓词互不相干,顺序不影响结果。
117
+ if (moment === MOMENT.close && isBatchFace(abs, docRoot)) return false
118
+ return !isExcludedDoc(abs, docRoot, prefixesByRoot)
119
+ })
120
+ }
92
121
 
93
- /** 跨仓引用读数行(零命中、只入回执——文案骨架单源 = `path-resolve.mjs` 的 `crossRepoNote`)。 */
94
- const crossRepoLine = (h) => `跨仓引用:${crossRepoNote(h.token, h)}`
122
+ /**
123
+ * 单行长度表(`y` 侧一维滚动):`out[k]` = `x` 与 `y[0…k-1]` 的最长公共子序列长度。
124
+ * 只留一行 ⇒ 空间线性于 `y`;这是 Hirschberg 的「一遍长度重算」。
125
+ */
126
+ function lcsRowOf(x, y) {
127
+ const out = new Array(y.length + 1).fill(0)
128
+ for (let i = 0; i < x.length; i += 1) {
129
+ let diag = 0 // = 上一行在 k-1 处的值(LCS(x[0…i-1], y[0…k-2]))
130
+ for (let k = 1; k <= y.length; k += 1) {
131
+ const carried = out[k]
132
+ out[k] = x[i] === y[k - 1] ? diag + 1 : out[k] >= out[k - 1] ? out[k] : out[k - 1]
133
+ diag = carried
134
+ }
135
+ }
136
+ return out
137
+ }
95
138
 
96
- /** `档缺` 命中行的追加提示(§2.6:缺的那一段 + 盘上同名——候选只提示,不改判态)。 */
97
- const missingHint = (base, h) => {
98
- const seg = typeof h.missing === "string" && h.missing !== "" ? `缺「${h.missing}」` : ""
99
- const same = Array.isArray(h.sameName) && h.sameName.length > 0 ? `盘上同名:${h.sameName.map((p) => rel(base, p)).join(" ∥ ")}` : ""
100
- const parts = [seg, same].filter(Boolean)
101
- return parts.length > 0 ? `(${parts.join(";")})` : ""
139
+ /**
140
+ * 按行对齐求最长公共子序列的**配对**(Hirschberg:正反各算一遍长度表,再按中分点分段回溯)。
141
+ * 返回 `[[i, j], …]`(两侧 0-based 下标,按序)。空间线性于较短那一份——行×行全表在文档面上装不下。
142
+ */
143
+ function lcsPairs(x, y) {
144
+ if (x.length === 0 || y.length === 0) return []
145
+ if (x.length === 1) {
146
+ const j = y.indexOf(x[0])
147
+ return j < 0 ? [] : [[0, j]]
148
+ }
149
+ const mid = Math.floor(x.length / 2)
150
+ const forward = lcsRowOf(x.slice(0, mid), y)
151
+ const backward = lcsRowOf(x.slice(mid).reverse(), y.slice().reverse())
152
+ let cut = 0
153
+ let best = -1
154
+ for (let k = 0; k <= y.length; k += 1) {
155
+ const v = forward[k] + backward[y.length - k]
156
+ if (v > best) {
157
+ best = v
158
+ cut = k
159
+ }
160
+ }
161
+ const left = lcsPairs(x.slice(0, mid), y.slice(0, cut))
162
+ const right = lcsPairs(x.slice(mid), y.slice(cut))
163
+ return left.concat(right.map(([i, j]) => [i + mid, j + cut]))
102
164
  }
103
165
 
104
- /** 锚命中的类名词(报面标签——类名由引擎定,本档只配显示形;三属同一条判据、同计「锚 N 条」)。 */
105
- const ANCHOR_LABELS = { 档缺: "锚·档缺", 节缺: "锚·节缺", 引缺: "锚·引缺" }
166
+ /**
167
+ * 两份文本求变更区(**写时点**的取区法;判据句单源 = `docs/core/design/DOC-CHECK.md` §6「写时点怎么取区间」)。
168
+ *
169
+ * 输入 = 调用方手上的两份整档文本:「盘上现文」与「这一笔要写的改后整份」。输出形与收口面的
170
+ * `changedRegionsOf`(`thincoder-core/agent-tools/batch-regions.mjs` 读 `git diff -U0`)**逐字同形**:
171
+ * `{rows, gaps}`——`rows` = 改后文本里变了的行(1-based),`gaps` = 纯删那一处的缝(缝前那一行在改后文本里的
172
+ * 行号,档头写 `0`)。两条链一个形状、一个消费面(`judgeText` ∥ `paragraphHits`),不各造一套语义。
173
+ *
174
+ * 算法 = 按行对齐求最长公共子序列;没被对齐的旧行与没被对齐的新行成**组**:组里有新行 ⇒ 新行全部进 `rows`;
175
+ * 组里没有新行 ⇒ 纯删,落一个 `gaps`。**不按前后缀裁剪了事**——那样两处远处的改动会连成一片,中间没变的行
176
+ * 被算成变更行,与「没变的行一条都不出」相反。前后缀只**减量**:剥掉公共前后缀后中段仍按行对齐求组,精度一字不减。
177
+ * 回溯用两遍长度重算(Hirschberg),空间线性于较短那一份——行数之积是时间上界,而文档面上有上万行的档,
178
+ * 行×行全表装不下。
179
+ *
180
+ * 本函数**不收 `null`**:两参都是字符串(不是字符串 ⇒ 当场抛)。「盘上取不到现文」这件事由调用方判(它改交
181
+ * `region: null`),不由本函数猜——猜了就是把「整份判」这条决定替调用方做了。
182
+ *
183
+ * @param {string} oldText 盘上现文
184
+ * @param {string} newText 这一笔要写的改后整份文本
185
+ * @returns {{rows:number[], gaps:number[]}}
186
+ */
187
+ export function changedRegionOf(oldText, newText) {
188
+ for (const [name, value] of [["oldText", oldText], ["newText", newText]]) {
189
+ if (typeof value !== "string") {
190
+ throw new Error(`changedRegionOf: \`${name}\` must be a string (got ${value === null ? "null" : typeof value}) — "no old text on disk" is the caller's call: it passes \`region: null\` (judge the whole document) instead of calling this function, and this function never guesses it.`)
191
+ }
192
+ }
193
+ const before = oldText.split("\n")
194
+ const after = newText.split("\n")
195
+ const limit = Math.min(before.length, after.length)
196
+ let head = 0
197
+ while (head < limit && before[head] === after[head]) head += 1
198
+ let tail = 0
199
+ while (tail < limit - head && before[before.length - 1 - tail] === after[after.length - 1 - tail]) tail += 1
200
+ const olds = before.slice(head, before.length - tail)
201
+ const news = after.slice(head, after.length - tail)
202
+ const rows = []
203
+ const gaps = []
204
+ // 一组 = 没被对齐的旧行 [oldFrom, oldTo) 与没被对齐的新行 [newFrom, newTo)。
205
+ // 组里有新行 ⇒ 新行全部进 `rows`(取代 ∥ 插入同一处置);组里没有新行 ⇒ 纯删,缝前那一行的行号 = `head + newFrom`。
206
+ const emit = (oldFrom, oldTo, newFrom, newTo) => {
207
+ if (oldFrom === oldTo && newFrom === newTo) return
208
+ if (newFrom === newTo) {
209
+ gaps.push(head + newFrom)
210
+ return
211
+ }
212
+ for (let j = newFrom; j < newTo; j += 1) rows.push(head + j + 1)
213
+ }
214
+ let oi = 0
215
+ let ni = 0
216
+ for (const [pi, pj] of lcsPairs(olds, news)) {
217
+ emit(oi, pi, ni, pj)
218
+ oi = pi + 1
219
+ ni = pj + 1
220
+ }
221
+ emit(oi, olds.length, ni, news.length)
222
+ return { rows, gaps }
223
+ }
106
224
 
107
- /** 锚命中行(报面单源——三命中类同形,按 `clazz` 分词):`档缺` 追加缺哪一段与盘上同名,
108
- * `节缺` 点名目标档,`引缺` 点名引文前 40 字(读者不必回目标档自己找哪一段不对)。
109
- * 两处消费(`gate` 报面 ∥ 报告态报面)只调本函数——各写一份三元式改一处必漏一处。 */
110
- const anchorHitLine = (base, h) => {
111
- const head = `✗ ${ANCHOR_LABELS[h.clazz] ?? `锚·${h.clazz}`} ${rel(base, h.file)}:${h.line} \`${h.token}\``
112
- if (h.clazz === "引缺") return `${head}(引文不在该档内:「${String(h.quote ?? "").slice(0, 40)}…」)`
113
- if (h.clazz === "节缺") return `${head}(目标 ${rel(base, h.target)} 无 §${h.section})`
114
- return head + missingHint(base, h)
225
+ /**
226
+ * 判一份文本的三件事(**判据的唯一入口**:读盘的、还没落盘的,都从这里过)。
227
+ * @param {string} text 档全文
228
+ * @param {{file:string, root:string, planned?:Set<string>, indexPath?:Set<string>|null,
229
+ * region:{rows:number[],gaps:number[]}|null}} o `file` = 绝对路径(报面坐标与命中身份的来源);
230
+ * `root` = 项目根(判据 ③ 找一次的基准);`planned` = 在途批档 §2 清单并集(判据 ③ 的「在建不报」);
231
+ * `region` = 本批变更区(**必填,不收缺省值**):`null` = 判整份,区间表 = 只判这几行——两件事由调用方明说。
232
+ * @returns {{file:string, line:number|null, kind:string, token?:string, len?:number}[]}
233
+ */
234
+ export function judgeText(text, { file, root, planned = new Set(), indexPath = null, region } = {}) {
235
+ if (region === undefined) {
236
+ throw new Error("doc_check: `region` must be given on every call — null (judge the whole document) or the changed-region entry for this document (judge only those lines). It is never defaulted: the default would decide the domain on the caller's behalf.")
237
+ }
238
+ const abs = resolve(file)
239
+ const rows = region === null ? null : new Set(region.rows ?? [])
240
+ // 行级判据(② ∥ ③)只认**变更行**;纯删的零宽区间在改后文本里没有可指的行 ⇒ 不产生命中(§6)。
241
+ const inRegion = (line) => rows === null || rows.has(line)
242
+ const hits = []
243
+ for (const h of paragraphHits(text, { promptFace: isPromptFace(abs), region })) {
244
+ hits.push({ file: abs, line: h.line, kind: HIT_KIND.paragraph, len: h.len })
245
+ }
246
+ for (const h of lineRefHits(text)) if (inRegion(h.line)) hits.push({ file: abs, line: h.line, kind: HIT_KIND.lineRef, token: h.token })
247
+ // 批档面整份不判悬空(§3):批档是可整份删掉的执行记录,不是导航——记录里出现一个不存在的档名
248
+ // 是这一轮的**发现**,判它等于把发现本身拦在门外。**这条豁免本身就是写时点的规则**:写的那一刻
249
+ // 段长 ∥ 行号锚对批档照旧生效;收口时点批档整份不进判域,那一半由 `judgedDomainDocs` 管(§9)。
250
+ if (!isBatchFace(abs, root)) {
251
+ for (const h of existenceHits(text, { root, planned, indexPath })) {
252
+ if (inRegion(h.line)) hits.push({ file: abs, line: h.line, kind: HIT_KIND.missing, token: h.token })
253
+ }
254
+ }
255
+ return hits
115
256
  }
116
257
 
117
- /** gate 报面(固定句形——§3.20「报面(固定句形 · 交付门 gate)」):首行 verdict = 唯一机判串。 */
118
- function gateReport({ base, docsSource, checkFiles, skipped, anchors, paragraphs }) {
119
- const total = anchors.hits.length + paragraphs.length
120
- const src = docsSource === "session" ? "本会话写过的文档" : "显式 docs"
121
- // 首行:锚与段分列(用户 11:16:段的问题叫「文字太长,难于阅读」,不是「命中 N 条」也不是字符数)
122
- const verdict = () => {
123
- if (total === 0) return checkFiles.length ? "DOC-CHECK GATE: PASS" : "DOC-CHECK GATE: PASS(0 档)"
124
- const parts = []
125
- if (anchors.hits.length) parts.push(`锚 ${anchors.hits.length} 条`)
126
- // 段与行分列——两类命中不得合并(提示词面一行 = 一个块,属「行太长」,不是「一段文字太长」)
127
- const paraCount = paragraphs.filter((h) => h.clazz === DOC_CLASS.para).length
128
- const lineCount = paragraphs.filter((h) => h.clazz === DOC_CLASS.line).length
129
- if (paraCount) parts.push(`${paraCount} 段${DOC_CLASS.para}`)
130
- if (lineCount) parts.push(`${lineCount} ${DOC_CLASS.line}`)
131
- return `DOC-CHECK GATE: REFUSED(${parts.join(" · ")})`
132
- }
133
- const out = [
134
- verdict(),
135
- "文档纪律机检(交付门 · gate)",
136
- checkFiles.length
137
- ? `范围:${src} ${checkFiles.length} 档`
138
- : `范围:${src} —— **0 档受检**(空清单:本次没有判任何档,不得读作「已检」)`,
139
- "判据:逐段检查——" + DOC_CLASS.para,
140
- ]
141
- if (skipped.missing.length) out.push(`跳过 ${skipped.missing.length} 档(已不在盘,未检):${skipped.missing.map((p) => rel(base, p)).join(" ∥ ")}`)
142
- if (skipped.notMarkdown.length) out.push(`跳过 ${skipped.notMarkdown.length} 档(非 markdown 档,未检):${skipped.notMarkdown.map((p) => rel(base, p)).join(" ∥ ")}`)
143
- // 跨仓引用读数(零命中类——不进 `total`、不改 verdict,只让作者看到「这一处没保证」);
144
- // 位置 = 命中区之前,末行仍留给结论 / 处置块。
145
- for (const h of anchors.crossRepo ?? []) out.push(crossRepoLine(h))
146
- if (checkFiles.length === 0) {
147
- // 空范围不静默当通过(K6)——照实说明 + 给出补充通道(两侧都不得读成「已检」)。
148
- // 措辞按「有没有跳过行」分流:无跳过行时不得写「见上方跳过行」。
149
- const hasSkips = skipped.missing.length > 0 || skipped.notMarkdown.length > 0
150
- out.push(docsSource === "session"
151
- ? (hasSkips
152
- ? "范围为空:本会话触达的档均不可判(见上方跳过行)——若确认改过 ⇒ 显式传 docs"
153
- : "范围为空:本会话没有写过 .md 档——若确认改过 ⇒ 显式传 docs")
154
- : (hasSkips
155
- ? "范围为空:显式 docs 里没有可判档——见上方跳过行"
156
- : "范围为空:显式 docs 是空清单——列出要判的档后复跑"))
157
- } else if (total === 0) {
158
- out.push(`结论:0 段有问题(${checkFiles.length} 档全清)`)
159
- } else {
160
- for (const h of anchors.hits) out.push(anchorHitLine(base, h))
161
- for (const w of paragraphs) out.push(paragraphHitLine(base, w))
162
- // 处置块只跟「段」命中走:仅有行太长时不得叫人对段落重写;字面单源 = `PARA_DISPOSE`(三处消费面同一份)
163
- if (paragraphs.some((h) => h.clazz === DOC_CLASS.para)) out.push(...PARA_DISPOSE)
164
- }
165
- return out.join("\n")
258
+ /**
259
+ * 一条命中的人话(报面行形的单一出处:三个调用点都不拼字面)。
260
+ * 字面 = `docs/core/design/DOC-CHECK.md` §5 的三句。
261
+ */
262
+ export function hitLine(root, h) {
263
+ const at = displayPath(root, h.file)
264
+ if (h.kind === HIT_KIND.missing) return `${at} ${h.token} 这个档不存在`
265
+ if (h.kind === HIT_KIND.paragraph) return `${at} 第 ${h.line} 段 ${h.len} 字,超过 ${PARAGRAPH_MAX}`
266
+ return `${at} 第 ${h.line} 行的 ${h.token} 用行号做锚,行号会漂`
166
267
  }
167
268
 
168
269
  /**
169
- * 跑一次文档纪律机检。
170
- * @param {string} root 项目根(解析序 ① 的基准)
171
- * @param {{docs?:string[], mode?:'report'|'gate', docsSource?:'session'|'explicit'}} [o]
172
- * `mode` 缺省 = `report`;`docs` = 被判档清单(相对 `root` 或绝对)——**必填**(两种问法同):
173
- * 缺省 ∥ 非数组 ⇒ 报错要求显式清单(零遍历、零全域兜底);`report` 面**空数组也报错**,`gate` 面空数组 ⇒
174
- * `PASS(0 档)` + 空范围说明(「本轮一档没碰」是真实读数);`report` 面不可判档 ⇒ 报错、整次零判定;
175
- * `gate` 面不可判档 ⇒ 跳过行;`docsSource` = 范围来源标签(`session` = 本会话触达记账 ∥ `explicit` = 显式
176
- * `docs`)——缺省 = `explicit`;只影响报面措辞。
177
- * @returns {{report:string, hits:{total:number, anchors:number, paragraph:number}, anchorHits:Array,
178
- * paragraphHits:Array, files:string[], checkFiles:string[], paragraphMax:number,
179
- * skipped:{missing:string[], notMarkdown:string[]}, lineRefs?:{body:Array, fenced:Array, total:number}}}
180
- * `lineRefs`(行号坐标清单的采集结果)**只在 `report` 面返回**——`gate` 面构造上不产该字段。
181
- * 消费面判「清」须读 `report` 首行(gate)∥ `hits.total`(report),不得只看其中一个。
270
+ * 跑一次文档机检。
271
+ * @param {string} root 基根(相对 `docs` 条目按它解析;某档不在任何项目内时也落它)
272
+ * @param {{docs:string[], moment:'writer'|'close',
273
+ * regions:Map<string,{rows:number[],gaps:number[]}>|null}} o `docs` = 被判档清单(相对 `root` 或绝对)——**必填**:
274
+ * 缺省 ∥ 非数组 ∥ 空清单 ⇒ 抛(什么都没有的清单一律不许读成「判过且干净」)。
275
+ * `moment` = 这一刻谁在调(**必填**,判法单源 = `judgedDomainDocs`):收口时点落进批档面的那些档整份不进判域
276
+ * ⇒ 它们连「不在盘,未判」都不出一行(那一句留给判域内读不到的档);调用方交进来的清单因此可能判完 0 档。
277
+ * `regions` = 本批变更区(**必填,不收缺省值**,判据句单源 = `docs/core/design/DOC-CHECK.md` §6):
278
+ * `null` = 判整份(诊断面 ∥ 写时点的新档与读不到现文那一支);表 = 只判表里那几行,键 = `resolve(<档>)`;
279
+ * **表里某一格可以是 `null`**(= 这一档判整份;写时点那一臂用它在「盘上读不到现文」时交整份)。
280
+ * **没有要判的行 ⇒ 这一档一行也不出**(不在表里 ∥ 表里没它的条目):不点名、不解释,也不计入 `checkFiles`。
281
+ * @returns {{report:string, verdict:'PASS'|'REFUSED', hits:Array, checkFiles:string[],
282
+ * missing:string[], unreadable:string[]}}
283
+ * `hits` = 三判据的命中(每条携 `file` ∥ `line` ∥ `kind`),`missing` ∥ `unreadable` = 没判成的档;
284
+ * `checkFiles` = **真判过的档**(判域外的档不在其中——回执与 `范围 N 档` 数的是同一件事)。
182
285
  */
183
- export function runDocCheck(root, { docs, mode = "report", docsSource } = {}) {
184
- const base = resolve(root)
185
- const gate = mode === "gate"
186
- if (docs !== undefined && !Array.isArray(docs)) {
187
- throw new Error(`doc_check: \`docs\` must be an array of paths (got ${typeof docs}) — a bare string is refused rather than read as a whole-domain request; pass ["<path>"].`)
286
+ export function runDocCheck(root, { docs, moment, regions } = {}) {
287
+ const base = resolve(String(root ?? "."))
288
+ if (regions === undefined) {
289
+ throw new Error("doc_check: `regions` must be given on every call — null (judge each document whole: the diagnostic face, or a write-time document with no old text to compare) or the changed-region table keyed by `resolve(<doc>)` (judge only those lines). It is never defaulted: the default would decide the domain on the caller's behalf.")
188
290
  }
189
291
  if (!Array.isArray(docs)) {
190
- throw new Error('doc_check: `docs` is required — pass the explicit list of documents to judge. There is no default range: nothing is scanned unless you name it.')
191
- }
192
- // 报告态空清单 = 报错(「没跑」不得装成「跑了且清」);gate 面空清单照实出 `PASS(0 档)` + 空范围说明
193
- // ——交付面「本轮一档没碰」是一种真实读数,不是省略。
194
- if (!gate && (docs.length === 0 || docs.every((d) => typeof d !== "string" || d.trim() === ""))) {
195
- throw new Error('doc_check: docs is empty — an empty list names no document, so nothing can be judged; list the documents you mean.')
196
- }
197
- const source = docsSource ?? "explicit"
198
- const range = resolveRange(base, docs)
199
- // 清单条目本身非法(非字符串 / 空白)——调用方错误,两种问法同拒:静默丢掉一条就是不静默地收窄范围。
200
- if (range.invalid.length) {
201
- throw new Error(`doc_check: \`docs\` entries ${range.invalid.map((i) => `[${i}]`).join(", ")} are not paths — every entry must be a non-empty string; no document was judged.`)
202
- }
203
- // 报告态 fail-closed:清单里有一个不可判档 ⇒ 报错点名、整次零判定——清单写错却报 0 命中就是「没跑」装成「跑了且清」。
204
- if (!gate && range.undecidable.length) {
205
- const named = range.undecidable.map((u) => `${rel(base, u.abs)}(${u.reason})`).join(" ∥ ")
206
- throw new Error(`doc_check: docs names ${range.undecidable.length} document(s) that cannot be judged — no document was checked: ${named}. Fix the list and re-run; nothing is silently skipped and the check never widens beyond the list.`)
207
- }
208
- const checkFiles = range.check
209
- const { paragraphMax, lineMax, paragraphExemptZones } = DOC_CHECK_BUILTINS
210
- const anchors = checkAnchors(base, { files: checkFiles })
211
- const paragraphs = checkParagraphs({ paragraphMax, lineMax, exemptZones: paragraphExemptZones, files: checkFiles })
212
-
213
- const hits = { total: anchors.hits.length + paragraphs.length, anchors: anchors.hits.length, paragraph: paragraphs.length }
214
- const shared = {
215
- hits, anchorHits: anchors.hits, paragraphHits: paragraphs, files: checkFiles, checkFiles, paragraphMax,
216
- skipped: { missing: range.missing, notMarkdown: range.notMarkdown },
292
+ throw new Error(`doc_check: \`docs\` must be an array of paths (got ${typeof docs}) — a bare string is refused rather than read as a whole-domain request; pass ["<path>"].`)
217
293
  }
218
- if (gate) {
219
- return { ...shared, report: gateReport({ base, docsSource: source, checkFiles, skipped: shared.skipped, anchors, paragraphs }) }
294
+ if (docs.length === 0 || docs.some((d) => typeof d !== "string" || d.trim() === "")) {
295
+ throw new Error("doc_check: `docs` names no document — pass the explicit list of documents to judge. There is no default range: nothing is scanned unless you name it.")
220
296
  }
221
-
222
- // 行号坐标清单的**唯一采集点**:放在 `if (gate)` 早返回之后——`gate` 分支上一行已返回,够不着这里。
223
- // 「闸看不见清单」靠这个结构成立(不是「算出来再声明它不参与」——一份存在但被声明无用的数,读者迟早拿它当判据)。
224
- const lineRefs = collectLineRefs({ files: checkFiles })
225
-
226
- const out = [
227
- "文档纪律机检(报告态 · 非门禁)",
228
- `射程:${base} · 传入清单 ${checkFiles.length} 档 · 区带豁免:${paragraphExemptZones.length ? paragraphExemptZones.join(" ∥ ") : "无"}`,
229
- "声明:判据参数 = 工具内置常量;范围 = 传入文件(判定范围 = 解析范围)",
230
- `范围:传入清单 ${checkFiles.length} 档(整档入判 · 判定范围 = 解析范围)`,
231
- `命中 ${hits.total} 条(锚 ${anchors.hits.length} · ${DOC_CLASS.para} ${paragraphs.filter((h) => h.clazz === DOC_CLASS.para).length} · ${DOC_CLASS.line} ${paragraphs.filter((h) => h.clazz === DOC_CLASS.line).length})`,
232
- ]
233
- for (const h of anchors.hits) out.push(anchorHitLine(base, h))
234
- for (const w of paragraphs) out.push(paragraphHitLine(base, w))
235
- // 跨仓引用读数(零命中类——只报不拦,位置 = 命中区之后、清单块之前)
236
- for (const h of anchors.crossRepo ?? []) out.push(crossRepoLine(h))
237
- // 清单块位置 = 命中区之后、末行 `结论:…` 之前(报面的末行恒是结论句,清单不抢它的位)。
238
- out.push(...lineRefsBlock({ base, files: checkFiles, refs: lineRefs }))
239
- out.push(hits.total ? `结论:${hits.total} 条命中——报告态,不作拒执行的理由` : `结论:0 条命中(锚 ∥ ${DOC_CLASS.para} ∥ ${DOC_CLASS.line} 均清)`)
240
-
241
- return { ...shared, report: out.join("\n"), lineRefs }
297
+ // 判域 = 交进来的清单 ∩ 这一刻要判的档(§9)。空清单的护栏在上面、按**交进来的**清单判:
298
+ // 「一张清单都没给」与「给的都在判域外」是两件事——后者是这一批确实没有别的档可判。
299
+ const domain = judgedDomainDocs(docs, { moment, root: base })
300
+ const plannedByRoot = new Map()
301
+ const plannedOf = (r) => {
302
+ if (!plannedByRoot.has(r)) plannedByRoot.set(r, plannedPathsOf(r))
303
+ return plannedByRoot.get(r)
304
+ }
305
+ const indexByRoot = new Map()
306
+ const indexOf = (r) => {
307
+ if (!indexByRoot.has(r)) indexByRoot.set(r, pathIndexOf(r))
308
+ return indexByRoot.get(r)
309
+ }
310
+ const checkFiles = []
311
+ const hits = []
312
+ const missing = []
313
+ const unreadable = []
314
+ for (const d of domain) {
315
+ const abs = resolve(base, d)
316
+ // 本批变更区(§6):表里没它的条目 ⇒ 这一档没有要判的行 ⇒ 一行也不出(不点名、不计数)。
317
+ const region = regions === null ? null : regions.get(abs)
318
+ if (regions !== null && region === undefined) continue
319
+ let text
320
+ try { text = readFileSync(abs, "utf8") } catch (e) {
321
+ // 区间面、区内只有纯删的缝(`rows` 空)、且盘上真没了(ENOENT)= 这一档在建档之后被删掉整份
322
+ // ⇒ 没有文本可判 ⇒ 一行也不出(§6)。两个条件缺一条就不是那个情形:还在地盘上却读不到,
323
+ // 那一句「读不到,未判」仍然是留给它的(§9)。
324
+ if (regions !== null && region !== null && (region.rows ?? []).length === 0 && e?.code === "ENOENT") continue
325
+ if (e?.code === "ENOENT") missing.push(abs)
326
+ else unreadable.push(abs)
327
+ continue
328
+ }
329
+ checkFiles.push(abs)
330
+ const docRoot = projectRootOf(abs, base)
331
+ hits.push(...judgeText(text, { file: abs, root: docRoot, planned: plannedOf(docRoot), indexPath: indexOf(docRoot), region }))
332
+ }
333
+ const out = [`DOC-CHECK GATE: ${hits.length ? "REFUSED" : "PASS"}`]
334
+ for (const h of hits) out.push(hitLine(base, h))
335
+ for (const p of missing) out.push(`${displayPath(base, p)} 不在盘,未判`)
336
+ for (const p of unreadable) out.push(`${displayPath(base, p)} 读不到,未判`)
337
+ return { report: out.join("\n"), verdict: hits.length ? "REFUSED" : "PASS", hits, checkFiles, missing, unreadable }
242
338
  }