Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
test(storage): pin review state rewrite and append ordering
Seraph-xe35121c940ce
diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rsindex 12b6274a0..070c42541 100644--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@ -5422,6 +5422,67 @@ mod tests {assert_eq!(last_seq, 3);}+ #[test]+ fn truncate_from_folds_review_state_into_the_retained_prefix() {+ 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"+ }}}));+ for message in [+ user_msg("root", "write", "2025-05-01T00:00:00Z"),+ tool,+ user_msg("later-root", "regenerate", "2025-05-01T00:00:02Z"),+ ] {+ append_message(&db, &session.id, &message, None).unwrap();+ }+ assert!(update_tool_review_state(+ &db,+ &session.id,+ "review-tool",+ "snapshot-1",+ "rolledBack"+ )+ .unwrap());+ truncate_from(&db, &session.id, Some("later-root"), None).unwrap();+ let raw = std::fs::read_to_string(+ db.data_dir()+ .join("sessions")+ .join(format!("{}.jsonl", session.id)),+ )+ .unwrap();+ let lines = raw+ .lines()+ .map(|line| serde_json::from_str::<Value>(line).unwrap())+ .collect::<Vec<_>>();+ assert!(!lines.iter().any(|line| line["type"] == "tool_review_state"));+ let stored_tool = lines+ .iter()+ .find(|line| line["id"] == "review-tool")+ .unwrap();+ assert_eq!(+ stored_tool["blocks"][0]["result"]["details"]["review"]["state"],+ "rolledBack"+ );+ let detail = get_session(&db, &session.id).unwrap().unwrap();+ assert_eq!(+ detail+ .messages+ .iter()+ .map(|message| message.id.as_str())+ .collect::<Vec<_>>(),+ ["root", "review-tool"]+ );+ assert_eq!(+ detail.messages[1].tool_result.as_ref().unwrap()["details"]["review"]["state"],+ "rolledBack"+ );+ }+#[test]fn tool_review_state_survives_fork_revision_activation_and_deletion() {let db = test_db();diff --git a/crates/host-core/src/transcripts/review_state_tests.rs b/crates/host-core/src/transcripts/review_state_tests.rsindex 74b5f41f0..3517a0e1f 100644--- a/crates/host-core/src/transcripts/review_state_tests.rs+++ b/crates/host-core/src/transcripts/review_state_tests.rs@@ -157,7 +157,7 @@ fn review_updates_preserve_positions_and_replay_through_warm_and_cold_layouts()"rolledBack");- // A fresh layout loads the disk cache and scans its appended state suffix.+ // A fresh layout rebuilds a lagging disk cache from the current generation.let cold = refresh_layout(dir.path(), "s1", TranscriptLayout::default()).unwrap();assert_eq!(cold.message_count(), 3);assert_eq!(@@ -211,6 +211,51 @@ fn review_state_is_last_write_wins_and_scoped_to_message_and_snapshot() {assert_eq!(state(&page.messages[0]), "rolledBack");}+#[test]+fn equal_length_state_appends_replay_in_file_order_across_cached_reads() {+ let dir = tempdir().unwrap();+ let mut record = tool("target", "snapshot");+ record.blocks[0]["padding"] = json!("x".repeat(3 * 1024 * 1024));+ write_transcript(dir.path(), "s1", CREATED_AT, &[record]).unwrap();+ layout::session_layout(dir.path(), "s1").unwrap();+ let path = transcript_path(dir.path(), "s1").unwrap();+ let update = |state: &str| ToolReviewStateRecord {+ message_id: "target".into(),+ snapshot_id: "snapshot".into(),+ state: state.into(),+ };+ let mut first = tagged("tool_review_state", &update("active")).unwrap();+ let second = tagged("tool_review_state", &update("rolledBack")).unwrap();+ // Equal-sized valid JSON, using actual review states and no timestamp or+ // sleeps: only the physical append order can select the effective state.+ first.push_str(&" ".repeat(second.len() - first.len()));+ assert_eq!(first.len(), second.len());+ let line_bytes = second.len() as u64 + 1;+ let mut previous_len = fs::metadata(&path).unwrap().len();+ for (index, (line, expected)) in [(first, "active"), (second, "rolledBack")]+ .into_iter()+ .enumerate()+ {+ append_line(&path, None, line).unwrap();+ let length = fs::metadata(&path).unwrap().len();+ assert_eq!(length - previous_len, line_bytes);+ previous_len = length;+ let warm = layout::session_layout(dir.path(), "s1").unwrap();+ assert_eq!(warm.message_count(), 1);+ assert_eq!(warm.tool_review_state_offsets.len(), index + 1);+ let cold = refresh_layout(dir.path(), "s1", TranscriptLayout::default()).unwrap();+ for cached in [&warm, &cold] {+ let read =+ read_transcript_window_with_layout(dir.path(), "s1", cached, 0, Some(1)).unwrap();+ assert_eq!(state(&read.messages[0]), expected);+ }+ assert_eq!(+ state(&read_transcript(dir.path(), "s1").unwrap()[0]),+ expected+ );+ }+}+#[test]fn review_append_repairs_a_torn_tail_and_exposes_write_errors() {let dir = tempdir().unwrap();diff --git a/docs/adr/append-only-review-state.md b/docs/adr/append-only-review-state.mdindex 8d451f5f4..dfc03d3f1 100644--- a/docs/adr/append-only-review-state.md+++ b/docs/adr/append-only-review-state.md@@ -35,14 +35,48 @@ flush/fsync append path, then update only the session timestamp. Existingrewrite, fork and revision operations consume the effective message projectionand thus fold its state into their new payloads.+### Rewrite and archive folding++`truncate_from` first calls `get_session`. Its uncapped read reaches+`read_transcript_with_compactions` / `read_transcript_window`, where+`apply_tool_review_states` overlays the appended records before any cut is+chosen. `rewrite_transcript_body` then calls `records_and_texts` / `ui_to_record`+and `write_transcript_with_compactions`: the surviving tool's effective state+is written into its canonical message, and the separate state lines are no+longer needed. The same effective discarded messages reach+`archive_discarded_regenerate_branch` and `save_message_revision` /+`refresh_message_revision`, preserving their state in the archived branch as+well.++`fork_session_through` reads the effective records through `read_transcript`;+`activate_message_revision_with_prefix` combines the effective live prefix and+stored branch before `records_and_texts` serializes them. Coverage includes+`truncate_from_folds_review_state_into_the_retained_prefix` and+`tool_review_state_survives_fork_revision_activation_and_deletion`.++### Ordering++File order is the order of record. Review-state records have no timestamp;+`append_line` writes each complete line and syncs it before returning, while+the calling RPC holds the Host state lock. Sequential reads keep file order,+and indexed reads sort offsets by their byte position, not by a timestamp.+`apply_tool_review_states` visits that sequence in order and replaces the value+for the same `(message_id, snapshot_id)`, so the last appended state wins even+when updates occur within the same clock tick.++`equal_length_state_appends_replay_in_file_order_across_cached_reads` uses+JSON whitespace to make valid `active` and `rolledBack` records exactly equal+in serialized length. Each append must still grow the file, add a distinct+state offset, and preserve last-write-wins state through warm and cold reads.+## ConsequencesA 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+verification. Ordinary reads also read the small state log. Deliberate+transcript replacement and othermetadata writers retain their existing rewrite behavior.The line type is additive to transcript format 2 and requires no database ordiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex c5d973efe..b551f7d92 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -8462,6 +8462,11 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.`PI_DESKTOP_HOST_BIN` to the candidate Host binary. No provider or user datais used. `transcripts::review_state_tests` additionally covers duplicate IDs,snapshot isolation, disk cache reuse, intentional rewrites and torn appends.+ `equal_length_state_appends_replay_in_file_order_across_cached_reads` pins+ file-order precedence for equal-sized state appends through warm and cold+ layouts. `truncate_from_folds_review_state_into_the_retained_prefix` verifies+ that a later truncate removes the state log while retaining the effective+ state in the surviving canonical tool message.This validates the review-state trigger in #1836; it does not assert WindowsUI timing or eliminate full rewrites for deliberate history replacement.