1use serde::{Deserialize, Serialize};
25
26use crate::backend::storage::filestore::{FileMeta, FileOpts, FileStore};
27
28pub(crate) const SEGMENTS_FILE: &str = "segments.jsonl";
29const TAIL_WINDOW_BYTES: i64 = 64 * 1024;
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum Rung {
37 Native,
39 Virtualized,
41 Fresh,
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
47#[serde(rename_all = "snake_case")]
48pub(crate) enum EndReason {
49 Exited,
51 Crashed,
53 Closed,
55 Restarted,
57 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 #[serde(default, skip_serializing_if = "Option::is_none")]
74 provider_bytes_end: Option<i64>,
75 },
76}
77
78#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
80pub struct Start {
81 pub segment_id: String,
82 pub agent_uid: String,
83 pub definition_id: Option<String>,
86 pub provider: String,
87 pub config_dir: Option<String>,
89 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 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 #[serde(default, skip_serializing_if = "Option::is_none")]
107 pub lease_epoch: Option<u64>,
108 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub identity_key: Option<String>,
114 #[serde(default, skip_serializing_if = "Option::is_none")]
118 pub forked_from: Option<String>,
119}
120
121#[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
131pub 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 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 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
156fn 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
175fn 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
207pub 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
239pub(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
255pub 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 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
290pub(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
301pub(crate) fn recovery_allowed(candidate: &str, head: Option<&str>) -> bool {
310 head.is_none_or(|h| h == candidate)
311}
312
313#[derive(Debug, Clone, PartialEq, Eq)]
316pub(crate) enum ResumeGate {
317 Allow,
320 Redirect { head: String },
322 Refuse { head: String },
325 Relocate { head: String, from_config_dir: String },
329 Fork { head: String },
334 ForkFrom { head: String, from_config_dir: String, from_cwd: String },
341}
342
343#[derive(Debug, Clone, Copy, Default)]
345pub(crate) struct GateInput<'a> {
346 pub candidate: &'a str,
348 pub head: Option<&'a Head>,
349 pub identity: Option<&'a str>,
351 pub poisoned: Option<&'a str>,
353 pub config_dir: &'a str,
355 pub cwd: &'a str,
356 pub fork_source: Option<&'a Head>,
359}
360
361#[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 pub provider_bytes_end: Option<i64>,
372}
373
374pub(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 if head.config_dir.as_deref().is_some_and(|dir| same_dir(dir, input.config_dir)) {
419 return refuse();
420 }
421 if is_candidate {
425 ResumeGate::Allow
426 } else {
427 refuse()
428 }
429}
430
431fn 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
449fn 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
469pub 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
490pub 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
506pub 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
522pub 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
534pub(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 #[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 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 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 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 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 #[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 #[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 #[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 #[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 #[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 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 #[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 #[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 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 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 #[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 #[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}