Skip to main content

agentmux_srv_core/backend/reactive/
held_notes.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! srv's informational `[AgentMux]` notes wait for the agent's next turn
5//! instead of starting one. A note sent as input is a turn of its own: when
6//! MuxBus and the model API went down together, every agent spent minutes
7//! retrying a turn for a note that asked nothing of it, and the user's own
8//! messages queued behind those turns.
9//!
10//! A held note goes with the next message the agent's pane is given by
11//! anything else (the user's input, a jekt, a broadcast, a scheduled prompt),
12//! after that message's own text ([`attach`], taken by
13//! `blockcontroller::deliver_agent_message_from` and
14//! `agent_handlers::run_agent_turn_joining`). A pane holds one note per key,
15//! a newer one replacing the older, and at most [`MAX_PER_PANE`]. A terminal
16//! agent typed into by keystrokes is never given held notes.
17//!
18//! A note the agent must get now (a worker's report to its leader, the answer
19//! to its own request) goes through `Handler::deliver_system_note` instead.
20
21use std::collections::{HashMap, HashSet, VecDeque};
22use std::io::Write;
23use std::path::PathBuf;
24use std::sync::{LazyLock, Mutex, MutexGuard};
25
26use super::handler::{Handler, ReactiveHandler, TargetResolution};
27
28/// Notes one pane holds at most; the oldest goes first.
29pub const MAX_PER_PANE: usize = 8;
30/// Panes with held notes at most; the one held for longest goes first (its
31/// pane is most likely closed).
32pub const MAX_PANES: usize = 512;
33
34/// Between a message and the notes that go with it.
35pub(crate) const SEPARATOR: &str = "\n\n";
36
37/// Held notes, per pane (block id): `(key, text)`, oldest first.
38#[derive(Debug, Default)]
39pub struct HeldNotes {
40    panes: HashMap<String, Pane>,
41    clock: u64,
42}
43
44#[derive(Debug, Default)]
45struct Pane {
46    notes: Vec<(String, String)>,
47    /// Keys invalidated since they were last held. A note can be out of the
48    /// set while a message carries it (it is taken on attach); if that message
49    /// is later dropped, [`HeldNotes::put_back`] must not resurrect a note its
50    /// own invalidation (`forget_key`/`replace`) has since removed.
51    forgotten: HashSet<String>,
52    touched: u64,
53}
54
55impl HeldNotes {
56    fn pane(&mut self, block_id: &str) -> &mut Pane {
57        self.clock += 1;
58        if !self.panes.contains_key(block_id) && self.panes.len() >= MAX_PANES {
59            if let Some(oldest) = self.panes.iter().min_by_key(|(_, p)| p.touched).map(|(b, _)| b.clone()) {
60                self.panes.remove(&oldest);
61            }
62        }
63        let pane = self.panes.entry(block_id.to_string()).or_default();
64        pane.touched = self.clock;
65        pane
66    }
67
68    /// Hold `text` for `block_id` under `key`, replacing a note held under it.
69    pub fn hold(&mut self, block_id: &str, key: &str, text: &str) {
70        let text = super::sanitize::with_system_note_marker(text);
71        let pane = self.pane(block_id);
72        pane.notes.retain(|(k, _)| k != key);
73        // A fresh note under this key supersedes any earlier invalidation.
74        pane.forgotten.remove(key);
75        pane.notes.push((key.to_string(), text.into_owned()));
76        if pane.notes.len() > MAX_PER_PANE {
77            pane.notes.remove(0);
78        }
79    }
80
81    /// Hold `text` under `key` in place of the note held under `old_key`.
82    /// `false`, holding nothing, when no note is held under `old_key`.
83    pub fn replace(&mut self, block_id: &str, old_key: &str, key: &str, text: &str) -> bool {
84        let pane = self.pane(block_id);
85        let before = pane.notes.len();
86        pane.notes.retain(|(k, _)| k != old_key);
87        // Even when the old note is out with a queued message, its key is now
88        // invalidated and must not come back if that message is dropped (#3894
89        // follow-up).
90        pane.forgotten.insert(old_key.to_string());
91        let replaced = pane.notes.len() != before;
92        if replaced {
93            self.hold(block_id, key, text);
94        }
95        replaced
96    }
97
98    /// Drop the note held for `block_id` under `key`, if any.
99    pub fn forget_key(&mut self, block_id: &str, key: &str) {
100        let pane = self.pane(block_id);
101        pane.notes.retain(|(k, _)| k != key);
102        // Recorded even when nothing is held: the note may be out with a
103        // message that is waiting, and must not return if that message is
104        // dropped (#3894 follow-up).
105        pane.forgotten.insert(key.to_string());
106    }
107
108    /// Whether a note is held for `block_id` under `key`.
109    pub fn holds(&self, block_id: &str, key: &str) -> bool {
110        self.panes.get(block_id).is_some_and(|p| p.notes.iter().any(|(k, _)| k == key))
111    }
112
113    /// Every note held for `block_id`, oldest first; none are held after. The
114    /// pane stays, with the keys invalidated while a message carries its
115    /// notes, so a later [`Self::put_back`] still sees them (#3894 follow-up).
116    pub fn take(&mut self, block_id: &str) -> Vec<(String, String)> {
117        let Some(pane) = self.panes.get_mut(block_id) else { return Vec::new() };
118        std::mem::take(&mut pane.notes)
119    }
120
121    /// `notes`, taken for a message that didn't go, are held again ahead of
122    /// any held since, except where a newer note took their key.
123    pub fn put_back(&mut self, block_id: &str, notes: Vec<(String, String)>) {
124        if notes.is_empty() {
125            return;
126        }
127        let pane = self.pane(block_id);
128        // Not a note its own invalidation removed while the message waited
129        // (#3894 follow-up), and not one a newer note has since taken.
130        let mut all: Vec<(String, String)> = notes
131            .into_iter()
132            .filter(|(k, _)| !pane.forgotten.contains(k) && !pane.notes.iter().any(|(newer, _)| newer == k))
133            .collect();
134        all.append(&mut pane.notes);
135        let excess = all.len().saturating_sub(MAX_PER_PANE);
136        pane.notes = all.split_off(excess);
137    }
138}
139
140static HELD: LazyLock<Mutex<HeldNotes>> = LazyLock::new(Default::default);
141
142fn held() -> MutexGuard<'static, HeldNotes> {
143    HELD.lock().unwrap_or_else(|e| e.into_inner())
144}
145
146/// Hold `text` for the pane `block_id` under `key`, replacing a note held
147/// under it. For a caller that already knows the pane; an agent's name or
148/// UID goes through [`ReactiveHandler::hold_system_note`].
149pub fn hold(block_id: &str, key: &str, text: &str) {
150    held().hold(block_id, key, text);
151}
152
153/// Notes that went on a message srv then dropped (a deferred jekt that
154/// expired before the process could take it): hold them again for the agent's
155/// next message, under their original keys. They are not the jekt's to lose —
156/// a `[AgentMux]` note about the app's own state outlives the sender's
157/// deadline (#3894) — and the keys are what a later `replace` or `forget_key`
158/// for the same note acts on, so a restored note can still be superseded.
159pub fn put_back(block_id: &str, notes: Vec<(String, String)>) {
160    held().put_back(block_id, notes);
161}
162
163/// Drop the note held for `block_id` under `key`, if any (it went stale).
164pub fn forget_key(block_id: &str, key: &str) {
165    held().forget_key(block_id, key);
166}
167
168/// `message`, then the notes held for its pane, one per line.
169pub fn with_notes(message: &str, notes: &[(String, String)]) -> String {
170    if notes.is_empty() {
171        return message.to_string();
172    }
173    let notes = notes.iter().map(|(_, text)| text.as_str()).collect::<Vec<_>>().join("\n");
174    if message.trim().is_empty() { notes } else { format!("{message}{SEPARATOR}{notes}") }
175}
176
177/// What a person wrote in a message that may carry held notes: the text
178/// before notes srv attached to it ([`AttachedLog`]). Text that only looks
179/// like attached notes, a pasted note say, is kept.
180pub fn strip_attached(text: &str) -> &str {
181    let mut log = ATTACHED.lock().unwrap_or_else(|e| e.into_inner());
182    strip_logged(text, &mut log)
183}
184
185fn strip_logged<'a>(text: &'a str, log: &mut AttachedLog) -> &'a str {
186    // What srv attaches starts with its own note marker or, for a bulletin, the bulletin's.
187    let note = format!("{SEPARATOR}{} ", crate::muxbus::delivery_status::notes::NOTE_MARKER);
188    let bulletin = format!("{SEPARATOR}[BULLETIN:");
189    let mut starts: Vec<usize> = text.match_indices(&note).chain(text.match_indices(&bulletin)).map(|(at, _)| at).collect();
190    starts.sort_unstable();
191    starts.into_iter().find(|&at| log.contains(&text[at..])).map_or(text, |at| &text[..at])
192}
193
194/// The exact text srv appended to messages that went (the separator and the
195/// notes), as hashes, so input history takes off exactly that and never
196/// what a person wrote ([`strip_attached`]). Kept in the channel folder, one
197/// hash a line: history is read from past conversations, across restarts.
198#[derive(Debug, Default)]
199struct AttachedLog {
200    path: Option<PathBuf>,
201    /// Read from `path` on first use.
202    hashes: Option<(VecDeque<String>, HashSet<String>)>,
203}
204
205/// The file [`AttachedLog`] is kept in.
206const ATTACHED_FILE: &str = "held-notes-attached.txt";
207/// Hashes [`AttachedLog`] keeps; the file is cut back to this many once it
208/// holds twice as many.
209const ATTACHED_KEPT: usize = 2000;
210
211fn suffix_hash(suffix: &str) -> String {
212    use sha2::Digest;
213    hex::encode(&sha2::Sha256::digest(suffix.as_bytes())[..16])
214}
215
216impl AttachedLog {
217    fn loaded(&mut self) -> &mut (VecDeque<String>, HashSet<String>) {
218        let path = self.path.clone();
219        self.hashes.get_or_insert_with(|| {
220            let lines: Vec<String> = path
221                .and_then(|p| std::fs::read_to_string(p).ok())
222                .map(|t| t.lines().map(str::to_string).collect())
223                .unwrap_or_default();
224            let order: VecDeque<String> = lines.into_iter().rev().take(ATTACHED_KEPT).rev().collect();
225            let set = order.iter().cloned().collect();
226            (order, set)
227        })
228    }
229
230    fn contains(&mut self, suffix: &str) -> bool {
231        self.loaded().1.contains(&suffix_hash(suffix))
232    }
233
234    fn record(&mut self, suffix: &str) {
235        let hash = suffix_hash(suffix);
236        let (order, set) = self.loaded();
237        if !set.insert(hash.clone()) {
238            return;
239        }
240        order.push_back(hash.clone());
241        let mut rewrite = false;
242        if order.len() > ATTACHED_KEPT {
243            if let Some(old) = order.pop_front() {
244                set.remove(&old);
245            }
246            rewrite = true;
247        }
248        let Some(path) = &self.path else { return };
249        let written = if rewrite && std::fs::metadata(path).is_ok_and(|m| m.len() > (ATTACHED_KEPT as u64) * 2 * 33) {
250            let all: String = self.hashes.iter().flat_map(|(o, _)| o.iter()).map(|h| format!("{h}\n")).collect();
251            std::fs::write(path, all)
252        } else {
253            std::fs::OpenOptions::new().create(true).append(true).open(path).and_then(|mut f| writeln!(f, "{hash}"))
254        };
255        if let Err(e) = written {
256            tracing::warn!(path = %path.display(), error = %e, "held notes: couldn't record attached notes");
257        }
258    }
259}
260
261static ATTACHED: LazyLock<Mutex<AttachedLog>> = LazyLock::new(|| {
262    let path = if cfg!(any(test, feature = "test-support")) {
263        None
264    } else {
265        agentmux_common::DataPaths::from_env().map(|p| p.instance_dir.join(ATTACHED_FILE))
266    };
267    Mutex::new(AttachedLog { path, hashes: None })
268});
269
270/// The notes taken for one message: held again when this is dropped, unless
271/// the message went ([`Attached::delivered`]).
272#[must_use = "call `delivered` once the message has gone, or the notes are held again"]
273pub struct Attached {
274    block_id: String,
275    notes: Vec<(String, String)>,
276    /// What was appended to the message's own text, if it had any.
277    suffix: Option<String>,
278}
279
280impl Attached {
281    /// The texts of the notes taken for the message, oldest first.
282    pub fn note_texts(&self) -> Vec<String> {
283        self.notes.iter().map(|(_, text)| text.clone()).collect()
284    }
285
286    /// The notes taken for the message with their original keys, so a message
287    /// that is dropped can put them back exactly as they were (the keys are
288    /// what [`HeldNotes::replace`] and [`HeldNotes::forget_key`] act on).
289    pub fn keyed_notes(&self) -> Vec<(String, String)> {
290        self.notes.clone()
291    }
292
293    /// The message carrying the notes went to the agent.
294    pub fn delivered(mut self) {
295        if !self.notes.is_empty() {
296            let keys = self.notes.iter().map(|(key, _)| key.as_str()).collect::<Vec<_>>().join(", ");
297            let tokens = crate::backend::context_reading::tokens_now(&self.block_id);
298            tracing::info!(block_id = %self.block_id, notes = %keys, tokens, "held notes: went to the agent with a message");
299        }
300        self.notes.clear();
301        if let Some(suffix) = self.suffix.take() {
302            ATTACHED.lock().unwrap_or_else(|e| e.into_inner()).record(&suffix);
303        }
304    }
305}
306
307impl Drop for Attached {
308    fn drop(&mut self) {
309        if !self.notes.is_empty() {
310            held().put_back(&self.block_id, std::mem::take(&mut self.notes));
311        }
312    }
313}
314
315/// [`attach`] for a turn from `origin`, except that a `/compact` AgentMux
316/// sends for the agent carries no notes: they would become part of its
317/// instructions, and Codex compacts only on exactly `/compact`
318/// (SPEC_AGENT_SELF_COMPACTION_2026_10_23.md §3.3). They stay held for the
319/// next turn.
320pub fn attach_for_turn(block_id: &str, message: &str, origin: crate::backend::blockcontroller::health::TurnOrigin) -> (String, Attached) {
321    let own_compact = origin == crate::backend::blockcontroller::health::TurnOrigin::System
322        && (message.trim() == "/compact" || message.starts_with("/compact "));
323    if own_compact {
324        return (message.to_string(), Attached { block_id: block_id.to_string(), notes: Vec::new(), suffix: None });
325    }
326    attach(block_id, message)
327}
328
329/// `message` with the notes held for `block_id` after it, and the guard that
330/// holds them again if the message doesn't go.
331pub fn attach(block_id: &str, message: &str) -> (String, Attached) {
332    let notes = held().take(block_id);
333    let full = with_notes(message, &notes);
334    let suffix = (!notes.is_empty() && !message.trim().is_empty()).then(|| full[message.len()..].to_string());
335    (full, Attached { block_id: block_id.to_string(), notes, suffix })
336}
337
338impl Handler {
339    /// The block a system note for `target_agent` goes to.
340    pub(super) fn note_target(&mut self, target_agent: &str) -> Result<String, String> {
341        match self.resolve_target(target_agent) {
342            TargetResolution::Uid(b) | TargetResolution::Name(b) | TargetResolution::FormerSlug { block: b, .. } => Ok(b),
343            TargetResolution::Ambiguous(candidates) => {
344                Err(format!("ambiguous agent name: '{target_agent}' is held by {} live agents", candidates.len()))
345            }
346            TargetResolution::NotFound => Err(format!("agent not found: {target_agent}")),
347        }
348    }
349
350    fn audit_note(&mut self, target_agent: &str, block_id: &str, text: &str, outcome: &str) {
351        let request_id = uuid::Uuid::new_v4().to_string();
352        self.log_audit(Some("agentmux"), target_agent, block_id, text, true, None, &request_id, Some(outcome), None);
353    }
354}
355
356impl ReactiveHandler {
357    /// Hold srv's own note `text` for `target_agent`'s next turn, under `key`
358    /// (a note held under it is replaced). Never input of its own: see the
359    /// module doc. Audited as `system_note_held` from `agentmux`.
360    pub fn hold_system_note(&self, target_agent: &str, key: &str, text: &str) -> Result<(), String> {
361        let mut handler = self.inner.lock();
362        let block_id = handler.note_target(target_agent)?;
363        held().hold(&block_id, key, text);
364        handler.audit_note(target_agent, &block_id, text, "system_note_held");
365        Ok(())
366    }
367
368    /// [`Self::hold_system_note`] in place of the note held under `old_key`;
369    /// `Ok(false)`, holding nothing, when none is held under it any more.
370    pub fn replace_held_system_note(&self, target_agent: &str, old_key: &str, key: &str, text: &str) -> Result<bool, String> {
371        let mut handler = self.inner.lock();
372        let block_id = handler.note_target(target_agent)?;
373        let replaced = held().replace(&block_id, old_key, key, text);
374        if replaced {
375            handler.audit_note(target_agent, &block_id, text, "system_note_held");
376        }
377        Ok(replaced)
378    }
379
380    /// Audit a note `block_id` was given without this handler
381    /// (`blockcontroller::system_note_into_turn_or_hold`): as `system_note`
382    /// when it joined the running turn, else as `system_note_held`.
383    pub fn audit_system_note(&self, target_agent: &str, block_id: &str, text: &str, joined: bool) {
384        let outcome = if joined { "system_note" } else { "system_note_held" };
385        self.inner.lock().audit_note(target_agent, block_id, text, outcome);
386    }
387
388    /// Whether a note is held for `target_agent` under `key`.
389    pub fn holds_system_note(&self, target_agent: &str, key: &str) -> bool {
390        let block_id = self.inner.lock().note_target(target_agent);
391        block_id.is_ok_and(|b| held().holds(&b, key))
392    }
393}
394
395#[cfg(test)]
396mod tests {
397    use super::*;
398    use crate::backend::reactive::types::SenderDelivery;
399    use std::sync::Arc;
400
401    #[test]
402    fn agentmuxs_own_compact_carries_no_notes_and_they_stay_held() {
403        use crate::backend::blockcontroller::health::TurnOrigin;
404        let b = format!("hn-{}", uuid::Uuid::new_v4());
405        hold(&b, "compact-hint", "[AgentMux] Your context is 512K");
406        for message in ["/compact", "/compact keep: PR #5401"] {
407            let (sent, guard) = attach_for_turn(&b, message, TurnOrigin::System);
408            assert_eq!(sent, message, "Codex compacts only on exactly /compact");
409            guard.delivered();
410            assert!(held().holds(&b, "compact-hint"), "kept for the next turn");
411        }
412        // The user typing /compact, or any other turn of AgentMux's, takes them.
413        let (sent, guard) = attach_for_turn(&b, "/compact", TurnOrigin::User);
414        assert!(sent.contains("[AgentMux] Your context is 512K"));
415        guard.delivered();
416        hold(&b, "compact-hint", "[AgentMux] again");
417        let (sent, guard) = attach_for_turn(&b, "hello", TurnOrigin::System);
418        assert!(sent.contains("[AgentMux] again"));
419        guard.delivered();
420    }
421
422    #[test]
423    fn a_stale_note_can_be_dropped_by_its_key() {
424        let b = format!("hn-{}", uuid::Uuid::new_v4());
425        hold(&b, "compact-hint", "old size");
426        hold(&b, "other", "keep me");
427        forget_key(&b, "compact-hint");
428        assert!(!held().holds(&b, "compact-hint") && held().holds(&b, "other"));
429        let _ = held().take(&b);
430    }
431
432    fn texts(notes: &[(String, String)]) -> Vec<&str> {
433        notes.iter().map(|(_, t)| t.as_str()).collect()
434    }
435
436    #[test]
437    fn a_note_is_held_once_per_key_the_newer_replacing_the_older() {
438        let mut h = HeldNotes::default();
439        h.hold("b", "paused", "[AgentMux] paused since 03:12");
440        h.hold("b", "other", "[AgentMux] other");
441        h.hold("b", "paused", "[AgentMux] paused since 03:12");
442        assert_eq!(texts(&h.take("b")), ["[AgentMux] other", "[AgentMux] paused since 03:12"], "no duplicate");
443        assert!(h.take("b").is_empty(), "taken once");
444    }
445
446    #[test]
447    fn a_replacement_needs_the_note_it_replaces_still_held() {
448        let mut h = HeldNotes::default();
449        assert!(!h.replace("b", "paused", "outage", "x"));
450        assert!(h.take("b").is_empty(), "nothing held in its place");
451        h.hold("b", "paused", "[AgentMux] paused");
452        assert!(h.holds("b", "paused"));
453        assert!(h.replace("b", "paused", "outage", "[AgentMux] were paused"));
454        assert!(!h.holds("b", "paused"));
455        assert_eq!(texts(&h.take("b")), ["[AgentMux] were paused"]);
456    }
457
458    /// #3894 follow-up: while a message waits (the controller's deferred
459    /// queue), the notes it took are out of the held set; an invalidation in
460    /// that window must still reach them, so a dropped message cannot restore
461    /// a note that has been superseded.
462    #[test]
463    fn a_note_invalidated_while_a_message_waits_is_not_put_back() {
464        let mut h = HeldNotes::default();
465        h.hold("b", "paused", "[AgentMux] cloud delivery paused");
466        let waiting = h.take("b");
467        h.forget_key("b", "paused");
468        h.put_back("b", waiting);
469        assert!(!h.holds("b", "paused"), "the invalidation wins over the dropped message");
470    }
471
472    #[test]
473    fn a_note_replaced_while_a_message_waits_is_not_put_back() {
474        let mut h = HeldNotes::default();
475        h.hold("b", "paused", "[AgentMux] cloud delivery paused");
476        let waiting = h.take("b");
477        assert!(!h.replace("b", "paused", "outage", "[AgentMux] still paused"), "nothing held to replace");
478        h.hold("b", "resumed", "[AgentMux] resumed");
479        h.put_back("b", waiting);
480        assert_eq!(texts(&h.take("b")), ["[AgentMux] resumed"]);
481    }
482
483    /// A second message taking the same pane must not clear the invalidation
484    /// the first one's wait recorded.
485    #[test]
486    fn an_invalidation_survives_a_later_take_of_the_same_pane() {
487        let mut h = HeldNotes::default();
488        h.hold("b", "paused", "[AgentMux] paused");
489        let first = h.take("b");
490        h.forget_key("b", "paused");
491        assert!(h.take("b").is_empty(), "the second message takes nothing");
492        h.put_back("b", first);
493        assert!(!h.holds("b", "paused"), "the invalidation still wins");
494    }
495
496    /// A dropped message's note still comes back when nothing invalidated it.
497    #[test]
498    fn a_note_untouched_while_the_message_waited_is_put_back() {
499        let mut h = HeldNotes::default();
500        h.hold("b", "other", "[AgentMux] other");
501        let waiting = h.take("b");
502        h.put_back("b", waiting);
503        assert!(h.holds("b", "other"));
504    }
505
506    #[test]
507    fn the_queue_is_bounded_per_pane_and_in_panes() {
508        let mut h = HeldNotes::default();
509        for i in 0..MAX_PER_PANE + 3 {
510            h.hold("b", &format!("k{i}"), &format!("[AgentMux] n{i}"));
511        }
512        let notes = h.take("b");
513        assert_eq!(notes.len(), MAX_PER_PANE);
514        assert_eq!(notes[0].1, "[AgentMux] n3", "the oldest went first");
515        for i in 0..MAX_PANES + 1 {
516            h.hold(&format!("pane{i}"), "k", "n");
517        }
518        assert_eq!(h.panes.len(), MAX_PANES);
519        assert!(!h.holds("pane0", "k"), "the pane held for longest went");
520        assert!(h.holds(&format!("pane{MAX_PANES}"), "k"));
521    }
522
523    #[test]
524    fn notes_put_back_go_ahead_of_newer_ones_unless_a_newer_one_took_their_key() {
525        let mut h = HeldNotes::default();
526        h.hold("b", "a", "old a");
527        h.hold("b", "c", "c");
528        let taken = h.take("b");
529        h.hold("b", "a", "new a");
530        h.put_back("b", taken);
531        assert_eq!(texts(&h.take("b")), ["[AgentMux] c", "[AgentMux] new a"]);
532    }
533
534    #[test]
535    fn held_notes_follow_the_message_and_never_lead_it() {
536        let notes = vec![("k".to_string(), "[AgentMux] one".to_string()), ("j".to_string(), "[AgentMux] two".to_string())];
537        let message = with_notes("[JEKT:FROM=a TIER=coord]\nreview PR 12", &notes);
538        assert_eq!(message, "[JEKT:FROM=a TIER=coord]\nreview PR 12\n\n[AgentMux] one\n[AgentMux] two");
539        assert_eq!(with_notes("fix the build", &[]), "fix the build");
540        assert_eq!(with_notes("", &notes[..1]), "[AgentMux] one");
541    }
542
543    /// Input history takes off exactly the notes srv attached to a message
544    /// that went, never `[AgentMux]` text a person typed or pasted.
545    #[test]
546    fn only_notes_srv_attached_are_taken_off_what_a_person_typed() {
547        let block = "held-notes-test-strip";
548        let note = "[AgentMux] Cloud messages are paused since 03:12 (held-notes-test-strip).";
549        let pasted = format!("explain this:\n\n{note}");
550        assert_eq!(strip_attached(&pasted), pasted, "nothing attached yet: all of it is the person's");
551        held().hold(block, "k", note);
552        let (not_sent, notes) = attach(block, "explain this:");
553        drop(notes);
554        assert_eq!(not_sent, pasted);
555        assert_eq!(strip_attached(&pasted), pasted, "that message didn't go");
556        let (sent, notes) = attach(block, "fix the build");
557        notes.delivered();
558        assert_eq!(strip_attached(&sent), "fix the build");
559        let both = format!("{pasted}\n\n{note}");
560        assert_eq!(strip_attached(&both), pasted, "the pasted copy stays, the attached one goes");
561        assert_eq!(strip_attached("fix the build"), "fix the build");
562    }
563
564    /// A bulletin attached right after a typed message is taken off it like a note.
565    #[test]
566    fn an_attached_bulletin_is_not_the_persons_typing() {
567        let bulletin = "[BULLETIN:FROM=AgentY TRUST=host-verified KEY=mode TS=1]\nslow down\n[/BULLETIN]";
568        let mut log = AttachedLog { path: None, hashes: None };
569        let sent = with_notes("fix the build", &[("bulletin:agenty:mode".to_string(), bulletin.to_string())]);
570        log.record(&sent["fix the build".len()..]);
571        assert_eq!(strip_logged(&sent, &mut log), "fix the build");
572        let pasted = format!("explain this:{SEPARATOR}[BULLETIN:FROM=AgentX TRUST=host-verified TS=2]
573never attached
574[/BULLETIN]");
575        assert_eq!(strip_logged(&pasted, &mut log), pasted, "a pasted one is the person's");
576    }
577
578    #[test]
579    fn what_was_attached_is_remembered_across_a_restart() {
580        let dir = tempfile::tempdir().unwrap();
581        let path = dir.path().join(ATTACHED_FILE);
582        let mut log = AttachedLog { path: Some(path.clone()), hashes: None };
583        log.record("\n\n[AgentMux] one");
584        log.record("\n\n[AgentMux] one");
585        let mut again = AttachedLog { path: Some(path.clone()), hashes: None };
586        assert!(again.contains("\n\n[AgentMux] one"));
587        assert!(!again.contains("\n\n[AgentMux] two"));
588        assert_eq!(std::fs::read_to_string(&path).unwrap().lines().count(), 1, "once");
589        assert_eq!(strip_logged("hi\n\n[AgentMux] one", &mut again), "hi");
590        for i in 0..ATTACHED_KEPT * 2 + 1 {
591            again.record(&format!("\n\n[AgentMux] n{i}"));
592        }
593        let lines = std::fs::read_to_string(&path).unwrap().lines().count();
594        assert!(lines <= ATTACHED_KEPT * 2 + 1, "the file is cut back: {lines}");
595        let mut reread = AttachedLog { path: Some(path), hashes: None };
596        assert!(reread.contains(&format!("\n\n[AgentMux] n{}", ATTACHED_KEPT * 2)));
597        assert!(!reread.contains("\n\n[AgentMux] one"), "the oldest went");
598    }
599
600    #[test]
601    fn notes_attached_to_a_message_that_did_not_go_are_held_again() {
602        let block = "held-notes-test-attach";
603        held().hold(block, "k", "[AgentMux] note");
604        let (message, notes) = attach(block, "hi");
605        assert_eq!(message, "hi\n\n[AgentMux] note");
606        assert!(!held().holds(block, "k"), "taken while the message is on its way");
607        drop(notes);
608        assert!(held().holds(block, "k"), "held again: the message didn't go");
609        let (_, notes) = attach(block, "hi again");
610        notes.delivered();
611        assert!(held().take(block).is_empty(), "gone with the message");
612        let (message, notes) = attach(block, "nothing held");
613        assert_eq!(message, "nothing held");
614        notes.delivered();
615    }
616
617    /// A held note is never input: no structured message and no keystrokes
618    /// reach the agent, so it starts no turn. It goes with the next message.
619    #[test]
620    fn holding_a_note_sends_the_agent_nothing() {
621        let sent = Arc::new(Mutex::new(0usize));
622        let handler = ReactiveHandler::new();
623        let (s1, s2) = (sent.clone(), sent.clone());
624        handler.set_message_sender(Arc::new(move |_: &str, _: &str, _: &[serde_json::Value], _origin: &crate::backend::message_origin::MessageOrigin, _expires_at_ms: Option<i64>| {
625            *s1.lock().unwrap() += 1;
626            Ok(SenderDelivery::Delivered)
627        }));
628        handler.set_input_sender(Arc::new(move |_: &str, _: &[u8]| {
629            *s2.lock().unwrap() += 1;
630            Ok(())
631        }));
632        let block = "held-notes-test-handler";
633        handler.register_agent("noteagent", block, None).unwrap();
634        let note = "[AgentMux] Cloud messages are paused since 14:22 (MuxBus needs a sign-in).";
635        handler.hold_system_note("NoteAgent", "muxbus:paused", note).unwrap();
636        assert_eq!(*sent.lock().unwrap(), 0, "nothing was sent");
637        assert!(handler.holds_system_note("noteagent", "muxbus:paused"));
638        assert_eq!(handler.get_audit_log(1)[0].outcome.as_deref(), Some("system_note_held"));
639        assert!(handler.hold_system_note("nobody", "k", note).unwrap_err().contains("agent not found"));
640        assert_eq!(handler.replace_held_system_note("noteagent", "muxbus:paused", "muxbus:outage", "[AgentMux] were"), Ok(true));
641        assert_eq!(handler.replace_held_system_note("noteagent", "muxbus:paused", "muxbus:outage", "[AgentMux] x"), Ok(false));
642        let (message, notes) = attach(block, "what's next?");
643        notes.delivered();
644        assert_eq!(message, "what's next?\n\n[AgentMux] were");
645    }
646
647    #[test]
648    fn a_held_note_without_the_marker_gets_it() {
649        let block = "held-notes-marker-test";
650        hold(block, "unmarked", "Task #5 can start");
651        hold(block, "marked", "[AgentMux] already marked");
652        let (message, notes) = attach(block, "go");
653        notes.delivered();
654        assert_eq!(message, "go\n\n[AgentMux] Task #5 can start\n[AgentMux] already marked");
655    }
656}