From 8f296c96ac4384763e2638fad8db31084602d72c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 6 Nov 2026 23:06:40 +0100 Subject: [PATCH] self_run resume: tests for warm_until, resumes, the keep dir and the carry path; Fake gains kept/keep --- crates/mind-body/src/self_run/decide/tests.rs | 62 ++++ crates/mind-body/src/self_run/tests.rs | 23 +- .../mind-body/src/self_run/tests/closure.rs | 2 +- crates/mind-body/src/self_run/tests/resume.rs | 292 ++++++++++++++++++ crates/mind-body/src/testkit.rs | 23 +- 5 files changed, 391 insertions(+), 11 deletions(-) create mode 100644 crates/mind-body/src/self_run/tests/resume.rs diff --git a/crates/mind-body/src/self_run/decide/tests.rs b/crates/mind-body/src/self_run/decide/tests.rs index a831deb..32d8fa1 100644 --- a/crates/mind-body/src/self_run/decide/tests.rs +++ b/crates/mind-body/src/self_run/decide/tests.rs @@ -510,3 +510,65 @@ fn a_flush_already_written_ends_the_session_by_itself_and_a_yield_does_not_cut_i let (_, action) = feed(state, Event::Yield, 3); assert_eq!(action, Action::None, "the flush's own answer closes stdin"); } + +// ---- the conversation worth keeping --------------------------------------------- + +/// Runs `events` from a state, then the child exits with `code` and its stream ends: the `warm_until` of the outcome the run finishes with. +fn warm_after(state: State, mut events: Vec<(Event, i64)>, code: Option) -> Option> { + events.extend([(Event::ChildExited(code), 9_000), (Event::StdoutEof, 9_000)]); + match run_from(state, events).1.pop() { + Some(Action::Finish(SelfRunOutcome::Ended { warm_until, .. })) => warm_until, + other => panic!("the run did not finish: {other:?}"), + } +} + +/// A cap that puts the rotation flush at second 100, before any idle lapse. +fn near_cap() -> State { + State::started(t(0), u64::try_from(ROTATE_MARGIN_S + 100).unwrap()) +} + +#[test] +fn a_clean_end_is_kept_until_its_last_request_plus_its_cache_lifetime_less_the_margin() { + // Two requests and a result at three different times: the base is the last request's. + let events = |result: Event| vec![(Event::Echo, 0), (req("a", 10), 10), (req("b", 20), 50), (result, 90)]; + assert_eq!(warm_after(working(), events(OK), Some(0)), Some(t(50 + 3600 - 60))); + assert_eq!(warm_after(working(), events(OK_SHORT), Some(0)), Some(t(50 + 300 - 60))); + // A repeated request id is not a new request and moves nothing. + let repeated = vec![(Event::Echo, 0), (req("a", 10), 10), (req("a", 10), 50), (OK, 90)]; + assert_eq!(warm_after(working(), repeated, Some(0)), Some(t(10 + 3600 - 60))); +} + +#[test] +fn the_rotation_flush_keeps_its_conversation_and_every_other_end_clears_it() { + let clean = vec![(Event::Echo, 0), (req("a", 10), 10), (OK, 20)]; + let with = |more: Vec<(Event, i64)>| [clean.clone(), more].concat(); + assert_eq!(warm_after(working(), clean.clone(), Some(0)), Some(t(10 + 3600 - 60))); + // The rotation: the flush is asked near the cap, answered, and the end is kept from that answer's request. + let rotation = vec![(Event::Tick, 100), (Event::Echo, 101), (req("b", 20), 101), (OK, 102)]; + assert_eq!(warm_after(near_cap(), with(rotation.clone()), Some(0)), Some(t(101 + 3600 - 60))); + // Each condition alone clears. + let idle = vec![(Event::Tick, 3560), (Event::Echo, 3561), (req("b", 20), 3561), (OK, 3562)]; + assert_eq!(warm_after(working(), with(idle), Some(0)), None, "an idle end is the clear"); + let ceiling = vec![(Event::Echo, 0), (req("a", CEILING_TOKENS), 10), (Event::Echo, 11), (OK, 20)]; + assert_eq!(warm_after(working(), ceiling, Some(0)), None, "a ceiling end would only flush again"); + let over_after_rotation = with(vec![(Event::Tick, 100), (Event::Echo, 101), (req("b", CEILING_TOKENS), 101), (OK, 102)]); + assert_eq!(warm_after(near_cap(), over_after_rotation, Some(0)), None, "the prefix alone, under a rotation flush"); + assert_eq!(warm_after(working(), with(vec![(delivered(Stop::Interrupt), 30)]), Some(0)), None, "a delivered signal"); + assert_eq!(warm_after(working(), with(vec![(Event::Signalled { how: Stop::Interrupt, delivered: false }, 30)]), Some(0)), Some(t(10 + 3600 - 60)), "a signal that never went out ended nothing"); + let blocked_but_ok = vec![(Event::Echo, 0), (req("a", 10), 10), (Event::Result { ok: true, blocked: true, ttl_1h: true }, 20), (OK, 30)]; + assert_eq!(warm_after(working(), blocked_but_ok, Some(0)), None, "blocked is sticky"); + assert_eq!(warm_after(working(), with(vec![(Event::Echo, 30), (FAILED, 40)]), Some(0)), None, "the last result failed"); + assert_eq!(warm_after(working(), with(vec![(Event::Echo, 30)]), Some(0)), None, "a turn was open"); + assert_eq!(warm_after(working(), clean.clone(), Some(1)), None, "a non-zero exit"); + assert_eq!(warm_after(working(), clean, None), None, "an exit by signal"); + assert_eq!(warm_after(working(), vec![(Event::Echo, 0), (OK, 20)], Some(0)), None, "no request, no cache"); +} + +#[test] +fn a_kept_conversation_resumes_until_its_warm_until_and_not_after_and_never_across_a_seed_change() { + let kept = |same_seed| Kept { session: uuid::Uuid::nil(), transcript: "/state/session/x.jsonl".into(), warm_until: t(100), same_seed }; + assert!(resumes(&kept(true), t(99))); + assert!(!resumes(&kept(true), t(100))); + assert!(!resumes(&kept(true), t(101))); + assert!(!resumes(&kept(false), t(0))); +} diff --git a/crates/mind-body/src/self_run/tests.rs b/crates/mind-body/src/self_run/tests.rs index 456cd29..79ed801 100644 --- a/crates/mind-body/src/self_run/tests.rs +++ b/crates/mind-body/src/self_run/tests.rs @@ -198,16 +198,22 @@ fn carry_scripted(seen: &Seen, steps: Vec, code: Option, dies_on: Opt carry_one(seen, steps, (code, dies_on, refuses, hangs)) } -fn carry_one(seen: &Seen, steps: Vec, (code, dies_on, refuses, hangs): (Option, Option, &[Stop], bool)) -> Ran { +fn carry_one(seen: &Seen, steps: Vec, how: (Option, Option, &[Stop], bool)) -> Ran { + carry_kept(seen, steps, how, None) +} + +/// The same, with `kept` the conversation the spawner reports as kept. +fn carry_kept(seen: &Seen, steps: Vec, (code, dies_on, refuses, hangs): (Option, Option, &[Stop], bool), kept: Option) -> Ran { let log = Rc::new(RefCell::new(Vec::new())); let clock = Rc::new(Fixed(Cell::new(at_start()))); let fake = Fake::with(Some(Scripted { steps: steps.into(), log: log.clone(), clock: clock.clone(), code, dies_on, refuses: refuses.to_vec(), hangs, exited: false, eof: false, asked: 0 }), false); + *fake.kept.borrow_mut() = kept; let lender = FakeLender::logging(log.clone(), Answer::Grant); let mut out = Vec::new(); let outcome = carry(seen, &*clock, &lender, &fake, TEST_CAP_S, &mut out); let all = log.borrow().clone(); // The child's own events; the lease's are in `all`, in order with them. - let events = all.iter().filter(|event| !matches!(event, Event::Lent | Event::Spawned | Event::Abandoned)).cloned().collect(); + let events = all.iter().filter(|event| !matches!(event, Event::Lent | Event::Spawned | Event::Abandoned | Event::Kept(_))).cloned().collect(); let spawns = fake.spawns.borrow().clone(); Ran { outcome, out: String::from_utf8(out).unwrap(), events, all, spawns, admits: seen.admits.get(), asked: lender.asked.borrow().clone() } } @@ -327,7 +333,7 @@ fn claude_args_is_exactly_the_fixed_list_for_a_session() { ] ); // Those belong to the run measure or to the unit's managed settings. - for forbidden in ["--resume", "--continue", "--fork-session", "--model", "--dangerously-skip-permissions", "--system-prompt", "--max-budget"] { + for forbidden in ["--continue", "--model", "--dangerously-skip-permissions", "--system-prompt", "--max-budget"] { assert!(!args.iter().any(|arg| arg.starts_with(forbidden) || arg.contains("dangerously")), "{forbidden}"); } // Print mode starts in Manual without a mode, and prompts none then denies. @@ -868,8 +874,8 @@ fn a_child_that_exited_is_never_signalled_however_long_its_stream_stays_open() { #[test] fn the_outcome_names_how_it_ended_and_the_exit_status_follows_the_childs_code() { let own = carry_with(&Seen::of(&with_run()), vec![Out(at("m1", 10)), Out(result_line())], Some(0), false); - assert_eq!(own.outcome.as_ref().unwrap(), &SelfRunOutcome::Ended { cause: Cause::Own, code: Some(0), requests: 1, prefix: 10 }); - assert_eq!(own.outcome.as_ref().unwrap().to_string(), "ended: own code 0 requests 1 prefix 10"); + assert_eq!(own.outcome.as_ref().unwrap(), &SelfRunOutcome::Ended { cause: Cause::Own, code: Some(0), requests: 1, prefix: 10, warm_until: Some(at_start() + ChronoDuration::seconds(TTL_1H_S - TTL_MARGIN_S)) }); + assert_eq!(own.outcome.as_ref().unwrap().to_string(), "ended: own code 0 requests 1 prefix 10 warm until 2026-10-09T14:14:00Z"); assert_eq!(own.outcome.unwrap().exit_status(), 0); let flushed = carry_with(&Seen::of(&with_run()), vec![Out(at("m1", CEILING_TOKENS)), Out(result_line())], Some(0), false); @@ -1104,7 +1110,7 @@ exit 0"); let mind = with_run(); let mut out = Vec::new(); let outcome = carry(&Seen::of(&mind), &SystemClock, &FakeLender::new(Answer::Grant), &Spawn(program), TEST_CAP_S, &mut out).unwrap(); - assert_eq!(outcome, SelfRunOutcome::Ended { cause: Cause::FlushRequested, code: Some(0), requests: 2, prefix: 300_000 }); + assert_eq!(outcome, SelfRunOutcome::Ended { cause: Cause::FlushRequested, code: Some(0), requests: 2, prefix: 300_000, warm_until: None }); let printed: String = String::from_utf8(out).unwrap().lines().filter(|line| !line.starts_with("decision ")).map(|line| format!("{line}\n")).collect(); assert_eq!(printed, "request 1 prefix 10 request 2 prefix 300000 @@ -1121,7 +1127,7 @@ result subtype=success is_error=false: The answer. let started = std::time::Instant::now(); let mut out = Vec::new(); let outcome = carry(&Seen::of(&with_run()), &SystemClock, &FakeLender::new(Answer::Grant), &Spawn(program), TEST_CAP_S, &mut out).unwrap(); - assert_eq!(outcome, SelfRunOutcome::Ended { cause: Cause::Own, code: Some(1), requests: 0, prefix: 0 }); + assert_eq!(outcome, SelfRunOutcome::Ended { cause: Cause::Own, code: Some(1), requests: 0, prefix: 0, warm_until: None }); assert_eq!(outcome.exit_status(), 1); assert!(!String::from_utf8_lossy(&out).contains("request "), "no request was heard"); assert!(started.elapsed() < StdDuration::from_secs(20), "it ended promptly"); @@ -1144,7 +1150,7 @@ result subtype=success is_error=false: The answer. let holder = std::fs::read_to_string(&pids).unwrap().trim().to_string(); let cause = if flushed { Cause::FlushRequested } else { Cause::Own }; let (requests, prefix) = if flushed { (1, CEILING_TOKENS) } else { (0, 0) }; - assert_eq!(outcome, SelfRunOutcome::Ended { cause, code: Some(0), requests, prefix }, "flushed: {flushed}"); + assert_eq!(outcome, SelfRunOutcome::Ended { cause, code: Some(0), requests, prefix, warm_until: None }, "flushed: {flushed}"); assert!(alive(&holder), "the actuator signals no one after the child is gone"); assert!(started.elapsed() < StdDuration::from_secs(20), "it ended on the child's exit: {:?}", started.elapsed()); Command::new("kill").arg(&holder).status().unwrap(); @@ -1193,6 +1199,7 @@ result subtype=success is_error=false: The answer. mod lease; mod closure; mod reply; +mod resume; // ---- the task in the start message --------------------------------------- diff --git a/crates/mind-body/src/self_run/tests/closure.rs b/crates/mind-body/src/self_run/tests/closure.rs index e7732a4..5fcbbc2 100644 --- a/crates/mind-body/src/self_run/tests/closure.rs +++ b/crates/mind-body/src/self_run/tests/closure.rs @@ -5,7 +5,7 @@ use eureka_pipeline::ResolutionOutcome; use super::*; /// The reason of the run's one closure; fails if it was closed other than once. -fn reason_of(mind: &TestMind, label: &str) -> String { +pub(super) fn reason_of(mind: &TestMind, label: &str) -> String { let id = format!("{INSTANCE}:resolution:run.{label}.n1"); let PipelineDocument::Resolution(closure) = mind.view(K::Resolution, &id).unwrap_or_else(|| panic!("{label} was not closed")).document else { panic!("not a resolution") }; assert!(mind.view(K::Resolution, &format!("{INSTANCE}:resolution:run.{label}.n2")).is_none(), "{label} was closed twice"); diff --git a/crates/mind-body/src/self_run/tests/resume.rs b/crates/mind-body/src/self_run/tests/resume.rs new file mode 100644 index 0000000..caa9df0 --- /dev/null +++ b/crates/mind-body/src/self_run/tests/resume.rs @@ -0,0 +1,292 @@ +//! A Mind's next Self process resumes the last one's conversation while its cache +//! is warm, and clears it once cold (rulings `eureka-body:ruling:session-rotate-and-resume` +//! and `eureka-body:ruling:live-session-floor-cache-evicts`). `decide` owns the +//! timing and is pinned in its own tests; here are the executions: the child's +//! arguments and first line, the one keep call per process, the files. + +use std::path::PathBuf; + +use super::closure::reason_of; +use super::*; + +const PREVIOUS: &str = "11111111-1111-4111-8111-111111111111"; + +fn previous() -> Uuid { + Uuid::parse_str(PREVIOUS).unwrap() +} + +fn kept_for(warm_for_s: i64, same_seed: bool) -> Kept { + Kept { session: previous(), transcript: PathBuf::from(format!("/state/session/{PREVIOUS}.jsonl")), warm_until: at_start() + ChronoDuration::seconds(warm_for_s), same_seed } +} + +fn session_a() -> Uuid { + Uuid::parse_str(SESSION_OF_RUN_A).unwrap() +} + +/// The events of `ran` after the child was started, in order, that are keeps. +fn keeps_after_spawn(ran: &Ran) -> Vec)>> { + let spawned = ran.all.iter().position(|event| *event == Event::Spawned).expect("a child was started"); + ran.all[spawned..] + .iter() + .filter_map(|event| match event { + Event::Kept(keep) => Some(*keep), + _ => None, + }) + .collect() +} + +fn answered() -> Vec { + vec![Out(at("m1", 10)), Out(echo()), Out(ok_result())] +} + +#[test] +fn claude_args_resumes_a_kept_transcript_by_its_path_forked_and_otherwise_is_the_fixed_list() { + let fresh = claude_args(session_a(), None); + let path = PathBuf::from(format!("/state/session/{PREVIOUS}.jsonl")); + let resumed = claude_args(session_a(), Some(&path)); + assert_eq!(resumed[..fresh.len()], fresh[..], "the fixed list is unchanged"); + assert_eq!(resumed[fresh.len()..], ["--resume".to_string(), path.to_string_lossy().into_owned(), "--fork-session".to_string()]); + assert!(!fresh.iter().any(|arg| arg == "--resume" || arg == "--fork-session")); + for forbidden in ["--continue", "--model", "--system-prompt", "--max-budget"] { + assert!(!resumed.iter().any(|arg| arg.starts_with(forbidden) || arg.contains("dangerously")), "{forbidden}"); + } +} + +#[test] +fn a_warm_kept_conversation_is_resumed_forked_and_told_it_continues_under_the_new_run() { + let mind = with_run(); + let ran = carry_kept(&Seen::of(&mind), answered(), (Some(0), None, &[], false), Some(kept_for(1800, true))); + ran.outcome.as_ref().unwrap(); + let path = PathBuf::from(format!("/state/session/{PREVIOUS}.jsonl")); + assert_eq!(ran.spawns, vec![claude_args(session_a(), Some(&path))]); + let first = &ran.written()[0]; + assert!(first.starts_with("Your session continues in a new process under a new run: your run is now `yggdrasil:run:selfrun-a`; the previous run is closed. Admit as faculty SelfFaculty, agent mind-self-run."), "{first}"); + assert!(first.contains("Plan usage: five_hour 42.3%"), "{first}"); + assert!(!first.contains("Use the eureka skill"), "the conversation holds the skill already: {first}"); + assert!(ran.out.contains(&format!("session resumed {PREVIOUS} warm until 2026-10-09T13:45:00Z")), "{}", ran.out); + assert!(reason_of(&mind, "selfrun-a").ends_with(&format!("; resumed {PREVIOUS}")), "{}", reason_of(&mind, "selfrun-a")); +} + +#[test] +fn a_resumed_start_line_carries_the_open_briefs_as_a_fresh_one_does() { + let first = |kept: Option| { + let mind = live_mind(); + persona_commit(&mind, vec![brief("p1", "Still open.")]); + carry_kept(&Seen::of(&mind), answered(), (Some(0), None, &[], false), kept).written().remove(0) + }; + let (resumed, fresh) = (first(Some(kept_for(1800, true))), first(None)); + let task = |line: &str| line[line.find("\n\nAlso open for you").expect("the briefs section")..].to_string(); + assert_eq!(task(&resumed), task(&fresh)); + assert!(task(&resumed).contains("Still open.")); +} + +#[test] +fn a_cold_or_seed_changed_or_absent_kept_conversation_is_cleared_before_the_child_starts_and_the_start_is_fresh() { + let cases: [(&str, Option); 4] = [ + ("none kept", None), + ("cold", Some(kept_for(-1, true))), + ("cold", Some(kept_for(0, true))), + ("seed changed", Some(kept_for(1800, false))), + ]; + for (why, kept) in cases { + let mind = with_run(); + let ran = carry_kept(&Seen::of(&mind), answered(), (Some(0), None, &[], false), kept); + ran.outcome.as_ref().unwrap(); + let first_keep = ran.all.iter().position(|event| matches!(event, Event::Kept(_))).unwrap(); + let spawned = ran.all.iter().position(|event| *event == Event::Spawned).unwrap(); + assert_eq!(ran.all[first_keep], Event::Kept(None), "{why}"); + assert!(first_keep < spawned, "the clear precedes the child: {why}"); + assert_eq!(ran.spawns, vec![claude_args(session_a(), None)], "{why}"); + assert!(ran.written()[0].starts_with("Use the eureka skill."), "{why}"); + assert!(ran.out.contains(&format!("session fresh: {why}")), "{why}: {}", ran.out); + assert!(reason_of(&mind, "selfrun-a").ends_with("; fresh"), "{why}"); + } +} + +#[test] +fn after_the_child_ends_a_clean_end_is_kept_under_this_runs_session_and_any_other_end_clears() { + // A clean end: one keep, naming this run's session and the outcome's warm_until. + let mind = with_run(); + let ran = carry_with(&Seen::of(&mind), answered(), Some(0), false); + let SelfRunOutcome::Ended { warm_until: Some(until), .. } = ran.outcome.as_ref().unwrap() else { panic!("not kept: {:?}", ran.outcome) }; + assert_eq!(keeps_after_spawn(&ran), vec![Some((session_a(), *until))]); + assert!(ran.out.contains("session kept until"), "{}", ran.out); + + // Ends that are not clean: one clearing keep each. + let ceiling = carry_with(&Seen::of(&with_run()), vec![Out(at("m1", CEILING_TOKENS)), Out(echo()), Out(ok_result())], Some(0), false); + let failed = carry_with(&Seen::of(&with_run()), answered(), Some(1), false); + let unanswered = carry_with(&Seen::of(&with_run()), vec![Out(at("m1", 10))], Some(0), false); + for (name, ran) in [("ceiling", ceiling), ("non-zero exit", failed), ("no result", unanswered)] { + assert_eq!(keeps_after_spawn(&ran), vec![None], "{name}"); + assert!(ran.out.contains("session cleared"), "{name}: {}", ran.out); + } +} + +#[test] +fn a_drive_that_fails_clears_the_conversation() { + struct Refuses; + impl Write for Refuses { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + if String::from_utf8_lossy(bytes).contains("result subtype") { + return Err(std::io::Error::other("closed")); + } + Ok(bytes.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let mind = with_run(); + let log = Rc::new(RefCell::new(Vec::new())); + let clock = Rc::new(Fixed(Cell::new(at_start()))); + let steps = answered(); + let fake = Fake::with(Some(Scripted { steps: steps.into(), log: log.clone(), clock: clock.clone(), code: Some(0), dies_on: None, refuses: vec![], hangs: false, exited: false, eof: false, asked: 0 }), false); + *fake.kept.borrow_mut() = Some(kept_for(1800, true)); + let ran = carry(&Seen::of(&mind), &*clock, &FakeLender::logging(log.clone(), Answer::Grant), &fake, TEST_CAP_S, &mut Refuses); + assert!(ran.is_err()); + let keeps: Vec<_> = log.borrow().iter().filter(|event| matches!(event, Event::Kept(_))).cloned().collect(); + assert_eq!(keeps, vec![Event::Kept(None)], "a resumed start keeps nothing, and the failed drive clears"); +} + +// ---- the files ----------------------------------------------------------------- + +fn write(path: &Path, text: &str) { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); +} + +fn names(dir: &Path) -> Vec { + let mut names: Vec = std::fs::read_dir(dir).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + names +} + +#[test] +fn the_configs_end_moves_the_main_transcripts_out_and_nothing_else_of_it() { + let scratch = tempfile::tempdir().unwrap(); + let state = tempfile::tempdir().unwrap(); + let keep = state.path().join("session"); + let config = FreshConfig::create(scratch.path(), None, Some(keep.clone())).unwrap(); + let dir = scratch.path().join(CONFIG_DIR_NAME); + write(&dir.join("projects/x/aaa.jsonl"), "main"); + write(&dir.join("projects/y/bbb.jsonl"), "other project"); + write(&dir.join("projects/x/memory/m.md"), "memory"); + write(&dir.join("projects/x/memory/n.jsonl"), "memory transcript"); + write(&dir.join("projects/x/aaa/sub.jsonl"), "session subdirectory"); + write(&dir.join("projects/x/deep/a/c.jsonl"), "too deep"); + write(&dir.join("projects/loose.jsonl"), "no project"); + write(&dir.join("projects/x/notes.txt"), "not a transcript"); + write(&dir.join("settings.json"), "{}"); + drop(config); + assert_eq!(names(&keep), ["aaa.jsonl", "bbb.jsonl"]); + assert_eq!(std::fs::read_to_string(keep.join("aaa.jsonl")).unwrap(), "main"); + assert!(!dir.exists(), "the config still goes"); + #[cfg(unix)] + assert_eq!(std::os::unix::fs::PermissionsExt::mode(&std::fs::metadata(&keep).unwrap().permissions()) & 0o777, 0o700); + + // Where nothing is kept, nothing is made. + let config = FreshConfig::create(scratch.path(), None, None).unwrap(); + write(&scratch.path().join(CONFIG_DIR_NAME).join("projects/x/ccc.jsonl"), "x"); + drop(config); + assert_eq!(names(&keep), ["aaa.jsonl", "bbb.jsonl"]); +} + +fn spawner_over(state: &Path, scratch: &Path, seed: Option<&Path>) -> ClaudeSpawner { + let mut environment = vec![(SCRATCH_VARIABLE.into(), scratch.into()), (STATE_DIRECTORY_VARIABLE.into(), state.into())]; + if let Some(seed) = seed { + environment.push((SEED_VARIABLE.into(), seed.into())); + } + ClaudeSpawner::new(environment).unwrap() +} + +fn transcript(state: &Path, session: Uuid) -> PathBuf { + let path = state.join("session").join(format!("{session}.jsonl")); + write(&path, "{}"); + path +} + +#[test] +fn keeping_one_conversation_removes_the_one_before_it_and_clearing_leaves_the_dir_empty() { + let state = tempfile::tempdir().unwrap(); + let spawner = spawner_over(state.path(), state.path(), None); + let (older, newer) = (previous(), session_a()); + let until = at_start() + ChronoDuration::seconds(900); + transcript(state.path(), older); + let newer_path = transcript(state.path(), newer); + write(&state.path().join("session/stray.jsonl.tmp"), "half"); + + spawner.keep(Some((newer, until))).unwrap(); + assert_eq!(names(&state.path().join("session")), ["kept.json", &format!("{newer}.jsonl")], "at most one transcript, and no stray"); + assert_eq!(spawner.kept(), Some(Kept { session: newer, transcript: newer_path, warm_until: until, same_seed: true })); + + spawner.keep(None).unwrap(); + assert!(names(&state.path().join("session")).is_empty()); + assert_eq!(spawner.kept(), None); + + // A conversation whose transcript did not come out is a fresh start, not a record naming nothing. + spawner.keep(Some((older, until))).unwrap(); + assert!(names(&state.path().join("session")).is_empty()); +} + +#[test] +fn a_record_that_is_missing_unreadable_or_names_a_missing_transcript_keeps_nothing() { + let state = tempfile::tempdir().unwrap(); + let spawner = spawner_over(state.path(), state.path(), None); + let dir = state.path().join("session"); + assert_eq!(spawner.kept(), None, "no directory"); + transcript(state.path(), previous()); + assert_eq!(spawner.kept(), None, "a transcript with no record"); + write(&dir.join("kept.json"), "not json"); + assert_eq!(spawner.kept(), None, "unparseable"); + write(&dir.join("kept.json"), &format!(r#"{{"session":"{PREVIOUS}","warm_until":"yesterday","seed":""}}"#)); + assert_eq!(spawner.kept(), None, "an unreadable instant"); + write(&dir.join("kept.json"), &format!(r#"{{"session":"{}","warm_until":"2026-10-09T13:45:00Z","seed":""}}"#, session_a())); + assert_eq!(spawner.kept(), None, "names a transcript that is not there"); + write(&dir.join("kept.json"), &format!(r#"{{"session":"{PREVIOUS}","warm_until":"2026-10-09T13:45:00Z","seed":""}}"#)); + assert!(spawner.kept().is_some_and(|kept| kept.same_seed)); +} + +#[test] +fn without_a_state_directory_nothing_is_kept_and_nothing_is_made() { + let scratch = tempfile::tempdir().unwrap(); + let spawner = ClaudeSpawner::new([(SCRATCH_VARIABLE.into(), scratch.path().into())]).unwrap(); + spawner.keep(Some((previous(), at_start()))).unwrap(); + spawner.keep(None).unwrap(); + assert_eq!(spawner.kept(), None); + assert!(names(scratch.path()).is_empty()); +} + +#[test] +fn a_changed_seed_file_or_link_target_changes_the_digest_and_an_identical_copy_does_not() { + #[cfg(unix)] + { + let seed = tempfile::tempdir().unwrap(); + write(&seed.path().join("skills/a.md"), "alpha"); + write(&seed.path().join("settings.json"), "{}"); + std::os::unix::fs::symlink("skills", seed.path().join("link")).unwrap(); + let digest = seed_digest(seed.path()).unwrap(); + assert_eq!(digest.len(), 64); + let copy = tempfile::tempdir().unwrap(); + copy_tree(seed.path(), copy.path()).unwrap(); + assert_eq!(seed_digest(copy.path()).unwrap(), digest, "an identical copy"); + write(©.path().join("skills/a.md"), "alphb"); + assert_ne!(seed_digest(copy.path()).unwrap(), digest, "one byte of a file"); + write(©.path().join("skills/a.md"), "alpha"); + std::fs::remove_file(copy.path().join("link")).unwrap(); + std::os::unix::fs::symlink("skills/../skills", copy.path().join("link")).unwrap(); + assert_ne!(seed_digest(copy.path()).unwrap(), digest, "a link's target"); + std::fs::rename(copy.path().join("settings.json"), copy.path().join("setting.json")).unwrap(); + std::fs::remove_file(copy.path().join("link")).unwrap(); + std::os::unix::fs::symlink("skills", copy.path().join("link")).unwrap(); + assert_ne!(seed_digest(copy.path()).unwrap(), digest, "a file's name"); + + // The spawner reports a kept conversation made under another seed as not the same seed. + let state = tempfile::tempdir().unwrap(); + transcript(state.path(), previous()); + let until = at_start() + ChronoDuration::seconds(900); + spawner_over(state.path(), state.path(), Some(seed.path())).keep(Some((previous(), until))).unwrap(); + assert!(spawner_over(state.path(), state.path(), Some(seed.path())).kept().unwrap().same_seed); + assert!(!spawner_over(state.path(), state.path(), Some(copy.path())).kept().unwrap().same_seed); + assert!(!spawner_over(state.path(), state.path(), None).kept().unwrap().same_seed); + } +} diff --git a/crates/mind-body/src/testkit.rs b/crates/mind-body/src/testkit.rs index 24f6c8f..433cca7 100644 --- a/crates/mind-body/src/testkit.rs +++ b/crates/mind-body/src/testkit.rs @@ -26,7 +26,8 @@ use tempfile::TempDir; use crate::launch::{Clock, Launcher}; use crate::lease_client::{Lease, LeaseRefusalKind, LeaseRefused, LeaseRequest, Lender, Lent, TokenFd, token_holding}; use crate::queue::MindPort; -use crate::self_run::{Child, Read, Spawner, Stop}; +use crate::self_run::{Child, Kept, Read, Spawner, Stop}; +use uuid::Uuid; pub(crate) const INSTANCE: &str = "yggdrasil"; pub(crate) const CAMPAIGN: &str = "eureka-body"; @@ -525,6 +526,8 @@ pub(crate) enum Event { Lent, /// A child was started. Spawned, + /// The spawner was told to keep this conversation until the instant, or to clear it. + Kept(Option<(Uuid, DateTime)>), /// The lease was dropped, which ends it: nothing is settled. Abandoned, } @@ -631,15 +634,31 @@ pub(crate) struct Fake { pub(crate) child: RefCell>, pub(crate) spawns: RefCell>>, pub(crate) refuse: bool, + /// The conversation the spawner reports as kept; a test sets it. + pub(crate) kept: RefCell>, + /// Where `keep` logs, in order with the child's own events: the first child's log. + log: Option>>>, } impl Fake { pub(crate) fn with(child: Option, refuse: bool) -> Self { - Self { child: RefCell::new(child), spawns: RefCell::new(Vec::new()), refuse } + let log = child.as_ref().map(|child| child.log.clone()); + Self { child: RefCell::new(child), spawns: RefCell::new(Vec::new()), refuse, kept: RefCell::new(None), log } } } impl Spawner for Fake { + fn kept(&self) -> Option { + self.kept.borrow().clone() + } + + fn keep(&self, keep: Option<(Uuid, DateTime)>) -> Result<()> { + if let Some(log) = &self.log { + log.borrow_mut().push(Event::Kept(keep)); + } + Ok(()) + } + fn spawn(&self, args: &[String], _token: &TokenFd) -> Result> { self.spawns.borrow_mut().push(args.to_vec()); if self.refuse {