@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
@@ -1,22 +1,25 @@
1
1
  /**
2
2
  * edit-diff.mjs — edit 工具的行级 diff 内核(权威语义 = EDIT.md——2026-09-04 拆出)。
3
3
  *
4
- * edit 语义(权威 = EDIT.md §2-§5——2026-09-08 语义升级 D1/D2/D3 已并入):两种定位形态(互斥)——
4
+ * edit 语义(权威 = EDIT.md——2026-09-08 语义升级 D1/D2/D3 已并入):两种定位形态(互斥)——
5
5
  * ① 按行号改(D1/F1):line(单行)/ startLine+endLine(1-based 闭区间)→ 直接替换该
6
6
  * 行/行范围为 new_string(无需 old_string——实现落点 edit-batch.mjs applyLineEdit);
7
- * 阶段 2 删行形态(EDIT.md §5——约束):省略 new_string = 删除该行/范围(有界意图);
7
+ * **先过行号锚护栏**(判据与拒文单源 = write-path.mjs 的 lineAnchorVerdict /
8
+ * lineAnchorRefusal——上一笔写之后目标区落在受影响区内即拒);
9
+ * 阶段 2 删行形态(EDIT.md §1「参数」——空值矩阵):省略 new_string 或传空串 = 删除该行/范围
10
+ * (有界意图——删行意图由行号表达,两种写法同一结局);
8
11
  * ② 内容定位:old_string = 变化区**当前内容**(单次匹配——匹配档位:逐字 → P15.11 唯一
9
12
  * 空白差异窗口 → D2/F2 模糊匹配(行级 normalize 后 ≥90% 行相等——edit-batch.mjs
10
13
  * findFuzzyWindow));new_string = 该区的**期望结果**。判定序:
11
- * 0. 分支 0(EDIT.md §4——单行精确替换):old 单行 && new 单行 && old 全文唯一 &&
14
+ * 0. 分支 0(单行精确替换):old 单行 && new 单行 && old 全文唯一 &&
12
15
  * new 非空 → **就地替换该行**(行数不变——EOL 由调用方 joinWithEol 恢复);
13
16
  * 1. 零重叠(old 每一行都不出现在 new 行集中)→ **替换即删**(D3/F3,2026-09-08——
14
17
  * breaking:old 行整体删除、new 取而代之——旧行不再保留;新增行用 insert_after);
15
18
  * 2. 有公共行(≥1)→ 行级 LCS——公共行保留、差异行增删;
16
19
  * 3. new 与 old 行级完全一致 → 原样替换(no-op 语义——仍报成功)。
17
20
  * 内容形态空 new_string(纯删除意图)→ 显式报错(不静默——先于分支 0——单行替换永不
18
- * 成删除);行号形态显式空串 → 同样显式错(防误删——模板落空 ≠ 删行意图;EDIT.md
19
- * §5 空串 vs 省略矩阵);**省略 new_string = 删行/范围**(阶段 2 命名删行形态);
21
+ * 成删除;无界意图:replace_all 配空串会删掉全部匹配);**行号形态省略 new_string 或
22
+ * 传空串 = 删行/范围**(同一结局——归一落点 applyLineEdit,EDIT.md §1「参数」/§2「匹配与应用」);
20
23
  * 分支 0 只在 computeEditEntry 条目判定层(壳/桥/批量自动继承)——
21
24
  * applyPatchLines(纯 diff 层)语义不动。old/new 行数各上限 1000(超限报错)。
22
25
  *
@@ -35,25 +38,22 @@ import {
35
38
  // 仅在调用期使用——ESM 循环下安全(无模块求值期取值)。
36
39
  // 写盘经单一写路径点(§2.13.5)——本档不再直调 fs。
37
40
  import { appendWriteContext } from "./file.mjs"
38
- import { writeThroughPath, lastWriteOf, isDirty } from "./write-path.mjs"
39
- // D1/D2 落点(EDIT.md §6——edit-batch.mjs):按行号改 + 模糊匹配纯函数。
41
+ import { writeThroughPath, lastWriteOf, isDirty, lineAnchorVerdict, lineAnchorRefusal } from "./write-path.mjs"
42
+ // D1/D2 落点(EDIT.md §2「匹配与应用」——edit-batch.mjs):按行号改 + 模糊匹配纯函数。
40
43
  import { applyLineEdit, findFuzzyWindow, FUZZY_MATCH_NOTE } from "./edit-batch.mjs"
41
44
 
42
45
  export const MAX_DIFF_LINES = 1000
43
46
  export const REGION_TOO_LARGE = "edit region too large — narrow the change"
44
- export const EMPTY_NEW_STRING = "empty new_string — for deletion, keep the context lines you want to preserve in both old_string and new_string"
45
- export const EMPTY_NEW_STRING_LINE = "empty new_string with line-based targeting is an explicit error — OMIT new_string to delete the line/range (deleting by number is explicit intent; an empty replacement is a mistake, not a delete)"
47
+ export const EMPTY_NEW_STRING = "empty new_string is an explicit error for content-based targeting (old_string) — a content entry's delete intent can only be expressed by the content, and replace_all + \"\" would delete every match with no bound; to delete, use line-based targeting (line / startLine+endLine), where new_string may be omitted or passed as an empty string"
46
48
  export const EDIT_ARGS_MUTEX = "edits array is mutually exclusive with top-level old_string/new_string/line/startLine/endLine — a top-level path is allowed (default for entries without their own path); provide each change's targeting (old_string or line range) and new_string inside its edits entry"
47
49
 
48
- // ─── #325 入参守卫文案(单源——EDIT.md §5 / §8 D-7:核 edit-batch 与 ACP 桥 bridge.mjs 同调用)───
50
+ // ─── #325 入参守卫文案(单源——核 edit-batch 与 ACP 桥 bridge.mjs 同调用)───
49
51
  /** 容器级成形错误(真值非数组 / 空数组——同一错误面)。 */
50
52
  export const EDITS_CONTAINER_ERROR = "edits must be a non-empty array of {path, old_string | line/startLine+endLine, new_string}"
51
53
  /** 条目级成形错误(i = 数组下标;非对象条目 = null / 字符串 / 数字 / 数组)。 */
52
54
  export const editsEntryError = (i) => `edits[${i}] must be an object of {path, old_string | line/startLine+endLine, new_string}`
53
55
  /** 条目缺 path 且无顶层默认路径。 */
54
56
  export const EDIT_ENTRY_NO_PATH = "each edit must have a path — give each entry its own path or pass a top-level path"
55
- /** 批量原子失败前缀(条目判定失败时拼在消息前的 abortPrefix)。 */
56
- export const EDIT_ABORT_PREFIX = "edit aborted (atomic — no files written): "
57
57
  /** 批量条目校验前缀(validateEditEntry 的 opts.label)。 */
58
58
  export const editEntryLabel = (path) => `edit for ${path}: `
59
59
 
@@ -133,7 +133,7 @@ function lcsMerge(a, b) {
133
133
  }
134
134
 
135
135
  /**
136
- * (2026-09-05 用户裁定——EDIT.md §5——顶层 path + edits 并存合法化:顶层 path = 无自带
136
+ * (2026-09-05 用户裁定——顶层 path + edits 并存合法化:顶层 path = 无自带
137
137
  * path 条目的默认——模型直觉形态「顶层 path + 数组条目」不再拒绝;条目自带 path 优先)。
138
138
  * 互斥收窄为只对顶层 old_string/new_string(+ 2026-09-08 D1 的 line/startLine/endLine)——
139
139
  * edits 下它们无批语义可解释——顶层 path 不再触发。
@@ -144,31 +144,24 @@ export function assertEditArgsExclusive(args) {
144
144
  }
145
145
  }
146
146
 
147
- /** 入参容器守卫(#325——EDIT.md §5):edits 真值非数组 / 空数组 ⇒ 成形错误(同句单源——
147
+ /** 入参容器守卫(#325):edits 真值非数组 / 空数组 ⇒ 成形错误(同句单源——
148
148
  * 核 edit-batch 与 ACP 桥 bridge.mjs 同调用)。批量判定序:容器 → 互斥 → 条目预扫 → 条目循环。 */
149
149
  export function assertEditsContainer(edits) {
150
150
  if (!Array.isArray(edits) || edits.length === 0) throw new Error(EDITS_CONTAINER_ERROR)
151
151
  }
152
152
 
153
- /** 入参条目守卫(#325——EDIT.md §5):条目非对象(null / 字符串 / 数字 / 数组)⇒ 含下标成形
154
- * 错误——预扫于条目循环之前(不读盘、不触盘、零部分应用)。 */
155
- export function assertEditEntries(edits) {
156
- for (let i = 0; i < edits.length; i++) {
157
- const e = edits[i]
158
- if (e === null || typeof e !== "object" || Array.isArray(e)) throw new Error(editsEntryError(i))
159
- }
160
- }
161
-
162
153
  /**
163
154
  * 前置校验——内容形态:空 old / 非字符串 new;按行号改形态(D1,2026-09-08;阶段 2
164
- * 删行——EDIT.md §5):与 old_string 互斥 / line 与 startLine|endLine 互斥 /
155
+ * 删行——EDIT.md §1「参数」):与 old_string 互斥 / line 与 startLine|endLine 互斥 /
165
156
  * startLine+endLine 须成对 / 正整数 / endLine ≥ startLine / replace_all 不适用 /
166
- * new_string:省略(undefined)= 删行 / 显式空串 = 显式错(防误删)/ 其他类型报错。
157
+ * new_string:省略(undefined)或空串 = 删行(同一结局——除行号外不给别的结局)/ 其他类型报错。
167
158
  * error 文本按调用形态(单形态 rich / 批量 label)。
168
- * opts: { label = ""(批量前缀 = editEntryLabel(path)), rich = true(单形态完整文本) }
159
+ * opts: { label = ""(批量前缀 = editEntryLabel(path)), rich = true(单形态完整文本),
160
+ * scope = "batch" 时一律按 rich=false(批面不带写盘结论——EDIT.md §3「写与桥」) }
169
161
  */
170
162
  export function validateEditEntry(entry, opts = {}) {
171
163
  const label = opts.label ?? ""
164
+ const rich = opts.scope === "batch" ? false : opts.rich !== false
172
165
  if (hasLineParams(entry)) {
173
166
  if (entry.old_string !== undefined) {
174
167
  throw new Error(label + "line/startLine/endLine are mutually exclusive with old_string — target by line number OR by content, not both")
@@ -190,37 +183,34 @@ export function validateEditEntry(entry, opts = {}) {
190
183
  if (entry.replace_all) {
191
184
  throw new Error(label + "replace_all does not apply to line-based edits (a line range is already a single explicit target)")
192
185
  }
193
- if (entry.new_string === "") {
194
- throw new Error(label + EMPTY_NEW_STRING_LINE + (opts.rich === false ? "" : " — nothing written"))
195
- }
196
186
  if (entry.new_string !== undefined && typeof entry.new_string !== "string") {
197
187
  throw new Error(
198
188
  label + `new_string must be a string (got ${typeof entry.new_string})` +
199
- (opts.rich === false ? "" : " — nothing written")
189
+ (rich ? " — nothing written" : "")
200
190
  )
201
191
  }
202
192
  return
203
193
  }
204
194
  if (!entry.old_string) {
205
195
  throw new Error(
206
- label + "old_string must not be empty" + (opts.rich === false ? "" : " (empty string matches everywhere and would corrupt the file)")
196
+ label + "old_string must not be empty" + (rich ? " (empty string matches everywhere and would corrupt the file)" : "")
207
197
  )
208
198
  }
209
199
  if (entry.new_string === "") {
210
- // 空串 vs 省略矩阵(EDIT.md §5/§8.1):内容形态空串 = 显式错(无界意图防静默)——
200
+ // 空串 vs 省略矩阵(EDIT.md §1「参数」):内容形态空串 = 显式错(无界意图防静默)——
211
201
  // 先于 replace_all 分支(否则 replace_all + 空串会静默删除全部 occurrences——绕过保护)
212
- throw new Error(label + EMPTY_NEW_STRING + (opts.rich === false ? "" : " — nothing written"))
202
+ throw new Error(label + EMPTY_NEW_STRING + (rich ? " — nothing written" : ""))
213
203
  }
214
204
  if (typeof entry.new_string !== "string") {
215
205
  throw new Error(
216
206
  label + `new_string must be a string${entry.new_string === undefined ? " (missing)" : ` (got ${typeof entry.new_string})`}` +
217
- (opts.rich === false ? "" : " — nothing written")
207
+ (rich ? " — nothing written" : "")
218
208
  )
219
209
  }
220
210
  }
221
211
 
222
212
  /**
223
- * 分支 0 形态判定(EDIT.md §4):old/new 各为单行——无内部换行(splitLines
213
+ * 分支 0 形态判定:old/new 各为单行——无内部换行(splitLines
224
214
  * 语义:尾随单个换行符是行终止而非新行——old/new 行内容均不含 \n)——且 new 非空
225
215
  * ("" 经 splitLines 切分为 []——由下方 !== "" 守卫先拦截——空 new 不落本分支——落
226
216
  * applyPatchLines 的空 new 显式错误——单行替换永不成删除)。多匹配与 replace_all 不落
@@ -235,12 +225,15 @@ function isSingleLineReplace(entry) {
235
225
  }
236
226
 
237
227
  /**
238
- * 条目级判定+应用(单形态与批量共用——EDIT.md §6"批量条目判定+应用调用 edit-diff"):
228
+ * 条目级判定+应用(单形态与批量共用——EDIT.md §2「匹配与应用」):
239
229
  * 匹配校验(精确存在——非 replace_all 单次)→ 按判定序应用(分支 0 单行替换 / 零重叠替换即删 /
240
230
  * LCS 替换 / replace_all 字面)→
241
231
  * 元数据(受影响区首行/行数差/次数——recordWrite 与结果回显用)。
242
232
  * 返回 { updated, editStartLine, lineShift, occurrences, note?, deleted? };失败抛错(含路径/引导)。
243
- * opts: { path, abortPrefix(批量 = EDIT_ABORT_PREFIX) }
233
+ * opts: { path, absPath, scope }
234
+ * `scope:"batch"` = 两个批面(EDIT.md §3「写与桥」):错误文本**不带任何写盘结论**
235
+ * ——不带 ` — nothing written` 后缀(批面逐条报,那句在批面为假);
236
+ * 其余取值(含缺省)= 单档面,照 `rich` 的既有取法(带后缀)。
244
237
  */
245
238
  /**
246
239
  * P15.11(2026-09-05 用户裁定——edit 连续失败分析):old_string 逐字 not-found 时——
@@ -278,10 +271,13 @@ function findWhitespaceVariant(content, old) {
278
271
  export const WHITESPACE_VARIANT_NOTE = "applied to the unique whitespace-only match (content identical, leading/trailing whitespace differs from your old_string)"
279
272
 
280
273
  export function computeEditEntry(content, entry, opts = {}) {
281
- validateEditEntry(entry, { ...opts, rich: !opts.abortPrefix })
282
- // D1 按行号改(EDIT.md §2/§5):行号定位条目直接按行替换(applyLineEdit——落点
283
- // edit-batch.mjs),不走 old_string 匹配/判定序;省略 new_string = 删行(EDIT.md §5);
284
- // 互斥/越界/显式空串均在 validateEditEntry/applyLineEdit 显式报错。
274
+ // 写盘结论面(EDIT.md §3「写与桥」):`scope:"batch"` 这一个开关压掉
275
+ // ` — nothing written` 后缀(批面逐条报,那句在批面为假)。前缀形已退役,不再有要拼的。
276
+ const batchScope = opts.scope === "batch"
277
+ validateEditEntry(entry, { ...opts, rich: !batchScope })
278
+ // D1 按行号改(EDIT.md §1「参数」/§2「匹配与应用」):行号定位条目直接按行替换(applyLineEdit——落点
279
+ // edit-batch.mjs),不走 old_string 匹配/判定序;省略 new_string 或传空串 = 删行(同一
280
+ // 结局,归一在 applyLineEdit 内落一次);互斥/越界在 validateEditEntry/applyLineEdit 显式报错。
285
281
  if (hasLineParams(entry)) return applyLineEdit(content, entry, opts)
286
282
  // P15.11:not-found 时先查唯一空白差异窗口——命中则以其原文为实际 old 继续(内容零差异
287
283
  // ——自动落点 + note 明示);实质差异/歧义仍走下方 not-found 报错(不猜内容)。
@@ -310,7 +306,7 @@ export function computeEditEntry(content, entry, opts = {}) {
310
306
  candText = "\n" + header + "\n" + cands.map((c) => ` L${c.line}: ${c.preview} (${Math.round(c.score * 100)}%)`).join("\n")
311
307
  }
312
308
  throw new Error(
313
- `${opts.abortPrefix ?? ""}old_string not found in ${opts.path ?? "file"}\n` +
309
+ `old_string not found in ${opts.path ?? "file"}\n` +
314
310
  ` searched: "${preview}${entry.old_string.length > 100 ? "…" : ""}" — use grep to locate the actual content\n` +
315
311
  (opts.absPath && lastWriteOf(opts.absPath)?.type === "write"
316
312
  ? ` hints: this file was modified since your last read (write 全文重写后内容全变) — re-read it to refresh your copy of the content, then retry\n`
@@ -322,7 +318,7 @@ export function computeEditEntry(content, entry, opts = {}) {
322
318
  }
323
319
  if (occurrences > 1 && !entry.replace_all) {
324
320
  throw new Error(
325
- `${opts.abortPrefix ?? ""}old_string matches ${occurrences} times in ${opts.path ?? "file"}; provide more context or set replace_all`
321
+ `old_string matches ${occurrences} times in ${opts.path ?? "file"}; provide more context or set replace_all`
326
322
  )
327
323
  }
328
324
  const matchIdx = content.indexOf(old)
@@ -330,11 +326,11 @@ export function computeEditEntry(content, entry, opts = {}) {
330
326
  let updated
331
327
  let resultForShift
332
328
  if (entry.replace_all) {
333
- // 字面替换——不做插入规则(old 多处时"插到哪处"无定义)——不落分支 0(EDIT.md §4)
329
+ // 字面替换——不做插入规则(old 多处时"插到哪处"无定义)——不落分支 0
334
330
  updated = content.split(old).join(entry.new_string)
335
331
  resultForShift = entry.new_string
336
332
  } else if (isSingleLineReplace(entry)) {
337
- // 分支 0(EDIT.md §4——单行精确替换):old 单行 && new 单行 && old 唯一匹配
333
+ // 分支 0(单行精确替换):old 单行 && new 单行 && old 唯一匹配
338
334
  // (occ==1 既有校验保证)&& new 非空(空 new 显式错误先于本分支——防删除)→ **就地
339
335
  // 替换该行**——不再零重叠插入(P15.8——行尾段编辑反复踩的插入坑)。只替换行内容段:
340
336
  // old/new 的尾随换行符属文件结构而非行内容——留在原位——行数不变——EOL 由调用方
@@ -357,6 +353,84 @@ export function computeEditEntry(content, entry, opts = {}) {
357
353
  return { updated, editStartLine, lineShift, occurrences: entry.replace_all ? occurrences : 1, note }
358
354
  }
359
355
 
356
+ /**
357
+ * `EDIT-HELPERS.md` §4「批量帧」的 R1–R4——同档多条 `edits` 的应用顺序:行号条目先全部应用、按 `startLine` 降序
358
+ * (从下往上改,上方行号不被同批自己顶偏);内容条目随后按数组序(位置无关寻址无帧问题)。
359
+ *
360
+ * **零 IO**(只看条目自身的行号):两个通道(本地 `edit-batch` ∥ ACP 桥)调同一份排法,
361
+ * 各自只提供自己的 IO——抄一份组循环就是本机制要根治的形状。
362
+ *
363
+ * @returns {{ order: number[], rejections: {index: number, reason: string}[] }}
364
+ * `order` = **未被拒**条目的应用序(下标指向传入的 `entries`,回显仍按调用序取原位);
365
+ * `rejections` = R3 重叠:**互指的每一条各得一行**(原因互指对方行范围——`EDIT-HELPERS.md` §4
366
+ * 「批量帧」,同档其余条照应用)。拒因是**纯原因句**——不带前缀、不带写盘结论
367
+ * (「no files written」在逐条模式为假);回执行由调用方按骨架组装。
368
+ * `path`(可选)= 拒文里点名的目标档(条目自带 path 优先——顶层 path 不在条目上)。
369
+ */
370
+ export function planEditEntries(entries, path = null) {
371
+ const rangeOf = (e) => [e.line ?? e.startLine, e.line ?? e.endLine]
372
+ const lineIdx = []
373
+ const contentIdx = []
374
+ entries.forEach((e, i) => { (hasLineParams(e) ? lineIdx : contentIdx).push(i) })
375
+ // R3:两条行号条目的范围在快照坐标上重叠 ⇒ 先改哪一条决定结果,模型意图在此矛盾
376
+ // ——两条都废(先改哪条都改意),互指对方行范围。
377
+ const rejected = new Map() // 条目下标 → 拒因
378
+ const byStart = [...lineIdx].sort((a, b) => rangeOf(entries[a])[0] - rangeOf(entries[b])[0])
379
+ for (let i = 1; i < byStart.length; i++) {
380
+ const a = byStart[i - 1]
381
+ const b = byStart[i]
382
+ const ra = rangeOf(entries[a])
383
+ const rb = rangeOf(entries[b])
384
+ if (rb[0] > ra[1]) continue
385
+ const label = entries[b].path ?? entries[a].path ?? path ?? "file"
386
+ const reason =
387
+ `line-number entries L${ra[0]}-L${ra[1]} and L${rb[0]}-L${rb[1]} (${label}) overlap — ` +
388
+ `two changes to the same region cannot both be anchored on the numbers you read; split them into separate calls`
389
+ if (!rejected.has(a)) rejected.set(a, reason)
390
+ if (!rejected.has(b)) rejected.set(b, reason)
391
+ }
392
+ const rejections = [...rejected.entries()]
393
+ .sort((x, y) => x[0] - y[0])
394
+ .map(([index, reason]) => ({ index, reason }))
395
+ // R2:降序(同档起始行不会相等——相等即重叠,已在 R3 拒掉)
396
+ const alive = lineIdx.filter((i) => !rejected.has(i))
397
+ const desc = [...alive].sort((a, b) => rangeOf(entries[b])[0] - rangeOf(entries[a])[0])
398
+ return { order: [...desc, ...contentIdx], rejections }
399
+ }
400
+
401
+ /**
402
+ * 按 `planEditEntries` 排出的应用序逐条 `computeEditEntry` 累积——**零 IO**。
403
+ * `results` 按调用序回到原位(回显顺序不变),元数据形同 `computeEditEntry` 返回。
404
+ *
405
+ * opts.onEntryError:`"throw"`(缺省——整批拒的调用面)∥ `"collect"`(逐条成败:一条抛错
406
+ * 就记它自己一行、累积内容不动、继续下一条——EDIT.md §2「匹配与应用」)。
407
+ */
408
+ export function applyPlannedEntries(content, entries, order, opts = {}) {
409
+ let cur = content
410
+ const results = new Array(entries.length)
411
+ const failures = []
412
+ const collect = opts.onEntryError === "collect"
413
+ for (const i of order) {
414
+ let out
415
+ try {
416
+ out = computeEditEntry(cur, entries[i], opts)
417
+ } catch (err) {
418
+ if (!collect) throw err
419
+ failures.push({ index: i, reason: err?.message ?? String(err) })
420
+ continue
421
+ }
422
+ results[i] = {
423
+ editStartLine: out.editStartLine,
424
+ lineShift: out.lineShift,
425
+ occurrences: out.occurrences,
426
+ note: out.note ?? null,
427
+ deleted: out.deleted ?? false,
428
+ }
429
+ cur = out.updated
430
+ }
431
+ return { content: cur, results, failures }
432
+ }
433
+
360
434
  /**
361
435
  * 单形态 edit 执行体(自 file.mjs 整段迁出——模块拆分写优先纪律:逻辑体不变)——
362
436
  * file.mjs 只留工具壳与转发。
@@ -365,11 +439,21 @@ export async function runSingleEdit(args, ctx) {
365
439
  const abs = resolveInCwd(ctx, args.path)
366
440
  const raw = await readFile(abs, "utf8")
367
441
  const content = normalizeEOL(raw)
442
+ // 行号锚护栏(判定点写死:读盘之后、computeEditEntry 之前):行号形才需判——内容形态是
443
+ // 位置无关寻址,没有可漂移的锚。判据与拒文单源 = write-path.mjs。
444
+ // 形态校验先于护栏:缺 endLine / 与 old_string 互斥这类错要报自己的句,不该被拒文顶掉。
445
+ if (hasLineParams(args)) {
446
+ validateEditEntry(args, { rich: true })
447
+ const startLine = args.line ?? args.startLine
448
+ const endLine = args.line ?? args.endLine
449
+ if (lineAnchorVerdict(abs, startLine, endLine)) throw new Error(lineAnchorRefusal(abs, startLine, endLine))
450
+ }
368
451
  const out = computeEditEntry(content, args, { path: args.path, absPath: abs })
369
452
  // 写回按原文行尾(joinWithEol)——normalizeEOL 先行避免 \r\n 污染 split/join
370
453
  // 单一写路径点:默认 = writeFile + 记账;端侧注入 ⇒ 编辑器径(§2.13.5)。
371
454
  await writeThroughPath(abs, joinWithEol(normalizeEOL(out.updated).split("\n"), raw), {
372
455
  op: "write",
456
+ agent: ctx.agent,
373
457
  record: { type: "edit", startLine: out.editStartLine, shift: out.lineShift },
374
458
  })
375
459
  const diff = await gitDiffOne(ctx.cwd, abs)
@@ -0,0 +1,39 @@
1
+ /**
2
+ * edit-receipt.mjs — 批级回执文案**单源**(两个具名构造器各领各的)。
3
+ *
4
+ * 契约 = `docs/core/design/EDIT.md` §2「匹配与应用」(回执按调用序、报真实条目/文件数);骨架单源 =
5
+ * `docs/core/design/EDIT-HELPERS.md` §4「批量帧」(回执由 editEntryFailureLine/editBatchSummary 统一构造)。
6
+ *
7
+ * 两个构造器:
8
+ * - 逐条 / 逐档失败行 ← `editEntryFailureLine(label, reason)`——`<定位> — failed: <原因原文>`,
9
+ * `— failed: ` 这一段逐字同形;定位由各工具填自己的天然坐标(`edits[<i>]` ∥ `<path>` / `<path> hunk <n>`),
10
+ * 所以入参是**定位串**而不是下标:两个工具共用同一个字面量,改一处就同时改到另一处。
11
+ * - 汇总行与其 `<K> file(s) written` 计数 ← `editBatchSummary({ tool, applied, total, unit, filesWritten })`。
12
+ *
13
+ * **末段存废由「报单位是不是档」定**(`FILE_UNIT`):`edit` 批面报条目、写档(`K ≤ M` ⇒ 末段带信息);
14
+ * `apply_patch` 报档、写档(两个数恒相等 ⇒ 末段只把同一个数印两遍,省)。第三个写入工具接入时
15
+ * 自己回答「我的单位是不是档」,不照抄一段多余的话。
16
+ *
17
+ * 为什么住在自己这一档而不进 `thincoder-core/tools/edit-diff.mjs`:后者已贴近 500 行硬线,
18
+ * 本批为它零增长。
19
+ */
20
+
21
+ /** 报单位 = 档时的单位词——末段 ` — <K> file(s) written` 的存在与否由 `unit` 与它是否相等决定。 */
22
+ export const FILE_UNIT = "file(s)"
23
+
24
+ /**
25
+ * 失败行(逐条 ∥ 逐档):`<定位> — failed: <原因原文>`。
26
+ * `reason` = 抛出的错误文本逐字(可以跨多行——不提炼、不改写)。
27
+ */
28
+ export const editEntryFailureLine = (label, reason) => `${label} — failed: ${reason}`
29
+
30
+ /**
31
+ * 末行汇总:`<tool>: <k>/<M> <unit> applied, <M−k> failed`,`unit` ≠ 档时再接 ` — <K> file(s) written`;
32
+ * `filesWritten` 非空(`K ≥ 1`)时后接 `: ` + 路径清单(调用方已按各自的序排好、以 `, ` 分隔)。
33
+ */
34
+ export function editBatchSummary({ tool, applied, total, unit, filesWritten = [] }) {
35
+ const head = `${tool}: ${applied}/${total} ${unit} applied, ${total - applied} failed`
36
+ const tail = unit === FILE_UNIT ? "" : ` — ${filesWritten.length} file(s) written`
37
+ const list = filesWritten.length >= 1 ? `: ${filesWritten.join(", ")}` : ""
38
+ return head + tail + list
39
+ }
package/tools/execute.mjs CHANGED
@@ -11,7 +11,7 @@
11
11
  * process is killed like bash).
12
12
  *
13
13
  * The child runs PURE node ESM — no helpers are injected (exec-prelude.mjs
14
- * retired 2026-09-03, TOOLS.md §12: preloaded readFile/writeFile/glob/grep/log
14
+ * retired 2026-09-03: preloaded readFile/writeFile/glob/grep/log
15
15
  * helpers made execute look like a file tool, bypassing the dedicated
16
16
  * read/ls/glob/grep/write/edit tools). Scripts that need fs/path import the
17
17
  * node: modules themselves — same boundary as bash, no fake sandbox.
@@ -26,9 +26,11 @@
26
26
  */
27
27
  import { spawn } from "node:child_process"
28
28
  import { resolve } from "node:path"
29
- import { DESC } from "./shared.mjs"
29
+ import { DESC, LEDGER_PARAM_DESC, PROJECT_PARAM_DESC } from "./shared.mjs"
30
30
  import { killProcessTree } from "./process-tree.mjs"
31
31
  import { nodeChildEnv } from "./node-child.mjs"
32
+ // 过程档标记(TOOLS.md §6.28):失败径同标(错误文本也是行内容),解析基准 = 子进程 cwd `baseDir`。
33
+ import { markProcessDocLines } from "./process-doc-mark.mjs"
32
34
 
33
35
  const MAX_SCRIPT = 50_000
34
36
  const MAX_OUTPUT = 50_000
@@ -197,6 +199,9 @@ export const executeTool = {
197
199
  maximum: 600000,
198
200
  description: `Timeout in milliseconds (default ${DEFAULT_TIMEOUT}, max 600000)`,
199
201
  },
202
+ ledger: { type: "string", description: LEDGER_PARAM_DESC },
203
+ // 项目声明面(决策 40):`workdir` 缺位时才被读(定位参数优先);纯声明,不改执行目录。
204
+ project: { type: "string", description: PROJECT_PARAM_DESC },
200
205
  },
201
206
  required: [],
202
207
  },
@@ -231,8 +236,9 @@ export const executeTool = {
231
236
  }
232
237
 
233
238
  const { text, ok } = await runNode(childArgs, baseDir, timeoutMs, ctx.signal)
234
- // Only filter successful output — never swallow an error report behind a filter.
235
- if (!ok) return text
236
- return args.filter ? applyFilter(text, args.filter) : text
239
+ // §6.28 单一出口:`filter` 只滤成功输出(原口径),打标接在它的后面;解析基准 = `baseDir`
240
+ // (= 子进程 cwd),不是 `ctx.cwd`——`workdir` 在场时只有按子进程 cwd 才解得对上。
241
+ const body = ok && args.filter ? applyFilter(text, args.filter) : text
242
+ return markProcessDocLines(body, baseDir)
237
243
  },
238
244
  }
package/tools/file.mjs CHANGED
@@ -11,12 +11,14 @@ import {
11
11
  joinWithEol,
12
12
  majorityEol,
13
13
  FFFD_WARNING,
14
+ LEDGER_PARAM_DESC,
15
+ PROJECT_PARAM_DESC,
14
16
  } from "./shared.mjs";
15
17
  import { applyEditBatch } from "./edit-batch.mjs";
16
18
  import { runSingleEdit } from "./edit-diff.mjs";
17
19
  // 单一写路径点(编辑器编辑径注入缝——CORE-UNIFICATION §2.13.5):本档三个写点全走它,
18
20
  // 记账面同源住该档(下面只做再导出——保既有 import 面稳定)。
19
- import { writeThroughPath, clearDirty, clearLastWrite, lastWriteOf, isDirty } from "./write-path.mjs";
21
+ import { writeThroughPath, clearDirty, clearLastWrite, lineAnchorVerdict, lineAnchorRefusal } from "./write-path.mjs";
20
22
  import { specForModel } from "../config.mjs";
21
23
  import { createHash } from "node:crypto";
22
24
  import { mkdir, readFile, stat } from "node:fs/promises";
@@ -192,6 +194,9 @@ export const writeTool = {
192
194
  properties: {
193
195
  path: { type: "string", description: "File path (relative to cwd or absolute)" },
194
196
  content: { type: "string", description: "Full content to write" },
197
+ ledger: { type: "string", description: LEDGER_PARAM_DESC },
198
+ // 工作区根窄口(设计档 §2.3.1):目标取不到项目根时才被读;目标有根时以路径为准(定位参数优先)。
199
+ project: { type: "string", description: PROJECT_PARAM_DESC },
195
200
  },
196
201
  required: ["path", "content"],
197
202
  },
@@ -208,7 +213,7 @@ export const writeTool = {
208
213
  const eol = prev != null ? detectFileEol(prev) : majorityEol(dirname(abs))
209
214
  const content = eol === "\r\n" ? normalizeEOL(args.content).replace(/\n/g, "\r\n") : args.content
210
215
  // 单一写路径点:默认 = writeFile + 记账;端侧注入 ⇒ 编辑器径(§2.13.5)。
211
- await writeThroughPath(abs, content, { op: "write", record: { type: "write", startLine: 1, shift: 0 } }) // 全文重写——全文件受影响
216
+ await writeThroughPath(abs, content, { op: "write", agent: ctx.agent, record: { type: "write", startLine: 1, shift: 0 } }) // 全文重写——全文件受影响
212
217
  const diff = await gitDiffOne(ctx.cwd, abs)
213
218
  return `Wrote ${args.content.length} chars to ${args.path}${diff ? "\n" + diff : ""}${await autoSyntaxCheck(abs)}`
214
219
  },
@@ -224,14 +229,14 @@ export const editTool = {
224
229
  properties: {
225
230
  path: { type: "string", description: "File path — single form: required; with the edits array: optional top-level default for entries without their own path" },
226
231
  old_string: { type: "string", description: "Exact text to replace (tolerant matching: exact → whitespace-only variant → fuzzy match at ≥90% line equality after whitespace/indent/quote normalization). Mutually exclusive with line/startLine/endLine" },
227
- new_string: { type: "string", description: "Replacement text — content-based edits require it (empty is an explicit error); with line-based targeting (line/startLine/endLine) give it to replace the line/range, or OMIT it to delete (an explicit empty string is an error — omission is the delete signal)" },
228
- line: { type: "integer", description: "1-based line number — replace that single line with new_string, or OMIT new_string to DELETE the line; no old_string needed (mutually exclusive with old_string and startLine/endLine)" },
229
- startLine: { type: "integer", description: "1-based first line of the range to replace with new_string (inclusive — requires endLine; mutually exclusive with old_string); OMIT new_string to DELETE the range" },
230
- endLine: { type: "integer", description: "1-based last line of the range to replace with new_string (inclusive — requires startLine; mutually exclusive with old_string); OMIT new_string to DELETE the range" },
232
+ new_string: { type: "string", description: "Replacement text — content-based edits require it (an empty string is an explicit error there: with replace_all it would delete every match); with line-based targeting (line/startLine/endLine) give it to replace the line/range, or OMIT it — an empty string is the same delete, not an error" },
233
+ line: { type: "integer", description: "1-based line number — replace that single line with new_string, or OMIT new_string (an empty string deletes too) to DELETE the line; no old_string needed (mutually exclusive with old_string and startLine/endLine)" },
234
+ startLine: { type: "integer", description: "1-based first line of the range to replace with new_string (inclusive — requires endLine; mutually exclusive with old_string); OMIT new_string (an empty string deletes too) to DELETE the range" },
235
+ endLine: { type: "integer", description: "1-based last line of the range to replace with new_string (inclusive — requires startLine; mutually exclusive with old_string); OMIT new_string (an empty string deletes too) to DELETE the range" },
231
236
  replace_all: { type: "boolean", description: "Replace all occurrences (default false)" },
232
237
  edits: {
233
238
  type: "array",
234
- description: "Batch form — multiple edits in ONE call, atomic (any failure writes nothing; same-file entries apply serially, each based on the previous result). Use it for multiple changes to the same file AND for independent changes across multiple files — prefer one batched call over N single edits. A top-level path is allowed — it defaults entries without their own path (entry paths win). Mutually exclusive with top-level old_string/new_string/line/startLine/endLine — provide each change's targeting (old_string, or line / startLine+endLine) inside its edits entry; new_string replaces when given, and line-targeted entries may omit it to DELETE the line/range.",
239
+ description: "Batch form — multiple edits in ONE call, each entry reported as its own block: an entry that fails is named and the rest still apply (a file whose final content is rejected writes nothing and all its entries fail; a file already written is never rolled back). Line-number entries apply first, in descending startLine order, and their ranges must not overlap — an overlapping pair fails on both sides; content entries then apply in array order. Use it for multiple changes to the same file AND for independent changes across multiple files — prefer one batched call over N single edits. A top-level path is allowed — it defaults entries without their own path (entry paths win). Mutually exclusive with top-level old_string/new_string/line/startLine/endLine — provide each change's targeting (old_string, or line / startLine+endLine) inside its edits entry; new_string replaces when given, and line-targeted entries may omit it (or pass an empty string — same delete) to DELETE the line/range, while content-targeted entries need a non-empty new_string.",
235
240
  items: {
236
241
  type: "object",
237
242
  properties: {
@@ -245,6 +250,8 @@ export const editTool = {
245
250
  },
246
251
  },
247
252
  },
253
+ ledger: { type: "string", description: LEDGER_PARAM_DESC },
254
+ project: { type: "string", description: PROJECT_PARAM_DESC },
248
255
  },
249
256
  required: [],
250
257
  },
@@ -268,8 +275,8 @@ export const editTool = {
268
275
  // (应用逻辑在 edit-batch.mjs——2026-09-01 拆出,500 行硬限,先例 git-ext.mjs)
269
276
  if (args.edits) return applyEditBatch(args, ctx)
270
277
 
271
- // 单文件(现状路径)——执行体整段迁出至 edit-diff.mjs(EDIT.md §6——
272
- // 行级 LCS 判定:零重叠→替换即删 / 一般 diff→LCS / 空 new→显式报错)
278
+ // 单文件(现状路径)——执行体整段迁出至 edit-diff.mjs(判定序:零重叠→替换即删 /
279
+ // 一般 diff→行级 LCS / 空 new→显式报错)
273
280
  return runSingleEdit(args, ctx)
274
281
  },
275
282
  }
@@ -286,6 +293,8 @@ export const insertAfterTool = {
286
293
  after_line: { type: "number", description: "Line number to insert after (1-based). Takes priority over after_regex." },
287
294
  after_regex: { type: "string", description: "JavaScript regex to find the line to insert after (must match exactly one line)" },
288
295
  content: { type: "string", description: "Text to insert (with leading newline if you need a blank line)" },
296
+ ledger: { type: "string", description: LEDGER_PARAM_DESC },
297
+ project: { type: "string", description: PROJECT_PARAM_DESC },
289
298
  },
290
299
  required: ["path", "content"],
291
300
  },
@@ -296,31 +305,16 @@ export const insertAfterTool = {
296
305
  // Read-before-insert guard: after_line anchors are line numbers, and any
297
306
  // write since the last read made them stale. Refuse instead of silently
298
307
  // inserting at a drifted position (the failure mode that corrupted test
299
- // structure repeatedly). after_regex callers get the same gate — a stale
300
- // target line is just as wrong, and the rule is simpler to reason about.
301
- // 2026-08-31 工具顺手度(用户批准):判定精确化——本 session 写入工具记录受影响区
302
- // (lastWrite),after_line 在未受影响区(<= startLine)→ 行号未漂移 → 允许
303
- // (消掉"我写的文件被当外部修改"的摩擦);受影响区内/write 全文重写 → 拒绝。
304
- const lw = lastWriteOf(abs)
305
- if (lw && args.after_line != null) {
306
- if (lw.type === "write") {
307
- throw new Error(
308
- `${args.path} 刚被 write 全文重写(was modified since your last read)——任何行号都可能漂移,必须重 read。`
309
- )
310
- }
311
- if (args.after_line > lw.startLine) {
312
- throw new Error(
313
- `${args.path} 的 after_line ${args.after_line} 在上次写入(L${lw.startLine})之后——` +
314
- `行号已漂移 ${lw.shift >= 0 ? "+" : ""}${lw.shift},请用新行号或先 read。`
315
- )
316
- }
317
- // after_line <= startLine → 行号未漂移 → 允许
318
- } else if (isDirty(abs)) {
319
- throw new Error(
320
- `${args.path} was modified since your last read — line numbers may be stale.\n` +
321
- `Read the file again (read tool) to refresh line numbers, then retry insert_after.`
322
- )
323
- }
308
+ // structure repeatedly).
309
+ // 2026-11-02:判据与拒文单源 = tools/write-path.mjs 的 lineAnchorVerdict /
310
+ // lineAnchorRefusal(与 edit 行号形同一句、同一六行表——INSERT-AFTER.md §3)。
311
+ // 本工具的边界 = `after_line <= startLine`(插入不读写目标行,比 edit 松一格——
312
+ // 边界按记账类型分,已在判据内);after_regex 没有模型给的行号(定位在工具内按当前
313
+ // 盘面做)⇒ 只判到记账态那一层(dirty 面无快照 ⇒ 第 6 行),与改前同判。
314
+ const afterLine = Number.isInteger(args.after_line) ? args.after_line : null
315
+ const hit = lineAnchorVerdict(abs, afterLine, afterLine)
316
+ if (hit) throw new Error(lineAnchorRefusal(abs, afterLine, afterLine))
317
+
324
318
  const raw = await readFile(abs, "utf8") // original bytes — EOL detection needs the file's real line endings
325
319
  const text = normalizeEOL(raw)
326
320
  const lines = text.split("\n")
@@ -358,6 +352,7 @@ export const insertAfterTool = {
358
352
  const updated = joinWithEol(lines, raw)
359
353
  await writeThroughPath(abs, updated, {
360
354
  op: "write",
355
+ agent: ctx.agent,
361
356
  record: { type: "insert", startLine: targetLine, shift: normalizeEOL(args.content).split("\n").length },
362
357
  })
363
358
  const diff = await gitDiffOne(ctx.cwd, abs)
@@ -385,6 +380,8 @@ export const hashlineEditTool = {
385
380
  path: { type: "string", description: "File path" },
386
381
  old_hashes: { type: "array", items: { type: "string" }, description: "SHA256 hashes (12 chars) of the lines to replace. Read the file with hashes=true first to obtain these hashes. Single line: pass 1 hash; multiple lines: pass the exact sequence of hashes." },
387
382
  new_content: { type: "string", description: "Replacement text (can span multiple lines)" },
383
+ ledger: { type: "string", description: LEDGER_PARAM_DESC },
384
+ project: { type: "string", description: PROJECT_PARAM_DESC },
388
385
  },
389
386
  required: ["path", "old_hashes", "new_content"],
390
387
  },
@@ -453,6 +450,7 @@ export const hashlineEditTool = {
453
450
  const updated = joinWithEol(lines, raw)
454
451
  await writeThroughPath(abs, updated, {
455
452
  op: "write",
453
+ agent: ctx.agent,
456
454
  record: { type: "edit", startLine: pos + 1, shift: newLines.length - target.length },
457
455
  })
458
456
  const diff = await gitDiffOne(ctx.cwd, abs)
package/tools/git.mjs CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  DESC,
3
3
  truncate,
4
4
  runGit,
5
- gitFailureMessage
5
+ gitFailureMessage,
6
6
  } from "./shared.mjs";
7
7
  import { spawnGit } from "./git-run.mjs";
8
8
  import { resolve } from "node:path";
@@ -90,6 +90,29 @@ export const gitTool = {
90
90
  required: ["action"],
91
91
  },
92
92
  readonly: false,
93
+ /**
94
+ * 动作级只读分类(决策 37 · 2026-11-03 笔-账绑定批——**本钩子是单源**)。
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「只读名单本体」)。
99
+ * 名单与 `thincoder-vscode/src/tools/index.mjs` 原端装饰体逐条同形(该覆写随本钩子同笔删除):
100
+ * 六项平铺 + 六条子动作分支。`checkpoint` 的 `list` ∥ `cat` 判只读——`checkpoint list` 有 F6 清理副作用
101
+ * (`lazyClearIfCommitted` 可能删除整个 checkpoint 目录),但清的是 commit 后已失去意义的过期快照 ⇒
102
+ * 保留只读分类免审批(`docs/core/design/CHECKPOINT.md` F6/D3 设计意图)。
103
+ * 缺此钩子的面回落到核名面谓词(无 `git` 分支 ⇒ false ⇒ 写型 ⇒ 走审批),fail-closed,不出洞。
104
+ */
105
+ isReadonlyAction(args) {
106
+ if (!args || typeof args.action !== "string") return false
107
+ if (["diff", "status", "log", "show", "ls-remote", "blame"].includes(args.action)) return true
108
+ if (args.action === "checkpoint") return ["list", "cat"].includes(args.checkpointAction)
109
+ if (args.action === "tag") return args.tagAction === "list"
110
+ if (args.action === "branch") return args.branchAction === "list"
111
+ if (args.action === "stash") return args.stashAction === "list"
112
+ if (args.action === "remote") return args.remoteAction === "list"
113
+ if (args.action === "worktree") return args.worktreeAction === "list"
114
+ return false // add/rm/commit/push/fetch/pull/reset/revert/merge/cherry-pick/checkout/restore + tag/branch/stash 写操作
115
+ },
93
116
  async execute(args, ctx) {
94
117
  // workdir: run git in a subdirectory (monorepo / multi-repo). Shadow ctx.cwd so
95
118
  // every action + snapshotBefore + checkpoint resolves against the workdir.
@@ -204,7 +227,25 @@ const gitActionCore = {
204
227
  if (args.path !== undefined && args.path !== null) {
205
228
  const trimmed = args.path.trim()
206
229
  if (!trimmed) return "Error: commit path is empty/whitespace — give at least one file path (space-separated)"
207
- 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])
208
249
  } else {
209
250
  const add = await runGitStrict(ctx.cwd, ["add", "-A"])
210
251
  if (!add.ok) return truncate(`git add failed: ${add.err || add.out || "(no output)"}`)