Skip to main content

agentmux_srv_core/backend/agent_session/
session_io.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Read/write/append snapshot state for the `agent:<defId>:current` zone,
5//! including the global-mirror normalization + one-shot heal.
6
7use crate::backend::storage::filestore::FileStore;
8
9use super::helpers::{ensure_file, write_zone_file};
10use super::zone_naming::{agent_current_zone, is_valid_definition_id, validate_and_current};
11
12// ---------------------------------------------------------------------------
13// File names within an agent session zone (mirrors per-block zone shape)
14// ---------------------------------------------------------------------------
15
16/// Full UI snapshot (JSON). Frontend reads this on pane mount.
17pub const SNAPSHOT_FILE: &str = "output.state.json";
18/// Raw NDJSON stream for crash-recovery replay.
19pub const OUTPUT_FILE: &str = "output";
20/// Receive-time sidecar for `output`: one NDJSON `{"off":<byte offset of the
21/// appended batch>,"ms":<unix ms>}` record per append batch. A pure addition —
22/// `output`'s own format and every existing parser are untouched; a missing or
23/// corrupt sidecar degrades reads to "no stamps" (today's behavior). Gives
24/// replayed transcript nodes real timestamps (hover peek after restore, day
25/// separators). Spec:
26/// SPEC_AGENT_PANE_SESSION_SCOPED_SCROLLBACK_AND_AGENT_HISTORY_VIEW_2026_08_09.md §4.4.
27pub const TSIDX_FILE: &str = "output.tsidx";
28
29/// In an archive zone made from lines recovered out of a per-channel copy: the id of the session whose lines
30/// they are, as text. The lines a person typed carry no session id of their own (the next line that has one
31/// names the session), and the lines that had one are not all in the archive; the record reader gives such a
32/// line to this session.
33pub const OWNER_FILE: &str = "output.owner";
34
35/// Write `content` to `output.state.json` in `agent:<defId>:current`.
36/// Idempotent — creates the file if missing, overwrites otherwise.
37///
38/// The per-channel write is primary (preserving all existing same-channel
39/// behaviour); the snapshot overlay is *additionally* mirrored into the GLOBAL
40/// transcript store (when installed) so a cross-channel open — and the
41/// migrated-agent backfill — find a coherent zone (overlay + `output`
42/// together). Mirroring is best-effort: a global-store failure is logged, never
43/// propagated. See `docs/analysis/ANALYSIS_CROSS_CHANNEL_CONVERSATION_HISTORY_2026_06_14.md`.
44pub fn write_session_state(
45    filestore: &FileStore,
46    definition_id: &str,
47    content: &[u8],
48) -> Result<(), String> {
49    let zone = validate_and_current(definition_id)?;
50    write_zone_file(filestore, &zone, SNAPSHOT_FILE, content)?;
51    // A zone found corrupt is not mirrored to: this channel's copy above is the one kept.
52    if let Some(gfs) = crate::backend::transcript::damage::global_for(&zone) {
53        // The GLOBAL mirror must be AGENT-anchored, not channel-anchored.
54        // `sourceBlockId` names the LOCAL block whose `output` a restore reads,
55        // and that id only exists in the writing channel. A different channel
56        // opening the agent would read from a block it doesn't have, and the read
57        // fallback (`global_output_source`) — which resolves the agent zone via
58        // that block's LOCAL meta — can't anchor it, so history renders empty.
59        // Strip it to "" in the global copy so a cross-channel open anchors on its
60        // own fresh local block (which maps to the agent). The per-channel copy
61        // above keeps the real id for same-channel restore. See
62        // docs/retro/retro-legacy-agent-history-cross-channel-2026-06-16.md.
63        let global_content = normalize_snapshot_for_global(content);
64        if let Err(e) = write_zone_file(&gfs, &zone, SNAPSHOT_FILE, &global_content) {
65            if !crate::backend::transcript::damage::note_corrupt_text(&zone, "snapshot mirror", &e) {
66                tracing::warn!(zone = %zone, error = %e, "global transcripts: snapshot mirror failed");
67            }
68        }
69    }
70    Ok(())
71}
72
73/// Strip `sourceBlockId` to "" for the GLOBAL (cross-channel) snapshot mirror.
74///
75/// In a local snapshot `sourceBlockId` names the block whose per-block `output` a
76/// restore reads. That id is channel-scoped, so a global copy carrying it is only
77/// usable by the writing channel — every other channel's reader can't anchor it.
78/// "" is the agent-anchored sentinel that makes the reader fall back to the opening
79/// channel's own block. Best-effort: returns the input unchanged if it isn't a
80/// JSON object.
81pub fn normalize_snapshot_for_global(content: &[u8]) -> Vec<u8> {
82    let Ok(mut v) = serde_json::from_slice::<serde_json::Value>(content) else {
83        return content.to_vec();
84    };
85    if let Some(obj) = v.as_object_mut() {
86        if obj.contains_key("sourceBlockId") {
87            obj.insert(
88                "sourceBlockId".to_string(),
89                serde_json::Value::String(String::new()),
90            );
91        }
92    }
93    let result = serde_json::to_vec(&v).unwrap_or_else(|_| content.to_vec());
94    // Invariant G1: global snapshot must NEVER carry a non-empty sourceBlockId.
95    // A non-empty id is channel-local and breaks cross-channel opens.
96    debug_assert!(
97        serde_json::from_slice::<serde_json::Value>(&result)
98            .ok()
99            .and_then(|v| v.get("sourceBlockId").and_then(|s| s.as_str()).map(|s| s.is_empty()))
100            .unwrap_or(true),
101        "normalize_snapshot_for_global: G1 violated — sourceBlockId was not stripped"
102    );
103    result
104}
105
106/// One-shot heal for global snapshots poisoned before the normalize-on-mirror fix
107/// (a channel-local `sourceBlockId` was mirrored into `agent:<defId>:current`,
108/// breaking cross-channel opens). For each `def_id`, rewrite its global snapshot's
109/// `sourceBlockId` to "" iff it isn't already. Idempotent and cheap (one small
110/// JSON per agent); returns the number healed. Best-effort per agent.
111pub fn heal_global_snapshot_source_block_ids(gfs: &FileStore, def_ids: &[String]) -> usize {
112    let mut healed = 0;
113    for def_id in def_ids {
114        if !is_valid_definition_id(def_id) {
115            continue;
116        }
117        let zone = agent_current_zone(def_id);
118        let bytes = match gfs.read_file(&zone, SNAPSHOT_FILE) {
119            Ok(Some(b)) => b,
120            _ => continue, // no global snapshot for this agent
121        };
122        // Only rewrite when currently poisoned (non-empty sourceBlockId).
123        let poisoned = serde_json::from_slice::<serde_json::Value>(&bytes)
124            .ok()
125            .and_then(|v| {
126                v.get("sourceBlockId")
127                    .and_then(|s| s.as_str())
128                    .map(|s| !s.is_empty())
129            })
130            .unwrap_or(false);
131        if !poisoned {
132            continue;
133        }
134        let fixed = normalize_snapshot_for_global(&bytes);
135        if write_zone_file(gfs, &zone, SNAPSHOT_FILE, &fixed).is_ok() {
136            healed += 1;
137            tracing::info!(zone = %zone, "global transcripts: healed poisoned snapshot sourceBlockId");
138        }
139    }
140    healed
141}
142
143/// Append `line` (with a trailing newline added if not present) to
144/// `output` in `agent:<defId>:current`. Creates the file if missing.
145pub fn append_session_output(
146    filestore: &FileStore,
147    definition_id: &str,
148    line: &str,
149) -> Result<u64, String> {
150    let zone = validate_and_current(definition_id)?;
151    // Normalize to NDJSON: each line ends with exactly one '\n'.
152    let mut buf = line.as_bytes().to_vec();
153    if !buf.ends_with(b"\n") {
154        buf.push(b'\n');
155    }
156    ensure_file(filestore, &zone, OUTPUT_FILE)?;
157    filestore
158        .append_data(&zone, OUTPUT_FILE, &buf)
159        .map_err(|e| format!("append_data: {e}"))?;
160    Ok(buf.len() as u64)
161}
162
163/// Read `output.state.json` from `agent:<defId>:current`. Returns
164/// `Ok((None, None))` when the zone doesn't exist — that's the
165/// "fresh agent, nothing to restore" path and is NOT an error.
166///
167/// Reads the GLOBAL store first (preferred). The global copy always holds an
168/// agent-anchored snapshot (`sourceBlockId = ""`), which works in any channel.
169/// Per-channel is the fallback for old builds that pre-date the global store.
170/// Symmetric with the `blockfile:read_range` fallback in
171/// `app_api/blockfile.rs`.
172/// See `docs/specs/SPEC_AGENT_GLOBAL_PORTABILITY_2026-06-16.md` invariant G2.
173pub fn read_session_state(
174    filestore: &FileStore,
175    definition_id: &str,
176) -> Result<(Option<String>, Option<i64>), String> {
177    let zone = validate_and_current(definition_id)?;
178    let global = crate::backend::transcript::damage::global_for(&zone);
179    read_session_state_in(filestore, global.as_deref(), &zone)
180}
181
182/// [`read_session_state`] with the global store given (`None`: none, or the agent's zone in it found corrupt).
183pub(crate) fn read_session_state_in(
184    filestore: &FileStore,
185    global: Option<&FileStore>,
186    zone: &str,
187) -> Result<(Option<String>, Option<i64>), String> {
188    // Read the global store first: it always holds the agent-anchored
189    // (sourceBlockId="") snapshot. The per-channel copy carries the
190    // writing channel's local block id, which is stale the moment any
191    // OTHER block opens the agent (same channel, different tab/build).
192    // Preferring global ensures cross-channel opens never get a foreign
193    // sourceBlockId — the root cause of the blank-pane regression.
194    // Per-channel is the fallback for pre-global-store builds only.
195    if let Some(gfs) = global {
196        match read_snapshot_from(gfs, zone) {
197            Ok(Some(found)) => return Ok((Some(found.0), Some(found.1))),
198            Ok(None) => {}
199            // A corrupt shared zone falls through to this channel's copy.
200            Err(e) if crate::backend::transcript::damage::note_corrupt_text(zone, "snapshot read", &e) => {}
201            Err(e) => return Err(e),
202        }
203    }
204    if let Some(found) = read_snapshot_from(filestore, zone)? {
205        return Ok((Some(found.0), Some(found.1)));
206    }
207    Ok((None, None))
208}
209
210/// Read `output.state.json` from `zone` in `store`. `Ok(None)` when absent.
211pub(super) fn read_snapshot_from(store: &FileStore, zone: &str) -> Result<Option<(String, i64)>, String> {
212    let stat = store
213        .stat(zone, SNAPSHOT_FILE)
214        .map_err(|e| format!("stat: {e}"))?;
215    let Some(file) = stat else {
216        return Ok(None);
217    };
218    let bytes = store
219        .read_file(zone, SNAPSHOT_FILE)
220        .map_err(|e| format!("read_file: {e}"))?
221        .unwrap_or_default();
222    Ok(Some((String::from_utf8_lossy(&bytes).into_owned(), file.modts)))
223}
224
225#[cfg(test)]
226mod damage_tests {
227    use super::*;
228    use crate::backend::transcript::damage::{self, test_support};
229
230    #[test]
231    fn a_corrupt_shared_snapshot_is_read_from_this_channels_copy_and_marks_the_zone() {
232        let zone = "agent:snap-damage-1:current";
233        let (own, gfs) = (FileStore::open_in_memory().unwrap(), FileStore::open_in_memory().unwrap());
234        write_zone_file(&own, zone, SNAPSHOT_FILE, b"{\"own\":1}").unwrap();
235        write_zone_file(&gfs, zone, SNAPSHOT_FILE, b"{\"global\":1}").unwrap();
236        // Healthy: the shared copy wins, as before.
237        assert_eq!(read_session_state_in(&own, Some(&gfs), zone).unwrap().0.as_deref(), Some("{\"global\":1}"));
238        test_support::corrupt(&gfs);
239        let (text, _) = read_session_state_in(&own, Some(&gfs), zone).unwrap();
240        assert_eq!(text.as_deref(), Some("{\"own\":1}"), "the channel's copy answers");
241        assert!(damage::is_damaged(zone));
242    }
243
244    #[test]
245    fn a_read_error_that_is_not_corruption_is_still_an_error() {
246        let zone = "agent:snap-damage-2:current";
247        let (own, gfs) = (FileStore::open_in_memory().unwrap(), FileStore::open_in_memory().unwrap());
248        gfs.conn().lock().unwrap().execute_batch("DROP TABLE db_wave_file;").unwrap();
249        assert!(read_session_state_in(&own, Some(&gfs), zone).is_err());
250        assert!(!damage::is_damaged(zone));
251    }
252}