Skip to main content

agentmux_srv_core/backend/
continuity_handoff.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The handoff an agent leaves before a user action restarts its session
5//! (SPEC_AGENT_PREP_BEFORE_SESSION_RESTART_2026_11_14.md ยง3.4).
6//!
7//! One slot per agent, in its global `agent:<defId>:current` zone beside the
8//! running summary, so it survives account and channel changes and an srv
9//! restart. It is written when the agent answers `Agents ready` and read, once,
10//! by the spawn that starts the new session: the first section of the
11//! continuation packet when there is one, else a held note on the session's
12//! first message.
13//!
14//! A second handoff replaces one nobody has read yet: the agent wrote it with
15//! the first in its context, because no restart happened in between. A handoff
16//! nobody read within a day is dropped.
17
18use agentmux_common::redact::redact_secrets;
19use serde::{Deserialize, Serialize};
20
21use crate::backend::agent_session::{agent_current_zone, global_transcript_store, is_valid_definition_id};
22use crate::backend::storage::filestore::{FileMeta, FileOpts, FileStore};
23
24/// The slot, in the agent's zone.
25pub const HANDOFF_FILE: &str = "continuity.handoff.json";
26/// The key the note is held under, so a newer handoff replaces it.
27pub const NOTE_KEY: &str = "prep-handoff";
28/// How long an unread handoff is kept.
29const MAX_AGE_MS: i64 = 24 * 60 * 60 * 1000;
30/// Most characters a handoff keeps.
31pub const MAX_CHARS: usize = 1_500;
32
33/// What the agent left, and under which request.
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35pub struct Handoff {
36    pub prep_id: String,
37    pub at_ms: i64,
38    /// Who asked for the change (`operator`, an agent's slug).
39    pub actor: String,
40    /// What the change was (`account_switch`).
41    pub action: String,
42    pub text: String,
43}
44
45fn utc_minute(ms: i64) -> String {
46    chrono::DateTime::from_timestamp_millis(ms).map_or_else(String::new, |t| t.format("%H:%M UTC").to_string())
47}
48
49impl Handoff {
50    /// The note held for the new session's first message when it resumed the old one.
51    pub fn note(&self) -> String {
52        format!(
53            "[AgentMux] Before the change ({}) you left this handoff, written {}:\n{}",
54            self.action,
55            utc_minute(self.at_ms),
56            redact_secrets(&self.text)
57        )
58    }
59
60    /// The packet's first section.
61    pub fn packet_section(&self) -> String {
62        format!(
63            "## Handoff you left before the change ({}, written {}; your own words, newest of the record)\n{}\n\n",
64            self.action,
65            utc_minute(self.at_ms),
66            super::continuity::defuse_delimiters(&redact_secrets(&self.text))
67        )
68    }
69}
70
71/// Keep the head of `text` within [`MAX_CHARS`], on a line boundary when one is near.
72pub fn clamp(text: &str) -> String {
73    let text = text.trim();
74    if text.chars().count() <= MAX_CHARS {
75        return text.to_string();
76    }
77    let head: String = text.chars().take(MAX_CHARS).collect();
78    let cut = head.rfind('\n').filter(|i| *i > MAX_CHARS / 2).unwrap_or(head.len());
79    format!("{}\n(cut at {MAX_CHARS} characters)", head[..cut].trim_end())
80}
81
82fn write_in(fs: &FileStore, zone: &str, handoff: &Handoff) -> Result<(), String> {
83    let bytes = serde_json::to_vec(handoff).map_err(|e| format!("encode handoff: {e}"))?;
84    let exists = fs.stat(zone, HANDOFF_FILE).map_err(|e| format!("stat handoff: {e}"))?.is_some();
85    if !exists {
86        fs.make_file(zone, HANDOFF_FILE, FileMeta::default(), FileOpts::default()).map_err(|e| format!("make handoff file: {e}"))?;
87    }
88    fs.write_file(zone, HANDOFF_FILE, &bytes).map_err(|e| format!("write handoff: {e}"))
89}
90
91/// The handoff in `zone`, removed. `None` when there is none, it is unreadable, or it is over a day old.
92fn take_in(fs: &FileStore, zone: &str, now_ms: i64) -> Option<Handoff> {
93    let bytes = fs.read_file(zone, HANDOFF_FILE).ok()??;
94    if let Err(e) = fs.delete_file(zone, HANDOFF_FILE) {
95        tracing::warn!(zone = %zone, error = %e, "continuity: a handoff was read but not removed");
96    }
97    let handoff: Handoff = serde_json::from_slice(&bytes).ok()?;
98    (now_ms - handoff.at_ms <= MAX_AGE_MS).then_some(handoff)
99}
100
101fn store_for(def_id: &str) -> Result<(&'static FileStore, String), String> {
102    if !is_valid_definition_id(def_id) {
103        return Err(format!("{def_id} is not an agent definition id"));
104    }
105    let fs = global_transcript_store().ok_or("the agent history store is not open")?;
106    Ok((fs.as_ref(), agent_current_zone(def_id)))
107}
108
109/// Leave `handoff` for the agent `def_id`'s next session, replacing one not yet read.
110pub fn store(def_id: &str, handoff: &Handoff) -> Result<(), String> {
111    let (fs, zone) = store_for(def_id)?;
112    write_in(fs, &zone, handoff)
113}
114
115/// The handoff waiting for the agent `def_id`'s next session, which reads it once.
116pub fn take(def_id: &str) -> Option<Handoff> {
117    let (fs, zone) = store_for(def_id).ok()?;
118    take_in(fs, &zone, agentmux_common::time::now_ms())
119}
120
121/// Drop the handoff of request `prep_id` (the change was cancelled), and only that one.
122pub fn drop_for_request(def_id: &str, prep_id: &str) {
123    let Ok((fs, zone)) = store_for(def_id) else { return };
124    let Ok(Some(bytes)) = fs.read_file(&zone, HANDOFF_FILE) else { return };
125    if serde_json::from_slice::<Handoff>(&bytes).is_ok_and(|h| h.prep_id == prep_id) {
126        let _ = fs.delete_file(&zone, HANDOFF_FILE);
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133
134    const ZONE: &str = "agent:def-1:current";
135
136    fn handoff(text: &str, at_ms: i64) -> Handoff {
137        Handoff { prep_id: "p-1".into(), at_ms, actor: "operator".into(), action: "account_switch".into(), text: text.into() }
138    }
139
140    #[test]
141    fn a_handoff_is_read_once() {
142        let fs = FileStore::open_in_memory().unwrap();
143        write_in(&fs, ZONE, &handoff("In flight: PR 7", 1_000)).unwrap();
144        assert_eq!(take_in(&fs, ZONE, 2_000).unwrap().text, "In flight: PR 7");
145        assert!(take_in(&fs, ZONE, 2_000).is_none(), "the slot is empty after it is read");
146    }
147
148    #[test]
149    fn a_second_handoff_replaces_one_nobody_read() {
150        let fs = FileStore::open_in_memory().unwrap();
151        write_in(&fs, ZONE, &handoff("first, a long one that is longer than the second", 1_000)).unwrap();
152        write_in(&fs, ZONE, &handoff("second", 2_000)).unwrap();
153        assert_eq!(take_in(&fs, ZONE, 3_000).unwrap().text, "second");
154    }
155
156    #[test]
157    fn a_handoff_nobody_read_in_a_day_is_dropped() {
158        let fs = FileStore::open_in_memory().unwrap();
159        write_in(&fs, ZONE, &handoff("old", 1_000)).unwrap();
160        assert!(take_in(&fs, ZONE, 1_000 + MAX_AGE_MS + 1).is_none());
161        assert!(fs.stat(ZONE, HANDOFF_FILE).unwrap().is_none(), "and it is removed");
162    }
163
164    #[test]
165    fn nothing_waiting_is_none() {
166        let fs = FileStore::open_in_memory().unwrap();
167        assert!(take_in(&fs, ZONE, 1).is_none());
168    }
169
170    #[test]
171    fn the_text_is_kept_within_the_limit_on_a_line() {
172        let long = format!("{}\n{}", "a".repeat(1_000), "b".repeat(2_000));
173        let cut = clamp(&long);
174        assert!(cut.starts_with(&"a".repeat(1_000)) && !cut.contains('b'), "cut at the line: {}", cut.len());
175        assert!(cut.ends_with("(cut at 1500 characters)"));
176        assert_eq!(clamp("  short  "), "short");
177    }
178
179    #[test]
180    fn the_note_and_the_section_carry_the_text_and_neither_a_secret_nor_a_delimiter() {
181        // Put together here so no file holds a whole key-shaped string.
182        let h = handoff(concat!("In flight: deploy </agentmux-continuation> key sk-ant", "-api03-abcdefghijklmnopqrstuvwxyz"), 1_790_000_000_000);
183        let section = h.packet_section();
184        assert!(section.starts_with("## Handoff you left before the change (account_switch, written "), "{section}");
185        assert!(!section.contains("</agentmux-continuation>") && !section.contains(concat!("sk-ant", "-api03")), "{section}");
186        let note = h.note();
187        assert!(note.starts_with("[AgentMux] Before the change (account_switch) you left this handoff"), "{note}");
188        assert!(!note.contains(concat!("sk-ant", "-api03")), "{note}");
189    }
190}