diff --git a/crates/dim-agent-runtime/src/agent.rs b/crates/dim-agent-runtime/src/agent.rs index 26edd54103..bd5c4fe3c6 100644 --- a/crates/dim-agent-runtime/src/agent.rs +++ b/crates/dim-agent-runtime/src/agent.rs @@ -62,7 +62,8 @@ impl CreateSessionOptions { /// completes. Without it, the Session is created under a generated UUIDv4. /// /// The id must be one normal path component, which is what Session - /// command-output storage addresses ([`check_session_id`]); + /// command-output storage addresses ([`check_session_id`]), and have the + /// shape every newly admitted id has ([`check_new_session_id`]); /// [`Agent::create_session`] rejects any other id before it prepares, /// writes or publishes. pub fn prepare(mut self, id: impl Into, prepare: F) -> Self @@ -110,6 +111,33 @@ pub fn check_session_id(id: &str) -> Result<()> { } Ok(()) } +/// The Windows device names a directory can never be named, with or without +/// an extension: on a Windows output volume they alias the device. +const WINDOWS_DEVICE_NAMES: &[&str] = &[ + "con", "prn", "aux", "nul", "com0", "com1", "com2", "com3", "com4", "com5", "com6", "com7", + "com8", "com9", "lpt0", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9", +]; +/// Requires the shape every newly admitted Session id has (#2204): one to +/// sixty-four characters, each a lowercase ASCII letter, digit, underscore or +/// hyphen, and never a Windows reserved device name. Lowercase ASCII has no +/// folding variants, so two ids admitted under this rule can never address +/// the same output directory on a volume that folds case; the length bound +/// and the reserved names close the Windows aliasing and overlong-name +/// hazards by construction. Only creation entries apply it — deletion, a +/// fork's source and restoration keep [`check_session_id`], so ids stored +/// before this rule stay operable. +pub fn check_new_session_id(id: &str) -> Result<()> { + if id.is_empty() + || id.len() > 64 + || !id.bytes().all(|byte| { + byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_' || byte == b'-' + }) + || WINDOWS_DEVICE_NAMES.contains(&id) + { + return Err(AgentError::InvalidInput(format!("invalid Session id {id}"))); + } + Ok(()) +} impl Agent { pub(crate) fn new(builder: AgentBuilder, assembly: Assembly, placement: Placement) -> Self { Self(Arc::new(AgentInner { @@ -144,6 +172,7 @@ impl Agent { let (id, start) = match prepare { Some((id, prepare)) => { check_session_id(&id)?; + check_new_session_id(&id)?; (id, SessionStart::Prepared(prepare)) } None => (Uuid::new_v4().to_string(), SessionStart::Create), diff --git a/crates/dim-app-server/src/cli.rs b/crates/dim-app-server/src/cli.rs index fd9d8c7365..a7af2518c0 100644 --- a/crates/dim-app-server/src/cli.rs +++ b/crates/dim-app-server/src/cli.rs @@ -579,6 +579,7 @@ pub fn run_with( .unwrap_or_else(|| product_home.join("rust")), ) .join(crate::storage::COMMAND_OUTPUT_DIRECTORY); + config.output_root = Some(output_root.clone()); defaults::install_local_execution( &mut builder, ModelProviderPlugin::process, diff --git a/crates/dim-app-server/src/lib.rs b/crates/dim-app-server/src/lib.rs index 5f14c5b34b..cd609999bd 100644 --- a/crates/dim-app-server/src/lib.rs +++ b/crates/dim-app-server/src/lib.rs @@ -82,6 +82,14 @@ pub struct ServerConfig { pub pipe_name: Option, pub websocket_address: Option, pub database_path: Option, + /// The root Session output directories join under, when it is not + /// `/command-output` (session files §3.1): a host + /// whose command-output layout moves away from the database — the CLI's + /// split home, the xtask harness — names it here so the Session-id + /// admission compares resolved output directories against the root the + /// writing side actually uses (#2204). Rust-internal: it stays out of + /// every serialized configuration and protocol surface. + pub output_root: Option, pub target_home: Option, pub product_home: Option, /// The user home the process reports, `$HOME` by default. A host that @@ -147,6 +155,7 @@ impl Default for ServerConfig { pipe_name: None, websocket_address: Some(([127, 0, 0, 1], 0).into()), database_path: None, + output_root: None, target_home: None, product_home: None, platform_home: None, @@ -955,14 +964,21 @@ pub async fn serve(mut builder: AgentBuilder, mut config: ServerConfig) -> Resul if let (Some(path), Some(files_root)) = (&config.database_path, session_files_root) { let path = path.clone(); let assembly_progress = assembly_progress.clone(); + let output_root = config.output_root.clone(); rows.push(register_part( &mut builtins, builder.catalog(), move |_| { - Ok(Box::new(match &assembly_progress { - Some(assembly_progress) => storage::SqliteStoragePlugin::new(path.clone()) - .with_assembly_progress(assembly_progress.clone()), + let plugin = match &output_root { + Some(output_root) => storage::SqliteStoragePlugin::new(path.clone()) + .with_output_root(output_root.clone()), None => storage::SqliteStoragePlugin::new(path.clone()), + }; + Ok(Box::new(match &assembly_progress { + Some(assembly_progress) => { + plugin.with_assembly_progress(assembly_progress.clone()) + } + None => plugin, })) }, )?); diff --git a/crates/dim-app-server/src/storage/sqlite.rs b/crates/dim-app-server/src/storage/sqlite.rs index f6ab5ec27c..0e93ebe777 100644 --- a/crates/dim-app-server/src/storage/sqlite.rs +++ b/crates/dim-app-server/src/storage/sqlite.rs @@ -628,10 +628,13 @@ fn same_schema(actual: &[(String, String)], mut expected: Vec<(&str, String)>) - } /// The read indexes the daemon creates at open: the latest-turn window's /// ([session-history-window §5.1](../../../../docs/design/appserver/session-history-window.md#51-the-derived-index)), -/// the policy window's turn starts, and the event query's by kind, which carries -/// the event id so a kind read needs no table body for it (ADR 019 D4). They -/// carry no data and no decode rule, so they are not part of the format: `schema` -/// and the format gate ignore them, and every open recreates them. +/// the policy window's turn starts, the event query's by kind, which carries +/// the event id so a kind read needs no table body for it (ADR 019 D4), the +/// case-insensitive Session id lookup the creation collision checks run, and +/// the stored ids outside the newly admitted alphabet, which the +/// output-directory conflict lookup reads (#2204). They carry no data and no +/// decode rule, so they are not part of the format: `schema` and the format +/// gate ignore them, and every open recreates them. const DERIVED_INDEXES: &[(&str, &str)] = &[ ( "timeline_history_anchors", @@ -645,6 +648,14 @@ const DERIVED_INDEXES: &[(&str, &str)] = &[ "timeline_policy_turns", "CREATE INDEX IF NOT EXISTS timeline_policy_turns ON timeline_events(session_id, branch_id, kind, sequence, event_id) WHERE kind = 'turn/start'", ), + ( + "agent_sessions_session_id_nocase", + "CREATE INDEX IF NOT EXISTS agent_sessions_session_id_nocase ON agent_sessions(session_id COLLATE NOCASE)", + ), + ( + "agent_sessions_session_id_non_ascii_word", + "CREATE INDEX IF NOT EXISTS agent_sessions_session_id_non_ascii_word ON agent_sessions(session_id) WHERE session_id GLOB '*[^0-9A-Za-z_-]*'", + ), ]; /// The schema objects of `connection`'s database that belong to the format, /// sorted by name. @@ -1269,6 +1280,12 @@ pub struct SqliteStorage { admission: Mutex, idle: tokio::sync::Notify, pub(super) path: PathBuf, + /// The root Session output directories join under (session files §3.1): + /// `/command-output`, or the root an embedding host + /// names through [`SqliteStorage::open_with_output_root`] when its + /// command-output layout differs. The Session-id admission compares a + /// stored id's resolved output directory against this root (#2204). + pub(super) output_root: PathBuf, upgraded_from: Option, /// What the v50 image conversion measured about its own work, kept for a /// flow test that bounds it; feature `testing` only. @@ -1462,11 +1479,22 @@ impl Drop for Operation { } impl SqliteStorage { pub fn open(path: PathBuf) -> Result> { - Self::open_reporting(path, None) + Self::open_reporting(path, None, None) + } + /// Opens the store with the output root its Sessions write under, when + /// the host's command-output layout is not `/command-output`. + /// The admission boundary compares resolved output directories against + /// this root (#2204); every write path of the store shares it. + pub fn open_with_output_root(path: PathBuf, output_root: PathBuf) -> Result> { + Self::open_reporting(path, None, Some(output_root)) } /// Opens the store; with `ctx`, a format upgrade reports its progress to /// that plugin's opening and keeps the CLI's progress note current. - pub(crate) fn open_reporting(path: PathBuf, ctx: Option<&Ctx>) -> Result> { + pub(crate) fn open_reporting( + path: PathBuf, + ctx: Option<&Ctx>, + output_root: Option, + ) -> Result> { let parent = path .parent() .filter(|path| !path.as_os_str().is_empty()) @@ -1890,6 +1918,11 @@ impl SqliteStorage { lease: Some(admission), }), idle: tokio::sync::Notify::new(), + output_root: output_root.unwrap_or_else(|| { + path.parent() + .map(|directory| directory.join(super::COMMAND_OUTPUT_DIRECTORY)) + .unwrap_or_else(|| PathBuf::from(super::COMMAND_OUTPUT_DIRECTORY)) + }), path, upgraded_from, #[cfg(feature = "testing")] @@ -1941,6 +1974,10 @@ impl SqliteStorage { lease: None, }), idle: tokio::sync::Notify::new(), + output_root: path + .parent() + .map(|directory| directory.join(super::COMMAND_OUTPUT_DIRECTORY)) + .unwrap_or_else(|| PathBuf::from(super::COMMAND_OUTPUT_DIRECTORY)), path, upgraded_from: None, #[cfg(feature = "testing")] @@ -2966,15 +3003,25 @@ fn storage_failure(error: AgentError) -> BridgeError { pub struct SqliteStoragePlugin { path: PathBuf, + output_root: Option, assembly: Option>, } impl SqliteStoragePlugin { pub fn new(path: PathBuf) -> Self { Self { path, + output_root: None, assembly: None, } } + /// The output root the host's Sessions write under, when it is not + /// `/command-output` (#2204): the admission boundary + /// compares resolved output directories against the root the writing + /// side actually uses. + pub fn with_output_root(mut self, output_root: PathBuf) -> Self { + self.output_root = Some(output_root); + self + } /// Reports the opening's progress in the startup note after this store's /// own note is gone; the host removes it when its listeners open. pub(crate) fn with_assembly_progress(mut self, assembly: Arc) -> Self { @@ -2990,8 +3037,9 @@ impl Plugin for SqliteStoragePlugin { async fn apply(&self, ctx: &Ctx, (): Self::Deps) -> rutis::Result { let path = self.path.clone(); let reports = ctx.clone(); + let output_root = self.output_root.clone(); let storage = tokio::task::spawn_blocking(move || { - SqliteStorage::open_reporting(path, Some(&reports)) + SqliteStorage::open_reporting(path, Some(&reports), output_root) }) .await .map_err(|error| rutis::Error::from(ErrorKind::PluginFailed(error.into())))??; diff --git a/crates/dim-app-server/src/storage/timeline.rs b/crates/dim-app-server/src/storage/timeline.rs index 4e4b4229b4..244a5ff850 100644 --- a/crates/dim-app-server/src/storage/timeline.rs +++ b/crates/dim-app-server/src/storage/timeline.rs @@ -30,6 +30,7 @@ use rutis::host::{CtxHost, DynPlugin, Effect, Key, TypeKey}; use rutis_bridge::session::{HostDispatch, host_key}; use serde::{Deserialize, Serialize}; use std::{ + cell::Cell, collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque}, ops::RangeInclusive, panic::{AssertUnwindSafe, catch_unwind}, @@ -94,6 +95,7 @@ enum Command { #[cfg(feature = "testing")] pub mod testing { use super::{StoredEvent, TimelineKey}; + use std::path::PathBuf; use std::sync::{Arc, Condvar, Mutex}; use tokio::sync::mpsc; @@ -189,6 +191,104 @@ pub mod testing { released = wake.wait(released).unwrap(); } } + + type ResolutionWatch = ( + PathBuf, + mpsc::UnboundedSender<()>, + Arc<(Mutex, Condvar)>, + ); + static RESOLUTION_WATCHES: Mutex> = Mutex::new(Vec::new()); + + /// One registered watch of the output-root resolution the admission + /// comparison runs (#2204). Feature `testing` only; production builds + /// have no hook. The tests of one process run in parallel, so the watch + /// matches the exact output-root path the store resolves and never + /// observes another test's root. + pub struct RootResolutionWatch { + output_root: PathBuf, + arrivals: mpsc::UnboundedReceiver<()>, + release: Arc<(Mutex, Condvar)>, + } + impl RootResolutionWatch { + /// Resolves once the resolution is entered. For a hold, the + /// resolution thread is parked at that point. + pub async fn arrived(&mut self) { + let _ = self.arrivals.recv().await; + } + /// The arrivals drained so far: how often the watched root resolved. + pub fn count(&mut self) -> usize { + let mut count = 0; + while self.arrivals.try_recv().is_ok() { + count += 1; + } + count + } + /// Lets a held resolution continue; a no-op for a pure observer. + pub fn release(&self) { + let (released, wake) = &*self.release; + *released.lock().unwrap() = true; + wake.notify_all(); + } + } + impl Drop for RootResolutionWatch { + fn drop(&mut self) { + self.release(); + let output_root = std::mem::take(&mut self.output_root); + RESOLUTION_WATCHES + .lock() + .unwrap() + .retain(|(root, ..)| *root != output_root); + } + } + + fn watch(output_root: PathBuf, released: bool) -> RootResolutionWatch { + let (arrived, arrivals) = mpsc::unbounded_channel(); + let release = Arc::new((Mutex::new(released), Condvar::new())); + RESOLUTION_WATCHES + .lock() + .unwrap() + .push((output_root.clone(), arrived, release.clone())); + RootResolutionWatch { + output_root, + arrivals, + release, + } + } + + /// Reports every output-root resolution of `output_root` without + /// disturbing it: the watch counts how often the admission comparison + /// resolves the root at all. + pub fn observe_root_resolutions(output_root: PathBuf) -> RootResolutionWatch { + watch(output_root, true) + } + + /// Parks the next output-root resolution of `output_root` at its entry + /// until [`RootResolutionWatch::release`]. It runs on the resolving + /// thread, so the hold takes no async lock and holds none while it waits. + pub fn hold_root_resolutions(output_root: PathBuf) -> RootResolutionWatch { + watch(output_root, false) + } + + /// Runs at the entry of every output-root resolution; production builds + /// carry no hook. + pub(super) fn resolution(output_root: &std::path::Path) { + let found = { + let watches = RESOLUTION_WATCHES.lock().unwrap(); + watches + .iter() + .filter(|(root, ..)| root == output_root) + .map(|(_, arrived, release)| (arrived.clone(), release.clone())) + .collect::>() + }; + for (arrived, release) in found { + let _ = arrived.send(()); + let (released, wake) = &*release; + let mut released = released.lock().unwrap(); + while !*released { + released = wake.wait(released).unwrap(); + } + } + } } /// One process writer batches every Session; only pending events reside here. @@ -619,6 +719,55 @@ impl From for TimelineBatch { } } +/// Runs a Session-inserting write through the admission's two phases +/// (#2204): the first transaction passes no output root, so a store whose +/// legacy index is empty inserts and commits in that one transaction without +/// a single filesystem probe. When the index is not empty the first +/// transaction reports it and rolls back unwritten, the output root resolves +/// outside the write lock and the connection mutex — the resolution walks the +/// filesystem — and a second transaction re-runs the authoritative conflict +/// lookup against it and the insertion together. +async fn write_with_output_root(db: &Arc, write: W) -> Result<()> +where + W: Fn(&Connection, Option<&OutputRoot>) -> Result + Send + Sync + 'static, +{ + let write = Arc::new(write); + let first = { + let write = write.clone(); + db.run(move |connection| { + let tx = connection + .transaction_with_behavior(TransactionBehavior::Immediate) + .map_err(error)?; + let needs = write(&tx, None)?; + if needs { + return Ok(true); + } + tx.commit().map_err(error)?; + Ok(false) + }) + .await? + }; + if !first { + return Ok(()); + } + let output_root = db.output_root.clone(); + let resolved = tokio::task::spawn_blocking(move || output_root_destinations(&output_root)) + .await + .map_err(error)?; + db.run(move |connection| { + let tx = connection + .transaction_with_behavior(TransactionBehavior::Immediate) + .map_err(error)?; + if write(&tx, Some(&resolved))? { + return Err(error( + "the admission needed the output root after it was resolved", + )); + } + tx.commit().map_err(error) + }) + .await +} + impl SqliteStorage { pub(super) async fn batch_end(self: &Arc, key: TimelineKey, sequence: u64) -> Result<()> { if self.batch_end_at(key, sequence).await? > sequence { @@ -670,12 +819,15 @@ impl SqliteStorage { session: String, config: SessionConfig, ) -> Result<()> { - self.run(move |connection| { - let tx = connection - .transaction_with_behavior(TransactionBehavior::Immediate) - .map_err(error)?; - create_session(&tx, &session, &config, None, SessionOrigin::Unknown)?; - tx.commit().map_err(error) + write_with_output_root(self, move |connection, root| { + create_session( + connection, + root, + &session, + &config, + None, + SessionOrigin::Unknown, + ) }) .await } @@ -1700,6 +1852,7 @@ impl SessionStore { ) -> Result<()> { dim_agent_runtime::check_session_id(source)?; dim_agent_runtime::check_session_id(fork)?; + dim_agent_runtime::check_new_session_id(fork)?; let _ownership = self.ownership.lock().await; if let Some(cwd) = config_cwd(config) { self.reject_deletion(&cwd).await?; @@ -1726,6 +1879,7 @@ impl SessionStore { worktree: Option, ) -> Result<()> { dim_agent_runtime::check_session_id(session_id)?; + dim_agent_runtime::check_new_session_id(session_id)?; let session = session_id.to_owned(); let config = config.clone(); let agent = agent_id.to_owned(); @@ -1758,37 +1912,44 @@ impl SessionStore { }, ) .transpose()?; - self.timeline - .db - .run(move |connection| { - let tx = connection - .transaction_with_behavior(TransactionBehavior::Immediate) - .map_err(error)?; - create_session(&tx, &session, &config, leader.as_deref(), origin)?; - tx.execute( + write_with_output_root(&self.timeline.db, move |connection, output_root| { + if create_session( + connection, + output_root, + &session, + &config, + leader.as_deref(), + origin, + )? { + return Ok(true); + } + connection + .execute( "INSERT INTO session_owners VALUES (?1, ?2, ?3)", params![session, agent, protocol_version], ) .map_err(error)?; - if let Some((repository, root, subtree, now)) = worktree { - tx.execute( + if let Some((repository, root, subtree, now)) = &worktree { + connection + .execute( "INSERT INTO worktree_directories (repository, root, last_used_at_ms) \ VALUES (?1, ?2, ?3) ON CONFLICT (repository, root) \ DO UPDATE SET last_used_at_ms=excluded.last_used_at_ms", params![repository, root, now], ) .map_err(error)?; - tx.execute( + connection + .execute( "INSERT INTO session_worktrees (session_id, repository, root, subtree) \ VALUES (?1, ?2, ?3, ?4) ON CONFLICT (session_id, repository, root) \ DO UPDATE SET subtree=excluded.subtree", params![session, repository, root, subtree], ) .map_err(error)?; - } - tx.commit().map_err(error) - }) - .await + } + Ok(false) + }) + .await } /// Atomically records a Git-verified directory and its Session association. /// Paths must be canonical absolute UTF-8 paths and `subtree` must be inside @@ -2359,13 +2520,633 @@ impl DynPlugin for SessionStorePlugin { } } +/// The stored Session ids equal to `candidate` under the case-insensitive +/// collation (#2204). The covering derived index `agent_sessions_session_id_nocase` +/// resolves the lookup; the caller compares bytes to tell a case-only variant, +/// which it rejects with InvalidInput, from a byte-identical duplicate, which +/// keeps its Storage error. +fn case_conflicts(connection: &Connection, candidate: &str) -> Result> { + let mut rows = Vec::new(); + let mut statement = connection + .prepare_cached( + "SELECT session_id FROM agent_sessions WHERE session_id = ?1 COLLATE NOCASE", + ) + .map_err(error)?; + for row in statement + .query_map([candidate], |row| row.get::<_, String>(0)) + .map_err(error)? + { + rows.push(row.map_err(error)?); + } + Ok(rows) +} + +/// The stored ids outside the alphabet every newly admitted id has, read +/// through the covering partial index `agent_sessions_session_id_non_ascii_word` +/// (#2204): they are the only ids that can share an output directory with a +/// newly admitted one beyond ASCII case folding. A store without legacy rows +/// is empty here, so the lookup is constant-time. +fn non_ascii_word_conflicts(connection: &Connection) -> Result> { + let mut rows = Vec::new(); + let mut statement = connection + .prepare_cached( + "SELECT session_id FROM agent_sessions WHERE session_id GLOB '*[^0-9A-Za-z_-]*'", + ) + .map_err(error)?; + for row in statement + .query_map([], |row| row.get::<_, String>(0)) + .map_err(error)? + { + rows.push(row.map_err(error)?); + } + Ok(rows) +} + +/// The identity of `name` on a volume that folds case — APFS, HFS+ or a +/// Linux casefold directory — as one canonical key: the Unicode +/// default-ignorable code points stripped first, which a casefold volume +/// drops before comparing, then lowercase, uppercase, then ASCII-lowercase. +/// Lowercase alone misses the pairs whose lowercase is the same non-ASCII +/// letter while their uppercase differs; uppercasing in between maps every +/// folding pair onto one key — ASCII case, the Kelvin sign, the long s, ß/ẞ +/// onto ss, the ligatures onto their expansion. +fn casefold_name(name: &str) -> String { + name.chars() + .filter(|c| !is_default_ignorable(*c)) + .collect::() + .to_lowercase() + .to_uppercase() + .to_ascii_lowercase() +} + +/// The Unicode default-ignorable code points a casefold volume strips from a +/// directory name before comparing it. Ranges per the +/// Default_Ignorable_Code_Point property in DerivedCoreProperties.txt +/// (Unicode 15.1): the soft hyphen, combining grapheme joiner, Arabic and +/// Mongolian format characters, the zero-width and directional formatting +/// characters, the Hangul fillers, variation selectors, tag characters and +/// the musical format controls. +fn is_default_ignorable(c: char) -> bool { + matches!(c as u32, + 0x00AD | 0x034F | 0x061C | 0x115F..=0x1160 | 0x17B4..=0x17B5 | 0x180B..=0x180F + | 0x200B..=0x200F | 0x202A..=0x202E | 0x2060..=0x206F | 0x3164 + | 0xFE00..=0xFE0F | 0xFEFF | 0xFFA0 | 0xFFF0..=0xFFF8 + | 0x1BCA0..=0x1BCA3 | 0x1D173..=0x1D17A | 0xE0000..=0xE0FFF) +} + +/// `stored` lowercased under the Windows volume rules: ASCII letters fold, +/// and the dotted capital İ, the dotless ı, the long s and the Kelvin sign +/// map onto their ASCII pair. Windows neither expands ß nor strips ignorable +/// characters; those forms are covered by the casefold rule. +fn windows_lower(stored: &str) -> String { + stored + .chars() + .map(|c| match c { + 'A'..='Z' => c.to_ascii_lowercase(), + '\u{130}' | '\u{131}' => 'i', + '\u{17F}' => 's', + '\u{212A}' => 'k', + other => other, + }) + .collect() +} + +/// Whether two path components can address the same entry on a Windows +/// volume: equal after the syntactic rules — the part before the first +/// colon, which the directory itself and every stream of it share, trailing +/// dots and spaces trimmed — under the Windows case mapping, or one the 8.3 +/// short name the volume can serve the other as. +fn windows_names_share(one: &str, other: &str) -> bool { + let windows_name = |name: &str| { + windows_lower( + name.split(':') + .next() + .unwrap_or(name) + .trim_end_matches(['.', ' ']), + ) + }; + let (one, other) = (windows_name(one), windows_name(other)); + one == other || windows_8_3_share(&one, &other) || windows_8_3_share(&other, &one) +} + +/// Whether `short` can be the 8.3 short name a Windows volume serves `long` +/// as, the directional half of [`windows_names_share`]: the classic form +/// truncates at the stem, so the name must exceed the eight characters the +/// volume caps the short form at. +fn windows_8_3_share(short: &str, long: &str) -> bool { + long.len() > 8 && short.len() <= 8 && windows_8_3_collides(short, long) +} + +/// Whether two path components can address the same entry under the identity +/// rules of a supported filesystem — a volume folding case, or a Windows +/// volume with its colon syntax, trailing characters and 8.3 short names. +fn components_share(one: &str, other: &str) -> bool { + casefold_name(one) == casefold_name(other) || windows_names_share(one, other) +} + +/// Whether `stem` (the Windows form of a stored id, tilde and tail included) +/// can be the 8.3 short name a Windows volume serves `candidate` as: the +/// classic form truncates the long name at the stem, and the hashed form +/// keeps the long name's leading characters, replaces the middle with four +/// hexadecimal checksum digits and appends the tail — so a candidate starting +/// with what precedes those digits collides with it too. The tails generated +/// are ASCII digits whose first digit runs from 1 upward, growing to two and +/// more digits as the collisions of one stem accumulate; the outer length +/// rule already caps the whole short name at eight characters. +fn windows_8_3_collides(stem: &str, candidate: &str) -> bool { + let Some((stem, tail)) = stem.rsplit_once('~') else { + return false; + }; + if stem.is_empty() + || !matches!(tail.bytes().next(), Some(b'1'..=b'9')) + || !tail.bytes().all(|digit| digit.is_ascii_digit()) + { + return false; + } + if candidate.starts_with(stem) { + return true; + } + let letters: Vec = stem.chars().collect(); + letters.len() >= 5 + && letters[letters.len() - 4..] + .iter() + .all(|c| c.is_ascii_hexdigit()) + && candidate.starts_with(&letters[..letters.len() - 4].iter().collect::()) +} + +/// The volume a destination lives on, normalized so that the verbatim forms +/// a canonicalized Windows path carries name the same volume as the plain +/// forms (#2204): `\\?\C:` is `Disk('C')` and `\\?\UNC\host\share` is +/// `Unc(host, share)`. `Volume` is the host volume an output root or a rooted +/// path sits on when no letter or share names it — a POSIX store parsed under +/// Windows rules has no volume, yet every rooted id inherits it. +#[derive(Clone, Debug, PartialEq, Eq)] +enum VolumeAnchor { + Posix, + Disk(char), + Unc(String, String), + Volume, +} + +/// A resolved filesystem destination: the volume it lives on and the +/// components below that volume's anchor, `.` and `..` already consumed. +/// `undecidable` marks a shape no static resolution can place — a device +/// namespace path or a drive-relative one on its own volume — which refuses +/// every candidate rather than a directory it cannot name. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Destination { + anchor: VolumeAnchor, + segments: Vec, + undecidable: bool, +} + +impl Destination { + fn decided(anchor: VolumeAnchor, segments: Vec) -> Self { + Self { + anchor, + segments, + undecidable: false, + } + } + fn undecidable() -> Self { + Self { + anchor: VolumeAnchor::Volume, + segments: Vec::new(), + undecidable: true, + } + } +} + +/// The output root as the filesystem sees it, parsed once per platform's +/// rules (#2204): POSIX separator parsing in `posix`, Windows prefix and +/// separator parsing in `windows`. Each side holds the literal absolute form +/// and, when it differs, the form the longest existing prefix canonicalizes +/// to — `/var` and `/private/var` are the same directory, and a comparison +/// that knew only one spelling would miss the overlap. +struct OutputRoot { + posix: Vec, + windows: Vec, +} + +/// The prefix a Windows parse strips before the segments: the volume the path +/// is anchored to, or the marker that the join keeps the base's anchor. +enum Prefix { + Disk(char), + Unc(String, String), + /// Rooted at the volume of the path it is joined onto (`\abc`). + Rooted, + /// `\\?\` or `\\.\` without a drive letter or UNC share behind it: + /// the device namespace, whose destinations no static comparison places. + Device, + /// `c:rest` with no separator after the colon: relative to the drive's + /// own current directory, which a static check cannot know. + DriveRelative(char), + /// Two leading separators with no usable host and share. + Malformed, + /// No prefix: the join keeps the base. + Join, +} + +fn ascii_prefix_insensitive(text: &str, prefix: &str) -> bool { + text.len() >= prefix.len() + && text.as_bytes()[..prefix.len()].eq_ignore_ascii_case(prefix.as_bytes()) +} + +/// `host\share\rest` with both parts nonempty: the normalized UNC anchor and +/// the rest. Host and share compare case-insensitively, so they normalize +/// lowercase here. +fn split_unc(text: &str) -> Option<(Prefix, &str)> { + let mut parts = text.splitn(3, ['/', '\\']); + let host = parts.next()?; + let share = parts.next()?; + if host.is_empty() || share.is_empty() { + return None; + } + let rest = parts.next().unwrap_or(""); + Some((Prefix::Unc(host.to_lowercase(), share.to_lowercase()), rest)) +} + +/// Parses the Windows prefix of `text` — verbatim drive and UNC forms, +/// ordinary drive and UNC forms, rooted and drive-relative — returning the +/// rest of the string with the prefix removed. +fn windows_prefix(text: &str) -> (Prefix, &str) { + let separator = |byte: u8| byte == b'/' || byte == b'\\'; + let bytes = text.as_bytes(); + if bytes.len() >= 2 && separator(bytes[0]) && separator(bytes[1]) { + let rest = text[2..].trim_start_matches(['/', '\\']); + if let Some(device) = rest.strip_prefix('?') { + let device = device.trim_start_matches(['/', '\\']); + if ascii_prefix_insensitive(device, "unc") { + let after = device[3..].trim_start_matches(['/', '\\']); + if let Some((anchor, tail)) = split_unc(after) { + return (anchor, tail); + } + return (Prefix::Device, ""); + } + let device_bytes = device.as_bytes(); + if device_bytes.len() >= 2 + && device_bytes[1] == b':' + && device_bytes[0].is_ascii_alphabetic() + { + let tail = device[2..].trim_start_matches(['/', '\\']); + return ( + Prefix::Disk((device_bytes[0] as char).to_ascii_uppercase()), + tail, + ); + } + return (Prefix::Device, ""); + } + if rest.starts_with('.') { + return (Prefix::Device, ""); + } + if let Some((anchor, tail)) = split_unc(rest) { + return (anchor, tail); + } + return (Prefix::Malformed, ""); + } + if bytes.first().is_some_and(|byte| separator(*byte)) { + return (Prefix::Rooted, text[1..].trim_start_matches(['/', '\\'])); + } + if bytes.len() >= 2 && bytes[1] == b':' && bytes[0].is_ascii_alphabetic() { + let letter = (bytes[0] as char).to_ascii_uppercase(); + if bytes.len() >= 3 && separator(bytes[2]) { + return ( + Prefix::Disk(letter), + text[3..].trim_start_matches(['/', '\\']), + ); + } + return (Prefix::DriveRelative(letter), &text[2..]); + } + (Prefix::Join, text) +} + +/// Resolution states one id may fork into. A segment of nothing but dots and +/// spaces keeps both its Windows resolution and its literal reading, so the +/// states multiply with the segment count; a segment whose doubling would +/// pass this cap ends the resolution as undecidable — the literal branch the +/// cap would drop is the only one that can prove an overlap, and a comparison +/// that cannot place the destination refuses rather than guessing disjoint. +const RESOLUTION_STATES: usize = 16; + +/// Advances one Windows resolution state over a segment: exact `.` and `..` +/// resolve on every platform, a segment of nothing but dots and spaces +/// normalizes to one of them once the trailing trim consumes the tail — the +/// parent when it begins with `..`, the current directory otherwise — and +/// forks into that resolution reading and the literal one, anything else is a +/// name — pushed raw, since the comparison normalizes trailing characters. +/// `None` when the fork would pass [`RESOLUTION_STATES`]: the bounded +/// comparison cannot establish the destination, so the caller treats the id +/// as undecidable and refuses (#2204). +fn advance_windows(states: Vec>, segment: &str) -> Option>> { + let trimmed = segment.trim_end_matches(['.', ' ']); + if trimmed.is_empty() + && !matches!(segment, "" | "." | "..") + && states.len() * 2 > RESOLUTION_STATES + { + return None; + } + let mut advanced = Vec::new(); + for state in states { + if segment.is_empty() || segment == "." { + advanced.push(state); + continue; + } + if segment == ".." { + let mut state = state; + state.pop(); + advanced.push(state); + continue; + } + if trimmed.is_empty() { + let mut resolved = state.clone(); + if segment.starts_with("..") { + resolved.pop(); + } + advanced.push(resolved); + let mut literal = state; + literal.push(segment.into()); + advanced.push(literal); + continue; + } + let mut state = state; + state.push(segment.into()); + advanced.push(state); + } + Some(advanced) +} + +/// Advances one POSIX resolution state over a segment: only exact `.` and +/// `..` resolve, every other byte sequence — trailing dots and spaces +/// included — is a literal name. +fn advance_posix(state: &mut Vec, segment: &str) { + if segment.is_empty() || segment == "." { + return; + } + if segment == ".." { + state.pop(); + return; + } + state.push(segment.into()); +} + +/// The destinations `stored` resolves to under a POSIX parse: `/` separates, +/// a leading one anchors the path at the POSIX root and replaces the output +/// root, anything else joins below it. +fn posix_destination(root: &Destination, stored: &str) -> Destination { + let (mut segments, anchor) = if stored.starts_with('/') { + (Vec::new(), VolumeAnchor::Posix) + } else { + (root.segments.clone(), root.anchor.clone()) + }; + for segment in stored.split('/') { + advance_posix(&mut segments, segment); + } + Destination::decided(anchor, segments) +} + +/// The destinations `stored` resolves to under a Windows parse — both +/// separators, the prefix handling of [`windows_prefix`], relative segments +/// resolved — one per fork the ambiguous segments take, and `None` for the +/// drive-relative shape provably disjoint from the root's volume. A rooted +/// id inherits the root form's anchor: joining `\abc` onto `C:\x` yields +/// `C:\abc`. +fn windows_destinations(root: &Destination, stored: &str) -> Vec { + let (prefix, text) = windows_prefix(stored); + if let Prefix::DriveRelative(letter) = prefix { + // A drive-relative id resolves against the drive's own current + // directory, which no static comparison knows: undecidable where the + // root can be that drive, disjoint where it provably is not. + if root.anchor == VolumeAnchor::Disk(letter) || root.anchor == VolumeAnchor::Volume { + return vec![Destination::undecidable()]; + } + return Vec::new(); + } + if matches!(prefix, Prefix::Device | Prefix::Malformed) { + return vec![Destination::undecidable()]; + } + let anchor = match &prefix { + Prefix::Join | Prefix::Rooted => root.anchor.clone(), + Prefix::Disk(letter) => VolumeAnchor::Disk(*letter), + Prefix::Unc(host, share) => VolumeAnchor::Unc(host.clone(), share.clone()), + Prefix::DriveRelative(_) | Prefix::Device | Prefix::Malformed => { + unreachable!() + } + }; + // A provably disjoint volume answers the comparison before any segment + // resolution runs, so a state-cap undecidable cannot widen a disjoint + // drive into a refusal (#2204). + if anchors_disjoint(&anchor, &root.anchor) { + return Vec::new(); + } + let mut states = if matches!(prefix, Prefix::Join) { + vec![root.segments.clone()] + } else { + vec![Vec::new()] + }; + for segment in text.split(['/', '\\']) { + let Some(advanced) = advance_windows(states, segment) else { + return vec![Destination::undecidable()]; + }; + states = advanced; + } + states + .into_iter() + .map(|segments| Destination::decided(anchor.clone(), segments)) + .collect() +} + +/// The Windows parse of an absolute root path: the prefix names its anchor, +/// the segments below resolve lexically. Rooted and unanchored forms — a +/// POSIX path read under Windows rules — sit on the host volume. +fn windows_root(text: &str) -> Destination { + let (prefix, rest) = windows_prefix(text); + let mut segments: Vec = Vec::new(); + for segment in rest.split(['/', '\\']) { + if segment.is_empty() || segment == "." { + continue; + } + if segment == ".." { + segments.pop(); + continue; + } + segments.push(segment.into()); + } + let anchor = match prefix { + Prefix::Disk(letter) => VolumeAnchor::Disk(letter), + Prefix::Unc(host, share) => VolumeAnchor::Unc(host, share), + _ => VolumeAnchor::Volume, + }; + Destination::decided(anchor, segments) +} + +/// The POSIX parse of an absolute root path. +fn posix_root(text: &str) -> Destination { + let mut segments: Vec = Vec::new(); + for segment in text.split('/') { + advance_posix(&mut segments, segment); + } + Destination::decided(VolumeAnchor::Posix, segments) +} + +/// The real forms of `output_root`: the absolute literal spelling and the +/// spelling the longest existing prefix canonicalizes to with the missing +/// tail rejoined — the same directory either way once the filesystem +/// resolves it. Canonicalization failure of the whole chain keeps the +/// literal form, which is correct for the fresh paths a new home carries. +fn real_root_forms(output_root: &Path) -> Vec { + let absolute = std::env::current_dir() + .map(|cwd| cwd.join(output_root)) + .unwrap_or_else(|_| output_root.to_path_buf()); + let mut missing: Vec = Vec::new(); + let mut existing = absolute.as_path(); + loop { + match existing.canonicalize() { + Ok(canonical) => { + let mut form = canonical; + for component in missing.iter().rev() { + form.push(component); + } + let mut forms = vec![absolute]; + if form != forms[0] { + forms.push(form); + } + return forms; + } + Err(_) => { + let Some(parent) = existing.parent() else { + return vec![absolute]; + }; + match existing.file_name() { + Some(name) => missing.push(name.to_os_string()), + None => return vec![absolute], + } + existing = parent; + } + } + } +} + +/// The output root's destinations per platform parse. Components are strings +/// because resolution and comparison are textual; a non-UTF-8 component +/// compares by its lossy form, which can only widen a refusal. Resolving the +/// root probes the filesystem, so the admission only runs it outside every +/// write lock, once the legacy index proves a comparison is needed (#2204). +fn output_root_destinations(output_root: &Path) -> OutputRoot { + #[cfg(feature = "testing")] + testing::resolution(output_root); + let mut posix = Vec::new(); + let mut windows = Vec::new(); + for form in real_root_forms(output_root) { + let text = form.to_string_lossy().into_owned(); + for destination in [posix_root(&text), windows_root(&text)] { + let targets = if destination.anchor == VolumeAnchor::Posix { + &mut posix + } else { + &mut windows + }; + if !targets.contains(&destination) { + targets.push(destination); + } + } + } + OutputRoot { posix, windows } +} + +/// Whether two anchors provably never name the same volume: the POSIX root +/// against anything the Windows parse produces, two drive letters, or two +/// UNC shares. Everything else stays undecided — `Volume` can be any letter, +/// and a UNC share can alias a drive — so the segments decide, and where the +/// segments cannot (a UNC path against a non-UNC root) the branch refuses. +fn anchors_disjoint(one: &VolumeAnchor, other: &VolumeAnchor) -> bool { + match (one, other) { + (VolumeAnchor::Posix, anchor) | (anchor, VolumeAnchor::Posix) => { + *anchor != VolumeAnchor::Posix + } + (VolumeAnchor::Disk(a), VolumeAnchor::Disk(b)) => a != b, + (VolumeAnchor::Unc(host_a, share_a), VolumeAnchor::Unc(host_b, share_b)) => { + host_a != host_b || share_a != share_b + } + _ => false, + } +} + +/// Whether one resolved branch overlaps the candidate's output directory: +/// the candidate's directory is the root form with the candidate appended, +/// so a positional walk over the shorter side decides — equality or one side +/// a prefix of the other is an overlap, any divergence within the walk is +/// disjoint. Segments compare under the union of the identity rules a +/// supported filesystem applies. A mixed UNC/non-UNC pair can never prove +/// its segments align on one volume — the share can alias the drive — so it +/// refuses without the walk. +fn branch_overlaps_candidate(branch: &Destination, root: &Destination, candidate: &str) -> bool { + if branch.undecidable { + return true; + } + if anchors_disjoint(&branch.anchor, &root.anchor) { + return false; + } + let unc = |anchor: &VolumeAnchor| matches!(anchor, VolumeAnchor::Unc(_, _)); + if unc(&branch.anchor) != unc(&root.anchor) { + return true; + } + let length = branch.segments.len().min(root.segments.len() + 1); + for position in 0..length { + let root_component = if position < root.segments.len() { + root.segments[position].as_str() + } else { + candidate + }; + if !components_share(&branch.segments[position], root_component) { + return false; + } + } + true +} + +/// Whether a stored Session id can share its output directory with a newly +/// admitted id, judged on the resolved destinations (#2204): the id parses +/// under both platforms' rules, each parse against the root forms of its own +/// platform, and any branch whose destination equals or contains the +/// candidate's directory — or whose destination no static resolution can +/// place — refuses. An id resolving onto the output root or one of its +/// ancestors overlaps every candidate, so it refuses them all until its row +/// is deleted; that is the isolation the refusal protects, not a false +/// positive. Both rule sets apply wherever the store runs, so a store moving +/// between platforms keeps its isolation: refusing too much is safe, missing +/// a collision is not. +fn shares_output_directory(root: &OutputRoot, stored: &str, candidate: &str) -> bool { + for form in &root.posix { + let branch = posix_destination(form, stored); + if branch_overlaps_candidate(&branch, form, candidate) { + return true; + } + } + for form in &root.windows { + for branch in windows_destinations(form, stored) { + if branch_overlaps_candidate(&branch, form, candidate) { + return true; + } + } + } + false +} + +/// Inserts a Session record after the admission check. Returns `true` when +/// `output_root` was `None` and the legacy index is not empty: nothing was +/// inserted, and the caller must resolve the output root outside the write +/// lock and run the insertion again with `Some` (#2204). fn create_session( connection: &Connection, + output_root: Option<&OutputRoot>, session: &str, config: &SessionConfig, leader: Option<&str>, origin: SessionOrigin, -) -> Result<()> { +) -> Result { + dim_agent_runtime::check_new_session_id(session)?; + if reject_conflicting_id(connection, output_root, session)? { + return Ok(true); + } let config = serde_json::to_string(config).map_err(error)?; connection .execute( @@ -2387,7 +3168,8 @@ fn create_session( create_anchor: None, }; insert_branch(connection, session, &info)?; - super::catalog::create(connection, session) + super::catalog::create(connection, session)?; + Ok(false) } /// The creation origin a stored value names. The column's `CHECK` and the /// format gate keep any other text out; reaching this error means the store @@ -2728,7 +3510,9 @@ fn write_batch( // words, whatever line the conversation moved to (session catalog §3.3). if batch.key.branch_id == ROOT_BRANCH_ID && batch.events.first().is_some_and(|record| record.event.sequence <= 256) - && batch.events.iter().any(|record| matches!(&record.event.kind, EventKind::InputMessage(input) if input.user.is_some())) + && batch.events.iter().any(|record| { + matches!(&record.event.kind, EventKind::InputMessage(input) if input.user.is_some()) + }) { super::catalog::refresh_preview(connection, &batch.key.session_id)?; } @@ -3033,10 +3817,20 @@ impl SqliteTimelineStore { .collect(); let (source, fork, config) = (source.to_owned(), fork.to_owned(), config.to_owned()); let reset = fork.clone(); + let output_root = self.db.output_root.clone(); let copied = self .db .run_copy(move |connection| { - copy_fork(connection, &source, &fork, at, &content, &arrays, &config) + copy_fork( + connection, + &output_root, + &source, + &fork, + at, + &content, + &arrays, + &config, + ) }) .await; if copied.is_ok() { @@ -3114,10 +3908,58 @@ fn chunk(connection: &mut Connection, step: impl FnOnce(&Connection) -> Resul Ok(value) } +/// Runs `step` with the admission's two phases (#2204): the first +/// transaction passes no output root, and when the legacy index is not empty +/// the transaction rolls back unwritten, the root resolves outside the write +/// transaction — this connection is the copy's own, so the resolution runs on +/// its blocking thread — and `resolved` keeps it for every later recheck of +/// the copy. A step that reports the need for a root after it was resolved +/// never wrote its transaction, so rolling it back loses nothing. +fn admission_chunk( + connection: &mut Connection, + output_root: &Path, + resolved: &mut Option, + mut step: impl FnMut(&Connection, Option<&OutputRoot>) -> Result<(T, bool)>, +) -> Result { + loop { + let tx = connection + .transaction_with_behavior(TransactionBehavior::Immediate) + .map_err(error)?; + let (value, needs) = step(&tx, resolved.as_ref())?; + if !needs { + tx.commit().map_err(error)?; + std::thread::sleep(Duration::from_millis(2)); + return Ok(value); + } + if resolved.is_some() { + return Err(error( + "the admission needed the output root after it was resolved", + )); + } + tx.rollback().map_err(error)?; + *resolved = Some(output_root_destinations(output_root)); + } +} + /// Copies a fork's rows in bounded transactions; the final transaction /// inserts the session row, so an interrupted copy leaves no Session. +/// +/// A fork id that names a stored Session — byte-identical or only by case — +/// is refused inside the first chunk transaction, before its first write +/// (#2204): the refusal rolls that transaction back, so it writes nothing and +/// no cleanup runs — a cleanup would only ever run against rows the copy +/// itself committed, and that transaction is the copy's only failure point +/// ahead of its first commit. The cleanup of a copy refused later drops the +/// id's rows only while no Session of that exact id exists; one another +/// connection committed during the copy keeps the cleanup from deleting its +/// rows. +#[expect( + clippy::too_many_arguments, + reason = "one parameter per piece of the copy" +)] fn copy_fork( connection: &mut Connection, + output_root: &Path, source: &str, fork: &str, at: u64, @@ -3125,23 +3967,97 @@ fn copy_fork( arrays: &BTreeMap, config: &str, ) -> Result<()> { - let copied = copy_fork_rows(connection, source, fork, at, content, arrays, config); - if copied.is_err() - && let Err(cleanup) = drop_session(connection, fork) - { - tracing::error!(session_id = fork, error = %cleanup, "Incomplete fork rows were kept"); + let committed = Cell::new(false); + let copied = copy_fork_rows( + connection, + output_root, + source, + fork, + at, + content, + arrays, + config, + &committed, + ); + if copied.is_err() && committed.get() { + match drop_fork_rows(connection, fork) { + Ok(true) => {} + Ok(false) => { + tracing::error!( + session_id = fork, + "Incomplete fork rows were kept: a Session of that id was committed during the copy" + ) + } + Err(cleanup) => { + tracing::error!(session_id = fork, error = %cleanup, "Incomplete fork rows were kept") + } + } } copied } +/// Rejects `candidate` when a stored Session id collides with it: equals it +/// under the case-insensitive collation or shares its output directory under +/// a supported filesystem's identity rules. Byte-identical keeps the +/// duplicate's Storage error even when a case variant or a directory-shape +/// collision is stored beside it (#2204); a case-only variant and a +/// directory-shape collision are InvalidInput. +/// +/// The directory comparison judges the legacy rows of the covering partial +/// index against `output_root`, resolved before the call because resolving +/// the root probes the filesystem and must never run inside a write +/// transaction. With `output_root` `None` only the indexed lookups run: an +/// empty index clears the candidate with no filesystem access at all, and a +/// nonempty one returns `true` — undecided — so the caller rolls back, resolves +/// the root outside the write lock, and runs the authoritative check again. +fn reject_conflicting_id( + connection: &Connection, + output_root: Option<&OutputRoot>, + candidate: &str, +) -> Result { + let conflicts = case_conflicts(connection, candidate)?; + if conflicts.iter().any(|stored| stored == candidate) { + return Err(error(format!("Session id {candidate} already exists"))); + } + if !conflicts.is_empty() { + return Err(AgentError::InvalidInput(format!( + "Session id {candidate} differs from a stored one only by case" + ))); + } + let rows = non_ascii_word_conflicts(connection)?; + if rows.is_empty() { + return Ok(false); + } + let Some(root) = output_root else { + return Ok(true); + }; + for stored in rows { + if shares_output_directory(root, &stored, candidate) { + return Err(AgentError::InvalidInput(format!( + "Session id {candidate} would share an output directory with stored Session {stored}" + ))); + } + } + Ok(false) +} + +/// Copies the rows; `committed` flips the moment the first chunk transaction +/// commits, so the caller can tell rows it may clean up apart from a refusal +/// that rolled back before the first write. +#[expect( + clippy::too_many_arguments, + reason = "one parameter per piece of the copy plus its commit report" +)] fn copy_fork_rows( connection: &mut Connection, + output_root: &Path, source: &str, fork: &str, at: u64, content: &[String], arrays: &BTreeMap, config: &str, + committed: &Cell, ) -> Result<()> { let cut = sql_sequence(at)?; // Intermediate chunks need no sync of their own: the final transaction @@ -3149,8 +4065,17 @@ fn copy_fork_rows( connection .pragma_update(None, "synchronous", "NORMAL") .map_err(error)?; + let mut resolved = None; let mut branches = Vec::new(); - chunk(connection, |tx| { + admission_chunk(connection, output_root, &mut resolved, |tx, root| { + // The first conflict check shares this transaction's write lock with + // the copy's first writes: a conflicting Session committed before the + // transaction started is seen here, and none can commit before the + // writes once the lock is held (#2204). A refusal rolls the chunk + // back, so the copy writes nothing. + if reject_conflicting_id(tx, root, fork)? { + return Ok(((), true)); + } branches = tx .prepare("SELECT branch_id, info FROM timeline_branches WHERE session_id=?1") .map_err(error)? @@ -3178,8 +4103,9 @@ fn copy_fork_rows( .map_err(error)?; super::members::branch(tx, fork, id)?; } - Ok(()) + Ok(((), false)) })?; + committed.set(true); for (array, length) in arrays { let mut after = 0; while after < *length { @@ -3272,7 +4198,13 @@ fn copy_fork_rows( connection .pragma_update(None, "synchronous", "FULL") .map_err(error)?; - chunk(connection, |tx| { + admission_chunk(connection, output_root, &mut resolved, |tx, root| { + // The first chunk's check covered the copy's start; this re-check + // closes the race against an insertion committed while the chunks + // copied (#2204). + if reject_conflicting_id(tx, root, fork)? { + return Ok(((), true)); + } // A fork is a new Session of the client that forked it, never its // source's origin (session classification §3.2). tx.execute( @@ -3353,47 +4285,49 @@ fn copy_fork_rows( files::share(tx, source, fork).map_err(error)?; files::share_output(tx, source, fork).map_err(error)?; // A fork is a new Session and does not inherit grants (ADR 012 D1). - Ok(()) + Ok(((), false)) }) } -/// Removes what makes a Session visible in one transaction, then its large -/// Timeline tables in bounded transactions. -fn drop_session(connection: &mut Connection, session: &str) -> Result { - connection - .pragma_update(None, "synchronous", "FULL") - .map_err(error)?; - let released = chunk(connection, |tx| { - let released = files::release(tx, session).map_err(error)?; +/// The rows that make a Session visible: its file and output owners, grants, +/// title, catalog, owner and session rows and its branch directories. +fn drop_visible_rows(tx: &Connection, session: &str) -> Result { + let released = files::release(tx, session).map_err(error)?; + tx.execute( + "UPDATE agent_sessions SET leader_session_id=NULL WHERE leader_session_id=?1 + AND CASE WHEN json_valid(config) THEN json_extract(config, '$.collaborationRole') END IS NOT 'member'", + [session], + ) + .map_err(error)?; + for table in [ + "session_output_owners", + "session_grants", + "session_worktrees", + "session_metadata", + "session_catalog", + "session_owners", + "timeline_branches", + "agent_sessions", + ] { tx.execute( - "UPDATE agent_sessions SET leader_session_id=NULL WHERE leader_session_id=?1 - AND CASE WHEN json_valid(config) THEN json_extract(config, '$.collaborationRole') END IS NOT 'member'", + &format!("DELETE FROM {table} WHERE session_id=?1"), [session], ) .map_err(error)?; - for table in [ - "session_output_owners", - "session_grants", - "session_worktrees", - "session_metadata", - "session_catalog", - "session_owners", - "timeline_branches", - "agent_sessions", - ] { - tx.execute( - &format!("DELETE FROM {table} WHERE session_id=?1"), - [session], - ) - .map_err(error)?; - } - Ok(released) - })?; - // The Session is invisible now; a lost delete chunk only leaves - // unreachable rows for a retry. - connection - .pragma_update(None, "synchronous", "NORMAL") - .map_err(error)?; + } + Ok(released) +} + +/// The large Timeline tables of a Session, in bounded transactions. `owned` +/// gates each transaction together with its delete: a copy cleanup passes a +/// check that the id still names no stored Session, so rows another +/// connection commits under the id are never deleted; a delete passes no +/// gate. +fn drop_timeline_rows( + connection: &mut Connection, + session: &str, + owned: impl Fn(&Connection) -> Result, +) -> Result> { for table in [ "timeline_output_ids", "timeline_member_roots", @@ -3408,7 +4342,10 @@ fn drop_session(connection: &mut Connection, session: &str) -> Result { "timeline_array_elements", ] { loop { - let deleted = chunk(connection, |tx| { + let Some(deleted) = chunk(connection, |tx| { + if !owned(tx)? { + return Ok(None); + } tx.execute( &format!( "DELETE FROM {table} WHERE rowid IN \ @@ -3417,15 +4354,71 @@ fn drop_session(connection: &mut Connection, session: &str) -> Result { [session], ) .map_err(error) - })?; + .map(Some) + })? + else { + return Ok(None); + }; if deleted == 0 { break; } } } + Ok(Some(())) +} + +/// Removes what makes a Session visible in one transaction, then its large +/// Timeline tables in bounded transactions. +fn drop_session(connection: &mut Connection, session: &str) -> Result { + connection + .pragma_update(None, "synchronous", "FULL") + .map_err(error)?; + let released = chunk(connection, |tx| drop_visible_rows(tx, session))?; + // The Session is invisible now; a lost delete chunk only leaves + // unreachable rows for a retry. + connection + .pragma_update(None, "synchronous", "NORMAL") + .map_err(error)?; + drop_timeline_rows(connection, session, |_| Ok(true))?; Ok(released) } +/// The rows a failed fork copy committed, best effort. Every delete shares +/// its transaction with a check that the id still names no stored Session: +/// the copy is the only writer that ever wrote rows of the id without its +/// session row, so while that check holds the rows are provably the copy's +/// own. Once another connection has committed a Session of the id the rows +/// can no longer be told apart, so nothing more is deleted and the copy's +/// rows stay as unreachable rows of the id (#2204). Returns false when such +/// a Session stopped the cleanup. +fn drop_fork_rows(connection: &mut Connection, fork: &str) -> Result { + let unclaimed = |connection: &Connection, id: &str| -> Result { + connection + .query_row( + "SELECT NOT EXISTS(SELECT 1 FROM agent_sessions WHERE session_id=?1)", + [id], + |row| row.get(0), + ) + .map_err(error) + }; + connection + .pragma_update(None, "synchronous", "FULL") + .map_err(error)?; + if !chunk(connection, |tx| { + if !unclaimed(tx, fork)? { + return Ok(false); + } + drop_visible_rows(tx, fork)?; + Ok(true) + })? { + return Ok(false); + } + connection + .pragma_update(None, "synchronous", "NORMAL") + .map_err(error)?; + Ok(drop_timeline_rows(connection, fork, |tx| unclaimed(tx, fork))?.is_some()) +} + /// The content rows the events of `source`'s `main` through `at` reference, /// parsed in bounded holds on read connections. async fn fork_references( diff --git a/crates/dim-app-server/tests/app_server_flow.rs b/crates/dim-app-server/tests/app_server_flow.rs index cbffa2417c..592ba4bbe7 100644 --- a/crates/dim-app-server/tests/app_server_flow.rs +++ b/crates/dim-app-server/tests/app_server_flow.rs @@ -34,5 +34,7 @@ mod storage_flow; mod storage_session_flow; #[cfg(unix)] mod transport_limits; +#[cfg(windows)] +mod windows_output_isolation_flow; #[cfg(not(unix))] mod worktree_removal_flow; diff --git a/crates/dim-app-server/tests/storage_flow.rs b/crates/dim-app-server/tests/storage_flow.rs index e9689ef492..c32e35eece 100644 --- a/crates/dim-app-server/tests/storage_flow.rs +++ b/crates/dim-app-server/tests/storage_flow.rs @@ -55,6 +55,9 @@ mod prompt_migration; #[path = "storage_flow/reclaim.rs"] mod reclaim; +#[path = "storage_flow/admission.rs"] +mod admission; + const INTERPRETER: &str = "dim/context-projection/v4"; fn snapshot(sequence: u64, checkpoint: &ProjectionCheckpoint) -> RecoverySnapshot { let mut snapshot = RecoverySnapshot { @@ -686,7 +689,8 @@ fn schema(connection: &Connection) -> Vec { .prepare( "SELECT sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' \ AND name NOT IN ('timeline_history_anchors', 'timeline_events_by_kind', \ - 'timeline_policy_turns') + 'timeline_policy_turns', 'agent_sessions_session_id_nocase', \ + 'agent_sessions_session_id_non_ascii_word') AND name NOT IN (SELECT name FROM pragma_table_list WHERE type='shadow' AND name LIKE 'timeline_text_fts_%')", ) .unwrap() @@ -8481,7 +8485,14 @@ async fn a_v41_store_upgrades_in_place_once_keeping_internal_launches() { .unwrap() .collect::>() .unwrap(); - assert_eq!(indexed, ["agent_sessions_by_leader"]); + assert_eq!( + indexed, + [ + "agent_sessions_by_leader", + "agent_sessions_session_id_nocase", + "agent_sessions_session_id_non_ascii_word" + ] + ); for (session, expected) in [("s1", "client"), ("member", "internal")] { let origin: String = connection .query_row( diff --git a/crates/dim-app-server/tests/storage_flow/admission.rs b/crates/dim-app-server/tests/storage_flow/admission.rs new file mode 100644 index 0000000000..2ec3b8b505 --- /dev/null +++ b/crates/dim-app-server/tests/storage_flow/admission.rs @@ -0,0 +1,2425 @@ +//! #2204: a new Session id admitted through `CreateSessionOptions::prepare`, +//! `createOwnedSession`, a fork's target or the low-level store creation the +//! `SqliteStorage.createSession` face dispatches to is lowercase ASCII — one +//! to sixty-four characters of `[a-z0-9_-]`, and never a Windows reserved +//! device name — and is rejected with InvalidInput before anything is +//! written. The +//! store refuses a write whose id differs from a stored one only by case, +//! and a write whose id would share an output directory with a stored one +//! under a supported filesystem's identity rules — Unicode folding pairs, +//! default-ignorable code points, the Windows separators, trailing dots and +//! spaces and Unicode mappings, the 8.3 short names, and the relative +//! segments either platform resolves before it accesses the directory. Ids +//! resolving at or outside the output root refuse nothing. Both refusals are +//! InvalidInput, while a byte-identical duplicate keeps its Storage error. A +//! fork refused before its copy starts writes nothing and drops nothing, so +//! it cannot delete the rows of the Session it conflicted with. Ids already +//! stored keep their bytes: restoration reads them as written, deletion plus +//! use as a fork source are unchanged, and deleting the stored row unblocks +//! the id it conflicted with. + +use super::*; + +fn seed_owner(connection: &Connection) { + connection + .execute( + "INSERT INTO agents(agent_id, profile, is_default) VALUES ('owner', ?1, 1)", + [serde_json::to_string(&AgentProfile { + name: "owner".into(), + description: String::new(), + system_prompt: String::new(), + tools: Some(vec![]), + model: None, + }) + .unwrap()], + ) + .unwrap(); +} + +/// A stored record written around every validation, the way a pre-#2204 or +/// external writer could leave it: uppercase letters and all. +fn seed_stored_session(connection: &Connection, session_id: &str) { + let config = serde_json::to_string(&SessionConfig::default()).unwrap(); + connection + .execute( + "INSERT INTO agent_sessions (session_id, config, created_at_ms, origin) \ + VALUES (?1, ?2, 0, 'client')", + params![session_id, config], + ) + .unwrap(); +} + +fn stored_events(connection: &Connection, session_id: &str) -> Vec { + connection + .prepare("SELECT sequence || ':' || body FROM timeline_events WHERE session_id=?1 ORDER BY sequence") + .unwrap() + .query_map([session_id], |row| row.get::<_, String>(0)) + .unwrap() + .collect::>>() + .unwrap() +} + +fn stored_rows(connection: &Connection, session_id: &str) -> i64 { + connection + .query_row( + "SELECT (SELECT count(*) FROM agent_sessions WHERE session_id=?1) + \ + (SELECT count(*) FROM timeline_branches WHERE session_id=?1) + \ + (SELECT count(*) FROM timeline_events WHERE session_id=?1)", + [session_id], + |row| row.get(0), + ) + .unwrap() +} + +#[tokio::test] +async fn prepared_creation_admits_only_lowercase_ascii_ids() { + let database = Database::new(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let store = SqliteTimelineStore::new(db.clone()); + let mut builder = AgentBuilder::new(AgentConfig::default()); + dim_agent_capabilities::defaults::mock_hosts(&mut builder); + dim_agent_capabilities::defaults::install(&mut builder); + builder.timeline_store(dim_agent_runtime::TimelineStoreBinding::new(store.clone())); + let agent = MinimalHost::start(&builder).await.unwrap(); + let connection = Connection::open(&database.0).unwrap(); + + let overlong = "x".repeat(65); + for id in [ + "Uppercase", + "with space", + "con", + "com0", + "lpt9", + "unicode-é", + overlong.as_str(), + ] { + let prepared_store = store.clone(); + let options = + dim_agent_runtime::CreateSessionOptions::default().prepare(id, move |id: String| { + Box::pin(async move { + prepared_store + .create_session(&id, &SessionConfig::default()) + .await + }) + }); + let result = agent + .create_session(SessionConfig::default(), options) + .await; + assert!( + matches!(result, Err(AgentError::InvalidInput(_))), + "prepared creation with id {id:?} must be rejected with InvalidInput, got {:?}", + result.err() + ); + assert_eq!( + stored_rows(&connection, id), + 0, + "nothing of {id:?} may be written" + ); + } + + let prepared_store = store.clone(); + let options = dim_agent_runtime::CreateSessionOptions::default().prepare( + "valid-id_1", + move |id: String| { + Box::pin(async move { + prepared_store + .create_session(&id, &SessionConfig::default()) + .await + }) + }, + ); + agent + .create_session(SessionConfig::default(), options) + .await + .unwrap(); + + drop(connection); + agent.close().await.unwrap(); + store.close().await.unwrap(); + db.close().await.unwrap(); +} + +#[tokio::test] +async fn owned_creation_admits_only_lowercase_ascii_ids() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_owner(&connection); + + let overlong = "x".repeat(65); + for id in [ + "Uppercase", + "with space", + "con", + "com0", + "lpt9", + "unicode-é", + overlong.as_str(), + ] { + let result = sessions + .create_owned_session( + id, + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await; + assert!( + matches!(result, Err(AgentError::InvalidInput(_))), + "owned creation with id {id:?} must be rejected with InvalidInput, got {result:?}" + ); + assert_eq!( + stored_rows(&connection, id), + 0, + "nothing of {id:?} may be written" + ); + } + + sessions + .create_owned_session( + "valid-id_1", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await + .unwrap(); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// The low-level creation the `SqliteStorage.createSession` plugin face and +/// the `timelineStore.createSession` process face both dispatch to, and the +/// plain `Agent::create_session` writes through: a caller-selected id admits +/// the same shape rule as the entries above, at the store's shared insertion +/// boundary. Every refusal is InvalidInput before anything is written. +#[tokio::test] +async fn store_creation_admits_only_lowercase_ascii_ids() { + let database = Database::new(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + + let overlong = "x".repeat(65); + for id in [ + "Uppercase", + "with space", + "with/slash", + "con", + "com0", + "lpt9", + "unicode-é", + overlong.as_str(), + ] { + let result = store.create_session(id, &SessionConfig::default()).await; + assert!( + matches!(result, Err(AgentError::InvalidInput(_))), + "store creation with id {id:?} must be rejected with InvalidInput, got {result:?}" + ); + assert_eq!( + stored_rows(&connection, id), + 0, + "nothing of {id:?} may be written" + ); + } + + store + .create_session("valid-id_1", &SessionConfig::default()) + .await + .unwrap(); + assert_eq!( + stored_rows(&connection, "valid-id_1"), + 2, + "a conforming id writes its Session and root branch rows" + ); + + drop(connection); + store.close().await.unwrap(); + db.close().await.unwrap(); +} + +/// The shared insertion boundary keeps the collision semantics the creation +/// entries pin: a case-only variant of a stored id is InvalidInput, while a +/// byte-identical duplicate keeps its Storage error. +#[tokio::test] +async fn store_creation_rejects_case_variants_and_keeps_storage_error_for_byte_duplicates() { + let database = Database::new(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_stored_session(&connection, "Stored-9"); + + let variant = store + .create_session("stored-9", &SessionConfig::default()) + .await; + assert!( + matches!(variant, Err(AgentError::InvalidInput(_))), + "a case-only variant must be InvalidInput at the low-level creation, got {variant:?}" + ); + assert_eq!( + stored_rows(&connection, "stored-9"), + 0, + "nothing of the variant may be written" + ); + + store + .create_session("valid-id", &SessionConfig::default()) + .await + .unwrap(); + let duplicate = store + .create_session("valid-id", &SessionConfig::default()) + .await; + assert!( + matches!(duplicate, Err(AgentError::Storage(_))), + "a byte-identical duplicate must keep its Storage error, got {duplicate:?}" + ); + assert_eq!( + connection + .query_row( + "SELECT count(*) FROM agent_sessions WHERE session_id='valid-id'", + [], + |row| row.get::<_, i64>(0) + ) + .unwrap(), + 1, + "the stored row is neither duplicated nor overwritten" + ); + + drop(connection); + store.close().await.unwrap(); + db.close().await.unwrap(); +} + +/// One `sqliteStorage` `createSession` call as a plugin makes it, through the +/// face's HostDispatch rather than the Rust binding: the wire error's `code`, +/// or the decoded reply when the call succeeds. +async fn dispatch_create_session( + face: &Arc, + session_id: &str, +) -> Result { + let request = serde_json::json!({ + "sessionId": session_id, + "config": SessionConfig::default(), + }); + let reply = face + .invoke( + "createSession", + rutis_bridge::session::Value::List(vec![request.into()]), + ) + .unwrap(); + let rutis_bridge::session::Value::Reference(future) = reply else { + panic!("createSession is asynchronous") + }; + future.wait_async().await.map(|value| value.json().unwrap()) +} + +/// #2204: the write entry eric8810 6094968589 names — the creation the +/// `SqliteStorage.createSession` plugin face dispatches to — admits the same +/// boundary as every other entry: a malformed or reserved id, a case-only +/// variant and a directory-sharing id are refused with the wire code +/// `invalid` before anything is written, and a byte-identical duplicate keeps +/// its `storage` code. +#[tokio::test] +async fn the_sqlite_storage_create_session_dispatch_applies_the_admission_boundary() { + use rutis_bridge::session::{HostDispatch, host_key}; + let database = Database::new(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(dim_app_server::storage::SqliteStoragePlugin::new( + database.0.clone(), + ))) + .await + .unwrap(); + let face = root + .get_at::(&host_key("sqliteStorage")) + .unwrap(); + let connection = Connection::open(&database.0).unwrap(); + seed_stored_session(&connection, "Stored-7"); + seed_stored_session(&connection, "abc\\def"); + + for (id, why) in [ + ("Uppercase", "an uppercase id violates the shape rule"), + ("with space", "an id with a space violates the shape rule"), + ("con", "a Windows reserved device name"), + ("stored-7", "differs from the stored Stored-7 only by case"), + ( + "abc", + "shares the output directory of the stored abc\\def under Windows rules", + ), + ] { + let error = dispatch_create_session(&face, id) + .await + .expect_err(&format!("{why}: creating {id:?} must be refused")); + assert_eq!( + error.code(), + Some("invalid"), + "{why}: the refusal of {id:?} must be the wire code invalid, got {error}" + ); + assert_eq!( + stored_rows(&connection, id), + 0, + "{why}: nothing of {id:?} may be written" + ); + } + + dispatch_create_session(&face, "valid-id") + .await + .expect("a conforming id is admitted"); + assert_eq!( + stored_rows(&connection, "valid-id"), + 2, + "the admitted creation writes its Session and root branch rows" + ); + let duplicate = dispatch_create_session(&face, "valid-id") + .await + .expect_err("a byte-identical duplicate must be refused"); + assert_eq!( + duplicate.code(), + Some("storage"), + "a byte-identical duplicate must keep the wire code storage, got {duplicate}" + ); + assert_eq!( + connection + .query_row( + "SELECT count(*) FROM agent_sessions WHERE session_id='valid-id'", + [], + |row| row.get::<_, i64>(0) + ) + .unwrap(), + 1, + "the stored row is neither duplicated nor overwritten" + ); + + drop(connection); + root.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn owned_creation_rejects_case_variants_and_keeps_storage_error_for_byte_duplicates() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_owner(&connection); + seed_stored_session(&connection, "Legacy-1"); + seed_stored_session(&connection, "stored-1"); + + let variant = sessions + .create_owned_session( + "legacy-1", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await; + assert!( + matches!(variant, Err(AgentError::InvalidInput(_))), + "an id differing only by case must be InvalidInput, got {variant:?}" + ); + // A byte-identical duplicate is only reachable under the admission rule + // when the stored id is itself conforming: the uppercase id above would + // already fail admission. The colliding write keeps the duplicate's + // Storage error; only the case variant is InvalidInput. + let duplicate = sessions + .create_owned_session( + "stored-1", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await; + assert!( + matches!(duplicate, Err(AgentError::Storage(_))), + "a byte-identical duplicate must keep its Storage error, got {duplicate:?}" + ); + assert_eq!( + stored_rows(&connection, "legacy-1"), + 0, + "the refused variant writes nothing" + ); + assert_eq!( + connection + .query_row("SELECT count(*) FROM agent_sessions", [], |row| row + .get::<_, i64>(0)) + .unwrap(), + 2, + "the stored records are untouched" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn fork_target_outside_the_admission_rule_or_in_case_collision_writes_nothing() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_stored_session(&connection, "Legacy-2"); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append(&store, key("source", "main"), vec![text(1, "source")]) + .await + .unwrap(); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + + for target in ["Uppercase", "con"] { + let result = sessions.fork_session("source", target, 1, &config).await; + assert!( + matches!(result, Err(AgentError::InvalidInput(_))), + "fork target {target:?} must be rejected with InvalidInput, got {result:?}" + ); + assert_eq!( + stored_rows(&connection, target), + 0, + "a refused fork target writes nothing" + ); + } + + let collision = sessions + .fork_session("source", "legacy-2", 1, &config) + .await; + assert!( + matches!(collision, Err(AgentError::InvalidInput(_))), + "a fork target differing only by case must be InvalidInput, got {collision:?}" + ); + assert_eq!( + stored_rows(&connection, "legacy-2"), + 0, + "the collision refusal writes nothing under the refused id" + ); + assert_eq!( + stored_rows(&connection, "Legacy-2"), + 1, + "the seeded uppercase session row is untouched" + ); + assert!( + stored_events(&connection, "legacy-2").is_empty(), + "no Timeline rows may be copied into the colliding id" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// #2204's worst case: a fork whose target is byte-identical to a stored +/// Session. The copy's final insert cannot succeed, and the copy's cleanup +/// drops every row of the id — including the Session that already owned it, +/// before the fix. The refusal must happen before the first copy chunk, so +/// nothing is written and no cleanup runs. +#[tokio::test] +async fn fork_with_a_byte_identical_target_is_refused_without_touching_the_existing_session() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append(&store, key("source", "main"), vec![text(1, "source")]) + .await + .unwrap(); + store + .create_session("victim", &SessionConfig::default()) + .await + .unwrap(); + append(&store, key("victim", "main"), vec![text(1, "victim")]) + .await + .unwrap(); + + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + let result = sessions.fork_session("source", "victim", 1, &config).await; + assert!( + matches!(result, Err(AgentError::Storage(_))), + "a byte-identical fork target must keep its Storage error, got {result:?}" + ); + + let connection = Connection::open(&database.0).unwrap(); + assert!( + connection + .query_row( + "SELECT EXISTS(SELECT 1 FROM agent_sessions WHERE session_id='victim')", + [], + |row| row.get::<_, bool>(0) + ) + .unwrap(), + "the existing Session's row must survive the refused fork" + ); + assert_eq!( + stored_events(&connection, "victim").len(), + 1, + "the existing Session's Timeline rows must survive the refused fork" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// Ids stored before the admission rule are neither migrated nor rewritten: +/// restoration reads them as written, an uppercase source forks into +/// a conforming target, and deletion removes it as before. The rows are +/// seeded around the creation boundary the way a pre-#2204 daemon wrote them. +/// This pins behavior the change must not alter. +#[tokio::test] +async fn stored_uppercase_ids_remain_operable() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_stored_session(&connection, "Legacy-9"); + connection + .execute( + "INSERT INTO timeline_branches (session_id, branch_id, info, sequence) \ + VALUES ('Legacy-9', 'main', '{\"id\":\"main\"}', 0)", + [], + ) + .unwrap(); + append( + &store, + key("Legacy-9", "main"), + vec![text(1, "first"), text(2, "second")], + ) + .await + .unwrap(); + + let config = sessions + .session_config_text("Legacy-9") + .await + .unwrap() + .unwrap(); + assert!( + sessions.session_config("Legacy-9").await.unwrap().is_some(), + "restoration reads the uppercase id's configuration as written" + ); + sessions + .fork_session("Legacy-9", "valid-fork", 2, &config) + .await + .unwrap(); + assert!( + !stored_events(&connection, "valid-fork").is_empty(), + "the uppercase source's rows are copied into the fork" + ); + + assert!(sessions.delete_session("Legacy-9").await.unwrap()); + assert!( + connection + .query_row( + "SELECT NOT EXISTS(SELECT 1 FROM agent_sessions WHERE session_id='Legacy-9')", + [], + |row| row.get::<_, bool>(0) + ) + .unwrap(), + "deletion removes the uppercase id as before" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// The collision check is the indexed lookup the maintainer decision requires: +/// the query the write entries run resolves through the covering derived +/// index instead of scanning the table. +#[tokio::test] +async fn case_collision_check_uses_the_derived_index() { + let database = Database::new(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let connection = Connection::open(&database.0).unwrap(); + let plan: Vec = connection + .prepare( + "EXPLAIN QUERY PLAN SELECT session_id FROM agent_sessions WHERE session_id = ?1 COLLATE NOCASE", + ) + .unwrap() + .query_map(["candidate"], |row| row.get::<_, String>(3)) + .unwrap() + .collect::>>() + .unwrap(); + assert!( + plan.iter() + .any(|step| step.contains("agent_sessions_session_id_nocase")), + "the collision check must use the covering index, plan: {plan:?}" + ); + + drop(connection); + db.close().await.unwrap(); +} + +/// Legacy ids stored before the admission rule can share an output directory +/// with a newly admitted lowercase id under a supported filesystem's identity +/// rules even though they differ byte-for-byte and under ASCII case folding: +/// Unicode folding pairs (Kelvin sign, long s, ß/ẞ, ligatures), Unicode +/// default-ignorable code points (casefold volumes), and the Windows shapes — +/// backslash and alternate-stream separators, trailing dots and spaces, +/// Unicode mappings — plus the 8.3 short names, both plain and hashed. The +/// write entries must refuse such a candidate with InvalidInput before +/// anything is published, while the stored row keeps its bytes. +async fn assert_directory_shape_rejected(stored: &str, candidate: &str, why: &str) { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_owner(&connection); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append(&store, key("source", "main"), vec![text(1, "source")]) + .await + .unwrap(); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + // A shape resolving onto the output root or its ancestor refuses every + // creation, so its row is seeded only once the fork source exists; the + // row predates every admission check the candidate runs either way. + seed_stored_session(&connection, stored); + + let created = sessions + .create_owned_session( + candidate, + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await; + assert!( + matches!(created, Err(AgentError::InvalidInput(_))), + "{why}: creating {candidate:?} while {stored:?} is stored must be InvalidInput, got {created:?}" + ); + let forked = sessions.fork_session("source", candidate, 1, &config).await; + assert!( + matches!(forked, Err(AgentError::InvalidInput(_))), + "{why}: forking into {candidate:?} while {stored:?} is stored must be InvalidInput, got {forked:?}" + ); + assert_eq!( + stored_rows(&connection, candidate), + 0, + "{why}: the refused candidate {candidate:?} writes nothing" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// One regression per output-directory-sharing shape (stored, candidate). +macro_rules! directory_shape { + ($name:ident, $stored:expr, $candidate:expr, $why:expr) => { + #[tokio::test] + async fn $name() { + assert_directory_shape_rejected($stored, $candidate, $why).await; + } + }; +} + +directory_shape!( + kelvin_sign_folds_to_ascii_k, + "ab\u{212A}", + "abk", + "APFS/HFS+/Linux-casefold fold the Kelvin sign U+212A to k" +); +directory_shape!( + long_s_folds_to_ascii_s, + "ab\u{17F}", + "abs", + "the long s U+017F folds to s under both volume rules" +); +directory_shape!( + sharp_s_uppercases_to_ss, + "ab\u{DF}", + "abss", + "ß uppercases to SS, so a casefold volume equates it with ss" +); +directory_shape!( + uppercase_sharp_s_uppercases_to_ss, + "ab\u{1E9E}", + "abss", + "ẞ uppercases to SS, so a casefold volume equates it with ss" +); +directory_shape!( + ff_ligature_uppercases_to_ff, + "ab\u{FB00}", + "abff", + "the ff ligature uppercases to FF, so a casefold volume equates it with ff" +); +directory_shape!( + default_ignorable_is_stripped_before_folding, + "abc\u{AD}", + "abc", + "the soft hyphen U+00AD is a default-ignorable a casefold volume strips" +); +directory_shape!( + windows_backslash_prefix_shares_the_first_segment, + "abc\\def", + "abc", + "under Windows rules abc\\def names a path inside abc" +); +directory_shape!( + windows_index_allocation_stream_shares_the_base, + "abc::$INDEX_ALLOCATION", + "abc", + "under Windows rules abc::$INDEX_ALLOCATION is a stream of abc" +); +directory_shape!( + windows_alternate_stream_shares_the_base, + "abc:x", + "abc", + "under Windows rules abc:x is an alternate stream of abc" +); +directory_shape!( + windows_trailing_dot_is_trimmed, + "abc.", + "abc", + "under Windows rules a trailing dot is trimmed, so abc. is abc" +); +directory_shape!( + windows_trailing_space_is_trimmed, + "abc ", + "abc", + "under Windows rules a trailing space is trimmed, so abc␣ is abc" +); +directory_shape!( + windows_dotted_capital_i_maps_to_i, + "ab\u{130}", + "abi", + "under Windows rules the dotted capital İ maps onto i" +); +directory_shape!( + windows_dotless_i_maps_to_i, + "ab\u{131}", + "abi", + "under Windows rules the dotless ı maps onto i" +); +directory_shape!( + windows_8_3_short_name_aliasing, + "ab12cd~7", + "ab12cdxyz", + "an 8.3 volume may serve the long name ab12cdxyz as ab12cd~7" +); +directory_shape!( + windows_8_3_hashed_short_name_aliasing, + "ab12cd~7", + "abwxyztuv", + "an 8.3 volume may serve the long name abwxyztuv as the hashed ab12cd~7" +); +directory_shape!( + windows_parent_segment_climbs_out_and_back_to_the_candidate, + "x\\..\\abc", + "abc", + "under Windows rules x\\..\\abc resolves the parent segment before the directory is accessed, landing on abc" +); +directory_shape!( + windows_dot_segment_is_dropped_before_the_directory_is_accessed, + ".\\abc", + "abc", + "under Windows rules the . segment is dropped, so .\\abc is abc" +); +directory_shape!( + windows_trailing_dot_segment_lands_on_the_parent, + "abc\\.", + "abc", + "under Windows rules abc\\. resolves inside abc, which the candidate's own directory covers" +); +directory_shape!( + windows_inner_parent_segment_cancels_into_the_first, + "abc\\x\\..", + "abc", + "under Windows rules abc\\x\\.. resolves to abc itself" +); +directory_shape!( + windows_reentry_after_a_climb_out_passes_through_the_root_name, + "..\\command-output\\abc", + "abc", + "under Windows rules ..\\command-output\\abc climbs out of the output root and re-enters it onto abc" +); +directory_shape!( + forward_slash_parent_segment_resolves_on_posix, + "x/../abc", + "abc", + "a forward-slash parent segment resolves on POSIX, so x/../abc lands on abc" +); + +directory_shape!( + windows_resolution_landing_on_the_root_refuses_every_candidate, + "abc\\..", + "abc", + "abc\\.. resolves onto the output root itself, which every candidate's directory sits inside" +); +directory_shape!( + dot_resolution_lands_on_the_root_and_refuses_every_candidate, + ".", + "abc", + ". resolves onto the output root itself" +); +directory_shape!( + parent_resolution_lands_above_the_root_and_refuses_every_candidate, + "..", + "abc", + ".. resolves onto an ancestor of the output root" +); +directory_shape!( + backslash_resolution_is_the_volume_root_and_refuses_every_candidate, + "\\", + "abc", + "\\ resolves onto the volume's own root, an ancestor of every candidate's directory" +); +directory_shape!( + drive_root_resolution_is_the_volume_root_and_refuses_every_candidate, + "C:\\", + "abc", + "C:\\ resolves onto the volume's own root, an ancestor of every candidate's directory" +); +directory_shape!( + unc_id_proves_no_disjoint_volume_and_refuses, + "\\\\host\\share\\abc", + "abc", + "no static comparison proves a UNC share disjoint from the output root's volume" +); +directory_shape!( + verbatim_unicode_id_is_the_device_namespace_and_refuses, + "\\\\?\\\u{e9}\u{e9}", + "abc", + "a verbatim path naming neither a drive nor a share is the device namespace, and a multibyte name may not break its parse" +); +directory_shape!( + device_namespace_id_resolves_no_destination_and_refuses, + "\\\\.\\device\\abc", + "abc", + "the device namespace places no statically checkable directory, so the destination is unknown" +); +directory_shape!( + posix_parent_segment_resolution_into_the_root_refuses, + "abc/../def", + "def", + "POSIX resolves abc/../def onto def, the candidate's own directory" +); +directory_shape!( + trailing_space_parent_segment_resolution_into_the_root_refuses, + "abc/.. /def", + "def", + "Windows trims the trailing space of .. and resolves it onto the parent, so abc/.. /def lands on the candidate def" +); +directory_shape!( + trailing_space_parent_resolution_lands_on_the_root_and_refuses_every_candidate, + "abc/.. ", + "def", + "Windows trims the trailing space of .. and resolves it onto the parent, so abc/.. lands on the output root every candidate's directory sits inside" +); +directory_shape!( + drive_absolute_parent_segment_resolution_refuses, + "c:/../abc", + "abc", + "POSIX reads c:/../abc as a relative path whose parent segment resolves it into the output root" +); + +/// A trailing-space parent segment keeps both of its readings: the Windows +/// resolution it normalizes into and the literal name that reading leaves +/// behind. `abc\.. \def` resolves onto the sibling `def`, which the +/// candidate `abc` does not cover, but its literal branch passes through +/// `abc` as a directory, so that candidate is refused on the literal branch +/// while an unrelated one is admitted on both. +#[tokio::test] +async fn trailing_space_parent_segment_keeps_its_literal_branch() { + assert_directory_shape_rejected( + "abc\\.. \\def", + "abc", + "the literal branch of the trailing-space parent segment passes through abc, the candidate's own directory", + ) + .await; + assert_directory_shape_admitted( + "abc\\.. \\def", + "ghi", + "an unrelated candidate shares no directory with either reading of abc\\.. \\def", + ) + .await; +} + +/// The normal components of a canonical output root, the names a Windows or +/// POSIX path spelling of that root carries. +fn normal_names(root: &std::path::Path) -> Vec { + root.components() + .filter_map(|component| match component { + std::path::Component::Normal(name) => Some(name.to_string_lossy().into_owned()), + _ => None, + }) + .collect() +} + +/// The drive letter of a canonical Windows output root, `c` where the root +/// names no letter: on a POSIX store every letter is undecidable alike, so +/// the fallback exercises the same refusal. +fn root_drive_letter(root: &std::path::Path) -> char { + let text = root.to_string_lossy(); + let bytes = text.as_bytes(); + if bytes.len() >= 2 && bytes[1] == b':' && bytes[0].is_ascii_alphabetic() { + (bytes[0] as char).to_ascii_lowercase() + } else { + 'c' + } +} + +/// A legacy id computed from the test's own output root, refused by its +/// resolved destination on both the creation and the fork entry. The +/// resolution forms the comparison judges — volume anchor, rooted form, +/// canonical spelling — only exist relative to the root the store writes +/// under, so the stored id derives from it instead of hardcoding a letter or +/// a layout. +async fn assert_computed_shape_rejected( + stored: impl Fn(&std::path::Path) -> String, + candidate: &str, + why: &str, +) { + let database = Database::new(); + let output_root = database + .0 + .parent() + .unwrap() + .canonicalize() + .unwrap() + .join("command-output"); + let stored = stored(&output_root); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_owner(&connection); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append(&store, key("source", "main"), vec![text(1, "source")]) + .await + .unwrap(); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + seed_stored_session(&connection, &stored); + + let created = sessions + .create_owned_session( + candidate, + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await; + assert!( + matches!(created, Err(AgentError::InvalidInput(_))), + "{why}: creating {candidate:?} while {stored:?} is stored must be InvalidInput, got {created:?}" + ); + let forked = sessions.fork_session("source", candidate, 1, &config).await; + assert!( + matches!(forked, Err(AgentError::InvalidInput(_))), + "{why}: forking into {candidate:?} while {stored:?} is stored must be InvalidInput, got {forked:?}" + ); + assert_eq!( + stored_rows(&connection, candidate), + 0, + "{why}: the refused candidate {candidate:?} writes nothing" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +macro_rules! root_shape { + ($name:ident, $compute:expr, $candidate:expr, $why:expr) => { + #[tokio::test] + async fn $name() { + assert_computed_shape_rejected($compute, $candidate, $why).await; + } + }; +} + +root_shape!( + windows_rooted_resolution_inside_the_root_refuses, + |root: &std::path::Path| format!("\\{}\\abc", normal_names(root).join("\\")), + "abc", + "a rooted id resolving back inside the output root overlaps the candidate's directory" +); +root_shape!( + windows_drive_absolute_resolution_inside_the_root_refuses, + |root: &std::path::Path| format!( + "{}:\\{}\\abc", + root_drive_letter(root), + normal_names(root).join("\\") + ), + "abc", + "a drive-absolute id resolving back inside the output root overlaps the candidate's directory" +); +root_shape!( + windows_verbatim_resolution_inside_the_root_refuses, + |root: &std::path::Path| format!( + "\\\\?\\{}:\\{}\\abc", + root_drive_letter(root), + normal_names(root).join("\\") + ), + "abc", + "a verbatim id resolves onto the same volume the drive letter names, so its destination inside the output root overlaps" +); +root_shape!( + drive_relative_id_resolves_no_destination_and_refuses, + |root: &std::path::Path| format!("{}:other", root_drive_letter(root)), + "abc", + "c:rest resolves against the drive's own current directory, which no static comparison knows" +); +root_shape!( + posix_absolute_resolution_inside_the_root_refuses, + |root: &std::path::Path| format!("/{}/abc", normal_names(root).join("/")), + "abc", + "a POSIX-absolute id resolving back inside the output root overlaps the candidate's directory" +); + +/// #2204: the comparison's output root is the one the store was opened with, +/// not `/command-output` by construction. A host whose +/// command-output layout moves away from the database — the CLI's split home +/// is one — opens the store with that root, and the admission judges ids +/// against it. The root is opened through its literal spelling while its +/// canonical spelling differs wherever a prefix of the temporary directory +/// is a symlink, so a rooted id spelling the canonical form must refuse +/// too: it names the same directory. +#[tokio::test] +async fn the_opened_output_root_is_the_one_the_admission_compares_against() { + let database = Database::new(); + let output_root = std::env::temp_dir() + .join(format!("dim-nocase-custom-{}", uuid::Uuid::new_v4())) + .join("command-output"); + std::fs::create_dir_all(&output_root).unwrap(); + let canonical_root = output_root.canonicalize().unwrap(); + let canonical_id = format!("\\{}\\abc", normal_names(&canonical_root).join("\\")); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open_with_output_root(database.0.clone(), output_root.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_owner(&connection); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append(&store, key("source", "main"), vec![text(1, "source")]) + .await + .unwrap(); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + // Only the canonical spelling is seeded: it names the same directory as + // the literal root the store was opened with, so the refusal exists only + // when the comparison canonicalizes the root's longest existing prefix. + // Where the temporary directory already spells its canonical form the two + // ids are one row. + seed_stored_session(&connection, &canonical_id); + + let created = sessions + .create_owned_session( + "abc", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await; + assert!( + matches!(created, Err(AgentError::InvalidInput(_))), + "a rooted id over the opened output root must refuse creation, got {created:?}" + ); + let forked = sessions.fork_session("source", "abc", 1, &config).await; + assert!( + matches!(forked, Err(AgentError::InvalidInput(_))), + "a rooted id over the opened output root must refuse the fork, got {forked:?}" + ); + assert_eq!( + stored_rows(&connection, "abc"), + 0, + "the refused candidate writes nothing" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); + let _ = std::fs::remove_dir_all(output_root.parent().unwrap()); +} + +/// #2204: the refusal follows the stored row, not the shape. Once the row of +/// an id resolving onto the output root is deleted, candidates the id blocked +/// are admitted again. +#[tokio::test] +async fn deleting_the_row_of_a_root_wide_shape_unblocks_the_candidates() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_owner(&connection); + seed_stored_session(&connection, ".."); + + let blocked = sessions + .create_owned_session( + "abc", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await; + assert!( + matches!(blocked, Err(AgentError::InvalidInput(_))), + "the root-wide id refuses the candidate while its row is stored, got {blocked:?}" + ); + + connection + .execute("DELETE FROM agent_sessions WHERE session_id='..'", []) + .unwrap(); + sessions + .create_owned_session( + "abc", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await + .unwrap(); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append(&store, key("source", "main"), vec![text(1, "source")]) + .await + .unwrap(); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + sessions + .fork_session("source", "def", 1, &config) + .await + .unwrap(); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// A legacy id whose resolved output directory never covers a candidate's: +/// its path climbs out of the output root without re-entering it, lands on +/// the root itself, leaves the root sideways, or the join replaces the root. +/// Refusing candidates over these would lock ids that share nothing. Creation +/// and the fork admission each run in a fresh store, since the admitted id is +/// written by then. +async fn assert_directory_shape_admitted(stored: &str, candidate: &str, why: &str) { + for fork_only in [false, true] { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_owner(&connection); + seed_stored_session(&connection, stored); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append(&store, key("source", "main"), vec![text(1, "source")]) + .await + .unwrap(); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + + if fork_only { + let forked = sessions.fork_session("source", candidate, 1, &config).await; + assert!( + forked.is_ok(), + "{why}: forking into {candidate:?} while {stored:?} is stored must succeed, got {forked:?}" + ); + } else { + let created = sessions + .create_owned_session( + candidate, + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await; + assert!( + created.is_ok(), + "{why}: creating {candidate:?} while {stored:?} is stored must succeed, got {created:?}" + ); + } + assert!( + stored_rows(&connection, candidate) > 0, + "{why}: the admitted candidate {candidate:?} is written" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); + } +} + +macro_rules! directory_shape_admitted { + ($name:ident, $stored:expr, $candidate:expr, $why:expr) => { + #[tokio::test] + async fn $name() { + assert_directory_shape_admitted($stored, $candidate, $why).await; + } + }; +} + +directory_shape_admitted!( + windows_climb_out_without_reentry_shares_nothing, + "..\\abc", + "abc", + "..\\abc resolves beside the output root, never inside the candidate's directory" +); +directory_shape_admitted!( + windows_resolution_leaving_the_root_sideways_shares_nothing, + "abc\\..\\def", + "abc", + "abc\\..\\def resolves to def, a sibling of the candidate's directory" +); +directory_shape_admitted!( + windows_rooted_path_replaces_the_output_root, + "\\unshared-root\\abc", + "abc", + "a rooted path resolving beside the output root's own directory shares nothing with the candidate" +); +directory_shape_admitted!( + windows_resolution_deeper_than_one_segment_shares_nothing, + "x\\abc", + "abc", + "x\\abc resolves two components deep, below x rather than inside abc" +); + +/// A trigger that stands in for another connection committing a Session of +/// `winner` the moment the copy writes its first `into` row for `fork` — the +/// timing a concurrent creation would have. Its rows ride the copy's own +/// transaction, so the interleaving is deterministic: `branches` makes the +/// commit land with the copy's first chunk, `events` with a chunk after it. +/// `INSERT OR IGNORE` keeps the copies of a later row from failing the +/// statement once the commit already happened. +fn commit_winner_when_copy_writes(connection: &Connection, into: &str, fork: &str, winner: &str) { + connection + .execute_batch(&format!( + "CREATE TRIGGER concurrent_creation AFTER INSERT ON {into} + WHEN NEW.session_id = '{fork}' + BEGIN + INSERT OR IGNORE INTO agent_sessions (session_id, config, created_at_ms, origin) + VALUES ('{winner}', '{{\"cwd\":\"/winner\"}}', 1, 'client'); + INSERT OR IGNORE INTO session_catalog (session_id, updated_at_ms, preview, cwd) + VALUES ('{winner}', 1, 'winner-preview', '/winner'); + INSERT OR IGNORE INTO session_metadata (session_id, revision, title, title_source) + VALUES ('{winner}', 1, 'winner-title', 'manual'); + INSERT OR IGNORE INTO timeline_events (session_id, branch_id, sequence, last_sequence, kind, body, event_id) + VALUES ('{winner}', 'main', 99, 99, 'winner-kind', '{{\"winner\":true}}', 'winner-marker'); + END;" + )) + .unwrap(); +} + +/// The concurrent winner's own rows, asserted field by field: the copy's +/// cleanup must never reach a Session another connection committed. +fn assert_winner_intact(connection: &Connection, winner: &str) { + let row: Option<(String, String)> = connection + .query_row( + "SELECT config, origin FROM agent_sessions WHERE session_id=?1", + [winner], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .optional() + .unwrap(); + let (config, origin) = + row.unwrap_or_else(|| panic!("the winning Session {winner:?} lost its agent_sessions row")); + assert_eq!( + config, "{\"cwd\":\"/winner\"}", + "the winning Session's config was overwritten" + ); + assert_eq!( + origin, "client", + "the winning Session's origin was overwritten" + ); + let catalog: Option<(i64, Option, String)> = connection + .query_row( + "SELECT updated_at_ms, preview, cwd FROM session_catalog WHERE session_id=?1", + [winner], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ) + .optional() + .unwrap(); + assert_eq!( + catalog, + Some((1, Some("winner-preview".to_owned()), "/winner".to_owned())), + "the winning Session's catalog row must survive unchanged" + ); + let metadata: Option<(i64, Option)> = connection + .query_row( + "SELECT revision, title FROM session_metadata WHERE session_id=?1", + [winner], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .optional() + .unwrap(); + assert_eq!( + metadata, + Some((1, Some("winner-title".to_owned()))), + "the winning Session's metadata row must survive unchanged" + ); + let marker: Option<(String, String)> = connection + .query_row( + "SELECT kind, body FROM timeline_events WHERE session_id=?1 AND branch_id='main' AND sequence=99", + [winner], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .optional() + .unwrap(); + assert_eq!( + marker, + Some(("winner-kind".to_owned(), "{\"winner\":true}".to_owned())), + "the winning Session's Timeline rows must survive the copy cleanup" + ); +} + +/// #2204: another connection commits the fork's target byte-identically while +/// the copy's first chunk writes. The fork is refused and the winning Session +/// keeps every row it committed; the cleanup may only remove rows the fork +/// itself wrote. +#[tokio::test] +async fn a_concurrent_creation_during_the_first_copy_write_is_refused_and_the_winner_survives() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append( + &store, + key("source", "main"), + vec![text(1, "first"), text(2, "second"), text(3, "third")], + ) + .await + .unwrap(); + let connection = Connection::open(&database.0).unwrap(); + commit_winner_when_copy_writes( + &connection, + "timeline_branches", + "fork-target", + "fork-target", + ); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + + let result = sessions + .fork_session("source", "fork-target", 3, &config) + .await; + assert!( + matches!(result, Err(AgentError::Storage(_))), + "a byte-identical concurrent creation must keep the fork's Storage refusal, got {result:?}" + ); + assert_winner_intact(&connection, "fork-target"); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// #2204: the concurrent creation commits after the copy's first chunks, so +/// only the final transaction's re-check can see it. The refusal must be the +/// re-check's, and the cleanup after it must still leave the winning Session +/// intact. +#[tokio::test] +async fn a_concurrent_creation_caught_by_the_final_recheck_keeps_the_winner_intact() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append( + &store, + key("source", "main"), + vec![text(1, "first"), text(2, "second"), text(3, "third")], + ) + .await + .unwrap(); + let connection = Connection::open(&database.0).unwrap(); + commit_winner_when_copy_writes(&connection, "timeline_events", "fork-target", "fork-target"); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + + let result = sessions + .fork_session("source", "fork-target", 3, &config) + .await; + assert!( + matches!(result, Err(AgentError::Storage(_))), + "a byte-identical concurrent creation must keep the fork's Storage refusal, got {result:?}" + ); + assert_winner_intact(&connection, "fork-target"); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// The final transaction's re-check tells a case-only variant apart from a +/// byte-identical duplicate: the concurrent creation commits `Fork-Target` +/// while the copy targets `fork-target`, so the refusal is InvalidInput and +/// the variant's rows stay untouched. +#[tokio::test] +async fn the_final_recheck_rejects_a_case_variant_with_invalid_input() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append( + &store, + key("source", "main"), + vec![text(1, "first"), text(2, "second"), text(3, "third")], + ) + .await + .unwrap(); + let connection = Connection::open(&database.0).unwrap(); + commit_winner_when_copy_writes(&connection, "timeline_events", "fork-target", "Fork-Target"); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + + let result = sessions + .fork_session("source", "fork-target", 3, &config) + .await; + assert!( + matches!(result, Err(AgentError::InvalidInput(_))), + "a concurrent creation differing only by case must be InvalidInput, got {result:?}" + ); + assert_winner_intact(&connection, "Fork-Target"); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// The conflict lookup is per stored row, not a frozen key set: once the +/// legacy row is deleted, the id it blocked is admitted again, on both the +/// creation and the fork entry. +#[tokio::test] +async fn deleting_the_legacy_row_unblocks_the_shape_it_conflicted_with() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_owner(&connection); + seed_stored_session(&connection, "Legacy-1"); + seed_stored_session(&connection, "ab\u{212A}"); + + let blocked = sessions + .create_owned_session( + "legacy-1", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await; + assert!( + matches!(blocked, Err(AgentError::InvalidInput(_))), + "the case variant is refused while the legacy row is stored, got {blocked:?}" + ); + let shaped = sessions + .create_owned_session( + "abk", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await; + assert!( + matches!(shaped, Err(AgentError::InvalidInput(_))), + "the folding variant is refused while the legacy row is stored, got {shaped:?}" + ); + + assert!(sessions.delete_session("Legacy-1").await.unwrap()); + connection + .execute( + "DELETE FROM agent_sessions WHERE session_id='ab\u{212A}'", + [], + ) + .unwrap(); + + sessions + .create_owned_session( + "legacy-1", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await + .unwrap(); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append(&store, key("source", "main"), vec![text(1, "source")]) + .await + .unwrap(); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + sessions + .fork_session("source", "abk", 1, &config) + .await + .unwrap(); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// #2204: the directory-shape lookup the write entries run must resolve +/// through the covering partial derived index — verbatim as the index defines +/// it — instead of scanning `agent_sessions`. +#[tokio::test] +async fn directory_shape_check_uses_the_derived_index() { + let database = Database::new(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let connection = Connection::open(&database.0).unwrap(); + let plan: Vec = connection + .prepare( + "EXPLAIN QUERY PLAN SELECT session_id FROM agent_sessions WHERE session_id GLOB '*[^0-9A-Za-z_-]*'", + ) + .unwrap() + .query_map([], |row| row.get::<_, String>(3)) + .unwrap() + .collect::>>() + .unwrap(); + assert!( + plan.iter() + .any(|step| { step.contains("agent_sessions_session_id_non_ascii_word") }), + "the directory-shape check must use the covering index, plan: {plan:?}" + ); + + drop(connection); + db.close().await.unwrap(); +} + +/// A write ledger for one fork target: every row the copy inserts or deletes +/// under the fork's id in the tables the copy touches is recorded, including +/// the cleanup's deletions. A fork refused before its first write must leave +/// the ledger empty — zero writes, zero cleanup. +fn ledger_fork_writes(connection: &Connection, fork: &str) { + connection + .execute_batch(&format!( + "CREATE TABLE copy_ledger (entry TEXT); + CREATE TRIGGER ledger_branches_insert AFTER INSERT ON timeline_branches + WHEN NEW.session_id = '{fork}' + BEGIN INSERT INTO copy_ledger VALUES ('timeline_branches'); END; + CREATE TRIGGER ledger_events_insert AFTER INSERT ON timeline_events + WHEN NEW.session_id = '{fork}' + BEGIN INSERT INTO copy_ledger VALUES ('timeline_events'); END; + CREATE TRIGGER ledger_content_insert AFTER INSERT ON timeline_content + WHEN NEW.session_id = '{fork}' + BEGIN INSERT INTO copy_ledger VALUES ('timeline_content'); END; + CREATE TRIGGER ledger_sessions_insert AFTER INSERT ON agent_sessions + WHEN NEW.session_id = '{fork}' + BEGIN INSERT INTO copy_ledger VALUES ('agent_sessions'); END; + CREATE TRIGGER ledger_branches_delete AFTER DELETE ON timeline_branches + WHEN OLD.session_id = '{fork}' + BEGIN INSERT INTO copy_ledger VALUES ('delete-timeline_branches'); END; + CREATE TRIGGER ledger_events_delete AFTER DELETE ON timeline_events + WHEN OLD.session_id = '{fork}' + BEGIN INSERT INTO copy_ledger VALUES ('delete-timeline_events'); END; + CREATE TRIGGER ledger_content_delete AFTER DELETE ON timeline_content + WHEN OLD.session_id = '{fork}' + BEGIN INSERT INTO copy_ledger VALUES ('delete-timeline_content'); END; + CREATE TRIGGER ledger_sessions_delete AFTER DELETE ON agent_sessions + WHEN OLD.session_id = '{fork}' + BEGIN INSERT INTO copy_ledger VALUES ('delete-agent_sessions'); END;" + )) + .unwrap(); +} + +fn ledger_entries(connection: &Connection) -> Vec { + connection + .prepare("SELECT entry FROM copy_ledger") + .unwrap() + .query_map([], |row| row.get::<_, String>(0)) + .unwrap() + .collect::>>() + .unwrap() +} + +/// A fork refused by a conflict that precedes the copy writes nothing and +/// runs no cleanup: the ledger proves not one row of the fork's id was ever +/// inserted or deleted, and the stored Session it conflicted with is +/// untouched. Shared by the case-collision and the directory-shape refusal. +async fn assert_refused_fork_never_writes(seed: &str, fork: &str, error: &str) { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append( + &store, + key("source", "main"), + vec![text(1, "first"), text(2, "second"), text(3, "third")], + ) + .await + .unwrap(); + let connection = Connection::open(&database.0).unwrap(); + seed_stored_session(&connection, seed); + ledger_fork_writes(&connection, fork); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + + let result = sessions.fork_session("source", fork, 3, &config).await; + match error { + "storage" => assert!( + matches!(result, Err(AgentError::Storage(_))), + "the refused fork must keep its Storage error, got {result:?}" + ), + _ => assert!( + matches!(result, Err(AgentError::InvalidInput(_))), + "the refused fork must be InvalidInput, got {result:?}" + ), + } + assert!( + ledger_entries(&connection).is_empty(), + "a fork refused before its first write may not write or delete a single row, ledger: {:?}", + ledger_entries(&connection) + ); + assert_eq!( + stored_rows(&connection, seed), + 1, + "the stored Session {seed:?} the fork conflicted with is untouched" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// #2204 (decision Q2 c (1)): a stored Session differing from the fork target +/// only by case refuses the fork inside the first chunk transaction, before +/// its first write — zero inserts, zero cleanup. +#[tokio::test] +async fn a_fork_conflicting_by_case_is_refused_with_zero_writes_and_zero_cleanup() { + assert_refused_fork_never_writes("Fork-Case", "fork-case", "invalid").await; +} + +/// #2204: the same zero-write guarantee covers the directory-shape check in +/// the first chunk transaction — the conflict the NOCASE lookup cannot see. +#[tokio::test] +async fn a_fork_conflicting_by_directory_shape_is_refused_with_zero_writes_and_zero_cleanup() { + assert_refused_fork_never_writes("fork-shape\u{212A}", "fork-shapek", "invalid").await; +} + +directory_shape!( + windows_8_3_two_digit_tail_aliasing, + "abcde~12", + "abcdefghij", + "an 8.3 volume may serve the long name abcdefghij as abcde~12 once the stem's collisions accumulate" +); + +directory_shape!( + mongolian_free_variation_selector_four_is_stripped_before_folding, + "abc\u{180F}", + "abc", + "the Mongolian free variation selector four U+180F is a default-ignorable a casefold volume strips" +); + +/// A stored id whose 8.3 stem is empty — the volume never generates such a +/// short name — must not collide with any long candidate, including the +/// ordinary UUID-shaped creation ids. +#[tokio::test] +async fn an_empty_8_3_stem_blocks_no_long_candidate() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_owner(&connection); + seed_stored_session(&connection, "~1"); + + sessions + .create_owned_session( + "abcdef123456", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await + .unwrap_or_else(|error| { + panic!("a long candidate must not collide with an empty 8.3 stem: {error:?}") + }); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append(&store, key("source", "main"), vec![text(1, "source")]) + .await + .unwrap(); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + sessions + .fork_session("source", "0f83c2da-4b18-4c61-9d1e-2a7b3c4d5e6f", 1, &config) + .await + .unwrap_or_else(|error| { + panic!("a UUID-shaped fork target must not collide with an empty 8.3 stem: {error:?}") + }); + assert_eq!( + stored_rows(&connection, "~1"), + 1, + "the stored row is untouched" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// A store predating #2204 can hold a byte-identical duplicate and a +/// conflicting variant of the candidate at once. The duplicate's error takes +/// precedence on both write entries: it is the existing Session's protection, +/// while the variant's InvalidInput is only the admission refusal. +async fn assert_byte_identical_precedence(variant: &str, of: &str) { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_owner(&connection); + seed_stored_session(&connection, "abc"); + seed_stored_session(&connection, variant); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append(&store, key("source", "main"), vec![text(1, "source")]) + .await + .unwrap(); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + + let created = sessions + .create_owned_session( + "abc", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await; + assert!( + matches!(created, Err(AgentError::Storage(_))), + "creating abc while abc and {variant} ({of}) are stored must keep the duplicate's Storage error, got {created:?}" + ); + let forked = sessions.fork_session("source", "abc", 1, &config).await; + assert!( + matches!(forked, Err(AgentError::Storage(_))), + "forking into abc while abc and {variant} ({of}) are stored must keep the duplicate's Storage error, got {forked:?}" + ); + assert_eq!( + connection + .query_row("SELECT count(*) FROM agent_sessions", [], |row| row + .get::<_, i64>(0)) + .unwrap(), + 3, + "abc, {variant} and the fork source stay stored, nothing else is written" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// #2204 (decision Q2 c (2)): a legacy store holding `abc` beside its +/// uppercase variant reports the byte-identical duplicate as Storage, not the +/// variant's InvalidInput. +#[tokio::test] +async fn a_byte_identical_duplicate_beats_a_case_variant_on_both_write_entries() { + assert_byte_identical_precedence("ABC", "a case variant").await; +} + +/// #2204 (decision Q2 c (2)): the precedence also covers a variant that +/// collides only through the directory-shape rules, so creation must not +/// report InvalidInput for a duplicate the fork entry already reports as +/// Storage. +#[tokio::test] +async fn a_byte_identical_duplicate_beats_a_directory_shape_variant_on_both_write_entries() { + assert_byte_identical_precedence("abc.", "a directory-shape variant").await; +} + +/// #2204: a fork refused inside the first chunk transaction — before its copy +/// committed anything — runs no cleanup at all. Rows already present under +/// the fork's id, written around every validation the way an external writer +/// or a crashed earlier copy could leave them, must survive the refusal; the +/// ledger records neither an insert nor a delete. +#[tokio::test] +async fn a_fork_refused_before_its_first_write_deletes_no_preexisting_rows() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append( + &store, + key("source", "main"), + vec![text(1, "first"), text(2, "second"), text(3, "third")], + ) + .await + .unwrap(); + let connection = Connection::open(&database.0).unwrap(); + seed_stored_session(&connection, "Fork-Keep"); + // The row stands in for what an external writer or a crashed copy leaves + // under an id no Session owns: it cannot satisfy the branch foreign key, + // so it is written with the checks off, the way such rows exist. + connection + .execute_batch( + "PRAGMA foreign_keys = OFF; + INSERT INTO timeline_branches (session_id, branch_id, info, sequence) \ + VALUES ('fork-keep', 'main', '{\"id\":\"main\",\"parent\":null,\"branch_point\":null,\"create_anchor\":null}', 0); + PRAGMA foreign_keys = ON;", + ) + .unwrap(); + ledger_fork_writes(&connection, "fork-keep"); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + + let result = sessions + .fork_session("source", "fork-keep", 3, &config) + .await; + assert!( + matches!(result, Err(AgentError::InvalidInput(_))), + "the case-variant fork must be refused with InvalidInput, got {result:?}" + ); + assert_eq!( + connection + .query_row( + "SELECT count(*) FROM timeline_branches WHERE session_id='fork-keep'", + [], + |row| row.get::<_, i64>(0) + ) + .unwrap(), + 1, + "the rows already present under the fork's id must survive a refusal that wrote nothing" + ); + assert!( + ledger_entries(&connection).is_empty(), + "the refusal may not write or delete a single row, ledger: {:?}", + ledger_entries(&connection) + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// #2204: a legacy id whose Windows resolution forks past the state cap — +/// every `.. ` segment doubles the comparison's states — cannot establish its +/// destination, so it is undecidable rather than disjoint: creation and the +/// fork refuse before either publishes anything, while the stored row keeps +/// its bytes, its reads and POSIX deletion are unchanged, and deleting the +/// row unblocks the candidates. Forking *from* the row while it is stored is +/// refused too: the target cannot prove its directory disjoint from a +/// destination no bounded comparison can place. +#[tokio::test] +async fn windows_state_cap_is_undecidable_and_refuses_create_and_fork() { + const CAPPED: &str = "abc\\.. \\.. \\.. \\.. \\.. \\.. \\.. \\.. \\.. \\def"; + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_owner(&connection); + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + append(&store, key("source", "main"), vec![text(1, "source")]) + .await + .unwrap(); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + seed_stored_session(&connection, CAPPED); + connection + .execute( + "INSERT INTO timeline_branches (session_id, branch_id, info, sequence) \ + VALUES (?1, 'main', '{\"id\":\"main\"}', 0)", + [CAPPED], + ) + .unwrap(); + append( + &store, + key(CAPPED, "main"), + vec![text(1, "first"), text(2, "second")], + ) + .await + .unwrap(); + + let created = sessions + .create_owned_session( + "abc", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await; + assert!( + matches!(created, Err(AgentError::InvalidInput(_))), + "an id whose resolution passes the state cap is undecidable, so creation must be InvalidInput, got {created:?}" + ); + let forked = sessions.fork_session("source", "abc", 1, &config).await; + assert!( + matches!(forked, Err(AgentError::InvalidInput(_))), + "an id whose resolution passes the state cap is undecidable, so the fork must be InvalidInput, got {forked:?}" + ); + assert_eq!( + stored_rows(&connection, "abc"), + 0, + "the refused candidate writes nothing" + ); + + let capped_config = sessions.session_config_text(CAPPED).await.unwrap().unwrap(); + assert!( + sessions.session_config(CAPPED).await.unwrap().is_some(), + "the stored row reads as written" + ); + let from_capped = sessions + .fork_session(CAPPED, "valid-fork", 2, &capped_config) + .await; + assert!( + matches!(from_capped, Err(AgentError::InvalidInput(_))), + "forking from the undecidable row is refused while the row is stored: the target cannot prove disjointness, got {from_capped:?}" + ); + assert_eq!( + stored_rows(&connection, "valid-fork"), + 0, + "the refused fork writes nothing" + ); + + assert!( + sessions.delete_session(CAPPED).await.unwrap(), + "POSIX deletes the row as before: its backslashes are ordinary bytes of one component" + ); + sessions + .create_owned_session( + "abc", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await + .unwrap(); + sessions + .fork_session("source", "def", 1, &config) + .await + .unwrap(); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} + +/// The test store's output root: the directory the admission comparison +/// resolves, spelled exactly as `SqliteStorage::open` derives it, so a watch +/// registered for it matches. +fn output_root(database: &Database) -> std::path::PathBuf { + database.0.parent().unwrap().join("command-output") +} + +/// #2204: the indexed admission is constant-time for a store without legacy +/// rows — and for one whose only non-conforming rows are pure ASCII, which +/// the covering partial index never lists. Neither opening the store nor any +/// creation or fork entry may resolve the output root: no filesystem probe +/// rides on the write path at all. A case-colliding candidate is refused by +/// the case lookup before the directory comparison is even needed. +#[tokio::test] +async fn the_indexed_admission_never_resolves_the_output_root() { + use dim_app_server::storage::timeline_testing; + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let mut watch = timeline_testing::observe_root_resolutions(output_root(&database)); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_owner(&connection); + + store + .create_session("alpha", &SessionConfig::default()) + .await + .unwrap(); + sessions + .create_owned_session( + "beta", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await + .unwrap(); + append(&store, key("alpha", "main"), vec![text(1, "source")]) + .await + .unwrap(); + let config = sessions + .session_config_text("alpha") + .await + .unwrap() + .unwrap(); + sessions + .fork_session("alpha", "gamma", 1, &config) + .await + .unwrap(); + assert_eq!( + watch.count(), + 0, + "an empty legacy index resolves the output root zero times across open and every creation and fork entry" + ); + + seed_stored_session(&connection, "Legacy-Case"); + store + .create_session("delta", &SessionConfig::default()) + .await + .unwrap(); + sessions + .create_owned_session( + "epsilon", + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await + .unwrap(); + sessions + .fork_session("alpha", "zeta", 1, &config) + .await + .unwrap(); + let colliding = store + .create_session("legacy-case", &SessionConfig::default()) + .await; + assert!( + matches!(colliding, Err(AgentError::InvalidInput(_))), + "the case-colliding candidate is refused by the case lookup alone, got {colliding:?}" + ); + assert_eq!( + watch.count(), + 0, + "pure ASCII rows never enter the partial index, so the output root still resolves zero times" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + drop(watch); + root.shutdown().await.unwrap(); +} + +/// #2204: resolving the output root probes the filesystem, so the two-phase +/// admission runs it after the first transaction rolled back — outside the +/// SQLite write lock and the connection mutex. With a legacy row stored, the +/// resolution is held at its entry: a second connection can begin and commit +/// an IMMEDIATE transaction in that interval, which the write lock would make +/// impossible, and once the resolution is released the conflict is still +/// refused before anything is written. +#[tokio::test] +async fn root_resolution_happens_outside_the_write_lock() { + use dim_app_server::storage::timeline_testing; + let database = Database::new(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_stored_session(&connection, "abc\\def"); + drop(connection); + + let mut watch = timeline_testing::hold_root_resolutions(output_root(&database)); + let creating = { + let store = store.clone(); + tokio::spawn(async move { store.create_session("abc", &SessionConfig::default()).await }) + }; + watch.arrived().await; + + let probe = Connection::open(&database.0).unwrap(); + probe.busy_timeout(Duration::ZERO).unwrap(); + probe + .execute_batch("BEGIN IMMEDIATE; COMMIT;") + .expect("a second write transaction begins and commits while the output root resolution is held outside the write lock"); + drop(probe); + + watch.release(); + let created = creating.await.unwrap(); + assert!( + matches!(created, Err(AgentError::InvalidInput(_))), + "the conflict is still refused once the resolution completes, got {created:?}" + ); + let connection = Connection::open(&database.0).unwrap(); + assert_eq!( + stored_rows(&connection, "abc"), + 0, + "the refused creation writes nothing" + ); + + drop(connection); + drop(watch); + store.close().await.unwrap(); + db.close().await.unwrap(); +} diff --git a/crates/dim-app-server/tests/transport_flow/process_typescript.rs b/crates/dim-app-server/tests/transport_flow/process_typescript.rs index 633d1dc703..8a92cd5281 100644 --- a/crates/dim-app-server/tests/transport_flow/process_typescript.rs +++ b/crates/dim-app-server/tests/transport_flow/process_typescript.rs @@ -1590,9 +1590,19 @@ async fn node_store_preserves_repository_results_and_worktree_removal_exclusion( ); raw.rollback_session(session).await.unwrap(); } - raw.create_session(protected.to_str().unwrap(), &config) - .await - .unwrap(); + { + let seeding = rusqlite::Connection::open(home.join("rust/dimcode.sqlite")).unwrap(); + seeding + .execute( + "INSERT INTO agent_sessions (session_id, config, created_at_ms, origin) \ + VALUES (?1, ?2, 0, 'client')", + rusqlite::params![ + protected.to_str().unwrap(), + serde_json::to_string(&SessionConfig::default()).unwrap() + ], + ) + .unwrap(); + } let refused = client .rpc( "storefixture.invalid_id", diff --git a/crates/dim-app-server/tests/windows_output_isolation_flow.rs b/crates/dim-app-server/tests/windows_output_isolation_flow.rs new file mode 100644 index 0000000000..7a2d6e0c21 --- /dev/null +++ b/crates/dim-app-server/tests/windows_output_isolation_flow.rs @@ -0,0 +1,403 @@ +//! #2204: the Session-id output-directory isolation on the Windows +//! filesystem it protects. POSIX hosts compare the ids' destinations +//! textually against volume rules they never execute; only here does the +//! drive-anchored resolution the comparison mirrors actually govern the +//! directories Sessions write. A legacy id resolving back inside the output +//! root — drive-absolute, or verbatim as a canonicalized Windows path spells +//! it — overlaps the candidate's own output directory and must refuse +//! creation and the fork with InvalidInput before either writes a row. + +use dim_agent_capabilities::file_storage::FileStoragePlugin; +use dim_agent_runtime::{AgentError, SessionConfig, StoredEvent, TimelineKey, TimelineStore}; +use dim_agent_types::{AgentEvent, AgentProfile, DeltaData, EventKind}; +use dim_app_server::protocol::SessionOrigin; +use dim_app_server::storage::{SqliteStorage, SqliteTimelineStore}; +use rusqlite::{Connection, params}; +use rutis::host::CtxHost; +use std::path::{Component, Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +struct Database(PathBuf); +impl Database { + fn new() -> Self { + let directory = + std::env::temp_dir().join(format!("dim-nocase-flow-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&directory).unwrap(); + Self(directory.join("dimcode.sqlite")) + } +} +impl Drop for Database { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(self.0.parent().unwrap()); + } +} + +/// The owner agent the store's writer foreign key requires: the writer +/// connection enforces `PRAGMA foreign_keys`, and the owned creation inserts +/// `session_owners.agent_id` against `agents`, so a test that never seeds it +/// fails on Windows — the platform this file runs on — with FOREIGN KEY +/// constraint failed instead of exercising the isolation. +fn seed_owner(connection: &Connection) { + connection + .execute( + "INSERT INTO agents(agent_id, profile, is_default) VALUES ('owner', ?1, 1)", + [serde_json::to_string(&AgentProfile { + name: "owner".into(), + description: String::new(), + system_prompt: String::new(), + tools: Some(vec![]), + model: None, + }) + .unwrap()], + ) + .unwrap(); +} + +/// A stored record written around every validation, the way a pre-#2204 or +/// external writer could leave it. +fn seed_stored_session(connection: &Connection, session_id: &str) { + let config = serde_json::to_string(&SessionConfig::default()).unwrap(); + connection + .execute( + "INSERT INTO agent_sessions (session_id, config, created_at_ms, origin) \ + VALUES (?1, ?2, 0, 'client')", + params![session_id, config], + ) + .unwrap(); +} + +fn stored_rows(connection: &Connection, session_id: &str) -> i64 { + connection + .query_row( + "SELECT (SELECT count(*) FROM agent_sessions WHERE session_id=?1) + \ + (SELECT count(*) FROM timeline_branches WHERE session_id=?1) + \ + (SELECT count(*) FROM timeline_events WHERE session_id=?1)", + [session_id], + |row| row.get(0), + ) + .unwrap() +} + +/// The normal components of a canonical path, the names a path spelling of +/// the output root carries. +fn normal_names(root: &Path) -> Vec { + root.components() + .filter_map(|component| match component { + Component::Normal(name) => Some(name.to_string_lossy().into_owned()), + _ => None, + }) + .collect() +} + +/// The drive letter of a canonical Windows path, the letter a verbatim +/// `\\?\` prefix or a plain `C:` prefix carries. +fn drive_letter(root: &Path) -> char { + let text = root.to_string_lossy(); + let text = text.strip_prefix(r"\\?\").unwrap_or(&text); + let bytes = text.as_bytes(); + assert!( + bytes.len() >= 2 && bytes[1] == b':' && bytes[0].is_ascii_alphabetic(), + "the test drive layout needs a lettered root, got {text}" + ); + (bytes[0] as char).to_ascii_lowercase() +} + +/// One stored legacy id, refused or admitted on both the creation and the +/// fork entry. `stored` derives from the test's own output root: the drive +/// layout and the root's real components only exist on the machine the test +/// runs on, so nothing in the id is hardcoded. Creation and the fork +/// admission each run in a fresh store, since the admitted id is written by +/// then. +async fn assert_shape( + stored: impl Fn(&Path) -> String, + candidate: &str, + admitted_control: bool, + why: &str, +) { + for fork_only in [false, true] { + let database = Database::new(); + let output_root = database + .0 + .parent() + .unwrap() + .canonicalize() + .unwrap() + .join("command-output"); + let stored = stored(&output_root); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + // The fork source needs no rows of its own: the refusal must precede + // the copy's first write, and an empty copy still exercises both + // chunk transactions the check rides on. + store + .create_session("source", &SessionConfig::default()) + .await + .unwrap(); + let connection = Connection::open(&database.0).unwrap(); + seed_owner(&connection); + let config = sessions + .session_config_text("source") + .await + .unwrap() + .unwrap(); + seed_stored_session(&connection, &stored); + + if fork_only { + let forked = sessions.fork_session("source", candidate, 1, &config).await; + if admitted_control { + assert!( + forked.is_ok(), + "{why}: forking into {candidate:?} while {stored:?} is stored must succeed, got {forked:?}" + ); + } else { + assert!( + matches!(forked, Err(AgentError::InvalidInput(_))), + "{why}: forking into {candidate:?} while {stored:?} is stored must be InvalidInput, got {forked:?}" + ); + } + } else { + let created = sessions + .create_owned_session( + candidate, + &SessionConfig::default(), + "owner", + 2, + None, + SessionOrigin::Client, + None, + ) + .await; + if admitted_control { + assert!( + created.is_ok(), + "{why}: creating {candidate:?} while {stored:?} is stored must succeed, got {created:?}" + ); + } else { + assert!( + matches!(created, Err(AgentError::InvalidInput(_))), + "{why}: creating {candidate:?} while {stored:?} is stored must be InvalidInput, got {created:?}" + ); + } + } + if admitted_control { + assert!( + stored_rows(&connection, candidate) > 0, + "{why}: the admitted candidate {candidate:?} is written" + ); + } else { + assert_eq!( + stored_rows(&connection, candidate), + 0, + "{why}: the refused candidate {candidate:?} writes nothing" + ); + } + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); + } +} + +/// A drive-absolute legacy id resolving back inside the output root — +/// `C:\\abc` — overlaps the candidate's own output +/// directory on the volume the test store lives on. Creation and the fork +/// must refuse the candidate before either writes, while the stored row +/// keeps its bytes; a candidate on an untouched directory is admitted. +#[tokio::test] +async fn drive_absolute_overlap_refuses_create_and_fork() { + assert_shape( + |root: &Path| { + format!( + "{}:\\{}\\abc", + drive_letter(root), + normal_names(root).join("\\") + ) + }, + "abc", + false, + "a drive-absolute id resolving inside the output root overlaps the candidate's directory", + ) + .await; + assert_shape( + |root: &Path| { + format!( + "{}:\\{}\\sibling", + drive_letter(root), + normal_names(root).join("\\") + ) + }, + "abc", + true, + "a drive-absolute id resolving beside the candidate's directory shares nothing with it", + ) + .await; + assert_shape( + |root: &Path| format!("\\{}\\abc", normal_names(root).join("\\")), + "abc", + false, + "a rooted id resolves inside the output root on the same volume, so it overlaps the candidate's directory", + ) + .await; + assert_shape( + |_: &Path| "\\unshared-root\\abc".to_owned(), + "abc", + true, + "a rooted id resolving beside the output root's own directory shares nothing with the candidate", + ) + .await; +} + +/// The verbatim spelling `\\?\C:\\abc` is the form +/// `canonicalize` returns on Windows: it names the same volume and directory +/// as the plain drive-absolute form, so the comparison's volume +/// normalization must treat it as one, and the id resolving inside the +/// output root refuses creation and the fork. +#[tokio::test] +async fn verbatim_overlap_refuses_create_and_fork() { + assert_shape( + |root: &Path| { + format!( + "\\\\?\\{}:\\{}\\abc", + drive_letter(root), + normal_names(root).join("\\") + ) + }, + "abc", + false, + "a verbatim id names the same volume and directory as the plain drive-absolute form", + ) + .await; +} + +fn key(session: &str, branch: &str) -> TimelineKey { + TimelineKey { + session_id: session.into(), + branch_id: branch.into(), + } +} + +fn record(sequence: u64, kind: EventKind) -> StoredEvent { + StoredEvent { + event: Arc::new(AgentEvent { + id: format!("event-{sequence}"), + sequence, + create_at: 1000 + sequence, + tags: Some(vec!["stored".into()]), + parent_call_id: None, + kind, + }), + trace: None, + batch_end: sequence, + } +} + +fn text(sequence: u64, delta: &str) -> StoredEvent { + record( + sequence, + EventKind::Text(DeltaData { + turn_id: "turn".into(), + request_id: "request".into(), + delta: delta.into(), + }), + ) +} + +async fn append( + store: &SqliteTimelineStore, + key: TimelineKey, + records: Vec, +) -> dim_agent_runtime::Result<()> { + let (sender, receiver) = tokio::sync::oneshot::channel(); + store.append( + key, + records, + Box::new(move |result| { + let _ = sender.send(result); + }), + )?; + tokio::time::timeout(Duration::from_secs(180), receiver) + .await + .unwrap() + .unwrap() +} + +/// A stored id already inside the output root keeps its bytes and its +/// behavior: restoration reads its rows as written, deletion removes it +/// through the product entry — a single plain component passes the deletion +/// boundary's shape check — and it forks as a source the way any Session +/// does. Only the admission of a conflicting new id is refused; the legacy +/// rows themselves never change. +#[tokio::test] +async fn legacy_single_component_ids_remain_operable() { + let database = Database::new(); + let directory = database.0.parent().unwrap().canonicalize().unwrap(); + let root = rutis::Ctx::root().unwrap(); + (&root.plugin(FileStoragePlugin::new(vec![directory.clone()]))) + .await + .unwrap(); + let db = SqliteStorage::open(database.0.clone()).unwrap(); + let sessions = dim_app_server::storage::SessionStore::new(db.clone(), root.clone(), 0); + let store = SqliteTimelineStore::new(db.clone()); + let connection = Connection::open(&database.0).unwrap(); + seed_owner(&connection); + seed_stored_session(&connection, "Legacy-9"); + connection + .execute( + "INSERT INTO timeline_branches (session_id, branch_id, info, sequence) \ + VALUES ('Legacy-9', 'main', '{\"id\":\"main\"}', 0)", + [], + ) + .unwrap(); + append( + &store, + key("Legacy-9", "main"), + vec![text(1, "first"), text(2, "second")], + ) + .await + .unwrap(); + + let config = sessions + .session_config_text("Legacy-9") + .await + .unwrap() + .unwrap(); + assert!( + sessions.session_config("Legacy-9").await.unwrap().is_some(), + "restoration reads the single-component legacy id's configuration as written" + ); + sessions + .fork_session("Legacy-9", "valid-fork", 2, &config) + .await + .unwrap(); + assert!( + stored_rows(&connection, "valid-fork") > 0, + "the legacy source's rows are copied into the fork" + ); + + assert!(sessions.delete_session("Legacy-9").await.unwrap()); + assert!( + connection + .query_row( + "SELECT NOT EXISTS(SELECT 1 FROM agent_sessions WHERE session_id='Legacy-9')", + [], + |row| row.get::<_, bool>(0) + ) + .unwrap(), + "deletion removes the single-component legacy id as before" + ); + + drop(connection); + drop(sessions); + store.close().await.unwrap(); + db.close().await.unwrap(); + root.shutdown().await.unwrap(); +} diff --git a/docs/architecture/build.md b/docs/architecture/build.md index e4ddcecf88..592869dc64 100644 --- a/docs/architecture/build.md +++ b/docs/architecture/build.md @@ -349,7 +349,7 @@ The root `./dev` entry performs incremental CLI/App Server builds without disabl The [Web workspace](../design/web-workspace.md) frontend in `web/` is a separate artifact (`scripts/stage-web.mjs` builds it; the CLI finds the installed `dimcode-web` package or a `web/` directory beside the executable or in the product home, or `DIMCODE_WEB_ASSETS` names one), so building `dim-app-server` and `dimcode` needs neither Node nor npm. Only `cargo build --features embedded-web` compiles the frontend in; then `build.rs` runs `npm ci` and `npm run build` when that frontend changed, and a host without npm fails the build. Otherwise Node is only needed for packaging, packaging checks and TypeScript plugin execution/development. `.node-version` pins the Node version bundled into account-enabled releases. The `runtime/package-lock.json` fixes the rutis Node runtime and its transitive dependencies; `npm ci --ignore-scripts --prefix runtime` installs them for local bridge testing. -Pull requests run workspace verification on self-hosted Linux x64 runners labelled `dim-verify`, with eight Cargo build jobs. The job checks that bubblewrap can create the sandbox the confined tests use (a user namespace with a private `/proc`) before running them. The macOS ARM64 runners use four Cargo jobs for the native Rust checks on pull requests and for full workspace verification on `main`. Use `node scripts/test-macos-native.mjs --list` to inspect the Rust selection from the current Cargo targets, Rust platform guards and host-specific test fixtures. On an Apple Silicon Mac, run `node scripts/test-macos-native.mjs` to build those targets and check each selected name against its compiled test binary before execution. Tests marked for manual execution keep their normal ignore status. The [workflow guide](../release/README.md#github-workflows) describes path selection, native packaging checks and manual dispatch. The separate `windows-cli` job runs the `dim-cli` library tests on a self-hosted Windows x64 runner, where its fixture writes to the clipboard. When a pull request changes Windows storage, host-platform, named-pipe or worktree-removal paths, when a push to `main` changes a path that selects the job, and on scheduled sweeps and manual dispatch, the same job also builds and runs the Windows-only boundary flows (`file_storage_flow`'s Windows checks, `host_platform_windows_flow`, `named_pipe_flow` and `worktree_removal_flow`) in that directory; `node scripts/test-windows-native.mjs --list` prints the selection and a run checks every selected name against its compiled test binary. The job keeps its fifteen-minute hard timeout. Across 25 sampled runs the whole job took 2.2–6.8 minutes and the native-flows step 1.1–4.4 minutes, so the compile that the step adds fits the budget. The layout workflow uses hosted `windows-2022` and `windows-11-arm` runners, with Python 3.13 and the pinned native MSVC Rust host toolchain provisioned explicitly. Release builds use GitHub-hosted VMs matching each target OS and CPU. See the [runner setup and release matrix](../release/README.md#runner-setup). +Pull requests run workspace verification on self-hosted Linux x64 runners labelled `dim-verify`, with eight Cargo build jobs. The job checks that bubblewrap can create the sandbox the confined tests use (a user namespace with a private `/proc`) before running them. The macOS ARM64 runners use four Cargo jobs for the native Rust checks on pull requests and for full workspace verification on `main`. Use `node scripts/test-macos-native.mjs --list` to inspect the Rust selection from the current Cargo targets, Rust platform guards and host-specific test fixtures. On an Apple Silicon Mac, run `node scripts/test-macos-native.mjs` to build those targets and check each selected name against its compiled test binary before execution. Tests marked for manual execution keep their normal ignore status. The [workflow guide](../release/README.md#github-workflows) describes path selection, native packaging checks and manual dispatch. The separate `windows-cli` job runs the `dim-cli` library tests on a self-hosted Windows x64 runner, where its fixture writes to the clipboard. When a pull request changes Windows storage, host-platform, named-pipe or worktree-removal paths, when a push to `main` changes a path that selects the job, and on scheduled sweeps and manual dispatch, the same job also builds and runs the Windows-only boundary flows (`file_storage_flow`'s Windows checks, `host_platform_windows_flow`, `named_pipe_flow`, `windows_output_isolation_flow` and `worktree_removal_flow`) in that directory; `node scripts/test-windows-native.mjs --list` prints the selection and a run checks every selected name against its compiled test binary. The job keeps its fifteen-minute hard timeout. Across 25 sampled runs the whole job took 2.2–6.8 minutes and the native-flows step 1.1–4.4 minutes, so the compile that the step adds fits the budget. The layout workflow uses hosted `windows-2022` and `windows-11-arm` runners, with Python 3.13 and the pinned native MSVC Rust host toolchain provisioned explicitly. Release builds use GitHub-hosted VMs matching each target OS and CPU. See the [runner setup and release matrix](../release/README.md#runner-setup). The macOS clipboard flows use private pasteboards and serialize access to the shared pasteboard server; other tests remain parallel. diff --git a/docs/design/appserver/native-storage-format.md b/docs/design/appserver/native-storage-format.md index 5d34144b45..c259d6c98a 100644 --- a/docs/design/appserver/native-storage-format.md +++ b/docs/design/appserver/native-storage-format.md @@ -214,7 +214,7 @@ v36 的文本索引和事件编码合同继续适用。 后续提案:[状态读取索引与数组元素](#提案状态读取索引与数组元素)。数组元素编码采用独立新格式;owner 结果复用既有事件索引。 -The current native format is **v48**, with optional command and delegation task titles, conditional queued-input Steer candidates in withdrawal commands, directly addressed large-array elements, versioned unfinished-member indexes, property text-candidate indexes, a submission identity index, a Session's activity time following its own activity, worktree directory and Session usage records with the directory's last-used time, `prompt/changed` events naming their delivery inputs, source-owned `settings_documents`, +The v48 native format introduced optional command and delegation task titles, conditional queued-input Steer candidates in withdrawal commands, directly addressed large-array elements, versioned unfinished-member indexes, property text-candidate indexes, a submission identity index, a Session's activity time following its own activity, worktree directory and Session usage records with the directory's last-used time, `prompt/changed` events naming their delivery inputs, source-owned `settings_documents`, SessionStore's Session-file rows, its title metadata, request messages stored as lists of content-addressed nodes, extension event rows, Session configurations and Agent profiles that may omit their mount list, the two @@ -222,11 +222,11 @@ branch end events, the tool-effect and digest fields, and tool schemas that may omit `type`, the Session catalog projection, a configuration's System source, a model limit that only a declaration writes, a delegation's Agent owner and member leader, a Session's creation origin, Session file grants, command output -ownership and the two context reading switches on timeline events. Startup -requires the exact v48 SQL schema and a single +ownership and the two context reading switches on timeline events. The v48 +startup gate required the exact v48 SQL schema and a single format marker of 48 before writable PRAGMAs, or the exact v47, main v42–v46 and resume v42–v44 families, v41, v40, v39, v38, v37, v36, v35, v34, v33, v32, v31, v30, v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, v19, v18, v17, v16, v15 or v13 schema with its own marker, -which the same startup transaction upgrades in place to v48 one step after +which the same startup transaction upgraded in place to v48 one step after another ([v48 task titles](#v48-task-titles), [v47 merged resume format](#v47合并-main-v46-与-resume-v44), [#1477 v46 reasoning count](#v46modelusage-携带推理-token-数), [#1451 v45 last-used time](#v45worktree-目录的最后使用时间), [v44 prompt changes](#v44提示变更携带其投递输入), [v43 conditional Steer](#v43-conditional-queued-input-steer), [v41 merged child tool-call and Timeline indexes](#v41合并-child-tool-call-与-timeline-索引格式), [#1421 v42 decision](#v42agent_sessions-接受-automation-来源), [v36 text candidates](#v36-property-text-candidates), [v35 submission index](#v35-submission-identity-index), [#1099 v34 decision](#1099-v34-格式决定), [#911 v33 decision](#911-v33-格式决定), [#605 v32 decision](#605-v32-格式决定), [#708 v31 decision](#708-v31-格式决定), [#557 v30 decision](#557-v30-格式决定), [ADR 013 v29 decision](#adr-013-v29-格式决定), [#717 v28 decision](#717-v28-格式决定), [#593 v27 decision](#593-v27-格式决定), [S5a v15 decision](#s5a-v15-格式决定), [S5b v16 decision](#s5b-v16-格式决定), [#193 v17 decision](#193-v17-格式决定), @@ -245,14 +245,20 @@ valid in v48, and v16 request rows stay readable as written. (`(session_id, branch_id, kind, sequence) WHERE kind IN ('turn/start', 'input/message')`, [latest-turn 窗口 §5.1](session-history-window.md#51-the-derived-index))、 `timeline_policy_turns`(`(session_id, branch_id, kind, sequence, event_id) WHERE kind = 'turn/start'`, -已无读者,删除它要作为格式步骤)与事件查询的 +已无读者,删除它要作为格式步骤)、事件查询的 `timeline_events_by_kind`(`(session_id, branch_id, kind, sequence, event_id)`,按 kind -读取事件而不碰事件体,[ADR 019](../../adr/019-event-query.md) D4):读写打开在启动事务内用 -`CREATE INDEX IF NOT EXISTS` 创建或补建,只读导出只接受它们。它们不含数据,可从 -`timeline_events` 重新推导,读同一份事件不因它们有无而不同,因此不属于格式:启动门禁的 -精确结构比较忽略这些名字,格式标记不变(当前 v48);其余任何多余对象仍按原规则拒绝。代价是早于 -该变更的二进制不认识这些名字,会以 "unsupported SQLite schema … preserved" 拒绝已有该 -索引的库(行不变,新二进制可再次打开)。 +读取事件而不碰事件体,[ADR 019](../../adr/019-event-query.md) D4)与 +`agent_sessions_session_id_nocase`(`agent_sessions(session_id COLLATE NOCASE)`,#2204 +创建写入入口的大小写冲突检查走它做索引查找而不是扫表)与 +`agent_sessions_session_id_non_ascii_word`(`agent_sessions(session_id) +WHERE session_id GLOB '*[^0-9A-Za-z_-]*'`,#2204 输出目录冲突检查按它逐个取出 +准入字母表之外的已存 id 再在 Rust 里按文件系统身份规则判断,常规库为空、不扫表): +读写打开在启动事务内用 +`CREATE INDEX IF NOT EXISTS` 创建或补建,只读导出只接受它们。它们不含数据,可从其 +基表重新推导,读同一份数据不因它们有无而不同,因此不属于格式:启动门禁的 +精确结构比较忽略这些名字,格式标记不变(当前 v53);其余任何多余对象仍按原规则拒绝。代价是早于 +该变更的二进制不认识这些名字,会以 "unsupported SQLite schema … preserved" 拒绝已有这些 +索引的库(行不变,原库保留,新二进制可再次打开)。 Storage versions are independent of RPC versions. Private MCP/Skill business documents do not belong in loader rows, events, diagnostics, Sessions or Timelines. diff --git a/docs/design/resource-faces.md b/docs/design/resource-faces.md index d85a031886..b59821d1c3 100644 --- a/docs/design/resource-faces.md +++ b/docs/design/resource-faces.md @@ -509,11 +509,17 @@ operation, without repeated remote probes. `trace` takes the same position and r and `saveSnapshot {sessionId,branchId,snapshot}` return `{}`. `sessionConfig {sessionId}` returns `{config}`. `latestSnapshot {sessionId,branchId,through,interpreter}` returns `{snapshot}`. These are storage lifecycle steps. `createSession` prepares the backend record; it does not -initialize or publish an Agent Session. `rollbackSession` undoes a successfully prepared creation -whose initialization failed, after its producers have stopped; it is not the general deletion -workflow. `releaseSession` drains accepted backend writes and releases their resources without -closing the Agent Session or its admission. App Server creation/deletion retain the repository -and lifecycle obligations in §5.2. +initialize or publish an Agent Session. Its id is caller-selected, so the native store's shared +insertion boundary applies the same admission as the creation entries in §5.2: one to sixty-four +characters of `[a-z0-9_-]`, never a Windows reserved device name, rejected with `invalid` before +anything is written, as is an id differing from a stored one only by case or sharing its output +directory with a stored legacy id; a byte-identical duplicate keeps its `storage` error. Ids +already stored are never re-validated: restoration reads them as written, and deletion plus use +as a fork source keep the single normal path component check (#2204). `rollbackSession` undoes a +successfully prepared creation whose initialization failed, after its producers have stopped; it +is not the general deletion workflow. `releaseSession` drains accepted backend writes and releases +their resources without closing the Agent Session or its admission. App Server creation/deletion +retain the repository and lifecycle obligations in §5.2. Snapshots retain their canonical fields (`sequence`, `event_id`, `interpreter`, `state`), optional acceleration semantics and owner validation. Domain errors preserve `{code,message}` using @@ -589,9 +595,17 @@ per-caller Session ownership or grant scoping. The lifecycle owner remains respo then initialize the fork under the source Agent/protocol. The repository copies the supplied text without applying live protocol exclusions or rebuilding the configuration. -`createOwnedSession`, `fork` and `delete` reject Session ids that are not a single normal path -component with `invalid`, before acquiring ownership or touching rows or output paths. These -checks are shared with the native Session admission/deletion boundary. +`createOwnedSession` and `fork` targets admit only lowercase ASCII Session ids — one to +sixty-four characters of `[a-z0-9_-]`, never a Windows reserved device name — rejecting any +other shape with `invalid` before acquiring ownership or touching rows or output paths. They +also reject with `invalid` an id that differs from a stored one only by case, and an id that +would share an output directory with a stored legacy id under a supported filesystem's +identity rules — Unicode folding pairs, default-ignorable code points, and the Windows +separators, trailing characters and 8.3 short names ([native storage +format](appserver/native-storage-format.md), #2204); a byte-identical duplicate keeps its +`storage` error. These creation checks are shared with the native Session admission boundary. +`delete` applies only the single normal path component check, so ids stored before the +admission rule stay deletable. Grant kind is `file` or `dir`, mode is `read` or `write`; adding read never downgrades an existing write grant. `language` is a ReplyLanguage code or null to clear it. diff --git a/docs/release/README.md b/docs/release/README.md index f41d0aec40..90f086ae1e 100644 --- a/docs/release/README.md +++ b/docs/release/README.md @@ -223,7 +223,7 @@ release packages use the ordinary Cargo executable. `ci.yml` runs on pull requests, pushes to `main`, a daily scheduled full sweep (`0 19 * * *` UTC), and manual dispatch. A pull request runs the groups its changed paths need, as decided by `scripts/ci-changes.mjs`. A push to `main` runs only `changes` and `ci-ok` when its entire push range changes only paths that select no check group (documentation and non-code repository metadata); pushes touching any checked path or whose base cannot be compared keep the full `main` run while the daily scheduled sweep is established (ADR 026 D5). Scheduled sweeps and manual dispatch select every group across both Linux and macOS: if a scheduled sweep fails on a cross-group regression, the maintainers triage it and bisect the `main` commit range since the previous passing sweep back to the regressing merge. Every push to `main` runs its selected jobs to completion: a later push does not cancel them, so each merge has its own result and the `main CI` badge in the [README](../../README.md) reports the latest finished one. -CI builds the workspace, checks formatting and Clippy, runs workspace tests and boundary checks, runs the packaging/development script tests in a dedicated Linux x64 `scripts` job, and exercises the ignored actual CLI profile and public Node-backed flows. `ci-ok` passes when every selected gating job passes, so it is the check to require. CI builds without debug info (`CARGO_PROFILE_DEV_DEBUG=0`). The [build environment](../architecture/build.md) describes test artifact reuse, concurrency limits, and target deadlines. Cargo runs documentation tests with the same features, and ignored CLI and Node flows reuse the recorded binaries without package-scoped recompilation. Web source changes run the lightweight `static-checks` job (`xtask-check`) on Linux x64 without compiling business runtime crates. Plugin pages select the runtime-assembled `xtask` check. From `scripts/`, `scripts/stage-web.mjs` and `scripts/run-rust-test.mjs` select the `web` job (the latter deliberately selects every group), while Rust files read directly by packaging scripts (`crates/dim-app-server/src/protocol.rs`, `crates/dim-app-server/src/storage/sqlite.rs`, and `crates/dim-app-server/resources/`) retain their owning packaging checks. Node-backed checks run for runtime, binding and service-contract paths, and CLI-only changes retain their ordinary and actual-profile flows. Windows client transport and CLI terminal crates (`crates/dim-cli/`, `crates/dim-client/`, `crates/dim-agent-types/`, `vendor/grok-build/`) trigger `windows-cli`. Windows storage, host-platform, named-pipe and worktree-removal paths (`crates/dim-agent-capabilities/src/file_storage*`, `crates/dim-agent-capabilities/src/host_platform*`, `crates/dim-app-server/src/lib.rs`, `transport.rs`, `pipe_client.rs`, `cli.rs`, `worktrees.rs` and the test files that hold those flows, including `worktree_removal_flow.rs`) also run its Windows-native boundary step, which `main` pushes that select the job, scheduled sweeps and manual dispatch execute as well. Evaluation tests use `xtask/eval-tests` for `xtask/` changes, debug-build CLI acceptances use `dimcode`'s `dev-tests` feature for their owning test files, and the wall-clock handoff runs for execution-related changes. PRs run `verify (linux)` for the selected Rust/`xtask` groups. Rust PRs also run `macos-native` on Apple Silicon, and changes affecting native packaging or code layout select its macOS script checks on PRs, `main` pushes, scheduled sweeps and manual runs. All selected jobs feed `ci-ok`. Full `main` pushes run `verify (macos)`, and scheduled sweeps and manual dispatch run full verification on both Linux and macOS. The `web` job runs on self-hosted Windows x64. It stages the frontend package, verifies generated declarations and bundled dependency notices, and runs the Web tests. +CI builds the workspace, checks formatting and Clippy, runs workspace tests and boundary checks, runs the packaging/development script tests in a dedicated Linux x64 `scripts` job, and exercises the ignored actual CLI profile and public Node-backed flows. `ci-ok` passes when every selected gating job passes, so it is the check to require. CI builds without debug info (`CARGO_PROFILE_DEV_DEBUG=0`). The [build environment](../architecture/build.md) describes test artifact reuse, concurrency limits, and target deadlines. Cargo runs documentation tests with the same features, and ignored CLI and Node flows reuse the recorded binaries without package-scoped recompilation. Web source changes run the lightweight `static-checks` job (`xtask-check`) on Linux x64 without compiling business runtime crates. Plugin pages select the runtime-assembled `xtask` check. From `scripts/`, `scripts/stage-web.mjs` and `scripts/run-rust-test.mjs` select the `web` job (the latter deliberately selects every group), while Rust files read directly by packaging scripts (`crates/dim-app-server/src/protocol.rs`, `crates/dim-app-server/src/storage/sqlite.rs`, and `crates/dim-app-server/resources/`) retain their owning packaging checks. Node-backed checks run for runtime, binding and service-contract paths, and CLI-only changes retain their ordinary and actual-profile flows. Windows client transport and CLI terminal crates (`crates/dim-cli/`, `crates/dim-client/`, `crates/dim-agent-types/`, `vendor/grok-build/`) trigger `windows-cli`. Windows storage, host-platform, named-pipe and worktree-removal paths (`crates/dim-agent-capabilities/src/file_storage*`, `crates/dim-agent-capabilities/src/host_platform*`, `crates/dim-app-server/src/lib.rs`, `transport.rs`, `pipe_client.rs`, `cli.rs`, `worktrees.rs`, `storage/timeline.rs` and the test files that hold those flows, including `windows_output_isolation_flow.rs` and `worktree_removal_flow.rs`) also run its Windows-native boundary step, which `main` pushes that select the job, scheduled sweeps and manual dispatch execute as well. Evaluation tests use `xtask/eval-tests` for `xtask/` changes, debug-build CLI acceptances use `dimcode`'s `dev-tests` feature for their owning test files, and the wall-clock handoff runs for execution-related changes. PRs run `verify (linux)` for the selected Rust/`xtask` groups. Rust PRs also run `macos-native` on Apple Silicon, and changes affecting native packaging or code layout select its macOS script checks on PRs, `main` pushes, scheduled sweeps and manual runs. All selected jobs feed `ci-ok`. Full `main` pushes run `verify (macos)`, and scheduled sweeps and manual dispatch run full verification on both Linux and macOS. The `web` job runs on self-hosted Windows x64. It stages the frontend package, verifies generated declarations and bundled dependency notices, and runs the Web tests. The `Verify Python plugins` step is off by default. When a Python plugin ships, set the repository Actions variable `DIM_CI_PYTHON_PLUGINS` to `true` to run it whenever the Node check group is selected. It prepares CPython for the `python_plugin_` flows and reuses the App Server test binary from the workspace build. See the [App Server verification commands](../../crates/dim-app-server/README.md#verification) to run the suites locally. diff --git a/npm/plugin.d.ts b/npm/plugin.d.ts index 141ab31283..8932f56faa 100644 --- a/npm/plugin.d.ts +++ b/npm/plugin.d.ts @@ -694,7 +694,7 @@ export interface SqliteStorage extends Pick): Promise<{ databaseBytes: number; walBytes: number; reclaimableBytes: number }>; } -/** Process repository operations for trusted plugins; ids are not scoped to the caller. Create/fork/delete reject ids that are not one normal path component. */ +/** Process repository operations for trusted plugins; ids are not scoped to the caller. Create/fork admit only lowercase ASCII ids — one to sixty-four characters of `[a-z0-9_-]`, never a Windows reserved device name — and reject an id that differs from a stored one only by case or would share its output directory with a stored legacy id under a supported filesystem's identity rules; delete applies only the single normal path component check. */ export interface Store { query(request: { scope: TimelineReadScope; query: import('./branch-services.js').QuerySpec; page?: import('./branch-services.js').QueryPage | null }): Promise<{ result: import('./branch-services.js').QueryOutput; next: import('./branch-services.js').QueryCursor | null }>; /** Stored page: database sequence and closed=false; the lifecycle owner supplies live enrichment. */ @@ -760,7 +760,8 @@ export interface TimelineStore { /** Registration completes before return; observe later admissions, without replay of earlier batches. */ commits(request: { sessionId: string }, listener: (completion: TimelineStoreCompletion) => void | Promise): Promise<{ subscriptionId: string }>; closeCommits(request: { subscriptionId: string }): Promise<{}>; - /** Prepare the backend record; the lifecycle owner initializes and publishes the Agent Session. */ + /** Prepare the backend record; the lifecycle owner initializes and publishes the Agent Session. + * The id is caller-selected and admits the same rule as create/fork targets: one to sixty-four characters of `[a-z0-9_-]`, never a Windows reserved device name, rejected with `invalid` before anything is written, as is an id differing from a stored one only by case or sharing its output directory with a stored legacy id; a byte-identical duplicate rejects `storage`. Ids already stored stay readable, deletable and usable as fork sources unchanged. */ createSession(request: { sessionId: string; config: SessionConfig }): Promise<{}>; sessionConfig(request: { sessionId: string }): Promise<{ config: SessionConfig | null }>; /** Drain accepted storage writes; does not close the Agent Session or its admission. */ diff --git a/scripts/ci-changes.mjs b/scripts/ci-changes.mjs index c426d1ad15..d5790401e4 100644 --- a/scripts/ci-changes.mjs +++ b/scripts/ci-changes.mjs @@ -22,7 +22,8 @@ const windowsNative=[ /^crates\/dim-agent-capabilities\/src\/(?:file_storage\.rs|file_storage\/|host_platform\.rs|host_platform\/)/, /^crates\/dim-agent-capabilities\/tests\/(?:capabilities_flow|file_storage_flow|host_platform_windows_flow)\.rs$/, /^crates\/dim-app-server\/src\/(?:lib|transport|pipe_client|cli|worktrees)\.rs$/, - /^crates\/dim-app-server\/tests\/(?:app_server_flow|named_pipe_flow|worktree_removal_flow)\.rs$/, + /^crates\/dim-app-server\/src\/storage\/timeline\.rs$/, + /^crates\/dim-app-server\/tests\/(?:app_server_flow|named_pipe_flow|worktree_removal_flow|windows_output_isolation_flow)\.rs$/, /^scripts\/test-windows-native\.mjs$/, ]; diff --git a/scripts/ci-changes.test.mjs b/scripts/ci-changes.test.mjs index ab66a06803..f51a941088 100644 --- a/scripts/ci-changes.test.mjs +++ b/scripts/ci-changes.test.mjs @@ -92,6 +92,8 @@ test('Windows-native flows follow their storage, host and named pipe paths',()=> 'crates/dim-app-server/tests/app_server_flow.rs', 'crates/dim-app-server/tests/named_pipe_flow.rs', 'crates/dim-app-server/tests/worktree_removal_flow.rs', + 'crates/dim-app-server/tests/windows_output_isolation_flow.rs', + 'crates/dim-app-server/src/storage/timeline.rs', 'scripts/test-windows-native.mjs', ]) assert.equal(classify([file]).windows_native,true,file); for (const file of [ diff --git a/scripts/test-windows-native.mjs b/scripts/test-windows-native.mjs index 469e601fff..c1cc041d4a 100644 --- a/scripts/test-windows-native.mjs +++ b/scripts/test-windows-native.mjs @@ -22,6 +22,9 @@ export const flows = [ {package: 'dim-app-server', target: 'app_server_flow', tests: [ 'named_pipe_flow::native_client_authenticates_before_rpc_and_exits_without_stdin_eof', 'named_pipe_flow::named_pipe_is_private_exclusive_and_shares_session_cleanup', + 'windows_output_isolation_flow::drive_absolute_overlap_refuses_create_and_fork', + 'windows_output_isolation_flow::legacy_single_component_ids_remain_operable', + 'windows_output_isolation_flow::verbatim_overlap_refuses_create_and_fork', 'worktree_removal_flow::a_non_force_removal_refuses_an_unregistered_directory', ]}, ]; diff --git a/xtask/src/app_server.rs b/xtask/src/app_server.rs index f5d56e0525..042a20f87d 100644 --- a/xtask/src/app_server.rs +++ b/xtask/src/app_server.rs @@ -255,6 +255,7 @@ pub async fn serve_home( }; let mut builder = AgentBuilder::new(AgentConfig::default()); dim_session_title::install(&mut builder); + config.output_root = Some(output_root.clone()); defaults::install_local_execution_with( &mut builder, ModelProviderPlugin::process,