diff --git a/crates/rhema-claw/src/handler.rs b/crates/rhema-claw/src/handler.rs index 9d9cffd..b6fb288 100644 --- a/crates/rhema-claw/src/handler.rs +++ b/crates/rhema-claw/src/handler.rs @@ -11,12 +11,14 @@ //! One turn per dispatch; a comment is posted only when the agent asks. //! //! Session continuity rides the dispatcher, not the filesystem: the -//! agent's session JSON is stashed into `ctx.session.core.driver_state` -//! before the run returns and restored with [`HostAgent::from_session`] -//! on the next dispatch of the same key, so a resumed thread keeps its -//! conversation. Commit-before-execute rides it too: the run installs the -//! context's commit hook, so the intent is in the store before the first -//! tool runs, and a crash-left dangling call revives at turn entry. +//! record's own core session is the conversation. The commit hook writes +//! it after every step and the run's end writes it back whole, so a turn +//! cut mid-flight leaves the live history where the next dispatch of the +//! same key resumes it ([`crate::interactive::resume_session`], which +//! still reads the whole-session copy older records nested in +//! `driver_state`). Commit-before-execute rides it too: the run installs +//! the context's commit hook, so the intent is in the store before the +//! first tool runs, and a crash-left dangling call revives at turn entry. //! Delivery is at-least-once: a re-delivered drained event //! re-dispatches, and this handler treats a dispatch as work to do — the //! dedup boundary is the dispatcher's, not re-derived here. @@ -29,7 +31,7 @@ use crate::bootstrap::{Bootstrap, BootstrapKind, DEFAULT_SYSTEM_MD, Surface}; use crate::forge::{WatchCredential, record_client, resolve_watch_credential}; use crate::watch_store::ClawStore; use rhema_bash::{AllowAll, ShellTools}; -use rhema_core::{Content, Event as ModelEvent, EventSink, Message, Session}; +use rhema_core::{Content, Event as ModelEvent, EventSink, Message}; use rhema_forge_integration::ForgeKind; use rhema_forge_integration::triage::Role; use rhema_forge_integration::{ @@ -358,7 +360,7 @@ impl ClawHandler { // at its current await — a streaming request, or a running // shell command, whose child dies with the drop. What the turn // committed so far is already the session (the commit hook), - // so the stash below hands it to the next dispatch. + // so the write back below hands it to the next dispatch. let mut abort = self.abort.listen(&key); let turned = tokio::select! { output = agent.turn(prompt, &mut sink) => { @@ -373,16 +375,14 @@ impl ClawHandler { None => { // Cut, not failed: the thread gets no half-answer, and // the session keeps whatever the turn committed. - ctx.session.core.driver_state = serde_json::to_value(agent.session()) - .map_err(|err| format!("session for {key} does not serialize: {err}"))?; + ctx.session.core = agent.session().clone(); return Ok(Outcome::Superseded); } }; - // Stash after the turn: a comment already posted and the turn's - // work both survive a later failure. - ctx.session.core.driver_state = serde_json::to_value(agent.session()) - .map_err(|err| format!("session for {key} does not serialize: {err}"))?; + // Written back after the turn: a comment already posted and the + // turn's work both survive a later failure. + ctx.session.core = agent.session().clone(); Ok(Outcome::Handled) } @@ -408,9 +408,10 @@ impl ClawHandler { .map_err(|err| format!("an inbox item for {key} does not decode: {err}")) } - /// The agent for this dispatch: the stashed session resumed when the - /// key has history, a fresh one otherwise. A stash that does not parse - /// fails the run loudly — silently resetting would re-orient the agent + /// The agent for this dispatch: the record's conversation resumed + /// when the key has one, a fresh agent otherwise. A `driver_state` + /// carrying a session stash that does not parse fails the run + /// loudly — silently resetting would re-orient the agent /// mid-conversation without anyone knowing. fn resume( &self, @@ -421,14 +422,10 @@ impl ClawHandler { ) -> Result { let (provider, model) = self.backends.current(); let config = self.agent_config(provider, &model, workspace, key, target)?; - let agent = match &ctx.session.core.driver_state { - // A never-dispatched key carries no stash: start clean. - serde_json::Value::Null => HostAgent::new(config), - stashed => { - let session: Session = serde_json::from_value(stashed.clone()) - .map_err(|err| format!("stashed session for {key} does not parse: {err}"))?; - HostAgent::from_session(config, session) - } + let agent = match crate::interactive::resume_session(&ctx.session.core, key)? { + // A never-dispatched key carries no conversation: start clean. + None => HostAgent::new(config), + Some(session) => HostAgent::from_session(config, session), }; agent.map_err(|err| format!("cannot start the coding agent for {key}: {err}")) } diff --git a/crates/rhema-claw/src/http.rs b/crates/rhema-claw/src/http.rs index a4c5831..1c616bb 100644 --- a/crates/rhema-claw/src/http.rs +++ b/crates/rhema-claw/src/http.rs @@ -1435,7 +1435,21 @@ fn stashed_history( let leased = record .as_ref() .is_some_and(|record| record.state == rhema_rsd::KeyState::Leased); - let events = crate::thread::events(&session.core, outcome, leased); + // The record's core is the conversation; a record written + // before the core was trusted carries it in the stash nested + // in `driver_state`, which `resume_session` prefers because + // that shape's core lags a round. A stash that does not + // parse leaves the page on the core rather than blanking it: + // the snapshot is read-only, and the core is still the + // engine's own checkpoint. + let session = match crate::interactive::resume_session(&session.core, key.as_str()) { + Ok(restored) => restored.unwrap_or_else(|| session.core.clone()), + Err(err) => { + eprintln!("[claw] history for {key}: {err}"); + session.core.clone() + } + }; + let events = crate::thread::events(&session, outcome, leased); crate::thread::page(&events, before, limit) } None => (Vec::new(), false), diff --git a/crates/rhema-claw/src/interactive.rs b/crates/rhema-claw/src/interactive.rs index d2c3ccf..3220a98 100644 --- a/crates/rhema-claw/src/interactive.rs +++ b/crates/rhema-claw/src/interactive.rs @@ -31,16 +31,22 @@ //! implicit one. //! //! Continuity rides the dispatcher exactly as the forge handler's does: -//! the whole [`rhema_core::Session`] is stashed into -//! `ctx.session.core.driver_state` before the run returns and restored -//! from there on the next dispatch (`Null` means fresh). The session is -//! the record of the conversation — the context the model returns to — -//! and the hub's record is the transcript: the stream is replayable, -//! the live deltas are the only best-effort part left. Commit-before- -//! execute rides it too: the run installs the context's commit hook, so -//! the intent is in the store before the first tool runs, and a -//! crash-left dangling call revives before the turn — safe tools re-run, -//! the rest report interrupted. +//! the record's own core session is the conversation. The commit hook +//! writes it after every step and the round's end writes it back whole, +//! so a turn cut mid-flight — a restart, an OOM kill, a lease swept — +//! leaves the live history where the next dispatch resumes it, its +//! dangling call revived at turn entry. A record from before the core +//! was trusted carries a serialized [`rhema_core::Session`] nested in +//! `ctx.session.core.driver_state` instead; [`resume_session`] reads +//! that copy (its core lags the conversation by a round) and falls back +//! to the core for everything newer. The session is the record of the +//! conversation — the context the model returns to — and the hub's +//! record is the transcript: the stream is replayable, the live deltas +//! are the only best-effort part left. Commit-before-execute rides it +//! too: the run installs the context's commit hook, so the intent is in +//! the store before the first tool runs, and a crash-left dangling call +//! revives before the turn — safe tools re-run, the rest report +//! interrupted. //! //! Deterministic setup first (spec §1, §8): the allowlist — permissive, //! v1's starting point — and the resolver chain are assembled before @@ -65,9 +71,9 @@ //! //! **Aborting** rides the same interrupt and ends instead of looping: //! a signal from the abort registry ([`crate::abort`]) drops the turn -//! future at its await, the dangling calls close, the session stashes, -//! and the dispatch releases as superseded with the `aborted` outcome -//! on the stream. Unlike a steer signal, an abort carries no inbox +//! future at its await, the dangling calls close, the session writes +//! back, and the dispatch releases as superseded with the `aborted` +//! outcome on the stream. Unlike a steer signal, an abort carries no inbox //! message, so a pending abort is honored between rounds, not cleared //! with the stale steer signals. @@ -544,12 +550,12 @@ impl InteractiveHandler { Arc::new(ResolverChain::new(resolvers)) } - /// One round: drain, restore, turn, stash, reply. The turn runs - /// under the steer/abort select, so a round that was interrupted - /// comes back as [`Round::Steered`] or [`Round::Aborted`] with the - /// session stashed and the dangling calls closed — steered, the - /// caller owes the inbox another round; aborted, the caller ends - /// the chain. + /// One round: drain, restore, turn, write back, reply. The turn + /// runs under the steer/abort select, so a round that was + /// interrupted comes back as [`Round::Steered`] or [`Round::Aborted`] + /// with the session written back and the dangling calls closed — + /// steered, the caller owes the inbox another round; aborted, the + /// caller ends the chain. async fn dispatch( &self, ctx: &mut SessionContext, @@ -722,13 +728,10 @@ impl InteractiveHandler { input }; - let mut agent = match &ctx.session.core.driver_state { - // A never-dispatched key carries no stash: start clean. - Value::Null => self.agent(&ctx.key)?, - stashed => { - let session = restore_session(stashed, &key)?; - self.resume(&ctx.key, session)? - } + let mut agent = match resume_session(&ctx.session.core, &key)? { + // A never-dispatched key carries no conversation: start clean. + None => self.agent(&ctx.key)?, + Some(session) => self.resume(&ctx.key, session)?, }; adopt_transcript(&mut agent); // Commit-before-execute: the intent is in the store before the @@ -794,11 +797,13 @@ impl InteractiveHandler { close_orphaned_calls(&mut agent.session_mut().history); } save_transcript(&mut agent); - // Stash before anything else: the conversation survives even if + // The record's session is the conversation: write the round's + // agent state back before anything else, so it survives even if // the subscriber never sees the stream — and a steered chain - // dies between rounds, the steered state is what resumes. - ctx.session.core.driver_state = serde_json::to_value(agent.session()) - .map_err(|err| format!("session for {key} does not serialize: {err}"))?; + // dies between rounds, the steered state is what resumes. The + // commit hook wrote the same core after every step, so a turn + // cut mid-flight leaves this state behind either way. + ctx.session.core = agent.session().clone(); match finished { Some(Ok(output)) => Ok(Round::Done(Ok(final_text(&output.message)))), Some(Err(reason)) => Err(reason), @@ -928,7 +933,7 @@ impl InteractiveHandler { } /// One dispatch round's shape. A steered or aborted round ended in an -/// interrupt: the session stashed, the dangling calls closed — steered, +/// interrupt: the session written back, the dangling calls closed — steered, /// the caller owes the inbox another round on the same lease, same /// session, same stream; aborted, the caller ends the chain. enum Round { @@ -1003,6 +1008,36 @@ fn save_transcript(agent: &mut HostAgent) { state[TRANSCRIPT_STATE_KEY] = value; } +/// The conversation a dispatch continues, read off the record the +/// dispatcher holds. +/// +/// The record's own core is the session: the commit hook writes the +/// agent's state after every step, so a run cut mid-turn leaves the live +/// history there and the next dispatch resumes it — the dangling call it +/// ended on revived at turn entry. A record written before the core was +/// trusted nested a whole serialized [`Session`] in `driver_state` +/// instead, and there the core lags: the run's last checkpoint wrote the +/// history it acquired with, so the nested copy is what the conversation +/// continued from and wins when it is there. `None` is a record that +/// never dispatched; anything else resumes. +/// +/// A `driver_state` shaped like a session stash that does not parse is +/// loud: falling through to the core would silently drop the round the +/// stash held. +pub(crate) fn resume_session(core: &Session, key: &str) -> Result, String> { + if core.driver_state.get("history").is_some() { + return restore_session(&core.driver_state, key).map(Some); + } + if core.history.is_empty() && core.driver_state.is_null() { + return Ok(None); + } + let mut session = core.clone(); + // A session checkpointed before paste spans existed carries the + // embedded form in its prompts; the provider must never see a mark. + crate::paste::migrate(&mut session.history); + Ok(Some(session)) +} + /// The stashed conversation: a serialized [`Session`], `Null` meaning /// fresh. A stash that does not parse is loud — silently resetting would /// re-orient the agent mid-conversation without anyone knowing. @@ -1983,6 +2018,68 @@ mod tests { assert!(err.contains("does not parse"), "{err}"); } + /// The record's own core is the conversation: an interrupted turn + /// leaves the history there, with the agent's own `driver_state` + /// beside it, and a record that never dispatched stays fresh. + #[test] + fn a_core_session_resumes_and_a_blank_record_is_fresh() { + let core = Session::default(); + assert!( + resume_session(&core, "interactive:web") + .expect("a blank record reads") + .is_none(), + "a never-dispatched key has nothing to resume" + ); + let mut core = Session::default(); + core.history + .push(CoreMessage::text(CoreRole::User, "hello")); + core.driver_state = json!({"environment_report": "the conversation's report"}); + let resumed = resume_session(&core, "interactive:web") + .expect("the core resumes") + .expect("a conversation"); + assert_eq!(resumed.history.len(), 1); + } + + /// A record written before the core was trusted nested a whole + /// session in `driver_state`, and its own history lags the + /// conversation by a round: the nested copy is what resumes. + #[test] + fn a_nested_stash_wins_over_a_stale_core() { + let mut core = Session::default(); + core.history + .push(CoreMessage::text(CoreRole::User, "the frozen first turn")); + let nested = Session { + history: vec![ + CoreMessage::text(CoreRole::User, "hello"), + CoreMessage::text(CoreRole::Assistant, "hi"), + ], + driver_state: json!({"claw_transcript": {"sections": []}}), + ..Session::default() + }; + core.driver_state = serde_json::to_value(&nested).expect("a session serializes"); + let resumed = resume_session(&core, "interactive:web") + .expect("the nested stash parses") + .expect("a conversation"); + assert_eq!( + resumed.history.len(), + 2, + "the stash's history, not the core's" + ); + } + + /// A `driver_state` shaped like a stash that no longer parses stays + /// loud: quietly resuming the stale core would drop the rounds the + /// stash held. + #[test] + fn a_stash_shaped_driver_state_that_does_not_parse_is_loud() { + let mut core = Session::default(); + core.history + .push(CoreMessage::text(CoreRole::User, "hello")); + core.driver_state = json!({"history": "garbage"}); + let err = resume_session(&core, "interactive:web").expect_err("garbage is loud"); + assert!(err.contains("does not parse"), "{err}"); + } + /// A session stashed before paste spans existed carries the embedded /// form in its prompts; the restore pass rewrites it so a provider /// never sees a mark, and the chip rides as the span note instead. @@ -2020,7 +2117,8 @@ mod tests { } /// The full dispatch, in-process: one message in, one scripted reply - /// out, the turn streamed through the hub, the conversation stashed. + /// out, the turn streamed through the hub, the conversation written + /// back to the record. #[tokio::test] async fn a_dispatch_drains_replies_and_stashes_the_conversation() { let store = Arc::new(ClawStore::in_memory().expect("store opens")); @@ -2108,7 +2206,7 @@ mod tests { /// A steered message cuts a live turn and runs as the next round on /// the same lease: the interrupted turn closes on the stream with /// the `steered` outcome, the steered question streams as its own - /// turn, and the stashed conversation carries both questions and + /// turn, and the session conversation carries both questions and /// the one answer that replaced the interrupted generation. #[tokio::test] async fn a_steered_message_cuts_the_live_turn_and_runs_as_the_next_round() { @@ -2239,10 +2337,8 @@ mod tests { let record = rhema_rsd::Store::load(volatile.as_ref(), &key) .expect("the record loads") .expect("the key has a record"); - let stashed: Session = - serde_json::from_value(record.session.expect("a session").core.driver_state) - .expect("the stash parses"); - let turns: Vec<(CoreRole, &str)> = stashed + let session: Session = record.session.expect("a session").core; + let turns: Vec<(CoreRole, &str)> = session .history .iter() .filter_map(|message| match &message.content[0] { @@ -2369,10 +2465,8 @@ mod tests { let record = rhema_rsd::Store::load(volatile.as_ref(), &key) .expect("the record loads") .expect("the key has a record"); - let stashed: Session = - serde_json::from_value(record.session.expect("a session").core.driver_state) - .expect("the stash parses"); - let turns: Vec<(CoreRole, &str)> = stashed + let session: Session = record.session.expect("a session").core; + let turns: Vec<(CoreRole, &str)> = session .history .iter() .filter_map(|message| match &message.content[0] { @@ -2788,9 +2882,12 @@ mod tests { assert!(!bootstrap.needs_onboarding(), "both files exist"); } - /// The stash proof, done properly through the dispatcher's record. + /// The write back, done properly through the dispatcher's record: the + /// exchange lands in the record's own session, where the commit hook + /// already wrote the steps, and not in a copy nested in + /// `driver_state`. #[tokio::test] - async fn a_dispatch_stashes_the_exchange_in_driver_state() { + async fn a_dispatch_writes_the_conversation_back_to_the_record() { use rhema_rsd::Store; let store = Arc::new(ClawStore::in_memory().expect("store opens")); @@ -2844,10 +2941,8 @@ mod tests { .load(&key) .expect("the record loads") .expect("the key has a record"); - let stashed: Session = - serde_json::from_value(record.session.expect("a session").core.driver_state) - .expect("the stash parses back into a session"); - let roles: Vec<(CoreRole, String)> = stashed + let session: Session = record.session.expect("a session").core; + let roles: Vec<(CoreRole, String)> = session .history .iter() .filter_map(|message| match &message.content[0] { @@ -2862,6 +2957,109 @@ mod tests { (CoreRole::Assistant, "hi back".to_owned()), ] ); + assert!( + session.driver_state.get("history").is_none(), + "no whole-session copy is nested in the record: {:?}", + session.driver_state + ); + } + + /// The failure this guards is a daemon killed mid-turn: the commit + /// hook leaves the conversation in the record's core, with the + /// agent's own `driver_state` beside it and no nested stash, and the + /// next message resumes it instead of failing with `missing field + /// history` and bricking the key. + #[tokio::test] + async fn an_interrupted_turn_resumes_from_the_records_core_session() { + use rhema_rsd::{KeyRecord, Store}; + + let store = Arc::new(ClawStore::in_memory().expect("store opens")); + let hub = Arc::new(EventHub::default()); + let workspace = tempfile::tempdir().expect("tempdir"); + let notifications = notifications(); + let extensions = test_extensions( + hub.clone(), + store, + notifications.clone(), + tasks(), + jobs(), + accounts(), + consents(), + bridge(), + attachments(), + phone(), + identity(), + &workspace.path().join("interactive"), + ); + let handler = InteractiveHandler::new( + test_registry(Arc::new(MockProvider::new([reply("hi back")]))), + workspace.path().join("interactive"), + Arc::new(rhema_memory::VolatileStore::new()), + Arc::new(Bootstrap::new(workspace.path().join("bootstrap")).expect("store opens")), + hub.clone(), + notifications.clone(), + attachments(), + crate::config::DEFAULT_MAX_TURN_STEPS, + extensions, + true, + ); + let backing = Arc::new(VolatileStore::new()); + let dispatcher = Arc::new(Dispatcher::new( + DispatcherConfig { + debounce_window_millis: 0, + ..DispatcherConfig::default() + }, + Arc::new(rhema_rsd::SystemClock), + backing.clone(), + )); + register_user(&dispatcher); + let key = Key::from("interactive:web"); + // The shape a run cut mid-turn leaves behind: the history the + // engine committed, the agent's own driver state, no nested + // session copy. + let mut record = KeyRecord::fresh(key.clone(), 1_000); + let mut session = rhema_rsd::Session::fresh(key.clone(), 1_000); + session.core.history = vec![ + CoreMessage::text(CoreRole::User, "before the restart"), + CoreMessage::text(CoreRole::Assistant, "on it"), + ]; + session.core.driver_state = json!({"environment_report": "the conversation's report"}); + record.session = Some(session); + backing.save(record, None).expect("the record seeds"); + + dispatcher + .ingest(user_event(key.as_str(), "again", &[], &[])) + .expect("ingests"); + let driver = rhema_rsd::Driver::new(dispatcher, Arc::new(handler)); + assert_eq!( + driver.run_once().await.expect("the run happens"), + vec![RsdOutcome::Handled], + "the interrupted session resumes instead of failing" + ); + + let record = backing + .load(&key) + .expect("the record loads") + .expect("the key has a record"); + let session: Session = record.session.expect("a session").core; + let roles: Vec<(CoreRole, String)> = session + .history + .iter() + .filter_map(|message| match &message.content[0] { + Content::Text(text) => Some((message.role, text.clone())), + _ => None, + }) + .collect(); + assert_eq!( + roles, + vec![ + (CoreRole::User, "before the restart".to_owned()), + (CoreRole::Assistant, "on it".to_owned()), + (CoreRole::User, "again".to_owned()), + (CoreRole::Assistant, "hi back".to_owned()), + ], + "the old conversation carried into the new turn" + ); } /// The auto-notify contract, end to end: a `task:` dispatch runs the @@ -2947,16 +3145,14 @@ mod tests { assert_eq!(pending[0].title, "claw"); assert_eq!(pending[0].body, "the bread is done."); - // The turn ran with the prompt — the stashed session carries it + // The turn ran with the prompt — the session session carries it // verbatim, under the delivery-contract framing. let record = backing .load(&Key::from("task:1")) .expect("the record loads") .expect("the key has a record"); - let stashed: Session = - serde_json::from_value(record.session.expect("a session").core.driver_state) - .expect("the stash parses"); - let user_texts: Vec<&str> = stashed + let session: Session = record.session.expect("a session").core; + let user_texts: Vec<&str> = session .history .iter() .filter_map(|message| match &message.content[0] { @@ -3087,17 +3283,15 @@ mod tests { "the wake ran in the named session, not a cold slot" ); - // The session kept its context: the stashed conversation holds + // The session kept its context: the session conversation holds // the evening's message, then the framed wake. use rhema_rsd::Store; let record = backing .load(&key) .expect("the record loads") .expect("the key has a record"); - let stashed: Session = - serde_json::from_value(record.session.expect("a session").core.driver_state) - .expect("the stash parses"); - let user_texts: Vec = stashed + let session: Session = record.session.expect("a session").core; + let user_texts: Vec = session .history .iter() .filter_map(|message| match &message.content[0] { diff --git a/crates/rhema-claw/src/job_store.rs b/crates/rhema-claw/src/job_store.rs index ae1676d..4786a2e 100644 --- a/crates/rhema-claw/src/job_store.rs +++ b/crates/rhema-claw/src/job_store.rs @@ -6,9 +6,9 @@ //! `CodingAgent` turn over an instance's workspace: prompt in, final //! text out, run off the chat turn by the jobs dispatcher (see //! [`crate::jobs`]). The conversation carries across a job boundary in -//! the instance row's session blob — the same stash the forge handler -//! keeps in the dispatcher's `driver_state`, keyed by instance instead -//! of by thread, so "run the tests" after "fix the lint" continues the +//! the instance row's session blob — the same conversation the forge +//! handler keeps in its record's session, keyed by instance instead of +//! by thread, so "run the tests" after "fix the lint" continues the //! same coding session. //! //! Two invariants the schema itself holds: at most one **live** job diff --git a/crates/rhema-claw/tests/continuity.rs b/crates/rhema-claw/tests/continuity.rs index 072f535..34fac09 100644 --- a/crates/rhema-claw/tests/continuity.rs +++ b/crates/rhema-claw/tests/continuity.rs @@ -1,9 +1,8 @@ //! Session continuity across processes: two `--once` passes over the same -//! SQLite db and the same thread. The first pass's conversation is -//! stashed into the dispatcher's `driver_state`; the second pass's agent -//! resumes from it — the MockProvider cannot record its requests, so the -//! stashed state itself is the proof: the restored history carries both -//! exchanges. +//! SQLite db and the same thread. The first pass's conversation lands in +//! the record's own session; the second pass's agent resumes from it — +//! the MockProvider cannot record its requests, so the record itself is +//! the proof: the restored history carries both exchanges. use std::sync::Arc; @@ -207,7 +206,7 @@ async fn the_second_dispatch_resumes_the_first_conversation() { assert_eq!(second.outcomes, vec![Outcome::Handled]); drop(second_post); - // The proof: the second run's stashed session carries the first + // The proof: the second run's session session carries the first // conversation — a fresh agent would hold only its own exchange. let store = SqliteStore::open(dir.path().join("dispatch.db")).expect("db reopens"); let record = store @@ -215,15 +214,8 @@ async fn the_second_dispatch_resumes_the_first_conversation() { .expect("the record loads") .expect("the key has a record"); assert_eq!(record.state, KeyState::Idle); - let stashed: Session = serde_json::from_value( - record - .session - .expect("the key has a session") - .core - .driver_state, - ) - .expect("the stash parses back into a session"); - let user_prompts: Vec<&str> = stashed + let session: Session = record.session.expect("the key has a session").core; + let user_prompts: Vec<&str> = session .history .iter() .filter_map(|message| match &message.content[0] { @@ -244,7 +236,7 @@ async fn the_second_dispatch_resumes_the_first_conversation() { user_prompts[1].contains("any progress?"), "pass two's prompt carried the new comment" ); - let replies: Vec<&str> = stashed + let replies: Vec<&str> = session .history .iter() .filter_map(|message| match &message.content[0] { diff --git a/crates/rhema-claw/tests/http.rs b/crates/rhema-claw/tests/http.rs index 80120e5..1a38ea4 100644 --- a/crates/rhema-claw/tests/http.rs +++ b/crates/rhema-claw/tests/http.rs @@ -356,17 +356,15 @@ async fn chat_streams_turns_and_remembers_across_messages() { .expect("the second message accepts"); read_until(&mut stream, &mut seen, "still on it").await; - // The proof, cold: the store's driver_state carries both exchanges. + // The proof, cold: the record's own session carries both exchanges. let store = SqliteStore::open(dir.path().join("dispatch.db")).expect("db reopens"); let key = ResourceKey::from("interactive:web"); let record = store .load(&key) .expect("the record loads") .expect("the key has a record"); - let stashed: Session = - serde_json::from_value(record.session.expect("a session").core.driver_state) - .expect("the stash parses"); - let turns: Vec<(Role, &str)> = stashed + let session: Session = record.session.expect("a session").core; + let turns: Vec<(Role, &str)> = session .history .iter() .filter_map(|message| match &message.content[0] { @@ -496,10 +494,8 @@ async fn a_message_into_a_live_turn_steers_it() { .load(&key) .expect("the record loads") .expect("the key has a record"); - let stashed: Session = - serde_json::from_value(record.session.expect("a session").core.driver_state) - .expect("the stash parses"); - let turns: Vec<(Role, &str)> = stashed + let session: Session = record.session.expect("a session").core; + let turns: Vec<(Role, &str)> = session .history .iter() .filter_map(|message| match &message.content[0] { @@ -895,11 +891,11 @@ async fn chat_messages_carry_images_into_the_attachment_store() { } /// A staged chip rides beside its draft and records as spans: the -/// echo on the stream and the stashed session both carry the plain +/// echo on the stream and the session session both carry the plain /// text with the `rhema-code` annotation beside it, and no mark ever /// crosses the wire. #[tokio::test] -async fn a_staged_chip_records_as_spans_on_the_stream_and_in_the_stash() { +async fn a_staged_chip_records_as_spans_on_the_stream_and_in_the_record() { let provider = Arc::new(MockProvider::new([reply("on it")])); let dir = tempfile::tempdir().expect("tempdir"); let daemon = Daemon::build( @@ -943,7 +939,7 @@ async fn a_staged_chip_records_as_spans_on_the_stream_and_in_the_stash() { ); assert!(!seen.contains('\u{FFFC}'), "no marks ride the wire: {seen}"); - // The stash: the checkpoint's user message carries the payload in + // The record's session: the user message carries the payload in // the text and the annotation that outlives the turn. let store = SqliteStore::open(dir.path().join("dispatch.db")).expect("db reopens"); let key = ResourceKey::from("interactive:web"); @@ -951,14 +947,12 @@ async fn a_staged_chip_records_as_spans_on_the_stream_and_in_the_stash() { .load(&key) .expect("the record loads") .expect("the key has a record"); - let stashed: Session = - serde_json::from_value(record.session.expect("a session").core.driver_state) - .expect("the stash parses"); - let ask = stashed + let session: Session = record.session.expect("a session").core; + let ask = session .history .iter() .find(|message| message.role == Role::User) - .expect("the question is stashed"); + .expect("the question is session"); assert_eq!(rhema_claw::paste::spans(ask).len(), 1); assert_eq!(rhema_claw::paste::spans(ask)[0].start, 12); assert_eq!(rhema_claw::paste::spans(ask)[0].end, 38); @@ -1637,10 +1631,8 @@ async fn the_shim_answers_whole_and_streamed_and_ignores_incoming_history() { .load(&ResourceKey::from("interactive:web")) .expect("the record loads") .expect("the key has a record"); - let stashed: Session = - serde_json::from_value(record.session.expect("a session").core.driver_state) - .expect("the stash parses"); - let prompts: Vec<&str> = stashed + let session: Session = record.session.expect("a session").core; + let prompts: Vec<&str> = session .history .iter() .filter_map(|message| match &message.content[0] { @@ -4646,6 +4638,38 @@ async fn a_forge_thread_reads_back_as_a_read_only_snapshot() { assert_eq!(events[2]["event"]["code"], 1); assert_eq!(events[4]["event"]["reply"], "The build is red; rerunning."); + // A record written before the core was trusted nested the whole + // session in `driver_state`, and its core lags the conversation: the + // page reads the nested copy, not the frozen core. + { + let store = SqliteStore::open(&db).expect("the store opens"); + let mut record = store + .load(&key) + .expect("the record loads") + .expect("the key has a record"); + let conversation = record.session.as_ref().expect("a session").core.clone(); + let mut stale = rhema_rsd::Session::fresh(key.clone(), 1); + stale.core.history = vec![Message::text(Role::User, "the frozen first turn")]; + stale.core.driver_state = serde_json::to_value(&conversation).expect("it serializes"); + record.session = Some(stale); + let revision = record.revision; + store + .save(record, Some(revision)) + .expect("the legacy record seeds"); + } + let page = client + .get(format!( + "{base}/v1/sessions/github%3Aissue%3Aacme%2Fwidgets%237/history" + )) + .send() + .await + .expect("the history request goes out"); + let legacy: Value = page.json().await.expect("the body parses"); + assert_eq!( + legacy["events"][0]["event"]["text"], "review the failing check", + "the nested stash wins over the lagging core: {legacy}" + ); + // Read-only for real: the message route still refuses the prefix, // and the stream route refuses it too — a client that followed // `read_only=false` would retry a 400 forever.