@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
@@ -0,0 +1,230 @@
1
+ /**
2
+ * compaction-work-state.mjs — 压缩后回注的「在飞工作状态」块(设计单源 = `docs/core/design/CONTEXT-COMPACTION.md` §6.1)。
3
+ *
4
+ * 机制:压缩落地那一刻,把「有哪些活在飞、去哪儿读它们」按固定形收成一条 `user` 消息,注进机读线末尾
5
+ * (注入点、顺序与滤旧 = `context.mjs` 的 `reinjectAfterCompaction`)。块只给指针——批档的项目根相对路径
6
+ * 与 `§1` 已定决定摘录、台账的行号与标题与状态;未决项的正文留在盘上那两份事实源里,按路径读。
7
+ *
8
+ * 两种载体各担一半(§6.1):摘要是模型写的,写漏了就是漏了;回注是机制写的,只要压缩发生就一定有。
9
+ * 块不落槽(§6.1「不落槽」):它随上次压缩的那条机读线走,内容由批档与台账现读得出,下一次压缩重新生成。
10
+ *
11
+ * **降级三环**(§6.1「降级」):读台账这一面失败 ⇒ 返回 `null` ⇒ 整块不出现,压缩照常完成;每环留一行
12
+ * `compaction:work-state-skip` 痕(核日志单一通道 `logEvent`,`reason` 三值)。三环 = 推不出项目根
13
+ * (manifest 读不到并进这一环:没有 manifest 就没有项目根)· `openLedger` 抛错 · `node:sqlite` 动态 import 失败。
14
+ *
15
+ * 批档面读不到**不作降级**(§6.1「批档面读不到不作降级」):`batchDirs` 与 `collectMarkdownFiles` 对声明面与
16
+ * 目录的读失败都是刻意不停机(`doc_check` 的既有口径),块跟同一口径,按零本批档处理、块照出。
17
+ * 库不在盘是**空账不是失败**(`openLedger` 读面返回 `null` ⇒ `ledgerQuery` 返回 `[]`),块照出、只少台账行。
18
+ *
19
+ * 读面(§6.1「读面与单源」,都是既有面,不另立):批档目录 = `batchDirs` · 批档枚举 =
20
+ * `collectMarkdownFiles` + `readBatchStatusLine === "open"` · 在途台账行 = `ledgerQuery` 按 `PENDING_STATUSES` 筛。
21
+ * 两个 import 面**都走动态 import**:台账链是 `ledger-db.mjs` 静态引 `node:sqlite`(W8 契约②);批档枚举是
22
+ * `batch-lifecycle.mjs` 牵进 `design-slots → advisor-async → agent/loop` 那条既有环(`loadBatchFace` 有实测)。
23
+ * `readBatchStatusLine` 与 `batchDirs` 两个轻面静态引——它们不触那条环。
24
+ */
25
+ import { readFileSync } from "node:fs"
26
+ import { relative, sep } from "node:path"
27
+
28
+ import { readBatchStatusLine } from "./agent-tools/batch-skeleton.mjs"
29
+ import { batchDirs } from "./doc-check/existence.mjs"
30
+ import { logEvent } from "./log.mjs"
31
+
32
+ /** 回注块前缀(生成面单源;同一段住 A 段的 `work-state` 那一格,写即覆盖——不再需要「注入前滤旧版」)。 */
33
+ export const WORK_STATE_REINJECT_PREFIX = "[System reminder: work in flight at the moment of compaction:"
34
+
35
+ /** 整块硬上界(字符)。2000 字符 ≈ 500 render token,压在摘要自身 1K 目标的一半以下(§6.1「有界」)。 */
36
+ export const WORK_STATE_MAX_CHARS = 2000
37
+
38
+ /** 条目行单行上界(字符):一条台账行、一条无已定决定的批档行各自受它管。 */
39
+ export const WORK_STATE_LINE_CHARS = 240
40
+
41
+ /** 块尾行(零条时正文只有首行与它)——它的 `]` 收掉首行那个方括号。 */
42
+ const FOOTER_LINE = "Continue from where you left off; read the batch record before acting on these.]"
43
+
44
+ /** `§1` 已定决定的固定形(提示词层面写死的那一行:决定 · 依据 · 时间),取到 `·` 之前即决定本身。 */
45
+ const DECIDED_RULING_RE = /^\s*-\s*\*\*已定决定\*\*\s*[::]?\s*(.*)$/
46
+
47
+ /** 条目行最多带两条已定决定(§6.1「块的形状」:`<最多两条>`;超出部分报条数、正文读档)。 */
48
+ const RULINGS_SHOWN = 2
49
+
50
+ /** 第二档收紧下标题截到的长度:单行界的四分之一——同一把尺的子段,不是新立的量。 */
51
+ const TITLE_TIGHT_CHARS = Math.floor(WORK_STATE_LINE_CHARS / 4)
52
+
53
+ /** 降级留痕:一行 `compaction:work-state-skip` + 该环的 `reason`,返回 `null`(整块不出现)。 */
54
+ function skip(reason) {
55
+ logEvent("compaction:work-state-skip", { reason })
56
+ return null
57
+ }
58
+
59
+ /** 收行:超界即截并留 `…` 标记——截断必须带标记,读的人才分得清「就这些」与「被砍过」(§1.2 同一条)。 */
60
+ const cutLine = (text, max = WORK_STATE_LINE_CHARS) => (text.length <= max ? text : `${text.slice(0, Math.max(0, max - 1))}…`)
61
+
62
+ /** 台账链(动态 import 的入口):根推导 / 未决四态 / 查询三面同源于 `ledger-db.mjs` 与 `ledger-cmd.mjs`。 */
63
+ async function loadLedgerFace() {
64
+ const db = await import("./ledger-db.mjs")
65
+ const cmd = await import("./ledger-cmd.mjs")
66
+ return { rootOf: db.resolveLedgerRoot, pendingStatuses: db.PENDING_STATUSES, query: cmd.ledgerQuery }
67
+ }
68
+
69
+ /**
70
+ * 批档枚举面(动态 import,与台账那条并列):`batch-lifecycle.mjs` 沿 `design-slots → advisor-async → agent/loop`
71
+ * 牵进那条既有环(`agent/loop.mjs` 带顶层 `await import`),而本档被 `context.mjs` 静态 import——静态引进来就把
72
+ * 整条 `context.mjs` 加载链拖进环里死锁(实测:`import("thincoder-core/context.mjs")` 永不落定)。
73
+ * 故只有 `collectMarkdownFiles` 走这一面;`readBatchStatusLine` 与 `batchDirs` 两个轻面静态引。
74
+ */
75
+ async function loadBatchFace() {
76
+ const { collectMarkdownFiles } = await import("./agent-tools/batch-lifecycle.mjs")
77
+ return { walk: collectMarkdownFiles }
78
+ }
79
+
80
+ /**
81
+ * `§1` 的已定决定摘录(§6.1「读面与单源」的切片规则):自 `## §1` 起、到下一个 `## §` 止,
82
+ * 取以 `- **已定决定**` 起头的行、取到 `·` 之前。顺序 = 文档顺序(首现优先)。
83
+ * @param {string} src 批档全文
84
+ * @returns {string[]} 决定文本(空行已滤)
85
+ */
86
+ function decidedRulingsOf(src) {
87
+ const head = /^## §1(?=\s|$)/m.exec(src)
88
+ if (!head) return []
89
+ const rest = src.slice(head.index + head[0].length)
90
+ const next = rest.search(/^## §/m)
91
+ const body = next < 0 ? rest : rest.slice(0, next)
92
+ const out = []
93
+ for (const line of body.split(/\r?\n/)) {
94
+ const m = DECIDED_RULING_RE.exec(line)
95
+ if (!m) continue
96
+ const ruling = m[1].split("·")[0].trim()
97
+ if (ruling !== "") out.push(ruling)
98
+ }
99
+ return out
100
+ }
101
+
102
+ /**
103
+ * 在飞批档(§6.1「读面与单源」):每个批档根下递归的 `*.md`,`§1` 状态行判 `open` 的收。
104
+ * 读不到的目录 / 读不到的档各自跳过(`collectMarkdownFiles` 对读不到的目录吞成空集)——批档面不作降级。
105
+ * @param {string} root 项目根
106
+ * @param {(dir: string) => string[]} walk 目录枚举面(`collectMarkdownFiles`,动态 import 取得)
107
+ * @returns {{path: string, rulings: string[]}[]} 项目根相对路径(`/` 分隔)+ 该档 `§1` 的已定决定
108
+ */
109
+ function inFlightBatches(root, walk) {
110
+ const out = []
111
+ for (const dir of batchDirs(root)) {
112
+ for (const abs of walk(dir)) {
113
+ let src
114
+ try { src = readFileSync(abs, "utf8") } catch { continue }
115
+ if (readBatchStatusLine(src) !== "open") continue
116
+ out.push({ path: relative(root, abs).split(sep).join("/"), rulings: decidedRulingsOf(src) })
117
+ }
118
+ }
119
+ return out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
120
+ }
121
+
122
+ /**
123
+ * 超界时先收尾部说明、保留行首路径(单行界的「谁让位」规则:路径是继续点,让位的是说明);
124
+ * 路径自己就装不下时(极少见)才切路径。说明(`N 条已省略,读档`)不能放在行尾等着被切——
125
+ * 「零静默截断」靠它。
126
+ */
127
+ function pathThenNote(pathHead, note, max = WORK_STATE_LINE_CHARS) {
128
+ if (pathHead.length + note.length <= max) return pathHead + note
129
+ const room = max - note.length
130
+ return room > 1 ? `${pathHead.slice(0, room - 1)}…${note}` : note.slice(0, max)
131
+ }
132
+
133
+ /**
134
+ * 批档行。带已定决定的那一行不受单行界管(§6.1「有界」:它由整块上限承担),
135
+ * 两条决定各自受 `WORK_STATE_LINE_CHARS` 约束;无决定的那一行与台账行同档,受单行界。
136
+ * `tight >= 1` 是第一档收紧:已定决定整段省略、只报条数(越限收紧次序的第一项)。
137
+ */
138
+ function batchLineOf(entry, tight) {
139
+ const head = `· batch ${entry.path}`
140
+ if (entry.rulings.length === 0) return cutLine(head)
141
+ if (tight >= 1) return pathThenNote(head, ` — §1 已定决定:${entry.rulings.length} 条已省略,读档`)
142
+ const shown = entry.rulings.slice(0, RULINGS_SHOWN).map((ruling) => cutLine(ruling))
143
+ const more = entry.rulings.length - shown.length
144
+ return `${head} — §1 已定决定:${shown.join(" · ")}${more > 0 ? `(另 ${more} 条读档)` : ""}`
145
+ }
146
+
147
+ /**
148
+ * 台账行。`tight >= 2` 是第二档收紧(台账行标题截短),`tight >= 3` 是第三档(只留批档与台账号)。
149
+ * **让位次序 = 标题先让、路径后让**(§6.1「有界」的「已定决定摘要 → 台账行标题 → 只留批档与台账号」):
150
+ * 行界不够时先收标题并留 `…`,`— batch <路径>` 这一段是继续点,不让它被行尾截掉;
151
+ * 第三档把标题整条让位、但仍留一个 `…`——读的人分得清「本来没有标题」与「标题被收紧掉」。
152
+ * 行挂哪本批档 = 行自己的 `task_book` 列原样(项目根相对路径);空 ⇒ `无批档`。
153
+ */
154
+ function ledgerLineOf(row, tight) {
155
+ const where = row.task_book ? String(row.task_book) : "无批档"
156
+ const head = `· ledger #${row.id} [${row.status}]`
157
+ const tail = ` — batch ${where}`
158
+ const fullTitle = String(row.title ?? "")
159
+ const budget = Math.max(0, WORK_STATE_LINE_CHARS - head.length - tail.length - 1)
160
+ if (tight >= 3) return cutLine(`${head}${fullTitle === "" || budget === 0 ? "" : " …"}${tail}`)
161
+ const title = fullTitle === "" ? "" : ` ${cutLine(fullTitle, tight >= 2 ? Math.min(TITLE_TIGHT_CHARS, budget) : budget)}`
162
+ return cutLine(`${head}${title}${tail}`)
163
+ }
164
+
165
+ /** 按某一档收紧渲染整块;`dropTail > 0` 时从尾部整条丢,并把丢掉的条数写进块里(零静默截断)。 */
166
+ function render(entries, tight, dropTail = 0) {
167
+ const kept = entries.slice(0, Math.max(0, entries.length - dropTail))
168
+ const lines = kept.map((e) => (e.kind === "batch" ? batchLineOf(e, tight) : ledgerLineOf(e, tight)))
169
+ if (dropTail > 0) lines.push(`· … 另省略 ${dropTail} 条`)
170
+ return [WORK_STATE_REINJECT_PREFIX, ...lines, FOOTER_LINE].join("\n")
171
+ }
172
+
173
+ /**
174
+ * 块装配(§6.1「块的形状」+「有界」):越限的收紧次序 = 已定决定摘要 → 台账行标题 → 只留批档与台账号,
175
+ * 三档都收紧完仍越界才从尾部整条丢(写出省略条数)。零条 ⇒ 正文只有首行与尾行(块照出——`null` 已被
176
+ * 「读失败」占用,零条若也返回 `null`,读的人分不出「读了、没有」与「没读到」)。
177
+ */
178
+ function assembleBlock(batches, rows) {
179
+ const entries = [
180
+ ...batches.map((b) => ({ kind: "batch", path: b.path, rulings: b.rulings })),
181
+ ...rows.map((r) => ({ kind: "ledger", id: r.id, status: r.status, title: r.title, task_book: r.task_book })),
182
+ ]
183
+ for (let tight = 0; tight <= 3; tight++) {
184
+ const text = render(entries, tight)
185
+ if (text.length <= WORK_STATE_MAX_CHARS) return text
186
+ }
187
+ for (let dropTail = 1; dropTail <= entries.length; dropTail++) {
188
+ const text = render(entries, 3, dropTail)
189
+ if (text.length <= WORK_STATE_MAX_CHARS) return text
190
+ }
191
+ // 兜底(当前不可达):条目逐条丢完时只剩首尾两行——此时没有条目可报,也就不存在「省了几条」。
192
+ return [WORK_STATE_REINJECT_PREFIX, FOOTER_LINE].join("\n")
193
+ }
194
+
195
+ /**
196
+ * 生成回注块(§6.1「契约」):成功给整块文本,降级给 `null`;**不抛**——抛就是把可选事实源的失败
197
+ * 升级成压缩失败,而压缩是内存里的救火动作。
198
+ * 两个坐标(§6.1 消费者表):`cwd` = 推导项目根的起点,`boundary` = 会话锚(上溯上界);默认场景下同值
199
+ * (都是 `agent.cwd`)。块只在会话锚就是项目根时出得来(`owningProject` 起点即停),锚落在项目内层子目录时
200
+ * 落进「推不出项目根」那一环——这是与台账工具面同一条既有约束。
201
+ * @param {{cwd?: string, boundary?: string}} coords
202
+ * @returns {Promise<string|null>}
203
+ */
204
+ export async function workStateBlock({ cwd, boundary } = {}) {
205
+ // 锚缺席与「没有 manifest」是同一个谓词的两面:没有起点就没有上溯,推不出项目根。
206
+ if (typeof cwd !== "string" || cwd === "" || typeof boundary !== "string" || boundary === "") return skip("no-project-root")
207
+ let face
208
+ try {
209
+ face = await loadLedgerFace()
210
+ } catch {
211
+ return skip("sqlite-import-failed")
212
+ }
213
+ const derived = face.rootOf(cwd, boundary)
214
+ if (!derived) return skip("no-project-root")
215
+ let rows
216
+ try {
217
+ rows = face.query({ cwd, boundary })
218
+ } catch {
219
+ return skip("ledger-open-failed")
220
+ }
221
+ const pending = rows.filter((row) => face.pendingStatuses.includes(row.status))
222
+ // 批档面不作降级:这一面的加载失败按零本批档处理,块照出、只少批档行(§6.1「降级」)。
223
+ let walk = () => []
224
+ try {
225
+ walk = (await loadBatchFace()).walk
226
+ } catch {
227
+ walk = () => []
228
+ }
229
+ return assembleBlock(inFlightBatches(derived.root, walk), pending)
230
+ }
package/compress-form.mjs CHANGED
@@ -2,23 +2,58 @@
2
2
  * compress-form.mjs — compression request form(CONTEXT-COMPACTION.md §6.14 / D-CC20 ·
3
3
  * 批次档 2026-09-18-compression-continuation §2.2):会话续写形态。
4
4
  *
5
- * 压缩请求复用同会话回合请求的消息前缀(同一个 system + 中段「真身」消息),尾部附加指令一条。
5
+ * 压缩请求复用同会话回合请求的消息前缀(同一个 system + 中段「真身」消息),尾部附加指令一条;
6
+ * 压缩面另把上一次摘要插在 system 之后(§6.2),蒸馏面传 null 不带。
6
7
  * 消费点(两处同形 · 同一构造):① 压缩 = `context.mjs`(中段切点 = `splitHistory.tailStart`);
7
- * ② 蒸馏 = `explore-distill.mjs`(切点 = 本 run 末块 `end` → §6.15)——两处均按引用原样携带中段,
8
+ * ② 蒸馏 = `explore-distill.mjs`(切点 = 本 run 末块 `end` → §6.15)——两处均按引用携带未改中段,
8
9
  * 均不持声明面(`tools` / `systemPrompt` 由调用点经 extras 随带)。
9
10
  *
11
+ * 累积摘要(§6.2):上一次摘要作为**独立一条 `user` 消息**插在 `system` 之后、中段第一条之前——
12
+ * 中段因此逐字不动(并进中段首条就得改写它:`tool` 结果会破坏配对,`assistant` 会把「这是上一次
13
+ * 摘要」与一条被引用的历史混成同一条消息)。`null` = 首次压缩,不插这一条。`systemPrompt` 缺省/空串
14
+ * (退化面 1)时摘要即请求首条消息——它仍在中段之前,位置语义不变。它只增加摘要调用这一次
15
+ * 的输入,不进压缩链的任何预算算式。上一份摘要没有说明前缀:格里就是摘要正文本身(§6.1)。
16
+ *
10
17
  * ⚠️ 缓存命中口径(v2 探针复测 2026-09-18 · 批次档 §5):压缩形态**首现复用回合所建前缀**的条件 = 带 tools 声明
11
18
  * (**不带** `tool_choice`)且 `reasoning_effort` 同值——8 格 84–98%;不带 tools / 带 `tool_choice:"none"`(该参数使
12
19
  * 服务端丢弃 tools 区)/ effort 异值 ⇒ 首现 0%(自建项复跑命中为例外)。v2(设计档 §6.14 备选②)由**调用点**
13
20
  * (context.mjs)随带与回合请求同一数组的 `tools`;本模块只构消息序,不持声明面。
14
21
  *
15
- * 纯函数、零 import:指令文本由实参传入(SUMMARIZE_PROMPT 住 context.mjs——不反向 import,免成环)。
16
- * 中段消息按引用原样携带(不拷贝 / 不截断);切点与摘要段同源(split.tailStart),不新增第二处切割判据。
22
+ * 纯函数面(不替调用方补默认、零网络调用;隔离读数为零时不写事件,`logEvent` 静默降级):指令文本由实参传入
23
+ * (`SUMMARIZE_PROMPT` 住 context.mjs——不反向 import,免成环)。本档的 import 只到 `origin-guard.mjs` 这个叶子档
24
+ * (跨 provider 历史的判据单源 = `quarantineForeignOrigin` / `logOriginQuarantine`;见 `docs/core/design/AGENT-LOOP.md` §5.5.4 读点)。
25
+ * 中段经完整历史隔离后有正文保留、纯工具空轮退出;未改消息按引用带入。切点与摘要段同源(split.tailStart)。
26
+ *
27
+ * 来源面(§5.5.4 读(压缩 ∥ 蒸馏请求)行):`providerName`、`spec`、`thinkingMode` 与 `toolsDeclared` 由调用点
28
+ * 按实际请求显式传入,本档不替调用方补默认。名字不可得时显式传 `undefined`,两个模式判据必须是布尔值。
17
29
  */
18
- export function buildCompressMessages(history, tailStart, systemPrompt, instruction) {
30
+ import { logOriginQuarantine, quarantineForeignOrigin } from "./origin-guard.mjs"
31
+
32
+ export function buildCompressMessages(history, tailStart, systemPrompt, instruction, previousSummary, providerName, spec, thinkingMode, toolsDeclared) {
33
+ if (arguments.length < 6) throw new Error("buildCompressMessages:providerName 必填(无默认)——不可得时显式传 undefined")
34
+ if (providerName !== undefined && (typeof providerName !== "string" || providerName === "")) {
35
+ throw new Error(`buildCompressMessages:providerName 必须是当前 provider 名(非空字符串)或 undefined(不可得),无默认——实收 ${JSON.stringify(providerName)}`)
36
+ }
37
+ if (spec === undefined) {
38
+ throw new Error("buildCompressMessages:spec 必填(当下 provider 的 spec,无默认)——未声明族传 null,省略不是「未声明」")
39
+ }
40
+ if (typeof thinkingMode !== "boolean") {
41
+ throw new Error(`buildCompressMessages:thinkingMode 必填且必须是布尔值——实收 ${JSON.stringify(thinkingMode)}`)
42
+ }
43
+ if (typeof toolsDeclared !== "boolean") {
44
+ throw new Error(`buildCompressMessages:toolsDeclared 必填且必须是布尔值——实收 ${JSON.stringify(toolsDeclared)}`)
45
+ }
46
+ if (previousSummary !== null && typeof previousSummary !== "string") {
47
+ const got = previousSummary === undefined ? "undefined(缺传)" : Array.isArray(previousSummary) ? "array" : typeof previousSummary
48
+ throw new Error(`buildCompressMessages:previousSummary 必填(string | null,无默认)——上一次摘要全文由调用点给,首次压缩传 null;实收 ${got}`)
49
+ }
19
50
  const messages = []
20
51
  if (systemPrompt) messages.push({ role: "system", content: systemPrompt }) // 缺省(undefined)/ 空串 ⇒ 不带头(退化面 1)
21
- messages.push(...history.slice(0, tailStart))
52
+ // 上一次摘要:紧跟 `system`、在被摘要的中段之前(§6.2 位置,需求 §4 定死)。
53
+ if (previousSummary !== null) messages.push({ role: "user", content: previousSummary })
54
+ const { messages: middle, reading } = quarantineForeignOrigin(history.slice(0, tailStart), { providerName, spec, thinkingMode, toolsDeclared })
55
+ messages.push(...middle)
22
56
  messages.push({ role: "user", content: instruction })
57
+ logOriginQuarantine({ site: "compress-form", providerName, reading })
23
58
  return messages
24
59
  }
@@ -24,12 +24,15 @@ export const DEFAULTS = {
24
24
  subagentModel: null, // default subagent model: "provider:model" | model name (parent provider); null = inherit parent provider
25
25
  subagentModels: {}, // per-type override: { explore, plan, coder, "eng-coder" } — priority: subagent tool model arg > this[role] > subagentModel > parent provider
26
26
  goalTurns: 200,
27
- // body 阶段读侧空闲超时(毫秒,TIMEOUT-DIGEST.md §2.1):长生成只要有数据流动就不超时,
27
+ // body 阶段读侧空闲超时(毫秒,TIMEOUT-DIGEST.md §1.1):长生成只要有数据流动就不超时,
28
28
  // 连续该值无新 chunk 才断。登记进 DEFAULTS 是为了 `settings list` 可见(判据 A3)——
29
29
  // 与 `agent.fetchTimeoutMs`(只被 config 提升、不进本表)不同的一处偏离,理由即此。
30
30
  bodyIdleTimeoutMs: DEFAULT_BODY_IDLE_MS,
31
- // compactThreshold: 键缺省 = auto(CONTEXT-COMPACTION.md §6.17 三档落值)——无默认值:留着默认值
31
+ // compactThreshold: 键缺省 = auto(CONTEXT-COMPACTION.md §2.2 三档落值)——无默认值:留着默认值
32
32
  // 会让每份配置看着都像显式。派生线只进 agent.compactThresholdResolved(内存面,不落盘)。
33
+ // keepToolTurns: 键缺省 = 全部保留(CONTEXT-COMPACTION.md §1「保留窗与跨轮清理」)——这里同样不添默认值:
34
+ // 缺省即「一条工具过程也不删」,而补一个 2 就把「未配置」静默改成保留两轮,方向与这条键的缺省相反。
35
+ // 这条注记本身就是那件要说的事——没有它,下一位维护者会把空位当成漏项补回来。
33
36
  verifyGuard: false, // push model back to verify when files were mutated but verify not run (opt-in)
34
37
  // Multi-model consultation ("会诊") + escalate ("飞刀") — CLI parity with the VS Code plugin.
35
38
  // consultModels: candidate pool for BOTH consult and escalate ({ provider, model, effort? }, up to 5).
package/config.mjs CHANGED
@@ -38,20 +38,24 @@ export { DEFAULTS }
38
38
  // Model capability table + spec lookup live in model-specs.mjs (2026-08-31
39
39
  // extract — config.mjs had grown past the 300-line advisory). Re-exported here
40
40
  // so the 23 existing importers keep their import paths.
41
- import { specForModel, providerSpec, providerSpecResolution, specMatch, formatContextK, assistantToolCallMessage } from "./model-specs.mjs"
42
- export { specForModel, providerSpec, providerSpecResolution, specMatch, formatContextK, assistantToolCallMessage }
41
+ import { specForModel, providerSpec, providerSpecResolution, specMatch, formatContextK, assistantEchoMessage, assistantTextMessage } from "./model-specs.mjs"
42
+ export { specForModel, providerSpec, providerSpecResolution, specMatch, formatContextK, assistantEchoMessage, assistantTextMessage }
43
+ // 有效思考模式的单点判定住 `think-off.mjs`(与 `thinkOffPath` 同档:off 形族与 off 路径本是一件事)。
44
+ // 转口给核内五个构造点调用方——`isThinkingRequest` 只有一个所有者,本档不复制判据。
45
+ import { isThinkingRequest } from "./think-off.mjs"
46
+ export { isThinkingRequest }
43
47
  // 上下文解析链的取值校验单点(PROVIDER.md §6.15):装载归一与读面共用一个谓词。
44
48
  import { positiveInt, warnContextOnce } from "./model-context.mjs"
45
49
 
46
50
 
47
51
  // 预算族(`outputReserve` ∥ `usableWindow` ∥ `requestBudget` ∥ `policyBudget` ∥ `effectiveWindow` ∥
48
- // `resolveCompactThreshold` ∥ `INJECT_HEADROOM_TOKENS` ∥ `RETAIN_CAP_TOKENS`)居 `window-policy.mjs`——`CONTEXT-COMPACTION.md` §2.1 ∥
52
+ // `resolveCompactThreshold` ∥ `COMPACT_RATIO` ∥ 两个注入余量常量)居 `window-policy.mjs`——`CONTEXT-COMPACTION.md` §2.1 ∥
49
53
  // §2.2 把「窗口事实」与「窗口策略」两件事分开,本档越 500 行硬限按设计给的候选线抽出;以下 re-export
50
54
  // 保既有导入面(同 `model-specs.mjs` 拆分形态)。`resolveCompactThreshold` 在本档装载期自用
51
- // (auto 档派生 `compactThresholdResolved`——按本会话档位现算,tiny 档随之落在有效窗口上),故先 import 再转口。
52
- import { resolveCompactThreshold } from "./window-policy.mjs"
55
+ // (auto 档派生 `compactThresholdResolved`——按在用渠道的模型窗口现算),故先 import 再转口。
56
+ import { nonNegativeIntValue, resolveCompactThreshold } from "./window-policy.mjs"
53
57
  export {
54
- TINY_WINDOW_CAP, INJECT_HEADROOM_TOKENS, RETAIN_CAP_TOKENS, effectiveWindow, outputReserve, usableWindow, requestBudget, policyBudget, resolveCompactThreshold,
58
+ COMPACT_RATIO, INJECT_HEADROOM_MAX_TOKENS, INJECT_HEADROOM_RATIO, effectiveWindow, outputReserve, usableWindow, requestBudget, policyBudget, resolveCompactThreshold,
55
59
  } from "./window-policy.mjs"
56
60
 
57
61
  /**
@@ -103,6 +107,21 @@ export { sanitizeSubagentModel, sanitizeSubagentModels, normalizeProxy, normaliz
103
107
  /** Module-level one-time warn dedupe for invalid providers[].context (PROVIDER.md §15 D-C1). */
104
108
  const warnedContextProviders = new Set()
105
109
 
110
+ /**
111
+ * 计数值配置键的装载期一次性告警(§1「保留窗与跨轮清理」∥ §2.2):去重键 = 键名,一个进程内同一个键只响一条。
112
+ * 报文点名键名、取值与该项的缺省语义——读的人要能据此改对文件,而不是只被告知「有一个值不对」。
113
+ * 只报不管:清键由调用点做(那一处才知道该键的缺省语义落到哪个值上),本函数不碰配置对象。
114
+ */
115
+ const warnedConfigCounts = new Set()
116
+ function warnConfigCountOnce(key, raw) {
117
+ if (warnedConfigCounts.has(key)) return
118
+ warnedConfigCounts.add(key)
119
+ const semantics = key === "compactThreshold"
120
+ ? "留空或 0 = 按当前窗口派生压缩线"
121
+ : "留空或 0 = 全部轮次保留"
122
+ console.warn(`[config] agent.${key} must be a non-negative integer — got ${JSON.stringify(raw)} — ignored: ${semantics}`)
123
+ }
124
+
106
125
  /**
107
126
  * Find provider by name in providers[].
108
127
  * Throws if name is non-empty but not found — a typo in the caller-supplied name (e.g. `defaultModel`) silently falling to the first provider would use the wrong key on the wrong endpoint.
@@ -313,24 +332,41 @@ export function loadConfig() {
313
332
  ? null
314
333
  : plan.reason ?? defaultModelReason(merged.providers, merged.defaultModel)
315
334
 
316
- // Compaction threshold 三档落值(CONTEXT-COMPACTION.md §6.17):数值在场 = 显式(原样,不猜来源);
317
- // 不在场 = auto——派生值只进 compactThresholdResolved,永不写 agent.compactThreshold、不落盘。
318
- const explicitThreshold = config.agent?.compactThreshold
319
- if (explicitThreshold != null) {
320
- merged.agent.compactThreshold = explicitThreshold
321
- merged.agent.compactThresholdResolved = explicitThreshold
322
- merged.agent.compactThresholdAuto = false
335
+ // Compaction threshold 三档落值(CONTEXT-COMPACTION.md §2.2):过同一个取值域谓词与同一个解析函数——
336
+ // 「显式」= 有限正数。正数 ⇒ 原样落 `compactThreshold`;0 ∥ 缺省 ∥ 手改的非法值 ⇒ auto 支,
337
+ // 键清出内存镜像(`delete`,与下面 `keepToolTurns` 同一做法),派生值只进 `compactThresholdResolved`、不落盘。
338
+ // 非法值(负数 ∥ 小数 ∥ 非数字)与 0 在内存镜像里同形(键不存 + `auto: true`),另告警一条点名键与取值:
339
+ // 磁盘上的 0 是用户的选择,磁盘上的 -1 是笔误,两者取值相同但只有后者该被说出来。
340
+ const rawThreshold = config.agent?.compactThreshold
341
+ const thresholdValue = nonNegativeIntValue(rawThreshold)
342
+ const thresholdResolved = resolveCompactThreshold(thresholdValue, merged.provider)
343
+ if (thresholdResolved.auto) delete merged.agent.compactThreshold
344
+ else merged.agent.compactThreshold = thresholdResolved.value
345
+ merged.agent.compactThresholdResolved = thresholdResolved.value
346
+ merged.agent.compactThresholdAuto = thresholdResolved.auto
347
+ if (rawThreshold != null && rawThreshold !== "" && thresholdValue === null) warnConfigCountOnce("compactThreshold", rawThreshold)
348
+
349
+ // 保留窗宽(CONTEXT-COMPACTION.md §1「保留窗与跨轮清理」):合法值归一成数字写回内存镜像,一个字节不动磁盘;
350
+ // 空值(缺省 ∥ `null` ∥ 空串)= 全部轮次保留,键不进镜像;非法值(负数 ∥ 小数 ∥ 非数字)清出镜像并按缺省
351
+ // 语义取值(0 = 全部保留),同一条一次性告警。进程不因手改文件的笔误被挡在门外。
352
+ const rawKeep = config.agent?.keepToolTurns
353
+ if (rawKeep == null || rawKeep === "") {
354
+ delete merged.agent.keepToolTurns
323
355
  } else {
324
- merged.agent.compactThreshold = undefined
325
- merged.agent.compactThresholdResolved = resolveCompactThreshold(null, merged.provider, merged.agent.mode).value
326
- merged.agent.compactThresholdAuto = true
356
+ const keep = nonNegativeIntValue(rawKeep)
357
+ if (keep === null) {
358
+ delete merged.agent.keepToolTurns
359
+ warnConfigCountOnce("keepToolTurns", rawKeep)
360
+ } else {
361
+ merged.agent.keepToolTurns = keep
362
+ }
327
363
  }
328
364
 
329
365
  // Write back to merged for convenient access by upper layers
330
366
  // fetch 超时可配置(2026-09-01:agent.fetchTimeoutMs——provider/core.mjs effectiveFetchTimeoutMs 消费)
331
367
  merged.provider.fetchTimeoutMs = Number.isFinite(merged.agent?.fetchTimeoutMs) && merged.agent.fetchTimeoutMs > 0
332
368
  ? merged.agent.fetchTimeoutMs : undefined
333
- // body 阶段空闲超时同形提升(TIMEOUT-DIGEST.md §2.1 —— provider/core.mjs effectiveBodyIdleMs 消费):
369
+ // body 阶段空闲超时同形提升(TIMEOUT-DIGEST.md §1.1 —— provider/core.mjs effectiveBodyIdleMs 消费):
334
370
  // 非法 ∥ 缺省 ⇒ undefined ⇒ 回退 DEFAULT_BODY_IDLE_MS(不静默禁用保护)
335
371
  merged.provider.bodyIdleTimeoutMs = Number.isFinite(merged.agent?.bodyIdleTimeoutMs) && merged.agent.bodyIdleTimeoutMs > 0
336
372
  ? merged.agent.bodyIdleTimeoutMs : undefined
@@ -4,34 +4,48 @@
4
4
  * `shrinkOversized`(splitHistory 无中间段时的单条超限收缩)——迁出块逐字。
5
5
  * 原档 `context.mjs` 经 `export { … } from` 转口保名(消费面 / 单元测试档 import 面零改);
6
6
  * 跨档被引的原私有面(`shrinkOversized`)补 `export` 关键字。
7
+ *
8
+ * 2026-11-17(机读线按轮嵌套 · `docs/core/design/CONTEXT-COMPACTION.md` §1.1「读面」):两处编辑都量在
9
+ * 拍平视图上、写在结构上——`retentionWindowStart` 给的是位置 `{ turn, msg }`,本档换算一次拍平下标;
10
+ * 命中项直接改那一轮自己的内层元素(外层数组与内层数组的引用都不换)。
7
11
  */
8
12
  import { collectStaleToolOutputs, contextUsage, estimateTokens, rebaseMeasured, tokenRatioOf } from "./token-window.mjs"
9
- // 保护尾跟着**有效窗口**走(`CONTEXT-COMPACTION.md` §2.1 / §4):档位自 agent 现取,不靠参数透传。
10
- import { resolveWorkMode } from "./config.mjs"
13
+ // 保护尾跟着**有效窗口**走(`CONTEXT-COMPACTION.md` §2.1 / §4):有效窗口恒等于模型窗口,档位不是入参。
11
14
  // 保留窗起点(#2431):prune 的合格集与压缩同一个切点——保留窗内那几轮的工具输出不被选中(§1.2)。
12
15
  import { retentionWindowStart } from "./agent/turn-projection.mjs"
16
+ // 拍平投影与两向换算(写面单点档):本档只读投影、只改结构。
17
+ import { flattenHistory, flatIndexOf } from "./context-push.mjs"
13
18
 
14
19
  /** prune stub 逐字(§6.16.3):只给「已清理 + 原长度 + 重跑路径」——prune 是**删**不是摘要,不声称可复原。 */
15
20
  const pruneStub = (chars) => `[pruned: stale tool output dropped (${chars} chars) — re-run the tool if you need it again.]`
16
21
 
17
- /** 本档两处编辑都量到「旧前缀里被改动的那一段」为止:`_usageAtLen` 之后的消息从没被量过,减它们就是减错账。 */
18
- function measuredEndOf(agent, history) {
19
- return Number.isInteger(agent?._usageAtLen) ? agent._usageAtLen : history.length
22
+ /** 保留窗起点 → 拍平下标(取不到 ⇒ 拍平条数 = 不收紧)。 */
23
+ function protectFromOf(agent, flat) {
24
+ const pos = retentionWindowStart(agent)
25
+ return pos ? flatIndexOf(agent.history, pos) : flat.length
26
+ }
27
+
28
+ /** 实测基线覆盖到的拍平下标(`_usageAt` 位置之后的消息从没被量过,减它们就是减错账)。 */
29
+ function measuredEndOf(agent, flat) {
30
+ return agent?._usageAt ? flatIndexOf(agent.history, agent._usageAt) : flat.length
20
31
  }
21
32
 
22
33
  /**
23
34
  * 陈旧工具输出清理(F-CC3 · §6.16.3):合格集 = `token-window.mjs` 单源(保护尾外 ∧ `role:"tool"` ∧ ≥ 门槛);
24
- * 命中项**原位换「内容」**(`history[i] = { ...m, content: stub }`——数组引用 / 长度 / 索引 / `tool_call_id` 全不变
25
- * ⇒ 配对**结构上不可能被拆**)。记录面零改(copy-on-write:消息对象与人读线共享)。
26
- * 基线按 §3.1 **重定,不归零**:原位替换 ⇒ `_usageAtLen` 原样,`_lastPromptTokens` 只扣那一截的估算差。
27
- * `fixedOverhead` ∥ `ratio` 的来处 = §2.3 表(`contextUsage(agent).overhead` · `tokenRatioOf(agent)`)。
35
+ * 命中项**原位换「内容」**(该轮内层那个元素换成 `{ ...m, content: stub }`——外层数组引用、内层条数、
36
+ * 顺序、`tool_call_id` 全不变 ⇒ 配对**结构上不可能被拆**)。记录面零改(copy-on-write:消息对象与人读线共享)。
37
+ * 基线按 §3.1 **重定,不归零**:原位替换 ⇒ `_usageAt` 位置原样,`_lastPromptTokens` 只扣那一截的估算差。
38
+ * `fixedOverhead` ∥ `ratio` 的来处 = §2.3 表(`contextUsage(agent, agent._ctxBasis?.overhead ?? {}).fixed − .compactionSummary` ·
39
+ * `tokenRatioOf(agent)`)——非对话面的底数只有 `fixed − compactionSummary` 一个。
28
40
  * @returns {{pruned:number, freed:number, candidates:number, tailKept:number, belowMin:number}}
29
41
  */
30
42
  export function pruneStaleToolOutputs(agent) {
31
- const history = agent.history
43
+ const flat = flattenHistory(agent.history)
44
+ // 非对话面底数 = `fixed − compactionSummary`(§2.3 表):与压缩链、`post` 同一个测度。
45
+ const usage = contextUsage(agent, agent?._ctxBasis?.overhead ?? {})
32
46
  const stale = collectStaleToolOutputs(
33
- history, agent.provider, resolveWorkMode(agent.config?.agent), retentionWindowStart(agent),
34
- contextUsage(agent).overhead, tokenRatioOf(agent),
47
+ flat, agent.provider, protectFromOf(agent, flat),
48
+ usage.fixed - usage.compactionSummary, tokenRatioOf(agent),
35
49
  )
36
50
  const counts = {
37
51
  pruned: stale.indexes.length,
@@ -41,18 +55,24 @@ export function pruneStaleToolOutputs(agent) {
41
55
  belowMin: stale.belowMin,
42
56
  }
43
57
  if (counts.pruned === 0) return counts
44
- const measuredEnd = measuredEndOf(agent, history)
58
+ const measuredEnd = measuredEndOf(agent, flat)
59
+ const hits = new Set(stale.indexes)
45
60
  let estBefore = 0
46
61
  let estAfter = 0
47
- for (const i of stale.indexes) {
48
- const m = history[i]
49
- const before = i < measuredEnd ? estimateTokens([m]) : 0
50
- // 多模态 tool 结果(content 数组)整体替换为 stub ⇒ 图像 part 丢弃(不可再取——prune 是删;回执只给重跑路径)
51
- const chars = typeof m.content === "string" ? m.content.length : JSON.stringify(m.content ?? "").length
52
- history[i] = { ...m, content: pruneStub(chars) }
53
- if (i < measuredEnd) {
54
- estBefore += before
55
- estAfter += estimateTokens([history[i]])
62
+ let at = 0
63
+ for (const turn of agent.history) {
64
+ const messages = Array.isArray(turn?.messages) ? turn.messages : []
65
+ for (let k = 0; k < messages.length; k++, at++) {
66
+ if (!hits.has(at)) continue
67
+ const m = messages[k]
68
+ const before = at < measuredEnd ? estimateTokens([m]) : 0
69
+ // 多模态 tool 结果(content 数组)整体替换为 stub ⇒ 图像 part 丢弃(不可再取——prune 是删;回执只给重跑路径)
70
+ const chars = typeof m.content === "string" ? m.content.length : JSON.stringify(m.content ?? "").length
71
+ messages[k] = { ...m, content: pruneStub(chars) }
72
+ if (at < measuredEnd) {
73
+ estBefore += before
74
+ estAfter += estimateTokens([messages[k]])
75
+ }
56
76
  }
57
77
  }
58
78
  rebaseMeasured(agent, estBefore, estAfter, { inPlace: true })
@@ -66,44 +86,55 @@ const OVERSIZE_CONTENT_LIMIT = 8_000
66
86
  * Deterministic shrinking: last resort when splitHistory can't find a middle section (history too short) but threshold is exceeded. No LLM call.
67
87
  * Truncates user/tool message bodies exceeding OVERSIZE_CONTENT_LIMIT to a stub (keeps head + tail);
68
88
  * does not touch reasoning_content (DeepSeek/Kimi echo protocol) or tool_calls pairing structure — no protocol 400
69
- * risk from this path (this module's echo-safety face is `applyCompression`: the compaction placeholder is never
70
- * committed as a separate reasoning-less assistant next to another assistant — D-CC18, 2026-09-16 batch).
89
+ * risk from this path (this module's echo-safety face is `applyCompression`: the compaction summary now rides
90
+ * `agent._inject` and never lands on the machine line — D-CC18, 2026-09-16 batch).
71
91
  * Only called after compressIfNeeded determines threshold is exceeded. Returns whether any message was truncated.
92
+ *
93
+ * 射程止于保留窗起点之前(`CONTEXT-COMPACTION.md` §1.1 ∥ §4):`retentionWindowStart(agent)` 之后的
94
+ * 消息一条不改——保留窗承诺的那两轮工具过程原文逐字留着。取不到起点(等于拍平条数)时等于不收紧。
95
+ * 代价写明:那一轮离开前,一条超大消息可能让压缩无事可做,由越窗守卫如实报错(§4 的已知边界)。
72
96
  */
73
97
  export function shrinkOversized(agent, limit = OVERSIZE_CONTENT_LIMIT) {
98
+ const flat = flattenHistory(agent.history)
99
+ const protectFrom = protectFromOf(agent, flat)
74
100
  let shrunk = false
75
- const measuredEnd = measuredEndOf(agent, agent.history)
101
+ const measuredEnd = measuredEndOf(agent, flat)
76
102
  let estBefore = 0
77
103
  let estAfter = 0
78
- // Copy-on-write: build a NEW array and replace only truncated entries. pushReal stores the SAME
104
+ // Copy-on-write: replace only truncated entries. pushReal stores the SAME
79
105
  // message object in both `agent.history` (machine line) and `agent._fullHistory` (human/persistence
80
106
  // line), so in-place `m.content = ...` would ALSO truncate the never-compacted human line and lose
81
107
  // the original pasted content on session persist (session.mjs persists _fullHistory). VS Code port
82
108
  // already copies (`history.map(m => ({ ...m }))`); this brings CLI to parity.
83
- const next = agent.history.map((m, i) => {
84
- if ((m.role !== "user" && m.role !== "tool") || typeof m.content !== "string") return m
85
- if (m.content.length <= limit) return m
86
- // Truncate keeping head + tail, insert stub in between; keepHead/keepTail proportional but not exceeding 50%/25% of limit
87
- const keepHead = Math.min(Math.floor(limit * 0.5), 4000)
88
- const keepTail = Math.min(Math.floor(limit * 0.25), 2000)
89
- shrunk = true
90
- const truncated = {
91
- ...m,
92
- content:
93
- m.content.slice(0, keepHead) +
94
- `\n[... ${m.content.length - keepHead - keepTail} chars truncated — single message too large for context window ...]\n` +
95
- m.content.slice(-keepTail),
96
- }
97
- if (i < measuredEnd) {
98
- estBefore += estimateTokens([m])
99
- estAfter += estimateTokens([truncated])
109
+ let at = 0
110
+ for (const turn of agent.history) {
111
+ const messages = Array.isArray(turn?.messages) ? turn.messages : []
112
+ for (let k = 0; k < messages.length; k++, at++) {
113
+ if (at >= protectFrom) continue
114
+ const m = messages[k]
115
+ if ((m.role !== "user" && m.role !== "tool") || typeof m.content !== "string") continue
116
+ if (m.content.length <= limit) continue
117
+ // Truncate keeping head + tail, insert stub in between; keepHead/keepTail proportional but not exceeding 50%/25% of limit
118
+ const keepHead = Math.min(Math.floor(limit * 0.5), 4000)
119
+ const keepTail = Math.min(Math.floor(limit * 0.25), 2000)
120
+ shrunk = true
121
+ const truncated = {
122
+ ...m,
123
+ content:
124
+ m.content.slice(0, keepHead) +
125
+ `\n[... ${m.content.length - keepHead - keepTail} chars truncated — single message too large for context window ...]\n` +
126
+ m.content.slice(-keepTail),
127
+ }
128
+ if (at < measuredEnd) {
129
+ estBefore += estimateTokens([m])
130
+ estAfter += estimateTokens([truncated])
131
+ }
132
+ messages[k] = truncated
100
133
  }
101
- return truncated
102
- })
134
+ }
103
135
  if (shrunk) {
104
- agent.history = next
105
- // 基线按 §3.1 **重定,不归零**:截断是原位替换(数组长度与下标不变)⇒ `_usageAtLen` 原样。
136
+ // 基线按 §3.1 **重定,不归零**:截断是原位替换(内层条数与顺序不变)⇒ `_usageAt` 位置原样。
106
137
  rebaseMeasured(agent, estBefore, estAfter, { inPlace: true })
107
138
  }
108
139
  return shrunk
109
- }
140
+ }