Skip to main content

agentmux_srv_core/backend/
context_reading.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! How full each agent's context is, as srv sees it
5//! (`docs/specs/SPEC_AGENT_SELF_COMPACTION_2026_10_23.md` §3.2), for
6//! `Agents context`, the self-compact rate limit and the turn-end hint.
7//!
8//! Claude: the main agent's per-call usage from `message_start` and `assistant`
9//! frames (input + cache creation + cache read), as the pane's own meter reads
10//! it (`frontend/app/view/agent/main-agent-usage.ts`); subagent frames carry a
11//! `parent_tool_use_id` and are skipped. The window and the auto-compact point
12//! come from the CLI's `get_context_usage` answer. Codex: the reading srv takes
13//! from its session file after each turn (`subprocess/codex_context.rs`).
14
15use std::collections::HashMap;
16use std::sync::{Arc, LazyLock, OnceLock};
17
18use serde::Serialize;
19use serde_json::Value;
20
21use crate::backend::usage_of::{CallKind, Source};
22
23/// `agent:compacthints`: the turn-end hint (§3.5), on unless `false`.
24pub const SETTING_HINTS: &str = "agent:compacthints";
25/// `agent:compacthintat`: the context size, in tokens, from which the hint
26/// suggests compacting.
27pub const SETTING_HINT_AT: &str = "agent:compacthintat";
28pub const DEFAULT_HINT_AT: u64 = 400000; // plain digits: settings-defaults.test.ts reads it
29/// `agent:compactbackstopat`: the context size, in tokens, over which srv itself compacts a container agent between
30/// turns (`compact_backstop`), because it ignored the hint. 0 turns it off.
31pub const SETTING_BACKSTOP_AT: &str = "agent:compactbackstopat";
32pub const DEFAULT_BACKSTOP_AT: u64 = 600000; // plain digits, as above
33/// `agent:freshhintat`: from this many tokens, a turn that finished a task
34/// suggests a fresh session instead.
35pub const SETTING_FRESH_HINT_AT: &str = "agent:freshhintat";
36pub const DEFAULT_FRESH_HINT_AT: u64 = 150000; // plain digits, as above
37/// Below this the hint never fires, and it fires again only after the context
38/// has dropped below it.
39const HINT_REARM_BELOW: u64 = 250_000;
40/// The key the turn-end hint is held under (`reactive::held_notes`).
41pub const HINT_NOTE_KEY: &str = "compact-hint";
42/// No self-compaction this soon after the last one, in calls or in time: also
43/// what stops a compact, catch-up, compact loop.
44pub const MIN_CALLS_BETWEEN: u64 = 50;
45pub const MIN_MS_BETWEEN: u64 = 10 * 60 * 1000;
46
47/// One pane's reading.
48#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
49pub struct ContextReading {
50    pub model: Option<String>,
51    /// Tokens in context at the last main-agent call.
52    pub tokens: Option<u64>,
53    pub window: Option<u64>,
54    /// Where the CLI compacts on its own, when it said.
55    pub auto_compact_at: Option<u64>,
56    /// A compaction is running now.
57    pub compacting: bool,
58    /// Main-agent API calls since the last compaction (or since srv started).
59    pub calls_since_compaction: u64,
60    /// The reading comes from an ACP harness's `usage_update`, which is not one per model call.
61    #[serde(skip)]
62    pub from_acp: bool,
63    /// When the last compaction finished (unix ms).
64    pub last_compaction_ms: Option<u64>,
65    /// Compactions finished since this pane's reading began (kept in memory, as the rest is).
66    pub compactions: u64,
67    /// When the tokens were last read (unix ms).
68    pub observed_ms: Option<u64>,
69    /// When the agent last asked to compact itself (unix ms).
70    #[serde(skip)]
71    pub last_self_compact_ms: Option<u64>,
72    /// A self-compaction is waiting for the turn to end.
73    #[serde(skip)]
74    pub compact_scheduled: bool,
75    /// The hint fired and the context hasn't dropped below the re-arm point.
76    #[serde(skip)]
77    pub hinted: bool,
78    /// This turn finished a Kanban task (`Tasks complete` or `submit`).
79    #[serde(skip)]
80    pub task_boundary: bool,
81    /// The next spawn is an `Agents fresh` one: it starts on the handoff alone,
82    /// without the continuation packet (which says "continue as if uninterrupted").
83    #[serde(skip)]
84    pub fresh_by_choice: bool,
85    #[serde(skip)]
86    last_message_id: Option<String>,
87    /// An ACP agent's compaction in progress: see [`begin_acp_compaction`].
88    #[serde(skip)]
89    acp_compaction: Option<AcpCompaction>,
90}
91
92/// What an ACP agent's context held when AgentMux sent it `/compact`, and whether the turn that carried it has ended.
93#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
94struct AcpCompaction {
95    before: u64,
96    /// The id of the `/compact` prompt, once it is written: only that prompt's end ends the compaction, not the end of
97    /// the turn before it that resolves in the gap between the two.
98    carrier: Option<u64>,
99    turn_over: bool,
100}
101
102static BY_BLOCK: LazyLock<parking_lot::Mutex<HashMap<String, ContextReading>>> = LazyLock::new(Default::default);
103static CONFIG: OnceLock<Arc<crate::backend::wconfig::ConfigState>> = OnceLock::new();
104
105/// Attach the live settings (bootstrap), so the hint's settings can be read.
106pub fn install_config(config: Arc<crate::backend::wconfig::ConfigState>) {
107    // The account usage notices read their thresholds from the same live settings.
108    crate::backend::account_usage::install_config(Arc::clone(&config));
109    let _ = CONFIG.set(config);
110}
111
112fn hints_on() -> bool {
113    CONFIG.get().and_then(|c| c.extra_bool(SETTING_HINTS)).unwrap_or(true)
114}
115
116fn hint_at() -> u64 {
117    CONFIG.get().and_then(|c| c.extra_u64(SETTING_HINT_AT)).unwrap_or(DEFAULT_HINT_AT)
118}
119
120/// The size over which srv compacts a container agent itself, or `None` when the setting is 0 (off).
121pub fn backstop_at() -> Option<u64> {
122    Some(CONFIG.get().and_then(|c| c.extra_u64(SETTING_BACKSTOP_AT)).unwrap_or(DEFAULT_BACKSTOP_AT)).filter(|at| *at > 0)
123}
124
125/// Told when a container agent's turn has ended well, so the compaction backstop can look at its context. A container
126/// has no per-response event of its own, as a route agent's spend watcher gives one.
127pub type TurnEndObserver = Box<dyn Fn(&str) + Send + Sync>;
128static TURN_END_OBSERVER: OnceLock<TurnEndObserver> = OnceLock::new();
129
130/// Register what [`container_turn_ended`] tells (bootstrap, once).
131pub fn observe_container_turn_ends(observer: TurnEndObserver) {
132    let _ = TURN_END_OBSERVER.set(observer);
133}
134
135/// A container agent's turn has ended well.
136pub fn container_turn_ended(block_id: &str) {
137    if let Some(observer) = TURN_END_OBSERVER.get() {
138        observer(block_id);
139    }
140}
141
142fn fresh_hint_at() -> u64 {
143    CONFIG.get().and_then(|c| c.extra_u64(SETTING_FRESH_HINT_AT)).unwrap_or(DEFAULT_FRESH_HINT_AT)
144}
145
146fn with<R>(block_id: &str, f: impl FnOnce(&mut ContextReading) -> R) -> R {
147    f(BY_BLOCK.lock().entry(block_id.to_string()).or_default())
148}
149
150/// `block_id`'s reading now.
151pub fn get(block_id: &str) -> Option<ContextReading> {
152    BY_BLOCK.lock().get(block_id).cloned()
153}
154
155/// Tokens in `block_id`'s context at its last reading, or 0 when there is none: for log lines, so what a compaction
156/// or a note about one cost can be counted from the logs.
157pub fn tokens_now(block_id: &str) -> u64 {
158    BY_BLOCK.lock().get(block_id).and_then(|r| r.tokens).unwrap_or(0)
159}
160
161/// A process was started on `model`: a reply from another model, seen before it, says nothing about it. Its model is dropped
162/// until the first reply of the new process names its own; the rest of the reading (the conversation's size) stands.
163pub fn drop_model_other_than(block_id: &str, model: &str) {
164    if let Some(r) = BY_BLOCK.lock().get_mut(block_id) {
165        if r.model.as_deref().is_some_and(|seen| !crate::backend::model_label::same_model(seen, model)) {
166            r.model = None;
167        }
168    }
169}
170
171/// Forget `block_id` (its pane closed).
172pub fn forget(block_id: &str) {
173    BY_BLOCK.lock().remove(block_id);
174}
175
176/// Take one Claude stream frame into `block_id`'s reading; frames that say
177/// nothing about context are ignored.
178pub fn observe_claude_frame(block_id: &str, frame: &Value) {
179    let kind = frame.get("type").and_then(Value::as_str);
180    if kind == Some("system") {
181        match frame.get("subtype").and_then(Value::as_str) {
182            Some("compact_boundary") => {
183                with(block_id, |r| {
184                    r.compacting = false;
185                    r.calls_since_compaction = 0;
186                    r.last_compaction_ms = Some(agentmux_common::time::now_ms_u64());
187                    r.compactions += 1;
188                    r.tokens = None;
189                });
190                // A held hint about the old size is stale now.
191                crate::backend::reactive::held_notes::forget_key(block_id, HINT_NOTE_KEY);
192            }
193            Some("status") => {
194                let compacting = frame.get("status").and_then(Value::as_str) == Some("compacting");
195                with(block_id, |r| r.compacting = compacting);
196            }
197            _ => {}
198        }
199        return;
200    }
201    // The one reading of a call's usage (`usage_of`); a subagent's call has its own context, often its own model.
202    let Some(call) = crate::backend::usage_of::usage_of_value(frame) else { return };
203    if call.source != Source::Claude || call.kind == CallKind::Subagent {
204        return;
205    }
206    let tokens = call.buckets.prompt();
207    if tokens == 0 {
208        return;
209    }
210    let (id, model) = (call.message_id, call.model);
211    with(block_id, |r| {
212        // One call is reported by its message_start and its assistant frames:
213        // count it once.
214        if id.is_none() || id != r.last_message_id {
215            r.calls_since_compaction += 1;
216        }
217        r.last_message_id = id;
218        r.tokens = Some(tokens);
219        r.observed_ms = Some(agentmux_common::time::now_ms_u64());
220        if model.is_some() {
221            r.model = model;
222        }
223        if tokens < HINT_REARM_BELOW {
224            r.hinted = false;
225        }
226    });
227}
228
229/// The CLI's `get_context_usage` answer for `block_id`.
230pub fn set_auto_compact(block_id: &str, auto_compact_at: Option<u64>, window: Option<u64>) {
231    with(block_id, |r| {
232        r.auto_compact_at = auto_compact_at;
233        if window.is_some() {
234            r.window = window;
235        }
236    });
237}
238
239/// A Codex turn's reading, from its session file.
240pub fn observe_codex(block_id: &str, tokens: u64, window: Option<u64>, model: Option<String>) {
241    with(block_id, |r| {
242        r.calls_since_compaction += 1;
243        r.tokens = Some(tokens);
244        r.window = window.or(r.window);
245        if model.is_some() {
246            r.model = model;
247        }
248        if tokens < HINT_REARM_BELOW {
249            r.hinted = false;
250        }
251        // A Codex turn gets no turn-end note; its boundary ends with the turn.
252        r.task_boundary = false;
253    });
254}
255
256/// A turn ended without giving its turn-end hint (an error result).
257pub fn clear_task_boundary(block_id: &str) {
258    with(block_id, |r| r.task_boundary = false);
259}
260
261/// What the §3.5 rule says for a reading: `fresh` from `fresh_at` tokens
262/// when this turn finished a task, else `compact` from `hint_at` tokens;
263/// otherwise `none`.
264pub fn hint_of(r: &ContextReading, hint_at: u64, fresh_at: u64, now_ms: u64) -> &'static str {
265    hint_of_at(r, (hint_at, fresh_at, HINT_REARM_BELOW), now_ms)
266}
267
268/// [`hint_of`] with the three sizes given: the compact hint's, the fresh hint's and the re-arm point.
269fn hint_of_at(r: &ContextReading, (hint_at, fresh_at, rearm_below): (u64, u64, u64), now_ms: u64) -> &'static str {
270    let Some(tokens) = r.tokens else { return "none" };
271    if r.compacting || r.compact_scheduled || refusal_reason(r, now_ms).is_some() {
272        return "none";
273    }
274    if r.task_boundary && tokens >= fresh_at {
275        return "fresh";
276    }
277    if tokens < rearm_below || tokens < hint_at {
278        return "none";
279    }
280    "compact"
281}
282
283/// The hint's sizes for a harness whose window is `window`: the settings' sizes assume a 1M window, so a smaller one
284/// gets them as shares of it (compact hint from 40%, fresh hint from 15%, re-arm below 25%) when those are lower.
285pub fn window_scaled(window: Option<u64>, hint_at: u64, fresh_at: u64) -> (u64, u64, u64) {
286    match window.filter(|w| *w > 0) {
287        Some(w) => (hint_at.min(w / 100 * 40), fresh_at.min(w / 100 * 15), HINT_REARM_BELOW.min(w / 100 * 25)),
288        None => (hint_at, fresh_at, HINT_REARM_BELOW),
289    }
290}
291
292/// What a turn-end hint is worked out and worded for: the kind of agent it goes to.
293#[derive(Debug, Clone, Copy, PartialEq, Eq)]
294pub struct HintFor {
295    /// The agent can start a fresh session (`Agents fresh`).
296    pub fresh_allowed: bool,
297    /// The sizes are shares of the harness's window (an ACP harness) and not the settings' own.
298    pub window_scaled: bool,
299    /// The agent can compact (`Agents compact`); when it can't, the note names `Agents fresh` alone.
300    pub compact_offered: bool,
301}
302
303impl HintFor {
304    /// A Claude or Codex agent: the settings' sizes, both actions.
305    pub const NATIVE: Self = Self { fresh_allowed: true, window_scaled: false, compact_offered: true };
306
307    /// An agent that has no fresh session to start (a container's).
308    pub fn without_fresh() -> Self {
309        Self { fresh_allowed: false, ..Self::NATIVE }
310    }
311
312    /// An ACP harness, which compacts only when it announced a compaction command.
313    pub fn acp(compact_offered: bool) -> Self {
314        Self { fresh_allowed: true, window_scaled: true, compact_offered }
315    }
316}
317
318/// The hint for `block_id` now, by the live settings (`none` when they're off).
319pub fn hint(block_id: &str) -> &'static str {
320    hint_for(block_id, HintFor::NATIVE)
321}
322
323/// [`hint`] for an agent of `kind`: one that may not be able to start a fresh session has a finished task count for
324/// nothing, so only the compact hint can come.
325pub fn hint_for(block_id: &str, kind: HintFor) -> &'static str {
326    if !hints_on() {
327        return "none";
328    }
329    get(block_id).map_or("none", |mut r| {
330        r.task_boundary &= kind.fresh_allowed;
331        let sizes = if kind.window_scaled { window_scaled(r.window, hint_at(), fresh_hint_at()) } else { (hint_at(), fresh_hint_at(), HINT_REARM_BELOW) };
332        hint_of_at(&r, sizes, agentmux_common::time::now_ms_u64())
333    })
334}
335
336/// Why a self-compaction (or a fresh session) can't be scheduled now, or `None`, saying when it will be allowed. The count
337/// of calls does not stop an ACP agent whose context is already past its fresh-start point: a harness's updates are not one
338/// per model call and its context may grow far in few of them, and it may have no compaction to shed it with. The ten
339/// minutes between two always hold: they are what stops a compact, catch-up, compact loop.
340pub fn refusal_reason(r: &ContextReading, now_ms: u64) -> Option<String> {
341    if r.compact_scheduled {
342        return Some("already scheduled".to_string());
343    }
344    if r.compacting {
345        return Some("already compacting".to_string());
346    }
347    let left = |t: Option<u64>| t.map_or(0, |t| MIN_MS_BETWEEN.saturating_sub(now_ms.saturating_sub(t)));
348    let wait_ms = left(r.last_self_compact_ms).max(left(r.last_compaction_ms));
349    if wait_ms > 0 {
350        return Some(format!("too soon: the last compaction was under 10 minutes ago; allowed again in {} min", wait_ms.div_ceil(60_000)));
351    }
352    if r.last_compaction_ms.is_none() || r.calls_since_compaction >= MIN_CALLS_BETWEEN {
353        return None;
354    }
355    let open_at = r.from_acp.then(|| window_scaled(r.window, hint_at(), fresh_hint_at()).1);
356    if open_at.is_some_and(|at| r.tokens.unwrap_or(0) >= at) {
357        return None;
358    }
359    let calls = format!("allowed after {} more calls", MIN_CALLS_BETWEEN - r.calls_since_compaction);
360    Some(match open_at {
361        Some(at) => format!("too soon: fewer than {MIN_CALLS_BETWEEN} calls since the last compaction; {calls}, or once your context reaches {}K tokens", at / 1000),
362        None => format!("too soon: fewer than {MIN_CALLS_BETWEEN} calls since the last compaction; {calls}"),
363    })
364}
365
366/// Mark a self-compaction scheduled for `block_id`, unless it can't be:
367/// `Err(reason)`.
368pub fn schedule_compact(block_id: &str, now_ms: u64) -> Result<(), String> {
369    with(block_id, |r| {
370        if let Some(why) = refusal_reason(r, now_ms) {
371            return Err(why);
372        }
373        r.compact_scheduled = true;
374        Ok(())
375    })
376}
377
378/// `block_id`'s agent finished a task in this turn.
379pub fn note_task_boundary(block_id: &str) {
380    with(block_id, |r| r.task_boundary = true);
381}
382
383/// The next spawn of `block_id` is the agent's own `Agents fresh`.
384pub fn mark_fresh_by_choice(block_id: &str) {
385    with(block_id, |r| r.fresh_by_choice = true);
386}
387
388/// Whether this spawn is an `Agents fresh` one; read once, by the spawn.
389pub fn take_fresh_by_choice(block_id: &str) -> bool {
390    with(block_id, |r| std::mem::take(&mut r.fresh_by_choice))
391}
392
393/// The scheduled fresh session was started (`sent`), or given up: one that
394/// started counts toward the rate limit and starts the reading over.
395pub fn fresh_sent(block_id: &str, sent: bool) {
396    with(block_id, |r| {
397        r.compact_scheduled = false;
398        // A start that went leaves its flag for the spawn to read: the handoff
399        // may only have been queued behind a spawn that hasn't reached it yet.
400        if !sent {
401            r.fresh_by_choice = false;
402        }
403        if sent {
404            let now = agentmux_common::time::now_ms_u64();
405            r.last_self_compact_ms = Some(now);
406            r.last_compaction_ms = Some(now);
407            r.calls_since_compaction = 0;
408            r.tokens = None;
409            r.hinted = false;
410        }
411    });
412}
413
414/// The scheduled self-compaction was sent (`sent`), or given up or refused by
415/// the controller: only one that went counts toward the rate limit.
416pub fn compact_sent(block_id: &str, sent: bool) {
417    with(block_id, |r| {
418        r.compact_scheduled = false;
419        if sent {
420            r.last_self_compact_ms = Some(agentmux_common::time::now_ms_u64());
421        }
422    });
423}
424
425/// Says in the log why a turn that ended with a large (or unread) context gave no compaction hint, so "why did this agent
426/// never get the note" can be answered from the log. Nothing is logged for a context below the hint's size or with the
427/// hints off.
428fn log_withheld(block_id: &str, r: &ContextReading, verdict: &str) {
429    if !hints_on() {
430        return;
431    }
432    let Some(tokens) = r.tokens else {
433        tracing::info!(block_id, "compaction hint withheld: no reading of this agent's context");
434        return;
435    };
436    if tokens < hint_at() {
437        return;
438    }
439    let why: String = if verdict == "compact" && r.hinted {
440        "the hint was already given for this climb".into()
441    } else if r.compacting {
442        "a compaction is marked as running".into()
443    } else if r.compact_scheduled {
444        "a compaction is waiting to be sent".into()
445    } else {
446        refusal_reason(r, agentmux_common::time::now_ms_u64()).unwrap_or_else(|| "below the re-arm size".into())
447    };
448    tracing::info!(block_id, tokens, why = %why, "compaction hint withheld");
449}
450
451/// At the end of a turn: the hint's note text when it's due. A compact hint
452/// is marked given, so it isn't repeated before the context drops and crosses
453/// again; a fresh hint belongs to the task that just finished, comes with each
454/// one and leaves the compact hint's mark alone. A task boundary counts for
455/// the turn it happened in only.
456pub fn take_turn_end_hint(block_id: &str) -> Option<String> {
457    take_turn_end_hint_for(block_id, true)
458}
459
460/// [`take_turn_end_hint`] for an agent that can't start a fresh session when `fresh_allowed` is false
461/// (`Agents fresh` is refused in a container): it is never told to, and gets the compact wording alone.
462pub fn take_turn_end_hint_for(block_id: &str, fresh_allowed: bool) -> Option<String> {
463    take_hint_for_kind(block_id, HintFor { fresh_allowed, ..HintFor::NATIVE })
464}
465
466/// [`take_turn_end_hint_for`] for an agent of any `kind`.
467pub fn take_hint_for_kind(block_id: &str, kind: HintFor) -> Option<String> {
468    let verdict = hint_for(block_id, kind);
469    with(block_id, |r| {
470        r.task_boundary = false;
471        if verdict == "none" || (verdict == "compact" && r.hinted) {
472            log_withheld(block_id, r, verdict);
473            return None;
474        }
475        if verdict == "compact" {
476            r.hinted = true;
477        }
478        let k = |n: u64| format!("{}K", n / 1000);
479        let of = r.window.map(|w| format!(" of {}", k(w))).unwrap_or_default();
480        let size = format!("Your context is {}{of} tokens.", k(r.tokens.unwrap_or(0)));
481        Some(hint_text(&size, verdict, kind.compact_offered))
482    })
483}
484
485/// The note: `size` says how full the context is, `verdict` is `fresh` or `compact`, and a harness that offers no compaction
486/// is told `Agents fresh` alone, so it is never pointed at an action that would be refused.
487fn hint_text(size: &str, verdict: &str, compact_offered: bool) -> String {
488    match (verdict, compact_offered) {
489        ("fresh", true) => format!(
490            "[AgentMux] {size} You finished a task: if your next work is unrelated, start fresh with \
491             Agents fresh and a handoff (task number, spec or file paths, open PRs, decisions, the next step); \
492             if it continues this work, compact instead (Agents compact). Either runs when this turn ends."
493        ),
494        ("fresh", false) => format!(
495            "[AgentMux] {size} You finished a task: if your next work is unrelated, start fresh with \
496             Agents fresh and a handoff (task number, spec or file paths, open PRs, decisions, the next step); \
497             it runs when this turn ends. Your harness has no compaction AgentMux can start."
498        ),
499        (_, true) => format!(
500            "[AgentMux] {size} If your next work continues this task, compact now: \
501             Agents compact, with a focus saying what to keep (PR and task numbers, files you're editing, \
502             decisions, the next step); it runs when this turn ends."
503        ),
504        (_, false) => format!(
505            "[AgentMux] {size} Your harness has no compaction AgentMux can start, so every call re-reads all of it: \
506             at a good stopping point, start fresh with Agents fresh and a handoff (task number, spec or file paths, \
507             open PRs, decisions, the next step); it runs when this turn ends."
508        ),
509    }
510}
511
512/// At the end of a turn that ended well: take the hint and hold it, so it rides the agent's next message.
513/// The persistent controller's reader and a container's turn both end a turn this way; `fresh_allowed` is
514/// whether the agent can start a fresh session.
515pub fn hold_turn_end_hint(block_id: &str, fresh_allowed: bool) {
516    hold_hint_for_kind(block_id, HintFor { fresh_allowed, ..HintFor::NATIVE });
517}
518
519/// [`hold_turn_end_hint`] for an agent of any `kind` (an ACP harness's turn end).
520pub fn hold_hint_for_kind(block_id: &str, kind: HintFor) {
521    if let Some(note) = take_hint_for_kind(block_id, kind) {
522        crate::backend::reactive::held_notes::hold(block_id, HINT_NOTE_KEY, &note);
523    }
524}
525
526/// The key the result of an ACP agent's compaction is held under.
527pub const COMPACTION_NOTE_KEY: &str = "compaction-result";
528
529/// An ACP harness's `usage_update`: `used` tokens in the conversation of a `window`-token context. Each one is a call.
530/// The first one after a compaction's turn is the size the compaction left, and says so in a note for the agent.
531pub fn observe_acp(block_id: &str, used: u64, window: Option<u64>) {
532    let note = with(block_id, |r| {
533        r.calls_since_compaction += 1;
534        r.from_acp = true;
535        r.tokens = Some(used);
536        r.window = window.filter(|w| *w > 0).or(r.window);
537        r.observed_ms = Some(agentmux_common::time::now_ms_u64());
538        if used < window_scaled(r.window, hint_at(), fresh_hint_at()).2 {
539            r.hinted = false;
540        }
541        finish_acp_compaction(r)
542    });
543    if let Some(note) = note {
544        crate::backend::reactive::held_notes::forget_key(block_id, HINT_NOTE_KEY);
545        crate::backend::reactive::held_notes::hold(block_id, COMPACTION_NOTE_KEY, &note);
546    }
547}
548
549/// `/compact` is about to be sent to an ACP agent: remember the size it holds. The answer is the first `usage_update` after
550/// the turn that carries it, because a reading during it may be of the summarizing call.
551pub fn begin_acp_compaction(block_id: &str) {
552    with(block_id, |r| {
553        r.compacting = true;
554        r.acp_compaction = Some(AcpCompaction { before: r.tokens.unwrap_or(0), carrier: None, turn_over: false });
555    });
556}
557
558/// The `/compact` of a compaction begun for `block_id` was written to the harness as prompt `prompt_id`. A `/compact` nobody
559/// begun (a person typed it) carries no compaction.
560pub fn acp_compaction_carried_by(block_id: &str, prompt_id: u64) {
561    with(block_id, |r| {
562        if let Some(c) = r.acp_compaction.as_mut() {
563            c.carrier = Some(prompt_id);
564        }
565    });
566}
567
568/// `/compact` could not be sent to an ACP agent.
569pub fn cancel_acp_compaction(block_id: &str) {
570    with(block_id, |r| {
571        r.compacting = false;
572        r.acp_compaction = None;
573    });
574}
575
576/// The prompt `prompt_id` of an ACP agent ended, `ok` or by an error. When it is the one that carried the compaction:
577/// `Some(note)` if it did not run (an error), else the compaction waits for the next reading of the size. Any other
578/// prompt's end leaves the compaction alone.
579pub fn acp_compaction_turn_ended(block_id: &str, prompt_id: u64, ok: bool) -> Option<String> {
580    with(block_id, |r| {
581        let carried = r.acp_compaction.as_mut().filter(|c| c.carrier == Some(prompt_id))?;
582        r.compacting = false;
583        if ok {
584            carried.turn_over = true;
585            return None;
586        }
587        r.acp_compaction = None;
588        Some("[AgentMux] The compaction did not run: the harness answered with an error. Your context is unchanged.".to_string())
589    })
590}
591
592/// A reading after a compaction's turn: the compaction is done. The note says what it left.
593fn finish_acp_compaction(r: &mut ContextReading) -> Option<String> {
594    if !r.acp_compaction.is_some_and(|c| c.turn_over) {
595        return None;
596    }
597    let before = r.acp_compaction.take()?.before;
598    r.compactions += 1;
599    r.last_compaction_ms = Some(agentmux_common::time::now_ms_u64());
600    r.calls_since_compaction = 0;
601    let after = r.tokens.unwrap_or(0);
602    let k = |n: u64| format!("{}K", n / 1000);
603    Some(match before {
604        0 => format!("[AgentMux] Compacted: your context is now {} tokens.", k(after)),
605        // Under nine tenths of what it was: a few thousand tokens off a 400K context is no compaction.
606        b if after.saturating_mul(10) < b.saturating_mul(9) => format!("[AgentMux] Compacted: {} to {} tokens.", k(b), k(after)),
607        b => format!(
608            "[AgentMux] The compaction ran, but your context is still {} tokens (it was {}): if your next work is unrelated, start fresh with Agents fresh and a handoff.",
609            k(after),
610            k(b)
611        ),
612    })
613}
614
615#[cfg(test)]
616mod tests {
617    use super::*;
618    use serde_json::json;
619
620    fn block() -> String {
621        format!("ctx-{}", uuid::Uuid::new_v4())
622    }
623
624    fn call(id: &str, tokens: u64) -> Value {
625        json!({"type": "assistant", "message": {"id": id, "model": "claude-opus-5-5",
626               "usage": {"input_tokens": 2, "cache_creation_input_tokens": 1000, "cache_read_input_tokens": tokens - 1002}}})
627    }
628
629    #[test]
630    fn a_process_started_on_another_model_drops_the_model_a_reply_before_it_named() {
631        let b = block();
632        observe_claude_frame(&b, &call("m1", 100_000));
633        assert_eq!(get(&b).unwrap().model.as_deref(), Some("claude-opus-5-5"));
634        drop_model_other_than(&b, "opus");
635        assert_eq!(get(&b).unwrap().model.as_deref(), Some("claude-opus-5-5"), "the same model by its alias: kept");
636        drop_model_other_than(&b, "sonnet");
637        let r = get(&b).unwrap();
638        assert_eq!((r.model, r.tokens), (None, Some(100_000)), "another model: its name goes, the conversation's size stays");
639        observe_claude_frame(&b, &call("m2", 110_000));
640        assert_eq!(get(&b).unwrap().model.as_deref(), Some("claude-opus-5-5"), "the next reply names its own");
641        drop_model_other_than("no-such-block", "sonnet");
642        forget(&b);
643    }
644
645    #[test]
646    fn a_main_agent_call_is_read_once_and_a_subagents_is_not() {
647        let b = block();
648        observe_claude_frame(&b, &json!({"type": "stream_event", "event": {"type": "message_start", "message": {
649            "id": "m1", "model": "claude-opus-5-5", "usage": {"input_tokens": 5, "cache_read_input_tokens": 99_995}}}}));
650        observe_claude_frame(&b, &call("m1", 100_000));
651        let r = get(&b).unwrap();
652        assert_eq!((r.tokens, r.calls_since_compaction, r.model.as_deref()), (Some(100_000), 1, Some("claude-opus-5-5")));
653        let mut sub = call("s1", 20_000);
654        sub["parent_tool_use_id"] = json!("toolu_1");
655        observe_claude_frame(&b, &sub);
656        assert_eq!(get(&b).unwrap().tokens, Some(100_000), "the subagent's fill is ignored");
657        observe_claude_frame(&b, &call("m2", 150_000));
658        assert_eq!(get(&b).unwrap().calls_since_compaction, 2);
659        forget(&b);
660    }
661
662    #[test]
663    fn a_compaction_resets_the_count_and_the_status_frames_mark_it() {
664        let b = block();
665        observe_claude_frame(&b, &call("m1", 900_000));
666        observe_claude_frame(&b, &json!({"type": "system", "subtype": "status", "status": "compacting"}));
667        assert!(get(&b).unwrap().compacting);
668        crate::backend::reactive::held_notes::hold(&b, HINT_NOTE_KEY, "[AgentMux] Your context is 900K");
669        observe_claude_frame(&b, &json!({"type": "system", "subtype": "compact_boundary"}));
670        let (sent, guard) = crate::backend::reactive::held_notes::attach(&b, "next");
671        assert_eq!(sent, "next", "the hint about the old size is dropped");
672        guard.delivered();
673        let r = get(&b).unwrap();
674        assert!(!r.compacting && r.calls_since_compaction == 0 && r.last_compaction_ms.is_some() && r.tokens.is_none());
675        forget(&b);
676    }
677
678    #[test]
679    fn each_compaction_is_counted_and_a_token_read_says_when_it_was_made() {
680        let b = block();
681        observe_claude_frame(&b, &call("m1", 100_000));
682        let first = get(&b).unwrap();
683        assert_eq!(first.compactions, 0, "nothing has compacted yet");
684        assert!(first.observed_ms.is_some(), "a token read is stamped");
685        observe_claude_frame(&b, &json!({"type": "system", "subtype": "compact_boundary"}));
686        observe_claude_frame(&b, &call("m2", 20_000));
687        observe_claude_frame(&b, &json!({"type": "system", "subtype": "compact_boundary"}));
688        assert_eq!(get(&b).unwrap().compactions, 2);
689        forget(&b);
690        assert!(get(&b).is_none(), "forgotten with its pane");
691    }
692
693    fn reading(tokens: u64) -> ContextReading {
694        ContextReading { tokens: Some(tokens), window: Some(1_000_000), ..Default::default() }
695    }
696
697    #[test]
698    fn the_hint_fires_from_its_threshold_and_not_below_the_rearm_point() {
699        assert_eq!(hint_of(&reading(399_999), 400_000, 150_000, 0), "none");
700        assert_eq!(hint_of(&reading(400_000), 400_000, 150_000, 0), "compact");
701        assert_eq!(hint_of(&reading(240_000), 100_000, 150_000, 0), "none", "never below 250K");
702        assert_eq!(hint_of(&ContextReading { compact_scheduled: true, ..reading(500_000) }, 400_000, 150_000, 0), "none");
703        assert_eq!(hint_of(&ContextReading { tokens: None, ..reading(0) }, 400_000, 150_000, 0), "none");
704        // A finished task: fresh from its own, lower threshold.
705        let done = |t| ContextReading { task_boundary: true, ..reading(t) };
706        assert_eq!(hint_of(&done(149_999), 400_000, 150_000, 0), "none");
707        assert_eq!(hint_of(&done(150_000), 400_000, 150_000, 0), "fresh");
708        assert_eq!(hint_of(&done(500_000), 400_000, 150_000, 0), "fresh", "fresh wins over compact at a boundary");
709    }
710
711    #[test]
712    fn a_self_compaction_is_rate_limited() {
713        let now = 100 * MIN_MS_BETWEEN;
714        let fresh = reading(500_000);
715        assert_eq!(refusal_reason(&fresh, now), None, "no compaction yet");
716        let just_compacted = ContextReading { last_compaction_ms: Some(now - 1000), calls_since_compaction: 80, ..fresh.clone() };
717        assert!(refusal_reason(&just_compacted, now).unwrap().contains("10 minutes"));
718        let few_calls = ContextReading { last_compaction_ms: Some(now - 2 * MIN_MS_BETWEEN), calls_since_compaction: 10, ..fresh.clone() };
719        assert!(refusal_reason(&few_calls, now).unwrap().contains("50 calls"));
720        let ok = ContextReading { last_compaction_ms: Some(now - 2 * MIN_MS_BETWEEN), calls_since_compaction: 50, ..fresh };
721        assert_eq!(refusal_reason(&ok, now), None);
722    }
723
724    /// An ACP agent past its fresh-start point is not held by the count of calls: its updates are not one per model call and it
725    /// may have no compaction to shed the context with. The refusal says when the way opens.
726    #[test]
727    fn an_acp_agent_past_its_fresh_point_is_not_held_by_the_call_count() {
728        let now = 100 * MIN_MS_BETWEEN;
729        let after = |tokens, from_acp, calls| ContextReading {
730            last_compaction_ms: Some(now - 2 * MIN_MS_BETWEEN),
731            calls_since_compaction: calls,
732            from_acp,
733            ..reading(tokens)
734        };
735        assert_eq!(refusal_reason(&after(300_000, true, 10), now), None, "300K on a 1M window is past 150K");
736        let below = refusal_reason(&after(100_000, true, 10), now).unwrap();
737        assert!(below.contains("40 more calls") && below.contains("150K tokens"), "{below}");
738        let native = refusal_reason(&after(300_000, false, 10), now).unwrap();
739        assert!(native.contains("40 more calls") && !native.contains("reaches"), "a Claude agent keeps the count: {native}");
740        let recent = ContextReading { last_compaction_ms: Some(now - 4 * 60_000), ..after(300_000, true, 10) };
741        assert!(refusal_reason(&recent, now).unwrap().contains("allowed again in 6 min"), "the ten minutes always hold");
742    }
743
744    #[test]
745    fn scheduling_holds_one_request_until_it_is_sent() {
746        let b = block();
747        observe_claude_frame(&b, &call("m1", 500_000));
748        assert_eq!(schedule_compact(&b, 1), Ok(()));
749        assert_eq!(schedule_compact(&b, 2), Err("already scheduled".to_string()));
750        compact_sent(&b, false);
751        assert_eq!(schedule_compact(&b, 3), Ok(()), "one that never went doesn't count");
752        compact_sent(&b, true);
753        let now = agentmux_common::time::now_ms_u64();
754        assert!(schedule_compact(&b, now).unwrap_err().contains("10 minutes"), "one that went does");
755        forget(&b);
756    }
757
758    #[test]
759    fn the_turn_end_hint_is_given_once_per_crossing() {
760        let b = block();
761        observe_claude_frame(&b, &call("m1", 512_000));
762        set_auto_compact(&b, Some(600_000), Some(1_000_000));
763        let note = take_turn_end_hint(&b).expect("due at 512K");
764        assert!(note.starts_with("[AgentMux] Your context is 512K of 1000K tokens."), "{note}");
765        assert_eq!(take_turn_end_hint(&b), None, "not again while it stays high");
766        observe_claude_frame(&b, &call("m2", 60_000));
767        observe_claude_frame(&b, &call("m3", 450_000));
768        assert!(take_turn_end_hint(&b).is_some(), "again after dropping below 250K and crossing");
769        forget(&b);
770    }
771
772    #[test]
773    fn a_finished_task_hints_fresh_for_that_turn_only() {
774        let b = block();
775        observe_claude_frame(&b, &call("m1", 200_000));
776        note_task_boundary(&b);
777        let note = take_turn_end_hint(&b).expect("a task finished at 200K");
778        assert!(note.contains("Agents fresh"), "{note}");
779        assert!(!get(&b).unwrap().hinted, "a fresh hint doesn't use up the compact hint");
780        note_task_boundary(&b);
781        clear_task_boundary(&b);
782        assert!(!get(&b).unwrap().task_boundary, "a failed turn leaves no boundary behind");
783        note_task_boundary(&b);
784        observe_codex(&b, 200_000, None, None);
785        assert!(!get(&b).unwrap().task_boundary, "nor does a Codex turn");
786        mark_fresh_by_choice(&b);
787        assert!(take_fresh_by_choice(&b) && !take_fresh_by_choice(&b), "the spawn reads it once");
788        assert!(!get(&b).unwrap().task_boundary, "the boundary is used up");
789        mark_fresh_by_choice(&b);
790        fresh_sent(&b, true);
791        assert!(take_fresh_by_choice(&b), "a started fresh session keeps its flag for the spawn");
792        let r = get(&b).unwrap();
793        assert!(r.tokens.is_none() && r.calls_since_compaction == 0 && r.last_self_compact_ms.is_some());
794        forget(&b);
795    }
796
797    /// A container agent can't start a fresh session, so a finished task never gives it the fresh note: it
798    /// gets the compact note when its context is large, and nothing when it is not.
799    #[test]
800    fn an_agent_that_cannot_start_fresh_is_never_told_to() {
801        let b = block();
802        observe_claude_frame(&b, &call("m1", 200_000));
803        note_task_boundary(&b);
804        assert_eq!(take_turn_end_hint_for(&b, false), None, "a finished task at 200K: nothing, not the fresh note");
805        assert!(!get(&b).unwrap().task_boundary, "and the boundary is used up for that turn");
806
807        observe_claude_frame(&b, &call("m2", 500_000));
808        note_task_boundary(&b);
809        let note = take_turn_end_hint_for(&b, false).expect("due at 500K");
810        assert!(note.contains("Agents compact") && !note.contains("Agents fresh"), "{note}");
811        note_task_boundary(&b);
812        assert_eq!(take_turn_end_hint_for(&b, false), None, "the compact hint is given once, finished task or not");
813        observe_claude_frame(&b, &call("m3", 60_000));
814        observe_claude_frame(&b, &call("m4", 450_000));
815        assert!(take_turn_end_hint_for(&b, false).is_some(), "again after dropping below 250K and crossing");
816
817        // A host agent is unchanged: the same finished task at 200K gives the fresh note.
818        let host = block();
819        observe_claude_frame(&host, &call("m1", 200_000));
820        note_task_boundary(&host);
821        assert!(take_turn_end_hint_for(&host, true).expect("fresh").contains("Agents fresh"));
822        forget(&b);
823        forget(&host);
824    }
825
826    /// The note is held under its own key, so it rides the agent's next message once and a second turn at the same
827    /// size adds none.
828    #[test]
829    fn the_held_turn_end_hint_rides_the_next_message_once() {
830        let b = block();
831        observe_claude_frame(&b, &call("m1", 500_000));
832        hold_turn_end_hint(&b, false);
833        hold_turn_end_hint(&b, false);
834        let (message, held) = crate::backend::reactive::held_notes::attach(&b, "next");
835        assert!(message.contains("compact now"), "{message}");
836        assert_eq!(message.matches("[AgentMux] Your context is").count(), 1, "{message}");
837        held.delivered();
838        let (plain, held) = crate::backend::reactive::held_notes::attach(&b, "after");
839        assert_eq!(plain, "after", "nothing held again at the same size");
840        held.delivered();
841        forget(&b);
842    }
843
844    #[test]
845    fn a_codex_turn_counts_and_reads() {
846        let b = block();
847        observe_codex(&b, 94_399, Some(258_400), Some("gpt-6-astra".into()));
848        let r = get(&b).unwrap();
849        assert_eq!((r.tokens, r.window, r.calls_since_compaction), (Some(94_399), Some(258_400), 1));
850        forget(&b);
851    }
852
853    #[test]
854    fn a_smaller_window_gets_the_hint_sizes_as_shares_of_it() {
855        assert_eq!(window_scaled(Some(1_000_000), 400_000, 150_000), (400_000, 150_000, 250_000), "the settings' own sizes fit a 1M window");
856        assert_eq!(window_scaled(Some(256_000), 400_000, 150_000), (102_400, 38_400, 64_000));
857        assert_eq!(window_scaled(Some(128_000), 400_000, 150_000), (51_200, 19_200, 32_000));
858        assert_eq!(window_scaled(None, 400_000, 150_000), (400_000, 150_000, 250_000), "no window known: the settings");
859        assert_eq!(window_scaled(Some(256_000), 50_000, 20_000), (50_000, 20_000, 64_000), "a setting lower than the share stays");
860    }
861
862    #[test]
863    fn an_acp_agent_on_a_256k_window_is_hinted_from_40_percent_and_told_what_works() {
864        let b = block();
865        observe_acp(&b, 90_000, Some(256_000));
866        assert_eq!(take_hint_for_kind(&b, HintFor::acp(true)), None, "under 40% of the window");
867        observe_acp(&b, 110_000, Some(256_000));
868        let note = take_hint_for_kind(&b, HintFor::acp(true)).expect("over 40%");
869        assert!(note.starts_with("[AgentMux] Your context is 110K of 256K tokens.") && note.contains("Agents compact"), "{note}");
870        assert_eq!(take_hint_for_kind(&b, HintFor::acp(true)), None, "once per crossing");
871        observe_acp(&b, 20_000, Some(256_000));
872        observe_acp(&b, 120_000, Some(256_000));
873        assert!(take_hint_for_kind(&b, HintFor::acp(true)).is_some(), "again after dropping below 25% of the window");
874        forget(&b);
875    }
876
877    #[test]
878    fn a_harness_with_no_compaction_is_told_agents_fresh_alone() {
879        let b = block();
880        observe_acp(&b, 600_000, Some(1_000_000));
881        let note = take_hint_for_kind(&b, HintFor::acp(false)).expect("over 40%");
882        assert!(note.contains("Agents fresh") && !note.contains("Agents compact"), "{note}");
883        note_task_boundary(&b);
884        observe_acp(&b, 300_000, Some(1_000_000));
885        let fresh = take_hint_for_kind(&b, HintFor::acp(false)).expect("a finished task at 300K");
886        assert!(fresh.contains("Agents fresh") && !fresh.contains("Agents compact"), "{fresh}");
887        forget(&b);
888    }
889
890    #[test]
891    fn the_acp_reading_counts_calls_and_keeps_the_last_window() {
892        let b = block();
893        observe_acp(&b, 10_000, Some(200_000));
894        observe_acp(&b, 12_000, None);
895        let r = get(&b).unwrap();
896        assert_eq!((r.tokens, r.window, r.calls_since_compaction), (Some(12_000), Some(200_000), 2));
897        forget(&b);
898    }
899
900    fn held_for(block: &str) -> String {
901        let (message, _held) = crate::backend::reactive::held_notes::attach(block, "next");
902        message
903    }
904
905    #[test]
906    fn an_acp_compaction_says_what_it_left_at_the_first_reading_after_its_turn() {
907        let b = block();
908        observe_acp(&b, 400_000, Some(1_000_000));
909        begin_acp_compaction(&b);
910        assert!(get(&b).unwrap().compacting, "the hint holds back while it runs");
911        acp_compaction_carried_by(&b, 7);
912        observe_acp(&b, 380_000, Some(1_000_000));
913        assert!(get(&b).unwrap().compacting, "a reading during the turn is not the answer");
914        assert_eq!(acp_compaction_turn_ended(&b, 7, true), None);
915        assert!(!get(&b).unwrap().compacting);
916        assert_eq!(held_for(&b), "next", "nothing is said before the next reading");
917        observe_acp(&b, 55_000, Some(1_000_000));
918        assert!(held_for(&b).contains("Compacted: 400K to 55K tokens."));
919        let r = get(&b).unwrap();
920        assert_eq!((r.compactions, r.calls_since_compaction, r.compacting), (1, 0, false));
921        forget(&b);
922    }
923
924    #[test]
925    fn a_compaction_that_leaves_the_size_says_so_and_names_fresh() {
926        let b = block();
927        observe_acp(&b, 400_000, Some(1_000_000));
928        begin_acp_compaction(&b);
929        acp_compaction_carried_by(&b, 7);
930        acp_compaction_turn_ended(&b, 7, true);
931        observe_acp(&b, 398_000, Some(1_000_000));
932        let note = held_for(&b);
933        assert!(note.contains("still 398K tokens (it was 400K)") && note.contains("Agents fresh"), "{note}");
934        forget(&b);
935    }
936
937    #[test]
938    fn a_compaction_whose_turn_ended_in_an_error_says_it_did_not_run() {
939        let b = block();
940        observe_acp(&b, 400_000, Some(1_000_000));
941        begin_acp_compaction(&b);
942        acp_compaction_carried_by(&b, 7);
943        let note = acp_compaction_turn_ended(&b, 7, false).expect("an error end");
944        assert!(note.contains("did not run"), "{note}");
945        let r = get(&b).unwrap();
946        assert!(!r.compacting && r.compactions == 0);
947        assert_eq!(acp_compaction_turn_ended(&b, 7, true), None, "nothing is left to finish");
948        forget(&b);
949    }
950
951    /// The turn before a compaction can end after the compaction began: its end is not the compaction's (#8943).
952    #[test]
953    fn the_end_of_an_earlier_prompt_does_not_end_the_compaction() {
954        let b = block();
955        observe_acp(&b, 400_000, Some(1_000_000));
956        begin_acp_compaction(&b);
957        assert_eq!(acp_compaction_turn_ended(&b, 6, false), None, "before the /compact is written, no prompt carries it");
958        acp_compaction_carried_by(&b, 7);
959        assert_eq!(acp_compaction_turn_ended(&b, 6, false), None, "an earlier prompt's error does not drop it");
960        assert!(get(&b).unwrap().compacting);
961        observe_acp(&b, 390_000, Some(1_000_000));
962        assert_eq!(held_for(&b), "next", "a reading during the compaction is not its answer");
963        assert_eq!(acp_compaction_turn_ended(&b, 7, true), None);
964        observe_acp(&b, 60_000, Some(1_000_000));
965        assert!(held_for(&b).contains("Compacted: 400K to 60K tokens."));
966        forget(&b);
967    }
968
969    #[test]
970    fn a_compact_nobody_began_carries_no_compaction() {
971        let b = block();
972        observe_acp(&b, 400_000, Some(1_000_000));
973        acp_compaction_carried_by(&b, 7);
974        assert_eq!(acp_compaction_turn_ended(&b, 7, false), None);
975        forget(&b);
976    }
977
978    #[test]
979    fn a_compaction_that_could_not_be_sent_is_dropped() {
980        let b = block();
981        observe_acp(&b, 400_000, Some(1_000_000));
982        begin_acp_compaction(&b);
983        cancel_acp_compaction(&b);
984        observe_acp(&b, 410_000, Some(1_000_000));
985        assert_eq!(held_for(&b), "next");
986        assert_eq!(get(&b).unwrap().compactions, 0);
987        forget(&b);
988    }
989}