fix(claw): resume a session from the record's own core
android / release (push) Successful in 2m7s
ci / checks (push) Successful in 2m53s
ci / web (push) Successful in 14s
ci / publish-edge-images (deploy/docker/ui.Dockerfile, rhema-claw-ui) (push) Successful in 10s
android / debug (push) Successful in 2m14s
ci / test (push) Successful in 1m12s
ci / chart (push) Successful in 6s
ci / docker (push) Successful in 2m0s
ci / publish-edge-images (deploy/docker/claw.Dockerfile, rhema-claw) (push) Successful in 2m10s
ci / publish-edge-chart (push) Successful in 4s

A daemon killed mid-turn left the key unusable. The interactive and
forge handlers stashed the whole session in the record's
`driver_state` and restored it on the next dispatch. The commit hook
wrote the same record after every step, but with the engine's own
session in it: no nested stash, the history at the top. A run cut
between two steps therefore left a record whose `driver_state` held
only the agent's state, and the next dispatch parsed that as a stash
and failed with `missing field history`. Every message after it failed
the same way. On the live claw it was interactive:web, 354 messages in
the core and a bash call at the end with no result.

The record's core is the conversation now. Both handlers write
`agent.session()` into `ctx.session.core` instead of nesting a copy of
it in `driver_state`, so the hook and the handler agree, the core's
history stops lagging the conversation, and a run killed mid-turn
leaves a session the next dispatch resumes. `resume_session` still
reads a nested stash when one is there, so records written before this
change keep their conversations (a live forge thread carries 940
messages in its stash against 202 in its core), and a stash-shaped
`driver_state` that does not parse is still a loud failure. The
read-only history page reads the session the same way, so a legacy
forge thread renders its conversation instead of the stale core.

cargo test -p rhema-claw and clippy with -D warnings pass. A record
seeded in the commit hook's shape resumes with its old conversation,
and the live interactive:web session parses back through the new read.
This commit is contained in:
vhaudiquet committed 2026-12-02 12:22:21 +01:00
1 parent 13da540ce5
commit 5504c6a91b
6 files changed
+344 -123

No files matched your search

+22 -25
View File
@@ -11,12 +11,14 @@
//! One turn per dispatch; a comment is posted only when the agent asks. //! One turn per dispatch; a comment is posted only when the agent asks.
//! //!
//! Session continuity rides the dispatcher, not the filesystem: the //! Session continuity rides the dispatcher, not the filesystem: the
//! agent's session JSON is stashed into `ctx.session.core.driver_state` //! record's own core session is the conversation. The commit hook writes
//! before the run returns and restored with [`HostAgent::from_session`] //! it after every step and the run's end writes it back whole, so a turn
//! on the next dispatch of the same key, so a resumed thread keeps its //! cut mid-flight leaves the live history where the next dispatch of the
//! conversation. Commit-before-execute rides it too: the run installs the //! same key resumes it ([`crate::interactive::resume_session`], which
//! context's commit hook, so the intent is in the store before the first //! still reads the whole-session copy older records nested in
//! tool runs, and a crash-left dangling call revives at turn entry. //! `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 //! Delivery is at-least-once: a re-delivered drained event
//! re-dispatches, and this handler treats a dispatch as work to do — the //! re-dispatches, and this handler treats a dispatch as work to do — the
//! dedup boundary is the dispatcher's, not re-derived here. //! 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::forge::{WatchCredential, record_client, resolve_watch_credential};
use crate::watch_store::ClawStore; use crate::watch_store::ClawStore;
use rhema_bash::{AllowAll, ShellTools}; 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::ForgeKind;
use rhema_forge_integration::triage::Role; use rhema_forge_integration::triage::Role;
use rhema_forge_integration::{ use rhema_forge_integration::{
@@ -358,7 +360,7 @@ impl ClawHandler {
// at its current await — a streaming request, or a running // at its current await — a streaming request, or a running
// shell command, whose child dies with the drop. What the turn // shell command, whose child dies with the drop. What the turn
// committed so far is already the session (the commit hook), // 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 mut abort = self.abort.listen(&key);
let turned = tokio::select! { let turned = tokio::select! {
output = agent.turn(prompt, &mut sink) => { output = agent.turn(prompt, &mut sink) => {
@@ -373,16 +375,14 @@ impl ClawHandler {
None => { None => {
// Cut, not failed: the thread gets no half-answer, and // Cut, not failed: the thread gets no half-answer, and
// the session keeps whatever the turn committed. // the session keeps whatever the turn committed.
ctx.session.core.driver_state = serde_json::to_value(agent.session()) ctx.session.core = agent.session().clone();
.map_err(|err| format!("session for {key} does not serialize: {err}"))?;
return Ok(Outcome::Superseded); return Ok(Outcome::Superseded);
} }
}; };
// Stash after the turn: a comment already posted and the turn's // Written back after the turn: a comment already posted and the
// work both survive a later failure. // turn's work both survive a later failure.
ctx.session.core.driver_state = serde_json::to_value(agent.session()) ctx.session.core = agent.session().clone();
.map_err(|err| format!("session for {key} does not serialize: {err}"))?;
Ok(Outcome::Handled) Ok(Outcome::Handled)
} }
@@ -408,9 +408,10 @@ impl ClawHandler {
.map_err(|err| format!("an inbox item for {key} does not decode: {err}")) .map_err(|err| format!("an inbox item for {key} does not decode: {err}"))
} }
/// The agent for this dispatch: the stashed session resumed when the /// The agent for this dispatch: the record's conversation resumed
/// key has history, a fresh one otherwise. A stash that does not parse /// when the key has one, a fresh agent otherwise. A `driver_state`
/// fails the run loudly — silently resetting would re-orient the agent /// carrying a session stash that does not parse fails the run
/// loudly — silently resetting would re-orient the agent
/// mid-conversation without anyone knowing. /// mid-conversation without anyone knowing.
fn resume( fn resume(
&self, &self,
@@ -421,14 +422,10 @@ impl ClawHandler {
) -> Result<HostAgent, String> { ) -> Result<HostAgent, String> {
let (provider, model) = self.backends.current(); let (provider, model) = self.backends.current();
let config = self.agent_config(provider, &model, workspace, key, target)?; let config = self.agent_config(provider, &model, workspace, key, target)?;
let agent = match &ctx.session.core.driver_state { let agent = match crate::interactive::resume_session(&ctx.session.core, key)? {
// A never-dispatched key carries no stash: start clean. // A never-dispatched key carries no conversation: start clean.
serde_json::Value::Null => HostAgent::new(config), None => HostAgent::new(config),
stashed => { Some(session) => HostAgent::from_session(config, session),
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)
}
}; };
agent.map_err(|err| format!("cannot start the coding agent for {key}: {err}")) agent.map_err(|err| format!("cannot start the coding agent for {key}: {err}"))
} }
+15 -1
View File
@@ -1435,7 +1435,21 @@ fn stashed_history(
let leased = record let leased = record
.as_ref() .as_ref()
.is_some_and(|record| record.state == rhema_rsd::KeyState::Leased); .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) crate::thread::page(&events, before, limit)
} }
None => (Vec::new(), false), None => (Vec::new(), false),
+251 -57
View File
@@ -31,16 +31,22 @@
//! implicit one. //! implicit one.
//! //!
//! Continuity rides the dispatcher exactly as the forge handler's does: //! Continuity rides the dispatcher exactly as the forge handler's does:
//! the whole [`rhema_core::Session`] is stashed into //! the record's own core session is the conversation. The commit hook
//! `ctx.session.core.driver_state` before the run returns and restored //! writes it after every step and the round's end writes it back whole,
//! from there on the next dispatch (`Null` means fresh). The session is //! so a turn cut mid-flight — a restart, an OOM kill, a lease swept —
//! the record of the conversation — the context the model returns to — //! leaves the live history where the next dispatch resumes it, its
//! and the hub's record is the transcript: the stream is replayable, //! dangling call revived at turn entry. A record from before the core
//! the live deltas are the only best-effort part left. Commit-before- //! was trusted carries a serialized [`rhema_core::Session`] nested in
//! execute rides it too: the run installs the context's commit hook, so //! `ctx.session.core.driver_state` instead; [`resume_session`] reads
//! the intent is in the store before the first tool runs, and a //! that copy (its core lags the conversation by a round) and falls back
//! crash-left dangling call revives before the turn — safe tools re-run, //! to the core for everything newer. The session is the record of the
//! the rest report interrupted. //! 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, //! Deterministic setup first (spec §1, §8): the allowlist — permissive,
//! v1's starting point — and the resolver chain are assembled before //! 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: //! **Aborting** rides the same interrupt and ends instead of looping:
//! a signal from the abort registry ([`crate::abort`]) drops the turn //! a signal from the abort registry ([`crate::abort`]) drops the turn
//! future at its await, the dangling calls close, the session stashes, //! future at its await, the dangling calls close, the session writes
//! and the dispatch releases as superseded with the `aborted` outcome //! back, and the dispatch releases as superseded with the `aborted`
//! on the stream. Unlike a steer signal, an abort carries no inbox //! outcome on the stream. Unlike a steer signal, an abort carries no inbox
//! message, so a pending abort is honored between rounds, not cleared //! message, so a pending abort is honored between rounds, not cleared
//! with the stale steer signals. //! with the stale steer signals.
@@ -544,12 +550,12 @@ impl InteractiveHandler {
Arc::new(ResolverChain::new(resolvers)) Arc::new(ResolverChain::new(resolvers))
} }
/// One round: drain, restore, turn, stash, reply. The turn runs /// One round: drain, restore, turn, write back, reply. The turn
/// under the steer/abort select, so a round that was interrupted /// runs under the steer/abort select, so a round that was
/// comes back as [`Round::Steered`] or [`Round::Aborted`] with the /// interrupted comes back as [`Round::Steered`] or [`Round::Aborted`]
/// session stashed and the dangling calls closed — steered, the /// with the session written back and the dangling calls closed —
/// caller owes the inbox another round; aborted, the caller ends /// steered, the caller owes the inbox another round; aborted, the
/// the chain. /// caller ends the chain.
async fn dispatch( async fn dispatch(
&self, &self,
ctx: &mut SessionContext, ctx: &mut SessionContext,
@@ -722,13 +728,10 @@ impl InteractiveHandler {
input input
}; };
let mut agent = match &ctx.session.core.driver_state { let mut agent = match resume_session(&ctx.session.core, &key)? {
// A never-dispatched key carries no stash: start clean. // A never-dispatched key carries no conversation: start clean.
Value::Null => self.agent(&ctx.key)?, None => self.agent(&ctx.key)?,
stashed => { Some(session) => self.resume(&ctx.key, session)?,
let session = restore_session(stashed, &key)?;
self.resume(&ctx.key, session)?
}
}; };
adopt_transcript(&mut agent); adopt_transcript(&mut agent);
// Commit-before-execute: the intent is in the store before the // 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); close_orphaned_calls(&mut agent.session_mut().history);
} }
save_transcript(&mut agent); 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 // the subscriber never sees the stream — and a steered chain
// dies between rounds, the steered state is what resumes. // dies between rounds, the steered state is what resumes. The
ctx.session.core.driver_state = serde_json::to_value(agent.session()) // commit hook wrote the same core after every step, so a turn
.map_err(|err| format!("session for {key} does not serialize: {err}"))?; // cut mid-flight leaves this state behind either way.
ctx.session.core = agent.session().clone();
match finished { match finished {
Some(Ok(output)) => Ok(Round::Done(Ok(final_text(&output.message)))), Some(Ok(output)) => Ok(Round::Done(Ok(final_text(&output.message)))),
Some(Err(reason)) => Err(reason), Some(Err(reason)) => Err(reason),
@@ -928,7 +933,7 @@ impl InteractiveHandler {
} }
/// One dispatch round's shape. A steered or aborted round ended in an /// 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 /// the caller owes the inbox another round on the same lease, same
/// session, same stream; aborted, the caller ends the chain. /// session, same stream; aborted, the caller ends the chain.
enum Round { enum Round {
@@ -1003,6 +1008,36 @@ fn save_transcript(agent: &mut HostAgent) {
state[TRANSCRIPT_STATE_KEY] = value; 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<Option<Session>, 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 /// The stashed conversation: a serialized [`Session`], `Null` meaning
/// fresh. A stash that does not parse is loud — silently resetting would /// fresh. A stash that does not parse is loud — silently resetting would
/// re-orient the agent mid-conversation without anyone knowing. /// re-orient the agent mid-conversation without anyone knowing.
@@ -1983,6 +2018,68 @@ mod tests {
assert!(err.contains("does not parse"), "{err}"); 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 /// A session stashed before paste spans existed carries the embedded
/// form in its prompts; the restore pass rewrites it so a provider /// 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. /// 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 /// 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] #[tokio::test]
async fn a_dispatch_drains_replies_and_stashes_the_conversation() { async fn a_dispatch_drains_replies_and_stashes_the_conversation() {
let store = Arc::new(ClawStore::in_memory().expect("store opens")); 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 /// 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 same lease: the interrupted turn closes on the stream with
/// the `steered` outcome, the steered question streams as its own /// 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. /// the one answer that replaced the interrupted generation.
#[tokio::test] #[tokio::test]
async fn a_steered_message_cuts_the_live_turn_and_runs_as_the_next_round() { 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) let record = rhema_rsd::Store::load(volatile.as_ref(), &key)
.expect("the record loads") .expect("the record loads")
.expect("the key has a record"); .expect("the key has a record");
let stashed: Session = let session: Session = record.session.expect("a session").core;
serde_json::from_value(record.session.expect("a session").core.driver_state) let turns: Vec<(CoreRole, &str)> = session
.expect("the stash parses");
let turns: Vec<(CoreRole, &str)> = stashed
.history .history
.iter() .iter()
.filter_map(|message| match &message.content[0] { .filter_map(|message| match &message.content[0] {
@@ -2369,10 +2465,8 @@ mod tests {
let record = rhema_rsd::Store::load(volatile.as_ref(), &key) let record = rhema_rsd::Store::load(volatile.as_ref(), &key)
.expect("the record loads") .expect("the record loads")
.expect("the key has a record"); .expect("the key has a record");
let stashed: Session = let session: Session = record.session.expect("a session").core;
serde_json::from_value(record.session.expect("a session").core.driver_state) let turns: Vec<(CoreRole, &str)> = session
.expect("the stash parses");
let turns: Vec<(CoreRole, &str)> = stashed
.history .history
.iter() .iter()
.filter_map(|message| match &message.content[0] { .filter_map(|message| match &message.content[0] {
@@ -2788,9 +2882,12 @@ mod tests {
assert!(!bootstrap.needs_onboarding(), "both files exist"); 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] #[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; use rhema_rsd::Store;
let store = Arc::new(ClawStore::in_memory().expect("store opens")); let store = Arc::new(ClawStore::in_memory().expect("store opens"));
@@ -2844,10 +2941,8 @@ mod tests {
.load(&key) .load(&key)
.expect("the record loads") .expect("the record loads")
.expect("the key has a record"); .expect("the key has a record");
let stashed: Session = let session: Session = record.session.expect("a session").core;
serde_json::from_value(record.session.expect("a session").core.driver_state) let roles: Vec<(CoreRole, String)> = session
.expect("the stash parses back into a session");
let roles: Vec<(CoreRole, String)> = stashed
.history .history
.iter() .iter()
.filter_map(|message| match &message.content[0] { .filter_map(|message| match &message.content[0] {
@@ -2862,6 +2957,109 @@ mod tests {
(CoreRole::Assistant, "hi back".to_owned()), (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 /// 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].title, "claw");
assert_eq!(pending[0].body, "the bread is done."); 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. // verbatim, under the delivery-contract framing.
let record = backing let record = backing
.load(&Key::from("task:1")) .load(&Key::from("task:1"))
.expect("the record loads") .expect("the record loads")
.expect("the key has a record"); .expect("the key has a record");
let stashed: Session = let session: Session = record.session.expect("a session").core;
serde_json::from_value(record.session.expect("a session").core.driver_state) let user_texts: Vec<&str> = session
.expect("the stash parses");
let user_texts: Vec<&str> = stashed
.history .history
.iter() .iter()
.filter_map(|message| match &message.content[0] { .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 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. // the evening's message, then the framed wake.
use rhema_rsd::Store; use rhema_rsd::Store;
let record = backing let record = backing
.load(&key) .load(&key)
.expect("the record loads") .expect("the record loads")
.expect("the key has a record"); .expect("the key has a record");
let stashed: Session = let session: Session = record.session.expect("a session").core;
serde_json::from_value(record.session.expect("a session").core.driver_state) let user_texts: Vec<String> = session
.expect("the stash parses");
let user_texts: Vec<String> = stashed
.history .history
.iter() .iter()
.filter_map(|message| match &message.content[0] { .filter_map(|message| match &message.content[0] {
+3 -3
View File
@@ -6,9 +6,9 @@
//! `CodingAgent` turn over an instance's workspace: prompt in, final //! `CodingAgent` turn over an instance's workspace: prompt in, final
//! text out, run off the chat turn by the jobs dispatcher (see //! text out, run off the chat turn by the jobs dispatcher (see
//! [`crate::jobs`]). The conversation carries across a job boundary in //! [`crate::jobs`]). The conversation carries across a job boundary in
//! the instance row's session blob — the same stash the forge handler //! the instance row's session blob — the same conversation the forge
//! keeps in the dispatcher's `driver_state`, keyed by instance instead //! handler keeps in its record's session, keyed by instance instead of
//! of by thread, so "run the tests" after "fix the lint" continues the //! by thread, so "run the tests" after "fix the lint" continues the
//! same coding session. //! same coding session.
//! //!
//! Two invariants the schema itself holds: at most one **live** job //! Two invariants the schema itself holds: at most one **live** job
+8 -16
View File
@@ -1,9 +1,8 @@
//! Session continuity across processes: two `--once` passes over the same //! Session continuity across processes: two `--once` passes over the same
//! SQLite db and the same thread. The first pass's conversation is //! SQLite db and the same thread. The first pass's conversation lands in
//! stashed into the dispatcher's `driver_state`; the second pass's agent //! the record's own session; the second pass's agent resumes from it —
//! resumes from it — the MockProvider cannot record its requests, so the //! the MockProvider cannot record its requests, so the record itself is
//! stashed state itself is the proof: the restored history carries both //! the proof: the restored history carries both exchanges.
//! exchanges.
use std::sync::Arc; use std::sync::Arc;
@@ -207,7 +206,7 @@ async fn the_second_dispatch_resumes_the_first_conversation() {
assert_eq!(second.outcomes, vec![Outcome::Handled]); assert_eq!(second.outcomes, vec![Outcome::Handled]);
drop(second_post); 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. // conversation — a fresh agent would hold only its own exchange.
let store = SqliteStore::open(dir.path().join("dispatch.db")).expect("db reopens"); let store = SqliteStore::open(dir.path().join("dispatch.db")).expect("db reopens");
let record = store let record = store
@@ -215,15 +214,8 @@ async fn the_second_dispatch_resumes_the_first_conversation() {
.expect("the record loads") .expect("the record loads")
.expect("the key has a record"); .expect("the key has a record");
assert_eq!(record.state, KeyState::Idle); assert_eq!(record.state, KeyState::Idle);
let stashed: Session = serde_json::from_value( let session: Session = record.session.expect("the key has a session").core;
record let user_prompts: Vec<&str> = session
.session
.expect("the key has a session")
.core
.driver_state,
)
.expect("the stash parses back into a session");
let user_prompts: Vec<&str> = stashed
.history .history
.iter() .iter()
.filter_map(|message| match &message.content[0] { .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?"), user_prompts[1].contains("any progress?"),
"pass two's prompt carried the new comment" "pass two's prompt carried the new comment"
); );
let replies: Vec<&str> = stashed let replies: Vec<&str> = session
.history .history
.iter() .iter()
.filter_map(|message| match &message.content[0] { .filter_map(|message| match &message.content[0] {
+45 -21
View File
@@ -356,17 +356,15 @@ async fn chat_streams_turns_and_remembers_across_messages() {
.expect("the second message accepts"); .expect("the second message accepts");
read_until(&mut stream, &mut seen, "still on it").await; 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 store = SqliteStore::open(dir.path().join("dispatch.db")).expect("db reopens");
let key = ResourceKey::from("interactive:web"); let key = ResourceKey::from("interactive:web");
let record = store let record = store
.load(&key) .load(&key)
.expect("the record loads") .expect("the record loads")
.expect("the key has a record"); .expect("the key has a record");
let stashed: Session = let session: Session = record.session.expect("a session").core;
serde_json::from_value(record.session.expect("a session").core.driver_state) let turns: Vec<(Role, &str)> = session
.expect("the stash parses");
let turns: Vec<(Role, &str)> = stashed
.history .history
.iter() .iter()
.filter_map(|message| match &message.content[0] { .filter_map(|message| match &message.content[0] {
@@ -496,10 +494,8 @@ async fn a_message_into_a_live_turn_steers_it() {
.load(&key) .load(&key)
.expect("the record loads") .expect("the record loads")
.expect("the key has a record"); .expect("the key has a record");
let stashed: Session = let session: Session = record.session.expect("a session").core;
serde_json::from_value(record.session.expect("a session").core.driver_state) let turns: Vec<(Role, &str)> = session
.expect("the stash parses");
let turns: Vec<(Role, &str)> = stashed
.history .history
.iter() .iter()
.filter_map(|message| match &message.content[0] { .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 /// 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 /// text with the `rhema-code` annotation beside it, and no mark ever
/// crosses the wire. /// crosses the wire.
#[tokio::test] #[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 provider = Arc::new(MockProvider::new([reply("on it")]));
let dir = tempfile::tempdir().expect("tempdir"); let dir = tempfile::tempdir().expect("tempdir");
let daemon = Daemon::build( 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}"); 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. // the text and the annotation that outlives the turn.
let store = SqliteStore::open(dir.path().join("dispatch.db")).expect("db reopens"); let store = SqliteStore::open(dir.path().join("dispatch.db")).expect("db reopens");
let key = ResourceKey::from("interactive:web"); 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) .load(&key)
.expect("the record loads") .expect("the record loads")
.expect("the key has a record"); .expect("the key has a record");
let stashed: Session = let session: Session = record.session.expect("a session").core;
serde_json::from_value(record.session.expect("a session").core.driver_state) let ask = session
.expect("the stash parses");
let ask = stashed
.history .history
.iter() .iter()
.find(|message| message.role == Role::User) .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).len(), 1);
assert_eq!(rhema_claw::paste::spans(ask)[0].start, 12); assert_eq!(rhema_claw::paste::spans(ask)[0].start, 12);
assert_eq!(rhema_claw::paste::spans(ask)[0].end, 38); 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")) .load(&ResourceKey::from("interactive:web"))
.expect("the record loads") .expect("the record loads")
.expect("the key has a record"); .expect("the key has a record");
let stashed: Session = let session: Session = record.session.expect("a session").core;
serde_json::from_value(record.session.expect("a session").core.driver_state) let prompts: Vec<&str> = session
.expect("the stash parses");
let prompts: Vec<&str> = stashed
.history .history
.iter() .iter()
.filter_map(|message| match &message.content[0] { .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[2]["event"]["code"], 1);
assert_eq!(events[4]["event"]["reply"], "The build is red; rerunning."); 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, // Read-only for real: the message route still refuses the prefix,
// and the stream route refuses it too — a client that followed // and the stream route refuses it too — a client that followed
// `read_only=false` would retry a 400 forever. // `read_only=false` would retry a 400 forever.