@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
@@ -0,0 +1,143 @@
1
+ import { listKnowledgeTopics, loadKnowledgeTopic, readKnowledgeEntries } from "../prompt-files.mjs"
2
+ import { DESC } from "./shared.mjs"
3
+
4
+ const SEARCH_SNIPPETS_PER_TOPIC = 3
5
+ /** 单主题定位片段的字长上限(导出给用例判同一组数)。 */
6
+ export const SEARCH_SNIPPET_CHARS = 240
7
+ /** 单次 search 的成本门:主题数与紧凑 JSON 字符数,先到者截断(导出给集成用例判同一组上限)。 */
8
+ export const SEARCH_MAX_TOPICS = 10
9
+ export const SEARCH_MAX_CHARS = 6000
10
+
11
+ /**
12
+ * 高频虚词:分词、转小写、去重之后、计分之前去掉,大小写不敏感。
13
+ * 它治的是排序噪声而不是体积(体积已由两个上限兜住)——`the` 命中几乎全部主题,会把 `evidence`
14
+ * 这种真信号顶出有界结果。中文不另做分词:按空白切,中文整句本就是一个词,虚词过滤对它无效,
15
+ * 中文查询靠主题首行的 `aliases:` 别名命中。
16
+ */
17
+ const SEARCH_STOPWORDS = new Set([
18
+ // 英文约二十个
19
+ "the", "a", "an", "of", "to", "in", "on", "at", "is", "are", "was", "were", "be", "been",
20
+ "for", "and", "or", "not", "with", "by", "from", "this", "that", "it", "as",
21
+ // 中文约二十个
22
+ "的", "了", "在", "是", "和", "与", "或", "就", "也", "都", "而", "及", "其", "之", "于", "对", "从", "把", "被", "让",
23
+ ])
24
+
25
+ /**
26
+ * 查询 → 参与计分的词。整串转小写后按空白切、逐词剥去首尾标点、丢掉剥空的词、去重、去停用词,最后
27
+ * 排序(查询词序因而影响不了片段集合与名次)。
28
+ * 剥的是词首尾「不属于字母、数字或组合附加符(`\p{L}` ∥ `\p{N}` ∥ `\p{M}`)」的字符:中文括号、全角
29
+ * 标点与表情一并剥掉,词内字符原样保留——`doc?` → `doc`、`compaction,` → `compaction`,而 `doc-check`
30
+ * 整词不动。按标点把整串拆开会把语料里唯一稳定的标识符形式打散:随包主题标识无一例外都带连字符。
31
+ * 去重必须排在剥之后:否则 `doc? doc` 留下两个 `doc`,`titleHits` 与 `totalHits` 各计两次,命中该词的
32
+ * 主题被同倍抬高,与别的词命中同一批主题的名次当场错开。
33
+ * 过滤后一个词都不剩 ⇒ 显式失败并点名 `query`:全虚词查询(`the`、`a of the`)与只有标点的查询(`?`)
34
+ * 走的就是这一支,报文点名两种清空原因,不退化成一句「没有匹配」——两者在模型看来长得一模一样。
35
+ */
36
+ function tokenizeQuery(query) {
37
+ const stripped = query
38
+ .toLowerCase()
39
+ .split(/\s+/)
40
+ .filter(Boolean)
41
+ .map((word) => word.replace(/^[^\p{L}\p{N}\p{M}]+|[^\p{L}\p{N}\p{M}]+$/gu, ""))
42
+ .filter(Boolean)
43
+ const tokens = [...new Set(stripped)]
44
+ const meaningful = tokens.filter((token) => !SEARCH_STOPWORDS.has(token)).sort()
45
+ if (meaningful.length === 0) {
46
+ throw new Error(`knowledge search: No searchable word in query ${JSON.stringify(query)} after stopword and punctuation filtering — replace it with a concrete noun, or call list for every topic id`)
47
+ }
48
+ return meaningful
49
+ }
50
+
51
+ /**
52
+ * 按一个主题条目计分。检索面 = 标识 ∥ 标题 ∥ 别名 ∥ 正文,任一词命中即入选(OR)。
53
+ * 标题级命中数 = 命中的**不同词数**(标识、标题、别名都算标题级:别名就是为引路而写的,命中它与
54
+ * 命中标题是同一个信号);总命中数 = 各词在正文里的出现次数之和(标题就在正文里,只数一次)。
55
+ * 同一主题内多个词命中同一段时只取一次,不重复计入字符预算;一段至多 `SEARCH_SNIPPET_CHARS` 字符。
56
+ * 两键都为 0 返回 null(只命中别名的主题也入选——中文查询走的就是那一支)。
57
+ * 命中偏移在小写串上算、从原串上切:两者只在「小写不改变长度」的字符上对齐(盘上主题是 ASCII 与中文)。
58
+ * 不做 Unicode 归一,所以会改变长度的字符(如 `İ`)会让片段错位——今日盘面无此类字符。
59
+ */
60
+ function scoreTopic(entry, tokens) {
61
+ const titleSurface = [entry.id, entry.title, ...entry.aliases].join("\n").toLowerCase()
62
+ const body = entry.content.toLowerCase()
63
+ const matches = []
64
+ const spans = []
65
+ let titleHits = 0
66
+ let totalHits = 0
67
+ for (const token of tokens) {
68
+ let bodyHits = 0
69
+ for (let at = body.indexOf(token); at >= 0; at = body.indexOf(token, at + token.length)) {
70
+ bodyHits += 1
71
+ if (matches.length >= SEARCH_SNIPPETS_PER_TOPIC) continue
72
+ // 先钉住词的结尾,再往前留至多一段——长词也整词落在片段里,且片段长度不越 SEARCH_SNIPPET_CHARS
73
+ const end = Math.min(entry.content.length, at + token.length + Math.floor(SEARCH_SNIPPET_CHARS / 2))
74
+ const start = Math.max(0, end - SEARCH_SNIPPET_CHARS)
75
+ if (spans.some(([from, to]) => start < to && from < end)) continue
76
+ spans.push([start, end])
77
+ matches.push(entry.content.slice(start, end))
78
+ }
79
+ totalHits += bodyHits
80
+ if (titleSurface.includes(token)) titleHits += 1
81
+ }
82
+ if (titleHits === 0 && totalHits === 0) return null
83
+ return { id: entry.id, title: entry.title, matches, titleHits, totalHits }
84
+ }
85
+
86
+ /**
87
+ * 定序并按两个上限收集:标题级命中数 → 总命中数 → 标识升序;下一个主题会越过主题数或字符数
88
+ * 任一上限时不再加入。字符数按整份返回的紧凑 JSON 计量(含外层字段),且用**此刻就要交付的那个**
89
+ * `truncated` 值计量:`true` 比 `false` 少一个字符,用错一侧就会让实际交付比计量值多一个字符、真的
90
+ * 越过上限。截断如实披露(`matched` / `shown` / `truncated`):只给 10 条而无一字说明,会被读成
91
+ * 「只有 10 条命中」,上限就从成本门变成了相关性判断。
92
+ */
93
+ function boundedHits(hits) {
94
+ const matched = hits.length
95
+ const ordered = [...hits].sort((a, b) => b.titleHits - a.titleHits || b.totalHits - a.totalHits || a.id.localeCompare(b.id))
96
+ const results = []
97
+ for (const hit of ordered) {
98
+ if (results.length >= SEARCH_MAX_TOPICS) break
99
+ const candidate = { id: hit.id, title: hit.title, matches: hit.matches }
100
+ // 加完这一条后是否还有命中被落下,就是交付时的 truncated 值——按它计量才与实际返回同长
101
+ const truncated = results.length + 1 < matched
102
+ const size = JSON.stringify({ matched, shown: results.length + 1, truncated, results: [...results, candidate] }).length
103
+ if (size > SEARCH_MAX_CHARS) break
104
+ results.push(candidate)
105
+ }
106
+ return { matched, shown: results.length, truncated: results.length < matched, results }
107
+ }
108
+
109
+ export const knowledgeTool = {
110
+ name: "knowledge",
111
+ description: DESC("knowledge"),
112
+ parameters: {
113
+ type: "object",
114
+ properties: {
115
+ action: { type: "string", enum: ["list", "search", "get"], description: "list topic ids and titles; search only locates topics; get reads one complete topic" },
116
+ query: { type: "string", description: "search keyword" },
117
+ topic: { type: "string", description: "exact topic identifier for get" },
118
+ },
119
+ required: ["action"],
120
+ },
121
+ readonly: true,
122
+ async execute(args) {
123
+ const action = args?.action
124
+ if (action === "list") {
125
+ return listKnowledgeTopics().map(({ id, title }) => `${id} — ${title}`).join("\n")
126
+ }
127
+ if (action === "get") {
128
+ if (typeof args.topic !== "string" || !args.topic.trim()) throw new Error("knowledge get: topic is required")
129
+ return loadKnowledgeTopic(args.topic)
130
+ }
131
+ if (action === "search") {
132
+ if (typeof args.query !== "string" || !args.query.trim()) throw new Error("knowledge search: query is required")
133
+ const query = args.query.trim()
134
+ const tokens = tokenizeQuery(query)
135
+ const hits = readKnowledgeEntries().map((entry) => scoreTopic(entry, tokens)).filter(Boolean)
136
+ if (hits.length === 0) {
137
+ return `No knowledge topics matched ${JSON.stringify(query)}. Try one English keyword, or call list to see every topic id.`
138
+ }
139
+ return JSON.stringify(boundedHits(hits))
140
+ }
141
+ throw new Error(`knowledge: action must be one of list/search/get — got ${JSON.stringify(action)}`)
142
+ },
143
+ }
package/tools/linter.mjs CHANGED
@@ -30,7 +30,7 @@ export const lintTool = {
30
30
  }
31
31
 
32
32
  // Full cascade: language-aware (tsc → node --check, ruff, cargo, go vet —
33
- // third-party linter cascade removed 2026-09-02, TOOLS.md §10.2: zero-dependency lint)
33
+ // third-party linter cascade removed 2026-09-02: zero-dependency lint)
34
34
  const ext = abs.split(".").pop()?.toLowerCase()
35
35
  const checkers = LANG_CHECKERS[ext]
36
36
  if (!checkers) return nodeCheckResult(abs, ctx.signal) // fall back to node --check
@@ -56,7 +56,7 @@ async function nodeCheckResult(abs, signal) {
56
56
  }
57
57
  }
58
58
 
59
- // ─── Full-check cascade checkers (third-party linter branch removed 2026-09-02, TOOLS.md §10.2) ──────
59
+ // ─── Full-check cascade checkers (third-party linter branch removed 2026-09-02) ──────
60
60
 
61
61
  async function tscCheck(file, { cwd, signal, existsSync, join, run }) {
62
62
  if (!existsSync(join(cwd, "tsconfig.json"))) return null
@@ -110,7 +110,7 @@ async function goVet(file, { cwd, signal, run }) {
110
110
  }
111
111
 
112
112
  const LANG_CHECKERS = {
113
- // js/mjs/cjs/jsx fall back to node --check (no entry — third-party linter cascade removed 2026-09-02, TOOLS.md §10.2)
113
+ // js/mjs/cjs/jsx fall back to node --check (no entry — third-party linter cascade removed 2026-09-02)
114
114
  ts: [tscCheck],
115
115
  tsx: [tscCheck],
116
116
  mts: [tscCheck],
package/tools/ops.mjs CHANGED
@@ -7,7 +7,7 @@
7
7
  * wait_for 条件族 +`bash id:N done`。list ∥ 既有条件面零变。批 browser-async-fix(#1045):kill id
8
8
  * 路由先 bg 后 browser(同一 id 命名空间)∥ wait_for 条件族 +`browser id:N done`。
9
9
  */
10
- import { DESC, resolveInCwd, truncate, LEDGER_PARAM_DESC } from "./shared.mjs"
10
+ import { DESC, resolveInCwd, truncate, LEDGER_PARAM_DESC, PROJECT_PARAM_DESC } from "./shared.mjs"
11
11
  // 单一写路径点(编辑器编辑径注入缝——CORE-UNIFICATION §2.13.5):路径操作也经它落盘
12
12
  // (默认径 = 既有 cp / rename / EXDEV 回退语义,零行为变)。
13
13
  import { writeThroughPath } from "./write-path.mjs"
@@ -27,6 +27,8 @@ export const fileOpsTool = {
27
27
  source: { type: "string", description: "Source path, relative to cwd or absolute" },
28
28
  dest: { type: "string", description: "Destination path" },
29
29
  ledger: { type: "string", description: LEDGER_PARAM_DESC },
30
+ // 工作区根窄口(设计档 §2.3.1):目标取不到项目根时才被读;目标有根时以路径为准(定位参数优先)。
31
+ project: { type: "string", description: PROJECT_PARAM_DESC },
30
32
  },
31
33
  required: ["action", "source", "dest"],
32
34
  },
package/tools/patch.mjs CHANGED
@@ -5,9 +5,13 @@ import {
5
5
  normalizeEOL,
6
6
  detectFileEol,
7
7
  majorityEol,
8
- LEDGER_PARAM_DESC
8
+ LEDGER_PARAM_DESC,
9
+ PROJECT_PARAM_DESC
9
10
  } from "./shared.mjs";
10
11
  import { writeThroughPath, TMP_SUFFIX, markDirty, clearLastWrite } from "./write-path.mjs";
12
+ // 失败回执(未全成)两件文案单源 = edit-receipt.mjs(骨架单源 = EDIT-HELPERS §4 ·
13
+ // 决策 = APPLY-PATCH §7 D-P4):与 `edit` 批面同一副骨架,本工具只填工具名 ∥ 单位 ∥ 定位。
14
+ import { editEntryFailureLine, editBatchSummary, FILE_UNIT } from "./edit-receipt.mjs";
11
15
  import { spawnGit } from "./git-run.mjs";
12
16
  import { mkdir, readFile, lstat, unlink } from "node:fs/promises";
13
17
  import { existsSync } from "node:fs";
@@ -140,7 +144,7 @@ function applyHunks(fileLines, hunks, eol, path) {
140
144
  const cr = eol === "\r\n" ? "\r" : ""
141
145
  for (let h = 0; h < hunks.length; h++) {
142
146
  const oldSeq = hunks[h].ops.filter((o) => o.type !== "+").map((o) => o.text)
143
- if (oldSeq.length === 0) throw new Error(`Hunk ${h + 1} in ${path} has no context/removed lines to locate`)
147
+ if (oldSeq.length === 0) throw hunkFailure(h + 1, `Hunk ${h + 1} in ${path} has no context/removed lines to locate`)
144
148
  const matches = []
145
149
  for (let pos = 0; pos + oldSeq.length <= fileLines.length; pos++) {
146
150
  let ok = true
@@ -151,11 +155,11 @@ function applyHunks(fileLines, hunks, eol, path) {
151
155
  }
152
156
  if (matches.length === 0) {
153
157
  const preview = oldSeq.slice(0, 3).join(" ⏎ ")
154
- throw new Error(`Hunk ${h + 1} in ${path} does not apply — context not found: "${preview}${oldSeq.length > 3 ? "…" : ""}". Read the file first and regenerate the patch from actual content.`)
158
+ throw hunkFailure(h + 1, `Hunk ${h + 1} in ${path} does not apply — context not found: "${preview}${oldSeq.length > 3 ? "…" : ""}". Read the file first and regenerate the patch from actual content.`)
155
159
  }
156
160
  if (matches.length > 1) {
157
161
  const preview = oldSeq.slice(0, 3).join(" ⏎ ")
158
- throw new Error(`Hunk ${h + 1} in ${path} matches ${matches.length} locations — add more context lines to make it unique. Anchor: "${preview}${oldSeq.length > 3 ? "…" : ""}"`)
162
+ throw hunkFailure(h + 1, `Hunk ${h + 1} in ${path} matches ${matches.length} locations — add more context lines to make it unique. Anchor: "${preview}${oldSeq.length > 3 ? "…" : ""}"`)
159
163
  }
160
164
  const pos = matches[0]
161
165
  const out = []
@@ -169,6 +173,66 @@ function applyHunks(fileLines, hunks, eol, path) {
169
173
  }
170
174
  }
171
175
 
176
+ /** hunk 段失败带上 hunk 序(1-based):回执的定位 = `<path> hunk <n>`(APPLY-PATCH.md §4)——
177
+ * 调用方据 `hunkNumber` 组装定位,不去解析文案(错误对象本来只有文本、不带路径)。 */
178
+ function hunkFailure(hunkNumber, message) {
179
+ const err = new Error(message)
180
+ err.hunkNumber = hunkNumber
181
+ return err
182
+ }
183
+
184
+ /**
185
+ * 失败回执(未全成):逐档一行、按补丁序 + 末行汇总——骨架单源 = `docs/core/design/EDIT-HELPERS.md`
186
+ * §4,本工具只填填充位(工具名 `apply_patch` · 单位 `file(s)` ⇒ 末段省:报单位 = 写单位 = 档)。
187
+ *
188
+ * 三态逐档行:已落盘 ` modified <path>` ∥ ` created <path>`(逐字复用全成路径那一行)·
189
+ * 失败那档 `<定位> — failed: <原因原文>`(hunk 段带 hunk 序)· 未落盘且没有自身原因的档
190
+ * ` not committed <path>`——不替它编一个原因(APPLY-PATCH.md §4)。
191
+ */
192
+ function failureReceipt({ entries, failedPath, failedHunk, reason }) {
193
+ const lines = []
194
+ for (const e of entries) {
195
+ if (failedPath != null && e.path === failedPath) {
196
+ lines.push(editEntryFailureLine(failedHunk == null ? e.path : `${e.path} hunk ${failedHunk}`, reason))
197
+ } else if (e.landed) {
198
+ lines.push(` ${e.isNew ? "created " : "modified"} ${e.path}`)
199
+ } else {
200
+ lines.push(` not committed ${e.path}`)
201
+ }
202
+ }
203
+ const written = entries.filter((e) => e.landed).map((e) => e.path)
204
+ lines.push(editBatchSummary({ tool: "apply_patch", applied: written.length, total: entries.length, unit: FILE_UNIT, filesWritten: written }))
205
+ return lines.join("\n")
206
+ }
207
+
208
+ /**
209
+ * 阶段一(hunk 段):读盘 + 内存算 + 全部 hunk 应用——任一档失败 ⇒ 调用方一个字节都还没写。
210
+ * `onFile(f)` = 正在算的那一档:失败回执靠它点名失败档,并与 `hunkNumber` 配对组装定位。
211
+ */
212
+ async function planFiles(files, ctx, onFile) {
213
+ const planned = []
214
+ for (const f of files) {
215
+ onFile(f)
216
+ const abs = resolveInCwd(ctx, f.path)
217
+ if (f.isNew) {
218
+ if (existsSync(abs)) throw new Error(`Cannot create ${f.path}: file already exists`)
219
+ // New file: follow the directory's majority EOL style (default LF).
220
+ const eol = majorityEol(dirname(abs))
221
+ const content = f.hunks.flatMap((h) => h.ops.filter((o) => o.type === "+").map((o) => o.text)).join(eol) + eol
222
+ planned.push({ abs, path: f.path, content, isNew: true })
223
+ } else {
224
+ const original = await readFile(abs, "utf8").catch(() => { throw new Error(`File not found: ${f.path}`) })
225
+ const eol = detectFileEol(original)
226
+ // Apply hunks in the normalized LF domain, then write back joined with the
227
+ // file's ORIGINAL EOL style — join("\n") here used to rewrite CRLF files as LF.
228
+ const lines = normalizeEOL(original).split("\n")
229
+ applyHunks(lines, f.hunks, "\n", f.path)
230
+ planned.push({ abs, path: f.path, content: lines.join(eol), isNew: false })
231
+ }
232
+ }
233
+ return planned
234
+ }
235
+
172
236
  export const applyPatchTool = {
173
237
  name: "apply_patch",
174
238
  description: DESC("apply_patch"),
@@ -177,6 +241,8 @@ export const applyPatchTool = {
177
241
  properties: {
178
242
  patch: { type: "string", description: "Unified diff. May span multiple files (multiple --- / +++ header pairs — including creating MULTIPLE new files via --- /dev/null); --- / +++ headers per file, @@ -old,count +new,count @@ hunks (a bare @@ header is also accepted — coordinate-less hunks are located by their anchor lines: context lines plus the removed (-) lines, matched as a contiguous sequence — a unique match applies; a zero/one-context hunk is accepted only when it removes (-) at least one line and that anchor sequence is unique, while anchor-free pure-+ (insert) hunks need at least 2 context lines). The +++ b/<path> pair may be omitted for existing files — a lone --- a/<path> (or --- b/<path>) header followed directly by hunks applies to that path (new files still need --- /dev/null + +++ b/<path>)." },
179
243
  ledger: { type: "string", description: LEDGER_PARAM_DESC },
244
+ // 工作区根窄口(设计档 §2.3.1):目标取不到项目根时才被读;目标有根时以路径为准(定位参数优先)。
245
+ project: { type: "string", description: PROJECT_PARAM_DESC },
180
246
  },
181
247
  required: ["patch"],
182
248
  },
@@ -187,62 +253,75 @@ export const applyPatchTool = {
187
253
  },
188
254
  async execute(args, ctx) {
189
255
  const files = parsePatch(args.patch ?? "")
190
- // Read all into memory first for trial: if any hunk fails, abort entirely — never write a partial patch (atomicity)
191
- const planned = []
192
- for (const f of files) {
193
- const abs = resolveInCwd(ctx, f.path)
194
- if (f.isNew) {
195
- if (existsSync(abs)) throw new Error(`Cannot create ${f.path}: file already exists`)
196
- // New file: follow the directory's majority EOL style (default LF).
197
- const eol = majorityEol(dirname(abs))
198
- const content = f.hunks.flatMap((h) => h.ops.filter((o) => o.type === "+").map((o) => o.text)).join(eol) + eol
199
- planned.push({ abs, path: f.path, content, isNew: true })
200
- } else {
201
- const original = await readFile(abs, "utf8").catch(() => { throw new Error(`File not found: ${f.path}`) })
202
- const eol = detectFileEol(original)
203
- // Apply hunks in the normalized LF domain, then write back joined with the
204
- // file's ORIGINAL EOL style — join("\n") here used to rewrite CRLF files as LF.
205
- const lines = normalizeEOL(original).split("\n")
206
- applyHunks(lines, f.hunks, "\n", f.path)
207
- planned.push({ abs, path: f.path, content: lines.join(eol), isNew: false })
208
- }
256
+ // 阶段一(hunk 段):读盘 + 内存算 + 全部 hunk 应用——任一档失败 ⇒ 一个字节都没写
257
+ // (APPLY-PATCH.md §4「两个失败段」)。失败回执按补丁序列出全部档:失败那档带 hunk 序、
258
+ // 其余档 `not committed`,末行 `k = 0`(零字节,故无路径清单、无末段——单位本来就是档)。
259
+ let inFlight = null // 正在处理的那一档:catch 靠它点名失败档(错误对象不带路径)
260
+ let planned
261
+ try {
262
+ planned = await planFiles(files, ctx, (f) => { inFlight = f })
263
+ } catch (err) {
264
+ throw new Error(failureReceipt({
265
+ entries: files.map((f) => ({ path: f.path, isNew: f.isNew, landed: false })),
266
+ failedPath: inFlight?.path ?? null,
267
+ failedHunk: err?.hunkNumber ?? null,
268
+ reason: err?.message ?? String(err),
269
+ }))
209
270
  }
210
- // Multi-file write: write all to .tmp first, rename only after all succeed — failure cleans up written .tmp without affecting committed files
271
+ // 阶段二(写盘段):逐档暂存 → 逐档提交。**非原子(登记行为)**——已落盘的档留在盘上、不回滚
272
+ // (APPLY-PATCH.md §4 ∥ §7 D-P2);失败时按盘上实况逐档报,`k` 计入每一个已落盘的档。
211
273
  // 两段式经单一写路径点(§2.13.5):阶段一全部 staging(写入各自 `<abs>.thincoder-tmp`)
212
- // ⇒ 阶段二逐档 commit(rename 到目标)。**默认径 = 改前语义逐字同**(任一失败无档落盘:
213
- // 阶段一失败时目标档全未动、阶段二失败时已提交档保持——同改前)。
214
- // 编辑器径(注入面)例外:内容在阶段一即提交(宿主侧同款——applyEdit + save)⇒ 阶段
215
- // 二跳过该档;已提交档不回滚(与宿主侧现行为一致,非本档引入的语义)。
274
+ // ⇒ 阶段二逐档 commit(rename 到目标)。
275
+ // 编辑器径(注入面)例外:内容在阶段一即提交(宿主侧同款——applyEdit + save)⇒ 阶段二跳过该档;
276
+ // 已提交档不回滚(与宿主侧现行为一致,非本档引入的语义),但它**算已落盘**——计入 k、列 modified。
216
277
  const staged = []
217
278
  const committedByEditor = new Set()
279
+ const committed = new Set() // 已落盘 = 注入径已提交 ∪ 提交段 rename 成功——回执的 k 与逐档行的唯一来源
280
+ // Mark every touched file dirty — insert_after must not run on stale line numbers.
281
+ // 整批记账(dirty)= apply_patch 的批级语义;**只对已落盘的档跑,成功 ∥ 失败两路同**(注入径那批在内)——
282
+ // 已落盘却未记账的档会让行号锚护栏拿着写前快照放行(EDIT-HELPERS §3 第 4 行),下一笔行号编辑按旧行号改到别处。
283
+ // 2026-11-02:落 dirty 同时清写入快照——apply_patch 不记快照,留着旧 `startLine` 就是
284
+ // 陈旧的锚:行号锚护栏第 2 行(dirty ∧ 快照在场)会拒,而第 4 行会拿旧值判「目标区在之前
285
+ // ⇒ 放行」——两种结果都不该由一笔没更新快照的写来决定(EDIT-HELPERS §3)。
286
+ const recordCommitted = () => {
287
+ for (const p of planned) {
288
+ if (!committed.has(p.abs)) continue
289
+ markDirty(p.abs)
290
+ clearLastWrite(p.abs)
291
+ }
292
+ }
218
293
  try {
219
294
  for (const p of planned) {
295
+ inFlight = p
220
296
  await mkdir(dirname(p.abs), { recursive: true })
221
- const r = await writeThroughPath(p.abs, p.content, { op: "write", stage: true })
222
- if (r.via === "editor") committedByEditor.add(p.abs)
223
- else staged.push(p.abs)
297
+ const r = await writeThroughPath(p.abs, p.content, { op: "write", stage: true, agent: ctx.agent })
298
+ if (r.via === "editor") {
299
+ committedByEditor.add(p.abs)
300
+ committed.add(p.abs) // 注入径无暂存档(即时提交)⇒ 它已经在盘上了
301
+ } else staged.push(p.abs)
224
302
  }
225
303
  for (const p of planned) {
226
304
  if (committedByEditor.has(p.abs)) continue
305
+ inFlight = p
227
306
  await writeThroughPath(p.abs, null, { op: "commit" })
307
+ committed.add(p.abs)
228
308
  }
229
- } catch (renameError) {
230
- // rename phase failed: clean up leftover .tmp files
309
+ } catch (writeError) {
310
+ // 失败路径照样记账:已落盘的档就是盘上事实,与成功路径同一把尺(否则见上面的护栏后果)。
311
+ recordCommitted()
312
+ // rename / staging 失败:清掉默认径已暂存的 .tmp(那些目标档逐字未动——它们是「没写」,不是「写了」)
231
313
  for (const abs of staged) {
232
314
  try { await unlink(abs + TMP_SUFFIX) } catch {}
233
315
  }
234
- throw renameError
316
+ throw new Error(failureReceipt({
317
+ entries: planned.map((p) => ({ path: p.path, isNew: p.isNew, landed: committed.has(p.abs) })),
318
+ failedPath: inFlight?.path ?? null,
319
+ failedHunk: null, // 写盘段的失败只到档——hunk 早在阶段一应用过,没有 hunk 序可报
320
+ reason: writeError?.message ?? String(writeError),
321
+ }))
235
322
  }
236
323
  const summary = planned.map((p) => ` ${p.isNew ? "created " : "modified"} ${p.path}`).join("\n")
237
- // Mark every touched file dirty — insert_after must not run on stale line numbers.
238
- // 整批记账(dirty)= apply_patch 的批级语义(两段式全成功后一次落账——与改前逐字同)。
239
- // 2026-11-02:落 dirty 同时清写入快照——apply_patch 不记快照,留着旧 `startLine` 就是
240
- // 陈旧的锚:行号锚护栏第 2 行(dirty ∧ 快照在场)会拒,而第 4 行会拿旧值判「目标区在之前
241
- // ⇒ 放行」——两种结果都不该由一笔没更新快照的写来决定(EDIT-HELPERS §7.1)。
242
- for (const p of planned) {
243
- markDirty(p.abs)
244
- clearLastWrite(p.abs)
245
- }
324
+ recordCommitted()
246
325
  const syntaxChecks = await Promise.all(planned.map(async (p) => {
247
326
  const r = await autoSyntaxCheck(p.abs)
248
327
  return r ? `${p.path}:${r.replace("Syntax: ", "")}` : ""
@@ -265,6 +344,7 @@ export const deleteTool = {
265
344
  path: { type: "string", description: "File or empty-directory path (relative to cwd or absolute)" },
266
345
  force: { type: "boolean", description: "Allow deleting git-tracked files (default false)" },
267
346
  ledger: { type: "string", description: LEDGER_PARAM_DESC },
347
+ project: { type: "string", description: PROJECT_PARAM_DESC },
268
348
  },
269
349
  required: ["path"],
270
350
  },
package/tools/shared.mjs CHANGED
@@ -7,7 +7,8 @@ import { execFile } from "node:child_process"
7
7
  import { readFileSync, existsSync, realpathSync, readdirSync, statSync, openSync, readSync, closeSync } from "node:fs"
8
8
  import { dirname, join, resolve } from "node:path"
9
9
  import { fileURLToPath } from "node:url"
10
- import { loadToolDoc, applyPromptInjections } from "../prompt-files.mjs"
10
+ import { loadToolDoc, applyPromptInjections, expandKnowledgeTopics } from "../prompt-files.mjs"
11
+ import { WORK_MODES } from "../config-migrate.mjs"
11
12
  import { spawnGit, gitTimeoutNote, GIT_TIMEOUT_MS } from "./git-run.mjs"
12
13
 
13
14
  const __dirname = dirname(fileURLToPath(import.meta.url))
@@ -21,27 +22,9 @@ export const DESC = (name) => loadToolDoc(name)
21
22
  export const MAX_READ_LINES = 2000
22
23
  export const MAX_OUTPUT_CHARS = 200_000
23
24
 
24
- // ─── 写门 `ledger` 参数(2026-11-03 笔-账绑定批 · 设计档 §2.3「工具 schema 面」)───────────────
25
- // 描述单源:十二把入口工具的 `parameters.properties.ledger` 共用下面这一条(文面逐字 = 设计档 §2.3)。
26
- // 为什么放这里:同一个参数在十二处各写一遍 = 同一机制十二份描述,措辞一旦漂移,模型读到的规则就有十二版;
27
- // 而 `git` ∥ `manifest` ∥ `memory` 的差异只是各接一句「本工具的哪一径要号」——差异走后缀,不复制全文。
28
- // 为什么不进 `required`(决策 35):`required` 是静态字面,而这十二把工具在两模式、子代理、出辖目标下共用;
29
- // 静态必填会让普通模式读到一条不成立的强制(写锁仅工程模式),也让子代理读到一条没人核的要求。
30
- // 机械强制在门(缺号即拒),schema 只负责让模型知道有这个参数;拒文因此是唯一教学面(决策 38)。
31
- export const LEDGER_PARAM_DESC = '本笔调用服务的在途台账号,`"#N"` 或 `"N"`;工程模式下父侧不带 = 拒'
32
- /** `git`:写型 action 要号、只读 action 不要(决策 37——枚举可判,不猜命令字面)。 */
33
- export const LEDGER_PARAM_DESC_GIT = LEDGER_PARAM_DESC
34
- + ';只读 action(`diff` ∥ `status` ∥ `log` ∥ `show` ∥ `ls-remote` ∥ `blame` ∥ 各 `*Action:"list"`)不需传号'
35
- /** `manifest`:只有 `init` ∥ `write` 写项目内档(决策 39)。 */
36
- export const LEDGER_PARAM_DESC_MANIFEST = LEDGER_PARAM_DESC + ';仅 `init` ∥ `write` 要号,`read` 不要'
37
- /** `memory`:只有 `layer:"project"` 写项目内 `.thincoder/memory/**`(决策 39;`put` 缺省 `personal`)。 */
38
- export const LEDGER_PARAM_DESC_MEMORY = LEDGER_PARAM_DESC
39
- + ';仅落 project 层的写型 action 要号:`layer:"project"`,或省略 `layer`、单条删除且 id 以 `project:` 开头(此时层由前缀定;`personal` ∥ `team` 落用户数据目录,不要号)'
40
- /** 写门 `project` 参数(2026-11-03 项目声明面批 · 设计档 §2.3「工具 schema 面」/ 决策 40):项目根路径(带
41
- * `PROJECT-MANIFEST.json` 的那个目录)—— 台账按项目根算键,所以「传项目」就是把这个根传进来,零映射表。
42
- * 五把可能缺定位参数的工具(`bash` ∥ `memory` ∥ `execute` ∥ `git` ∥ `manifest`)共用这一条(文面逐字 = 设计档
43
- * §2.3);写盘七件不加——目标路径恒在。定位参数在场时以它为准,`project` 只补位;纯声明,不改执行目录。 */
44
- export const PROJECT_PARAM_DESC = '本笔调用服务的项目根——带 `PROJECT-MANIFEST.json` 的那个目录(绝对路径,或相对会话 cwd);工程模式下父侧 `bash` ∥ `memory` 必带,`execute` ∥ `git` ∥ `manifest` 在定位参数缺位时必带。纯声明:不改执行目录(`bash` 仍在会话 cwd 执行,`workdir` 才是改执行目录的那个)。'
25
+ // 写门两参的说明文本已搬出本档(设计 TOOLS §1.2):文本单点 = `./write-gate-params.mjs`,这里只转出同一常量,
26
+ // 八处导入档的导入面(`from "./shared.mjs"`)一个字不改。
27
+ export { LEDGER_PARAM_DESC, LEDGER_PARAM_DESC_MEMORY, PROJECT_PARAM_DESC } from "./write-gate-params.mjs"
45
28
 
46
29
  const ENCODING_DETECT_MAX_TRIM = 3
47
30
  const SYNTAX_CHECK_TIMEOUT = 10000
@@ -185,16 +168,34 @@ export function findCandidates(lines, oldString, topN = 3, threshold = 0.5) {
185
168
  /** Appended to hashline_edit results when the file contains U+FFFD (encoding-corruption probe). */
186
169
  export const FFFD_WARNING = "⚠ file contains U+FFFD (replacement char) — encoding may be corrupted; hash-based addressing may be unreliable. Consider fixing the file encoding first."
187
170
 
171
+ /**
172
+ * 工具描述分档展开薄壳(设计 TOOLS §1 ∥ PROMPT-SYSTEM 设计档 §2 §7):母版描述里的
173
+ * `{{knowledge:<id>}}` 锚在这里按档展开,展开体一律交 `prompt-files.mjs` 的 `expandKnowledgeTopics`
174
+ * ——壳只校验 mode 并选极简支,不复刻锚文法(另起一套展开器 = 逐字一致那条规则写在两处,漂一处查不出)。
175
+ * mode **必填、不给缺省**:缺省会让一次运行悄悄用上另一档的文本,而错处要到模型按错文本行事时才显形。
176
+ * 非字符串描述恒等过(无锚可展开——与下方 `applyPromptInjections` 同一判据)。
177
+ */
178
+ export function expandToolDescription(text, mode) {
179
+ if (mode === undefined) throw new Error(`tool description: mode is required — pass one of ${WORK_MODES.join(" / ")}; no default is applied (a missing mode silently renders another tier's text)`)
180
+ if (!WORK_MODES.includes(mode)) throw new Error(`tool description: mode must be one of ${WORK_MODES.join(" / ")} — got ${JSON.stringify(mode)}`)
181
+ if (typeof text !== "string") return text
182
+ return expandKnowledgeTopics(text, { tiny: mode === "tiny" })
183
+ }
184
+
188
185
  /** Convert to OpenAI tools parameter format.
189
- * 锚替换缝(CORE-UNIFICATION §2.13.8——U0):`description` 经 `applyPromptInjections`
190
- * (未配置 = 恒等);两个调用点(`agent/setup.mjs` · `advisor/loop.mjs`)同经本函数。
191
- * 非字符串 description 恒等过(无锚可替换)。*/
192
- export function toOpenAISchema(tool) {
186
+ * 分档缝 + 锚替换缝:`description` 先按 mode 展开知识锚(`expandToolDescription`)、再跑
187
+ * `applyPromptInjections`。顺序不可倒——注入值由端侧提供,倒过来会把注入值当主题锚再展开一次。
188
+ * 调用点与各自传的档见设计 TOOLS §1 的表:主链按会话现读的 mode,其余五面取完整档 `"normal"`。
189
+ * 非字符串 description 恒等过(无锚可替换)。
190
+ * `descriptionPostProcess`(可选钩子)跑在两者之后:宿主端对某端不存在的动作做行级剔除,剔的必须是
191
+ * **装配完的那份描述**(设计 TOOLS §1.1)——锚展开在装配期,剔除点放在展开之前就看不到展开面的内容。*/
192
+ export function toOpenAISchema(tool, mode) {
193
+ const assembled = applyPromptInjections(expandToolDescription(tool.description, mode))
193
194
  return {
194
195
  type: "function",
195
196
  function: {
196
197
  name: tool.name,
197
- description: applyPromptInjections(tool.description),
198
+ description: typeof tool.descriptionPostProcess === "function" ? tool.descriptionPostProcess(assembled) : assembled,
198
199
  parameters: tool.parameters,
199
200
  },
200
201
  }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * write-gate-params.mjs — 写门两参的说明文本单点(设计 TOOLS §1.2)。
3
+ *
4
+ * 为什么单独一档:`tools/shared.mjs` 越过了 500 行设计时线(`docs/core/standards/CODE-TIER.md` §7 的量法),
5
+ * 而这三条常量是它里面唯一能整块搬走、且搬走不动任何调用语义的部分。`tools/shared.mjs` 仍转出同一常量,
6
+ * 八处导入档的导入面一个字不改——文本单点与导入面分开,改口径只改一处,消费面不跟着改名。
7
+ *
8
+ * 两条身份句只答「这一笔该传什么」;完整口径(哪一档生效 ∥ 哪些工具必带 ∥ 缺什么怎么被拒)只讲一次,
9
+ * 在 `prompts/discipline-engineering.md` 的写门参数一节。参数行不重述它:每个入口工具各带一份近乎逐字的
10
+ * 副本,改一处口径要改每一处,漏一处就是两套规则在跑。
11
+ */
12
+
13
+ // ─── 写门 `ledger` 参数(2026-11-03 笔-账绑定批 · 设计档 §2.3「工具 schema 面」)───────────────
14
+ // 描述单源:入口集十一把工具的 `parameters.properties.ledger` 共用下面这一条。
15
+ // 为什么放一处:同一个参数在十一处各写一遍 = 同一机制十一份描述,措辞一旦漂移,模型读到的规则就有十一版;
16
+ // 而 `memory` 的差异只是各接一句「本工具的哪一径要号」——差异走后缀,不复制全文。
17
+ // 为什么不进 `required`(决策 35):`required` 是静态字面,而这十一把工具在两模式、子代理、出辖目标下共用;
18
+ // 静态必填会让普通模式读到一条不成立的强制(写锁仅工程模式),也让子代理读到一条没人核的要求。
19
+ // 机械强制在门(缺号即拒),schema 只负责让模型知道有这个参数;拒文因此是唯一教学面(决策 38)。
20
+ export const LEDGER_PARAM_DESC = '本笔调用服务的在途台账号,`"#N"` 或 `"N"`'
21
+ /** `memory`:只有 `layer:"project"` 写项目内 `.thincoder/memory/**`(决策 39;`put` 缺省 `personal`)。 */
22
+ export const LEDGER_PARAM_DESC_MEMORY = LEDGER_PARAM_DESC
23
+ + ';仅落 project 层的写型 action 要号:`layer:"project"`,或省略 `layer`、单条删除且 id 以 `project:` 开头(此时层由前缀定;`personal` ∥ `team` 落用户数据目录,不要号)'
24
+ /** 写门 `project` 参数(2026-11-03 项目声明面批 · 设计档 §2.3「工具 schema 面」/ 决策 40):项目根路径(带
25
+ * `PROJECT-MANIFEST.json` 的那个目录)—— 台账按项目根算键,所以「传项目」就是把这个根传进来,零映射表。
26
+ * 定位参数在场时以它为准,`project` 只补位;纯声明,不改执行目录(第二句因此是语义,不是「何时必带」)。
27
+ * 为什么写盘七件也各带一格(2026-11-08 工作区根窄口批 · 设计档 §2.3.1):它们的定位参数是一支支目标路径,
28
+ * 而「目标取不到项目根」真会发生(工作区根的文件)——那时 `project` 是唯一可用的判据点,schema 不给
29
+ * 这一格,门里的口子就永远触发不了(模型不知道有这个参数,第一次撞的还是拒文)。何时必带那条口径
30
+ * 在工程纪律段的写门参数一节,参数行只留身份。 */
31
+ export const PROJECT_PARAM_DESC = '本笔调用服务的项目根——带 `PROJECT-MANIFEST.json` 的那个目录(绝对路径,或相对会话 cwd)。纯声明:不改执行目录(`bash` 仍在会话 cwd 执行,`workdir` 才是改执行目录的那个)。'
@@ -16,11 +16,17 @@
16
16
  * 记账面(dirty-file tracking)**同源住本档**:核内写盘只此一处 ⇒ 记账面只此一处(Map/Set +
17
17
  * 函数)。默认径的记账由本档代落——`meta.record` ⇒ `recordWrite`、`op="delete"` ⇒ `markDirty`;
18
18
  * 调用方不再自行 `recordWrite` / `markDirty`(**不重复记账**)。**唯一例外 = apply_patch 的批级
19
- * 记账**(两段式全部成功后由调用方一次 `markDirty`——批级语义,与改前逐字同)。`file.mjs` 只做
20
- * 再导出,保既有 import 面稳定(模块拆分写优先纪律)。
19
+ * 记账**——判据(谁在哪一层写记账表):写点内由写点自己记、调用方只交记录的值,只有「调用方
20
+ * 自持」才不经写点;`edit` 批面把合并快照当 `record` 交给本档 ⇒ 仍属写点内,不是例外。
21
+ * 量法(结论可复跑):仓根 `grep -rn "markDirty(\|clearLastWrite(\|recordWrite(" thincoder-core/tools`
22
+ * ⇒ 只有 `write-path.mjs`(定义 ∥ 写点内自用)· `patch.mjs`(批级循环,对已落盘档跑,成功 ∥ 失败
23
+ * 两路同、含注入径已提交那批)· `file.mjs`(`read` 清快照)三档命中;出现第四档就是又一个调用方
24
+ * 自持的记账面,这一句要重判。`file.mjs` 只做再导出,保既有 import 面稳定(模块拆分写优先纪律)。
21
25
  */
22
26
  import { writeFile, unlink, rename, cp, rm, rmdir } from "node:fs/promises"
23
27
 
28
+ import { runDocWriteGate } from "./doc-write-gate.mjs"
29
+
24
30
  /** apply_patch 两段式的暂存后缀(单点定义——阶段一落暂存档、阶段二提交、失败清理均用它)。 */
25
31
  export const TMP_SUFFIX = ".thincoder-tmp"
26
32
 
@@ -79,7 +85,7 @@ export const dirtyRefusalMessage = (abs) =>
79
85
  // ────────────────────────────────────────
80
86
  /**
81
87
  * 判据(六行按序判):放行 ⇒ `null`;拒绝 ⇒ 命中行的实况
82
- * `{ row, type?, startLine?, shift? }`(row = §7.1 的行号 1–6)。
88
+ * `{ row, type?, startLine?, shift? }`(row = §3 的行号 1–6)。
83
89
  *
84
90
  * @param {string} abs 目标绝对路径(记账键)
85
91
  * @param {number|null} startLine 目标区首行;`null` = 调用方没有行号目标(正则定位形)
@@ -244,9 +250,15 @@ async function defaultPath(abs, content, meta) {
244
250
  * `via:"editor"` 与 `meta.stage` 组合 = 编辑器径已直接提交目标档(无暂存档)
245
251
  */
246
252
  export async function writeThroughPath(abs, content, meta = {}) {
253
+ const op = meta.op ?? "write"
254
+ // **写前文档机检门**(`docs/core/design/DOC-DISCIPLINE.md` §3.26 条目 Z):只挂内容写点,且写在两条落盘径
255
+ // 之前——命中即 throw,于是目标档与暂存档都还是零字节。其余 op(commit ∥ delete ∥ rmdir ∥ copy ∥ move ∥
256
+ // rename)不写文档内容 ⇒ 零门调用。`apply_patch` 两段式的第一段(`op:"write"` + `stage`)判,提交段不判。
257
+ // 普通模式(meta.agent.config.agent.engineering === false)不运行内容写门;无 agent 的低层调用保持原行为。
258
+ if (op === "write" && meta.agent?.config?.agent?.engineering !== false) await runDocWriteGate({ abs, content })
247
259
  // `op="commit"` = 默认径两段式的收尾(暂存档 → 目标)——编辑器径是即时提交、不产生暂存
248
260
  // 档 ⇒ 无端侧载体,不再问注入面(避免无意义的门禁调用;目标档的门禁已在 staging 问过)。
249
- if ((meta.op ?? "write") !== "commit") {
261
+ if (op !== "commit") {
250
262
  const handled = await tryInjectedPath(abs, content, meta)
251
263
  if (handled) return handled
252
264
  }