diff --git a/crates/mind-body/src/bin/mind-self-run.rs b/crates/mind-body/src/bin/mind-self-run.rs index 52322cf..ebeec8c 100644 --- a/crates/mind-body/src/bin/mind-self-run.rs +++ b/crates/mind-body/src/bin/mind-self-run.rs @@ -10,6 +10,9 @@ //! `MIND_SELF_RUN_CAP_S` is the unit's `RuntimeMaxSec` in seconds, the one length of a run. //! `RUNTIME_DIRECTORY` (the unit's `RuntimeDirectory=`) holds each child's fresh //! configuration; `MIND_SELF_CONFIG_SEED` optionally names a root-owned directory copied into it. +//! `STATE_DIRECTORY` (the unit's `StateDirectory=`) keeps her last clean +//! conversation in its second directory, outside her working directory (the first), for the next +//! process; with only one directory every start is fresh. //! The connector's lease socket is `CLAUDE_LEASE_SOCKET`: the token itself is //! never in this process's environment, only the descriptor the lease grants. @@ -21,7 +24,7 @@ use mind_body::cli::instance_and_endpoint; use mind_body::launch::SystemClock; use mind_body::lease_client::{LEASE_SOCKET_VARIABLE, SocketLender}; use mind_body::queue::HuginnMind; -use mind_body::self_run::{ClaudeSpawner, RUN_CAP_VARIABLE, carry}; +use mind_body::self_run::{ClaudeSpawner, RUN_CAP_VARIABLE, STATE_DIRECTORY_VARIABLE, carry}; /// How long one call to the mind may take. const TIMEOUT: Duration = Duration::from_secs(15); @@ -40,6 +43,9 @@ fn run() -> Result { .and_then(|seconds| seconds.parse().ok()) .filter(|seconds| *seconds > 0) .ok_or_else(|| anyhow!("{RUN_CAP_VARIABLE} is not set to the unit's RuntimeMaxSec in seconds"))?; + if std::env::var_os(STATE_DIRECTORY_VARIABLE).is_none_or(|directories| !directories.to_string_lossy().contains(':')) { + println!("{STATE_DIRECTORY_VARIABLE} names no second directory: no conversation is kept and every start is fresh"); + } let mind = HuginnMind::new(HuginnClient::new(address, instance, TIMEOUT)); let outcome = carry(&mind, &SystemClock, &SocketLender::new(socket), &ClaudeSpawner::new(std::env::vars_os())?, run_cap_s, &mut std::io::stdout())?; println!("{outcome}"); diff --git a/crates/mind-body/src/self_run.rs b/crates/mind-body/src/self_run.rs index 52f017e..f33628a 100644 --- a/crates/mind-body/src/self_run.rs +++ b/crates/mind-body/src/self_run.rs @@ -26,8 +26,15 @@ //! answers; the actuator closes none, and a brief she left open is told to her //! next session. Compaction is off in //! the CLI (`DISABLE_COMPACT=1`): the organ's own ceiling, flush, end and rehydrate -//! is the only path. The session ends where its cache would be evicted, near the -//! unit's cap, at the context ceiling, or after the flush each of those asks. +//! is the only path. The session ends where its cache would be evicted (and is +//! then cleared), near the unit's cap, at the context ceiling, or after the flush +//! each of those asks. A clean end inside the cache's life is kept +//! (`decide::warm_until`), and the next process resumes it with +//! `--resume --fork-session` while the cache is still warm and the +//! seed is unchanged (`decide::resumes`; rulings +//! `eureka-body:ruling:session-rotate-and-resume` and +//! `eureka-body:ruling:live-session-floor-cache-evicts`). The kept transcript is a +//! cache of the conversation, never memory: her mind and replies stay the truth. //! //! Every timing decision is one pure function, `decide` (the `decide` module, //! ruling `eureka-body:ruling:self-run-decider`). `carry` is the loop that turns @@ -65,7 +72,7 @@ use std::sync::mpsc::{Receiver, RecvTimeoutError, channel}; use std::time::Duration as StdDuration; use anyhow::{Context, Result, anyhow, bail}; -use chrono::{DateTime, Utc}; +use chrono::{DateTime, SecondsFormat, Utc}; use cultnet_rs::Selection; use eureka_pipeline::{PipelineDocument, PipelineKind, PipelineRef, PipelineReply, ResolutionOutcome, RunTurn, Slug}; use huginn_mind::{PipelineAdmissionOutcome, PipelinePageItems}; @@ -159,6 +166,16 @@ pub fn start_message(instance: &Slug, run: &PipelineRef, plan_quota: &[PlanQuota ) } +/// What a resumed process is told instead of the start message: the conversation +/// is hers already (the skill is loaded), so only the new run and its plan are new. +pub fn continue_message(run: &PipelineRef, plan_quota: &[PlanQuota], now_ms: u64) -> String { + format!( + "Your session continues in a new process under a new run: your run is now `{}`; the previous run is closed. Admit as faculty SelfFaculty, agent {AGENT}. What you say when you end a turn still reaches your Persona as a reply, and your Persona's answers come as briefs.\n\n{}", + run.id.0, + render_plan(plan_quota, now_ms) + ) +} + /// The task section of the start message: one section per claim, in claim /// order. A claimed follow-up gives its id, campaign, repo and `item` verbatim, /// because the brief lives in the claim and a run that cannot reach its mind @@ -203,7 +220,7 @@ pub const FLUSH_MESSAGE: &str = "The context ceiling is reached. Admit to the mi fn flush_text(why: Why) -> String { let cause = match why { Why::Ceiling => "", - Why::Rotation => " (This session ends soon: the unit's time is nearly up.)", + Why::Rotation => " (This process ends soon: the unit's time is nearly up. If your next brief comes within the hour, the next process continues this conversation.)", Why::Idle => " (This session ends because nothing is waiting and its cache would lapse.)", }; format!("{FLUSH_MESSAGE}{cause} Resolve each brief you answered (Recorded, your answer as rationale); a brief you are still working stays open and the next session continues it.") @@ -214,8 +231,13 @@ pub fn session_id(run: &PipelineRef) -> Uuid { Uuid::new_v5(&SESSION_NAMESPACE, run.id.0.as_bytes()) } -/// The argument list of the child, and nothing else: no resume, continue or -/// fork, no model, no settings and no hooks belong to this actuator. It asks the +/// The argument list of the child, and nothing else: no continue flag, no model, +/// no settings and no hooks belong to this actuator. With a kept conversation it +/// appends `--resume --fork-session`: the fork is why the new +/// run's own `--session-id` is accepted beside a resume (the CLI refuses the two +/// without it, probe P2b; ruling `eureka-body:ruling:claude-code-handle-reseeds`), +/// and the path, not the CLI's cwd-slug lookup, is what finds the transcript +/// (probe P2d). It asks the /// CLI to echo each stdin line it takes into a request (`--replay-user-messages`), /// which is how delivery is counted. It fixes the permission mode: print mode starts in Manual when nothing on the command /// line sets a mode (the managed `defaultMode` was not applied in print mode, @@ -227,11 +249,11 @@ pub fn session_id(run: &PipelineRef) -> Uuid { /// user's settings load (the fresh configuration directory /// the seed fills); the working directory's project and local settings, which a /// run could have written, do not. -pub fn claude_args(session: Uuid) -> Vec { +pub fn claude_args(session: Uuid, resume: Option<&Path>) -> Vec { // `--disallowedTools` (probe, claude 2.1.312): the init line's tools lose these two. A turn the CLI begins on its own must be a // notification turn the actuator tracks (a task's), so no wake of the Self's own is scheduled in the CLI: her heartbeat owns her wakes. const DENIED_TOOLS: &str = "ScheduleWakeup,CronCreate"; - [ + let mut args: Vec = [ "-p", "--input-format", "stream-json", @@ -253,7 +275,11 @@ pub fn claude_args(session: Uuid) -> Vec { DENIED_TOOLS, ] .map(String::from) - .to_vec() + .to_vec(); + if let Some(transcript) = resume { + args.extend(["--resume".to_string(), transcript.to_string_lossy().into_owned(), "--fork-session".to_string()]); + } + args } /// What a user line starts with when the CLI replays a task notification to the model. @@ -420,9 +446,33 @@ impl Stop { } } +/// The organ's one kept conversation: the transcript of the last clean process, +/// the instant its cache runs out, and whether the seed is still the one it was +/// made under. Whether it is resumed is `decide::resumes`, nothing else. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Kept { + /// The session id the kept transcript was written under. + pub session: Uuid, + pub transcript: PathBuf, + pub warm_until: DateTime, + /// When the record was written; `warm_until` may not lie more than the longest cache lifetime past it. + pub written_at: DateTime, + pub same_seed: bool, +} + pub trait Spawner { /// Starts the child with `token` as its credential descriptor. fn spawn(&self, args: &[String], token: &TokenFd) -> Result>; + + /// The organ's one kept conversation, if any. A spawner that keeps nothing says none. + fn kept(&self) -> Option { + None + } + + /// Keeps the conversation this process ended under `session` until the instant, replacing any other; none clears it. + fn keep(&self, _keep: Option<(Uuid, DateTime)>) -> Result<()> { + Ok(()) + } } /// Why a run ended. @@ -445,7 +495,8 @@ pub enum SelfRunOutcome { NoRun, /// The connector would not lend: the run is closed Recorded and nothing was started. LeaseRefused { kind: LeaseRefusalKind }, - Ended { cause: Cause, code: Option, requests: u64, prefix: u64 }, + /// `warm_until`: until when the conversation is worth resuming (`decide::warm_until`), none when it is not. + Ended { cause: Cause, code: Option, requests: u64, prefix: u64, warm_until: Option> }, } impl SelfRunOutcome { @@ -466,7 +517,7 @@ impl fmt::Display for SelfRunOutcome { match self { Self::NoRun => write!(f, "no run: she has no single open Self run"), Self::LeaseRefused { kind } => write!(f, "no run: the connector refused the lease ({kind:?})"), - Self::Ended { cause, code, requests, prefix } => { + Self::Ended { cause, code, requests, prefix, warm_until } => { let cause = match cause { Cause::Own => "own", Cause::FlushRequested => "flush-requested", @@ -476,8 +527,12 @@ impl fmt::Display for SelfRunOutcome { Cause::Unstoppable => "unstoppable", }; match code { - Some(code) => write!(f, "ended: {cause} code {code} requests {requests} prefix {prefix}"), - None => write!(f, "ended: {cause} signal requests {requests} prefix {prefix}"), + Some(code) => write!(f, "ended: {cause} code {code} requests {requests} prefix {prefix}")?, + None => write!(f, "ended: {cause} signal requests {requests} prefix {prefix}")?, + } + match warm_until { + Some(until) => write!(f, " warm until {}", until.to_rfc3339_opts(SecondsFormat::Secs, true)), + None => Ok(()), } } } @@ -503,6 +558,8 @@ fn her_run(mind: &dyn MindPort) -> Result) struct Heard { /// The last result heard, ok or not: its head line. concluded: Option, + /// The session this process resumed; none when it started fresh. Set at the start, read by the closure's reason. + resumed: Option, } impl Heard { @@ -551,6 +608,10 @@ fn close_if_open(mind: &dyn MindPort, clock: &dyn Clock, run: &PipelineRef, ran: Some(head) => format!("{how}; {head}"), None => format!("{how}; claude gave no result"), }; + let reason = match heard.resumed { + Some(previous) => format!("{reason}; resumed {previous}"), + None => format!("{reason}; fresh"), + }; admit_closure(mind, clock, run, ResolutionOutcome::Recorded { reason: reason.as_str().into() }, CARRIER_CLOSED) } @@ -639,10 +700,45 @@ fn lend_and_drive(mind: &dyn MindPort, clock: &dyn Clock, lender: &dyn Lender, s } Lent::Refused(refused) => return close_refused(mind, clock, run, refused.kind), }; - let child = spawner.spawn(&claude_args(session_id(run)), lease.token())?; - let mut inbox = SelfInbox::new(mind, (run, claims), task, (lease.plan_quota(), started_ms), (told, conversation), heard); + // The one start decision: a kept conversation is resumed iff `decide::resumes`; any other is cleared before the child starts. + let kept = spawner.kept(); + let mut resume = kept.clone().filter(|kept| decide::resumes(kept, clock.now())); + if let Some(warm) = &resume { + // A resumed start consumes the record before the child exists: the same conversation, kept as already cold (its transcript stays for `--resume`), + // so a process that never reaches the end keep (a signal, a panic) cannot let the next resume from before the run it was killed in. + if spawner.keep(Some((warm.session, clock.now()))).is_err() { + resume = None; + } + } + if resume.is_none() { + let why = match &kept { + None => "none kept", + Some(kept) if !kept.same_seed => "seed changed", + Some(_) => "cold", + }; + if spawner.keep(None).is_err() { + writeln!(out, "session cache could not be cleared")?; + } + writeln!(out, "session fresh: {why}")?; + } + if let Some(kept) = &resume { + heard.resumed = Some(kept.session); + writeln!(out, "session resumed {} warm until {}", kept.session, kept.warm_until.to_rfc3339_opts(SecondsFormat::Secs, true))?; + } + let child = spawner.spawn(&claude_args(session_id(run), resume.as_ref().map(|kept| kept.transcript.as_path())), lease.token())?; + let mut inbox = SelfInbox::new(mind, (run, claims), task, (lease.plan_quota(), started_ms), (told, conversation), heard, resume.is_some()); let ran = drive(clock, child, &mut inbox, run_cap_s, out); inbox.admit_unadmitted(); + // The one end decision: a clean end inside the cache's life is kept under this run's session, any other end (an Err included) clears. + let keep = match &ran { + Ok(SelfRunOutcome::Ended { warm_until: Some(until), .. }) => Some((session_id(run), *until)), + _ => None, + }; + let _ = match (spawner.keep(keep), keep) { + (Ok(()), Some((_, until))) => writeln!(out, "session kept until {}", until.to_rfc3339_opts(SecondsFormat::Secs, true)), + (Ok(()), None) => writeln!(out, "session cleared"), + (Err(_), _) => writeln!(out, "session cache could not be updated"), + }; ran } @@ -681,9 +777,11 @@ struct SelfInbox<'a> { } impl<'a> SelfInbox<'a> { - /// The start line carries the claimed follow-ups and every brief already open (`told`), all of `serving`'s conversation. - fn new(mind: &'a dyn MindPort, (run, claims): (&PipelineRef, &[PipelineRef]), task: &str, (plan_quota, now_ms): (&[PlanQuota], u64), (told, serving): (&'a mut Vec, Conversation), heard: &'a mut Heard) -> Self { - let start = format!("{}{task}", start_message(mind.instance(), run, plan_quota, now_ms)); + /// The start line carries the claimed follow-ups and every brief already open (`told`), all of `serving`'s conversation. A resumed conversation holds the skill already. + fn new(mind: &'a dyn MindPort, (run, claims): (&PipelineRef, &[PipelineRef]), task: &str, (plan_quota, now_ms): (&[PlanQuota], u64), (told, serving): (&'a mut Vec, Conversation), heard: &'a mut Heard, resumed: bool) -> Self { + // A resumed conversation holds the skill already: it is told only that it continues under this run, then its task. + let opening = if resumed { continue_message(run, plan_quota, now_ms) } else { start_message(mind.instance(), run, plan_quota, now_ms) }; + let start = format!("{opening}{task}"); let mut carried: Vec = claims.iter().filter(|claim| claim.kind == PipelineKind::FollowUp).map(|claim| claim.id.0.clone()).collect(); for brief in told.iter() { if !carried.contains(&brief.id) { @@ -829,7 +927,7 @@ fn describe_result(event: &serde_json::Map, limit: usize) -> Stri } /// What `claude` concluded, written to the unit's stdout so it reaches the -/// journal before the transcript goes with the runtime directory. +/// journal: the transcript is a cache, and the result's words are kept here. fn write_result(line: &str, out: &mut dyn Write) -> std::io::Result<()> { let Ok(Value::Object(event)) = serde_json::from_str::(line) else { return Ok(()) }; if event.get("type").and_then(Value::as_str) != Some("result") { @@ -849,12 +947,30 @@ pub struct ClaudeSpawner { seed: Option, /// Her sandbox: with it the child runs under bubblewrap (`sandbox_args`), the Persona's; the Self passes none. sandbox: Option, + /// Where her one kept conversation lives (the second of the unit's `STATE_DIRECTORY` entries, outside her working directory, the first); none keeps nothing, and every start is fresh. + keep: Option, + /// The digest of the seed tree this process copies from (empty without a seed); none when the seed cannot be read, which no kept conversation matches. + seed_digest: Option, } impl ClaudeSpawner { - /// From the unit's environment: it must name [`SCRATCH_VARIABLE`], and may name [`SEED_VARIABLE`]. + /// From the unit's environment: it must name [`SCRATCH_VARIABLE`], and may name [`SEED_VARIABLE`] and + /// [`STATE_DIRECTORY_VARIABLE`]. With the last, the spawner keeps her last clean conversation for the next process; + /// without it every start is fresh, and the journal says so. pub fn new(unit_environment: impl IntoIterator) -> Result { - Self::in_sandbox(unit_environment, SEED_VARIABLE, None) + let unit_environment: Vec<(OsString, OsString)> = unit_environment.into_iter().collect(); + // systemd lists several state directories colon-separated: the first is her working directory, the second the kept conversation's own, outside it. + let keep = unit_environment + .iter() + .find(|(name, _)| name == STATE_DIRECTORY_VARIABLE) + .and_then(|(_, value)| value.to_string_lossy().split(':').nth(1).filter(|second| !second.is_empty()).map(PathBuf::from)); + let mut spawner = Self::in_sandbox(unit_environment, SEED_VARIABLE, None)?; + spawner.seed_digest = match &spawner.seed { + Some(seed) => seed_digest(seed).ok(), + None => Some(String::new()), + }; + spawner.keep = keep; + Ok(spawner) } /// The same, with the seed named by `seed_variable` and, if `sandbox` is given, the child run under bubblewrap with that directory as its writable home. @@ -864,13 +980,105 @@ impl ClaudeSpawner { // systemd lists several runtime directories colon-separated; the unit names one. let scratch = named(SCRATCH_VARIABLE).filter(|path| !path.as_os_str().is_empty()).ok_or_else(|| anyhow!("{SCRATCH_VARIABLE} is not set: the unit needs RuntimeDirectory="))?; let seed = named(seed_variable).filter(|path| !path.as_os_str().is_empty()); - Ok(Self { unit_environment, scratch, seed, sandbox }) + Ok(Self { unit_environment, scratch, seed, sandbox, keep: None, seed_digest: None }) } } +/// The unit's `StateDirectory=`, which systemd names in the environment, colon-separated: her working directory first, then the kept conversation's own directory (ruling `eureka-body:ruling:kept-session-ordinary-separation`). +pub const STATE_DIRECTORY_VARIABLE: &str = "STATE_DIRECTORY"; +/// The record of the kept conversation beside its transcript: `{"session", "warm_until", "seed"}`. +const KEPT_RECORD: &str = "kept.json"; + +/// The digest of a seed tree: sha256 over every file's and link's relative path in sorted order, +/// each with the file's bytes or the link's target, as lowercase hex. A conversation made under +/// one seed is never resumed under another. +fn seed_digest(seed: &Path) -> std::io::Result { + use sha2::{Digest, Sha256}; + fn walk(root: &Path, dir: &Path, hash: &mut Sha256) -> std::io::Result<()> { + let mut entries = std::fs::read_dir(dir)?.collect::>>()?; + entries.sort_by_key(std::fs::DirEntry::file_name); + for entry in entries { + let kind = entry.file_type()?; + let path = entry.path(); + let relative = path.strip_prefix(root).unwrap_or(&path).to_string_lossy().into_owned(); + if kind.is_dir() { + walk(root, &path, hash)?; + continue; + } + let (tag, body) = if kind.is_symlink() { (b'l', std::fs::read_link(&path)?.to_string_lossy().into_owned().into_bytes()) } else { (b'f', std::fs::read(&path)?) }; + hash.update([tag]); + hash.update((relative.len() as u64).to_le_bytes()); + hash.update(relative.as_bytes()); + hash.update((body.len() as u64).to_le_bytes()); + hash.update(&body); + } + Ok(()) + } + let mut hash = Sha256::new(); + walk(seed, seed, &mut hash)?; + Ok(hash.finalize().iter().map(|byte| format!("{byte:02x}")).collect()) +} + +/// Writes `bytes` to `dir/name` through a `.tmp` and a rename. +fn write_through_tmp(dir: &Path, name: &str, bytes: &[u8]) -> std::io::Result<()> { + let tmp = dir.join(format!("{name}.tmp")); + std::fs::write(&tmp, bytes)?; + std::fs::rename(tmp, dir.join(name)) +} + +/// Makes the kept directory owner-only if it is not there. +fn make_kept_dir(dir: &Path) -> std::io::Result<()> { + let mut made = std::fs::DirBuilder::new(); + made.recursive(true); + #[cfg(unix)] + std::os::unix::fs::DirBuilderExt::mode(&mut made, 0o700); + made.create(dir) +} + +/// Removes every file of the kept directory but `except`. +fn clear_kept_dir(dir: &Path, except: &[String]) -> std::io::Result<()> { + let entries = match std::fs::read_dir(dir) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error), + }; + for entry in entries { + let entry = entry?; + if !except.contains(&entry.file_name().to_string_lossy().into_owned()) && entry.file_type()?.is_file() { + std::fs::remove_file(entry.path())?; + } + } + Ok(()) +} + impl Spawner for ClaudeSpawner { + fn kept(&self) -> Option { + let dir = self.keep.as_ref()?; + let record: Value = serde_json::from_slice(&std::fs::read(dir.join(KEPT_RECORD)).ok()?).ok()?; + let session = Uuid::parse_str(record.get("session")?.as_str()?).ok()?; + let warm_until = DateTime::parse_from_rfc3339(record.get("warm_until")?.as_str()?).ok()?.with_timezone(&Utc); + let transcript = dir.join(format!("{session}.jsonl")); + transcript.is_file().then_some(())?; + let same_seed = self.seed_digest.as_deref() == Some(record.get("seed")?.as_str()?); + let written_at = DateTime::parse_from_rfc3339(record.get("written_at")?.as_str()?).ok()?.with_timezone(&Utc); + Some(Kept { session, transcript, warm_until, written_at, same_seed }) + } + + fn keep(&self, keep: Option<(Uuid, DateTime)>) -> Result<()> { + let Some(dir) = &self.keep else { return Ok(()) }; + let kept = keep.and_then(|(session, until)| Some((session, until, self.seed_digest.as_ref()?))); + let Some((session, until, seed)) = kept.filter(|(session, ..)| dir.join(format!("{session}.jsonl")).is_file()) else { + // The clear: the record goes first, so no record ever names a transcript that is gone. + let _ = std::fs::remove_file(dir.join(KEPT_RECORD)); + return clear_kept_dir(dir, &[]).context("the kept conversation could not be cleared"); + }; + let record = serde_json::json!({"session": session.to_string(), "warm_until": until.to_rfc3339_opts(SecondsFormat::Secs, true), "written_at": Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true), "seed": seed}); + write_through_tmp(dir, KEPT_RECORD, record.to_string().as_bytes()).context("the kept conversation's record could not be written")?; + clear_kept_dir(dir, &[KEPT_RECORD.to_string(), format!("{session}.jsonl")]).context("the conversation before it could not be removed") + } + fn spawn(&self, args: &[String], token: &TokenFd) -> Result> { - let config = FreshConfig::create(&self.scratch, self.seed.as_deref())?; + let config = FreshConfig::create(&self.scratch, self.seed.as_deref(), self.keep.clone())?; let Some(sandbox) = &self.sandbox else { return spawn_program(Path::new("claude"), args, token, &self.unit_environment, config) }; let mut wrapped = sandbox_args(sandbox, &self.scratch); wrapped.push("claude".into()); @@ -920,10 +1128,14 @@ const CONFIG_DIR_NAME: &str = "claude-config"; /// owner-only, and removed when the child's handle goes. Whatever the run writes /// there (settings that set an environment variable, an `apiKeyHelper`, a base /// URL, a hook) lasts only as long as that run: the next one starts from the seed. -struct FreshConfig(PathBuf); +struct FreshConfig { + dir: PathBuf, + /// Where the main transcripts go when the config does: the kept directory, none where nothing is kept. + keep: Option, +} impl FreshConfig { - fn create(scratch: &Path, seed: Option<&Path>) -> Result { + fn create(scratch: &Path, seed: Option<&Path>, keep: Option) -> Result { let dir = scratch.join(CONFIG_DIR_NAME); match std::fs::remove_dir_all(&dir) { Ok(()) => {} @@ -934,9 +1146,9 @@ impl FreshConfig { #[cfg(unix)] std::os::unix::fs::DirBuilderExt::mode(&mut made, 0o700); made.create(&dir).context("the configuration directory could not be made")?; - let fresh = Self(dir); + let fresh = Self { dir, keep }; if let Some(seed) = seed { - copy_tree(seed, &fresh.0).context("the configuration seed could not be copied")?; + copy_tree(seed, &fresh.dir).context("the configuration seed could not be copied")?; } Ok(fresh) } @@ -944,10 +1156,38 @@ impl FreshConfig { impl Drop for FreshConfig { fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); + if let Some(keep) = &self.keep { + // A conversation that cannot be copied out is a fresh start; nothing here decides whether it is kept. + let _ = move_out_transcripts(&self.dir, keep); + } + let _ = std::fs::remove_dir_all(&self.dir); } } +/// Copies the main transcripts out of a config directory, `projects/*/*.jsonl` +/// and nothing deeper (never a project's `memory/` or a session's own directory), +/// into `keep` as ``, each through a `.tmp` and a rename. +fn move_out_transcripts(config: &Path, keep: &Path) -> std::io::Result<()> { + make_kept_dir(keep)?; + for project in std::fs::read_dir(config.join("projects"))? { + let project = project?; + if !project.file_type()?.is_dir() { + continue; + } + for file in std::fs::read_dir(project.path())? { + let file = file?; + let path = file.path(); + if file.file_type()?.is_file() && path.extension().is_some_and(|extension| extension == "jsonl") { + let name = file.file_name().to_string_lossy().into_owned(); + let tmp = keep.join(format!("{name}.tmp")); + std::fs::copy(&path, &tmp)?; + std::fs::rename(tmp, keep.join(name))?; + } + } + } + Ok(()) +} + /// A seed link the copy refuses: it would reach outside the seed. #[derive(Debug)] struct SeedLinkRefused { @@ -1047,7 +1287,7 @@ fn spawn_program(program: &Path, args: &[String], token: &TokenFd, unit: &[(OsSt let mut command = Command::new(program); command.args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::inherit()); command.env_clear().envs(child_environment(unit)); - command.env("HOME", &config.0).env(CONFIG_DIR_VARIABLE, &config.0); + command.env("HOME", &config.dir).env(CONFIG_DIR_VARIABLE, &config.dir); command.env(DISABLE_COMPACT_VARIABLE, "1").env(TOKEN_FD_VARIABLE, inheritable.number().to_string()).env(ENV_SCRUB_VARIABLE, if scrub_is_off(unit) { "0" } else { "1" }); // Its own process group, so that a signal reaches what the child started too. #[cfg(unix)] diff --git a/crates/mind-body/src/self_run/decide.rs b/crates/mind-body/src/self_run/decide.rs index 8c4c6dd..dbfc42a 100644 --- a/crates/mind-body/src/self_run/decide.rs +++ b/crates/mind-body/src/self_run/decide.rs @@ -50,7 +50,7 @@ use std::collections::{BTreeMap, BTreeSet, HashSet}; use chrono::{DateTime, Duration, Utc}; use super::{ - CEILING_TOKENS, Cause, ESCALATE_AFTER_S, EXIT_DRAIN_S, FLUSH_GRACE_S, FLUSH_HEADROOM_TOKENS, LADDER_S, ROTATE_MARGIN_S, SelfRunOutcome, Stop, TTL_1H_S, TTL_5M_S, TTL_MARGIN_S, + CEILING_TOKENS, Cause, ESCALATE_AFTER_S, EXIT_DRAIN_S, FLUSH_GRACE_S, FLUSH_HEADROOM_TOKENS, LADDER_S, ROTATE_MARGIN_S, Kept, SelfRunOutcome, Stop, TTL_1H_S, TTL_5M_S, TTL_MARGIN_S, }; /// Why the flush was asked: the session's own end, three ways. @@ -167,6 +167,14 @@ pub(super) struct State { /// An ok result has come: the session holds an answer worth its cache. answered_once: bool, last_result_at: Option>, + /// When the last new request of the main thread began, as far as the stream shows: the line before its first assistant line, never that line's own read time, which comes after the request started. The cache's lifetime runs from a request's start (research `cache-pricing`), so `warm_until` counts from here and never from the last result; a slow response only makes the window shorter than the cache's real life. + last_request_at: Option>, + /// When the last line of the stream that matters (an echo, a result, or a request's line) was read: the earliest bound the stream gives on when the next request began, since a request starts after the line before it. + stream_at: Option>, + /// The last result was not an error. + last_ok: bool, + /// The CLI refused a result as over its context limit; once seen, it stays seen. + blocked: bool, /// The cache lifetime the last result left, in seconds. pub(super) ttl_s: i64, pub(super) inbox: bool, @@ -222,7 +230,40 @@ impl State { } fn outcome(state: &State, cause: Cause, code: Option) -> SelfRunOutcome { - SelfRunOutcome::Ended { cause, code, requests: state.requests, prefix: state.prefix } + SelfRunOutcome::Ended { cause, code, requests: state.requests, prefix: state.prefix, warm_until: warm_until(state) } +} + +/// Until when the conversation this process ended is worth resuming: its last +/// request plus its cache's lifetime less the margin. Some only for a clean end +/// inside the cache's life: no signal was delivered, the child exited 0, no turn +/// was open, the last result was ok and none was blocked, the prefix is under the +/// ceiling, and no flush was asked or it was the rotation's. An idle flush means +/// the cache is about to be evicted and the session is cleared then (ruling +/// `eureka-body:ruling:live-session-floor-cache-evicts`); a ceiling end would only +/// flush again. This is the one place a conversation's worth is decided; the next +/// process resumes it by [`resumes`] (ruling `eureka-body:ruling:session-rotate-and-resume`). +pub(super) fn warm_until(state: &State) -> Option> { + let clean = state.delivered.is_none() + && matches!(state.exited, Some((Some(0), _))) + && !state.turn_open + && state.last_ok + && !state.blocked + && state.prefix < CEILING_TOKENS + && state.flush.as_ref().is_none_or(|flush| flush.why == Why::Rotation); + if !clean { + return None; + } + state.last_request_at.map(|at| at + Duration::seconds(state.ttl_s - TTL_MARGIN_S)) +} + +/// Whether a kept conversation is resumed by a process starting at `now`: its +/// cache is still warm, its seed is the one it was made under, and its record +/// claims no more warmth than a cache has: a `warm_until` later than the record's +/// write time plus the longest lifetime (one hour) is forged or wrong, and the +/// conversation is cold (ruling `eureka-body:ruling:kept-session-ordinary-separation`). +/// Nothing else decides resume or fresh. +pub(super) fn resumes(kept: &Kept, now: DateTime) -> bool { + kept.same_seed && now < kept.warm_until && kept.warm_until <= kept.written_at + Duration::seconds(TTL_1H_S) } /// How the run ended, by what was done to the child: the strongest signal delivered, else the flush, else nothing. @@ -356,8 +397,11 @@ pub(super) fn decide(mut state: State, event: Event, now: DateTime) -> (Sta Event::Request { id, prefix, stops } => { state.open_turn(Some(TurnBy::Cli)); state.stopped_by_us.extend(stops); + let began = state.stream_at.or(state.cap.map(|(at, _)| at)).unwrap_or(now); + state.stream_at = Some(now); if state.seen.insert(id) { state.requests += 1; + state.last_request_at = Some(began); state.prefix = prefix; if let Some(flush) = state.flush.as_mut() && flush.consumed @@ -371,6 +415,7 @@ pub(super) fn decide(mut state: State, event: Event, now: DateTime) -> (Sta } } Event::Echo => { + state.stream_at = Some(now); state.consumed += 1; state.open_turn(Some(TurnBy::Us)); let consumed = state.consumed; @@ -387,6 +432,9 @@ pub(super) fn decide(mut state: State, event: Event, now: DateTime) -> (Sta let (turns, by) = (state.turns, state.turn_by); state.owed.retain(|_, owed| !(owed.taken || (by != TurnBy::Us && owed.since < turns))); state.last_result_at = Some(now); + state.stream_at = Some(now); + state.last_ok = ok; + state.blocked |= blocked; state.ttl_s = if ttl_1h { TTL_1H_S } else { TTL_5M_S }; let no_answer = !ok && !state.answered_once; state.answered_once |= ok; diff --git a/crates/mind-body/src/self_run/decide/tests.rs b/crates/mind-body/src/self_run/decide/tests.rs index af99613..2c2165b 100644 --- a/crates/mind-body/src/self_run/decide/tests.rs +++ b/crates/mind-body/src/self_run/decide/tests.rs @@ -63,7 +63,7 @@ fn delivered(how: Stop) -> Event { } fn ended(cause: Cause, code: Option, requests: u64, prefix: u64) -> Action { - Action::Finish(SelfRunOutcome::Ended { cause, code, requests, prefix }) + Action::Finish(SelfRunOutcome::Ended { cause, code, requests, prefix, warm_until: None }) } const GRACE: i64 = FLUSH_GRACE_S; @@ -689,3 +689,86 @@ fn the_cache_end_flush_waits_for_a_task_in_the_level_and_its_timer_runs_from_the // Another conversation's waiting brief is no reason to end the session at its cache's end either: it is switched to at idle. assert_eq!(last([answered_start(), vec![(other_waits(), 2 + ttl)]].concat()), switches()); } + +// ---- 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(10 + 3600 - 60))); + assert_eq!(warm_after(working(), events(OK_SHORT), Some(0)), Some(t(10 + 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(3600 - 60))); +} + +#[test] +fn a_requests_start_is_bounded_by_the_line_before_it_never_by_its_own_first_line() { + // The first assistant line arrives 500 s after the echo: the request began somewhere in between, and the earliest bound is the echo. + assert_eq!(warm_after(working(), vec![(Event::Echo, 0), (req("a", 10), 500), (OK, 600)], Some(0)), Some(t(3600 - 60))); + // The next request of the turn begins after the previous request's last line, not after its result. + assert_eq!(warm_after(working(), vec![(Event::Echo, 0), (req("a", 10), 100), (req("a", 10), 200), (req("b", 10), 900), (OK, 950)], Some(0)), Some(t(200 + 3600 - 60))); + // A request with no echo before it (nothing was written) is bounded by the result before it. + assert_eq!(warm_after(working(), vec![(Event::Echo, 0), (req("a", 10), 10), (OK, 20), (req("b", 10), 900)], Some(0)), Some(t(20 + 3600 - 60))); + // After a result, the next turn's echo is the bound. + assert_eq!(warm_after(working(), vec![(Event::Echo, 0), (req("a", 10), 10), (OK, 20), (Event::Echo, 300), (req("b", 10), 900), (OK, 950)], Some(0)), Some(t(300 + 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(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(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), written_at: t(0), 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))); +} + +#[test] +fn a_record_claiming_more_warmth_than_a_cache_has_is_cold() { + let written = |warm_until, written_at| Kept { session: uuid::Uuid::nil(), transcript: "/state/session/x.jsonl".into(), warm_until, written_at, same_seed: true }; + // One hour from the write is the longest a cache lives; a record may claim up to it and no more. + assert!(resumes(&written(t(1000 + 3600), t(1000)), t(1100))); + assert!(!resumes(&written(t(1000 + 3600 + 1), t(1000)), t(1100)), "a forged far-future warm_until"); + assert!(!resumes(&written(t(1_000_000), t(1000)), t(1100))); +} diff --git a/crates/mind-body/src/self_run/tests.rs b/crates/mind-body/src/self_run/tests.rs index 470e1bb..18a6a86 100644 --- a/crates/mind-body/src/self_run/tests.rs +++ b/crates/mind-body/src/self_run/tests.rs @@ -145,7 +145,7 @@ struct Ran { impl Ran { fn ended(&self) -> (Cause, Option, u64, u64) { match self.outcome.as_ref().unwrap() { - SelfRunOutcome::Ended { cause, code, requests, prefix } => (*cause, *code, *requests, *prefix), + SelfRunOutcome::Ended { cause, code, requests, prefix, .. } => (*cause, *code, *requests, *prefix), other => panic!("not ended: {other:?}"), } } @@ -167,7 +167,7 @@ impl Ran { /// What the unit's stdout holds apart from the decisions the actuator journals. fn lines(&self) -> String { - self.out.lines().filter(|line| !line.starts_with("decision ")).map(|line| format!("{line}\n")).collect() + self.out.lines().filter(|line| !line.starts_with("decision ") && !line.starts_with("session ")).map(|line| format!("{line}\n")).collect() } fn count(&self, wanted: &Event) -> usize { @@ -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() } } @@ -303,7 +309,7 @@ fn a_mind_that_cannot_be_read_or_a_child_that_cannot_start_is_an_error_not_an_ou #[test] fn claude_args_is_exactly_the_fixed_list_for_a_session() { let session = Uuid::parse_str(SESSION_OF_RUN_A).unwrap(); - let args = claude_args(session); + let args = claude_args(session, None); assert_eq!( args, [ @@ -329,7 +335,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. @@ -353,7 +359,7 @@ fn the_child_is_started_for_her_run_with_the_fixed_list_whatever_the_run_record_ mind.committed(vec![self_run("selfrun-b", budget)]); let ran = carry_with(&Seen::of(&mind), vec![Out(result_line())], Some(0), false); assert_eq!(ran.spawns.len(), 1, "{budget}"); - assert_eq!(ran.spawns[0], claude_args(Uuid::parse_str(SESSION_OF_RUN_B).unwrap()), "{budget}"); + assert_eq!(ran.spawns[0], claude_args(Uuid::parse_str(SESSION_OF_RUN_B).unwrap(), None), "{budget}"); } } @@ -548,7 +554,7 @@ fn records_that_share_a_message_id_count_once_and_subagent_records_never_move_th steps.insert(3, Out(subagent("msg_sub", 999_999))); let ran = go(steps); assert_eq!( - ran.out, + ran.lines(), "request 1 prefix 84210 request 2 prefix 100751 request 3 prefix 117174 @@ -874,7 +880,7 @@ 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(), &SelfRunOutcome::Ended { cause: Cause::Own, code: Some(0), requests: 1, prefix: 10, warm_until: None }); assert_eq!(own.outcome.as_ref().unwrap().to_string(), "ended: own code 0 requests 1 prefix 10"); assert_eq!(own.outcome.unwrap().exit_status(), 0); @@ -956,7 +962,7 @@ mod process { fn start_with(program: &Path, args: &[String], token: &TokenFd) -> Box { for _ in 0..50 { - let config = FreshConfig::create(program.parent().unwrap(), None).unwrap(); + let config = FreshConfig::create(program.parent().unwrap(), None, None).unwrap(); match spawn_program(program, args, token, &unit_environment(), config) { Ok(child) => return child, Err(error) if format!("{error:#}").contains("busy") => std::thread::sleep(StdDuration::from_millis(100)), @@ -1028,7 +1034,7 @@ mod process { fn a_program_that_cannot_start_is_an_error_that_names_no_argument() { let canary = "canary-argument-6b0d"; let scratch = tempfile::tempdir().unwrap(); - let config = FreshConfig::create(scratch.path(), None).unwrap(); + let config = FreshConfig::create(scratch.path(), None, None).unwrap(); let error = spawn_program(Path::new("/nonexistent/claude"), &[canary.to_string()], &token_holding("tok-canary"), &[], config).err().unwrap(); assert!(!format!("{error:#}").contains(canary) && !format!("{error:#}").contains("nonexistent"), "{error:#}"); } @@ -1110,8 +1116,8 @@ 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 }); - let printed: String = String::from_utf8(out).unwrap().lines().filter(|line| !line.starts_with("decision ")).map(|line| format!("{line}\n")).collect(); + 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 ") && !line.starts_with("session ")).map(|line| format!("{line}\n")).collect(); assert_eq!(printed, "request 1 prefix 10 request 2 prefix 300000 result subtype=success is_error=false: The answer. @@ -1127,7 +1133,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"); @@ -1150,7 +1156,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(); @@ -1200,6 +1206,7 @@ mod lease; mod closure; mod conversation; 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/lease.rs b/crates/mind-body/src/self_run/tests/lease.rs index 5a2de7b..82b4a62 100644 --- a/crates/mind-body/src/self_run/tests/lease.rs +++ b/crates/mind-body/src/self_run/tests/lease.rs @@ -56,7 +56,7 @@ fn a_lease_is_asked_for_before_claude_starts_for_the_units_runtime_cap() { let ran = go(vec![Out(result_line())]); assert_eq!(ran.asked, vec![LeaseRequest { expires_at_unix_ms: u64::try_from(at_start().timestamp_millis()).unwrap() + TEST_CAP_S * 1000 }], "the request is only the expiry, the cap the unit gave"); assert_eq!(ran.all.first(), Some(&Event::Lent), "nothing happens before the lease"); - assert_eq!(ran.all.get(1), Some(&Event::Spawned), "the child is the next thing"); + assert_eq!(ran.all.get(2), Some(&Event::Spawned), "the child is the next thing after the (empty) kept conversation is cleared"); } #[test] diff --git a/crates/mind-body/src/self_run/tests/process/lease_child.rs b/crates/mind-body/src/self_run/tests/process/lease_child.rs index 187997c..7398afe 100644 --- a/crates/mind-body/src/self_run/tests/process/lease_child.rs +++ b/crates/mind-body/src/self_run/tests/process/lease_child.rs @@ -27,7 +27,7 @@ fn granted_fd_reaches_child_env_var() { let dir = tempfile::tempdir().unwrap(); let program = script(&dir, READS_ITS_CREDENTIAL); let token = token_holding("tok-canary-7f3a"); - let mut child = start_with(&program, &claude_args(session_id(&run_ref("selfrun-a"))), &token); + let mut child = start_with(&program, &claude_args(session_id(&run_ref("selfrun-a")), None), &token); child.close_input(); let (lines, code) = drain(&mut *child); assert_eq!(code, Some(0), "{lines:?}"); @@ -90,7 +90,7 @@ echo left > "$CLAUDE_CONFIG_DIR/leftover" "#; fn run_once(program: &Path, scratch: &Path, seed: Option<&Path>) -> Vec { - let config = FreshConfig::create(scratch, seed).unwrap(); + let config = FreshConfig::create(scratch, seed, None).unwrap(); let mut child = spawn_program(program, &[], &token_holding("tok-canary-7f3a"), &unit_environment(), config).unwrap(); child.close_input(); let (lines, code) = drain(&mut *child); @@ -116,7 +116,7 @@ fn each_run_gets_a_fresh_owner_only_configuration_that_what_it_writes_does_not_o assert!(!dir.path().join("claude-config").exists(), "removed when the child's handle went"); std::os::unix::fs::symlink("/etc/passwd", seed.path().join("link")).unwrap(); - let refused = FreshConfig::create(dir.path(), Some(seed.path())).err().expect("an absolute seed link is refused"); + let refused = FreshConfig::create(dir.path(), Some(seed.path()), None).err().expect("an absolute seed link is refused"); assert!(format!("{refused:#}").contains("leaves the seed"), "{refused:#}"); assert!(!dir.path().join("claude-config").exists(), "a refused copy leaves no configuration behind"); @@ -166,7 +166,7 @@ fn the_child_scrubs_its_subprocesses_unless_the_unit_says_off() { let scrub_with = |value: Option<&str>| { let mut unit = unit_environment(); unit.extend(value.map(|value| (SCRUB_VARIABLE.into(), value.into()))); - let config = FreshConfig::create(dir.path(), None).unwrap(); + let config = FreshConfig::create(dir.path(), None, None).unwrap(); let mut child = spawn_program(&program, &[], &token_holding("tok-canary-7f3a"), &unit, config).unwrap(); child.close_input(); let (lines, _) = drain(&mut *child); 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..55e2e53 --- /dev/null +++ b/crates/mind-body/src/self_run/tests/resume.rs @@ -0,0 +1,371 @@ +//! 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), written_at: at_start(), 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(Some((previous(), at_start()))), Event::Kept(None)], "a resumed start consumes the record, 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 { + // The unit's two state directories: her working directory, and the kept conversation's own beside it. + let directories = format!("{}:{}", state.join("work").display(), state.join("session").display()); + let mut environment = vec![(SCRATCH_VARIABLE.into(), scratch.into()), (STATE_DIRECTORY_VARIABLE.into(), directories.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")), [format!("{newer}.jsonl"), "kept.json".to_string()], "at most one transcript, and no stray"); + let kept = spawner.kept().unwrap(); + assert_eq!((kept.session, &kept.transcript, kept.warm_until, kept.same_seed), (newer, &newer_path, until, true)); + assert!((chrono::Utc::now() - kept.written_at).num_seconds().abs() < 60, "the record says when it was written"); + + 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","written_at":"2026-10-09T13:00:00Z","seed":""}}"#)); + assert_eq!(spawner.kept(), None, "an unreadable instant"); + write(&dir.join("kept.json"), &format!(r#"{{"session":"{}","warm_until":"2026-10-09T13:45:00Z","written_at":"2026-10-09T13:00: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_eq!(spawner.kept(), None, "a record that does not say when it was written"); + write(&dir.join("kept.json"), &format!(r#"{{"session":"{PREVIOUS}","warm_until":"2026-10-09T13:45:00Z","written_at":"2026-10-09T13:00: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); + } +} + +#[test] +fn clearing_a_kept_directory_that_does_not_exist_is_nothing_and_one_that_cannot_be_read_is_an_error() { + let state = tempfile::tempdir().unwrap(); + let spawner = spawner_over(state.path(), state.path(), None); + spawner.keep(None).expect("no directory is already clear"); + write(&state.path().join("session"), "a file where the directory belongs"); + assert!(spawner.keep(None).is_err(), "a conversation that cannot be cleared is told, not swallowed"); +} + +/// Her files for `kept`/`keep`, a child that never starts: the process ends where a signal or a panic would end it, before the end keep. +struct FilesThenDies { + files: ClaudeSpawner, + dies: Fake, +} + +impl Spawner for FilesThenDies { + fn kept(&self) -> Option { + self.files.kept() + } + + fn keep(&self, keep: Option<(Uuid, chrono::DateTime)>) -> Result<()> { + self.files.keep(keep) + } + + fn spawn(&self, args: &[String], token: &TokenFd) -> Result> { + self.dies.spawn(args, token) + } +} + +fn start_over_files(state: &Path, seen: &Seen) -> (String, ClaudeSpawner) { + let log = Rc::new(RefCell::new(Vec::new())); + let clock = Rc::new(Fixed(Cell::new(at_start()))); + let spawner = FilesThenDies { files: spawner_over(state, state, None), dies: Fake::with(None, true) }; + let mut out = Vec::new(); + let _ = carry(seen, &*clock, &FakeLender::logging(log, Answer::Grant), &spawner, TEST_CAP_S, &mut out); + (String::from_utf8_lossy(&out).into_owned(), spawner.files) +} + +#[test] +fn a_process_killed_after_resuming_leaves_a_record_the_next_start_does_not_resume_from() { + let state = tempfile::tempdir().unwrap(); + let files = spawner_over(state.path(), state.path(), None); + let path = transcript(state.path(), previous()); + files.keep(Some((previous(), at_start() + ChronoDuration::seconds(1800)))).unwrap(); + assert!(files.kept().is_some_and(|kept| decide::resumes(&kept, at_start())), "kept, warm"); + + // The next process resumes it; its child is gone before any end keep could run. + let mind = with_run(); + let (out, files) = start_over_files(state.path(), &Seen::of(&mind)); + assert!(out.contains(&format!("session resumed {PREVIOUS}")), "{out}"); + let after = files.kept().expect("the transcript stays for --resume"); + assert_eq!(after.transcript, path); + assert!(path.is_file()); + assert!(!decide::resumes(&after, at_start() + ChronoDuration::seconds(1)), "the record no longer resumes"); + assert!(!decide::resumes(&after, at_start()), "not even at the instant it was consumed"); +} + +#[test] +fn a_forged_far_future_record_is_cold_and_cleared() { + let state = tempfile::tempdir().unwrap(); + let files = spawner_over(state.path(), state.path(), None); + transcript(state.path(), previous()); + write( + &state.path().join("session/kept.json"), + &format!(r#"{{"session":"{PREVIOUS}","warm_until":"2030-01-01T00:00:00Z","written_at":"2026-10-09T13:00:00Z","seed":""}}"#), + ); + assert!(files.kept().is_some_and(|kept| kept.same_seed), "it parses, and it is the clock that refuses it"); + let (out, files) = start_over_files(state.path(), &Seen::of(&with_run())); + assert!(out.contains("session fresh: cold"), "{out}"); + assert_eq!(files.kept(), None); + assert!(names(&state.path().join("session")).is_empty()); +} diff --git a/crates/mind-body/src/testkit.rs b/crates/mind-body/src/testkit.rs index e56da8c..462685d 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"; @@ -526,6 +527,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, } @@ -632,15 +635,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 { diff --git a/crates/mind-body/tests/public_surface.txt b/crates/mind-body/tests/public_surface.txt index d85d269..7c98c97 100644 --- a/crates/mind-body/tests/public_surface.txt +++ b/crates/mind-body/tests/public_surface.txt @@ -220,7 +220,7 @@ mind_body::recall: impl Recalled mind_body::self_run: # [derive (Clone , Copy , Debug , PartialEq , Eq , PartialOrd , Ord)] pub enum Stop { Interrupt , Terminate , Kill , } mind_body::self_run: # [derive (Clone , Copy , Debug , PartialEq , Eq)] pub enum Cause { Own , FlushRequested , Signalled (Stop) , Unstoppable , } mind_body::self_run: # [derive (Clone , Debug , PartialEq , Eq)] pub enum Read { Line (String) , Timeout , Eof , Exited (Option < i32 >) , } -mind_body::self_run: # [derive (Clone , Debug , PartialEq , Eq)] pub enum SelfRunOutcome { NoRun , LeaseRefused { kind : LeaseRefusalKind } , Ended { cause : Cause , code : Option < i32 > , requests : u64 , prefix : u64 } , } +mind_body::self_run: # [derive (Clone , Debug , PartialEq , Eq)] pub enum SelfRunOutcome { NoRun , LeaseRefused { kind : LeaseRefusalKind } , Ended { cause : Cause , code : Option < i32 > , requests : u64 , prefix : u64 , warm_until : Option < DateTime < Utc > > } , } mind_body::self_run: # [derive (Clone , Debug , PartialEq , Eq)] pub enum Usage { Request { id : String , prefix : u64 , stops : Vec < String > } , Echo , TurnBegan , BackgroundTasks { live : Vec < String > , main : Vec < String > , shell : Vec < String > } , TaskBackgrounded { id : String , shell : bool } , TaskNotified { id : String , stopped : bool } , NotificationTaken { id : String } , Result { ok : bool , blocked : bool } , Other , Unreadable , } mind_body::self_run: const AGENT : & str mind_body::self_run: const CEILING_TOKENS : u64 @@ -237,11 +237,13 @@ mind_body::self_run: const RUN_CAP_VARIABLE : & str mind_body::self_run: const SCRATCH_VARIABLE : & str mind_body::self_run: const SEED_VARIABLE : & str mind_body::self_run: const SESSION_NAMESPACE : Uuid +mind_body::self_run: const STATE_DIRECTORY_VARIABLE : & str mind_body::self_run: const TTL_1H_S : i64 mind_body::self_run: const TTL_5M_S : i64 mind_body::self_run: const TTL_MARGIN_S : i64 mind_body::self_run: fn carry (mind : & dyn MindPort , clock : & dyn Clock , lender : & dyn Lender , spawner : & dyn Spawner , run_cap_s : u64 , out : & mut dyn Write) -> Result < SelfRunOutcome > -mind_body::self_run: fn claude_args (session : Uuid) -> Vec < String > +mind_body::self_run: fn claude_args (session : Uuid , resume : Option < & Path >) -> Vec < String > +mind_body::self_run: fn continue_message (run : & PipelineRef , plan_quota : & [PlanQuota] , now_ms : u64) -> String mind_body::self_run: fn read_usage (line : & str) -> Usage mind_body::self_run: fn session_id (run : & PipelineRef) -> Uuid mind_body::self_run: fn start_message (instance : & Slug , run : & PipelineRef , plan_quota : & [PlanQuota] , now_ms : u64) -> String @@ -264,8 +266,9 @@ mind_body::self_run: impl std :: error :: Error for SeedLinkRefused mind_body::self_run: impl< 'a > SelfInbox < 'a > mind_body::self_run: mod inbox mind_body::self_run: pub trait Child { fn write_line (& mut self , line : & str) ; fn close_input (& mut self) ; fn next (& mut self , timeout : StdDuration) -> Read ; fn stop (& mut self , how : Stop) -> bool ; } -mind_body::self_run: pub trait Spawner { fn spawn (& self , args : & [String] , token : & TokenFd) -> Result < Box < dyn Child > > ; } +mind_body::self_run: pub trait Spawner { fn spawn (& self , args : & [String] , token : & TokenFd) -> Result < Box < dyn Child > > ; fn kept (& self) -> Option < Kept > { None } fn keep (& self , _keep : Option < (Uuid , DateTime < Utc >) >) -> Result < () > { Ok (()) } } mind_body::self_run: struct ClaudeSpawner pub-fields[] +mind_body::self_run: struct Kept # [derive (Clone , Debug , PartialEq , Eq)] pub-fields[session: Uuid, transcript: PathBuf, warm_until: DateTime < Utc >, written_at: DateTime < Utc >, same_seed: bool] mind_body::self_run::decide: impl State mind_body::self_run::inbox: const OWNER : & str mind_body::self_run::inbox: fn backlog (mind : & dyn MindPort) -> Result < Vec < (Brief , String) > > diff --git a/crates/mind-body/tests/self_run.rs b/crates/mind-body/tests/self_run.rs index 2300795..274b89f 100644 --- a/crates/mind-body/tests/self_run.rs +++ b/crates/mind-body/tests/self_run.rs @@ -185,10 +185,17 @@ mod lane { /// The daemon over a store seeded with `documents`, and the endpoint it listens on. /// It needs a built `huginn-daemon` beside the binary (`cargo build -p huginn-daemon`). fn serve(documents: Vec) -> (Daemon, TempDir, String) { - let slug = Slug(INSTANCE.into()); let state = TempDir::new().unwrap(); + admit(state.path(), documents); + let (daemon, endpoint) = daemon_over(state.path()); + (daemon, state, endpoint) + } + + /// Admits `documents` into the store at `state`, which no daemon holds open. + fn admit(state: &Path, documents: Vec) { + let slug = Slug(INSTANCE.into()); { - let mut mind = Mind::open(state.path(), &slug).unwrap(); + let mut mind = Mind::open(state, &slug).unwrap(); let batch = PipelineAdmissionBatch { instance: slug.clone(), provenance: PipelineProvenance { faculty: Faculty::Hands, agent: "test".into(), session: "test".into(), tool: "test".into() }, @@ -196,29 +203,42 @@ mod lane { }; assert!(matches!(mind.admit(batch, Utc::now()), PipelineAdmissionOutcome::Committed { .. })); } + } + + /// A daemon over the store at `state`, and the endpoint it listens on. + fn daemon_over(state: &Path) -> (Daemon, String) { let port = UdpSocket::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); let exe = Path::new(env!("CARGO_BIN_EXE_mind-self-run")); let daemon_exe = exe.with_file_name("huginn-daemon"); assert!(daemon_exe.exists(), "build huginn-daemon first: {}", daemon_exe.display()); let daemon = Daemon( Command::new(&daemon_exe) - .args(["--state-root", state.path().to_str().unwrap(), "--instance", INSTANCE, "--bind", &format!("127.0.0.1:{port}")]) + .args(["--state-root", state.to_str().unwrap(), "--instance", INSTANCE, "--bind", &format!("127.0.0.1:{port}")]) .args(["--qdrant-url", "http://127.0.0.1:1", "--ollama-url", "http://127.0.0.1:1", "--embedding-model", "x"]) .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn() .unwrap(), ); - (daemon, state, format!("rudp://127.0.0.1:{port}")) + (daemon, format!("rudp://127.0.0.1:{port}")) } /// The binary with `bin` first on `PATH`, until the daemon answers (exit 2 before that /// has started nothing). `SELF_RUN_ENV_CANARY` is a variable of the unit's environment. fn ask(endpoint: &str, bin: &Path, socket: &Path) -> Output { + ask_in(endpoint, bin, socket, Some(Path::new(&format!("{0}/state:{0}/kept", bin.display())))) + } + + /// The same, in a unit whose `StateDirectory=` is `state_directory`. + fn ask_in(endpoint: &str, bin: &Path, socket: &Path, state_directory: Option<&Path>) -> Output { let exe = Path::new(env!("CARGO_BIN_EXE_mind-self-run")); let path = format!("{}:/usr/bin:/bin", bin.display()); for _ in 0..40 { - let attempt = Command::new(exe) + let mut command = Command::new(exe); + if let Some(state_directory) = state_directory { + command.env("STATE_DIRECTORY", state_directory); + } + let attempt = command .args(["--instance", INSTANCE, "--endpoint", endpoint]) .env("PATH", &path) .env("SELF_RUN_ENV_CANARY", ENV_CANARY) @@ -323,7 +343,7 @@ mod lane { let body = format!( "read -r -u \"$CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR\" cred echo journal-line >&2 -echo '{first}'\necho '{second}'\nread -t 5 start\nread -t 5 flush\necho \"$start\" >> {record}\necho \"$flush\" >> {record}\necho \"$SELF_RUN_ENV_CANARY\" >> {record}\necho \"$cred\" >> {record}\necho '{echo}'\necho '{echo}'\necho '{{\"type\":\"result\"}}'\nwhile read more; do :; done\nexit 0", +echo '{first}'\necho '{second}'\necho '{echo}'\nread -t 5 start\nread -t 5 flush\necho \"$start\" >> {record}\necho \"$flush\" >> {record}\necho \"$SELF_RUN_ENV_CANARY\" >> {record}\necho \"$cred\" >> {record}\necho '{echo}'\necho '{{\"type\":\"result\"}}'\nwhile read more; do :; done\nexit 0", first = request("msg_1", 100), second = request("msg_2", 299_999), echo = r#"{"type":"user","isReplay":true,"message":{"role":"user","content":"x"}}"#, @@ -336,7 +356,7 @@ echo '{first}'\necho '{second}'\nread -t 5 start\nread -t 5 flush\necho \"$start let stdout = String::from_utf8_lossy(&output.stdout).to_string(); assert_eq!(output.status.code(), Some(0), "{stdout}\n{}", String::from_utf8_lossy(&output.stderr)); - let printed: String = stdout.lines().filter(|line| !line.starts_with("decision ") && !line.starts_with("result")).map(|line| format!("{line}\n")).collect(); + let printed: String = stdout.lines().filter(|line| !line.starts_with("decision ") && !line.starts_with("result") && !line.starts_with("session ")).map(|line| format!("{line}\n")).collect(); assert_eq!(printed, "request 1 prefix 101\nrequest 2 prefix 300000\nended: flush-requested code 0 requests 2 prefix 300000\n"); assert!(!all_output(&output).contains(ENV_CANARY), "the unit environment is not echoed"); assert!(String::from_utf8_lossy(&output.stderr).contains("journal-line"), "the child's stderr is the unit's journal"); @@ -370,4 +390,63 @@ echo '{first}'\necho '{second}'\nread -t 5 start\nread -t 5 flush\necho \"$start assert_eq!(String::from_utf8_lossy(&output.stdout), "no run: she has no single open Self run\n"); assert!(!record.exists(), "claude was started"); } + + /// Two real `mind-self-run` processes share one `STATE_DIRECTORY`. The fake `claude` + /// writes its transcript where the CLI would, prints a request that wrote an hour's + /// cache and an ok result, and exits 0: a clean end inside the cache's life. The second + /// process, under a second run, resumes the first's kept transcript by its path, forked. + #[test] + #[ignore = "container only: a built huginn-daemon beside the binary, and a POSIX shell"] + fn two_real_processes_sharing_a_state_directory_resume_across_the_unit_boundary() { + use eureka_pipeline::{PipelineKind, PipelineRef}; + use mind_body::self_run::session_id; + + let (daemon, state, endpoint) = serve(seed()); + let units_state = TempDir::new().unwrap(); + let bin = TempDir::new().unwrap(); + let argv_log = bin.path().join("argv-log"); + let body = format!( + "sid=''; prev=''; for a in \"$@\"; do [ \"$prev\" = --session-id ] && sid=$a; prev=$a; done +echo \"$@\" >> {argv_log} +mkdir -p \"$CLAUDE_CONFIG_DIR/projects/p\"; echo '{{}}' > \"$CLAUDE_CONFIG_DIR/projects/p/$sid.jsonl\" +read -t 5 start +echo '{request}'\necho '{echo}'\necho '{result}'\nexit 0", + argv_log = argv_log.display(), + request = r#"{"type":"assistant","parent_tool_use_id":null,"message":{"id":"msg_1","usage":{"input_tokens":1,"cache_read_input_tokens":100,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_1h_input_tokens":5}}}}"#, + echo = r#"{"type":"user","isReplay":true,"message":{"role":"user","content":"x"}}"#, + result = r#"{"type":"result","subtype":"success","is_error":false,"result":""}"#, + ); + fake_claude(bin.path(), &body); + let connector = fake_connector(); + + let first = ask_in(&endpoint, bin.path(), &connector.path, Some(Path::new(&format!("{0}/work:{0}/kept", units_state.path().display())))); + assert_eq!(first.status.code(), Some(0), "{}", all_output(&first)); + let kept = units_state.path().join("kept"); + let mut names: Vec = std::fs::read_dir(&kept).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + assert_eq!(names, [format!("{LANE_SESSION}.jsonl"), "kept.json".to_string()], "the first process kept its conversation"); + + // Her second run: the first closed itself, so the store is quiet while the next is admitted. + drop(daemon); + let mut second_run = seed().pop().unwrap(); + let PipelineDocument::Run(run) = &mut second_run else { unreachable!() }; + run.label = eureka_pipeline::Label("selfrun-lane-two".into()); + admit(state.path(), vec![second_run]); + let (daemon, endpoint) = daemon_over(state.path()); + let second = ask_in(&endpoint, bin.path(), &connector.path, Some(Path::new(&format!("{0}/work:{0}/kept", units_state.path().display())))); + drop(daemon); + assert_eq!(second.status.code(), Some(0), "{}", all_output(&second)); + + let second_session = session_id(&PipelineRef { kind: PipelineKind::Run, id: format!("{INSTANCE}:run:selfrun-lane-two").as_str().into() }); + let argvs = std::fs::read_to_string(&argv_log).unwrap(); + let second_argv = argvs.lines().nth(1).expect("the second process started"); + assert!(second_argv.contains(&format!("--session-id {second_session}")), "{second_argv}"); + assert!(second_argv.contains(&format!("--resume {}/{LANE_SESSION}.jsonl --fork-session", kept.display())), "{second_argv}"); + assert!(!argvs.lines().next().unwrap().contains("--resume"), "the first process had nothing to resume"); + let stdout = String::from_utf8_lossy(&second.stdout).to_string(); + assert!(stdout.contains(&format!("session resumed {LANE_SESSION}")), "{stdout}"); + let mut names: Vec = std::fs::read_dir(&kept).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + assert_eq!(names, [format!("{second_session}.jsonl"), "kept.json".to_string()], "one transcript, the newer"); + } } diff --git a/docs/research/2026-10-31-live-mind-sessions-sequence.md b/docs/research/2026-10-31-live-mind-sessions-sequence.md index 7324b11..1b21c32 100644 --- a/docs/research/2026-10-31-live-mind-sessions-sequence.md +++ b/docs/research/2026-10-31-live-mind-sessions-sequence.md @@ -133,7 +133,7 @@ Live first. Memory-write runs beside cut 1 with no shared file. | 1 | **`self-session-live`** r2 (spec admitted): her Self stays alive across briefs; a brief is closed by its result; briefs to a live Self are told between tool calls; it ends at the task boundary, at the cache TTL, near the cap, or at the ceiling; a PreCompact block | Huginn | `decide.rs` `Result => CloseStdin`. A Self process cannot end at its first result, and `Busy` no longer drops a brief. | 2 | | 2 | **`persona-memory-write` r3** (spec admitted): r2 without its two `self_run.rs` changes (they move to cut 5) | Huginn | `admit_pulse` | 1 | | 3 | `plan-readout-live`: lease socket `plan` request; the Self appends a fresh plan line per batch | ModelConnector + Huginn | the start-message-only plan line | 1, 2 | -| 4 | `self-session-resume`: transcripts in StateDirectory, `--resume ` when warm, rotation under the cap, rental rule; Self capture of memory (from r2) | Huginn | `claude_args` "no resume" and the "fresh session per run" `session_id(run)` | after 1, 2 | +| 4 | `self-session-resume`: transcripts in StateDirectory, `--resume ` when warm, rotation under the cap, rental rule; Self capture of memory (from r2) | Huginn | `claude_args` "no resume" and the "fresh session per run" `session_id(run)` Status: cut `self-session-resume` builds resume and clear (the kept transcript, `--resume --fork-session`, `decide::warm_until`); the rental rule is follow-up `cut-self-session-rental`, the rotation successor is `self-rotation-successor`, and this row's memory capture is not in that cut. | after 1, 2 | | 5 | `self-reports-to-persona`: Self capture paragraph and claim/ask view (moved from r2); keeper wakes her Persona on her Self's new memory or self-run resolution | Huginn | heartbeat's `self_end > last_turn` as the only Self-to-Persona signal | after 2 | | 6 | **`persona-session`** r1 (LANDED, ruling `persona-session-landed`, deployed 2026-11-01; do not re-dispatch; spec admitted, section 4): `mind-persona` carries a leased, long-lived claude under bwrap, one conversation at a time, through the Self's own `drive`/`decide`; full shell, `huginn` and the web in `/var/lib/mind-/sandbox`; chat written as stdin lines mid-turn or idle; a constant `--json-schema`, each result decoded into one `PersonaReply` and acted on; unit cap 4 h; the gamecult-ops unit, seed and connector lease row in the same cut | Huginn + gamecult-ops | `persona.rs` `TurnRequest`, the `Connector` port and `MAX_TURNS_PER_START`; `connector.rs` `KitConnector`; the unit's connector-key credential; the per-Mind connector `--caller` rows | after 2 | | 6b | `persona-hears-her-self`: the Persona actuator polls her mind every 30 s for resolutions of the briefs she gave and memories her Self admitted, and tells them like chat ("replies when it finishes"); her Self's start message asks a first-turn acknowledgement memory ("replies within a minute"). Folds cut 5's keeper wake into the live Persona's own poll | Huginn | heartbeat's `self_end > last_turn` as the Self-to-Persona signal | after 6 (same files) |