bots-garden/mini-mepublic Fork
⑂ 9e902ec
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/mini-me.git
git clone ssh://git@rickub.com/bots-garden/mini-me.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

Merge branch 'feature/compaction-turns': compaction inside a turn (tickets 289-292)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
agent committed 2026-11-30T09:39:17+01:00 Browse files
9e902ec parents: 9596de5 d45b013
added .tickets/issues/0284-info-panel-into-the-tui.yaml +17 -0
new file mode 100644
@@ -0,0 +1,17 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 284
3+title: Info panel into the TUI
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-29T06:47:29.513Z
9+updatedAt: 2026-11-29T06:48:35.651Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: |
13+ Display the list of the tools, skills, ...
14+ Memory Pressure if available
15+ (or if a LLM Server is exposing it)
16+tasks: []
17+comments: []
new file mode 100644
@@ -0,0 +1,17 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 284
3+title: Info panel into the TUI
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-29T06:47:29.513Z
9+updatedAt: 2026-11-29T06:48:35.651Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: |
13+ Display the list of the tools, skills, ...
14+ Memory Pressure if available
15+ (or if a LLM Server is exposing it)
16+tasks: []
17+comments: []
added .tickets/issues/0285-spinner-thinking-add-some-changing-message.yaml +15 -0
new file mode 100644
@@ -0,0 +1,15 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 285
3+title: Spinner ⠋ thinking -> add some changing message
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-29T12:23:13.406Z
9+updatedAt: 2026-11-29T12:23:35.294Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+epic: Improve TUI
13+body: ""
14+tasks: []
15+comments: []
new file mode 100644
@@ -0,0 +1,15 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 285
3+title: Spinner ⠋ thinking -> add some changing message
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-29T12:23:13.406Z
9+updatedAt: 2026-11-29T12:23:35.294Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+epic: Improve TUI
13+body: ""
14+tasks: []
15+comments: []
added .tickets/issues/0286-add-a-retry-command-do-something-depending-the-e.yaml +14 -0
new file mode 100644
@@ -0,0 +1,14 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 286
3+title: Add a /retry command (do something depending the erro)
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-29T16:16:08.910Z
9+updatedAt: 2026-11-29T16:16:08.910Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: ""
13+tasks: []
14+comments: []
new file mode 100644
@@ -0,0 +1,14 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 286
3+title: Add a /retry command (do something depending the erro)
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-29T16:16:08.910Z
9+updatedAt: 2026-11-29T16:16:08.910Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: ""
13+tasks: []
14+comments: []
added .tickets/issues/0287-create-a-handoff-method-it-s-possible-to-use-ano.yaml +14 -0
new file mode 100644
@@ -0,0 +1,14 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 287
3+title: Create a /handoff method (it's possible to use another model, but we need to unload the current one)
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-29T16:17:24.602Z
9+updatedAt: 2026-11-29T16:17:24.602Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: ""
13+tasks: []
14+comments: []
new file mode 100644
@@ -0,0 +1,14 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 287
3+title: Create a /handoff method (it's possible to use another model, but we need to unload the current one)
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-29T16:17:24.602Z
9+updatedAt: 2026-11-29T16:17:24.602Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: ""
13+tasks: []
14+comments: []
added .tickets/issues/0288-fix-the-label-enter-queues-a-question.yaml +14 -0
new file mode 100644
@@ -0,0 +1,14 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 288
3+title: "Fix the label: Enter queues a question"
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-29T16:20:41.149Z
9+updatedAt: 2026-11-29T16:20:41.149Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: ""
13+tasks: []
14+comments: []
new file mode 100644
@@ -0,0 +1,14 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 288
3+title: "Fix the label: Enter queues a question"
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-29T16:20:41.149Z
9+updatedAt: 2026-11-29T16:20:41.149Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: ""
13+tasks: []
14+comments: []
added .tickets/issues/0289-compaction-loop-with-injected-user-messages.yaml +167 -0
new file mode 100644
@@ -0,0 +1,167 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 289
3+title: Compaction loop with injected user messages
4+state: closed
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-30T02:18:39.000Z
9+updatedAt: 2026-11-30T08:38:53.000Z
10+labels:
11+ - bug
12+ - kind::bug
13+ - priority::high
14+ - To be tested
15+milestone: v2.2.1
16+epic: Loop
17+related:
18+ - 251
19+ - 265
20+body: |
21+ ## Summary
22+
23+ When a session holds mm's own injected user messages, the between-questions compaction keeps far more history than `keepLastTurns` intends. The history then stays above `context.threshold`, so `compressInTurn` runs before every model call and the model re-reads the files it just lost. Observed: **3.5 h, ~30 identical read cycles, no progress**, on mm `9596de5` with Inkling-2-Mini via razorbill 1.2.1.
24+
25+ Two side effects make it worse: the progressive in-turn `shrink` changes old messages, so the server's prompt cache misses on every call, and each step re-reads 15-25k tokens (4-6 min on the test Mac).
26+
27+ ## Observed
28+
29+ One session of 151 model calls on 2026-11-29 (task: build a Go + SPA issue tracker). Config: `contextWindow: 16384`, `context.threshold: 75` (about 12.3k tokens), `keepLastTurns` default 3, `compressInTurn` default on, `maxOutput: 8000`.
30+
31+ | Calls | Time (local) | What happened |
32+ | --- | --- | --- |
33+ | 0151 | 11-30 02:29 | Turn-start compaction of 71 messages, cancelled by the user (`context canceled`) |
34+ | 0150 | 23:03 | 24.8k-token prompt, no cache: only `: keep-alive` for 5 min, watchdog cut: "generation timed out (stalled)" |
35+ | 0089-0149 | 19:28-23:01 | Loop: a 1200-token in-turn summary request, then a 114-message (~24k tokens) request re-reading the same `sed -n` ranges of `server.go` / `store.go`; about 30 cycles |
36+ | 0083-0088 | 19:21-19:28 | Turn "yes do it step by step": turn-start compaction summarised only 15 messages; 106 messages (~20k tokens) went out |
37+ | 0049-0081 | 17:15-19:13 | `cached_tokens` absent on most calls: old tool outputs rewritten in place |
38+ | 0001-0048 | 15:59-17:14 | Includes turn 1 ("read @prompt.txt and implement it"), ended at `maxTurns` 40 |
39+
40+ The message count stays at exactly 114 from 0090 to 0150: each step adds one exchange and the in-turn summary removes one.
41+
42+ ## Root cause
43+
44+ `compact.Split` (`internal/compact/compact.go`) starts a new turn at **every** `user` message. mm injects user messages itself, so they count as turns:
45+
46+ - the cut-tool-call notice, "[mm: your last tool call was not run: it was cut off before its end…]";
47+ - `engine.SteerLabel`, "[message from the user during this turn]".
48+
49+ In the session, the history before the question "yes do it step by step" split as follows:
50+
51+ | Turn as Split sees it | Messages | Real question? |
52+ | --- | --- | --- |
53+ | earlier summary pair | 2 | no |
54+ | cut-tool-call notice | 67 | no (rest of question 1) |
55+ | "try again but optimise the tool calls" | 33 | yes |
56+ | steer message + answer | 2 | no (mid-turn) |
57+
58+ With `keepLastTurns: 3` the last three are kept, which is 102 messages and about 20k tokens. The only old turn is the summary, so `summaryOf` returns `ErrNothingToCompact` and nothing is compressed.
59+
60+ Then, before each model call, `InTurnDecide` sees the history above the threshold, and `CompactTurn` (`internal/compact/inturn.go`) shrinks and summarises the current turn down to the last `KeepToolCalls` (4) exchanges. It can never get under the threshold, because the floor is outside the turn. So it fires on every call: the model loses its oldest read, reads it again, and loops.
61+
62+ Cache side effect: `shrink` rewrites tool results that are already in the prompt, a little more at each step. Any server that reuses a prompt prefix (razorbill here) then misses from that message on, and with a non-trimmable cache (Inkling 2) it re-reads the whole prompt. Each in-turn summary request also takes the server's cache slot between two agent calls.
63+
64+ ## Proposed changes
65+
66+ The injected messages are plain `ai.NewUserTextMessage` today, with no metadata: `internal/engine/toolargs.go` (lines 105, 156, 188, prefix `argsRetryPrefix`) and `internal/engine/steer.go:109` (`SteerLabel`).
67+
68+ 1. **Tag injected user messages.** Set a metadata key (for example `Metadata["mm"] = "notice"` or `"steer"`) on the three `toolargs.go` notices and on steered messages.
69+ 2. **Do not start a turn at a tagged message.** `compact.Split` appends it to the current turn; `turnBounds` skips it when it looks for the turn's question (a steered message is the user's words, but it belongs to the running turn).
70+ 3. **Detect a floor above the threshold.** When `Compact` returns `ErrNothingToCompact` or keeps more than the threshold, say so in the 🗜️ line, and let `CompactTurn` stop after one summary per turn when the history stays above the threshold anyway. Today it silently runs before every call.
71+ 4. ~~Optional: shrink once.~~ Moved to #290, since rewritten: [#290 — In-turn compression: go down to a lower target, so the next calls keep the prompt cache](.tickets/issues/0290-in-turn-compression-go-down-to-a-lower-target-so.yaml) (shrink already cuts a result once).
72+
73+ ### Acceptance criteria
74+
75+ - [ ] A history of 3 real questions, where question 1 contains a cut-tool-call notice and question 2 a steered message, splits into 3 turns.
76+ - [ ] With `keepLastTurns: 3` and that history above the threshold, `Compact` compresses the oldest real question.
77+ - [ ] In a turn whose history outside the turn is above the threshold, `CompactTurn` sends at most one summary request per turn (not one per call), and the 🗜️ line says the floor is too high.
78+ - [ ] Unit tests in `internal/compact` for `Split` and `turnBounds` with tagged messages; `Valid` still passes on every result.
79+ - [ ] Sessions saved before the change still load (untagged notices are recognised by their prefix, or handled as today).
80+
81+ ## Workaround and evidence
82+
83+ Workaround in the agent file, until the fix: `context.keepLastTurns: 1`, so only the last turn (as Split sees it) stays raw. Not yet re-run with the model. Asking for small steps, one session per step, also keeps the history low.
84+
85+ Evidence, in the razorbill repository under `demos/inkling-2-mini/.mm/`:
86+
87+ - `sessions/20261129-160857-f02ca749.json`: the `errors` field lists the three stops (max iterations, stalled, compaction cancelled);
88+ - `traces/*nestor-0083*` to `*nestor-0150*`: the loop, each pair `request.json` + `response-200.sse`;
89+ - `agent.yaml`: the settings used, with the workaround and its comment.
90+
91+ Traces hold the whole conversation: share excerpts, not the folder.
92+tasks:
93+ - id: 1
94+ title: "Tag injected user messages (toolargs.go notices and steered messages) with a metadata key"
95+ state: closed
96+ priority: none
97+ author:
98+ name: k33g
99+ email: ph.charriere@gmail.com
100+ createdAt: 2026-11-30T02:18:39.000Z
101+ updatedAt: 2026-11-30T02:37:09.000Z
102+ closedAt: 2026-11-30T02:37:09.000Z
103+ - id: 2
104+ title: "compact.Split: do not start a turn at a tagged message; turnBounds skips it"
105+ state: closed
106+ priority: none
107+ author:
108+ name: k33g
109+ email: ph.charriere@gmail.com
110+ createdAt: 2026-11-30T02:18:39.000Z
111+ updatedAt: 2026-11-30T02:37:09.000Z
112+ closedAt: 2026-11-30T02:37:09.000Z
113+ - id: 3
114+ title: "Detect a floor above the threshold: say it in the 🗜️ line, at most one in-turn summary per turn"
115+ state: closed
116+ priority: none
117+ author:
118+ name: k33g
119+ email: ph.charriere@gmail.com
120+ createdAt: 2026-11-30T02:18:39.000Z
121+ updatedAt: 2026-11-30T02:37:09.000Z
122+ closedAt: 2026-11-30T02:37:09.000Z
123+ - id: 5
124+ title: "Unit tests in internal/compact for Split and turnBounds with tagged messages; Valid still passes"
125+ state: closed
126+ priority: none
127+ author:
128+ name: k33g
129+ email: ph.charriere@gmail.com
130+ createdAt: 2026-11-30T02:18:39.000Z
131+ updatedAt: 2026-11-30T02:37:09.000Z
132+ closedAt: 2026-11-30T02:37:09.000Z
133+ - id: 6
134+ title: "Sessions saved before the change still load"
135+ state: closed
136+ priority: none
137+ author:
138+ name: k33g
139+ email: ph.charriere@gmail.com
140+ createdAt: 2026-11-30T02:18:39.000Z
141+ updatedAt: 2026-11-30T02:37:09.000Z
142+ closedAt: 2026-11-30T02:37:09.000Z
143+comments:
144+ - id: 1
145+ author:
146+ name: k33g
147+ email: ph.charriere@gmail.com
148+ createdAt: 2026-11-30T02:37:09.000Z
149+ body: |
150+ Implemented on branch `feature/compaction-turns` (not committed).
151+
152+ - `internal/compact/injected.go`: metadata key `mm` (`notice` | `steer`), `MarkInjected`, `IsInjected`. `Split` and `turnBounds` skip marked messages.
153+ - `internal/engine/notes.go` `noteMessage`: the 4 notes (cut tool call, cut reply, failed edit, loop) are marked `notice`; `takeSteer` marks `steer`. The hook-blocked prompt and `/redirect` still start a turn (they replace a real question).
154+ - Floor: the history before the turn + its question (not the kept exchanges: they move on as the turn goes, and `TestGenerateCompressesInsideALongTurn` relies on repeated summaries there). When it passes the threshold, one summary per turn, and the 🗜️ line says so even with `showStats: false`; later calls only shrink.
155+ - Sessions saved before: handled as today (user's choice), unmarked notices still start a turn.
156+ - Between questions, the automatic "nothing to compact" stays silent: `Apply` does not know the window; with the marks, the oldest real question gets compressed again.
157+
158+ Tests: `go test ./... -count=1` green; the new tests fail without the fix. Quality gate PASS (run 18). Docs EN+FR: explanation/context-compression, how-to/manage-the-context-window, reference/configuration.
159+
160+ Left to check: the Inkling-2-Mini session again (without the `keepLastTurns: 1` workaround).
161+ - id: 2
162+ author:
163+ name: k33g
164+ email: ph.charriere@gmail.com
165+ createdAt: 2026-11-30T08:38:53.000Z
166+ body: |
167+ Closed at the user's request for release v2.2.1 (merged from `feature/compaction-turns`).
new file mode 100644
@@ -0,0 +1,167 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 289
3+title: Compaction loop with injected user messages
4+state: closed
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-30T02:18:39.000Z
9+updatedAt: 2026-11-30T08:38:53.000Z
10+labels:
11+ - bug
12+ - kind::bug
13+ - priority::high
14+ - To be tested
15+milestone: v2.2.1
16+epic: Loop
17+related:
18+ - 251
19+ - 265
20+body: |
21+ ## Summary
22+
23+ When a session holds mm's own injected user messages, the between-questions compaction keeps far more history than `keepLastTurns` intends. The history then stays above `context.threshold`, so `compressInTurn` runs before every model call and the model re-reads the files it just lost. Observed: **3.5 h, ~30 identical read cycles, no progress**, on mm `9596de5` with Inkling-2-Mini via razorbill 1.2.1.
24+
25+ Two side effects make it worse: the progressive in-turn `shrink` changes old messages, so the server's prompt cache misses on every call, and each step re-reads 15-25k tokens (4-6 min on the test Mac).
26+
27+ ## Observed
28+
29+ One session of 151 model calls on 2026-11-29 (task: build a Go + SPA issue tracker). Config: `contextWindow: 16384`, `context.threshold: 75` (about 12.3k tokens), `keepLastTurns` default 3, `compressInTurn` default on, `maxOutput: 8000`.
30+
31+ | Calls | Time (local) | What happened |
32+ | --- | --- | --- |
33+ | 0151 | 11-30 02:29 | Turn-start compaction of 71 messages, cancelled by the user (`context canceled`) |
34+ | 0150 | 23:03 | 24.8k-token prompt, no cache: only `: keep-alive` for 5 min, watchdog cut: "generation timed out (stalled)" |
35+ | 0089-0149 | 19:28-23:01 | Loop: a 1200-token in-turn summary request, then a 114-message (~24k tokens) request re-reading the same `sed -n` ranges of `server.go` / `store.go`; about 30 cycles |
36+ | 0083-0088 | 19:21-19:28 | Turn "yes do it step by step": turn-start compaction summarised only 15 messages; 106 messages (~20k tokens) went out |
37+ | 0049-0081 | 17:15-19:13 | `cached_tokens` absent on most calls: old tool outputs rewritten in place |
38+ | 0001-0048 | 15:59-17:14 | Includes turn 1 ("read @prompt.txt and implement it"), ended at `maxTurns` 40 |
39+
40+ The message count stays at exactly 114 from 0090 to 0150: each step adds one exchange and the in-turn summary removes one.
41+
42+ ## Root cause
43+
44+ `compact.Split` (`internal/compact/compact.go`) starts a new turn at **every** `user` message. mm injects user messages itself, so they count as turns:
45+
46+ - the cut-tool-call notice, "[mm: your last tool call was not run: it was cut off before its end…]";
47+ - `engine.SteerLabel`, "[message from the user during this turn]".
48+
49+ In the session, the history before the question "yes do it step by step" split as follows:
50+
51+ | Turn as Split sees it | Messages | Real question? |
52+ | --- | --- | --- |
53+ | earlier summary pair | 2 | no |
54+ | cut-tool-call notice | 67 | no (rest of question 1) |
55+ | "try again but optimise the tool calls" | 33 | yes |
56+ | steer message + answer | 2 | no (mid-turn) |
57+
58+ With `keepLastTurns: 3` the last three are kept, which is 102 messages and about 20k tokens. The only old turn is the summary, so `summaryOf` returns `ErrNothingToCompact` and nothing is compressed.
59+
60+ Then, before each model call, `InTurnDecide` sees the history above the threshold, and `CompactTurn` (`internal/compact/inturn.go`) shrinks and summarises the current turn down to the last `KeepToolCalls` (4) exchanges. It can never get under the threshold, because the floor is outside the turn. So it fires on every call: the model loses its oldest read, reads it again, and loops.
61+
62+ Cache side effect: `shrink` rewrites tool results that are already in the prompt, a little more at each step. Any server that reuses a prompt prefix (razorbill here) then misses from that message on, and with a non-trimmable cache (Inkling 2) it re-reads the whole prompt. Each in-turn summary request also takes the server's cache slot between two agent calls.
63+
64+ ## Proposed changes
65+
66+ The injected messages are plain `ai.NewUserTextMessage` today, with no metadata: `internal/engine/toolargs.go` (lines 105, 156, 188, prefix `argsRetryPrefix`) and `internal/engine/steer.go:109` (`SteerLabel`).
67+
68+ 1. **Tag injected user messages.** Set a metadata key (for example `Metadata["mm"] = "notice"` or `"steer"`) on the three `toolargs.go` notices and on steered messages.
69+ 2. **Do not start a turn at a tagged message.** `compact.Split` appends it to the current turn; `turnBounds` skips it when it looks for the turn's question (a steered message is the user's words, but it belongs to the running turn).
70+ 3. **Detect a floor above the threshold.** When `Compact` returns `ErrNothingToCompact` or keeps more than the threshold, say so in the 🗜️ line, and let `CompactTurn` stop after one summary per turn when the history stays above the threshold anyway. Today it silently runs before every call.
71+ 4. ~~Optional: shrink once.~~ Moved to #290, since rewritten: [#290 — In-turn compression: go down to a lower target, so the next calls keep the prompt cache](.tickets/issues/0290-in-turn-compression-go-down-to-a-lower-target-so.yaml) (shrink already cuts a result once).
72+
73+ ### Acceptance criteria
74+
75+ - [ ] A history of 3 real questions, where question 1 contains a cut-tool-call notice and question 2 a steered message, splits into 3 turns.
76+ - [ ] With `keepLastTurns: 3` and that history above the threshold, `Compact` compresses the oldest real question.
77+ - [ ] In a turn whose history outside the turn is above the threshold, `CompactTurn` sends at most one summary request per turn (not one per call), and the 🗜️ line says the floor is too high.
78+ - [ ] Unit tests in `internal/compact` for `Split` and `turnBounds` with tagged messages; `Valid` still passes on every result.
79+ - [ ] Sessions saved before the change still load (untagged notices are recognised by their prefix, or handled as today).
80+
81+ ## Workaround and evidence
82+
83+ Workaround in the agent file, until the fix: `context.keepLastTurns: 1`, so only the last turn (as Split sees it) stays raw. Not yet re-run with the model. Asking for small steps, one session per step, also keeps the history low.
84+
85+ Evidence, in the razorbill repository under `demos/inkling-2-mini/.mm/`:
86+
87+ - `sessions/20261129-160857-f02ca749.json`: the `errors` field lists the three stops (max iterations, stalled, compaction cancelled);
88+ - `traces/*nestor-0083*` to `*nestor-0150*`: the loop, each pair `request.json` + `response-200.sse`;
89+ - `agent.yaml`: the settings used, with the workaround and its comment.
90+
91+ Traces hold the whole conversation: share excerpts, not the folder.
92+tasks:
93+ - id: 1
94+ title: "Tag injected user messages (toolargs.go notices and steered messages) with a metadata key"
95+ state: closed
96+ priority: none
97+ author:
98+ name: k33g
99+ email: ph.charriere@gmail.com
100+ createdAt: 2026-11-30T02:18:39.000Z
101+ updatedAt: 2026-11-30T02:37:09.000Z
102+ closedAt: 2026-11-30T02:37:09.000Z
103+ - id: 2
104+ title: "compact.Split: do not start a turn at a tagged message; turnBounds skips it"
105+ state: closed
106+ priority: none
107+ author:
108+ name: k33g
109+ email: ph.charriere@gmail.com
110+ createdAt: 2026-11-30T02:18:39.000Z
111+ updatedAt: 2026-11-30T02:37:09.000Z
112+ closedAt: 2026-11-30T02:37:09.000Z
113+ - id: 3
114+ title: "Detect a floor above the threshold: say it in the 🗜️ line, at most one in-turn summary per turn"
115+ state: closed
116+ priority: none
117+ author:
118+ name: k33g
119+ email: ph.charriere@gmail.com
120+ createdAt: 2026-11-30T02:18:39.000Z
121+ updatedAt: 2026-11-30T02:37:09.000Z
122+ closedAt: 2026-11-30T02:37:09.000Z
123+ - id: 5
124+ title: "Unit tests in internal/compact for Split and turnBounds with tagged messages; Valid still passes"
125+ state: closed
126+ priority: none
127+ author:
128+ name: k33g
129+ email: ph.charriere@gmail.com
130+ createdAt: 2026-11-30T02:18:39.000Z
131+ updatedAt: 2026-11-30T02:37:09.000Z
132+ closedAt: 2026-11-30T02:37:09.000Z
133+ - id: 6
134+ title: "Sessions saved before the change still load"
135+ state: closed
136+ priority: none
137+ author:
138+ name: k33g
139+ email: ph.charriere@gmail.com
140+ createdAt: 2026-11-30T02:18:39.000Z
141+ updatedAt: 2026-11-30T02:37:09.000Z
142+ closedAt: 2026-11-30T02:37:09.000Z
143+comments:
144+ - id: 1
145+ author:
146+ name: k33g
147+ email: ph.charriere@gmail.com
148+ createdAt: 2026-11-30T02:37:09.000Z
149+ body: |
150+ Implemented on branch `feature/compaction-turns` (not committed).
151+
152+ - `internal/compact/injected.go`: metadata key `mm` (`notice` | `steer`), `MarkInjected`, `IsInjected`. `Split` and `turnBounds` skip marked messages.
153+ - `internal/engine/notes.go` `noteMessage`: the 4 notes (cut tool call, cut reply, failed edit, loop) are marked `notice`; `takeSteer` marks `steer`. The hook-blocked prompt and `/redirect` still start a turn (they replace a real question).
154+ - Floor: the history before the turn + its question (not the kept exchanges: they move on as the turn goes, and `TestGenerateCompressesInsideALongTurn` relies on repeated summaries there). When it passes the threshold, one summary per turn, and the 🗜️ line says so even with `showStats: false`; later calls only shrink.
155+ - Sessions saved before: handled as today (user's choice), unmarked notices still start a turn.
156+ - Between questions, the automatic "nothing to compact" stays silent: `Apply` does not know the window; with the marks, the oldest real question gets compressed again.
157+
158+ Tests: `go test ./... -count=1` green; the new tests fail without the fix. Quality gate PASS (run 18). Docs EN+FR: explanation/context-compression, how-to/manage-the-context-window, reference/configuration.
159+
160+ Left to check: the Inkling-2-Mini session again (without the `keepLastTurns: 1` workaround).
161+ - id: 2
162+ author:
163+ name: k33g
164+ email: ph.charriere@gmail.com
165+ createdAt: 2026-11-30T08:38:53.000Z
166+ body: |
167+ Closed at the user's request for release v2.2.1 (merged from `feature/compaction-turns`).
added .tickets/issues/0290-in-turn-compression-go-down-to-a-lower-target-so.yaml +141 -0
new file mode 100644
@@ -0,0 +1,141 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 290
3+title: "In-turn compression: go down to a lower target, so the next calls keep the prompt cache"
4+state: closed
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-30T02:24:02.000Z
9+updatedAt: 2026-11-30T08:38:53.000Z
10+labels:
11+ - enhancement
12+ - kind::feature
13+ - priority::medium
14+ - To be tested
15+milestone: v2.2.1
16+epic: Loop
17+related:
18+ - 289
19+ - 251
20+ - 291
21+body: |
22+ Rewritten on 2026-11-30 (comment 1 says why). Follows [#291 — In-turn compression ignores the server's token count](.tickets/issues/0291-in-turn-compression-ignores-the-server-s-token-cou.yaml).
23+
24+ ## Problem
25+
26+ The in-turn compression (`compact.CompactTurn`) fires when the request passes `context.threshold`, and compresses **just enough** to get back under it. The next tool result passes the threshold again, so the turn is compressed again before the next call, and so on:
27+
28+ - each compression rewrites the prompt (a shrunk result, notes added to the question near the top), so the server's prefix cache misses on the next call: the whole prompt is read again (~3 min for 17k tokens with Inkling-2-Mini on razorbill);
29+ - each summary is one more model request (~1200 tokens out), and the model loses a little more of what it read.
30+
31+ Seen in `TestGenerateSummarisesOnTheServersCount` (`internal/engine/calibrate_test.go`): window 8000, threshold 6000, each read ~1.6k calibrated tokens. After #291, the turn is summarised before nearly every call (`8.4k → 5.1k`, then the next read brings it back to 6.7k).
32+
33+ ## Proposed change
34+
35+ Hysteresis: the trigger stays at `threshold`, but once it fires, the compression goes down to a lower **target** — for example two thirds of the threshold (75 → 50 %, 60 → 40 %), or a `context.inTurnTarget` key if a fixed rule is not enough.
36+
37+ - The shrink step is unchanged (older than the last 4 exchanges).
38+ - The summary is made when the shrunk history is still above the **target** (not the threshold), and `summaryCut` keeps as many exchanges as fit under the target (at least 1).
39+ - The floor check (#289) and the "not sent" guard (#291) keep their current limits (threshold, window).
40+
41+ Then several calls follow a compression without touching the prompt, and they get the prefix cache.
42+
43+ ## Acceptance criteria
44+
45+ - [ ] Unit test: after one compression, a turn that grows by one exchange per call goes several calls without a new compression (no rewrite of the earlier messages).
46+ - [ ] End-to-end test: fewer summaries than calls in `TestGenerateSummarisesOnTheServersCount`'s scenario.
47+ - [ ] Measured on the Inkling demo: `cached_tokens` present on the calls between two compressions, and the time per call.
48+ - [ ] Docs EN+FR (configuration reference, context-compression explanation).
49+tasks:
50+ - id: 4
51+ title: "Compress down to a target below the threshold (summary decision and summaryCut)"
52+ state: closed
53+ priority: none
54+ author:
55+ name: k33g
56+ email: ph.charriere@gmail.com
57+ createdAt: 2026-11-30T03:33:26.000Z
58+ updatedAt: 2026-11-30T08:06:20.000Z
59+ closedAt: 2026-11-30T08:06:20.000Z
60+ - id: 5
61+ title: "Unit test: several calls without a new compression after one"
62+ state: closed
63+ priority: none
64+ author:
65+ name: k33g
66+ email: ph.charriere@gmail.com
67+ createdAt: 2026-11-30T03:33:26.000Z
68+ updatedAt: 2026-11-30T08:06:20.000Z
69+ closedAt: 2026-11-30T08:06:20.000Z
70+ - id: 6
71+ title: "End-to-end test: fewer summaries than calls"
72+ state: closed
73+ priority: none
74+ author:
75+ name: k33g
76+ email: ph.charriere@gmail.com
77+ createdAt: 2026-11-30T03:33:26.000Z
78+ updatedAt: 2026-11-30T08:06:20.000Z
79+ closedAt: 2026-11-30T08:06:20.000Z
80+ - id: 7
81+ title: "Measure cached_tokens and time per call on the Inkling demo"
82+ state: closed
83+ priority: none
84+ author:
85+ name: k33g
86+ email: ph.charriere@gmail.com
87+ createdAt: 2026-11-30T03:33:26.000Z
88+ updatedAt: 2026-11-30T08:38:53.000Z
89+ closedAt: 2026-11-30T08:38:53.000Z
90+ - id: 8
91+ title: "Docs EN+FR"
92+ state: closed
93+ priority: none
94+ author:
95+ name: k33g
96+ email: ph.charriere@gmail.com
97+ createdAt: 2026-11-30T03:33:26.000Z
98+ updatedAt: 2026-11-30T08:06:20.000Z
99+ closedAt: 2026-11-30T08:06:20.000Z
100+comments:
101+ - id: 1
102+ author:
103+ name: k33g
104+ email: ph.charriere@gmail.com
105+ createdAt: 2026-11-30T03:33:26.000Z
106+ body: |
107+ Rewritten. The first version ("cut an old tool result once") rested on a wrong premise: `shrink` already cuts a result once — `headLine` leaves at most ~350 characters, under `shrinkOver` (400), so a shrunk result is never shrunk again. Its tasks 1-3 were dropped. The cache misses come from compressing again at nearly every call; this ticket is now about that.
108+ - id: 2
109+ author:
110+ name: k33g
111+ email: ph.charriere@gmail.com
112+ createdAt: 2026-11-30T04:20:30.000Z
113+ body: |
114+ Measured with the #289 + #291 binary, `demos/inkling-2-mini` (threshold 60, maxOutput 2500, keepLastTurns 1), traces 2026-11-30 04:32 → 05:07, calls 0001-0042:
115+
116+ - No stall, no "not sent": the prompt stays at 7.2-10k tokens of a 16k window; calibration ratio ≈ 1.8.
117+ - **18 of 41 calls without cache**, ~98 s each, against ~13 s for a cached call: **29.5 of the 34.5 minutes** are spent re-reading the prompt.
118+ - Calls 0011-0022: the prefix breaks one call in two (shrink, then a read brings it back over the threshold). Calls 0024-0029: every call (1.5-4.5 min each). Only one summary in the whole run (0030).
119+
120+ Design consequence: the target must apply to the **shrink step too**, not only to the summary. Today a shrink cuts what is older than the last 4 exchanges, gets just under the threshold, and the next read passes it again: one shrink per call or two, each one a cache miss. With a target, a compression must shrink (and, if needed, summarise) until the history is under the target — for example by keeping fewer raw exchanges than 4 when the threshold is passed — so that several calls follow without touching the prompt.
121+ - id: 3
122+ author:
123+ name: k33g
124+ email: ph.charriere@gmail.com
125+ createdAt: 2026-11-30T08:06:20.000Z
126+ body: |
127+ Implemented on `feature/compaction-turns` (not committed).
128+
129+ - Config `context.inTurnTarget` (int %, default 0 = two thirds of `threshold`; validated 0..threshold).
130+ - `compact.Budget.Target`, `target()`, `aboveTarget()` (new file `internal/compact/budget.go`, with `shrinkTail` and `summaryCut`, to keep inturn.go under the complexity gate).
131+ - `CompactTurn`: trigger unchanged (threshold); shrink the older exchanges, summarise while above the TARGET (summaryCut keeps as many exchanges as fit under it), then, as a last resort, `shrinkTail` shrinks the kept exchanges but the last one. Summary before tail shrink on purpose: a first version shrank the tail first, the summary never ran and the model lost its last reads without notes (4 tests caught it).
132+ - Demo `demos/inkling-2-mini/.mm/agent.yaml`: `inTurnTarget: 40` (threshold 60) and `summaryMaxTokens: 1600`, both with the measured reason.
133+
134+ Tests: `TestBudgetTarget`, `TestCompactTurnGoesDownToTheTarget` (the Inkling shape: ≥ 2 calls before the next compression, ≤ 1 without the target), `TestCompactTurnShrinksTheTailAsALastResort`, `TestInTurnTarget` (config); the #291 end-to-end scenario went from 10 compressions / 8 summaries to 5 / 3 for 12 calls. `go test ./... -count=1` green; gate: mm 0 smells. Docs EN+FR. Left: task 7, the measure on the demo.
135+ - id: 4
136+ author:
137+ name: k33g
138+ email: ph.charriere@gmail.com
139+ createdAt: 2026-11-30T08:38:53.000Z
140+ body: |
141+ Closed at the user's request for release v2.2.1 (merged from `feature/compaction-turns`). Closed without the demo re-run it asked for: title: "Measure cached_tokens and time per call on the Inkling demo" — to be checked on the next Inkling run.
new file mode 100644
@@ -0,0 +1,141 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 290
3+title: "In-turn compression: go down to a lower target, so the next calls keep the prompt cache"
4+state: closed
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-30T02:24:02.000Z
9+updatedAt: 2026-11-30T08:38:53.000Z
10+labels:
11+ - enhancement
12+ - kind::feature
13+ - priority::medium
14+ - To be tested
15+milestone: v2.2.1
16+epic: Loop
17+related:
18+ - 289
19+ - 251
20+ - 291
21+body: |
22+ Rewritten on 2026-11-30 (comment 1 says why). Follows [#291 — In-turn compression ignores the server's token count](.tickets/issues/0291-in-turn-compression-ignores-the-server-s-token-cou.yaml).
23+
24+ ## Problem
25+
26+ The in-turn compression (`compact.CompactTurn`) fires when the request passes `context.threshold`, and compresses **just enough** to get back under it. The next tool result passes the threshold again, so the turn is compressed again before the next call, and so on:
27+
28+ - each compression rewrites the prompt (a shrunk result, notes added to the question near the top), so the server's prefix cache misses on the next call: the whole prompt is read again (~3 min for 17k tokens with Inkling-2-Mini on razorbill);
29+ - each summary is one more model request (~1200 tokens out), and the model loses a little more of what it read.
30+
31+ Seen in `TestGenerateSummarisesOnTheServersCount` (`internal/engine/calibrate_test.go`): window 8000, threshold 6000, each read ~1.6k calibrated tokens. After #291, the turn is summarised before nearly every call (`8.4k → 5.1k`, then the next read brings it back to 6.7k).
32+
33+ ## Proposed change
34+
35+ Hysteresis: the trigger stays at `threshold`, but once it fires, the compression goes down to a lower **target** — for example two thirds of the threshold (75 → 50 %, 60 → 40 %), or a `context.inTurnTarget` key if a fixed rule is not enough.
36+
37+ - The shrink step is unchanged (older than the last 4 exchanges).
38+ - The summary is made when the shrunk history is still above the **target** (not the threshold), and `summaryCut` keeps as many exchanges as fit under the target (at least 1).
39+ - The floor check (#289) and the "not sent" guard (#291) keep their current limits (threshold, window).
40+
41+ Then several calls follow a compression without touching the prompt, and they get the prefix cache.
42+
43+ ## Acceptance criteria
44+
45+ - [ ] Unit test: after one compression, a turn that grows by one exchange per call goes several calls without a new compression (no rewrite of the earlier messages).
46+ - [ ] End-to-end test: fewer summaries than calls in `TestGenerateSummarisesOnTheServersCount`'s scenario.
47+ - [ ] Measured on the Inkling demo: `cached_tokens` present on the calls between two compressions, and the time per call.
48+ - [ ] Docs EN+FR (configuration reference, context-compression explanation).
49+tasks:
50+ - id: 4
51+ title: "Compress down to a target below the threshold (summary decision and summaryCut)"
52+ state: closed
53+ priority: none
54+ author:
55+ name: k33g
56+ email: ph.charriere@gmail.com
57+ createdAt: 2026-11-30T03:33:26.000Z
58+ updatedAt: 2026-11-30T08:06:20.000Z
59+ closedAt: 2026-11-30T08:06:20.000Z
60+ - id: 5
61+ title: "Unit test: several calls without a new compression after one"
62+ state: closed
63+ priority: none
64+ author:
65+ name: k33g
66+ email: ph.charriere@gmail.com
67+ createdAt: 2026-11-30T03:33:26.000Z
68+ updatedAt: 2026-11-30T08:06:20.000Z
69+ closedAt: 2026-11-30T08:06:20.000Z
70+ - id: 6
71+ title: "End-to-end test: fewer summaries than calls"
72+ state: closed
73+ priority: none
74+ author:
75+ name: k33g
76+ email: ph.charriere@gmail.com
77+ createdAt: 2026-11-30T03:33:26.000Z
78+ updatedAt: 2026-11-30T08:06:20.000Z
79+ closedAt: 2026-11-30T08:06:20.000Z
80+ - id: 7
81+ title: "Measure cached_tokens and time per call on the Inkling demo"
82+ state: closed
83+ priority: none
84+ author:
85+ name: k33g
86+ email: ph.charriere@gmail.com
87+ createdAt: 2026-11-30T03:33:26.000Z
88+ updatedAt: 2026-11-30T08:38:53.000Z
89+ closedAt: 2026-11-30T08:38:53.000Z
90+ - id: 8
91+ title: "Docs EN+FR"
92+ state: closed
93+ priority: none
94+ author:
95+ name: k33g
96+ email: ph.charriere@gmail.com
97+ createdAt: 2026-11-30T03:33:26.000Z
98+ updatedAt: 2026-11-30T08:06:20.000Z
99+ closedAt: 2026-11-30T08:06:20.000Z
100+comments:
101+ - id: 1
102+ author:
103+ name: k33g
104+ email: ph.charriere@gmail.com
105+ createdAt: 2026-11-30T03:33:26.000Z
106+ body: |
107+ Rewritten. The first version ("cut an old tool result once") rested on a wrong premise: `shrink` already cuts a result once — `headLine` leaves at most ~350 characters, under `shrinkOver` (400), so a shrunk result is never shrunk again. Its tasks 1-3 were dropped. The cache misses come from compressing again at nearly every call; this ticket is now about that.
108+ - id: 2
109+ author:
110+ name: k33g
111+ email: ph.charriere@gmail.com
112+ createdAt: 2026-11-30T04:20:30.000Z
113+ body: |
114+ Measured with the #289 + #291 binary, `demos/inkling-2-mini` (threshold 60, maxOutput 2500, keepLastTurns 1), traces 2026-11-30 04:32 → 05:07, calls 0001-0042:
115+
116+ - No stall, no "not sent": the prompt stays at 7.2-10k tokens of a 16k window; calibration ratio ≈ 1.8.
117+ - **18 of 41 calls without cache**, ~98 s each, against ~13 s for a cached call: **29.5 of the 34.5 minutes** are spent re-reading the prompt.
118+ - Calls 0011-0022: the prefix breaks one call in two (shrink, then a read brings it back over the threshold). Calls 0024-0029: every call (1.5-4.5 min each). Only one summary in the whole run (0030).
119+
120+ Design consequence: the target must apply to the **shrink step too**, not only to the summary. Today a shrink cuts what is older than the last 4 exchanges, gets just under the threshold, and the next read passes it again: one shrink per call or two, each one a cache miss. With a target, a compression must shrink (and, if needed, summarise) until the history is under the target — for example by keeping fewer raw exchanges than 4 when the threshold is passed — so that several calls follow without touching the prompt.
121+ - id: 3
122+ author:
123+ name: k33g
124+ email: ph.charriere@gmail.com
125+ createdAt: 2026-11-30T08:06:20.000Z
126+ body: |
127+ Implemented on `feature/compaction-turns` (not committed).
128+
129+ - Config `context.inTurnTarget` (int %, default 0 = two thirds of `threshold`; validated 0..threshold).
130+ - `compact.Budget.Target`, `target()`, `aboveTarget()` (new file `internal/compact/budget.go`, with `shrinkTail` and `summaryCut`, to keep inturn.go under the complexity gate).
131+ - `CompactTurn`: trigger unchanged (threshold); shrink the older exchanges, summarise while above the TARGET (summaryCut keeps as many exchanges as fit under it), then, as a last resort, `shrinkTail` shrinks the kept exchanges but the last one. Summary before tail shrink on purpose: a first version shrank the tail first, the summary never ran and the model lost its last reads without notes (4 tests caught it).
132+ - Demo `demos/inkling-2-mini/.mm/agent.yaml`: `inTurnTarget: 40` (threshold 60) and `summaryMaxTokens: 1600`, both with the measured reason.
133+
134+ Tests: `TestBudgetTarget`, `TestCompactTurnGoesDownToTheTarget` (the Inkling shape: ≥ 2 calls before the next compression, ≤ 1 without the target), `TestCompactTurnShrinksTheTailAsALastResort`, `TestInTurnTarget` (config); the #291 end-to-end scenario went from 10 compressions / 8 summaries to 5 / 3 for 12 calls. `go test ./... -count=1` green; gate: mm 0 smells. Docs EN+FR. Left: task 7, the measure on the demo.
135+ - id: 4
136+ author:
137+ name: k33g
138+ email: ph.charriere@gmail.com
139+ createdAt: 2026-11-30T08:38:53.000Z
140+ body: |
141+ Closed at the user's request for release v2.2.1 (merged from `feature/compaction-turns`). Closed without the demo re-run it asked for: title: "Measure cached_tokens and time per call on the Inkling demo" — to be checked on the next Inkling run.
added .tickets/issues/0291-in-turn-compression-ignores-the-server-s-token-cou.yaml +83 -0
new file mode 100644
@@ -0,0 +1,83 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 291
3+title: "In-turn compression ignores the server's token count: shrink only, every call, until a stall"
4+state: closed
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-30T03:14:25.000Z
9+updatedAt: 2026-11-30T08:39:04.000Z
10+labels:
11+ - bug
12+ - kind::bug
13+ - priority::high
14+ - To be tested
15+milestone: v2.2.1
16+epic: Loop
17+related:
18+ - 289
19+ - 290
20+ - 251
21+body: |
22+ ## Observed
23+
24+ `demos/inkling-2-mini`, 2026-11-30, two runs of "finish the front of this application" (one turn each, no injected message: #289 does not apply). Config: `contextWindow: 16384`, `threshold: 75` (12.3k tokens), `keepLastTurns: 1`, razorbill, Inkling-2-Mini. Both runs end with `generation timed out (stalled)`: the server sends only `: keep-alive` for 10 min (`watchdogTimeout`).
25+
26+ Second run (traces `20261130-0340…` to `-034956`, nestor-0001 to 0011):
27+
28+ | Call | Messages | Server prompt_tokens | cached_tokens | mm Estimate | Prefix kept |
29+ | --- | --- | --- | --- | --- | --- |
30+ | 0008 | 16 | 17169 | 8989 | 8384 | 14/14 |
31+ | 0009 | 18 | 17176 | none | 8223 | 5/16 |
32+ | 0010 | 20 | 17226 | none | 8279 | 11/18 |
33+ | 0011 | 22 | (stalled) | | 8322 | 13/20 |
34+
35+ The first run shows the same pattern at 11.5-13.8k tokens: one call in two breaks the prefix, and it stalls at 0016.
36+
37+ ## Root cause
38+
39+ `compact.Estimate` (chars / 3.5) is **half** of the real count here: 28.8k characters of Go, HTML and shell output come to 15-17k tokens with Inkling's tokenizer (≈ 1.8 chars/token), plus 5k characters of tool schemas the estimate never sees.
40+
41+ - `InTurnDecide` takes `max(Estimate, measured)`: the server's 17k passes the threshold, so it fires before every call.
42+ - `CompactTurn` then decides the summary on `Estimate(out)` alone, about 8k, under the threshold: **it never summarises**. It only shrinks the exchange that just left the last 4. The model reads a new 5k chunk at each step, so the prompt stays at 17k, above the 16k window too.
43+ - Each shrink rewrites a message in the middle of the prompt, so the prefix cache misses on every call: 17k tokens re-read each time (~3 min), until the server stops answering.
44+ - The #289 floor check uses `Estimate` too, so it would miss a high floor here as well.
45+
46+ ## Proposed change
47+
48+ Calibrate the estimate with the server's measure: pass `measured` to `CompactTurn`, take `ratio = measured / Estimate(msgs)` when the measure is larger, and scale the estimates used for the summary decision and for the floor. Then, in this case, the first compression would summarise down under the threshold, and the following calls would keep the prefix.
49+
50+ ## Acceptance criteria
51+
52+ - [ ] With a measure twice the estimate, above the threshold, `CompactTurn` summarises (unit test).
53+ - [ ] The floor check uses the calibrated figure.
54+ - [ ] Without a measure (0), the behaviour is the current one.
55+ - [ ] Re-run of the demo: no "shrink only" series, cached_tokens back on the calls after a compression.
56+
57+ The stall itself is on the server side (razorbill/MLX: no first token in 10 min for a 17k-token prompt that took ~3 min the call before). mm makes it likely by sending prompts above the declared window, without cache, at every call.
58+tasks: []
59+comments:
60+ - id: 1
61+ author:
62+ name: k33g
63+ email: ph.charriere@gmail.com
64+ createdAt: 2026-11-30T03:30:13.000Z
65+ body: |
66+ Implemented on branch `feature/compaction-turns` (not committed), with the user's go for points 1, 2 and 4.
67+
68+ - `internal/compact/calibrate.go`: `Calibration` (ratio + tools estimate), `Calibrate`, `EstimateTools`; ratio capped at 4, never below 1.
69+ - `compact.Budget` (window, threshold, calibration): `CompactTurn(ctx, msgs, budget, summarize)` and `InTurnDecide(…, cal, cfg)` decide, summarise, and check the floor on the calibrated size; the report figures are calibrated too.
70+ - `summaryCut`: when the last 4 exchanges alone pass the threshold, the summary keeps fewer (as many as fit, at least 1); when not even 1 fits, all 4 stay.
71+ - Engine: `recordUsage` stores the ratio (`Engine.ratio`, survives `ForgetInputTokens`). `compactInTurn` returns `requestTooBig` when the compressed request is still larger than the window: not sent, the turn ends with the overflow line (never retried), `t.full` keeps the work (`turn.compressBeforeCall`).
72+ - Demo `demos/inkling-2-mini/.mm/agent.yaml`: `threshold: 60`, `maxOutput: 2500` (that folder is untracked and `.mm/` gitignored).
73+
74+ Tests: new `calibrate_test.go` in compact and engine (incl. end to end through Generate with a server counting 2× the estimate). `go test ./... -count=1` green. Quality: mm's code 0 smells; the gate FAILS only on `demos/inkling-2-mini/tickets/` (the app the demo agent writes: 14 smells, 1 CVE warning in its go.mod, 2 gofmt) — user to decide.
75+
76+ Seen in the end-to-end test: when each tool result adds a large share of the window, the turn is summarised before nearly every call (each summary lands just under the threshold, the next read passes it again). That is #290 rewritten as hysteresis: compress to a lower target.
77+ - id: 2
78+ author:
79+ name: k33g
80+ email: ph.charriere@gmail.com
81+ createdAt: 2026-11-30T08:39:04.000Z
82+ body: |
83+ Closed at the user's request for release v2.2.1 (merged from `feature/compaction-turns`).
new file mode 100644
@@ -0,0 +1,83 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 291
3+title: "In-turn compression ignores the server's token count: shrink only, every call, until a stall"
4+state: closed
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-30T03:14:25.000Z
9+updatedAt: 2026-11-30T08:39:04.000Z
10+labels:
11+ - bug
12+ - kind::bug
13+ - priority::high
14+ - To be tested
15+milestone: v2.2.1
16+epic: Loop
17+related:
18+ - 289
19+ - 290
20+ - 251
21+body: |
22+ ## Observed
23+
24+ `demos/inkling-2-mini`, 2026-11-30, two runs of "finish the front of this application" (one turn each, no injected message: #289 does not apply). Config: `contextWindow: 16384`, `threshold: 75` (12.3k tokens), `keepLastTurns: 1`, razorbill, Inkling-2-Mini. Both runs end with `generation timed out (stalled)`: the server sends only `: keep-alive` for 10 min (`watchdogTimeout`).
25+
26+ Second run (traces `20261130-0340…` to `-034956`, nestor-0001 to 0011):
27+
28+ | Call | Messages | Server prompt_tokens | cached_tokens | mm Estimate | Prefix kept |
29+ | --- | --- | --- | --- | --- | --- |
30+ | 0008 | 16 | 17169 | 8989 | 8384 | 14/14 |
31+ | 0009 | 18 | 17176 | none | 8223 | 5/16 |
32+ | 0010 | 20 | 17226 | none | 8279 | 11/18 |
33+ | 0011 | 22 | (stalled) | | 8322 | 13/20 |
34+
35+ The first run shows the same pattern at 11.5-13.8k tokens: one call in two breaks the prefix, and it stalls at 0016.
36+
37+ ## Root cause
38+
39+ `compact.Estimate` (chars / 3.5) is **half** of the real count here: 28.8k characters of Go, HTML and shell output come to 15-17k tokens with Inkling's tokenizer (≈ 1.8 chars/token), plus 5k characters of tool schemas the estimate never sees.
40+
41+ - `InTurnDecide` takes `max(Estimate, measured)`: the server's 17k passes the threshold, so it fires before every call.
42+ - `CompactTurn` then decides the summary on `Estimate(out)` alone, about 8k, under the threshold: **it never summarises**. It only shrinks the exchange that just left the last 4. The model reads a new 5k chunk at each step, so the prompt stays at 17k, above the 16k window too.
43+ - Each shrink rewrites a message in the middle of the prompt, so the prefix cache misses on every call: 17k tokens re-read each time (~3 min), until the server stops answering.
44+ - The #289 floor check uses `Estimate` too, so it would miss a high floor here as well.
45+
46+ ## Proposed change
47+
48+ Calibrate the estimate with the server's measure: pass `measured` to `CompactTurn`, take `ratio = measured / Estimate(msgs)` when the measure is larger, and scale the estimates used for the summary decision and for the floor. Then, in this case, the first compression would summarise down under the threshold, and the following calls would keep the prefix.
49+
50+ ## Acceptance criteria
51+
52+ - [ ] With a measure twice the estimate, above the threshold, `CompactTurn` summarises (unit test).
53+ - [ ] The floor check uses the calibrated figure.
54+ - [ ] Without a measure (0), the behaviour is the current one.
55+ - [ ] Re-run of the demo: no "shrink only" series, cached_tokens back on the calls after a compression.
56+
57+ The stall itself is on the server side (razorbill/MLX: no first token in 10 min for a 17k-token prompt that took ~3 min the call before). mm makes it likely by sending prompts above the declared window, without cache, at every call.
58+tasks: []
59+comments:
60+ - id: 1
61+ author:
62+ name: k33g
63+ email: ph.charriere@gmail.com
64+ createdAt: 2026-11-30T03:30:13.000Z
65+ body: |
66+ Implemented on branch `feature/compaction-turns` (not committed), with the user's go for points 1, 2 and 4.
67+
68+ - `internal/compact/calibrate.go`: `Calibration` (ratio + tools estimate), `Calibrate`, `EstimateTools`; ratio capped at 4, never below 1.
69+ - `compact.Budget` (window, threshold, calibration): `CompactTurn(ctx, msgs, budget, summarize)` and `InTurnDecide(…, cal, cfg)` decide, summarise, and check the floor on the calibrated size; the report figures are calibrated too.
70+ - `summaryCut`: when the last 4 exchanges alone pass the threshold, the summary keeps fewer (as many as fit, at least 1); when not even 1 fits, all 4 stay.
71+ - Engine: `recordUsage` stores the ratio (`Engine.ratio`, survives `ForgetInputTokens`). `compactInTurn` returns `requestTooBig` when the compressed request is still larger than the window: not sent, the turn ends with the overflow line (never retried), `t.full` keeps the work (`turn.compressBeforeCall`).
72+ - Demo `demos/inkling-2-mini/.mm/agent.yaml`: `threshold: 60`, `maxOutput: 2500` (that folder is untracked and `.mm/` gitignored).
73+
74+ Tests: new `calibrate_test.go` in compact and engine (incl. end to end through Generate with a server counting 2× the estimate). `go test ./... -count=1` green. Quality: mm's code 0 smells; the gate FAILS only on `demos/inkling-2-mini/tickets/` (the app the demo agent writes: 14 smells, 1 CVE warning in its go.mod, 2 gofmt) — user to decide.
75+
76+ Seen in the end-to-end test: when each tool result adds a large share of the window, the turn is summarised before nearly every call (each summary lands just under the threshold, the next read passes it again). That is #290 rewritten as hysteresis: compress to a lower target.
77+ - id: 2
78+ author:
79+ name: k33g
80+ email: ph.charriere@gmail.com
81+ createdAt: 2026-11-30T08:39:04.000Z
82+ body: |
83+ Closed at the user's request for release v2.2.1 (merged from `feature/compaction-turns`).
added .tickets/issues/0292-re-read-cycle-the-model-reads-the-same-files-agai.yaml +157 -0
new file mode 100644
@@ -0,0 +1,157 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 292
3+title: "Re-read cycle: the model reads the same files again and again when they do not fit the window"
4+state: closed
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-30T04:25:36.000Z
9+updatedAt: 2026-11-30T08:39:04.000Z
10+labels:
11+ - bug
12+ - kind::bug
13+ - priority::high
14+ - To be tested
15+milestone: v2.2.1
16+epic: Loop
17+related:
18+ - 289
19+ - 290
20+ - 291
21+body: |
22+ ## Observed
23+
24+ `demos/inkling-2-mini`, 2026-11-30 04:32-05:07, binary with #289 and #291. "finish the front of this application" ended with `exceeded maximum tool call iterations (40)`: 40 tool calls, **all reads, no write**. `server.go` was read in the same `sed -n` ranges 4 times (calls 0013-16, 0019-22, 0027-31, 0040-42), `store.go` 3-4 times (0008-11, 0023-26, 0033-36).
25+
26+ ## Cause
27+
28+ - The two files (~1000 lines, 15-20k tokens with Inkling's tokenizer) do not fit the 16k window. The model reads them in chunks; by the end, the first chunks were shrunk to their first line (`package server`), so it starts again.
29+ - The in-turn summary prompt says "Do not quote file contents": the routes, signatures and JSON fields the front end needs are exactly what it drops.
30+ - The loop detector does not see it: a cycle of 4 different commands, not one command repeated.
31+
32+ ## Proposed changes
33+
34+ 1. **Shrink code to its outline.** A long tool result (or a long write_file argument) that holds declarations keeps them — `func`, `type`, struct fields with JSON tags, routes, classes, functions — instead of its first line only. A shrunk message is never shrunk again.
35+ 2. **In-turn notes keep the API.** The in-turn summary prompt asks for the declarations another step needs (signatures, routes, types and fields), not the code bodies.
36+ 3. **Say when a dropped result is read again.** A tool call identical to one already run in the turn, after a compression dropped its result, gets a note in its result: read before, dropped to make room; write notes or start the change. In the tool result, not a user message (no new turn, see #289).
37+
38+ ## Acceptance criteria
39+
40+ - [ ] A shrunk Go file keeps its func/type/route lines; text without declarations keeps its first line as today.
41+ - [ ] Shrinking a shrunk message changes nothing.
42+ - [ ] The in-turn prompt asks for signatures, routes and types.
43+ - [ ] A repeated command after a compression gets the note; before any compression, or a new command, it does not.
44+ - [ ] Re-run of the demo: fewer repeated reads, at least one write before maxTurns.
45+tasks:
46+ - id: 1
47+ title: "Shrink a code result or argument to its outline"
48+ state: closed
49+ priority: none
50+ author:
51+ name: k33g
52+ email: ph.charriere@gmail.com
53+ createdAt: 2026-11-30T04:25:36.000Z
54+ updatedAt: 2026-11-30T04:31:17.000Z
55+ closedAt: 2026-11-30T04:31:17.000Z
56+ - id: 2
57+ title: "A shrunk message is never shrunk again"
58+ state: closed
59+ priority: none
60+ author:
61+ name: k33g
62+ email: ph.charriere@gmail.com
63+ createdAt: 2026-11-30T04:25:36.000Z
64+ updatedAt: 2026-11-30T04:31:17.000Z
65+ closedAt: 2026-11-30T04:31:17.000Z
66+ - id: 3
67+ title: "In-turn summary prompt keeps signatures, routes and types"
68+ state: closed
69+ priority: none
70+ author:
71+ name: k33g
72+ email: ph.charriere@gmail.com
73+ createdAt: 2026-11-30T04:25:36.000Z
74+ updatedAt: 2026-11-30T04:31:17.000Z
75+ closedAt: 2026-11-30T04:31:17.000Z
76+ - id: 4
77+ title: "Note on a tool call repeated after a compression dropped its result"
78+ state: closed
79+ priority: none
80+ author:
81+ name: k33g
82+ email: ph.charriere@gmail.com
83+ createdAt: 2026-11-30T04:25:36.000Z
84+ updatedAt: 2026-11-30T04:31:17.000Z
85+ closedAt: 2026-11-30T04:31:17.000Z
86+ - id: 5
87+ title: "Docs EN+FR"
88+ state: closed
89+ priority: none
90+ author:
91+ name: k33g
92+ email: ph.charriere@gmail.com
93+ createdAt: 2026-11-30T04:25:36.000Z
94+ updatedAt: 2026-11-30T04:31:17.000Z
95+ closedAt: 2026-11-30T04:31:17.000Z
96+ - id: 6
97+ title: "Re-run the Inkling demo"
98+ state: closed
99+ priority: none
100+ author:
101+ name: k33g
102+ email: ph.charriere@gmail.com
103+ createdAt: 2026-11-30T04:25:36.000Z
104+ updatedAt: 2026-11-30T08:39:04.000Z
105+ closedAt: 2026-11-30T08:39:04.000Z
106+comments:
107+ - id: 1
108+ author:
109+ name: k33g
110+ email: ph.charriere@gmail.com
111+ createdAt: 2026-11-30T04:31:17.000Z
112+ body: |
113+ Implemented on `feature/compaction-turns` (not committed).
114+
115+ - `internal/compact/outline.go`: `shortened` = outline (declaration lines: Go func/type, JSON-tagged fields, routes, JS/TS/Python/Rust/Java declarations, `fetch(`; at least 3, at most 2000 characters, only when at most half of the text) or the first line as before. On real server.go/store.go chunks from the traces: 2539 → 1103 and 2538 → 788 characters, handlers, types and JSON fields kept.
116+ - `shrink` skips a message tagged `shrunk` (an outline can exceed 400 characters).
117+ - `turnPrompt`: keeps signatures, routes (method, path, handler), types with fields and JSON names; no bodies; 40 lines max.
118+ - `internal/engine/reread.go`: `rereads` (per turn, mutex) + `wrap` around `wrapTool` (registered in `turn.options`, so turn.go stays under the complexity gate). The note goes before a string tool output, never as a user message.
119+
120+ Tests green (`go test ./... -count=1`), incl. an end-to-end cycle of 6 reads on a small window. Quality: mm's code 0 smells; the gate still fails only on `demos/inkling-2-mini/tickets/`. Docs EN+FR updated. Left: task 6, the demo re-run.
121+ - id: 2
122+ author:
123+ name: k33g
124+ email: ph.charriere@gmail.com
125+ createdAt: 2026-11-30T05:59:51.000Z
126+ body: |
127+ Re-run 2026-11-30 05:33-06:27 with the first #292 binary: maxTurns 40 again, reads only — but outlines present, 6 re-read notes, 6 in-turn summaries whose notes held the whole API (20 routes, handlers, request shapes). What kept the model reading: mm's own notes wrapper ("re-read a file or re-run a command before relying on it"), the notes' "Remaining: read full type definitions … must read before editing", and a note that never escalates.
128+
129+ Fixed on the same branch: the wrapper now says the notes are what is needed and to re-read only the lines the next change needs; the in-turn prompt ends the notes with the next concrete change (file + content), "not more reading"; from the 2nd re-read of a turn, the note is "re-read number N — you are reading in circles … Stop reading. Make the first change now". Tests green; docs EN+FR updated.
130+ - id: 3
131+ author:
132+ name: k33g
133+ email: ph.charriere@gmail.com
134+ createdAt: 2026-11-30T08:06:20.000Z
135+ body: |
136+ Re-run 07:10-08:08 (round-2 binary): still reads only; the "Stop reading" notes were ignored, and 5 of 6 in-turn summaries were cut at max_tokens 1200 (finish_reason length), so the "next change" line asked at the END was never written.
137+
138+ Fixed: the in-turn notes START with "Next change: …"; `engine.Summarize` detects finish_reason length, drops the unfinished last line, appends "- [notes cut at the length limit]" and shows "🗜️ a summary was cut at its limit (N tokens)…" once per run (both summary kinds). Not done (user's decision pending): refusing to run a read repeated 3 times.
139+ - id: 4
140+ author:
141+ name: k33g
142+ email: ph.charriere@gmail.com
143+ createdAt: 2026-11-30T08:17:33.000Z
144+ body: |
145+ User's go ("oui refuser une 3eme relecture identique (c'est parametrable ?)"): implemented, configurable.
146+
147+ - `context.rereadLimit` (int, default 1, ≥ 0): re-reads of the same call allowed per turn; past it the call is NOT run, its result is "[mm: not run — this exact call already ran N times in this task … make the change now …]" and the user sees "🔁 not run: <tool>, the same call for the Nth time …". 0 = notes only.
148+ - A re-read = same tool + same JSON args (the existing `callKey` of toolschema.go), a compression since its last run, and NO successful write_file/edit_file since — so `go test` after a fix is never counted (bash edits are not seen). A refused call keeps its state: asking again at once is refused again.
149+ - Demo agent.yaml: `rereadLimit: 1` with the measured reason.
150+ - Tests: unit (limit, change resets, refusal repeated, 0 = never), end to end (3 rounds of 6 reads: the third round is refused, the tool does not run), config default/validation. Docs EN+FR.
151+ - id: 5
152+ author:
153+ name: k33g
154+ email: ph.charriere@gmail.com
155+ createdAt: 2026-11-30T08:39:04.000Z
156+ body: |
157+ Closed at the user's request for release v2.2.1 (merged from `feature/compaction-turns`). Closed without the demo re-run it asked for: title: "Re-run the Inkling demo" — to be checked on the next Inkling run.
new file mode 100644
@@ -0,0 +1,157 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 292
3+title: "Re-read cycle: the model reads the same files again and again when they do not fit the window"
4+state: closed
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-30T04:25:36.000Z
9+updatedAt: 2026-11-30T08:39:04.000Z
10+labels:
11+ - bug
12+ - kind::bug
13+ - priority::high
14+ - To be tested
15+milestone: v2.2.1
16+epic: Loop
17+related:
18+ - 289
19+ - 290
20+ - 291
21+body: |
22+ ## Observed
23+
24+ `demos/inkling-2-mini`, 2026-11-30 04:32-05:07, binary with #289 and #291. "finish the front of this application" ended with `exceeded maximum tool call iterations (40)`: 40 tool calls, **all reads, no write**. `server.go` was read in the same `sed -n` ranges 4 times (calls 0013-16, 0019-22, 0027-31, 0040-42), `store.go` 3-4 times (0008-11, 0023-26, 0033-36).
25+
26+ ## Cause
27+
28+ - The two files (~1000 lines, 15-20k tokens with Inkling's tokenizer) do not fit the 16k window. The model reads them in chunks; by the end, the first chunks were shrunk to their first line (`package server`), so it starts again.
29+ - The in-turn summary prompt says "Do not quote file contents": the routes, signatures and JSON fields the front end needs are exactly what it drops.
30+ - The loop detector does not see it: a cycle of 4 different commands, not one command repeated.
31+
32+ ## Proposed changes
33+
34+ 1. **Shrink code to its outline.** A long tool result (or a long write_file argument) that holds declarations keeps them — `func`, `type`, struct fields with JSON tags, routes, classes, functions — instead of its first line only. A shrunk message is never shrunk again.
35+ 2. **In-turn notes keep the API.** The in-turn summary prompt asks for the declarations another step needs (signatures, routes, types and fields), not the code bodies.
36+ 3. **Say when a dropped result is read again.** A tool call identical to one already run in the turn, after a compression dropped its result, gets a note in its result: read before, dropped to make room; write notes or start the change. In the tool result, not a user message (no new turn, see #289).
37+
38+ ## Acceptance criteria
39+
40+ - [ ] A shrunk Go file keeps its func/type/route lines; text without declarations keeps its first line as today.
41+ - [ ] Shrinking a shrunk message changes nothing.
42+ - [ ] The in-turn prompt asks for signatures, routes and types.
43+ - [ ] A repeated command after a compression gets the note; before any compression, or a new command, it does not.
44+ - [ ] Re-run of the demo: fewer repeated reads, at least one write before maxTurns.
45+tasks:
46+ - id: 1
47+ title: "Shrink a code result or argument to its outline"
48+ state: closed
49+ priority: none
50+ author:
51+ name: k33g
52+ email: ph.charriere@gmail.com
53+ createdAt: 2026-11-30T04:25:36.000Z
54+ updatedAt: 2026-11-30T04:31:17.000Z
55+ closedAt: 2026-11-30T04:31:17.000Z
56+ - id: 2
57+ title: "A shrunk message is never shrunk again"
58+ state: closed
59+ priority: none
60+ author:
61+ name: k33g
62+ email: ph.charriere@gmail.com
63+ createdAt: 2026-11-30T04:25:36.000Z
64+ updatedAt: 2026-11-30T04:31:17.000Z
65+ closedAt: 2026-11-30T04:31:17.000Z
66+ - id: 3
67+ title: "In-turn summary prompt keeps signatures, routes and types"
68+ state: closed
69+ priority: none
70+ author:
71+ name: k33g
72+ email: ph.charriere@gmail.com
73+ createdAt: 2026-11-30T04:25:36.000Z
74+ updatedAt: 2026-11-30T04:31:17.000Z
75+ closedAt: 2026-11-30T04:31:17.000Z
76+ - id: 4
77+ title: "Note on a tool call repeated after a compression dropped its result"
78+ state: closed
79+ priority: none
80+ author:
81+ name: k33g
82+ email: ph.charriere@gmail.com
83+ createdAt: 2026-11-30T04:25:36.000Z
84+ updatedAt: 2026-11-30T04:31:17.000Z
85+ closedAt: 2026-11-30T04:31:17.000Z
86+ - id: 5
87+ title: "Docs EN+FR"
88+ state: closed
89+ priority: none
90+ author:
91+ name: k33g
92+ email: ph.charriere@gmail.com
93+ createdAt: 2026-11-30T04:25:36.000Z
94+ updatedAt: 2026-11-30T04:31:17.000Z
95+ closedAt: 2026-11-30T04:31:17.000Z
96+ - id: 6
97+ title: "Re-run the Inkling demo"
98+ state: closed
99+ priority: none
100+ author:
101+ name: k33g
102+ email: ph.charriere@gmail.com
103+ createdAt: 2026-11-30T04:25:36.000Z
104+ updatedAt: 2026-11-30T08:39:04.000Z
105+ closedAt: 2026-11-30T08:39:04.000Z
106+comments:
107+ - id: 1
108+ author:
109+ name: k33g
110+ email: ph.charriere@gmail.com
111+ createdAt: 2026-11-30T04:31:17.000Z
112+ body: |
113+ Implemented on `feature/compaction-turns` (not committed).
114+
115+ - `internal/compact/outline.go`: `shortened` = outline (declaration lines: Go func/type, JSON-tagged fields, routes, JS/TS/Python/Rust/Java declarations, `fetch(`; at least 3, at most 2000 characters, only when at most half of the text) or the first line as before. On real server.go/store.go chunks from the traces: 2539 → 1103 and 2538 → 788 characters, handlers, types and JSON fields kept.
116+ - `shrink` skips a message tagged `shrunk` (an outline can exceed 400 characters).
117+ - `turnPrompt`: keeps signatures, routes (method, path, handler), types with fields and JSON names; no bodies; 40 lines max.
118+ - `internal/engine/reread.go`: `rereads` (per turn, mutex) + `wrap` around `wrapTool` (registered in `turn.options`, so turn.go stays under the complexity gate). The note goes before a string tool output, never as a user message.
119+
120+ Tests green (`go test ./... -count=1`), incl. an end-to-end cycle of 6 reads on a small window. Quality: mm's code 0 smells; the gate still fails only on `demos/inkling-2-mini/tickets/`. Docs EN+FR updated. Left: task 6, the demo re-run.
121+ - id: 2
122+ author:
123+ name: k33g
124+ email: ph.charriere@gmail.com
125+ createdAt: 2026-11-30T05:59:51.000Z
126+ body: |
127+ Re-run 2026-11-30 05:33-06:27 with the first #292 binary: maxTurns 40 again, reads only — but outlines present, 6 re-read notes, 6 in-turn summaries whose notes held the whole API (20 routes, handlers, request shapes). What kept the model reading: mm's own notes wrapper ("re-read a file or re-run a command before relying on it"), the notes' "Remaining: read full type definitions … must read before editing", and a note that never escalates.
128+
129+ Fixed on the same branch: the wrapper now says the notes are what is needed and to re-read only the lines the next change needs; the in-turn prompt ends the notes with the next concrete change (file + content), "not more reading"; from the 2nd re-read of a turn, the note is "re-read number N — you are reading in circles … Stop reading. Make the first change now". Tests green; docs EN+FR updated.
130+ - id: 3
131+ author:
132+ name: k33g
133+ email: ph.charriere@gmail.com
134+ createdAt: 2026-11-30T08:06:20.000Z
135+ body: |
136+ Re-run 07:10-08:08 (round-2 binary): still reads only; the "Stop reading" notes were ignored, and 5 of 6 in-turn summaries were cut at max_tokens 1200 (finish_reason length), so the "next change" line asked at the END was never written.
137+
138+ Fixed: the in-turn notes START with "Next change: …"; `engine.Summarize` detects finish_reason length, drops the unfinished last line, appends "- [notes cut at the length limit]" and shows "🗜️ a summary was cut at its limit (N tokens)…" once per run (both summary kinds). Not done (user's decision pending): refusing to run a read repeated 3 times.
139+ - id: 4
140+ author:
141+ name: k33g
142+ email: ph.charriere@gmail.com
143+ createdAt: 2026-11-30T08:17:33.000Z
144+ body: |
145+ User's go ("oui refuser une 3eme relecture identique (c'est parametrable ?)"): implemented, configurable.
146+
147+ - `context.rereadLimit` (int, default 1, ≥ 0): re-reads of the same call allowed per turn; past it the call is NOT run, its result is "[mm: not run — this exact call already ran N times in this task … make the change now …]" and the user sees "🔁 not run: <tool>, the same call for the Nth time …". 0 = notes only.
148+ - A re-read = same tool + same JSON args (the existing `callKey` of toolschema.go), a compression since its last run, and NO successful write_file/edit_file since — so `go test` after a fix is never counted (bash edits are not seen). A refused call keeps its state: asking again at once is refused again.
149+ - Demo agent.yaml: `rereadLimit: 1` with the measured reason.
150+ - Tests: unit (limit, change resets, refusal repeated, 0 = never), end to end (3 rounds of 6 reads: the third round is refused, the tool does not run), config default/validation. Docs EN+FR.
151+ - id: 5
152+ author:
153+ name: k33g
154+ email: ph.charriere@gmail.com
155+ createdAt: 2026-11-30T08:39:04.000Z
156+ body: |
157+ Closed at the user's request for release v2.2.1 (merged from `feature/compaction-turns`). Closed without the demo re-run it asked for: title: "Re-run the Inkling demo" — to be checked on the next Inkling run.
added .tickets/issues/0293-option-to-compress-context-once-a-task-is-finish.yaml +14 -0
new file mode 100644
@@ -0,0 +1,14 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 293
3+title: Option to compress context once a task is finished in plan mode
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-30T07:55:28.472Z
9+updatedAt: 2026-11-30T07:55:28.472Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: ""
13+tasks: []
14+comments: []
new file mode 100644
@@ -0,0 +1,14 @@
1+# Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2+id: 293
3+title: Option to compress context once a task is finished in plan mode
4+state: open
5+author:
6+ name: k33g
7+ email: ph.charriere@gmail.com
8+createdAt: 2026-11-30T07:55:28.472Z
9+updatedAt: 2026-11-30T07:55:28.472Z
10+labels: []
11+milestone: "[Draft] Christmas"
12+body: ""
13+tasks: []
14+comments: []
modified .tickets/milestones.yaml +6 -0
@@ -81,3 +81,9 @@ milestones:
8181 - title: v2.2.0
8282 state: closed
8383 description: After v2.1.1 — decisionContext (decision models by configuration), the curl installer
84+ - title: "[Draft] Christmas"
85+ state: open
86+ dueOn: 2026-12-25
87+ - title: v2.2.1
88+ state: open
89+ description: Fixes after v2.2.0 — the compaction loop with injected user messages (ticket 289), the prefix cache under in-turn shrink (ticket 290)
@@ -81,3 +81,9 @@ milestones:
81 - title: v2.2.081 - title: v2.2.0
82 state: closed82 state: closed
83 description: After v2.1.1 — decisionContext (decision models by configuration), the curl installer83 description: After v2.1.1 — decisionContext (decision models by configuration), the curl installer
84+ - title: "[Draft] Christmas"
85+ state: open
86+ dueOn: 2026-12-25
87+ - title: v2.2.1
88+ state: open
89+ description: Fixes after v2.2.0 — the compaction loop with injected user messages (ticket 289), the prefix cache under in-turn shrink (ticket 290)
modified docs/en/explanation/context-compression.md +10 -0
@@ -12,6 +12,8 @@ The `compact` package replaces the old question turns by one summary written by
1212
1313 **The cut falls on a turn boundary.** A tool call and its result must never be split; reusing whole turns guarantees it.
1414
15+**A turn starts at a question the user asked, not at every user message.** mm writes some messages in the user's role itself: the notes it hands the model (`[mm: your last tool call was not run…]`, a reply cut at the token limit, a failed edit, a loop) and the messages the user types while a turn runs. Each of them used to open a turn of its own, so `keepLastTurns: 3` could keep one real question and a hundred messages around it — about 20k tokens of a 16k window, in one observed session — with nothing old left to summarise. These messages now carry a marker and stay in the turn they were added to. Sessions saved before the marker existed are split as they used to be.
16+
1517 **Two triggers, because the window is not always known.** The primary trigger is a share of the context window, 75 % by default, leaving a quarter for the next question, its tool outputs and the answer. The server's own input-token count from the last call is preferred to the local estimate when it is larger, because it sees the tools' JSON and the chat template. When the window is unknown, Docker Model Runner tells nothing and `contextWindow` may be `0`, only the message-count trigger can fire, and the agent says so at start-up.
1618
1719 **One key for the window.** The banner and the trigger read the same `contextWindow`; two keys for the same number would drift apart.
@@ -28,6 +30,14 @@ The `compact` package replaces the old question turns by one summary written by
2830
2931 **Inside a long turn, a second, lighter compression** (`context.compressInTurn`, on by default). One question can be enough to overflow the window: observed with Inkling-2-Mini on a 65536-token window, one "resume" became 77 messages and 38 tool calls before the server refused a 65811-token request — the between-questions compression never got its chance. So before each model call of a turn, past the same threshold, the current turn is made smaller. First the cheap step: the tool exchanges but the last four lose their bulk, each result and each long argument (a whole file given to `write_file`) keeping its first line — `scene.go: created, 516 line(s)` — and a note saying what was dropped. The model can read a file again; it cannot win its window back. Only if that is not enough are the same exchanges summarised, and the notes go at the end of the turn's question — a user message, so the user/assistant alternation chat templates expect holds; a later compression merges them instead of stacking a second set. The middleware that sees every model call replaces the request's messages, and Genkit builds the next calls from them, so the smaller history is also what the session keeps. It does not wait for `enabled`: a turn that outgrows the window fails whatever the between-questions setting says.
3032
33+**When the history before the turn is too big already, one summary per turn.** The summary inside a turn can only work on the turn's own exchanges; the earlier turns and the question are its floor. When that floor alone passes the threshold, no summary can get the history back under it, and summarising before every call only makes the model lose its oldest reads and do them again — observed: 3.5 hours, about thirty identical read cycles, no progress. So in that case the turn is summarised once, the `🗜️` line says why it will not be again (it is shown even when `showStats` is off, because the user can act on it and the model cannot), and the later calls only shrink. The next question then goes through the between-questions compression, which can reach the earlier turns.
34+
35+**Sizes are calibrated on the server's count.** The estimate counts 3.5 characters per token, which holds for English prose. Code and HTML are denser — about 1.8 characters per token with Inkling-2-Mini on Go, HTML and shell output — and the request also carries the tools' schemas. Observed: mm estimated 8.3k tokens where the server read 17.2k. The compression fired on the server's count but judged its own work with the estimate, found it under the threshold, never summarised, shrank one exchange per call, broke the prompt cache every time, and sent 17k tokens to a 16k window until the server stopped answering. So every in-turn decision now scales the estimate by the ratio of the server's last count to the estimate of that same request. The ratio describes the tokenizer and the kind of text, so it outlives a compression, unlike the count. Two consequences follow. When the last four exchanges alone pass the threshold, the summary keeps fewer of them, because a summary that cannot get under the threshold would run again before the next call. And a request that is still larger than the window once compressed is not sent: an honest error that ends the turn beats a prompt the server reads for minutes, or never answers.
36+
37+**When the files do not fit the window, the model must not read them in circles.** A model that needs two 500-line files to write a front end reads them in chunks; by the time it reaches the end, the first chunks were shrunk away and it starts again. Observed: 40 tool calls, all reads, the same `sed -n` ranges four times, no file written. Three changes break that circle. A shrunk result that holds code keeps its outline — the declarations, the routes, the JSON fields — instead of its first line, which for a Go file was `package server`: the model keeps the map of the code and reads a body only when it needs that body. The in-turn notes keep the same kind of facts; they used to be forbidden to quote file contents, a rule that suits the between-questions summary (a file may change between two questions) but threw away exactly what the next step of the same task needed. And when the model runs again a call whose result was dropped, the new result says so and suggests writing notes or starting the change: the loop detector cannot see this, because it is a cycle of different commands, not one command repeated. The note is part of the tool result, never a user message, which would start a turn of its own for the compaction. A first test showed that this was not enough: the outlines were there, the notes held all twenty routes, six gentle notes were sent — and the model kept reading, because mm's own wrapper around the notes told it to "re-read a file or re-run a command before relying on it", and the notes ended with "Remaining: read full type definitions … before editing". Both now point at the next change instead, and from the second re-read of a turn the note says plainly to stop reading and write a first version. A second test showed that a model can read such a note and still go on reading; so past `rereadLimit` re-reads of the same call (one by default), mm does not run it at all and answers with the reason instead. A call repeated after a `write_file` or `edit_file` is never counted: running the tests again after a fix is the opposite of reading in circles.
38+
39+**A compression must last.** The in-turn compression fires at the threshold; if it only gets back just under it, the next tool result passes it again, and the turn is compressed before nearly every call. Each compression rewrites the prompt, and a server that reuses what it already read (llama.cpp, razorbill) then reads it all again: measured on Inkling-2-Mini, ~98 s for such a call against ~13 s for one that hits the cache — 29.5 minutes of a 34.5-minute run. So the compression aims lower than it triggers (`inTurnTarget`, two thirds of the threshold by default): the older exchanges are shrunk, then summarised — keeping fewer exchanges raw when needed — and only then, as a last resort, the kept ones are shrunk too, never the last one. Summary before shrinking, because notes keep what a shrunk result loses. The price is that the model keeps less of what it just read; a target equal to the threshold restores the old behaviour. The notes themselves start with the next change to make, and a summary cut at `summaryMaxTokens` loses its unfinished line and says so: five summaries of six were cut in the same session, and the line asked for at the end never got written.
40+
3141 ## Rejected alternatives
3242
3343 - **Truncating the oldest messages.** Rejected: it would drop tool results whose calls remain, and lose the goal of the session.
@@ -12,6 +12,8 @@ The `compact` package replaces the old question turns by one summary written by
12 12
13 **The cut falls on a turn boundary.** A tool call and its result must never be split; reusing whole turns guarantees it.13 **The cut falls on a turn boundary.** A tool call and its result must never be split; reusing whole turns guarantees it.
14 14
15+**A turn starts at a question the user asked, not at every user message.** mm writes some messages in the user's role itself: the notes it hands the model (`[mm: your last tool call was not run…]`, a reply cut at the token limit, a failed edit, a loop) and the messages the user types while a turn runs. Each of them used to open a turn of its own, so `keepLastTurns: 3` could keep one real question and a hundred messages around it — about 20k tokens of a 16k window, in one observed session — with nothing old left to summarise. These messages now carry a marker and stay in the turn they were added to. Sessions saved before the marker existed are split as they used to be.
16+
15 **Two triggers, because the window is not always known.** The primary trigger is a share of the context window, 75 % by default, leaving a quarter for the next question, its tool outputs and the answer. The server's own input-token count from the last call is preferred to the local estimate when it is larger, because it sees the tools' JSON and the chat template. When the window is unknown, Docker Model Runner tells nothing and `contextWindow` may be `0`, only the message-count trigger can fire, and the agent says so at start-up.17 **Two triggers, because the window is not always known.** The primary trigger is a share of the context window, 75 % by default, leaving a quarter for the next question, its tool outputs and the answer. The server's own input-token count from the last call is preferred to the local estimate when it is larger, because it sees the tools' JSON and the chat template. When the window is unknown, Docker Model Runner tells nothing and `contextWindow` may be `0`, only the message-count trigger can fire, and the agent says so at start-up.
16 18
17 **One key for the window.** The banner and the trigger read the same `contextWindow`; two keys for the same number would drift apart.19 **One key for the window.** The banner and the trigger read the same `contextWindow`; two keys for the same number would drift apart.
@@ -28,6 +30,14 @@ The `compact` package replaces the old question turns by one summary written by
28 30
29 **Inside a long turn, a second, lighter compression** (`context.compressInTurn`, on by default). One question can be enough to overflow the window: observed with Inkling-2-Mini on a 65536-token window, one "resume" became 77 messages and 38 tool calls before the server refused a 65811-token request — the between-questions compression never got its chance. So before each model call of a turn, past the same threshold, the current turn is made smaller. First the cheap step: the tool exchanges but the last four lose their bulk, each result and each long argument (a whole file given to `write_file`) keeping its first line — `scene.go: created, 516 line(s)` — and a note saying what was dropped. The model can read a file again; it cannot win its window back. Only if that is not enough are the same exchanges summarised, and the notes go at the end of the turn's question — a user message, so the user/assistant alternation chat templates expect holds; a later compression merges them instead of stacking a second set. The middleware that sees every model call replaces the request's messages, and Genkit builds the next calls from them, so the smaller history is also what the session keeps. It does not wait for `enabled`: a turn that outgrows the window fails whatever the between-questions setting says.31 **Inside a long turn, a second, lighter compression** (`context.compressInTurn`, on by default). One question can be enough to overflow the window: observed with Inkling-2-Mini on a 65536-token window, one "resume" became 77 messages and 38 tool calls before the server refused a 65811-token request — the between-questions compression never got its chance. So before each model call of a turn, past the same threshold, the current turn is made smaller. First the cheap step: the tool exchanges but the last four lose their bulk, each result and each long argument (a whole file given to `write_file`) keeping its first line — `scene.go: created, 516 line(s)` — and a note saying what was dropped. The model can read a file again; it cannot win its window back. Only if that is not enough are the same exchanges summarised, and the notes go at the end of the turn's question — a user message, so the user/assistant alternation chat templates expect holds; a later compression merges them instead of stacking a second set. The middleware that sees every model call replaces the request's messages, and Genkit builds the next calls from them, so the smaller history is also what the session keeps. It does not wait for `enabled`: a turn that outgrows the window fails whatever the between-questions setting says.
30 32
33+**When the history before the turn is too big already, one summary per turn.** The summary inside a turn can only work on the turn's own exchanges; the earlier turns and the question are its floor. When that floor alone passes the threshold, no summary can get the history back under it, and summarising before every call only makes the model lose its oldest reads and do them again — observed: 3.5 hours, about thirty identical read cycles, no progress. So in that case the turn is summarised once, the `🗜️` line says why it will not be again (it is shown even when `showStats` is off, because the user can act on it and the model cannot), and the later calls only shrink. The next question then goes through the between-questions compression, which can reach the earlier turns.
34+
35+**Sizes are calibrated on the server's count.** The estimate counts 3.5 characters per token, which holds for English prose. Code and HTML are denser — about 1.8 characters per token with Inkling-2-Mini on Go, HTML and shell output — and the request also carries the tools' schemas. Observed: mm estimated 8.3k tokens where the server read 17.2k. The compression fired on the server's count but judged its own work with the estimate, found it under the threshold, never summarised, shrank one exchange per call, broke the prompt cache every time, and sent 17k tokens to a 16k window until the server stopped answering. So every in-turn decision now scales the estimate by the ratio of the server's last count to the estimate of that same request. The ratio describes the tokenizer and the kind of text, so it outlives a compression, unlike the count. Two consequences follow. When the last four exchanges alone pass the threshold, the summary keeps fewer of them, because a summary that cannot get under the threshold would run again before the next call. And a request that is still larger than the window once compressed is not sent: an honest error that ends the turn beats a prompt the server reads for minutes, or never answers.
36+
37+**When the files do not fit the window, the model must not read them in circles.** A model that needs two 500-line files to write a front end reads them in chunks; by the time it reaches the end, the first chunks were shrunk away and it starts again. Observed: 40 tool calls, all reads, the same `sed -n` ranges four times, no file written. Three changes break that circle. A shrunk result that holds code keeps its outline — the declarations, the routes, the JSON fields — instead of its first line, which for a Go file was `package server`: the model keeps the map of the code and reads a body only when it needs that body. The in-turn notes keep the same kind of facts; they used to be forbidden to quote file contents, a rule that suits the between-questions summary (a file may change between two questions) but threw away exactly what the next step of the same task needed. And when the model runs again a call whose result was dropped, the new result says so and suggests writing notes or starting the change: the loop detector cannot see this, because it is a cycle of different commands, not one command repeated. The note is part of the tool result, never a user message, which would start a turn of its own for the compaction. A first test showed that this was not enough: the outlines were there, the notes held all twenty routes, six gentle notes were sent — and the model kept reading, because mm's own wrapper around the notes told it to "re-read a file or re-run a command before relying on it", and the notes ended with "Remaining: read full type definitions … before editing". Both now point at the next change instead, and from the second re-read of a turn the note says plainly to stop reading and write a first version. A second test showed that a model can read such a note and still go on reading; so past `rereadLimit` re-reads of the same call (one by default), mm does not run it at all and answers with the reason instead. A call repeated after a `write_file` or `edit_file` is never counted: running the tests again after a fix is the opposite of reading in circles.
38+
39+**A compression must last.** The in-turn compression fires at the threshold; if it only gets back just under it, the next tool result passes it again, and the turn is compressed before nearly every call. Each compression rewrites the prompt, and a server that reuses what it already read (llama.cpp, razorbill) then reads it all again: measured on Inkling-2-Mini, ~98 s for such a call against ~13 s for one that hits the cache — 29.5 minutes of a 34.5-minute run. So the compression aims lower than it triggers (`inTurnTarget`, two thirds of the threshold by default): the older exchanges are shrunk, then summarised — keeping fewer exchanges raw when needed — and only then, as a last resort, the kept ones are shrunk too, never the last one. Summary before shrinking, because notes keep what a shrunk result loses. The price is that the model keeps less of what it just read; a target equal to the threshold restores the old behaviour. The notes themselves start with the next change to make, and a summary cut at `summaryMaxTokens` loses its unfinished line and says so: five summaries of six were cut in the same session, and the line asked for at the end never got written.
40+
31 ## Rejected alternatives41 ## Rejected alternatives
32 42
33 - **Truncating the oldest messages.** Rejected: it would drop tool results whose calls remain, and lose the goal of the session.43 - **Truncating the oldest messages.** Rejected: it would drop tool results whose calls remain, and lose the goal of the session.
modified docs/en/how-to/manage-the-context-window.md +4 -0
@@ -30,6 +30,10 @@ This guide shows how to stop a long session from overflowing the model's context
3030 - **The server was started after the agent.** The window is re-probed before the first question while it is still unknown and compression is on; you do not need to restart.
3131 - **Your own summary prompt.** Set `context.prompt` to replace the built-in seven-section prompt.
3232 - **A compression that fails** (server down, watchdog) leaves the history unchanged and prints `[compact: failed, history kept: …]`.
33+- **A `🗜️ in-turn:` line ends with "the history before this turn is above the threshold by itself".** The earlier turns alone fill the window past the threshold, so the turn is not summarised again. Lower `context.keepLastTurns` (to `1` for the smallest windows), or run `/compact` (or `/new`) before the next question; asking for smaller steps also keeps the history low.
34+- **A turn ends with "the request (about N tokens, even compressed) is larger than the context window (W), so it was not sent".** The work done is kept: ask to continue. If the server serves more than `contextWindow`, raise `contextWindow` to its real size; otherwise lower `maxOutput` so a single tool output takes less of the window, or lower `threshold`.
35+- **Tool results start with "[mm: you already ran this exact call earlier in this task…"** or the turn ends at `maxTurns` with reads only. The files the task needs do not fit the window together. Split the request so each step needs less at once — for example "list the routes of server.go and their JSON bodies in API.md", then "write web/app.js from API.md" — or raise `contextWindow` if the server serves more. Raising `maxTurns` only makes the reading last longer. A `🔁 not run: …` line means `context.rereadLimit` refused a third identical read; set it to `0` to keep the notes without refusing.
36+- **Each call after a compression is slow** (the server reads the whole prompt again: no `cached_tokens` in a trace). The compression comes back too often: lower `context.inTurnTarget` (for example 40 with `threshold: 60`), so a compression lasts several calls. Raise `context.summaryMaxTokens` if a `🗜️ a summary was cut` line appears.
3337
3438 ## See also
3539
@@ -30,6 +30,10 @@ This guide shows how to stop a long session from overflowing the model's context
30 - **The server was started after the agent.** The window is re-probed before the first question while it is still unknown and compression is on; you do not need to restart.30 - **The server was started after the agent.** The window is re-probed before the first question while it is still unknown and compression is on; you do not need to restart.
31 - **Your own summary prompt.** Set `context.prompt` to replace the built-in seven-section prompt.31 - **Your own summary prompt.** Set `context.prompt` to replace the built-in seven-section prompt.
32 - **A compression that fails** (server down, watchdog) leaves the history unchanged and prints `[compact: failed, history kept: …]`.32 - **A compression that fails** (server down, watchdog) leaves the history unchanged and prints `[compact: failed, history kept: …]`.
33+- **A `🗜️ in-turn:` line ends with "the history before this turn is above the threshold by itself".** The earlier turns alone fill the window past the threshold, so the turn is not summarised again. Lower `context.keepLastTurns` (to `1` for the smallest windows), or run `/compact` (or `/new`) before the next question; asking for smaller steps also keeps the history low.
34+- **A turn ends with "the request (about N tokens, even compressed) is larger than the context window (W), so it was not sent".** The work done is kept: ask to continue. If the server serves more than `contextWindow`, raise `contextWindow` to its real size; otherwise lower `maxOutput` so a single tool output takes less of the window, or lower `threshold`.
35+- **Tool results start with "[mm: you already ran this exact call earlier in this task…"** or the turn ends at `maxTurns` with reads only. The files the task needs do not fit the window together. Split the request so each step needs less at once — for example "list the routes of server.go and their JSON bodies in API.md", then "write web/app.js from API.md" — or raise `contextWindow` if the server serves more. Raising `maxTurns` only makes the reading last longer. A `🔁 not run: …` line means `context.rereadLimit` refused a third identical read; set it to `0` to keep the notes without refusing.
36+- **Each call after a compression is slow** (the server reads the whole prompt again: no `cached_tokens` in a trace). The compression comes back too often: lower `context.inTurnTarget` (for example 40 with `threshold: 60`), so a compression lasts several calls. Raise `context.summaryMaxTokens` if a `🗜️ a summary was cut` line appears.
33 37
34 ## See also38 ## See also
35 39
modified docs/en/reference/configuration.md +7 -3
@@ -75,11 +75,13 @@ Where `mm` looks for this file: [Configuration file resolution](cli.md#configura
7575 | `enabled` | bool | `false` | Turn the automatic compression on. `/compact` works regardless. |
7676 | `threshold` | int | `75` | Percentage of the context window beyond which the history is compressed before the next question. Between 1 and 100. |
7777 | `maxMessages` | int | `80` | Message count that triggers a compression when the window is unknown or the estimate is low. `0` disables. Must be ≥ 0. |
78-| `keepLastTurns` | int | `3` | Question turns kept raw at the end of the history. Must be ≥ 1. |
79-| `summaryMaxTokens` | int | `1200` | `max_tokens` of the summary request. Must be > 0. A thinking model's reasoning counts against it: on `dmr`, `llamacpp`, `llmman` and `kronk` the summary request turns reasoning off (`chat_template_kwargs.enable_thinking: false`), on `ollama` too (`reasoning_effort: "none"`, the one switch Ollama obeys) — whatever `sampling` says; other `chat_template_kwargs` are kept, and a `reasoning_effort` set there is lowered to `low` (gpt-oss has no "off"); elsewhere, if the error says the model "reasoned until the limit", raise it. |
78+| `keepLastTurns` | int | `3` | Question turns kept raw at the end of the history. Must be ≥ 1. A turn starts at a message the user sent as a question; mm's own notes to the model (`[mm: …]`) and messages typed during a turn belong to the turn they were added to (in sessions saved since ticket 289). |
79+| `summaryMaxTokens` | int | `1200` | `max_tokens` of the summary request. Must be > 0. A thinking model's reasoning counts against it: on `dmr`, `llamacpp`, `llmman` and `kronk` the summary request turns reasoning off (`chat_template_kwargs.enable_thinking: false`), on `ollama` too (`reasoning_effort: "none"`, the one switch Ollama obeys) — whatever `sampling` says; other `chat_template_kwargs` are kept, and a `reasoning_effort` set there is lowered to `low` (gpt-oss has no "off"); elsewhere, if the error says the model "reasoned until the limit", raise it. A summary cut at this limit drops its unfinished last line and ends with `- [notes cut at the length limit]`; a `🗜️ a summary was cut at its limit (N tokens)…` notice says so once per run. |
8080 | `prompt` | string | `""` | Replaces the built-in summary prompt when not empty. |
8181 | `showStats` | bool | `true` | Print the one-line `🗜️` report after each compression. |
82-| `compressInTurn` | bool | `true` | Compress INSIDE a long turn, between tool calls: before each model call, when the history passes `threshold` of a known window, the tool exchanges of the current turn but the last 4 lose their bulk (a tool result or a long call argument — a whole file given to `write_file` — keeps its first line and a note saying what was dropped); if that is not enough, they are replaced by notes the model writes about them, appended to the turn's question (merged with earlier notes on a later compression). The question, the last 4 exchanges and the earlier turns are never touched; a tool call is never separated from its result. Independent of `enabled`: a turn that outgrows the window fails either way. Needs a known window (`contextWindow`, or the server's). One `🗜️ in-turn: …` line per compression when `showStats` is on. `false` keeps the turn as it grows. |
82+| `compressInTurn` | bool | `true` | Compress INSIDE a long turn, between tool calls: before each model call, when the history passes `threshold` of a known window, the tool exchanges of the current turn but the last 4 lose their bulk (a tool result or a long call argument — a whole file given to `write_file` — keeps its first line and a note saying what was dropped); if that is not enough, they are replaced by notes the model writes about them, appended to the turn's question (merged with earlier notes on a later compression). The question, the last 4 exchanges and the earlier turns are never touched; a tool call is never separated from its result. Independent of `enabled`: a turn that outgrows the window fails either way. Needs a known window (`contextWindow`, or the server's). One `🗜️ in-turn: …` line per compression when `showStats` is on. When the history before the turn, with its question, passes `threshold` by itself, the turn is summarised once only, and its `🗜️` line, shown whatever `showStats` says, ends with `the history before this turn is above the threshold by itself: no more summaries in this turn (…)`; later calls of the turn only shrink. Sizes are the estimate (3.5 characters per token, tools' schemas included) scaled by the ratio of the server's last count to the estimate of the same request, so a dense tokenizer (code, HTML) is not under-counted. When the last 4 exchanges alone pass `threshold`, the summary keeps fewer of them, at least one. A request whose scaled size is still larger than the window after the compression is not sent: the turn ends with `the request (about N tokens, even compressed) is larger than the context window (W), so it was not sent — …`, and the work done is kept. A shrunk result (or long argument) that holds code keeps its outline — `func`, `type`, class and function lines, struct fields with their JSON names, HTTP routes, `fetch(` calls — under a `[mm: outline of a N-line output …]` note; other text keeps its first line. A shrunk message is never shrunk again. The in-turn notes keep the signatures, routes and types of the files read. A tool call identical to one already run in the turn, after a compression dropped results, gets `[mm: you already ran this exact call earlier in this task …]` before its result; from the second such call in a turn, `[mm: this is re-read number N in this task — … Stop reading. Make the first change now …]`. The notes end with the next change to make, and their wrapper asks to re-read only the lines that change needs. The notes start with a `Next change:` line. `false` keeps the turn as it grows. |
83+| `inTurnTarget` | int | `0` | Where an in-turn compression brings the history down to, in percent of the window. The compression fires at `threshold`; it then shrinks the older exchanges, summarises, and as a last resort shrinks the kept exchanges too (never the last one) until the history is under this target, so the next calls find the same prompt and the server's prompt cache. `0` = two thirds of `threshold` (75 → 50, 60 → 40). Equal to `threshold`: compress just under it. Must be between 0 and `threshold`. |
84+| `rereadLimit` | int | `1` | How many times, in one turn, the same tool call (same tool, same arguments) may run again after an in-turn compression dropped its result and no `write_file`/`edit_file` succeeded in between. Such a repeat runs with a note before its result; past the limit the call is NOT run, its result is `[mm: not run — this exact call already ran N times in this task … make the change now …]`, and a `🔁 not run: …` line shows it. `1`: the third identical read is refused. `0`: notes only, never refused. A file changed through `bash` is not seen as a change. Must be ≥ 0. |
8385
8486 ## `sessions` keys
8587
@@ -718,6 +720,8 @@ Reported on stderr as `[config error: <path>: <message>]`, exit code 1 — in ev
718720 | `context.threshold must be between 1 and 100` | out of range |
719721 | `context.keepLastTurns must be >= 1` | zero or negative |
720722 | `context.summaryMaxTokens must be > 0` | zero or negative |
723+| `context.inTurnTarget must be between 0 and context.threshold` | negative, or above `threshold` |
724+| `context.rereadLimit must be >= 0` | negative |
721725 | `context.maxMessages must be >= 0` | negative value |
722726 | `sessions.dir must not be empty` | empty string |
723727 | `docSearch.dirs must name at least one folder` | `dirs: []` with a switch on |
@@ -75,11 +75,13 @@ Where `mm` looks for this file: [Configuration file resolution](cli.md#configura
75 | `enabled` | bool | `false` | Turn the automatic compression on. `/compact` works regardless. |75 | `enabled` | bool | `false` | Turn the automatic compression on. `/compact` works regardless. |
76 | `threshold` | int | `75` | Percentage of the context window beyond which the history is compressed before the next question. Between 1 and 100. |76 | `threshold` | int | `75` | Percentage of the context window beyond which the history is compressed before the next question. Between 1 and 100. |
77 | `maxMessages` | int | `80` | Message count that triggers a compression when the window is unknown or the estimate is low. `0` disables. Must be ≥ 0. |77 | `maxMessages` | int | `80` | Message count that triggers a compression when the window is unknown or the estimate is low. `0` disables. Must be ≥ 0. |
78-| `keepLastTurns` | int | `3` | Question turns kept raw at the end of the history. Must be ≥ 1. |78+| `keepLastTurns` | int | `3` | Question turns kept raw at the end of the history. Must be ≥ 1. A turn starts at a message the user sent as a question; mm's own notes to the model (`[mm: …]`) and messages typed during a turn belong to the turn they were added to (in sessions saved since ticket 289). |
79-| `summaryMaxTokens` | int | `1200` | `max_tokens` of the summary request. Must be > 0. A thinking model's reasoning counts against it: on `dmr`, `llamacpp`, `llmman` and `kronk` the summary request turns reasoning off (`chat_template_kwargs.enable_thinking: false`), on `ollama` too (`reasoning_effort: "none"`, the one switch Ollama obeys) — whatever `sampling` says; other `chat_template_kwargs` are kept, and a `reasoning_effort` set there is lowered to `low` (gpt-oss has no "off"); elsewhere, if the error says the model "reasoned until the limit", raise it. |79+| `summaryMaxTokens` | int | `1200` | `max_tokens` of the summary request. Must be > 0. A thinking model's reasoning counts against it: on `dmr`, `llamacpp`, `llmman` and `kronk` the summary request turns reasoning off (`chat_template_kwargs.enable_thinking: false`), on `ollama` too (`reasoning_effort: "none"`, the one switch Ollama obeys) — whatever `sampling` says; other `chat_template_kwargs` are kept, and a `reasoning_effort` set there is lowered to `low` (gpt-oss has no "off"); elsewhere, if the error says the model "reasoned until the limit", raise it. A summary cut at this limit drops its unfinished last line and ends with `- [notes cut at the length limit]`; a `🗜️ a summary was cut at its limit (N tokens)…` notice says so once per run. |
80 | `prompt` | string | `""` | Replaces the built-in summary prompt when not empty. |80 | `prompt` | string | `""` | Replaces the built-in summary prompt when not empty. |
81 | `showStats` | bool | `true` | Print the one-line `🗜️` report after each compression. |81 | `showStats` | bool | `true` | Print the one-line `🗜️` report after each compression. |
82-| `compressInTurn` | bool | `true` | Compress INSIDE a long turn, between tool calls: before each model call, when the history passes `threshold` of a known window, the tool exchanges of the current turn but the last 4 lose their bulk (a tool result or a long call argument — a whole file given to `write_file` — keeps its first line and a note saying what was dropped); if that is not enough, they are replaced by notes the model writes about them, appended to the turn's question (merged with earlier notes on a later compression). The question, the last 4 exchanges and the earlier turns are never touched; a tool call is never separated from its result. Independent of `enabled`: a turn that outgrows the window fails either way. Needs a known window (`contextWindow`, or the server's). One `🗜️ in-turn: …` line per compression when `showStats` is on. `false` keeps the turn as it grows. |82+| `compressInTurn` | bool | `true` | Compress INSIDE a long turn, between tool calls: before each model call, when the history passes `threshold` of a known window, the tool exchanges of the current turn but the last 4 lose their bulk (a tool result or a long call argument — a whole file given to `write_file` — keeps its first line and a note saying what was dropped); if that is not enough, they are replaced by notes the model writes about them, appended to the turn's question (merged with earlier notes on a later compression). The question, the last 4 exchanges and the earlier turns are never touched; a tool call is never separated from its result. Independent of `enabled`: a turn that outgrows the window fails either way. Needs a known window (`contextWindow`, or the server's). One `🗜️ in-turn: …` line per compression when `showStats` is on. When the history before the turn, with its question, passes `threshold` by itself, the turn is summarised once only, and its `🗜️` line, shown whatever `showStats` says, ends with `the history before this turn is above the threshold by itself: no more summaries in this turn (…)`; later calls of the turn only shrink. Sizes are the estimate (3.5 characters per token, tools' schemas included) scaled by the ratio of the server's last count to the estimate of the same request, so a dense tokenizer (code, HTML) is not under-counted. When the last 4 exchanges alone pass `threshold`, the summary keeps fewer of them, at least one. A request whose scaled size is still larger than the window after the compression is not sent: the turn ends with `the request (about N tokens, even compressed) is larger than the context window (W), so it was not sent — …`, and the work done is kept. A shrunk result (or long argument) that holds code keeps its outline — `func`, `type`, class and function lines, struct fields with their JSON names, HTTP routes, `fetch(` calls — under a `[mm: outline of a N-line output …]` note; other text keeps its first line. A shrunk message is never shrunk again. The in-turn notes keep the signatures, routes and types of the files read. A tool call identical to one already run in the turn, after a compression dropped results, gets `[mm: you already ran this exact call earlier in this task …]` before its result; from the second such call in a turn, `[mm: this is re-read number N in this task — … Stop reading. Make the first change now …]`. The notes end with the next change to make, and their wrapper asks to re-read only the lines that change needs. The notes start with a `Next change:` line. `false` keeps the turn as it grows. |
83+| `inTurnTarget` | int | `0` | Where an in-turn compression brings the history down to, in percent of the window. The compression fires at `threshold`; it then shrinks the older exchanges, summarises, and as a last resort shrinks the kept exchanges too (never the last one) until the history is under this target, so the next calls find the same prompt and the server's prompt cache. `0` = two thirds of `threshold` (75 → 50, 60 → 40). Equal to `threshold`: compress just under it. Must be between 0 and `threshold`. |
84+| `rereadLimit` | int | `1` | How many times, in one turn, the same tool call (same tool, same arguments) may run again after an in-turn compression dropped its result and no `write_file`/`edit_file` succeeded in between. Such a repeat runs with a note before its result; past the limit the call is NOT run, its result is `[mm: not run — this exact call already ran N times in this task … make the change now …]`, and a `🔁 not run: …` line shows it. `1`: the third identical read is refused. `0`: notes only, never refused. A file changed through `bash` is not seen as a change. Must be ≥ 0. |
83 85
84 ## `sessions` keys86 ## `sessions` keys
85 87
@@ -718,6 +720,8 @@ Reported on stderr as `[config error: <path>: <message>]`, exit code 1 — in ev
718 | `context.threshold must be between 1 and 100` | out of range |720 | `context.threshold must be between 1 and 100` | out of range |
719 | `context.keepLastTurns must be >= 1` | zero or negative |721 | `context.keepLastTurns must be >= 1` | zero or negative |
720 | `context.summaryMaxTokens must be > 0` | zero or negative |722 | `context.summaryMaxTokens must be > 0` | zero or negative |
723+| `context.inTurnTarget must be between 0 and context.threshold` | negative, or above `threshold` |
724+| `context.rereadLimit must be >= 0` | negative |
721 | `context.maxMessages must be >= 0` | negative value |725 | `context.maxMessages must be >= 0` | negative value |
722 | `sessions.dir must not be empty` | empty string |726 | `sessions.dir must not be empty` | empty string |
723 | `docSearch.dirs must name at least one folder` | `dirs: []` with a switch on |727 | `docSearch.dirs must name at least one folder` | `dirs: []` with a switch on |
modified docs/fr/explanation/context-compression.md +10 -0
@@ -12,6 +12,8 @@ Le paquet `compact` remplace les anciens tours de question par un résumé écri
1212
1313 **La coupure tombe sur une frontière de tour.** Un appel d'outil et son résultat ne doivent jamais être séparés ; réutiliser des tours entiers le garantit.
1414
15+**Un tour commence à une question posée par l'utilisateur, pas à chaque message utilisateur.** mm écrit lui-même certains messages dans le rôle de l'utilisateur : les notes qu'il adresse au modèle (`[mm: your last tool call was not run…]`, une réponse coupée à la limite de tokens, une édition échouée, une boucle) et les messages que l'utilisateur tape pendant qu'un tour tourne. Chacun d'eux ouvrait auparavant un tour à lui seul, si bien que `keepLastTurns: 3` pouvait garder une seule vraie question et une centaine de messages autour — environ 20k tokens d'une fenêtre de 16k, dans une session observée — sans plus rien d'ancien à résumer. Ces messages portent désormais une marque et restent dans le tour où ils ont été ajoutés. Les sessions enregistrées avant l'existence de cette marque sont découpées comme avant.
16+
1517 **Deux déclencheurs, parce que la fenêtre n'est pas toujours connue.** Le déclencheur principal est une part de la fenêtre de contexte, 75 % par défaut, qui laisse un quart pour la question suivante, ses sorties d'outils et la réponse. Le compte de tokens d'entrée rapporté par le serveur au dernier appel est préféré à l'estimation locale quand il est plus grand, parce qu'il voit le JSON des outils et le template de chat. Quand la fenêtre est inconnue, Docker Model Runner ne dit rien et `contextWindow` peut valoir `0`, seul le déclencheur sur le nombre de messages peut jouer, et l'agent le dit au démarrage.
1618
1719 **Une seule clé pour la fenêtre.** La bannière et le déclencheur lisent le même `contextWindow` ; deux clés pour le même nombre finiraient par diverger.
@@ -28,6 +30,14 @@ Le paquet `compact` remplace les anciens tours de question par un résumé écri
2830
2931 **À l'intérieur d'un long tour, une seconde compression, plus légère** (`context.compressInTurn`, active par défaut). Une seule question peut suffire à déborder la fenêtre : observé avec Inkling-2-Mini sur une fenêtre de 65536 tokens, un « resume » est devenu 77 messages et 38 appels d'outils avant que le serveur refuse une requête de 65811 tokens — la compression entre deux questions n'a jamais eu sa chance. Avant chaque appel au modèle d'un tour, au-delà du même seuil, le tour en cours est donc réduit. D'abord l'étape bon marché : les échanges d'outils sauf les quatre derniers perdent leur volume, chaque résultat et chaque long argument (un fichier entier donné à `write_file`) gardant sa première ligne — `scene.go: created, 516 line(s)` — et une note qui dit ce qui a été retiré. Le modèle peut relire un fichier ; il ne peut pas récupérer sa fenêtre. Seulement si cela ne suffit pas, ces mêmes échanges sont résumés, et les notes vont à la fin de la question du tour — un message utilisateur, ce qui préserve l'alternance utilisateur/assistant qu'attendent les templates de chat ; une compression suivante les fusionne au lieu d'empiler un second jeu. Le middleware qui voit chaque appel au modèle remplace les messages de la requête, et Genkit construit les appels suivants à partir d'eux : l'historique réduit est aussi celui que la session garde. Elle n'attend pas `enabled` : un tour qui dépasse la fenêtre échoue quel que soit le réglage entre deux questions.
3032
33+**Quand l'historique avant le tour est déjà trop gros, un seul résumé par tour.** Le résumé à l'intérieur d'un tour ne peut porter que sur les échanges du tour ; les tours précédents et la question en sont le plancher. Quand ce plancher dépasse à lui seul le seuil, aucun résumé ne peut ramener l'historique en dessous, et résumer avant chaque appel ne fait que faire perdre au modèle ses lectures les plus anciennes, qu'il refait aussitôt — observé : 3 h 30, une trentaine de cycles de lecture identiques, aucun progrès. Dans ce cas le tour est donc résumé une fois, la ligne `🗜️` dit pourquoi il ne le sera plus (elle s'affiche même quand `showStats` est désactivé, parce que l'utilisateur peut agir et pas le modèle), et les appels suivants ne font que réduire. La question suivante passe ensuite par la compression entre questions, qui peut atteindre les tours précédents.
34+
35+**Les tailles sont calibrées sur le compte du serveur.** L'estimation compte 3,5 caractères par token, ce qui vaut pour de la prose anglaise. Le code et le HTML sont plus denses — environ 1,8 caractère par token avec Inkling-2-Mini sur du Go, du HTML et des sorties shell — et la requête porte aussi les schémas des outils. Observé : mm estimait 8,3k tokens là où le serveur en lisait 17,2k. La compression se déclenchait sur le compte du serveur mais jugeait son propre travail avec l'estimation, le trouvait sous le seuil, ne résumait jamais, réduisait un échange par appel, cassait le cache du prompt à chaque fois et envoyait 17k tokens à une fenêtre de 16k, jusqu'à ce que le serveur ne réponde plus. Désormais chaque décision prise dans un tour multiplie donc l'estimation par le rapport entre le dernier compte du serveur et l'estimation de cette même requête. Ce rapport décrit le tokenizer et le genre de texte : il survit à une compression, contrairement au compte. Deux conséquences en découlent. Quand les quatre derniers échanges dépassent à eux seuls le seuil, le résumé en garde moins, parce qu'un résumé qui ne peut pas passer sous le seuil recommencerait avant l'appel suivant. Et une requête qui dépasse encore la fenêtre une fois compressée n'est pas envoyée : une erreur franche qui termine le tour vaut mieux qu'un prompt que le serveur lit pendant des minutes, ou auquel il ne répond jamais.
36+
37+**Quand les fichiers ne tiennent pas dans la fenêtre, le modèle ne doit pas les lire en rond.** Un modèle qui a besoin de deux fichiers de 500 lignes pour écrire un front les lit par morceaux ; quand il arrive au bout, les premiers morceaux ont été réduits et il recommence. Observé : 40 appels d'outils, tous des lectures, les mêmes plages `sed -n` quatre fois, aucun fichier écrit. Trois changements cassent ce cercle. Un résultat réduit qui contient du code garde son plan — les déclarations, les routes, les champs JSON — au lieu de sa première ligne, qui pour un fichier Go était `package server` : le modèle garde la carte du code et ne relit un corps de fonction que lorsqu'il en a besoin. Les notes du tour gardent le même genre de faits ; il leur était interdit de citer le contenu des fichiers, une règle qui convient au résumé entre deux questions (un fichier peut changer entre deux questions) mais qui jetait exactement ce dont l'étape suivante de la même tâche avait besoin. Et quand le modèle relance un appel dont le résultat a été retiré, le nouveau résultat le dit et propose d'écrire des notes ou de commencer la modification : le détecteur de boucle ne peut pas le voir, car c'est un cycle de commandes différentes, pas une commande répétée. La note fait partie du résultat de l'outil, jamais d'un message utilisateur, qui ouvrirait un tour à lui seul pour la compaction. Un premier essai a montré que cela ne suffisait pas : les plans étaient là, les notes contenaient les vingt routes, six notes douces avaient été envoyées — et le modèle continuait de lire, parce que l'en-tête que mm place devant les notes lui disait « re-read a file or re-run a command before relying on it », et que les notes se terminaient par « Remaining: read full type definitions … before editing ». Les deux désignent maintenant la prochaine modification, et à partir de la deuxième relecture d'un tour la note dit clairement d'arrêter de lire et d'écrire une première version. Un deuxième essai a montré qu'un modèle peut lire une telle note et continuer de lire ; au-delà de `rereadLimit` relectures du même appel (une par défaut), mm ne l'exécute donc plus du tout et répond à la place par la raison. Un appel répété après un `write_file` ou un `edit_file` n'est jamais compté : relancer les tests après une correction est le contraire de lire en rond.
38+
39+**Une compression doit durer.** La compression dans un tour se déclenche au seuil ; si elle ne redescend que juste en dessous, le résultat d'outil suivant le dépasse de nouveau, et le tour est compressé avant presque chaque appel. Chaque compression réécrit le prompt, et un serveur qui réutilise ce qu'il a déjà lu (llama.cpp, razorbill) relit alors tout : mesuré avec Inkling-2-Mini, ~98 s pour un tel appel contre ~13 s pour un appel servi par le cache — 29,5 minutes d'un run de 34,5. La compression vise donc plus bas qu'elle ne se déclenche (`inTurnTarget`, deux tiers du seuil par défaut) : les anciens échanges sont réduits, puis résumés — en gardant moins d'échanges intacts si besoin — et seulement ensuite, en dernier recours, les échanges conservés sont réduits à leur tour, jamais le dernier. Le résumé avant la réduction, parce que les notes gardent ce qu'un résultat réduit perd. Le prix : le modèle garde moins de ce qu'il vient de lire ; une cible égale au seuil rétablit l'ancien comportement. Les notes elles-mêmes commencent par la prochaine modification à faire, et un résumé coupé à `summaryMaxTokens` perd sa ligne inachevée et le dit : cinq résumés sur six avaient été coupés dans la même session, et la ligne demandée à la fin n'avait jamais été écrite.
40+
3141 ## Alternatives écartées
3242
3343 - **Tronquer les messages les plus anciens.** Écarté : on perdrait des résultats d'outils dont les appels resteraient, et l'objectif de la session.
@@ -12,6 +12,8 @@ Le paquet `compact` remplace les anciens tours de question par un résumé écri
12 12
13 **La coupure tombe sur une frontière de tour.** Un appel d'outil et son résultat ne doivent jamais être séparés ; réutiliser des tours entiers le garantit.13 **La coupure tombe sur une frontière de tour.** Un appel d'outil et son résultat ne doivent jamais être séparés ; réutiliser des tours entiers le garantit.
14 14
15+**Un tour commence à une question posée par l'utilisateur, pas à chaque message utilisateur.** mm écrit lui-même certains messages dans le rôle de l'utilisateur : les notes qu'il adresse au modèle (`[mm: your last tool call was not run…]`, une réponse coupée à la limite de tokens, une édition échouée, une boucle) et les messages que l'utilisateur tape pendant qu'un tour tourne. Chacun d'eux ouvrait auparavant un tour à lui seul, si bien que `keepLastTurns: 3` pouvait garder une seule vraie question et une centaine de messages autour — environ 20k tokens d'une fenêtre de 16k, dans une session observée — sans plus rien d'ancien à résumer. Ces messages portent désormais une marque et restent dans le tour où ils ont été ajoutés. Les sessions enregistrées avant l'existence de cette marque sont découpées comme avant.
16+
15 **Deux déclencheurs, parce que la fenêtre n'est pas toujours connue.** Le déclencheur principal est une part de la fenêtre de contexte, 75 % par défaut, qui laisse un quart pour la question suivante, ses sorties d'outils et la réponse. Le compte de tokens d'entrée rapporté par le serveur au dernier appel est préféré à l'estimation locale quand il est plus grand, parce qu'il voit le JSON des outils et le template de chat. Quand la fenêtre est inconnue, Docker Model Runner ne dit rien et `contextWindow` peut valoir `0`, seul le déclencheur sur le nombre de messages peut jouer, et l'agent le dit au démarrage.17 **Deux déclencheurs, parce que la fenêtre n'est pas toujours connue.** Le déclencheur principal est une part de la fenêtre de contexte, 75 % par défaut, qui laisse un quart pour la question suivante, ses sorties d'outils et la réponse. Le compte de tokens d'entrée rapporté par le serveur au dernier appel est préféré à l'estimation locale quand il est plus grand, parce qu'il voit le JSON des outils et le template de chat. Quand la fenêtre est inconnue, Docker Model Runner ne dit rien et `contextWindow` peut valoir `0`, seul le déclencheur sur le nombre de messages peut jouer, et l'agent le dit au démarrage.
16 18
17 **Une seule clé pour la fenêtre.** La bannière et le déclencheur lisent le même `contextWindow` ; deux clés pour le même nombre finiraient par diverger.19 **Une seule clé pour la fenêtre.** La bannière et le déclencheur lisent le même `contextWindow` ; deux clés pour le même nombre finiraient par diverger.
@@ -28,6 +30,14 @@ Le paquet `compact` remplace les anciens tours de question par un résumé écri
28 30
29 **À l'intérieur d'un long tour, une seconde compression, plus légère** (`context.compressInTurn`, active par défaut). Une seule question peut suffire à déborder la fenêtre : observé avec Inkling-2-Mini sur une fenêtre de 65536 tokens, un « resume » est devenu 77 messages et 38 appels d'outils avant que le serveur refuse une requête de 65811 tokens — la compression entre deux questions n'a jamais eu sa chance. Avant chaque appel au modèle d'un tour, au-delà du même seuil, le tour en cours est donc réduit. D'abord l'étape bon marché : les échanges d'outils sauf les quatre derniers perdent leur volume, chaque résultat et chaque long argument (un fichier entier donné à `write_file`) gardant sa première ligne — `scene.go: created, 516 line(s)` — et une note qui dit ce qui a été retiré. Le modèle peut relire un fichier ; il ne peut pas récupérer sa fenêtre. Seulement si cela ne suffit pas, ces mêmes échanges sont résumés, et les notes vont à la fin de la question du tour — un message utilisateur, ce qui préserve l'alternance utilisateur/assistant qu'attendent les templates de chat ; une compression suivante les fusionne au lieu d'empiler un second jeu. Le middleware qui voit chaque appel au modèle remplace les messages de la requête, et Genkit construit les appels suivants à partir d'eux : l'historique réduit est aussi celui que la session garde. Elle n'attend pas `enabled` : un tour qui dépasse la fenêtre échoue quel que soit le réglage entre deux questions.31 **À l'intérieur d'un long tour, une seconde compression, plus légère** (`context.compressInTurn`, active par défaut). Une seule question peut suffire à déborder la fenêtre : observé avec Inkling-2-Mini sur une fenêtre de 65536 tokens, un « resume » est devenu 77 messages et 38 appels d'outils avant que le serveur refuse une requête de 65811 tokens — la compression entre deux questions n'a jamais eu sa chance. Avant chaque appel au modèle d'un tour, au-delà du même seuil, le tour en cours est donc réduit. D'abord l'étape bon marché : les échanges d'outils sauf les quatre derniers perdent leur volume, chaque résultat et chaque long argument (un fichier entier donné à `write_file`) gardant sa première ligne — `scene.go: created, 516 line(s)` — et une note qui dit ce qui a été retiré. Le modèle peut relire un fichier ; il ne peut pas récupérer sa fenêtre. Seulement si cela ne suffit pas, ces mêmes échanges sont résumés, et les notes vont à la fin de la question du tour — un message utilisateur, ce qui préserve l'alternance utilisateur/assistant qu'attendent les templates de chat ; une compression suivante les fusionne au lieu d'empiler un second jeu. Le middleware qui voit chaque appel au modèle remplace les messages de la requête, et Genkit construit les appels suivants à partir d'eux : l'historique réduit est aussi celui que la session garde. Elle n'attend pas `enabled` : un tour qui dépasse la fenêtre échoue quel que soit le réglage entre deux questions.
30 32
33+**Quand l'historique avant le tour est déjà trop gros, un seul résumé par tour.** Le résumé à l'intérieur d'un tour ne peut porter que sur les échanges du tour ; les tours précédents et la question en sont le plancher. Quand ce plancher dépasse à lui seul le seuil, aucun résumé ne peut ramener l'historique en dessous, et résumer avant chaque appel ne fait que faire perdre au modèle ses lectures les plus anciennes, qu'il refait aussitôt — observé : 3 h 30, une trentaine de cycles de lecture identiques, aucun progrès. Dans ce cas le tour est donc résumé une fois, la ligne `🗜️` dit pourquoi il ne le sera plus (elle s'affiche même quand `showStats` est désactivé, parce que l'utilisateur peut agir et pas le modèle), et les appels suivants ne font que réduire. La question suivante passe ensuite par la compression entre questions, qui peut atteindre les tours précédents.
34+
35+**Les tailles sont calibrées sur le compte du serveur.** L'estimation compte 3,5 caractères par token, ce qui vaut pour de la prose anglaise. Le code et le HTML sont plus denses — environ 1,8 caractère par token avec Inkling-2-Mini sur du Go, du HTML et des sorties shell — et la requête porte aussi les schémas des outils. Observé : mm estimait 8,3k tokens là où le serveur en lisait 17,2k. La compression se déclenchait sur le compte du serveur mais jugeait son propre travail avec l'estimation, le trouvait sous le seuil, ne résumait jamais, réduisait un échange par appel, cassait le cache du prompt à chaque fois et envoyait 17k tokens à une fenêtre de 16k, jusqu'à ce que le serveur ne réponde plus. Désormais chaque décision prise dans un tour multiplie donc l'estimation par le rapport entre le dernier compte du serveur et l'estimation de cette même requête. Ce rapport décrit le tokenizer et le genre de texte : il survit à une compression, contrairement au compte. Deux conséquences en découlent. Quand les quatre derniers échanges dépassent à eux seuls le seuil, le résumé en garde moins, parce qu'un résumé qui ne peut pas passer sous le seuil recommencerait avant l'appel suivant. Et une requête qui dépasse encore la fenêtre une fois compressée n'est pas envoyée : une erreur franche qui termine le tour vaut mieux qu'un prompt que le serveur lit pendant des minutes, ou auquel il ne répond jamais.
36+
37+**Quand les fichiers ne tiennent pas dans la fenêtre, le modèle ne doit pas les lire en rond.** Un modèle qui a besoin de deux fichiers de 500 lignes pour écrire un front les lit par morceaux ; quand il arrive au bout, les premiers morceaux ont été réduits et il recommence. Observé : 40 appels d'outils, tous des lectures, les mêmes plages `sed -n` quatre fois, aucun fichier écrit. Trois changements cassent ce cercle. Un résultat réduit qui contient du code garde son plan — les déclarations, les routes, les champs JSON — au lieu de sa première ligne, qui pour un fichier Go était `package server` : le modèle garde la carte du code et ne relit un corps de fonction que lorsqu'il en a besoin. Les notes du tour gardent le même genre de faits ; il leur était interdit de citer le contenu des fichiers, une règle qui convient au résumé entre deux questions (un fichier peut changer entre deux questions) mais qui jetait exactement ce dont l'étape suivante de la même tâche avait besoin. Et quand le modèle relance un appel dont le résultat a été retiré, le nouveau résultat le dit et propose d'écrire des notes ou de commencer la modification : le détecteur de boucle ne peut pas le voir, car c'est un cycle de commandes différentes, pas une commande répétée. La note fait partie du résultat de l'outil, jamais d'un message utilisateur, qui ouvrirait un tour à lui seul pour la compaction. Un premier essai a montré que cela ne suffisait pas : les plans étaient là, les notes contenaient les vingt routes, six notes douces avaient été envoyées — et le modèle continuait de lire, parce que l'en-tête que mm place devant les notes lui disait « re-read a file or re-run a command before relying on it », et que les notes se terminaient par « Remaining: read full type definitions … before editing ». Les deux désignent maintenant la prochaine modification, et à partir de la deuxième relecture d'un tour la note dit clairement d'arrêter de lire et d'écrire une première version. Un deuxième essai a montré qu'un modèle peut lire une telle note et continuer de lire ; au-delà de `rereadLimit` relectures du même appel (une par défaut), mm ne l'exécute donc plus du tout et répond à la place par la raison. Un appel répété après un `write_file` ou un `edit_file` n'est jamais compté : relancer les tests après une correction est le contraire de lire en rond.
38+
39+**Une compression doit durer.** La compression dans un tour se déclenche au seuil ; si elle ne redescend que juste en dessous, le résultat d'outil suivant le dépasse de nouveau, et le tour est compressé avant presque chaque appel. Chaque compression réécrit le prompt, et un serveur qui réutilise ce qu'il a déjà lu (llama.cpp, razorbill) relit alors tout : mesuré avec Inkling-2-Mini, ~98 s pour un tel appel contre ~13 s pour un appel servi par le cache — 29,5 minutes d'un run de 34,5. La compression vise donc plus bas qu'elle ne se déclenche (`inTurnTarget`, deux tiers du seuil par défaut) : les anciens échanges sont réduits, puis résumés — en gardant moins d'échanges intacts si besoin — et seulement ensuite, en dernier recours, les échanges conservés sont réduits à leur tour, jamais le dernier. Le résumé avant la réduction, parce que les notes gardent ce qu'un résultat réduit perd. Le prix : le modèle garde moins de ce qu'il vient de lire ; une cible égale au seuil rétablit l'ancien comportement. Les notes elles-mêmes commencent par la prochaine modification à faire, et un résumé coupé à `summaryMaxTokens` perd sa ligne inachevée et le dit : cinq résumés sur six avaient été coupés dans la même session, et la ligne demandée à la fin n'avait jamais été écrite.
40+
31 ## Alternatives écartées41 ## Alternatives écartées
32 42
33 - **Tronquer les messages les plus anciens.** Écarté : on perdrait des résultats d'outils dont les appels resteraient, et l'objectif de la session.43 - **Tronquer les messages les plus anciens.** Écarté : on perdrait des résultats d'outils dont les appels resteraient, et l'objectif de la session.
modified docs/fr/how-to/manage-the-context-window.md +4 -0
@@ -30,6 +30,10 @@ Ce guide montre comment empêcher une longue session de déborder du contexte du
3030 - **Le serveur a été démarré après l'agent.** La fenêtre est re-sondée avant la première question tant qu'elle est inconnue et que la compression est activée ; pas besoin de relancer.
3131 - **Votre propre prompt de résumé.** Fixez `context.prompt` pour remplacer le prompt intégré en sept sections.
3232 - **Une compression qui échoue** (serveur arrêté, watchdog) laisse l'historique inchangé et affiche `[compact: failed, history kept: …]`.
33+- **Une ligne `🗜️ in-turn:` se termine par « the history before this turn is above the threshold by itself ».** Les tours précédents remplissent à eux seuls la fenêtre au-delà du seuil, donc le tour n'est plus résumé. Baissez `context.keepLastTurns` (à `1` pour les plus petites fenêtres), ou lancez `/compact` (ou `/new`) avant la question suivante ; demander des étapes plus petites garde aussi l'historique bas.
34+- **Un tour se termine par « the request (about N tokens, even compressed) is larger than the context window (W), so it was not sent ».** Le travail fait est conservé : demandez de continuer. Si le serveur sert plus que `contextWindow`, montez `contextWindow` à sa vraie taille ; sinon baissez `maxOutput` pour qu'une seule sortie d'outil prenne moins de place dans la fenêtre, ou baissez `threshold`.
35+- **Des résultats d'outils commencent par « [mm: you already ran this exact call earlier in this task… »**, ou le tour s'arrête à `maxTurns` sans avoir fait autre chose que lire. Les fichiers dont la tâche a besoin ne tiennent pas ensemble dans la fenêtre. Découpez la demande pour que chaque étape ait besoin de moins à la fois — par exemple « liste les routes de server.go et leurs corps JSON dans API.md », puis « écris web/app.js à partir de API.md » — ou montez `contextWindow` si le serveur sert davantage. Monter `maxTurns` ne fait que prolonger la lecture. Une ligne `🔁 not run: …` signifie que `context.rereadLimit` a refusé une troisième lecture identique ; mettez-le à `0` pour garder les notes sans refus.
36+- **Chaque appel qui suit une compression est lent** (le serveur relit tout le prompt : pas de `cached_tokens` dans une trace). La compression revient trop souvent : baissez `context.inTurnTarget` (par exemple 40 avec `threshold: 60`), pour qu'une compression dure plusieurs appels. Montez `context.summaryMaxTokens` si une ligne `🗜️ a summary was cut` apparaît.
3337
3438 ## Voir aussi
3539
@@ -30,6 +30,10 @@ Ce guide montre comment empêcher une longue session de déborder du contexte du
30 - **Le serveur a été démarré après l'agent.** La fenêtre est re-sondée avant la première question tant qu'elle est inconnue et que la compression est activée ; pas besoin de relancer.30 - **Le serveur a été démarré après l'agent.** La fenêtre est re-sondée avant la première question tant qu'elle est inconnue et que la compression est activée ; pas besoin de relancer.
31 - **Votre propre prompt de résumé.** Fixez `context.prompt` pour remplacer le prompt intégré en sept sections.31 - **Votre propre prompt de résumé.** Fixez `context.prompt` pour remplacer le prompt intégré en sept sections.
32 - **Une compression qui échoue** (serveur arrêté, watchdog) laisse l'historique inchangé et affiche `[compact: failed, history kept: …]`.32 - **Une compression qui échoue** (serveur arrêté, watchdog) laisse l'historique inchangé et affiche `[compact: failed, history kept: …]`.
33+- **Une ligne `🗜️ in-turn:` se termine par « the history before this turn is above the threshold by itself ».** Les tours précédents remplissent à eux seuls la fenêtre au-delà du seuil, donc le tour n'est plus résumé. Baissez `context.keepLastTurns` (à `1` pour les plus petites fenêtres), ou lancez `/compact` (ou `/new`) avant la question suivante ; demander des étapes plus petites garde aussi l'historique bas.
34+- **Un tour se termine par « the request (about N tokens, even compressed) is larger than the context window (W), so it was not sent ».** Le travail fait est conservé : demandez de continuer. Si le serveur sert plus que `contextWindow`, montez `contextWindow` à sa vraie taille ; sinon baissez `maxOutput` pour qu'une seule sortie d'outil prenne moins de place dans la fenêtre, ou baissez `threshold`.
35+- **Des résultats d'outils commencent par « [mm: you already ran this exact call earlier in this task… »**, ou le tour s'arrête à `maxTurns` sans avoir fait autre chose que lire. Les fichiers dont la tâche a besoin ne tiennent pas ensemble dans la fenêtre. Découpez la demande pour que chaque étape ait besoin de moins à la fois — par exemple « liste les routes de server.go et leurs corps JSON dans API.md », puis « écris web/app.js à partir de API.md » — ou montez `contextWindow` si le serveur sert davantage. Monter `maxTurns` ne fait que prolonger la lecture. Une ligne `🔁 not run: …` signifie que `context.rereadLimit` a refusé une troisième lecture identique ; mettez-le à `0` pour garder les notes sans refus.
36+- **Chaque appel qui suit une compression est lent** (le serveur relit tout le prompt : pas de `cached_tokens` dans une trace). La compression revient trop souvent : baissez `context.inTurnTarget` (par exemple 40 avec `threshold: 60`), pour qu'une compression dure plusieurs appels. Montez `context.summaryMaxTokens` si une ligne `🗜️ a summary was cut` apparaît.
33 37
34 ## Voir aussi38 ## Voir aussi
35 39
modified docs/fr/reference/configuration.md +7 -3
@@ -75,11 +75,13 @@ Où `mm` cherche ce fichier : [Résolution du fichier de configuration](cli.md#r
7575 | `enabled` | booléen | `false` | Active la compression automatique. `/compact` fonctionne dans tous les cas. |
7676 | `threshold` | entier | `75` | Pourcentage de la fenêtre de contexte au-delà duquel l'historique est compressé avant la question suivante. Entre 1 et 100. |
7777 | `maxMessages` | entier | `80` | Nombre de messages qui déclenche une compression quand la fenêtre est inconnue ou l'estimation trop basse. `0` désactive. Doit être ≥ 0. |
78-| `keepLastTurns` | entier | `3` | Tours de question conservés bruts en fin d'historique. Doit être ≥ 1. |
79-| `summaryMaxTokens` | entier | `1200` | `max_tokens` de la requête de résumé. Doit être > 0. Le raisonnement d'un modèle qui réfléchit est décompté de ce budget : sur `dmr`, `llamacpp`, `llmman` et `kronk`, la requête de résumé désactive le raisonnement (`chat_template_kwargs.enable_thinking: false`), sur `ollama` aussi (`reasoning_effort: "none"`, le seul interrupteur qu'Ollama respecte) — quoi que dise `sampling` ; les autres `chat_template_kwargs` sont gardés, et un `reasoning_effort` qui y est fixé est ramené à `low` (gpt-oss n'a pas d'« arrêt ») ; ailleurs, si l'erreur dit que le modèle « reasoned until the limit », augmentez-le. |
78+| `keepLastTurns` | entier | `3` | Tours de question conservés bruts en fin d'historique. Doit être ≥ 1. Un tour commence à un message envoyé par l'utilisateur comme question ; les notes de mm au modèle (`[mm: …]`) et les messages tapés pendant un tour appartiennent au tour où ils ont été ajoutés (dans les sessions enregistrées depuis le ticket 289). |
79+| `summaryMaxTokens` | entier | `1200` | `max_tokens` de la requête de résumé. Doit être > 0. Le raisonnement d'un modèle qui réfléchit est décompté de ce budget : sur `dmr`, `llamacpp`, `llmman` et `kronk`, la requête de résumé désactive le raisonnement (`chat_template_kwargs.enable_thinking: false`), sur `ollama` aussi (`reasoning_effort: "none"`, le seul interrupteur qu'Ollama respecte) — quoi que dise `sampling` ; les autres `chat_template_kwargs` sont gardés, et un `reasoning_effort` qui y est fixé est ramené à `low` (gpt-oss n'a pas d'« arrêt ») ; ailleurs, si l'erreur dit que le modèle « reasoned until the limit », augmentez-le. Un résumé coupé à cette limite perd sa dernière ligne inachevée et se termine par `- [notes cut at the length limit]` ; une ligne `🗜️ a summary was cut at its limit (N tokens)…` le signale une fois par exécution. |
8080 | `prompt` | chaîne | `""` | Remplace le prompt de résumé intégré quand non vide. |
8181 | `showStats` | booléen | `true` | Affiche le rapport `🗜️` d'une ligne après chaque compression. |
82-| `compressInTurn` | booléen | `true` | Compresse À L'INTÉRIEUR d'un long tour, entre deux appels d'outils : avant chaque appel au modèle, quand l'historique dépasse `threshold` d'une fenêtre connue, les échanges d'outils du tour en cours sauf les 4 derniers perdent leur volume (un résultat d'outil ou un long argument d'appel — un fichier entier donné à `write_file` — garde sa première ligne et une note qui dit ce qui a été retiré) ; si cela ne suffit pas, ils sont remplacés par des notes que le modèle écrit à leur sujet, ajoutées à la question du tour (fusionnées avec les notes précédentes lors d'une compression suivante). La question, les 4 derniers échanges et les tours précédents ne sont jamais touchés ; un appel d'outil n'est jamais séparé de son résultat. Indépendant d'`enabled` : un tour qui dépasse la fenêtre échoue de toute façon. Demande une fenêtre connue (`contextWindow`, ou celle du serveur). Une ligne `🗜️ in-turn: …` par compression quand `showStats` est actif. `false` laisse le tour grandir. |
82+| `compressInTurn` | booléen | `true` | Compresse À L'INTÉRIEUR d'un long tour, entre deux appels d'outils : avant chaque appel au modèle, quand l'historique dépasse `threshold` d'une fenêtre connue, les échanges d'outils du tour en cours sauf les 4 derniers perdent leur volume (un résultat d'outil ou un long argument d'appel — un fichier entier donné à `write_file` — garde sa première ligne et une note qui dit ce qui a été retiré) ; si cela ne suffit pas, ils sont remplacés par des notes que le modèle écrit à leur sujet, ajoutées à la question du tour (fusionnées avec les notes précédentes lors d'une compression suivante). La question, les 4 derniers échanges et les tours précédents ne sont jamais touchés ; un appel d'outil n'est jamais séparé de son résultat. Indépendant d'`enabled` : un tour qui dépasse la fenêtre échoue de toute façon. Demande une fenêtre connue (`contextWindow`, ou celle du serveur). Une ligne `🗜️ in-turn: …` par compression quand `showStats` est actif. Quand l'historique avant le tour, avec sa question, dépasse à lui seul `threshold`, le tour n'est résumé qu'une fois, et sa ligne `🗜️`, affichée quelle que soit la valeur de `showStats`, se termine par `the history before this turn is above the threshold by itself: no more summaries in this turn (…)` ; les appels suivants du tour ne font que réduire. Les tailles sont l'estimation (3,5 caractères par token, schémas des outils compris) multipliée par le rapport entre le dernier compte du serveur et l'estimation de la même requête, si bien qu'un tokenizer dense (code, HTML) n'est pas sous-compté. Quand les 4 derniers échanges dépassent à eux seuls `threshold`, le résumé en garde moins, au moins un. Une requête dont la taille ainsi corrigée dépasse encore la fenêtre après la compression n'est pas envoyée : le tour se termine par `the request (about N tokens, even compressed) is larger than the context window (W), so it was not sent — …`, et le travail fait est conservé. Un résultat (ou un long argument) réduit qui contient du code garde son plan — les lignes `func`, `type`, de classe et de fonction, les champs de structure avec leur nom JSON, les routes HTTP, les appels `fetch(` — sous une note `[mm: outline of a N-line output …]` ; un autre texte garde sa première ligne. Un message réduit ne l'est jamais une seconde fois. Les notes du tour gardent les signatures, les routes et les types des fichiers lus. Un appel d'outil identique à un appel déjà lancé dans le tour, après qu'une compression a retiré des résultats, reçoit `[mm: you already ran this exact call earlier in this task …]` avant son résultat ; à partir du deuxième appel de ce genre dans un tour, `[mm: this is re-read number N in this task — … Stop reading. Make the first change now …]`. Les notes se terminent par la prochaine modification à faire, et leur en-tête demande de ne relire que les lignes dont cette modification a besoin. Les notes commencent par une ligne `Next change:`. `false` laisse le tour grandir. |
83+| `inTurnTarget` | entier | `0` | Le niveau auquel une compression à l'intérieur d'un tour ramène l'historique, en pourcentage de la fenêtre. La compression se déclenche à `threshold` ; elle réduit ensuite les anciens échanges, résume, et en dernier recours réduit aussi les échanges conservés (jamais le dernier) jusqu'à passer sous cette cible, pour que les appels suivants retrouvent le même prompt et le cache du serveur. `0` = deux tiers de `threshold` (75 → 50, 60 → 40). Égal à `threshold` : compresser juste en dessous. Doit être entre 0 et `threshold`. |
84+| `rereadLimit` | entier | `1` | Combien de fois, dans un tour, le même appel d'outil (même outil, mêmes arguments) peut être relancé après qu'une compression du tour a retiré son résultat, sans qu'un `write_file`/`edit_file` ait réussi entre-temps. Une telle répétition s'exécute avec une note avant son résultat ; au-delà de la limite, l'appel n'est PAS exécuté, son résultat est `[mm: not run — this exact call already ran N times in this task … make the change now …]`, et une ligne `🔁 not run: …` le signale. `1` : la troisième lecture identique est refusée. `0` : des notes seulement, jamais de refus. Un fichier modifié par `bash` n'est pas vu comme une modification. Doit être ≥ 0. |
8385
8486 ## Clés de `sessions`
8587
@@ -718,6 +720,8 @@ Signalées sur stderr sous la forme `[config error: <chemin>: <message>]`, code
718720 | `context.threshold must be between 1 and 100` | hors intervalle |
719721 | `context.keepLastTurns must be >= 1` | zéro ou négatif |
720722 | `context.summaryMaxTokens must be > 0` | zéro ou négatif |
723+| `context.inTurnTarget must be between 0 and context.threshold` | négatif, ou au-dessus de `threshold` |
724+| `context.rereadLimit must be >= 0` | négatif |
721725 | `context.maxMessages must be >= 0` | valeur négative |
722726 | `sessions.dir must not be empty` | chaîne vide |
723727 | `docSearch.dirs must name at least one folder` | `dirs: []` avec un interrupteur activé |
@@ -75,11 +75,13 @@ Où `mm` cherche ce fichier : [Résolution du fichier de configuration](cli.md#r
75 | `enabled` | booléen | `false` | Active la compression automatique. `/compact` fonctionne dans tous les cas. |75 | `enabled` | booléen | `false` | Active la compression automatique. `/compact` fonctionne dans tous les cas. |
76 | `threshold` | entier | `75` | Pourcentage de la fenêtre de contexte au-delà duquel l'historique est compressé avant la question suivante. Entre 1 et 100. |76 | `threshold` | entier | `75` | Pourcentage de la fenêtre de contexte au-delà duquel l'historique est compressé avant la question suivante. Entre 1 et 100. |
77 | `maxMessages` | entier | `80` | Nombre de messages qui déclenche une compression quand la fenêtre est inconnue ou l'estimation trop basse. `0` désactive. Doit être ≥ 0. |77 | `maxMessages` | entier | `80` | Nombre de messages qui déclenche une compression quand la fenêtre est inconnue ou l'estimation trop basse. `0` désactive. Doit être ≥ 0. |
78-| `keepLastTurns` | entier | `3` | Tours de question conservés bruts en fin d'historique. Doit être ≥ 1. |78+| `keepLastTurns` | entier | `3` | Tours de question conservés bruts en fin d'historique. Doit être ≥ 1. Un tour commence à un message envoyé par l'utilisateur comme question ; les notes de mm au modèle (`[mm: …]`) et les messages tapés pendant un tour appartiennent au tour où ils ont été ajoutés (dans les sessions enregistrées depuis le ticket 289). |
79-| `summaryMaxTokens` | entier | `1200` | `max_tokens` de la requête de résumé. Doit être > 0. Le raisonnement d'un modèle qui réfléchit est décompté de ce budget : sur `dmr`, `llamacpp`, `llmman` et `kronk`, la requête de résumé désactive le raisonnement (`chat_template_kwargs.enable_thinking: false`), sur `ollama` aussi (`reasoning_effort: "none"`, le seul interrupteur qu'Ollama respecte) — quoi que dise `sampling` ; les autres `chat_template_kwargs` sont gardés, et un `reasoning_effort` qui y est fixé est ramené à `low` (gpt-oss n'a pas d'« arrêt ») ; ailleurs, si l'erreur dit que le modèle « reasoned until the limit », augmentez-le. |79+| `summaryMaxTokens` | entier | `1200` | `max_tokens` de la requête de résumé. Doit être > 0. Le raisonnement d'un modèle qui réfléchit est décompté de ce budget : sur `dmr`, `llamacpp`, `llmman` et `kronk`, la requête de résumé désactive le raisonnement (`chat_template_kwargs.enable_thinking: false`), sur `ollama` aussi (`reasoning_effort: "none"`, le seul interrupteur qu'Ollama respecte) — quoi que dise `sampling` ; les autres `chat_template_kwargs` sont gardés, et un `reasoning_effort` qui y est fixé est ramené à `low` (gpt-oss n'a pas d'« arrêt ») ; ailleurs, si l'erreur dit que le modèle « reasoned until the limit », augmentez-le. Un résumé coupé à cette limite perd sa dernière ligne inachevée et se termine par `- [notes cut at the length limit]` ; une ligne `🗜️ a summary was cut at its limit (N tokens)…` le signale une fois par exécution. |
80 | `prompt` | chaîne | `""` | Remplace le prompt de résumé intégré quand non vide. |80 | `prompt` | chaîne | `""` | Remplace le prompt de résumé intégré quand non vide. |
81 | `showStats` | booléen | `true` | Affiche le rapport `🗜️` d'une ligne après chaque compression. |81 | `showStats` | booléen | `true` | Affiche le rapport `🗜️` d'une ligne après chaque compression. |
82-| `compressInTurn` | booléen | `true` | Compresse À L'INTÉRIEUR d'un long tour, entre deux appels d'outils : avant chaque appel au modèle, quand l'historique dépasse `threshold` d'une fenêtre connue, les échanges d'outils du tour en cours sauf les 4 derniers perdent leur volume (un résultat d'outil ou un long argument d'appel — un fichier entier donné à `write_file` — garde sa première ligne et une note qui dit ce qui a été retiré) ; si cela ne suffit pas, ils sont remplacés par des notes que le modèle écrit à leur sujet, ajoutées à la question du tour (fusionnées avec les notes précédentes lors d'une compression suivante). La question, les 4 derniers échanges et les tours précédents ne sont jamais touchés ; un appel d'outil n'est jamais séparé de son résultat. Indépendant d'`enabled` : un tour qui dépasse la fenêtre échoue de toute façon. Demande une fenêtre connue (`contextWindow`, ou celle du serveur). Une ligne `🗜️ in-turn: …` par compression quand `showStats` est actif. `false` laisse le tour grandir. |82+| `compressInTurn` | booléen | `true` | Compresse À L'INTÉRIEUR d'un long tour, entre deux appels d'outils : avant chaque appel au modèle, quand l'historique dépasse `threshold` d'une fenêtre connue, les échanges d'outils du tour en cours sauf les 4 derniers perdent leur volume (un résultat d'outil ou un long argument d'appel — un fichier entier donné à `write_file` — garde sa première ligne et une note qui dit ce qui a été retiré) ; si cela ne suffit pas, ils sont remplacés par des notes que le modèle écrit à leur sujet, ajoutées à la question du tour (fusionnées avec les notes précédentes lors d'une compression suivante). La question, les 4 derniers échanges et les tours précédents ne sont jamais touchés ; un appel d'outil n'est jamais séparé de son résultat. Indépendant d'`enabled` : un tour qui dépasse la fenêtre échoue de toute façon. Demande une fenêtre connue (`contextWindow`, ou celle du serveur). Une ligne `🗜️ in-turn: …` par compression quand `showStats` est actif. Quand l'historique avant le tour, avec sa question, dépasse à lui seul `threshold`, le tour n'est résumé qu'une fois, et sa ligne `🗜️`, affichée quelle que soit la valeur de `showStats`, se termine par `the history before this turn is above the threshold by itself: no more summaries in this turn (…)` ; les appels suivants du tour ne font que réduire. Les tailles sont l'estimation (3,5 caractères par token, schémas des outils compris) multipliée par le rapport entre le dernier compte du serveur et l'estimation de la même requête, si bien qu'un tokenizer dense (code, HTML) n'est pas sous-compté. Quand les 4 derniers échanges dépassent à eux seuls `threshold`, le résumé en garde moins, au moins un. Une requête dont la taille ainsi corrigée dépasse encore la fenêtre après la compression n'est pas envoyée : le tour se termine par `the request (about N tokens, even compressed) is larger than the context window (W), so it was not sent — …`, et le travail fait est conservé. Un résultat (ou un long argument) réduit qui contient du code garde son plan — les lignes `func`, `type`, de classe et de fonction, les champs de structure avec leur nom JSON, les routes HTTP, les appels `fetch(` — sous une note `[mm: outline of a N-line output …]` ; un autre texte garde sa première ligne. Un message réduit ne l'est jamais une seconde fois. Les notes du tour gardent les signatures, les routes et les types des fichiers lus. Un appel d'outil identique à un appel déjà lancé dans le tour, après qu'une compression a retiré des résultats, reçoit `[mm: you already ran this exact call earlier in this task …]` avant son résultat ; à partir du deuxième appel de ce genre dans un tour, `[mm: this is re-read number N in this task — … Stop reading. Make the first change now …]`. Les notes se terminent par la prochaine modification à faire, et leur en-tête demande de ne relire que les lignes dont cette modification a besoin. Les notes commencent par une ligne `Next change:`. `false` laisse le tour grandir. |
83+| `inTurnTarget` | entier | `0` | Le niveau auquel une compression à l'intérieur d'un tour ramène l'historique, en pourcentage de la fenêtre. La compression se déclenche à `threshold` ; elle réduit ensuite les anciens échanges, résume, et en dernier recours réduit aussi les échanges conservés (jamais le dernier) jusqu'à passer sous cette cible, pour que les appels suivants retrouvent le même prompt et le cache du serveur. `0` = deux tiers de `threshold` (75 → 50, 60 → 40). Égal à `threshold` : compresser juste en dessous. Doit être entre 0 et `threshold`. |
84+| `rereadLimit` | entier | `1` | Combien de fois, dans un tour, le même appel d'outil (même outil, mêmes arguments) peut être relancé après qu'une compression du tour a retiré son résultat, sans qu'un `write_file`/`edit_file` ait réussi entre-temps. Une telle répétition s'exécute avec une note avant son résultat ; au-delà de la limite, l'appel n'est PAS exécuté, son résultat est `[mm: not run — this exact call already ran N times in this task … make the change now …]`, et une ligne `🔁 not run: …` le signale. `1` : la troisième lecture identique est refusée. `0` : des notes seulement, jamais de refus. Un fichier modifié par `bash` n'est pas vu comme une modification. Doit être ≥ 0. |
83 85
84 ## Clés de `sessions`86 ## Clés de `sessions`
85 87
@@ -718,6 +720,8 @@ Signalées sur stderr sous la forme `[config error: <chemin>: <message>]`, code
718 | `context.threshold must be between 1 and 100` | hors intervalle |720 | `context.threshold must be between 1 and 100` | hors intervalle |
719 | `context.keepLastTurns must be >= 1` | zéro ou négatif |721 | `context.keepLastTurns must be >= 1` | zéro ou négatif |
720 | `context.summaryMaxTokens must be > 0` | zéro ou négatif |722 | `context.summaryMaxTokens must be > 0` | zéro ou négatif |
723+| `context.inTurnTarget must be between 0 and context.threshold` | négatif, ou au-dessus de `threshold` |
724+| `context.rereadLimit must be >= 0` | négatif |
721 | `context.maxMessages must be >= 0` | valeur négative |725 | `context.maxMessages must be >= 0` | valeur négative |
722 | `sessions.dir must not be empty` | chaîne vide |726 | `sessions.dir must not be empty` | chaîne vide |
723 | `docSearch.dirs must name at least one folder` | `dirs: []` avec un interrupteur activé |727 | `docSearch.dirs must name at least one folder` | `dirs: []` avec un interrupteur activé |
added internal/compact/budget.go +95 -0
new file mode 100644
@@ -0,0 +1,95 @@
1+package compact
2+
3+import "github.com/firebase/genkit/go/ai"
4+
5+// What an in-turn compression measures against, and how far it goes
6+// (tickets 290, 291): the trigger, the target under it, the calibrated
7+// size, and the two ways to reach the target — keeping fewer exchanges
8+// raw after a summary, and, as a last resort, shrinking them.
9+
10+// Budget is what CompactTurn measures a history against: a known window,
11+// the share of it not to pass, and the estimate's scale.
12+//
13+// b := compact.Budget{Window: 16384, Threshold: 75, Calibration: cal}
14+// r, err := compact.CompactTurn(ctx, msgs, b, summarize)
15+type Budget struct {
16+ Window int // tokens; 0 = unknown, never passed
17+ Threshold int // percent of Window: the trigger
18+ // Target is the percent of Window a compression brings the history
19+ // down to (context.inTurnTarget); 0 = two thirds of Threshold.
20+ Target int
21+ Calibration
22+}
23+
24+// over reports whether tokens reach the threshold of a known window.
25+func (b Budget) over(tokens int) bool {
26+ return b.Window > 0 && tokens*100 >= b.Window*b.Threshold
27+}
28+
29+// above reports whether the calibrated size of msgs reaches the threshold.
30+func (b Budget) above(msgs []*ai.Message) bool {
31+ return b.over(b.Tokens(msgs))
32+}
33+
34+// target is the percent a compression aims at: Target, at most Threshold,
35+// or two thirds of Threshold when unset.
36+func (b Budget) target() int {
37+ if b.Target > 0 {
38+ return min(b.Target, b.Threshold)
39+ }
40+ return b.Threshold * 2 / 3
41+}
42+
43+// aboveTarget reports whether the calibrated size of msgs reaches the target.
44+func (b Budget) aboveTarget(msgs []*ai.Message) bool {
45+ return b.Window > 0 && b.Tokens(msgs)*100 >= b.Window*b.target()
46+}
47+
48+// shrinkTail shrinks the kept exchanges too, oldest first, while the
49+// history stays above the target — never the last exchange, the one the
50+// model is working on. It returns how many results and arguments it cut.
51+// CompactTurn calls it after the summary: notes keep what a shrunk result
52+// loses.
53+// Shrinking the older half of the turn alone gets the history just under
54+// the threshold, and the next read passes it again: one compression per
55+// call, each one a prompt-cache miss (ticket 290).
56+func shrinkTail(out []*ai.Message, cut int, b Budget) int {
57+ last := len(out)
58+ for i := len(out) - 1; i >= cut; i-- {
59+ if out[i].Role == ai.RoleModel && hasToolRequest(out[i]) {
60+ last = i
61+ break
62+ }
63+ }
64+ n := 0
65+ for i := cut; i < last && b.aboveTarget(out); i++ {
66+ if m, k := shrink(out[i]); k > 0 {
67+ out[i], n = m, n+k
68+ }
69+ }
70+ return n
71+}
72+
73+// summaryCut is where the raw tail starts once the turn is summarised: the
74+// last KeepToolCalls exchanges (cut), or fewer when those alone keep the
75+// history above the target — as many as fit under it, at least one. When
76+// not even the last one fits, all KeepToolCalls stay: dropping work would
77+// not reach the threshold anyway. Without it, a turn
78+// whose last four results are big files (three `cat`s of 5k characters are
79+// 13k tokens with a dense tokenizer, over a 12.3k threshold) is summarised
80+// before every call and never gets under the threshold (ticket 291).
81+func summaryCut(out []*ai.Message, q, cut int, b Budget) int {
82+ var starts []int // the kept exchanges, oldest first
83+ for i := cut; i < len(out); i++ {
84+ if out[i].Role == ai.RoleModel && hasToolRequest(out[i]) {
85+ starts = append(starts, i)
86+ }
87+ }
88+ for _, start := range starts {
89+ kept := append(append([]*ai.Message{}, out[:q+1]...), out[start:]...)
90+ if !b.aboveTarget(kept) {
91+ return start
92+ }
93+ }
94+ return cut
95+}
new file mode 100644
@@ -0,0 +1,95 @@
1+package compact
2+
3+import "github.com/firebase/genkit/go/ai"
4+
5+// What an in-turn compression measures against, and how far it goes
6+// (tickets 290, 291): the trigger, the target under it, the calibrated
7+// size, and the two ways to reach the target — keeping fewer exchanges
8+// raw after a summary, and, as a last resort, shrinking them.
9+
10+// Budget is what CompactTurn measures a history against: a known window,
11+// the share of it not to pass, and the estimate's scale.
12+//
13+// b := compact.Budget{Window: 16384, Threshold: 75, Calibration: cal}
14+// r, err := compact.CompactTurn(ctx, msgs, b, summarize)
15+type Budget struct {
16+ Window int // tokens; 0 = unknown, never passed
17+ Threshold int // percent of Window: the trigger
18+ // Target is the percent of Window a compression brings the history
19+ // down to (context.inTurnTarget); 0 = two thirds of Threshold.
20+ Target int
21+ Calibration
22+}
23+
24+// over reports whether tokens reach the threshold of a known window.
25+func (b Budget) over(tokens int) bool {
26+ return b.Window > 0 && tokens*100 >= b.Window*b.Threshold
27+}
28+
29+// above reports whether the calibrated size of msgs reaches the threshold.
30+func (b Budget) above(msgs []*ai.Message) bool {
31+ return b.over(b.Tokens(msgs))
32+}
33+
34+// target is the percent a compression aims at: Target, at most Threshold,
35+// or two thirds of Threshold when unset.
36+func (b Budget) target() int {
37+ if b.Target > 0 {
38+ return min(b.Target, b.Threshold)
39+ }
40+ return b.Threshold * 2 / 3
41+}
42+
43+// aboveTarget reports whether the calibrated size of msgs reaches the target.
44+func (b Budget) aboveTarget(msgs []*ai.Message) bool {
45+ return b.Window > 0 && b.Tokens(msgs)*100 >= b.Window*b.target()
46+}
47+
48+// shrinkTail shrinks the kept exchanges too, oldest first, while the
49+// history stays above the target — never the last exchange, the one the
50+// model is working on. It returns how many results and arguments it cut.
51+// CompactTurn calls it after the summary: notes keep what a shrunk result
52+// loses.
53+// Shrinking the older half of the turn alone gets the history just under
54+// the threshold, and the next read passes it again: one compression per
55+// call, each one a prompt-cache miss (ticket 290).
56+func shrinkTail(out []*ai.Message, cut int, b Budget) int {
57+ last := len(out)
58+ for i := len(out) - 1; i >= cut; i-- {
59+ if out[i].Role == ai.RoleModel && hasToolRequest(out[i]) {
60+ last = i
61+ break
62+ }
63+ }
64+ n := 0
65+ for i := cut; i < last && b.aboveTarget(out); i++ {
66+ if m, k := shrink(out[i]); k > 0 {
67+ out[i], n = m, n+k
68+ }
69+ }
70+ return n
71+}
72+
73+// summaryCut is where the raw tail starts once the turn is summarised: the
74+// last KeepToolCalls exchanges (cut), or fewer when those alone keep the
75+// history above the target — as many as fit under it, at least one. When
76+// not even the last one fits, all KeepToolCalls stay: dropping work would
77+// not reach the threshold anyway. Without it, a turn
78+// whose last four results are big files (three `cat`s of 5k characters are
79+// 13k tokens with a dense tokenizer, over a 12.3k threshold) is summarised
80+// before every call and never gets under the threshold (ticket 291).
81+func summaryCut(out []*ai.Message, q, cut int, b Budget) int {
82+ var starts []int // the kept exchanges, oldest first
83+ for i := cut; i < len(out); i++ {
84+ if out[i].Role == ai.RoleModel && hasToolRequest(out[i]) {
85+ starts = append(starts, i)
86+ }
87+ }
88+ for _, start := range starts {
89+ kept := append(append([]*ai.Message{}, out[:q+1]...), out[start:]...)
90+ if !b.aboveTarget(kept) {
91+ return start
92+ }
93+ }
94+ return cut
95+}
added internal/compact/calibrate.go +81 -0
new file mode 100644
@@ -0,0 +1,81 @@
1+package compact
2+
3+import (
4+ "encoding/json"
5+
6+ "github.com/firebase/genkit/go/ai"
7+)
8+
9+// Calibration (ticket 291): Estimate counts 3.5 characters per token, which
10+// holds for English prose. Code and HTML tokenise denser, and the request
11+// also carries the tools' schemas, which a history never shows. Observed
12+// with Inkling-2-Mini on Go, HTML and shell output: Estimate said 8.3k, the
13+// server read 17.2k. The in-turn compression fired on the server's count,
14+// then judged its own work with the estimate — "under the threshold" — so it
15+// never summarised: one shrink per call, a 17k-token prompt re-read without
16+// cache at every call, until the server stopped answering.
17+//
18+// So the estimate is scaled by what the server measured last time: the
19+// ratio between its count and the estimate of the same request (messages
20+// and tools). It is a property of the model's tokenizer and of the kind of
21+// text in the session, so it outlives a compression, unlike the count.
22+
23+// maxRatio caps the scale: a server that counts more than four tokens per
24+// estimated token is reporting something else (a cumulative count, a bug).
25+const maxRatio = 4.0
26+
27+// Calibration turns an estimate into the server's tokens. The zero value
28+// (no measure yet) is the plain estimate.
29+type Calibration struct {
30+ // Ratio is the server's count over the estimate of the same request;
31+ // values under 1 are not used: the estimate is already the safe side.
32+ Ratio float64
33+ // Tools is the estimate of the tools' schemas the next request carries.
34+ Tools int
35+}
36+
37+// Calibrate is the calibration a measured request gives: the server read
38+// `measured` tokens of a request whose estimate was `estimated` (messages
39+// plus tools). A missing measure gives the zero ratio.
40+//
41+// cal := compact.Calibrate(17226, 9800, 1480) // Ratio ≈ 1.76
42+// cal.Tokens(msgs) // ≈ 1.76 × (Estimate(msgs) + 1480)
43+func Calibrate(measured, estimated, tools int) Calibration {
44+ c := Calibration{Tools: tools}
45+ if measured > 0 && estimated > 0 {
46+ c.Ratio = min(float64(measured)/float64(estimated), maxRatio)
47+ }
48+ return c
49+}
50+
51+// Tokens is the calibrated size of a request made of msgs and the tools.
52+func (c Calibration) Tokens(msgs []*ai.Message) int {
53+ return c.scale(Estimate(msgs) + c.Tools)
54+}
55+
56+// scale applies the ratio to an estimate, never below it.
57+func (c Calibration) scale(estimate int) int {
58+ if c.Ratio <= 1 {
59+ return estimate
60+ }
61+ return int(float64(estimate) * c.Ratio)
62+}
63+
64+// EstimateTools is the estimate of the tools' schemas as a request carries
65+// them: name, description and input schema, at the same 3.5 characters per
66+// token as Estimate.
67+//
68+// compact.EstimateTools(params.Request.Tools) // ≈ 1480 for mm's 4 tools
69+func EstimateTools(tools []*ai.ToolDefinition) int {
70+ chars := 0
71+ for _, t := range tools {
72+ if t == nil {
73+ continue
74+ }
75+ chars += len(t.Name) + len(t.Description)
76+ if b, err := json.Marshal(t.InputSchema); err == nil {
77+ chars += len(b)
78+ }
79+ }
80+ return (chars*2 + 6) / 7
81+}
new file mode 100644
@@ -0,0 +1,81 @@
1+package compact
2+
3+import (
4+ "encoding/json"
5+
6+ "github.com/firebase/genkit/go/ai"
7+)
8+
9+// Calibration (ticket 291): Estimate counts 3.5 characters per token, which
10+// holds for English prose. Code and HTML tokenise denser, and the request
11+// also carries the tools' schemas, which a history never shows. Observed
12+// with Inkling-2-Mini on Go, HTML and shell output: Estimate said 8.3k, the
13+// server read 17.2k. The in-turn compression fired on the server's count,
14+// then judged its own work with the estimate — "under the threshold" — so it
15+// never summarised: one shrink per call, a 17k-token prompt re-read without
16+// cache at every call, until the server stopped answering.
17+//
18+// So the estimate is scaled by what the server measured last time: the
19+// ratio between its count and the estimate of the same request (messages
20+// and tools). It is a property of the model's tokenizer and of the kind of
21+// text in the session, so it outlives a compression, unlike the count.
22+
23+// maxRatio caps the scale: a server that counts more than four tokens per
24+// estimated token is reporting something else (a cumulative count, a bug).
25+const maxRatio = 4.0
26+
27+// Calibration turns an estimate into the server's tokens. The zero value
28+// (no measure yet) is the plain estimate.
29+type Calibration struct {
30+ // Ratio is the server's count over the estimate of the same request;
31+ // values under 1 are not used: the estimate is already the safe side.
32+ Ratio float64
33+ // Tools is the estimate of the tools' schemas the next request carries.
34+ Tools int
35+}
36+
37+// Calibrate is the calibration a measured request gives: the server read
38+// `measured` tokens of a request whose estimate was `estimated` (messages
39+// plus tools). A missing measure gives the zero ratio.
40+//
41+// cal := compact.Calibrate(17226, 9800, 1480) // Ratio ≈ 1.76
42+// cal.Tokens(msgs) // ≈ 1.76 × (Estimate(msgs) + 1480)
43+func Calibrate(measured, estimated, tools int) Calibration {
44+ c := Calibration{Tools: tools}
45+ if measured > 0 && estimated > 0 {
46+ c.Ratio = min(float64(measured)/float64(estimated), maxRatio)
47+ }
48+ return c
49+}
50+
51+// Tokens is the calibrated size of a request made of msgs and the tools.
52+func (c Calibration) Tokens(msgs []*ai.Message) int {
53+ return c.scale(Estimate(msgs) + c.Tools)
54+}
55+
56+// scale applies the ratio to an estimate, never below it.
57+func (c Calibration) scale(estimate int) int {
58+ if c.Ratio <= 1 {
59+ return estimate
60+ }
61+ return int(float64(estimate) * c.Ratio)
62+}
63+
64+// EstimateTools is the estimate of the tools' schemas as a request carries
65+// them: name, description and input schema, at the same 3.5 characters per
66+// token as Estimate.
67+//
68+// compact.EstimateTools(params.Request.Tools) // ≈ 1480 for mm's 4 tools
69+func EstimateTools(tools []*ai.ToolDefinition) int {
70+ chars := 0
71+ for _, t := range tools {
72+ if t == nil {
73+ continue
74+ }
75+ chars += len(t.Name) + len(t.Description)
76+ if b, err := json.Marshal(t.InputSchema); err == nil {
77+ chars += len(b)
78+ }
79+ }
80+ return (chars*2 + 6) / 7
81+}
added internal/compact/calibrate_test.go +140 -0
new file mode 100644
@@ -0,0 +1,140 @@
1+package compact
2+
3+import (
4+ "context"
5+ "math"
6+ "strings"
7+ "testing"
8+
9+ "github.com/firebase/genkit/go/ai"
10+)
11+
12+func TestCalibrate(t *testing.T) {
13+ // The figures of the observed session: 17226 tokens read, 9800 estimated.
14+ if c := Calibrate(17226, 9800, 1480); math.Abs(c.Ratio-1.7578) > 0.001 || c.Tools != 1480 {
15+ t.Errorf("Calibrate = %+v, want ratio ≈ 1.758 and the tools kept", c)
16+ }
17+ if c := Calibrate(100000, 10, 0); c.Ratio != maxRatio {
18+ t.Errorf("ratio %v, want capped at %v", c.Ratio, maxRatio)
19+ }
20+ if c := Calibrate(0, 9800, 0); c.Ratio != 0 {
21+ t.Errorf("no measure: ratio %v, want 0", c.Ratio)
22+ }
23+ msgs := history(turn("q1", 2, "some output"))
24+ if got, want := (Calibration{}).Tokens(msgs), Estimate(msgs); got != want {
25+ t.Errorf("zero calibration: %d, want the plain estimate %d", got, want)
26+ }
27+ if got, want := (Calibration{Ratio: 0.5, Tools: 10}).Tokens(msgs), Estimate(msgs)+10; got != want {
28+ t.Errorf("ratio under 1: %d, want the estimate %d (never below it)", got, want)
29+ }
30+ if got, want := (Calibration{Ratio: 2, Tools: 10}).Tokens(msgs), 2*(Estimate(msgs)+10); got != want {
31+ t.Errorf("ratio 2: %d, want %d", got, want)
32+ }
33+}
34+
35+func TestEstimateTools(t *testing.T) {
36+ tools := []*ai.ToolDefinition{
37+ {Name: "bash", Description: "run a command", InputSchema: map[string]any{"type": "object"}},
38+ nil,
39+ }
40+ if n := EstimateTools(tools); n <= 0 {
41+ t.Errorf("EstimateTools = %d, want > 0", n)
42+ }
43+ if n := EstimateTools(nil); n != 0 {
44+ t.Errorf("no tools: %d, want 0", n)
45+ }
46+}
47+
48+// Ticket 291: the estimate is half of the server's count. Plain, the shrunk
49+// turn looks under the threshold and is never summarised; calibrated, it is.
50+func TestCompactTurnSummarisesOnTheCalibratedSize(t *testing.T) {
51+ msgs := longTurn(10)
52+ shrunk, err := CompactTurn(context.Background(), msgs, budget(0, Calibration{}), nil)
53+ if err != nil {
54+ t.Fatal(err)
55+ }
56+ // After shrinking: 60 % of the window by the estimate, 120 % calibrated.
57+ window := shrunk.After * 100 / 60
58+
59+ // Target = threshold: this test isolates the calibration from the
60+ // hysteresis of ticket 290.
61+ at := func(cal Calibration) Budget {
62+ return Budget{Window: window, Threshold: 75, Target: 75, Calibration: cal}
63+ }
64+ plain, calibrated := 0, 0
65+ if _, err := CompactTurn(context.Background(), msgs, at(Calibration{}), counting(&plain)); err != nil {
66+ t.Fatal(err)
67+ }
68+ r, err := CompactTurn(context.Background(), msgs, at(Calibration{Ratio: 2}), counting(&calibrated))
69+ if err != nil {
70+ t.Fatal(err)
71+ }
72+ if plain != 0 || calibrated != 1 {
73+ t.Errorf("summary requests: plain %d (want 0), calibrated %d (want 1)", plain, calibrated)
74+ }
75+ if r.Before != (Calibration{Ratio: 2}).Tokens(msgs) {
76+ t.Errorf("report sizes are not calibrated: before %d", r.Before)
77+ }
78+ if err := Valid(r.Messages); err != nil {
79+ t.Fatal(err)
80+ }
81+}
82+
83+// The floor of ticket 289 is judged on the calibrated size too.
84+func TestCompactTurnFloorUsesTheCalibration(t *testing.T) {
85+ msgs := longTurn(10)
86+ msgs[2] = ai.NewModelTextMessage(strings.Repeat("an earlier answer. ", 300))
87+ window := 2 * floorOf(msgs) // 50 % by the estimate, 100 % calibrated
88+ asked := 0
89+ r, err := CompactTurn(context.Background(), msgs, budget(window, Calibration{Ratio: 2}), counting(&asked))
90+ if err != nil {
91+ t.Fatal(err)
92+ }
93+ if !r.FloorTooHigh {
94+ t.Errorf("floor at 100 %% calibrated: FloorTooHigh false (%+v)", r)
95+ }
96+}
97+
98+func TestInTurnDecideUsesTheCalibration(t *testing.T) {
99+ msgs := longTurn(4)
100+ window := Estimate(msgs) * 100 / 60 // 60 % by the estimate
101+ if InTurnDecide(msgs, 0, window, Calibration{}, inTurnCfg()) {
102+ t.Error("plain estimate at 60 %: must not decide")
103+ }
104+ if !InTurnDecide(msgs, 0, window, Calibration{Ratio: 2}, inTurnCfg()) {
105+ t.Error("calibrated at 120 %: must decide")
106+ }
107+}
108+
109+// When the last KeepToolCalls exchanges alone pass the threshold, the
110+// summary keeps fewer of them, so the history gets under it — not a summary
111+// before every call (ticket 291).
112+func TestCompactTurnKeepsFewerExchangesWhenTheTailIsTooBig(t *testing.T) {
113+ msgs := longTurn(10)
114+ q, cut := turnBounds(msgs)
115+ tail := append(append([]*ai.Message{}, msgs[:q+1]...), msgs[cut:]...)
116+ window := Estimate(tail) // the head and the 4 kept exchanges: 100 %
117+ asked := 0
118+ r, err := CompactTurn(context.Background(), msgs, budget(window, Calibration{}), counting(&asked))
119+ if err != nil {
120+ t.Fatal(err)
121+ }
122+ if asked != 1 || r.Summarised == 0 {
123+ t.Fatalf("no summary: %+v", r)
124+ }
125+ if budget(window, Calibration{}).above(r.Messages) {
126+ t.Errorf("still above the threshold after the summary: %d of %d", Estimate(r.Messages), window)
127+ }
128+ kept := 0
129+ for _, m := range r.Messages[q+1:] {
130+ if m.Role == ai.RoleModel && hasToolRequest(m) {
131+ kept++
132+ }
133+ }
134+ if kept < 1 || kept >= KeepToolCalls {
135+ t.Errorf("%d exchanges kept, want between 1 and %d", kept, KeepToolCalls-1)
136+ }
137+ if err := Valid(r.Messages); err != nil {
138+ t.Fatal(err)
139+ }
140+}
new file mode 100644
@@ -0,0 +1,140 @@
1+package compact
2+
3+import (
4+ "context"
5+ "math"
6+ "strings"
7+ "testing"
8+
9+ "github.com/firebase/genkit/go/ai"
10+)
11+
12+func TestCalibrate(t *testing.T) {
13+ // The figures of the observed session: 17226 tokens read, 9800 estimated.
14+ if c := Calibrate(17226, 9800, 1480); math.Abs(c.Ratio-1.7578) > 0.001 || c.Tools != 1480 {
15+ t.Errorf("Calibrate = %+v, want ratio ≈ 1.758 and the tools kept", c)
16+ }
17+ if c := Calibrate(100000, 10, 0); c.Ratio != maxRatio {
18+ t.Errorf("ratio %v, want capped at %v", c.Ratio, maxRatio)
19+ }
20+ if c := Calibrate(0, 9800, 0); c.Ratio != 0 {
21+ t.Errorf("no measure: ratio %v, want 0", c.Ratio)
22+ }
23+ msgs := history(turn("q1", 2, "some output"))
24+ if got, want := (Calibration{}).Tokens(msgs), Estimate(msgs); got != want {
25+ t.Errorf("zero calibration: %d, want the plain estimate %d", got, want)
26+ }
27+ if got, want := (Calibration{Ratio: 0.5, Tools: 10}).Tokens(msgs), Estimate(msgs)+10; got != want {
28+ t.Errorf("ratio under 1: %d, want the estimate %d (never below it)", got, want)
29+ }
30+ if got, want := (Calibration{Ratio: 2, Tools: 10}).Tokens(msgs), 2*(Estimate(msgs)+10); got != want {
31+ t.Errorf("ratio 2: %d, want %d", got, want)
32+ }
33+}
34+
35+func TestEstimateTools(t *testing.T) {
36+ tools := []*ai.ToolDefinition{
37+ {Name: "bash", Description: "run a command", InputSchema: map[string]any{"type": "object"}},
38+ nil,
39+ }
40+ if n := EstimateTools(tools); n <= 0 {
41+ t.Errorf("EstimateTools = %d, want > 0", n)
42+ }
43+ if n := EstimateTools(nil); n != 0 {
44+ t.Errorf("no tools: %d, want 0", n)
45+ }
46+}
47+
48+// Ticket 291: the estimate is half of the server's count. Plain, the shrunk
49+// turn looks under the threshold and is never summarised; calibrated, it is.
50+func TestCompactTurnSummarisesOnTheCalibratedSize(t *testing.T) {
51+ msgs := longTurn(10)
52+ shrunk, err := CompactTurn(context.Background(), msgs, budget(0, Calibration{}), nil)
53+ if err != nil {
54+ t.Fatal(err)
55+ }
56+ // After shrinking: 60 % of the window by the estimate, 120 % calibrated.
57+ window := shrunk.After * 100 / 60
58+
59+ // Target = threshold: this test isolates the calibration from the
60+ // hysteresis of ticket 290.
61+ at := func(cal Calibration) Budget {
62+ return Budget{Window: window, Threshold: 75, Target: 75, Calibration: cal}
63+ }
64+ plain, calibrated := 0, 0
65+ if _, err := CompactTurn(context.Background(), msgs, at(Calibration{}), counting(&plain)); err != nil {
66+ t.Fatal(err)
67+ }
68+ r, err := CompactTurn(context.Background(), msgs, at(Calibration{Ratio: 2}), counting(&calibrated))
69+ if err != nil {
70+ t.Fatal(err)
71+ }
72+ if plain != 0 || calibrated != 1 {
73+ t.Errorf("summary requests: plain %d (want 0), calibrated %d (want 1)", plain, calibrated)
74+ }
75+ if r.Before != (Calibration{Ratio: 2}).Tokens(msgs) {
76+ t.Errorf("report sizes are not calibrated: before %d", r.Before)
77+ }
78+ if err := Valid(r.Messages); err != nil {
79+ t.Fatal(err)
80+ }
81+}
82+
83+// The floor of ticket 289 is judged on the calibrated size too.
84+func TestCompactTurnFloorUsesTheCalibration(t *testing.T) {
85+ msgs := longTurn(10)
86+ msgs[2] = ai.NewModelTextMessage(strings.Repeat("an earlier answer. ", 300))
87+ window := 2 * floorOf(msgs) // 50 % by the estimate, 100 % calibrated
88+ asked := 0
89+ r, err := CompactTurn(context.Background(), msgs, budget(window, Calibration{Ratio: 2}), counting(&asked))
90+ if err != nil {
91+ t.Fatal(err)
92+ }
93+ if !r.FloorTooHigh {
94+ t.Errorf("floor at 100 %% calibrated: FloorTooHigh false (%+v)", r)
95+ }
96+}
97+
98+func TestInTurnDecideUsesTheCalibration(t *testing.T) {
99+ msgs := longTurn(4)
100+ window := Estimate(msgs) * 100 / 60 // 60 % by the estimate
101+ if InTurnDecide(msgs, 0, window, Calibration{}, inTurnCfg()) {
102+ t.Error("plain estimate at 60 %: must not decide")
103+ }
104+ if !InTurnDecide(msgs, 0, window, Calibration{Ratio: 2}, inTurnCfg()) {
105+ t.Error("calibrated at 120 %: must decide")
106+ }
107+}
108+
109+// When the last KeepToolCalls exchanges alone pass the threshold, the
110+// summary keeps fewer of them, so the history gets under it — not a summary
111+// before every call (ticket 291).
112+func TestCompactTurnKeepsFewerExchangesWhenTheTailIsTooBig(t *testing.T) {
113+ msgs := longTurn(10)
114+ q, cut := turnBounds(msgs)
115+ tail := append(append([]*ai.Message{}, msgs[:q+1]...), msgs[cut:]...)
116+ window := Estimate(tail) // the head and the 4 kept exchanges: 100 %
117+ asked := 0
118+ r, err := CompactTurn(context.Background(), msgs, budget(window, Calibration{}), counting(&asked))
119+ if err != nil {
120+ t.Fatal(err)
121+ }
122+ if asked != 1 || r.Summarised == 0 {
123+ t.Fatalf("no summary: %+v", r)
124+ }
125+ if budget(window, Calibration{}).above(r.Messages) {
126+ t.Errorf("still above the threshold after the summary: %d of %d", Estimate(r.Messages), window)
127+ }
128+ kept := 0
129+ for _, m := range r.Messages[q+1:] {
130+ if m.Role == ai.RoleModel && hasToolRequest(m) {
131+ kept++
132+ }
133+ }
134+ if kept < 1 || kept >= KeepToolCalls {
135+ t.Errorf("%d exchanges kept, want between 1 and %d", kept, KeepToolCalls-1)
136+ }
137+ if err := Valid(r.Messages); err != nil {
138+ t.Fatal(err)
139+ }
140+}
modified internal/compact/compact.go +5 -2
@@ -189,7 +189,10 @@ func summaryOf(ctx context.Context, old [][]*ai.Message, prompt string, summariz
189189 // Split separates the leading system message(s) from the question turns. A
190190 // turn starts at a user message and runs until the next one, so it holds the
191191 // whole model ↔ tools exchange the question caused; an earlier summary pair is
192-// a turn of its own, since it starts with a user message too.
192+// a turn of its own, since it starts with a user message too. A message mm
193+// injected in the user's role (IsInjected: a note to the model, a message
194+// steered into a running turn) does not start a turn: it belongs to the turn
195+// it was added to.
193196 //
194197 // Every strategy of CONTEXT_WINDOW.md cuts on these boundaries: cutting on a
195198 // message count can leave a `tool` message without the `assistant` that asked
@@ -201,7 +204,7 @@ func Split(msgs []*ai.Message) (head []*ai.Message, turns [][]*ai.Message) {
201204 }
202205 head = msgs[:i]
203206 for _, m := range msgs[i:] {
204- if m.Role == ai.RoleUser || len(turns) == 0 {
207+ if (m.Role == ai.RoleUser && !IsInjected(m)) || len(turns) == 0 {
205208 turns = append(turns, nil)
206209 }
207210 turns[len(turns)-1] = append(turns[len(turns)-1], m)
@@ -189,7 +189,10 @@ func summaryOf(ctx context.Context, old [][]*ai.Message, prompt string, summariz
189 // Split separates the leading system message(s) from the question turns. A189 // Split separates the leading system message(s) from the question turns. A
190 // turn starts at a user message and runs until the next one, so it holds the190 // turn starts at a user message and runs until the next one, so it holds the
191 // whole model ↔ tools exchange the question caused; an earlier summary pair is191 // whole model ↔ tools exchange the question caused; an earlier summary pair is
192-// a turn of its own, since it starts with a user message too.192+// a turn of its own, since it starts with a user message too. A message mm
193+// injected in the user's role (IsInjected: a note to the model, a message
194+// steered into a running turn) does not start a turn: it belongs to the turn
195+// it was added to.
193 //196 //
194 // Every strategy of CONTEXT_WINDOW.md cuts on these boundaries: cutting on a197 // Every strategy of CONTEXT_WINDOW.md cuts on these boundaries: cutting on a
195 // message count can leave a `tool` message without the `assistant` that asked198 // message count can leave a `tool` message without the `assistant` that asked
@@ -201,7 +204,7 @@ func Split(msgs []*ai.Message) (head []*ai.Message, turns [][]*ai.Message) {
201 }204 }
202 head = msgs[:i]205 head = msgs[:i]
203 for _, m := range msgs[i:] {206 for _, m := range msgs[i:] {
204- if m.Role == ai.RoleUser || len(turns) == 0 {207+ if (m.Role == ai.RoleUser && !IsInjected(m)) || len(turns) == 0 {
205 turns = append(turns, nil)208 turns = append(turns, nil)
206 }209 }
207 turns[len(turns)-1] = append(turns[len(turns)-1], m)210 turns[len(turns)-1] = append(turns[len(turns)-1], m)
added internal/compact/injected.go +56 -0
new file mode 100644
@@ -0,0 +1,56 @@
1+package compact
2+
3+import "github.com/firebase/genkit/go/ai"
4+
5+// Messages mm writes itself in the user's role (ticket 289).
6+//
7+// mm hands the model some notes as user messages — "[mm: your last tool call
8+// was not run…]", a message the user typed while the turn was running — but
9+// none of them is a new question. Split used to start a turn at every user
10+// message, so each of these counted against keepLastTurns: in one observed
11+// session the last "three turns" were 102 messages (about 20k tokens of a
12+// 16k window), the compaction had nothing old to summarise, and the in-turn
13+// compression then fired before every model call, for hours.
14+//
15+// A message marked here stays where it is in the history; it only no longer
16+// opens a turn, for Split (between questions) nor for turnBounds (inside a
17+// turn). Messages saved before the mark existed carry none, and are split as
18+// they used to be.
19+
20+// InjectedKey is the metadata key of a message mm injected in the user's
21+// role. It is not metaKey: a compression re-tags the turn's question
22+// ("in-turn"), which must never remove this mark.
23+const InjectedKey = "mm"
24+
25+// The kinds of injected message.
26+const (
27+ // InjectedNotice is a note mm writes to the model — a tool call that was
28+ // cut off, a reply cut at the token limit, a failed edit, a loop.
29+ InjectedNotice = "notice"
30+ // InjectedSteer is a message the user typed during a turn (ticket 265):
31+ // the user's words, but part of the running turn.
32+ InjectedSteer = "steer"
33+)
34+
35+// MarkInjected tags m as a message mm injected, of the given kind, and
36+// returns it. Its other metadata is kept.
37+//
38+// note := compact.MarkInjected(ai.NewUserTextMessage("[mm: …]"), compact.InjectedNotice)
39+// compact.IsInjected(note) // true
40+func MarkInjected(m *ai.Message, kind string) *ai.Message {
41+ if m.Metadata == nil {
42+ m.Metadata = map[string]any{}
43+ }
44+ m.Metadata[InjectedKey] = kind
45+ return m
46+}
47+
48+// IsInjected reports whether m is a user message mm injected (MarkInjected):
49+// it belongs to the turn it appears in, it does not start one.
50+func IsInjected(m *ai.Message) bool {
51+ if m == nil || m.Role != ai.RoleUser {
52+ return false
53+ }
54+ kind, _ := m.Metadata[InjectedKey].(string)
55+ return kind != ""
56+}
new file mode 100644
@@ -0,0 +1,56 @@
1+package compact
2+
3+import "github.com/firebase/genkit/go/ai"
4+
5+// Messages mm writes itself in the user's role (ticket 289).
6+//
7+// mm hands the model some notes as user messages — "[mm: your last tool call
8+// was not run…]", a message the user typed while the turn was running — but
9+// none of them is a new question. Split used to start a turn at every user
10+// message, so each of these counted against keepLastTurns: in one observed
11+// session the last "three turns" were 102 messages (about 20k tokens of a
12+// 16k window), the compaction had nothing old to summarise, and the in-turn
13+// compression then fired before every model call, for hours.
14+//
15+// A message marked here stays where it is in the history; it only no longer
16+// opens a turn, for Split (between questions) nor for turnBounds (inside a
17+// turn). Messages saved before the mark existed carry none, and are split as
18+// they used to be.
19+
20+// InjectedKey is the metadata key of a message mm injected in the user's
21+// role. It is not metaKey: a compression re-tags the turn's question
22+// ("in-turn"), which must never remove this mark.
23+const InjectedKey = "mm"
24+
25+// The kinds of injected message.
26+const (
27+ // InjectedNotice is a note mm writes to the model — a tool call that was
28+ // cut off, a reply cut at the token limit, a failed edit, a loop.
29+ InjectedNotice = "notice"
30+ // InjectedSteer is a message the user typed during a turn (ticket 265):
31+ // the user's words, but part of the running turn.
32+ InjectedSteer = "steer"
33+)
34+
35+// MarkInjected tags m as a message mm injected, of the given kind, and
36+// returns it. Its other metadata is kept.
37+//
38+// note := compact.MarkInjected(ai.NewUserTextMessage("[mm: …]"), compact.InjectedNotice)
39+// compact.IsInjected(note) // true
40+func MarkInjected(m *ai.Message, kind string) *ai.Message {
41+ if m.Metadata == nil {
42+ m.Metadata = map[string]any{}
43+ }
44+ m.Metadata[InjectedKey] = kind
45+ return m
46+}
47+
48+// IsInjected reports whether m is a user message mm injected (MarkInjected):
49+// it belongs to the turn it appears in, it does not start one.
50+func IsInjected(m *ai.Message) bool {
51+ if m == nil || m.Role != ai.RoleUser {
52+ return false
53+ }
54+ kind, _ := m.Metadata[InjectedKey].(string)
55+ return kind != ""
56+}
added internal/compact/injected_test.go +144 -0
new file mode 100644
@@ -0,0 +1,144 @@
1+package compact
2+
3+import (
4+ "context"
5+ "encoding/json"
6+ "strings"
7+ "testing"
8+
9+ "github.com/firebase/genkit/go/ai"
10+)
11+
12+// turnWith is a question turn with a message mm injected between its two
13+// tool exchanges — the shape of a cut tool call's notice, or of a message
14+// the user steered into the running turn.
15+func turnWith(question string, injected *ai.Message, output string) []*ai.Message {
16+ a, b := question+"-a", question+"-b"
17+ return []*ai.Message{
18+ ai.NewUserTextMessage(question),
19+ ai.NewModelMessage(req(a, "echo "+a)),
20+ ai.NewMessage(ai.RoleTool, nil, resp(a, output)),
21+ injected,
22+ ai.NewModelMessage(req(b, "echo "+b)),
23+ ai.NewMessage(ai.RoleTool, nil, resp(b, output)),
24+ ai.NewModelMessage(ai.NewTextPart("done " + question)),
25+ }
26+}
27+
28+func notice() *ai.Message {
29+ return MarkInjected(ai.NewUserTextMessage("[mm: your last tool call was not run: it was cut off before its end]"), InjectedNotice)
30+}
31+
32+func steer() *ai.Message {
33+ return MarkInjected(ai.NewUserTextMessage("[message from the user during this turn] use the v2 API"), InjectedSteer)
34+}
35+
36+func TestMarkInjected(t *testing.T) {
37+ m := ai.NewMessage(ai.RoleUser, map[string]any{"other": 1}, ai.NewTextPart("[mm: note]"))
38+ if IsInjected(m) {
39+ t.Error("an unmarked message must not be injected")
40+ }
41+ if MarkInjected(m, InjectedNotice) != m || !IsInjected(m) {
42+ t.Error("MarkInjected must mark the message it returns")
43+ }
44+ if m.Metadata["other"] != 1 {
45+ t.Error("MarkInjected must keep the other metadata")
46+ }
47+ if IsInjected(MarkInjected(ai.NewModelTextMessage("x"), InjectedNotice)) {
48+ t.Error("only a user message can be injected in the user's role")
49+ }
50+ if IsInjected(nil) {
51+ t.Error("nil is not injected")
52+ }
53+}
54+
55+// The mark must survive what a saved session does to it: a JSON round trip.
56+func TestInjectedMarkSurvivesJSON(t *testing.T) {
57+ b, err := json.Marshal(steer())
58+ if err != nil {
59+ t.Fatal(err)
60+ }
61+ var back ai.Message
62+ if err := json.Unmarshal(b, &back); err != nil {
63+ t.Fatal(err)
64+ }
65+ if !IsInjected(&back) {
66+ t.Errorf("mark lost in JSON: %s", b)
67+ }
68+}
69+
70+// Ticket 289: three real questions, a notice in the first, a steered
71+// message in the second, are three turns — not five.
72+func TestSplitKeepsInjectedMessagesInTheirTurn(t *testing.T) {
73+ q1, q2, q3 := turnWith("q1", notice(), "x"), turnWith("q2", steer(), "x"), turn("q3", 1, "x")
74+ _, turns := Split(history(q1, q2, q3))
75+ if len(turns) != 3 {
76+ t.Fatalf("turns = %d, want 3", len(turns))
77+ }
78+ for i, want := range []int{len(q1), len(q2), len(q3)} {
79+ if len(turns[i]) != want {
80+ t.Errorf("turn %d has %d messages, want %d", i+1, len(turns[i]), want)
81+ }
82+ }
83+}
84+
85+// Messages saved before the mark existed are split as they always were.
86+func TestSplitUnmarkedNoticeStillStartsATurn(t *testing.T) {
87+ legacy := ai.NewUserTextMessage("[mm: your last tool call was not run]")
88+ _, turns := Split(history(turnWith("q1", legacy, "x")))
89+ if len(turns) != 2 {
90+ t.Fatalf("turns = %d, want 2 (unmarked: handled as before)", len(turns))
91+ }
92+}
93+
94+// The case of the observed session: an earlier summary, then three real
95+// questions with injected messages. keepLastTurns 3 must compress the
96+// oldest real question (merged with the summary), not find nothing to do.
97+func TestCompactWithInjectedMessagesCompressesTheOldestQuestion(t *testing.T) {
98+ big := strings.Repeat("line of tool output\n", 60)
99+ pair := SummaryPair("old notes", 12, 3, 5)
100+ q1, q2, q3, q4 := turnWith("q1", notice(), big), turnWith("q2", steer(), big), turn("q3", 1, big), turn("q4", 0, "")
101+ msgs := history(pair, q1, q2, q3, q4)
102+ summarize, seen := fixed("merged notes")
103+
104+ res, err := Compact(context.Background(), msgs, cfg(3), summarize)
105+ if err != nil {
106+ t.Fatalf("Compact: %v", err)
107+ }
108+ if res.Compressed != len(pair)+len(q1) {
109+ t.Errorf("compressed %d messages, want %d (summary pair + q1)", res.Compressed, len(pair)+len(q1))
110+ }
111+ if res.Kept != len(q2)+len(q3)+len(q4) {
112+ t.Errorf("kept %d messages, want %d", res.Kept, len(q2)+len(q3)+len(q4))
113+ }
114+ if !strings.Contains((*seen)[len(*seen)-1].Text(), "earlier summary") {
115+ t.Error("the earlier summary must be merged")
116+ }
117+ if err := Valid(res.Messages); err != nil {
118+ t.Errorf("compressed history invalid: %v", err)
119+ }
120+}
121+
122+// Inside a turn, a steered message is not the turn's question: the notes of
123+// an in-turn compression go to the question the user asked.
124+func TestTurnBoundsSkipsInjectedMessages(t *testing.T) {
125+ msgs := longTurn(3)
126+ question := len(msgs) - 7
127+ msgs = append(msgs, steer())
128+ msgs = append(msgs, longTurn(3)[4:]...)
129+ q, _ := turnBounds(msgs)
130+ if q != question {
131+ t.Fatalf("question at %d (%q), want %d", q, msgs[q].Text(), question)
132+ }
133+
134+ res, err := CompactTurn(context.Background(), msgs, budget(Estimate(msgs), Calibration{}), nil)
135+ if err != nil {
136+ t.Fatalf("CompactTurn: %v", err)
137+ }
138+ if res.Messages[q].Text() != "build the game" {
139+ t.Errorf("the question moved: %q", res.Messages[q].Text())
140+ }
141+ if err := Valid(res.Messages); err != nil {
142+ t.Errorf("history invalid: %v", err)
143+ }
144+}
new file mode 100644
@@ -0,0 +1,144 @@
1+package compact
2+
3+import (
4+ "context"
5+ "encoding/json"
6+ "strings"
7+ "testing"
8+
9+ "github.com/firebase/genkit/go/ai"
10+)
11+
12+// turnWith is a question turn with a message mm injected between its two
13+// tool exchanges — the shape of a cut tool call's notice, or of a message
14+// the user steered into the running turn.
15+func turnWith(question string, injected *ai.Message, output string) []*ai.Message {
16+ a, b := question+"-a", question+"-b"
17+ return []*ai.Message{
18+ ai.NewUserTextMessage(question),
19+ ai.NewModelMessage(req(a, "echo "+a)),
20+ ai.NewMessage(ai.RoleTool, nil, resp(a, output)),
21+ injected,
22+ ai.NewModelMessage(req(b, "echo "+b)),
23+ ai.NewMessage(ai.RoleTool, nil, resp(b, output)),
24+ ai.NewModelMessage(ai.NewTextPart("done " + question)),
25+ }
26+}
27+
28+func notice() *ai.Message {
29+ return MarkInjected(ai.NewUserTextMessage("[mm: your last tool call was not run: it was cut off before its end]"), InjectedNotice)
30+}
31+
32+func steer() *ai.Message {
33+ return MarkInjected(ai.NewUserTextMessage("[message from the user during this turn] use the v2 API"), InjectedSteer)
34+}
35+
36+func TestMarkInjected(t *testing.T) {
37+ m := ai.NewMessage(ai.RoleUser, map[string]any{"other": 1}, ai.NewTextPart("[mm: note]"))
38+ if IsInjected(m) {
39+ t.Error("an unmarked message must not be injected")
40+ }
41+ if MarkInjected(m, InjectedNotice) != m || !IsInjected(m) {
42+ t.Error("MarkInjected must mark the message it returns")
43+ }
44+ if m.Metadata["other"] != 1 {
45+ t.Error("MarkInjected must keep the other metadata")
46+ }
47+ if IsInjected(MarkInjected(ai.NewModelTextMessage("x"), InjectedNotice)) {
48+ t.Error("only a user message can be injected in the user's role")
49+ }
50+ if IsInjected(nil) {
51+ t.Error("nil is not injected")
52+ }
53+}
54+
55+// The mark must survive what a saved session does to it: a JSON round trip.
56+func TestInjectedMarkSurvivesJSON(t *testing.T) {
57+ b, err := json.Marshal(steer())
58+ if err != nil {
59+ t.Fatal(err)
60+ }
61+ var back ai.Message
62+ if err := json.Unmarshal(b, &back); err != nil {
63+ t.Fatal(err)
64+ }
65+ if !IsInjected(&back) {
66+ t.Errorf("mark lost in JSON: %s", b)
67+ }
68+}
69+
70+// Ticket 289: three real questions, a notice in the first, a steered
71+// message in the second, are three turns — not five.
72+func TestSplitKeepsInjectedMessagesInTheirTurn(t *testing.T) {
73+ q1, q2, q3 := turnWith("q1", notice(), "x"), turnWith("q2", steer(), "x"), turn("q3", 1, "x")
74+ _, turns := Split(history(q1, q2, q3))
75+ if len(turns) != 3 {
76+ t.Fatalf("turns = %d, want 3", len(turns))
77+ }
78+ for i, want := range []int{len(q1), len(q2), len(q3)} {
79+ if len(turns[i]) != want {
80+ t.Errorf("turn %d has %d messages, want %d", i+1, len(turns[i]), want)
81+ }
82+ }
83+}
84+
85+// Messages saved before the mark existed are split as they always were.
86+func TestSplitUnmarkedNoticeStillStartsATurn(t *testing.T) {
87+ legacy := ai.NewUserTextMessage("[mm: your last tool call was not run]")
88+ _, turns := Split(history(turnWith("q1", legacy, "x")))
89+ if len(turns) != 2 {
90+ t.Fatalf("turns = %d, want 2 (unmarked: handled as before)", len(turns))
91+ }
92+}
93+
94+// The case of the observed session: an earlier summary, then three real
95+// questions with injected messages. keepLastTurns 3 must compress the
96+// oldest real question (merged with the summary), not find nothing to do.
97+func TestCompactWithInjectedMessagesCompressesTheOldestQuestion(t *testing.T) {
98+ big := strings.Repeat("line of tool output\n", 60)
99+ pair := SummaryPair("old notes", 12, 3, 5)
100+ q1, q2, q3, q4 := turnWith("q1", notice(), big), turnWith("q2", steer(), big), turn("q3", 1, big), turn("q4", 0, "")
101+ msgs := history(pair, q1, q2, q3, q4)
102+ summarize, seen := fixed("merged notes")
103+
104+ res, err := Compact(context.Background(), msgs, cfg(3), summarize)
105+ if err != nil {
106+ t.Fatalf("Compact: %v", err)
107+ }
108+ if res.Compressed != len(pair)+len(q1) {
109+ t.Errorf("compressed %d messages, want %d (summary pair + q1)", res.Compressed, len(pair)+len(q1))
110+ }
111+ if res.Kept != len(q2)+len(q3)+len(q4) {
112+ t.Errorf("kept %d messages, want %d", res.Kept, len(q2)+len(q3)+len(q4))
113+ }
114+ if !strings.Contains((*seen)[len(*seen)-1].Text(), "earlier summary") {
115+ t.Error("the earlier summary must be merged")
116+ }
117+ if err := Valid(res.Messages); err != nil {
118+ t.Errorf("compressed history invalid: %v", err)
119+ }
120+}
121+
122+// Inside a turn, a steered message is not the turn's question: the notes of
123+// an in-turn compression go to the question the user asked.
124+func TestTurnBoundsSkipsInjectedMessages(t *testing.T) {
125+ msgs := longTurn(3)
126+ question := len(msgs) - 7
127+ msgs = append(msgs, steer())
128+ msgs = append(msgs, longTurn(3)[4:]...)
129+ q, _ := turnBounds(msgs)
130+ if q != question {
131+ t.Fatalf("question at %d (%q), want %d", q, msgs[q].Text(), question)
132+ }
133+
134+ res, err := CompactTurn(context.Background(), msgs, budget(Estimate(msgs), Calibration{}), nil)
135+ if err != nil {
136+ t.Fatalf("CompactTurn: %v", err)
137+ }
138+ if res.Messages[q].Text() != "build the game" {
139+ t.Errorf("the question moved: %q", res.Messages[q].Text())
140+ }
141+ if err := Valid(res.Messages); err != nil {
142+ t.Errorf("history invalid: %v", err)
143+ }
144+}
modified internal/compact/inturn.go +90 -26
@@ -32,13 +32,34 @@ import (
3232 // model writes about them, appended to the turn's question — a user
3333 // message, so the user/assistant alternation chat templates expect holds.
3434 //
35-// The question, the last KeepToolCalls exchanges and everything before the
35+// The trigger is the threshold; the aim is lower (Budget.target, ticket
36+// 290): once it fires, the compression shrinks the older exchanges,
37+// summarises, and as a last resort shrinks the kept exchanges too (but the
38+// last one), until the history is under the TARGET, so the
39+// next calls find the same prompt and the server's cache. Compressing just
40+// under the threshold made the next read pass it again: measured on the
41+// Inkling demo, 18 calls of 41 without cache, 29.5 of 34.5 minutes spent
42+// re-reading the prompt.
43+//
44+// The question, the last exchange and everything before the
3645 // turn are never touched; a tool call is never split from its result
3746 // (Valid). On any failure the history is left as it was.
47+//
48+// The floor (ticket 289): what no summary of the turn can ever make smaller —
49+// everything before the turn, and its question. (The kept exchanges are not
50+// part of it: they move on as the turn goes, and a later summary takes the
51+// ones that aged.) When the floor alone passes the threshold, no summary can
52+// bring the history back under it, and one
53+// summary per model call only makes the model lose, then read again, its
54+// oldest results — observed: 3.5 hours, ~30 identical read cycles. So with
55+// the floor above the threshold the turn is summarised ONCE (its question
56+// then carries the notes), the report says why it will not be again, and
57+// later calls only shrink.
3858
3959 // KeepToolCalls is the number of tool exchanges (a model message with its
4060 // calls, then their results) left raw at the end of the turn: the work the
41-// model is doing right now.
61+// model is doing right now. A summary keeps fewer when these alone pass the
62+// threshold (summaryCut).
4263 const KeepToolCalls = 4
4364
4465 // shrinkOver is the length past which a tool result or a call argument is
@@ -46,14 +67,15 @@ const KeepToolCalls = 4
4667 const shrinkOver = 400
4768
4869 // InTurnDecide says whether the turn must be made smaller before the next
49-// call: the larger of the measure and the estimate passes the threshold of
50-// a known window. It does not read context.enabled: a turn that grows past
51-// the window fails whatever the between-questions setting says.
52-func InTurnDecide(msgs []*ai.Message, measured, window int, cfg config.ContextConfig) bool {
70+// call: the larger of the last measure and the calibrated estimate of msgs
71+// (Calibration) passes the threshold of a known window. It does not read
72+// context.enabled: a turn that grows past the window fails whatever the
73+// between-questions setting says.
74+func InTurnDecide(msgs []*ai.Message, measured, window int, cal Calibration, cfg config.ContextConfig) bool {
5375 if !cfg.CompressInTurn || window <= 0 || cfg.Threshold <= 0 {
5476 return false
5577 }
56- return max(Estimate(msgs), measured)*100 >= window*cfg.Threshold
78+ return Budget{Window: window, Threshold: cfg.Threshold}.over(max(cal.Tokens(msgs), measured))
5779 }
5880
5981 // InTurnResult is what CompactTurn did, for the one-line report.
@@ -61,14 +83,20 @@ type InTurnResult struct {
6183 Messages []*ai.Message
6284 Shrunk int // tool results and arguments shrunk
6385 Summarised int // messages replaced by the notes (0 = no summary)
64- Before int // estimated tokens before
65- After int
66- Elapsed time.Duration
86+ // FloorTooHigh: the history before the turn, with its question, is
87+ // above the threshold by itself, so no further summary is made in this
88+ // turn.
89+ FloorTooHigh bool
90+ Before int // calibrated tokens before (Calibration.Tokens)
91+ After int
92+ Elapsed time.Duration
6793 }
6894
6995 // Report is the 🗜️ line:
7096 //
7197 // in-turn: shrank 12 tool call(s) and result(s), summarised 20 message(s) (61.2k → 18.4k tokens, 4.1s)
98+//
99+// followed, when FloorTooHigh, by why no further summary will be made.
72100 func (r InTurnResult) Report() string {
73101 var parts []string
74102 if r.Shrunk > 0 {
@@ -77,17 +105,27 @@ func (r InTurnResult) Report() string {
77105 if r.Summarised > 0 {
78106 parts = append(parts, fmt.Sprintf("summarised %d message(s)", r.Summarised))
79107 }
80- return fmt.Sprintf("in-turn: %s (%s → %s tokens, %s)", strings.Join(parts, ", "),
108+ line := fmt.Sprintf("in-turn: %s (%s → %s tokens, %s)", strings.Join(parts, ", "),
81109 Kilo(r.Before), Kilo(r.After), seconds(r.Elapsed))
110+ if r.FloorTooHigh {
111+ line += floorNote
112+ }
113+ return line
82114 }
83115
116+// floorNote ends the report of a compression whose floor passes the
117+// threshold: the user can act on it, the model cannot.
118+const floorNote = " — the history before this turn is above the threshold by itself: no more summaries in this turn (lower context.keepLastTurns, or /compact or /new between questions)"
119+
84120 // CompactTurn makes the current turn of msgs smaller: shrink first, then,
85-// when the estimate still passes the threshold (window > 0), summarise. It
121+// when the calibrated estimate (b.Calibration — the zero value is the plain
122+// estimate) still passes b's threshold (b.Window > 0), summarise —
123+// only once per turn when the floor passes the threshold too. It
86124 // returns ErrNothingToCompact when the turn has no exchange older than the
87125 // kept ones. msgs itself is never modified.
88-func CompactTurn(ctx context.Context, msgs []*ai.Message, window int, cfg config.ContextConfig, summarize Summarizer) (InTurnResult, error) {
126+func CompactTurn(ctx context.Context, msgs []*ai.Message, b Budget, summarize Summarizer) (InTurnResult, error) {
89127 start := time.Now()
90- r := InTurnResult{Before: Estimate(msgs)}
128+ r := InTurnResult{Before: b.Tokens(msgs)}
91129 q, cut := turnBounds(msgs)
92130 if q < 0 || cut <= q+1 {
93131 return InTurnResult{}, ErrNothingToCompact
@@ -101,8 +139,13 @@ func CompactTurn(ctx context.Context, msgs []*ai.Message, window int, cfg config
101139 }
102140 }
103141
104- if window > 0 && Estimate(out)*100 >= window*cfg.Threshold && summarize != nil {
105- older := out[q+1 : cut]
142+ floor := b.above(out[:q+1])
143+ // Already summarised in this turn (the question carries the notes) and
144+ // the floor is too high: another summary cannot reach the threshold.
145+ again := floor && out[q].Metadata[metaKey] == "in-turn"
146+ if b.aboveTarget(out) && summarize != nil && !again {
147+ keep := summaryCut(out, q, cut, b)
148+ older := out[q+1 : keep]
106149 // The question first: the note-taker knows the task, and the request
107150 // opens with a user message, as chat templates expect.
108151 prompt := turnPrompt
@@ -112,30 +155,34 @@ func CompactTurn(ctx context.Context, msgs []*ai.Message, window int, cfg config
112155 notes, err := summarize(ctx, Request(append([]*ai.Message{out[q]}, older...), prompt, false))
113156 if err == nil && strings.TrimSpace(notes) != "" {
114157 question := withNotes(out[q], notes, len(older))
115- summed := append(append(append([]*ai.Message{}, out[:q]...), question), out[cut:]...)
158+ summed := append(append(append([]*ai.Message{}, out[:q]...), question), out[keep:]...)
116159 if Valid(summed) == nil {
117- out, r.Summarised = summed, len(older)
160+ out, r.Summarised, r.FloorTooHigh = summed, len(older), floor
161+ cut = q + 1 // the kept exchanges now follow the question
118162 }
119163 }
120164 }
165+ // Last resort, when the summary was not enough, not possible or not
166+ // allowed: the kept exchanges lose their bulk too, but the last one.
167+ r.Shrunk += shrinkTail(out, cut, b)
121168 if r.Shrunk == 0 && r.Summarised == 0 {
122169 return InTurnResult{}, ErrNothingToCompact
123170 }
124171 if err := Valid(out); err != nil {
125172 return InTurnResult{}, fmt.Errorf("in-turn compression broke the history: %w", err)
126173 }
127- r.Messages, r.After, r.Elapsed = out, Estimate(out), time.Since(start)
174+ r.Messages, r.After, r.Elapsed = out, b.Tokens(out), time.Since(start)
128175 return r, nil
129176 }
130177
131178 // turnBounds finds the current turn's question (the last user message that
132-// is not tool results) and the start of its kept tail: the model message of
179+// is neither tool results nor a message mm injected — IsInjected) and the start of its kept tail: the model message of
133180 // the KeepToolCalls-th last exchange. q is -1 when there is no question;
134181 // cut <= q+1 when nothing is older than the tail.
135182 func turnBounds(msgs []*ai.Message) (q, cut int) {
136183 q = -1
137184 for i := len(msgs) - 1; i >= 0; i-- {
138- if msgs[i].Role == ai.RoleUser && !hasToolResponse(msgs[i]) {
185+ if msgs[i].Role == ai.RoleUser && !hasToolResponse(msgs[i]) && !IsInjected(msgs[i]) {
139186 q = i
140187 break
141188 }
@@ -179,23 +226,40 @@ func hasToolResponse(m *ai.Message) bool {
179226 }
180227
181228 // turnPrompt asks for notes on the turn's older exchanges.
229+//
230+// It keeps the declarations of the files read (ticket 292): a front end
231+// written against a back end needs its routes and JSON fields, and notes
232+// without them sent the model back to read the files again, and again. And
233+// it opens with the next change, not with what is left to read: observed,
234+// notes ending "Remaining: read full type definitions … must read before
235+// editing" were followed to the letter, until maxTurns. First, not last:
236+// five summaries of six were cut at summaryMaxTokens, and a last line
237+// asked for never got written.
182238 const turnPrompt = `Everything above, after the system message, is the first part of the work
183239 an agent did on ONE task, through tool calls. Write notes the same agent will
184240 use to continue that task without this part, in English, as short bullet
185-points: the files read, created or changed (exact paths, what changed), the
241+points. Start with ONE line: "Next change: " then the file to write or
242+edit and what goes in it — not more reading: the agent will continue from
243+these notes alone. Then: the files read, created or changed (exact paths, what changed), the
186244 commands run and the results that still matter (failing tests, exact errors),
187-the decisions taken, and what remained to do at that point. Do not quote file
188-contents. Do not invent anything. At most 25 lines.`
245+the decisions taken. For the files
246+read, keep what the next steps need to use them without reading them again:
247+function signatures, HTTP routes (method, path, handler), types with their
248+fields and JSON names. Do not copy function bodies. Do not invent anything.
249+At most 30 short lines.`
189250
190251 // turnMergeLine is added when the question already carries notes of an
191252 // earlier compression of the same turn.
192253 const turnMergeLine = "\n\nThe question above already ends with notes on an earlier part of the work: merge them into your notes, do not repeat them as-is."
193254
194255 // withNotes is the turn's question with the notes on its older exchanges
195-// appended: still the user's message, so the next message (the model's
256+// appended. Their wrapper used to say "re-read a file or re-run a command
257+// before relying on it" — a sound caution between two questions (a file
258+// may have changed), but inside the turn an order to read everything again
259+// (ticket 292). It now points at the next change: still the user's message, so the next message (the model's
196260 // kept tool call) keeps the alternation.
197261 func withNotes(question *ai.Message, notes string, n int) *ai.Message {
198- text := fmt.Sprintf("[mm: progress on this task so far — %d earlier message(s) of this turn were compressed into the notes below. Treat them as notes, not as observations: re-read a file or re-run a command before relying on it.]\n\n%s",
262+ text := fmt.Sprintf("[mm: progress on this task so far — %d earlier message(s) of this turn were compressed into the notes below. They are what you need to continue: do not read everything again — re-read only the exact lines the next change needs, then make that change.]\n\n%s",
199263 n, strings.TrimSpace(notes))
200264 // The question's own parts (text, an image…) stay as they were; notes
201265 // of an earlier compression — its last part — are replaced, the new
@@ -32,13 +32,34 @@ import (
32 // model writes about them, appended to the turn's question — a user32 // model writes about them, appended to the turn's question — a user
33 // message, so the user/assistant alternation chat templates expect holds.33 // message, so the user/assistant alternation chat templates expect holds.
34 //34 //
35-// The question, the last KeepToolCalls exchanges and everything before the35+// The trigger is the threshold; the aim is lower (Budget.target, ticket
36+// 290): once it fires, the compression shrinks the older exchanges,
37+// summarises, and as a last resort shrinks the kept exchanges too (but the
38+// last one), until the history is under the TARGET, so the
39+// next calls find the same prompt and the server's cache. Compressing just
40+// under the threshold made the next read pass it again: measured on the
41+// Inkling demo, 18 calls of 41 without cache, 29.5 of 34.5 minutes spent
42+// re-reading the prompt.
43+//
44+// The question, the last exchange and everything before the
36 // turn are never touched; a tool call is never split from its result45 // turn are never touched; a tool call is never split from its result
37 // (Valid). On any failure the history is left as it was.46 // (Valid). On any failure the history is left as it was.
47+//
48+// The floor (ticket 289): what no summary of the turn can ever make smaller —
49+// everything before the turn, and its question. (The kept exchanges are not
50+// part of it: they move on as the turn goes, and a later summary takes the
51+// ones that aged.) When the floor alone passes the threshold, no summary can
52+// bring the history back under it, and one
53+// summary per model call only makes the model lose, then read again, its
54+// oldest results — observed: 3.5 hours, ~30 identical read cycles. So with
55+// the floor above the threshold the turn is summarised ONCE (its question
56+// then carries the notes), the report says why it will not be again, and
57+// later calls only shrink.
38 58
39 // KeepToolCalls is the number of tool exchanges (a model message with its59 // KeepToolCalls is the number of tool exchanges (a model message with its
40 // calls, then their results) left raw at the end of the turn: the work the60 // calls, then their results) left raw at the end of the turn: the work the
41-// model is doing right now.61+// model is doing right now. A summary keeps fewer when these alone pass the
62+// threshold (summaryCut).
42 const KeepToolCalls = 463 const KeepToolCalls = 4
43 64
44 // shrinkOver is the length past which a tool result or a call argument is65 // shrinkOver is the length past which a tool result or a call argument is
@@ -46,14 +67,15 @@ const KeepToolCalls = 4
46 const shrinkOver = 40067 const shrinkOver = 400
47 68
48 // InTurnDecide says whether the turn must be made smaller before the next69 // InTurnDecide says whether the turn must be made smaller before the next
49-// call: the larger of the measure and the estimate passes the threshold of70+// call: the larger of the last measure and the calibrated estimate of msgs
50-// a known window. It does not read context.enabled: a turn that grows past71+// (Calibration) passes the threshold of a known window. It does not read
51-// the window fails whatever the between-questions setting says.72+// context.enabled: a turn that grows past the window fails whatever the
52-func InTurnDecide(msgs []*ai.Message, measured, window int, cfg config.ContextConfig) bool {73+// between-questions setting says.
74+func InTurnDecide(msgs []*ai.Message, measured, window int, cal Calibration, cfg config.ContextConfig) bool {
53 if !cfg.CompressInTurn || window <= 0 || cfg.Threshold <= 0 {75 if !cfg.CompressInTurn || window <= 0 || cfg.Threshold <= 0 {
54 return false76 return false
55 }77 }
56- return max(Estimate(msgs), measured)*100 >= window*cfg.Threshold78+ return Budget{Window: window, Threshold: cfg.Threshold}.over(max(cal.Tokens(msgs), measured))
57 }79 }
58 80
59 // InTurnResult is what CompactTurn did, for the one-line report.81 // InTurnResult is what CompactTurn did, for the one-line report.
@@ -61,14 +83,20 @@ type InTurnResult struct {
61 Messages []*ai.Message83 Messages []*ai.Message
62 Shrunk int // tool results and arguments shrunk84 Shrunk int // tool results and arguments shrunk
63 Summarised int // messages replaced by the notes (0 = no summary)85 Summarised int // messages replaced by the notes (0 = no summary)
64- Before int // estimated tokens before86+ // FloorTooHigh: the history before the turn, with its question, is
65- After int87+ // above the threshold by itself, so no further summary is made in this
66- Elapsed time.Duration88+ // turn.
89+ FloorTooHigh bool
90+ Before int // calibrated tokens before (Calibration.Tokens)
91+ After int
92+ Elapsed time.Duration
67 }93 }
68 94
69 // Report is the 🗜️ line:95 // Report is the 🗜️ line:
70 //96 //
71 // in-turn: shrank 12 tool call(s) and result(s), summarised 20 message(s) (61.2k → 18.4k tokens, 4.1s)97 // in-turn: shrank 12 tool call(s) and result(s), summarised 20 message(s) (61.2k → 18.4k tokens, 4.1s)
98+//
99+// followed, when FloorTooHigh, by why no further summary will be made.
72 func (r InTurnResult) Report() string {100 func (r InTurnResult) Report() string {
73 var parts []string101 var parts []string
74 if r.Shrunk > 0 {102 if r.Shrunk > 0 {
@@ -77,17 +105,27 @@ func (r InTurnResult) Report() string {
77 if r.Summarised > 0 {105 if r.Summarised > 0 {
78 parts = append(parts, fmt.Sprintf("summarised %d message(s)", r.Summarised))106 parts = append(parts, fmt.Sprintf("summarised %d message(s)", r.Summarised))
79 }107 }
80- return fmt.Sprintf("in-turn: %s (%s → %s tokens, %s)", strings.Join(parts, ", "),108+ line := fmt.Sprintf("in-turn: %s (%s → %s tokens, %s)", strings.Join(parts, ", "),
81 Kilo(r.Before), Kilo(r.After), seconds(r.Elapsed))109 Kilo(r.Before), Kilo(r.After), seconds(r.Elapsed))
110+ if r.FloorTooHigh {
111+ line += floorNote
112+ }
113+ return line
82 }114 }
83 115
116+// floorNote ends the report of a compression whose floor passes the
117+// threshold: the user can act on it, the model cannot.
118+const floorNote = " — the history before this turn is above the threshold by itself: no more summaries in this turn (lower context.keepLastTurns, or /compact or /new between questions)"
119+
84 // CompactTurn makes the current turn of msgs smaller: shrink first, then,120 // CompactTurn makes the current turn of msgs smaller: shrink first, then,
85-// when the estimate still passes the threshold (window > 0), summarise. It121+// when the calibrated estimate (b.Calibration — the zero value is the plain
122+// estimate) still passes b's threshold (b.Window > 0), summarise —
123+// only once per turn when the floor passes the threshold too. It
86 // returns ErrNothingToCompact when the turn has no exchange older than the124 // returns ErrNothingToCompact when the turn has no exchange older than the
87 // kept ones. msgs itself is never modified.125 // kept ones. msgs itself is never modified.
88-func CompactTurn(ctx context.Context, msgs []*ai.Message, window int, cfg config.ContextConfig, summarize Summarizer) (InTurnResult, error) {126+func CompactTurn(ctx context.Context, msgs []*ai.Message, b Budget, summarize Summarizer) (InTurnResult, error) {
89 start := time.Now()127 start := time.Now()
90- r := InTurnResult{Before: Estimate(msgs)}128+ r := InTurnResult{Before: b.Tokens(msgs)}
91 q, cut := turnBounds(msgs)129 q, cut := turnBounds(msgs)
92 if q < 0 || cut <= q+1 {130 if q < 0 || cut <= q+1 {
93 return InTurnResult{}, ErrNothingToCompact131 return InTurnResult{}, ErrNothingToCompact
@@ -101,8 +139,13 @@ func CompactTurn(ctx context.Context, msgs []*ai.Message, window int, cfg config
101 }139 }
102 }140 }
103 141
104- if window > 0 && Estimate(out)*100 >= window*cfg.Threshold && summarize != nil {142+ floor := b.above(out[:q+1])
105- older := out[q+1 : cut]143+ // Already summarised in this turn (the question carries the notes) and
144+ // the floor is too high: another summary cannot reach the threshold.
145+ again := floor && out[q].Metadata[metaKey] == "in-turn"
146+ if b.aboveTarget(out) && summarize != nil && !again {
147+ keep := summaryCut(out, q, cut, b)
148+ older := out[q+1 : keep]
106 // The question first: the note-taker knows the task, and the request149 // The question first: the note-taker knows the task, and the request
107 // opens with a user message, as chat templates expect.150 // opens with a user message, as chat templates expect.
108 prompt := turnPrompt151 prompt := turnPrompt
@@ -112,30 +155,34 @@ func CompactTurn(ctx context.Context, msgs []*ai.Message, window int, cfg config
112 notes, err := summarize(ctx, Request(append([]*ai.Message{out[q]}, older...), prompt, false))155 notes, err := summarize(ctx, Request(append([]*ai.Message{out[q]}, older...), prompt, false))
113 if err == nil && strings.TrimSpace(notes) != "" {156 if err == nil && strings.TrimSpace(notes) != "" {
114 question := withNotes(out[q], notes, len(older))157 question := withNotes(out[q], notes, len(older))
115- summed := append(append(append([]*ai.Message{}, out[:q]...), question), out[cut:]...)158+ summed := append(append(append([]*ai.Message{}, out[:q]...), question), out[keep:]...)
116 if Valid(summed) == nil {159 if Valid(summed) == nil {
117- out, r.Summarised = summed, len(older)160+ out, r.Summarised, r.FloorTooHigh = summed, len(older), floor
161+ cut = q + 1 // the kept exchanges now follow the question
118 }162 }
119 }163 }
120 }164 }
165+ // Last resort, when the summary was not enough, not possible or not
166+ // allowed: the kept exchanges lose their bulk too, but the last one.
167+ r.Shrunk += shrinkTail(out, cut, b)
121 if r.Shrunk == 0 && r.Summarised == 0 {168 if r.Shrunk == 0 && r.Summarised == 0 {
122 return InTurnResult{}, ErrNothingToCompact169 return InTurnResult{}, ErrNothingToCompact
123 }170 }
124 if err := Valid(out); err != nil {171 if err := Valid(out); err != nil {
125 return InTurnResult{}, fmt.Errorf("in-turn compression broke the history: %w", err)172 return InTurnResult{}, fmt.Errorf("in-turn compression broke the history: %w", err)
126 }173 }
127- r.Messages, r.After, r.Elapsed = out, Estimate(out), time.Since(start)174+ r.Messages, r.After, r.Elapsed = out, b.Tokens(out), time.Since(start)
128 return r, nil175 return r, nil
129 }176 }
130 177
131 // turnBounds finds the current turn's question (the last user message that178 // turnBounds finds the current turn's question (the last user message that
132-// is not tool results) and the start of its kept tail: the model message of179+// is neither tool results nor a message mm injected — IsInjected) and the start of its kept tail: the model message of
133 // the KeepToolCalls-th last exchange. q is -1 when there is no question;180 // the KeepToolCalls-th last exchange. q is -1 when there is no question;
134 // cut <= q+1 when nothing is older than the tail.181 // cut <= q+1 when nothing is older than the tail.
135 func turnBounds(msgs []*ai.Message) (q, cut int) {182 func turnBounds(msgs []*ai.Message) (q, cut int) {
136 q = -1183 q = -1
137 for i := len(msgs) - 1; i >= 0; i-- {184 for i := len(msgs) - 1; i >= 0; i-- {
138- if msgs[i].Role == ai.RoleUser && !hasToolResponse(msgs[i]) {185+ if msgs[i].Role == ai.RoleUser && !hasToolResponse(msgs[i]) && !IsInjected(msgs[i]) {
139 q = i186 q = i
140 break187 break
141 }188 }
@@ -179,23 +226,40 @@ func hasToolResponse(m *ai.Message) bool {
179 }226 }
180 227
181 // turnPrompt asks for notes on the turn's older exchanges.228 // turnPrompt asks for notes on the turn's older exchanges.
229+//
230+// It keeps the declarations of the files read (ticket 292): a front end
231+// written against a back end needs its routes and JSON fields, and notes
232+// without them sent the model back to read the files again, and again. And
233+// it opens with the next change, not with what is left to read: observed,
234+// notes ending "Remaining: read full type definitions … must read before
235+// editing" were followed to the letter, until maxTurns. First, not last:
236+// five summaries of six were cut at summaryMaxTokens, and a last line
237+// asked for never got written.
182 const turnPrompt = `Everything above, after the system message, is the first part of the work238 const turnPrompt = `Everything above, after the system message, is the first part of the work
183 an agent did on ONE task, through tool calls. Write notes the same agent will239 an agent did on ONE task, through tool calls. Write notes the same agent will
184 use to continue that task without this part, in English, as short bullet240 use to continue that task without this part, in English, as short bullet
185-points: the files read, created or changed (exact paths, what changed), the241+points. Start with ONE line: "Next change: " then the file to write or
242+edit and what goes in it — not more reading: the agent will continue from
243+these notes alone. Then: the files read, created or changed (exact paths, what changed), the
186 commands run and the results that still matter (failing tests, exact errors),244 commands run and the results that still matter (failing tests, exact errors),
187-the decisions taken, and what remained to do at that point. Do not quote file245+the decisions taken. For the files
188-contents. Do not invent anything. At most 25 lines.`246+read, keep what the next steps need to use them without reading them again:
247+function signatures, HTTP routes (method, path, handler), types with their
248+fields and JSON names. Do not copy function bodies. Do not invent anything.
249+At most 30 short lines.`
189 250
190 // turnMergeLine is added when the question already carries notes of an251 // turnMergeLine is added when the question already carries notes of an
191 // earlier compression of the same turn.252 // earlier compression of the same turn.
192 const turnMergeLine = "\n\nThe question above already ends with notes on an earlier part of the work: merge them into your notes, do not repeat them as-is."253 const turnMergeLine = "\n\nThe question above already ends with notes on an earlier part of the work: merge them into your notes, do not repeat them as-is."
193 254
194 // withNotes is the turn's question with the notes on its older exchanges255 // withNotes is the turn's question with the notes on its older exchanges
195-// appended: still the user's message, so the next message (the model's256+// appended. Their wrapper used to say "re-read a file or re-run a command
257+// before relying on it" — a sound caution between two questions (a file
258+// may have changed), but inside the turn an order to read everything again
259+// (ticket 292). It now points at the next change: still the user's message, so the next message (the model's
196 // kept tool call) keeps the alternation.260 // kept tool call) keeps the alternation.
197 func withNotes(question *ai.Message, notes string, n int) *ai.Message {261 func withNotes(question *ai.Message, notes string, n int) *ai.Message {
198- text := fmt.Sprintf("[mm: progress on this task so far — %d earlier message(s) of this turn were compressed into the notes below. Treat them as notes, not as observations: re-read a file or re-run a command before relying on it.]\n\n%s",262+ text := fmt.Sprintf("[mm: progress on this task so far — %d earlier message(s) of this turn were compressed into the notes below. They are what you need to continue: do not read everything again — re-read only the exact lines the next change needs, then make that change.]\n\n%s",
199 n, strings.TrimSpace(notes))263 n, strings.TrimSpace(notes))
200 // The question's own parts (text, an image…) stay as they were; notes264 // The question's own parts (text, an image…) stay as they were; notes
201 // of an earlier compression — its last part — are replaced, the new265 // of an earlier compression — its last part — are replaced, the new
modified internal/compact/inturn_test.go +113 -8
@@ -33,6 +33,11 @@ func longTurn(n int) []*ai.Message {
3333 return msgs
3434 }
3535
36+// budget is the Budget of inTurnCfg for a window and a calibration.
37+func budget(window int, cal Calibration) Budget {
38+ return Budget{Window: window, Threshold: inTurnCfg().Threshold, Calibration: cal}
39+}
40+
3641 func inTurnCfg() config.ContextConfig {
3742 return config.ContextConfig{CompressInTurn: true, Threshold: 75, SummaryMaxTokens: 512}
3843 }
@@ -41,17 +46,17 @@ func TestInTurnDecide(t *testing.T) {
4146 msgs := longTurn(8)
4247 tokens := Estimate(msgs)
4348 c := inTurnCfg()
44- if !InTurnDecide(msgs, 0, tokens, c) || InTurnDecide(msgs, 0, tokens*2, c) {
49+ if !InTurnDecide(msgs, 0, tokens, Calibration{}, c) || InTurnDecide(msgs, 0, tokens*2, Calibration{}, c) {
4550 t.Error("threshold: want compress at 100 %, not at 50 %")
4651 }
47- if !InTurnDecide(msgs, tokens*2, tokens*2, c) {
52+ if !InTurnDecide(msgs, tokens*2, tokens*2, Calibration{}, c) {
4853 t.Error("the server's measure, larger than the estimate, must count")
4954 }
50- if InTurnDecide(msgs, 0, 0, c) {
55+ if InTurnDecide(msgs, 0, 0, Calibration{}, c) {
5156 t.Error("unknown window: must not decide")
5257 }
5358 c.CompressInTurn = false
54- if InTurnDecide(msgs, 0, tokens, c) {
59+ if InTurnDecide(msgs, 0, tokens, Calibration{}, c) {
5560 t.Error("compressInTurn false: must not decide")
5661 }
5762 }
@@ -62,7 +67,7 @@ func TestCompactTurnShrinksOlderExchanges(t *testing.T) {
6267 msgs := longTurn(8)
6368 before := Estimate(msgs)
6469 called := false
65- r, err := CompactTurn(context.Background(), msgs, before*10, inTurnCfg(), func(context.Context, []*ai.Message) (string, error) {
70+ r, err := CompactTurn(context.Background(), msgs, budget(before*10, Calibration{}), func(context.Context, []*ai.Message) (string, error) {
6671 called = true
6772 return "notes", nil
6873 })
@@ -104,7 +109,7 @@ func TestCompactTurnShrinksOlderExchanges(t *testing.T) {
104109 func TestCompactTurnSummarisesWhenShrinkingIsNotEnough(t *testing.T) {
105110 msgs := longTurn(10)
106111 var asked []*ai.Message
107- r, err := CompactTurn(context.Background(), msgs, 100, inTurnCfg(), func(_ context.Context, req []*ai.Message) (string, error) {
112+ r, err := CompactTurn(context.Background(), msgs, budget(100, Calibration{}), func(_ context.Context, req []*ai.Message) (string, error) {
108113 asked = req
109114 return "- wrote f0.go … f5.go", nil
110115 })
@@ -135,13 +140,113 @@ func TestCompactTurnSummarisesWhenShrinkingIsNotEnough(t *testing.T) {
135140 // A failed summary keeps what shrinking did; a short turn has nothing older
136141 // than its kept tail.
137142 func TestCompactTurnFallbacks(t *testing.T) {
138- r, err := CompactTurn(context.Background(), longTurn(10), 100, inTurnCfg(), func(context.Context, []*ai.Message) (string, error) {
143+ r, err := CompactTurn(context.Background(), longTurn(10), budget(100, Calibration{}), func(context.Context, []*ai.Message) (string, error) {
139144 return "", errors.New("server down")
140145 })
141146 if err != nil || r.Summarised != 0 || r.Shrunk == 0 || Valid(r.Messages) != nil {
142147 t.Errorf("failed summary: %+v, %v — want the shrunk history", r, err)
143148 }
144- if _, err := CompactTurn(context.Background(), longTurn(KeepToolCalls), 100, inTurnCfg(), nil); !errors.Is(err, ErrNothingToCompact) {
149+ if _, err := CompactTurn(context.Background(), longTurn(KeepToolCalls), budget(100, Calibration{}), nil); !errors.Is(err, ErrNothingToCompact) {
145150 t.Errorf("short turn: %v, want ErrNothingToCompact", err)
146151 }
147152 }
153+
154+// exchanges is n more tool exchanges like longTurn's, refs prefixed so they
155+// never collide with earlier ones.
156+func exchanges(prefix string, n int) []*ai.Message {
157+ var out []*ai.Message
158+ for _, m := range longTurn(n)[4:] {
159+ c := *m
160+ c.Content = nil
161+ for _, p := range m.Content {
162+ switch {
163+ case p.IsToolRequest():
164+ r := *p.ToolRequest
165+ r.Ref = prefix + r.Ref
166+ c.Content = append(c.Content, ai.NewToolRequestPart(&r))
167+ case p.IsToolResponse():
168+ r := *p.ToolResponse
169+ r.Ref = prefix + r.Ref
170+ c.Content = append(c.Content, ai.NewToolResponsePart(&r))
171+ }
172+ }
173+ out = append(out, &c)
174+ }
175+ return out
176+}
177+
178+// floorOf is the estimate of what no summary of msgs' turn can make
179+// smaller: the history before the turn and its question.
180+func floorOf(msgs []*ai.Message) int {
181+ q, _ := turnBounds(msgs)
182+ return Estimate(msgs[:q+1])
183+}
184+
185+// counting is a Summarizer that counts its calls.
186+func counting(n *int) Summarizer {
187+ return func(context.Context, []*ai.Message) (string, error) {
188+ *n++
189+ return "- wrote some files", nil
190+ }
191+}
192+
193+// Ticket 289: the history before the turn alone passes the threshold. The
194+// turn is summarised once, the report says why it will not be again, and
195+// the next calls of the same turn ask for no summary.
196+func TestCompactTurnSummarisesOnceWhenTheFloorIsTooHigh(t *testing.T) {
197+ msgs := longTurn(10)
198+ msgs[2] = ai.NewModelTextMessage(strings.Repeat("a long earlier answer. ", 3000))
199+ window := floorOf(msgs) // the floor is at 100 % of the window
200+ asked := 0
201+
202+ r, err := CompactTurn(context.Background(), msgs, budget(window, Calibration{}), counting(&asked))
203+ if err != nil {
204+ t.Fatal(err)
205+ }
206+ if asked != 1 || !r.FloorTooHigh || !strings.Contains(r.Report(), "no more summaries in this turn") {
207+ t.Fatalf("first call: %d summary request(s), floorTooHigh %v, report %q", asked, r.FloorTooHigh, r.Report())
208+ }
209+ history := r.Messages
210+ for i := range 3 {
211+ history = append(history, exchanges(fmt.Sprintf("n%d-", i), 2)...)
212+ r, err = CompactTurn(context.Background(), history, budget(window, Calibration{}), counting(&asked))
213+ if err != nil {
214+ t.Fatalf("call %d: %v", i+2, err)
215+ }
216+ if r.FloorTooHigh || r.Summarised != 0 {
217+ t.Errorf("call %d summarised again: %+v", i+2, r)
218+ }
219+ if err := Valid(r.Messages); err != nil {
220+ t.Fatal(err)
221+ }
222+ history = r.Messages
223+ }
224+ if asked != 1 {
225+ t.Errorf("%d summary requests in the turn, want 1", asked)
226+ }
227+}
228+
229+// A floor under the threshold changes nothing: each time the turn grows
230+// past the threshold again, it is summarised again.
231+func TestCompactTurnSummarisesAgainWhenTheFloorIsLow(t *testing.T) {
232+ msgs := longTurn(10)
233+ // Large enough that the notes added to the question stay a small part.
234+ msgs[2] = ai.NewModelTextMessage(strings.Repeat("an earlier answer. ", 100))
235+ window := 2 * floorOf(msgs) // the floor is at 50 %, under 75 %
236+ asked := 0
237+
238+ r, err := CompactTurn(context.Background(), msgs, budget(window, Calibration{}), counting(&asked))
239+ if err != nil || asked != 1 || r.FloorTooHigh {
240+ t.Fatalf("first call: err %v, %d request(s), floorTooHigh %v", err, asked, r.FloorTooHigh)
241+ }
242+ if strings.Contains(r.Report(), "no more summaries") {
243+ t.Errorf("report %q", r.Report())
244+ }
245+ grown := append(r.Messages, exchanges("n-", 6)...)
246+ if r, err = CompactTurn(context.Background(), grown, budget(window, Calibration{}), counting(&asked)); err != nil || asked != 2 {
247+ t.Fatalf("second call: err %v, %d request(s), want 2", err, asked)
248+ }
249+ if err := Valid(r.Messages); err != nil {
250+ t.Fatal(err)
251+ }
252+}
@@ -33,6 +33,11 @@ func longTurn(n int) []*ai.Message {
33 return msgs33 return msgs
34 }34 }
35 35
36+// budget is the Budget of inTurnCfg for a window and a calibration.
37+func budget(window int, cal Calibration) Budget {
38+ return Budget{Window: window, Threshold: inTurnCfg().Threshold, Calibration: cal}
39+}
40+
36 func inTurnCfg() config.ContextConfig {41 func inTurnCfg() config.ContextConfig {
37 return config.ContextConfig{CompressInTurn: true, Threshold: 75, SummaryMaxTokens: 512}42 return config.ContextConfig{CompressInTurn: true, Threshold: 75, SummaryMaxTokens: 512}
38 }43 }
@@ -41,17 +46,17 @@ func TestInTurnDecide(t *testing.T) {
41 msgs := longTurn(8)46 msgs := longTurn(8)
42 tokens := Estimate(msgs)47 tokens := Estimate(msgs)
43 c := inTurnCfg()48 c := inTurnCfg()
44- if !InTurnDecide(msgs, 0, tokens, c) || InTurnDecide(msgs, 0, tokens*2, c) {49+ if !InTurnDecide(msgs, 0, tokens, Calibration{}, c) || InTurnDecide(msgs, 0, tokens*2, Calibration{}, c) {
45 t.Error("threshold: want compress at 100 %, not at 50 %")50 t.Error("threshold: want compress at 100 %, not at 50 %")
46 }51 }
47- if !InTurnDecide(msgs, tokens*2, tokens*2, c) {52+ if !InTurnDecide(msgs, tokens*2, tokens*2, Calibration{}, c) {
48 t.Error("the server's measure, larger than the estimate, must count")53 t.Error("the server's measure, larger than the estimate, must count")
49 }54 }
50- if InTurnDecide(msgs, 0, 0, c) {55+ if InTurnDecide(msgs, 0, 0, Calibration{}, c) {
51 t.Error("unknown window: must not decide")56 t.Error("unknown window: must not decide")
52 }57 }
53 c.CompressInTurn = false58 c.CompressInTurn = false
54- if InTurnDecide(msgs, 0, tokens, c) {59+ if InTurnDecide(msgs, 0, tokens, Calibration{}, c) {
55 t.Error("compressInTurn false: must not decide")60 t.Error("compressInTurn false: must not decide")
56 }61 }
57 }62 }
@@ -62,7 +67,7 @@ func TestCompactTurnShrinksOlderExchanges(t *testing.T) {
62 msgs := longTurn(8)67 msgs := longTurn(8)
63 before := Estimate(msgs)68 before := Estimate(msgs)
64 called := false69 called := false
65- r, err := CompactTurn(context.Background(), msgs, before*10, inTurnCfg(), func(context.Context, []*ai.Message) (string, error) {70+ r, err := CompactTurn(context.Background(), msgs, budget(before*10, Calibration{}), func(context.Context, []*ai.Message) (string, error) {
66 called = true71 called = true
67 return "notes", nil72 return "notes", nil
68 })73 })
@@ -104,7 +109,7 @@ func TestCompactTurnShrinksOlderExchanges(t *testing.T) {
104 func TestCompactTurnSummarisesWhenShrinkingIsNotEnough(t *testing.T) {109 func TestCompactTurnSummarisesWhenShrinkingIsNotEnough(t *testing.T) {
105 msgs := longTurn(10)110 msgs := longTurn(10)
106 var asked []*ai.Message111 var asked []*ai.Message
107- r, err := CompactTurn(context.Background(), msgs, 100, inTurnCfg(), func(_ context.Context, req []*ai.Message) (string, error) {112+ r, err := CompactTurn(context.Background(), msgs, budget(100, Calibration{}), func(_ context.Context, req []*ai.Message) (string, error) {
108 asked = req113 asked = req
109 return "- wrote f0.go … f5.go", nil114 return "- wrote f0.go … f5.go", nil
110 })115 })
@@ -135,13 +140,113 @@ func TestCompactTurnSummarisesWhenShrinkingIsNotEnough(t *testing.T) {
135 // A failed summary keeps what shrinking did; a short turn has nothing older140 // A failed summary keeps what shrinking did; a short turn has nothing older
136 // than its kept tail.141 // than its kept tail.
137 func TestCompactTurnFallbacks(t *testing.T) {142 func TestCompactTurnFallbacks(t *testing.T) {
138- r, err := CompactTurn(context.Background(), longTurn(10), 100, inTurnCfg(), func(context.Context, []*ai.Message) (string, error) {143+ r, err := CompactTurn(context.Background(), longTurn(10), budget(100, Calibration{}), func(context.Context, []*ai.Message) (string, error) {
139 return "", errors.New("server down")144 return "", errors.New("server down")
140 })145 })
141 if err != nil || r.Summarised != 0 || r.Shrunk == 0 || Valid(r.Messages) != nil {146 if err != nil || r.Summarised != 0 || r.Shrunk == 0 || Valid(r.Messages) != nil {
142 t.Errorf("failed summary: %+v, %v — want the shrunk history", r, err)147 t.Errorf("failed summary: %+v, %v — want the shrunk history", r, err)
143 }148 }
144- if _, err := CompactTurn(context.Background(), longTurn(KeepToolCalls), 100, inTurnCfg(), nil); !errors.Is(err, ErrNothingToCompact) {149+ if _, err := CompactTurn(context.Background(), longTurn(KeepToolCalls), budget(100, Calibration{}), nil); !errors.Is(err, ErrNothingToCompact) {
145 t.Errorf("short turn: %v, want ErrNothingToCompact", err)150 t.Errorf("short turn: %v, want ErrNothingToCompact", err)
146 }151 }
147 }152 }
153+
154+// exchanges is n more tool exchanges like longTurn's, refs prefixed so they
155+// never collide with earlier ones.
156+func exchanges(prefix string, n int) []*ai.Message {
157+ var out []*ai.Message
158+ for _, m := range longTurn(n)[4:] {
159+ c := *m
160+ c.Content = nil
161+ for _, p := range m.Content {
162+ switch {
163+ case p.IsToolRequest():
164+ r := *p.ToolRequest
165+ r.Ref = prefix + r.Ref
166+ c.Content = append(c.Content, ai.NewToolRequestPart(&r))
167+ case p.IsToolResponse():
168+ r := *p.ToolResponse
169+ r.Ref = prefix + r.Ref
170+ c.Content = append(c.Content, ai.NewToolResponsePart(&r))
171+ }
172+ }
173+ out = append(out, &c)
174+ }
175+ return out
176+}
177+
178+// floorOf is the estimate of what no summary of msgs' turn can make
179+// smaller: the history before the turn and its question.
180+func floorOf(msgs []*ai.Message) int {
181+ q, _ := turnBounds(msgs)
182+ return Estimate(msgs[:q+1])
183+}
184+
185+// counting is a Summarizer that counts its calls.
186+func counting(n *int) Summarizer {
187+ return func(context.Context, []*ai.Message) (string, error) {
188+ *n++
189+ return "- wrote some files", nil
190+ }
191+}
192+
193+// Ticket 289: the history before the turn alone passes the threshold. The
194+// turn is summarised once, the report says why it will not be again, and
195+// the next calls of the same turn ask for no summary.
196+func TestCompactTurnSummarisesOnceWhenTheFloorIsTooHigh(t *testing.T) {
197+ msgs := longTurn(10)
198+ msgs[2] = ai.NewModelTextMessage(strings.Repeat("a long earlier answer. ", 3000))
199+ window := floorOf(msgs) // the floor is at 100 % of the window
200+ asked := 0
201+
202+ r, err := CompactTurn(context.Background(), msgs, budget(window, Calibration{}), counting(&asked))
203+ if err != nil {
204+ t.Fatal(err)
205+ }
206+ if asked != 1 || !r.FloorTooHigh || !strings.Contains(r.Report(), "no more summaries in this turn") {
207+ t.Fatalf("first call: %d summary request(s), floorTooHigh %v, report %q", asked, r.FloorTooHigh, r.Report())
208+ }
209+ history := r.Messages
210+ for i := range 3 {
211+ history = append(history, exchanges(fmt.Sprintf("n%d-", i), 2)...)
212+ r, err = CompactTurn(context.Background(), history, budget(window, Calibration{}), counting(&asked))
213+ if err != nil {
214+ t.Fatalf("call %d: %v", i+2, err)
215+ }
216+ if r.FloorTooHigh || r.Summarised != 0 {
217+ t.Errorf("call %d summarised again: %+v", i+2, r)
218+ }
219+ if err := Valid(r.Messages); err != nil {
220+ t.Fatal(err)
221+ }
222+ history = r.Messages
223+ }
224+ if asked != 1 {
225+ t.Errorf("%d summary requests in the turn, want 1", asked)
226+ }
227+}
228+
229+// A floor under the threshold changes nothing: each time the turn grows
230+// past the threshold again, it is summarised again.
231+func TestCompactTurnSummarisesAgainWhenTheFloorIsLow(t *testing.T) {
232+ msgs := longTurn(10)
233+ // Large enough that the notes added to the question stay a small part.
234+ msgs[2] = ai.NewModelTextMessage(strings.Repeat("an earlier answer. ", 100))
235+ window := 2 * floorOf(msgs) // the floor is at 50 %, under 75 %
236+ asked := 0
237+
238+ r, err := CompactTurn(context.Background(), msgs, budget(window, Calibration{}), counting(&asked))
239+ if err != nil || asked != 1 || r.FloorTooHigh {
240+ t.Fatalf("first call: err %v, %d request(s), floorTooHigh %v", err, asked, r.FloorTooHigh)
241+ }
242+ if strings.Contains(r.Report(), "no more summaries") {
243+ t.Errorf("report %q", r.Report())
244+ }
245+ grown := append(r.Messages, exchanges("n-", 6)...)
246+ if r, err = CompactTurn(context.Background(), grown, budget(window, Calibration{}), counting(&asked)); err != nil || asked != 2 {
247+ t.Fatalf("second call: err %v, %d request(s), want 2", err, asked)
248+ }
249+ if err := Valid(r.Messages); err != nil {
250+ t.Fatal(err)
251+ }
252+}
added internal/compact/outline.go +94 -0
new file mode 100644
@@ -0,0 +1,94 @@
1+package compact
2+
3+import (
4+ "fmt"
5+ "regexp"
6+ "strings"
7+)
8+
9+// Outline of a shrunk code output (ticket 292).
10+//
11+// A shrunk tool result used to keep its first line only. For a source file
12+// that line is `package server`: everything the next steps need — the
13+// routes, the handlers, the types and their JSON fields — was gone, so the
14+// model read the file again, chunk by chunk, until the chunks it read first
15+// were shrunk in turn. Observed with Inkling-2-Mini on a 16k window: 40 tool
16+// calls, all reads, server.go read four times in the same ranges.
17+//
18+// So a long output that holds declarations keeps them: the model keeps the
19+// map of the code, not its bodies, and reads a body again only when it needs
20+// that body.
21+
22+// declaration matches a line worth keeping in an outline: functions, types,
23+// classes and their kin in the common languages, struct fields with a JSON
24+// tag, HTTP routes, and calls to an HTTP API from a front end.
25+var declaration = regexp.MustCompile(`^\s*(` +
26+ `func\s|type\s|` + // Go
27+ `(export\s+)?(default\s+)?(async\s+)?function\b|(export\s+)?class\s|(export\s+)?(const|let|var)\s+\w+\s*=\s*(async\s*)?(\(|function\b)|` + // JavaScript, TypeScript
28+ `(async\s+)?def\s|` + // Python (class: above)
29+ `(pub(\([\w:]+\))?\s+)?(fn|struct|enum|trait|impl)\s|` + // Rust
30+ `((public|private|protected|static|abstract|final)\s+)*(interface|enum|record)\s` + // Java, C#, TypeScript
31+ `)` +
32+ `|json:"` + // a Go struct field with its JSON name
33+ `|HandleFunc\(|\.Handle\(|\.(GET|POST|PUT|PATCH|DELETE)\(|"(GET|POST|PUT|PATCH|DELETE) /` + // routes
34+ `|fetch\(`) // a front end calling its API
35+
36+const (
37+ // minDeclarations: below that, the output is not code worth an outline.
38+ minDeclarations = 3
39+ // outlineMax bounds an outline's size; past it the last lines are
40+ // counted, not kept.
41+ outlineMax = 2000
42+ // outlineLineMax bounds one kept line.
43+ outlineLineMax = 160
44+)
45+
46+// shortened is what a long text becomes when it is shrunk: its outline when
47+// it holds code, its first line otherwise, each with a note saying what was
48+// dropped.
49+func shortened(s string) string {
50+ if o, ok := outline(s); ok {
51+ return o
52+ }
53+ return headLine(s)
54+}
55+
56+// outline is the declaration lines of s, in order, under a note; ok is false
57+// when s holds fewer than minDeclarations, or when the outline would not be
58+// at most half of s.
59+//
60+// outline("package server\n\nfunc New() *Server {\n…")
61+// // "[mm: outline of a 580-line output — …]\nfunc New() *Server {\n…", true
62+func outline(s string) (string, bool) {
63+ lines := strings.Split(s, "\n")
64+ var kept []string
65+ size, more := 0, 0
66+ for _, line := range lines {
67+ if !declaration.MatchString(line) {
68+ continue
69+ }
70+ line = strings.TrimRight(line, " \t")
71+ if len(line) > outlineLineMax {
72+ line = line[:outlineLineMax] + "…"
73+ }
74+ if size+len(line)+1 > outlineMax {
75+ more++
76+ continue
77+ }
78+ kept = append(kept, line)
79+ size += len(line) + 1
80+ }
81+ if len(kept)+more < minDeclarations {
82+ return "", false
83+ }
84+ note := fmt.Sprintf("[mm: outline of a %d-line output (%d characters) — %d declaration line(s) kept, the bodies were dropped to keep the context small; read a part again only for a body you need]",
85+ len(lines), len(s), len(kept))
86+ if more > 0 {
87+ note += fmt.Sprintf("\n[mm: … and %d more declaration line(s)]", more)
88+ }
89+ out := note + "\n" + strings.Join(kept, "\n")
90+ if len(out)*2 > len(s) {
91+ return "", false
92+ }
93+ return out, true
94+}
new file mode 100644
@@ -0,0 +1,94 @@
1+package compact
2+
3+import (
4+ "fmt"
5+ "regexp"
6+ "strings"
7+)
8+
9+// Outline of a shrunk code output (ticket 292).
10+//
11+// A shrunk tool result used to keep its first line only. For a source file
12+// that line is `package server`: everything the next steps need — the
13+// routes, the handlers, the types and their JSON fields — was gone, so the
14+// model read the file again, chunk by chunk, until the chunks it read first
15+// were shrunk in turn. Observed with Inkling-2-Mini on a 16k window: 40 tool
16+// calls, all reads, server.go read four times in the same ranges.
17+//
18+// So a long output that holds declarations keeps them: the model keeps the
19+// map of the code, not its bodies, and reads a body again only when it needs
20+// that body.
21+
22+// declaration matches a line worth keeping in an outline: functions, types,
23+// classes and their kin in the common languages, struct fields with a JSON
24+// tag, HTTP routes, and calls to an HTTP API from a front end.
25+var declaration = regexp.MustCompile(`^\s*(` +
26+ `func\s|type\s|` + // Go
27+ `(export\s+)?(default\s+)?(async\s+)?function\b|(export\s+)?class\s|(export\s+)?(const|let|var)\s+\w+\s*=\s*(async\s*)?(\(|function\b)|` + // JavaScript, TypeScript
28+ `(async\s+)?def\s|` + // Python (class: above)
29+ `(pub(\([\w:]+\))?\s+)?(fn|struct|enum|trait|impl)\s|` + // Rust
30+ `((public|private|protected|static|abstract|final)\s+)*(interface|enum|record)\s` + // Java, C#, TypeScript
31+ `)` +
32+ `|json:"` + // a Go struct field with its JSON name
33+ `|HandleFunc\(|\.Handle\(|\.(GET|POST|PUT|PATCH|DELETE)\(|"(GET|POST|PUT|PATCH|DELETE) /` + // routes
34+ `|fetch\(`) // a front end calling its API
35+
36+const (
37+ // minDeclarations: below that, the output is not code worth an outline.
38+ minDeclarations = 3
39+ // outlineMax bounds an outline's size; past it the last lines are
40+ // counted, not kept.
41+ outlineMax = 2000
42+ // outlineLineMax bounds one kept line.
43+ outlineLineMax = 160
44+)
45+
46+// shortened is what a long text becomes when it is shrunk: its outline when
47+// it holds code, its first line otherwise, each with a note saying what was
48+// dropped.
49+func shortened(s string) string {
50+ if o, ok := outline(s); ok {
51+ return o
52+ }
53+ return headLine(s)
54+}
55+
56+// outline is the declaration lines of s, in order, under a note; ok is false
57+// when s holds fewer than minDeclarations, or when the outline would not be
58+// at most half of s.
59+//
60+// outline("package server\n\nfunc New() *Server {\n…")
61+// // "[mm: outline of a 580-line output — …]\nfunc New() *Server {\n…", true
62+func outline(s string) (string, bool) {
63+ lines := strings.Split(s, "\n")
64+ var kept []string
65+ size, more := 0, 0
66+ for _, line := range lines {
67+ if !declaration.MatchString(line) {
68+ continue
69+ }
70+ line = strings.TrimRight(line, " \t")
71+ if len(line) > outlineLineMax {
72+ line = line[:outlineLineMax] + "…"
73+ }
74+ if size+len(line)+1 > outlineMax {
75+ more++
76+ continue
77+ }
78+ kept = append(kept, line)
79+ size += len(line) + 1
80+ }
81+ if len(kept)+more < minDeclarations {
82+ return "", false
83+ }
84+ note := fmt.Sprintf("[mm: outline of a %d-line output (%d characters) — %d declaration line(s) kept, the bodies were dropped to keep the context small; read a part again only for a body you need]",
85+ len(lines), len(s), len(kept))
86+ if more > 0 {
87+ note += fmt.Sprintf("\n[mm: … and %d more declaration line(s)]", more)
88+ }
89+ out := note + "\n" + strings.Join(kept, "\n")
90+ if len(out)*2 > len(s) {
91+ return "", false
92+ }
93+ return out, true
94+}
added internal/compact/outline_test.go +106 -0
new file mode 100644
@@ -0,0 +1,106 @@
1+package compact
2+
3+import (
4+ "context"
5+ "fmt"
6+ "strings"
7+ "testing"
8+
9+ "github.com/firebase/genkit/go/ai"
10+)
11+
12+// goServer is a Go file the size of the observed server.go chunks.
13+func goServer() string {
14+ var b strings.Builder
15+ b.WriteString("package server\n\nimport \"net/http\"\n\ntype Issue struct {\n\tID string `json:\"id\"`\n\tTitle string `json:\"title\"`\n}\n\n")
16+ b.WriteString("func (s *Server) routes() {\n\ts.mux.HandleFunc(\"GET /api/issues\", s.listIssues)\n\ts.mux.HandleFunc(\"POST /api/issues\", s.createIssue)\n}\n\n")
17+ for i := range 12 {
18+ fmt.Fprintf(&b, "func (s *Server) handler%d(w http.ResponseWriter, r *http.Request) {\n", i)
19+ b.WriteString(strings.Repeat("\tif err := doSomething(); err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n", 4))
20+ b.WriteString("}\n\n")
21+ }
22+ return b.String()
23+}
24+
25+func TestOutlineKeepsTheDeclarations(t *testing.T) {
26+ src := goServer()
27+ got := shortened(src)
28+ for _, want := range []string{"type Issue struct", "`json:\"title\"`", `HandleFunc("POST /api/issues"`, "func (s *Server) handler11(", "[mm: outline of a"} {
29+ if !strings.Contains(got, want) {
30+ t.Errorf("outline lacks %q:\n%s", want, got)
31+ }
32+ }
33+ if strings.Contains(got, "http.Error") {
34+ t.Error("the outline kept a body line")
35+ }
36+ if len(got)*2 > len(src) {
37+ t.Errorf("outline %d characters for %d: not worth it", len(got), len(src))
38+ }
39+}
40+
41+func TestOutlineFallsBackToTheFirstLine(t *testing.T) {
42+ prose := strings.Repeat("a line of a test log, nothing declared here\n", 50)
43+ if got := shortened(prose); !strings.HasPrefix(got, "a line of a test log") || !strings.Contains(got, "was dropped") {
44+ t.Errorf("prose: %q", got)
45+ }
46+ if _, ok := outline("func a() {}\nfunc b() {}\n"); ok {
47+ t.Error("two declarations: no outline")
48+ }
49+}
50+
51+func TestOutlineIsBounded(t *testing.T) {
52+ var b strings.Builder
53+ for i := range 400 {
54+ fmt.Fprintf(&b, "func f%d() { return }\n// %s\n", i, strings.Repeat("x", 40))
55+ }
56+ got, ok := outline(b.String())
57+ if !ok {
58+ t.Fatal("no outline")
59+ }
60+ if len(got) > outlineMax+400 || !strings.Contains(got, "more declaration line(s)") {
61+ t.Errorf("outline of %d characters, or no count of the rest", len(got))
62+ }
63+}
64+
65+// A shrunk message is never shrunk again: same message, no rewrite.
66+func TestShrinkIsDoneOnce(t *testing.T) {
67+ m := ai.NewMessage(ai.RoleTool, nil, ai.NewToolResponsePart(&ai.ToolResponse{Name: "bash", Ref: "1", Output: goServer()}))
68+ once, n := shrink(m)
69+ if n != 1 {
70+ t.Fatalf("first shrink: %d", n)
71+ }
72+ if twice, n := shrink(once); n != 0 || twice != once {
73+ t.Errorf("second shrink changed the message (%d)", n)
74+ }
75+}
76+
77+// The in-turn notes are asked to keep the API of the files read.
78+func TestInTurnPromptKeepsTheDeclarations(t *testing.T) {
79+ var asked []*ai.Message
80+ _, err := CompactTurn(t.Context(), longTurn(10), budget(100, Calibration{}), func(_ context.Context, req []*ai.Message) (string, error) {
81+ asked = req
82+ return "- notes", nil
83+ })
84+ if err != nil {
85+ t.Fatal(err)
86+ }
87+ prompt := asked[len(asked)-1].Text()
88+ for _, want := range []string{"function signatures", "HTTP routes", "JSON names", "Do not copy function bodies", "Start with ONE line: \"Next change: \""} {
89+ if !strings.Contains(prompt, want) {
90+ t.Errorf("prompt lacks %q", want)
91+ }
92+ }
93+}
94+
95+// Inside a turn, the notes' wrapper points at the next change, not at
96+// re-reading everything (ticket 292).
97+func TestInTurnNotesWrapperDoesNotOrderARereading(t *testing.T) {
98+ q := withNotes(ai.NewUserTextMessage("build the front"), "- notes", 12)
99+ text := q.Text()
100+ if strings.Contains(text, "re-read a file or re-run a command before relying on it") {
101+ t.Error("the wrapper still orders a re-reading")
102+ }
103+ if !strings.Contains(text, "[mm: progress on this task so far") || !strings.Contains(text, "then make that change") {
104+ t.Errorf("wrapper: %q", text)
105+ }
106+}
new file mode 100644
@@ -0,0 +1,106 @@
1+package compact
2+
3+import (
4+ "context"
5+ "fmt"
6+ "strings"
7+ "testing"
8+
9+ "github.com/firebase/genkit/go/ai"
10+)
11+
12+// goServer is a Go file the size of the observed server.go chunks.
13+func goServer() string {
14+ var b strings.Builder
15+ b.WriteString("package server\n\nimport \"net/http\"\n\ntype Issue struct {\n\tID string `json:\"id\"`\n\tTitle string `json:\"title\"`\n}\n\n")
16+ b.WriteString("func (s *Server) routes() {\n\ts.mux.HandleFunc(\"GET /api/issues\", s.listIssues)\n\ts.mux.HandleFunc(\"POST /api/issues\", s.createIssue)\n}\n\n")
17+ for i := range 12 {
18+ fmt.Fprintf(&b, "func (s *Server) handler%d(w http.ResponseWriter, r *http.Request) {\n", i)
19+ b.WriteString(strings.Repeat("\tif err := doSomething(); err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n", 4))
20+ b.WriteString("}\n\n")
21+ }
22+ return b.String()
23+}
24+
25+func TestOutlineKeepsTheDeclarations(t *testing.T) {
26+ src := goServer()
27+ got := shortened(src)
28+ for _, want := range []string{"type Issue struct", "`json:\"title\"`", `HandleFunc("POST /api/issues"`, "func (s *Server) handler11(", "[mm: outline of a"} {
29+ if !strings.Contains(got, want) {
30+ t.Errorf("outline lacks %q:\n%s", want, got)
31+ }
32+ }
33+ if strings.Contains(got, "http.Error") {
34+ t.Error("the outline kept a body line")
35+ }
36+ if len(got)*2 > len(src) {
37+ t.Errorf("outline %d characters for %d: not worth it", len(got), len(src))
38+ }
39+}
40+
41+func TestOutlineFallsBackToTheFirstLine(t *testing.T) {
42+ prose := strings.Repeat("a line of a test log, nothing declared here\n", 50)
43+ if got := shortened(prose); !strings.HasPrefix(got, "a line of a test log") || !strings.Contains(got, "was dropped") {
44+ t.Errorf("prose: %q", got)
45+ }
46+ if _, ok := outline("func a() {}\nfunc b() {}\n"); ok {
47+ t.Error("two declarations: no outline")
48+ }
49+}
50+
51+func TestOutlineIsBounded(t *testing.T) {
52+ var b strings.Builder
53+ for i := range 400 {
54+ fmt.Fprintf(&b, "func f%d() { return }\n// %s\n", i, strings.Repeat("x", 40))
55+ }
56+ got, ok := outline(b.String())
57+ if !ok {
58+ t.Fatal("no outline")
59+ }
60+ if len(got) > outlineMax+400 || !strings.Contains(got, "more declaration line(s)") {
61+ t.Errorf("outline of %d characters, or no count of the rest", len(got))
62+ }
63+}
64+
65+// A shrunk message is never shrunk again: same message, no rewrite.
66+func TestShrinkIsDoneOnce(t *testing.T) {
67+ m := ai.NewMessage(ai.RoleTool, nil, ai.NewToolResponsePart(&ai.ToolResponse{Name: "bash", Ref: "1", Output: goServer()}))
68+ once, n := shrink(m)
69+ if n != 1 {
70+ t.Fatalf("first shrink: %d", n)
71+ }
72+ if twice, n := shrink(once); n != 0 || twice != once {
73+ t.Errorf("second shrink changed the message (%d)", n)
74+ }
75+}
76+
77+// The in-turn notes are asked to keep the API of the files read.
78+func TestInTurnPromptKeepsTheDeclarations(t *testing.T) {
79+ var asked []*ai.Message
80+ _, err := CompactTurn(t.Context(), longTurn(10), budget(100, Calibration{}), func(_ context.Context, req []*ai.Message) (string, error) {
81+ asked = req
82+ return "- notes", nil
83+ })
84+ if err != nil {
85+ t.Fatal(err)
86+ }
87+ prompt := asked[len(asked)-1].Text()
88+ for _, want := range []string{"function signatures", "HTTP routes", "JSON names", "Do not copy function bodies", "Start with ONE line: \"Next change: \""} {
89+ if !strings.Contains(prompt, want) {
90+ t.Errorf("prompt lacks %q", want)
91+ }
92+ }
93+}
94+
95+// Inside a turn, the notes' wrapper points at the next change, not at
96+// re-reading everything (ticket 292).
97+func TestInTurnNotesWrapperDoesNotOrderARereading(t *testing.T) {
98+ q := withNotes(ai.NewUserTextMessage("build the front"), "- notes", 12)
99+ text := q.Text()
100+ if strings.Contains(text, "re-read a file or re-run a command before relying on it") {
101+ t.Error("the wrapper still orders a re-reading")
102+ }
103+ if !strings.Contains(text, "[mm: progress on this task so far") || !strings.Contains(text, "then make that change") {
104+ t.Errorf("wrapper: %q", text)
105+ }
106+}
modified internal/compact/shrink.go +9 -3
@@ -9,8 +9,14 @@ import (
99 )
1010
1111 // shrink returns a copy of m with its long tool results and call arguments
12-// cut to their first line, and how many it cut; m itself when none.
12+// cut to their outline or their first line (shortened), and how many it
13+// cut; m itself when none, or when m was shrunk already: an outline can be
14+// longer than shrinkOver, and shrinking it again would rewrite a message
15+// already in the server's prompt cache for nothing.
1316 func shrink(m *ai.Message) (*ai.Message, int) {
17+ if m.Metadata[metaKey] == "shrunk" {
18+ return m, 0
19+ }
1420 n := 0
1521 parts := make([]*ai.Part, len(m.Content))
1622 for i, p := range m.Content {
@@ -36,7 +42,7 @@ func shrinkPart(p *ai.Part) (*ai.Part, bool) {
3642 return p, false
3743 }
3844 r := *p.ToolResponse
39- r.Output = headLine(text)
45+ r.Output = shortened(text)
4046 return ai.NewToolResponsePart(&r), true
4147 case p.IsToolRequest() && p.ToolRequest != nil:
4248 cut := shrinkArgs(p.ToolRequest.Input)
@@ -67,7 +73,7 @@ func shrinkArgs(input any) map[string]any {
6773 if cut == nil {
6874 cut = maps.Clone(in)
6975 }
70- cut[k] = headLine(s)
76+ cut[k] = shortened(s)
7177 }
7278 return cut
7379 }
@@ -9,8 +9,14 @@ import (
9 )9 )
10 10
11 // shrink returns a copy of m with its long tool results and call arguments11 // shrink returns a copy of m with its long tool results and call arguments
12-// cut to their first line, and how many it cut; m itself when none.12+// cut to their outline or their first line (shortened), and how many it
13+// cut; m itself when none, or when m was shrunk already: an outline can be
14+// longer than shrinkOver, and shrinking it again would rewrite a message
15+// already in the server's prompt cache for nothing.
13 func shrink(m *ai.Message) (*ai.Message, int) {16 func shrink(m *ai.Message) (*ai.Message, int) {
17+ if m.Metadata[metaKey] == "shrunk" {
18+ return m, 0
19+ }
14 n := 020 n := 0
15 parts := make([]*ai.Part, len(m.Content))21 parts := make([]*ai.Part, len(m.Content))
16 for i, p := range m.Content {22 for i, p := range m.Content {
@@ -36,7 +42,7 @@ func shrinkPart(p *ai.Part) (*ai.Part, bool) {
36 return p, false42 return p, false
37 }43 }
38 r := *p.ToolResponse44 r := *p.ToolResponse
39- r.Output = headLine(text)45+ r.Output = shortened(text)
40 return ai.NewToolResponsePart(&r), true46 return ai.NewToolResponsePart(&r), true
41 case p.IsToolRequest() && p.ToolRequest != nil:47 case p.IsToolRequest() && p.ToolRequest != nil:
42 cut := shrinkArgs(p.ToolRequest.Input)48 cut := shrinkArgs(p.ToolRequest.Input)
@@ -67,7 +73,7 @@ func shrinkArgs(input any) map[string]any {
67 if cut == nil {73 if cut == nil {
68 cut = maps.Clone(in)74 cut = maps.Clone(in)
69 }75 }
70- cut[k] = headLine(s)76+ cut[k] = shortened(s)
71 }77 }
72 return cut78 return cut
73 }79 }
added internal/compact/target_test.go +81 -0
new file mode 100644
@@ -0,0 +1,81 @@
1+package compact
2+
3+import (
4+ "context"
5+ "fmt"
6+ "testing"
7+
8+ "github.com/firebase/genkit/go/ai"
9+)
10+
11+func TestBudgetTarget(t *testing.T) {
12+ for _, c := range []struct{ threshold, target, want int }{
13+ {75, 0, 50}, // unset: two thirds of the threshold
14+ {60, 0, 40}, // the Inkling demo's threshold
15+ {75, 40, 40}, // set
16+ {75, 75, 75}, // equal: compress just under the threshold, as before
17+ {60, 90, 60}, // never above the threshold
18+ } {
19+ if got := (Budget{Threshold: c.threshold, Target: c.target}).target(); got != c.want {
20+ t.Errorf("threshold %d, inTurnTarget %d: target %d, want %d", c.threshold, c.target, got, c.want)
21+ }
22+ }
23+}
24+
25+// callsWithoutCompression grows a compressed turn by one exchange per call
26+// and counts the calls that go out before the threshold fires again.
27+func callsWithoutCompression(t *testing.T, b Budget) int {
28+ t.Helper()
29+ msgs := longTurn(8)
30+ r, err := CompactTurn(context.Background(), msgs, b, counting(new(int)))
31+ if err != nil {
32+ t.Fatal(err)
33+ }
34+ history := r.Messages
35+ for call := range 10 {
36+ history = append(history, exchanges(fmt.Sprintf("n%d-", call), 1)...)
37+ if InTurnDecide(history, 0, b.Window, b.Calibration, inTurnCfg()) {
38+ return call
39+ }
40+ }
41+ return 10
42+}
43+
44+// Ticket 290: compressed down to the target, the turn runs several calls
45+// without compressing again — the prompt stays the same and the server's
46+// cache serves them. Compressed just under the threshold, the next call
47+// compresses again.
48+func TestCompactTurnGoesDownToTheTarget(t *testing.T) {
49+ // The Inkling case: the last 4 reads alone are 70 % of the window, just
50+ // under the 75 % threshold, and each new read is ~17 % more.
51+ one := Estimate(exchanges("x-", 1))
52+ window := 4 * one * 100 / 70
53+ hysteresis := callsWithoutCompression(t, Budget{Window: window, Threshold: 75})
54+ justUnder := callsWithoutCompression(t, Budget{Window: window, Threshold: 75, Target: 75})
55+ if hysteresis < 2 || justUnder > 1 || hysteresis <= justUnder {
56+ t.Errorf("calls before the next compression: %d with the target, %d without; want ≥ 2 and ≤ 1", hysteresis, justUnder)
57+ }
58+}
59+
60+// When the summary is not allowed (no summariser), the kept exchanges are
61+// shrunk too, but the last, to reach the target.
62+func TestCompactTurnShrinksTheTailAsALastResort(t *testing.T) {
63+ msgs := longTurn(10)
64+ q, cut := turnBounds(msgs)
65+ tail := append(append([]*ai.Message{}, msgs[:q+1]...), msgs[cut:]...)
66+ b := Budget{Window: Estimate(tail) * 100 / 60, Threshold: 75} // the raw tail: 60 %, above the 50 % target
67+ r, err := CompactTurn(context.Background(), msgs, b, nil)
68+ if err != nil {
69+ t.Fatal(err)
70+ }
71+ if b.aboveTarget(r.Messages) {
72+ t.Errorf("still above the target: %d tokens of %d", r.After, b.Window)
73+ }
74+ last := r.Messages[len(r.Messages)-1]
75+ if last.Metadata[metaKey] == "shrunk" {
76+ t.Error("the last exchange was shrunk")
77+ }
78+ if err := Valid(r.Messages); err != nil {
79+ t.Fatal(err)
80+ }
81+}
new file mode 100644
@@ -0,0 +1,81 @@
1+package compact
2+
3+import (
4+ "context"
5+ "fmt"
6+ "testing"
7+
8+ "github.com/firebase/genkit/go/ai"
9+)
10+
11+func TestBudgetTarget(t *testing.T) {
12+ for _, c := range []struct{ threshold, target, want int }{
13+ {75, 0, 50}, // unset: two thirds of the threshold
14+ {60, 0, 40}, // the Inkling demo's threshold
15+ {75, 40, 40}, // set
16+ {75, 75, 75}, // equal: compress just under the threshold, as before
17+ {60, 90, 60}, // never above the threshold
18+ } {
19+ if got := (Budget{Threshold: c.threshold, Target: c.target}).target(); got != c.want {
20+ t.Errorf("threshold %d, inTurnTarget %d: target %d, want %d", c.threshold, c.target, got, c.want)
21+ }
22+ }
23+}
24+
25+// callsWithoutCompression grows a compressed turn by one exchange per call
26+// and counts the calls that go out before the threshold fires again.
27+func callsWithoutCompression(t *testing.T, b Budget) int {
28+ t.Helper()
29+ msgs := longTurn(8)
30+ r, err := CompactTurn(context.Background(), msgs, b, counting(new(int)))
31+ if err != nil {
32+ t.Fatal(err)
33+ }
34+ history := r.Messages
35+ for call := range 10 {
36+ history = append(history, exchanges(fmt.Sprintf("n%d-", call), 1)...)
37+ if InTurnDecide(history, 0, b.Window, b.Calibration, inTurnCfg()) {
38+ return call
39+ }
40+ }
41+ return 10
42+}
43+
44+// Ticket 290: compressed down to the target, the turn runs several calls
45+// without compressing again — the prompt stays the same and the server's
46+// cache serves them. Compressed just under the threshold, the next call
47+// compresses again.
48+func TestCompactTurnGoesDownToTheTarget(t *testing.T) {
49+ // The Inkling case: the last 4 reads alone are 70 % of the window, just
50+ // under the 75 % threshold, and each new read is ~17 % more.
51+ one := Estimate(exchanges("x-", 1))
52+ window := 4 * one * 100 / 70
53+ hysteresis := callsWithoutCompression(t, Budget{Window: window, Threshold: 75})
54+ justUnder := callsWithoutCompression(t, Budget{Window: window, Threshold: 75, Target: 75})
55+ if hysteresis < 2 || justUnder > 1 || hysteresis <= justUnder {
56+ t.Errorf("calls before the next compression: %d with the target, %d without; want ≥ 2 and ≤ 1", hysteresis, justUnder)
57+ }
58+}
59+
60+// When the summary is not allowed (no summariser), the kept exchanges are
61+// shrunk too, but the last, to reach the target.
62+func TestCompactTurnShrinksTheTailAsALastResort(t *testing.T) {
63+ msgs := longTurn(10)
64+ q, cut := turnBounds(msgs)
65+ tail := append(append([]*ai.Message{}, msgs[:q+1]...), msgs[cut:]...)
66+ b := Budget{Window: Estimate(tail) * 100 / 60, Threshold: 75} // the raw tail: 60 %, above the 50 % target
67+ r, err := CompactTurn(context.Background(), msgs, b, nil)
68+ if err != nil {
69+ t.Fatal(err)
70+ }
71+ if b.aboveTarget(r.Messages) {
72+ t.Errorf("still above the target: %d tokens of %d", r.After, b.Window)
73+ }
74+ last := r.Messages[len(r.Messages)-1]
75+ if last.Metadata[metaKey] == "shrunk" {
76+ t.Error("the last exchange was shrunk")
77+ }
78+ if err := Valid(r.Messages); err != nil {
79+ t.Fatal(err)
80+ }
81+}
modified internal/config/config.go +19 -0
@@ -780,6 +780,21 @@ type ContextConfig struct {
780780 // compact.KeepToolCalls exchanges stay raw. On by default; independent of
781781 // Enabled — a turn that outgrows the window fails either way.
782782 CompressInTurn bool `yaml:"compressInTurn"`
783+
784+ // InTurnTarget (ticket 290): once the in-turn compression fires (at
785+ // Threshold), the share of the window, in percent, it brings the history
786+ // down to — lower than Threshold, so the next calls run without
787+ // compressing again and keep the server's prompt cache. 0 = two thirds
788+ // of Threshold (75 → 50). Equal to Threshold: compress just under it,
789+ // as before.
790+ InTurnTarget int `yaml:"inTurnTarget"`
791+
792+ // RereadLimit (ticket 292): how many times, in one turn, the same tool
793+ // call (same arguments) may run again after a compression dropped its
794+ // result and no file was changed — the third identical read with the
795+ // default 1. Past it, the call is not run: its result tells the model to
796+ // work from its notes. 0 = no limit (a note only).
797+ RereadLimit int `yaml:"rereadLimit"`
783798 }
784799
785800 // The values of toolFormat.
@@ -919,6 +934,10 @@ which ones you left running.`,
919934 // a runaway model from filling the window it was asked to empty.
920935 SummaryMaxTokens: 1200,
921936 ShowStats: true,
937+ // One re-read with a note, then the call is refused: observed, a
938+ // model read the same four ranges of a file four times, notes or
939+ // not, until maxTurns.
940+ RereadLimit: 1,
922941 },
923942 MCP: MCPConfig{
924943 Enabled: false,
@@ -780,6 +780,21 @@ type ContextConfig struct {
780 // compact.KeepToolCalls exchanges stay raw. On by default; independent of780 // compact.KeepToolCalls exchanges stay raw. On by default; independent of
781 // Enabled — a turn that outgrows the window fails either way.781 // Enabled — a turn that outgrows the window fails either way.
782 CompressInTurn bool `yaml:"compressInTurn"`782 CompressInTurn bool `yaml:"compressInTurn"`
783+
784+ // InTurnTarget (ticket 290): once the in-turn compression fires (at
785+ // Threshold), the share of the window, in percent, it brings the history
786+ // down to — lower than Threshold, so the next calls run without
787+ // compressing again and keep the server's prompt cache. 0 = two thirds
788+ // of Threshold (75 → 50). Equal to Threshold: compress just under it,
789+ // as before.
790+ InTurnTarget int `yaml:"inTurnTarget"`
791+
792+ // RereadLimit (ticket 292): how many times, in one turn, the same tool
793+ // call (same arguments) may run again after a compression dropped its
794+ // result and no file was changed — the third identical read with the
795+ // default 1. Past it, the call is not run: its result tells the model to
796+ // work from its notes. 0 = no limit (a note only).
797+ RereadLimit int `yaml:"rereadLimit"`
783 }798 }
784 799
785 // The values of toolFormat.800 // The values of toolFormat.
@@ -919,6 +934,10 @@ which ones you left running.`,
919 // a runaway model from filling the window it was asked to empty.934 // a runaway model from filling the window it was asked to empty.
920 SummaryMaxTokens: 1200,935 SummaryMaxTokens: 1200,
921 ShowStats: true,936 ShowStats: true,
937+ // One re-read with a note, then the call is refused: observed, a
938+ // model read the same four ranges of a file four times, notes or
939+ // not, until maxTurns.
940+ RereadLimit: 1,
922 },941 },
923 MCP: MCPConfig{942 MCP: MCPConfig{
924 Enabled: false,943 Enabled: false,
added internal/config/inturntarget_test.go +41 -0
new file mode 100644
@@ -0,0 +1,41 @@
1+package config
2+
3+import (
4+ "strings"
5+ "testing"
6+)
7+
8+// context.inTurnTarget (ticket 290): 0 by default, read from the file,
9+// refused below 0 or above context.threshold.
10+func TestInTurnTarget(t *testing.T) {
11+ if err := loadYAML(t, "model: m\n"); err != nil {
12+ t.Fatal(err)
13+ }
14+ if Cfg.Context.InTurnTarget != 0 {
15+ t.Errorf("default %d, want 0 (two thirds of the threshold)", Cfg.Context.InTurnTarget)
16+ }
17+ if err := loadYAML(t, "model: m\ncontext:\n threshold: 60\n inTurnTarget: 40\n"); err != nil || Cfg.Context.InTurnTarget != 40 {
18+ t.Errorf("read: %d, %v", Cfg.Context.InTurnTarget, err)
19+ }
20+ for _, body := range []string{
21+ "model: m\ncontext:\n inTurnTarget: -1\n",
22+ "model: m\ncontext:\n threshold: 60\n inTurnTarget: 70\n",
23+ } {
24+ if err := loadYAML(t, body); err == nil || !strings.Contains(err.Error(), "context.inTurnTarget must be between 0 and context.threshold") {
25+ t.Errorf("%q: Load = %v", body, err)
26+ }
27+ }
28+}
29+
30+// context.rereadLimit (ticket 292): 1 by default, 0 allowed, never negative.
31+func TestRereadLimitConfig(t *testing.T) {
32+ if err := loadYAML(t, "model: m\n"); err != nil || Cfg.Context.RereadLimit != 1 {
33+ t.Errorf("default %d (%v), want 1", Cfg.Context.RereadLimit, err)
34+ }
35+ if err := loadYAML(t, "model: m\ncontext:\n rereadLimit: 0\n"); err != nil || Cfg.Context.RereadLimit != 0 {
36+ t.Errorf("0: %d, %v", Cfg.Context.RereadLimit, err)
37+ }
38+ if err := loadYAML(t, "model: m\ncontext:\n rereadLimit: -1\n"); err == nil || !strings.Contains(err.Error(), "context.rereadLimit must be >= 0") {
39+ t.Errorf("-1: %v", err)
40+ }
41+}
new file mode 100644
@@ -0,0 +1,41 @@
1+package config
2+
3+import (
4+ "strings"
5+ "testing"
6+)
7+
8+// context.inTurnTarget (ticket 290): 0 by default, read from the file,
9+// refused below 0 or above context.threshold.
10+func TestInTurnTarget(t *testing.T) {
11+ if err := loadYAML(t, "model: m\n"); err != nil {
12+ t.Fatal(err)
13+ }
14+ if Cfg.Context.InTurnTarget != 0 {
15+ t.Errorf("default %d, want 0 (two thirds of the threshold)", Cfg.Context.InTurnTarget)
16+ }
17+ if err := loadYAML(t, "model: m\ncontext:\n threshold: 60\n inTurnTarget: 40\n"); err != nil || Cfg.Context.InTurnTarget != 40 {
18+ t.Errorf("read: %d, %v", Cfg.Context.InTurnTarget, err)
19+ }
20+ for _, body := range []string{
21+ "model: m\ncontext:\n inTurnTarget: -1\n",
22+ "model: m\ncontext:\n threshold: 60\n inTurnTarget: 70\n",
23+ } {
24+ if err := loadYAML(t, body); err == nil || !strings.Contains(err.Error(), "context.inTurnTarget must be between 0 and context.threshold") {
25+ t.Errorf("%q: Load = %v", body, err)
26+ }
27+ }
28+}
29+
30+// context.rereadLimit (ticket 292): 1 by default, 0 allowed, never negative.
31+func TestRereadLimitConfig(t *testing.T) {
32+ if err := loadYAML(t, "model: m\n"); err != nil || Cfg.Context.RereadLimit != 1 {
33+ t.Errorf("default %d (%v), want 1", Cfg.Context.RereadLimit, err)
34+ }
35+ if err := loadYAML(t, "model: m\ncontext:\n rereadLimit: 0\n"); err != nil || Cfg.Context.RereadLimit != 0 {
36+ t.Errorf("0: %d, %v", Cfg.Context.RereadLimit, err)
37+ }
38+ if err := loadYAML(t, "model: m\ncontext:\n rereadLimit: -1\n"); err == nil || !strings.Contains(err.Error(), "context.rereadLimit must be >= 0") {
39+ t.Errorf("-1: %v", err)
40+ }
41+}
modified internal/config/validate.go +2 -0
@@ -190,6 +190,8 @@ func (c Config) sectionError() error {
190190 problem(c.Context.KeepLastTurns < 1, "context.keepLastTurns must be >= 1"),
191191 problem(c.Context.SummaryMaxTokens <= 0, "context.summaryMaxTokens must be > 0"),
192192 problem(c.Context.MaxMessages < 0, "context.maxMessages must be >= 0"),
193+ problem(c.Context.InTurnTarget < 0 || c.Context.InTurnTarget > c.Context.Threshold, "context.inTurnTarget must be between 0 and context.threshold"),
194+ problem(c.Context.RereadLimit < 0, "context.rereadLimit must be >= 0"),
193195 problem(c.Sessions.Dir == "", "sessions.dir must not be empty"),
194196 problem(c.Trace.Enabled && strings.TrimSpace(c.Trace.Dir) == "", "trace.dir must not be empty"),
195197 problem(c.AgentsMd.Enabled && strings.TrimSpace(c.AgentsMd.Path) == "", "agentsMd.path must not be empty"),
@@ -190,6 +190,8 @@ func (c Config) sectionError() error {
190 problem(c.Context.KeepLastTurns < 1, "context.keepLastTurns must be >= 1"),190 problem(c.Context.KeepLastTurns < 1, "context.keepLastTurns must be >= 1"),
191 problem(c.Context.SummaryMaxTokens <= 0, "context.summaryMaxTokens must be > 0"),191 problem(c.Context.SummaryMaxTokens <= 0, "context.summaryMaxTokens must be > 0"),
192 problem(c.Context.MaxMessages < 0, "context.maxMessages must be >= 0"),192 problem(c.Context.MaxMessages < 0, "context.maxMessages must be >= 0"),
193+ problem(c.Context.InTurnTarget < 0 || c.Context.InTurnTarget > c.Context.Threshold, "context.inTurnTarget must be between 0 and context.threshold"),
194+ problem(c.Context.RereadLimit < 0, "context.rereadLimit must be >= 0"),
193 problem(c.Sessions.Dir == "", "sessions.dir must not be empty"),195 problem(c.Sessions.Dir == "", "sessions.dir must not be empty"),
194 problem(c.Trace.Enabled && strings.TrimSpace(c.Trace.Dir) == "", "trace.dir must not be empty"),196 problem(c.Trace.Enabled && strings.TrimSpace(c.Trace.Dir) == "", "trace.dir must not be empty"),
195 problem(c.AgentsMd.Enabled && strings.TrimSpace(c.AgentsMd.Path) == "", "agentsMd.path must not be empty"),197 problem(c.AgentsMd.Enabled && strings.TrimSpace(c.AgentsMd.Path) == "", "agentsMd.path must not be empty"),
added internal/engine/calibrate_test.go +159 -0
new file mode 100644
@@ -0,0 +1,159 @@
1+package engine
2+
3+import (
4+ "context"
5+ "errors"
6+ "fmt"
7+ "strings"
8+ "testing"
9+
10+ "mm/internal/compact"
11+ "mm/internal/config"
12+
13+ "github.com/firebase/genkit/go/ai"
14+ "github.com/firebase/genkit/go/genkit"
15+)
16+
17+// The ratio a measured call gives is kept for the next decisions, and
18+// survives the forgetting of the count after a compression (ticket 291).
19+func TestEngineCalibration(t *testing.T) {
20+ e := &Engine{}
21+ if c := e.calibration(nil); c.Ratio != 0 {
22+ t.Fatalf("before any measure: ratio %v, want 0", c.Ratio)
23+ }
24+ req := &ai.ModelRequest{Messages: []*ai.Message{ai.NewSystemTextMessage("system"), ai.NewUserTextMessage(strings.Repeat("code ", 700))}}
25+ estimated := compact.Estimate(req.Messages)
26+ e.calibrate(req, 2*estimated)
27+ e.ForgetInputTokens()
28+ if c := e.calibration(nil); c.Ratio < 1.99 || c.Ratio > 2.01 {
29+ t.Errorf("ratio %v, want 2", c.Ratio)
30+ }
31+ tools := []*ai.ToolDefinition{{Name: "bash", Description: "run a command"}}
32+ if c := e.calibration(tools); c.Tools != compact.EstimateTools(tools) {
33+ t.Errorf("tools %d, want %d", c.Tools, compact.EstimateTools(tools))
34+ }
35+}
36+
37+// A request still larger than the window once compressed is not sent: the
38+// turn ends with the overflow line, never retried (ticket 291).
39+func TestCompactInTurnRefusesARequestLargerThanTheWindow(t *testing.T) {
40+ saved := config.Cfg
41+ t.Cleanup(func() { config.Cfg = saved })
42+ config.Cfg.Context.CompressInTurn = true
43+ config.Cfg.Context.Threshold = 75
44+
45+ big := strings.Repeat("a line of the tool's output\n", 100)
46+ msgs := []*ai.Message{
47+ ai.NewSystemTextMessage("system"),
48+ ai.NewUserTextMessage("read the file"),
49+ ai.NewModelMessage(ai.NewToolRequestPart(&ai.ToolRequest{Name: "cat", Ref: "1", Input: map[string]any{"path": "f"}})),
50+ ai.NewMessage(ai.RoleTool, nil, ai.NewToolResponsePart(&ai.ToolResponse{Name: "cat", Ref: "1", Output: big})),
51+ }
52+ e := &Engine{ContextWindow: compact.Estimate(msgs) * 3 / 2} // 67 % by the estimate
53+ params := &ai.ModelParams{Request: &ai.ModelRequest{Messages: msgs}}
54+ if err := e.compactInTurn(context.Background(), params); err != nil {
55+ t.Fatalf("plain estimate under the window: %v", err)
56+ }
57+
58+ e.calibrate(&ai.ModelRequest{Messages: msgs}, 2*compact.Estimate(msgs)) // the server counts twice as much
59+ err := e.compactInTurn(context.Background(), params)
60+ var tooBig *requestTooBig
61+ if !errors.As(err, &tooBig) {
62+ t.Fatalf("err = %v, want requestTooBig", err)
63+ }
64+ if !contextOverflow(err) {
65+ t.Error("requestTooBig must count as an overflow (never retried)")
66+ }
67+ if line := e.Explain(err); !strings.Contains(line, "not sent") || !strings.Contains(line, "contextWindow") {
68+ t.Errorf("Explain = %q", line)
69+ }
70+}
71+
72+// End to end (ticket 291): a server that counts twice the estimate. Without
73+// its counts, the shrunk turn looks under the threshold and is never
74+// summarised; with them, the calibrated size triggers the summary.
75+func TestGenerateSummarisesOnTheServersCount(t *testing.T) {
76+ saved := config.Cfg
77+ t.Cleanup(func() { config.Cfg = saved })
78+ config.Cfg.Context.CompressInTurn = true
79+ config.Cfg.Context.Threshold = 75
80+ config.Cfg.MaxTurns = 20
81+
82+ run := func(reportUsage bool) (summaries int) {
83+ big := strings.Repeat("a line of the tool's output\n", 100) // ~800 tokens
84+ g := genkit.Init(context.Background())
85+ calls := 0
86+ genkit.DefineModelAction(g, "dmr/"+config.Cfg.Model,
87+ &ai.ModelOptions{Supports: &ai.ModelSupports{Tools: true, Multiturn: true, SystemRole: true}},
88+ func(_ context.Context, r *ai.ModelRequest, _ any, _ ai.ModelStreamCallback) (*ai.ModelResponse, error) {
89+ if len(r.Tools) == 0 {
90+ summaries++
91+ return modelTurn(ai.NewTextPart("- read f1 … f8")), nil
92+ }
93+ calls++
94+ resp := modelTurn(ai.NewToolRequestPart(&ai.ToolRequest{Name: "cat", Ref: fmt.Sprint(calls),
95+ Input: map[string]any{"path": fmt.Sprintf("f%d", calls)}}))
96+ if calls > 12 {
97+ resp = modelTurn(ai.NewTextPart("done"))
98+ }
99+ if reportUsage {
100+ resp.Usage = &ai.GenerationUsage{InputTokens: 2 * (compact.Estimate(r.Messages) + compact.EstimateTools(r.Tools))}
101+ }
102+ return resp, nil
103+ })
104+ genkit.DefineTool(g, "cat", "print a file", func(_ *ai.ToolContext, in struct {
105+ Path string `json:"path"`
106+ }) (string, error) {
107+ return in.Path + ": 100 line(s)\n" + big, nil
108+ })
109+ e := testEngine(g)
110+ // Threshold 6000: the kept tail (4 exchanges, ~3.2k estimated)
111+ // stays under it plainly, not once doubled.
112+ e.ContextWindow = 8000
113+ _, full, err := e.Generate(context.Background(),
114+ []*ai.Message{ai.NewSystemTextMessage("system"), ai.NewUserTextMessage("read every file")},
115+ []ai.ToolRef{ai.ToolName("cat")})
116+ if err != nil && !contextOverflow(err) {
117+ t.Fatalf("Generate: %v", err)
118+ }
119+ if err := compact.Valid(full); err != nil {
120+ t.Errorf("history: %v", err)
121+ }
122+ return summaries
123+ }
124+ if n := run(false); n != 0 {
125+ t.Errorf("no server counts: %d summaries, want 0 (the plain estimate stays under the threshold)", n)
126+ }
127+ // With the target under the threshold (ticket 290), a compression
128+ // lasts several calls: fewer summaries than half the 12 calls (8 of
129+ // them before the target existed).
130+ if n := run(true); n == 0 || n > 6 {
131+ t.Errorf("server counts twice the estimate: %d summaries, want 1 to 6", n)
132+ }
133+}
134+
135+// A summary cut at its length limit loses its unfinished line and says it
136+// is incomplete; the user is told once (ticket 292).
137+func TestSummarizeMarksACutSummary(t *testing.T) {
138+ g := genkit.Init(context.Background())
139+ genkit.DefineModelAction(g, "dmr/"+config.Cfg.Model,
140+ &ai.ModelOptions{Supports: &ai.ModelSupports{Multiturn: true, SystemRole: true}},
141+ func(context.Context, *ai.ModelRequest, any, ai.ModelStreamCallback) (*ai.ModelResponse, error) {
142+ return &ai.ModelResponse{Message: ai.NewModelTextMessage("Next change: web/app.js\n- routes: GET /api/issues\n- roadmap builds Cell{Issues"),
143+ FinishReason: ai.FinishReasonLength}, nil
144+ })
145+ e := testEngine(g)
146+ text, err := e.Summarize(context.Background(), []*ai.Message{ai.NewUserTextMessage("summarise")}, 100)
147+ if err != nil {
148+ t.Fatal(err)
149+ }
150+ if strings.Contains(text, "Cell{Issues") || !strings.HasSuffix(text, "[notes cut at the length limit]") || !strings.HasPrefix(text, "Next change: web/app.js") {
151+ t.Errorf("cut summary: %q", text)
152+ }
153+ if !e.summaryCutWarned.Load() {
154+ t.Error("the user was not told")
155+ }
156+ if got := cutSummary("one line only"); got != "one line only\n- [notes cut at the length limit]" {
157+ t.Errorf("single line: %q", got)
158+ }
159+}
new file mode 100644
@@ -0,0 +1,159 @@
1+package engine
2+
3+import (
4+ "context"
5+ "errors"
6+ "fmt"
7+ "strings"
8+ "testing"
9+
10+ "mm/internal/compact"
11+ "mm/internal/config"
12+
13+ "github.com/firebase/genkit/go/ai"
14+ "github.com/firebase/genkit/go/genkit"
15+)
16+
17+// The ratio a measured call gives is kept for the next decisions, and
18+// survives the forgetting of the count after a compression (ticket 291).
19+func TestEngineCalibration(t *testing.T) {
20+ e := &Engine{}
21+ if c := e.calibration(nil); c.Ratio != 0 {
22+ t.Fatalf("before any measure: ratio %v, want 0", c.Ratio)
23+ }
24+ req := &ai.ModelRequest{Messages: []*ai.Message{ai.NewSystemTextMessage("system"), ai.NewUserTextMessage(strings.Repeat("code ", 700))}}
25+ estimated := compact.Estimate(req.Messages)
26+ e.calibrate(req, 2*estimated)
27+ e.ForgetInputTokens()
28+ if c := e.calibration(nil); c.Ratio < 1.99 || c.Ratio > 2.01 {
29+ t.Errorf("ratio %v, want 2", c.Ratio)
30+ }
31+ tools := []*ai.ToolDefinition{{Name: "bash", Description: "run a command"}}
32+ if c := e.calibration(tools); c.Tools != compact.EstimateTools(tools) {
33+ t.Errorf("tools %d, want %d", c.Tools, compact.EstimateTools(tools))
34+ }
35+}
36+
37+// A request still larger than the window once compressed is not sent: the
38+// turn ends with the overflow line, never retried (ticket 291).
39+func TestCompactInTurnRefusesARequestLargerThanTheWindow(t *testing.T) {
40+ saved := config.Cfg
41+ t.Cleanup(func() { config.Cfg = saved })
42+ config.Cfg.Context.CompressInTurn = true
43+ config.Cfg.Context.Threshold = 75
44+
45+ big := strings.Repeat("a line of the tool's output\n", 100)
46+ msgs := []*ai.Message{
47+ ai.NewSystemTextMessage("system"),
48+ ai.NewUserTextMessage("read the file"),
49+ ai.NewModelMessage(ai.NewToolRequestPart(&ai.ToolRequest{Name: "cat", Ref: "1", Input: map[string]any{"path": "f"}})),
50+ ai.NewMessage(ai.RoleTool, nil, ai.NewToolResponsePart(&ai.ToolResponse{Name: "cat", Ref: "1", Output: big})),
51+ }
52+ e := &Engine{ContextWindow: compact.Estimate(msgs) * 3 / 2} // 67 % by the estimate
53+ params := &ai.ModelParams{Request: &ai.ModelRequest{Messages: msgs}}
54+ if err := e.compactInTurn(context.Background(), params); err != nil {
55+ t.Fatalf("plain estimate under the window: %v", err)
56+ }
57+
58+ e.calibrate(&ai.ModelRequest{Messages: msgs}, 2*compact.Estimate(msgs)) // the server counts twice as much
59+ err := e.compactInTurn(context.Background(), params)
60+ var tooBig *requestTooBig
61+ if !errors.As(err, &tooBig) {
62+ t.Fatalf("err = %v, want requestTooBig", err)
63+ }
64+ if !contextOverflow(err) {
65+ t.Error("requestTooBig must count as an overflow (never retried)")
66+ }
67+ if line := e.Explain(err); !strings.Contains(line, "not sent") || !strings.Contains(line, "contextWindow") {
68+ t.Errorf("Explain = %q", line)
69+ }
70+}
71+
72+// End to end (ticket 291): a server that counts twice the estimate. Without
73+// its counts, the shrunk turn looks under the threshold and is never
74+// summarised; with them, the calibrated size triggers the summary.
75+func TestGenerateSummarisesOnTheServersCount(t *testing.T) {
76+ saved := config.Cfg
77+ t.Cleanup(func() { config.Cfg = saved })
78+ config.Cfg.Context.CompressInTurn = true
79+ config.Cfg.Context.Threshold = 75
80+ config.Cfg.MaxTurns = 20
81+
82+ run := func(reportUsage bool) (summaries int) {
83+ big := strings.Repeat("a line of the tool's output\n", 100) // ~800 tokens
84+ g := genkit.Init(context.Background())
85+ calls := 0
86+ genkit.DefineModelAction(g, "dmr/"+config.Cfg.Model,
87+ &ai.ModelOptions{Supports: &ai.ModelSupports{Tools: true, Multiturn: true, SystemRole: true}},
88+ func(_ context.Context, r *ai.ModelRequest, _ any, _ ai.ModelStreamCallback) (*ai.ModelResponse, error) {
89+ if len(r.Tools) == 0 {
90+ summaries++
91+ return modelTurn(ai.NewTextPart("- read f1 … f8")), nil
92+ }
93+ calls++
94+ resp := modelTurn(ai.NewToolRequestPart(&ai.ToolRequest{Name: "cat", Ref: fmt.Sprint(calls),
95+ Input: map[string]any{"path": fmt.Sprintf("f%d", calls)}}))
96+ if calls > 12 {
97+ resp = modelTurn(ai.NewTextPart("done"))
98+ }
99+ if reportUsage {
100+ resp.Usage = &ai.GenerationUsage{InputTokens: 2 * (compact.Estimate(r.Messages) + compact.EstimateTools(r.Tools))}
101+ }
102+ return resp, nil
103+ })
104+ genkit.DefineTool(g, "cat", "print a file", func(_ *ai.ToolContext, in struct {
105+ Path string `json:"path"`
106+ }) (string, error) {
107+ return in.Path + ": 100 line(s)\n" + big, nil
108+ })
109+ e := testEngine(g)
110+ // Threshold 6000: the kept tail (4 exchanges, ~3.2k estimated)
111+ // stays under it plainly, not once doubled.
112+ e.ContextWindow = 8000
113+ _, full, err := e.Generate(context.Background(),
114+ []*ai.Message{ai.NewSystemTextMessage("system"), ai.NewUserTextMessage("read every file")},
115+ []ai.ToolRef{ai.ToolName("cat")})
116+ if err != nil && !contextOverflow(err) {
117+ t.Fatalf("Generate: %v", err)
118+ }
119+ if err := compact.Valid(full); err != nil {
120+ t.Errorf("history: %v", err)
121+ }
122+ return summaries
123+ }
124+ if n := run(false); n != 0 {
125+ t.Errorf("no server counts: %d summaries, want 0 (the plain estimate stays under the threshold)", n)
126+ }
127+ // With the target under the threshold (ticket 290), a compression
128+ // lasts several calls: fewer summaries than half the 12 calls (8 of
129+ // them before the target existed).
130+ if n := run(true); n == 0 || n > 6 {
131+ t.Errorf("server counts twice the estimate: %d summaries, want 1 to 6", n)
132+ }
133+}
134+
135+// A summary cut at its length limit loses its unfinished line and says it
136+// is incomplete; the user is told once (ticket 292).
137+func TestSummarizeMarksACutSummary(t *testing.T) {
138+ g := genkit.Init(context.Background())
139+ genkit.DefineModelAction(g, "dmr/"+config.Cfg.Model,
140+ &ai.ModelOptions{Supports: &ai.ModelSupports{Multiturn: true, SystemRole: true}},
141+ func(context.Context, *ai.ModelRequest, any, ai.ModelStreamCallback) (*ai.ModelResponse, error) {
142+ return &ai.ModelResponse{Message: ai.NewModelTextMessage("Next change: web/app.js\n- routes: GET /api/issues\n- roadmap builds Cell{Issues"),
143+ FinishReason: ai.FinishReasonLength}, nil
144+ })
145+ e := testEngine(g)
146+ text, err := e.Summarize(context.Background(), []*ai.Message{ai.NewUserTextMessage("summarise")}, 100)
147+ if err != nil {
148+ t.Fatal(err)
149+ }
150+ if strings.Contains(text, "Cell{Issues") || !strings.HasSuffix(text, "[notes cut at the length limit]") || !strings.HasPrefix(text, "Next change: web/app.js") {
151+ t.Errorf("cut summary: %q", text)
152+ }
153+ if !e.summaryCutWarned.Load() {
154+ t.Error("the user was not told")
155+ }
156+ if got := cutSummary("one line only"); got != "one line only\n- [notes cut at the length limit]" {
157+ t.Errorf("single line: %q", got)
158+ }
159+}
modified internal/engine/ctxsize.go +10 -3
@@ -1,6 +1,7 @@
11 package engine
22
33 import (
4+ "errors"
45 "fmt"
56 "regexp"
67 "strconv"
@@ -37,12 +38,16 @@ var (
3738
3839 // contextOverflow recognises a server's refusal of a request larger than its
3940 // window: llama.cpp's `exceed_context_size_error`, the OpenAI API's
40-// `context_length_exceeded`, or a "maximum context length" message. Such a
41-// request fails the same way every time: it is never retried.
41+// `context_length_exceeded`, or a "maximum context length" message — or mm's
42+// own refusal to send one (requestTooBig). Such a request fails the same way
43+// every time: it is never retried.
4244 func contextOverflow(err error) bool {
4345 if err == nil {
4446 return false
4547 }
48+ if tooBig := (*requestTooBig)(nil); errors.As(err, &tooBig) {
49+ return true // mm's own refusal (ticket 291), before the server's
50+ }
4651 msg := err.Error()
4752 return strings.Contains(msg, "exceed_context_size_error") ||
4853 strings.Contains(msg, "context_length_exceeded") ||
@@ -59,7 +64,9 @@ func overflowLine(err error) (string, bool) {
5964 }
6065 msg := err.Error()
6166 what := "the request is larger than the server's context window"
62- if p, n := number(promptTokens, msg), number(servedCtx, msg); p > 0 && n > 0 {
67+ if tooBig := (*requestTooBig)(nil); errors.As(err, &tooBig) {
68+ what = fmt.Sprintf("the request (about %d tokens, even compressed) is larger than the context window (%d), so it was not sent", tooBig.tokens, tooBig.window)
69+ } else if p, n := number(promptTokens, msg), number(servedCtx, msg); p > 0 && n > 0 {
6370 what = fmt.Sprintf("the request (%d tokens) is larger than the server's window (%d)", p, n)
6471 }
6572 return what + " — restart the server with a larger window (--ctx-size for llama.cpp), or lower contextWindow so the conversation is compressed sooner; the work done before is kept: ask to continue", true
@@ -1,6 +1,7 @@
1 package engine1 package engine
2 2
3 import (3 import (
4+ "errors"
4 "fmt"5 "fmt"
5 "regexp"6 "regexp"
6 "strconv"7 "strconv"
@@ -37,12 +38,16 @@ var (
37 38
38 // contextOverflow recognises a server's refusal of a request larger than its39 // contextOverflow recognises a server's refusal of a request larger than its
39 // window: llama.cpp's `exceed_context_size_error`, the OpenAI API's40 // window: llama.cpp's `exceed_context_size_error`, the OpenAI API's
40-// `context_length_exceeded`, or a "maximum context length" message. Such a41+// `context_length_exceeded`, or a "maximum context length" message — or mm's
41-// request fails the same way every time: it is never retried.42+// own refusal to send one (requestTooBig). Such a request fails the same way
43+// every time: it is never retried.
42 func contextOverflow(err error) bool {44 func contextOverflow(err error) bool {
43 if err == nil {45 if err == nil {
44 return false46 return false
45 }47 }
48+ if tooBig := (*requestTooBig)(nil); errors.As(err, &tooBig) {
49+ return true // mm's own refusal (ticket 291), before the server's
50+ }
46 msg := err.Error()51 msg := err.Error()
47 return strings.Contains(msg, "exceed_context_size_error") ||52 return strings.Contains(msg, "exceed_context_size_error") ||
48 strings.Contains(msg, "context_length_exceeded") ||53 strings.Contains(msg, "context_length_exceeded") ||
@@ -59,7 +64,9 @@ func overflowLine(err error) (string, bool) {
59 }64 }
60 msg := err.Error()65 msg := err.Error()
61 what := "the request is larger than the server's context window"66 what := "the request is larger than the server's context window"
62- if p, n := number(promptTokens, msg), number(servedCtx, msg); p > 0 && n > 0 {67+ if tooBig := (*requestTooBig)(nil); errors.As(err, &tooBig) {
68+ what = fmt.Sprintf("the request (about %d tokens, even compressed) is larger than the context window (%d), so it was not sent", tooBig.tokens, tooBig.window)
69+ } else if p, n := number(promptTokens, msg), number(servedCtx, msg); p > 0 && n > 0 {
63 what = fmt.Sprintf("the request (%d tokens) is larger than the server's window (%d)", p, n)70 what = fmt.Sprintf("the request (%d tokens) is larger than the server's window (%d)", p, n)
64 }71 }
65 return what + " — restart the server with a larger window (--ctx-size for llama.cpp), or lower contextWindow so the conversation is compressed sooner; the work done before is kept: ask to continue", true72 return what + " — restart the server with a larger window (--ctx-size for llama.cpp), or lower contextWindow so the conversation is compressed sooner; the work done before is kept: ask to continue", true
modified internal/engine/engine.go +10 -0
@@ -47,10 +47,20 @@ type Engine struct {
4747 // the exact figure the compression trigger prefers over its estimate.
4848 lastInput atomic.Int64
4949
50+ // ratio is the last call's compact.Calibration ratio — the server's
51+ // count over the estimate of the same request — as math.Float64bits
52+ // (ticket 291). Unlike lastInput it survives a compression: it describes
53+ // the tokenizer and the kind of text, not the history's size.
54+ ratio atomic.Uint64
55+
5056 // inTurnProbed: the in-turn compression asked the server for its window
5157 // once already (inturn.go) — never again in this process.
5258 inTurnProbed atomic.Bool
5359
60+ // summaryCutWarned: the "summary was cut" notice was shown once already
61+ // (summarize.go, ticket 292).
62+ summaryCutWarned atomic.Bool
63+
5464 // hooks runs the `hooks:` block (hooks.go). nil — an Engine built by
5565 // hand, in a test — runs none.
5666 hooks *hooks.Runner
@@ -47,10 +47,20 @@ type Engine struct {
47 // the exact figure the compression trigger prefers over its estimate.47 // the exact figure the compression trigger prefers over its estimate.
48 lastInput atomic.Int6448 lastInput atomic.Int64
49 49
50+ // ratio is the last call's compact.Calibration ratio — the server's
51+ // count over the estimate of the same request — as math.Float64bits
52+ // (ticket 291). Unlike lastInput it survives a compression: it describes
53+ // the tokenizer and the kind of text, not the history's size.
54+ ratio atomic.Uint64
55+
50 // inTurnProbed: the in-turn compression asked the server for its window56 // inTurnProbed: the in-turn compression asked the server for its window
51 // once already (inturn.go) — never again in this process.57 // once already (inturn.go) — never again in this process.
52 inTurnProbed atomic.Bool58 inTurnProbed atomic.Bool
53 59
60+ // summaryCutWarned: the "summary was cut" notice was shown once already
61+ // (summarize.go, ticket 292).
62+ summaryCutWarned atomic.Bool
63+
54 // hooks runs the `hooks:` block (hooks.go). nil — an Engine built by64 // hooks runs the `hooks:` block (hooks.go). nil — an Engine built by
55 // hand, in a test — runs none.65 // hand, in a test — runs none.
56 hooks *hooks.Runner66 hooks *hooks.Runner
modified internal/engine/inturn.go +76 -15
@@ -3,6 +3,9 @@ package engine
33 import (
44 "context"
55 "errors"
6+ "fmt"
7+ "math"
8+ "slices"
69
710 "mm/internal/compact"
811 "mm/internal/config"
@@ -12,13 +15,38 @@ import (
1215 "github.com/firebase/genkit/go/ai"
1316 )
1417
18+// compressBeforeCall runs compactInTurn from the turn's second call on —
19+// tools have run. A request it refuses (requestTooBig) is not sent: the
20+// history the turn built so far, compressed or not, is still the session's.
21+func (t *turn) compressBeforeCall(ctx context.Context, params *ai.ModelParams) error {
22+ if !config.Cfg.Context.CompressInTurn || len(params.Request.Messages) <= len(t.messages) {
23+ return nil
24+ }
25+ t.pl.expect()
26+ before := params.Request.Messages
27+ err := t.e.compactInTurn(ctx, params)
28+ if !slices.Equal(before, params.Request.Messages) {
29+ t.reads.compressed() // results were dropped (reread.go)
30+ }
31+ if err != nil {
32+ t.full = slices.Clone(params.Request.Messages)
33+ }
34+ return err
35+}
36+
1537 // compactInTurn makes the turn smaller before a model call when its history
1638 // passed context.threshold (ticket 251, compact.CompactTurn): params'
1739 // messages are replaced, so Genkit builds the next calls from the smaller
1840 // history too, and the session keeps it. Every front end goes through here —
19-// the line mode, the window, -p, ACP. A failure leaves the history as it was:
20-// the call is sent, and the server says whether it fits.
21-func (e *Engine) compactInTurn(ctx context.Context, params *ai.ModelParams) {
41+// the line mode, the window, -p, ACP. A failed compression leaves the history
42+// as it was: the call is sent, and the server says whether it fits.
43+//
44+// The sizes are the estimate scaled by the last measure (calibration, ticket
45+// 291). A request whose calibrated size is still larger than the window
46+// after the compression is not sent: the error ends the turn (the work done
47+// is kept), instead of a request the server reads for minutes, or never
48+// answers — observed with razorbill, 17k tokens on a 16k window.
49+func (e *Engine) compactInTurn(ctx context.Context, params *ai.ModelParams) error {
2250 cfg := config.Cfg.Context
2351 msgs := params.Request.Messages
2452 // -p shows no banner, so the start-up probe never ran: ask the server
@@ -27,10 +55,12 @@ func (e *Engine) compactInTurn(ctx context.Context, params *ai.ModelParams) {
2755 if e.ContextWindow == 0 && e.Provider != nil && !e.inTurnProbed.Swap(true) {
2856 e.EnsureContextWindow(ctx)
2957 }
30- if !compact.InTurnDecide(msgs, e.LastInputTokens(), e.ContextWindow, cfg) {
31- return
58+ cal := e.calibration(params.Request.Tools)
59+ if !compact.InTurnDecide(msgs, e.LastInputTokens(), e.ContextWindow, cal, cfg) {
60+ return nil
3261 }
3362 spinner.Start("Compressing the turn")
63+ defer spinner.Stop()
3464 // A context of its own: the turn's values (its reasoning display, its
3565 // speed meter) must not see the summary request; the turn's end still
3666 // stops it.
@@ -41,20 +71,51 @@ func (e *Engine) compactInTurn(ctx context.Context, params *ai.ModelParams) {
4171 summarize := func(ctx context.Context, req []*ai.Message) (string, error) {
4272 return e.Summarize(ctx, req, max(cfg.SummaryMaxTokens, 512))
4373 }
44- r, err := compact.CompactTurn(sumCtx, msgs, e.ContextWindow, cfg, summarize)
74+ r, err := compact.CompactTurn(sumCtx, msgs, compact.Budget{Window: e.ContextWindow, Threshold: cfg.Threshold, Target: cfg.InTurnTarget, Calibration: cal}, summarize)
4575 switch {
4676 case errors.Is(err, compact.ErrNothingToCompact):
47- return
4877 case err != nil:
4978 ui.Notice("🗜️ in-turn compression failed: " + err.Error())
50- return
79+ return nil
80+ default:
81+ params.Request.Messages = r.Messages
82+ // The server's last count was of the longer history: forgotten, or
83+ // the next decision would compress again on a stale figure. The
84+ // ratio stays.
85+ e.lastInput.Store(0)
86+ // A floor above the threshold is a warning the user can act on:
87+ // shown even without showStats.
88+ if cfg.ShowStats || r.FloorTooHigh {
89+ ui.Notice("🗜️ " + r.Report())
90+ }
5191 }
52- params.Request.Messages = r.Messages
53- // The server's last count was of the longer history: forgotten, or the
54- // next decision would compress again on a stale figure.
55- e.lastInput.Store(0)
56- spinner.Stop()
57- if cfg.ShowStats {
58- ui.Notice("🗜️ " + r.Report())
92+ if tokens := cal.Tokens(params.Request.Messages); tokens > e.ContextWindow {
93+ return &requestTooBig{tokens: tokens, window: e.ContextWindow}
5994 }
95+ return nil
96+}
97+
98+// requestTooBig is the turn's end when even the compressed request is larger
99+// than the window: Explain gives it the overflow line.
100+type requestTooBig struct{ tokens, window int }
101+
102+func (r *requestTooBig) Error() string {
103+ return fmt.Sprintf("the request (about %d tokens) is larger than the context window (%d): not sent", r.tokens, r.window)
104+}
105+
106+// calibrate records the ratio between the server's count and the estimate of
107+// the request it read (compact.Calibrate).
108+func (e *Engine) calibrate(req *ai.ModelRequest, measured int) {
109+ if req == nil {
110+ return
111+ }
112+ estimated := compact.Estimate(req.Messages) + compact.EstimateTools(req.Tools)
113+ c := compact.Calibrate(measured, estimated, 0)
114+ e.ratio.Store(math.Float64bits(c.Ratio))
115+}
116+
117+// calibration is the estimate's scale for a request carrying tools: the
118+// last ratio, or none before the first measured call.
119+func (e *Engine) calibration(tools []*ai.ToolDefinition) compact.Calibration {
120+ return compact.Calibration{Ratio: math.Float64frombits(e.ratio.Load()), Tools: compact.EstimateTools(tools)}
60121 }
@@ -3,6 +3,9 @@ package engine
3 import (3 import (
4 "context"4 "context"
5 "errors"5 "errors"
6+ "fmt"
7+ "math"
8+ "slices"
6 9
7 "mm/internal/compact"10 "mm/internal/compact"
8 "mm/internal/config"11 "mm/internal/config"
@@ -12,13 +15,38 @@ import (
12 "github.com/firebase/genkit/go/ai"15 "github.com/firebase/genkit/go/ai"
13 )16 )
14 17
18+// compressBeforeCall runs compactInTurn from the turn's second call on —
19+// tools have run. A request it refuses (requestTooBig) is not sent: the
20+// history the turn built so far, compressed or not, is still the session's.
21+func (t *turn) compressBeforeCall(ctx context.Context, params *ai.ModelParams) error {
22+ if !config.Cfg.Context.CompressInTurn || len(params.Request.Messages) <= len(t.messages) {
23+ return nil
24+ }
25+ t.pl.expect()
26+ before := params.Request.Messages
27+ err := t.e.compactInTurn(ctx, params)
28+ if !slices.Equal(before, params.Request.Messages) {
29+ t.reads.compressed() // results were dropped (reread.go)
30+ }
31+ if err != nil {
32+ t.full = slices.Clone(params.Request.Messages)
33+ }
34+ return err
35+}
36+
15 // compactInTurn makes the turn smaller before a model call when its history37 // compactInTurn makes the turn smaller before a model call when its history
16 // passed context.threshold (ticket 251, compact.CompactTurn): params'38 // passed context.threshold (ticket 251, compact.CompactTurn): params'
17 // messages are replaced, so Genkit builds the next calls from the smaller39 // messages are replaced, so Genkit builds the next calls from the smaller
18 // history too, and the session keeps it. Every front end goes through here —40 // history too, and the session keeps it. Every front end goes through here —
19-// the line mode, the window, -p, ACP. A failure leaves the history as it was:41+// the line mode, the window, -p, ACP. A failed compression leaves the history
20-// the call is sent, and the server says whether it fits.42+// as it was: the call is sent, and the server says whether it fits.
21-func (e *Engine) compactInTurn(ctx context.Context, params *ai.ModelParams) {43+//
44+// The sizes are the estimate scaled by the last measure (calibration, ticket
45+// 291). A request whose calibrated size is still larger than the window
46+// after the compression is not sent: the error ends the turn (the work done
47+// is kept), instead of a request the server reads for minutes, or never
48+// answers — observed with razorbill, 17k tokens on a 16k window.
49+func (e *Engine) compactInTurn(ctx context.Context, params *ai.ModelParams) error {
22 cfg := config.Cfg.Context50 cfg := config.Cfg.Context
23 msgs := params.Request.Messages51 msgs := params.Request.Messages
24 // -p shows no banner, so the start-up probe never ran: ask the server52 // -p shows no banner, so the start-up probe never ran: ask the server
@@ -27,10 +55,12 @@ func (e *Engine) compactInTurn(ctx context.Context, params *ai.ModelParams) {
27 if e.ContextWindow == 0 && e.Provider != nil && !e.inTurnProbed.Swap(true) {55 if e.ContextWindow == 0 && e.Provider != nil && !e.inTurnProbed.Swap(true) {
28 e.EnsureContextWindow(ctx)56 e.EnsureContextWindow(ctx)
29 }57 }
30- if !compact.InTurnDecide(msgs, e.LastInputTokens(), e.ContextWindow, cfg) {58+ cal := e.calibration(params.Request.Tools)
31- return59+ if !compact.InTurnDecide(msgs, e.LastInputTokens(), e.ContextWindow, cal, cfg) {
60+ return nil
32 }61 }
33 spinner.Start("Compressing the turn")62 spinner.Start("Compressing the turn")
63+ defer spinner.Stop()
34 // A context of its own: the turn's values (its reasoning display, its64 // A context of its own: the turn's values (its reasoning display, its
35 // speed meter) must not see the summary request; the turn's end still65 // speed meter) must not see the summary request; the turn's end still
36 // stops it.66 // stops it.
@@ -41,20 +71,51 @@ func (e *Engine) compactInTurn(ctx context.Context, params *ai.ModelParams) {
41 summarize := func(ctx context.Context, req []*ai.Message) (string, error) {71 summarize := func(ctx context.Context, req []*ai.Message) (string, error) {
42 return e.Summarize(ctx, req, max(cfg.SummaryMaxTokens, 512))72 return e.Summarize(ctx, req, max(cfg.SummaryMaxTokens, 512))
43 }73 }
44- r, err := compact.CompactTurn(sumCtx, msgs, e.ContextWindow, cfg, summarize)74+ r, err := compact.CompactTurn(sumCtx, msgs, compact.Budget{Window: e.ContextWindow, Threshold: cfg.Threshold, Target: cfg.InTurnTarget, Calibration: cal}, summarize)
45 switch {75 switch {
46 case errors.Is(err, compact.ErrNothingToCompact):76 case errors.Is(err, compact.ErrNothingToCompact):
47- return
48 case err != nil:77 case err != nil:
49 ui.Notice("🗜️ in-turn compression failed: " + err.Error())78 ui.Notice("🗜️ in-turn compression failed: " + err.Error())
50- return79+ return nil
80+ default:
81+ params.Request.Messages = r.Messages
82+ // The server's last count was of the longer history: forgotten, or
83+ // the next decision would compress again on a stale figure. The
84+ // ratio stays.
85+ e.lastInput.Store(0)
86+ // A floor above the threshold is a warning the user can act on:
87+ // shown even without showStats.
88+ if cfg.ShowStats || r.FloorTooHigh {
89+ ui.Notice("🗜️ " + r.Report())
90+ }
51 }91 }
52- params.Request.Messages = r.Messages92+ if tokens := cal.Tokens(params.Request.Messages); tokens > e.ContextWindow {
53- // The server's last count was of the longer history: forgotten, or the93+ return &requestTooBig{tokens: tokens, window: e.ContextWindow}
54- // next decision would compress again on a stale figure.
55- e.lastInput.Store(0)
56- spinner.Stop()
57- if cfg.ShowStats {
58- ui.Notice("🗜️ " + r.Report())
59 }94 }
95+ return nil
96+}
97+
98+// requestTooBig is the turn's end when even the compressed request is larger
99+// than the window: Explain gives it the overflow line.
100+type requestTooBig struct{ tokens, window int }
101+
102+func (r *requestTooBig) Error() string {
103+ return fmt.Sprintf("the request (about %d tokens) is larger than the context window (%d): not sent", r.tokens, r.window)
104+}
105+
106+// calibrate records the ratio between the server's count and the estimate of
107+// the request it read (compact.Calibrate).
108+func (e *Engine) calibrate(req *ai.ModelRequest, measured int) {
109+ if req == nil {
110+ return
111+ }
112+ estimated := compact.Estimate(req.Messages) + compact.EstimateTools(req.Tools)
113+ c := compact.Calibrate(measured, estimated, 0)
114+ e.ratio.Store(math.Float64bits(c.Ratio))
115+}
116+
117+// calibration is the estimate's scale for a request carrying tools: the
118+// last ratio, or none before the first measured call.
119+func (e *Engine) calibration(tools []*ai.ToolDefinition) compact.Calibration {
120+ return compact.Calibration{Ratio: math.Float64frombits(e.ratio.Load()), Tools: compact.EstimateTools(tools)}
60 }121 }
modified internal/engine/notes.go +17 -1
@@ -1,6 +1,12 @@
11 package engine
22
3-import "strings"
3+import (
4+ "strings"
5+
6+ "mm/internal/compact"
7+
8+ "github.com/firebase/genkit/go/ai"
9+)
410
511 // argsRetryPrefix opens the note argsRetryNote hands the model in place of a
612 // tool call whose arguments did not parse.
@@ -16,3 +22,13 @@ const argsRetryPrefix = "[mm: "
1622 func IsNote(text string) bool {
1723 return strings.HasPrefix(text, argsRetryPrefix) || strings.HasPrefix(text, blockedPrompt)
1824 }
25+
26+// noteMessage is a note mm hands the model in the user's role, marked as
27+// injected (compact.InjectedNotice): it belongs to the running turn, so the
28+// compaction does not count it as a question of its own (ticket 289).
29+//
30+// msg := noteMessage(argsRetryPrefix + "your last reply was cut off …]")
31+// compact.IsInjected(msg) // true
32+func noteMessage(text string) *ai.Message {
33+ return compact.MarkInjected(ai.NewUserTextMessage(text), compact.InjectedNotice)
34+}
@@ -1,6 +1,12 @@
1 package engine1 package engine
2 2
3-import "strings"3+import (
4+ "strings"
5+
6+ "mm/internal/compact"
7+
8+ "github.com/firebase/genkit/go/ai"
9+)
4 10
5 // argsRetryPrefix opens the note argsRetryNote hands the model in place of a11 // argsRetryPrefix opens the note argsRetryNote hands the model in place of a
6 // tool call whose arguments did not parse.12 // tool call whose arguments did not parse.
@@ -16,3 +22,13 @@ const argsRetryPrefix = "[mm: "
16 func IsNote(text string) bool {22 func IsNote(text string) bool {
17 return strings.HasPrefix(text, argsRetryPrefix) || strings.HasPrefix(text, blockedPrompt)23 return strings.HasPrefix(text, argsRetryPrefix) || strings.HasPrefix(text, blockedPrompt)
18 }24 }
25+
26+// noteMessage is a note mm hands the model in the user's role, marked as
27+// injected (compact.InjectedNotice): it belongs to the running turn, so the
28+// compaction does not count it as a question of its own (ticket 289).
29+//
30+// msg := noteMessage(argsRetryPrefix + "your last reply was cut off …]")
31+// compact.IsInjected(msg) // true
32+func noteMessage(text string) *ai.Message {
33+ return compact.MarkInjected(ai.NewUserTextMessage(text), compact.InjectedNotice)
34+}
modified internal/engine/notes_test.go +23 -1
@@ -1,6 +1,12 @@
11 package engine
22
3-import "testing"
3+import (
4+ "testing"
5+
6+ "mm/internal/compact"
7+
8+ "github.com/firebase/genkit/go/ai"
9+)
410
511 // The notes mm writes into the history are recognised from the very messages
612 // that write them, so a reworded note cannot slip past IsNote.
@@ -21,3 +27,19 @@ func TestIsNoteRecognisesMmOwnMessages(t *testing.T) {
2127 }
2228 }
2329 }
30+
31+// Every note mm hands the model in the user's role is marked as injected, so
32+// the compaction keeps it inside the running turn (ticket 289).
33+func TestNotesAreMarkedInjected(t *testing.T) {
34+ for name, msg := range map[string]*ai.Message{
35+ "args, truncated": argsRetryNote(true),
36+ "args, malformed": argsRetryNote(false),
37+ "cut reply": cutRetryNote(),
38+ "failed edit": failedEditNote("edit_file", "old text not found"),
39+ "loop": loopRetryNote("I will now", 5),
40+ } {
41+ if msg.Metadata[compact.InjectedKey] != compact.InjectedNotice {
42+ t.Errorf("%s: metadata %v, want %s=%s", name, msg.Metadata, compact.InjectedKey, compact.InjectedNotice)
43+ }
44+ }
45+}
@@ -1,6 +1,12 @@
1 package engine1 package engine
2 2
3-import "testing"3+import (
4+ "testing"
5+
6+ "mm/internal/compact"
7+
8+ "github.com/firebase/genkit/go/ai"
9+)
4 10
5 // The notes mm writes into the history are recognised from the very messages11 // The notes mm writes into the history are recognised from the very messages
6 // that write them, so a reworded note cannot slip past IsNote.12 // that write them, so a reworded note cannot slip past IsNote.
@@ -21,3 +27,19 @@ func TestIsNoteRecognisesMmOwnMessages(t *testing.T) {
21 }27 }
22 }28 }
23 }29 }
30+
31+// Every note mm hands the model in the user's role is marked as injected, so
32+// the compaction keeps it inside the running turn (ticket 289).
33+func TestNotesAreMarkedInjected(t *testing.T) {
34+ for name, msg := range map[string]*ai.Message{
35+ "args, truncated": argsRetryNote(true),
36+ "args, malformed": argsRetryNote(false),
37+ "cut reply": cutRetryNote(),
38+ "failed edit": failedEditNote("edit_file", "old text not found"),
39+ "loop": loopRetryNote("I will now", 5),
40+ } {
41+ if msg.Metadata[compact.InjectedKey] != compact.InjectedNotice {
42+ t.Errorf("%s: metadata %v, want %s=%s", name, msg.Metadata, compact.InjectedKey, compact.InjectedNotice)
43+ }
44+ }
45+}
added internal/engine/reread.go +188 -0
new file mode 100644
@@ -0,0 +1,188 @@
1+package engine
2+
3+import (
4+ "context"
5+ "fmt"
6+ "sync"
7+
8+ "mm/internal/config"
9+ "mm/internal/ui"
10+
11+ "github.com/firebase/genkit/go/ai"
12+)
13+
14+// Re-reads (ticket 292). A model whose files do not fit the window reads
15+// them in chunks; by the time it reaches the end, the first chunks were
16+// compressed away, and it starts again. Observed with Inkling-2-Mini on a
17+// 16k window: 40 tool calls, all reads, server.go read four times in the
18+// same `sed -n` ranges. The loop detector sees nothing: four different
19+// commands in a cycle, not one repeated.
20+//
21+// So a tool call identical to one already run in the turn, AFTER a
22+// compression dropped results and with no file changed since, carries a
23+// note in its own result: it was read before, the window cannot hold
24+// everything, write down what matters or start the change. The notes were
25+// read and ignored in the observed session, so past context.rereadLimit
26+// re-reads of the same call (1 by default: the third identical read) the
27+// call is not run at all. The note goes in the tool result, not in a user
28+// message: a user message is a new turn for the compaction (ticket 289).
29+
30+// rereadNote opens the result of a call repeated after a compression.
31+const rereadNote = "[mm: you already ran this exact call earlier in this task, and its result was dropped from the context to make room — the context cannot hold everything you read, and it will drop this again. Do not read everything once more: write down what you need (for example in NOTES.md), or start the change now with what you know.]\n\n"
32+
33+// rereadAgainNote opens the result of the second and later re-reads of a
34+// turn: a gentle note alone was read, acknowledged and ignored six times in
35+// the observed session, so the later ones say plainly what to do.
36+const rereadAgainNote = "[mm: this is re-read number %d in this task — you are reading in circles, and the context keeps dropping what you read. Stop reading. Make the first change now with what you know: create or edit one file (a first version is fine, you will extend it later), and read again only the exact lines that change needs.]\n\n"
37+
38+// rereadNoteFor is the note of the n-th re-read of a turn (n ≥ 1).
39+//
40+// rereadNoteFor(1) // rereadNote
41+// rereadNoteFor(3) // "[mm: this is re-read number 3 in this task — …"
42+func rereadNoteFor(n int) string {
43+ if n <= 1 {
44+ return rereadNote
45+ }
46+ return fmt.Sprintf(rereadAgainNote, n)
47+}
48+
49+// rereadRefusal replaces the result of a call refused by
50+// context.rereadLimit: the call is not run.
51+const rereadRefusal = "[mm: not run — this exact call already ran %d times in this task, and each time the context dropped its result: running it again will not help. Work from your notes and from what is still in the context: make the change now (write or edit a file), or read a different, smaller part (grep -n, a narrower range).]"
52+
53+// writeTools are the tools whose success counts as a change: a call
54+// repeated after one of them (`go test` after an edit) is not a re-read.
55+// A file changed through bash (sed -i, a redirect) is not seen.
56+var writeTools = map[string]bool{"write_file": true, "edit_file": true}
57+
58+// callState is what rereads remembers of one call (tool and arguments).
59+type callState struct {
60+ compressions int // the turn's compressions when it last ran
61+ edits int // the turn's file changes when it last ran
62+ rereads int // the times it was a re-read
63+}
64+
65+// rereads remembers the tool calls of one turn, the compressions and the
66+// file changes between them. Safe for tools run in parallel.
67+type rereads struct {
68+ mu sync.Mutex
69+ seen map[string]*callState
70+ compressions int
71+ edits int
72+ noted int // re-reads noted so far in the turn
73+}
74+
75+// compressed counts one in-turn compression of the turn's history.
76+func (r *rereads) compressed() {
77+ r.mu.Lock()
78+ r.compressions++
79+ r.mu.Unlock()
80+}
81+
82+// changed counts a successful write_file or edit_file.
83+func (r *rereads) changed(req *ai.ToolRequest) {
84+ if req == nil || !writeTools[req.Name] {
85+ return
86+ }
87+ r.mu.Lock()
88+ r.edits++
89+ r.mu.Unlock()
90+}
91+
92+// repeated records req and says whether it is a re-read: the same call
93+// (tool and arguments) ran before in the turn, a compression dropped
94+// results since, and no file was changed since. rank is its rank among
95+// the noted re-reads of the turn (0 = not a re-read, or refused); refused
96+// is true past `limit` re-reads of this call (0 = no limit). A refused
97+// call keeps its state, so asking again at once is refused again.
98+func (r *rereads) repeated(req *ai.ToolRequest, limit int) (rank int, refused int) {
99+ if req == nil {
100+ return 0, 0
101+ }
102+ key := callKey(req.Name, req.Input) // the one toolschema.go counts invalid calls by
103+ r.mu.Lock()
104+ defer r.mu.Unlock()
105+ st := r.state(key)
106+ again := st.compressions < r.compressions && st.edits == r.edits
107+ if again && limit > 0 && st.rereads >= limit {
108+ return 0, st.rereads + 1 // the runs so far: the first, then each re-read
109+ }
110+ st.compressions, st.edits = r.compressions, r.edits
111+ if again {
112+ st.rereads++
113+ r.noted++
114+ rank = r.noted
115+ }
116+ return rank, 0
117+}
118+
119+// state is the call's state, created as of now on its first run (so that
120+// a first run is never a re-read). r.mu is held.
121+func (r *rereads) state(key string) *callState {
122+ if r.seen == nil {
123+ r.seen = map[string]*callState{}
124+ }
125+ st, ok := r.seen[key]
126+ if !ok {
127+ st = &callState{compressions: r.compressions, edits: r.edits}
128+ r.seen[key] = st
129+ }
130+ return st
131+}
132+
133+// toolHook is the shape of a WrapTool hook.
134+type toolHook = func(ctx context.Context, params *ai.ToolParams, next ai.ToolNext) (*ai.MultipartToolResponse, error)
135+
136+// wrap is inner with re-reads handled: a call repeated after a compression
137+// (repeated) gets a note before its result, and past context.rereadLimit
138+// re-reads of the same call it is not run at all — its result says why. A
139+// failed call is left as it is; a successful write_file or edit_file
140+// counts as a change.
141+func (r *rereads) wrap(inner toolHook) toolHook {
142+ return func(ctx context.Context, params *ai.ToolParams, next ai.ToolNext) (*ai.MultipartToolResponse, error) {
143+ rank, refused := r.repeated(params.Request, config.Cfg.Context.RereadLimit)
144+ if refused > 0 {
145+ ui.Notice(fmt.Sprintf("🔁 not run: %s, the same call for the %s time after its result was dropped (context.rereadLimit)", params.Request.Name, ordinal(refused+1)))
146+ return &ai.MultipartToolResponse{Output: fmt.Sprintf(rereadRefusal, refused)}, nil
147+ }
148+ resp, err := inner(ctx, params, next)
149+ if err != nil {
150+ return resp, err
151+ }
152+ r.changed(params.Request)
153+ if rank > 0 {
154+ resp = withRereadNote(resp, rereadNoteFor(rank))
155+ }
156+ return resp, nil
157+ }
158+}
159+
160+// ordinal is n in words for the notice: 3 → "3rd".
161+func ordinal(n int) string {
162+ switch {
163+ case n%100 >= 11 && n%100 <= 13:
164+ return fmt.Sprintf("%dth", n)
165+ case n%10 == 1:
166+ return fmt.Sprintf("%dst", n)
167+ case n%10 == 2:
168+ return fmt.Sprintf("%dnd", n)
169+ case n%10 == 3:
170+ return fmt.Sprintf("%drd", n)
171+ }
172+ return fmt.Sprintf("%dth", n)
173+}
174+
175+// withRereadNote is resp with note before a text output; other outputs
176+// are returned as they are.
177+func withRereadNote(resp *ai.MultipartToolResponse, note string) *ai.MultipartToolResponse {
178+ if resp == nil {
179+ return resp
180+ }
181+ text, ok := resp.Output.(string)
182+ if !ok {
183+ return resp
184+ }
185+ out := *resp
186+ out.Output = note + text
187+ return &out
188+}
new file mode 100644
@@ -0,0 +1,188 @@
1+package engine
2+
3+import (
4+ "context"
5+ "fmt"
6+ "sync"
7+
8+ "mm/internal/config"
9+ "mm/internal/ui"
10+
11+ "github.com/firebase/genkit/go/ai"
12+)
13+
14+// Re-reads (ticket 292). A model whose files do not fit the window reads
15+// them in chunks; by the time it reaches the end, the first chunks were
16+// compressed away, and it starts again. Observed with Inkling-2-Mini on a
17+// 16k window: 40 tool calls, all reads, server.go read four times in the
18+// same `sed -n` ranges. The loop detector sees nothing: four different
19+// commands in a cycle, not one repeated.
20+//
21+// So a tool call identical to one already run in the turn, AFTER a
22+// compression dropped results and with no file changed since, carries a
23+// note in its own result: it was read before, the window cannot hold
24+// everything, write down what matters or start the change. The notes were
25+// read and ignored in the observed session, so past context.rereadLimit
26+// re-reads of the same call (1 by default: the third identical read) the
27+// call is not run at all. The note goes in the tool result, not in a user
28+// message: a user message is a new turn for the compaction (ticket 289).
29+
30+// rereadNote opens the result of a call repeated after a compression.
31+const rereadNote = "[mm: you already ran this exact call earlier in this task, and its result was dropped from the context to make room — the context cannot hold everything you read, and it will drop this again. Do not read everything once more: write down what you need (for example in NOTES.md), or start the change now with what you know.]\n\n"
32+
33+// rereadAgainNote opens the result of the second and later re-reads of a
34+// turn: a gentle note alone was read, acknowledged and ignored six times in
35+// the observed session, so the later ones say plainly what to do.
36+const rereadAgainNote = "[mm: this is re-read number %d in this task — you are reading in circles, and the context keeps dropping what you read. Stop reading. Make the first change now with what you know: create or edit one file (a first version is fine, you will extend it later), and read again only the exact lines that change needs.]\n\n"
37+
38+// rereadNoteFor is the note of the n-th re-read of a turn (n ≥ 1).
39+//
40+// rereadNoteFor(1) // rereadNote
41+// rereadNoteFor(3) // "[mm: this is re-read number 3 in this task — …"
42+func rereadNoteFor(n int) string {
43+ if n <= 1 {
44+ return rereadNote
45+ }
46+ return fmt.Sprintf(rereadAgainNote, n)
47+}
48+
49+// rereadRefusal replaces the result of a call refused by
50+// context.rereadLimit: the call is not run.
51+const rereadRefusal = "[mm: not run — this exact call already ran %d times in this task, and each time the context dropped its result: running it again will not help. Work from your notes and from what is still in the context: make the change now (write or edit a file), or read a different, smaller part (grep -n, a narrower range).]"
52+
53+// writeTools are the tools whose success counts as a change: a call
54+// repeated after one of them (`go test` after an edit) is not a re-read.
55+// A file changed through bash (sed -i, a redirect) is not seen.
56+var writeTools = map[string]bool{"write_file": true, "edit_file": true}
57+
58+// callState is what rereads remembers of one call (tool and arguments).
59+type callState struct {
60+ compressions int // the turn's compressions when it last ran
61+ edits int // the turn's file changes when it last ran
62+ rereads int // the times it was a re-read
63+}
64+
65+// rereads remembers the tool calls of one turn, the compressions and the
66+// file changes between them. Safe for tools run in parallel.
67+type rereads struct {
68+ mu sync.Mutex
69+ seen map[string]*callState
70+ compressions int
71+ edits int
72+ noted int // re-reads noted so far in the turn
73+}
74+
75+// compressed counts one in-turn compression of the turn's history.
76+func (r *rereads) compressed() {
77+ r.mu.Lock()
78+ r.compressions++
79+ r.mu.Unlock()
80+}
81+
82+// changed counts a successful write_file or edit_file.
83+func (r *rereads) changed(req *ai.ToolRequest) {
84+ if req == nil || !writeTools[req.Name] {
85+ return
86+ }
87+ r.mu.Lock()
88+ r.edits++
89+ r.mu.Unlock()
90+}
91+
92+// repeated records req and says whether it is a re-read: the same call
93+// (tool and arguments) ran before in the turn, a compression dropped
94+// results since, and no file was changed since. rank is its rank among
95+// the noted re-reads of the turn (0 = not a re-read, or refused); refused
96+// is true past `limit` re-reads of this call (0 = no limit). A refused
97+// call keeps its state, so asking again at once is refused again.
98+func (r *rereads) repeated(req *ai.ToolRequest, limit int) (rank int, refused int) {
99+ if req == nil {
100+ return 0, 0
101+ }
102+ key := callKey(req.Name, req.Input) // the one toolschema.go counts invalid calls by
103+ r.mu.Lock()
104+ defer r.mu.Unlock()
105+ st := r.state(key)
106+ again := st.compressions < r.compressions && st.edits == r.edits
107+ if again && limit > 0 && st.rereads >= limit {
108+ return 0, st.rereads + 1 // the runs so far: the first, then each re-read
109+ }
110+ st.compressions, st.edits = r.compressions, r.edits
111+ if again {
112+ st.rereads++
113+ r.noted++
114+ rank = r.noted
115+ }
116+ return rank, 0
117+}
118+
119+// state is the call's state, created as of now on its first run (so that
120+// a first run is never a re-read). r.mu is held.
121+func (r *rereads) state(key string) *callState {
122+ if r.seen == nil {
123+ r.seen = map[string]*callState{}
124+ }
125+ st, ok := r.seen[key]
126+ if !ok {
127+ st = &callState{compressions: r.compressions, edits: r.edits}
128+ r.seen[key] = st
129+ }
130+ return st
131+}
132+
133+// toolHook is the shape of a WrapTool hook.
134+type toolHook = func(ctx context.Context, params *ai.ToolParams, next ai.ToolNext) (*ai.MultipartToolResponse, error)
135+
136+// wrap is inner with re-reads handled: a call repeated after a compression
137+// (repeated) gets a note before its result, and past context.rereadLimit
138+// re-reads of the same call it is not run at all — its result says why. A
139+// failed call is left as it is; a successful write_file or edit_file
140+// counts as a change.
141+func (r *rereads) wrap(inner toolHook) toolHook {
142+ return func(ctx context.Context, params *ai.ToolParams, next ai.ToolNext) (*ai.MultipartToolResponse, error) {
143+ rank, refused := r.repeated(params.Request, config.Cfg.Context.RereadLimit)
144+ if refused > 0 {
145+ ui.Notice(fmt.Sprintf("🔁 not run: %s, the same call for the %s time after its result was dropped (context.rereadLimit)", params.Request.Name, ordinal(refused+1)))
146+ return &ai.MultipartToolResponse{Output: fmt.Sprintf(rereadRefusal, refused)}, nil
147+ }
148+ resp, err := inner(ctx, params, next)
149+ if err != nil {
150+ return resp, err
151+ }
152+ r.changed(params.Request)
153+ if rank > 0 {
154+ resp = withRereadNote(resp, rereadNoteFor(rank))
155+ }
156+ return resp, nil
157+ }
158+}
159+
160+// ordinal is n in words for the notice: 3 → "3rd".
161+func ordinal(n int) string {
162+ switch {
163+ case n%100 >= 11 && n%100 <= 13:
164+ return fmt.Sprintf("%dth", n)
165+ case n%10 == 1:
166+ return fmt.Sprintf("%dst", n)
167+ case n%10 == 2:
168+ return fmt.Sprintf("%dnd", n)
169+ case n%10 == 3:
170+ return fmt.Sprintf("%drd", n)
171+ }
172+ return fmt.Sprintf("%dth", n)
173+}
174+
175+// withRereadNote is resp with note before a text output; other outputs
176+// are returned as they are.
177+func withRereadNote(resp *ai.MultipartToolResponse, note string) *ai.MultipartToolResponse {
178+ if resp == nil {
179+ return resp
180+ }
181+ text, ok := resp.Output.(string)
182+ if !ok {
183+ return resp
184+ }
185+ out := *resp
186+ out.Output = note + text
187+ return &out
188+}
added internal/engine/reread_test.go +249 -0
new file mode 100644
@@ -0,0 +1,249 @@
1+package engine
2+
3+import (
4+ "context"
5+ "fmt"
6+ "strings"
7+ "testing"
8+
9+ "mm/internal/compact"
10+ "mm/internal/config"
11+
12+ "github.com/firebase/genkit/go/ai"
13+ "github.com/firebase/genkit/go/genkit"
14+)
15+
16+func catRequest(path string) *ai.ToolRequest {
17+ return &ai.ToolRequest{Name: "bash", Input: map[string]any{"command": "sed -n '1,120p' " + path}}
18+}
19+
20+func TestRereadsAfterACompressionOnly(t *testing.T) {
21+ var r rereads
22+ rank := func(req *ai.ToolRequest) int {
23+ n, _ := r.repeated(req, 0)
24+ return n
25+ }
26+ if rank(catRequest("a.go")) != 0 {
27+ t.Error("first call: not a re-read")
28+ }
29+ if rank(catRequest("a.go")) != 0 {
30+ t.Error("repeated without a compression in between: no note (nothing was dropped)")
31+ }
32+ r.compressed()
33+ if rank(catRequest("b.go")) != 0 {
34+ t.Error("a new call after a compression: not a re-read")
35+ }
36+ if rank(catRequest("a.go")) != 1 {
37+ t.Error("the same call after a compression: re-read number 1")
38+ }
39+ if rank(catRequest("a.go")) != 0 {
40+ t.Error("once noted, the next repeat without a compression gets no note")
41+ }
42+ r.compressed()
43+ if n := rank(catRequest("b.go")); n != 2 {
44+ t.Errorf("second re-read of the turn: rank %d, want 2", n)
45+ }
46+ if rank(nil) != 0 {
47+ t.Error("nil request")
48+ }
49+}
50+
51+// A file changed since the last run: running the call again is checking
52+// the change (`go test` after an edit), not a re-read.
53+func TestRereadsIgnoreACallAfterAChange(t *testing.T) {
54+ var r rereads
55+ test := &ai.ToolRequest{Name: "bash", Input: map[string]any{"command": "go test ./..."}}
56+ r.repeated(test, 1)
57+ r.compressed()
58+ r.changed(&ai.ToolRequest{Name: "edit_file"})
59+ if n, refused := r.repeated(test, 1); n != 0 || refused != 0 {
60+ t.Errorf("after an edit: rank %d, refused %d, want neither", n, refused)
61+ }
62+ r.changed(&ai.ToolRequest{Name: "bash"}) // not a change mm can see
63+ r.compressed()
64+ if n, _ := r.repeated(test, 1); n != 1 {
65+ t.Errorf("no edit since: rank %d, want 1", n)
66+ }
67+}
68+
69+// context.rereadLimit 1: the third identical read is refused, and asking
70+// again at once is refused again; 0 never refuses.
71+func TestRereadLimit(t *testing.T) {
72+ var r rereads
73+ read := catRequest("server.go")
74+ r.repeated(read, 1) // 1st read
75+ r.compressed()
76+ if n, refused := r.repeated(read, 1); n != 1 || refused != 0 {
77+ t.Fatalf("2nd read: rank %d, refused %d — want a noted re-read", n, refused)
78+ }
79+ r.compressed()
80+ if _, refused := r.repeated(read, 1); refused != 2 {
81+ t.Errorf("3rd read: refused %d, want 2 (runs so far)", refused)
82+ }
83+ if _, refused := r.repeated(read, 1); refused != 2 {
84+ t.Errorf("asked again at once: refused %d, want refused again", refused)
85+ }
86+
87+ var unlimited rereads
88+ unlimited.repeated(read, 0)
89+ for range 5 {
90+ unlimited.compressed()
91+ if _, refused := unlimited.repeated(read, 0); refused != 0 {
92+ t.Fatal("rereadLimit 0 refused a call")
93+ }
94+ }
95+}
96+
97+func TestOrdinal(t *testing.T) {
98+ for n, want := range map[int]string{1: "1st", 2: "2nd", 3: "3rd", 4: "4th", 11: "11th", 12: "12th", 13: "13th", 21: "21st", 22: "22nd"} {
99+ if got := ordinal(n); got != want {
100+ t.Errorf("ordinal(%d) = %q, want %q", n, got, want)
101+ }
102+ }
103+}
104+
105+// The first re-read gets the gentle note; the later ones say to stop
106+// reading and make a change.
107+func TestRereadNoteEscalates(t *testing.T) {
108+ if rereadNoteFor(1) != rereadNote {
109+ t.Error("first re-read: the gentle note")
110+ }
111+ if got := rereadNoteFor(3); !strings.Contains(got, "re-read number 3") || !strings.Contains(got, "Stop reading") {
112+ t.Errorf("third re-read: %q", got)
113+ }
114+}
115+
116+func TestWithRereadNote(t *testing.T) {
117+ got := withRereadNote(&ai.MultipartToolResponse{Output: "package server"}, rereadNote)
118+ if s, _ := got.Output.(string); !strings.HasPrefix(s, rereadNote) || !strings.HasSuffix(s, "package server") {
119+ t.Errorf("output %q", got.Output)
120+ }
121+ structured := &ai.MultipartToolResponse{Output: map[string]any{"ok": true}}
122+ if withRereadNote(structured, rereadNote) != structured {
123+ t.Error("a structured output must be left alone")
124+ }
125+ if withRereadNote(nil, rereadNote) != nil {
126+ t.Error("nil")
127+ }
128+}
129+
130+// End to end: a model that reads six files in a cycle on a small window.
131+// The second round of reads, after compressions, carries the note; the
132+// first round does not.
133+func TestGenerateNotesAReadRepeatedAfterACompression(t *testing.T) {
134+ saved := config.Cfg
135+ t.Cleanup(func() { config.Cfg = saved })
136+ config.Cfg.Context.CompressInTurn = true
137+ config.Cfg.Context.Threshold = 75
138+ config.Cfg.Context.RereadLimit = 0
139+ config.Cfg.MaxTurns = 20
140+
141+ big := strings.Repeat("a line of the file\n", 120)
142+ g := genkit.Init(context.Background())
143+ calls := 0
144+ genkit.DefineModelAction(g, "dmr/"+config.Cfg.Model,
145+ &ai.ModelOptions{Supports: &ai.ModelSupports{Tools: true, Multiturn: true, SystemRole: true}},
146+ func(_ context.Context, r *ai.ModelRequest, _ any, _ ai.ModelStreamCallback) (*ai.ModelResponse, error) {
147+ if len(r.Tools) == 0 {
148+ return modelTurn(ai.NewTextPart("- read some files")), nil
149+ }
150+ calls++
151+ if calls > 12 {
152+ return modelTurn(ai.NewTextPart("done")), nil
153+ }
154+ return modelTurn(ai.NewToolRequestPart(&ai.ToolRequest{Name: "cat", Ref: fmt.Sprint(calls),
155+ Input: map[string]any{"path": fmt.Sprintf("f%d", (calls-1)%6)}})), nil
156+ })
157+ genkit.DefineTool(g, "cat", "print a file", func(_ *ai.ToolContext, in struct {
158+ Path string `json:"path"`
159+ }) (string, error) {
160+ return in.Path + "\n" + big, nil
161+ })
162+ e := testEngine(g)
163+ e.ContextWindow = 4000
164+ _, full, err := e.Generate(context.Background(),
165+ []*ai.Message{ai.NewSystemTextMessage("system"), ai.NewUserTextMessage("read the files")},
166+ []ai.ToolRef{ai.ToolName("cat")})
167+ if err != nil && !contextOverflow(err) {
168+ t.Fatalf("Generate: %v", err)
169+ }
170+ if err := compact.Valid(full); err != nil {
171+ t.Fatal(err)
172+ }
173+ noted := 0
174+ for _, m := range full {
175+ for _, p := range m.Content {
176+ if !p.IsToolResponse() || p.ToolResponse == nil {
177+ continue
178+ }
179+ if out := fmt.Sprint(p.ToolResponse.Output); strings.HasPrefix(out, "[mm: you already ran") || strings.HasPrefix(out, "[mm: this is re-read number") {
180+ noted++
181+ if p.ToolResponse.Ref <= "6" && len(p.ToolResponse.Ref) == 1 {
182+ t.Errorf("call %s is in the first round: no note expected", p.ToolResponse.Ref)
183+ }
184+ }
185+ }
186+ }
187+ if noted == 0 {
188+ t.Error("no re-read was noted in the second round")
189+ }
190+}
191+
192+// End to end: three rounds of the same six reads with rereadLimit 1. The
193+// third round is not run: its results are the refusal.
194+func TestGenerateRefusesTheThirdIdenticalRead(t *testing.T) {
195+ saved := config.Cfg
196+ t.Cleanup(func() { config.Cfg = saved })
197+ config.Cfg.Context.CompressInTurn = true
198+ config.Cfg.Context.Threshold = 75
199+ config.Cfg.Context.RereadLimit = 1
200+ config.Cfg.MaxTurns = 30
201+
202+ big := strings.Repeat("a line of the file\n", 120)
203+ g := genkit.Init(context.Background())
204+ calls, ran := 0, 0
205+ genkit.DefineModelAction(g, "dmr/"+config.Cfg.Model,
206+ &ai.ModelOptions{Supports: &ai.ModelSupports{Tools: true, Multiturn: true, SystemRole: true}},
207+ func(_ context.Context, r *ai.ModelRequest, _ any, _ ai.ModelStreamCallback) (*ai.ModelResponse, error) {
208+ if len(r.Tools) == 0 {
209+ return modelTurn(ai.NewTextPart("- read some files")), nil
210+ }
211+ calls++
212+ if calls > 18 {
213+ return modelTurn(ai.NewTextPart("done")), nil
214+ }
215+ return modelTurn(ai.NewToolRequestPart(&ai.ToolRequest{Name: "cat", Ref: fmt.Sprint(calls),
216+ Input: map[string]any{"path": fmt.Sprintf("f%d", (calls-1)%6)}})), nil
217+ })
218+ genkit.DefineTool(g, "cat", "print a file", func(_ *ai.ToolContext, in struct {
219+ Path string `json:"path"`
220+ }) (string, error) {
221+ ran++
222+ return in.Path + "\n" + big, nil
223+ })
224+ e := testEngine(g)
225+ e.ContextWindow = 4000
226+ _, full, err := e.Generate(context.Background(),
227+ []*ai.Message{ai.NewSystemTextMessage("system"), ai.NewUserTextMessage("read the files")},
228+ []ai.ToolRef{ai.ToolName("cat")})
229+ if err != nil && !contextOverflow(err) {
230+ t.Fatalf("Generate: %v", err)
231+ }
232+ if err := compact.Valid(full); err != nil {
233+ t.Fatal(err)
234+ }
235+ if ran >= 18 {
236+ t.Errorf("the tool ran %d times for 18 calls: nothing was refused", ran)
237+ }
238+ refused := 0
239+ for _, m := range full {
240+ for _, p := range m.Content {
241+ if p.IsToolResponse() && p.ToolResponse != nil && strings.HasPrefix(fmt.Sprint(p.ToolResponse.Output), "[mm: not run") {
242+ refused++
243+ }
244+ }
245+ }
246+ if refused == 0 {
247+ t.Error("no refusal in the history")
248+ }
249+}
new file mode 100644
@@ -0,0 +1,249 @@
1+package engine
2+
3+import (
4+ "context"
5+ "fmt"
6+ "strings"
7+ "testing"
8+
9+ "mm/internal/compact"
10+ "mm/internal/config"
11+
12+ "github.com/firebase/genkit/go/ai"
13+ "github.com/firebase/genkit/go/genkit"
14+)
15+
16+func catRequest(path string) *ai.ToolRequest {
17+ return &ai.ToolRequest{Name: "bash", Input: map[string]any{"command": "sed -n '1,120p' " + path}}
18+}
19+
20+func TestRereadsAfterACompressionOnly(t *testing.T) {
21+ var r rereads
22+ rank := func(req *ai.ToolRequest) int {
23+ n, _ := r.repeated(req, 0)
24+ return n
25+ }
26+ if rank(catRequest("a.go")) != 0 {
27+ t.Error("first call: not a re-read")
28+ }
29+ if rank(catRequest("a.go")) != 0 {
30+ t.Error("repeated without a compression in between: no note (nothing was dropped)")
31+ }
32+ r.compressed()
33+ if rank(catRequest("b.go")) != 0 {
34+ t.Error("a new call after a compression: not a re-read")
35+ }
36+ if rank(catRequest("a.go")) != 1 {
37+ t.Error("the same call after a compression: re-read number 1")
38+ }
39+ if rank(catRequest("a.go")) != 0 {
40+ t.Error("once noted, the next repeat without a compression gets no note")
41+ }
42+ r.compressed()
43+ if n := rank(catRequest("b.go")); n != 2 {
44+ t.Errorf("second re-read of the turn: rank %d, want 2", n)
45+ }
46+ if rank(nil) != 0 {
47+ t.Error("nil request")
48+ }
49+}
50+
51+// A file changed since the last run: running the call again is checking
52+// the change (`go test` after an edit), not a re-read.
53+func TestRereadsIgnoreACallAfterAChange(t *testing.T) {
54+ var r rereads
55+ test := &ai.ToolRequest{Name: "bash", Input: map[string]any{"command": "go test ./..."}}
56+ r.repeated(test, 1)
57+ r.compressed()
58+ r.changed(&ai.ToolRequest{Name: "edit_file"})
59+ if n, refused := r.repeated(test, 1); n != 0 || refused != 0 {
60+ t.Errorf("after an edit: rank %d, refused %d, want neither", n, refused)
61+ }
62+ r.changed(&ai.ToolRequest{Name: "bash"}) // not a change mm can see
63+ r.compressed()
64+ if n, _ := r.repeated(test, 1); n != 1 {
65+ t.Errorf("no edit since: rank %d, want 1", n)
66+ }
67+}
68+
69+// context.rereadLimit 1: the third identical read is refused, and asking
70+// again at once is refused again; 0 never refuses.
71+func TestRereadLimit(t *testing.T) {
72+ var r rereads
73+ read := catRequest("server.go")
74+ r.repeated(read, 1) // 1st read
75+ r.compressed()
76+ if n, refused := r.repeated(read, 1); n != 1 || refused != 0 {
77+ t.Fatalf("2nd read: rank %d, refused %d — want a noted re-read", n, refused)
78+ }
79+ r.compressed()
80+ if _, refused := r.repeated(read, 1); refused != 2 {
81+ t.Errorf("3rd read: refused %d, want 2 (runs so far)", refused)
82+ }
83+ if _, refused := r.repeated(read, 1); refused != 2 {
84+ t.Errorf("asked again at once: refused %d, want refused again", refused)
85+ }
86+
87+ var unlimited rereads
88+ unlimited.repeated(read, 0)
89+ for range 5 {
90+ unlimited.compressed()
91+ if _, refused := unlimited.repeated(read, 0); refused != 0 {
92+ t.Fatal("rereadLimit 0 refused a call")
93+ }
94+ }
95+}
96+
97+func TestOrdinal(t *testing.T) {
98+ for n, want := range map[int]string{1: "1st", 2: "2nd", 3: "3rd", 4: "4th", 11: "11th", 12: "12th", 13: "13th", 21: "21st", 22: "22nd"} {
99+ if got := ordinal(n); got != want {
100+ t.Errorf("ordinal(%d) = %q, want %q", n, got, want)
101+ }
102+ }
103+}
104+
105+// The first re-read gets the gentle note; the later ones say to stop
106+// reading and make a change.
107+func TestRereadNoteEscalates(t *testing.T) {
108+ if rereadNoteFor(1) != rereadNote {
109+ t.Error("first re-read: the gentle note")
110+ }
111+ if got := rereadNoteFor(3); !strings.Contains(got, "re-read number 3") || !strings.Contains(got, "Stop reading") {
112+ t.Errorf("third re-read: %q", got)
113+ }
114+}
115+
116+func TestWithRereadNote(t *testing.T) {
117+ got := withRereadNote(&ai.MultipartToolResponse{Output: "package server"}, rereadNote)
118+ if s, _ := got.Output.(string); !strings.HasPrefix(s, rereadNote) || !strings.HasSuffix(s, "package server") {
119+ t.Errorf("output %q", got.Output)
120+ }
121+ structured := &ai.MultipartToolResponse{Output: map[string]any{"ok": true}}
122+ if withRereadNote(structured, rereadNote) != structured {
123+ t.Error("a structured output must be left alone")
124+ }
125+ if withRereadNote(nil, rereadNote) != nil {
126+ t.Error("nil")
127+ }
128+}
129+
130+// End to end: a model that reads six files in a cycle on a small window.
131+// The second round of reads, after compressions, carries the note; the
132+// first round does not.
133+func TestGenerateNotesAReadRepeatedAfterACompression(t *testing.T) {
134+ saved := config.Cfg
135+ t.Cleanup(func() { config.Cfg = saved })
136+ config.Cfg.Context.CompressInTurn = true
137+ config.Cfg.Context.Threshold = 75
138+ config.Cfg.Context.RereadLimit = 0
139+ config.Cfg.MaxTurns = 20
140+
141+ big := strings.Repeat("a line of the file\n", 120)
142+ g := genkit.Init(context.Background())
143+ calls := 0
144+ genkit.DefineModelAction(g, "dmr/"+config.Cfg.Model,
145+ &ai.ModelOptions{Supports: &ai.ModelSupports{Tools: true, Multiturn: true, SystemRole: true}},
146+ func(_ context.Context, r *ai.ModelRequest, _ any, _ ai.ModelStreamCallback) (*ai.ModelResponse, error) {
147+ if len(r.Tools) == 0 {
148+ return modelTurn(ai.NewTextPart("- read some files")), nil
149+ }
150+ calls++
151+ if calls > 12 {
152+ return modelTurn(ai.NewTextPart("done")), nil
153+ }
154+ return modelTurn(ai.NewToolRequestPart(&ai.ToolRequest{Name: "cat", Ref: fmt.Sprint(calls),
155+ Input: map[string]any{"path": fmt.Sprintf("f%d", (calls-1)%6)}})), nil
156+ })
157+ genkit.DefineTool(g, "cat", "print a file", func(_ *ai.ToolContext, in struct {
158+ Path string `json:"path"`
159+ }) (string, error) {
160+ return in.Path + "\n" + big, nil
161+ })
162+ e := testEngine(g)
163+ e.ContextWindow = 4000
164+ _, full, err := e.Generate(context.Background(),
165+ []*ai.Message{ai.NewSystemTextMessage("system"), ai.NewUserTextMessage("read the files")},
166+ []ai.ToolRef{ai.ToolName("cat")})
167+ if err != nil && !contextOverflow(err) {
168+ t.Fatalf("Generate: %v", err)
169+ }
170+ if err := compact.Valid(full); err != nil {
171+ t.Fatal(err)
172+ }
173+ noted := 0
174+ for _, m := range full {
175+ for _, p := range m.Content {
176+ if !p.IsToolResponse() || p.ToolResponse == nil {
177+ continue
178+ }
179+ if out := fmt.Sprint(p.ToolResponse.Output); strings.HasPrefix(out, "[mm: you already ran") || strings.HasPrefix(out, "[mm: this is re-read number") {
180+ noted++
181+ if p.ToolResponse.Ref <= "6" && len(p.ToolResponse.Ref) == 1 {
182+ t.Errorf("call %s is in the first round: no note expected", p.ToolResponse.Ref)
183+ }
184+ }
185+ }
186+ }
187+ if noted == 0 {
188+ t.Error("no re-read was noted in the second round")
189+ }
190+}
191+
192+// End to end: three rounds of the same six reads with rereadLimit 1. The
193+// third round is not run: its results are the refusal.
194+func TestGenerateRefusesTheThirdIdenticalRead(t *testing.T) {
195+ saved := config.Cfg
196+ t.Cleanup(func() { config.Cfg = saved })
197+ config.Cfg.Context.CompressInTurn = true
198+ config.Cfg.Context.Threshold = 75
199+ config.Cfg.Context.RereadLimit = 1
200+ config.Cfg.MaxTurns = 30
201+
202+ big := strings.Repeat("a line of the file\n", 120)
203+ g := genkit.Init(context.Background())
204+ calls, ran := 0, 0
205+ genkit.DefineModelAction(g, "dmr/"+config.Cfg.Model,
206+ &ai.ModelOptions{Supports: &ai.ModelSupports{Tools: true, Multiturn: true, SystemRole: true}},
207+ func(_ context.Context, r *ai.ModelRequest, _ any, _ ai.ModelStreamCallback) (*ai.ModelResponse, error) {
208+ if len(r.Tools) == 0 {
209+ return modelTurn(ai.NewTextPart("- read some files")), nil
210+ }
211+ calls++
212+ if calls > 18 {
213+ return modelTurn(ai.NewTextPart("done")), nil
214+ }
215+ return modelTurn(ai.NewToolRequestPart(&ai.ToolRequest{Name: "cat", Ref: fmt.Sprint(calls),
216+ Input: map[string]any{"path": fmt.Sprintf("f%d", (calls-1)%6)}})), nil
217+ })
218+ genkit.DefineTool(g, "cat", "print a file", func(_ *ai.ToolContext, in struct {
219+ Path string `json:"path"`
220+ }) (string, error) {
221+ ran++
222+ return in.Path + "\n" + big, nil
223+ })
224+ e := testEngine(g)
225+ e.ContextWindow = 4000
226+ _, full, err := e.Generate(context.Background(),
227+ []*ai.Message{ai.NewSystemTextMessage("system"), ai.NewUserTextMessage("read the files")},
228+ []ai.ToolRef{ai.ToolName("cat")})
229+ if err != nil && !contextOverflow(err) {
230+ t.Fatalf("Generate: %v", err)
231+ }
232+ if err := compact.Valid(full); err != nil {
233+ t.Fatal(err)
234+ }
235+ if ran >= 18 {
236+ t.Errorf("the tool ran %d times for 18 calls: nothing was refused", ran)
237+ }
238+ refused := 0
239+ for _, m := range full {
240+ for _, p := range m.Content {
241+ if p.IsToolResponse() && p.ToolResponse != nil && strings.HasPrefix(fmt.Sprint(p.ToolResponse.Output), "[mm: not run") {
242+ refused++
243+ }
244+ }
245+ }
246+ if refused == 0 {
247+ t.Error("no refusal in the history")
248+ }
249+}
modified internal/engine/steer.go +5 -2
@@ -5,6 +5,8 @@ import (
55 "strings"
66 "sync"
77
8+ "mm/internal/compact"
9+
810 "github.com/firebase/genkit/go/ai"
911 )
1012
@@ -99,14 +101,15 @@ func steerInbox(ctx context.Context) *Inbox {
99101 // call — and after the model's own text — nothing is taken: a user message
100102 // right after the question, or right after an answer, is not what the
101103 // chat templates expect; the message waits for the next tool round, or for
102-// the end of the turn (Close).
104+// the end of the turn (Close). They are marked compact.InjectedSteer: part
105+// of the running turn, not a new question for the compaction (ticket 289).
103106 func takeSteer(ctx context.Context, msgs []*ai.Message) []*ai.Message {
104107 b := steerInbox(ctx)
105108 if b == nil || len(msgs) == 0 || msgs[len(msgs)-1].Role != ai.RoleTool {
106109 return msgs
107110 }
108111 for _, text := range b.take() {
109- msgs = append(msgs, ai.NewUserTextMessage(SteerLabel+" "+text))
112+ msgs = append(msgs, compact.MarkInjected(ai.NewUserTextMessage(SteerLabel+" "+text), compact.InjectedSteer))
110113 if b.taken != nil {
111114 b.taken(text)
112115 }
@@ -5,6 +5,8 @@ import (
5 "strings"5 "strings"
6 "sync"6 "sync"
7 7
8+ "mm/internal/compact"
9+
8 "github.com/firebase/genkit/go/ai"10 "github.com/firebase/genkit/go/ai"
9 )11 )
10 12
@@ -99,14 +101,15 @@ func steerInbox(ctx context.Context) *Inbox {
99 // call — and after the model's own text — nothing is taken: a user message101 // call — and after the model's own text — nothing is taken: a user message
100 // right after the question, or right after an answer, is not what the102 // right after the question, or right after an answer, is not what the
101 // chat templates expect; the message waits for the next tool round, or for103 // chat templates expect; the message waits for the next tool round, or for
102-// the end of the turn (Close).104+// the end of the turn (Close). They are marked compact.InjectedSteer: part
105+// of the running turn, not a new question for the compaction (ticket 289).
103 func takeSteer(ctx context.Context, msgs []*ai.Message) []*ai.Message {106 func takeSteer(ctx context.Context, msgs []*ai.Message) []*ai.Message {
104 b := steerInbox(ctx)107 b := steerInbox(ctx)
105 if b == nil || len(msgs) == 0 || msgs[len(msgs)-1].Role != ai.RoleTool {108 if b == nil || len(msgs) == 0 || msgs[len(msgs)-1].Role != ai.RoleTool {
106 return msgs109 return msgs
107 }110 }
108 for _, text := range b.take() {111 for _, text := range b.take() {
109- msgs = append(msgs, ai.NewUserTextMessage(SteerLabel+" "+text))112+ msgs = append(msgs, compact.MarkInjected(ai.NewUserTextMessage(SteerLabel+" "+text), compact.InjectedSteer))
110 if b.taken != nil {113 if b.taken != nil {
111 b.taken(text)114 b.taken(text)
112 }115 }
modified internal/engine/steer_test.go +8 -0
@@ -101,6 +101,14 @@ func TestSteerReachesTheNextModelCall(t *testing.T) {
101101 if err := compact.Valid(full); err != nil {
102102 t.Errorf("history: %v", err)
103103 }
104+ // Marked as part of the running turn (ticket 289): the history is still
105+ // one question turn for the compaction.
106+ if !compact.IsInjected(last) || last.Metadata[compact.InjectedKey] != compact.InjectedSteer {
107+ t.Errorf("steer metadata %v, want %s=%s", last.Metadata, compact.InjectedKey, compact.InjectedSteer)
108+ }
109+ if _, turns := compact.Split(full); len(turns) != 1 {
110+ t.Errorf("history splits into %d turns, want 1", len(turns))
111+ }
104112 if len(taken) != 1 || taken[0] != "use the v2 API" {
105113 t.Errorf("taken = %q", taken)
106114 }
@@ -101,6 +101,14 @@ func TestSteerReachesTheNextModelCall(t *testing.T) {
101 if err := compact.Valid(full); err != nil {101 if err := compact.Valid(full); err != nil {
102 t.Errorf("history: %v", err)102 t.Errorf("history: %v", err)
103 }103 }
104+ // Marked as part of the running turn (ticket 289): the history is still
105+ // one question turn for the compaction.
106+ if !compact.IsInjected(last) || last.Metadata[compact.InjectedKey] != compact.InjectedSteer {
107+ t.Errorf("steer metadata %v, want %s=%s", last.Metadata, compact.InjectedKey, compact.InjectedSteer)
108+ }
109+ if _, turns := compact.Split(full); len(turns) != 1 {
110+ t.Errorf("history splits into %d turns, want 1", len(turns))
111+ }
104 if len(taken) != 1 || taken[0] != "use the v2 API" {112 if len(taken) != 1 || taken[0] != "use the v2 API" {
105 t.Errorf("taken = %q", taken)113 t.Errorf("taken = %q", taken)
106 }114 }
modified internal/engine/summarize.go +27 -0
@@ -8,6 +8,7 @@ import (
88 "sync/atomic"
99
1010 "mm/internal/config"
11+ "mm/internal/ui"
1112
1213 "github.com/firebase/genkit/go/ai"
1314 "github.com/firebase/genkit/go/genkit"
@@ -71,9 +72,35 @@ func (e *Engine) Summarize(ctx context.Context, messages []*ai.Message, maxToken
7172 if text == "" {
7273 return "", emptySummary(resp, maxTokens, int(reasoned.Load()))
7374 }
75+ if resp.FinishReason == ai.FinishReasonLength {
76+ text = cutSummary(text)
77+ e.warnCutSummary(maxTokens)
78+ }
7479 return text, nil
7580 }
7681
82+// cutSummary is a summary the length limit cut (ticket 292): its unfinished
83+// last line dropped — observed, notes ending in the middle of a word,
84+// `Cell{Issues` — and a line saying the notes are incomplete. Still worth
85+// keeping: the notes put what matters most first.
86+//
87+// cutSummary("- a\n- b, half of") // "- a\n- [notes cut at the length limit]"
88+func cutSummary(text string) string {
89+ if i := strings.LastIndexByte(text, '\n'); i > 0 {
90+ text = strings.TrimRight(text[:i], " \n")
91+ }
92+ return text + "\n- [notes cut at the length limit]"
93+}
94+
95+// warnCutSummary says once per process that a summary was cut, and what to
96+// change: the user can raise the budget, the model cannot.
97+func (e *Engine) warnCutSummary(maxTokens int) {
98+ if e.summaryCutWarned.Swap(true) {
99+ return
100+ }
101+ ui.Notice(fmt.Sprintf("🗜️ a summary was cut at its limit (%d tokens): its notes are incomplete — raise context.summaryMaxTokens", maxTokens))
102+}
103+
77104 // summaryError says why a summary failed: a silence (the same test as in
78105 // generate: the contexts, not the wrapped error), the server's own words when
79106 // it streamed some, else the error.
@@ -8,6 +8,7 @@ import (
8 "sync/atomic"8 "sync/atomic"
9 9
10 "mm/internal/config"10 "mm/internal/config"
11+ "mm/internal/ui"
11 12
12 "github.com/firebase/genkit/go/ai"13 "github.com/firebase/genkit/go/ai"
13 "github.com/firebase/genkit/go/genkit"14 "github.com/firebase/genkit/go/genkit"
@@ -71,9 +72,35 @@ func (e *Engine) Summarize(ctx context.Context, messages []*ai.Message, maxToken
71 if text == "" {72 if text == "" {
72 return "", emptySummary(resp, maxTokens, int(reasoned.Load()))73 return "", emptySummary(resp, maxTokens, int(reasoned.Load()))
73 }74 }
75+ if resp.FinishReason == ai.FinishReasonLength {
76+ text = cutSummary(text)
77+ e.warnCutSummary(maxTokens)
78+ }
74 return text, nil79 return text, nil
75 }80 }
76 81
82+// cutSummary is a summary the length limit cut (ticket 292): its unfinished
83+// last line dropped — observed, notes ending in the middle of a word,
84+// `Cell{Issues` — and a line saying the notes are incomplete. Still worth
85+// keeping: the notes put what matters most first.
86+//
87+// cutSummary("- a\n- b, half of") // "- a\n- [notes cut at the length limit]"
88+func cutSummary(text string) string {
89+ if i := strings.LastIndexByte(text, '\n'); i > 0 {
90+ text = strings.TrimRight(text[:i], " \n")
91+ }
92+ return text + "\n- [notes cut at the length limit]"
93+}
94+
95+// warnCutSummary says once per process that a summary was cut, and what to
96+// change: the user can raise the budget, the model cannot.
97+func (e *Engine) warnCutSummary(maxTokens int) {
98+ if e.summaryCutWarned.Swap(true) {
99+ return
100+ }
101+ ui.Notice(fmt.Sprintf("🗜️ a summary was cut at its limit (%d tokens): its notes are incomplete — raise context.summaryMaxTokens", maxTokens))
102+}
103+
77 // summaryError says why a summary failed: a silence (the same test as in104 // summaryError says why a summary failed: a silence (the same test as in
78 // generate: the contexts, not the wrapped error), the server's own words when105 // generate: the contexts, not the wrapped error), the server's own words when
79 // it streamed some, else the error.106 // it streamed some, else the error.
modified internal/engine/textloop.go +1 -1
@@ -129,7 +129,7 @@ func (w *loopWatch) disarm() {
129129
130130 // loopRetryNote is what the model reads after a call cut for looping.
131131 func loopRetryNote(sample string, times int) *ai.Message {
132- return ai.NewUserTextMessage(fmt.Sprintf("%syou were repeating yourself — %q, %d times in a row — so mm stopped your reply. "+
132+ return noteMessage(fmt.Sprintf("%syou were repeating yourself — %q, %d times in a row — so mm stopped your reply. "+
133133 "Do NOT start over and do not repeat that sentence. You already have what you need in this conversation: "+
134134 "give your answer now (or make the one tool call still needed), with at most a few lines of reasoning.]",
135135 argsRetryPrefix, shorten(sample, 120), times))
@@ -129,7 +129,7 @@ func (w *loopWatch) disarm() {
129 129
130 // loopRetryNote is what the model reads after a call cut for looping.130 // loopRetryNote is what the model reads after a call cut for looping.
131 func loopRetryNote(sample string, times int) *ai.Message {131 func loopRetryNote(sample string, times int) *ai.Message {
132- return ai.NewUserTextMessage(fmt.Sprintf("%syou were repeating yourself — %q, %d times in a row — so mm stopped your reply. "+132+ return noteMessage(fmt.Sprintf("%syou were repeating yourself — %q, %d times in a row — so mm stopped your reply. "+
133 "Do NOT start over and do not repeat that sentence. You already have what you need in this conversation: "+133 "Do NOT start over and do not repeat that sentence. You already have what you need in this conversation: "+
134 "give your answer now (or make the one tool call still needed), with at most a few lines of reasoning.]",134 "give your answer now (or make the one tool call still needed), with at most a few lines of reasoning.]",
135 argsRetryPrefix, shorten(sample, 120), times))135 argsRetryPrefix, shorten(sample, 120), times))
modified internal/engine/toolargs.go +3 -3
@@ -102,7 +102,7 @@ func argsRetryNote(truncated bool) *ai.Message {
102102 b.WriteString("its arguments were not valid JSON. " +
103103 "Call the tool again with a single JSON object matching its parameters; escape quotes, backslashes and newlines inside strings.]")
104104 }
105- return ai.NewUserTextMessage(b.String())
105+ return noteMessage(b.String())
106106 }
107107
108108 // badToolArgs is Explain's line for the same error once the retries are
@@ -153,7 +153,7 @@ func cutRetryNote() *ai.Message {
153153 if mt := maxTokens(); mt != "" {
154154 limit += " (" + mt + " tokens)"
155155 }
156- return ai.NewUserTextMessage(argsRetryPrefix + "your last reply was cut off at " + limit +
156+ return noteMessage(argsRetryPrefix + "your last reply was cut off at " + limit +
157157 " while you were still reasoning: nothing was said and no tool was called. " +
158158 "Do NOT restart your analysis. Act now — call the next tool, or give your answer — after a few lines of reasoning at most.]")
159159 }
@@ -185,7 +185,7 @@ const maxEditRetries = 1
185185 // failedEditNote is what the model reads after its answer, when its last file
186186 // change failed.
187187 func failedEditNote(tool, failure string) *ai.Message {
188- return ai.NewUserTextMessage(fmt.Sprintf("%syour last %s call failed (%s): the file was NOT changed, so an answer saying it was is false. "+
188+ return noteMessage(fmt.Sprintf("%syour last %s call failed (%s): the file was NOT changed, so an answer saying it was is false. "+
189189 "Fix the call and send it again — copy old from what read_file printed; if old appears several times, add \"line\" with the line number of the occurrence to change — "+
190190 "or tell the user plainly that the change could not be made.]", argsRetryPrefix, tool, lastRunes(failure, 160)))
191191 }
@@ -102,7 +102,7 @@ func argsRetryNote(truncated bool) *ai.Message {
102 b.WriteString("its arguments were not valid JSON. " +102 b.WriteString("its arguments were not valid JSON. " +
103 "Call the tool again with a single JSON object matching its parameters; escape quotes, backslashes and newlines inside strings.]")103 "Call the tool again with a single JSON object matching its parameters; escape quotes, backslashes and newlines inside strings.]")
104 }104 }
105- return ai.NewUserTextMessage(b.String())105+ return noteMessage(b.String())
106 }106 }
107 107
108 // badToolArgs is Explain's line for the same error once the retries are108 // badToolArgs is Explain's line for the same error once the retries are
@@ -153,7 +153,7 @@ func cutRetryNote() *ai.Message {
153 if mt := maxTokens(); mt != "" {153 if mt := maxTokens(); mt != "" {
154 limit += " (" + mt + " tokens)"154 limit += " (" + mt + " tokens)"
155 }155 }
156- return ai.NewUserTextMessage(argsRetryPrefix + "your last reply was cut off at " + limit +156+ return noteMessage(argsRetryPrefix + "your last reply was cut off at " + limit +
157 " while you were still reasoning: nothing was said and no tool was called. " +157 " while you were still reasoning: nothing was said and no tool was called. " +
158 "Do NOT restart your analysis. Act now — call the next tool, or give your answer — after a few lines of reasoning at most.]")158 "Do NOT restart your analysis. Act now — call the next tool, or give your answer — after a few lines of reasoning at most.]")
159 }159 }
@@ -185,7 +185,7 @@ const maxEditRetries = 1
185 // failedEditNote is what the model reads after its answer, when its last file185 // failedEditNote is what the model reads after its answer, when its last file
186 // change failed.186 // change failed.
187 func failedEditNote(tool, failure string) *ai.Message {187 func failedEditNote(tool, failure string) *ai.Message {
188- return ai.NewUserTextMessage(fmt.Sprintf("%syour last %s call failed (%s): the file was NOT changed, so an answer saying it was is false. "+188+ return noteMessage(fmt.Sprintf("%syour last %s call failed (%s): the file was NOT changed, so an answer saying it was is false. "+
189 "Fix the call and send it again — copy old from what read_file printed; if old appears several times, add \"line\" with the line number of the occurrence to change — "+189 "Fix the call and send it again — copy old from what read_file printed; if old appears several times, add \"line\" with the line number of the occurrence to change — "+
190 "or tell the user plainly that the change could not be made.]", argsRetryPrefix, tool, lastRunes(failure, 160)))190 "or tell the user plainly that the change could not be made.]", argsRetryPrefix, tool, lastRunes(failure, 160)))
191 }191 }
modified internal/engine/turn.go +11 -7
@@ -47,6 +47,9 @@ type turn struct {
4747 // invalid counts the tool calls that failed the schema (toolschema.go):
4848 // the same invalid call repeated ends the turn.
4949 invalid invalidCalls
50+ // reads spots a call repeated after a compression dropped its result
51+ // (reread.go, ticket 292).
52+ reads rereads
5053 // The hand-backs of this generation, each bounded by its max*Retries.
5154 argRetries, cutRetries, loopRetries, editRetries int
5255 // printed: some answer text reached the screen or the client.
@@ -67,7 +70,7 @@ func (t *turn) finishSpeed() {
6770 // options are the Genkit options of the turn, the middleware included.
6871 func (t *turn) options(tools []ai.ToolRef) []ai.GenerateOption {
6972 capture := ai.MiddlewareFunc(func(context.Context) (*ai.Hooks, error) {
70- return &ai.Hooks{WrapModel: t.wrapModel, WrapTool: t.wrapTool}, nil
73+ return &ai.Hooks{WrapModel: t.wrapModel, WrapTool: t.reads.wrap(t.wrapTool)}, nil
7174 })
7275 opts := []ai.GenerateOption{
7376 ai.WithModelName(t.e.Model),
@@ -232,9 +235,8 @@ func (t *turn) wrapModel(ctx context.Context, params *ai.ModelParams, next ai.Mo
232235 // From the turn's second call on — tools have run — a history past the
233236 // threshold is made smaller first (inturn.go, ticket 251). The wait
234237 // counts as the call's: the summary is no beat.
235- if config.Cfg.Context.CompressInTurn && len(params.Request.Messages) > len(t.messages) {
236- t.pl.expect()
237- t.e.compactInTurn(ctx, params)
238+ if err := t.compressBeforeCall(ctx, params); err != nil {
239+ return nil, err
238240 }
239241 // Messages the user sent during the turn (ticket 265, steer.go) join the
240242 // history after the tool results.
@@ -258,7 +260,7 @@ func (t *turn) wrapModel(ctx context.Context, params *ai.ModelParams, next ai.Mo
258260 resp, err = t.retryBrokenArgs(ctx, params, call, resp, err)
259261 resp, err = t.retryCutReasoning(ctx, params, call, resp, err)
260262 resp, err = t.retryFailedEdit(ctx, params, call, resp, err)
261- t.recordUsage(resp)
263+ t.recordUsage(params, resp)
262264 dropReasoning(resp)
263265 if resp != nil {
264266 t.reply = resp.Message
@@ -385,15 +387,17 @@ func isAnswer(resp *ai.ModelResponse, err error) bool {
385387 }
386388
387389 // recordUsage keeps the server's own count of what it just read — the one
388-// exact measure of the context size, for the compression trigger — settles
390+// exact measure of the context size, for the compression trigger — and its
391+// ratio to the estimate of the same request (compact.Calibrate), settles
389392 // the call's speed, and hands every call's counts to a front end that wants
390393 // them (ACP: the context meter, the tokens a turn cost).
391-func (t *turn) recordUsage(resp *ai.ModelResponse) {
394+func (t *turn) recordUsage(params *ai.ModelParams, resp *ai.ModelResponse) {
392395 if resp == nil {
393396 return
394397 }
395398 if resp.Usage != nil && resp.Usage.InputTokens > 0 {
396399 t.e.lastInput.Store(int64(resp.Usage.InputTokens))
400+ t.e.calibrate(params.Request, resp.Usage.InputTokens)
397401 }
398402 if t.speed != nil {
399403 out := 0
@@ -47,6 +47,9 @@ type turn struct {
47 // invalid counts the tool calls that failed the schema (toolschema.go):47 // invalid counts the tool calls that failed the schema (toolschema.go):
48 // the same invalid call repeated ends the turn.48 // the same invalid call repeated ends the turn.
49 invalid invalidCalls49 invalid invalidCalls
50+ // reads spots a call repeated after a compression dropped its result
51+ // (reread.go, ticket 292).
52+ reads rereads
50 // The hand-backs of this generation, each bounded by its max*Retries.53 // The hand-backs of this generation, each bounded by its max*Retries.
51 argRetries, cutRetries, loopRetries, editRetries int54 argRetries, cutRetries, loopRetries, editRetries int
52 // printed: some answer text reached the screen or the client.55 // printed: some answer text reached the screen or the client.
@@ -67,7 +70,7 @@ func (t *turn) finishSpeed() {
67 // options are the Genkit options of the turn, the middleware included.70 // options are the Genkit options of the turn, the middleware included.
68 func (t *turn) options(tools []ai.ToolRef) []ai.GenerateOption {71 func (t *turn) options(tools []ai.ToolRef) []ai.GenerateOption {
69 capture := ai.MiddlewareFunc(func(context.Context) (*ai.Hooks, error) {72 capture := ai.MiddlewareFunc(func(context.Context) (*ai.Hooks, error) {
70- return &ai.Hooks{WrapModel: t.wrapModel, WrapTool: t.wrapTool}, nil73+ return &ai.Hooks{WrapModel: t.wrapModel, WrapTool: t.reads.wrap(t.wrapTool)}, nil
71 })74 })
72 opts := []ai.GenerateOption{75 opts := []ai.GenerateOption{
73 ai.WithModelName(t.e.Model),76 ai.WithModelName(t.e.Model),
@@ -232,9 +235,8 @@ func (t *turn) wrapModel(ctx context.Context, params *ai.ModelParams, next ai.Mo
232 // From the turn's second call on — tools have run — a history past the235 // From the turn's second call on — tools have run — a history past the
233 // threshold is made smaller first (inturn.go, ticket 251). The wait236 // threshold is made smaller first (inturn.go, ticket 251). The wait
234 // counts as the call's: the summary is no beat.237 // counts as the call's: the summary is no beat.
235- if config.Cfg.Context.CompressInTurn && len(params.Request.Messages) > len(t.messages) {238+ if err := t.compressBeforeCall(ctx, params); err != nil {
236- t.pl.expect()239+ return nil, err
237- t.e.compactInTurn(ctx, params)
238 }240 }
239 // Messages the user sent during the turn (ticket 265, steer.go) join the241 // Messages the user sent during the turn (ticket 265, steer.go) join the
240 // history after the tool results.242 // history after the tool results.
@@ -258,7 +260,7 @@ func (t *turn) wrapModel(ctx context.Context, params *ai.ModelParams, next ai.Mo
258 resp, err = t.retryBrokenArgs(ctx, params, call, resp, err)260 resp, err = t.retryBrokenArgs(ctx, params, call, resp, err)
259 resp, err = t.retryCutReasoning(ctx, params, call, resp, err)261 resp, err = t.retryCutReasoning(ctx, params, call, resp, err)
260 resp, err = t.retryFailedEdit(ctx, params, call, resp, err)262 resp, err = t.retryFailedEdit(ctx, params, call, resp, err)
261- t.recordUsage(resp)263+ t.recordUsage(params, resp)
262 dropReasoning(resp)264 dropReasoning(resp)
263 if resp != nil {265 if resp != nil {
264 t.reply = resp.Message266 t.reply = resp.Message
@@ -385,15 +387,17 @@ func isAnswer(resp *ai.ModelResponse, err error) bool {
385 }387 }
386 388
387 // recordUsage keeps the server's own count of what it just read — the one389 // recordUsage keeps the server's own count of what it just read — the one
388-// exact measure of the context size, for the compression trigger — settles390+// exact measure of the context size, for the compression trigger — and its
391+// ratio to the estimate of the same request (compact.Calibrate), settles
389 // the call's speed, and hands every call's counts to a front end that wants392 // the call's speed, and hands every call's counts to a front end that wants
390 // them (ACP: the context meter, the tokens a turn cost).393 // them (ACP: the context meter, the tokens a turn cost).
391-func (t *turn) recordUsage(resp *ai.ModelResponse) {394+func (t *turn) recordUsage(params *ai.ModelParams, resp *ai.ModelResponse) {
392 if resp == nil {395 if resp == nil {
393 return396 return
394 }397 }
395 if resp.Usage != nil && resp.Usage.InputTokens > 0 {398 if resp.Usage != nil && resp.Usage.InputTokens > 0 {
396 t.e.lastInput.Store(int64(resp.Usage.InputTokens))399 t.e.lastInput.Store(int64(resp.Usage.InputTokens))
400+ t.e.calibrate(params.Request, resp.Usage.InputTokens)
397 }401 }
398 if t.speed != nil {402 if t.speed != nil {
399 out := 0403 out := 0