@thincoder/core 0.11.1 → 0.11.3

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 (382) hide show
  1. package/CHANGELOG.md +64 -2
  2. package/advisor/compaction.mjs +7 -5
  3. package/advisor/convergence.mjs +34 -3
  4. package/advisor/history.mjs +24 -11
  5. package/advisor/loop.mjs +49 -12
  6. package/advisor/messages.mjs +114 -33
  7. package/advisor/project-context.mjs +171 -42
  8. package/advisor/run.mjs +24 -10
  9. package/advisor.mjs +36 -46
  10. package/agent/batch-attribution.mjs +87 -0
  11. package/agent/batch-changed-surface.mjs +129 -0
  12. package/agent/chat-call.mjs +14 -9
  13. package/agent/completion.mjs +70 -41
  14. package/agent/continue-decision.mjs +14 -8
  15. package/agent/digest-account.mjs +133 -59
  16. package/agent/dispatch-gates.mjs +6 -0
  17. package/agent/dispatch-run.mjs +1 -1
  18. package/agent/dispatch.mjs +10 -4
  19. package/agent/family-tools.mjs +37 -23
  20. package/agent/helpers.mjs +139 -73
  21. package/agent/image-heal.mjs +18 -4
  22. package/agent/offload.mjs +25 -29
  23. package/agent/post-turn.mjs +36 -35
  24. package/agent/record-results.mjs +39 -7
  25. package/agent/run-stages.mjs +132 -52
  26. package/agent/run-start.mjs +150 -78
  27. package/agent/setup-reminders.mjs +194 -91
  28. package/agent/setup.mjs +219 -140
  29. package/agent/spawn-child.mjs +40 -3
  30. package/agent/suspension.mjs +43 -15
  31. package/agent/timers.mjs +9 -4
  32. package/agent/turn-domain-text.mjs +105 -0
  33. package/agent/turn-loop.mjs +84 -27
  34. package/agent/turn-projection.mjs +286 -0
  35. package/agent/turn-task-state.mjs +274 -0
  36. package/agent/turn-tool-process.mjs +163 -0
  37. package/agent/write-gate-ledger.mjs +569 -0
  38. package/agent/write-gate.mjs +29 -352
  39. package/agent-tools/advisor-async.mjs +35 -172
  40. package/agent-tools/advisor-launch.mjs +178 -0
  41. package/agent-tools/advisor-settle.mjs +28 -1
  42. package/agent-tools/advisor.mjs +37 -48
  43. package/agent-tools/async-discard.mjs +7 -2
  44. package/agent-tools/async-settle.mjs +18 -12
  45. package/agent-tools/audit-block.mjs +6 -6
  46. package/agent-tools/bash-async.mjs +5 -2
  47. package/agent-tools/batch-closeout.mjs +223 -35
  48. package/agent-tools/batch-gate.mjs +142 -342
  49. package/agent-tools/batch-ledger-bind.mjs +240 -20
  50. package/agent-tools/batch-ledger-view.mjs +109 -0
  51. package/agent-tools/batch-lifecycle.mjs +197 -48
  52. package/agent-tools/batch-paths.mjs +29 -8
  53. package/agent-tools/batch-read.mjs +151 -4
  54. package/agent-tools/batch-record-write.mjs +417 -0
  55. package/agent-tools/batch-regions.mjs +215 -0
  56. package/agent-tools/batch-reopen.mjs +23 -11
  57. package/agent-tools/batch-segment-vocab.mjs +459 -0
  58. package/agent-tools/batch-skeleton.mjs +196 -239
  59. package/agent-tools/batch-supersede.mjs +232 -0
  60. package/agent-tools/batch-tier-gate.mjs +214 -0
  61. package/agent-tools/batch.mjs +192 -439
  62. package/agent-tools/browser-async.mjs +5 -2
  63. package/agent-tools/consult.mjs +17 -11
  64. package/agent-tools/context.mjs +76 -33
  65. package/agent-tools/design-review-record.mjs +225 -0
  66. package/agent-tools/design-slots.mjs +1 -1
  67. package/agent-tools/design-token.mjs +279 -81
  68. package/agent-tools/digest-budget.mjs +10 -9
  69. package/agent-tools/doc-check.mjs +43 -33
  70. package/agent-tools/doc-graph.mjs +140 -0
  71. package/agent-tools/eng.mjs +12 -12
  72. package/agent-tools/escalate-async.mjs +5 -5
  73. package/agent-tools/goal.mjs +5 -2
  74. package/agent-tools/judge-domain.mjs +347 -0
  75. package/agent-tools/manifest.mjs +34 -18
  76. package/agent-tools/parent-channel.mjs +6 -3
  77. package/agent-tools/plan.mjs +11 -10
  78. package/agent-tools/read-history.mjs +112 -11
  79. package/agent-tools/review-facts.mjs +19 -6
  80. package/agent-tools/settings.mjs +23 -2
  81. package/agent-tools/skill.mjs +7 -8
  82. package/agent-tools/spawn-gates.mjs +14 -24
  83. package/agent-tools/ssh-session.mjs +8 -5
  84. package/agent-tools/ssh-text.mjs +155 -0
  85. package/agent-tools/ssh-transfer.mjs +1 -1
  86. package/agent-tools/ssh-transport.mjs +19 -148
  87. package/agent-tools/subagent-actions-query.mjs +10 -6
  88. package/agent-tools/subagent-actions.mjs +2 -2
  89. package/agent-tools/subagent-async.mjs +19 -17
  90. package/agent-tools/subagent-brief.mjs +76 -0
  91. package/agent-tools/subagent-design-token.mjs +168 -0
  92. package/agent-tools/subagent-run.mjs +1 -1
  93. package/agent-tools/subagent-scheduler.mjs +13 -13
  94. package/agent-tools/subagent-spawn.mjs +92 -112
  95. package/agent-tools/subagent.mjs +16 -28
  96. package/agent-tools/task.mjs +0 -8
  97. package/agent-tools/taskbook-block.mjs +94 -0
  98. package/agent-tools/timer.mjs +12 -8
  99. package/agent-tools/verify.mjs +13 -4
  100. package/agent-tools.mjs +7 -3
  101. package/agent.mjs +26 -7
  102. package/attachments.mjs +3 -3
  103. package/auto-think.mjs +5 -2
  104. package/browser/actions.mjs +9 -3
  105. package/browser/cdp.mjs +45 -17
  106. package/browser/launch.mjs +25 -43
  107. package/browser/pool.mjs +299 -0
  108. package/browser/queue.mjs +2 -0
  109. package/browser/session-state.mjs +450 -0
  110. package/browser/session.mjs +127 -151
  111. package/browser/snapshot.mjs +89 -0
  112. package/client-identity.mjs +1 -1
  113. package/compaction-work-state.mjs +230 -0
  114. package/compress-form.mjs +41 -6
  115. package/config-defaults.mjs +7 -3
  116. package/config-migrate.mjs +40 -0
  117. package/config-normalize.mjs +28 -2
  118. package/config-reload.mjs +59 -0
  119. package/config.mjs +110 -110
  120. package/context-degrade.mjs +93 -34
  121. package/context-echo.mjs +6 -15
  122. package/context-push.mjs +328 -31
  123. package/context.mjs +298 -170
  124. package/conventions.mjs +11 -9
  125. package/declaration.mjs +126 -22
  126. package/declared-repos.mjs +94 -0
  127. package/doc-check/doc-names.mjs +73 -0
  128. package/doc-check/doc-tokens.mjs +110 -0
  129. package/doc-check/existence.mjs +160 -0
  130. package/doc-check/index.mjs +309 -213
  131. package/doc-check/line-refs.mjs +27 -101
  132. package/doc-check/paragraph.mjs +218 -102
  133. package/doc-graph/anchors.mjs +474 -0
  134. package/doc-graph/doc-batch-face.mjs +59 -0
  135. package/doc-graph/doc-suffix.mjs +27 -0
  136. package/doc-graph/graph-tokens.mjs +160 -0
  137. package/doc-graph.mjs +778 -0
  138. package/escape.mjs +6 -5
  139. package/explore-distill.mjs +41 -8
  140. package/generate-title.mjs +10 -1
  141. package/i18n.mjs +1 -1
  142. package/instance-inbox-watch.mjs +272 -0
  143. package/instance-inbox.mjs +218 -0
  144. package/instance-registry.mjs +179 -0
  145. package/knowledge/README.md +3 -0
  146. package/knowledge/prompt-resources.md +10 -0
  147. package/ledger-close-proof.mjs +100 -49
  148. package/ledger-close.mjs +188 -0
  149. package/ledger-cmd.mjs +47 -91
  150. package/ledger-consistency.mjs +113 -0
  151. package/ledger-db.mjs +47 -15
  152. package/ledger-executors.mjs +1 -1
  153. package/ledger-tools.mjs +121 -62
  154. package/ledger-write-ops.mjs +162 -46
  155. package/ledger.mjs +1 -1
  156. package/manifest-discovery.mjs +3 -1
  157. package/manifest-schema.mjs +27 -5
  158. package/memory/docs.mjs +51 -15
  159. package/memory/file-list.mjs +6 -0
  160. package/memory/schema.mjs +2 -2
  161. package/model-specs.mjs +87 -21
  162. package/origin-guard.mjs +190 -0
  163. package/package.json +3 -1
  164. package/path-resolve.mjs +338 -57
  165. package/prompt-files.mjs +114 -2
  166. package/prompt-overlays.mjs +21 -11
  167. package/prompts/advisor-design.md +96 -36
  168. package/prompts/advisor-round1.md +48 -4
  169. package/prompts/advisor-round2.md +54 -10
  170. package/prompts/advisor-round3.md +53 -9
  171. package/prompts/common.md +99 -434
  172. package/prompts/consult-base.md +7 -4
  173. package/prompts/discipline-engineering.md +504 -295
  174. package/prompts/discipline-normal.md +106 -281
  175. package/prompts/knowledge/business-gates.md +30 -0
  176. package/prompts/knowledge/decision-quality.md +21 -0
  177. package/prompts/knowledge/doc-lookup.md +30 -0
  178. package/prompts/knowledge/document-writing.md +33 -0
  179. package/prompts/knowledge/documentation-evaluation.md +48 -0
  180. package/prompts/knowledge/evidence-discipline.md +38 -0
  181. package/prompts/knowledge/normal-coding-workflow.md +110 -0
  182. package/prompts/knowledge/normal-delivery-collaboration.md +124 -0
  183. package/prompts/knowledge/normal-work-management.md +60 -0
  184. package/prompts/knowledge/product-security.md +28 -0
  185. package/prompts/knowledge/project-records.md +73 -0
  186. package/prompts/knowledge/tool-advisor.md +29 -0
  187. package/prompts/knowledge/tool-apply-patch.md +17 -0
  188. package/prompts/knowledge/tool-bash.md +48 -0
  189. package/prompts/knowledge/tool-batch-eng-coder.md +19 -0
  190. package/prompts/knowledge/tool-batch-eng-designer.md +20 -0
  191. package/prompts/knowledge/tool-batch-review.md +18 -0
  192. package/prompts/knowledge/tool-batch.md +94 -0
  193. package/prompts/knowledge/tool-browser.md +68 -0
  194. package/prompts/knowledge/tool-code-search.md +4 -0
  195. package/prompts/knowledge/tool-consult-start.md +12 -0
  196. package/prompts/knowledge/tool-consult-stop.md +6 -0
  197. package/prompts/knowledge/tool-context.md +6 -0
  198. package/prompts/knowledge/tool-delete.md +21 -0
  199. package/prompts/knowledge/tool-doc-check.md +71 -0
  200. package/prompts/knowledge/tool-doc-graph-read.md +20 -0
  201. package/prompts/knowledge/tool-doc-graph.md +49 -0
  202. package/prompts/knowledge/tool-doc-search.md +6 -0
  203. package/prompts/knowledge/tool-edit.md +41 -0
  204. package/prompts/knowledge/tool-eng.md +2 -0
  205. package/prompts/knowledge/tool-execute.md +21 -0
  206. package/prompts/knowledge/tool-fetch.md +18 -0
  207. package/prompts/knowledge/tool-file-ops.md +21 -0
  208. package/prompts/knowledge/tool-get-current-time.md +7 -0
  209. package/prompts/knowledge/tool-git-read.md +21 -0
  210. package/prompts/knowledge/tool-git.md +29 -0
  211. package/prompts/knowledge/tool-glob.md +17 -0
  212. package/prompts/knowledge/tool-goal.md +8 -0
  213. package/prompts/knowledge/tool-grep.md +21 -0
  214. package/prompts/knowledge/tool-hashline-edit.md +16 -0
  215. package/prompts/knowledge/tool-insert-after.md +17 -0
  216. package/prompts/knowledge/tool-instance-list.md +6 -0
  217. package/prompts/knowledge/tool-instance-send.md +10 -0
  218. package/prompts/knowledge/tool-knowledge.md +18 -0
  219. package/prompts/knowledge/tool-ledger-read.md +28 -0
  220. package/prompts/knowledge/tool-ledger.md +46 -0
  221. package/prompts/knowledge/tool-lint.md +16 -0
  222. package/prompts/knowledge/tool-ls.md +15 -0
  223. package/prompts/knowledge/tool-lsp.md +11 -0
  224. package/prompts/knowledge/tool-main-history.md +2 -0
  225. package/prompts/knowledge/tool-manifest-read.md +14 -0
  226. package/prompts/knowledge/tool-manifest.md +34 -0
  227. package/prompts/knowledge/tool-memory-read.md +20 -0
  228. package/prompts/knowledge/tool-memory.md +19 -0
  229. package/prompts/knowledge/tool-notify-parent.md +12 -0
  230. package/prompts/knowledge/tool-operations.md +102 -0
  231. package/prompts/knowledge/tool-peer-instances.md +2 -0
  232. package/prompts/knowledge/tool-plan.md +5 -0
  233. package/prompts/knowledge/tool-process-read.md +13 -0
  234. package/prompts/knowledge/tool-process.md +15 -0
  235. package/prompts/knowledge/tool-question.md +16 -0
  236. package/prompts/knowledge/tool-read-history-batch.md +22 -0
  237. package/prompts/knowledge/tool-read-history.md +35 -0
  238. package/prompts/knowledge/tool-read-image.md +11 -0
  239. package/prompts/knowledge/tool-read.md +22 -0
  240. package/prompts/knowledge/tool-recent-changes.md +6 -0
  241. package/prompts/knowledge/tool-repo-outline.md +4 -0
  242. package/prompts/knowledge/tool-settings-read.md +12 -0
  243. package/prompts/knowledge/tool-settings.md +17 -0
  244. package/prompts/knowledge/tool-skill.md +6 -0
  245. package/prompts/knowledge/tool-ssh.md +74 -0
  246. package/prompts/knowledge/tool-subagent.md +57 -0
  247. package/prompts/knowledge/tool-task.md +14 -0
  248. package/prompts/knowledge/tool-team-ledger-read.md +11 -0
  249. package/prompts/knowledge/tool-team-ledger.md +15 -0
  250. package/prompts/knowledge/tool-timer.md +23 -0
  251. package/prompts/knowledge/tool-tree.md +16 -0
  252. package/prompts/knowledge/tool-verify.md +19 -0
  253. package/prompts/knowledge/tool-wait-for.md +25 -0
  254. package/prompts/knowledge/tool-websearch.md +19 -0
  255. package/prompts/knowledge/tool-write.md +12 -0
  256. package/prompts/knowledge/upstream-protocol.md +45 -0
  257. package/prompts/persona-coder.md +1 -3
  258. package/prompts/persona-eng-coder.md +24 -6
  259. package/prompts/persona-eng-designer.md +150 -171
  260. package/prompts/persona-engineering.md +531 -442
  261. package/prompts/persona-explore.md +1 -3
  262. package/prompts/persona-normal.md +17 -9
  263. package/prompts/persona-plan.md +5 -3
  264. package/prompts/persona-tester.md +0 -2
  265. package/prompts/subagent-base.md +2 -2
  266. package/provider/anthropic.mjs +10 -6
  267. package/provider/core.mjs +8 -5
  268. package/provider/errors.mjs +63 -4
  269. package/provider/google.mjs +29 -10
  270. package/provider/reasoning-echo.mjs +16 -0
  271. package/provider/responses.mjs +7 -3
  272. package/provider/sse.mjs +11 -6
  273. package/provider-flows.mjs +2 -2
  274. package/rules.mjs +11 -10
  275. package/session-index-build.mjs +1 -1
  276. package/session-index-pass.mjs +1 -1
  277. package/session-index-query.mjs +1 -1
  278. package/session-index.mjs +1 -1
  279. package/session-lifecycle.mjs +131 -42
  280. package/session-slot-write.mjs +38 -6
  281. package/session.mjs +30 -11
  282. package/shell-identity.mjs +129 -22
  283. package/skip-dirs.mjs +26 -2
  284. package/team-ledger.mjs +34 -30
  285. package/text-budget.mjs +1 -1
  286. package/think-off.mjs +27 -0
  287. package/token-ttl.mjs +74 -5
  288. package/token-window.mjs +371 -47
  289. package/tool-docs/advisor.md +2 -27
  290. package/tool-docs/apply_patch.md +1 -15
  291. package/tool-docs/bash.md +2 -43
  292. package/tool-docs/batch-eng-coder.md +3 -0
  293. package/tool-docs/batch-eng-designer.md +3 -0
  294. package/tool-docs/batch-review.md +3 -0
  295. package/tool-docs/batch.md +2 -84
  296. package/tool-docs/browser.md +2 -49
  297. package/tool-docs/code_search.md +2 -2
  298. package/tool-docs/consult_start.md +2 -8
  299. package/tool-docs/consult_stop.md +2 -4
  300. package/tool-docs/context.md +1 -5
  301. package/tool-docs/delete.md +2 -17
  302. package/tool-docs/doc_check.md +2 -107
  303. package/tool-docs/doc_graph-read.md +3 -0
  304. package/tool-docs/doc_graph.md +3 -0
  305. package/tool-docs/doc_search.md +2 -4
  306. package/tool-docs/edit.md +1 -38
  307. package/tool-docs/eng.md +3 -1
  308. package/tool-docs/execute.md +2 -18
  309. package/tool-docs/fetch.md +2 -14
  310. package/tool-docs/file_ops.md +2 -18
  311. package/tool-docs/get_current_time.md +1 -6
  312. package/tool-docs/git-read.md +3 -0
  313. package/tool-docs/git.md +2 -35
  314. package/tool-docs/glob.md +2 -10
  315. package/tool-docs/goal.md +1 -6
  316. package/tool-docs/grep.md +2 -18
  317. package/tool-docs/hashline_edit.md +2 -15
  318. package/tool-docs/insert_after.md +2 -16
  319. package/tool-docs/instance_list.md +3 -0
  320. package/tool-docs/instance_send.md +3 -0
  321. package/tool-docs/knowledge.md +3 -0
  322. package/tool-docs/ledger-read.md +3 -0
  323. package/tool-docs/ledger.md +3 -8
  324. package/tool-docs/lint.md +2 -10
  325. package/tool-docs/ls.md +2 -11
  326. package/tool-docs/lsp.md +2 -9
  327. package/tool-docs/main_history.md +3 -1
  328. package/tool-docs/manifest-read.md +2 -8
  329. package/tool-docs/manifest.md +2 -35
  330. package/tool-docs/memory-read.md +3 -0
  331. package/tool-docs/memory.md +2 -20
  332. package/tool-docs/notify_parent.md +2 -13
  333. package/tool-docs/peer_instances.md +3 -1
  334. package/tool-docs/plan.md +1 -5
  335. package/tool-docs/process-read.md +3 -0
  336. package/tool-docs/process.md +2 -13
  337. package/tool-docs/question.md +3 -17
  338. package/tool-docs/read.md +2 -19
  339. package/tool-docs/read_history-batch.md +3 -0
  340. package/tool-docs/read_history.md +2 -18
  341. package/tool-docs/read_image.md +2 -9
  342. package/tool-docs/recent_changes.md +2 -2
  343. package/tool-docs/repo_outline.md +2 -2
  344. package/tool-docs/settings-read.md +3 -0
  345. package/tool-docs/settings.md +1 -12
  346. package/tool-docs/skill.md +2 -6
  347. package/tool-docs/ssh.md +1 -62
  348. package/tool-docs/subagent.md +2 -100
  349. package/tool-docs/task.md +1 -7
  350. package/tool-docs/team_ledger-read.md +3 -0
  351. package/tool-docs/team_ledger.md +3 -9
  352. package/tool-docs/timer.md +2 -19
  353. package/tool-docs/tree.md +2 -13
  354. package/tool-docs/verify.md +2 -12
  355. package/tool-docs/wait_for.md +2 -32
  356. package/tool-docs/websearch.md +2 -19
  357. package/tool-docs/write.md +2 -12
  358. package/tools/browser.mjs +54 -9
  359. package/tools/doc-write-gate.mjs +73 -0
  360. package/tools/edit-batch.mjs +170 -92
  361. package/tools/edit-diff.mjs +78 -62
  362. package/tools/edit-receipt.mjs +39 -0
  363. package/tools/execute.mjs +3 -3
  364. package/tools/file.mjs +28 -14
  365. package/tools/git.mjs +36 -21
  366. package/tools/index.mjs +6 -0
  367. package/tools/knowledge.mjs +143 -0
  368. package/tools/linter.mjs +3 -3
  369. package/tools/ops.mjs +5 -3
  370. package/tools/patch.mjs +124 -44
  371. package/tools/process-doc-mark.mjs +33 -4
  372. package/tools/repomap.mjs +25 -3
  373. package/tools/search.mjs +74 -26
  374. package/tools/shared.mjs +29 -27
  375. package/tools/ssh.mjs +5 -5
  376. package/tools/tree.mjs +32 -10
  377. package/tools/web-deepseek.mjs +1 -1
  378. package/tools/web.mjs +2 -2
  379. package/tools/write-gate-params.mjs +31 -0
  380. package/tools/write-path.mjs +16 -4
  381. package/window-policy.mjs +243 -0
  382. package/doc-check/anchors.mjs +0 -235
package/tools/git.mjs CHANGED
@@ -3,8 +3,6 @@ import {
3
3
  truncate,
4
4
  runGit,
5
5
  gitFailureMessage,
6
- LEDGER_PARAM_DESC_GIT,
7
- PROJECT_PARAM_DESC,
8
6
  } from "./shared.mjs";
9
7
  import { spawnGit } from "./git-run.mjs";
10
8
  import { resolve } from "node:path";
@@ -58,10 +56,10 @@ export const gitTool = {
58
56
  parameters: {
59
57
  type: "object",
60
58
  properties: {
61
- action: { type: "string", enum: ["diff", "status", "log", "show", "checkpoint", "add", "rm", "commit", "push", "tag", "branch", "checkout", "restore", "stash", "fetch", "pull", "reset", "revert", "merge", "cherry-pick", "ls-remote", "clone", "init", "rebase", "remote", "clean", "switch", "apply", "worktree", "archive", "blame", "mv"], description: "diff / status / log / show / checkpoint / add / rm / commit / push / tag / branch / checkout / restore / stash / fetch / pull / reset / revert / merge / cherry-pick / ls-remote / clone / init / rebase / remote / clean / switch / apply / worktree / archive / blame / mv — clean/rebase 操作前自动快照,checkpointAction=rewind 恢复" },
59
+ action: { type: "string", enum: ["diff", "status", "log", "show", "checkpoint", "add", "rm", "commit", "push", "tag", "branch", "checkout", "restore", "stash", "fetch", "pull", "reset", "revert", "merge", "cherry-pick", "ls-remote", "clone", "init", "rebase", "remote", "clean", "switch", "apply", "worktree", "archive", "blame", "mv"], description: "Subcommand to run. `clean` and `rebase` snapshot the tree first; recover with `checkpointAction: \"rewind\"`." },
62
60
  // diff/log params
63
61
  staged: { type: "boolean", description: "(diff) Show staged changes instead of working tree" },
64
- path: { type: "string", description: "(diff/log/add/commit/checkout/restore/checkpoint:cat/versions/rewind/rm/apply/archive/blame/mv/worktree) File or directory to scope to / stage / restore(checkout/restore 操作前自动快照,checkpointAction=rewind 恢复)— add/rm/commit: space-separated for multiple(git add a b c——2026-09-05 发版痛点;含空格的文件名会被按多路径拆分——请用 bash git 处理)" },
62
+ path: { type: "string", description: "File or directory this subcommand acts on. `checkout -- <path>` and `restore` snapshot the tree first; recover with `checkpointAction: \"rewind\"`. `add`, `rm` and `commit` take several paths, space-separated — a name containing spaces is split as several paths." },
65
63
  ref: { type: "string", description: "(diff/show/checkout/reset/revert/merge/cherry-pick/tag:create/branch:create/rebase/worktree:add/archive) Commit/branch/ref; (push/pull/fetch) the branch or tag (space-separated for multiple)" },
66
64
  count: { type: "number", description: "(log) Number of commits (default 10)" },
67
65
  oneline: { type: "boolean", description: "(log) One-line-per-commit format" },
@@ -70,40 +68,39 @@ export const gitTool = {
70
68
  // write-op params
71
69
  name: { type: "string", description: "(branch/tag) The branch or tag name (create/delete/switch)" },
72
70
  remote: { type: "string", description: "(push/fetch/pull) Remote name (e.g. origin). Default: current upstream" },
73
- workdir: { type: "string", description: "Run git in this subdirectory (monorepo / multi-repo). Path relative to cwd — no directory restriction. Default: the discovered project repo root(缺省 = 发现的项目仓根;显式 workdir 优先)" },
71
+ workdir: { type: "string", description: "Run git in this subdirectory (monorepo / multi-repo). Path relative to cwd — no directory restriction. Default: the discovered project repo root; an explicit workdir wins." },
74
72
  config: { type: "array", items: { type: "string" }, description: "(network actions: push/fetch/pull/ls-remote) git -c overrides, e.g. [\"http.proxy=http://10.2.2.112:3128\"] for blocked remotes" },
75
73
  tags: { type: "boolean", description: "(push) Also push all tags (--tags)" },
76
- mode: { type: "string", enum: ["soft", "mixed", "hard"], description: "(reset) reset mode — hard snapshots the tree first + needs confirmation(操作前自动快照,checkpointAction=rewind 恢复)" },
77
- tagAction: { type: "string", enum: ["list", "create", "delete"], description: "(tag) list tags / create one / delete one(delete 操作前自动快照,checkpointAction=rewind 恢复)" },
78
- branchAction: { type: "string", enum: ["list", "create", "delete", "switch"], description: "(branch) list branches / create / delete / switch to one(delete 操作前自动快照,checkpointAction=rewind 恢复)" },
79
- stashAction: { type: "string", enum: ["push", "pop", "list"], description: "(stash) push (stash now) / pop (apply+drop) / list(pop 操作前自动快照,checkpointAction=rewind 恢复)" },
74
+ mode: { type: "string", enum: ["soft", "mixed", "hard"], description: "(reset) Reset mode. `hard` snapshots the tree first and needs confirmation; recover with `checkpointAction: \"rewind\"`." },
75
+ tagAction: { type: "string", enum: ["list", "create", "delete"], description: "(tag) Which tag action to run. `delete` snapshots first; recover with `checkpointAction: \"rewind\"`." },
76
+ branchAction: { type: "string", enum: ["list", "create", "delete", "switch"], description: "(branch) Which branch action to run. `delete` snapshots first; recover with `checkpointAction: \"rewind\"`." },
77
+ stashAction: { type: "string", enum: ["push", "pop", "list"], description: "(stash) Which stash action to run. `pop` applies then drops the entry, and snapshots first; recover with `checkpointAction: \"rewind\"`." },
80
78
  // checkpoint params
81
- checkpointAction: { type: "string", enum: ["list", "create", "rewind", "cat", "versions"], description: "(checkpoint) list snapshots / create one / restore by id / read file from snapshot / list a file's historical versions(rewind 可恢复操作前状态,恢复前自动快照可逆)" },
79
+ checkpointAction: { type: "string", enum: ["list", "create", "rewind", "cat", "versions"], description: "(checkpoint) Which snapshot action to run. `rewind` restores a pre-operation state (it snapshots first, so it is reversible); `cat` needs `checkpointId`." },
82
80
  checkpointId: { type: "string", description: "(checkpoint) Snapshot id — required for rewind and cat; optional for list (shows file tree)" },
83
81
  // F7 new-action params
84
- remoteAction: { type: "string", enum: ["list", "add", "remove", "set-url"], description: "(remote) list remotes / add / remove / set-url" },
82
+ remoteAction: { type: "string", enum: ["list", "add", "remove", "set-url"], description: "(remote) Which remote action to run; `add` and `set-url` need `remoteUrl`." },
85
83
  remoteUrl: { type: "string", description: "(remote add/set-url) Remote URL (https/git/ssh or local path)" },
86
- rebaseAction: { type: "string", enum: ["start", "abort", "continue"], description: "(rebase) start (ref required) / abort / continue(操作前自动快照,checkpointAction=rewind 恢复)" },
87
- dryRun: { type: "boolean", description: "(clean) preview only (-n) — no deletion, no snapshot; real clean 操作前自动快照,checkpointAction=rewind 恢复" },
84
+ rebaseAction: { type: "string", enum: ["start", "abort", "continue"], description: "(rebase) Which rebase step to run. `start` needs `ref`; the tree is snapshotted first — recover with `checkpointAction: \"rewind\"`." },
85
+ dryRun: { type: "boolean", description: "(clean) Preview only (-n) — no deletion, no snapshot. A real `clean` snapshots first; recover with `checkpointAction: \"rewind\"`." },
88
86
  create: { type: "boolean", description: "(switch) create the branch then switch (-c)" },
89
87
  dest: { type: "string", description: "(mv) destination path (file or directory)" },
90
- worktreeAction: { type: "string", enum: ["list", "add", "remove"], description: "(worktree) list / add (path, ref) / remove (path)" },
91
- ledger: { type: "string", description: LEDGER_PARAM_DESC_GIT },
92
- // 项目声明面(决策 40):`path` ∥ `workdir` 缺位时才被读(定位参数优先);纯声明,不改执行目录。
93
- project: { type: "string", description: PROJECT_PARAM_DESC },
88
+ worktreeAction: { type: "string", enum: ["list", "add", "remove"], description: "(worktree) Which worktree action to run; `add` takes `path` and `ref`, `remove` takes `path`." },
94
89
  },
95
90
  required: ["action"],
96
91
  },
97
92
  readonly: false,
98
93
  /**
99
94
  * 动作级只读分类(决策 37 · 2026-11-03 笔-账绑定批——**本钩子是单源**)。
100
- * 消费面两处:`thincoder-core/agent/dispatch-gates.mjs` 的 `readonlyActionOf(tool, "git", args)`
101
- * (planMode 门 ∥ 权限短路 ∥ 写门的 `git` 写型/只读判定)——三面(CLI ∥ desktop ∥ vscode)同答案。
95
+ * 消费面 = **审批面**:`thincoder-core/agent/dispatch-gates.mjs` 的 `readonlyActionOf(tool, "git", args)`
96
+ * (planMode 门 ∥ 免审批短路,调用点 = `thincoder-core/agent/dispatch.mjs`)——三面(CLI ∥ desktop ∥ vscode)同答案。
97
+ * 写门那个消费者随 2026-11-05 免号批退场:`git` 整把不在写门入口集,写型与只读在门上同判(都不要号);
98
+ * 名单照留——谁消费谁负责,一处不用不是删它的理由(设计档 §2.3「只读名单本体」)。
102
99
  * 名单与 `thincoder-vscode/src/tools/index.mjs` 原端装饰体逐条同形(该覆写随本钩子同笔删除):
103
100
  * 六项平铺 + 六条子动作分支。`checkpoint` 的 `list` ∥ `cat` 判只读——`checkpoint list` 有 F6 清理副作用
104
101
  * (`lazyClearIfCommitted` 可能删除整个 checkpoint 目录),但清的是 commit 后已失去意义的过期快照 ⇒
105
102
  * 保留只读分类免审批(`docs/core/design/CHECKPOINT.md` F6/D3 设计意图)。
106
- * 缺此钩子的面回落到核名面谓词(无 `git` 分支 ⇒ false ⇒ 写型 ⇒ 要号),fail-closed,不出洞。
103
+ * 缺此钩子的面回落到核名面谓词(无 `git` 分支 ⇒ false ⇒ 写型 ⇒ 走审批),fail-closed,不出洞。
107
104
  */
108
105
  isReadonlyAction(args) {
109
106
  if (!args || typeof args.action !== "string") return false
@@ -230,7 +227,25 @@ const gitActionCore = {
230
227
  if (args.path !== undefined && args.path !== null) {
231
228
  const trimmed = args.path.trim()
232
229
  if (!trimmed) return "Error: commit path is empty/whitespace — give at least one file path (space-separated)"
233
- commit = await runGitStrict(ctx.cwd, ["commit", "--only", "-m", args.message, "--", ...trimmed.split(/\s+/)])
230
+ const paths = trimmed.split(/\s+/)
231
+ // 未跟踪预检(`docs/core/design/TOOLS.md` §4.1):`--only` 只认已进索引的路径——请求里任一档从未进过索引时,
232
+ // git 只抛 `pathspec '…' did not match any file(s) known to git`,读起来像路径打错,
233
+ // 真实原因却只有一个。判据取索引视图、**不拿 git 的报错文案做分支**(换措辞或换语言环境即失效);
234
+ // 逐条问 git 自己的 pathspec 引擎,目录 / 通配 / 已 `git add` 的新档三种形都不需要额外分支。
235
+ // `--with-tree=HEAD` 不能省:`git rm <档>` 之后该档已不在索引里(纯索引视图读到空),
236
+ // 而 `--only` 拿它提交是**成功**的(实测:`1 file changed, 1 deletion(-)`)——
237
+ // 只查索引就会把一次可成功的提交拒掉,正是这条预检存在的反面。HEAD 里仍在的档因此放行。
238
+ // 逐条互不依赖、只读索引 ⇒ 并行问,不为一串路径排 N 次往返。
239
+ const probes = await Promise.all(
240
+ paths.map((p) => runGitStrict(ctx.cwd, ["ls-files", "-z", "--with-tree=HEAD", "--", p]))
241
+ )
242
+ // 预检自身失败(`ls-files` 非零退出:路径规格语法错、HEAD 尚未出生)⇒ 该路径不判,
243
+ // 落回原提交路径由 git 报它自己的错。把技术故障读成「未跟踪」会拒掉一次本可成功的提交——
244
+ // 那才是改变业务结果。
245
+ const untracked = paths.filter((p, i) => probes[i].ok && !probes[i].out)
246
+ // 全有或全无:`--only` 本就是原子语义,放行一半会让「提交了哪些档」与请求集对不上。
247
+ if (untracked.length) return truncate(`Error: commit path not tracked by git — untracked: ${untracked.join(" ")} — run git add on them first, or omit path to commit all changes (add -A + full commit)`)
248
+ commit = await runGitStrict(ctx.cwd, ["commit", "--only", "-m", args.message, "--", ...paths])
234
249
  } else {
235
250
  const add = await runGitStrict(ctx.cwd, ["add", "-A"])
236
251
  if (!add.ok) return truncate(`git add failed: ${add.err || add.out || "(no output)"}`)
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, 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"
@@ -23,10 +23,12 @@ export const fileOpsTool = {
23
23
  parameters: {
24
24
  type: "object",
25
25
  properties: {
26
- action: { type: "string", enum: ["move", "copy", "rename"], description: "move | copy | rename" },
26
+ action: { type: "string", enum: ["move", "copy", "rename"], description: "The action to run." },
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
  },
@@ -58,7 +60,7 @@ export const processTool = {
58
60
  action: { type: "string", enum: ["list", "kill"], description: "list (default) — show running processes; kill — terminate a process tree (target: pid) or a background task (target: id)" },
59
61
  name: { type: "string", description: "Optional name substring filter for list (case-insensitive)" },
60
62
  pid: { type: "number", description: "kill target: process id — the whole tree is terminated (taskkill /T /F on win32; POSIX group kill)" },
61
- id: { type: "number", description: "kill target: background task id — a bash#N (bash async ack) or browser#N (browser async ack): bash ⇒ its process tree is terminated; browser ⇒ a queued task is dropped, a running one is aborted (the browser itself is not killed); either way the entry leaves the pool and no digest will arrive." },
63
+ id: { type: "number", description: "kill target: background task id — the N from a `bash#N` or `browser#N` ack, as a number. bash ⇒ its process tree is terminated. browser ⇒ a queued task is dropped, a running one aborted (the browser itself is not killed). Either way the entry leaves the pool and no digest arrives." },
62
64
  },
63
65
  },
64
66
  // #9:动作分级——list 保持只读分类(dispatch-gates `isReadonlyAction`:planMode 放行/
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,14 +173,76 @@ 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"),
175
239
  parameters: {
176
240
  type: "object",
177
241
  properties: {
178
- 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>)." },
242
+ patch: { type: "string", description: "Unified diff. One `--- a/<path>` / `+++ b/<path>` pair per file, then @@ hunks. Creating files: `--- /dev/null` plus the path header. A bare `@@` hunk is located by its anchor lines — the context lines plus the removed (-) lines, matched as one contiguous unique sequence; it applies only when that sequence is unique and it either removes at least one line or carries at least 2 context lines. Anchor-free pure-+ hunks need at least 2 context lines. For an existing file the `+++ b/<path>` pair may be omitted: a lone `--- a/<path>` (or `--- b/<path>`) header followed directly by hunks applies to that 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
  },