aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-cli / src / turn_journal.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! sovereign-core #665: persist-before-act for the `aien` chat loop. |
| 17 | //! |
| 18 | //! Mechanism after Hermes Agent (Nous Research, MIT, commit 5480918), |
| 19 | //! re-implemented; no code copied. Same rule as the Aienux continuity commit |
| 20 | //! (aienos ADR 0016): advance the record, then act. |
| 21 | //! |
| 22 | //! Every message the loop adds, and every tool request, is appended to an |
| 23 | //! append-only, hash-chained journal and flushed to disk *before* the loop acts |
| 24 | //! on it. A tool runs only after its request is on disk. If the process dies |
| 25 | //! between the request and the result, a resumed session finds the request with |
| 26 | //! no result: read-only tools are run again, and anything that may have changed |
| 27 | //! the world is reported to the model as "not known whether it happened" and is |
| 28 | //! never run a second time. So nothing is lost and nothing is done twice. |
| 29 | //! |
| 30 | //! Shape (ADR 0024): the pure part ([`replay`], [`resume_steps`], |
| 31 | //! [`effect_of`], [`tool_response_message`]) has no I/O and works on |
| 32 | //! content-addressed records, so it can move to Omega later. [`Journal`] is the |
| 33 | //! only edge that touches the disk. |
| 34 | //! |
| 35 | //! File format, one JSON object per line: |
| 36 | //! `{"v":1,"prev":<digest of previous line or "genesis">,"digest":<hex>,"record":{...}}` |
| 37 | //! where `digest = sha256("AIEN_TURN_JOURNAL_V1\n" + prev + "\n" + record bytes)`. |
| 38 | //! A torn last line (the process died mid-write) is dropped on resume; damage |
| 39 | //! anywhere else is refused, never guessed around. |
| 40 | |
| 41 | use serde::{Deserialize, Serialize}; |
| 42 | use serde_json::{json, Value}; |
| 43 | use sha2::{Digest, Sha256}; |
| 44 | use std::fs::{File, OpenOptions}; |
| 45 | use std::io::Write; |
| 46 | use std::path::{Path, PathBuf}; |
| 47 | |
| 48 | const DOMAIN: &str = "AIEN_TURN_JOURNAL_V1"; |
| 49 | const GENESIS: &str = "genesis"; |
| 50 | |
| 51 | /// Whether running a tool again could change the world a second time. |
| 52 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 53 | #[serde(rename_all = "snake_case")] |
| 54 | pub enum Effect { |
| 55 | /// Only reads; safe to run again after a crash. |
| 56 | ReadOnly, |
| 57 | /// May write, run commands, spend, or talk to the outside. Never re-run blindly. |
| 58 | Effectful, |
| 59 | } |
| 60 | |
| 61 | /// Every name `dispatch_tool_with` accepts, and whether running it again could |
| 62 | /// change the world a second time. Aliases share the arm they dispatch through: |
| 63 | /// `list_directory` is the same read as `list_dir`. A name that is not here, |
| 64 | /// including one the model invented, is effectful, so resume will not run it |
| 65 | /// again. Adding a tool to the dispatcher without a row here fails |
| 66 | /// `every_dispatched_tool_is_classified`. |
| 67 | pub const TOOL_EFFECTS: &[(&str, Effect)] = &[ |
| 68 | ("run_command", Effect::Effectful), |
| 69 | ("view_file", Effect::ReadOnly), |
| 70 | ("write_to_file", Effect::Effectful), |
| 71 | ("create_file", Effect::Effectful), |
| 72 | ("replace_file_content", Effect::Effectful), |
| 73 | ("edit_file", Effect::Effectful), |
| 74 | ("list_dir", Effect::ReadOnly), |
| 75 | ("list_directory", Effect::ReadOnly), |
| 76 | ("grep_search", Effect::ReadOnly), |
| 77 | ("search_directory", Effect::ReadOnly), |
| 78 | ("find_by_name", Effect::ReadOnly), |
| 79 | ("find_file", Effect::ReadOnly), |
| 80 | ("ask_question", Effect::Effectful), |
| 81 | ("create_dir", Effect::Effectful), |
| 82 | ("crumb", Effect::Effectful), |
| 83 | ("skill", Effect::Effectful), |
| 84 | ("skills", Effect::Effectful), |
| 85 | ("context7", Effect::Effectful), |
| 86 | ("goal", Effect::Effectful), |
| 87 | ("cortex", Effect::Effectful), |
| 88 | ("vault", Effect::Effectful), |
| 89 | ("walkthrough", Effect::Effectful), |
| 90 | ("hive", Effect::Effectful), |
| 91 | ("socratic", Effect::Effectful), |
| 92 | ("socratic_inquiry", Effect::Effectful), |
| 93 | ("adapter", Effect::Effectful), |
| 94 | ("model_adapter", Effect::Effectful), |
| 95 | ("model_adapters", Effect::Effectful), |
| 96 | ("sandbox", Effect::Effectful), |
| 97 | ("browser", Effect::Effectful), |
| 98 | ("invoke_subagent", Effect::Effectful), |
| 99 | ("subagent", Effect::Effectful), |
| 100 | ("subagents", Effect::Effectful), |
| 101 | ]; |
| 102 | |
| 103 | /// Whether a tool may change the world a second time. See [`TOOL_EFFECTS`]. |
| 104 | pub fn effect_of(tool_name: &str) -> Effect { |
| 105 | TOOL_EFFECTS |
| 106 | .iter() |
| 107 | .find(|(name, _)| *name == tool_name) |
| 108 | .map(|(_, effect)| *effect) |
| 109 | .unwrap_or(Effect::Effectful) |
| 110 | } |
| 111 | |
| 112 | /// A tool request as it was recorded before it ran. |
| 113 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 114 | pub struct ToolIntent { |
| 115 | pub call_id: String, |
| 116 | pub name: String, |
| 117 | pub args: Value, |
| 118 | pub effect: Effect, |
| 119 | } |
| 120 | |
| 121 | /// One line of the journal. |
| 122 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 123 | #[serde(tag = "kind", rename_all = "snake_case")] |
| 124 | pub enum Record { |
| 125 | /// A message appended to the conversation, stored exactly as it is sent. |
| 126 | Message { message: Value }, |
| 127 | /// The whole conversation as it stands at the end of a turn (after any |
| 128 | /// compaction). Replay starts from the newest snapshot. |
| 129 | Snapshot { messages: Vec<Value> }, |
| 130 | /// A tool request, written and flushed before the tool runs. |
| 131 | ToolIntent(ToolIntent), |
| 132 | /// The result of a tool request, as the message the model will see. |
| 133 | ToolOutcome { call_id: String, message: Value }, |
| 134 | /// The turn ended early, with the reason the operator was shown. |
| 135 | TurnStop { reason: String }, |
| 136 | } |
| 137 | |
| 138 | /// Why a turn ended without finishing. Each one has a fixed name the operator sees. |
| 139 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 140 | pub enum TurnStop { |
| 141 | /// A message or tool request could not be written to disk, so nothing after it ran. |
| 142 | PersistFailed(String), |
| 143 | /// Compaction changed the live transcript, and the snapshot of that |
| 144 | /// transcript never reached disk. Callers must not take another model or |
| 145 | /// tool step. Resume loads the pre-compaction history, which is already |
| 146 | /// in the journal. |
| 147 | CompactionUnrecorded(String), |
| 148 | /// The recovery rules ran out (see `turn_recovery`). |
| 149 | Recovery(&'static str), |
| 150 | } |
| 151 | |
| 152 | impl TurnStop { |
| 153 | pub fn describe(&self) -> String { |
| 154 | match self { |
| 155 | TurnStop::PersistFailed(e) => format!( |
| 156 | "turn stopped (persist-failed): could not record the next step on disk ({e}); nothing after it was run" |
| 157 | ), |
| 158 | TurnStop::CompactionUnrecorded(e) => format!( |
| 159 | "turn stopped (compaction-unrecorded): the compacted history could not be recorded ({e}); nothing further was run on it. A resumed session loads the history from before this compaction" |
| 160 | ), |
| 161 | TurnStop::Recovery(reason) => format!("turn stopped ({reason})"), |
| 162 | } |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | /// What a journal says, read back. |
| 167 | #[derive(Debug, Clone, PartialEq, Default)] |
| 168 | pub struct Replay { |
| 169 | /// The conversation to continue from. |
| 170 | pub messages: Vec<Value>, |
| 171 | /// Tool requests that were recorded but have no recorded result. |
| 172 | pub in_doubt: Vec<ToolIntent>, |
| 173 | /// Reasons of turns that stopped early, oldest first. |
| 174 | pub stops: Vec<String>, |
| 175 | /// Digest of the last good line (`"genesis"` for an empty journal). |
| 176 | pub last_digest: String, |
| 177 | /// The next unused tool call number. |
| 178 | pub next_call: u64, |
| 179 | /// Bytes of the file that are whole, chained lines. |
| 180 | pub valid_len: usize, |
| 181 | /// True if a partly written last line was dropped. |
| 182 | pub torn_tail: bool, |
| 183 | } |
| 184 | |
| 185 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 186 | pub enum JournalError { |
| 187 | /// A line other than the last does not parse, or the chain is broken. |
| 188 | Corrupt { |
| 189 | line: usize, |
| 190 | why: String, |
| 191 | }, |
| 192 | Io(String), |
| 193 | } |
| 194 | |
| 195 | impl std::fmt::Display for JournalError { |
| 196 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 197 | match self { |
| 198 | JournalError::Corrupt { line, why } => { |
| 199 | write!(f, "journal damaged at line {line}: {why}") |
| 200 | } |
| 201 | JournalError::Io(e) => write!(f, "journal I/O: {e}"), |
| 202 | } |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | fn digest_of(prev: &str, record: &Value) -> String { |
| 207 | let body = serde_json::to_vec(record).unwrap_or_default(); |
| 208 | let mut h = Sha256::new(); |
| 209 | h.update(DOMAIN.as_bytes()); |
| 210 | h.update(b"\n"); |
| 211 | h.update(prev.as_bytes()); |
| 212 | h.update(b"\n"); |
| 213 | h.update(&body); |
| 214 | hex::encode(h.finalize()) |
| 215 | } |
| 216 | |
| 217 | fn call_number(call_id: &str) -> Option<u64> { |
| 218 | call_id.strip_prefix("call-")?.parse().ok() |
| 219 | } |
| 220 | |
| 221 | /// Reads a journal back. Pure: no I/O. |
| 222 | pub fn replay(text: &str) -> Result<Replay, JournalError> { |
| 223 | let mut out = Replay { |
| 224 | last_digest: GENESIS.to_string(), |
| 225 | ..Replay::default() |
| 226 | }; |
| 227 | let mut offset = 0usize; |
| 228 | let mut lines = text.split_inclusive('\n').enumerate().peekable(); |
| 229 | while let Some((idx, raw)) = lines.next() { |
| 230 | let is_last = lines.peek().is_none(); |
| 231 | let whole = raw.ends_with('\n'); |
| 232 | let line = raw.trim_end_matches('\n'); |
| 233 | if line.trim().is_empty() { |
| 234 | offset += raw.len(); |
| 235 | continue; |
| 236 | } |
| 237 | let parsed: Option<Value> = serde_json::from_str(line).ok(); |
| 238 | let Some(parsed) = parsed.filter(|_| whole) else { |
| 239 | if is_last { |
| 240 | // Died mid-write: the line never finished, so nothing acted on it. |
| 241 | out.torn_tail = true; |
| 242 | break; |
| 243 | } |
| 244 | return Err(JournalError::Corrupt { |
| 245 | line: idx + 1, |
| 246 | why: "not a whole JSON line".into(), |
| 247 | }); |
| 248 | }; |
| 249 | let prev = parsed.get("prev").and_then(Value::as_str).unwrap_or(""); |
| 250 | let digest = parsed.get("digest").and_then(Value::as_str).unwrap_or(""); |
| 251 | let record_v = parsed.get("record").cloned().unwrap_or(Value::Null); |
| 252 | if prev != out.last_digest { |
| 253 | return Err(JournalError::Corrupt { |
| 254 | line: idx + 1, |
| 255 | why: "chain broken (prev does not match the line before)".into(), |
| 256 | }); |
| 257 | } |
| 258 | if digest != digest_of(prev, &record_v) { |
| 259 | return Err(JournalError::Corrupt { |
| 260 | line: idx + 1, |
| 261 | why: "digest does not match the record".into(), |
| 262 | }); |
| 263 | } |
| 264 | let record: Record = |
| 265 | serde_json::from_value(record_v).map_err(|e| JournalError::Corrupt { |
| 266 | line: idx + 1, |
| 267 | why: format!("unknown record: {e}"), |
| 268 | })?; |
| 269 | match record { |
| 270 | Record::Message { message } => out.messages.push(message), |
| 271 | Record::Snapshot { messages } => out.messages = messages, |
| 272 | Record::ToolIntent(intent) => { |
| 273 | if let Some(n) = call_number(&intent.call_id) { |
| 274 | out.next_call = out.next_call.max(n + 1); |
| 275 | } |
| 276 | out.in_doubt.push(intent); |
| 277 | } |
| 278 | Record::ToolOutcome { call_id, message } => { |
| 279 | out.in_doubt.retain(|i| i.call_id != call_id); |
| 280 | out.messages.push(message); |
| 281 | } |
| 282 | Record::TurnStop { reason } => out.stops.push(reason), |
| 283 | } |
| 284 | out.last_digest = digest.to_string(); |
| 285 | offset += raw.len(); |
| 286 | out.valid_len = offset; |
| 287 | } |
| 288 | Ok(out) |
| 289 | } |
| 290 | |
| 291 | /// The message the model sees for a tool result. Kept byte-for-byte the same |
| 292 | /// as the loop has always sent, so prompts do not change. |
| 293 | pub fn tool_response_message(name: &str, result: &Value) -> Value { |
| 294 | let body = serde_json::to_string(result).unwrap_or_default(); |
| 295 | json!({ |
| 296 | "role": "user", |
| 297 | "content": format!("<tool_response name=\"{}\">\n{}\n</tool_response>", name, body) |
| 298 | }) |
| 299 | } |
| 300 | |
| 301 | /// What a resumed session does with one in-doubt request. |
| 302 | #[derive(Debug, Clone, PartialEq)] |
| 303 | pub enum ResumeStep { |
| 304 | /// A pure read: run it again. |
| 305 | Rerun(ToolIntent), |
| 306 | /// May have changed the world: tell the model, do not run it again. |
| 307 | ReportUnknown { intent: ToolIntent, message: Value }, |
| 308 | } |
| 309 | |
| 310 | /// Decides how to settle in-doubt requests. Pure. |
| 311 | pub fn resume_steps(in_doubt: &[ToolIntent]) -> Vec<ResumeStep> { |
| 312 | in_doubt |
| 313 | .iter() |
| 314 | .map(|i| match i.effect { |
| 315 | Effect::ReadOnly => ResumeStep::Rerun(i.clone()), |
| 316 | Effect::Effectful => ResumeStep::ReportUnknown { |
| 317 | intent: i.clone(), |
| 318 | message: tool_response_message( |
| 319 | &i.name, |
| 320 | &json!({ |
| 321 | "status": "outcome_unknown", |
| 322 | "call_id": i.call_id, |
| 323 | "detail": "The session stopped after this request was recorded and before its result was. It was not run again, so it is not known whether it happened. Check its effect before asking for it again." |
| 324 | }), |
| 325 | ), |
| 326 | }, |
| 327 | }) |
| 328 | .collect() |
| 329 | } |
| 330 | |
| 331 | /// The on-disk journal. The only part of this module that does I/O. |
| 332 | pub struct Journal { |
| 333 | path: PathBuf, |
| 334 | file: File, |
| 335 | last: String, |
| 336 | next_call: u64, |
| 337 | /// Length of the whole records on disk. A failed append truncates back to it. |
| 338 | len: u64, |
| 339 | /// `Some(0)` makes the next append fail before it writes. Test builds only. |
| 340 | #[cfg(test)] |
| 341 | writes_left: Option<u32>, |
| 342 | /// The next append writes half its line, then fails. Test builds only. |
| 343 | #[cfg(test)] |
| 344 | tear_next: bool, |
| 345 | } |
| 346 | |
| 347 | impl Journal { |
| 348 | /// Starts a new journal. Refuses to overwrite an existing one. |
| 349 | pub fn create(path: &Path) -> Result<Self, JournalError> { |
| 350 | if let Some(dir) = path.parent() { |
| 351 | std::fs::create_dir_all(dir).map_err(|e| JournalError::Io(e.to_string()))?; |
| 352 | } |
| 353 | let file = OpenOptions::new() |
| 354 | .create_new(true) |
| 355 | .append(true) |
| 356 | .open(path) |
| 357 | .map_err(|e| JournalError::Io(format!("{}: {e}", path.display())))?; |
| 358 | if let Some(dir) = path.parent() { |
| 359 | // Make the new file's name durable too (best effort; not every OS allows it). |
| 360 | if let Ok(d) = File::open(dir) { |
| 361 | let _ = d.sync_all(); |
| 362 | } |
| 363 | } |
| 364 | Ok(Self { |
| 365 | path: path.to_path_buf(), |
| 366 | file, |
| 367 | last: GENESIS.to_string(), |
| 368 | next_call: 0, |
| 369 | len: 0, |
| 370 | #[cfg(test)] |
| 371 | writes_left: None, |
| 372 | #[cfg(test)] |
| 373 | tear_next: false, |
| 374 | }) |
| 375 | } |
| 376 | |
| 377 | /// Opens an existing journal to continue it. Drops a torn last line first, |
| 378 | /// so the chain continues from the last whole line. |
| 379 | pub fn resume(path: &Path) -> Result<(Self, Replay), JournalError> { |
| 380 | let text = std::fs::read_to_string(path) |
| 381 | .map_err(|e| JournalError::Io(format!("{}: {e}", path.display())))?; |
| 382 | let rep = replay(&text)?; |
| 383 | let file = OpenOptions::new() |
| 384 | .append(true) |
| 385 | .open(path) |
| 386 | .map_err(|e| JournalError::Io(e.to_string()))?; |
| 387 | if rep.valid_len < text.len() { |
| 388 | file.set_len(rep.valid_len as u64) |
| 389 | .map_err(|e| JournalError::Io(e.to_string()))?; |
| 390 | file.sync_data() |
| 391 | .map_err(|e| JournalError::Io(e.to_string()))?; |
| 392 | } |
| 393 | Ok(( |
| 394 | Self { |
| 395 | path: path.to_path_buf(), |
| 396 | file, |
| 397 | last: rep.last_digest.clone(), |
| 398 | next_call: rep.next_call, |
| 399 | len: rep.valid_len as u64, |
| 400 | #[cfg(test)] |
| 401 | writes_left: None, |
| 402 | #[cfg(test)] |
| 403 | tear_next: false, |
| 404 | }, |
| 405 | rep, |
| 406 | )) |
| 407 | } |
| 408 | |
| 409 | pub fn path(&self) -> &Path { |
| 410 | &self.path |
| 411 | } |
| 412 | |
| 413 | /// Appends one record and flushes it to disk before returning. A write |
| 414 | /// that fails part way is cut back to the last whole record, so the next |
| 415 | /// append does not glue its line onto a torn one (#832). |
| 416 | pub fn append(&mut self, record: &Record) -> Result<(), JournalError> { |
| 417 | #[cfg(test)] |
| 418 | if self.writes_left == Some(0) { |
| 419 | return Err(JournalError::Io("journal write rejected by test".into())); |
| 420 | } |
| 421 | let record_v = serde_json::to_value(record).map_err(|e| JournalError::Io(e.to_string()))?; |
| 422 | let digest = digest_of(&self.last, &record_v); |
| 423 | let line = json!({"v": 1, "prev": self.last, "digest": digest, "record": record_v}); |
| 424 | let mut bytes = serde_json::to_vec(&line).map_err(|e| JournalError::Io(e.to_string()))?; |
| 425 | bytes.push(b'\n'); |
| 426 | if let Err(e) = self.write_record(&bytes) { |
| 427 | // Drop whatever part of the line reached the file. If this fails |
| 428 | // too, `resume` still drops a torn last line. |
| 429 | if self.file.set_len(self.len).is_ok() { |
| 430 | let _ = self.file.sync_data(); |
| 431 | } |
| 432 | return Err(JournalError::Io(e.to_string())); |
| 433 | } |
| 434 | self.len += bytes.len() as u64; |
| 435 | self.last = digest; |
| 436 | #[cfg(test)] |
| 437 | if let Some(left) = self.writes_left { |
| 438 | self.writes_left = Some(left - 1); |
| 439 | } |
| 440 | Ok(()) |
| 441 | } |
| 442 | |
| 443 | fn write_record(&mut self, bytes: &[u8]) -> std::io::Result<()> { |
| 444 | #[cfg(test)] |
| 445 | if std::mem::take(&mut self.tear_next) { |
| 446 | self.file.write_all(&bytes[..bytes.len() / 2])?; |
| 447 | return Err(std::io::Error::other("journal write torn by test")); |
| 448 | } |
| 449 | self.file.write_all(bytes)?; |
| 450 | self.file.sync_data() |
| 451 | } |
| 452 | |
| 453 | /// The next append writes half of its line and then fails, as a full |
| 454 | /// disk or a signal part way through a write would. |
| 455 | #[cfg(test)] |
| 456 | pub fn tear_next_write_for_test(&mut self) { |
| 457 | self.tear_next = true; |
| 458 | } |
| 459 | |
| 460 | /// The next `n` appends succeed. The one after that fails before it writes. |
| 461 | /// `n == 0` fails the next append. Tests use this where a full disk would |
| 462 | /// stop a turn ahead of a tool. |
| 463 | #[cfg(test)] |
| 464 | pub fn accept_only_n_writes_for_test(&mut self, n: u32) { |
| 465 | self.writes_left = Some(n); |
| 466 | } |
| 467 | |
| 468 | /// Records a message, then adds it to the conversation. The conversation |
| 469 | /// only grows after the disk has it. |
| 470 | pub fn push(&mut self, messages: &mut Vec<Value>, message: Value) -> Result<(), TurnStop> { |
| 471 | self.append(&Record::Message { |
| 472 | message: message.clone(), |
| 473 | }) |
| 474 | .map_err(|e| TurnStop::PersistFailed(e.to_string()))?; |
| 475 | messages.push(message); |
| 476 | Ok(()) |
| 477 | } |
| 478 | |
| 479 | /// Records the whole conversation at the end of a turn. |
| 480 | pub fn snapshot(&mut self, messages: &[Value]) -> Result<(), JournalError> { |
| 481 | self.append(&Record::Snapshot { |
| 482 | messages: messages.to_vec(), |
| 483 | }) |
| 484 | } |
| 485 | |
| 486 | /// Records a tool request. The tool must not run unless this returns Ok. |
| 487 | pub fn intent(&mut self, name: &str, args: &Value) -> Result<ToolIntent, JournalError> { |
| 488 | let intent = ToolIntent { |
| 489 | call_id: format!("call-{}", self.next_call), |
| 490 | name: name.to_string(), |
| 491 | args: args.clone(), |
| 492 | effect: effect_of(name), |
| 493 | }; |
| 494 | self.append(&Record::ToolIntent(intent.clone()))?; |
| 495 | self.next_call += 1; |
| 496 | Ok(intent) |
| 497 | } |
| 498 | |
| 499 | /// Records a tool result and adds it to the conversation. |
| 500 | pub fn outcome( |
| 501 | &mut self, |
| 502 | messages: &mut Vec<Value>, |
| 503 | intent: &ToolIntent, |
| 504 | message: Value, |
| 505 | ) -> Result<(), TurnStop> { |
| 506 | self.append(&Record::ToolOutcome { |
| 507 | call_id: intent.call_id.clone(), |
| 508 | message: message.clone(), |
| 509 | }) |
| 510 | .map_err(|e| TurnStop::PersistFailed(e.to_string()))?; |
| 511 | messages.push(message); |
| 512 | Ok(()) |
| 513 | } |
| 514 | |
| 515 | /// Records that a turn ended early (best effort: the reason is also printed). |
| 516 | pub fn stop(&mut self, stop: &TurnStop) { |
| 517 | let _ = self.append(&Record::TurnStop { |
| 518 | reason: stop.describe(), |
| 519 | }); |
| 520 | } |
| 521 | } |
| 522 | |
| 523 | /// Runs a batch of tool calls under persist-before-act: for each call the |
| 524 | /// request is on disk before the tool runs, and the result is on disk before |
| 525 | /// the model sees it. |
| 526 | pub fn run_tool_calls<F>( |
| 527 | journal: &mut Journal, |
| 528 | messages: &mut Vec<Value>, |
| 529 | calls: Vec<(String, Value)>, |
| 530 | mut dispatch: F, |
| 531 | ) -> Result<(), TurnStop> |
| 532 | where |
| 533 | F: FnMut(&str, &Value) -> Value, |
| 534 | { |
| 535 | for (name, args) in calls { |
| 536 | let intent = journal |
| 537 | .intent(&name, &args) |
| 538 | .map_err(|e| TurnStop::PersistFailed(e.to_string()))?; |
| 539 | let result = dispatch(&name, &args); |
| 540 | journal.outcome(messages, &intent, tool_response_message(&name, &result))?; |
| 541 | } |
| 542 | Ok(()) |
| 543 | } |
| 544 | |
| 545 | /// Settles the in-doubt requests of a resumed session: re-runs reads, reports |
| 546 | /// the rest as unknown. Every settlement is journaled like a normal result. |
| 547 | pub fn settle_in_doubt<F>( |
| 548 | journal: &mut Journal, |
| 549 | messages: &mut Vec<Value>, |
| 550 | in_doubt: &[ToolIntent], |
| 551 | mut dispatch: F, |
| 552 | ) -> Result<Vec<ResumeStep>, TurnStop> |
| 553 | where |
| 554 | F: FnMut(&str, &Value) -> Value, |
| 555 | { |
| 556 | let steps = resume_steps(in_doubt); |
| 557 | for step in &steps { |
| 558 | match step { |
| 559 | ResumeStep::Rerun(i) => { |
| 560 | let result = dispatch(&i.name, &i.args); |
| 561 | journal.outcome(messages, i, tool_response_message(&i.name, &result))?; |
| 562 | } |
| 563 | ResumeStep::ReportUnknown { intent, message } => { |
| 564 | journal.outcome(messages, intent, message.clone())?; |
| 565 | } |
| 566 | } |
| 567 | } |
| 568 | Ok(steps) |
| 569 | } |
| 570 | |
| 571 | #[cfg(all(test, unix))] |
| 572 | #[path = "turn_journal/crash_tests.rs"] |
| 573 | mod crash_tests; |
| 574 | |
| 575 | #[cfg(test)] |
| 576 | mod tests { |
| 577 | use super::*; |
| 578 | |
| 579 | fn tmp() -> (tempfile::TempDir, PathBuf) { |
| 580 | let d = tempfile::tempdir().unwrap(); |
| 581 | let p = d.path().join("s.journal.jsonl"); |
| 582 | (d, p) |
| 583 | } |
| 584 | |
| 585 | fn user(t: &str) -> Value { |
| 586 | json!({"role": "user", "content": t}) |
| 587 | } |
| 588 | |
| 589 | #[test] |
| 590 | fn effect_defaults_to_effectful_for_unknown_tools() { |
| 591 | assert_eq!(effect_of("view_file"), Effect::ReadOnly); |
| 592 | assert_eq!(effect_of("grep_search"), Effect::ReadOnly); |
| 593 | assert_eq!(effect_of("list_directory"), Effect::ReadOnly); |
| 594 | assert_eq!(effect_of("run_command"), Effect::Effectful); |
| 595 | assert_eq!(effect_of("write_to_file"), Effect::Effectful); |
| 596 | assert_eq!(effect_of("some_new_tool"), Effect::Effectful); |
| 597 | } |
| 598 | |
| 599 | /// Names on the tool-dispatch arms (`dispatch_tool_with`). Nested matches, |
| 600 | /// such as a subagent action, sit deeper than the eight-space tool arms |
| 601 | /// and are not tools. |
| 602 | fn tool_names_in_dispatch(src: &str) -> Result<Vec<String>, String> { |
| 603 | let marker = "let (res, success) = match name {"; |
| 604 | let start = src.find(marker).ok_or("dispatch match not found")?; |
| 605 | let rest = &src[start + marker.len()..]; |
| 606 | let end = rest |
| 607 | .find("\n other =>") |
| 608 | .ok_or("dispatch fallback not found")?; |
| 609 | let mut names = Vec::new(); |
| 610 | for line in rest[..end].lines() { |
| 611 | let Some(arrow) = line.find("=>") else { |
| 612 | continue; |
| 613 | }; |
| 614 | let head = &line[..arrow]; |
| 615 | let indent = head.len() - head.trim_start().len(); |
| 616 | let trimmed = head.trim(); |
| 617 | if indent != 8 || !trimmed.starts_with('"') { |
| 618 | continue; |
| 619 | } |
| 620 | for part in trimmed.split('|') { |
| 621 | let part = part.trim(); |
| 622 | let name = part |
| 623 | .strip_prefix('"') |
| 624 | .and_then(|s| s.strip_suffix('"')) |
| 625 | .ok_or_else(|| format!("unparsed tool arm: {line}"))?; |
| 626 | if name.is_empty() { |
| 627 | return Err(format!("empty tool name: {line}")); |
| 628 | } |
| 629 | names.push(name.to_string()); |
| 630 | } |
| 631 | } |
| 632 | if names.is_empty() { |
| 633 | return Err("no tool names parsed from dispatch_tool_with".into()); |
| 634 | } |
| 635 | Ok(names) |
| 636 | } |
| 637 | |
| 638 | #[test] |
| 639 | fn the_dispatch_parser_reports_a_tool_that_has_no_classification() { |
| 640 | let src = "fn f() {\n let (res, success) = match name {\n \"view_file\" => {}\n \"brand_new_tool\" => {}\n \"list\" => {}\n other => {}\n }\n"; |
| 641 | let names = tool_names_in_dispatch(src).unwrap(); |
| 642 | assert_eq!( |
| 643 | names, |
| 644 | vec!["view_file".to_string(), "brand_new_tool".to_string()] |
| 645 | ); |
| 646 | assert!( |
| 647 | !TOOL_EFFECTS.iter().any(|(n, _)| *n == "brand_new_tool"), |
| 648 | "the fixture name must stay unclassified" |
| 649 | ); |
| 650 | } |
| 651 | |
| 652 | /// The read-only set is the pure reads in `tools.rs`. `list_directory` is |
| 653 | /// the alias of `list_dir` (same arm). Everything else the dispatcher |
| 654 | /// accepts is effectful, on purpose: resume must not run it again. |
| 655 | #[test] |
| 656 | fn every_dispatched_tool_is_classified() { |
| 657 | let dispatched = tool_names_in_dispatch(include_str!("tools.rs")).unwrap(); |
| 658 | let mut from_dispatch = dispatched.clone(); |
| 659 | from_dispatch.sort(); |
| 660 | let mut unique = from_dispatch.clone(); |
| 661 | unique.dedup(); |
| 662 | assert_eq!( |
| 663 | from_dispatch, unique, |
| 664 | "duplicate name in dispatch_tool_with" |
| 665 | ); |
| 666 | |
| 667 | let mut classified: Vec<String> = |
| 668 | TOOL_EFFECTS.iter().map(|(n, _)| (*n).to_string()).collect(); |
| 669 | let mut classified_unique = classified.clone(); |
| 670 | classified_unique.sort(); |
| 671 | classified_unique.dedup(); |
| 672 | classified.sort(); |
| 673 | assert_eq!( |
| 674 | classified, classified_unique, |
| 675 | "duplicate name in TOOL_EFFECTS" |
| 676 | ); |
| 677 | assert_eq!( |
| 678 | from_dispatch, classified, |
| 679 | "a tool was added to dispatch_tool_with or TOOL_EFFECTS without the other" |
| 680 | ); |
| 681 | |
| 682 | let mut read_only: Vec<&str> = TOOL_EFFECTS |
| 683 | .iter() |
| 684 | .filter(|(_, effect)| *effect == Effect::ReadOnly) |
| 685 | .map(|(name, _)| *name) |
| 686 | .collect(); |
| 687 | read_only.sort(); |
| 688 | let mut expected = vec![ |
| 689 | "find_by_name", |
| 690 | "find_file", |
| 691 | "grep_search", |
| 692 | "list_dir", |
| 693 | "list_directory", |
| 694 | "search_directory", |
| 695 | "view_file", |
| 696 | ]; |
| 697 | expected.sort(); |
| 698 | assert_eq!(read_only, expected); |
| 699 | |
| 700 | let intent = ToolIntent { |
| 701 | call_id: "call-0".into(), |
| 702 | name: "list_directory".into(), |
| 703 | args: json!({}), |
| 704 | effect: effect_of("list_directory"), |
| 705 | }; |
| 706 | assert!(matches!( |
| 707 | resume_steps(&[intent]).as_slice(), |
| 708 | [ResumeStep::Rerun(_)] |
| 709 | )); |
| 710 | } |
| 711 | |
| 712 | #[test] |
| 713 | fn replay_rebuilds_the_conversation_byte_identical() { |
| 714 | let (_d, p) = tmp(); |
| 715 | let mut j = Journal::create(&p).unwrap(); |
| 716 | let mut msgs = Vec::new(); |
| 717 | j.push(&mut msgs, json!({"role": "system", "content": "sys"})) |
| 718 | .unwrap(); |
| 719 | j.push(&mut msgs, user("hello \"Allen\" \u{1F30A}")) |
| 720 | .unwrap(); |
| 721 | j.push( |
| 722 | &mut msgs, |
| 723 | json!({"role": "assistant", "content": "<tool_call>{\"name\":\"view_file\",\"arguments\":{\"path\":\"a\"}}</tool_call>"}), |
| 724 | ) |
| 725 | .unwrap(); |
| 726 | run_tool_calls( |
| 727 | &mut j, |
| 728 | &mut msgs, |
| 729 | vec![("view_file".into(), json!({"path": "a"}))], |
| 730 | |_, _| json!({"ok": true, "lines": ["x"]}), |
| 731 | ) |
| 732 | .unwrap(); |
| 733 | drop(j); |
| 734 | let rep = replay(&std::fs::read_to_string(&p).unwrap()).unwrap(); |
| 735 | assert_eq!( |
| 736 | serde_json::to_vec(&rep.messages).unwrap(), |
| 737 | serde_json::to_vec(&msgs).unwrap() |
| 738 | ); |
| 739 | assert!(rep.in_doubt.is_empty()); |
| 740 | assert!(!rep.torn_tail); |
| 741 | } |
| 742 | |
| 743 | #[test] |
| 744 | fn snapshot_replaces_history_so_compaction_survives_resume() { |
| 745 | let (_d, p) = tmp(); |
| 746 | let mut j = Journal::create(&p).unwrap(); |
| 747 | let mut msgs = Vec::new(); |
| 748 | for i in 0..5 { |
| 749 | j.push(&mut msgs, user(&format!("m{i}"))).unwrap(); |
| 750 | } |
| 751 | let compacted = vec![user("summary of m0..m3"), user("m4")]; |
| 752 | j.snapshot(&compacted).unwrap(); |
| 753 | let mut after = compacted.clone(); |
| 754 | j.push(&mut after, user("m5")).unwrap(); |
| 755 | drop(j); |
| 756 | let rep = replay(&std::fs::read_to_string(&p).unwrap()).unwrap(); |
| 757 | assert_eq!(rep.messages, after); |
| 758 | } |
| 759 | |
| 760 | #[test] |
| 761 | fn a_tool_runs_only_after_its_request_is_on_disk() { |
| 762 | let (_d, p) = tmp(); |
| 763 | let mut j = Journal::create(&p).unwrap(); |
| 764 | let mut msgs = Vec::new(); |
| 765 | let path = p.clone(); |
| 766 | run_tool_calls( |
| 767 | &mut j, |
| 768 | &mut msgs, |
| 769 | vec![("run_command".into(), json!({"command": "true"}))], |
| 770 | |name, _| { |
| 771 | // At the moment the tool runs, the disk already holds the request. |
| 772 | let rep = replay(&std::fs::read_to_string(&path).unwrap()).unwrap(); |
| 773 | assert_eq!(rep.in_doubt.len(), 1); |
| 774 | assert_eq!(rep.in_doubt[0].name, name); |
| 775 | json!({"exit": 0}) |
| 776 | }, |
| 777 | ) |
| 778 | .unwrap(); |
| 779 | } |
| 780 | |
| 781 | #[test] |
| 782 | fn crash_between_request_and_run_reports_effectful_as_unknown_and_reruns_reads() { |
| 783 | let (_d, p) = tmp(); |
| 784 | let mut j = Journal::create(&p).unwrap(); |
| 785 | let mut msgs = Vec::new(); |
| 786 | j.push(&mut msgs, user("go")).unwrap(); |
| 787 | // Two requests recorded, then the process "dies" before either runs. |
| 788 | j.intent("write_to_file", &json!({"path": "out.txt", "content": "x"})) |
| 789 | .unwrap(); |
| 790 | j.intent("view_file", &json!({"path": "in.txt"})).unwrap(); |
| 791 | drop(j); |
| 792 | |
| 793 | let (mut j, rep) = Journal::resume(&p).unwrap(); |
| 794 | assert_eq!(rep.in_doubt.len(), 2); |
| 795 | let mut msgs = rep.messages.clone(); |
| 796 | let mut ran = Vec::new(); |
| 797 | let steps = settle_in_doubt(&mut j, &mut msgs, &rep.in_doubt, |name, _| { |
| 798 | ran.push(name.to_string()); |
| 799 | json!({"ok": true}) |
| 800 | }) |
| 801 | .unwrap(); |
| 802 | // The write is not done again; the read is. |
| 803 | assert_eq!(ran, vec!["view_file".to_string()]); |
| 804 | assert!(matches!(steps[0], ResumeStep::ReportUnknown { .. })); |
| 805 | assert!(msgs[1]["content"] |
| 806 | .as_str() |
| 807 | .unwrap() |
| 808 | .contains("outcome_unknown")); |
| 809 | drop(j); |
| 810 | // Settled: a second resume has nothing in doubt and the same conversation. |
| 811 | let (_j, rep2) = Journal::resume(&p).unwrap(); |
| 812 | assert!(rep2.in_doubt.is_empty()); |
| 813 | assert_eq!(rep2.messages, msgs); |
| 814 | assert_eq!(rep2.next_call, 2); |
| 815 | } |
| 816 | |
| 817 | #[test] |
| 818 | fn a_torn_last_line_is_dropped_and_the_chain_continues() { |
| 819 | let (_d, p) = tmp(); |
| 820 | let mut j = Journal::create(&p).unwrap(); |
| 821 | let mut msgs = Vec::new(); |
| 822 | j.push(&mut msgs, user("one")).unwrap(); |
| 823 | drop(j); |
| 824 | // The process died halfway through writing the next line. |
| 825 | let mut f = OpenOptions::new().append(true).open(&p).unwrap(); |
| 826 | f.write_all(b"{\"v\":1,\"prev\":\"abc\",\"dig").unwrap(); |
| 827 | drop(f); |
| 828 | let (mut j, rep) = Journal::resume(&p).unwrap(); |
| 829 | assert!(rep.torn_tail); |
| 830 | assert_eq!(rep.messages, msgs); |
| 831 | j.push(&mut msgs, user("two")).unwrap(); |
| 832 | drop(j); |
| 833 | let rep = replay(&std::fs::read_to_string(&p).unwrap()).unwrap(); |
| 834 | assert!(!rep.torn_tail); |
| 835 | assert_eq!(rep.messages, msgs); |
| 836 | } |
| 837 | |
| 838 | #[test] |
| 839 | fn a_write_torn_in_process_is_cut_back_before_the_next_append() { |
| 840 | let (_d, p) = tmp(); |
| 841 | let mut j = Journal::create(&p).unwrap(); |
| 842 | let mut msgs = Vec::new(); |
| 843 | j.push(&mut msgs, user("one")).unwrap(); |
| 844 | let whole_len = std::fs::metadata(&p).unwrap().len(); |
| 845 | j.tear_next_write_for_test(); |
| 846 | assert!(j.push(&mut msgs, user("lost")).is_err()); |
| 847 | assert_eq!(msgs, vec![user("one")]); |
| 848 | assert_eq!(std::fs::metadata(&p).unwrap().len(), whole_len); |
| 849 | // The same process keeps going; its next line must not land on the torn one. |
| 850 | j.push(&mut msgs, user("two")).unwrap(); |
| 851 | drop(j); |
| 852 | let rep = replay(&std::fs::read_to_string(&p).unwrap()).unwrap(); |
| 853 | assert!(!rep.torn_tail); |
| 854 | assert_eq!(rep.messages, msgs); |
| 855 | } |
| 856 | |
| 857 | #[test] |
| 858 | fn damage_before_the_last_line_is_refused() { |
| 859 | let (_d, p) = tmp(); |
| 860 | let mut j = Journal::create(&p).unwrap(); |
| 861 | let mut msgs = Vec::new(); |
| 862 | j.push(&mut msgs, user("one")).unwrap(); |
| 863 | j.push(&mut msgs, user("two")).unwrap(); |
| 864 | drop(j); |
| 865 | let text = std::fs::read_to_string(&p) |
| 866 | .unwrap() |
| 867 | .replacen("one", "0ne", 1); |
| 868 | assert!(matches!( |
| 869 | replay(&text), |
| 870 | Err(JournalError::Corrupt { line: 1, .. }) |
| 871 | )); |
| 872 | } |
| 873 | |
| 874 | #[test] |
| 875 | fn a_failed_write_stops_the_turn_before_the_tool_runs() { |
| 876 | let (_d, p) = tmp(); |
| 877 | let mut j = Journal::create(&p).unwrap(); |
| 878 | // Swap the file for a read-only handle so every append fails. |
| 879 | j.file = File::open(&p).unwrap(); |
| 880 | let mut msgs = Vec::new(); |
| 881 | let mut ran = false; |
| 882 | let r = run_tool_calls( |
| 883 | &mut j, |
| 884 | &mut msgs, |
| 885 | vec![("run_command".into(), json!({"command": "rm x"}))], |
| 886 | |_, _| { |
| 887 | ran = true; |
| 888 | json!({}) |
| 889 | }, |
| 890 | ); |
| 891 | assert!(matches!(r, Err(TurnStop::PersistFailed(_)))); |
| 892 | assert!(!ran); |
| 893 | assert!(msgs.is_empty()); |
| 894 | } |
| 895 | |
| 896 | #[test] |
| 897 | fn create_refuses_to_overwrite_a_journal() { |
| 898 | let (_d, p) = tmp(); |
| 899 | let _j = Journal::create(&p).unwrap(); |
| 900 | assert!(Journal::create(&p).is_err()); |
| 901 | } |
| 902 | |
| 903 | /// Child half of `killed_between_record_and_effect_*`. A no-op unless the |
| 904 | /// parent test starts this binary with `AIEN_JOURNAL_KILL_DIR` set. |
| 905 | #[test] |
| 906 | fn kill_child() { |
| 907 | let Ok(dir) = std::env::var("AIEN_JOURNAL_KILL_DIR") else { |
| 908 | return; |
| 909 | }; |
| 910 | let dir = PathBuf::from(dir); |
| 911 | let mut j = Journal::create(&dir.join("s.journal.jsonl")).unwrap(); |
| 912 | let mut msgs = Vec::new(); |
| 913 | j.push(&mut msgs, user("write the report")).unwrap(); |
| 914 | let _ = run_tool_calls( |
| 915 | &mut j, |
| 916 | &mut msgs, |
| 917 | vec![( |
| 918 | "write_to_file".into(), |
| 919 | json!({"path": "report.md", "content": "x"}), |
| 920 | )], |
| 921 | |_, _| { |
| 922 | // The request is on disk now. Tell the parent, then take long |
| 923 | // enough that the parent kills us before the effect happens. |
| 924 | std::fs::write(dir.join("running"), b"").unwrap(); |
| 925 | std::thread::sleep(std::time::Duration::from_secs(30)); |
| 926 | std::fs::write(dir.join("effect"), b"done").unwrap(); |
| 927 | json!({"ok": true}) |
| 928 | }, |
| 929 | ); |
| 930 | } |
| 931 | |
| 932 | /// sc#665 acceptance: kill the process between persist and tool run; the |
| 933 | /// resumed session has the request recorded, and the effect is neither lost |
| 934 | /// (the model is told it is unknown) nor doubled (it is not run again). |
| 935 | #[test] |
| 936 | fn killed_between_record_and_effect_resumes_without_loss_or_double() { |
| 937 | let d = tempfile::tempdir().unwrap(); |
| 938 | let mut child = std::process::Command::new(std::env::current_exe().unwrap()) |
| 939 | .args([ |
| 940 | "--exact", |
| 941 | "turn_journal::tests::kill_child", |
| 942 | "--nocapture", |
| 943 | "--test-threads=1", |
| 944 | ]) |
| 945 | .env("AIEN_JOURNAL_KILL_DIR", d.path()) |
| 946 | .stdout(std::process::Stdio::null()) |
| 947 | .stderr(std::process::Stdio::null()) |
| 948 | .spawn() |
| 949 | .unwrap(); |
| 950 | let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); |
| 951 | while !d.path().join("running").exists() { |
| 952 | assert!( |
| 953 | std::time::Instant::now() < deadline, |
| 954 | "child never reached the tool" |
| 955 | ); |
| 956 | std::thread::sleep(std::time::Duration::from_millis(20)); |
| 957 | } |
| 958 | child.kill().unwrap(); // SIGKILL on Unix: no cleanup runs in the child. |
| 959 | let _ = child.wait(); |
| 960 | assert!(!d.path().join("effect").exists()); |
| 961 | |
| 962 | let p = d.path().join("s.journal.jsonl"); |
| 963 | let (mut j, rep) = Journal::resume(&p).unwrap(); |
| 964 | assert_eq!(rep.messages, vec![user("write the report")]); |
| 965 | assert_eq!( |
| 966 | rep.in_doubt.len(), |
| 967 | 1, |
| 968 | "the request was recorded before the tool ran" |
| 969 | ); |
| 970 | assert_eq!(rep.in_doubt[0].name, "write_to_file"); |
| 971 | |
| 972 | let mut msgs = rep.messages.clone(); |
| 973 | let mut reran = 0; |
| 974 | settle_in_doubt(&mut j, &mut msgs, &rep.in_doubt, |_, _| { |
| 975 | reran += 1; |
| 976 | json!({}) |
| 977 | }) |
| 978 | .unwrap(); |
| 979 | assert_eq!(reran, 0, "an effectful request is never run a second time"); |
| 980 | assert!(msgs[1]["content"] |
| 981 | .as_str() |
| 982 | .unwrap() |
| 983 | .contains("outcome_unknown")); |
| 984 | drop(j); |
| 985 | let (_j, again) = Journal::resume(&p).unwrap(); |
| 986 | assert!(again.in_doubt.is_empty(), "settled once, settled for good"); |
| 987 | } |
| 988 | } |