@thincoder/core 0.11.2 → 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 (198) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/advisor/compaction.mjs +7 -5
  3. package/advisor/history.mjs +24 -11
  4. package/advisor/loop.mjs +13 -8
  5. package/advisor/messages.mjs +72 -8
  6. package/advisor/run.mjs +24 -13
  7. package/advisor.mjs +7 -3
  8. package/agent/chat-call.mjs +14 -9
  9. package/agent/completion.mjs +28 -40
  10. package/agent/continue-decision.mjs +14 -8
  11. package/agent/digest-account.mjs +133 -59
  12. package/agent/dispatch-run.mjs +1 -1
  13. package/agent/dispatch.mjs +2 -1
  14. package/agent/family-tools.mjs +12 -13
  15. package/agent/helpers.mjs +17 -72
  16. package/agent/image-heal.mjs +18 -4
  17. package/agent/post-turn.mjs +13 -26
  18. package/agent/record-results.mjs +21 -6
  19. package/agent/run-stages.mjs +72 -37
  20. package/agent/run-start.mjs +148 -113
  21. package/agent/setup-reminders.mjs +187 -91
  22. package/agent/setup.mjs +204 -138
  23. package/agent/spawn-child.mjs +2 -2
  24. package/agent/suspension.mjs +43 -15
  25. package/agent/timers.mjs +4 -1
  26. package/agent/turn-domain-text.mjs +105 -0
  27. package/agent/turn-loop.mjs +54 -22
  28. package/agent/turn-projection.mjs +127 -227
  29. package/agent/turn-tool-process.mjs +32 -37
  30. package/agent-tools/advisor-async.mjs +6 -3
  31. package/agent-tools/advisor-launch.mjs +5 -5
  32. package/agent-tools/advisor.mjs +1 -1
  33. package/agent-tools/async-discard.mjs +7 -2
  34. package/agent-tools/async-settle.mjs +18 -12
  35. package/agent-tools/bash-async.mjs +5 -2
  36. package/agent-tools/batch-closeout.mjs +12 -62
  37. package/agent-tools/batch-ledger-bind.mjs +19 -8
  38. package/agent-tools/batch-lifecycle.mjs +37 -11
  39. package/agent-tools/batch-read.mjs +151 -4
  40. package/agent-tools/batch-record-write.mjs +5 -5
  41. package/agent-tools/batch-segment-vocab.mjs +84 -4
  42. package/agent-tools/batch-skeleton.mjs +18 -14
  43. package/agent-tools/batch-supersede.mjs +1 -1
  44. package/agent-tools/batch-tier-gate.mjs +36 -119
  45. package/agent-tools/batch.mjs +30 -20
  46. package/agent-tools/browser-async.mjs +5 -2
  47. package/agent-tools/consult.mjs +10 -7
  48. package/agent-tools/context.mjs +47 -31
  49. package/agent-tools/digest-budget.mjs +10 -9
  50. package/agent-tools/eng.mjs +3 -4
  51. package/agent-tools/escalate-async.mjs +3 -3
  52. package/agent-tools/goal.mjs +5 -2
  53. package/agent-tools/judge-domain.mjs +347 -0
  54. package/agent-tools/manifest.mjs +2 -2
  55. package/agent-tools/parent-channel.mjs +6 -3
  56. package/agent-tools/plan.mjs +11 -10
  57. package/agent-tools/review-facts.mjs +9 -3
  58. package/agent-tools/skill.mjs +7 -8
  59. package/agent-tools/spawn-gates.mjs +5 -16
  60. package/agent-tools/ssh-session.mjs +6 -3
  61. package/agent-tools/ssh-transfer.mjs +1 -1
  62. package/agent-tools/subagent-actions.mjs +2 -2
  63. package/agent-tools/subagent-async.mjs +11 -8
  64. package/agent-tools/subagent-scheduler.mjs +9 -9
  65. package/agent-tools/subagent-spawn.mjs +2 -2
  66. package/agent-tools/subagent.mjs +5 -18
  67. package/agent-tools/task.mjs +0 -8
  68. package/agent.mjs +15 -15
  69. package/auto-think.mjs +5 -2
  70. package/compaction-work-state.mjs +230 -0
  71. package/compress-form.mjs +41 -6
  72. package/config-defaults.mjs +5 -2
  73. package/config.mjs +53 -17
  74. package/context-degrade.mjs +79 -48
  75. package/context-echo.mjs +6 -26
  76. package/context-push.mjs +328 -31
  77. package/context.mjs +203 -141
  78. package/conventions.mjs +1 -1
  79. package/declaration.mjs +95 -17
  80. package/escape.mjs +6 -5
  81. package/explore-distill.mjs +35 -8
  82. package/generate-title.mjs +10 -1
  83. package/knowledge/prompt-resources.md +5 -1
  84. package/ledger-tools.mjs +50 -50
  85. package/ledger-write-ops.mjs +43 -16
  86. package/memory/docs.mjs +51 -15
  87. package/memory/file-list.mjs +6 -0
  88. package/model-specs.mjs +87 -21
  89. package/origin-guard.mjs +190 -0
  90. package/package.json +1 -1
  91. package/prompt-files.mjs +33 -11
  92. package/prompt-overlays.mjs +12 -5
  93. package/prompts/advisor-design.md +55 -36
  94. package/prompts/advisor-round1.md +18 -7
  95. package/prompts/advisor-round2.md +18 -7
  96. package/prompts/advisor-round3.md +18 -7
  97. package/prompts/common.md +89 -51
  98. package/prompts/consult-base.md +2 -3
  99. package/prompts/discipline-engineering.md +474 -440
  100. package/prompts/discipline-normal.md +107 -31
  101. package/prompts/knowledge/business-gates.md +23 -15
  102. package/prompts/knowledge/decision-quality.md +16 -18
  103. package/prompts/knowledge/doc-lookup.md +22 -27
  104. package/prompts/knowledge/document-writing.md +31 -49
  105. package/prompts/knowledge/documentation-evaluation.md +37 -45
  106. package/prompts/knowledge/evidence-discipline.md +36 -55
  107. package/prompts/knowledge/normal-coding-workflow.md +27 -21
  108. package/prompts/knowledge/normal-delivery-collaboration.md +33 -17
  109. package/prompts/knowledge/normal-work-management.md +10 -7
  110. package/prompts/knowledge/product-security.md +22 -17
  111. package/prompts/knowledge/project-records.md +63 -52
  112. package/prompts/knowledge/tool-apply-patch.md +12 -13
  113. package/prompts/knowledge/tool-bash.md +13 -4
  114. package/prompts/knowledge/tool-batch-eng-coder.md +13 -6
  115. package/prompts/knowledge/tool-batch-eng-designer.md +14 -6
  116. package/prompts/knowledge/tool-batch-review.md +12 -6
  117. package/prompts/knowledge/tool-batch.md +76 -62
  118. package/prompts/knowledge/tool-browser.md +45 -34
  119. package/prompts/knowledge/tool-context.md +2 -2
  120. package/prompts/knowledge/tool-delete.md +5 -1
  121. package/prompts/knowledge/tool-doc-check.md +25 -24
  122. package/prompts/knowledge/tool-doc-graph-read.md +3 -3
  123. package/prompts/knowledge/tool-doc-graph.md +15 -15
  124. package/prompts/knowledge/tool-edit.md +26 -23
  125. package/prompts/knowledge/tool-execute.md +9 -4
  126. package/prompts/knowledge/tool-fetch.md +7 -1
  127. package/prompts/knowledge/tool-file-ops.md +6 -1
  128. package/prompts/knowledge/tool-git-read.md +3 -1
  129. package/prompts/knowledge/tool-git.md +1 -1
  130. package/prompts/knowledge/tool-glob.md +3 -1
  131. package/prompts/knowledge/tool-grep.md +5 -2
  132. package/prompts/knowledge/tool-hashline-edit.md +4 -2
  133. package/prompts/knowledge/tool-insert-after.md +3 -1
  134. package/prompts/knowledge/tool-ledger-read.md +6 -13
  135. package/prompts/knowledge/tool-ledger.md +14 -10
  136. package/prompts/knowledge/tool-ls.md +2 -0
  137. package/prompts/knowledge/tool-manifest.md +10 -7
  138. package/prompts/knowledge/tool-memory.md +15 -11
  139. package/prompts/knowledge/tool-operations.md +59 -71
  140. package/prompts/knowledge/tool-plan.md +1 -2
  141. package/prompts/knowledge/tool-process.md +1 -1
  142. package/prompts/knowledge/tool-read-history.md +6 -7
  143. package/prompts/knowledge/tool-read.md +1 -0
  144. package/prompts/knowledge/tool-settings.md +6 -7
  145. package/prompts/knowledge/tool-ssh.md +37 -15
  146. package/prompts/knowledge/tool-subagent.md +37 -39
  147. package/prompts/knowledge/tool-task.md +3 -1
  148. package/prompts/knowledge/tool-team-ledger.md +5 -1
  149. package/prompts/knowledge/tool-tree.md +2 -0
  150. package/prompts/knowledge/tool-wait-for.md +16 -16
  151. package/prompts/knowledge/tool-write.md +4 -1
  152. package/prompts/knowledge/upstream-protocol.md +39 -37
  153. package/prompts/persona-coder.md +1 -3
  154. package/prompts/persona-eng-coder.md +5 -5
  155. package/prompts/persona-eng-designer.md +34 -17
  156. package/prompts/persona-engineering.md +532 -501
  157. package/prompts/persona-explore.md +0 -2
  158. package/prompts/persona-normal.md +17 -9
  159. package/prompts/persona-plan.md +0 -2
  160. package/prompts/persona-tester.md +0 -2
  161. package/prompts/subagent-base.md +0 -2
  162. package/provider/anthropic.mjs +4 -2
  163. package/provider/core.mjs +5 -3
  164. package/provider/errors.mjs +41 -7
  165. package/provider/google.mjs +5 -3
  166. package/provider/reasoning-echo.mjs +16 -0
  167. package/provider/responses.mjs +4 -2
  168. package/provider/sse.mjs +11 -6
  169. package/rules.mjs +11 -10
  170. package/session-lifecycle.mjs +115 -81
  171. package/session-slot-write.mjs +1 -1
  172. package/session.mjs +23 -20
  173. package/shell-identity.mjs +129 -22
  174. package/skip-dirs.mjs +24 -0
  175. package/team-ledger.mjs +22 -22
  176. package/text-budget.mjs +1 -1
  177. package/think-off.mjs +27 -0
  178. package/token-ttl.mjs +1 -1
  179. package/token-window.mjs +278 -88
  180. package/tool-docs/bash.md +0 -2
  181. package/tool-docs/consult_start.md +2 -2
  182. package/tool-docs/consult_stop.md +2 -2
  183. package/tools/browser.mjs +8 -8
  184. package/tools/execute.mjs +2 -2
  185. package/tools/file.mjs +17 -11
  186. package/tools/git.mjs +12 -12
  187. package/tools/ops.mjs +2 -2
  188. package/tools/patch.mjs +1 -1
  189. package/tools/process-doc-mark.mjs +33 -4
  190. package/tools/repomap.mjs +25 -3
  191. package/tools/search.mjs +74 -26
  192. package/tools/shared.mjs +4 -3
  193. package/tools/ssh.mjs +5 -5
  194. package/tools/tree.mjs +32 -10
  195. package/tools/web-deepseek.mjs +1 -1
  196. package/tools/web.mjs +2 -2
  197. package/tools/write-gate-params.mjs +3 -3
  198. package/window-policy.mjs +118 -78
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,39 +13,67 @@
13
13
 
14
14
  import { chat } from "./provider/index.mjs"
15
15
  import { buildCompressMessages } from "./compress-form.mjs"
16
- import { contextUsage, estimateTokens, keepTailSize, splitHistory, NOTE_ESTIMATE, rebaseMeasured, tailBudgetTokens, tokenRatioOf } from "./token-window.mjs"
17
- import { COMPACTION_PREFIX, COMPACTION_PLACEHOLDER, withPlaceholderPrefix } from "./context-echo.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"
18
28
  import { pruneStaleToolOutputs, shrinkOversized } from "./context-degrade.mjs"
19
29
  // 固定开销越线判据的另一半(#2398):`limit` 单源 = `policyBudget`(有效窗口——与守卫面同一个数)。
20
- import { policyBudget, resolveWorkMode } from "./config.mjs"
21
- // 覆盖条数(#2399):按折叠身份账算——轮投影与压缩共用同一张账,不在本档另立一份判据。
30
+ import { policyBudget } from "./config.mjs"
31
+ // 覆盖条数(#2399):按切点算——一层元素全在切点之前才算覆盖,一轮被切开不记(单源 = `turn-projection.mjs`)。
22
32
  // 保留窗起点(#2431):`splitHistory` 的必填第四参——切点一处收紧,压缩与 prune 同源受益(§1.2)。
23
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
+ }
24
49
 
25
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.
26
51
  Requirements:
27
52
  - Write in first person, present tense — these are "my" handover notes, continuing my own train of thought
28
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
29
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
30
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
31
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
32
59
  - Explicitly list UNRESOLVED ISSUES / TODOs: anything still open plus the next steps — so post-compaction recovery knows where to resume
33
60
  - Drop: pleasantries, repetition, fine-grained tool output details
34
61
  - Honestly mark uncertain items: anything not actually verified must say "unverified"; do not present guesses as facts
35
- - 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.
36
63
  `
37
64
 
38
- // 注记 + 占位的估算(§6.17 可达性门的 `note` 项 ∥ §4 减法链的末项)住 `token-window.mjs` 的 `NOTE_ESTIMATE`——
39
- // 尾预算也要用它,而本档 import 那一档(反向就会成环)。两条固定文本的单源 = `context-echo.mjs`。
65
+ // 压缩摘要的估算(可达性门的 `compactionSummary` 项 ∥ §4 减法链的末项)住 `token-window.mjs` 的
66
+ // `COMPACTION_SUMMARY_TOKEN_ESTIMATE`——尾预算也要用它,而本档 import 那一档(反向就会成环)。
67
+ // 压缩摘要的文本就是摘要正文本身(§6.1)——本档不为它拼任何固定文本;回声明占位已退场,本值不再为它留预算。
40
68
  // 残余方向:真实摘要超 1K 时本值低估 `post`(门可能放行一次压不到线下的压缩),不会反向误拦——守卫面仍抛三实数。
41
- // 另:`applyCompression` 压完还会追加任务表回注与 plan 提醒(`agent.tasks` / `planMode` 非空时),本值同样不含——
42
- // 同向低估(大任务表会话里 `post` 偏小),不会把本该压的格拦下。
69
+ // 压完之后任务表回注、plan 提醒与工作状态块住 `_inject` 的三个格,会话头块住 `agent._sessionHead`——
70
+ // 它们不靠本值计,而在 `fixed` 里(§2.5 六项之一)。
43
71
 
44
72
  /** Task re-injection reminder prefix (after compaction, clear old versions from history first for a single source of truth) */
45
73
  const TASK_REINJECT_PREFIX = "[System reminder: your current task list after compaction:"
46
74
 
47
- /** Truncation fallback note (deterministic discard, no LLM call — §5.1 第 ⑥ 步) */
48
- const FALLBACK_NOTE =
75
+ /** Truncation fallback summary (deterministic discard, no LLM call — §5.1 第 ⑥ 步) */
76
+ const FALLBACK_COMPACTION_SUMMARY =
49
77
  "[Context was truncated because summarization failed. " +
50
78
  "The middle portion of earlier work was dropped WITHOUT a summary. " +
51
79
  "Re-verify any state you need with tools before relying on it.]\n\n"
@@ -72,124 +100,126 @@ function anchorText(agent) {
72
100
  return lines.length > 0 ? lines.join("\n") : null
73
101
  }
74
102
 
75
- /** Replace middle with a note, then re-inject task/plan state (shared by LLM summary and truncation fallback) */
76
- function applyCompression(agent, headEnd, tailStart, note) {
77
- // 在途段起点(#2397):压缩重建整个机读数组,旧下标落在更短的数组上就是另一条消息——
78
- // 先记下它指向的那条消息对象,重建后按身份找回下标(CONTEXT-COMPACTION.md §1.1)。
79
- const inFlightAnchor = Number.isInteger(agent._turnStartLen) ? agent.history[agent._turnStartLen] : null
80
- // 覆盖条数(#2399):按折叠身份账算——该轮记录消息全部落在切割点之前才算覆盖(一轮被切开不记)。
81
- const turnsCovered = coveredTurnCount(agent, tailStart)
82
- // _fullHistory already holds every real message (written at the source via pushReal),
83
- // so compaction only shrinks the machine line — nothing to preserve here.
84
- // head is normally empty (KEEP_HEAD = 0) — the summary note becomes the first message,
85
- // which is exactly the intent: post-compaction context anchors on the current task, not on
86
- // possibly-completed earlier requests.
87
- const head = agent.history.slice(0, headEnd)
88
- const tail = agent.history.slice(tailStart)
89
- // 结构编辑后的实测基线(§3.1):压缩是「替换非删除」——被改的那一段 = 中段,替换后的那一段 = 注记(+ 占位)。
90
- // 编辑前的数组与它被量到的长度先记下:`_usageAtLen` 要按身份重算,不能沿用旧下标。
91
- const before = agent.history
92
- const measuredEnd = Number.isInteger(agent._usageAtLen) ? agent._usageAtLen : before.length
93
- const estBefore = estimateTokens(before.slice(headEnd, 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
- // 实测基线按 §3.1 **重定,不归零**:压缩之后恰恰是最需要准确读数的时刻,而真值要等一整次往返。
138
- // `estAfter` = 替换中段的那一段(注记 + 占位,归并支里占位并进了 `tail[0]`,不进这一段);重定本身
139
- // 放在函数尾——上面的摘旧行与回注都会挪下标,身份扫描必须在数组定形之后。
140
- const estAfter = estimateTokens(
141
- tail[0]?.role === "assistant"
142
- ? [{ role: "user", content: note }]
143
- : [{ role: "user", content: note }, { role: "assistant", content: COMPACTION_PLACEHOLDER }],
144
- )
138
+ return out
139
+ }
145
140
 
146
- // After compaction, re-inject the task list (the agent needs to know what it was doing).
147
- // Single source of truth: first remove any stale re-injections from the tail, then inject the latest version —
148
- // no longer embedded in the summary body (would duplicate and grow stale)
149
- agent.history = agent.history.filter(
150
- (m) => !(m.role === "user" && typeof m.content === "string" && m.content.startsWith(TASK_REINJECT_PREFIX))
151
- )
152
- if (agent.tasks.length > 0) {
153
- const taskSummary = agent.tasks.map((t) => `- [${t.status}] ${t.title}`).join("\n")
154
- agent.history.push({
155
- role: "user",
156
- content: `${TASK_REINJECT_PREFIX}\n${taskSummary}\nContinue from where you left off.]`,
157
- })
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}`)
158
149
  }
150
+ }
159
151
 
160
- // Plan mode compaction: re-inject plan mode guidance
161
- if (agent.planMode) {
162
- agent.history.push({
163
- role: "user",
164
- 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.]",
165
- })
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}`)
166
161
  }
162
+ }
167
163
 
168
- // 在途段起点按消息身份重定(CONTEXT-COMPACTION.md §1.1):找不回(那条已进摘要)⇒ 取注记与占位之后的第一条
169
- // 原文(= 本轮 `_runStartHistoryLen` 的口径)。终点 `_turnResponseEnd` 在轮循环返回处才采集,压缩先于它发生,不受影响。
170
- // 放在函数尾:上面的摘旧行与回注都会挪下标,重定必须在数组定形之后。
171
- if (Number.isInteger(agent._turnStartLen)) {
172
- const at = inFlightAnchor ? agent.history.indexOf(inFlightAnchor) : -1
173
- agent._turnStartLen = at >= 0 ? at : agent._runStartHistoryLen
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) })
174
204
  }
175
205
  // 压缩成果落内存载体(#2399):槽保存取它、恢复播种取它(SESSION.md §2 ∥ CONTEXT-COMPACTION.md §6)。
176
- agent._compactCheckpoint = { note, turnsCovered }
177
- // §3.1 基线重定(数组已定形):中段换成注记,`measuredEnd` 之后的消息从没被量过,故只按身份找
178
- // 「旧前缀最后一个还在线上的消息」,其后第一个下标就是新的 `_usageAtLen`。
206
+ agent._compactCheckpoint = { compactionSummary, turnsCovered }
207
+ // §3.1 基线重定(结构已定形):中段被摘要取走,`measuredEnd` 之后的消息从没被量过,故只按身份找
208
+ // 「旧前缀最后一个还在线上的消息」,其后第一个位置就是新的 `_usageAt`。
179
209
  rebaseMeasured(agent, estBefore, estAfter, { before, measuredEnd })
180
210
  }
181
211
 
182
212
  /**
183
213
  * 可达性门(CONTEXT-COMPACTION.md §6.17「压缩触发判据(可达性门)」):压完之后 `total` 能不能落到阈值之下。
184
- * `post` 按 `applyCompression` 实际留下的形态估——head(KEEP_HEAD = 0 ⇒ 恒空)+ 注记 + 占位 + tail;`middle` = 本次会摘掉的
185
- * 那段(与本次压缩同一次 `splitHistory` 产出)。压缩后 `_lastPromptTokens` 失效 ⇒ 只有估算支可比,故走 estimated 支并乘同一
186
- * `_tokRatio`(与 `contextUsage` 的估算支同尺)。
187
- * 为什么要有它:`system + tools` 是固定开销、压不掉,把它算进判据左侧会让「固定开销本身逼近阈值」的会话反复触发压缩却压不出
188
- * 任何东西——每触发一次白付一次摘要请求(台账 `#1833`)。
214
+ * `post` 按 §2.5 的同一个测度估:对话面只留 tail、非对话面是 `fixed − compactionSummary` 加压缩摘要预留额。`middle` = 本次会摘掉的
215
+ * 那段(与本次压缩同一次 `splitHistory` 产出)。压缩后 `_lastPromptTokens` 失效 ⇒ 只有估算支可比,故走 estimated 支
216
+ * 并乘同一 `_tokRatio`(与 `contextUsage` 的估算支同尺)。
217
+ * 为什么要有它:非对话面是固定开销、压不掉,把它算进判据左侧会让「固定开销本身逼近阈值」的会话反复触发压缩却
218
+ * 压不出任何东西——每触发一次白付一次摘要请求(台账 `#1833`)。
189
219
  */
190
220
  function postCompactionTotal(agent, usage, middle) {
191
- const ratio = agent?._tokRatio ?? 1
192
- 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)
193
223
  }
194
224
 
195
225
  /**
@@ -207,8 +237,8 @@ function postCompactionTotal(agent, usage, middle) {
207
237
  * ```
208
238
  *
209
239
  * `force` 面也 prune,但不因 prune 就早退,也不因 ④ 就停:`/compact` 与越窗自愈要的是一次真实的压缩动作,
210
- * prune 只让中段变小、摘要请求更省。第 ③ 步的射程:合格集非空的只有 §7.2 列的那两类状态(尚无一条轮记录带
211
- * `toolProcess` ∥ 由 `history` 播种的旧槽);其余状态下 `tool` 消息全在保留窗内、因而全在保护尾里,prune 返回
240
+ * prune 只让中段变小、摘要请求更省。第 ③ 步的射程:合格集非空的只有 §7.2 列的那三类状态(已登记轮不足窗宽∥
241
+ * 本批之前的旧槽——消息上没有 `turn` ∥ 窗内那几轮在线上一条不剩);其余状态下 `tool` 消息全在保留窗内、因而全在保护尾里,prune 返回
212
242
  * 0 条——③ 是一步 no-op,常见路径的成本落在 ⑤。
213
243
  *
214
244
  * 返回是否发生了压缩(摘要成功 ∥ 弃真的发生)。摘要失败一次就走到丢弃,不等连续失败——「一次网络抖动换一个
@@ -223,9 +253,10 @@ function postCompactionTotal(agent, usage, middle) {
223
253
  * 可达性门的 `post > threshold`),其余全同(同切分 / 同尾部预算 / 同摘要链 / 同回注 / 同基线重定);
224
254
  * `focus` 追加在摘要指令尾段。
225
255
  */
226
- export async function compressIfNeeded(agent, threshold, callbacks, extras = {}, signal) {
227
- // 档位 = 本 run 的策略输入(§2.3 握有 agent 的面自取):守卫、尾预算、固定开销判据全从它派生有效窗口。
228
- const workMode = resolveWorkMode(agent.config?.agent)
256
+ export async function compressIfNeeded(agent, threshold, callbacks, extras, signal) {
257
+ // `extras` 必填、无缺省(§2.3 的同一纪律):本函数的每一次读数与每一条门都按 `fixed` 算,
258
+ // 缺这一段即 system ∥ tools 两段记 0——读数偏低而看起来正常。缺参在 `contextUsage` 那里抛出并点名。
259
+ // 窗口 = 有效窗口(恒等于模型窗口,§2.1)——守卫、尾预算、固定开销判据都从它派生。
229
260
  const ratio = tokenRatioOf(agent)
230
261
  // 单源(§6.16.4):total 与 stats 面同一函数(既有内联式改调 contextUsage,判定语义零改)。
231
262
  // ① 阈值早退(force 跳过)
@@ -233,29 +264,37 @@ export async function compressIfNeeded(agent, threshold, callbacks, extras = {},
233
264
  if (!extras.force && usage.total <= threshold) return false
234
265
  // ② 固定开销单独越线(#2398 · §5):history 归零后 `total` 仍等于固定开销 ⇒ 压缩无解。强压面也不放行
235
266
  // (压一次白付一次摘要请求,压完仍抛同一个错);判据窗口 = 有效窗口(§2.2)。
236
- if (usage.fixedFloor > policyBudget(agent.provider, undefined, workMode).limit) return false
267
+ if (usage.fixedFloor > policyBudget(agent.provider).limit) return false
237
268
  // ③ prune 一次 → 基线按 §3.1 重定(在 prune 内部)→ 重测
238
269
  if (pruneStaleToolOutputs(agent).pruned > 0) usage = contextUsage(agent, extras)
239
270
  // ④ 未 force 且重测后已够 ⇒ 停:prune 换来的线下,不必再付一次摘要请求
240
271
  if (!extras.force && usage.total <= threshold) return false
241
272
  const tokens = usage.total
242
273
 
243
- const keepTail = keepTailSize(agent.provider, agent.history.length, workMode)
244
- const split = splitHistory(agent.history, keepTail, tailBudgetTokens(agent.provider, workMode, usage.overhead, ratio), retentionWindowStart(agent))
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))
245
278
  if (!split) {
246
279
  // History is too short (≤KEEP_HEAD+keepTail+1 messages) to find a middle section, but tokens exceed threshold — typically a single giant message
247
280
  // (large paste / huge injection). When summarization has no room, degrade to deterministic shrinking to ensure context always reduces
248
281
  return shrinkOversized(agent)
249
282
  }
250
283
 
251
- const middle = agent.history.slice(split.headEnd, split.tailStart)
284
+ const middle = flat.slice(split.headEnd, split.tailStart)
252
285
  // 可达性门(§6.17):压完落不到线下 ⇒ 不压——不为一次没有净减的摘要白付请求。`force` 全文豁免(模型主动压缩 ∥
253
286
  // 守卫强压:模型判定优先于阈值,压后仍超由守卫面抛三实数)。到不了线下的格仍由守卫 `enforceContextFit` 兜住。
254
287
  // 判据的输入是 prune 之后的 `usage` 与 prune 之后的 `middle`(同一次 `splitHistory` 产出),判据本身零改。
255
288
  if (!extras.force && postCompactionTotal(agent, usage, middle) > threshold) return false
256
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
+
257
296
  // Compression request form v2/v3 (§6.14 / D-CC20): continuation — same system + same tools declaration (the turn's own
258
- // 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)
259
298
  // 且 `reasoning_effort` 与回合侧同值——v2 探针复测:8 格 84–98%(读数详表见批次档 §5);不带 tools / 带 tool_choice:"none" / effort 异值 ⇒ 首现 0%(自建项复跑例外);无 extras.tools ⇒ 不发 tools。
260
299
  // ⚠️ **不带 `tool_choice`**(设计 §6.14 备选② · 预注册判定规则「S3 <0.9 且 S4 ≥0.9 ⇒ 采纳 v2 减 tool_choice」启用——实测该参数使服务端丢弃 tools 区 ⇒ 首现命中 0%)。
261
300
  // ⚠️ v3(父侧 2026-09-18 裁定):**随带与回合请求同源的 `reasoning_effort`**——下行不再覆盖 `agent.provider.reasoningEffort`(回合调用 `chat(agent.provider, …)` 同字段;
@@ -267,9 +306,24 @@ export async function compressIfNeeded(agent, threshold, callbacks, extras = {},
267
306
  // the lifecycle is surfaced, never the summary body. N = the number of history messages being summarized.
268
307
  callbacks?.onCompressStart?.({ messages: middle.length })
269
308
  const startedAt = performance.now()
270
- // F-CC2 焦点块(§6.16.2):仅模型主动面携带——追加在**指令末条尾段**(`SUMMARIZE_PROMPT` 文本零改,
271
- // 只追加焦点块;无 focus ⇒ 请求体逐字节同修前——compress-form.test.mjs 零回归)。
272
- const messages = buildCompressMessages(agent.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
+ )
273
327
  if (extras.focus) {
274
328
  const last = messages.at(-1)
275
329
  messages[messages.length - 1] = { ...last, content: last.content + focusBlock(String(extras.focus), anchorText(agent)) }
@@ -292,9 +346,9 @@ export async function compressIfNeeded(agent, threshold, callbacks, extras = {},
292
346
  },
293
347
  })
294
348
  // Blank-summary guard (§6.14 退化面 3): a blank summary would land in applyCompression as
295
- // "middle dropped + empty note" and still count as success — treat it as this call failing.
349
+ // "middle dropped + empty compaction summary" and still count as success — treat it as this call failing.
296
350
  if (!summary.content?.trim()) throw new Error("compaction summary is empty")
297
- applyCompression(agent, split.headEnd, split.tailStart, COMPACTION_PREFIX + summary.content)
351
+ applyCompression(agent, split.headEnd, split.tailStart, summary.content, workState, outline)
298
352
  // Completion info for the compression panel (D-C2): tokens freed = the pre-compression prompt
299
353
  // estimate (`tokens` — the value that tripped the threshold, incl. system/tools overhead on the
300
354
  // pure-estimation path) minus the post-compression estimate on the SAME basis (`contextUsage`
@@ -315,7 +369,7 @@ export async function compressIfNeeded(agent, threshold, callbacks, extras = {},
315
369
  // ⑥ 摘要失败,或压后仍在线上一档之上 ⇒ 丢弃(零网络、确定性),再重测。
316
370
  const after = contextUsage(agent, extras)
317
371
  if (!summarized || after.total > threshold) {
318
- if (compressFallback(agent)) return true
372
+ if (compressFallback(agent, workState, outline)) return true
319
373
  // 没有中段可丢:无摘要产物,把摘要那个错交回调用点(既有失败链记一行回执)。
320
374
  if (summaryError) throw summaryError
321
375
  }
@@ -328,19 +382,23 @@ export async function compressIfNeeded(agent, threshold, callbacks, extras = {},
328
382
  * 丢弃要报量(§5.1):`discardedMessages` = 被丢弃的消息条数;`discardedTurns` = 其中全部记录消息都落在
329
383
  * 该区间的轮次数(与 §6 的覆盖账同一本);`tailMessages` = 留下的尾部条数——只报留下的条数,读的人推不出丢了什么。
330
384
  */
331
- export function compressFallback(agent) {
332
- const workMode = resolveWorkMode(agent.config?.agent)
385
+ export function compressFallback(agent, workState, outline) {
386
+ assertWorkState("compressFallback", workState)
387
+ assertOutline("compressFallback", outline)
333
388
  const ratio = tokenRatioOf(agent)
334
- const overhead = contextUsage(agent).overhead
335
- const keepTail = keepTailSize(agent.provider, agent.history.length, workMode)
336
- const split = splitHistory(agent.history, keepTail, tailBudgetTokens(agent.provider, workMode, overhead, ratio), retentionWindowStart(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))
337
395
  if (!split) return false
338
- const tailMessages = agent.history.length - split.tailStart
396
+ const tailMessages = flat.length - split.tailStart
339
397
  const discardedMessages = split.tailStart - split.headEnd
340
- const discardedTurns = coveredTurnCount(agent, split.tailStart)
341
- applyCompression(agent, split.headEnd, split.tailStart, FALLBACK_NOTE)
398
+ const discardedTurns = coveredTurnCount(agent, positionOf(agent.history, split.tailStart))
399
+ applyCompression(agent, split.headEnd, split.tailStart, FALLBACK_COMPACTION_SUMMARY, workState, outline)
342
400
  // Fallback completion info (D-C2): mode marks the deterministic-discard path — the panel shows the
343
- // degradation note on the same callback, distinguished by `mode === "fallback"` alone.
401
+ // degradation summary on the same callback, distinguished by `mode === "fallback"` alone.
344
402
  agent._lastCompressInfo = { mode: "fallback", discardedMessages, discardedTurns, tailMessages }
345
403
  return true
346
404
  }
@@ -348,7 +406,11 @@ export function compressFallback(agent) {
348
406
  // ─── 迁出面(import 面保持:TUI / verify-compress / VSC 对拍经本档取——先例 = 下方 explore-distill 再导出)──
349
407
  export { estimateTokens }
350
408
  // ─── 拆分转口(2026-10-01 拆分批 · #755 ∥ #786):写缝 ∥ 回声 ∥ 降级三面外提——消费面 / 单元测试档 import 面零改 ───
351
- 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"
352
414
  export { isAssistantEchoPair, mergeAdjacentAssistantEchoes } from "./context-echo.mjs"
353
415
  export { pruneStaleToolOutputs } from "./context-degrade.mjs"
354
416
  // ─── End-of-run exploration distillation(2026-09-05 module-split:524 > 500 硬限——verbatim
package/conventions.mjs CHANGED
@@ -191,4 +191,4 @@ export function isStatePath(p, conv) {
191
191
  // 迁出面(2026-10-01 拆分批 · #755 ∥ #786):声明装载面外提 `declaration.mjs`——本档经
192
192
  // 转口保名(消费面 / 单元测试档 import 面零改;`DEFAULT_DECLARATION` 另供本档分类裁判缺省取用)。
193
193
  // ─────────────────────────────────────────────────────────────────────────────
194
- export { loadProjectDeclaration, declarationForTarget, DEFAULT_DECLARATION, isExcludedRelPath, declaredIndexScope, isInDeclaredScope, declaredPublicRoots, declaredWritableRoots, clearDeclarationCache } from "./declaration.mjs"
194
+ export { loadProjectDeclaration, declarationForTarget, DEFAULT_DECLARATION, isExcludedRelPath, declaredIndexScope, isInDeclaredScope, declaredPublicRoots, declaredWritableRoots, clearDeclarationCache, docLayers, docLayerOf } from "./declaration.mjs"