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(host-core): reference a live regenerate branch instead of copying it
vastsaffb17099498a
diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rsindex 22f73d3d2..c94245a5e 100644--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@ -2127,7 +2127,96 @@ fn compaction_valid_for_records(compaction: &CompactionRecord, records: &[Messag})}+/// Store in full every regenerate family this rewrite is about to drop.+///+/// A branch that is still live is referenced rather than copied, so its+/// reference line only resolves while its root is in the transcript. A rewrite+/// that removes the root — deleting the turn that owns the family, a regenerate+/// or edit that cuts a later family away, a revision switch that restores a+/// prefix from before it — would otherwise leave the file naming a suffix that+/// no longer exists. Every dropped family is written out first, from `before`,+/// exactly as a revision switch writes the branch it pages away from.+///+/// A rewrite that only shortens a live branch is left alone: the reference then+/// describes the transcript as the user just made it, which is the same+/// authority the durable transcript has everywhere else.+///+/// `already_stored` names families the caller has just written itself, so the+/// payload is not written twice.+fn archive_dropped_live_branches(+ db: &Database,+ session_id: &str,+ before: &[UiMessage],+ kept: &[UiMessage],+ already_stored: &[String],+) -> Result<()> {+ for root in dropped_revision_roots(db, session_id, kept, already_stored)? {+ archive_live_branch(db, session_id, &root, before)?;+ }+ Ok(())+}++/// The families indexed for this session whose root `kept` no longer holds: the+/// branches a rewrite from the current transcript would strand. Index rows only,+/// so a rewrite that drops nothing pays no transcript read.+fn dropped_revision_roots(+ db: &Database,+ session_id: &str,+ kept: &[UiMessage],+ already_stored: &[String],+) -> Result<Vec<String>> {+ let conn = db.conn();+ let mut stmt = conn.prepare_cached(+ "SELECT DISTINCT root_user_id FROM message_revisions WHERE session_id = ?1",+ )?;+ let rows = stmt.query_map(params![session_id], |row| row.get::<_, String>(0))?;+ let mut dropped = Vec::new();+ for row in rows {+ let root = row?;+ if already_stored.iter().any(|stored| stored == &root) {+ continue;+ }+ if live_branch_start(kept, &root).is_none() {+ dropped.push(root);+ }+ }+ Ok(dropped)+}++/// Rewrite a session's whole transcript from `messages`, leaving every+/// regenerate family the rewrite would drop stored in full.pub fn replace_messages(db: &Database, session_id: &str, messages: &[UiMessage]) -> Result<()> {+ rewrite_transcript(db, session_id, messages, &[])+}++/// Rewrite the transcript and reseat the index rows.+///+/// `already_stored` names families the caller stored on its own way here, so+/// [`archive_dropped_live_branches`] does not write them a second time.+fn rewrite_transcript(+ db: &Database,+ session_id: &str,+ messages: &[UiMessage],+ already_stored: &[String],+) -> Result<()> {+ // The guard writes from the OLD transcript, so it has to read it before the+ // rewrite below replaces it — and only when a family is actually dropped.+ if !dropped_revision_roots(db, session_id, messages, already_stored)?.is_empty() {+ if let Some(detail) = get_session(db, session_id)? {+ archive_dropped_live_branches(+ db,+ session_id,+ &detail.messages,+ messages,+ already_stored,+ )?;+ }+ }+ rewrite_transcript_body(db, session_id, messages)+}++/// The rewrite itself, with no regard for the revisions the caller drops.+fn rewrite_transcript_body(db: &Database, session_id: &str, messages: &[UiMessage]) -> Result<()> {let session_created = session_created_at(db, session_id)?;crate::session_collaboration::validate_replacement(db, session_id, messages)?;let (records, texts) = records_and_texts(messages);@@ -2250,7 +2339,14 @@ pub fn truncate_from(let aborted_turn_id = abort_running_turn(db, session_id)?;let revision = archive_discarded_regenerate_branch(db, session_id, discarded)?;- replace_messages(db, session_id, kept)?;+ // The regenerate root's branch is already stored above; every OTHER family+ // the cut takes away is not, and the guard in `rewrite_transcript` stores+ // those. Skipping the one that is done keeps it from being written twice.+ let already_stored: Vec<String> = revision+ .iter()+ .map(|meta| meta.root_user_id.clone())+ .collect();+ rewrite_transcript(db, session_id, kept, &already_stored)?;let _ = transcripts::remove_inflight(db.data_dir(), session_id);Ok(TruncateFromResult {ok: true,@@ -2287,6 +2383,10 @@ fn abort_running_turn(db: &Database, session_id: &str) -> Result<Option<String>>/// Archive the discarded regenerate tail the way Electron main used to, but/// without copying the branch across the JSON-RPC pipe.+///+/// The tail is about to be cut out of the transcript, so this always writes the+/// payload in full: a live reference would stop resolving the moment+/// `truncate_from` replaces the file.fn archive_discarded_regenerate_branch(db: &Database,session_id: &str,@@ -2547,6 +2647,82 @@ pub fn refresh_message_revision(})}+/// Record a branch that is still live as revision `revision_index` of its user+/// root, without copying its messages: while the branch is live the transcript+/// *is* the payload, so the file gets its identity and turn attribution, and+/// the index row gets the count the pager reads.+///+/// The line is written before the index transaction, like every other+/// transcript write, so a crash between the two costs an index row rather than+/// content.+fn save_live_branch_revision(+ db: &Database,+ session_id: &str,+ root_user_id: &str,+ revision_index: i64,+ branch: &[UiMessage],+) -> Result<MessageRevisionSummary> {+ let conn = db.conn();+ let existing: Option<(i64, bool)> = conn+ .query_row(+ "SELECT created_at, is_active FROM message_revisions+ WHERE session_id = ?1 AND root_user_id = ?2 AND revision_index = ?3",+ params![session_id, root_user_id, revision_index],+ |row| Ok((row.get(0)?, row.get::<_, i64>(1)? != 0)),+ )+ .optional()?;+ let created = existing.map_or_else(now_ms, |(created, _)| created);+ let is_active = existing.is_none_or(|(_, is_active)| is_active);+ transcripts::append_live_revision(+ db.data_dir(),+ session_id,+ &transcripts::LiveRevisionRecord {+ root_user_id: root_user_id.to_string(),+ revision_index,+ created_at: ms_to_ts(created),+ },+ )?;+ let tx = conn.unchecked_transaction()?;+ if existing.is_some() {+ tx.prepare_cached(+ "UPDATE message_revisions SET message_count = ?4+ WHERE session_id = ?1 AND root_user_id = ?2 AND revision_index = ?3",+ )?+ .execute(params![+ session_id,+ root_user_id,+ revision_index,+ branch.len() as i64+ ])?;+ } else {+ tx.prepare_cached(+ "UPDATE message_revisions SET is_active = 0+ WHERE session_id = ?1 AND root_user_id = ?2",+ )?+ .execute(params![session_id, root_user_id])?;+ tx.prepare_cached(+ "INSERT INTO message_revisions (+ id, session_id, root_user_id, revision_index, is_active, message_count, created_at+ ) VALUES (?1, ?2, ?3, ?4, 1, ?5, ?6)",+ )?+ .execute(params![+ Uuid::new_v4().to_string(),+ session_id,+ root_user_id,+ revision_index,+ branch.len() as i64,+ created+ ])?;+ }+ tx.commit()?;+ Ok(MessageRevisionSummary {+ revision_index,+ is_active,+ created_at: ms_to_ts(created),+ message_count: branch.len() as i64,+ })+}+/// Where a revision family starts in the live transcript: the root itself, or/// (after a regenerate gave the live prompt a new id) the first user message/// stamped with that family key.@@ -2566,6 +2742,10 @@ fn live_branch_start(messages: &[UiMessage], root_user_id: &str) -> Option<usize/// (later prompts, error-ended turns that never hit agent_end) would otherwise/// vanish the moment the user pages away and back.///+/// This is also what turns a live reference back into a stored payload: while+/// the branch is live the revisions file holds no copy of it, and this call+/// writes one before the switch below takes the branch away.+////// Returns the branch start in `live` when the family is present at all.fn archive_live_branch(db: &Database,@@ -2681,28 +2861,27 @@ pub fn save_active_branch_revision(let already_archived = existing.iter().any(|revision| revision.revision_index == desired_active);- let mut active = if desired_active > 0 {+ let branch = &messages[root_index..];+ // The branch is still live, so the transcript already holds its payload and+ // this records a reference to it. Refreshing a stored copy here is what made+ // the file quadratic: the copy grew with the branch, so a session that ran N+ // turns wrote O(N²) bytes to restate what the transcript already said. A+ // branch leaves the transcript only through `archive_live_branch` or+ // `archive_discarded_regenerate_branch`, and both write the full copy first.+ let mut active = if already_archived {+ save_live_branch_revision(db, session_id, &root_user_id, desired_active, branch)?;desired_active} else {- existing.len() as i64 + 1+ let next = existing+ .iter()+ .map(|revision| revision.revision_index)+ .max()+ .unwrap_or(0)+ + 1;+ save_live_branch_revision(db, session_id, &root_user_id, next, branch)?;+ next};- let mut archived = false;- if already_archived {- // The branch grew past its stored copy (this turn appended to it).- // Refresh the payload so paging away and back restores all of it.- refresh_message_revision(- db,- session_id,- &root_user_id,- desired_active,- &messages[root_index..],- )?;- } else {- let saved =- save_message_revision(db, session_id, &root_user_id, &messages[root_index..], true)?;- active = saved.revision_index;- archived = true;- }+ let archived = !already_archived;let total = list_message_revisions(db, session_id, &root_user_id)?.len() as i64;if active < 1 {active = total;@@ -2759,11 +2938,33 @@ pub fn activate_message_revision(None => prefix,};- let revision =+ let payload =transcripts::read_revision(db.data_dir(), session_id, root_user_id, revision_index)?.ok_or_else(|| anyhow!("revision payload missing from revisions file"))?;- let archived_turns = revision.turns;- let branch: Vec<UiMessage> = revision.messages.into_iter().map(record_to_ui).collect();+ let archived_turns = payload.turns().clone();+ let branch: Vec<UiMessage> = match payload {+ transcripts::RevisionPayload::Stored(record) => {+ record.messages.into_iter().map(record_to_ui).collect()+ }+ // The branch never left the transcript, so its messages are the live+ // suffix rooted at its user turn — the same slice `archive_live_branch`+ // measured one call ago, and the reason no copy of it is on disk.+ transcripts::RevisionPayload::Live(record) => {+ // The line names the family it belongs to; the slice below is only+ // that family's if the two agree.+ if record.root_user_id != root_user_id || record.revision_index != revision_index {+ return Err(anyhow!(+ "revision payload names {}/{} not {root_user_id}/{revision_index}",+ record.root_user_id,+ record.revision_index+ ));+ }+ let start = live_start.ok_or_else(|| {+ anyhow!("revision payload missing from transcript for {root_user_id}")+ })?;+ live.get(start..).unwrap_or_default().to_vec()+ }+ };let conn = db.conn();let total: i64 = conn.query_row(@@ -2805,6 +3006,17 @@ pub fn activate_message_revision(.into_iter().filter(|record| compaction_valid_for_records(record, &records)).collect();+ // The switch drops everything the restored variant does not contain. Any+ // other family whose root is in that prefix was referenced rather than+ // copied while it was live, so it has to be stored in full before the+ // transcript stops holding it. The target family was archived above.+ archive_dropped_live_branches(+ db,+ session_id,+ &live,+ &combined,+ &[root_user_id.to_string()],+ )?;invalidate_transcript_layout(session_id);transcripts::write_transcript_with_compactions(db.data_dir(),@@ -5262,12 +5474,15 @@ mod tests {assert_eq!(detail.messages[0].active_revision, Some(2));assert_eq!(detail.messages[0].revision_root_id.as_deref(), Some("u1"));- // The archived branch carries the final answer, so switching back to it- // later restores a complete turn.- let branch = transcripts::read_revision(db.data_dir(), &session.id, "u1", 2)+ // The branch carries the final answer, so switching back to it later+ // restores a complete turn. It is still live, so what the file holds is+ // a reference to the transcript suffix rather than a second copy of it.+ let payload = transcripts::read_revision(db.data_dir(), &session.id, "u1", 2).unwrap().expect("branch payload");- assert_eq!(branch.messages.last().unwrap().id, "a9");+ assert!(matches!(payload, transcripts::RevisionPayload::Live(_)));+ let branch = &detail.messages[live_branch_start(&detail.messages, "u1").unwrap()..];+ assert_eq!(branch.last().unwrap().id, "a9");// A one-line stamp must not reseat the index: seq order and the owning// turn stay intact.@@ -5362,15 +5577,17 @@ mod tests {.unwrap();assert!(!saved.archived, "no new index is minted");assert_eq!(saved.revision_count, 1);- let branch = transcripts::read_revision(db.data_dir(), &session.id, "u1", 1)+ // The branch is still live, so the refresh records a reference and the+ // messages stay in the transcript instead of being copied into the+ // revisions file again on every turn.+ let payload = transcripts::read_revision(db.data_dir(), &session.id, "u1", 1).unwrap().unwrap();+ assert!(matches!(payload, transcripts::RevisionPayload::Live(_)));+ let live = get_session(&db, &session.id).unwrap().unwrap().messages;+ let branch = &live[live_branch_start(&live, "u1").unwrap()..];assert_eq!(- branch- .messages- .iter()- .map(|m| m.id.as_str())- .collect::<Vec<_>>(),+ branch.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(),vec!["u1", "u2", "a2"],);let listed = list_message_revisions(&db, &session.id, "u1").unwrap();@@ -5378,6 +5595,284 @@ mod tests {assert!(listed[0].is_active);}+ /// The reason a live branch is referenced and not copied: a branch that is+ /// still in the transcript must cost the revisions file nothing, however+ /// many turns run over it. Copying it per turn is what made a real session+ /// reach 107 MB for 1152 messages — every turn rewrote a tail that had grown+ /// since the turn before, which is O(N²) bytes for content the transcript+ /// already held.+ #[test]+ fn a_live_branch_is_referenced_and_never_copied() {+ let db = test_db();+ let session = create_session(&db, None, None, None, None, None).unwrap();+ let turn = begin_turn(&db, &session.id, Some("p1"), Some("m1")).unwrap();+ let mut root = user_msg("u1", "start", "2025-05-01T00:00:00Z");+ root.revision_count = Some(1);+ root.active_revision = Some(1);+ append_message(&db, &session.id, &root, Some(&turn)).unwrap();++ // Ten finished turns, each appending a sizeable answer, each archived+ // exactly the way a real turn ends.+ for index in 0..10 {+ let mut answer = user_msg(+ &format!("a{index}"),+ &"x".repeat(20_000),+ "2025-05-01T00:01:00Z",+ );+ answer.role = "assistant".into();+ append_message(&db, &session.id, &answer, Some(&turn)).unwrap();+ assert!(+ save_active_branch_revision(&db, &session.id)+ .unwrap()+ .is_some(),+ "the stamped root archives on every turn"+ );+ }++ let path = transcripts::revisions_path(db.data_dir(), &session.id).unwrap();+ let written = std::fs::metadata(&path).unwrap().len();+ assert!(+ written < 8 * 1024,+ "ten turns over a 200 KB branch wrote {written} bytes; \+ a live branch must be referenced, not copied"+ );++ // The branch is still one revision, still counted, and still resolves+ // to every message the transcript holds.+ let listed = list_message_revisions(&db, &session.id, "u1").unwrap();+ assert_eq!(listed.len(), 1);+ assert_eq!(listed[0].message_count, 11);+ assert!(matches!(+ transcripts::read_revision(db.data_dir(), &session.id, "u1", 1)+ .unwrap()+ .unwrap(),+ transcripts::RevisionPayload::Live(_)+ ));+ let live = get_session(&db, &session.id).unwrap().unwrap().messages;+ let branch = &live[live_branch_start(&live, "u1").unwrap()..];+ assert_eq!(branch.len(), 11);+ assert_eq!(branch.last().unwrap().id, "a9");+ // The reference carries no turn map: a live branch's rows are the+ // session's own index rows, so a restore reads their turns from there.+ // That is what keeps the reference constant-sized instead of one entry+ // per branch message on every turn.+ let payload = transcripts::read_revision(db.data_dir(), &session.id, "u1", 1)+ .unwrap()+ .unwrap();+ assert!(payload.turns().is_empty());+ let line_bytes = {+ let raw = std::fs::read_to_string(+ transcripts::revisions_path(db.data_dir(), &session.id).unwrap(),+ )+ .unwrap();+ raw.lines().last().unwrap().len()+ };+ assert!(+ line_bytes < 160,+ "the newest reference is {line_bytes} bytes; it must not grow with the branch"+ );++ // And the restore still re-attaches every message to its turn.+ let restored = activate_message_revision(&db, &session.id, "u1", 1, &[]).unwrap();+ assert_eq!(restored.len(), 11);+ let with_turn: i64 = db+ .conn()+ .query_row(+ "SELECT COUNT(*) FROM messages+ WHERE session_id = ?1 AND turn_id = ?2",+ params![session.id, turn],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(with_turn, 11, "all eleven rows keep their owning turn");+ }++ /// Deleting the turn that owns a regenerate family takes its branch out of+ /// the transcript, so the reference written while that branch was live has+ /// to become a stored payload in the same breath. Otherwise the file names+ /// a suffix that no longer exists and paging back to the variant fails.+ #[test]+ fn dropping_a_branch_root_stores_its_live_reference_first() {+ let db = test_db();+ let session = create_session(&db, None, None, None, None, None).unwrap();+ let turn = begin_turn(&db, &session.id, Some("p1"), Some("m1")).unwrap();+ let mut root = user_msg("u1", "start", "2025-05-01T00:00:00Z");+ root.revision_count = Some(1);+ root.active_revision = Some(1);+ append_message(&db, &session.id, &root, Some(&turn)).unwrap();+ let mut answer = user_msg("a1", "the answer", "2025-05-01T00:01:00Z");+ answer.role = "assistant".into();+ append_message(&db, &session.id, &answer, Some(&turn)).unwrap();+ save_active_branch_revision(&db, &session.id)+ .unwrap()+ .unwrap();+ assert!(matches!(+ transcripts::read_revision(db.data_dir(), &session.id, "u1", 1)+ .unwrap()+ .unwrap(),+ transcripts::RevisionPayload::Live(_)+ ));++ // The user deletes the turn. No revision call of its own runs for it.+ let mut other = user_msg("u2", "another question", "2025-05-01T00:02:00Z");+ other.role = "assistant".into();+ replace_messages(&db, &session.id, &[other]).unwrap();++ let stored = match transcripts::read_revision(db.data_dir(), &session.id, "u1", 1)+ .unwrap()+ .expect("the dropped branch was stored before the rewrite")+ {+ transcripts::RevisionPayload::Stored(record) => record,+ transcripts::RevisionPayload::Live(_) => {+ panic!("a branch that left the transcript must be stored")+ }+ };+ assert_eq!(+ stored+ .messages+ .iter()+ .map(|m| m.id.as_str())+ .collect::<Vec<_>>(),+ vec!["u1", "a1"]+ );+ }++ /// Two user turns each own a regenerate family and both are referenced, then+ /// an edit cuts the earlier one away. The later family's root leaves the+ /// transcript in that same rewrite, so its reference has to be stored in+ /// full — it is not the branch the truncate archives itself.+ #[test]+ fn truncate_from_stores_a_later_familys_reference_first() {+ let db = test_db();+ let session = create_session(&db, None, None, None, None, None).unwrap();+ let turn = begin_turn(&db, &session.id, Some("p1"), Some("m1")).unwrap();+ let mut first = user_msg("u1", "one", "2025-05-01T00:00:00Z");+ first.revision_count = Some(1);+ first.active_revision = Some(1);+ append_message(&db, &session.id, &first, Some(&turn)).unwrap();+ let mut first_answer = user_msg("a1", "first answer", "2025-05-01T00:00:01Z");+ first_answer.role = "assistant".into();+ append_message(&db, &session.id, &first_answer, Some(&turn)).unwrap();+ save_active_branch_revision(&db, &session.id)+ .unwrap()+ .unwrap();++ let mut second = user_msg("u2", "two", "2025-05-01T00:01:00Z");+ second.revision_count = Some(1);+ second.active_revision = Some(1);+ append_message(&db, &session.id, &second, Some(&turn)).unwrap();+ let mut second_answer = user_msg("a2", "second answer", "2025-05-01T00:01:01Z");+ second_answer.role = "assistant".into();+ append_message(&db, &session.id, &second_answer, Some(&turn)).unwrap();+ save_active_branch_revision(&db, &session.id)+ .unwrap()+ .unwrap();++ let second_index =+ list_message_revisions(&db, &session.id, "u2").unwrap()[0].revision_index;+ assert!(matches!(+ transcripts::read_revision(db.data_dir(), &session.id, "u2", second_index)+ .unwrap()+ .unwrap(),+ transcripts::RevisionPayload::Live(_)+ ));++ // Editing the FIRST turn cuts the whole second turn away from the+ // transcript, and only the first family is the regenerate root.+ truncate_from(&db, &session.id, Some("u1"), None).unwrap();++ let stored =+ match transcripts::read_revision(db.data_dir(), &session.id, "u2", second_index)+ .unwrap()+ .expect("the later family was stored before its root left the transcript")+ {+ transcripts::RevisionPayload::Stored(record) => record,+ transcripts::RevisionPayload::Live(_) => {+ panic!("a branch that left the transcript must be stored")+ }+ };+ assert_eq!(+ stored+ .messages+ .iter()+ .map(|m| m.id.as_str())+ .collect::<Vec<_>>(),+ vec!["u2", "a2"]+ );+ }++ /// The other half of the same hazard: a revision switch restores a prefix+ /// from before a later family, and that later family leaves the transcript+ /// without the switch ever naming it.+ #[test]+ fn activate_message_revision_stores_a_later_familys_reference_first() {+ let db = test_db();+ let session = create_session(&db, None, None, None, None, None).unwrap();+ let turn = begin_turn(&db, &session.id, Some("p1"), Some("m1")).unwrap();+ // Family u1 has two variants: the first does not contain u2 at all.+ let mut first = user_msg("u1", "one", "2025-05-01T00:00:00Z");+ first.revision_count = Some(2);+ first.active_revision = Some(2);+ append_message(&db, &session.id, &first, Some(&turn)).unwrap();+ let mut first_answer = user_msg("a1", "v1 answer", "2025-05-01T00:00:01Z");+ first_answer.role = "assistant".into();+ save_message_revision(+ &db,+ &session.id,+ "u1",+ &[first.clone(), first_answer.clone()],+ false,+ )+ .unwrap();+ append_message(&db, &session.id, &first_answer, Some(&turn)).unwrap();++ let mut second = user_msg("u2", "two", "2025-05-01T00:01:00Z");+ second.revision_count = Some(1);+ second.active_revision = Some(1);+ append_message(&db, &session.id, &second, Some(&turn)).unwrap();+ let mut second_answer = user_msg("a2", "second answer", "2025-05-01T00:01:01Z");+ second_answer.role = "assistant".into();+ append_message(&db, &session.id, &second_answer, Some(&turn)).unwrap();+ save_active_branch_revision(&db, &session.id)+ .unwrap()+ .unwrap();++ let second_index =+ list_message_revisions(&db, &session.id, "u2").unwrap()[0].revision_index;+ assert!(matches!(+ transcripts::read_revision(db.data_dir(), &session.id, "u2", second_index)+ .unwrap()+ .unwrap(),+ transcripts::RevisionPayload::Live(_)+ ));++ // Variant 1 of u1 predates u2, so restoring it drops u2 entirely.+ let restored = activate_message_revision(&db, &session.id, "u1", 1, &[]).unwrap();+ assert_eq!(+ restored.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(),+ vec!["u1", "a1"]+ );++ let stored =+ match transcripts::read_revision(db.data_dir(), &session.id, "u2", second_index)+ .unwrap()+ .expect("the later family was stored before the switch dropped it")+ {+ transcripts::RevisionPayload::Stored(record) => record,+ transcripts::RevisionPayload::Live(_) => {+ panic!("a branch that left the transcript must be stored")+ }+ };+ assert_eq!(+ stored+ .messages+ .iter()+ .map(|m| m.id.as_str())+ .collect::<Vec<_>>(),+ vec!["u2", "a2"]+ );+ }+/// The incident shape: a branch archived on agent_end kept growing (later/// prompts, an error-ended turn that never re-archived it). Paging away and/// back must restore all of it, not the copy taken at the first archive.@@ -5513,8 +6008,14 @@ mod tests {let original = transcripts::read_revision(db.data_dir(), &session.id, "u1", 1).unwrap().unwrap();+ let stored = match original {+ transcripts::RevisionPayload::Stored(record) => record,+ transcripts::RevisionPayload::Live(_) => {+ panic!("variant 1 was archived before the switch and stays stored")+ }+ };assert_eq!(- original.messages.last().unwrap().id,+ stored.messages.last().unwrap().id,"a1","variant 1 is intact");@@ -5675,8 +6176,14 @@ mod tests {let payload = transcripts::read_revision(db.data_dir(), &session.id, "u1", 1).unwrap().unwrap();+ let stored = match payload {+ transcripts::RevisionPayload::Stored(record) => record,+ transcripts::RevisionPayload::Live(_) => {+ panic!("a branch that left the transcript must be stored in full")+ }+ };assert_eq!(- payload+ stored.messages.iter().map(|m| m.id.as_str())diff --git a/crates/host-core/src/transcripts.rs b/crates/host-core/src/transcripts.rsindex df0f85dba..d0f3bf297 100644--- a/crates/host-core/src/transcripts.rs+++ b/crates/host-core/src/transcripts.rs@@ -11,10 +11,14 @@//!//! The transcript starts with a `{"type":"session",...}` header line followed//! by one `{"type":"message",...}` line per message; `seq` is implied by line-//! order. The revisions file is append-only — one `{"type":"revision",...}`-//! line per archived branch; the active flag lives in the DB index only.-//! Readers skip unknown line types and a torn trailing line, so new line-//! kinds need no migration and a crash mid-append cannot poison the file.+//! order. The revisions file is append-only and holds one line per archived+//! branch. A branch that is still live needs no payload line — it already is+//! the transcript from its root — so `{"type":"revision_live",...}` records+//! its identity only, while `{"type":"revision",...}` stores the messages of+//! the branches that have left the transcript. The active flag lives in the+//! DB index only. Readers skip unknown line types and a torn trailing line, so+//! new line kinds need no migration and a crash mid-append cannot poison the+//! file.//!//! Unlike scratch dirs these files are user data: they are removed only with//! their session, never by an age or orphan sweep.@@ -89,6 +93,67 @@ pub struct RevisionRecord {pub turns: std::collections::HashMap<String, String>,}+/// One `revision_live` line: a branch whose payload is still the live+/// transcript, so only its identity and turn attribution are stored.+///+/// A branch is the transcript suffix rooted at its user turn, so a live branch+/// is byte-identical to content the session already keeps on disk. Refreshing a+/// stored copy on every finished turn therefore copied that suffix once per+/// turn, and because the suffix grows with every turn the file grew+/// quadratically: one measured session wrote 107 MB to hold 16 MB of unique+/// content, 94% of it tool output copied over and over.+///+/// The line is written only while the branch is live, and it must stop being+/// the reader's answer the moment the branch leaves the transcript. Three+/// writers cover that: `archive_live_branch` (revision switch) and+/// `archive_discarded_regenerate_branch` (regenerate, edit) write the full+/// `revision` line before the rewrite that stops holding the branch, and+/// `archive_dropped_live_branches` does the same for a rewrite that deletes the+/// root turn itself (`session.replaceMessages`). A new path that drops a branch+/// from the transcript without archiving it first would strand its reference.+///+/// It carries no `turns` map, unlike a stored branch, and that is not an+/// omission. That map exists for the messages a restore has to re-attach after+/// the branch left the index; a live branch's messages *are* the session's own+/// index rows, so a restore reads their turns from the index directly. Carrying+/// a copy here would put one entry per branch message on every finished turn —+/// 197 bytes on the first turn of a measured session, 1943 bytes by the+/// fortieth — which is the same quadratic growth this line exists to remove.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct LiveRevisionRecord {+ pub root_user_id: String,+ pub revision_index: i64,+ pub created_at: String,+}++/// The payload of one archived branch, as the revisions file records it.+#[derive(Debug, Clone)]+pub enum RevisionPayload {+ /// The branch messages are stored in the revisions file.+ Stored(RevisionRecord),+ /// The branch is the live transcript from its root. Resolve it against the+ /// transcript the caller already holds: it is the same suffix+ /// `live_branch_start` picks out for that root.+ Live(LiveRevisionRecord),+}++impl RevisionPayload {+ /// message id -> owning turn id, for a branch that has left the index.+ ///+ /// Empty for a live branch: its messages are still the session's own index+ /// rows, so a restore reads their turns from there. See+ /// [`LiveRevisionRecord`].+ pub fn turns(&self) -> &std::collections::HashMap<String, String> {+ static NONE: std::sync::OnceLock<std::collections::HashMap<String, String>> =+ std::sync::OnceLock::new();+ match self {+ RevisionPayload::Stored(record) => &record.turns,+ RevisionPayload::Live(_) => NONE.get_or_init(Default::default),+ }+ }+}+#[derive(Debug, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]struct SessionHeader {@@ -249,6 +314,7 @@ fn sniff_line_kind(line: &str) -> Option<&'static str> {b"compaction" => Some("compaction"),b"session" => Some("session"),b"revision" => Some("revision"),+ b"revision_live" => Some("revision_live"),_ => None,};}@@ -897,42 +963,211 @@ pub fn append_revision(data_dir: &Path, session_id: &str, record: &RevisionRecor.with_context(|| format!("append revisions {}", path.display()))}-/// Find one archived branch by its family key and index (linear scan; the-/// file holds at most a handful of branches per root). The LAST match wins:-/// a crash between file append and index commit can leave a duplicate index-/// on disk, and the newest line is the one the DB accepted.+/// Append the reference line for a branch that is still live. Cheap by+/// construction: this is the line every finished turn writes, so it must not+/// scale with the branch it names.+pub fn append_live_revision(+ data_dir: &Path,+ session_id: &str,+ record: &LiveRevisionRecord,+) -> Result<()> {+ let path = revisions_path(data_dir, session_id)?;+ append_line(&path, None, tagged("revision_live", record)?)+ .with_context(|| format!("append revisions {}", path.display()))+}+/// The kind and the family keys at the top level of one revisions line, read+/// without decoding the line.+///+/// `serde_json` sorts the object it serializes, so `messages` sits between+/// `type` and the family keys and a decoder has to walk the whole payload to+/// reach them. This walks the object's top level and skips each value by depth+/// instead, so a multi-megabyte snapshot belonging to another branch costs a+/// byte scan and no allocation.+///+/// It reads the keys the record itself would carry, nested keys and strings+/// that only look like keys are never considered, so the caller can decide a+/// match on this alone. A line that is not a `revision` / `revision_live`+/// record — including one torn before its last key, which cannot be read at all+/// — returns `None`.+fn revision_line_head(line: &str) -> Option<(&'static str, &str, i64)> {+ let bytes = line.as_bytes();+ let mut index = 0usize;+ while index < bytes.len() && bytes[index].is_ascii_whitespace() {+ index += 1;+ }+ if index >= bytes.len() || bytes[index] != b'{' {+ return None;+ }+ index += 1;+ let mut depth = 1usize;+ let mut kind: Option<&'static str> = None;+ let mut root: Option<&str> = None;+ let mut revision: Option<i64> = None;+ while index < bytes.len() {+ match bytes[index] {+ b'"' => {+ let (key, next) = scan_json_string(bytes, index)?;+ index = next;+ // A top-level member is a key only when ':' follows it; a string+ // in value position is stepped over by the next iteration.+ if depth != 1 {+ continue;+ }+ let mut colon = index;+ while colon < bytes.len() && bytes[colon].is_ascii_whitespace() {+ colon += 1;+ }+ if colon >= bytes.len() || bytes[colon] != b':' {+ continue;+ }+ index = colon + 1;+ while index < bytes.len() && bytes[index].is_ascii_whitespace() {+ index += 1;+ }+ match key {+ b"type" => {+ if bytes.get(index) != Some(&b'"') {+ return None;+ }+ let (value, next) = scan_json_string(bytes, index)?;+ kind = match value {+ b"revision" => Some("revision"),+ b"revision_live" => Some("revision_live"),+ _ => return None,+ };+ index = next;+ }+ b"rootUserId" => {+ if bytes.get(index) != Some(&b'"') {+ return None;+ }+ let (value, next) = scan_json_string(bytes, index)?;+ root = Some(std::str::from_utf8(value).ok()?);+ index = next;+ }+ b"revisionIndex" => {+ let start = index;+ while index < bytes.len()+ && (bytes[index].is_ascii_digit() || bytes[index] == b'-')+ {+ index += 1;+ }+ revision = Some(+ std::str::from_utf8(&bytes[start..index])+ .ok()?+ .parse::<i64>()+ .ok()?,+ );+ }+ _ => {}+ }+ if let (Some(kind), Some(root), Some(revision)) = (kind, root, revision) {+ return Some((kind, root, revision));+ }+ }+ b'{' | b'[' => {+ depth += 1;+ index += 1;+ }+ b'}' | b']' => {+ depth -= 1;+ index += 1;+ if depth == 0 {+ return None;+ }+ }+ _ => index += 1,+ }+ }+ None+}++/// Find one archived branch by its family key and index. The LAST matching line+/// that decodes wins: a crash between file append and index commit can leave a+/// duplicate on disk, the newest line is the one the DB accepted, and a line+/// torn mid-append must not answer for the copy behind it.+///+/// The file is streamed once to record where its matching lines are, and only+/// the newest of them is decoded. Both halves matter for size. `serde_json`+/// sorts the object it serializes, so `messages` sits *before* the family keys+/// and a decoder has to walk the whole payload to reach them; and every refresh+/// of one branch repeats that branch's key, so matching alone would decode the+/// branch once per refresh. A real 107 MB file of eleven snapshots decoded ten+/// of them — 102 MB — to answer with the eleventh.+///+/// `revision_line_head` reads the top level instead of decoding it, so the+/// match decision is the record's own keys and nothing else: text inside a tool+/// result that happens to be spelled like a family key is not a key, and cannot+/// answer for a family it does not belong to.+///+/// A live reference resolves against the transcript, so a branch that is still+/// live is returned without the file holding a second copy of it.pub fn read_revision(data_dir: &Path,session_id: &str,root_user_id: &str,revision_index: i64,-) -> Result<Option<RevisionRecord>> {+) -> Result<Option<RevisionPayload>> {let path = revisions_path(data_dir, session_id)?;- let raw = match fs::read_to_string(&path) {- Ok(raw) => raw,+ let file = match File::open(&path) {+ Ok(file) => file,Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),Err(e) => return Err(e).with_context(|| format!("read {}", path.display())),};- let mut found = None;- for line in raw.lines() {- let line = line.trim();- if line.is_empty() {- continue;+ // (byte offset, line kind) of every matching line, oldest first.+ let mut matches: Vec<(u64, &'static str)> = Vec::new();+ let mut reader = BufReader::new(file);+ let mut line = String::new();+ let mut offset = 0u64;+ loop {+ // A rejected snapshot must not leave its capacity attached to every+ // following read.+ if line.capacity() > 1024 * 1024 {+ line = String::new();}- let Ok(value) = serde_json::from_str::<Value>(line) else {- continue;- };- if value.get("type").and_then(|t| t.as_str()) != Some("revision") {- continue;+ line.clear();+ let read = reader.read_line(&mut line)?;+ if read == 0 {+ break;+ }+ // A torn trailing line has no newline yet. `append_line` terminates it+ // before the next record, which turns it into a complete line that this+ // head read rejects on its own; until then there is nothing after it to+ // find, so the scan is done.+ if !line.ends_with('\n') {+ break;+ }+ if let Some((kind, root, index)) = revision_line_head(line.trim()) {+ if root == root_user_id && index == revision_index {+ matches.push((offset, kind));+ }+ }+ offset += read as u64;+ }+ for (offset, kind) in matches.iter().rev() {+ if line.capacity() > 1024 * 1024 {+ line = String::new();}- let Ok(record) = serde_json::from_value::<RevisionRecord>(value) else {+ line.clear();+ reader.seek(SeekFrom::Start(*offset))?;+ if reader.read_line(&mut line)? == 0 {continue;+ }+ let body = line.trim();+ let decoded = if *kind == "revision_live" {+ serde_json::from_str::<LiveRevisionRecord>(body)+ .ok()+ .map(RevisionPayload::Live)+ } else {+ serde_json::from_str::<RevisionRecord>(body)+ .ok()+ .map(RevisionPayload::Stored)};- if record.root_user_id == root_user_id && record.revision_index == revision_index {- found = Some(record);+ if decoded.is_some() {+ return Ok(decoded);}}- Ok(found)+ Ok(None)}/// Remove a session's transcript, revisions, and any temp leftover@@ -1583,11 +1818,145 @@ mod tests {append_revision(dir.path(), "s1", &rev(2, "second")).unwrap();let found = read_revision(dir.path(), "s1", "u1", 2).unwrap().unwrap();+ let RevisionPayload::Stored(found) = found else {+ panic!("a stored line must read back as a stored payload");+ };assert_eq!(found.messages[0].blocks[0]["text"], "second");assert!(read_revision(dir.path(), "s1", "u9", 1).unwrap().is_none());assert!(read_revision(dir.path(), "s1", "u1", 3).unwrap().is_none());}+ /// The two line kinds coexist in one file and the last matching line is the+ /// answer whichever kind it is: a snapshot written by an older build stays+ /// readable, the reference written after it takes over while the branch is+ /// live, and the full copy written when the branch leaves takes over again+ /// without the reference ever having to be removed.+ #[test]+ fn revisions_resolve_the_newest_line_across_kinds() {+ let dir = tempdir().unwrap();+ let stored = |text: &str| RevisionRecord {+ turns: Default::default(),+ root_user_id: "u1".into(),+ revision_index: 1,+ created_at: "2026-07-26T00:00:00Z".into(),+ messages: vec![record("m", text)],+ };+ let live = LiveRevisionRecord {+ root_user_id: "u1".into(),+ revision_index: 1,+ created_at: "2026-07-26T00:00:00Z".into(),+ };++ append_revision(dir.path(), "s1", &stored("archived")).unwrap();+ append_live_revision(dir.path(), "s1", &live).unwrap();+ assert!(+ matches!(+ read_revision(dir.path(), "s1", "u1", 1).unwrap().unwrap(),+ RevisionPayload::Live(_)+ ),+ "the reference written last is the answer"+ );++ append_revision(dir.path(), "s1", &stored("materialized")).unwrap();+ let found = read_revision(dir.path(), "s1", "u1", 1).unwrap().unwrap();+ let RevisionPayload::Stored(found) = found else {+ panic!("the stored line written last is the answer");+ };+ assert_eq!(found.messages[0].blocks[0]["text"], "materialized");+ }++ /// A branch's messages are arbitrary text, and a transcript prints files. A+ /// tool result that happens to contain the compact spelling of another+ /// family's keys must not be that family's answer: the match is decided on+ /// the line's own top-level keys, not on the bytes somewhere inside it.+ #[test]+ fn a_payload_that_spells_another_family_is_not_an_answer() {+ let dir = tempdir().unwrap();+ let decoy = RevisionRecord {+ turns: Default::default(),+ root_user_id: "u1".into(),+ revision_index: 1,+ created_at: "2026-07-26T00:00:00Z".into(),+ messages: vec![record(+ "m",+ "{\"rootUserId\":\"u2\",\"revisionIndex\":7,\"messages\":[]}",+ )],+ };+ append_revision(dir.path(), "s1", &decoy).unwrap();++ assert!(+ read_revision(dir.path(), "s1", "u2", 7).unwrap().is_none(),+ "text inside a payload is not a family key"+ );+ let RevisionPayload::Stored(found) =+ read_revision(dir.path(), "s1", "u1", 1).unwrap().unwrap()+ else {+ panic!("the family the line actually names is still readable");+ };+ assert_eq!(found.messages.len(), 1);+ }++ /// A crash mid-append is terminated by the next append rather than repaired,+ /// so the fragment becomes a complete line whose head reads and whose body+ /// does not. The newest match has to fall back to the copy behind it instead+ /// of answering with nothing.+ #[test]+ fn a_torn_newest_match_falls_back_to_the_stored_copy() {+ let dir = tempdir().unwrap();+ append_revision(+ dir.path(),+ "s1",+ &RevisionRecord {+ turns: Default::default(),+ root_user_id: "u1".into(),+ revision_index: 1,+ created_at: "2026-07-26T00:00:00Z".into(),+ messages: vec![record("m", "intact")],+ },+ )+ .unwrap();+ let path = revisions_path(dir.path(), "s1").unwrap();++ // The bytes a write that died before its final brace leaves behind, after+ // the next append terminated them and added its own record.+ let torn = tagged(+ "revision",+ &RevisionRecord {+ turns: Default::default(),+ root_user_id: "u1".into(),+ revision_index: 1,+ created_at: "2026-07-26T00:00:00Z".into(),+ messages: vec![record("m", "torn")],+ },+ )+ .unwrap();+ assert!(torn.ends_with('}'));+ {+ let mut file = OpenOptions::new().append(true).open(&path).unwrap();+ file.write_all(&torn.as_bytes()[..torn.len() - 1]).unwrap();+ file.write_all(b"\n").unwrap();+ }+ append_revision(+ dir.path(),+ "s1",+ &RevisionRecord {+ turns: Default::default(),+ root_user_id: "u9".into(),+ revision_index: 1,+ created_at: "2026-07-26T00:00:01Z".into(),+ messages: vec![record("m", "other family")],+ },+ )+ .unwrap();++ let RevisionPayload::Stored(found) =+ read_revision(dir.path(), "s1", "u1", 1).unwrap().unwrap()+ else {+ panic!("the intact copy behind the fragment answers");+ };+ assert_eq!(found.messages[0].blocks[0]["text"], "intact");+ }+#[test]fn remove_is_idempotent_and_clears_both_files() {let dir = tempdir().unwrap();diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex 0b3258fb4..808ff5eb1 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -134,8 +134,28 @@ revisions never rewrites this file:```jsonl{"type":"revision","rootUserId":"u1","revisionIndex":1,"createdAt":"…","messages":[…message records…],"turns":{"<messageId>":"<turnId>"}}+{"type":"revision_live","rootUserId":"u2","revisionIndex":2,"createdAt":"…"}```+A branch is the transcript suffix rooted at its user turn, so a branch that is+**still live** is byte-identical to content the transcript already stores. That+branch gets a `revision_live` line: identity only, no `messages` payload, with+the reader resolving the branch against the transcript. Storing the suffix+instead is what made this file grow quadratically — a measured session wrote+107 MB to hold 16 MB of unique content, because every finished turn rewrote a+tail that had grown since the turn before. `revision` stays the line for a+branch that has **left** the transcript, and it is the only line kind a legacy+file contains.++A reference line is constant-sized (99 bytes for a UUID family in a measured+session) and does not grow with the branch it names. It deliberately omits the+`turns` map a stored branch carries: that map exists for messages a restore has+to re-attach after they left the index, and a live branch's messages *are* the+session's index rows, so a restore reads their turns from the index. A copy here+would put one entry per branch message on every finished turn — measured at 197+bytes on the first turn and 1943 by the fortieth, which is the same quadratic+growth this line kind exists to remove.+Rules:- `blocks` is the canonical block vocabulary (§4.7) — not the UiMessage@@ -145,6 +165,17 @@ Rules:keeps integer ms.- Readers skip unknown `type` lines and a torn trailing line: new line kindsneed no migration, and a crash mid-append cannot poison the file.+- A `revision_live` line is meaningful only while its branch is the live+ transcript suffix. Three writers keep that true: `archive_live_branch`+ (revision switch) and `archive_discarded_regenerate_branch` (regenerate,+ edit) each write the full `revision` line *before* the rewrite that stops+ holding the branch, and `archive_dropped_live_branches` — reached through+ `replace_messages` — does the same when a rewrite deletes the root turn+ itself (message delete, smart Stop). A branch that is no longer live+ therefore always ends with a stored payload, and a reader only ever resolves+ a reference for the branch that is live right now. A new path that drops a+ branch from the transcript without archiving it first would strand that+ branch's reference line.- `compaction` is a model-context checkpoint, not a message — but it isrendered, as a divider row rather than a chat bubble (D203). Readers returnevery message unchanged and separately return **every** still-valid@@ -883,7 +914,9 @@ Archives discarded regenerate branches so users can page previous variantswithout stacking them in the live transcript (D105/D109). One row is onelinear branch rooted at a user turn; the branch **payload** lives in theappend-only `sessions/<id>.revisions.jsonl` (§2.1), keyed by-`(rootUserId, revisionIndex)`.+`(rootUserId, revisionIndex)`. A branch that is still live stores a reference+(`revision_live`) instead of a second copy of a transcript suffix the session+already has; see §2.1.```sqlCREATE TABLE message_revisions (@@ -1125,8 +1158,8 @@ is the source of truth, the index is derived and self-healing.| session fork (`session.fork`) | write a new transcript with remapped message/tool-call ids; copy/remap the checkpoint only when its boundary is included | single tx: clone session configuration, insert child index rows, set `last_seq`; remove child file on failure || regenerate branch save | append revision line (with `revisionIndex`: a refresh line for that existing variant) | index row with `message_count` (+ `is_active` flip); a refresh only updates `message_count` |-| turn-completion branch archive (`session.saveActiveRevision`) | append revision line (a refresh line when the active variant is already archived), then rewrite only the root user's transcript line for the pager stamp | index row with `message_count` (+ `is_active` flip); index rows for other messages untouched |-| revision switch | append a refresh line for the live branch's own variant, read the target branch, atomic transcript rewrite keeping checkpoints whose anchors survive | flip `is_active`, rebuild index rows carrying each surviving message's owning `turn_id`, reset `last_seq` |+| turn-completion branch archive (`session.saveActiveRevision`) | append a `revision_live` reference line — the branch is still live, so its payload is the transcript — then rewrite only the root user's transcript line for the pager stamp | index row with `message_count` (+ `is_active` flip); index rows for other messages untouched |+| revision switch | append a full `revision` line for the live branch's own variant (it is about to leave the transcript, so its reference is materialized), read the target branch, atomic transcript rewrite keeping checkpoints whose anchors survive | flip `is_active`, rebuild index rows carrying each surviving message's owning `turn_id`, reset `last_seq` || import | write transcript file | one tx per session: session row + index rows; on failure the file is removed || session delete | remove both session files after row delete | `DELETE FROM sessions` (cascades); Electron main drops that session's outbox entries (D318) || project delete (`projects.remove`) | remove each owned session's files after its row delete | one tx per session (`DELETE FROM sessions`, cascades) plus the project row and its `projectMemory` kv entry; the project folder on disk is never touched |@@ -1392,7 +1425,11 @@ columns for anything the host filters, joins, sums, or indexes.13. Regenerated assistant variants survive restart in`sessions/<id>.revisions.jsonl`; the live root user turn reloads with`revisionCount` / `activeRevision`, the pager can restore any archived- branch, and switching branches never rewrites the revisions file+ branch, and switching branches never rewrites the revisions file. A branch+ that is still live is referenced, not copied, so repeated turns over one+ branch cost the file nothing; a branch that leaves the transcript is stored+ in full first, and a file written only by an older build still reads back+ message-for-message.14. Completed and failed turns atomically create one durable notification;repeated terminal updates do not duplicate it, aborted turns create none,and the newest-200 cap survives restartdiff --git a/scripts/e2e-smoke.mjs b/scripts/e2e-smoke.mjsindex bfcad1b5f..4d8338600 100755--- a/scripts/e2e-smoke.mjs+++ b/scripts/e2e-smoke.mjs@@ -698,6 +698,133 @@ async function main() {skip("E2E-009-stream", "PI_DESKTOP_TEST_API_KEY not set");}+ // E2E-SESSION-revision-round-trip — a regenerate branch that is still live+ // is a reference on disk, not a second copy of a transcript suffix the+ // session already holds. The reference resolves to the branch as it stands,+ // including messages appended after the reference was written; the branch is+ // stored in full only once it leaves the transcript; and both variants+ // restore through `session.activateRevision`.+ {+ const bound = await host.call("session.create", {+ title: "E2E revision round trip",+ mode: "agent",+ });+ const sessionId = bound.session.id;+ const revisionsPath = join(dataDir, "sessions", `${sessionId}.revisions.jsonl`);+ const readRevisions = () =>+ existsSync(revisionsPath)+ ? readFileSync(revisionsPath, "utf8")+ .split("\n")+ .filter((line) => line.trim())+ .map((line) => JSON.parse(line))+ : [];+ const append = (message) =>+ host.call("session.appendMessage", { sessionId, message });+ const user = (id, text, rootId, count, active) => ({+ id,+ role: "user",+ content: text,+ createdAt: new Date().toISOString(),+ status: "complete",+ revisionRootId: rootId,+ revisionCount: count,+ activeRevision: active,+ });+ const assistant = (id, text) => ({+ id,+ role: "assistant",+ content: text,+ createdAt: new Date().toISOString(),+ status: "complete",+ });+ const ids = (messages) => messages.map((message) => message.id);++ // One live branch, archived twice: the second archive must refresh the+ // reference, not mint a variant.+ const first = randomUUID();+ const firstAnswer = randomUUID();+ const laterAnswer = randomUUID();+ await append(user(first, "first prompt", first, 1, 1));+ await append(assistant(firstAnswer, "first answer"));+ const archived = await host.call("session.saveActiveRevision", { sessionId });+ await append(assistant(laterAnswer, "a later answer on the same branch"));+ const refreshed = await host.call("session.saveActiveRevision", { sessionId });++ const references = readRevisions().filter((line) => line.type === "revision_live");+ const listed = await host.call("session.listRevisions", {+ sessionId,+ rootUserId: first,+ });+ const restored = await host.call("session.activateRevision", {+ sessionId,+ rootUserId: first,+ revisionIndex: 1,+ prefix: [],+ });++ // A regenerate of that prompt discards the second turn, which takes the+ // branch out of the transcript: it has to be stored in full first.+ const second = randomUUID();+ const secondAnswer = randomUUID();+ await append(user(second, "second prompt", first, 2, 2));+ await append(assistant(secondAnswer, "second answer"));+ await host.call("session.saveActiveRevision", { sessionId });+ const truncated = await host.call("session.truncateFrom", {+ sessionId,+ fromMessageId: second,+ });+ const storedForSecond = readRevisions().filter(+ (line) => line.type === "revision" && line.revisionIndex === 2,+ );+ const backToFirst = await host.call("session.activateRevision", {+ sessionId,+ rootUserId: first,+ revisionIndex: 1,+ prefix: [],+ });+ const backToSecond = await host.call("session.activateRevision", {+ sessionId,+ rootUserId: first,+ revisionIndex: 2,+ prefix: [],+ });++ const checks = {+ "archives the live branch as revision 1": archived.saved?.activeRevision === 1,+ "a second archive refreshes instead of minting": refreshed.saved?.archived === false,+ "still one variant after the refresh": refreshed.saved?.revisionCount === 1,+ "the live branch was written as a reference": references.length >= 2,+ "the reference carries no payload": references.every(+ (line) => !("messages" in line) && !("turns" in line),+ ),+ "the reference does not grow with the branch": references.every(+ (line) => JSON.stringify(line).length < 200,+ ),+ "one variant is listed": listed.revisions.length === 1,+ "it counts the whole live branch": listed.revisions[0]?.messageCount === 3,+ "the reference resolves to the branch as it stands": ids(restored.messages).join() ===+ [first, firstAnswer, laterAnswer].join(),+ "the regenerate discarded the second turn": truncated.discardedCount === 2,+ "the branch that left is stored in full": storedForSecond.some(+ (line) => (line.messages ?? []).length === 2,+ ),+ "variant 2 restores its own messages":+ ids(backToSecond.messages).join() === [second, secondAnswer].join(),+ "variant 1 restores the grown branch":+ ids(backToFirst.messages).join() === [first, firstAnswer, laterAnswer].join(),+ };+ const failed = Object.entries(checks)+ .filter(([, ok]) => !ok)+ .map(([name]) => name);+ record(+ "E2E-SESSION-revision-round-trip",+ failed.length === 0,+ failed.length === 0+ ? `refs=${references.length} stored=${storedForSecond.length} v1=3 v2=2`+ : `failed: ${failed.join("; ")}`,+ );+ }+// agent-runtime unit-ish import checktry {await import(pathToFileURL(join(root, "packages/agent-runtime/dist/index.js")).href);