Skip to main content

agentmux_srv_core/backend/memory/
delivery.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent's memory, delivered through Claude Code's `SessionStart` hook
5//! (docs/specs/SPEC_GLOBAL_MEMORY_DELIVERY_2026_09_27.md §7 P2).
6//!
7//! The hook's `additionalContext` reaches the model without showing as a
8//! conversation turn — but, measured against the CLI AgentMux bundles
9//! (2.1.280), only up to about 10,000 characters **per hook command**: past
10//! that the CLI swaps it for a saved file plus a 2 KB preview, which the model
11//! can't reliably read. Several hook commands' contexts are all delivered,
12//! each under its own cap, in the order the hooks *finish* (they run in
13//! parallel). So the memory is split into [`MAX_PART_CHARS`] parts, each
14//! labelled "part N of M", and [`HOOK_PARTS`] hook commands each ask for one.
15//!
16//! This module is pure: composition, splitting and the source rules. The
17//! per-session cache, the acknowledgements and the notice live in the server
18//! handlers.
19//!
20//! Personal Memory goes in as an index (`index.rs`), and the Global Memory the agent's startup file already
21//! carries is not sent again (SPEC_MEMORY_DELIVERY_INDEX_NOT_FULL_TEXT_2026_11_17.md).
22
23use super::index::{self, IndexPlan};
24
25/// The most characters one part carries. The measured per-hook cap is about
26/// 10,000; the margin covers the part label and any counting difference.
27pub const MAX_PART_CHARS: usize = 9_000;
28
29/// How many hook commands are installed, so the most a delivery can carry is
30/// `HOOK_PARTS * MAX_PART_CHARS` characters. A memory larger than that is cut
31/// at the end, and the last part says so.
32pub const HOOK_PARTS: usize = 8;
33
34/// Why memory is being delivered — the `SessionStart` hook's `source`, for the
35/// sources that get a delivery.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
37pub enum Reason {
38    /// A new session (`startup`).
39    Startup,
40    /// `/clear` started a new, empty conversation.
41    Clear,
42    /// The conversation was just compacted.
43    Compact,
44}
45
46impl Reason {
47    /// The reason for a hook `source`, or `None` when that source gets no
48    /// delivery: `resume` and `fork` continue a conversation that is intact,
49    /// and the startup file still carries the memory (owner decision D10).
50    pub fn from_hook_source(source: &str) -> Option<Reason> {
51        match source {
52            "startup" => Some(Reason::Startup),
53            "clear" => Some(Reason::Clear),
54            "compact" => Some(Reason::Compact),
55            _ => None,
56        }
57    }
58
59    pub fn as_str(self) -> &'static str {
60        match self {
61            Reason::Startup => "startup",
62            Reason::Clear => "clear",
63            Reason::Compact => "compact",
64        }
65    }
66
67    fn clause(self) -> &'static str {
68        match self {
69            Reason::Startup => "This is the start of a new session.",
70            Reason::Clear => "The conversation was just cleared.",
71            Reason::Compact => COMPACTION_CLAUSE,
72        }
73    }
74}
75
76/// Whether an entry is Global Memory (Operator Config included) or the agent's
77/// own Personal Memory.
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub enum Tier {
80    Global,
81    Personal,
82}
83
84impl Tier {
85    pub fn as_str(self) -> &'static str {
86        match self {
87            Tier::Global => "global",
88            Tier::Personal => "personal",
89        }
90    }
91}
92
93/// One memory entry: a Global Memory section as the startup file carries it,
94/// or one Personal Memory file.
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub struct Entry {
97    /// What the notice calls it (`[AgentMux System] MuxAPI`, `notes.md`, …).
98    pub label: String,
99    pub tier: Tier,
100    /// The full text sent to the model.
101    pub text: String,
102    /// The entry's own name: the Global Memory entry's name, or the file name.
103    pub name: String,
104    /// Global Memory only: AgentMux's own system tier, not the workspace's.
105    pub system: bool,
106    /// Global Memory only: the entry's id.
107    pub bundle_id: Option<String>,
108    /// Personal Memory only: the file it was read from.
109    pub path: Option<String>,
110}
111
112/// The text delivered to the model: the Global Memory block (its sections
113/// joined exactly as the startup file joins them), the Personal Memory files,
114/// and — after a compaction — AgentMux's running summary, which the provider's
115/// own compaction summary can't drop.
116///
117/// `None` when there is nothing to deliver.
118#[cfg(test)]
119pub fn compose(entries: &[Entry], reason: Reason, running_summary: Option<&str>) -> Option<String> {
120    compose_items(entries, reason, running_summary).map(|c| c.text)
121}
122
123/// Where one item sits in a composed delivery, in characters
124/// (SPEC_CONTEXT_DELIVERY_2026_09_30 §3.4 step 3).
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126pub struct ItemSpan {
127    /// The item's index in `entries`, or `None` for the running summary.
128    pub entry: Option<usize>,
129    pub start: usize,
130    pub end: usize,
131}
132
133/// A composed delivery and where each item sits in it.
134#[derive(Debug, Clone, PartialEq, Eq)]
135pub struct Composed {
136    pub text: String,
137    /// In delivery order: Global Memory, Personal Memory, then the summary.
138    pub spans: Vec<ItemSpan>,
139}
140
141/// A string being built, with its length in characters kept alongside.
142struct Tracked {
143    out: String,
144    chars: usize,
145}
146
147impl Tracked {
148    /// Appends `s` and returns the character range it now occupies.
149    fn push(&mut self, s: &str) -> (usize, usize) {
150        let start = self.chars;
151        self.out.push_str(s);
152        self.chars += s.chars().count();
153        (start, self.chars)
154    }
155}
156
157/// [`compose`], also recording where each item landed so the notice can say
158/// which items a cut delivery carried whole, in part, or not at all.
159#[cfg(any(test, feature = "test-support"))]
160pub fn compose_items(entries: &[Entry], reason: Reason, running_summary: Option<&str>) -> Option<Composed> {
161    compose_items_with(entries, reason, running_summary, false)
162}
163
164/// How much of the Global Memory the agent's startup file already carries
165/// (SPEC_MEMORY_DELIVERY_INDEX_NOT_FULL_TEXT_2026_11_17.md §3.1). A file AgentMux wrote that holds a section
166/// byte for byte carries it; a section the file lacks, or holds in an older form, is newer than the file and
167/// is sent whole.
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub enum StartupCarry {
170    /// No AgentMux-owned startup file carries any current section: the whole Global Memory is sent.
171    None,
172    /// Every current section is in the file: none is sent.
173    All,
174    /// Some are: only the newer ones are sent.
175    Partly,
176}
177
178/// What a delivery carries besides the entries it sends in full: how much Global Memory the startup file
179/// holds, the Personal Memory index, and a closing note (`memory::fit`'s left-out note and pruning nudge).
180pub struct Layout<'a> {
181    pub carry: StartupCarry,
182    pub index: IndexPlan<'a>,
183    pub tail: Option<&'a str>,
184}
185
186impl<'a> Layout<'a> {
187    /// A delivery with no index and no tail.
188    pub fn plain(carry: StartupCarry) -> Layout<'a> {
189        Layout { carry, index: IndexPlan { files: &[], over_limit: &[], always: 0, tool_only: false }, tail: None }
190    }
191
192    /// Whether there is a closing note to deliver. A note alone is a delivery: a Global entry too big to fit leaves
193    /// nothing else, and the agent still has to be told it was left out.
194    fn has_tail(&self) -> bool {
195        self.tail.is_some_and(|t| !t.trim().is_empty())
196    }
197}
198
199impl From<bool> for StartupCarry {
200    fn from(in_file: bool) -> Self {
201        if in_file { StartupCarry::All } else { StartupCarry::None }
202    }
203}
204
205/// [`compose_items`], saying so when the Global Memory was left out because
206/// the agent's startup file already carries it (a new Claude session that
207/// loaded `AGENTMUX_MEMORY.md` or an AgentMux-owned `CLAUDE.md`;
208/// SPEC_LAUNCH_CONTEXT_WORKSPACE_RULE_AND_STARTUP_FILES_2026_09_30.md §4.4).
209pub fn compose_items_with(
210    entries: &[Entry],
211    reason: Reason,
212    running_summary: Option<&str>,
213    global_in_startup_file: bool,
214) -> Option<Composed> {
215    compose_items_tail(entries, reason, running_summary, &Layout::plain(global_in_startup_file.into()))
216}
217
218/// The opening of a delivery: what it is, what the startup file already holds, and what follows.
219fn opening(clause: &str, layout: &Layout, has_global: bool, has_personal: bool) -> String {
220    let global = match (layout.carry, has_global) {
221        (StartupCarry::All, _) => "Your Global Memory is already in your startup instructions, so it isn't repeated here. ",
222        (StartupCarry::Partly, _) => {
223            "Your startup instructions carry your Global Memory except the entries below, which are newer than that copy: read them now. "
224        }
225        (StartupCarry::None, true) => "Read your Global Memory below now. ",
226        (StartupCarry::None, false) => "",
227    };
228    let personal = if has_personal { "Your Personal Memory follows as an index of its files. " } else { "" };
229    format!("{clause} {global}{personal}").trim_end().to_string()
230}
231
232/// [`compose_items_with`], with the Personal Memory index and a closing note (`memory::fit`'s left-out note and
233/// pruning nudge) after the memory and before the running summary.
234pub fn compose_items_tail(
235    entries: &[Entry],
236    reason: Reason,
237    running_summary: Option<&str>,
238    layout: &Layout,
239) -> Option<Composed> {
240    let global: Vec<usize> = (0..entries.len()).filter(|&i| entries[i].tier == Tier::Global).collect();
241    let personal: Vec<usize> = (0..entries.len()).filter(|&i| entries[i].tier == Tier::Personal).collect();
242    let summary = running_summary.filter(|s| !s.trim().is_empty() && reason == Reason::Compact);
243    let has_personal = !personal.is_empty() || !layout.index.is_empty();
244    if global.is_empty() && !has_personal && summary.is_none() && !layout.has_tail() {
245        return None;
246    }
247
248    let mut b = Tracked { out: String::new(), chars: 0 };
249    b.push(&format!("AgentMux memory for this agent. {}\n\n", opening(reason.clause(), layout, !global.is_empty(), has_personal)));
250    let tail = layout.tail;
251    let mut spans = Vec::new();
252    let mut wrote_section = push_sections(&mut b, entries, &global, &personal, layout, &mut spans);
253    if let Some(tail) = tail.filter(|t| !t.trim().is_empty()) {
254        if wrote_section {
255            b.push("\n");
256        }
257        b.push(tail);
258        b.push("\n");
259        wrote_section = true;
260    }
261    if let Some(summary) = summary {
262        if wrote_section {
263            b.push("\n");
264        }
265        let (start, end) = b.push(summary);
266        spans.push(ItemSpan { entry: None, start, end });
267    }
268    Some(Composed { text: b.out, spans })
269}
270
271/// `# Global Memory (n entries)` and `# Personal Memory (…)`, each item's
272/// text whole, sections separated by a blank line; empty sections left out.
273/// The frontend's `composeReinjectionMessage` writes the same, so a
274/// re-delivery carries the startup block's sections byte for byte. Returns
275/// whether anything was written.
276fn push_sections(
277    b: &mut Tracked,
278    entries: &[Entry],
279    global: &[usize],
280    personal: &[usize],
281    layout: &Layout,
282    spans: &mut Vec<ItemSpan>,
283) -> bool {
284    let mut wrote_section = false;
285    // The index goes first and stays under its own budget, so it sits whole in the first part.
286    if let Some(index) = index::render(&layout.index) {
287        b.push(&index);
288        wrote_section = true;
289    }
290    let global_heading = if layout.carry == StartupCarry::Partly { "Global Memory newer than your startup copy" } else { "Global Memory" };
291    let sections = [
292        (global_heading, global, crate::backend::storage::bundles::GLOBAL_SECTION_SEPARATOR),
293        ("Personal Memory marked always", personal, "\n---\n"),
294    ];
295    for (heading, list, separator) in sections {
296        if list.is_empty() {
297            continue;
298        }
299        if wrote_section {
300            b.push("\n");
301        }
302        let noun = if list.len() == 1 { "entry" } else { "entries" };
303        b.push(&format!("# {heading} ({} {noun})\n", list.len()));
304        for (k, &i) in list.iter().enumerate() {
305            if k > 0 {
306                b.push(separator);
307            }
308            let (start, end) = b.push(&entries[i].text);
309            spans.push(ItemSpan { entry: Some(i), start, end });
310        }
311        b.push("\n");
312        wrote_section = true;
313    }
314    wrote_section
315}
316
317/// The sentence after the signature when a compaction caused the delivery:
318/// one definition for the hook's text, the fallback's, and the check that
319/// adds the running summary (`continuity_state`).
320pub const COMPACTION_CLAUSE: &str = "Your recent conversation was just compacted into a summary.";
321
322/// The sentence every hidden memory re-delivery opens with, whatever the
323/// reason: what `is_hidden_reinjection_text` (srv) and
324/// `isMemoryReinjectionMessage` (frontend) recognise it by.
325pub const REINJECTION_SIGNATURE: &str = "Your memory was reinjected because your working context was just reset.";
326
327/// Why the frontend's fallback re-delivers memory
328/// (`memory-reinjection.ts`'s `ReinjectionReason`).
329#[derive(Debug, Clone, Copy, PartialEq, Eq)]
330pub enum FallbackReason {
331    /// The conversation was compacted.
332    Compaction,
333    /// AgentMux couldn't resume the prior session, so a fresh one started.
334    FreshSession,
335}
336
337impl FallbackReason {
338    pub fn from_wire(reason: &str) -> Option<Self> {
339        match reason {
340            "compaction" => Some(Self::Compaction),
341            "fresh_session" => Some(Self::FreshSession),
342            _ => None,
343        }
344    }
345
346    /// The second sentence — the frontend's `REASON_CLAUSE`, verbatim.
347    pub fn clause(self) -> &'static str {
348        match self {
349            Self::Compaction => COMPACTION_CLAUSE,
350            Self::FreshSession => {
351                "AgentMux could not resume this agent's prior session, so a fresh one was started. Any record \
352                 of the prior conversation AgentMux had came with your first message, in an \
353                 <agentmux-continuation> block."
354            }
355        }
356    }
357}
358
359/// The fallback's hidden message, composed on srv
360/// (SPEC_CONTEXT_DELIVERY_2026_09_30.md §3.4 step 2, CD2b). Its wire format
361/// is the frontend's `composeReinjectionMessage`, unchanged: the
362/// `<system-reminder>` envelope and [`REINJECTION_SIGNATURE`] are how srv's
363/// digest, the continuation packet and replay recognise a hidden turn. No
364/// part cap: the fallback is one message. `None` when there is no memory.
365/// A compaction's running summary is not here: srv's input handler appends
366/// it (`continuity_state::with_state_after_compaction`).
367pub fn compose_fallback(entries: &[Entry], reason: FallbackReason) -> Option<Composed> {
368    compose_fallback_with(entries, reason, false)
369}
370
371/// [`compose_fallback`], saying so when the Global Memory is left out because
372/// the new session's startup file already carries it (`entries` then holds
373/// the Personal Memory only), as the hook's delivery does
374/// ([`compose_items_with`]).
375pub fn compose_fallback_with(entries: &[Entry], reason: FallbackReason, global_in_startup_file: bool) -> Option<Composed> {
376    compose_fallback_layout(entries, reason, &Layout::plain(global_in_startup_file.into()))
377}
378
379/// [`compose_fallback_with`] with the Personal Memory index and a closing note, as the hook's delivery has them.
380/// No part cap here, but the same classes: the index first, files marked always, the Global Memory the startup
381/// file lacks, then the note.
382pub fn compose_fallback_layout(entries: &[Entry], reason: FallbackReason, layout: &Layout) -> Option<Composed> {
383    let global: Vec<usize> = (0..entries.len()).filter(|&i| entries[i].tier == Tier::Global).collect();
384    let personal: Vec<usize> = (0..entries.len()).filter(|&i| entries[i].tier == Tier::Personal).collect();
385    let has_personal = !personal.is_empty() || !layout.index.is_empty();
386    if global.is_empty() && !has_personal && !layout.has_tail() {
387        return None;
388    }
389    let mut b = Tracked { out: String::new(), chars: 0 };
390    b.push(&format!(
391        "<system-reminder>\n{REINJECTION_SIGNATURE} {}\n\n",
392        opening(reason.clause(), layout, !global.is_empty(), has_personal)
393    ));
394    let mut spans = Vec::new();
395    let wrote = push_sections(&mut b, entries, &global, &personal, layout, &mut spans);
396    if let Some(tail) = layout.tail.filter(|t| !t.trim().is_empty()) {
397        if wrote {
398            b.push("\n");
399        }
400        b.push(tail);
401        b.push("\n");
402    }
403    b.push("</system-reminder>\n");
404    Some(Composed { text: b.out, spans })
405}
406
407/// What opens the catch-up block of a resume phase's message, and what
408/// `is_hidden_reinjection_text` (srv) and the stream parser (frontend) know
409/// the message by when it carries no memory. The block is AgentMux's, not the
410/// user's: the pane shows a card for it, never the text, but the agent's reply
411/// is shown (SPEC_RESUME_PHASE_CATCH_UP_TURN_2026_10_13.md §3.3).
412pub const CATCH_UP_SIGNATURE: &str = "AgentMux catch-up:";
413
414/// Which resume phase a catch-up turn follows.
415#[derive(Debug, Clone, Copy, PartialEq, Eq)]
416pub enum CatchUpKind {
417    /// A fresh session started and carries AgentMux's record of the
418    /// conversation (an account switch, a refused or rejected resume).
419    FreshSession,
420    /// The conversation was compacted.
421    Compaction,
422    /// The user resumed the conversation; the provider kept its context.
423    Resumed,
424}
425
426impl CatchUpKind {
427    pub fn from_wire(reason: &str) -> Option<Self> {
428        match reason {
429            "fresh_session" => Some(Self::FreshSession),
430            "compaction" => Some(Self::Compaction),
431            "resumed" => Some(Self::Resumed),
432            _ => None,
433        }
434    }
435
436    /// The memory event this phase shares with the `SessionStart` hook, when
437    /// the phase delivers memory at all.
438    pub fn memory_reason(self) -> Option<FallbackReason> {
439        match self {
440            Self::FreshSession => Some(FallbackReason::FreshSession),
441            Self::Compaction => Some(FallbackReason::Compaction),
442            Self::Resumed => None,
443        }
444    }
445
446    fn situation(self) -> &'static str {
447        match self {
448            Self::FreshSession => {
449                "You are picking up this conversation in a new session, for example after an account switch."
450            }
451            Self::Compaction => "You are picking up this conversation after a compaction.",
452            Self::Resumed => "You are picking up this conversation after it was resumed.",
453        }
454    }
455}
456
457/// What the agent is told to do once it has read what it was given. One
458/// constant so every resume phase says the same thing.
459const CATCH_UP_INSTRUCTION: &str = "Review the conversation and anything AgentMux just gave you. Before replying you may re-check real state \
460read-only (git status, open pull requests, files) to confirm what is still true; do not change anything yet. \
461Then reply to the user in a few lines: where you are picking up (the last thing they asked and whether it was \
462done), anything in flight or waiting on them, and two or three suggested next steps they can choose from. Then \
463stop and wait for them.";
464
465/// The message of a catch-up turn: the memory re-delivery when `memory` is the
466/// text of one (`compose_fallback`), then the catch-up block, in one
467/// `<system-reminder>`. Without memory the block stands alone: the hook
468/// already delivered it, or the phase delivers none.
469pub fn compose_catch_up(kind: CatchUpKind, memory: Option<&str>) -> String {
470    let mut out = match memory {
471        Some(text) => text.trim_end().trim_end_matches("</system-reminder>").trim_end().to_string() + "\n\n",
472        None => "<system-reminder>\n".to_string(),
473    };
474    out.push_str(&format!("{CATCH_UP_SIGNATURE} {} {CATCH_UP_INSTRUCTION}\n</system-reminder>\n", kind.situation()));
475    out
476}
477
478/// The last words of the instruction, which end every catch-up block. The
479/// frontend's `isCatchUpMessage` matches the block by them too.
480pub const CATCH_UP_TAIL: &str = "Then stop and wait for them.";
481
482/// Whether `text` is a catch-up message, which has no reinjection signature
483/// when it carries no memory. Its input is hidden, but the agent's reply is
484/// shown and read: the ambient digest and the continuation record skip the
485/// input without hiding what follows, and the hidden-reinjection gate
486/// (`set_hidden_reinjection_active`) is not set for it.
487///
488/// Structural, not a substring: the block is the single last line of the
489/// message, so a memory body that happens to contain the marker is not taken
490/// for one.
491pub fn is_catch_up_text(text: &str) -> bool {
492    if !text.starts_with("<system-reminder>") {
493        return false;
494    }
495    let Some(body) = text.strip_suffix("\n</system-reminder>\n") else { return false };
496    let Some(at) = body.rfind(&format!("\n{CATCH_UP_SIGNATURE} ")) else { return false };
497    let block = &body[at + 1..];
498    !block.contains('\n') && block.ends_with(CATCH_UP_TAIL)
499}
500
501/// How much of one item a delivery carried.
502#[derive(Debug, Clone, Copy, PartialEq, Eq)]
503pub enum Delivered {
504    Full,
505    /// Cut by the part cap: this many of its characters went out.
506    Partial(usize),
507    Omitted,
508    /// Listed in the Personal Memory index, not sent in full.
509    Indexed,
510}
511
512impl Delivered {
513    /// Where `span` falls against the first `delivered_chars` characters of
514    /// the composed text, which is all a cut delivery carries.
515    pub fn of(span: &ItemSpan, delivered_chars: usize) -> Delivered {
516        if span.end <= delivered_chars {
517            Delivered::Full
518        } else if span.start >= delivered_chars {
519            Delivered::Omitted
520        } else {
521            Delivered::Partial(delivered_chars - span.start)
522        }
523    }
524
525    pub fn as_str(self) -> &'static str {
526        match self {
527            Delivered::Full => "full",
528            Delivered::Partial(_) => "partial",
529            Delivered::Omitted => "omitted",
530            Delivered::Indexed => "indexed",
531        }
532    }
533}
534
535/// `text` split into parts of at most `max_chars` characters each, label
536/// included, every one saying which part of how many it is (the hooks
537/// deliver in the order they finish, not in order). Cuts at a line end where
538/// one falls in the second half of a part, else mid-line. More than
539/// `max_parts` parts: the text is cut, and the last part ends with a note
540/// giving how much was left out.
541#[cfg(test)]
542pub fn split_into_parts(text: &str, max_chars: usize, max_parts: usize) -> Vec<String> {
543    split_into_parts_counted(text, max_chars, max_parts).0
544}
545
546/// [`split_into_parts`], plus how many of `text`'s characters the parts carry:
547/// all of them unless the text was cut.
548pub fn split_into_parts_counted(text: &str, max_chars: usize, max_parts: usize) -> (Vec<String>, usize) {
549    // The label is at most "[AgentMux memory — part 99 of 99]\n".
550    const LABEL_ROOM: usize = 40;
551    const CUT_NOTE_ROOM: usize = 120;
552    let budget = max_chars.saturating_sub(LABEL_ROOM).max(1);
553
554    let chars: Vec<char> = text.chars().collect();
555    let mut chunks: Vec<String> = Vec::new();
556    let mut at = 0;
557    while at < chars.len() {
558        let end = (at + budget).min(chars.len());
559        let cut = if end == chars.len() {
560            end
561        } else {
562            // The last newline in the second half of this chunk, if any.
563            (at + budget / 2..end).rev().find(|&i| chars[i] == '\n').map_or(end, |i| i + 1)
564        };
565        chunks.push(chars[at..cut].iter().collect());
566        at = cut;
567    }
568
569    let mut delivered = chars.len();
570    if chunks.len() > max_parts {
571        let kept: usize = chunks[..max_parts].iter().map(|c| c.chars().count()).sum();
572        let omitted = chars.len() - kept;
573        chunks.truncate(max_parts);
574        let last = chunks.last_mut().expect("max_parts >= 1");
575        // Make room for the note inside the last part's budget.
576        let keep = last.chars().count().min(budget.saturating_sub(CUT_NOTE_ROOM));
577        let dropped = last.chars().count() - keep;
578        *last = last.chars().take(keep).collect();
579        last.push_str(&format!(
580            "\n\n[AgentMux: memory cut here — {} more characters did not fit in one delivery.]",
581            omitted + dropped
582        ));
583        delivered = kept - dropped;
584    }
585
586    let of = chunks.len();
587    let parts = chunks
588        .into_iter()
589        .enumerate()
590        .map(|(i, c)| format!("[AgentMux memory — part {} of {of}]\n{c}", i + 1))
591        .collect();
592    (parts, delivered)
593}
594
595#[cfg(test)]
596mod tests {
597    use super::*;
598
599    fn entry(label: &str, tier: Tier, text: &str) -> Entry {
600        Entry { label: label.into(), tier, text: text.into(), name: label.into(), system: false, bundle_id: None, path: None }
601    }
602
603    #[test]
604    fn spans_point_at_each_item_in_the_composed_text() {
605        let entries = [
606            entry("A", Tier::Global, "alpha"),
607            entry("n.md", Tier::Personal, "notes"),
608            entry("B", Tier::Global, "beta"),
609        ];
610        let c = compose_items(&entries, Reason::Compact, Some("summary")).unwrap();
611        assert_eq!(c.text, compose(&entries, Reason::Compact, Some("summary")).unwrap(), "same text as compose");
612        let chars: Vec<char> = c.text.chars().collect();
613        let at = |s: &ItemSpan| chars[s.start..s.end].iter().collect::<String>();
614        // Global first (in entry order), then Personal, then the summary.
615        let order: Vec<Option<usize>> = c.spans.iter().map(|s| s.entry).collect();
616        assert_eq!(order, vec![Some(0), Some(2), Some(1), None]);
617        assert_eq!(c.spans.iter().map(at).collect::<Vec<_>>(), vec!["alpha", "beta", "notes", "summary"]);
618    }
619
620    #[test]
621    fn spans_are_counted_in_characters_not_bytes() {
622        let entries = [entry("é", Tier::Global, "ééé"), entry("x", Tier::Personal, "xyz")];
623        let c = compose_items(&entries, Reason::Startup, None).unwrap();
624        let chars: Vec<char> = c.text.chars().collect();
625        assert_eq!(chars[c.spans[1].start..c.spans[1].end].iter().collect::<String>(), "xyz");
626    }
627
628    #[test]
629    fn delivered_status_follows_the_cut() {
630        let span = ItemSpan { entry: Some(0), start: 100, end: 200 };
631        assert_eq!(Delivered::of(&span, 200), Delivered::Full);
632        assert_eq!(Delivered::of(&span, 5_000), Delivered::Full);
633        assert_eq!(Delivered::of(&span, 150), Delivered::Partial(50));
634        assert_eq!(Delivered::of(&span, 100), Delivered::Omitted);
635        assert_eq!(Delivered::of(&span, 10), Delivered::Omitted);
636    }
637
638    #[test]
639    fn counted_split_reports_everything_when_uncut() {
640        let text = "z".repeat(20_000);
641        let (parts, delivered) = split_into_parts_counted(&text, MAX_PART_CHARS, HOOK_PARTS);
642        assert_eq!(delivered, text.chars().count());
643        assert_eq!(parts, split_into_parts(&text, MAX_PART_CHARS, HOOK_PARTS));
644    }
645
646    #[test]
647    fn counted_split_reports_exactly_the_delivered_prefix_when_cut() {
648        let text = (0..200_000).map(|i| char::from(b'a' + (i % 26) as u8)).collect::<String>();
649        let (parts, delivered) = split_into_parts_counted(&text, MAX_PART_CHARS, HOOK_PARTS);
650        assert!(delivered < text.chars().count());
651        let carried: String = parts
652            .iter()
653            .map(|p| p.split_once('\n').unwrap().1.split("\n\n[AgentMux: memory cut here").next().unwrap())
654            .collect();
655        assert_eq!(carried.chars().count(), delivered);
656        assert!(text.starts_with(&carried), "the parts carry a prefix of the text");
657    }
658
659    #[test]
660    fn resume_and_fork_get_no_delivery() {
661        assert_eq!(Reason::from_hook_source("startup"), Some(Reason::Startup));
662        assert_eq!(Reason::from_hook_source("clear"), Some(Reason::Clear));
663        assert_eq!(Reason::from_hook_source("compact"), Some(Reason::Compact));
664        assert_eq!(Reason::from_hook_source("resume"), None, "D10");
665        assert_eq!(Reason::from_hook_source("fork"), None, "a fork continues an intact conversation");
666        assert_eq!(Reason::from_hook_source("anything"), None);
667    }
668
669    #[test]
670    fn composes_global_block_then_personal_then_summary_on_compact() {
671        let entries = [
672            entry("[AgentMux System] App API", Tier::Global, "IMPORTANT: …\n\n# [AgentMux System] App API\n\napi"),
673            entry("[Workspace] Rules", Tier::Global, "# [Workspace] Rules\n\nrules"),
674            entry("notes.md", Tier::Personal, "my notes"),
675        ];
676        let text = compose(&entries, Reason::Compact, Some("# Running summary …\nsummary")).unwrap();
677        let global_block = format!(
678            "IMPORTANT: …\n\n# [AgentMux System] App API\n\napi{}# [Workspace] Rules\n\nrules",
679            crate::backend::storage::bundles::GLOBAL_SECTION_SEPARATOR
680        );
681        assert!(text.contains(&format!("# Global Memory (2 entries)\n{global_block}\n")), "{text}");
682        assert!(text.contains("# Personal Memory marked always (1 entry)\nmy notes\n"));
683        let (g, p, s) = (text.find("# Global").unwrap(), text.find("# Personal").unwrap(), text.find("# Running summary").unwrap());
684        assert!(g < p && p < s);
685        assert!(text.contains("just compacted"));
686    }
687
688    #[test]
689    fn the_summary_rides_only_on_a_compaction() {
690        let entries = [entry("notes.md", Tier::Personal, "n")];
691        let startup = compose(&entries, Reason::Startup, Some("# Running summary …")).unwrap();
692        assert!(!startup.contains("Running summary"));
693        assert!(startup.contains("start of a new session"));
694    }
695
696    #[test]
697    fn nothing_to_deliver_is_none() {
698        assert_eq!(compose(&[], Reason::Startup, None), None);
699        assert_eq!(compose(&[], Reason::Startup, Some("summary")), None, "no summary outside a compaction");
700        assert!(compose(&[], Reason::Compact, Some("summary")).is_some(), "a summary alone is worth delivering");
701    }
702
703    #[test]
704    fn small_text_is_one_labelled_part() {
705        let parts = split_into_parts("hello", MAX_PART_CHARS, HOOK_PARTS);
706        assert_eq!(parts, vec!["[AgentMux memory — part 1 of 1]\nhello".to_string()]);
707    }
708
709    #[test]
710    fn every_part_fits_the_cap_and_the_parts_rebuild_the_text() {
711        let text = (0..3_000).map(|i| format!("line {i} of the memory\n")).collect::<String>();
712        let parts = split_into_parts(&text, MAX_PART_CHARS, HOOK_PARTS);
713        assert!(parts.len() > 1);
714        for (i, p) in parts.iter().enumerate() {
715            assert!(p.chars().count() <= MAX_PART_CHARS, "part {i} is {} chars", p.chars().count());
716            assert!(p.starts_with(&format!("[AgentMux memory — part {} of {}]\n", i + 1, parts.len())));
717        }
718        let rebuilt: String = parts.iter().map(|p| p.split_once('\n').unwrap().1).collect();
719        assert_eq!(rebuilt, text);
720        assert!(parts[..parts.len() - 1].iter().all(|p| p.ends_with('\n')), "cut at line ends");
721    }
722
723    #[test]
724    fn a_long_line_is_cut_mid_line() {
725        let text = "x".repeat(20_000);
726        let parts = split_into_parts(&text, MAX_PART_CHARS, HOOK_PARTS);
727        assert!(parts.iter().all(|p| p.chars().count() <= MAX_PART_CHARS));
728        let rebuilt: String = parts.iter().map(|p| p.split_once('\n').unwrap().1).collect();
729        assert_eq!(rebuilt, text);
730    }
731
732    #[test]
733    fn more_than_the_hooks_can_carry_is_cut_with_a_note() {
734        let text = "y".repeat(MAX_PART_CHARS * (HOOK_PARTS + 2));
735        let parts = split_into_parts(&text, MAX_PART_CHARS, HOOK_PARTS);
736        assert_eq!(parts.len(), HOOK_PARTS);
737        assert!(parts.iter().all(|p| p.chars().count() <= MAX_PART_CHARS));
738        let last = parts.last().unwrap();
739        assert!(last.contains("memory cut here"), "{}", &last[last.len() - 200..]);
740        let kept: usize = parts
741            .iter()
742            .map(|p| p.split_once('\n').unwrap().1.split("\n\n[AgentMux: memory cut here").next().unwrap().len())
743            .sum();
744        let omitted: usize = last.rsplit_once("— ").unwrap().1.split(' ').next().unwrap().parse().unwrap();
745        assert_eq!(kept + omitted, text.len(), "the note's count is exact");
746    }
747
748    #[test]
749    fn multibyte_text_is_counted_in_characters() {
750        let text = "é".repeat(12_000);
751        let parts = split_into_parts(&text, MAX_PART_CHARS, HOOK_PARTS);
752        assert!(parts.iter().all(|p| p.chars().count() <= MAX_PART_CHARS));
753        let rebuilt: String = parts.iter().map(|p| p.split_once('\n').unwrap().1).collect();
754        assert_eq!(rebuilt, text);
755    }
756
757    /// The fallback's wire format is the frontend's `composeReinjectionMessage`
758    /// byte for byte (CD2b). `memory-reinjection.test.ts` pins this same
759    /// literal for the same entries, so the two can't drift.
760    #[test]
761    fn compose_fallback_writes_the_frontends_exact_message() {
762        let entries = vec![
763            Entry {
764                label: "[AgentMux System] App API".into(),
765                tier: Tier::Global,
766                text: "# [AgentMux System] App API\n\nG1".into(),
767                name: "App API".into(),
768                system: true,
769                bundle_id: Some("b1".into()),
770                path: None,
771            },
772            Entry {
773                label: "[Workspace] Rules".into(),
774                tier: Tier::Global,
775                text: "# [Workspace] Rules\n\nG2".into(),
776                name: "Rules".into(),
777                system: false,
778                bundle_id: Some("b2".into()),
779                path: None,
780            },
781            Entry {
782                label: "notes.md".into(),
783                tier: Tier::Personal,
784                text: "P1".into(),
785                name: "notes.md".into(),
786                system: false,
787                bundle_id: None,
788                path: Some("/m/notes.md".into()),
789            },
790        ];
791        let c = compose_fallback(&entries, FallbackReason::Compaction).unwrap();
792        assert_eq!(
793            c.text,
794            "<system-reminder>\n\
795             Your memory was reinjected because your working context was just reset. Your recent conversation was just compacted into a summary. Read your Global Memory below now. Your Personal Memory follows as an index of its files.\n\n\
796             # Global Memory (2 entries)\n\
797             # [AgentMux System] App API\n\nG1\n\n---\n\n# [Workspace] Rules\n\nG2\n\
798             \n\
799             # Personal Memory marked always (1 entry)\n\
800             P1\n\
801             </system-reminder>\n"
802        );
803        assert_eq!(c.spans.len(), 3);
804        assert!(crate::ambient::digest::is_hidden_reinjection_text(&c.text));
805
806        let fresh = compose_fallback(&entries[2..], FallbackReason::FreshSession).unwrap();
807        assert!(fresh.text.contains(
808            "AgentMux could not resume this agent's prior session, so a fresh one was started. Any record of the prior \
809             conversation AgentMux had came with your first message, in an <agentmux-continuation> block."
810        ));
811        assert!(!fresh.text.contains("# Global Memory"), "an empty section is left out");
812        assert_eq!(compose_fallback(&[], FallbackReason::Compaction), None);
813    }
814
815    #[test]
816    fn a_fresh_session_fallback_without_the_global_memory_says_where_it_is() {
817        let personal = vec![Entry {
818            label: "notes.md".into(),
819            tier: Tier::Personal,
820            text: "P1".into(),
821            name: "notes.md".into(),
822            system: false,
823            bundle_id: None,
824            path: None,
825        }];
826        let c = compose_fallback_with(&personal, FallbackReason::FreshSession, true).unwrap();
827        assert!(c.text.contains("Your Global Memory is already in your startup"), "{}", c.text);
828        assert!(!c.text.contains("# Global Memory"), "{}", c.text);
829        assert!(c.text.contains("# Personal Memory marked always (1 entry)\nP1\n"));
830        assert!(crate::ambient::digest::is_hidden_reinjection_text(&c.text), "still a hidden reinjection");
831        assert_eq!(compose_fallback_with(&[], FallbackReason::FreshSession, true), None, "nothing left to say");
832        assert_eq!(compose_fallback_with(&personal, FallbackReason::FreshSession, false), compose_fallback(&personal, FallbackReason::FreshSession));
833    }
834
835    #[test]
836    fn fallback_reasons_are_the_frontends() {
837        assert_eq!(FallbackReason::from_wire("compaction"), Some(FallbackReason::Compaction));
838        assert_eq!(FallbackReason::from_wire("fresh_session"), Some(FallbackReason::FreshSession));
839        assert_eq!(FallbackReason::from_wire("startup"), None);
840    }
841
842    #[test]
843    fn a_delivery_without_the_global_memory_says_where_it_is() {
844        let personal = vec![Entry {
845            label: "notes.md".into(),
846            tier: Tier::Personal,
847            text: "P1".into(),
848            name: "notes.md".into(),
849            system: false,
850            bundle_id: None,
851            path: None,
852        }];
853        let c = compose_items_with(&personal, Reason::Startup, None, true).unwrap();
854        assert!(c.text.contains("Your Global Memory is already in your startup instructions"), "{}", c.text);
855        assert!(!c.text.contains("# Global Memory"));
856        assert!(c.text.contains("# Personal Memory marked always (1 entry)\nP1\n"));
857        assert_eq!(compose_items_with(&[], Reason::Startup, None, true), None);
858    }
859    #[test]
860    fn catch_up_kinds_are_the_frontends() {
861        assert_eq!(CatchUpKind::from_wire("fresh_session"), Some(CatchUpKind::FreshSession));
862        assert_eq!(CatchUpKind::from_wire("compaction"), Some(CatchUpKind::Compaction));
863        assert_eq!(CatchUpKind::from_wire("resumed"), Some(CatchUpKind::Resumed));
864        assert_eq!(CatchUpKind::from_wire("startup"), None);
865        assert_eq!(CatchUpKind::Resumed.memory_reason(), None);
866        assert_eq!(CatchUpKind::FreshSession.memory_reason(), Some(FallbackReason::FreshSession));
867    }
868
869    #[test]
870    fn a_catch_up_without_memory_is_the_block_alone() {
871        let text = compose_catch_up(CatchUpKind::Resumed, None);
872        assert!(text.starts_with("<system-reminder>\nAgentMux catch-up: "), "{text}");
873        assert!(text.ends_with("</system-reminder>\n"));
874        assert!(!text.contains(REINJECTION_SIGNATURE));
875        assert!(is_catch_up_text(&text));
876        assert!(text.contains("suggested next steps"));
877    }
878
879    #[test]
880    fn a_catch_up_with_memory_keeps_the_reinjection_message_whole_and_adds_one_block() {
881        let entries = vec![Entry {
882            label: "notes.md".into(),
883            tier: Tier::Personal,
884            text: "P1".into(),
885            name: "notes.md".into(),
886            system: false,
887            bundle_id: None,
888            path: None,
889        }];
890        let memory = compose_fallback(&entries, FallbackReason::FreshSession).unwrap();
891        let text = compose_catch_up(CatchUpKind::FreshSession, Some(&memory.text));
892        // Everything before the closing tag is the re-delivery, unchanged, so
893        // the card's item spans still index into it.
894        let body = memory.text.trim_end().trim_end_matches("</system-reminder>");
895        assert!(text.starts_with(body), "{text}");
896        assert_eq!(text.matches("<system-reminder>").count(), 1);
897        assert_eq!(text.matches("</system-reminder>").count(), 1);
898        assert!(text.contains(REINJECTION_SIGNATURE) && is_catch_up_text(&text));
899        assert!(text.ends_with("</system-reminder>\n"));
900    }
901
902    #[test]
903    fn ordinary_text_is_not_a_catch_up() {
904        assert!(!is_catch_up_text("AgentMux catch-up: please"));
905        assert!(!is_catch_up_text("<system-reminder>unrelated</system-reminder>"));
906    }
907
908    #[test]
909    fn the_instruction_ends_with_the_tail_the_matchers_use() {
910        assert!(CATCH_UP_INSTRUCTION.ends_with(CATCH_UP_TAIL));
911    }
912
913    /// A memory body is copied into a reinjection verbatim: one that happens to
914    /// contain the marker, even as its last line, is still a reinjection.
915    #[test]
916    fn a_memory_body_that_contains_the_marker_is_not_a_catch_up() {
917        for body in [
918            "notes\nAgentMux catch-up: how this works\nmore notes".to_string(),
919            "notes\nAgentMux catch-up: how this works".to_string(),
920            format!("notes\nAgentMux catch-up: how this works. {CATCH_UP_TAIL}\nmore notes"),
921        ] {
922            let entries = vec![Entry {
923                label: "notes.md".into(),
924                tier: Tier::Personal,
925                text: body,
926                name: "notes.md".into(),
927                system: false,
928                bundle_id: None,
929                path: None,
930            }];
931            let memory = compose_fallback(&entries, FallbackReason::Compaction).unwrap();
932            assert!(!is_catch_up_text(&memory.text), "{}", memory.text);
933            // And appending the real block still makes it one.
934            assert!(is_catch_up_text(&compose_catch_up(CatchUpKind::Compaction, Some(&memory.text))));
935        }
936    }
937}