@thincoder/core 0.10.13 → 0.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (366) hide show
  1. package/CHANGELOG.md +74 -1
  2. package/advisor/convergence.mjs +34 -3
  3. package/advisor/loop.mjs +42 -10
  4. package/advisor/messages.mjs +46 -27
  5. package/advisor/notice.mjs +1 -1
  6. package/advisor/project-context.mjs +253 -14
  7. package/advisor/run.mjs +7 -4
  8. package/advisor.mjs +29 -43
  9. package/agent/batch-attribution.mjs +87 -0
  10. package/agent/batch-changed-surface.mjs +129 -0
  11. package/agent/completion.mjs +57 -4
  12. package/agent/digest-account.mjs +73 -46
  13. package/agent/dispatch-gates.mjs +6 -0
  14. package/agent/dispatch-run.mjs +1 -1
  15. package/agent/dispatch.mjs +35 -22
  16. package/agent/family-tools.mjs +36 -17
  17. package/agent/helpers.mjs +123 -95
  18. package/agent/offload.mjs +84 -0
  19. package/agent/post-turn.mjs +24 -10
  20. package/agent/record-results.mjs +19 -7
  21. package/agent/run-stages.mjs +127 -61
  22. package/agent/run-start.mjs +45 -8
  23. package/agent/setup-reminders.mjs +9 -2
  24. package/agent/setup.mjs +27 -22
  25. package/agent/spawn-child.mjs +38 -1
  26. package/agent/suspension.mjs +1 -1
  27. package/agent/timers.mjs +5 -3
  28. package/agent/turn-loop.mjs +60 -6
  29. package/agent/turn-projection.mjs +386 -0
  30. package/agent/turn-task-state.mjs +274 -0
  31. package/agent/turn-tool-process.mjs +168 -0
  32. package/agent/write-face.mjs +99 -0
  33. package/agent/write-gate-ledger.mjs +569 -0
  34. package/agent/write-gate.mjs +39 -13
  35. package/agent-tools/advisor-async.mjs +29 -169
  36. package/agent-tools/advisor-launch.mjs +178 -0
  37. package/agent-tools/advisor-settle.mjs +28 -1
  38. package/agent-tools/advisor.mjs +136 -31
  39. package/agent-tools/async-settle.mjs +2 -2
  40. package/agent-tools/audit-block.mjs +6 -6
  41. package/agent-tools/bash-async.mjs +8 -2
  42. package/agent-tools/batch-closeout.mjs +444 -0
  43. package/agent-tools/batch-gate.mjs +152 -138
  44. package/agent-tools/batch-ledger-bind.mjs +392 -0
  45. package/agent-tools/batch-ledger-link.mjs +73 -0
  46. package/agent-tools/batch-ledger-view.mjs +109 -0
  47. package/agent-tools/batch-lifecycle.mjs +245 -376
  48. package/agent-tools/batch-paths.mjs +73 -47
  49. package/agent-tools/batch-read.mjs +1 -1
  50. package/agent-tools/batch-record-write.mjs +417 -0
  51. package/agent-tools/batch-regions.mjs +215 -0
  52. package/agent-tools/batch-reopen.mjs +154 -0
  53. package/agent-tools/batch-segment-vocab.mjs +379 -0
  54. package/agent-tools/batch-skeleton.mjs +344 -196
  55. package/agent-tools/batch-supersede.mjs +232 -0
  56. package/agent-tools/batch-tier-gate.mjs +297 -0
  57. package/agent-tools/batch.mjs +189 -253
  58. package/agent-tools/consult.mjs +7 -4
  59. package/agent-tools/context.mjs +47 -17
  60. package/agent-tools/design-review-record.mjs +225 -0
  61. package/agent-tools/design-slots.mjs +24 -24
  62. package/agent-tools/design-token.mjs +318 -39
  63. package/agent-tools/doc-check.mjs +55 -29
  64. package/agent-tools/doc-graph.mjs +140 -0
  65. package/agent-tools/eng.mjs +10 -9
  66. package/agent-tools/escalate-async.mjs +5 -5
  67. package/agent-tools/manifest.mjs +34 -15
  68. package/agent-tools/read-history.mjs +115 -14
  69. package/agent-tools/review-facts.mjs +40 -15
  70. package/agent-tools/settings.mjs +23 -2
  71. package/agent-tools/spawn-gates.mjs +19 -22
  72. package/agent-tools/ssh-session.mjs +120 -111
  73. package/agent-tools/ssh-text.mjs +155 -0
  74. package/agent-tools/ssh-transfer.mjs +210 -0
  75. package/agent-tools/ssh-transport.mjs +183 -81
  76. package/agent-tools/subagent-actions-query.mjs +11 -7
  77. package/agent-tools/subagent-actions.mjs +1 -1
  78. package/agent-tools/subagent-async.mjs +11 -11
  79. package/agent-tools/subagent-brief.mjs +76 -0
  80. package/agent-tools/subagent-design-token.mjs +168 -0
  81. package/agent-tools/subagent-run.mjs +1 -1
  82. package/agent-tools/subagent-scheduler.mjs +45 -11
  83. package/agent-tools/subagent-spawn.mjs +143 -104
  84. package/agent-tools/subagent.mjs +26 -23
  85. package/agent-tools/taskbook-block.mjs +94 -0
  86. package/agent-tools/timer.mjs +12 -8
  87. package/agent-tools/verify.mjs +13 -4
  88. package/agent-tools.mjs +7 -3
  89. package/agent.mjs +20 -1
  90. package/attachments.mjs +3 -3
  91. package/browser/actions.mjs +9 -3
  92. package/browser/cdp.mjs +45 -17
  93. package/browser/launch.mjs +25 -43
  94. package/browser/pool.mjs +299 -0
  95. package/browser/queue.mjs +2 -0
  96. package/browser/session-state.mjs +450 -0
  97. package/browser/session.mjs +127 -151
  98. package/browser/snapshot.mjs +89 -0
  99. package/client-identity.mjs +22 -6
  100. package/config-defaults.mjs +2 -1
  101. package/config-migrate.mjs +40 -0
  102. package/config-normalize.mjs +28 -2
  103. package/config-presets.mjs +5 -3
  104. package/config-reload.mjs +59 -0
  105. package/config.mjs +62 -98
  106. package/context-degrade.mjs +38 -10
  107. package/context-echo.mjs +11 -0
  108. package/context.mjs +165 -68
  109. package/conventions.mjs +11 -9
  110. package/declaration.mjs +33 -7
  111. package/declared-repos.mjs +94 -0
  112. package/doc-check/doc-names.mjs +73 -0
  113. package/doc-check/doc-tokens.mjs +110 -0
  114. package/doc-check/existence.mjs +160 -0
  115. package/doc-check/index.mjs +312 -163
  116. package/doc-check/line-refs.mjs +38 -0
  117. package/doc-check/paragraph.mjs +220 -91
  118. package/doc-graph/anchors.mjs +474 -0
  119. package/doc-graph/doc-batch-face.mjs +59 -0
  120. package/doc-graph/doc-suffix.mjs +27 -0
  121. package/doc-graph/graph-tokens.mjs +160 -0
  122. package/doc-graph.mjs +778 -0
  123. package/explore-distill.mjs +12 -6
  124. package/i18n.mjs +2 -2
  125. package/index-discover.mjs +4 -1
  126. package/instance-inbox-watch.mjs +272 -0
  127. package/instance-inbox.mjs +218 -0
  128. package/instance-registry.mjs +179 -0
  129. package/knowledge/README.md +3 -0
  130. package/knowledge/prompt-resources.md +6 -0
  131. package/ledger-close-proof.mjs +95 -62
  132. package/ledger-close.mjs +188 -0
  133. package/ledger-cmd.mjs +76 -244
  134. package/ledger-consistency.mjs +113 -0
  135. package/ledger-db.mjs +70 -37
  136. package/ledger-executors.mjs +1 -1
  137. package/ledger-migrate.mjs +4 -4
  138. package/ledger-read.mjs +10 -8
  139. package/ledger-surface.mjs +1 -1
  140. package/ledger-tools.mjs +83 -24
  141. package/ledger-variant-notice.mjs +1 -1
  142. package/ledger-write-ops.mjs +462 -0
  143. package/ledger.mjs +2 -2
  144. package/manifest-discovery.mjs +5 -3
  145. package/manifest-schema.mjs +28 -2
  146. package/memory/memory-tool.mjs +5 -2
  147. package/memory/schema.mjs +6 -27
  148. package/package.json +3 -1
  149. package/path-resolve.mjs +498 -0
  150. package/permission.mjs +4 -0
  151. package/prompt-files.mjs +91 -1
  152. package/prompt-overlays.mjs +14 -6
  153. package/prompts/advisor-design.md +66 -22
  154. package/prompts/advisor-round1.md +37 -3
  155. package/prompts/advisor-round2.md +44 -10
  156. package/prompts/advisor-round3.md +43 -9
  157. package/prompts/common.md +15 -375
  158. package/prompts/consult-base.md +6 -1
  159. package/prompts/discipline-engineering.md +251 -95
  160. package/prompts/discipline-normal.md +4 -250
  161. package/prompts/knowledge/business-gates.md +22 -0
  162. package/prompts/knowledge/decision-quality.md +23 -0
  163. package/prompts/knowledge/doc-lookup.md +35 -0
  164. package/prompts/knowledge/document-writing.md +51 -0
  165. package/prompts/knowledge/documentation-evaluation.md +56 -0
  166. package/prompts/knowledge/evidence-discipline.md +57 -0
  167. package/prompts/knowledge/normal-coding-workflow.md +104 -0
  168. package/prompts/knowledge/normal-delivery-collaboration.md +108 -0
  169. package/prompts/knowledge/normal-work-management.md +57 -0
  170. package/prompts/knowledge/product-security.md +23 -0
  171. package/prompts/knowledge/project-records.md +62 -0
  172. package/prompts/knowledge/tool-advisor.md +29 -0
  173. package/prompts/knowledge/tool-apply-patch.md +18 -0
  174. package/prompts/knowledge/tool-bash.md +39 -0
  175. package/prompts/knowledge/tool-batch-eng-coder.md +12 -0
  176. package/prompts/knowledge/tool-batch-eng-designer.md +12 -0
  177. package/prompts/knowledge/tool-batch-review.md +12 -0
  178. package/prompts/knowledge/tool-batch.md +80 -0
  179. package/prompts/knowledge/tool-browser.md +57 -0
  180. package/prompts/knowledge/tool-code-search.md +4 -0
  181. package/prompts/knowledge/tool-consult-start.md +12 -0
  182. package/prompts/knowledge/tool-consult-stop.md +6 -0
  183. package/prompts/knowledge/tool-context.md +6 -0
  184. package/prompts/knowledge/tool-delete.md +17 -0
  185. package/prompts/knowledge/tool-doc-check.md +70 -0
  186. package/prompts/knowledge/tool-doc-graph-read.md +20 -0
  187. package/prompts/knowledge/tool-doc-graph.md +49 -0
  188. package/prompts/knowledge/tool-doc-search.md +6 -0
  189. package/prompts/knowledge/tool-edit.md +38 -0
  190. package/prompts/knowledge/tool-eng.md +2 -0
  191. package/prompts/knowledge/tool-execute.md +16 -0
  192. package/prompts/knowledge/tool-fetch.md +12 -0
  193. package/prompts/knowledge/tool-file-ops.md +16 -0
  194. package/prompts/knowledge/tool-get-current-time.md +7 -0
  195. package/prompts/knowledge/tool-git-read.md +19 -0
  196. package/prompts/knowledge/tool-git.md +29 -0
  197. package/prompts/knowledge/tool-glob.md +15 -0
  198. package/prompts/knowledge/tool-goal.md +8 -0
  199. package/prompts/knowledge/tool-grep.md +18 -0
  200. package/prompts/knowledge/tool-hashline-edit.md +14 -0
  201. package/prompts/knowledge/tool-insert-after.md +15 -0
  202. package/prompts/knowledge/tool-instance-list.md +6 -0
  203. package/prompts/knowledge/tool-instance-send.md +10 -0
  204. package/prompts/knowledge/tool-knowledge.md +18 -0
  205. package/prompts/knowledge/tool-ledger-read.md +35 -0
  206. package/prompts/knowledge/tool-ledger.md +42 -0
  207. package/prompts/knowledge/tool-lint.md +16 -0
  208. package/prompts/knowledge/tool-ls.md +13 -0
  209. package/prompts/knowledge/tool-lsp.md +11 -0
  210. package/prompts/knowledge/tool-main-history.md +2 -0
  211. package/prompts/knowledge/tool-manifest-read.md +14 -0
  212. package/prompts/knowledge/tool-manifest.md +31 -0
  213. package/prompts/knowledge/tool-memory-read.md +20 -0
  214. package/prompts/knowledge/tool-memory.md +15 -0
  215. package/prompts/knowledge/tool-notify-parent.md +12 -0
  216. package/prompts/knowledge/tool-operations.md +114 -0
  217. package/prompts/knowledge/tool-peer-instances.md +2 -0
  218. package/prompts/knowledge/tool-plan.md +6 -0
  219. package/prompts/knowledge/tool-process-read.md +13 -0
  220. package/prompts/knowledge/tool-process.md +15 -0
  221. package/prompts/knowledge/tool-question.md +16 -0
  222. package/prompts/knowledge/tool-read-history-batch.md +22 -0
  223. package/prompts/knowledge/tool-read-history.md +36 -0
  224. package/prompts/knowledge/tool-read-image.md +11 -0
  225. package/prompts/knowledge/tool-read.md +21 -0
  226. package/prompts/knowledge/tool-recent-changes.md +6 -0
  227. package/prompts/knowledge/tool-repo-outline.md +4 -0
  228. package/prompts/knowledge/tool-settings-read.md +12 -0
  229. package/prompts/knowledge/tool-settings.md +18 -0
  230. package/prompts/knowledge/tool-skill.md +6 -0
  231. package/prompts/knowledge/tool-ssh.md +52 -0
  232. package/prompts/knowledge/tool-subagent.md +59 -0
  233. package/prompts/knowledge/tool-task.md +12 -0
  234. package/prompts/knowledge/tool-team-ledger-read.md +11 -0
  235. package/prompts/knowledge/tool-team-ledger.md +11 -0
  236. package/prompts/knowledge/tool-timer.md +23 -0
  237. package/prompts/knowledge/tool-tree.md +14 -0
  238. package/prompts/knowledge/tool-verify.md +19 -0
  239. package/prompts/knowledge/tool-wait-for.md +25 -0
  240. package/prompts/knowledge/tool-websearch.md +19 -0
  241. package/prompts/knowledge/tool-write.md +9 -0
  242. package/prompts/knowledge/upstream-protocol.md +43 -0
  243. package/prompts/persona-eng-coder.md +29 -3
  244. package/prompts/persona-eng-designer.md +131 -159
  245. package/prompts/persona-engineering.md +202 -131
  246. package/prompts/persona-explore.md +1 -1
  247. package/prompts/persona-plan.md +6 -1
  248. package/prompts/persona-tester.md +55 -0
  249. package/prompts/subagent-base.md +2 -0
  250. package/provider/anthropic.mjs +6 -4
  251. package/provider/core.mjs +5 -4
  252. package/provider/errors.mjs +29 -4
  253. package/provider/google.mjs +39 -12
  254. package/provider/rate.mjs +11 -3
  255. package/provider/responses.mjs +3 -1
  256. package/provider/sse.mjs +15 -4
  257. package/provider-flows.mjs +2 -2
  258. package/session-identity.mjs +21 -0
  259. package/session-index-build.mjs +1 -1
  260. package/session-index-pass.mjs +1 -1
  261. package/session-index-query.mjs +1 -1
  262. package/session-index.mjs +1 -1
  263. package/session-lifecycle.mjs +79 -19
  264. package/session-slot-write.mjs +37 -5
  265. package/session-slots.mjs +9 -14
  266. package/session.mjs +29 -8
  267. package/skip-dirs.mjs +48 -0
  268. package/team-ledger.mjs +17 -13
  269. package/text-budget.mjs +4 -0
  270. package/token-ttl.mjs +73 -4
  271. package/token-window.mjs +244 -34
  272. package/tool-docs/advisor.md +2 -27
  273. package/tool-docs/apply_patch.md +1 -13
  274. package/tool-docs/bash.md +2 -37
  275. package/tool-docs/batch-eng-coder.md +3 -0
  276. package/tool-docs/batch-eng-designer.md +3 -0
  277. package/tool-docs/batch-review.md +3 -0
  278. package/tool-docs/batch.md +3 -1
  279. package/tool-docs/browser.md +2 -47
  280. package/tool-docs/code_search.md +3 -1
  281. package/tool-docs/consult_start.md +2 -4
  282. package/tool-docs/consult_stop.md +2 -2
  283. package/tool-docs/context.md +1 -5
  284. package/tool-docs/delete.md +2 -14
  285. package/tool-docs/doc_check.md +2 -72
  286. package/tool-docs/doc_graph-read.md +3 -0
  287. package/tool-docs/doc_graph.md +3 -0
  288. package/tool-docs/doc_search.md +3 -1
  289. package/tool-docs/edit.md +2 -18
  290. package/tool-docs/eng.md +3 -1
  291. package/tool-docs/execute.md +2 -12
  292. package/tool-docs/fetch.md +2 -12
  293. package/tool-docs/file_ops.md +2 -16
  294. package/tool-docs/get_current_time.md +1 -6
  295. package/tool-docs/git-read.md +3 -0
  296. package/tool-docs/git.md +2 -27
  297. package/tool-docs/glob.md +2 -10
  298. package/tool-docs/goal.md +2 -5
  299. package/tool-docs/grep.md +2 -18
  300. package/tool-docs/hashline_edit.md +2 -13
  301. package/tool-docs/insert_after.md +2 -14
  302. package/tool-docs/instance_list.md +3 -0
  303. package/tool-docs/instance_send.md +3 -0
  304. package/tool-docs/knowledge.md +3 -0
  305. package/tool-docs/ledger-read.md +3 -0
  306. package/tool-docs/ledger.md +3 -8
  307. package/tool-docs/lint.md +2 -9
  308. package/tool-docs/ls.md +2 -11
  309. package/tool-docs/lsp.md +2 -9
  310. package/tool-docs/main_history.md +3 -1
  311. package/tool-docs/manifest-read.md +2 -7
  312. package/tool-docs/manifest.md +2 -28
  313. package/tool-docs/memory-read.md +3 -0
  314. package/tool-docs/memory.md +3 -11
  315. package/tool-docs/notify_parent.md +2 -13
  316. package/tool-docs/peer_instances.md +3 -1
  317. package/tool-docs/plan.md +2 -4
  318. package/tool-docs/process-read.md +3 -0
  319. package/tool-docs/process.md +2 -13
  320. package/tool-docs/question.md +3 -17
  321. package/tool-docs/read.md +2 -19
  322. package/tool-docs/read_history-batch.md +3 -0
  323. package/tool-docs/read_history.md +2 -6
  324. package/tool-docs/read_image.md +2 -7
  325. package/tool-docs/recent_changes.md +3 -1
  326. package/tool-docs/repo_outline.md +3 -1
  327. package/tool-docs/settings-read.md +3 -0
  328. package/tool-docs/settings.md +2 -5
  329. package/tool-docs/skill.md +3 -5
  330. package/tool-docs/ssh.md +2 -50
  331. package/tool-docs/subagent.md +2 -63
  332. package/tool-docs/task.md +2 -6
  333. package/tool-docs/team_ledger-read.md +3 -0
  334. package/tool-docs/team_ledger.md +3 -9
  335. package/tool-docs/timer.md +3 -13
  336. package/tool-docs/tree.md +2 -13
  337. package/tool-docs/verify.md +3 -1
  338. package/tool-docs/wait_for.md +2 -32
  339. package/tool-docs/websearch.md +2 -17
  340. package/tool-docs/write.md +2 -10
  341. package/tools/bash.mjs +12 -2
  342. package/tools/browser.mjs +52 -7
  343. package/tools/doc-write-gate.mjs +73 -0
  344. package/tools/edit-batch.mjs +176 -91
  345. package/tools/edit-diff.mjs +129 -45
  346. package/tools/edit-receipt.mjs +39 -0
  347. package/tools/execute.mjs +11 -5
  348. package/tools/file.mjs +32 -34
  349. package/tools/git.mjs +43 -2
  350. package/tools/index.mjs +6 -0
  351. package/tools/knowledge.mjs +143 -0
  352. package/tools/linter.mjs +3 -3
  353. package/tools/ops.mjs +4 -1
  354. package/tools/patch.mjs +127 -38
  355. package/tools/process-doc-mark.mjs +139 -0
  356. package/tools/search.mjs +15 -6
  357. package/tools/shared.mjs +31 -7
  358. package/tools/ssh.mjs +48 -7
  359. package/tools/tree.mjs +4 -1
  360. package/tools/write-gate-params.mjs +31 -0
  361. package/tools/write-path.mjs +79 -6
  362. package/traces/trace-store.mjs +4 -3
  363. package/window-policy.mjs +203 -0
  364. package/agent/light-round.mjs +0 -63
  365. package/agent/unbooked-pen.mjs +0 -62
  366. package/doc-check/anchors.mjs +0 -135
package/tools/index.mjs CHANGED
@@ -66,6 +66,10 @@ export async function assembleBuiltinTools({ memory, cwd, projectDir = null, aut
66
66
  const { repoOutlineTool } = await import("./repomap.mjs");
67
67
  const { settingsTool } = await import("../agent-tools/settings.mjs");
68
68
  const { peerInstancesTool } = await import("../peer-instances.mjs");
69
+ // 投递面工具两件(MULTI-INSTANCE-COLLAB §5.2 / §5.8):装配点 = `peer_instances` 同点——核基集一处,
70
+ // 两壳(CLI / VSC)同得;`instance_list` 随名册档、`instance_send` 随 inbox 档。
71
+ const { instanceListTool } = await import("../instance-registry.mjs");
72
+ const { instanceSendTool } = await import("../instance-inbox.mjs");
69
73
  const imageOk = Boolean(specForModel(model)?.multimodal);
70
74
  return [
71
75
  ...builtinTools,
@@ -77,6 +81,8 @@ export async function assembleBuiltinTools({ memory, cwd, projectDir = null, aut
77
81
  repoOutlineTool(memory?.db, cwd),
78
82
  settingsTool(),
79
83
  peerInstancesTool,
84
+ instanceListTool,
85
+ instanceSendTool,
80
86
  // 台账工具面(统一入口 `ledger`——含读二)随家族段 `agent/family-tools.mjs`(2026-10-05 统一入口批:本基集清零)
81
87
  ];
82
88
  }
@@ -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 } 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"
@@ -26,6 +26,9 @@ export const fileOpsTool = {
26
26
  action: { type: "string", enum: ["move", "copy", "rename"], description: "move | copy | rename" },
27
27
  source: { type: "string", description: "Source path, relative to cwd or absolute" },
28
28
  dest: { type: "string", description: "Destination path" },
29
+ ledger: { type: "string", description: LEDGER_PARAM_DESC },
30
+ // 工作区根窄口(设计档 §2.3.1):目标取不到项目根时才被读;目标有根时以路径为准(定位参数优先)。
31
+ project: { type: "string", description: PROJECT_PARAM_DESC },
29
32
  },
30
33
  required: ["action", "source", "dest"],
31
34
  },
package/tools/patch.mjs CHANGED
@@ -4,9 +4,14 @@ import {
4
4
  resolveInCwd,
5
5
  normalizeEOL,
6
6
  detectFileEol,
7
- majorityEol
7
+ majorityEol,
8
+ LEDGER_PARAM_DESC,
9
+ PROJECT_PARAM_DESC
8
10
  } from "./shared.mjs";
9
- import { writeThroughPath, TMP_SUFFIX, markDirty } from "./write-path.mjs";
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";
10
15
  import { spawnGit } from "./git-run.mjs";
11
16
  import { mkdir, readFile, lstat, unlink } from "node:fs/promises";
12
17
  import { existsSync } from "node:fs";
@@ -139,7 +144,7 @@ function applyHunks(fileLines, hunks, eol, path) {
139
144
  const cr = eol === "\r\n" ? "\r" : ""
140
145
  for (let h = 0; h < hunks.length; h++) {
141
146
  const oldSeq = hunks[h].ops.filter((o) => o.type !== "+").map((o) => o.text)
142
- 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`)
143
148
  const matches = []
144
149
  for (let pos = 0; pos + oldSeq.length <= fileLines.length; pos++) {
145
150
  let ok = true
@@ -150,11 +155,11 @@ function applyHunks(fileLines, hunks, eol, path) {
150
155
  }
151
156
  if (matches.length === 0) {
152
157
  const preview = oldSeq.slice(0, 3).join(" ⏎ ")
153
- 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.`)
154
159
  }
155
160
  if (matches.length > 1) {
156
161
  const preview = oldSeq.slice(0, 3).join(" ⏎ ")
157
- 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 ? "…" : ""}"`)
158
163
  }
159
164
  const pos = matches[0]
160
165
  const out = []
@@ -168,6 +173,66 @@ function applyHunks(fileLines, hunks, eol, path) {
168
173
  }
169
174
  }
170
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
+
171
236
  export const applyPatchTool = {
172
237
  name: "apply_patch",
173
238
  description: DESC("apply_patch"),
@@ -175,6 +240,9 @@ export const applyPatchTool = {
175
240
  type: "object",
176
241
  properties: {
177
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>)." },
243
+ ledger: { type: "string", description: LEDGER_PARAM_DESC },
244
+ // 工作区根窄口(设计档 §2.3.1):目标取不到项目根时才被读;目标有根时以路径为准(定位参数优先)。
245
+ project: { type: "string", description: PROJECT_PARAM_DESC },
178
246
  },
179
247
  required: ["patch"],
180
248
  },
@@ -185,56 +253,75 @@ export const applyPatchTool = {
185
253
  },
186
254
  async execute(args, ctx) {
187
255
  const files = parsePatch(args.patch ?? "")
188
- // Read all into memory first for trial: if any hunk fails, abort entirely — never write a partial patch (atomicity)
189
- const planned = []
190
- for (const f of files) {
191
- const abs = resolveInCwd(ctx, f.path)
192
- if (f.isNew) {
193
- if (existsSync(abs)) throw new Error(`Cannot create ${f.path}: file already exists`)
194
- // New file: follow the directory's majority EOL style (default LF).
195
- const eol = majorityEol(dirname(abs))
196
- const content = f.hunks.flatMap((h) => h.ops.filter((o) => o.type === "+").map((o) => o.text)).join(eol) + eol
197
- planned.push({ abs, path: f.path, content, isNew: true })
198
- } else {
199
- const original = await readFile(abs, "utf8").catch(() => { throw new Error(`File not found: ${f.path}`) })
200
- const eol = detectFileEol(original)
201
- // Apply hunks in the normalized LF domain, then write back joined with the
202
- // file's ORIGINAL EOL style — join("\n") here used to rewrite CRLF files as LF.
203
- const lines = normalizeEOL(original).split("\n")
204
- applyHunks(lines, f.hunks, "\n", f.path)
205
- planned.push({ abs, path: f.path, content: lines.join(eol), isNew: false })
206
- }
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
+ }))
207
270
  }
208
- // 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` 计入每一个已落盘的档。
209
273
  // 两段式经单一写路径点(§2.13.5):阶段一全部 staging(写入各自 `<abs>.thincoder-tmp`)
210
- // ⇒ 阶段二逐档 commit(rename 到目标)。**默认径 = 改前语义逐字同**(任一失败无档落盘:
211
- // 阶段一失败时目标档全未动、阶段二失败时已提交档保持——同改前)。
212
- // 编辑器径(注入面)例外:内容在阶段一即提交(宿主侧同款——applyEdit + save)⇒ 阶段
213
- // 二跳过该档;已提交档不回滚(与宿主侧现行为一致,非本档引入的语义)。
274
+ // ⇒ 阶段二逐档 commit(rename 到目标)。
275
+ // 编辑器径(注入面)例外:内容在阶段一即提交(宿主侧同款——applyEdit + save)⇒ 阶段二跳过该档;
276
+ // 已提交档不回滚(与宿主侧现行为一致,非本档引入的语义),但它**算已落盘**——计入 k、列 modified。
214
277
  const staged = []
215
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
+ }
216
293
  try {
217
294
  for (const p of planned) {
295
+ inFlight = p
218
296
  await mkdir(dirname(p.abs), { recursive: true })
219
- const r = await writeThroughPath(p.abs, p.content, { op: "write", stage: true })
220
- if (r.via === "editor") committedByEditor.add(p.abs)
221
- 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)
222
302
  }
223
303
  for (const p of planned) {
224
304
  if (committedByEditor.has(p.abs)) continue
305
+ inFlight = p
225
306
  await writeThroughPath(p.abs, null, { op: "commit" })
307
+ committed.add(p.abs)
226
308
  }
227
- } catch (renameError) {
228
- // rename phase failed: clean up leftover .tmp files
309
+ } catch (writeError) {
310
+ // 失败路径照样记账:已落盘的档就是盘上事实,与成功路径同一把尺(否则见上面的护栏后果)。
311
+ recordCommitted()
312
+ // rename / staging 失败:清掉默认径已暂存的 .tmp(那些目标档逐字未动——它们是「没写」,不是「写了」)
229
313
  for (const abs of staged) {
230
314
  try { await unlink(abs + TMP_SUFFIX) } catch {}
231
315
  }
232
- 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
+ }))
233
322
  }
234
323
  const summary = planned.map((p) => ` ${p.isNew ? "created " : "modified"} ${p.path}`).join("\n")
235
- // Mark every touched file dirty — insert_after must not run on stale line numbers.
236
- // 整批记账(dirty)= apply_patch 的批级语义(两段式全成功后一次落账——与改前逐字同)。
237
- for (const p of planned) markDirty(p.abs)
324
+ recordCommitted()
238
325
  const syntaxChecks = await Promise.all(planned.map(async (p) => {
239
326
  const r = await autoSyntaxCheck(p.abs)
240
327
  return r ? `${p.path}:${r.replace("Syntax: ", "")}` : ""
@@ -256,6 +343,8 @@ export const deleteTool = {
256
343
  properties: {
257
344
  path: { type: "string", description: "File or empty-directory path (relative to cwd or absolute)" },
258
345
  force: { type: "boolean", description: "Allow deleting git-tracked files (default false)" },
346
+ ledger: { type: "string", description: LEDGER_PARAM_DESC },
347
+ project: { type: "string", description: PROJECT_PARAM_DESC },
259
348
  },
260
349
  required: ["path"],
261
350
  },
@@ -0,0 +1,139 @@
1
+ /**
2
+ * process-doc-mark.mjs — 工具输出里的过程档标记(单源小档;机制 = `docs/core/design/TOOLS.md` §6.28)。
3
+ *
4
+ * 依赖面说清楚:本档**不**是零依赖叶档——谓词都来自判据单源 `../declaration.mjs`,而它的静态闭包
5
+ * 经 `memory/file-walk.mjs` 达 `memory/schema.mjs`(`node:sqlite`)。因此端壳里静态引本档 = 把那条链拉进静态闭包;
6
+ * 当前端装配面本已静态可达同一链(`setup-tooltable.mjs` → 核 `agent-tools/verify.mjs` → `conventions.mjs`),
7
+ * 零新增风险,但别把它当零依赖档随手引。
8
+ *
9
+ * 一句话:输出里**判定得出**来源档落在索引排除集(batches 段 ∥ `_archive` 前缀)的行,
10
+ * 行首加 `[process doc: not a design basis]`(原行整体后随);其余行一个字节不动。**不是门**——
11
+ * 不拦、不筛、不改命中集,只加可读信息。
12
+ *
13
+ * 两套判据、一份文案、一个谓词、一个 helper:
14
+ * - `grep` 面按命中行的**档**判(消费面直调 `isProcessDocPath`——grep 自己已有 `h.file`,本档不参与拼装);
15
+ * - 命令面(`bash` 同步 ∥ `bash` 后台摘要 ∥ `execute` ∥ VSC 端 `bash`)的输出是任意文本,只能按
16
+ * **行首路径 token 真解析到盘上**判(`markProcessDocLines`)——解析不到 = 判不了 = 不动输出。
17
+ *
18
+ * 判据单源 = `../declaration.mjs` 的 `isExcludedRelPath`(面① 前缀 ∪ 面⑥ 段序列):本档零新排除名单、
19
+ * 零新谓词。第三参必须传 `decl.root`——`isExcludedRelPath` 内 `resolve(base, s)` 对绝对参恒等,
20
+ * 再由 `relative(root, …)` 换成根相对面,面① 前缀才判得住(只被面① 命中的 `_archive` 靠这一点)。
21
+ *
22
+ * 零 console 噪声:本档不调用 `console`。判据只走 `declarationForTarget` → `loadProjectDeclaration`,
23
+ * 后者按档缓存,只在声明档不可用 / 读不出时 warn(既有降级面,非本档新增)。
24
+ */
25
+ import { existsSync } from "node:fs"
26
+ import { isAbsolute, resolve } from "node:path"
27
+ import { declarationForTarget, isExcludedRelPath } from "../declaration.mjs"
28
+
29
+ /** 逐字文案(33 字符 · 全 ASCII · 方括号闭合):工具输出面全英文,同一行混中英破坏「一词一物」。 */
30
+ export const PROCESS_DOC_MARK = "[process doc: not a design basis]"
31
+
32
+ /** 末尾汇总行(仅命令面):N = 本次输出被判为过程档的行数;N = 0 不加(`grep` 面不加此形)。 */
33
+ export const processDocSummary = (n) =>
34
+ `[process doc: ${n} of this output's lines come from process docs — not a design basis]`
35
+
36
+ /** 行首 token 的字符帽(步骤 ①):超过即成不了路径,该行跳过不解析。 */
37
+ const MAX_TOKEN_CHARS = 260
38
+
39
+ /**
40
+ * 档判据(一次调用内按档记忆:`Map<absoluteFile, boolean>`)。
41
+ * @param {string} absFile 档的绝对路径(grep 面 = 命中行的 `h.file`;命令面 = 盘上解析出的绝对路径)
42
+ * @param {Map<string, boolean>} [cache] 记忆表(缺省自建——不传就没有跳调用的记忆)
43
+ * @returns {boolean} 所属档在索引排除集内 ⇒ true;出辖(祖先链无 manifest)⇒ false(无档类可判)
44
+ */
45
+ export function isProcessDocPath(absFile, cache) {
46
+ const key = String(absFile ?? "")
47
+ if (!key) return false
48
+ const memo = cache instanceof Map ? cache : new Map() // 缺省自建:一次调用内按档记忆
49
+ if (memo.has(key)) return memo.get(key)
50
+ const decl = declarationForTarget(key) // null = 出辖(场景:会话锚在无 manifest 的目录里跑检索)
51
+ const marked = decl ? isExcludedRelPath(key, decl, decl.root) : false
52
+ memo.set(key, marked)
53
+ return marked
54
+ }
55
+
56
+ /** 剥两侧成对引号(步骤 ①)——行首字段被引起来的输出很常见。 */
57
+ function stripPairedQuotes(s) {
58
+ if (s.length < 2) return s
59
+ const first = s[0]
60
+ const last = s[s.length - 1]
61
+ if ((first === '"' && last === '"') || (first === "'" && last === "'")) return s.slice(1, -1)
62
+ return s
63
+ }
64
+
65
+ /**
66
+ * 行首路径 token(步骤 ①–③)。判不了 ⇒ null(调用方原样保留该行)。
67
+ * @param {string} line 输出行
68
+ * @returns {string|null}
69
+ */
70
+ function headPathToken(line) {
71
+ const head = /^\S+/.exec(String(line ?? "").trimStart())
72
+ if (!head) return null // 空行 / 纯空白行
73
+ const raw = stripPairedQuotes(head[0])
74
+ if (!raw || raw.length > MAX_TOKEN_CHARS) return null
75
+ // ② 剥尾:内层 `grep` ∥ `rg` ∥ `findstr` 的 `path:12: text` 形与尾随冒号一并剥掉
76
+ const token = raw.replace(/[:\-]\d+[:\-]?$/, "").replace(/:+$/, "")
77
+ if (!token) return null
78
+ // ③ 预筛:不含 `/` `\` `.` 的字段不做盘上解析(`[stdout]:` ∥ `(exit code 0)` ∥ 纯数字过不了这一关)
79
+ if (!/[/\\.]/.test(token)) return null
80
+ return token
81
+ }
82
+
83
+ /**
84
+ * 盘上解析(步骤 ④):驱动绝对形 → MSYS 形 → 相对基准 `base`,取**第一个在盘上存在**者。
85
+ * 三支都不存在 ⇒ null(= 判不了)。UNC(`\\server\share\…`)走驱动绝对形一支。
86
+ * @param {string} token 行进字段(已剥尾)
87
+ * @param {string} [base] 解析基准:`bash` 同步 = `ctx.cwd` ∥ 后台径 = entry 记下的 `cwd` ∥ `execute` = `baseDir`
88
+ * @returns {string|null}
89
+ */
90
+ function resolveOnDisk(token, base) {
91
+ const candidates = []
92
+ if (/^[A-Za-z]:[\\/]/.test(token) || token.startsWith("\\\\")) {
93
+ candidates.push(token) // 驱动绝对形 ∥ UNC
94
+ } else {
95
+ // MSYS 形(`/c/teamcode/…`)在 win32 上 `isAbsolute` 也为真,会落成当前盘的 `/c/…`
96
+ // ⇒ 必须显式把首段 `^/([A-Za-z])/` 映射为 `X:/`,否则这一支恒不命中。
97
+ const msys = /^\/([A-Za-z])(\/.*)?$/.exec(token)
98
+ if (msys) candidates.push(`${msys[1].toUpperCase()}:${msys[2] ?? "/"}`)
99
+ else if (isAbsolute(token)) candidates.push(token) // POSIX 绝对形(`resolve` 对绝对参恒等,同一支)
100
+ }
101
+ if (base) candidates.push(resolve(String(base), token))
102
+ for (const c of candidates) if (existsSync(c)) return c
103
+ return null
104
+ }
105
+
106
+ /**
107
+ * 命令面打标(§6.28「命令输出面」六步,`bash` ∥ `execute` ∥ VSC 端 `bash` 共用):
108
+ * 逐行取行首 token → 真解析到盘上 → 判归属 → 命中者行首加前缀(行其余部分原样)。
109
+ * N > 0 ⇒ 正文之后追加一行汇总;N = 0 ⇒ **原样返回入参**(一个字节不动,无空汇总行)。
110
+ *
111
+ * 纪律:不许按「看起来像路径」打标——解析不到盘上就不标(误标比不标更坏)。
112
+ *
113
+ * @param {string} text 输出文本
114
+ * @param {string} [base] 解析基准(见 `resolveOnDisk`)
115
+ * @returns {string}
116
+ */
117
+ export function markProcessDocLines(text, base) {
118
+ const src = String(text ?? "")
119
+ if (!src) return src
120
+ const fileCache = new Map() // 档 → boolean
121
+ const tokenCache = new Map() // token → boolean(一次调用内按 token 记忆;不设解析上限)
122
+ let n = 0
123
+ const out = src.split("\n").map((line) => {
124
+ const token = headPathToken(line)
125
+ if (!token) return line
126
+ let marked = tokenCache.get(token)
127
+ if (marked === undefined) {
128
+ const abs = resolveOnDisk(token, base)
129
+ marked = abs ? isProcessDocPath(abs, fileCache) : false
130
+ tokenCache.set(token, marked)
131
+ }
132
+ if (!marked) return line
133
+ n += 1
134
+ return `${PROCESS_DOC_MARK} ${line}`
135
+ })
136
+ if (n === 0) return src
137
+ const body = out.join("\n")
138
+ return `${body}${body.endsWith("\n") ? "" : "\n"}${processDocSummary(n)}`
139
+ }
package/tools/search.mjs CHANGED
@@ -6,8 +6,12 @@ import {
6
6
  splitGlobPatterns,
7
7
  compileGlobMatchers,
8
8
  normalizeEOL,
9
- IGNORED_DIRS,
10
9
  } from "./shared.mjs";
10
+ // 排除名单单源(零依赖叶档 `../skip-dirs.mjs`——2026-10-27 四份名单合一):旧名 `IGNORED_DIRS`
11
+ // 退场,本档三处直接引 `SKIP_DIRS`(一词一物)。
12
+ import { SKIP_DIRS } from "../skip-dirs.mjs";
13
+ // 过程档标记(TOOLS.md §6.28):命中行的**档**在索引排除集内 ⇒ 行首逐字前缀。只加可读信息,不改命中集。
14
+ import { PROCESS_DOC_MARK, isProcessDocPath } from "./process-doc-mark.mjs";
11
15
  import { readFile, readdir, stat, lstat } from "node:fs/promises";
12
16
  import { join } from "node:path";
13
17
 
@@ -60,7 +64,7 @@ export const globTool = {
60
64
  },
61
65
  }
62
66
 
63
- /** Recursively traverse files, yield relative paths (skip IGNORED_DIRS) */
67
+ /** Recursively traverse files, yield relative paths (skip SKIP_DIRS) */
64
68
  async function* walkFiles(dir, rel = "") {
65
69
  let entries
66
70
  try {
@@ -71,7 +75,7 @@ async function* walkFiles(dir, rel = "") {
71
75
  for (const e of entries) {
72
76
  // Skip ignored dirs AND symbolic links (symlinks to directories would cause infinite loops)
73
77
  if (e.isSymbolicLink()) continue
74
- if (e.isDirectory() && IGNORED_DIRS.has(e.name)) continue
78
+ if (e.isDirectory() && SKIP_DIRS.has(e.name)) continue
75
79
  const relPath = rel ? `${rel}/${e.name}` : e.name
76
80
  if (e.isDirectory()) {
77
81
  yield* walkFiles(join(dir, e.name), relPath)
@@ -169,7 +173,7 @@ export const grepTool = {
169
173
  return
170
174
  }
171
175
  for (const e of entries) {
172
- if (e.isDirectory() && IGNORED_DIRS.has(e.name)) continue
176
+ if (e.isDirectory() && SKIP_DIRS.has(e.name)) continue
173
177
  await walk(join(target, e.name), rel ? `${rel}/${e.name}` : e.name)
174
178
  }
175
179
  }
@@ -177,9 +181,14 @@ export const grepTool = {
177
181
  await walk(base, "")
178
182
  if (hits.length === 0) return "(no matches)"
179
183
 
184
+ // §6.28:一次调用一个档记忆表;命中行与上下文行都在原有文案前镀前缀(判据是**档**不是行——
185
+ // 不标则同一档的上下文行读起来像普通档的内容)。打标在 `truncate` 之前,不新增截断点。
186
+ const markCache = new Map()
187
+ const mark = (f) => (isProcessDocPath(f, markCache) ? `${PROCESS_DOC_MARK} ` : "")
188
+
180
189
  // No context: keep original path:line: content format
181
190
  if (!wantCtx) {
182
- return truncate(hits.map((h) => `${h.file}:${h.line}: ${h.text}`).join("\n"))
191
+ return truncate(hits.map((h) => `${mark(h.file)}${h.file}:${h.line}: ${h.text}`).join("\n"))
183
192
  }
184
193
 
185
194
  // With context: matching lines use ':', context lines use '-' (like ripgrep); overlapping ranges in same file are merged and de-duplicated
@@ -197,7 +206,7 @@ export const grepTool = {
197
206
  }
198
207
  for (const l of [...lineSet].sort((a, b) => a - b)) {
199
208
  const sep = matchedLines.has(l) ? ":" : "-"
200
- out.push(`${file}${sep}${l}${sep} ${lines[l - 1]}`)
209
+ out.push(`${mark(file)}${file}${sep}${l}${sep} ${lines[l - 1]}`)
201
210
  }
202
211
  }
203
212
  return truncate(out.join("\n"))