From 6b2624f0ba912b8b7b32ca87dfdbcef0dc2ef445 Mon Sep 17 00:00:00 2001 From: Valentin Haudiquet Date: Wed, 2 Dec 2026 18:01:38 +0100 Subject: [PATCH] room: advance the steer cursor after the checkpoint The steering source seeded from `config.absorbed_seq`, which the runner loaded before the boundary pass advanced the row. When the burst that started the turn held a chat line before the mention, the first drain read that line back, appended it a second time, and moved the row backwards, so the next boundary pass appended the mention again. The row now has one writer. `RoomSteering::drain` keeps the cursor in memory, `commit` writes it after `save_session` succeeds, and the boundary pass hands its own cursor down in the config the turn reads. That is the order the boundary pass already uses, append then checkpoint then advance, and the framework's contract for a steering source: a line that comes back is deduped within the turn, a line retired too early is gone. A failed commit leaves the row behind, so a line can repeat, and it reports the failure instead of swallowing it. The drain rule moves to `steerable`, a pure function over the messages, and four tests cover it, the cursor handoff, and the row's waits. --- AGENTS.md | 5 +- specs/rhema-together.md | 15 ++- src/room/agent.rs | 7 +- src/room/runner.rs | 279 +++++++++++++++++++++++++++++++++++----- 4 files changed, 263 insertions(+), 43 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 32a45b0..d4ca657 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -84,8 +84,9 @@ web/app/ Nuxt 4 SPA (no SSR) the turn future (turn-level steering) and starts a new turn over the committed session. A message without a mention never drops anything: `runner::RoomSteering` hands it to the framework's steering hook, which - appends it at the next step boundary and advances `absorbed_seq` so the - next boundary pass cannot repeat it. Do not drop the room task. + appends it at the next step boundary; the turn advances `absorbed_seq` + once that session is saved, so the next boundary pass cannot repeat it. + Do not drop the room task. - The preview host label is `r-p--.` for a port, or `r-s--.` for a static target. The HMAC covers the target and expiry with a key diff --git a/specs/rhema-together.md b/specs/rhema-together.md index 735a87e..65b4a35 100644 --- a/specs/rhema-together.md +++ b/specs/rhema-together.md @@ -194,11 +194,16 @@ The mid-turn half of that is the framework's steering hook (`HostAgentConfig::steering`), not a step-level drop: the turn's `RoomSteering` source hands the driver one User-role line per drain at a step boundary, so a member can correct the agent while it works without -the step in flight dying. It stops at the first line it cannot carry — -a mention, which the drop path owns, or a message with images, which a -line cannot — and leaves the cursor there, so the boundary pass appends -them in the log's order. What steering still cannot do is stop a running -command: only the mention drop does that, and only between steps. +the step in flight dying. It stops at the first line it cannot carry, a +mention (the drop path owns that one) or a message with images (a line +of text cannot hold them), and leaves the cursor there, so the boundary +pass appends them in the log's order. The source only reads that +cursor. The turn writes it after the session holding the drained lines +is saved, the order the boundary pass already uses: append, checkpoint, +advance. A crash before the checkpoint repeats a line at worst, and the +framework's per-turn dedupe drops the repeat. What steering still cannot +do is stop a running command: only the mention drop does that, and only +between steps. A burst of mentions that lands before the first drop completes all goes into the same restart, in order, one message each. Nothing is folded. diff --git a/src/room/agent.rs b/src/room/agent.rs index b4befef..6837068 100644 --- a/src/room/agent.rs +++ b/src/room/agent.rs @@ -29,6 +29,9 @@ pub struct TurnConfig { /// The model's stored vision fact; `None` is unknown, not no. pub supports_vision: Option, pub max_turn_steps: u32, + /// The cursor the turn starts from. The boundary pass moves it to + /// the last line it appended, so the turn's steering source reads on + /// from there and never over what is already in the history. pub absorbed_seq: i64, pub seeded: bool, pub owner_name: String, @@ -308,7 +311,7 @@ pub fn build_agent( state: &Shared, config: &TurnConfig, session: Session, - steering: Option>, + steering: Arc, ) -> AppResult { let sandbox = build_sandbox(state, config)?; let executor = Arc::new(ShellSandbox::new(Arc::new(sandbox))); @@ -359,7 +362,7 @@ pub fn build_agent( shell_env: Default::default(), transcript: Some(Default::default()), summary_worker: None, - steering, + steering: Some(steering), home: None, environment: Some(rhema_host_agent::remote_notice( "ssh", diff --git a/src/room/runner.rs b/src/room/runner.rs index 675a100..eed8255 100644 --- a/src/room/runner.rs +++ b/src/room/runner.rs @@ -40,7 +40,7 @@ pub async fn run(state: Shared, room: String, mut rx: UnboundedReceiver) { continue; } loop { - let config = match agent::load_turn_config(&state, &room) { + let mut config = match agent::load_turn_config(&state, &room) { Ok(config) => config, Err(err) => { notice(&state, &room, "error", err.message); @@ -87,11 +87,18 @@ pub async fn run(state: Shared, room: String, mut rx: UnboundedReceiver) { pending_mention = false; break; } - let last = pending.last().map(|message| message.seq).unwrap_or(0); + // The batch's cursor, in the row and in the config the turn + // reads, so the turn's steering source starts after what this + // pass just appended instead of reading it back. + let last = pending + .last() + .map(|message| message.seq as i64) + .unwrap_or(config.absorbed_seq); let _ = state.db.conn().execute( "UPDATE rooms SET absorbed_seq = ?1 WHERE id = ?2", - rusqlite::params![last as i64, room], + rusqlite::params![last, room], ); + config.absorbed_seq = last; pending_mention = false; let trigger = pending .iter() @@ -124,8 +131,12 @@ async fn run_turn( rx: &mut UnboundedReceiver, pending_mention: &mut bool, ) { - let steering = steering_for(state, room, config); - let mut agent = match agent::build_agent(state, config, session, Some(steering)) { + let steering = Arc::new(RoomSteering::new( + state.clone(), + room.to_owned(), + config.absorbed_seq, + )); + let mut agent = match agent::build_agent(state, config, session, steering.clone()) { Ok(agent) => agent, Err(err) => { notice(state, room, "error", err.message); @@ -170,6 +181,8 @@ async fn run_turn( let session = agent.session().clone(); if let Err(err) = agent::save_session(state, room, &session) { notice(state, room, "error", err.message); + } else { + steering.commit(); } let data = match outcome { Some(Ok(output)) => { @@ -224,34 +237,57 @@ async fn run_turn( /// /// Neither is lost: the turn loop's boundary pass reads from the same /// `absorbed_seq` cursor and appends whatever the drain left behind. +/// +/// The source is a query over that cursor and never writes it. The turn +/// commits what it drained once the session holding those lines is +/// saved, so the row can lag behind the history but never lead it, which +/// is the framework's own contract for [`Steering::drain`]: a line that +/// comes back is a line the driver dedupes away, a line retired too early +/// is gone. struct RoomSteering { state: Shared, room: String, - /// The room's `absorbed_seq`, as the history and the log agree on it. - /// Shared with the turn loop through the row: a line drained here is - /// already appended, so the next boundary pass must not append it - /// again. + /// The row's cursor when the turn started, the boundary pass's last + /// append. The source never goes behind it: those lines are in the + /// history, and reading them again would append them twice. + seeded: i64, + /// The cursor after this turn's drains. Held here, not in the row: + /// only [`RoomSteering::commit`] writes it, once the session that + /// holds the lines is saved. absorbed: AtomicI64, } impl RoomSteering { - fn new(state: Shared, room: String, absorbed: i64) -> Self { + fn new(state: Shared, room: String, seeded: i64) -> Self { Self { state, room, - absorbed: AtomicI64::new(absorbed), + seeded, + absorbed: AtomicI64::new(seeded), } } - /// Moves the cursor in the row, and only then in memory, so a failed - /// write re-announces the line next turn instead of dropping it. - fn advance(&self, seq: i64) { + /// Writes the drained cursor to the room's row, the boundary pass's + /// order: append, checkpoint, advance. A crash before the checkpoint + /// leaves the row behind, so the next boundary pass re-announces a + /// line rather than losing it, and the framework's per-turn dedupe + /// keeps that repeat out of one turn's history. + fn commit(&self) { + let absorbed = self.absorbed.load(Ordering::SeqCst); + if absorbed == self.seeded { + return; + } let written = self.state.db.conn().execute( "UPDATE rooms SET absorbed_seq = ?1 WHERE id = ?2", - rusqlite::params![seq, self.room], + rusqlite::params![absorbed, self.room], ); - if written.is_ok() { - self.absorbed.store(seq, Ordering::SeqCst); + if let Err(err) = written { + notice( + &self.state, + &self.room, + "error", + format!("cannot advance the room's message cursor: {err}"), + ); } } } @@ -262,29 +298,30 @@ impl Steering for RoomSteering { let Ok(messages) = pending_messages(&self.state, &self.room, absorbed) else { return Vec::new(); }; - let mut lines = Vec::new(); - let mut last = absorbed; - for message in messages { - if message.mentions || !message.attachments.is_empty() { - break; - } - lines.push(format!("{}: {}", message.author_name, message.text)); - last = message.seq as i64; - } + let (lines, last) = steerable(&messages, absorbed); if last != absorbed { - self.advance(last); + self.absorbed.store(last, Ordering::SeqCst); } lines } } -/// The turn's steering source, over the cursor the turn started from. -fn steering_for(state: &Shared, room: &str, config: &TurnConfig) -> Arc { - Arc::new(RoomSteering::new( - state.clone(), - room.to_owned(), - config.absorbed_seq, - )) +/// The lines one drain can carry, and the cursor after them: everything +/// in log order up to the first line it cannot carry, a mention (the drop +/// path owns that one) or a message with images (a line of text cannot +/// hold them). The caller leaves the rest to the next boundary pass, so +/// the room log is appended in its own order. +fn steerable(messages: &[RoomMessage], from: i64) -> (Vec, i64) { + let mut lines = Vec::new(); + let mut last = from; + for message in messages { + if message.mentions || !message.attachments.is_empty() { + break; + } + lines.push(format!("{}: {}", message.author_name, message.text)); + last = message.seq as i64; + } + (lines, last) } fn pending_messages(state: &Shared, room: &str, absorbed: i64) -> AppResult> { @@ -485,3 +522,177 @@ fn truncate(text: &str, max: usize) -> String { } format!("{}\n[truncated]", &text[..end]) } + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + + use super::*; + use crate::models::Attachment; + + fn line(seq: u64, text: &str, mentions: bool) -> RoomMessage { + RoomMessage { + seq, + id: format!("m{seq}"), + author_id: Some("a1".into()), + author_name: "ana".into(), + author_kind: "human".into(), + text: text.into(), + mentions, + created_at: 0, + attachments: Vec::new(), + } + } + + fn image(seq: u64, text: &str) -> RoomMessage { + RoomMessage { + attachments: vec![Attachment { + id: format!("att{seq}"), + mime: "image/png".into(), + size: 40, + }], + ..line(seq, text, false) + } + } + + /// A state over a fresh database holding one account and one room. + fn room(absorbed: i64) -> (Shared, PathBuf) { + let dir = std::env::temp_dir().join(format!("rhema-steering-{}", random_id(10))); + let db = crate::db::Db::open(&dir.join("test.db")).expect("db"); + let secrets = + crate::crypto::Secrets::load_or_create(&dir.join("test.key")).expect("secrets"); + let state = Arc::new(crate::state::AppState { + config: crate::config::Config::default(), + db, + secrets, + hub: crate::state::Hub::default(), + rooms: Default::default(), + workers: Default::default(), + presence: Default::default(), + logins: Default::default(), + }); + let conn = state.db.conn(); + conn.execute( + "INSERT INTO accounts (id, handle, display_name, created_at) + VALUES ('a1', 'ana', 'Ana', 1)", + [], + ) + .expect("account"); + conn.execute( + "INSERT INTO rooms (id, name, owner_id, workspace, absorbed_seq, created_at) + VALUES ('r1', 'Room', 'a1', 'ws', ?1, 1)", + rusqlite::params![absorbed], + ) + .expect("room"); + drop(conn); + (state, dir) + } + + /// Posts one chat line the way the API does: the event's sequence is + /// the message's own, and the cursor reads that field. + fn post(state: &Shared, mut message: RoomMessage) -> i64 { + let seq = state.hub.next_seq(&state.db, "r1"); + message.seq = seq; + let data = serde_json::to_value(&message).expect("json"); + state + .hub + .insert(&state.db, "r1", seq, "message", &data) + .expect("event"); + seq as i64 + } + + fn cursor(state: &Shared) -> i64 { + state + .db + .scalar("SELECT absorbed_seq FROM rooms WHERE id = 'r1'", []) + .expect("cursor") + } + + #[test] + fn a_drain_stops_at_the_first_line_it_cannot_carry() { + let messages = [ + line(4, "one", false), + image(5, "two"), + line(6, "three", false), + ]; + assert_eq!(steerable(&messages, 3), (vec!["ana: one".to_owned()], 4)); + + let messages = [ + line(4, "one", false), + line(5, "@rhema two", true), + line(6, "three", false), + ]; + assert_eq!(steerable(&messages, 3), (vec!["ana: one".to_owned()], 4)); + + let (lines, cursor) = steerable(&[line(4, "@rhema two", true)], 3); + assert!(lines.is_empty()); + assert_eq!(cursor, 3, "a drain that carries nothing moves nothing"); + } + + #[test] + fn a_drain_seeded_at_the_boundary_pass_reads_nothing_back() { + let (state, dir) = room(0); + post(&state, line(0, "check the other branch", false)); + let boundary = post(&state, line(0, "@rhema go", true)); + state + .db + .conn() + .execute( + "UPDATE rooms SET absorbed_seq = ?1 WHERE id = 'r1'", + rusqlite::params![boundary], + ) + .expect("boundary cursor"); + + let steering = RoomSteering::new(state.clone(), "r1".into(), boundary); + assert!( + steering.drain().is_empty(), + "the batch the boundary pass appended is already in the history" + ); + steering.commit(); + assert_eq!(cursor(&state), boundary); + + drop(steering); + drop(state); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_drain_holds_the_row_until_the_turn_commits() { + let (state, dir) = room(0); + let first = post(&state, line(0, "check the other branch", false)); + let steering = RoomSteering::new(state.clone(), "r1".into(), 0); + + assert_eq!(steering.drain(), ["ana: check the other branch"]); + assert_eq!(cursor(&state), 0, "the row waits for the checkpoint"); + assert!( + steering.drain().is_empty(), + "a line the turn took does not come back" + ); + + steering.commit(); + assert_eq!(cursor(&state), first); + + drop(steering); + drop(state); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_mention_left_to_the_boundary_pass_is_not_committed() { + let (state, dir) = room(0); + post(&state, line(0, "@rhema go", true)); + let steering = RoomSteering::new(state.clone(), "r1".into(), 0); + + assert!(steering.drain().is_empty()); + steering.commit(); + assert_eq!( + cursor(&state), + 0, + "a drain that took nothing commits nothing" + ); + + drop(steering); + drop(state); + let _ = std::fs::remove_dir_all(&dir); + } +}