1use super::index::{self, IndexPlan};
24
25pub const MAX_PART_CHARS: usize = 9_000;
28
29pub const HOOK_PARTS: usize = 8;
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
37pub enum Reason {
38 Startup,
40 Clear,
42 Compact,
44}
45
46impl Reason {
47 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#[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#[derive(Debug, Clone, PartialEq, Eq)]
96pub struct Entry {
97 pub label: String,
99 pub tier: Tier,
100 pub text: String,
102 pub name: String,
104 pub system: bool,
106 pub bundle_id: Option<String>,
108 pub path: Option<String>,
110}
111
112#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126pub struct ItemSpan {
127 pub entry: Option<usize>,
129 pub start: usize,
130 pub end: usize,
131}
132
133#[derive(Debug, Clone, PartialEq, Eq)]
135pub struct Composed {
136 pub text: String,
137 pub spans: Vec<ItemSpan>,
139}
140
141struct Tracked {
143 out: String,
144 chars: usize,
145}
146
147impl Tracked {
148 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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub enum StartupCarry {
170 None,
172 All,
174 Partly,
176}
177
178pub 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 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 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
205pub 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
218fn 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
232pub 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
271fn 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 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
317pub const COMPACTION_CLAUSE: &str = "Your recent conversation was just compacted into a summary.";
321
322pub const REINJECTION_SIGNATURE: &str = "Your memory was reinjected because your working context was just reset.";
326
327#[derive(Debug, Clone, Copy, PartialEq, Eq)]
330pub enum FallbackReason {
331 Compaction,
333 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 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
359pub fn compose_fallback(entries: &[Entry], reason: FallbackReason) -> Option<Composed> {
368 compose_fallback_with(entries, reason, false)
369}
370
371pub 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
379pub 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
407pub const CATCH_UP_SIGNATURE: &str = "AgentMux catch-up:";
413
414#[derive(Debug, Clone, Copy, PartialEq, Eq)]
416pub enum CatchUpKind {
417 FreshSession,
420 Compaction,
422 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 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
457const 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
465pub 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
478pub const CATCH_UP_TAIL: &str = "Then stop and wait for them.";
481
482pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
503pub enum Delivered {
504 Full,
505 Partial(usize),
507 Omitted,
508 Indexed,
510}
511
512impl Delivered {
513 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#[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
546pub fn split_into_parts_counted(text: &str, max_chars: usize, max_parts: usize) -> (Vec<String>, usize) {
549 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 (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 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 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 #[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 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 #[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 assert!(is_catch_up_text(&compose_catch_up(CatchUpKind::Compaction, Some(&memory.text))));
935 }
936 }
937}