Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(storage): append review state without rewriting history
Seraph-xb10ec8bd2373
diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rsindex 4597bb3a8..12b6274a0 100644--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@ -3062,38 +3062,66 @@ pub fn update_tool_review_state(snapshot_id: &str,state: &str,) -> Result<bool> {- let Some(detail) = get_session(db, session_id)? else {+ if !session_exists(db, session_id)? {return Ok(false);- };- let mut messages = detail.messages;- let mut changed = false;- for message in &mut messages {- if message.id != message_id || message.role != "tool" {- continue;+ }+ let record = transcripts::layout::with_layout_recovery(db.data_dir(), session_id, |layout| {+ if layout.message_count() == 0 {+ return Ok(None);}- let Some(tool_result) = message.tool_result.as_mut().and_then(Value::as_object_mut) else {- continue;- };- let Some(details) = tool_result- .get_mut("details")- .and_then(Value::as_object_mut)+ let Some(position) =+ transcripts::find_message_position(db.data_dir(), session_id, layout, message_id)?else {- continue;- };- let Some(review) = details.get_mut("review").and_then(Value::as_object_mut) else {- continue;+ return Ok(None);};- if review.get("snapshotId").and_then(Value::as_str) != Some(snapshot_id) {- continue;- }- review.insert("state".into(), Value::String(state.to_string()));- changed = true;- break;+ Ok(transcripts::read_transcript_window_with_layout(+ db.data_dir(),+ session_id,+ layout,+ position,+ Some(1),+ )?+ .messages+ .pop())+ })?;+ let Some(record) = record else {+ return Ok(false);+ };+ let message = record_to_ui(record);+ let matches_snapshot = message.role == "tool"+ && message+ .tool_result+ .as_ref()+ .and_then(Value::as_object)+ .and_then(|result| result.get("details"))+ .and_then(Value::as_object)+ .and_then(|details| details.get("review"))+ .and_then(Value::as_object)+ .and_then(|review| review.get("snapshotId"))+ .and_then(Value::as_str)+ == Some(snapshot_id);+ if !matches_snapshot {+ return Ok(false);}- if changed {- replace_messages(db, session_id, &messages)?;+ if message+ .tool_result+ .as_ref()+ .and_then(|result| result.get("details")?.get("review")?.get("state")?.as_str())+ == Some(state)+ {+ return Ok(true);}- Ok(changed)+ transcripts::append_tool_review_state(+ db.data_dir(),+ session_id,+ message_id,+ snapshot_id,+ state,+ )?;+ db.conn()+ .prepare_cached("UPDATE sessions SET updated_at = ?1 WHERE id = ?2")?+ .execute(params![now_ms(), session_id])?;+ Ok(true)}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -5319,11 +5347,55 @@ mod tests {],).unwrap();+ append_message(+ &db,+ &session.id,+ &user_msg("m3", "继续", "2025-05-01T00:00:04Z"),+ None,+ )+ .unwrap();+ let transcript = db+ .data_dir()+ .join("sessions")+ .join(format!("{}.jsonl", session.id));+ let before_review_update = std::fs::read(&transcript).unwrap();assert!(update_tool_review_state(&db, &session.id, "m2", "snapshot-1", "rolledBack",).unwrap());+ let after_review_update = std::fs::read(&transcript).unwrap();+ assert!(+ after_review_update.starts_with(&before_review_update),+ "review state updates must append instead of rewriting retained history"+ );+ assert!(after_review_update.len() - before_review_update.len() < 256);+ assert!(+ update_tool_review_state(&db, &session.id, "m2", "snapshot-1", "rolledBack").unwrap()+ );+ for (message_id, snapshot_id) in [+ ("missing", "snapshot-1"),+ ("m2", "wrong"),+ ("m1", "snapshot-1"),+ ] {+ assert!(!update_tool_review_state(+ &db,+ &session.id,+ message_id,+ snapshot_id,+ "rolledBack"+ )+ .unwrap());+ }+ assert_eq!(std::fs::read(&transcript).unwrap(), after_review_update);let updated = get_session(&db, &session.id).unwrap().unwrap();- assert_eq!(updated.summary.message_count, 2);+ assert_eq!(updated.summary.message_count, 3);+ assert_eq!(+ updated+ .messages+ .iter()+ .map(|message| message.id.as_str())+ .collect::<Vec<_>>(),+ vec!["m1", "m2", "m3"]+ );assert_eq!(updated.messages[1].tool_result,Some(json!({@@ -5347,7 +5419,78 @@ mod tests {|r| r.get(0),).unwrap();- assert_eq!(last_seq, 2);+ assert_eq!(last_seq, 3);+ }++ #[test]+ fn tool_review_state_survives_fork_revision_activation_and_deletion() {+ let db = test_db();+ let session = create_session(&db, None, None, None, None, None).unwrap();+ let mut tool = user_msg("review-tool", "written", "2025-05-01T00:00:01Z");+ tool.role = "tool".into();+ tool.tool_call_id = Some("review-call".into());+ tool.tool_name = Some("Write".into());+ tool.tool_result = Some(json!({"details": {"review": {+ "snapshotId": "snapshot-1", "state": "active"+ }}}));+ let mut answer = user_msg("answer", "done", "2025-05-01T00:00:02Z");+ answer.role = "assistant".into();+ for message in [+ user_msg("root", "write", "2025-05-01T00:00:00Z"),+ tool,+ answer,+ ] {+ append_message(&db, &session.id, &message, None).unwrap();+ }+ assert!(update_tool_review_state(+ &db,+ &session.id,+ "review-tool",+ "snapshot-1",+ "rolledBack"+ )+ .unwrap());+ let assert_rolled_back = |messages: &[UiMessage]| {+ let tool = messages+ .iter()+ .find(|message| message.role == "tool")+ .unwrap();+ assert_eq!(+ tool.tool_result.as_ref().unwrap()["details"]["review"]["state"],+ "rolledBack"+ );+ };+ let ForkSessionResult::Created(child) =+ fork_session_through(&db, &session.id, None, None).unwrap()+ else {+ panic!("fork must succeed");+ };+ assert_rolled_back(&child.messages);++ truncate_from(&db, &session.id, Some("root"), None).unwrap();+ let mut replacement = user_msg("other-root", "new variant", "2025-05-01T00:00:03Z");+ replacement.revision_root_id = Some("root".into());+ replacement.revision_count = Some(2);+ replacement.active_revision = Some(2);+ append_message(&db, &session.id, &replacement, None).unwrap();+ let restored = activate_message_revision_canonical(&db, &session.id, "root", 1).unwrap();+ assert_rolled_back(&restored);+ assert!(delete_message(&db, &session.id, "answer").unwrap().deleted);+ let path = db.data_dir().join("test.sqlite");+ drop(db);+ let reopened = Database::open(&path).unwrap();+ assert_rolled_back(+ &get_session(&reopened, &session.id)+ .unwrap()+ .unwrap()+ .messages,+ );+ assert_rolled_back(+ &get_session(&reopened, &child.summary.id)+ .unwrap()+ .unwrap()+ .messages,+ );}#[test]diff --git a/crates/host-core/src/transcripts.rs b/crates/host-core/src/transcripts.rsindex dc6d87c94..46c7ce55c 100644--- a/crates/host-core/src/transcripts.rs+++ b/crates/host-core/src/transcripts.rs@@ -40,6 +40,8 @@ pub(crate) mod binary_storage;mod binary_storage_tests;pub mod layout;#[cfg(test)]+mod review_state_tests;+#[cfg(test)]use layout::refresh_layout;pub use layout::TranscriptLayout;@@ -66,6 +68,31 @@ pub struct MessageRecord {pub created_at: String,}+/// Append-only metadata update for a review snapshot owned by a tool message.+/// Keeping this separate from the message line preserves its physical position+/// without copying the rest of a potentially very large transcript.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ToolReviewStateRecord {+ pub message_id: String,+ pub snapshot_id: String,+ pub state: String,+}++fn parse_tool_review_state(+ line: &str,+ invalid_utf8: bool,+) -> Result<Option<ToolReviewStateRecord>> {+ match serde_json::from_str(line) {+ Ok(record) => Ok(Some(record)),+ Err(error) if invalid_utf8 || error.is_eof() => {+ tracing::warn!(%error, "skipping torn tool review state line");+ Ok(None)+ }+ Err(error) => Err(error).context("decode tool review state"),+ }+}+/// Durable model-context checkpoint. The visible message transcript remains/// untouched; this record only changes the context reconstructed for a model.#[derive(Debug, Clone, Serialize, Deserialize)]@@ -183,6 +210,46 @@ pub struct TranscriptRead {pub compactions: Vec<CompactionRecord>,}+fn apply_tool_review_states(messages: &mut [MessageRecord], updates: &[ToolReviewStateRecord]) {+ let latest: std::collections::HashMap<_, _> = updates+ .iter()+ .map(|update| {+ (+ (update.message_id.as_str(), update.snapshot_id.as_str()),+ update.state.as_str(),+ )+ })+ .collect();+ for message in messages.iter_mut().filter(|message| message.role == "tool") {+ let Some(blocks) = message.blocks.as_array_mut() else {+ continue;+ };+ for block in blocks {+ if block.get("type").and_then(Value::as_str) != Some("tool_call") {+ continue;+ }+ let Some(review) = block+ .get_mut("result")+ .and_then(Value::as_object_mut)+ .and_then(|result| result.get_mut("details"))+ .and_then(Value::as_object_mut)+ .and_then(|details| details.get_mut("review"))+ .and_then(Value::as_object_mut)+ else {+ continue;+ };+ let Some(state) = review+ .get("snapshotId")+ .and_then(Value::as_str)+ .and_then(|snapshot_id| latest.get(&(message.id.as_str(), snapshot_id)))+ else {+ continue;+ };+ review.insert("state".into(), Value::String((*state).to_string()));+ }+ }+}+/// Resolve a stable ID without materializing historical message bodies. The/// reverse scan agrees with last-write-wins transcript deduplication.pub fn find_message_position(@@ -201,8 +268,27 @@ pub fn find_message_position(let mut raw = Vec::new();let mut line = String::new();for (position, offset) in layout.message_offsets.iter().enumerate().rev() {+ if layout+ .message_ids+ .get(position)+ .and_then(Option::as_deref)+ .is_some_and(|id| id != message_id)+ {+ continue;+ }let invalid_utf8 = read_layout_line(&mut reader, *offset, "message", &mut raw, &mut line)?;- match serde_json::from_str::<Identity>(&line) {+ let decoded = serde_json::from_str::<Identity>(&line);+ if let Ok(identity) = &decoded {+ if layout+ .message_ids+ .get(position)+ .and_then(Option::as_deref)+ .is_some_and(|cached| cached != identity.id)+ {+ return Err(layout::invalid_boundary());+ }+ }+ match decoded {Ok(identity) if identity.id == message_id => return Ok(Some(position)),Ok(_) => {}Err(error) if invalid_utf8 => {@@ -256,7 +342,23 @@ pub fn read_tool_call(});if matches_call {match binary_storage::read(&line) {- Ok(record) => return Ok(Some(record)),+ Ok(mut record) => {+ let mut updates = Vec::new();+ for offset in &layout.tool_review_state_offsets {+ let invalid_utf8 = read_layout_line(+ &mut reader,+ *offset,+ "tool_review_state",+ &mut raw,+ &mut line,+ )?;+ if let Some(update) = parse_tool_review_state(&line, invalid_utf8)? {+ updates.push(update);+ }+ }+ apply_tool_review_states(std::slice::from_mut(&mut record), &updates);+ return Ok(Some(record));+ }Err(error) if binary_storage::is_error(&error) => return Err(error),Err(error) if invalid_utf8 => {tracing::warn!(%error, "skipping invalid indexed tool-call message");@@ -307,6 +409,8 @@ fn read_layout_line(raw: &mut Vec<u8>,line: &mut String,) -> Result<bool> {+ #[cfg(test)]+ LAYOUT_LINE_READS.with(|reads| reads.set(reads.get() + 1));reader.seek(SeekFrom::Start(offset))?;let (read, invalid_utf8) = read_line_tolerant(reader, raw, line)?;if read == 0 {@@ -318,6 +422,11 @@ fn read_layout_line(Ok(invalid_utf8)}+#[cfg(test)]+thread_local! {+ static LAYOUT_LINE_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };+}+/// Whether a JSON string for this value is the value itself.////// serde_json escapes only the quote, the backslash and the C0 controls, so a@@ -427,6 +536,7 @@ fn sniff_line_kind(line: &str) -> Option<&'static str> {b"session" => Some("session"),b"revision" => Some("revision"),b"revision_live" => Some("revision_live"),+ b"tool_review_state" => Some("tool_review_state"),_ => None,};}@@ -796,6 +906,8 @@ fn append_line(path: &Path, header: Option<String>, line: String) -> Result<()>}let fresh = !path.exists();let mut file = OpenOptions::new().create(true).append(true).open(path)?;+ let before = file.metadata()?;+ let before_stamp = layout::modification_stamp(path, &before);let mut buf = String::new();if fresh {buf.push_str(@@ -817,7 +929,9 @@ fn append_line(path: &Path, header: Option<String>, line: String) -> Result<()>file.flush()?;file.sync_data().with_context(|| format!("flush {}", path.display()))?;- binary_integrity::appended(path, file)+ binary_integrity::appended(path, file)?;+ layout::note_append(path, &before, before_stamp.as_deref());+ Ok(())}/// Whether a non-empty file ends in a newline; an empty file counts as@@ -878,6 +992,30 @@ pub fn append_compaction(.with_context(|| format!("append compaction {}", path.display()))}+/// Append a review-state mutation without rewriting the message or transcript.+pub fn append_tool_review_state(+ data_dir: &Path,+ session_id: &str,+ message_id: &str,+ snapshot_id: &str,+ state: &str,+) -> Result<()> {+ let path = transcript_path(data_dir, session_id)?;+ append_line(+ &path,+ None,+ tagged(+ "tool_review_state",+ &ToolReviewStateRecord {+ message_id: message_id.to_string(),+ snapshot_id: snapshot_id.to_string(),+ state: state.to_string(),+ },+ )?,+ )+ .with_context(|| format!("append tool review state {}", path.display()))+}+/// Load the live transcript. A missing file is an empty transcript; unknown/// line types and a torn trailing line are skipped, not errors.pub fn read_transcript(data_dir: &Path, session_id: &str) -> Result<Vec<MessageRecord>> {@@ -947,14 +1085,27 @@ pub fn read_transcript_window_with_layout(};// Every offset that has to be visited, in ascending file order, so one// forward-only reader can serve both kinds without seeking backwards.- let mut wanted: Vec<(u64, bool)> =- Vec::with_capacity(end.saturating_sub(start) + active_compactions.len());+ let mut wanted: Vec<(u64, &str)> = Vec::with_capacity(+ end.saturating_sub(start)+ + active_compactions.len()+ + layout.tool_review_state_offsets.len(),+ );wanted.extend(layout.message_offsets[start..end].iter()- .map(|offset| (*offset, true)),+ .map(|offset| (*offset, "message")),+ );+ wanted.extend(+ active_compactions+ .iter()+ .map(|offset| (*offset, "compaction")),+ );+ wanted.extend(+ layout+ .tool_review_state_offsets+ .iter()+ .map(|offset| (*offset, "tool_review_state")),);- wanted.extend(active_compactions.iter().map(|offset| (*offset, false)));if wanted.is_empty() {return Ok(out);}@@ -968,22 +1119,21 @@ pub fn read_transcript_window_with_layout(let mut reader = BufReader::new(file);let mut raw = Vec::new();let mut line = String::new();- for (offset, is_message) in wanted {- let kind = if is_message { "message" } else { "compaction" };+ let mut review_states = Vec::new();+ for (offset, kind) in wanted {let invalid_utf8 = read_layout_line(&mut reader, offset, kind, &mut raw, &mut line).with_context(|| format!("read indexed transcript line in {}", path.display()))?;let trimmed = line.trim();- if is_message {- match binary_storage::read::<MessageRecord>(trimmed) {+ match kind {+ "message" => match binary_storage::read::<MessageRecord>(trimmed) {Ok(record) => out.messages.push(record),Err(error) if binary_storage::is_error(&error) => return Err(error),Err(error) if invalid_utf8 => {tracing::warn!(path = %path.display(), %error, "skipping invalid indexed message line");}Err(error) => return Err(error).context("decode indexed transcript message"),- }- } else {- match binary_storage::read::<CompactionRecord>(trimmed) {+ },+ "compaction" => match binary_storage::read::<CompactionRecord>(trimmed) {Ok(record) => out.compactions.push(record),Err(error) if binary_storage::is_error(&error) => return Err(error),Err(error) if invalid_utf8 => {@@ -992,7 +1142,13 @@ pub fn read_transcript_window_with_layout(Err(error) => {return Err(error).context("decode indexed transcript compaction");}+ },+ "tool_review_state" => {+ if let Some(record) = parse_tool_review_state(trimmed, invalid_utf8)? {+ review_states.push(record);+ }}+ _ => unreachable!("layout only indexes supported transcript line kinds"),}if raw.capacity() > 1024 * 1024 {raw = Vec::new();@@ -1001,6 +1157,7 @@ pub fn read_transcript_window_with_layout(line = String::new();}}+ apply_tool_review_states(&mut out.messages, &review_states);Ok(out)}@@ -1027,9 +1184,11 @@ pub fn read_transcript_window(let end = message_limit.map(|limit| message_start.saturating_add(limit));let mut message_index = 0usize;let mut out = TranscriptRead::default();+ let mut review_states = Vec::new();loop {line.clear();- if read_line_tolerant(&mut reader, &mut raw, &mut line)?.0 == 0 {+ let (read, invalid_utf8) = read_line_tolerant(&mut reader, &mut raw, &mut line)?;+ if read == 0 {break;}// Classify by a bounded prefix scan: a full parse here walks every byte@@ -1060,6 +1219,11 @@ pub fn read_transcript_window(tracing::warn!(path = %path.display(), %error, "skipping invalid compaction line");}},+ "tool_review_state" => {+ if let Some(record) = parse_tool_review_state(line.trim(), invalid_utf8)? {+ review_states.push(record);+ }+ }_ => {}}// A skipped 50 MB line must not leave its capacity attached to every@@ -1069,6 +1233,7 @@ pub fn read_transcript_window(line = String::new();}}+ apply_tool_review_states(&mut out.messages, &review_states);Ok(out)}diff --git a/crates/host-core/src/transcripts/binary_integrity.rs b/crates/host-core/src/transcripts/binary_integrity.rsindex 7d3e2c5cd..a4cc93e6b 100644--- a/crates/host-core/src/transcripts/binary_integrity.rs+++ b/crates/host-core/src/transcripts/binary_integrity.rs@@ -51,7 +51,7 @@ impl Generation {}#[cfg(windows)]-fn change_time(file: &File) -> Result<i64> {+pub(super) fn change_time(file: &File) -> Result<i64> {use std::{mem::size_of, os::windows::io::AsRawHandle};use windows_sys::Win32::{Foundation::HANDLE,diff --git a/crates/host-core/src/transcripts/layout.rs b/crates/host-core/src/transcripts/layout.rsindex 7a2dec946..b434734e5 100644--- a/crates/host-core/src/transcripts/layout.rs+++ b/crates/host-core/src/transcripts/layout.rs@@ -19,7 +19,12 @@ use super::{sniff_line_kind, swap_into_place, transcript_path};const LAYOUT_CACHE_MIN_LEN: u64 = 2 * 1024 * 1024;const LAYOUT_CACHE_MAX_LAG: u64 = 4 * 1024 * 1024;const LAYOUT_CACHE_MAGIC: &str = "PI-DESKTOP-TRANSCRIPT-LAYOUT";-const LAYOUT_CACHE_VERSION: &str = "2";+const LAYOUT_CACHE_VERSION: &str = "3";++#[cfg(test)]+thread_local! {+ pub(super) static SCANNED_LINES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };+}/// A stable identity available on filesystems that expose one.#[derive(Debug, Clone, Default, PartialEq, Eq)]@@ -77,11 +82,47 @@ impl FileIdentity {pub struct TranscriptLayout {/// Byte offset of each message line, in file order.pub message_offsets: Vec<u64>,+ /// Parsed identities parallel to message offsets. Invalid rows keep None so+ /// point reads still expose their decoding errors instead of hiding them.+ pub(super) message_ids: Vec<Option<String>>,/// Byte offset of each compaction line, in file order.pub compaction_offsets: Vec<u64>,+ /// Byte offset of each append-only tool review state line.+ pub tool_review_state_offsets: Vec<u64>,/// Byte length of the file prefix this layout describes.pub file_len: u64,pub(crate) identity: FileIdentity,+ pub(super) modification_stamp: Option<String>,+}++#[derive(serde::Deserialize)]+struct MessageIdentity {+ id: String,+}++pub(super) fn modification_stamp(_path: &Path, metadata: &fs::Metadata) -> Option<String> {+ let modified = metadata+ .modified()+ .ok()?+ .duration_since(std::time::UNIX_EPOCH)+ .ok()?+ .as_nanos();+ #[cfg(unix)]+ {+ use std::os::unix::fs::MetadataExt;+ Some(format!(+ "{modified}:{}:{}",+ metadata.ctime(),+ metadata.ctime_nsec()+ ))+ }+ #[cfg(windows)]+ {+ let changed = super::binary_integrity::change_time(&File::open(_path).ok()?).ok()?;+ Some(format!("{modified}:{changed}"))+ }+ #[cfg(not(any(unix, windows)))]+ Some(modified.to_string())}impl TranscriptLayout {@@ -118,6 +159,42 @@ fn layout_key(data_dir: &Path, session_id: &str) -> LayoutKey {}}+/// Extend a cached prefix's generation proof only for an append made by this+/// writer to the generation it already described. Unknown mutations force a+/// rescan, even when they also grow the file.+pub(super) fn note_append(path: &Path, before: &fs::Metadata, before_stamp: Option<&str>) {+ let Some((data_dir, session_id)) = path.parent().and_then(Path::parent).zip(+ path.file_name()+ .and_then(|name| name.to_str())+ .and_then(|name| name.strip_suffix(".jsonl")),+ ) else {+ return;+ };+ let Ok(mut guard) = layout_cache().lock() else {+ return;+ };+ let Some(layout) = guard.get_mut(&layout_key(data_dir, session_id)) else {+ return;+ };+ let after = match fs::metadata(path) {+ Ok(metadata) => metadata,+ Err(error) => {+ layout.modification_stamp = None;+ tracing::warn!(%error, "failed to refresh transcript layout generation after append");+ return;+ }+ };+ if before_stamp.is_some()+ && layout.modification_stamp.as_deref() == before_stamp+ && layout.identity == file_identity(path, before)+ && layout.identity == file_identity(path, &after)+ {+ layout.modification_stamp = modification_stamp(path, &after);+ } else {+ layout.modification_stamp = None;+ }+}+fn layout_cache_path(data_dir: &Path, session_id: &str) -> Result<PathBuf> {Ok(transcript_path(data_dir, session_id)?.with_extension("jsonl.layout"))}@@ -236,23 +313,31 @@ fn refresh_with_identity(identity: FileIdentity,) -> Result<TranscriptLayout> {let path = transcript_path(data_dir, session_id)?;- let mut base =- if identity.is_available() && base.identity == identity && base.file_len <= length {- base- } else {- TranscriptLayout::empty(identity.clone())- };+ let stamp = modification_stamp(&path, &fs::metadata(&path)?);+ let mut base = if identity.is_available()+ && base.identity == identity+ && base.file_len <= length+ && stamp.is_some()+ && base.modification_stamp == stamp+ {+ base+ } else {+ TranscriptLayout::empty(identity.clone())+ };if !identity.is_available() {// Without a reliable identity, no existing offsets can be trusted.- base = TranscriptLayout::empty(identity);+ base = TranscriptLayout::empty(identity.clone());} else if base.file_len == 0 {base = load_layout_cache(data_dir, session_id, &identity, length)?.unwrap_or_else(|| TranscriptLayout::empty(identity.clone()));}if length == base.file_len {- return Ok(base);+ if stamp.is_some() && base.modification_stamp == stamp {+ return Ok(base);+ }+ base = TranscriptLayout::empty(identity);}let base_len = base.file_len;let layout = scan_layout(&path, base)?;@@ -299,6 +384,8 @@ fn scan_layout(path: &Path, mut layout: TranscriptLayout) -> Result<TranscriptLaif read == 0 {break;}+ #[cfg(test)]+ SCANNED_LINES.with(|lines| lines.set(lines.get() + 1));// A torn append is excluded until its newline arrives.if !raw.ends_with(b"\n") {break;@@ -307,8 +394,16 @@ fn scan_layout(path: &Path, mut layout: TranscriptLayout) -> Result<TranscriptLa// contains bytes from a character that was torn during a crash.let line = String::from_utf8_lossy(&raw);match sniff_line_kind(line.trim_end()) {- Some("message") => layout.message_offsets.push(offset),+ Some("message") => {+ layout.message_offsets.push(offset);+ layout.message_ids.push(+ serde_json::from_str::<MessageIdentity>(&line)+ .ok()+ .map(|identity| identity.id),+ );+ }Some("compaction") => layout.compaction_offsets.push(offset),+ Some("tool_review_state") => layout.tool_review_state_offsets.push(offset),_ => {}}offset += read as u64;@@ -317,6 +412,7 @@ fn scan_layout(path: &Path, mut layout: TranscriptLayout) -> Result<TranscriptLa}}layout.file_len = offset;+ layout.modification_stamp = modification_stamp(path, &reader.get_ref().metadata()?);Ok(layout)}@@ -356,19 +452,32 @@ fn load_layout_cache(let Some(file_len) = tokens.next().and_then(|token| token.parse::<u64>().ok()) else {return Ok(None);};- if file_len < LAYOUT_CACHE_MIN_LEN || file_len > current_len {+ if file_len < LAYOUT_CACHE_MIN_LEN || file_len != current_len {+ return Ok(None);+ }+ let Some(stamp) = tokens.next() else {+ return Ok(None);+ };+ let transcript = transcript_path(data_dir, session_id)?;+ if modification_stamp(&transcript, &fs::metadata(&transcript)?).as_deref() != Some(stamp) {return Ok(None);}- let (Some(message_count), Some(compaction_count)) = (tokens.next(), tokens.next()) else {+ let (Some(message_count), Some(compaction_count), Some(review_state_count)) =+ (tokens.next(), tokens.next(), tokens.next())+ else {return Ok(None);};- let (Some(message_count), Some(compaction_count)) = (+ let (Some(message_count), Some(compaction_count), Some(review_state_count)) = (message_count.parse::<usize>().ok(),compaction_count.parse::<usize>().ok(),+ review_state_count.parse::<usize>().ok(),) else {return Ok(None);};- let Some(offset_count) = message_count.checked_add(compaction_count) else {+ let Some(offset_count) = message_count+ .checked_add(compaction_count)+ .and_then(|count| count.checked_add(review_state_count))+ else {return Ok(None);};let Ok(file_len_usize) = usize::try_from(file_len) else {@@ -381,9 +490,12 @@ fn load_layout_cache(}let mut layout = TranscriptLayout {message_offsets: Vec::with_capacity(message_count),+ message_ids: Vec::with_capacity(message_count),compaction_offsets: Vec::with_capacity(compaction_count),+ tool_review_state_offsets: Vec::with_capacity(review_state_count),file_len,identity: cached_identity,+ modification_stamp: Some(stamp.to_string()),};for index in 0..offset_count {let Some(offset) = tokens.next().and_then(|token| token.parse::<u64>().ok()) else {@@ -391,10 +503,32 @@ fn load_layout_cache(};if index < message_count {layout.message_offsets.push(offset);- } else {+ } else if index < message_count + compaction_count {layout.compaction_offsets.push(offset);+ } else {+ layout.tool_review_state_offsets.push(offset);}}+ for _ in 0..message_count {+ let Some(token) = tokens.next() else {+ return Ok(None);+ };+ let id = if token == "-" {+ None+ } else {+ let Some(encoded) = token.strip_prefix('+') else {+ return Ok(None);+ };+ let Some(id) = hex::decode(encoded)+ .ok()+ .and_then(|bytes| String::from_utf8(bytes).ok())+ else {+ return Ok(None);+ };+ Some(id)+ };+ layout.message_ids.push(id);+ }let transcript = transcript_path(data_dir, session_id)?;let (Some(checksum_label), Some(checksum)) = (tokens.next(), tokens.next()) else {return Ok(None);@@ -414,49 +548,30 @@ fn load_layout_cache(}fn offsets_are_valid(layout: &TranscriptLayout) -> bool {- if layout- .message_offsets- .windows(2)- .any(|pair| pair[0] >= pair[1])- || layout- .compaction_offsets- .windows(2)- .any(|pair| pair[0] >= pair[1])- {- return false;- }- let mut messages = layout.message_offsets.iter().copied().peekable();- let mut compactions = layout.compaction_offsets.iter().copied().peekable();+ let groups = [+ &layout.message_offsets,+ &layout.compaction_offsets,+ &layout.tool_review_state_offsets,+ ];+ let mut positions = [0; 3];let mut previous = None;loop {- let next_message = messages.peek().copied();- let next_compaction = compactions.peek().copied();- let next = match (next_message, next_compaction) {- (None, None) => break,- (Some(message), Some(compaction)) if message == compaction => return false,- (Some(message), Some(compaction)) if message < compaction => {- messages.next();- message- }- (Some(_), Some(compaction)) => {- compactions.next();- compaction- }- (Some(message), None) => {- messages.next();- message- }- (None, Some(compaction)) => {- compactions.next();- compaction- }+ let next = groups+ .iter()+ .enumerate()+ .filter_map(|(index, offsets)| {+ offsets.get(positions[index]).map(|offset| (*offset, index))+ })+ .min();+ let Some((offset, group)) = next else {+ return true;};- if next >= layout.file_len || previous.is_some_and(|offset| offset >= next) {+ if offset >= layout.file_len || previous.is_some_and(|previous| previous >= offset) {return false;}- previous = Some(next);+ positions[group] += 1;+ previous = Some(offset);}- true}fn prefix_ends_on_line_boundary(path: &Path, file_len: u64) -> Result<bool> {@@ -480,6 +595,12 @@ fn offsets_look_like_scan(path: &Path, layout: &TranscriptLayout) -> Result<bool.compaction_offsets.first().map(|offset| (*offset, "compaction")),+ )+ .chain(+ layout+ .tool_review_state_offsets+ .first()+ .map(|offset| (*offset, "tool_review_state")),);for (offset, kind) in head {if offset >= layout.file_len {@@ -514,15 +635,34 @@ fn layout_cache_digest(layout: &TranscriptLayout) -> String {FileIdentity::Unavailable => digest.update(b"unavailable"),}digest.update(layout.file_len.to_le_bytes());+ digest.update(+ layout+ .modification_stamp+ .as_deref()+ .unwrap_or_default()+ .as_bytes(),+ );digest.update((layout.message_offsets.len() as u64).to_le_bytes());digest.update((layout.compaction_offsets.len() as u64).to_le_bytes());+ digest.update((layout.tool_review_state_offsets.len() as u64).to_le_bytes());for offset in layout.message_offsets.iter().chain(&layout.compaction_offsets)+ .chain(&layout.tool_review_state_offsets){digest.update(offset.to_le_bytes());}+ for id in &layout.message_ids {+ match id {+ Some(id) => {+ digest.update([1]);+ digest.update((id.len() as u64).to_le_bytes());+ digest.update(id.as_bytes());+ }+ None => digest.update([0]),+ }+ }hex::encode(digest.finalize())}@@ -530,9 +670,15 @@ fn store_layout_cache(data_dir: &Path, session_id: &str, layout: &TranscriptLayoif layout.file_len < LAYOUT_CACHE_MIN_LEN || !layout.identity.is_available() {return Ok(());}+ let Some(stamp) = layout.modification_stamp.as_deref() else {+ return Ok(());+ };let path = transcript_path(data_dir, session_id)?;let metadata = fs::metadata(&path)?;- if metadata.len() != layout.file_len || file_identity(&path, &metadata) != layout.identity {+ if metadata.len() != layout.file_len+ || file_identity(&path, &metadata) != layout.identity+ || modification_stamp(&path, &metadata).as_deref() != Some(stamp)+ {return Ok(());}let cache = layout_cache_path(data_dir, session_id)?;@@ -542,13 +688,19 @@ fn store_layout_cache(data_dir: &Path, session_id: &str, layout: &TranscriptLayowriteln!(writer, "{LAYOUT_CACHE_MAGIC} {LAYOUT_CACHE_VERSION}")?;layout.identity.write_tokens(&mut writer)?;writeln!(writer, "{}", layout.file_len)?;+ writeln!(writer, "{stamp}")?;writeln!(writer,- "{} {}",+ "{} {} {}",layout.message_offsets.len(),- layout.compaction_offsets.len()+ layout.compaction_offsets.len(),+ layout.tool_review_state_offsets.len())?;- for offsets in [&layout.message_offsets, &layout.compaction_offsets] {+ for offsets in [+ &layout.message_offsets,+ &layout.compaction_offsets,+ &layout.tool_review_state_offsets,+ ] {for (index, offset) in offsets.iter().enumerate() {if index % 8 == 7 {writeln!(writer, "{offset}")?;@@ -560,6 +712,12 @@ fn store_layout_cache(data_dir: &Path, session_id: &str, layout: &TranscriptLayowriteln!(writer)?;}}+ for id in &layout.message_ids {+ match id {+ Some(id) => writeln!(writer, "+{}", hex::encode(id))?,+ None => writeln!(writer, "-")?,+ }+ }writeln!(writer, "checksum {}", layout_cache_digest(layout))?;writer.flush()?;writer.get_ref().sync_data()?;diff --git a/crates/host-core/src/transcripts/review_state_tests.rs b/crates/host-core/src/transcripts/review_state_tests.rsnew file mode 100644index 000000000..74b5f41f0--- /dev/null+++ b/crates/host-core/src/transcripts/review_state_tests.rs@@ -0,0 +1,237 @@+use super::*;+use serde_json::json;+use tempfile::tempdir;++const CREATED_AT: &str = "2026-10-28T00:00:00Z";++fn tool(id: &str, snapshot: &str) -> MessageRecord {+ MessageRecord {+ id: id.into(),+ role: "tool".into(),+ tool_name: Some("Write".into()),+ is_error: false,+ blocks: json!([{+ "type": "tool_call", "callId": id,+ "result": { "details": { "review": {+ "snapshotId": snapshot, "state": "active"+ }}}+ }]),+ meta: None,+ created_at: CREATED_AT.into(),+ }+}++fn state(record: &MessageRecord) -> &str {+ record.blocks[0]["result"]["details"]["review"]["state"]+ .as_str()+ .unwrap()+}++#[test]+fn review_target_lookup_reads_only_its_own_line_after_layout_is_cached() {+ let dir = tempdir().unwrap();+ let records = (0..100)+ .map(|index| tool(&format!("tool-{index}"), "snapshot"))+ .collect::<Vec<_>>();+ write_transcript(dir.path(), "s1", CREATED_AT, &records).unwrap();+ let layout = refresh_layout(dir.path(), "s1", TranscriptLayout::default()).unwrap();+ LAYOUT_LINE_READS.with(|reads| reads.set(0));+ assert_eq!(+ find_message_position(dir.path(), "s1", &layout, "tool-0").unwrap(),+ Some(0)+ );+ LAYOUT_LINE_READS.with(|reads| {+ assert_eq!(+ reads.get(),+ 1,+ "cached identity lookup must not read historical bodies"+ )+ });+}++#[test]+fn owned_appends_extend_the_cached_identity_prefix_without_rescanning_history() {+ let dir = tempdir().unwrap();+ let records = (0..100)+ .map(|index| tool(&format!("tool-{index}"), "snapshot"))+ .collect::<Vec<_>>();+ write_transcript(dir.path(), "s1", CREATED_AT, &records).unwrap();+ layout::session_layout(dir.path(), "s1").unwrap();+ layout::SCANNED_LINES.with(|lines| lines.set(0));+ append_message(dir.path(), "s1", CREATED_AT, &tool("next", "snapshot")).unwrap();+ let layout = layout::session_layout(dir.path(), "s1").unwrap();+ assert_eq!(layout.message_count(), 101);+ layout::SCANNED_LINES.with(|lines| assert_eq!(lines.get(), 1));+ assert_eq!(+ find_message_position(dir.path(), "s1", &layout, "tool-0").unwrap(),+ Some(0)+ );+}++#[test]+fn cached_message_identities_rebuild_after_an_in_place_same_length_edit() {+ let dir = tempdir().unwrap();+ let mut record = tool("before-id", "snapshot");+ record.blocks[0]["padding"] = json!("x".repeat(3 * 1024 * 1024));+ write_transcript(dir.path(), "s1", CREATED_AT, &[record]).unwrap();+ let warm = refresh_layout(dir.path(), "s1", TranscriptLayout::default()).unwrap();+ let path = transcript_path(dir.path(), "s1").unwrap();+ let edited = fs::read_to_string(&path)+ .unwrap()+ .replace("before-id", "edited-id");+ fs::write(&path, edited).unwrap();+ for base in [warm, TranscriptLayout::default()] {+ let refreshed = refresh_layout(dir.path(), "s1", base).unwrap();+ assert_eq!(+ find_message_position(dir.path(), "s1", &refreshed, "edited-id").unwrap(),+ Some(0)+ );+ assert_eq!(+ find_message_position(dir.path(), "s1", &refreshed, "before-id").unwrap(),+ None+ );+ }+}++#[test]+fn cached_message_identities_rebuild_after_an_edit_followed_by_append() {+ let dir = tempdir().unwrap();+ let mut record = tool("before-id", "snapshot");+ record.blocks[0]["padding"] = json!("x".repeat(3 * 1024 * 1024));+ write_transcript(dir.path(), "s1", CREATED_AT, &[record]).unwrap();+ let warm = refresh_layout(dir.path(), "s1", TranscriptLayout::default()).unwrap();+ let path = transcript_path(dir.path(), "s1").unwrap();+ let edited = fs::read_to_string(&path)+ .unwrap()+ .replace("before-id", "edited-id");+ fs::write(&path, edited).unwrap();+ append_message(dir.path(), "s1", CREATED_AT, &tool("next", "snapshot")).unwrap();+ for base in [warm, TranscriptLayout::default()] {+ let refreshed = refresh_layout(dir.path(), "s1", base).unwrap();+ assert_eq!(+ find_message_position(dir.path(), "s1", &refreshed, "edited-id").unwrap(),+ Some(0)+ );+ assert_eq!(+ find_message_position(dir.path(), "s1", &refreshed, "before-id").unwrap(),+ None+ );+ }+}++#[test]+fn review_updates_preserve_positions_and_replay_through_warm_and_cold_layouts() {+ let dir = tempdir().unwrap();+ let mut large = tool("image", "unrelated");+ large.blocks[0]["result"]["body"] = json!("x".repeat(3 * 1024 * 1024));+ let records = [+ tool("first", "snapshot-1"),+ large,+ tool("last", "snapshot-2"),+ ];+ write_transcript(dir.path(), "s1", CREATED_AT, &records).unwrap();+ let path = transcript_path(dir.path(), "s1").unwrap();+ let before = fs::read(&path).unwrap();+ let warm = refresh_layout(dir.path(), "s1", TranscriptLayout::default()).unwrap();+ append_tool_review_state(dir.path(), "s1", "first", "snapshot-1", "rolledBack").unwrap();+ let after = fs::read(&path).unwrap();+ assert!(after.starts_with(&before));+ assert!(after.len() - before.len() < 256);++ let grown = refresh_layout(dir.path(), "s1", warm).unwrap();+ assert_eq!(grown.message_count(), 3);+ assert_eq!(grown.tool_review_state_offsets.len(), 1);+ assert_eq!(+ find_message_position(dir.path(), "s1", &grown, "first").unwrap(),+ Some(0)+ );+ let page = read_transcript_window_with_layout(dir.path(), "s1", &grown, 0, Some(1)).unwrap();+ assert_eq!(page.messages.len(), 1);+ assert_eq!(state(&page.messages[0]), "rolledBack");+ assert_eq!(+ state(+ &read_tool_call(dir.path(), "s1", &grown, "first")+ .unwrap()+ .unwrap()+ ),+ "rolledBack"+ );++ // A fresh layout loads the disk cache and scans its appended state suffix.+ let cold = refresh_layout(dir.path(), "s1", TranscriptLayout::default()).unwrap();+ assert_eq!(cold.message_count(), 3);+ assert_eq!(+ cold.tool_review_state_offsets,+ grown.tool_review_state_offsets+ );+ let full = read_transcript(dir.path(), "s1").unwrap();+ assert_eq!(state(&full[0]), "rolledBack");+ assert_eq!(state(&full[2]), "active");+ let sequential = read_transcript_window(dir.path(), "s1", 0, Some(1)).unwrap();+ assert_eq!(state(&sequential.messages[0]), "rolledBack");++ // A deliberate whole-history rewrite folds the effective state into the+ // canonical message and removes obsolete mutation lines.+ write_transcript(dir.path(), "s1", CREATED_AT, &full).unwrap();+ let rewritten = refresh_layout(dir.path(), "s1", cold).unwrap();+ assert!(rewritten.tool_review_state_offsets.is_empty());+ assert_eq!(+ state(&read_transcript(dir.path(), "s1").unwrap()[0]),+ "rolledBack"+ );+}++#[test]+fn review_state_is_last_write_wins_and_scoped_to_message_and_snapshot() {+ let dir = tempdir().unwrap();+ let mut user = tool("user", "snapshot-1");+ user.role = "user".into();+ let records = [+ tool("target", "snapshot-1"),+ tool("other", "snapshot-1"),+ user,+ tool("target", "snapshot-1"),+ ];+ write_transcript(dir.path(), "s1", CREATED_AT, &records).unwrap();+ for (id, snapshot, state) in [+ ("target", "snapshot-1", "active"),+ ("target", "snapshot-1", "rolledBack"),+ ("target", "other-snapshot", "ignored"),+ ("user", "snapshot-1", "ignored"),+ ] {+ append_tool_review_state(dir.path(), "s1", id, snapshot, state).unwrap();+ }+ let loaded = read_transcript(dir.path(), "s1").unwrap();+ assert_eq!(state(&loaded[0]), "rolledBack");+ assert_eq!(state(&loaded[1]), "active");+ assert_eq!(state(&loaded[2]), "active");+ assert_eq!(state(&loaded[3]), "rolledBack");+ let layout = refresh_layout(dir.path(), "s1", TranscriptLayout::default()).unwrap();+ let page = read_transcript_window_with_layout(dir.path(), "s1", &layout, 3, Some(1)).unwrap();+ assert_eq!(state(&page.messages[0]), "rolledBack");+}++#[test]+fn review_append_repairs_a_torn_tail_and_exposes_write_errors() {+ let dir = tempdir().unwrap();+ write_transcript(dir.path(), "s1", CREATED_AT, &[tool("target", "snapshot")]).unwrap();+ let path = transcript_path(dir.path(), "s1").unwrap();+ OpenOptions::new()+ .append(true)+ .open(&path)+ .unwrap()+ .write_all(b"{\"type\":\"tool_review_state\"")+ .unwrap();+ append_tool_review_state(dir.path(), "s1", "target", "snapshot", "rolledBack").unwrap();+ assert_eq!(+ state(&read_transcript(dir.path(), "s1").unwrap()[0]),+ "rolledBack"+ );+ let layout = refresh_layout(dir.path(), "s1", TranscriptLayout::default()).unwrap();+ let loaded = read_transcript_window_with_layout(dir.path(), "s1", &layout, 0, None).unwrap();+ assert_eq!(state(&loaded.messages[0]), "rolledBack");++ let invalid = transcript_path(dir.path(), "unwritable").unwrap();+ fs::create_dir(&invalid).unwrap();+ assert!(append_tool_review_state(dir.path(), "unwritable", "m", "s", "rolledBack").is_err());+}diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 7ecbdf198..c64b0e9bd 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -20,6 +20,7 @@ Each ADR includes:| ID | Title | Status ||---|---|---|+| append-only-review-state | [Append-only review state](append-only-review-state.md) | Implemented candidate || lossless-tool-image-storage | [Lossless tool-image storage and bounded history mutations](lossless-tool-image-storage.md) | Implemented candidate || plugin-remote-workspace-reads | [Plugin reads in remote workspaces](plugin-remote-workspace-reads.md) | Implemented candidate || browser-background-lifecycle | [Browser page execution outlives side-panel presentation](browser-background-lifecycle.md) | Accepted |diff --git a/docs/adr/append-only-review-state.md b/docs/adr/append-only-review-state.mdnew file mode 100644index 000000000..8d451f5f4--- /dev/null+++ b/docs/adr/append-only-review-state.md@@ -0,0 +1,59 @@+# ADR: Append-only review state++- Status: Implemented candidate+- Date: 2026-10-28+- Related: Issue #1836, ADR 0043, ADR 0060, ADR 0127++## Context++Rolling back one historical tool card loaded the complete session and called+`replace_messages` to persist `details.review.state`. This rewrote the entire+transcript and rebuilt every SQLite message index row under the Host state+lock. The work scaled with retained image/output bytes, although only one+small metadata value changed. Appending a replacement message directly would+move its physical position and break bounded history navigation.++## Decision++Append a distinct `tool_review_state` line keyed by message and snapshot IDs.+Keep the original message line and all message-window coordinates unchanged.+Replay the latest matching state in full reads, bounded reads and tool-parent+lookups. Index these small mutation offsets separately in layout-cache format+3; rebuild previous disposable cache versions normally. Cache parsed message+identities alongside the offsets, and validate the selected identity against+its original line. Invalid rows keep an unresolved identity and continue to+expose the existing point-read decoding errors.++Cache reuse requires a matching file identity and modification/change-time+stamp. Only a Host-owned append from the proven generation advances an+in-memory prefix's generation without rescanning. A lagging disk cache or an+unrecognized change is rebuilt, including an in-place edit followed by append.++Validate the owning tool snapshot before appending, and avoid writing duplicate+state acknowledgements. Preserve file-first durability through the existing+flush/fsync append path, then update only the session timestamp. Existing+rewrite, fork and revision operations consume the effective message projection+and thus fold its state into their new payloads.++## Consequences++A review update writes only its IDs and state instead of retained history.+Target lookup scans cached identities and reads only its selected message;+building a cold layout parses identities once without retaining message bodies.+The first mutation after restart still performs the existing storage-integrity+verification. Ordinary reads+also read the small state log. Deliberate transcript replacement and other+metadata writers retain their existing rewrite behavior.++The line type is additive to transcript format 2 and requires no database or+RPC migration. Older readers skip it and may display stale review-card state;+the separate snapshot metadata still prevents a second destructive rollback.+Intentional rewrites fold state into canonical message payloads.++## Alternatives++- Calling `update_message` still copies all historical bytes for a non-tail+ message and therefore leaves the reported review trigger.+- Appending the whole tool message creates a new physical message position.+- A separate metadata file adds another authoritative storage and recovery+ lifecycle; the existing transcript append path already provides durability.diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex c979a72f0..5210fa326 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -259,6 +259,24 @@ snapshot directory with `session.delete` and sweeps directories whose sessionno longer exists at startup. A snapshot is never inferred from Git, so a latercommit does not remove historical review evidence.+Review rollback state is persisted as a small append-only `tool_review_state`+line (`messageId`, `snapshotId`, `state`) in the live transcript. It changes no+message position, `seq`, `turn_id`, search text, or message count. Readers apply+the latest state for the matching tool message and snapshot after decoding the+selected messages, including bounded windows and nested-tool navigation.+Repeated acknowledgements of the same state append nothing. Resolving the+target scans cached message identities and decodes only its record; historical bodies+are not materialized as a session-wide `UiMessage` array.++The transcript layout separately indexes state-line offsets. Its disposable+disk-cache version is 3; older caches are rebuilt from the JSONL source. A+deliberate rewrite or revision archive stores the effective state in its message+payload, so no mutation log is needed to restore that payload. The snapshot's+own metadata continues to guard repeated rollback. Older app versions that+ignore this additive line type can show the previous card state until it is+folded into a rewritten message; they still enforce the snapshot rollback guard.+No SQLite schema or RPC contract changes are involved.+### 2.1 Transcript files (D119)`sessions/<sessionId>.jsonl` — first line is a session header, then one line@@ -269,6 +287,7 @@ per message; `seq` is implied by line order:{"type":"message","id":"m1","role":"user","createdAt":"…","blocks":[{"type":"text","text":"…"}]}{"type":"message","id":"m2","role":"tool","toolName":"Write","blocks":[{"type":"tool_call","callId":"c1","args":{},"result":{},"status":"success"}]}{"type":"message","id":"m3","role":"assistant","createdAt":"…","blocks":[{"type":"thinking","text":"…"},{"type":"text","text":"…"}],"meta":{"usage":{},"modelId":"…"}}+{"type":"tool_review_state","messageId":"m2","snapshotId":"snapshot-1","state":"rolledBack"}{"type":"compaction","id":"cp1","summary":"…","firstKeptMessageId":"m2","throughMessageId":"m3","tokensBefore":917000,"retainedTail":[…],"providerId":"…","modelId":"…","createdAt":"…"}```@@ -1550,8 +1569,15 @@ cached read is proportional to the requested page. Consequences:prefix before reuse. Missing, old, unknown, corrupt, or mismatched caches areignored and rebuilt from the JSONL source. Cache read/write failures arediagnostic only and do not make the session unreadable.-- A matching identity and complete prefix permits append-only incremental- scanning. A transcript rewrite invalidates both in-memory and disk layouts+- Format 3 additionally caches parsed message identities, with malformed rows+ retaining an unresolved identity for explicit validation on point reads.+ A cold scan parses each identity once; cached identity lookup reads only the+ selected message line and verifies its ID before returning its position.+- Reuse requires a matching identity and modification/change-time generation.+ Host-owned appends from that proven generation extend an in-memory prefix+ incrementally. A lagging disk cache or an unknown change forces a rescan,+ including an equal-length ID edit followed by append. A transcript rewrite+ invalidates both in-memory and disk layoutsonly after its atomic replacement succeeds; delete also removes both. Cacheinvalidation stays in transcript rewrite/delete ownership, not the genericatomic-swap helper used by unrelated files.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 651ef0d22..c5d973efe 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -8441,6 +8441,30 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.3,484-message transcript, three follow-up turns, restart, and a revisionround trip. Set `PI_DESKTOP_HOST_BIN` to a host built from the candidate.+#### E2E-REVIEW-append-state: Rolling back a historical tool card does not rewrite its session++- **Preconditions**: An isolated real Host process, a temporary workspace with+ a file changed by `Write`, and a transcript with 16 MiB of synthetic retained+ tool output after the review-owning message. Use `--large` for 384 MiB.+- **Steps**: Run `review.rollback`, compare the transcript prefix hash and+ appended bytes, read the review with a one-message `messageAround` window,+ read the tail, restart the Host, and retry the same rollback.+- **Expected**: Workspace bytes are restored. The original transcript prefix+ is unchanged and fewer than 256 bytes are appended. The selected card reads+ `rolledBack` before and after restart, its original position and the last+ message remain correct, and message count is unchanged. Retrying returns+ `alreadyRolledBack` without appending another state record.+- **Specs linked**: `03-runtime/04-data-storage.md` §2.0; ADR+ [append-only-review-state](../../adr/append-only-review-state.md).+- **Acceptance**: C (conversation), F (persistence), Quality.+- **Milestone**: M6.+- **Status**: Automated by `pnpm test:e2e:review-state`; set+ `PI_DESKTOP_HOST_BIN` to the candidate Host binary. No provider or user data+ is used. `transcripts::review_state_tests` additionally covers duplicate IDs,+ snapshot isolation, disk cache reuse, intentional rewrites and torn appends.+ This validates the review-state trigger in #1836; it does not assert Windows+ UI timing or eliminate full rewrites for deliberate history replacement.+#### E2E-246: Retrying a large session truncates without a whole-transcript RPCdiff --git a/package.json b/package.jsonindex c336ae95a..e0d8751a5 100644--- a/package.json+++ b/package.json@@ -32,6 +32,7 @@"test:e2e:rpc-unicode": "node scripts/e2e-rpc-unicode.mjs","test:e2e:tool-result-persistence": "node --max-old-space-size=4096 scripts/e2e-tool-result-persistence.mjs","test:e2e:transcript-cache": "node scripts/e2e-transcript-cache.mjs",+ "test:e2e:review-state": "node scripts/e2e-review-state-persistence.mjs","test:e2e:plan": "node scripts/e2e-plan.mjs","test:e2e:plan-history": "node scripts/e2e-plan-history.mjs","test:e2e:plan-ui": "node scripts/e2e-plan-ui.mjs",diff --git a/scripts/e2e-review-state-persistence.mjs b/scripts/e2e-review-state-persistence.mjsnew file mode 100644index 000000000..7b81c68ed--- /dev/null+++ b/scripts/e2e-review-state-persistence.mjs@@ -0,0 +1,122 @@+#!/usr/bin/env node+/** Real Host rollback and restart, with an isolated synthetic large transcript. */+import assert from "node:assert/strict";+import { createHash } from "node:crypto";+import { createReadStream } from "node:fs";+import { mkdir, mkdtemp, open, readFile, rm, stat, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { performance } from "node:perf_hooks";+import { Host, resolveHostBinary } from "./e2e/host.mjs";+import { configureSession, createSession } from "./e2e/session.mjs";++const temp = await mkdtemp(join(tmpdir(), "pi-review-state-e2e-"));+const workspace = join(temp, "workspace");+const dataDir = join(temp, "data");+const host = new Host(resolveHostBinary(), dataDir);+const createdAt = "2026-10-28T00:00:00Z";+const historyMiB = process.argv.includes("--large") ? 384 : 16;++async function prefixHash(path, length) {+ const hash = createHash("sha256");+ for await (const chunk of createReadStream(path, { start: 0, end: length - 1 })) {+ hash.update(chunk);+ }+ return hash.digest("hex");+}++async function suffix(path, start) {+ const file = await open(path, "r");+ try {+ const bytes = Buffer.alloc((await file.stat()).size - start);+ const { bytesRead } = await file.read(bytes, 0, bytes.length, start);+ assert.equal(bytesRead, bytes.length);+ return bytes.toString("utf8");+ } finally {+ await file.close();+ }+}++try {+ await mkdir(workspace);+ await writeFile(join(workspace, "review.txt"), "before\n");+ await host.start();+ const session = await createSession(host, workspace, "Large review rollback");+ await configureSession(host, session, "agent", "auto");+ const written = await host.call("tools.execute", {+ sessionId: session.id,+ toolCallId: "review-write",+ toolName: "Write",+ args: { path: "review.txt", content: "after\n" },+ mode: "agent",+ });+ assert.equal(written.ok, true);+ const review = written.content.review;+ assert.equal(review.state, "active");+ const append = (message) => host.call("session.appendMessage", { sessionId: session.id, message });+ await append({+ id: review.messageId,+ role: "tool",+ toolCallId: "review-write",+ toolName: "Write",+ toolResult: { details: written.content },+ toolStatus: "success",+ content: "Wrote review.txt",+ createdAt,+ });+ const body = "x".repeat(1024 * 1024);+ for (let index = 0; index < historyMiB; index++) {+ await append({+ id: `history-${index}`, role: "tool", toolName: "Read",+ toolCallId: `history-${index}`, toolStatus: "success",+ toolResult: { content: body }, content: "Retained tool output", createdAt,+ });+ }+ const path = join(dataDir, "sessions", `${session.id}.jsonl`);+ // Opening the conversation builds its derived layout once. The rollback+ // must then locate a historical card without re-reading retained bodies.+ const openingStarted = performance.now();+ await host.call("session.get", { id: session.id, messageLimit: 1, contentLimit: 100 });+ const coldOpenMs = performance.now() - openingStarted;+ const before = await stat(path);+ const hash = await prefixHash(path, before.size);+ const started = performance.now();+ const outcome = await host.call("review.rollback", { sessionId: session.id, snapshotId: review.snapshotId });+ const elapsedMs = performance.now() - started;+ assert.equal(outcome.status, "rolledBack");+ assert.equal(await readFile(join(workspace, "review.txt"), "utf8"), "before\n");+ const after = await stat(path);+ const appendedBytes = after.size - before.size;+ assert.ok(appendedBytes > 0 && appendedBytes < 256);+ assert.equal(await prefixHash(path, before.size), hash, "retained transcript bytes must be untouched");+ const update = JSON.parse(await suffix(path, before.size));+ assert.deepEqual(update, {+ type: "tool_review_state", messageId: review.messageId,+ snapshotId: review.snapshotId, state: "rolledBack",+ });++ async function verify() {+ const { session: page } = await host.call("session.get", {+ id: session.id, messageAround: review.messageId, messageLimit: 1,+ });+ assert.equal(page.messages[0].id, review.messageId);+ assert.equal(page.messages[0].toolResult.details.review.state, "rolledBack");+ assert.equal(page.messageCount, historyMiB + 1);+ const { session: tail } = await host.call("session.get", { id: session.id, messageLimit: 1, contentLimit: 100 });+ assert.equal(tail.messages[0].id, `history-${historyMiB - 1}`);+ }+ await verify();+ await host.restart();+ await verify();+ const repeated = await host.call("review.rollback", { sessionId: session.id, snapshotId: review.snapshotId });+ assert.equal(repeated.status, "alreadyRolledBack");+ assert.equal((await stat(path)).size, after.size, "retries must not append duplicate state");+ console.log(JSON.stringify({+ scenario: "review-state-persistence", transcriptBytes: before.size,+ appendedBytes, coldOpenMs: Math.round(coldOpenMs), elapsedMs: Math.round(elapsedMs),+ restart: "pass", result: "pass",+ }));+} finally {+ await host.stop();+ await rm(temp, { recursive: true, force: true });+}diff --git a/scripts/e2e-transcript-cache.mjs b/scripts/e2e-transcript-cache.mjsindex 95d2e445c..8eb19ccdc 100644--- a/scripts/e2e-transcript-cache.mjs+++ b/scripts/e2e-transcript-cache.mjs@@ -128,7 +128,7 @@ try {let hasDiskCache = false;try {const cache = await readFile(layoutPath, "utf8");- assert.ok(cache.startsWith("PI-DESKTOP-TRANSCRIPT-LAYOUT 2\n"));+ assert.ok(cache.startsWith("PI-DESKTOP-TRANSCRIPT-LAYOUT 3\n"));hasDiskCache = true;} catch (error) {if (error.code !== "ENOENT") throw error;@@ -239,7 +239,7 @@ try {if (error.code !== "ENOENT") throw error;}if (hasDiskCache) {- assert.ok(rebuiltCache?.startsWith("PI-DESKTOP-TRANSCRIPT-LAYOUT 2\n"));+ assert.ok(rebuiltCache?.startsWith("PI-DESKTOP-TRANSCRIPT-LAYOUT 3\n"));}const damagedSession = await host.call("session.create", {