@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/context.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  * context.mjs — Context management and compaction
3
3
  * When no measured token count is available, use estimation as fallback (ASCII/4 + non-ASCII/1, no tokenizer dependency).
4
4
  * When a measured value exists (response usage.prompt_tokens), trust it — estimation underestimates CJK by 3-4x and relying solely on it may never trigger compaction.
5
- * Compaction strategy: summarize everything before the tail into one LLM note, keep the latest N messages verbatim.
5
+ * Compaction strategy: summarize everything before the tail into one LLM summary, keep the latest N messages verbatim.
6
6
  * NOTE: no dedicated head is kept (KEEP_HEAD = 0) — in multi-task sessions the earliest messages are
7
7
  * typically a COMPLETED earlier task; preserving them verbatim anchored the model's attention on stale
8
8
  * work after compaction. The earliest messages now go into the summary (which distinguishes completed
@@ -13,50 +13,68 @@
13
13
 
14
14
  import { chat } from "./provider/index.mjs"
15
15
  import { buildCompressMessages } from "./compress-form.mjs"
16
- import { contextUsage, estimateTokens, keepTailSize, splitHistory, SUMMARY_TOKEN_ESTIMATE, tailBudgetTokens } from "./token-window.mjs"
17
- import { COMPACTION_PLACEHOLDER, withPlaceholderPrefix } from "./context-echo.mjs"
18
- import { shrinkOversized } from "./context-degrade.mjs"
16
+ import { contextUsage, estimateTokens, keepTailSize, splitHistory, COMPACTION_SUMMARY_TOKEN_ESTIMATE, rebaseMeasured, tailBudgetTokens, tokenRatioOf } from "./token-window.mjs"
17
+ // 写面单点(机器线按轮嵌套):压缩只做结构编辑,消息怎么进线归 `context-push.mjs`;三段回注住 A 段格位。
18
+ import { flattenHistory, flatIndexOf, positionOf, setInject } from "./context-push.mjs"
19
+ // 会话头块的两个单点(`CONTEXT-COMPACTION.md` §1.1「会话头块」):写入方 = `pushSessionHeadBlock`,
20
+ // 大纲正文 = `sessionOutlineOf`。压缩是本批的第二个刷新点——切走第一条真实用户消息所在轮之后重算一次,
21
+ // 下一次装配就贴到压缩边界后的新锚点上。
22
+ import { pushSessionHeadBlock, sessionOutlineOf } from "./agent/setup-reminders.mjs"
23
+ // 降级留痕(头块写入失败那一支)——核日志单一通道。
24
+ import { logEvent } from "./log.mjs"
25
+ // 压缩后回注的工作状态块(§6.1「工作状态的找回」):块怎么生成住 `compaction-work-state.mjs`;
26
+ // 本档只负责「注在哪」——三段回注的唯一落点是下面的 `reinjectAfterCompaction`。
27
+ import { workStateBlock } from "./compaction-work-state.mjs"
28
+ import { pruneStaleToolOutputs, shrinkOversized } from "./context-degrade.mjs"
29
+ // 固定开销越线判据的另一半(#2398):`limit` 单源 = `policyBudget`(有效窗口——与守卫面同一个数)。
30
+ import { policyBudget } from "./config.mjs"
31
+ // 覆盖条数(#2399):按切点算——一层元素全在切点之前才算覆盖,一轮被切开不记(单源 = `turn-projection.mjs`)。
32
+ // 保留窗起点(#2431):`splitHistory` 的必填第四参——切点一处收紧,压缩与 prune 同源受益(§1.2)。
33
+ import { coveredTurnCount, retentionWindowStart } from "./agent/turn-projection.mjs"
34
+ // 压缩请求形的来源面(AGENT-LOOP.md §5.5.4 读(压缩 ∥ 蒸馏请求)行):当前 provider 的 spec 由调用点解出——
35
+ // `specForModel(agent.provider?.model)` 与本档其它 spec 读面同源,不另写族别表。
36
+ import { specForModel } from "./model-specs.mjs"
37
+ import { isThinkingRequest } from "./think-off.mjs"
38
+
39
+
40
+ /**
41
+ * 保留窗起点 → `splitHistory` 的第四参(拍平下标)。
42
+ * 起点按外层轮元素位置取(`{ turn, msg }`);取不到(轮元素不足窗宽)⇒ 传拍平条数 = 不收紧。
43
+ * 整数守卫在 `splitHistory` 里,本函数只做一次两向换算。
44
+ */
45
+ function protectFromOf(agent, flat) {
46
+ const pos = retentionWindowStart(agent)
47
+ return pos ? flatIndexOf(agent.history, pos) : flat.length
48
+ }
19
49
 
20
50
  export const SUMMARIZE_PROMPT = `The conversation above is our work log so far — summarize it into a compact summary for use as context in the ongoing conversation.
21
51
  Requirements:
22
52
  - Write in first person, present tense — these are "my" handover notes, continuing my own train of thought
23
53
  - Most important: preserve design decisions and their reasons — architecture choices, API contracts, naming conventions, trade-off rationale. These are the anchors the subsequent code must not deviate from
54
+ - Preserve the user's explicit constraints as their own bullet, quoting the user's own words: forbidden scopes (what the user said not to do or not to touch), allowed scopes (what the user explicitly permitted), priority order (what the user said to do first), and deferred items (what the user said to postpone). Do not rewrite them as design decisions and do not fold them into unresolved issues
24
55
  - Distinguish COMPLETED vs IN-PROGRESS work: completed tasks get a ONE-LINE recap each (what was done, key outcome); spend the detail budget on unresolved issues, next steps, and the CURRENT task
25
56
  - The user's most recent request defines the current task — anchor on it. Earlier requests are likely already completed and only need the one-line recap; do NOT preserve them at full fidelity
57
+ - My previous handover note is attached above as a message of its own. When it is attached, fold its facts into this new note and produce ONE merged summary covering everything compacted so far: no fact from it may be dropped, and the old note is not repeated beside the new one. The note is not one of those earlier requests — what is still live in it must survive, and "completed ⇒ one-line recap" applies only to work that is actually finished
26
58
  - Explicitly list FILES CHANGED: every modified file path plus a one-line "why" — so post-compaction work can re-locate what was edited and where
27
59
  - Explicitly list UNRESOLVED ISSUES / TODOs: anything still open plus the next steps — so post-compaction recovery knows where to resume
28
60
  - Drop: pleasantries, repetition, fine-grained tool output details
29
61
  - Honestly mark uncertain items: anything not actually verified must say "unverified"; do not present guesses as facts
30
- - Use bullet-point output. Stay under ~1K tokens (≈1000 Chinese chars / 4000 ASCII chars) — a hard target. An oversized summary wastes window and dilutes the tail; the old unbounded-length guidance is deprecated. When over budget, trim in this order: completed recaps to one line; FILES CHANGED why-notes to bare paths; in-progress prose tightened. NEVER cut design anchors or UNRESOLVED ISSUES/TODOs — recovery depends on them.
62
+ - Use bullet-point output. Stay under ~1K tokens (≈1000 Chinese chars / 4000 ASCII chars) — a hard target. An oversized summary wastes window and dilutes the tail; the old unbounded-length guidance is deprecated. When over budget, trim in this order: completed recaps to one line; FILES CHANGED why-notes to bare paths; in-progress prose tightened. NEVER cut design anchors, UNRESOLVED ISSUES/TODOs, or user constraints — recovery depends on them.
31
63
  `
32
64
 
33
- /** Context prefix after compaction, informing the agent what happened */
34
- const COMPACTION_PREFIX =
35
- "[Context was automatically compacted. Below is a summary of earlier work. " +
36
- "Treat it as notes, not proof — trust its conclusions (don't redo what it reports as done) " +
37
- "but re-verify transient state with tools. Check memory search for any missing decisions.]\n\n"
38
-
39
- /**
40
- * 注记 + 占位的估算(§6.17 可达性门的 `note` 项):摘要正文取 `SUMMARY_TOKEN_ESTIMATE`(§6.9 的 ~1K 目标,常量单源 =
41
- * `token-window.mjs`),注记前缀与占位句按 §6.3 估算式(`estimateTokens` 走同一 `estimateText`)——零新常数、零新算式。
42
- * 残余方向:真实摘要超 1K 时本值低估 `post`(门可能放行一次压不到线下的压缩),不会反向误拦——守卫面仍抛三实数。
43
- * 另:`applyCompression` 压完还会追加任务表回注与 plan 提醒(`agent.tasks` / `planMode` 非空时),本值同样不含——
44
- * 同向低估(大任务表会话里 `post` 偏小),不会把本该压的格拦下。
45
- */
46
- const NOTE_ESTIMATE = SUMMARY_TOKEN_ESTIMATE + estimateTokens([
47
- { role: "user", content: COMPACTION_PREFIX },
48
- { role: "assistant", content: COMPACTION_PLACEHOLDER },
49
- ])
50
-
51
- /** After this many consecutive compaction summary failures, degrade to deterministic truncation (losing info is better than task-killing 400 errors) */
52
- export const COMPRESS_FAILURE_LIMIT = 3
65
+ // 压缩摘要的估算(可达性门的 `compactionSummary` 项 ∥ §4 减法链的末项)住 `token-window.mjs` 的
66
+ // `COMPACTION_SUMMARY_TOKEN_ESTIMATE`——尾预算也要用它,而本档 import 那一档(反向就会成环)。
67
+ // 压缩摘要的文本就是摘要正文本身(§6.1)——本档不为它拼任何固定文本;回声明占位已退场,本值不再为它留预算。
68
+ // 残余方向:真实摘要超 1K 时本值低估 `post`(门可能放行一次压不到线下的压缩),不会反向误拦——守卫面仍抛三实数。
69
+ // 压完之后任务表回注、plan 提醒与工作状态块住 `_inject` 的三个格,会话头块住 `agent._sessionHead`——
70
+ // 它们不靠本值计,而在 `fixed` 里(§2.5 六项之一)。
53
71
 
54
72
  /** Task re-injection reminder prefix (after compaction, clear old versions from history first for a single source of truth) */
55
73
  const TASK_REINJECT_PREFIX = "[System reminder: your current task list after compaction:"
56
74
 
57
- /** Truncation fallback note (used when the summary LLM fails repeatedly; no LLM call) */
58
- const FALLBACK_NOTE =
59
- "[Context was truncated after repeated summarization failures. " +
75
+ /** Truncation fallback summary (deterministic discard, no LLM call — §5.1 第 ⑥ 步) */
76
+ const FALLBACK_COMPACTION_SUMMARY =
77
+ "[Context was truncated because summarization failed. " +
60
78
  "The middle portion of earlier work was dropped WITHOUT a summary. " +
61
79
  "Re-verify any state you need with tools before relying on it.]\n\n"
62
80
 
@@ -82,136 +100,201 @@ function anchorText(agent) {
82
100
  return lines.length > 0 ? lines.join("\n") : null
83
101
  }
84
102
 
85
- /** Replace middle with a note, then re-inject task/plan state (shared by LLM summary and truncation fallback) */
86
- function applyCompression(agent, headEnd, tailStart, note) {
87
- // _fullHistory already holds every real message (written at the source via pushReal),
88
- // so compaction only shrinks the machine line — nothing to preserve here.
89
- // head is normally empty (KEEP_HEAD = 0) — the summary note becomes the first message,
90
- // which is exactly the intent: post-compaction context anchors on the current task, not on
91
- // possibly-completed earlier requests.
92
- const head = agent.history.slice(0, headEnd)
93
- const tail = agent.history.slice(tailStart)
94
- // SESSION.md §6.9: compaction-injected messages carry a ts — Date.now() at the compaction
95
- // moment (the note below; and the separate "Understood" placeholder in the non-merge branch).
96
- // They are machine-only (never in _fullHistory), but the machine-line timeline stays consistent
97
- // for any audit use. D-CC18 exception: in the merge branch the placeholder rides inside a REAL
98
- // tail message, which keeps its OWN ts — merging must not rewrite that message's time semantics
99
- // (and must not backfill ts-less restored messages either, D-S3).
100
- const now = Date.now()
101
- // D-CC18 echo safety: an assistant WITHOUT reasoning_content directly followed by another
102
- // assistant is rejected 400 by DeepSeek-family thinking mode ("The `reasoning_content` in the
103
- // thinking mode must be passed back to the API." — traced from a subagent's first post-compaction
104
- // request, 2026-09-16). The synthetic placeholder has no reasoning to echo, so when the tail
105
- // starts with an assistant the placeholder is merged INTO that message — copy-on-write, because
106
- // pushReal shares message objects with _fullHistory (never mutate in place) — instead of being
107
- // emitted as a separate message.
108
- //
109
- // Compaction REBUILDS the machine line (head + note + placeholder + tail), so the pre-compaction
110
- // _runStartHistoryLen index is stale — a longer array shrank beneath it, and end-of-run exploration
111
- // distillation would then silently skip or slice from the wrong offset. Reset the boundary to the
112
- // first verbatim tail message: head.length + 1 in the merge branch (the placeholder rides inside
113
- // the rewritten tail[0], which keeps its index), head.length + 2 otherwise (the note and the
114
- // separate "Understood" placeholder sit between head and tail). Exploration before the tail was
115
- // already covered by the compaction summary, so only the still-raw tail needs distilling. `head`
116
- // is empty today (KEEP_HEAD = 0) — the formula stays correct if KEEP_HEAD ever grows.
117
- // (shrinkOversized only truncates message bodies in place and leaves the array length unchanged,
118
- // so this boundary stays valid there — no reset needed.)
119
- if (tail[0]?.role === "assistant") {
120
- const merged = { ...tail[0], content: withPlaceholderPrefix(tail[0].content) }
121
- agent.history = [
122
- ...head,
123
- { role: "user", content: note, ts: now },
124
- merged,
125
- ...tail.slice(1),
126
- ]
127
- agent._runStartHistoryLen = head.length + 1
128
- } else {
129
- agent.history = [
130
- ...head,
131
- { role: "user", content: note, ts: now },
132
- { role: "assistant", content: COMPACTION_PLACEHOLDER, ts: now },
133
- ...tail,
134
- ]
135
- agent._runStartHistoryLen = head.length + 2
103
+ /**
104
+ * 压缩后三段回注的**唯一落点**(CONTEXT-COMPACTION.md §6.1「注在哪里」):顺序写死为
105
+ * 「任务表 → plan 提醒 → 工作状态块」,各写 A 段自己那一格。
106
+ * 三个格位写即覆盖旧值——**不再扫线摘旧版本**:任务表 / plan 提示 / 工作状态块都不是线上消息(§1.1 注入三段)。
107
+ * `null` 或空串 ⇒ 该格清空(没有值的状态与「这一格从来没过」在装配面上同形)。
108
+ * 它不读盘:`workState` 是调用方给的那个值(`applyCompression` 的同名参数),与它同源。
109
+ * @param {object} agent
110
+ * @param {string|null} workState — 已生成的工作状态块;`null` = 台账面读失败 ⇒ 整块不出现
111
+ */
112
+ function reinjectAfterCompaction(agent, workState) {
113
+ setInject(agent, "tasks", agent.tasks.length > 0
114
+ ? `${TASK_REINJECT_PREFIX}\n${agent.tasks.map((t) => `- [${t.status}] ${t.title}`).join("\n")}\nContinue from where you left off.]`
115
+ : null)
116
+ setInject(agent, "plan", agent.planMode
117
+ ? "[System reminder: plan mode is active. Explore the codebase read-only, design your solution, then call plan with action='exit' to present it for user approval.]"
118
+ : null)
119
+ setInject(agent, "work-state", workState)
120
+ }
121
+
122
+ /**
123
+ * 按结构切一刀(§1.1「压缩的切点」):`from` 之前的轮元素整条移出外层,`to` 之前的消息进摘要,
124
+ * `(to.turn, to.msg)` 起的原文原样留下。`from.turn === to.turn` 时同一轮里切两刀(头段与尾段各留一段)。
125
+ * 切完为空的轮元素整条丢掉——一轮的消息全离开机读线时,它的轮元素就移出外层。
126
+ */
127
+ function cutTurns(history, from, to) {
128
+ const out = []
129
+ for (let t = 0; t < history.length; t++) {
130
+ const messages = Array.isArray(history[t]?.messages) ? history[t].messages : []
131
+ let kept
132
+ if (t < from.turn || t > to.turn) kept = messages
133
+ else if (t === to.turn) kept = [...(t === from.turn ? messages.slice(0, from.msg) : []), ...messages.slice(to.msg)]
134
+ else if (t === from.turn) kept = messages.slice(0, from.msg)
135
+ else kept = []
136
+ if (kept.length > 0) out.push({ messages: kept })
136
137
  }
137
- // Measured token baseline is invalidated along with old history (prompt_tokens were for pre-compaction context), fall back to estimation until next response
138
- agent._lastPromptTokens = null
139
- agent._usageAtLen = null
138
+ return out
139
+ }
140
140
 
141
- // After compaction, re-inject the task list (the agent needs to know what it was doing).
142
- // Single source of truth: first remove any stale re-injections from the tail, then inject the latest version —
143
- // no longer embedded in the summary body (would duplicate and grow stale)
144
- agent.history = agent.history.filter(
145
- (m) => !(m.role === "user" && typeof m.content === "string" && m.content.startsWith(TASK_REINJECT_PREFIX))
146
- )
147
- if (agent.tasks.length > 0) {
148
- const taskSummary = agent.tasks.map((t) => `- [${t.status}] ${t.title}`).join("\n")
149
- agent.history.push({
150
- role: "user",
151
- content: `${TASK_REINJECT_PREFIX}\n${taskSummary}\nContinue from where you left off.]`,
152
- })
141
+ /**
142
+ * 摘要支与丢弃支共用的 `workState` 契约(§6.1「契约」):必填、无默认。
143
+ * 默认值等于替调用方决定「这一格要不要指针」——与「压缩面一处拼装」相反;缺传当场抛并点名该参数。
144
+ */
145
+ function assertWorkState(fnName, workState) {
146
+ if (workState !== null && typeof workState !== "string") {
147
+ const got = workState === undefined ? "undefined(缺传)" : Array.isArray(workState) ? "array" : typeof workState
148
+ throw new Error(`${fnName}:workState 必填(string | null,无默认)——压缩后回注的工作状态块由调用方给,实收 ${got}`)
153
149
  }
150
+ }
154
151
 
155
- // Plan mode compaction: re-inject plan mode guidance
156
- if (agent.planMode) {
157
- agent.history.push({
158
- role: "user",
159
- content: "[System reminder: plan mode is active. Explore the codebase read-only, design your solution, then call plan with action='exit' to present it for user approval.]",
160
- })
152
+ /**
153
+ * 两个压缩出口共用的 `outline` 契约(§1.1「会话头块」):必填、无默认,本趟没有大纲就传空串。
154
+ * 它在这里先拦一次,让人读到的错点名 `applyCompression` ∥ `compressFallback` 与 `outline` 本身,
155
+ * 而不是下一层写入方 `pushSessionHeadBlock` 报的同一件事。
156
+ */
157
+ function assertOutline(fnName, outline) {
158
+ if (typeof outline !== "string") {
159
+ const got = outline === undefined ? "undefined(缺传)" : Array.isArray(outline) ? "array" : typeof outline
160
+ throw new Error(`${fnName}:outline 必填(string,无默认)——本趟的大纲正文由调用方给,没有就传空串;实收 ${got}`)
161
+ }
162
+ }
163
+
164
+ /** Replace middle with the compaction summary, then re-inject task/plan/work-state pointers (shared by LLM summary and truncation fallback).
165
+ * `outline` = 本次压缩后重建的依赖大纲正文(必填、无默认:没有就传空串——`pushSessionHeadBlock` 据此省掉大纲那两段)。
166
+ * 它由调用方构好传进来,因为本函数是同步的,而大纲要读库与源文件。 */
167
+ export function applyCompression(agent, headEnd, tailStart, compactionSummary, workState, outline) {
168
+ assertWorkState("applyCompression", workState)
169
+ assertOutline("applyCompression", outline)
170
+ // 切点 = `{ turn, msg }`(§1.1):两个整数下标在函数体开头换算一次,此后只碰结构。
171
+ const from = positionOf(agent.history, headEnd)
172
+ const to = positionOf(agent.history, tailStart)
173
+ // 覆盖条数(#2399):按切点算——该轮元素全在切点之前才算覆盖(一轮被切开不记)。
174
+ const turnsCovered = coveredTurnCount(agent, to)
175
+ // 结构编辑后的实测基线(§3.1「形态」):压缩是**整段删除**——被摘要覆盖的轮元素整条移出外层,
176
+ // 压缩摘要写 `_compactCheckpoint`、由装配拼进 `_inject` 而不落线,所以线上不存在「中段换成压缩摘要」
177
+ // 的替换:被改的那一段就是整段中段,`estAfter` 取 0。位置落在被移出那一段时 `_usageAt` 落到线头。
178
+ const before = agent.history
179
+ const beforeFlat = flattenHistory(before)
180
+ const measuredEnd = agent._usageAt ? flatIndexOf(before, agent._usageAt) : beforeFlat.length
181
+ const estBefore = estimateTokens(beforeFlat.slice(headEnd, tailStart))
182
+ const estAfter = 0
183
+ // _fullHistory already holds every real message (written at the source via pushReal),
184
+ // so compaction only shrinks the machine line — nothing to preserve here.
185
+ // head is normally empty (KEEP_HEAD = 0): with no dedicated head the summary covers every
186
+ // earlier turn, and the post-compaction context anchors on the current task, not on
187
+ // possibly-completed earlier requests.
188
+ //
189
+ // 压缩摘要不落机读线(§1「压缩摘要的位置」):它住 `_inject` 的 `compaction-summary` 格,装配时排在对话之前。
190
+ // 合成占位(`COMPACTION_PLACEHOLDER`)随之退场——没有相邻 assistant 要它隔开了;压缩后的首个
191
+ // 非 system 消息因此是累积段或压缩摘要本身,不会是 assistant(原 tail[0] 的角色)。
192
+ agent.history = cutTurns(before, from, to)
193
+ setInject(agent, "compaction-summary", compactionSummary)
194
+ // 三段回注(任务表 → plan 提醒 → 工作状态块):顺序与落点在 `reinjectAfterCompaction` 一处。
195
+ reinjectAfterCompaction(agent, workState)
196
+ // 会话头块(§1.1「会话头块」):切完元素、`compaction-summary` 格也已写好——第一条真实用户消息所在轮
197
+ // 刚被切走,重算重存一次,下一次装配就贴到压缩边界后的新锚点上(不叠加第二处:整段替换)。
198
+ // 它是可选注入的写入,不是压缩本体:它抛了只记一行日志——不让一次头块写入失败把一次已成功的压缩
199
+ // 报成摘要失败(那条路会再走一遍 `compressFallback`,把好摘要换成降级摘要)。
200
+ try {
201
+ pushSessionHeadBlock(agent, { outline })
202
+ } catch (err) {
203
+ logEvent("session-head:write-skip", { reason: err?.message ?? String(err) })
161
204
  }
205
+ // 压缩成果落内存载体(#2399):槽保存取它、恢复播种取它(SESSION.md §2 ∥ CONTEXT-COMPACTION.md §6)。
206
+ agent._compactCheckpoint = { compactionSummary, turnsCovered }
207
+ // §3.1 基线重定(结构已定形):中段被摘要取走,`measuredEnd` 之后的消息从没被量过,故只按身份找
208
+ // 「旧前缀最后一个还在线上的消息」,其后第一个位置就是新的 `_usageAt`。
209
+ rebaseMeasured(agent, estBefore, estAfter, { before, measuredEnd })
162
210
  }
163
211
 
164
212
  /**
165
213
  * 可达性门(CONTEXT-COMPACTION.md §6.17「压缩触发判据(可达性门)」):压完之后 `total` 能不能落到阈值之下。
166
- * `post` 按 `applyCompression` 实际留下的形态估——head(KEEP_HEAD = 0 ⇒ 恒空)+ 注记 + 占位 + tail;`middle` = 本次会摘掉的
167
- * 那段(与本次压缩同一次 `splitHistory` 产出)。压缩后 `_lastPromptTokens` 失效 ⇒ 只有估算支可比,故走 estimated 支并乘同一
168
- * `_tokRatio`(与 `contextUsage` 的估算支同尺)。
169
- * 为什么要有它:`system + tools` 是固定开销、压不掉,把它算进判据左侧会让「固定开销本身逼近阈值」的会话反复触发压缩却压不出
170
- * 任何东西——每触发一次白付一次摘要请求(台账 `#1833`)。
214
+ * `post` 按 §2.5 的同一个测度估:对话面只留 tail、非对话面是 `fixed − compactionSummary` 加压缩摘要预留额。`middle` = 本次会摘掉的
215
+ * 那段(与本次压缩同一次 `splitHistory` 产出)。压缩后 `_lastPromptTokens` 失效 ⇒ 只有估算支可比,故走 estimated 支
216
+ * 并乘同一 `_tokRatio`(与 `contextUsage` 的估算支同尺)。
217
+ * 为什么要有它:非对话面是固定开销、压不掉,把它算进判据左侧会让「固定开销本身逼近阈值」的会话反复触发压缩却
218
+ * 压不出任何东西——每触发一次白付一次摘要请求(台账 `#1833`)。
171
219
  */
172
220
  function postCompactionTotal(agent, usage, middle) {
173
- const ratio = agent?._tokRatio ?? 1
174
- return Math.round((usage.history - estimateTokens(middle) + NOTE_ESTIMATE + usage.overhead) * ratio)
221
+ const ratio = tokenRatioOf(agent)
222
+ return Math.round((usage.history - estimateTokens(middle) + COMPACTION_SUMMARY_TOKEN_ESTIMATE + (usage.fixed - usage.compactionSummary)) * ratio)
175
223
  }
176
224
 
177
225
  /**
178
- * Compact when the prompt is over the threshold AND compaction can actually get back under it
179
- * (CONTEXT-COMPACTION.md §6.17 reachability gate); `extras.force` skips both early-exit criteria.
180
- * Returns whether compaction happened.
181
- * Only called at safe points in the loop (history ends with user or tool message — a complete exchange boundary).
182
- * Automatically re-injects task list state after compaction.
226
+ * 压缩链(`CONTEXT-COMPACTION.md` §5.1):越线不等于要付一次摘要请求——越线之后先做一次零成本、
227
+ * 确定性的 prune,再重测。裁 → 摘要 → 丢弃,三步串联,每步之后重测,够则停:
228
+ *
229
+ * ```text
230
+ * ① 阈值早退(total ≤ threshold,force 跳过)
231
+ * ② 固定开销越线门(force 跳不过)
232
+ * ③ prune 一次 → 重定基线(§3.1)→ 重测 contextUsage
233
+ * ④ 未 force 且重测后 total ≤ threshold ⇒ 停(零摘要请求)
234
+ * ⑤ splitHistory(尾预算 = §4 的减法链)→ 可达性门 → 摘要请求 → 重测
235
+ * ⑥ 摘要失败,或压后 total 仍 > threshold ⇒ compressFallback(丢弃,零网络)→ 重测
236
+ * ⑦ 压后 total 仍 > limit ⇒ 守卫抛三实数(`enforceContextFit`,本链之外的同一个原子)
237
+ * ```
238
+ *
239
+ * `force` 面也 prune,但不因 prune 就早退,也不因 ④ 就停:`/compact` 与越窗自愈要的是一次真实的压缩动作,
240
+ * prune 只让中段变小、摘要请求更省。第 ③ 步的射程:合格集非空的只有 §7.2 列的那三类状态(已登记轮不足窗宽∥
241
+ * 本批之前的旧槽——消息上没有 `turn` ∥ 窗内那几轮在线上一条不剩);其余状态下 `tool` 消息全在保留窗内、因而全在保护尾里,prune 返回
242
+ * 0 条——③ 是一步 no-op,常见路径的成本落在 ⑤。
243
+ *
244
+ * 返回是否发生了压缩(摘要成功 ∥ 弃真的发生)。摘要失败一次就走到丢弃,不等连续失败——「一次网络抖动换一个
245
+ * 死会话」正是这条链要避开的结局;只有在丢弃也无中段可丢时才把那个错抛出去(调用点照既有失败链记一行回执)。
246
+ * 摘要请求是 SILENT 的(从不转 onToken/onReasoning——压缩是内部机制,不是模型回复);`onCompressStart` 在
247
+ * 摘要请求发出前触发(§6.8 D-C1 生命周期可见)。只在安全点调用(history 以完整交换结尾)。
183
248
  * @param {object} agent
184
249
  * @param {number} threshold - compaction threshold in tokens
185
- * @param {object} callbacks - { onToken, onReasoning, onCompress, onCompressStart } — summary
186
- * generation is SILENT (never forwards onToken/onReasoning: the compaction process is an
187
- * internal mechanism, not a model reply); onCompressStart fires right before the summary call
188
- * (§6.8 D-C1, compression lifecycle visibility — panel start state)
250
+ * @param {object} callbacks - { onCompress, onCompressStart, onCompressFail }
189
251
  * @param {object} extras - { systemPrompt?, tools?, force?, focus? } — 固定开销面(system + tools 估计)+
190
- * 模型主动压缩面(§6.16.2):`force` **跳过阈值面的全部早退判据**(`total <= threshold` 与 §6.17 可达性门的
191
- * `post > threshold` 两条),其余全同(同切分 / 同尾部预算 / 同摘要链 / 同回注 / 同基线失效);`focus` 追加在摘要指令尾段。
252
+ * 模型主动压缩面(§6.16.2):`force` **跳过阈值面的全部早退判据**(`total <= threshold`、第 ④ 步与 §6.17
253
+ * 可达性门的 `post > threshold`),其余全同(同切分 / 同尾部预算 / 同摘要链 / 同回注 / 同基线重定);
254
+ * `focus` 追加在摘要指令尾段。
192
255
  */
193
- export async function compressIfNeeded(agent, threshold, callbacks, extras = {}, signal) {
194
- const history = agent.history
195
- // 单源(§6.16.4):total 与 stats 面同一函数(既有内联式改调 contextUsage,判定语义零改)
196
- const usage = contextUsage(agent, extras)
256
+ export async function compressIfNeeded(agent, threshold, callbacks, extras, signal) {
257
+ // `extras` 必填、无缺省(§2.3 的同一纪律):本函数的每一次读数与每一条门都按 `fixed` 算,
258
+ // 缺这一段即 system ∥ tools 两段记 0——读数偏低而看起来正常。缺参在 `contextUsage` 那里抛出并点名。
259
+ // 窗口 = 有效窗口(恒等于模型窗口,§2.1)——守卫、尾预算、固定开销判据都从它派生。
260
+ const ratio = tokenRatioOf(agent)
261
+ // 单源(§6.16.4):total 与 stats 面同一函数(既有内联式改调 contextUsage,判定语义零改)。
262
+ // ① 阈值早退(force 跳过)
263
+ let usage = contextUsage(agent, extras)
264
+ if (!extras.force && usage.total <= threshold) return false
265
+ // ② 固定开销单独越线(#2398 · §5):history 归零后 `total` 仍等于固定开销 ⇒ 压缩无解。强压面也不放行
266
+ // (压一次白付一次摘要请求,压完仍抛同一个错);判据窗口 = 有效窗口(§2.2)。
267
+ if (usage.fixedFloor > policyBudget(agent.provider).limit) return false
268
+ // ③ prune 一次 → 基线按 §3.1 重定(在 prune 内部)→ 重测
269
+ if (pruneStaleToolOutputs(agent).pruned > 0) usage = contextUsage(agent, extras)
270
+ // ④ 未 force 且重测后已够 ⇒ 停:prune 换来的线下,不必再付一次摘要请求
271
+ if (!extras.force && usage.total <= threshold) return false
197
272
  const tokens = usage.total
198
- if (!extras.force && tokens <= threshold) return false
199
273
 
200
- const keepTail = keepTailSize(agent.provider, history.length)
201
- const split = splitHistory(history, keepTail, tailBudgetTokens(agent.provider))
274
+ // 切点在拍平视图上算(配对修复与 `suffixTokens` 都在拍平序),保护尾由位置换算一次(§1.2)。
275
+ const flat = flattenHistory(agent.history)
276
+ const keepTail = keepTailSize(agent.provider, flat.length)
277
+ const split = splitHistory(flat, keepTail, tailBudgetTokens(agent.provider, usage.fixed - usage.compactionSummary, ratio), protectFromOf(agent, flat))
202
278
  if (!split) {
203
279
  // History is too short (≤KEEP_HEAD+keepTail+1 messages) to find a middle section, but tokens exceed threshold — typically a single giant message
204
280
  // (large paste / huge injection). When summarization has no room, degrade to deterministic shrinking to ensure context always reduces
205
281
  return shrinkOversized(agent)
206
282
  }
207
283
 
208
- const middle = history.slice(split.headEnd, split.tailStart)
284
+ const middle = flat.slice(split.headEnd, split.tailStart)
209
285
  // 可达性门(§6.17):压完落不到线下 ⇒ 不压——不为一次没有净减的摘要白付请求。`force` 全文豁免(模型主动压缩 ∥
210
286
  // 守卫强压:模型判定优先于阈值,压后仍超由守卫面抛三实数)。到不了线下的格仍由守卫 `enforceContextFit` 兜住。
287
+ // 判据的输入是 prune 之后的 `usage` 与 prune 之后的 `middle`(同一次 `splitHistory` 产出),判据本身零改。
211
288
  if (!extras.force && postCompactionTotal(agent, usage, middle) > threshold) return false
212
289
 
290
+ // 工作状态块(§6.1「消费者表」):计算点绑在可达性门之后、摘要请求之前——没压缩的回合零 I/O,
291
+ // 一次压缩只读一次盘、开一次库。第 ⑥ 步转 `compressFallback` 复用这个值,不重读;它不抛(降级给 `null`)。
292
+ const workState = await workStateBlock({ cwd: agent.cwd, boundary: agent.cwd })
293
+ // 会话头块的依赖大纲同在这一刻重建(与 workState 同一处 I/O 面:压缩之后才付这份成本)。
294
+ const outline = await sessionOutlineOf(agent)
295
+
213
296
  // Compression request form v2/v3 (§6.14 / D-CC20): continuation — same system + same tools declaration (the turn's own
214
- // array) + the middle's verbatim messages + one tail instruction. 首现即复用回合所建前缀 ⟺ 带 tools 声明(无 tool_choice)
297
+ // array) + the previous summary right after system (§6.2) + the middle's verbatim messages + one tail instruction. 首现即复用回合所建前缀 ⟺ 带 tools 声明(无 tool_choice)
215
298
  // 且 `reasoning_effort` 与回合侧同值——v2 探针复测:8 格 84–98%(读数详表见批次档 §5);不带 tools / 带 tool_choice:"none" / effort 异值 ⇒ 首现 0%(自建项复跑例外);无 extras.tools ⇒ 不发 tools。
216
299
  // ⚠️ **不带 `tool_choice`**(设计 §6.14 备选② · 预注册判定规则「S3 <0.9 且 S4 ≥0.9 ⇒ 采纳 v2 减 tool_choice」启用——实测该参数使服务端丢弃 tools 区 ⇒ 首现命中 0%)。
217
300
  // ⚠️ v3(父侧 2026-09-18 裁定):**随带与回合请求同源的 `reasoning_effort`**——下行不再覆盖 `agent.provider.reasoningEffort`(回合调用 `chat(agent.provider, …)` 同字段;
@@ -223,66 +306,111 @@ export async function compressIfNeeded(agent, threshold, callbacks, extras = {},
223
306
  // the lifecycle is surfaced, never the summary body. N = the number of history messages being summarized.
224
307
  callbacks?.onCompressStart?.({ messages: middle.length })
225
308
  const startedAt = performance.now()
226
- // F-CC2 焦点块(§6.16.2):仅模型主动面携带——追加在**指令末条尾段**(`SUMMARIZE_PROMPT` 文本零改,
227
- // 只追加焦点块;无 focus ⇒ 请求体逐字节同修前——compress-form.test.mjs 零回归)。
228
- const messages = buildCompressMessages(history, split.tailStart, extras?.systemPrompt, SUMMARIZE_PROMPT)
309
+ // F-CC2 焦点块(§6.16.2):仅模型主动面携带——追加在**指令末条尾段**(焦点块不改写 `SUMMARIZE_PROMPT` 本身,
310
+ // 只追加在指令末条;无 focus ⇒ 末条就是 `SUMMARIZE_PROMPT` 原文)。
311
+ // 累积摘要(§6.2):上一次摘要紧随 `system`、在被摘要的中段之前;首次压缩(尚无检查点)传 null,不插这一条。
312
+ // 检查点里可能是降级文本(`FALLBACK_COMPACTION_SUMMARY`)——照给、不分支(§6.2 D-3):那句说的是「那段没有摘要」,
313
+ // 是这段历史的真话;丢掉就既无原文也无交代。
314
+ // 来源面(AGENT-LOOP.md §5.5.4 读(压缩 ∥ 蒸馏请求)行):当前 provider 名与当下 spec 由本调用点显式传入,构造器不补默认。
315
+ const spec = specForModel(agent.provider?.model)
316
+ const messages = buildCompressMessages(
317
+ flat,
318
+ split.tailStart,
319
+ extras?.systemPrompt,
320
+ SUMMARIZE_PROMPT,
321
+ agent._compactCheckpoint?.compactionSummary ?? null,
322
+ agent.provider?.name,
323
+ spec,
324
+ isThinkingRequest({ ...agent.provider, thinking: null }, spec),
325
+ Array.isArray(extras?.tools) && extras.tools.length > 0,
326
+ )
229
327
  if (extras.focus) {
230
328
  const last = messages.at(-1)
231
329
  messages[messages.length - 1] = { ...last, content: last.content + focusBlock(String(extras.focus), anchorText(agent)) }
232
330
  }
233
- const summary = await chat({ ...agent.provider, thinking: null }, {
234
- messages,
235
- tools: extras?.tools,
236
- signal,
237
- // TRACES.md §6.1 D-TR4:轨迹元数据增补——kind=compress(上下文构建面——agent 元数据透出;
238
- // depth 经 extras.traceDepth——agent.mjs 主作用域传入——compress 调用点补齐)
239
- logCtx: {
240
- stage: "compress", child: agent._logId, kind: "compress",
241
- role: agent._role ?? null, depth: extras?.traceDepth ?? null,
242
- session: agent._sessionStart ?? null, cwd: agent.cwd,
243
- traces: agent.config?.traces?.enabled !== false,
244
- },
245
- })
246
-
247
- // Blank-summary guard (§6.14 退化面 3): a blank summary would land in applyCompression as
248
- // "middle dropped + empty note" and still count as success — throw into the failure chain instead.
249
- if (!summary.content?.trim()) throw new Error("compaction summary is empty")
250
-
251
- applyCompression(agent, split.headEnd, split.tailStart, COMPACTION_PREFIX + summary.content)
252
-
253
- // Completion info for the compression panel (D-C2): tokens freed = the pre-compression prompt
254
- // estimate (`tokens` — the value that tripped the threshold, incl. system/tools overhead on the
255
- // pure-estimation path) minus the post-compression estimate on the SAME basis (`contextUsage`
256
- // — a bare `estimateTokens` sum would skip the §6.17 `_tokRatio` and overstate the freed tokens).
257
- // Elapsed = the summary call + splice duration. agent.mjs forwards this to onCompress unchanged.
258
- agent._lastCompressInfo = {
259
- mode: "summary",
260
- tokensFreed: Math.max(0, Math.round(tokens - contextUsage(agent, extras).total)),
261
- elapsedMs: performance.now() - startedAt,
331
+ // ⑤ 摘要请求。失败不抛给上游(除用户中止):单次失败即发 `onCompressFail`,随后走 ⑥ 的丢弃。
332
+ let summarized = false
333
+ let summaryError = null
334
+ try {
335
+ const summary = await chat({ ...agent.provider, thinking: null }, {
336
+ messages,
337
+ tools: extras?.tools,
338
+ signal,
339
+ // TRACES.md §6.1 D-TR4:轨迹元数据增补——kind=compress(上下文构建面——agent 元数据透出;
340
+ // depth 经 extras.traceDepth——agent.mjs 主作用域传入——compress 调用点补齐)
341
+ logCtx: {
342
+ stage: "compress", child: agent._logId, kind: "compress",
343
+ role: agent._role ?? null, depth: extras?.traceDepth ?? null,
344
+ session: agent._sessionStart ?? null, cwd: agent.cwd,
345
+ traces: agent.config?.traces?.enabled !== false,
346
+ },
347
+ })
348
+ // Blank-summary guard (§6.14 退化面 3): a blank summary would land in applyCompression as
349
+ // "middle dropped + empty compaction summary" and still count as success — treat it as this call failing.
350
+ if (!summary.content?.trim()) throw new Error("compaction summary is empty")
351
+ applyCompression(agent, split.headEnd, split.tailStart, summary.content, workState, outline)
352
+ // Completion info for the compression panel (D-C2): tokens freed = the pre-compression prompt
353
+ // estimate (`tokens` — the value that tripped the threshold, incl. system/tools overhead on the
354
+ // pure-estimation path) minus the post-compression estimate on the SAME basis (`contextUsage`
355
+ // — a bare `estimateTokens` sum would skip the §6.17 `_tokRatio` and overstate the freed tokens).
356
+ // Elapsed = the summary call + splice duration. agent.mjs forwards this to onCompress unchanged.
357
+ agent._lastCompressInfo = {
358
+ mode: "summary",
359
+ tokensFreed: Math.max(0, Math.round(tokens - contextUsage(agent, extras).total)),
360
+ elapsedMs: performance.now() - startedAt,
361
+ }
362
+ summarized = true
363
+ } catch (e) {
364
+ // 用户中止不是压缩失败:原样透传(调用点据此不记账、不降级)。
365
+ if (e?.name === "AbortError" || signal?.aborted) throw e
366
+ summaryError = e
367
+ callbacks?.onCompressFail?.(e)
262
368
  }
263
- return true
369
+ // ⑥ 摘要失败,或压后仍在线上一档之上 ⇒ 丢弃(零网络、确定性),再重测。
370
+ const after = contextUsage(agent, extras)
371
+ if (!summarized || after.total > threshold) {
372
+ if (compressFallback(agent, workState, outline)) return true
373
+ // 没有中段可丢:无摘要产物,把摘要那个错交回调用点(既有失败链记一行回执)。
374
+ if (summaryError) throw summaryError
375
+ }
376
+ return summarized
264
377
  }
265
378
 
266
379
  /**
267
- * Deterministic truncation fallback: called when the summary LLM fails repeatedly, no network call.
380
+ * Deterministic truncation fallback(§5.1 第 ⑥ 步):dropped without a summary, no network call.
268
381
  * Drops the middle so the task can continue. Returns whether truncation happened.
382
+ * 丢弃要报量(§5.1):`discardedMessages` = 被丢弃的消息条数;`discardedTurns` = 其中全部记录消息都落在
383
+ * 该区间的轮次数(与 §6 的覆盖账同一本);`tailMessages` = 留下的尾部条数——只报留下的条数,读的人推不出丢了什么。
269
384
  */
270
- export function compressFallback(agent) {
271
- const keepTail = keepTailSize(agent.provider, agent.history.length)
272
- const split = splitHistory(agent.history, keepTail, tailBudgetTokens(agent.provider))
385
+ export function compressFallback(agent, workState, outline) {
386
+ assertWorkState("compressFallback", workState)
387
+ assertOutline("compressFallback", outline)
388
+ const ratio = tokenRatioOf(agent)
389
+ // 非对话面底数 = `fixed − compactionSummary`(§2.3 表 ∥ §4):压缩摘要格那一份先减掉、尾预算再按预留额加回来。
390
+ // 本函数没有 extras 形参(调用点只有同档的 `compressIfNeeded`),非对话面就取本回合暂存那一份。
391
+ const usage = contextUsage(agent, agent?._ctxBasis?.overhead ?? {})
392
+ const flat = flattenHistory(agent.history)
393
+ const keepTail = keepTailSize(agent.provider, flat.length)
394
+ const split = splitHistory(flat, keepTail, tailBudgetTokens(agent.provider, usage.fixed - usage.compactionSummary, ratio), protectFromOf(agent, flat))
273
395
  if (!split) return false
274
- const tailMessages = agent.history.length - split.tailStart
275
- applyCompression(agent, split.headEnd, split.tailStart, FALLBACK_NOTE)
276
- // Fallback completion info (D-C2): mode marks the deterministic-truncation path — the panel
277
- // shows the degradation note ("truncated to N messages") ONLY after 3 consecutive failures.
278
- agent._lastCompressInfo = { mode: "fallback", tailMessages }
396
+ const tailMessages = flat.length - split.tailStart
397
+ const discardedMessages = split.tailStart - split.headEnd
398
+ const discardedTurns = coveredTurnCount(agent, positionOf(agent.history, split.tailStart))
399
+ applyCompression(agent, split.headEnd, split.tailStart, FALLBACK_COMPACTION_SUMMARY, workState, outline)
400
+ // Fallback completion info (D-C2): mode marks the deterministic-discard path — the panel shows the
401
+ // degradation summary on the same callback, distinguished by `mode === "fallback"` alone.
402
+ agent._lastCompressInfo = { mode: "fallback", discardedMessages, discardedTurns, tailMessages }
279
403
  return true
280
404
  }
281
405
 
282
406
  // ─── 迁出面(import 面保持:TUI / verify-compress / VSC 对拍经本档取——先例 = 下方 explore-distill 再导出)──
283
407
  export { estimateTokens }
284
408
  // ─── 拆分转口(2026-10-01 拆分批 · #755 ∥ #786):写缝 ∥ 回声 ∥ 降级三面外提——消费面 / 单元测试档 import 面零改 ───
285
- export { pushReal, pushRecord } from "./context-push.mjs"
409
+ // 机读线按轮嵌套(2026-11-17):写面与装配面的全部入口经本档转出,调用方不必另记一道路径。
410
+ export {
411
+ beginTurn, pushReal, pushInject, setInject, setSessionHead, retain, pushRecord,
412
+ flattenHistory, assembleRequestMessages, flatIndexOf, positionOf, INJECT_SLOTS,
413
+ } from "./context-push.mjs"
286
414
  export { isAssistantEchoPair, mergeAdjacentAssistantEchoes } from "./context-echo.mjs"
287
415
  export { pruneStaleToolOutputs } from "./context-degrade.mjs"
288
416
  // ─── End-of-run exploration distillation(2026-09-05 module-split:524 > 500 硬限——verbatim