@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/token-window.mjs CHANGED
@@ -2,15 +2,31 @@
2
2
  * token-window.mjs — token 计量 / 窗口 / 切割族(自 `context.mjs` **逐字迁出**)+ 上下文用量单源
3
3
  * (CONTEXT-COMPACTION.md §6.16.3 / §6.16.4 / §6.16.8 · context-tool 批 2026-09-21)。
4
4
  * 迁出三族(语义零改——原档越限在即,本批按 §6.16.8 拆出):① 计量面(IMAGE_TOKEN_ESTIMATE + `estimateTokens`);
5
- * ② 尾族(KEEP_HEAD 头注 + TAIL_BUDGET_FRACTION / SUMMARY_TOKEN_ESTIMATE / TAIL_FLOOR_MESSAGES + `keepTailSize` + `tailBudgetTokens`);
5
+ * ② 尾族(KEEP_HEAD 头注 + SUMMARY_TOKEN_ESTIMATE / TAIL_FLOOR_MESSAGES + `keepTailSize` + `tailBudgetTokens`);
6
6
  * ③ 切分与配对修复族(`splitHistory` + `repairedTailStart` + `tightenTailByBudget`)。
7
- * 新增族:`contextUsage`(与 `compressIfNeeded` 的 token 判定**同一函数**)· `historyReading` / `historyPercent`(状态行
8
- * 百分比——与 CLI ∥ VSC **同源**:一个实现点,端侧零自算式,消费面全是本档的投影)·
9
- * `collectStaleToolOutputs`(陈旧工具输出合格集)+ 门槛常量 `PRUNE_MIN_TOKENS`(**与合格集同住本档** ⇒ 消费方单向取用、零回指)。
10
- * 依赖面 = `provider/rate.mjs`(`estimateText` / `ESTIMATOR_VERSION`)+ `config.mjs`(`providerSpec` / `resolveCompactThreshold`)——**零 import 环**。
7
+ * 新增族:`faceEstimate`(非对话面六项与对话面的**唯一**估算点,§2.5)· `contextUsage`(整量:装配面六段,
8
+ * 与 `compressIfNeeded` 的 token 判定**同一函数**)· `contextReading`(整量读数单点:状态行 ∥ stats ∥ Desktop ∥
9
+ * VSC 四个有 agent 的面全读它)· `historyReading` / `historyPercent`(仅对话那一段的估算,
10
+ * 消费面只剩打开态与无 agent 转口)· `overheadSegments`(非对话面六项的分段读法,越线报文两处共用)·
11
+ * `collectStaleToolOutputs`(陈旧工具输出合格集)+ 门槛常量 `PRUNE_MIN_TOKENS`(**与合格集同住本档** ⇒ 消费方单向取用、零回指)·
12
+ * `rebaseMeasured`(结构编辑后的实测基线重定,§3.1)。
13
+ * 窗口面(2026-11-14 · tiny 档上限批;2026-11-21 · 本批):本档一切窗口读数取**有效窗口** `effectiveWindow`
14
+ * (`window-policy.mjs` §2.1),不再直读 `providerSpec().context`——有效窗口恒等于模型窗口,档位不是入参
15
+ * (本档的窗口消费入口 `keepTailSize` ∥ `tailBudgetTokens` ∥ `historyReading` ∥ `historyPercent` 都只收 provider,
16
+ * `collectStaleToolOutputs` 同形;必填清单的单一出处 = §2.3)。
17
+ * 保留窗面(2026-11-14 · tool-output-retention 批):`splitHistory` 的第四参 `protectFrom` 必填、无缺省——尾起点不晚于
18
+ * 保留窗起点,压缩中段 ∥ prune 合格集 ∥ 尾部预算三面同源受益(`CONTEXT-COMPACTION.md` §1.2);起点由 `agent` 面的
19
+ * `retentionWindowStart` 按消息身份当刻解析,本档只收这个下标(纯函数面不读 agent 状态)。
20
+ * 尾预算面(2026-11-15 · window-reserve-and-baseline 批):`tailBudgetTokens` 由窗口比例改为**可用容量减法链**(§4)——
21
+ * 尾的宽度从压缩线倒推,不取窗口的比例。
22
+ * 依赖面 = `provider/rate.mjs`(`estimateText` / `ESTIMATOR_VERSION`)+ `config.mjs`(有效窗口 ∥
23
+ * 预算族转口)+ `context-push.mjs`(拍平投影与位置换算两向)——`context-push.mjs` 不回头 import 本档,
24
+ * **零 import 环**(压缩摘要不再带固定文本,本档因此不再 import `context-echo.mjs`)。
11
25
  */
12
26
  import { estimateText, ESTIMATOR_VERSION } from "./provider/rate.mjs"
13
- import { providerSpec, resolveCompactThreshold } from "./config.mjs"
27
+ import { effectiveWindow, resolveCompactThreshold, policyBudget } from "./config.mjs"
28
+ // 拍平投影与位置换算(两向同住一档)——本档的读数、切点与基线重定都在拍平视图上算,位置只在结构上取。
29
+ import { flattenHistory, flatIndexOf, positionOf, INJECT_SLOTS } from "./context-push.mjs"
14
30
 
15
31
  const IMAGE_TOKEN_ESTIMATE = 2000 // rough estimate for image content tokens (CLI legacy 256 underestimated real image costs, delaying compaction)
16
32
 
@@ -37,23 +53,60 @@ const KEEP_HEAD = 0 // No dedicated head: earliest messages may be a COMPLETED e
37
53
  // sessions — keeping them verbatim anchored attention on stale work. Everything before the tail is
38
54
  // summarized (the summary itself distinguishes completed vs in-progress work; see SUMMARIZE_PROMPT).
39
55
  // Tail count formula (D4): window-adaptive (~30 msgs per 100K — old fixed 10 too thin on 1M), capped
40
- // at 40% of history; §6.4④ D-T1/D-T2 make the count only a CANDIDATE — a token budget (TAIL_BUDGET_FRACTION
41
- // × window − SUMMARY_TOKEN_ESTIMATE ≈1K, §6.9) tightens it over pair-safe boundaries when compaction runs,
42
- // never below TAIL_FLOOR_MESSAGES; ordinary sessions never reach it (D-T4: the trigger ratio lives in `config.mjs` — untouched here).
43
- const TAIL_BUDGET_FRACTION = 0.15
44
- export const SUMMARY_TOKEN_ESTIMATE = 1000 // §6.9: summary output target ~1K tokens — reserved from the 15%;§6.17 可达性门的 `note` 项同取本常量
56
+ // at 40% of history; §6.4④ D-T1/D-T2 make the count only a CANDIDATE — the token budget
57
+ // (`tailBudgetTokens`, §4) tightens it over pair-safe boundaries when compaction runs, never below
58
+ // TAIL_FLOOR_MESSAGES; ordinary sessions never reach it (D-T4: the trigger line is §2.2's).
59
+ export const SUMMARY_TOKEN_ESTIMATE = 1000 // §6.9: summary output target ~1K tokens —— 压缩摘要的预留额同取本常量
45
60
  const TAIL_FLOOR_MESSAGES = 10 // §6.4④ D-T2: the tail keeps ≥10 verbatim messages — floor beats budget
61
+
62
+ /** 压缩摘要的估算(§4 减法链的末项,也是可达性门的 `compactionSummary` 项):只剩摘要正文这一项,取值即
63
+ * `SUMMARY_TOKEN_ESTIMATE`(§6.9 的 ~1K 目标)。两个量说的是两件事——摘要写多长 · 压缩摘要在请求面上占多少,
64
+ * 只是当前取值重合(设计档 §6.1「压缩摘要的文本 = 摘要正文本身」:成功路径的压缩摘要不带任何固定文本)。 */
65
+ export const COMPACTION_SUMMARY_TOKEN_ESTIMATE = SUMMARY_TOKEN_ESTIMATE
66
+
67
+ /** 必填数值参数(§2.3 缺参即拒):无缺省,非法值在入口拒绝并点名参数。
68
+ * `fixedOverhead` 缺省等于把「这份 run 的固定开销」静默定成 0,尾会按一个装不下的量去切;
69
+ * `ratio` 缺省等于把校准后的阈值和未校准的估算放进同一次减法。 */
70
+ function assertTailArgs(fnName, fixedOverhead, ratio) {
71
+ if (!Number.isFinite(fixedOverhead) || fixedOverhead < 0) {
72
+ throw new Error(`${fnName}: \`fixedOverhead\` is required (the non-conversation face minus the compaction-summary slot, i.e. \`fixed − compactionSummary\`, no default) — got ${JSON.stringify(fixedOverhead)}`)
73
+ }
74
+ if (!Number.isFinite(ratio) || ratio <= 0) {
75
+ throw new Error(`${fnName}: \`ratio\` is required (the calibration ratio from tokenRatioOf, no default) — got ${JSON.stringify(ratio)}`)
76
+ }
77
+ }
78
+
46
79
  export function keepTailSize(provider, historyLen) {
47
- // provider is guaranteed at every call site (runAgent always builds one); providerSpec
48
- // degrades to DEFAULT_SPEC (128K) only if provider is somehow absent — acceptable
80
+ // provider is guaranteed at every call site (runAgent always builds one); the window below
81
+ // degrades to DEFAULT_SPEC (256K) only if provider is somehow absent — acceptable
49
82
  // because the 40% history cap still bounds the tail. providers[].context override
50
83
  // (K units) is honored here (PROVIDER.md §6.15 T-C2: tail formula follows the window).
51
- const ctxWindow = providerSpec(provider).context
84
+ // 窗口 = **有效窗口**(§2.1/§4)——它恒等于模型窗口,档位不参与(tiny 不再压窗口)。
85
+ // 它是**条数上限**,不是预算:一条消息的体量跨三个数量级,条数推不出容量(§4)。
86
+ const ctxWindow = effectiveWindow(provider)
52
87
  return Math.min(Math.max(10, Math.floor((ctxWindow / 100_000) * 30)), Math.floor(historyLen * 0.4))
53
88
  }
54
- // §6.4④ D-T1 tail token budget: window×15% − summary ~1K — the compressed history segment (summary + placeholder + tail) lands ≈ 15% (B 口径 §6.4④).
55
- export function tailBudgetTokens(provider) {
56
- return Math.max(0, Math.floor(providerSpec(provider).context * TAIL_BUDGET_FRACTION) - SUMMARY_TOKEN_ESTIMATE)
89
+
90
+ /**
91
+ * 尾预算(§4)——可用容量倒推,不由窗口比例决定:
92
+ *
93
+ * ```text
94
+ * tailBudgetTokens(provider, fixedOverhead, ratio)
95
+ * = max(0, floor(threshold / ratio) − fixedOverhead − SUMMARY_TOKEN_ESTIMATE)
96
+ * ```
97
+ *
98
+ * `threshold` 取 §2.2 的压缩线(有效窗口上现推),`fixedOverhead` = 非对话面六项扣掉压缩摘要格(`fixed − compactionSummary`),
99
+ * `ratio` = 校准比(`tokenRatioOf`)。减掉的这一项就是压缩摘要:成功路径的它不带固定文本(§6.1),
100
+ * 只剩摘要正文一项,取值即 `SUMMARY_TOKEN_ESTIMATE`;`COMPACTION_SUMMARY_TOKEN_ESTIMATE` 仍供 `post` 与 `fixedFloor` 用(§2.5)。
101
+ * 减法链把「压完之后落在 `threshold` 以下」写成构造而不是事后检查:压后的量是
102
+ * `(tail + 压缩摘要 + 固定开销) × ratio`,尾按上式取,它就落在 `threshold` 以内。
103
+ * 乘除 `ratio` 是必需的:`threshold` 是校准后的量,尾的估算要换到同一把尺上才可比。
104
+ * `fixedOverhead` ∥ `ratio` 都必填无缺省(§2.3)。
105
+ */
106
+ export function tailBudgetTokens(provider, fixedOverhead, ratio) {
107
+ assertTailArgs("tailBudgetTokens", fixedOverhead, ratio)
108
+ const threshold = policyBudget(provider).threshold
109
+ return Math.max(0, Math.floor(threshold / ratio) - fixedOverhead - SUMMARY_TOKEN_ESTIMATE)
57
110
  }
58
111
 
59
112
  /**
@@ -63,8 +116,16 @@ export function tailBudgetTokens(provider) {
63
116
  * `budgetTokens` (optional, §6.4④ D-T1): when the candidate's estimate exceeds it, the boundary moves
64
117
  * forward until the tail fits — never below the D-T2 floor (10 msgs, or the candidate itself when
65
118
  * the 40% cap made it < 10 — short history).
119
+ * `protectFrom` (REQUIRED, no default — `CONTEXT-COMPACTION.md` §1.2 保留窗与保护尾): an index the tail
120
+ * must never start after, so the tool-process retention window always sits inside the protected tail.
121
+ * The relation is structural, not arithmetic — it holds for every window size and call-group count.
122
+ * No retention window ⇒ the caller passes `history.length` (== no tightening). A default here would
123
+ * decide the caller's protection amount for it, the very silent trade-off §1.2 removes.
66
124
  */
67
- export function splitHistory(history, keepTail, budgetTokens = null) {
125
+ export function splitHistory(history, keepTail, budgetTokens = null, protectFrom) {
126
+ if (!Number.isInteger(protectFrom) || protectFrom < 0) {
127
+ throw new Error(`splitHistory: \`protectFrom\` is required (a history index, no default) — pass the retention-window start, or history.length when there is no retention window; got ${JSON.stringify(protectFrom)}`)
128
+ }
68
129
  if (history.length <= KEEP_HEAD + keepTail + 1) return null
69
130
  let headEnd = KEEP_HEAD
70
131
  // head must not end with dangling tool_calls: when assistant declares tool_calls, all its tool results must stay in head.
@@ -80,6 +141,13 @@ export function splitHistory(history, keepTail, budgetTokens = null) {
80
141
  const floor = repairedTailStart(history, headEnd, history.length - TAIL_FLOOR_MESSAGES)
81
142
  if (floor > candidate) tailStart = tightenTailByBudget(history, candidate, floor, budgetTokens)
82
143
  }
144
+ // 保留窗结构保护(§1.2):切点一处收紧,压缩中段、prune 合格集与尾部预算三面同源受益。
145
+ // 收紧后仍走一遍配对修复:修得对了它会把起点**往前挪**(成组的 assistant 被拉进尾,尾变长),
146
+ // 但遇上孤立的 `tool` 消息(前面找不到 owner)时它会把起点往后跨过去——那是尾变短的方向。
147
+ // 保留窗起点落在这种位置上不可能:折叠按组成对进出,切片里不会有孤立结果(§1.1)。
148
+ tailStart = repairedTailStart(history, headEnd, Math.min(tailStart, protectFrom))
149
+ // 保护尾吃掉全部中段 ⇒ 无可压(与「历史太短」同一支:全史即保护尾,见 `collectStaleToolOutputs`)
150
+ if (tailStart <= headEnd) return null
83
151
  return { headEnd, tailStart }
84
152
  }
85
153
 
@@ -126,33 +194,160 @@ function tightenTailByBudget(history, start, floorStart, budgetTokens) {
126
194
  }
127
195
 
128
196
  /**
129
- * 上下文用量单源(§6.16.4「取自哪里」)——与 `compressIfNeeded` 的 token 判定**同一函数**:实测优先 =
130
- * `_lastPromptTokens + 增量(history.slice(_usageAtLen))`;无实测 = `estimateTokens(history) + system + tools`(固定开销面经 extras 随带)。
131
- * `threshold` = 该回合检查所用值(`agent._ctxBasis.threshold`——核 `agent.mjs` / VSC `checkAndCompact` 各一处暂存);缺省回退 `resolveCompactThreshold`(退化面①)。
132
- * `window` = `providerSpec(agent.provider).context`。
133
- * @returns {{basis:"measured"|"estimated", total, history, system, tools, overhead, threshold, window}}
197
+ * 基线位置 → 拍平下标(实测支的后缀起点)。位置不成立(结构编辑漏了重定 §3.1)⇒ 取线尾,
198
+ * 与「基线为 null」同形:宁可少算后缀,也不把已计进真值的那一段再加一遍。
199
+ */
200
+ function usageBaselineIndex(agent, flat) {
201
+ const pos = agent?._usageAt
202
+ if (!pos || typeof pos !== "object") return flat.length
203
+ try {
204
+ return flatIndexOf(agent.history, pos)
205
+ } catch {
206
+ return flat.length
207
+ }
208
+ }
209
+
210
+ /**
211
+ * 真值那一刻的非对话面估算(`_usageFixedBase`)的读侧唯一一处。
212
+ * 它与 `_lastPromptTokens` 同一个写点(`agent/turn-loop.mjs` 写真值的那一支)、同一批置 null 点;
213
+ * measured 支下缺它只可能是那个写点漏了,此时抛出并点名——不拿 0 顶上:拿 0 会把整个非对话面
214
+ * 再加一遍,正是 §2.5 要消灭的重复计数。
134
215
  */
135
- export function contextUsage(agent, extras = {}) {
136
- const history = Array.isArray(agent?.history) ? agent.history : []
216
+ function usageFixedBaseOf(agent) {
217
+ const base = agent?._usageFixedBase
218
+ if (!Number.isFinite(base)) {
219
+ throw new Error("contextUsage: `_usageFixedBase` is missing while `_lastPromptTokens` is set — both are written at the same point (agent/turn-loop.mjs), and every null point clears both")
220
+ }
221
+ return base
222
+ }
223
+
224
+ /**
225
+ * 装配面六段里非对话面六项与对话面的**唯一**估算点(`CONTEXT-COMPACTION.md` §2.5)——
226
+ * 读数(`contextUsage`)与真值基线(`_usageFixedBase`)都从它取,不各自累加:
227
+ *
228
+ * ```text
229
+ * system = extras.systemPrompt 的估算 retained = agent._retained 各条目 message 的估算
230
+ * tools = extras.tools 的估算 inject = agent._inject 十格全部内容(compactionSummary 在它里面)
231
+ * pending = agent._pendingInject 的估算 sessionHead = agent._sessionHead 那一个字符串(未写过记 0)
232
+ * fixed = system + tools + retained + inject + sessionHead + pending
233
+ * history = 拍平线(对话面)的估算
234
+ * ```
235
+ *
236
+ * 五段(`retained` ∥ `inject` ∥ `sessionHead` ∥ `pending` ∥ `history`)由本函数自己从 agent 读,不经 extras;`extras` 必填、
237
+ * 无缺省——忘传即少算系统提示词与工具声明两段,读数偏低而看起来完全正常(与 §2.3 同一条纪律)。
238
+ * `compactionSummary` 是 `inject` 里压缩摘要那一格:压缩链先减掉它、再按 `COMPACTION_SUMMARY_TOKEN_ESTIMATE`
239
+ * 加回预留额,同一份不算两遍(§4 ∥ §5)。
240
+ */
241
+ export function faceEstimate(agent, extras) {
242
+ if (extras === undefined) {
243
+ throw new Error("faceEstimate: `extras` is required (no default) — pass agent?._ctxBasis?.overhead ?? {}")
244
+ }
137
245
  const system = extras.systemPrompt ? estimateText(extras.systemPrompt) : 0
138
246
  const tools = extras.tools ? estimateText(JSON.stringify(extras.tools)) : 0
139
- const overhead = system + tools
140
- const historyTokens = estimateTokens(history)
141
- const measured = agent?._lastPromptTokens != null
247
+ const retained = estimateTokens(
248
+ (Array.isArray(agent?._retained) ? agent._retained : []).map((e) => e?.message).filter(Boolean),
249
+ )
250
+ const slots = Array.isArray(agent?._inject) ? agent._inject : []
251
+ const inject = estimateTokens(slots.filter(Boolean))
252
+ const summarySlot = slots[INJECT_SLOTS.indexOf("compaction-summary")]
253
+ const compactionSummary = summarySlot ? estimateTokens([summarySlot]) : 0
254
+ const pending = estimateTokens((Array.isArray(agent?._pendingInject) ? agent._pendingInject : []).filter(Boolean))
255
+ // 会话头块(§2.5):不在 `_inject` 也不在 `_pendingInject`,却每条请求都在⇒不单算就是
256
+ // 「请求里在、读数里不在」(压缩判定偏晚、越窗守卫少算、状态行少报)。
257
+ const sessionHead = typeof agent?._sessionHead === "string" && agent._sessionHead ? estimateText(agent._sessionHead) : 0
258
+ const history = estimateTokens(flattenHistory(Array.isArray(agent?.history) ? agent.history : []))
259
+ return {
260
+ system,
261
+ tools,
262
+ retained,
263
+ inject,
264
+ compactionSummary,
265
+ pending,
266
+ sessionHead,
267
+ fixed: system + tools + retained + inject + sessionHead + pending,
268
+ history,
269
+ }
270
+ }
271
+
272
+ /**
273
+ * 非对话面六项的分段读法(`CONTEXT-COMPACTION.md` §2.5 的次序):越线报文两处共用——发送前守卫的 typed error
274
+ * (`provider/errors.mjs`)与 `context compact` 的 no-op 回执(`agent-tools/context.mjs`)。
275
+ * 六项的名字就是各自那一格的名字;`fixed` 是它们的和,不是第七段。字段缺了不补 0——报文里会印出
276
+ * `undefined`,比一个看起来正常的 0 更容易被发现。
277
+ */
278
+ export function overheadSegments(usage) {
279
+ return [
280
+ ["systemPrompt", usage?.system],
281
+ ["tools", usage?.tools],
282
+ ["_retained", usage?.retained],
283
+ ["_inject", usage?.inject],
284
+ ["_sessionHead", usage?.sessionHead],
285
+ ["_pendingInject", usage?.pending],
286
+ ]
287
+ }
288
+
289
+ /**
290
+ * 上下文用量单源(§2.5「显示与判定同基准」)——与 `compressIfNeeded` 的 token 判定**同一函数**:
291
+ *
292
+ * ```text
293
+ * 实测支 total = _lastPromptTokens
294
+ * + round(estimateTokens(_usageAt 之后的拍平线) × ratio)
295
+ * + round((fixed − _usageFixedBase) × ratio)
296
+ * 估算支 total = round((fixed + history) × ratio)
297
+ * fixedFloor = round(((fixed − compactionSummary) + COMPACTION_SUMMARY_TOKEN_ESTIMATE) × ratio)
298
+ * ```
299
+ *
300
+ * 整量 = 本回合请求的装配面(`faceEstimate` 的六段),与 `assembleRequestMessages` 拼出的那一条同面。
301
+ * 实测支的第二项补对话增量、第三项补非对话增量:压缩摘要落 `_inject` 的 `compaction-summary` 格、待发队进条目、编辑器上下文刷新,
302
+ * 改的都只是非对话面,不补就是读数比真实请求小一个量级;反过来无条件把 `fixed` 加上去,会把已含在真值里
303
+ * 的那一份算第二遍(常驻的压缩摘要接近一倍)。差可正可负。
304
+ * `fixedFloor` = 压掉全部对话后 `total` 的下界:压后非对话面 = `(fixed − compactionSummary) + COMPACTION_SUMMARY_TOKEN_ESTIMATE`,换成估算尺
305
+ * 即上式。§5.1 的 ②⑤⑦ 三道门、§4 的尾预算与 §5 的 `post` 都读这一个测度(定义只在 §2.5)。
306
+ * 压缩摘要按预留额计、不跟量到的 `compactionSummary` 走:那一格在「本会话还没压过」时为空、压过之后非空(重开一个压过的
307
+ * 会话时由槽里的检查点补回),两种状态都要为同一条压缩摘要留出同一份空间。
308
+ * 机读线按轮嵌套:一切计量在拍平视图上算(外层条数是轮数,不是消息数);基线位置是 `{ turn, msg }`。
309
+ * `threshold` = 该回合判定所用值(`agent._ctxBasis.threshold`——核 `agent.mjs` / VSC `checkAndCompact` 各一处暂存);
310
+ * 缺省回退 `resolveCompactThreshold`(退化面①)。
311
+ * `window` = **有效窗口** `effectiveWindow(agent.provider)`(§2.1)——它恒等于模型窗口,
312
+ * 而这个值就是 stats 首行百分比的分母(agent 在场,不靠参数透传)。
313
+ * `overhead` = `system + tools`(`fixed` 的子集,模型与参数预判面读它);压缩链读 `fixed − compactionSummary`,不读它。
314
+ * @returns {{basis:"measured"|"estimated", total, history, system, tools, retained, inject, compactionSummary, sessionHead, pending, fixed, overhead, fixedFloor, threshold, window}}
315
+ */
316
+ export function contextUsage(agent, extras) {
317
+ if (extras === undefined) {
318
+ throw new Error("contextUsage: `extras` is required (no default) — pass agent?._ctxBasis?.overhead ?? {}")
319
+ }
320
+ const face = faceEstimate(agent, extras)
142
321
  // §6.3 / §6.17 估算自校准:估算值乘 `_tokRatio`;`_lastPromptTokens` 是服务端真值,不乘。
143
322
  const ratio = tokenRatioOf(agent) // 取比单源(同下 `historyReading` 的第三参来源)
323
+ const measured = agent?._lastPromptTokens != null
324
+ let total
325
+ if (measured) {
326
+ const flat = flattenHistory(Array.isArray(agent?.history) ? agent.history : [])
327
+ const suffix = estimateTokens(flat.slice(usageBaselineIndex(agent, flat)))
328
+ total = agent._lastPromptTokens
329
+ + Math.round(suffix * ratio)
330
+ + Math.round((face.fixed - usageFixedBaseOf(agent)) * ratio)
331
+ } else {
332
+ total = Math.round((face.fixed + face.history) * ratio)
333
+ }
144
334
  return {
145
335
  basis: measured ? "measured" : "estimated",
146
- total: measured
147
- ? agent._lastPromptTokens + Math.round(estimateTokens(history.slice(agent._usageAtLen ?? history.length)) * ratio)
148
- : Math.round((historyTokens + overhead) * ratio),
149
- history: historyTokens,
150
- system,
151
- tools,
152
- overhead,
336
+ total,
337
+ history: face.history,
338
+ system: face.system,
339
+ tools: face.tools,
340
+ retained: face.retained,
341
+ inject: face.inject,
342
+ compactionSummary: face.compactionSummary,
343
+ pending: face.pending,
344
+ sessionHead: face.sessionHead,
345
+ fixed: face.fixed,
346
+ overhead: face.system + face.tools,
347
+ fixedFloor: Math.round(((face.fixed - face.compactionSummary) + COMPACTION_SUMMARY_TOKEN_ESTIMATE) * ratio),
153
348
  threshold: agent?._ctxBasis?.threshold
154
349
  ?? resolveCompactThreshold(agent?.config?.agent?.compactThreshold, agent?.provider).value,
155
- window: providerSpec(agent?.provider).context,
350
+ window: effectiveWindow(agent?.provider),
156
351
  }
157
352
  }
158
353
 
@@ -221,25 +416,75 @@ function validSample(sample, provider) {
221
416
  }
222
417
 
223
418
  /**
224
- * 核读数(§6.16.4「与状态行 ctx% 的单源关系」)——这个量**只有本函数一个实现点**,五处消费面全是它的投影:
225
- * stats 第 6 行 · 打开态读数 · 桌面 `ev:usage` · VSC `specs.mjs` · CLI 状态行(经 `ctxCacheOf` 缓存)。
226
- * 一点出两值:`tokens` = 校准后的历史估算 `round(estimateTokens(history) × ratio)`、`pct` = 它 ÷ 窗口、
227
- * `window` = `providerSpec(provider).context`——同屏「context X% Yk」必须同尺,两值各自算一次就是两把尺;
228
- * `window` 随读带出,消费面不再二次派生同一个量。
419
+ * 核读数(§6.16.4「与状态行 ctx% 的单源关系」)——**只量对话那一段**的行史估算,`.pct` 的消费面只剩两处(§2.5):
420
+ * 打开态读数(经 `historyPercent`)与无 agent 转口(VSC `specs.mjs` 的 `ctxUsageForHistory`)。
421
+ * 有 agent 的四个面(CLI 状态行 ∥ stats 第 6 行 ∥ Desktop `ev:usage` ∥ VSC 的 agent 面)一律读 `contextReading`——
422
+ * 它才是「整条请求」的量;本函数从此只回答「对话那一段大概多少」,不是状态行的分子。
423
+ * 一次读数出五个值:`tokens` = 校准后的历史估算 `round(estimateTokens(history) × ratio)`;`window` / `limit` /
424
+ * `threshold` = 同一份 `policyBudget` 的三个字段(有效窗口那一边);`pct` = `round(tokens / limit × 100)`——
425
+ * **分母 = `limit`**(用户实际可填的量):`window` 含输出预留,拿它当分母时 100% 永远到不了。
426
+ * `threshold` 随读带出,状态行的告警判据读它(`tokens >= threshold`),端侧不各发明一档阈值。
229
427
  * `ratio` **无缺省**:忘传 ⇒ `estimateTokens × undefined` = `NaN` ⇒ `tokens` / `pct` 皆 `NaN`。三面显示门
230
428
  * 都把非正值读作「不显示」(CLI `ctxPct > 0` · VSC 分子为假回 `null` · 桌面 `usageFrameWanted` 不发帧)
231
429
  * ⇒ 读数**缺席**(不会是错数);给缺省 1 则相反——忘传处静默显示未校准读数,看着完全正常而差一整个校准比。
232
430
  * 两种形状里只有后者会被当作事实读走,所以宁可缺席。
431
+ * `workMode` 不是入参(§2.3):分母的取法只有一种,窗口恒等于模型窗口,档位不参与预算。
233
432
  * 空历史 ⇒ 0(状态行的 `ctxPct > 0` 显示门在端侧,不入本函数面)。
234
433
  */
235
434
  export function historyReading(history, provider, ratio) {
236
- const window = providerSpec(provider).context
435
+ const budget = policyBudget(provider)
237
436
  const tokens = Math.round(estimateTokens(history ?? []) * ratio)
238
- return { tokens, pct: Math.round((tokens / window) * 100), window }
437
+ return {
438
+ tokens,
439
+ pct: Math.round((tokens / budget.limit) * 100),
440
+ window: budget.window,
441
+ limit: budget.limit,
442
+ threshold: budget.threshold,
443
+ }
444
+ }
445
+ /**
446
+ * 整量读数单点(§2.5「显示与判定同基准」)——状态行 `context N% NNk` 的分子、stats 首行与第 6 行、
447
+ * 桌面 `ev:usage`、VSC 的 agent 面全读它一处:
448
+ *
449
+ * ```text
450
+ * tokens = contextUsage(agent, extras).total // 装配面六段:非对话面六项 + 对话面,实测优先
451
+ * pct = round(tokens / limit × 100)
452
+ * window ∥ limit = policyBudget(provider) 的两个字段
453
+ * threshold = contextUsage(agent, extras).threshold // 本回合判定所用的那条线
454
+ * basis = "measured" | "estimated"
455
+ * fixed = contextUsage(agent, extras).fixed // 非对话面六项(§5.1 ② 的门读 fixedFloor)
456
+ * compactionSummary = contextUsage(agent, extras).compactionSummary // 压缩摘要格当前内容(压缩链减掉它再加预留额)
457
+ * ```
458
+ *
459
+ * `threshold` 取 `contextUsage` 的那一个而不是 `policyBudget().threshold`:会话配了显式 `compactThreshold`
460
+ * 时后者是预算派生值、不是压缩线——显示与判定各读一条线,「同基准」当场破。
461
+ * 读数不封顶(`pct` 可大于 100):夹住就把「已越线多少」这个信息抹掉,而用户要判断的正是这件事。
462
+ *
463
+ * `extras` 必填、无缺省(同理 §2.3):忘传即静默退回仅对话的估算——正是本函数要消灭的那个量,
464
+ * 而它看起来完全正常。四个面都传 `agent?._ctxBasis?.overhead ?? {}`(`agent/turn-loop.mjs` 每回合暂存)。
465
+ * 例外两个:打开态(无 agent,走 `historyPercent`)与本进程还没跑过 run(空 extras + 无真值 ⇒ 仅对话的估算)。
466
+ */
467
+ export function contextReading(agent, extras) {
468
+ if (extras === undefined) {
469
+ throw new Error("contextReading: `extras` is required (no default) — pass agent?._ctxBasis?.overhead ?? {}")
470
+ }
471
+ const usage = contextUsage(agent, extras)
472
+ const budget = policyBudget(agent?.provider)
473
+ return {
474
+ tokens: usage.total,
475
+ pct: Math.round((usage.total / budget.limit) * 100),
476
+ window: budget.window,
477
+ limit: budget.limit,
478
+ threshold: usage.threshold,
479
+ basis: usage.basis,
480
+ fixed: usage.fixed,
481
+ compactionSummary: usage.compactionSummary,
482
+ }
239
483
  }
240
484
 
241
- /** 状态行百分比薄转口(名面与 export 不变):`historyReading` 的 `pct`——与 stats ∥ CLI ∥ VSC **同源**
242
- * (各处全是这一实现点的投影,端侧零自算式)。第三参 `ratio` 同 `historyReading`:无缺省。 */
485
+ /** 状态行百分比薄转口(名面与 export 不变):`historyReading` 的 `pct`——打开态读数(`sessionReading`)
486
+ * 与无 agent 转口两处用;有 agent 的四个面(CLI 状态行 ∥ stats ∥ Desktop ∥ VSC agent 面)一律读 `contextReading`。
487
+ * 第三参 `ratio` 同 `historyReading`:无缺省;档位不是入参。 */
243
488
  export function historyPercent(history, provider, ratio) {
244
489
  return historyReading(history, provider, ratio).pct
245
490
  }
@@ -265,10 +510,15 @@ export const PRUNE_MIN_TOKENS = 200
265
510
  * 陈旧工具输出合格集(§6.16.3——三条件合取,单源实现):① `role === "tool"`;② **保护尾之外**(复用 `splitHistory` 的同一 `tailStart`——不新增第二处切割判据);③ 估算 ≥ `PRUNE_MIN_TOKENS`。
266
511
  * 返回逐条计数面(prune 回执 + stats 两处消费):`indexes` 合格索引(升序)· `tokens` 合格集估算和 · `candidates` 全史 tool 结果数 · `tailKept` 保护尾内保留数 · `belowMin` 门槛下跳过数 · `tailCount` 保护尾消息数。
267
512
  * **短历史(无中段)⇒ 合格集为空**(no-op——§6.16.3 边界)。
513
+ * `workMode` 不是入参(§2.3):保护尾与压缩面同取有效窗口(恒等于模型窗口),档位不参与。
514
+ * `protectFrom` 无缺省(`CONTEXT-COMPACTION.md` §1.2):保留窗起点,原样转给 `splitHistory` 的第四参。
515
+ * 拿不到保留窗的调用方传 `history.length`(= 不收紧);留一个缺省就是把「保留窗内该不该被清」
516
+ * 静默定给调用方——这一档正是本批要保护的格。
517
+ * `fixedOverhead` ∥ `ratio` 无缺省(§2.3):尾预算的减法链要用它们;四个消费点各自算好再传(§2.3 表)。
268
518
  */
269
- export function collectStaleToolOutputs(history, provider) {
519
+ export function collectStaleToolOutputs(history, provider, protectFrom, fixedOverhead, ratio) {
270
520
  const h = Array.isArray(history) ? history : []
271
- const split = splitHistory(h, keepTailSize(provider, h.length), tailBudgetTokens(provider))
521
+ const split = splitHistory(h, keepTailSize(provider, h.length), tailBudgetTokens(provider, fixedOverhead, ratio), protectFrom)
272
522
  // 无中段(短历史)⇒ 可摘要面为空 ⇒ **全史即保护尾**(tailStart = 0——合格集必为空,同压缩面 no-op)
273
523
  const tailStart = split ? split.tailStart : 0
274
524
  const r = { indexes: [], tokens: 0, candidates: 0, tailKept: 0, belowMin: 0, tailCount: h.length - tailStart }
@@ -283,3 +533,77 @@ export function collectStaleToolOutputs(history, provider) {
283
533
  }
284
534
  return r
285
535
  }
536
+
537
+ /**
538
+ * 结构编辑后的实测基线重定(§3.1)——prune ∥ shrink ∥ 压缩 ∥ 蒸馏四处只改动机读线的一部分,
539
+ * 前缀因此对不上旧真值:**不能沿用,也不必归零**,改掉那一段的估算差就是它在实测尺上的差。
540
+ *
541
+ * ```text
542
+ * _lastPromptTokens' = _lastPromptTokens − round((estBefore − estAfter) × ratio)
543
+ * _usageAt' = 剪切后仍属于旧前缀的那些消息之后的位置(就地替换 ⇒ 不变)
544
+ * _usageFixedBase' = 原样
545
+ * ```
546
+ *
547
+ * `estBefore` / `estAfter` = 旧前缀里被改动的那一段、与它在编辑后对应的那一段,各取 `estimateTokens`。
548
+ * 乘 `ratio` 与实测支对后缀的换算同一把尺:整条读数 = 「前缀的实测值」+「后缀的估算值 × ratio」。
549
+ * 减到非正 ⇒ 基线不再描述任何东西,退回 `null`(与归零同形,但只在算不出来时走);两个真值字段一起退回。
550
+ * `_usageFixedBase` 在正常路径上原样,理由不是「结构编辑只改对话面」:非对话面同样会动(压缩摘要重写、
551
+ * 待发队进出、编辑器上下文刷新)。它不动是因为那份变化已有承接方——实测支的第三项
552
+ * `(fixed − _usageFixedBase) × ratio` 量的就是非对话面与基线之差,重定基线等于把同一份变化扣两次。
553
+ *
554
+ * @param {object} agent
555
+ * @param {number} estBefore 被改那一段的旧估算
556
+ * @param {number} estAfter 它在编辑后对应那一段的估算
557
+ * @param {{inPlace?: boolean, before?: object[], measuredEnd?: number}} [opts]
558
+ * `inPlace` = 结构不变(prune ∥ shrink 的原位替换)⇒ `_usageAt` 原样:被替换那条仍在
559
+ * 前缀里,它的新估算已经由上面那笔减法折进基线,再进后缀就是重复计一次。
560
+ * `before` = 编辑前的机读线(嵌套);`measuredEnd` = 它被量到的拍平下标(剪切类编辑按身份找回旧前缀的尾巴)。
561
+ */
562
+ export function rebaseMeasured(agent, estBefore, estAfter, { inPlace = false, before = null, measuredEnd = null } = {}) {
563
+ if (agent?._lastPromptTokens == null) return
564
+ const ratio = tokenRatioOf(agent)
565
+ const next = agent._lastPromptTokens - Math.round((estBefore - estAfter) * ratio)
566
+ if (!(next > 0)) {
567
+ agent._lastPromptTokens = null
568
+ agent._usageAt = null
569
+ agent._usageFixedBase = null
570
+ return
571
+ }
572
+ agent._lastPromptTokens = next
573
+ if (inPlace) return
574
+ const history = Array.isArray(agent.history) ? agent.history : []
575
+ const source = Array.isArray(before) ? before : history
576
+ const limit = Number.isInteger(measuredEnd) ? measuredEnd : flatLengthOf(source)
577
+ // 旧前缀的成员按**身份**取:压缩重建数组后下标会漂、身份不漂(与在途段起点同一条重定规则,§1.1)。
578
+ const kept = new Set()
579
+ let seen = 0
580
+ for (const turn of source) {
581
+ for (const m of Array.isArray(turn?.messages) ? turn.messages : []) {
582
+ if (seen >= limit) break
583
+ kept.add(m)
584
+ seen++
585
+ }
586
+ if (seen >= limit) break
587
+ }
588
+ agent._usageAt = endPositionOf(history, kept)
589
+ }
590
+
591
+ /** 嵌套线的拍平条数(外层条数是轮数,不是消息数)。 */
592
+ function flatLengthOf(history) {
593
+ let n = 0
594
+ for (const turn of Array.isArray(history) ? history : []) {
595
+ n += Array.isArray(turn?.messages) ? turn.messages.length : 0
596
+ }
597
+ return n
598
+ }
599
+
600
+ /** 旧前缀最后一条仍在线上那一条之后的位置(找不到 ⇒ 线头)。 */
601
+ function endPositionOf(history, kept) {
602
+ for (let t = history.length - 1; t >= 0; t--) {
603
+ const messages = Array.isArray(history[t]?.messages) ? history[t].messages : []
604
+ for (let m = messages.length - 1; m >= 0; m--) {
605
+ if (kept.has(messages[m])) return { turn: t, msg: m + 1 }
606
+ }
607
+ }
608
+ return { turn: 0, msg: 0 }
609
+ }
@@ -1,28 +1,3 @@
1
- Run an independent review of your work. `type` is REQUIRED — one of exactly two values, no default and no silent fallback.
1
+ Run an independent review of your work.
2
2
 
3
- - `type="design"` — design review: reviews design / requirement documents BEFORE implementation. Pass `documents=[...]` and `batchDoc` — the batch record this review belongs to. **`batchDoc` is required**: a design review without it is refused before launch, because the token it would mint has no batch to close it.
4
- - `type="code"` — code review: reviews the code you changed AFTER implementation. Pass `paths=[...]` to scope files/directories; `documents=[...]` adds acceptance-criteria context.
5
-
6
- `documents` — one rule: a relative path resolves against the session project root (e.g. `docs/<area>/<name>.md`); an absolute path is used as-is.
7
-
8
- The relative form needs the session anchor to be inside a project. When the anchor is a workspace root (several projects below it, no manifest of its own) there is no single project root to resolve against, and a relative path is refused with `no-project-root` — write the absolute path there.
9
-
10
- Accepted = an existing `.md` file anywhere inside a project — a doc sitting at the repo root counts. Anything else is refused with the resolved path, the reason and the two expected forms.
11
-
12
- A call without a type (or with a conflicting `object.type`) is refused.
13
-
14
- The advisor is an independent read-only sub-agent (explores the codebase, reads files, traces callers via grep/lsp).
15
-
16
- - Code review converges: round 1 full review → round 2 verifies the agent's fix claims → round 3+ re-checks only the fix claims.
17
- - Design review is a single pass against methodology and requirements.
18
- - Criteria come from `.thincoder/advisor.md` (if present) or sensible defaults.
19
- - After the review you MUST produce a response table (format = discipline rules); on all-clear, call `verify`.
20
-
21
- `object={type,target,status,reason,exclude}` optionally anchors the review target — mechanically injected at the start of the review message; absent = no injection.
22
-
23
- ASYNC (depth 0 only): the review runs in the BACKGROUND by default — ack immediately, the report arrives automatically in a digest turn.
24
-
25
- - One shared pool: `agent.poolLimits.advisor`, default 4 — configurable via `/config` 并发池 or config.json. Pool-full and same-scope launches are refused stating the current limit; launch reviews one at a time.
26
- - Inside a child (depth>0) reviews are always synchronous (`async:true` rejected).
27
-
28
- Returns the verdict: all-clear (call `verify`) or a findings list to fix.
3
+ {{knowledge:tool-advisor}}
@@ -1,17 +1,3 @@
1
1
  Apply a unified diff to one or more files, atomically: if any hunk fails to apply, nothing is written.
2
2
 
3
- **Use it for whole-file and multi-file changes:** creating MULTIPLE new files at once (`--- /dev/null` header per file), whole-file replacement, and cross-file refactors — one unified-diff call covers the whole change. A batched call is one permission ask and one turn instead of N separate calls.
4
-
5
- Parameters:
6
- - patch (required): Unified diff text. One `--- a/path` / `+++ b/path` header pair per file, then `@@ -old,count +new,count @@` hunks. Use `--- /dev/null` to create a new file. 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`).
7
-
8
- Notes:
9
- - Hunk header "@@" without coordinates is 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. The anchor-free forms require context: a hunk with no removed (-) lines (pure additions) needs at least 2 context lines for a unique match; a zero/one-context hunk with at least one removed (-) line is located by its anchor sequence (context + removed lines, in order) and applies on a unique match.
10
- - Returns the applied-file summary (`Applied patch to N file(s)` plus per-file change lines and syntax-check notes for changed .mjs files)
11
- - Use this for multi-file changes (e.g. rename an interface + update all callers) — one call, all-or-nothing
12
- - Hunks are located by their context/removed lines, not line numbers — but the context must match the file EXACTLY. Read the files first and generate the patch from actual content
13
- - If a hunk's context matches multiple locations it is rejected — add more surrounding context lines
14
- - Deleting files is not supported — use the delete tool
15
- - For single-file edits, edit is simpler; for full rewrites, write is simpler
16
-
17
- **`ledger`** — the in-flight ledger row this call serves: `"#N"` or `"N"`. In engineering mode the parent agent must pass it — a call that does not say which row it serves is refused.
3
+ {{knowledge:tool-apply-patch}}
package/tool-docs/bash.md CHANGED
@@ -1,43 +1,2 @@
1
- Execute a shell command and return stdout+stderr. Use for running commands, builds, tests.
2
-
3
- **Route to a dedicated tool instead of bash:**
4
- - `cat file` / `head` / `tail` → `read`
5
- - `ls` / `dir` → `ls`
6
- - `find` / glob search → `glob`
7
- - `grep` / `rg` → `grep`
8
- - `echo >` / `sed` / `printf >` / `cat << EOF` → `write` / `edit` / `hashline_edit` / `apply_patch` (preferred: write tools handle encoding/EOL correctly)
9
- - `git diff` / `git status` / `git log` → `git` tool
10
-
11
- Parameters:
12
- - command (required): Shell command to execute
13
- - timeout: Timeout in milliseconds (default 120000 for synchronous runs; background runs have no default — an explicit timeout still applies; no upper bound)
14
- - filter: Optional — a regex; only output lines matching it are returned (case-insensitive). Use instead of hand-writing a pipe into `findstr`/`grep`.
15
- - async: Run in the background (default false) — returns an ack at once (bash#<id>, log path); the result arrives as a digest when the process exits. Depth-0 only.
16
- {{inject:bash-terminal-face}}
17
-
18
- Output format:
19
- ```
20
- [stdout]:
21
- <standard output, or "(empty)">
22
-
23
- [stderr]:
24
- <standard error, only present if non-empty>
25
-
26
- (exit code N)
27
- ```
28
-
29
- Notes:
30
- - There is NO TTY — editors, pagers (vim, less), and interactive prompts WILL hang. Always pass non-interactive flags: `git commit -m`, `git --no-pager`, `-y`/`--yes` where applicable
31
- - The environment sets GIT_PAGER=cat, PAGER=cat, EDITOR=true, TERM=dumb — but still always use non-interactive flags
32
- - Output is capped at ~200K chars; if you need more, redirect to a file and read it. Truncated output ends with a `[... truncated: N chars omitted]` marker — the missing tail may contain errors, so read the saved log file's tail before trusting success. Use `filter` to narrow instead of hand-piping.
33
- - Check `[stderr]` for error messages, warnings, and diagnostic output — it is separated from `[stdout]` so you can quickly identify problems.
34
- - Shell identity: the bash tool's shell is NOT fixed — it depends on configuration and environment. The current executor is declared in the Executor line above; write commands for THAT shell, and when a command fails read its error output to identify the actual shell.
35
- - Never use bash to read, copy, or transmit secret files (.env, keys, tokens)
36
- - Do NOT run destructive commands (rm -rf, force-push, drop table) without explicit user confirmation
37
- - After commands that change files (git checkout, npm install, etc.), repo_outline and code_search may be stale — re-run them to get current results.
38
- - Prefer read/glob/grep/ls for file operations inside the project — file tools and bash reach the same paths (no directory restriction).
39
- - NEVER use bash to write or modify files (echo/sed/printf > file, cat << EOF, etc.). Use write/edit/insert_after/apply_patch instead — they handle encoding, escaping, and EOL conventions correctly.
40
-
41
- **`ledger`** — the in-flight ledger row this call serves: `"#N"` or `"N"`. In engineering mode the parent agent must pass it — a call that does not say which row it serves is refused, and read-only commands are judged the same way (no command-line classification).
42
-
43
- **`project`** — the project this call belongs to: the absolute path of the project root (the directory carrying PROJECT-MANIFEST.json). Engineering mode: pass it together with `ledger`. Pure declaration: it does not change the execution directory.
1
+ Execute a shell command and return stdout+stderr.
2
+ {{knowledge:tool-bash}}
@@ -0,0 +1,3 @@
1
+ Write the batch record's implementation section (§5) — your pen on this record.
2
+
3
+ {{knowledge:tool-batch-eng-coder}}
@@ -0,0 +1,3 @@
1
+ Write the batch record's design section (§2) — your pen on this record.
2
+
3
+ {{knowledge:tool-batch-eng-designer}}
@@ -0,0 +1,3 @@
1
+ Write the batch record's design-review section (§3) — your pen on this record.
2
+
3
+ {{knowledge:tool-batch-review}}