Skip to main content

agentmux_srv_core/backend/
continuity_segments.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Segment index (SPEC_DURABLE_CONVERSATION_MEMORY_2026_09_23.md §4.1, P1):
5//! one record per provider session an agent has run, so "this agent's
6//! conversation" is a chain AgentMux owns rather than whatever session id a
7//! pane happens to hold.
8//!
9//! Stored as an append-only event log, `segments.jsonl` in the global
10//! transcript store's `agent-uid:<uid>:segments` zone, not as a SQL table
11//! (§4.1.1): that store is shared by every srv on the machine and takes
12//! additions without a schema version bump, where a new table in
13//! `identity-store.db` would bump its version and lock older builds out of
14//! it (`check_schema_compat`). Events: `start` at spawn, `session` when a
15//! fresh process reports its provider session id, `end` when the process
16//! goes away. [`segments`] folds them back into one row per segment.
17//!
18//! The zone is keyed by the agent's UID (`AGENTMUX_AGENT_UID`), not its
19//! definition id: a template launch shares the template's transcript zone
20//! but is a different agent. It is deliberately not the transcript zone, so
21//! "New conversation" (which clears `agent:<defId>:current`) never erases the
22//! chain; a new conversation is just a segment whose rung is `fresh`.
23
24use serde::{Deserialize, Serialize};
25
26use crate::backend::storage::filestore::{FileMeta, FileOpts, FileStore};
27
28pub(crate) const SEGMENTS_FILE: &str = "segments.jsonl";
29/// Enough of the log's end to find the newest segment for a predecessor link
30/// without reading an agent's whole history.
31const TAIL_WINDOW_BYTES: i64 = 64 * 1024;
32
33/// How a segment began (§4.2's rungs; `relocated` arrives with P4).
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum Rung {
37    /// The provider resumed the previous session.
38    Native,
39    /// A fresh provider session, given AgentMux's record of the conversation.
40    Virtualized,
41    /// A fresh provider session with nothing carried over.
42    Fresh,
43}
44
45/// Why a segment's process went away.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
47#[serde(rename_all = "snake_case")]
48pub(crate) enum EndReason {
49    /// Exited on its own with status 0.
50    Exited,
51    /// Exited on its own with a non-zero status.
52    Crashed,
53    /// The pane was closed.
54    Closed,
55    /// Stopped to apply a runtime-config change; the next spawn resumes it.
56    Restarted,
57    /// Stopped for any other reason (user stop, controller replaced).
58    Stopped,
59}
60
61#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
62#[serde(tag = "event", rename_all = "snake_case")]
63enum Event {
64    Start(Start),
65    Session { segment_id: String, provider_session_id: String, at_ms: i64 },
66    End {
67        segment_id: String,
68        ended_at_ms: i64,
69        end_reason: EndReason,
70        byte_end: Option<i64>,
71        /// Size of the provider's session file when the process went away
72        /// (spec §4.4). `None`: unknown, or a record from before the field.
73        #[serde(default, skip_serializing_if = "Option::is_none")]
74        provider_bytes_end: Option<i64>,
75    },
76}
77
78/// What is known about a segment when its process starts.
79#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
80pub struct Start {
81    pub segment_id: String,
82    pub agent_uid: String,
83    /// The block's `agentId`: the transcript zone's key, which differs from
84    /// `agent_uid` for a template launch.
85    pub definition_id: Option<String>,
86    pub provider: String,
87    /// Where native resume would have to look (`CLAUDE_CONFIG_DIR`, …).
88    pub config_dir: Option<String>,
89    /// Known up front on a resume; otherwise filled in by a `session` event.
90    pub provider_session_id: Option<String>,
91    pub cwd: String,
92    pub channel: String,
93    pub agentmux_version: String,
94    pub block_id: String,
95    /// The global transcript zone this segment appends to, and its size then.
96    pub zone: Option<String>,
97    pub byte_start: Option<i64>,
98    pub started_at_ms: i64,
99    pub continuity_rung: Rung,
100    pub predecessor_segment_id: Option<String>,
101    /// The single-live-instance lease epoch this segment's process held
102    /// (SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24 Phase 3). A change between
103    /// consecutive segments is an ownership change — another instance, or a
104    /// takeover — visible in the ledger. `None`: no lease (older build, no
105    /// UID) or a record written before this field.
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub lease_epoch: Option<u64>,
108    /// The Anthropic identity `config_dir` was signed in as
109    /// (`account_email::identity_key_from_oauth_dir`,
110    /// SPEC_RESUME_GATE_AND_SAME_IDENTITY_CONTINUATION_2026_09_25.md §4.1).
111    /// `None`: unknown, or a record written before this field.
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub identity_key: Option<String>,
114    /// The session this spawn resumed with `--fork-session` after
115    /// relocating it from another login of the same identity (spec §4.3).
116    /// Its own id arrives in the segment's `session` event.
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub forked_from: Option<String>,
119}
120
121/// One segment, folded from its events.
122#[derive(Debug, Clone, PartialEq)]
123pub struct Segment {
124    pub start: Start,
125    pub ended_at_ms: Option<i64>,
126    pub end_reason: Option<EndReason>,
127    pub byte_end: Option<i64>,
128    pub provider_bytes_end: Option<i64>,
129}
130
131/// `agent-uid:<uid>:segments`, or `None` for a UID outside the safe zone-name
132/// character set.
133pub fn zone_for(agent_uid: &str) -> Option<String> {
134    crate::backend::agent_session::is_valid_definition_id(agent_uid).then(|| format!("agent-uid:{agent_uid}:segments"))
135}
136
137fn append(fs: &FileStore, zone: &str, event: &Event) -> Result<(), String> {
138    use crate::backend::transcript::damage;
139    // A log found corrupt is not written to again in this process.
140    if damage::is_damaged(zone) {
141        return Err("the agent's segment log is damaged".to_string());
142    }
143    let seen = |op: &str, e: crate::backend::storage::error::StoreError| {
144        damage::note_if_shared(fs, zone, "segment log", &e);
145        format!("{op}: {e}")
146    };
147    let mut line = serde_json::to_vec(event).map_err(|e| format!("encode segment event: {e}"))?;
148    line.push(b'\n');
149    if fs.stat(zone, SEGMENTS_FILE).map_err(|e| seen("stat segments", e))?.is_none() {
150        // Two srvs can race to create it; losing that race is fine.
151        let _ = fs.make_file(zone, SEGMENTS_FILE, FileMeta::default(), FileOpts::default());
152    }
153    fs.append_data(zone, SEGMENTS_FILE, &line).map_err(|e| seen("append segment event", e))
154}
155
156/// The segment log's bytes: `None` for none, or for a log found corrupt (marked here, the first time).
157fn read_log(fs: &FileStore, zone: &str) -> Option<Vec<u8>> {
158    use crate::backend::transcript::damage;
159    if damage::is_damaged(zone) {
160        return None;
161    }
162    match fs.read_file(zone, SEGMENTS_FILE) {
163        Ok(data) => data,
164        Err(e) => {
165            damage::note_if_shared(fs, zone, "segment log", &e);
166            None
167        }
168    }
169}
170
171fn events_in(bytes: &[u8]) -> impl Iterator<Item = Event> + '_ {
172    bytes.split(|b| *b == b'\n').filter_map(|line| serde_json::from_slice::<Event>(line).ok())
173}
174
175/// The id of the agent's newest segment, from the end of its log.
176fn newest_segment_id(fs: &FileStore, zone: &str) -> Option<String> {
177    use crate::backend::transcript::damage;
178    if damage::is_damaged(zone) {
179        return None;
180    }
181    let file = match fs.stat(zone, SEGMENTS_FILE) {
182        Ok(file) => file?,
183        Err(e) => {
184            damage::note_if_shared(fs, zone, "segment log", &e);
185            return None;
186        }
187    };
188    let offset = (file.size - TAIL_WINDOW_BYTES).max(0);
189    let (_, data) = match fs.read_at(zone, SEGMENTS_FILE, offset, file.size - offset) {
190        Ok(read) => read,
191        Err(e) => {
192            damage::note_if_shared(fs, zone, "segment log", &e);
193            return None;
194        }
195    };
196    let mut newest: Option<(i64, String)> = None;
197    for event in events_in(&data) {
198        if let Event::Start(s) = event {
199            if newest.as_ref().is_none_or(|(at, _)| s.started_at_ms >= *at) {
200                newest = Some((s.started_at_ms, s.segment_id));
201            }
202        }
203    }
204    newest.map(|(_, id)| id)
205}
206
207/// Records a segment's start and returns its id. `start.segment_id` and
208/// `start.predecessor_segment_id` are filled in here.
209pub fn record_start(fs: &FileStore, mut start: Start) -> Result<String, String> {
210    let zone = zone_for(&start.agent_uid).ok_or("agent uid is not a valid zone key")?;
211    start.segment_id = uuid::Uuid::new_v4().to_string();
212    start.predecessor_segment_id = newest_segment_id(fs, &zone);
213    let id = start.segment_id.clone();
214    append(fs, &zone, &Event::Start(start))?;
215    Ok(id)
216}
217
218pub(crate) fn record_session(fs: &FileStore, agent_uid: &str, segment_id: &str, provider_session_id: &str, at_ms: i64) -> Result<(), String> {
219    let zone = zone_for(agent_uid).ok_or("agent uid is not a valid zone key")?;
220    append(
221        fs,
222        &zone,
223        &Event::Session { segment_id: segment_id.to_string(), provider_session_id: provider_session_id.to_string(), at_ms },
224    )
225}
226
227#[cfg(test)]
228pub(crate) fn record_end(
229    fs: &FileStore,
230    agent_uid: &str,
231    segment_id: &str,
232    end_reason: EndReason,
233    byte_end: Option<i64>,
234    ended_at_ms: i64,
235) -> Result<(), String> {
236    record_end_with_provider_bytes(fs, agent_uid, segment_id, end_reason, byte_end, None, ended_at_ms)
237}
238
239/// [`record_end`], also recording the provider session file's size then
240/// (spec §4.4), so a later spawn can tell whether something outside
241/// AgentMux wrote to it since.
242pub(crate) fn record_end_with_provider_bytes(
243    fs: &FileStore,
244    agent_uid: &str,
245    segment_id: &str,
246    end_reason: EndReason,
247    byte_end: Option<i64>,
248    provider_bytes_end: Option<i64>,
249    ended_at_ms: i64,
250) -> Result<(), String> {
251    let zone = zone_for(agent_uid).ok_or("agent uid is not a valid zone key")?;
252    append(fs, &zone, &Event::End { segment_id: segment_id.to_string(), ended_at_ms, end_reason, byte_end, provider_bytes_end })
253}
254
255/// Every segment the agent has run, oldest first. A segment with no `end` is
256/// running, or its srv died before it could record one.
257pub fn segments(fs: &FileStore, agent_uid: &str) -> Vec<Segment> {
258    let Some(zone) = zone_for(agent_uid) else { return Vec::new() };
259    let Some(data) = read_log(fs, &zone) else { return Vec::new() };
260    fold(events_in(&data))
261}
262
263fn fold(events: impl Iterator<Item = Event>) -> Vec<Segment> {
264    let mut out: Vec<Segment> = Vec::new();
265    for event in events {
266        match event {
267            Event::Start(start) => {
268                out.push(Segment { start, ended_at_ms: None, end_reason: None, byte_end: None, provider_bytes_end: None });
269            }
270            Event::Session { segment_id, provider_session_id, .. } => {
271                if let Some(s) = out.iter_mut().rev().find(|s| s.start.segment_id == segment_id) {
272                    s.start.provider_session_id = Some(provider_session_id);
273                }
274            }
275            Event::End { segment_id, ended_at_ms, end_reason, byte_end, provider_bytes_end } => {
276                // Closed exactly once: the first `end` wins.
277                if let Some(s) = out.iter_mut().rev().find(|s| s.start.segment_id == segment_id && s.ended_at_ms.is_none()) {
278                    s.ended_at_ms = Some(ended_at_ms);
279                    s.end_reason = Some(end_reason);
280                    s.byte_end = byte_end;
281                    s.provider_bytes_end = provider_bytes_end;
282                }
283            }
284        }
285    }
286    out.sort_by_key(|s| s.start.started_at_ms);
287    out
288}
289
290/// The provider session the agent's conversation was last in: the session
291/// of the newest segment, other than `current` (the spawn now running or
292/// just failed), that has one. `None` when the agent has no such segment.
293pub(crate) fn head_session(segments: &[Segment], current: Option<&str>) -> Option<String> {
294    segments
295        .iter()
296        .rev()
297        .filter(|s| Some(s.start.segment_id.as_str()) != current)
298        .find_map(|s| s.start.provider_session_id.clone())
299}
300
301/// Whether a resume-failure recovery may continue `candidate` (§4.2: only
302/// the head of the chain is this conversation). With a chain, any other
303/// session is older or unrelated history. It's typically the same agent's
304/// session from the last time it ran under this account, and resuming it
305/// would show "Resumed" on the wrong conversation, so the caller falls
306/// through to a fresh session carrying the continuation packet. With no
307/// known head (an agent from before the segment index, whose only segment is
308/// the current one), nothing better is known and recovery works as before.
309pub(crate) fn recovery_allowed(candidate: &str, head: Option<&str>) -> bool {
310    head.is_none_or(|h| h == candidate)
311}
312
313/// What the resume gate decided for a session a spawn is about to `--resume`
314/// (SPEC_RESUME_GATE_AND_SAME_IDENTITY_CONTINUATION_2026_09_25.md §4.2).
315#[derive(Debug, Clone, PartialEq, Eq)]
316pub(crate) enum ResumeGate {
317    /// Resume the candidate: it is the chain head, or the chain can't say
318    /// otherwise.
319    Allow,
320    /// The conversation moved on to `head`, reachable here: resume that.
321    Redirect { head: String },
322    /// The conversation moved on to `head`, which this spawn can't reach:
323    /// resume nothing, so the spawn starts fresh and carries the record.
324    Refuse { head: String },
325    /// `head` lives under another login of the same identity, readable at
326    /// `from_config_dir`: copy it in and resume it with `--fork-session`
327    /// (spec §4.3).
328    Relocate { head: String, from_config_dir: String },
329    /// `head` is reachable here, but its file grew after AgentMux last saw
330    /// it: the conversation continued outside AgentMux. Resume it with
331    /// `--fork-session`, so that branch is never appended to by a second
332    /// writer (spec §4.4, H4).
333    Fork { head: String },
334    /// This agent has no conversation of its own yet, and the agent it was
335    /// forked from is at the candidate (`GateInput::fork_source`): copy that
336    /// session in from `from_config_dir` / `from_cwd` (a fork works in its own
337    /// directory, so the CLI can't find it there) and resume it with
338    /// `--fork-session`, so the fork starts from its parent's conversation and
339    /// never writes to it (the fork-isolation report in #4744, F5).
340    ForkFrom { head: String, from_config_dir: String, from_cwd: String },
341}
342
343/// What the gate weighs about the spawn.
344#[derive(Debug, Clone, Copy, Default)]
345pub(crate) struct GateInput<'a> {
346    /// The session the spawn would `--resume`.
347    pub candidate: &'a str,
348    pub head: Option<&'a Head>,
349    /// The spawn's identity key.
350    pub identity: Option<&'a str>,
351    /// An id this controller already saw the CLI reject.
352    pub poisoned: Option<&'a str>,
353    /// The spawn's provider config dir and working dir.
354    pub config_dir: &'a str,
355    pub cwd: &'a str,
356    /// The chain head of the agent this one was forked from, when this one
357    /// has none of its own (`fork_source_head`).
358    pub fork_source: Option<&'a Head>,
359}
360
361/// Where the agent's conversation was last: the newest segment that has a
362/// provider session, and what that segment recorded about it.
363#[derive(Debug, Clone, Default, PartialEq, Eq)]
364pub struct Head {
365    pub session_id: String,
366    pub identity_key: Option<String>,
367    pub config_dir: Option<String>,
368    pub provider: String,
369    pub cwd: String,
370    /// The provider file's size when the head's segment ended, when known.
371    pub provider_bytes_end: Option<i64>,
372}
373
374/// Only the chain head is resumed natively (spec §3 I1), and never across
375/// identities (I2). `input.head` is the agent's [`chain_head`]; `None` (an
376/// agent from before the segment index, or no readable chain) allows the
377/// candidate, as before the gate existed. A head equal to the poisoned id
378/// allows too: that head is known dead, so the chain has nothing better to
379/// offer than the candidate. The identity check refuses only when both
380/// sides are known and differ. A head recorded under the spawn's own config
381/// dir whose file isn't there is refused too: the provider never wrote it.
382///
383/// `size_here(sid)`: the size of the session's file under the spawn's
384/// config dir and cwd, `None` when it isn't there. `resumable_at(config_dir,
385/// cwd, sid)`: a session file for that working dir exists under that config
386/// dir with a complete record to copy (§4.3; its last record may still be
387/// being written, and the copy is cut back to a complete one).
388pub(crate) fn resume_gate(
389    input: &GateInput<'_>,
390    size_here: impl Fn(&str) -> Option<u64>,
391    resumable_at: impl Fn(&str, &str, &str) -> bool,
392) -> ResumeGate {
393    let Some(head) = input.head else { return fork_from(input, &resumable_at).unwrap_or(ResumeGate::Allow) };
394    if Some(head.session_id.as_str()) == input.poisoned {
395        return ResumeGate::Allow;
396    }
397    let refuse = || ResumeGate::Refuse { head: head.session_id.clone() };
398    if matches!((head.identity_key.as_deref(), input.identity), (Some(h), Some(s)) if h != s) {
399        return refuse();
400    }
401    let is_candidate = head.session_id == input.candidate;
402    if let Some(size) = size_here(&head.session_id) {
403        if head.provider_bytes_end.is_some_and(|end| i64::try_from(size).unwrap_or(i64::MAX) > end) {
404            return ResumeGate::Fork { head: head.session_id.clone() };
405        }
406        return if is_candidate { ResumeGate::Allow } else { ResumeGate::Redirect { head: head.session_id.clone() } };
407    }
408    if let Some(from) = relocation_source(head, input) {
409        if resumable_at(from, input.cwd, &head.session_id) {
410            return ResumeGate::Relocate { head: head.session_id.clone(), from_config_dir: from.to_string() };
411        }
412    }
413    // Recorded under this very config dir, yet its file isn't here: Claude
414    // never wrote it (a session is saved with its first turn, and this one was
415    // restarted before it had one), or it was deleted since. `--resume` can
416    // only fail, and the user would see the CLI's error; start fresh with the
417    // record instead.
418    if head.config_dir.as_deref().is_some_and(|dir| same_dir(dir, input.config_dir)) {
419        return refuse();
420    }
421    // The head is out of reach and can't be relocated. As the candidate, it
422    // goes on to `--resume` as before the gate: the CLI's rejection and the
423    // retry path already handle it. As anything else, nothing is resumed.
424    if is_candidate {
425        ResumeGate::Allow
426    } else {
427        refuse()
428    }
429}
430
431/// The head's config dir when §4.3's metadata preconditions hold: a Claude
432/// session, under another config dir than the spawn's, recorded under the
433/// spawn's own identity (both known, I2), for the same project dir.
434fn relocation_source<'h>(head: &'h Head, input: &GateInput<'_>) -> Option<&'h str> {
435    if !matches!(head.provider.as_str(), "claude" | "claude-code") {
436        return None;
437    }
438    let from = head.config_dir.as_deref()?;
439    if same_dir(from, input.config_dir) {
440        return None;
441    }
442    if head.identity_key.as_deref()? != input.identity? {
443        return None;
444    }
445    let slug = crate::backend::claude_layout::project_dir_name;
446    (slug(&head.cwd) == slug(input.cwd)).then_some(from)
447}
448
449/// `ResumeGate::ForkFrom` when this agent has no chain and the agent it was
450/// forked from is at the candidate: a Claude session, under the spawn's own
451/// identity (both known, I2), whose file holds a complete record where it
452/// was recorded.
453fn fork_from(input: &GateInput<'_>, resumable_at: &impl Fn(&str, &str, &str) -> bool) -> Option<ResumeGate> {
454    let source = input.fork_source?;
455    if source.session_id != input.candidate || !matches!(source.provider.as_str(), "claude" | "claude-code") {
456        return None;
457    }
458    if source.identity_key.as_deref()? != input.identity? {
459        return None;
460    }
461    let from = source.config_dir.as_deref()?;
462    resumable_at(from, &source.cwd, &source.session_id).then(|| ResumeGate::ForkFrom {
463        head: source.session_id.clone(),
464        from_config_dir: from.to_string(),
465        from_cwd: source.cwd.clone(),
466    })
467}
468
469/// The chain head of the agent `agent_uid` was forked from (its definition
470/// has a `branch_label` and a `parent_id`): what a fork with no conversation
471/// of its own starts from (`ResumeGate::ForkFrom`). Shared by the spawn's
472/// gate and the pane's resume preflight.
473pub fn fork_source_head(
474    store: &crate::backend::storage::store::Store,
475    fs: &FileStore,
476    agent_uid: &str,
477) -> Option<Head> {
478    let def = store.agent_def_get(agent_uid).ok()??;
479    if def.branch_label.trim().is_empty() || def.parent_id.trim().is_empty() {
480        return None;
481    }
482    chain_head(fs, def.parent_id.trim()).map(with_legacy_identity)
483}
484
485fn same_dir(a: &str, b: &str) -> bool {
486    let norm = |s: &str| s.replace('\\', "/").trim_end_matches('/').to_lowercase();
487    norm(a) == norm(b)
488}
489
490/// A head whose segment predates `identity_key` (recorded by a build
491/// before #3839) takes the identity from its own config dir's
492/// `.claude.json`, so an agent's first upgrade from such a build can still
493/// relocate (spec §4.1). That file names whoever is signed in there now,
494/// which for an account's own dir is the login the session ran under unless
495/// the dir was since re-logged-into as someone else; a recorded key always
496/// wins. Unreadable (the dir is gone) stays unknown, which never relocates.
497pub fn with_legacy_identity(mut head: Head) -> Head {
498    if head.identity_key.is_none() {
499        if let Some(dir) = head.config_dir.as_deref() {
500            head.identity_key = crate::identity::account_email::identity_key_from_oauth_dir(&head.provider, dir);
501        }
502    }
503    head
504}
505
506/// Where the agent's conversation was last, read from its chain in `fs`.
507/// `None` when the UID has no chain.
508pub fn chain_head(fs: &FileStore, agent_uid: &str) -> Option<Head> {
509    segments(fs, agent_uid).into_iter().rev().find_map(|s| {
510        let session_id = s.start.provider_session_id?;
511        Some(Head {
512            session_id,
513            identity_key: s.start.identity_key,
514            config_dir: s.start.config_dir,
515            provider: s.start.provider,
516            cwd: s.start.cwd,
517            provider_bytes_end: s.provider_bytes_end,
518        })
519    })
520}
521
522/// The rung a spawn started on, from what the spawn knows: whether it passed
523/// `--resume`, and whether it carries a continuation packet.
524pub fn rung_for_spawn(resumed: bool, carries_packet: bool) -> Rung {
525    if resumed {
526        Rung::Native
527    } else if carries_packet {
528        Rung::Virtualized
529    } else {
530        Rung::Fresh
531    }
532}
533
534/// Why a killed process went away, from the controller's state at the kill.
535pub(crate) fn kill_reason(closing_this_generation: bool, restart_pending: bool) -> EndReason {
536    if closing_this_generation {
537        EndReason::Closed
538    } else if restart_pending {
539        EndReason::Restarted
540    } else {
541        EndReason::Stopped
542    }
543}
544
545pub(crate) fn exit_reason(exit_code: i32) -> EndReason {
546    if exit_code == 0 { EndReason::Exited } else { EndReason::Crashed }
547}
548
549#[cfg(test)]
550mod tests {
551    use super::*;
552
553    const UID: &str = "uid-1";
554
555    fn start(at: i64, rung: Rung) -> Start {
556        Start {
557            segment_id: String::new(),
558            agent_uid: UID.into(),
559            definition_id: Some("def-1".into()),
560            provider: "claude".into(),
561            config_dir: Some("C:/cfg/a".into()),
562            provider_session_id: None,
563            cwd: "C:/work".into(),
564            channel: "stable".into(),
565            agentmux_version: "0.57.2".into(),
566            block_id: "block-1".into(),
567            zone: Some("agent:def-1:current".into()),
568            byte_start: Some(100),
569            started_at_ms: at,
570            continuity_rung: rung,
571            predecessor_segment_id: None,
572            lease_epoch: None,
573            identity_key: None,
574            forked_from: None,
575        }
576    }
577
578    /// SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24 Phase 3: each segment
579    /// records the lease epoch its process held, so an ownership change
580    /// between segments is visible in the ledger; a record written before
581    /// the field existed still reads, as `None`.
582    #[test]
583    fn segments_record_the_lease_epoch_and_older_records_still_read() {
584        let fs = FileStore::open_in_memory().unwrap();
585        let first = record_start(&fs, Start { lease_epoch: Some(3), ..start(1_000, Rung::Fresh) }).unwrap();
586        record_start(&fs, Start { lease_epoch: Some(4), ..start(2_000, Rung::Native) }).unwrap();
587        let all = segments(&fs, UID);
588        assert_eq!(all.iter().map(|s| s.start.lease_epoch).collect::<Vec<_>>(), vec![Some(3), Some(4)]);
589        assert_eq!(all[0].start.segment_id, first);
590
591        let old = serde_json::json!({
592            "event": "start", "segment_id": "s", "agent_uid": UID, "definition_id": null, "provider": "claude",
593            "config_dir": null, "provider_session_id": null, "cwd": "", "channel": "stable",
594            "agentmux_version": "0.57.0", "block_id": "b", "zone": null, "byte_start": null,
595            "started_at_ms": 1, "continuity_rung": "fresh", "predecessor_segment_id": null,
596        });
597        match serde_json::from_value::<Event>(old).unwrap() {
598            Event::Start(s) => assert_eq!(s.lease_epoch, None),
599            other => panic!("expected a start event, got {other:?}"),
600        }
601    }
602
603    #[test]
604    fn segments_chain_to_their_predecessor_and_fold_their_events() {
605        let fs = FileStore::open_in_memory().unwrap();
606        let first = record_start(&fs, start(1_000, Rung::Fresh)).unwrap();
607        record_session(&fs, UID, &first, "sid-a", 1_001).unwrap();
608        record_end(&fs, UID, &first, EndReason::Crashed, Some(900), 2_000).unwrap();
609        let second = record_start(&fs, start(3_000, Rung::Virtualized)).unwrap();
610
611        let all = segments(&fs, UID);
612        assert_eq!(all.len(), 2);
613        assert_eq!(all[0].start.segment_id, first);
614        assert_eq!(all[0].start.provider_session_id.as_deref(), Some("sid-a"));
615        assert_eq!((all[0].ended_at_ms, all[0].end_reason, all[0].byte_end), (Some(2_000), Some(EndReason::Crashed), Some(900)));
616        assert_eq!(all[0].start.predecessor_segment_id, None);
617        assert_eq!(all[1].start.predecessor_segment_id.as_deref(), Some(first.as_str()));
618        assert_eq!(all[1].start.continuity_rung, Rung::Virtualized);
619        assert!(all[1].ended_at_ms.is_none(), "still running");
620        assert_ne!(first, second);
621    }
622
623    // ── resume_gate (SPEC_RESUME_GATE_AND_SAME_IDENTITY_CONTINUATION §4.2) ──
624
625    fn head(sid: &str, identity: Option<&str>) -> Head {
626        Head { session_id: sid.into(), identity_key: identity.map(str::to_string), ..Default::default() }
627    }
628
629    /// The gate over a spawn in `C:/cfg/new` for `C:/work`, where `here` are
630    /// the sessions under the spawn's config dir and `elsewhere` the ones
631    /// complete under any other.
632    fn gate(candidate: &str, head: Option<&Head>, identity: Option<&str>, poisoned: Option<&str>, here: &[&str], elsewhere: &[&str]) -> ResumeGate {
633        let input = GateInput { candidate, head, identity, poisoned, config_dir: "C:/cfg/new", cwd: "C:/work", fork_source: None };
634        resume_gate(&input, |sid| here.contains(&sid).then_some(10), |_, _, sid| elsewhere.contains(&sid))
635    }
636
637    // A fork's first spawn (the fork-isolation report in #4744, F5).
638
639    fn fork_source(sid: &str, identity: Option<&str>) -> Head {
640        Head {
641            session_id: sid.into(),
642            identity_key: identity.map(str::to_string),
643            config_dir: Some("C:/cfg/parent".into()),
644            provider: "claude".into(),
645            cwd: "C:/parent".into(),
646            provider_bytes_end: None,
647        }
648    }
649
650    /// The gate for a fork with no chain, `source` its parent's head, whose
651    /// file is complete at the parent's own config dir and working dir.
652    fn fork_gate(candidate: &str, source: &Head, identity: Option<&str>, complete: bool) -> ResumeGate {
653        let input = GateInput {
654            candidate,
655            head: None,
656            identity,
657            poisoned: None,
658            config_dir: "C:/cfg/new",
659            cwd: "C:/work",
660            fork_source: Some(source),
661        };
662        resume_gate(&input, |_| None, |dir, cwd, sid| complete && dir == "C:/cfg/parent" && cwd == "C:/parent" && sid == candidate)
663    }
664
665    #[test]
666    fn a_fork_without_a_chain_forks_from_its_parents_head() {
667        let source = fork_source("p1", Some("k1"));
668        assert_eq!(
669            fork_gate("p1", &source, Some("k1"), true),
670            ResumeGate::ForkFrom { head: "p1".into(), from_config_dir: "C:/cfg/parent".into(), from_cwd: "C:/parent".into() }
671        );
672    }
673
674    #[test]
675    fn a_fork_forks_only_its_parents_complete_head_under_its_own_identity() {
676        let source = fork_source("p1", Some("k1"));
677        assert_eq!(fork_gate("p0", &source, Some("k1"), true), ResumeGate::Allow, "not the parent's head");
678        assert_eq!(fork_gate("p1", &source, Some("k2"), true), ResumeGate::Allow, "another identity (I2)");
679        assert_eq!(fork_gate("p1", &source, None, true), ResumeGate::Allow, "identity unknown");
680        assert_eq!(fork_gate("p1", &source, Some("k1"), false), ResumeGate::Allow, "no complete file there");
681    }
682
683    #[test]
684    fn the_chain_head_itself_is_resumed() {
685        let h = head("s2", None);
686        assert_eq!(gate("s2", Some(&h), None, None, &["s2"], &[]), ResumeGate::Allow);
687    }
688
689    #[test]
690    fn without_a_chain_the_candidate_is_resumed_as_before() {
691        assert_eq!(gate("s1", None, Some("k1"), None, &[], &[]), ResumeGate::Allow);
692    }
693
694    /// The operator's case: the pane holds S1, the conversation moved on to S2.
695    #[test]
696    fn a_stale_candidate_is_redirected_to_a_reachable_head() {
697        let h = head("s2", None);
698        assert_eq!(gate("s1", Some(&h), None, None, &["s1", "s2"], &[]), ResumeGate::Redirect { head: "s2".into() });
699    }
700
701    #[test]
702    fn a_stale_candidate_is_refused_when_the_head_is_out_of_reach() {
703        let h = head("s2", None);
704        assert_eq!(gate("s1", Some(&h), None, None, &["s1"], &[]), ResumeGate::Refuse { head: "s2".into() });
705    }
706
707    /// The head as the candidate but out of reach, and not relocatable: it
708    /// goes to `--resume` as before the gate; the CLI's rejection and the
709    /// retry path handle it.
710    #[test]
711    fn an_unreachable_head_as_the_candidate_is_left_to_the_retry_path() {
712        let h = head("s2", None);
713        assert_eq!(gate("s2", Some(&h), None, None, &[], &[]), ResumeGate::Allow);
714    }
715
716    /// A fresh session restarted before its first turn (a model change right
717    /// after an account switch): recorded under the spawn's own config dir,
718    /// never written there. Resuming it could only fail.
719    #[test]
720    fn a_head_never_written_under_the_spawns_own_dir_is_not_resumed() {
721        let h = Head { config_dir: Some("c:\\cfg\\new\\".into()), provider: "claude".into(), ..head("s2", Some("k1")) };
722        assert_eq!(gate("s2", Some(&h), Some("k1"), None, &[], &[]), ResumeGate::Refuse { head: "s2".into() });
723        assert_eq!(gate("s2", Some(&h), Some("k1"), None, &["s2"], &[]), ResumeGate::Allow, "written: resumed");
724    }
725
726    #[test]
727    fn a_poisoned_head_never_displaces_the_candidate() {
728        let h = head("s2", None);
729        assert_eq!(gate("s1", Some(&h), None, Some("s2"), &["s2"], &[]), ResumeGate::Allow);
730    }
731
732    // Identity (spec §3 I2, H3): never resume across identities.
733
734    /// The config dir was re-logged-into as someone else: the head's file is
735    /// here, but it belongs to another identity.
736    #[test]
737    fn the_head_under_another_identity_is_not_resumed() {
738        let h = head("s2", Some("k-old"));
739        assert_eq!(gate("s2", Some(&h), Some("k-new"), None, &["s2"], &[]), ResumeGate::Refuse { head: "s2".into() });
740        assert_eq!(gate("s1", Some(&h), Some("k-new"), None, &["s2"], &[]), ResumeGate::Refuse { head: "s2".into() });
741    }
742
743    #[test]
744    fn the_same_identity_resumes_and_redirects() {
745        let h = head("s2", Some("k1"));
746        assert_eq!(gate("s2", Some(&h), Some("k1"), None, &["s2"], &[]), ResumeGate::Allow);
747        assert_eq!(gate("s1", Some(&h), Some("k1"), None, &["s2"], &[]), ResumeGate::Redirect { head: "s2".into() });
748    }
749
750    /// Either side unknown (an older record, an unreadable `.claude.json`):
751    /// no information, so the gate behaves as it did before identities.
752    #[test]
753    fn an_unknown_identity_on_either_side_changes_nothing() {
754        let known = head("s2", Some("k1"));
755        let unknown = head("s2", None);
756        assert_eq!(gate("s2", Some(&known), None, None, &["s2"], &[]), ResumeGate::Allow);
757        assert_eq!(gate("s2", Some(&unknown), Some("k1"), None, &["s2"], &[]), ResumeGate::Allow);
758        assert_eq!(gate("s1", Some(&known), None, None, &["s2"], &[]), ResumeGate::Redirect { head: "s2".into() });
759    }
760
761    // Relocation (spec §4.3): the head under another login of the same identity.
762
763    fn elsewhere(sid: &str, identity: Option<&str>) -> Head {
764        Head {
765            session_id: sid.into(),
766            identity_key: identity.map(str::to_string),
767            config_dir: Some("C:/cfg/old".into()),
768            provider: "claude".into(),
769            cwd: "C:/work".into(),
770            provider_bytes_end: None,
771        }
772    }
773
774    /// A rebuild: new login, same person. The pane holds the head, whose file
775    /// is only under the old login.
776    #[test]
777    fn the_head_under_another_login_of_the_same_identity_is_relocated() {
778        let h = elsewhere("s2", Some("k1"));
779        let relocate = ResumeGate::Relocate { head: "s2".into(), from_config_dir: "C:/cfg/old".into() };
780        assert_eq!(gate("s2", Some(&h), Some("k1"), None, &[], &["s2"]), relocate);
781        assert_eq!(gate("s1", Some(&h), Some("k1"), None, &["s1"], &["s2"]), relocate, "a stale candidate too");
782    }
783
784    #[test]
785    fn relocation_needs_every_precondition() {
786        let base = elsewhere("s2", Some("k1"));
787        let not_relocated = |h: &Head, identity: Option<&str>, elsewhere: &[&str]| {
788            !matches!(gate("s1", Some(h), identity, None, &[], elsewhere), ResumeGate::Relocate { .. })
789        };
790        assert!(not_relocated(&base, Some("k1"), &[]), "no complete source file");
791        assert!(not_relocated(&base, None, &["s2"]), "spawn identity unknown");
792        assert!(not_relocated(&Head { identity_key: None, ..base.clone() }, Some("k1"), &["s2"]), "head identity unknown");
793        assert!(not_relocated(&Head { provider: "codex".into(), ..base.clone() }, Some("k1"), &["s2"]), "not Claude");
794        assert!(not_relocated(&Head { config_dir: None, ..base.clone() }, Some("k1"), &["s2"]), "no recorded dir");
795        assert!(not_relocated(&Head { config_dir: Some("c:\\cfg\\new\\".into()), ..base.clone() }, Some("k1"), &["s2"]), "the same dir");
796        assert!(not_relocated(&Head { cwd: "C:/elsewhere".into(), ..base.clone() }, Some("k1"), &["s2"]), "another project");
797        assert_eq!(
798            gate("s1", Some(&Head { identity_key: Some("k2".into()), ..base }), Some("k1"), None, &[], &["s2"]),
799            ResumeGate::Refuse { head: "s2".into() },
800            "another identity is refused outright"
801        );
802    }
803
804    // Continued outside AgentMux (spec §4.4, H4).
805
806    /// The head's file is larger than when its segment ended: something
807    /// outside AgentMux (a terminal `claude --resume`) continued it.
808    #[test]
809    fn a_head_that_grew_outside_agentmux_is_forked() {
810        let h = Head { provider_bytes_end: Some(9), ..head("s2", None) };
811        assert_eq!(gate("s2", Some(&h), None, None, &["s2"], &[]), ResumeGate::Fork { head: "s2".into() });
812        assert_eq!(gate("s1", Some(&h), None, None, &["s2"], &[]), ResumeGate::Fork { head: "s2".into() });
813    }
814
815    #[test]
816    fn a_head_as_agentmux_left_it_resumes_in_place() {
817        let same = Head { provider_bytes_end: Some(10), ..head("s2", None) };
818        let unknown = Head { provider_bytes_end: None, ..head("s2", None) };
819        assert_eq!(gate("s2", Some(&same), None, None, &["s2"], &[]), ResumeGate::Allow);
820        assert_eq!(gate("s2", Some(&unknown), None, None, &["s2"], &[]), ResumeGate::Allow);
821    }
822
823    #[test]
824    fn a_segment_end_records_the_provider_file_size_and_older_ends_still_read() {
825        let fs = FileStore::open_in_memory().unwrap();
826        let a = record_start(&fs, start(1_000, Rung::Fresh)).unwrap();
827        record_session(&fs, UID, &a, "sid-a", 1_001).unwrap();
828        record_end_with_provider_bytes(&fs, UID, &a, EndReason::Exited, None, Some(4_096), 2_000).unwrap();
829        assert_eq!(chain_head(&fs, UID).unwrap().provider_bytes_end, Some(4_096));
830
831        let old = serde_json::json!({"event": "end", "segment_id": "s", "ended_at_ms": 5, "end_reason": "exited", "byte_end": null});
832        match serde_json::from_value::<Event>(old).unwrap() {
833            Event::End { provider_bytes_end, .. } => assert_eq!(provider_bytes_end, None),
834            other => panic!("expected an end event, got {other:?}"),
835        }
836    }
837
838    // A head recorded before identity keys existed (spec §4.1).
839
840    fn login_dir(account: &str, org: &str) -> tempfile::TempDir {
841        let d = tempfile::tempdir().unwrap();
842        std::fs::write(
843            d.path().join(".claude.json"),
844            format!(r#"{{"oauthAccount":{{"accountUuid":"{account}","organizationUuid":"{org}"}}}}"#),
845        )
846        .unwrap();
847        d
848    }
849
850    #[test]
851    fn a_legacy_head_takes_its_identity_from_its_own_config_dir() {
852        let dir = login_dir("acc-1", "org-1");
853        let path = dir.path().to_string_lossy().to_string();
854        let legacy = Head { config_dir: Some(path.clone()), provider: "claude".into(), ..head("s2", None) };
855        let expected = crate::identity::account_email::identity_key_from_oauth_dir("claude", &path);
856        assert!(expected.is_some());
857        assert_eq!(with_legacy_identity(legacy).identity_key, expected);
858    }
859
860    #[test]
861    fn a_recorded_identity_always_wins_and_an_unreadable_dir_stays_unknown() {
862        let dir = login_dir("acc-1", "org-1");
863        let path = dir.path().to_string_lossy().to_string();
864        let recorded = Head { config_dir: Some(path), provider: "claude".into(), ..head("s2", Some("k-recorded")) };
865        assert_eq!(with_legacy_identity(recorded).identity_key.as_deref(), Some("k-recorded"));
866        let gone = Head { config_dir: Some("/no/such/dir".into()), provider: "claude".into(), ..head("s2", None) };
867        assert_eq!(with_legacy_identity(gone).identity_key, None);
868        let no_dir = Head { provider: "claude".into(), ..head("s2", None) };
869        assert_eq!(with_legacy_identity(no_dir).identity_key, None);
870    }
871
872    #[test]
873    fn the_chain_head_is_the_newest_segment_with_a_session() {
874        let fs = FileStore::open_in_memory().unwrap();
875        assert_eq!(chain_head(&fs, UID), None);
876        let a = record_start(&fs, start(1_000, Rung::Fresh)).unwrap();
877        record_session(&fs, UID, &a, "sid-a", 1_001).unwrap();
878        let b = record_start(&fs, Start { identity_key: Some("k1".into()), ..start(2_000, Rung::Fresh) }).unwrap();
879        record_session(&fs, UID, &b, "sid-b", 2_001).unwrap();
880        // A spawn that died before reporting a session doesn't move the head.
881        record_start(&fs, start(3_000, Rung::Fresh)).unwrap();
882        let h = chain_head(&fs, UID).expect("a head");
883        assert_eq!(h.session_id, "sid-b");
884        assert_eq!(h.identity_key.as_deref(), Some("k1"));
885        assert_eq!(h.config_dir.as_deref(), Some("C:/cfg/a"));
886        assert_eq!(h.provider, "claude");
887    }
888
889    /// A record written before `identity_key` existed still reads, as `None`.
890    #[test]
891    fn older_records_without_an_identity_still_read() {
892        let old = serde_json::json!({
893            "event": "start", "segment_id": "s", "agent_uid": UID, "definition_id": null, "provider": "claude",
894            "config_dir": null, "provider_session_id": "sid", "cwd": "", "channel": "stable",
895            "agentmux_version": "0.57.5", "block_id": "b", "zone": null, "byte_start": null,
896            "started_at_ms": 1, "continuity_rung": "native", "predecessor_segment_id": null, "lease_epoch": 2,
897        });
898        match serde_json::from_value::<Event>(old).unwrap() {
899            Event::Start(s) => assert_eq!(s.identity_key, None),
900            other => panic!("expected a start event, got {other:?}"),
901        }
902    }
903
904    #[test]
905    fn a_segment_is_closed_exactly_once() {
906        let fs = FileStore::open_in_memory().unwrap();
907        let id = record_start(&fs, start(1, Rung::Fresh)).unwrap();
908        record_end(&fs, UID, &id, EndReason::Closed, None, 10).unwrap();
909        record_end(&fs, UID, &id, EndReason::Crashed, None, 20).unwrap();
910        let s = &segments(&fs, UID)[0];
911        assert_eq!((s.ended_at_ms, s.end_reason), (Some(10), Some(EndReason::Closed)));
912    }
913
914    #[test]
915    fn agents_have_separate_chains() {
916        let fs = FileStore::open_in_memory().unwrap();
917        record_start(&fs, start(1, Rung::Fresh)).unwrap();
918        let mut other = start(2, Rung::Fresh);
919        other.agent_uid = "uid-2".into();
920        let id = record_start(&fs, other).unwrap();
921        assert_eq!(segments(&fs, UID).len(), 1);
922        let theirs = segments(&fs, "uid-2");
923        assert_eq!(theirs[0].start.segment_id, id);
924        assert_eq!(theirs[0].start.predecessor_segment_id, None, "another agent's segment is not a predecessor");
925    }
926
927    #[test]
928    fn a_corrupt_line_is_skipped() {
929        let fs = FileStore::open_in_memory().unwrap();
930        let id = record_start(&fs, start(1, Rung::Fresh)).unwrap();
931        fs.append_data("agent-uid:uid-1:segments", SEGMENTS_FILE, b"{\"event\":\"start\",\"trunc\n").unwrap();
932        let next = record_start(&fs, start(2, Rung::Native)).unwrap();
933        let all = segments(&fs, UID);
934        assert_eq!(all.len(), 2);
935        assert_eq!(all[1].start.segment_id, next);
936        assert_eq!(all[1].start.predecessor_segment_id.as_deref(), Some(id.as_str()));
937    }
938
939    #[test]
940    fn an_unsafe_uid_is_refused() {
941        let fs = FileStore::open_in_memory().unwrap();
942        let mut bad = start(1, Rung::Fresh);
943        bad.agent_uid = "../x:y".into();
944        assert!(record_start(&fs, bad).is_err());
945        assert!(segments(&fs, "../x:y").is_empty());
946    }
947
948    #[test]
949    fn events_are_tagged_json_lines() {
950        let e = Event::End { segment_id: "s".into(), ended_at_ms: 5, end_reason: EndReason::Restarted, byte_end: None, provider_bytes_end: None };
951        let json = serde_json::to_string(&e).unwrap();
952        assert!(json.contains("\"event\":\"end\"") && json.contains("\"end_reason\":\"restarted\""), "{json}");
953    }
954
955    fn seg(id: &str, sid: Option<&str>) -> Segment {
956        let mut s = start(0, Rung::Fresh);
957        s.segment_id = id.into();
958        s.provider_session_id = sid.map(str::to_string);
959        Segment { start: s, ended_at_ms: None, end_reason: None, byte_end: None, provider_bytes_end: None }
960    }
961
962    #[test]
963    fn the_head_is_the_newest_earlier_segment_with_a_session() {
964        let chain = [seg("a", Some("sid-old")), seg("b", Some("sid-head")), seg("c", None), seg("now", Some("sid-attempted"))];
965        assert_eq!(head_session(&chain, Some("now")).as_deref(), Some("sid-head"));
966        assert_eq!(head_session(&chain, None).as_deref(), Some("sid-attempted"));
967        assert_eq!(head_session(&[], Some("now")), None);
968    }
969
970    /// The account-switch case: the head (the old account's session) was
971    /// just rejected, and the new account's config dir holds an older
972    /// session of the same agent. Recovering it would resume the wrong
973    /// conversation.
974    #[test]
975    fn recovery_only_continues_the_head_of_the_chain() {
976        assert!(!recovery_allowed("sid-old", Some("sid-head")));
977        assert!(recovery_allowed("sid-head", Some("sid-head")), "a stale pane id whose real session is the head");
978        assert!(recovery_allowed("sid-any", None), "no known head (pre-index agent): behave as before the index");
979    }
980
981    #[test]
982    fn rungs_and_reasons() {
983        assert_eq!(rung_for_spawn(true, false), Rung::Native);
984        assert_eq!(rung_for_spawn(true, true), Rung::Native, "a resume never carries a packet, but resume wins");
985        assert_eq!(rung_for_spawn(false, true), Rung::Virtualized);
986        assert_eq!(rung_for_spawn(false, false), Rung::Fresh);
987        assert_eq!(kill_reason(true, true), EndReason::Closed);
988        assert_eq!(kill_reason(false, true), EndReason::Restarted);
989        assert_eq!(kill_reason(false, false), EndReason::Stopped);
990        assert_eq!(exit_reason(0), EndReason::Exited);
991        assert_eq!(exit_reason(1), EndReason::Crashed);
992        assert_eq!(exit_reason(-1), EndReason::Crashed);
993    }
994}
995
996#[cfg(test)]
997mod damage_tests {
998    use super::*;
999    use crate::backend::transcript::damage::{self, test_support};
1000
1001    fn start_for(uid: &str) -> Start {
1002        Start {
1003            segment_id: String::new(),
1004            agent_uid: uid.into(),
1005            definition_id: None,
1006            provider: "claude".into(),
1007            config_dir: None,
1008            provider_session_id: None,
1009            cwd: "C:/work".into(),
1010            channel: "stable".into(),
1011            agentmux_version: "0.59.34".into(),
1012            block_id: "block-damage".into(),
1013            zone: None,
1014            byte_start: None,
1015            started_at_ms: 1,
1016            continuity_rung: Rung::Fresh,
1017            predecessor_segment_id: None,
1018            lease_epoch: None,
1019            identity_key: None,
1020            forked_from: None,
1021        }
1022    }
1023
1024    #[test]
1025    fn a_segment_log_found_corrupt_is_marked_and_not_written_or_read_again() {
1026        let uid = "uid-damage-seg-1";
1027        let zone = zone_for(uid).unwrap();
1028        let fs = FileStore::open_in_memory().unwrap();
1029        let _shared = test_support::register(&fs);
1030        record_start(&fs, start_for(uid)).unwrap();
1031        test_support::corrupt(&fs);
1032
1033        assert!(record_start(&fs, start_for(uid)).is_err());
1034        assert!(damage::is_damaged(&zone), "the failed write is the incident");
1035        assert_eq!(segments(&fs, uid), Vec::new(), "a damaged log has no chain to offer");
1036        let again = record_start(&fs, start_for(uid)).unwrap_err();
1037        assert!(again.contains("damaged"), "{again}");
1038    }
1039
1040    #[test]
1041    fn a_read_of_a_corrupt_log_marks_it_and_another_agents_log_is_untouched() {
1042        let (damaged, fine) = ("uid-damage-seg-2", "uid-damage-seg-3");
1043        let fs = FileStore::open_in_memory().unwrap();
1044        let _shared = test_support::register(&fs);
1045        record_start(&fs, start_for(damaged)).unwrap();
1046        test_support::corrupt(&fs);
1047        assert!(segments(&fs, damaged).is_empty());
1048        assert!(damage::is_damaged(&zone_for(damaged).unwrap()));
1049        assert!(!damage::is_damaged(&zone_for(fine).unwrap()), "only the zone that failed is marked");
1050    }
1051}