1use 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
23pub const SETTING_HINTS: &str = "agent:compacthints";
25pub const SETTING_HINT_AT: &str = "agent:compacthintat";
28pub const DEFAULT_HINT_AT: u64 = 400000; pub const SETTING_BACKSTOP_AT: &str = "agent:compactbackstopat";
32pub const DEFAULT_BACKSTOP_AT: u64 = 600000; pub const SETTING_FRESH_HINT_AT: &str = "agent:freshhintat";
36pub const DEFAULT_FRESH_HINT_AT: u64 = 150000; const HINT_REARM_BELOW: u64 = 250_000;
40pub const HINT_NOTE_KEY: &str = "compact-hint";
42pub const MIN_CALLS_BETWEEN: u64 = 50;
45pub const MIN_MS_BETWEEN: u64 = 10 * 60 * 1000;
46
47#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
49pub struct ContextReading {
50 pub model: Option<String>,
51 pub tokens: Option<u64>,
53 pub window: Option<u64>,
54 pub auto_compact_at: Option<u64>,
56 pub compacting: bool,
58 pub calls_since_compaction: u64,
60 #[serde(skip)]
62 pub from_acp: bool,
63 pub last_compaction_ms: Option<u64>,
65 pub compactions: u64,
67 pub observed_ms: Option<u64>,
69 #[serde(skip)]
71 pub last_self_compact_ms: Option<u64>,
72 #[serde(skip)]
74 pub compact_scheduled: bool,
75 #[serde(skip)]
77 pub hinted: bool,
78 #[serde(skip)]
80 pub task_boundary: bool,
81 #[serde(skip)]
84 pub fresh_by_choice: bool,
85 #[serde(skip)]
86 last_message_id: Option<String>,
87 #[serde(skip)]
89 acp_compaction: Option<AcpCompaction>,
90}
91
92#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
94struct AcpCompaction {
95 before: u64,
96 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
105pub fn install_config(config: Arc<crate::backend::wconfig::ConfigState>) {
107 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
120pub 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
125pub type TurnEndObserver = Box<dyn Fn(&str) + Send + Sync>;
128static TURN_END_OBSERVER: OnceLock<TurnEndObserver> = OnceLock::new();
129
130pub fn observe_container_turn_ends(observer: TurnEndObserver) {
132 let _ = TURN_END_OBSERVER.set(observer);
133}
134
135pub 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
150pub fn get(block_id: &str) -> Option<ContextReading> {
152 BY_BLOCK.lock().get(block_id).cloned()
153}
154
155pub fn tokens_now(block_id: &str) -> u64 {
158 BY_BLOCK.lock().get(block_id).and_then(|r| r.tokens).unwrap_or(0)
159}
160
161pub 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
171pub fn forget(block_id: &str) {
173 BY_BLOCK.lock().remove(block_id);
174}
175
176pub 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 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 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 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
229pub 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
239pub 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 r.task_boundary = false;
253 });
254}
255
256pub fn clear_task_boundary(block_id: &str) {
258 with(block_id, |r| r.task_boundary = false);
259}
260
261pub 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
268fn 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
283pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
294pub struct HintFor {
295 pub fresh_allowed: bool,
297 pub window_scaled: bool,
299 pub compact_offered: bool,
301}
302
303impl HintFor {
304 pub const NATIVE: Self = Self { fresh_allowed: true, window_scaled: false, compact_offered: true };
306
307 pub fn without_fresh() -> Self {
309 Self { fresh_allowed: false, ..Self::NATIVE }
310 }
311
312 pub fn acp(compact_offered: bool) -> Self {
314 Self { fresh_allowed: true, window_scaled: true, compact_offered }
315 }
316}
317
318pub fn hint(block_id: &str) -> &'static str {
320 hint_for(block_id, HintFor::NATIVE)
321}
322
323pub 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
336pub 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
366pub 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
378pub fn note_task_boundary(block_id: &str) {
380 with(block_id, |r| r.task_boundary = true);
381}
382
383pub fn mark_fresh_by_choice(block_id: &str) {
385 with(block_id, |r| r.fresh_by_choice = true);
386}
387
388pub fn take_fresh_by_choice(block_id: &str) -> bool {
390 with(block_id, |r| std::mem::take(&mut r.fresh_by_choice))
391}
392
393pub fn fresh_sent(block_id: &str, sent: bool) {
396 with(block_id, |r| {
397 r.compact_scheduled = false;
398 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
414pub 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
425fn 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
451pub fn take_turn_end_hint(block_id: &str) -> Option<String> {
457 take_turn_end_hint_for(block_id, true)
458}
459
460pub 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
466pub 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
485fn 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
512pub 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
519pub 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, ¬e);
523 }
524}
525
526pub const COMPACTION_NOTE_KEY: &str = "compaction-result";
528
529pub 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, ¬e);
546 }
547}
548
549pub 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
558pub 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
568pub fn cancel_acp_compaction(block_id: &str) {
570 with(block_id, |r| {
571 r.compacting = false;
572 r.acp_compaction = None;
573 });
574}
575
576pub 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
592fn 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 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 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 #[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 #[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 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 #[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 #[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}