From 8383611b219f7aee7f1cfe279cc0ba2d6434ce2a Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 12:00:12 -0400 Subject: [PATCH 1/8] Add native steps for discarding one unpublished construction stage Observe a stage through a no-follow, non-blocking handle (regular single-link file, 1 MiB bound, SHA-256), move it with a no-replace rename into a private discarded// slot of its namespace and unlink it there only while its identity still matches. Checkout claim and acknowledgement stages are fenced by their constructor lock and published records; file-copy cancellation-record stages are bound to their exact origin, the namespace lock and the owner's lifetime lock, and quarantined bytes keep counting toward the snapshot cap. --- crates/cyber-core/src/construction_discard.rs | 580 ++++++++++++++++++ crates/cyber-core/src/lib.rs | 1 + crates/cyber-core/src/worktrees.rs | 5 +- crates/cyber-core/src/worktrees/activity.rs | 5 +- .../src/worktrees/activity/snapshot.rs | 2 + .../activity/snapshot/acknowledgement.rs | 18 + .../worktrees/activity/snapshot/discard.rs | 308 ++++++++++ crates/cyber-snapshot/src/copy/discard.rs | 457 ++++++++++++++ crates/cyber-snapshot/src/copy/mod.rs | 7 + crates/cyber-snapshot/src/lib.rs | 50 ++ 10 files changed, 1430 insertions(+), 3 deletions(-) create mode 100644 crates/cyber-core/src/construction_discard.rs create mode 100644 crates/cyber-core/src/worktrees/activity/snapshot/discard.rs create mode 100644 crates/cyber-snapshot/src/copy/discard.rs diff --git a/crates/cyber-core/src/construction_discard.rs b/crates/cyber-core/src/construction_discard.rs new file mode 100644 index 00000000..3be84736 --- /dev/null +++ b/crates/cyber-core/src/construction_discard.rs @@ -0,0 +1,580 @@ +//! Native steps of an owner-confirmed discard of one unpublished construction stage. +//! +//! A stage is observed through a no-follow, non-blocking handle (regular file, one +//! link, at most [`STAGE_LIMIT`] bytes) and identified by device, inode, size, +//! modification time and SHA-256. A discard moves exactly that file with a +//! no-replace rename into `discarded//` beside its private namespace, flushes +//! both directories and only then unlinks it from the quarantine. Every step +//! compares the observed identity with the reviewed one first; a different file is +//! reported and never deleted. Nothing here decides who may discard: callers fence +//! the owner activity before [`quarantine`]. +use cap_std::fs::Dir; +use serde::{Deserialize, Serialize}; +use std::fs::File; +use std::io; + +/// Largest stage a review digests; larger stages are refused. +pub const STAGE_LIMIT: u64 = 1024 * 1024; +/// The private quarantine directory created in a stage's namespace. +pub const QUARANTINE: &str = "discarded"; + +/// Native identity and contents of one stage at review. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct StageEvidence { + pub device: u64, + pub inode: u64, + pub size: u64, + /// Modification time in nanoseconds since the Unix epoch. + pub modified_ns: i64, + /// Lowercase hex SHA-256 of the stage bytes. + pub sha256: String, +} + +/// Where a reviewed stage is now. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Place { + /// Still at its original name with the reviewed identity. + Source, + /// Moved into its quarantine slot with the reviewed identity. + Quarantined, + /// Neither: the unlink already happened. + Gone, + /// A file with another identity holds the name; it is never deleted. + Changed(String), +} + +/// One quarantined entry that still awaits its unlink. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Pending { + pub key: String, + pub name: String, + pub size: u64, +} + +fn invalid(message: impl Into) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message.into()) +} + +/// A single plain path component, as every stage and slot name must be. +pub fn valid_component(name: &str) -> bool { + !name.is_empty() + && name.len() <= 255 + && !matches!(name, "." | "..") + && name + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"_-.".contains(&byte)) +} + +/// Quarantine slots are lowercase SHA-256 hex digests chosen by the caller. +pub fn valid_key(key: &str) -> bool { + key.len() == 64 + && key + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) +} + +fn require_component(name: &str) -> io::Result<()> { + if valid_component(name) { + Ok(()) + } else { + Err(invalid("Invalid construction stage name")) + } +} + +#[cfg(unix)] +mod native { + use super::*; + use cap_fs_ext::{DirExt, FollowSymlinks, OpenOptionsFollowExt}; + use cap_std::fs::{DirBuilder, DirBuilderExt, OpenOptions, OpenOptionsExt}; + use sha2::{Digest, Sha256}; + use std::os::unix::fs::{FileExt, MetadataExt}; + + /// Open `name` without following links or blocking on special files and + /// record its evidence. Refuses anything but a single-link regular file. + pub fn observe(dir: &Dir, name: &str) -> io::Result<(File, StageEvidence)> { + require_component(name)?; + let mut options = OpenOptions::new(); + options + .read(true) + .follow(FollowSymlinks::No) + .custom_flags(libc::O_NONBLOCK | libc::O_NOCTTY); + let file = dir.open_with(name, &options)?.into_std(); + let evidence = evidence(&file)?; + Ok((file, evidence)) + } + + /// Evidence of an already open handle; the bytes are read through it. + pub fn evidence(file: &File) -> io::Result { + let before = file.metadata()?; + if !before.is_file() { + return Err(invalid("Construction stage is not a regular file")); + } + if before.nlink() != 1 { + return Err(invalid("Construction stage has aliases")); + } + if before.len() > STAGE_LIMIT { + return Err(invalid(format!( + "Construction stage exceeds the {STAGE_LIMIT}-byte review limit" + ))); + } + let sha256 = digest(file)?; + let after = file.metadata()?; + if (after.len(), after.mtime(), after.mtime_nsec()) + != (before.len(), before.mtime(), before.mtime_nsec()) + { + return Err(invalid("Construction stage changed while it was read")); + } + Ok(StageEvidence { + device: after.dev(), + inode: after.ino(), + size: after.len(), + modified_ns: after + .mtime() + .saturating_mul(1_000_000_000) + .saturating_add(after.mtime_nsec()), + sha256, + }) + } + + fn digest(file: &File) -> io::Result { + let mut hasher = Sha256::new(); + let mut chunk = [0u8; 8192]; + let mut offset = 0u64; + loop { + let read = file.read_at(&mut chunk, offset)?; + if read == 0 { + return Ok(format!("{:x}", hasher.finalize())); + } + offset += read as u64; + if offset > STAGE_LIMIT { + return Err(invalid("Construction stage grew beyond the review limit")); + } + hasher.update(&chunk[..read]); + } + } + + /// Exclusive, non-blocking advisory lock on the stage. A live constructor + /// holds it from creation through publication. + pub fn try_lock(file: &File) -> io::Result { + match file.try_lock() { + Ok(()) => Ok(true), + Err(std::fs::TryLockError::WouldBlock) => Ok(false), + Err(std::fs::TryLockError::Error(error)) => Err(error), + } + } + + pub fn sync(dir: &Dir) -> io::Result<()> { + let fd = rustix::fs::openat( + dir, + ".", + rustix::fs::OFlags::RDONLY + | rustix::fs::OFlags::DIRECTORY + | rustix::fs::OFlags::CLOEXEC + | rustix::fs::OFlags::NOFOLLOW, + rustix::fs::Mode::empty(), + )?; + File::from(fd).sync_all() + } + + fn owner_uid(dir: &Dir) -> io::Result { + Ok(dir.try_clone()?.into_std_file().metadata()?.uid()) + } + + /// The private `name` directory in `parent`, created 0700 when `create`. + /// Returns `None` when it is missing and `create` is false. + fn private_dir(parent: &Dir, name: &str, create: bool) -> io::Result> { + if create { + let mut builder = DirBuilder::new(); + builder.mode(0o700); + match parent.create_dir_with(name, &builder) { + Ok(()) => sync(parent)?, + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {} + Err(error) => return Err(error), + } + } + let dir = match parent.open_dir_nofollow(name) { + Ok(dir) => dir, + Err(error) if error.kind() == io::ErrorKind::NotFound && !create => return Ok(None), + Err(error) => return Err(error), + }; + let metadata = dir.try_clone()?.into_std_file().metadata()?; + if metadata.uid() != owner_uid(parent)? || metadata.mode() & 0o077 != 0 { + return Err(invalid("Construction quarantine is not private")); + } + Ok(Some(dir)) + } + + fn slot(namespace: &Dir, key: &str, create: bool) -> io::Result> { + if !valid_key(key) { + return Err(invalid("Invalid construction quarantine key")); + } + let Some(quarantine) = private_dir(namespace, QUARANTINE, create)? else { + return Ok(None); + }; + Ok(private_dir(&quarantine, key, create)?.map(|slot| (quarantine, slot))) + } + + /// Move the held, reviewed stage into `discarded//` with no replacement. + /// `file` must be the handle the caller fenced; the name must still route to it. + pub fn quarantine( + source: &Dir, + name: &str, + namespace: &Dir, + key: &str, + file: &File, + expected: &StageEvidence, + ) -> io::Result<()> { + require_component(name)?; + if evidence(file)? != *expected { + return Err(invalid("Construction stage changed since review")); + } + let (_, routed) = observe(source, name)?; + if routed != *expected { + return Err(invalid( + "Construction stage name no longer routes to the reviewed file", + )); + } + let (quarantine, slot) = slot(namespace, key, true)?.expect("created quarantine slot"); + rustix::fs::renameat_with( + source, + name, + &slot, + name, + rustix::fs::RenameFlags::NOREPLACE, + )?; + sync(&slot)?; + sync(source)?; + sync(&quarantine)?; + let (_, moved) = observe(&slot, name)?; + if moved != *expected { + // Never keep or delete a file nobody reviewed: return it, no replacement. + let _ = rustix::fs::renameat_with( + &slot, + name, + source, + name, + rustix::fs::RenameFlags::NOREPLACE, + ); + let _ = sync(source); + return Err(invalid( + "A different file was moved; it was returned unchanged", + )); + } + Ok(()) + } + + /// Unlink the quarantined stage when it still has the reviewed identity. + pub fn unlink( + namespace: &Dir, + key: &str, + name: &str, + expected: &StageEvidence, + ) -> io::Result { + require_component(name)?; + let Some((quarantine, slot)) = slot(namespace, key, false)? else { + return Ok(Place::Gone); + }; + match observe(&slot, name) { + Ok((_, observed)) if observed != *expected => { + return Ok(Place::Changed( + "The quarantined file differs from the reviewed stage".into(), + )); + } + Ok(_) => { + slot.remove_file(name)?; + sync(&slot)?; + } + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + // Another entry or a concurrent retry may keep the slot; the stage is gone. + if quarantine.remove_dir(key).is_ok() { + sync(&quarantine)?; + } + Ok(Place::Gone) + } + + /// Where the reviewed stage is now, without changing anything. + pub fn locate( + source: Option<&Dir>, + name: &str, + namespace: &Dir, + key: &str, + expected: &StageEvidence, + ) -> io::Result { + require_component(name)?; + if let Some(source) = source { + match observe(source, name) { + Ok((_, observed)) if observed == *expected => return Ok(Place::Source), + Ok(_) => { + return Ok(Place::Changed( + "The stage name now holds a different file".into(), + )); + } + Err(error) if error.kind() == io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + } + } + let Some((_, slot)) = slot(namespace, key, false)? else { + return Ok(Place::Gone); + }; + match observe(&slot, name) { + Ok((_, observed)) if observed == *expected => Ok(Place::Quarantined), + Ok(_) => Ok(Place::Changed( + "The quarantined file differs from the reviewed stage".into(), + )), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(Place::Gone), + Err(error) => Err(error), + } + } + + /// Entries still in `discarded/` under `namespace`, bounded by `limit`. + pub fn pending(namespace: &Dir, limit: usize) -> io::Result> { + let Some(quarantine) = private_dir(namespace, QUARANTINE, false)? else { + return Ok(vec![]); + }; + let mut found = vec![]; + for entry in quarantine.entries()? { + let key = entry?.file_name().to_string_lossy().into_owned(); + let slot = quarantine.open_dir_nofollow(&key)?; + for entry in slot.entries()? { + let entry = entry?; + if found.len() >= limit { + return Err(invalid("Construction quarantine exceeds its listing limit")); + } + found.push(Pending { + key: key.clone(), + name: entry.file_name().to_string_lossy().into_owned(), + size: entry.metadata()?.len(), + }); + } + } + Ok(found) + } +} + +#[cfg(unix)] +pub use native::{evidence, locate, observe, pending, quarantine, sync, try_lock, unlink}; + +#[cfg(not(unix))] +mod unsupported { + use super::*; + fn unsupported() -> io::Result { + Err(io::Error::new( + io::ErrorKind::Unsupported, + "Construction evidence discard is unavailable on this platform", + )) + } + pub fn observe(_: &Dir, _: &str) -> io::Result<(File, StageEvidence)> { + unsupported() + } + pub fn evidence(_: &File) -> io::Result { + unsupported() + } + pub fn try_lock(_: &File) -> io::Result { + unsupported() + } + pub fn sync(_: &Dir) -> io::Result<()> { + unsupported() + } + pub fn quarantine( + _: &Dir, + _: &str, + _: &Dir, + _: &str, + _: &File, + _: &StageEvidence, + ) -> io::Result<()> { + unsupported() + } + pub fn unlink(_: &Dir, _: &str, _: &str, _: &StageEvidence) -> io::Result { + unsupported() + } + pub fn locate( + _: Option<&Dir>, + _: &str, + _: &Dir, + _: &str, + _: &StageEvidence, + ) -> io::Result { + unsupported() + } + pub fn pending(_: &Dir, _: usize) -> io::Result> { + unsupported() + } +} +#[cfg(not(unix))] +pub use unsupported::{evidence, locate, observe, pending, quarantine, sync, try_lock, unlink}; + +fn open_optional(path: &std::path::Path) -> io::Result> { + match Dir::open_ambient_dir(path, cap_std::ambient_authority()) { + Ok(dir) => Ok(Some(dir)), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error), + } +} + +/// [`locate`] by recorded paths. The source lies inside its namespace, so a +/// missing namespace means the stage is gone. +pub fn locate_at( + source: &std::path::Path, + namespace: &std::path::Path, + name: &str, + key: &str, + expected: &StageEvidence, +) -> io::Result { + let Some(namespace) = open_optional(namespace)? else { + return Ok(Place::Gone); + }; + locate( + open_optional(source)?.as_ref(), + name, + &namespace, + key, + expected, + ) +} + +/// [`unlink`] by the recorded namespace path. +pub fn unlink_at( + namespace: &std::path::Path, + key: &str, + name: &str, + expected: &StageEvidence, +) -> io::Result { + match open_optional(namespace)? { + Some(namespace) => unlink(&namespace, key, name, expected), + None => Ok(Place::Gone), + } +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use std::os::unix::fs::PermissionsExt; + + fn dirs(root: &std::path::Path) -> (Dir, Dir) { + std::fs::create_dir_all(root.join("ns/source")).unwrap(); + let namespace = + Dir::open_ambient_dir(root.join("ns"), cap_std::ambient_authority()).unwrap(); + let source = namespace.open_dir("source").unwrap(); + (namespace, source) + } + const KEY: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + + #[test] + fn reviewed_stage_moves_into_its_slot_and_is_unlinked_from_there_only() { + let temp = tempfile::tempdir().unwrap(); + let (namespace, source) = dirs(temp.path()); + std::fs::write(temp.path().join("ns/source/tmp_stage"), b"stage").unwrap(); + let (file, evidence) = observe(&source, "tmp_stage").unwrap(); + assert_eq!(evidence.size, 5); + assert!(try_lock(&file).unwrap()); + quarantine(&source, "tmp_stage", &namespace, KEY, &file, &evidence).unwrap(); + assert!(!temp.path().join("ns/source/tmp_stage").exists()); + let slot = temp.path().join("ns").join(QUARANTINE).join(KEY); + assert_eq!( + std::fs::metadata(&slot).unwrap().permissions().mode() & 0o777, + 0o700 + ); + assert_eq!( + locate(Some(&source), "tmp_stage", &namespace, KEY, &evidence).unwrap(), + Place::Quarantined + ); + assert_eq!(pending(&namespace, 10).unwrap().len(), 1); + assert_eq!( + unlink(&namespace, KEY, "tmp_stage", &evidence).unwrap(), + Place::Gone + ); + assert!(!slot.exists()); + assert_eq!( + locate(Some(&source), "tmp_stage", &namespace, KEY, &evidence).unwrap(), + Place::Gone + ); + assert_eq!( + unlink(&namespace, KEY, "tmp_stage", &evidence).unwrap(), + Place::Gone + ); + assert!(pending(&namespace, 10).unwrap().is_empty()); + } + + #[test] + fn links_special_files_aliases_and_oversized_stages_are_refused() { + let temp = tempfile::tempdir().unwrap(); + let (_, source) = dirs(temp.path()); + let base = temp.path().join("ns/source"); + std::fs::write(temp.path().join("outside"), b"outside").unwrap(); + std::os::unix::fs::symlink(temp.path().join("outside"), base.join("link")).unwrap(); + std::fs::create_dir(base.join("dir")).unwrap(); + std::fs::write(base.join("aliased"), b"a").unwrap(); + std::fs::hard_link(base.join("aliased"), base.join("alias")).unwrap(); + std::fs::write(base.join("large"), vec![0u8; STAGE_LIMIT as usize + 1]).unwrap(); + assert!( + std::process::Command::new("mkfifo") + .arg(base.join("fifo")) + .status() + .unwrap() + .success() + ); + for name in [ + "link", + "dir", + "aliased", + "large", + "fifo", + "../outside", + "..", + ] { + assert!(observe(&source, name).is_err(), "{name}"); + } + assert_eq!( + std::fs::read(temp.path().join("outside")).unwrap(), + b"outside" + ); + } + + #[test] + fn a_changed_stage_is_neither_moved_nor_deleted() { + let temp = tempfile::tempdir().unwrap(); + let (namespace, source) = dirs(temp.path()); + let path = temp.path().join("ns/source/tmp_stage"); + std::fs::write(&path, b"stage").unwrap(); + let (file, evidence) = observe(&source, "tmp_stage").unwrap(); + std::fs::write(&path, b"other").unwrap(); + assert!(quarantine(&source, "tmp_stage", &namespace, KEY, &file, &evidence).is_err()); + assert_eq!(std::fs::read(&path).unwrap(), b"other"); + assert!(matches!( + locate(Some(&source), "tmp_stage", &namespace, KEY, &evidence).unwrap(), + Place::Changed(_) + )); + // A replaced name (new inode) is refused as well. + std::fs::remove_file(&path).unwrap(); + std::fs::write(&path, b"stage").unwrap(); + assert!(quarantine(&source, "tmp_stage", &namespace, KEY, &file, &evidence).is_err()); + assert!(path.exists()); + } + + #[test] + fn a_foreign_quarantined_file_is_reported_and_kept() { + let temp = tempfile::tempdir().unwrap(); + let (namespace, source) = dirs(temp.path()); + std::fs::write(temp.path().join("ns/source/tmp_stage"), b"stage").unwrap(); + let (file, evidence) = observe(&source, "tmp_stage").unwrap(); + quarantine(&source, "tmp_stage", &namespace, KEY, &file, &evidence).unwrap(); + let moved = temp + .path() + .join("ns") + .join(QUARANTINE) + .join(KEY) + .join("tmp_stage"); + std::fs::remove_file(&moved).unwrap(); + std::fs::write(&moved, b"foreign").unwrap(); + assert!(matches!( + unlink(&namespace, KEY, "tmp_stage", &evidence).unwrap(), + Place::Changed(_) + )); + assert_eq!(std::fs::read(&moved).unwrap(), b"foreign"); + assert!(!valid_key("../escape") && !valid_component("a/b")); + } +} diff --git a/crates/cyber-core/src/lib.rs b/crates/cyber-core/src/lib.rs index 0ee4e284..24fca812 100644 --- a/crates/cyber-core/src/lib.rs +++ b/crates/cyber-core/src/lib.rs @@ -7,6 +7,7 @@ pub mod browser; pub mod budget; pub mod commands; pub mod config; +pub mod construction_discard; pub mod env; pub mod eval; pub mod features; diff --git a/crates/cyber-core/src/worktrees.rs b/crates/cyber-core/src/worktrees.rs index 894a1265..ded2712a 100644 --- a/crates/cyber-core/src/worktrees.rs +++ b/crates/cyber-core/src/worktrees.rs @@ -11,8 +11,9 @@ mod setup; #[cfg(any(target_os = "linux", target_os = "macos"))] pub use activity::CheckoutRetirementGuard; pub use activity::{ - CheckoutAcknowledgement, CheckoutActivity, CheckoutBinding, CheckoutLease, CheckoutOwner, - SnapshotClaim, SnapshotConstruction, SnapshotConstructionKind, + CheckoutAcknowledgement, CheckoutActivity, CheckoutBinding, CheckoutConstructionFence, + CheckoutConstructionReview, CheckoutLease, CheckoutOwner, SnapshotClaim, SnapshotConstruction, + SnapshotConstructionKind, }; pub use activity::{CheckoutRetirementFile, CheckoutRetirementPlan}; pub use changes::{ChangedFile, Changes}; diff --git a/crates/cyber-core/src/worktrees/activity.rs b/crates/cyber-core/src/worktrees/activity.rs index 0aa23a6c..2368d778 100644 --- a/crates/cyber-core/src/worktrees/activity.rs +++ b/crates/cyber-core/src/worktrees/activity.rs @@ -11,8 +11,11 @@ mod snapshot; #[cfg(any(target_os = "linux", target_os = "macos"))] pub use snapshot::CheckoutRetirementGuard; pub use snapshot::{CheckoutAcknowledgement, CheckoutBinding, CheckoutOwner, SnapshotClaim}; +pub use snapshot::{ + CheckoutConstructionFence, CheckoutConstructionReview, SnapshotConstruction, + SnapshotConstructionKind, +}; pub use snapshot::{CheckoutRetirementFile, CheckoutRetirementPlan}; -pub use snapshot::{SnapshotConstruction, SnapshotConstructionKind}; #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] struct UseRecord { diff --git a/crates/cyber-core/src/worktrees/activity/snapshot.rs b/crates/cyber-core/src/worktrees/activity/snapshot.rs index c1715a84..d7c4ccde 100644 --- a/crates/cyber-core/src/worktrees/activity/snapshot.rs +++ b/crates/cyber-core/src/worktrees/activity/snapshot.rs @@ -2,12 +2,14 @@ use super::{Managed, UseRecord, invalid}; pub(super) mod acknowledgement; pub(super) mod constructions; +mod discard; mod publication; mod retirement; pub use acknowledgement::CheckoutAcknowledgement; use cap_fs_ext::{DirExt, FollowSymlinks, OpenOptionsFollowExt}; use cap_std::fs::{Dir, OpenOptions}; pub use constructions::{SnapshotConstruction, SnapshotConstructionKind}; +pub use discard::{CheckoutConstructionFence, CheckoutConstructionReview}; pub(super) use publication::publish; #[cfg(any(target_os = "linux", target_os = "macos"))] pub use retirement::CheckoutRetirementGuard; diff --git a/crates/cyber-core/src/worktrees/activity/snapshot/acknowledgement.rs b/crates/cyber-core/src/worktrees/activity/snapshot/acknowledgement.rs index 8b90ef5a..a687c455 100644 --- a/crates/cyber-core/src/worktrees/activity/snapshot/acknowledgement.rs +++ b/crates/cyber-core/src/worktrees/activity/snapshot/acknowledgement.rs @@ -312,6 +312,24 @@ impl CheckoutAcknowledgement { } } +/// The construction stage the published acknowledgement of `owner` names, when +/// one is published. Read-only: nothing is locked, verified or adopted. +pub(super) fn published_stage( + directory: &cap_std::fs::Dir, + owner: &str, +) -> io::Result> { + let file = match open_file(directory, &format!("{owner}{SUFFIX}")) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error), + }; + let record: Record = serde_json::from_slice(&contents(&file, LIMIT)?).map_err(invalid)?; + if record.binding.owner_id != owner { + return Err(invalid("Checkout acknowledgement names another owner")); + } + Ok(Some(record.staging_name)) +} + pub(in crate::worktrees::activity) fn for_removal( managed: &Managed, record: &UseRecord, diff --git a/crates/cyber-core/src/worktrees/activity/snapshot/discard.rs b/crates/cyber-core/src/worktrees/activity/snapshot/discard.rs new file mode 100644 index 00000000..32e90a59 --- /dev/null +++ b/crates/cyber-core/src/worktrees/activity/snapshot/discard.rs @@ -0,0 +1,308 @@ +//! Owner-confirmed discard of one checkout claim or acknowledgement construction +//! stage. Review is read-only. The fence holds the stage's own constructor lock +//! exclusively (a live constructor keeps it from creation through publication) and +//! checks the activity's published records before the caller may quarantine it. +use super::super::super::{Managed, Repository}; +use super::super::{LockedRecord, invalid}; +use super::constructions::{SnapshotConstruction, SnapshotConstructionKind, classify}; +use crate::construction_discard::{self as native, StageEvidence}; +use cap_fs_ext::DirExt; +use cap_std::fs::Dir; +use std::io; +use std::path::{Path, PathBuf}; + +const ROOT: &str = "cyber-worktree-activity"; + +/// A fenced stage: its constructor lock is held until this value is dropped. +pub struct CheckoutConstructionFence { + root: Dir, + activity: Dir, + file: LockedRecord, + name: String, + evidence: StageEvidence, +} + +impl CheckoutConstructionFence { + /// Move the fenced stage into `discarded//` beside the activity directories. + pub fn quarantine(&self, key: &str) -> io::Result<()> { + native::quarantine( + &self.activity, + &self.name, + &self.root, + key, + &self.file, + &self.evidence, + ) + } +} + +fn managed_at(directory: &Path, worktree_id: &str) -> io::Result> { + Ok(Repository::managed_locations_at(directory)? + .into_iter() + .map(|(_, managed)| managed) + .find(|managed| managed.id == worktree_id)) +} + +/// The private activity namespace and this checkout's activity directory. +fn namespace(managed: &Managed) -> io::Result<(Dir, Dir, PathBuf)> { + super::super::safe_id(&managed.id, "wt")?; + if std::fs::symlink_metadata(&managed.common_dir)? + .file_type() + .is_symlink() + { + return Err(invalid("Checkout common directory is a symlink")); + } + let common = Dir::open_ambient_dir(&managed.common_dir, cap_std::ambient_authority())?; + let root = common.open_dir_nofollow(ROOT)?; + let activity = root.open_dir_nofollow(&managed.id)?; + Ok((root, activity, managed.common_dir.join(ROOT))) +} + +/// A reviewed checkout stage and where it lives. +pub struct CheckoutConstructionReview { + pub stage: SnapshotConstruction, + pub evidence: StageEvidence, + /// The activity directory that holds the stage. + pub source: PathBuf, + /// The namespace whose `discarded/` receives it. + pub namespace: PathBuf, +} + +impl Repository { + /// Read-only review of one claim or acknowledgement stage of the managed + /// checkout `worktree_id` enclosing `directory`. `None` when there is no such + /// stage; nothing is opened for writing, locked or adopted. + pub fn review_snapshot_construction( + directory: &Path, + worktree_id: &str, + name: &str, + ) -> io::Result> { + let Some((kind, owner_id)) = classify(name) else { + return Ok(None); + }; + let Some(managed) = managed_at(directory, worktree_id)? else { + return Ok(None); + }; + let (_, activity, namespace) = match namespace(&managed) { + Ok(found) => found, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error), + }; + let evidence = match native::observe(&activity, name) { + Ok((_, evidence)) => evidence, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error), + }; + Ok(Some(CheckoutConstructionReview { + stage: SnapshotConstruction { + worktree_id: managed.id.clone(), + owner_id, + kind, + name: name.into(), + }, + evidence, + source: namespace.join(&managed.id), + namespace, + })) + } + + /// Fence one reviewed stage for discard: the name must parse to `owner`, its + /// constructor lock must be free, the stage must still have the reviewed + /// evidence, and the activity's published records must allow it (no published + /// claim for a claim stage; an acknowledgement published from another stage + /// for an acknowledgement stage). + pub fn fence_snapshot_construction( + directory: &Path, + worktree_id: &str, + name: &str, + owner: &str, + expected: &StageEvidence, + ) -> io::Result { + let (kind, parsed) = + classify(name).ok_or_else(|| invalid("Not a checkout construction stage"))?; + if parsed.as_deref() != Some(owner) { + return Err(invalid( + "Construction stage name has no derivable owner; it stays fenced", + )); + } + let managed = managed_at(directory, worktree_id)? + .ok_or_else(|| invalid("Managed checkout of this Session is unavailable"))?; + fence_managed(&managed, kind, name, owner, expected) + } +} + +fn fence_managed( + managed: &Managed, + kind: SnapshotConstructionKind, + name: &str, + owner: &str, + expected: &StageEvidence, +) -> io::Result { + let (root, activity, _) = namespace(managed)?; + let (file, observed) = native::observe(&activity, name)?; + if !native::try_lock(&file)? { + return Err(io::Error::new( + io::ErrorKind::WouldBlock, + "Checkout constructor still holds this stage", + )); + } + let file = LockedRecord(file); + if observed != *expected || native::evidence(&file)? != *expected { + return Err(invalid("Construction stage changed since review")); + } + published_records_allow(&activity, kind, owner, name)?; + Ok(CheckoutConstructionFence { + root, + activity, + file, + name: name.into(), + evidence: expected.clone(), + }) +} + +fn published_records_allow( + activity: &Dir, + kind: SnapshotConstructionKind, + owner: &str, + name: &str, +) -> io::Result<()> { + match kind { + SnapshotConstructionKind::CheckoutClaim => { + match activity.symlink_metadata(format!("{owner}.lock")) { + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(error), + Ok(_) => Err(invalid(format!( + "A checkout claim is published for {owner}; ordinary recovery applies" + ))), + } + } + SnapshotConstructionKind::CheckoutAcknowledgement => { + match super::acknowledgement::published_stage(activity, owner)? { + None => Err(invalid(format!( + "The claim of {owner} is not acknowledged yet; reconcile its receipt \ + (recovery-preparation-request --acknowledge) before discarding this stage" + ))), + Some(stage) if stage == name => Err(invalid( + "The published acknowledgement names this stage; ordinary recovery applies", + )), + Some(_) => Ok(()), + } + } + } +} + +#[cfg(all(test, any(target_os = "macos", target_os = "linux")))] +mod tests { + use super::*; + + fn fixture(root: &Path) -> (Managed, PathBuf) { + let common = root.join("common"); + let activity = common.join(ROOT).join("wt_fixture"); + std::fs::create_dir_all(&activity).unwrap(); + let managed = Managed { + id: "wt_fixture".into(), + name: "fixture".into(), + path: root.join("work"), + branch: "cyber/fixture".into(), + base: "main".into(), + common_dir: common, + ready: true, + included: vec![], + }; + (managed, activity) + } + const KEY: &str = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"; + fn claim() -> String { + format!("preparing_10_op_fixture_{}", ulid::Ulid::new()) + } + + fn fence(managed: &Managed, name: &str, owner: &str) -> io::Result { + let (_, activity, _) = namespace(managed)?; + let (_, evidence) = native::observe(&activity, name)?; + let (kind, _) = classify(name).unwrap(); + fence_managed(managed, kind, name, owner, &evidence) + } + + #[test] + fn unpublished_claim_stage_is_quarantined_and_unlinked() { + let temp = tempfile::tempdir().unwrap(); + let (managed, activity) = fixture(temp.path()); + let name = claim(); + std::fs::write(activity.join(&name), b"{}").unwrap(); + let fenced = fence(&managed, &name, "op_fixture").unwrap(); + fenced.quarantine(KEY).unwrap(); + drop(fenced); + assert!(!activity.join(&name).exists()); + let (root, _, _) = namespace(&managed).unwrap(); + let evidence_path = managed + .common_dir + .join(ROOT) + .join("discarded") + .join(KEY) + .join(&name); + assert!(evidence_path.exists()); + let (_, evidence) = native::observe( + &root.open_dir("discarded").unwrap().open_dir(KEY).unwrap(), + &name, + ) + .unwrap(); + assert_eq!( + native::unlink(&root, KEY, &name, &evidence).unwrap(), + native::Place::Gone + ); + assert!(!evidence_path.exists()); + } + + #[test] + fn a_held_stage_lock_or_a_published_claim_refuses() { + let temp = tempfile::tempdir().unwrap(); + let (managed, activity) = fixture(temp.path()); + let name = claim(); + std::fs::write(activity.join(&name), b"{}").unwrap(); + let held = std::fs::File::open(activity.join(&name)).unwrap(); + held.lock().unwrap(); + let error = fence(&managed, &name, "op_fixture").err().unwrap(); + assert_eq!(error.kind(), io::ErrorKind::WouldBlock); + held.unlock().unwrap(); + std::fs::write(activity.join("op_fixture.lock"), b"{}").unwrap(); + let error = fence(&managed, &name, "op_fixture").err().unwrap(); + assert!(error.to_string().contains("ordinary recovery"), "{error}"); + assert!(activity.join(&name).exists()); + } + + #[test] + fn acknowledgement_stage_waits_for_reconciliation() { + let temp = tempfile::tempdir().unwrap(); + let (managed, activity) = fixture(temp.path()); + let name = format!("ack_preparing_10_op_fixture_{}", ulid::Ulid::new()); + std::fs::write(activity.join(&name), b"{}").unwrap(); + let error = fence(&managed, &name, "op_fixture").err().unwrap(); + assert!( + error.to_string().contains("not acknowledged yet"), + "{error}" + ); + assert!(activity.join(&name).exists()); + } + + #[test] + fn malformed_or_foreign_stage_names_have_no_owner() { + assert!(classify("preparing_x_op_fixture").is_some_and(|(_, owner)| owner.is_none())); + let temp = tempfile::tempdir().unwrap(); + let error = Repository::fence_snapshot_construction( + temp.path(), + "wt_fixture", + "preparing_bad", + "op_fixture", + &StageEvidence { + device: 0, + inode: 0, + size: 0, + modified_ns: 0, + sha256: String::new(), + }, + ) + .err() + .unwrap(); + assert!(error.to_string().contains("no derivable owner"), "{error}"); + } +} diff --git a/crates/cyber-snapshot/src/copy/discard.rs b/crates/cyber-snapshot/src/copy/discard.rs new file mode 100644 index 00000000..49ab2a77 --- /dev/null +++ b/crates/cyber-snapshot/src/copy/discard.rs @@ -0,0 +1,457 @@ +//! File-copy cancellation-record construction stages: a `tmp_*` file beside a +//! journal's `preparation.json` that `storage::atomic` flushed but never renamed. +//! A stage counts only when its bytes are the cancellation receipt of the exact +//! origin that owns the journal; any other journal file is not construction +//! evidence and stays untouched. The namespace is found from the origin's +//! recorded Location and identities, so it works after the Location was removed. +use super::preparation::{FILE, LIMIT}; +use super::storage::{self, Result}; +use cap_fs_ext::DirExt; +use cap_std::fs::Dir; +use cyber_core::construction_discard::{self as native, StageEvidence}; +use cyber_server::runtime::{ + ConstructionFence, ConstructionFenceError, ConstructionStageKind, NativeConstructionStage, + SnapshotOrigin, SnapshotPreparationReceipt, +}; +use std::fs::File; +use std::path::{Path, PathBuf}; + +const STAGE_PREFIX: &str = "tmp_"; + +struct Namespace { + dir: Dir, + journal: Dir, + path: PathBuf, +} + +fn child(parent: &Dir, name: &str, private: bool) -> Result> { + match parent.symlink_metadata(name) { + Ok(_) => storage::existing_child(parent, name, private).map(Some), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(storage::fail(error)), + } +} + +/// The origin's namespace and journal, with their recorded identities. +fn namespace(data: &Path, origin: &SnapshotOrigin) -> Result> { + let binding = &origin.binding; + if !binding.journal_id.starts_with("restore_") + || !native::valid_component(&binding.journal_id) + || !origin.activity_id.starts_with("op_") + || !native::valid_component(&origin.activity_id) + { + return Err("Invalid snapshot journal binding".into()); + } + if !data.exists() { + return Ok(None); + } + let data = data.canonicalize().map_err(storage::fail)?; + let root = Dir::open_ambient_dir(&data, cap_std::ambient_authority()).map_err(storage::fail)?; + let Some(snapshot) = child(&root, "snapshot", false)? else { + return Ok(None); + }; + let Some(global) = child(&snapshot, "global", true)? else { + return Ok(None); + }; + let key = storage::digest( + format!("{}\0{}", binding.directory.display(), binding.root_identity).as_bytes(), + ); + let Some(dir) = child(&global, &key, true)? else { + return Ok(None); + }; + let Some(journals) = child(&dir, "journals", true)? else { + return Ok(None); + }; + if storage::dir_identity(&journals)? != binding.namespace_identity { + return Err("Snapshot journal namespace changed".into()); + } + let journal = match journals.open_dir_nofollow(&binding.journal_id) { + Ok(journal) => journal, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(storage::fail(error)), + }; + if storage::dir_identity(&journal)? != binding.journal_identity { + return Err("Snapshot journal identity changed".into()); + } + Ok(Some(Namespace { + dir, + journal, + path: data.join("snapshot").join("global").join(key), + })) +} + +/// Whether `name` is a complete cancellation receipt stage of exactly `origin`. +fn is_stage(journal: &Dir, name: &str, origin: &SnapshotOrigin) -> bool { + if !name.starts_with(STAGE_PREFIX) || !native::valid_component(name) { + return false; + } + let Ok(bytes) = storage::read(journal, name, LIMIT) else { + return false; + }; + serde_json::from_slice::(&bytes).is_ok_and(|receipt| { + receipt.activity_id == origin.activity_id && receipt.origin.as_ref() == Some(origin) + }) +} + +pub(crate) fn stages(data: &Path, origin: &SnapshotOrigin) -> Result> { + let Some(namespace) = namespace(data, origin)? else { + return Ok(vec![]); + }; + let mut found: Vec = storage::names(&namespace.journal, super::ENTRY_LIMIT * 3)? + .into_iter() + .filter(|name| is_stage(&namespace.journal, name, origin)) + .collect(); + found.sort(); + Ok(found) +} + +pub(crate) fn stage( + data: &Path, + origin: &SnapshotOrigin, + name: &str, +) -> Result> { + let Some(namespace) = namespace(data, origin)? else { + return Ok(None); + }; + if !is_stage(&namespace.journal, name, origin) { + return Ok(None); + } + let (_, evidence) = native::observe(&namespace.journal, name).map_err(storage::fail)?; + Ok(Some(native_stage(&namespace, origin, name, evidence))) +} + +fn native_stage( + namespace: &Namespace, + origin: &SnapshotOrigin, + name: &str, + evidence: StageEvidence, +) -> NativeConstructionStage { + NativeConstructionStage { + name: name.into(), + kind: ConstructionStageKind::CancellationRecord, + activity_id: Some(origin.activity_id.clone()), + worktree_id: origin.worktree_id.clone(), + journal_id: Some(origin.binding.journal_id.clone()), + evidence, + source: namespace + .path + .join("journals") + .join(&origin.binding.journal_id), + namespace: namespace.path.clone(), + } +} + +/// Held namespace lock, owner lifetime lock and stage handle. +pub(crate) struct Fence { + namespace: Dir, + journal: Dir, + _lock: File, + _worker: Option, + file: File, + name: String, + evidence: StageEvidence, +} + +impl ConstructionFence for Fence { + fn quarantine(&mut self, key: &str) -> std::result::Result<(), String> { + native::quarantine( + &self.journal, + &self.name, + &self.namespace, + key, + &self.file, + &self.evidence, + ) + .map_err(storage::fail) + } +} + +fn refused(error: impl std::fmt::Display) -> ConstructionFenceError { + ConstructionFenceError::Refused(error.to_string()) +} + +/// The owner's lifetime lock, held exclusively; a held lock is a live worker. +fn lock_worker( + dir: &Dir, + activity: &str, +) -> std::result::Result, ConstructionFenceError> { + let Some(workers) = child(dir, "workers", true).map_err(refused)? else { + return Ok(None); + }; + let file = match storage::open(&workers, Path::new(activity)) { + Ok(file) => file, + Err(_) if workers.symlink_metadata(activity).is_err() => return Ok(None), + Err(error) => return Err(refused(error)), + }; + match native::try_lock(&file) { + Ok(true) => Ok(Some(file)), + Ok(false) => Err(ConstructionFenceError::Busy( + "Snapshot worker is still active".into(), + )), + Err(error) => Err(refused(error)), + } +} + +pub(crate) fn fence( + data: &Path, + origin: &SnapshotOrigin, + stage: &NativeConstructionStage, +) -> std::result::Result { + let namespace = namespace(data, origin) + .map_err(refused)? + .ok_or_else(|| refused("The journal of this cancellation record is gone"))?; + let expected = native_stage(&namespace, origin, &stage.name, stage.evidence.clone()); + if expected != *stage { + return Err(refused("Cancellation record stage moved since review")); + } + let lock = storage::lock(&namespace.dir, false).map_err(|error| { + if error == "Snapshot storage is busy" { + ConstructionFenceError::Busy(error) + } else { + refused(error) + } + })?; + if let Some(identity) = &origin.binding.lock_identity + && storage::identity(&lock).map_err(refused)? != *identity + { + return Err(refused("Snapshot namespace lock was replaced")); + } + let worker = lock_worker(&namespace.dir, &origin.activity_id)?; + if !is_stage(&namespace.journal, &stage.name, origin) { + return Err(refused( + "Not a cancellation-record stage of this activity; it stays untouched", + )); + } + if namespace.journal.symlink_metadata(FILE).is_err() { + return Err(refused( + "The cancellation of this activity is not reconciled yet; run recovery-preparation-request --acknowledge before discarding this stage", + )); + } + let (file, observed) = native::observe(&namespace.journal, &stage.name).map_err(refused)?; + if observed != stage.evidence { + return Err(refused("Construction stage changed since review")); + } + Ok(Fence { + namespace: namespace.dir, + journal: namespace.journal, + _lock: lock, + _worker: worker, + file, + name: stage.name.clone(), + evidence: stage.evidence.clone(), + }) +} + +/// Bytes of quarantined stages that still await their unlink; they count toward +/// the snapshot cap until removed. +pub(super) fn pending_bytes(namespace: &Dir) -> Result { + native::pending(namespace, super::ENTRY_LIMIT) + .map_err(storage::fail)? + .iter() + .try_fold(0u64, |total, entry| total.checked_add(entry.size)) + .ok_or_else(|| "Snapshot storage overflow".into()) +} + +#[cfg(test)] +mod tests { + use super::super::{Options, Store, lifetime::Lifetime}; + use super::*; + use cyber_server::runtime::{SnapshotBinding, SnapshotLifetime, SnapshotLifetimeRequest}; + + const KEY: &str = "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"; + + fn options() -> Options { + Options { + max_file: 65536, + max_total: 4 * 1024 * 1024, + ignore: vec![], + private_roots: vec![], + } + } + + /// A cancelled preparation whose cancellation record was cut after its stage was + /// flushed and before it was renamed: the exact state `storage::atomic` leaves. + fn setup() -> ( + tempfile::TempDir, + Store, + Lifetime, + SnapshotPreparationReceipt, + String, + ) { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().join("work"); + std::fs::create_dir(&root).unwrap(); + let store = + Store::open(&temp.path().join("data"), root.to_str().unwrap(), options()).unwrap(); + let lifetime = store + .reserve_lifetime(SnapshotLifetimeRequest { + activity_id: "op_discard".into(), + session_id: "ses_fixture".into(), + session_created_id: "evt_fixture".into(), + directory: store.root.clone(), + worktree_id: None, + }) + .unwrap(); + let dir = storage::private_child(&store.journals, "restore_discard").unwrap(); + let origin = SnapshotOrigin { + version: 1, + activity_id: "op_discard".into(), + session_id: "ses_fixture".into(), + session_created_id: "evt_fixture".into(), + worktree_id: None, + binding: SnapshotBinding { + directory: store.root.clone(), + root_identity: store.root_id.clone(), + namespace_identity: storage::dir_identity(&store.journals).unwrap(), + journal_id: "restore_discard".into(), + journal_identity: storage::dir_identity(&dir).unwrap(), + lock_identity: Some(store.lock_identity().unwrap()), + }, + }; + let receipt = SnapshotPreparationReceipt { + activity_id: origin.activity_id.clone(), + request_id: "cancel-discard".into(), + confirmation: "a".repeat(64), + lifetime: lifetime.binding().clone(), + native_sequence: 1, + session_sequence: 8, + origin: Some(origin), + source_admitted: Some(false), + checkout_resources_digest: None, + }; + let stage = format!("tmp_{}", ulid::Ulid::new()); + storage::create(&dir, &stage, &serde_json::to_vec(&receipt).unwrap()).unwrap(); + (temp, store, lifetime, receipt, stage) + } + + fn data(temp: &tempfile::TempDir) -> PathBuf { + temp.path().join("data") + } + + fn busy(result: std::result::Result) -> bool { + matches!(result, Err(ConstructionFenceError::Busy(_))) + } + + fn refused(result: std::result::Result, text: &str) { + match result { + Err(ConstructionFenceError::Refused(message)) => { + assert!(message.contains(text), "{message}") + } + Err(other) => panic!("{other:?}"), + Ok(_) => panic!("fence admitted"), + } + } + + #[test] + fn only_an_exact_cancellation_receipt_stage_is_construction_evidence() { + let (temp, store, _lifetime, receipt, stage) = setup(); + let origin = receipt.origin.clone().unwrap(); + let journal = store.journals.open_dir_nofollow("restore_discard").unwrap(); + // Another journal stage and a receipt of a foreign origin are not evidence. + storage::create(&journal, "tmp_other", b"intent bytes").unwrap(); + let mut foreign = receipt.clone(); + foreign.origin.as_mut().unwrap().activity_id = "op_foreign".into(); + storage::create( + &journal, + "tmp_foreign", + &serde_json::to_vec(&foreign).unwrap(), + ) + .unwrap(); + assert_eq!(stages(&data(&temp), &origin).unwrap(), vec![stage.clone()]); + assert!(stage_of(&temp, &origin, "tmp_other").is_none()); + let reviewed = stage_of(&temp, &origin, &stage).unwrap(); + assert_eq!(reviewed.kind, ConstructionStageKind::CancellationRecord); + assert_eq!(reviewed.activity_id.as_deref(), Some("op_discard")); + assert_eq!(reviewed.journal_id.as_deref(), Some("restore_discard")); + assert!(reviewed.source.ends_with("journals/restore_discard")); + } + + fn stage_of( + temp: &tempfile::TempDir, + origin: &SnapshotOrigin, + name: &str, + ) -> Option { + stage(&data(temp), origin, name).unwrap() + } + + #[test] + fn unreconciled_live_or_busy_owners_refuse_and_keep_the_stage() { + let (temp, store, lifetime, receipt, stage) = setup(); + let origin = receipt.origin.clone().unwrap(); + let reviewed = stage_of(&temp, &origin, &stage).unwrap(); + // The live worker's lifetime lock and the held namespace lock are live holders. + assert!(busy(fence(&data(&temp), &origin, &reviewed))); + drop(store); + assert!(busy(fence(&data(&temp), &origin, &reviewed))); + drop(lifetime); + // The published cancellation record is still missing: reconcile it first. + refused(fence(&data(&temp), &origin, &reviewed), "not reconciled"); + let journal = data(&temp).join("snapshot/global"); + assert!(walk(&journal).iter().any(|path| path.ends_with(&stage))); + } + + fn walk(root: &Path) -> Vec { + let mut found = vec![]; + for entry in std::fs::read_dir(root).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + found.extend(walk(&path)); + } else { + found.push(path); + } + } + found + } + + #[test] + fn reconciled_stage_is_quarantined_counted_and_unlinked_even_after_location_removal() { + let (temp, store, lifetime, receipt, stage) = setup(); + let origin = receipt.origin.clone().unwrap(); + store.acknowledge_preparation(&receipt).unwrap(); + let before = store.usage().unwrap(); + drop((store, lifetime)); + // The Location directory is removed: the stage is still found by its origin. + std::fs::remove_dir_all(temp.path().join("work")).unwrap(); + let reviewed = stage_of(&temp, &origin, &stage).unwrap(); + let mut changed = reviewed.clone(); + changed.evidence.size += 1; + refused( + fence(&data(&temp), &origin, &changed), + "changed since review", + ); + let mut fenced = fence(&data(&temp), &origin, &reviewed).unwrap(); + fenced.quarantine(KEY).unwrap(); + drop(fenced); + assert!(stages(&data(&temp), &origin).unwrap().is_empty()); + let namespace = + Dir::open_ambient_dir(&reviewed.namespace, cap_std::ambient_authority()).unwrap(); + assert_eq!(pending_bytes(&namespace).unwrap(), reviewed.evidence.size); + assert_eq!( + native::unlink(&namespace, KEY, &stage, &reviewed.evidence).unwrap(), + native::Place::Gone + ); + assert_eq!(pending_bytes(&namespace).unwrap(), 0); + assert!(before > 0); + } + + #[test] + fn quarantined_bytes_count_toward_the_snapshot_cap() { + let (temp, store, lifetime, receipt, stage) = setup(); + let origin = receipt.origin.clone().unwrap(); + store.acknowledge_preparation(&receipt).unwrap(); + drop((store, lifetime)); + let root = temp.path().join("work"); + let fresh = || Store::open(&data(&temp), root.to_str().unwrap(), options()).unwrap(); + let before = fresh().usage().unwrap(); + let reviewed = stage_of(&temp, &origin, &stage).unwrap(); + let mut fenced = fence(&data(&temp), &origin, &reviewed).unwrap(); + fenced.quarantine(KEY).unwrap(); + drop(fenced); + // The stage moved from the journal into the quarantine: still counted. + assert_eq!(fresh().usage().unwrap(), before); + let namespace = + Dir::open_ambient_dir(&reviewed.namespace, cap_std::ambient_authority()).unwrap(); + native::unlink(&namespace, KEY, &stage, &reviewed.evidence).unwrap(); + assert_eq!(fresh().usage().unwrap(), before - reviewed.evidence.size); + } +} diff --git a/crates/cyber-snapshot/src/copy/mod.rs b/crates/cyber-snapshot/src/copy/mod.rs index 6cf668dd..7695179c 100644 --- a/crates/cyber-snapshot/src/copy/mod.rs +++ b/crates/cyber-snapshot/src/copy/mod.rs @@ -4,6 +4,7 @@ pub(crate) fn object_digest(bytes: &[u8]) -> String { storage::digest(bytes) } mod collection; +pub(crate) mod discard; pub(crate) mod generated_rules; mod git; pub(crate) mod git_capture; @@ -355,6 +356,12 @@ impl Store { for name in storage::names(&self.namespace, ENTRY_LIMIT)? { let metadata = self.namespace.symlink_metadata(&name).map_err(fail)?; if metadata.is_dir() { + if name == cyber_core::construction_discard::QUARANTINE { + size = size + .checked_add(discard::pending_bytes(&self.namespace)?) + .ok_or("Snapshot storage overflow")?; + continue; + } if !matches!( name.as_str(), "files" | "manifests" | "journals" | "workers" diff --git a/crates/cyber-snapshot/src/lib.rs b/crates/cyber-snapshot/src/lib.rs index c799af24..fd6e800b 100644 --- a/crates/cyber-snapshot/src/lib.rs +++ b/crates/cyber-snapshot/src/lib.rs @@ -606,6 +606,56 @@ impl GitSnapshots { } impl Snapshots for GitSnapshots { + #[cfg(any(target_os = "macos", target_os = "linux"))] + fn cancellation_stages( + &self, + origin: cyber_server::runtime::SnapshotOrigin, + ) -> BoxFuture<'_, Result, String>> { + let data = self.data_dir.clone(); + Box::pin(async move { + tokio::task::spawn_blocking(move || copy::discard::stages(&data, &origin)) + .await + .map_err(|error| error.to_string())? + }) + } + #[cfg(any(target_os = "macos", target_os = "linux"))] + fn cancellation_stage( + &self, + origin: cyber_server::runtime::SnapshotOrigin, + name: String, + ) -> BoxFuture<'_, Result, String>> { + let data = self.data_dir.clone(); + Box::pin(async move { + tokio::task::spawn_blocking(move || copy::discard::stage(&data, &origin, &name)) + .await + .map_err(|error| error.to_string())? + }) + } + #[cfg(any(target_os = "macos", target_os = "linux"))] + fn fence_cancellation_stage( + &self, + origin: cyber_server::runtime::SnapshotOrigin, + stage: cyber_server::runtime::NativeConstructionStage, + ) -> BoxFuture< + '_, + Result< + Box, + cyber_server::runtime::ConstructionFenceError, + >, + > { + let data = self.data_dir.clone(); + Box::pin(async move { + tokio::task::spawn_blocking(move || { + copy::discard::fence(&data, &origin, &stage).map(|fence| { + Box::new(fence) as Box + }) + }) + .await + .map_err(|error| { + cyber_server::runtime::ConstructionFenceError::Refused(error.to_string()) + })? + }) + } fn lock_worker( &self, binding: cyber_server::runtime::SnapshotLifetimeBinding, From c0f27df544a373495a0651b3204af62fa2bc0fc5 Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 12:00:12 -0400 Subject: [PATCH 2/8] Expose owner-only construction discard in the runtime and HTTP API Review is read-only and fingerprints the stage and Session revision; confirm re-fences the Session and owner activity, records a durable session.snapshot.construction_discarded.1 intent, quarantines and unlinks the stage and completes the receipt. A repeated request ID resumes the frozen plan, lookup never acts and maintenance retries pending unlinks hourly. Review and confirm refuse bearer, peer, browser and MCP callers with 403. --- crates/cyber-app/src/host.rs | 19 + crates/cyber-app/src/lib.rs | 4 + crates/cyber-server/src/http/openapi.rs | 12 + crates/cyber-server/src/http/sessions.rs | 91 +++ .../src/runtime/construction_discard.rs | 577 ++++++++++++++++++ .../runtime/construction_discard/confirm.rs | 392 ++++++++++++ crates/cyber-server/src/runtime/events.rs | 7 + crates/cyber-server/src/runtime/host.rs | 53 ++ crates/cyber-server/src/runtime/mod.rs | 7 + crates/cyber-server/tests/http.rs | 51 ++ crates/cyber-tools/src/host.rs | 88 +++ sdk/openapi.json | 563 +++++++++++++++++ sdk/typescript/src/generated/operations.ts | 84 +++ sdk/typescript/src/generated/types.ts | 96 +++ 14 files changed, 2044 insertions(+) create mode 100644 crates/cyber-server/src/runtime/construction_discard.rs create mode 100644 crates/cyber-server/src/runtime/construction_discard/confirm.rs diff --git a/crates/cyber-app/src/host.rs b/crates/cyber-app/src/host.rs index 5fbdd91d..f937b247 100644 --- a/crates/cyber-app/src/host.rs +++ b/crates/cyber-app/src/host.rs @@ -323,6 +323,25 @@ impl ToolHost for AppHost { self.builtin.snapshot_checkout_constructions(info) } + fn snapshot_construction_stage( + &self, + info: &cyber_server::runtime::SessionInfo, + name: &str, + ) -> Result, String> { + self.builtin.snapshot_construction_stage(info, name) + } + + fn fence_snapshot_construction( + &self, + info: &cyber_server::runtime::SessionInfo, + stage: &cyber_server::runtime::NativeConstructionStage, + ) -> Result< + Box, + cyber_server::runtime::ConstructionFenceError, + > { + self.builtin.fence_snapshot_construction(info, stage) + } + fn reacquire_snapshot_location( &self, info: &cyber_server::runtime::SessionInfo, diff --git a/crates/cyber-app/src/lib.rs b/crates/cyber-app/src/lib.rs index f1d20bfe..1a89ded0 100644 --- a/crates/cyber-app/src/lib.rs +++ b/crates/cyber-app/src/lib.rs @@ -379,6 +379,10 @@ impl App { .map_err(|error| error.to_string())?; } host.attach(runtime.clone()); + if opts.snapshots { + // Owner-confirmed construction discards whose unlink failed are retried forever. + cyber_server::runtime::construction_discard::spawn_retry(runtime.clone()); + } // One fair scheduler of the slots of every Workflow agent of this server // (`workflows.max_concurrent`, reduced to the core count), fixed at startup like the // listener settings. diff --git a/crates/cyber-server/src/http/openapi.rs b/crates/cyber-server/src/http/openapi.rs index 2ba57971..8e276462 100644 --- a/crates/cyber-server/src/http/openapi.rs +++ b/crates/cyber-server/src/http/openapi.rs @@ -810,6 +810,18 @@ pub fn operations(g: &mut SchemaGenerator) -> Vec { .ok::>(g), op("post", "/sessions/{sessionID}/rewind/preparations/{activityID}/requests/{requestID}/acknowledge", "v1.session.snapshotPreparationAcknowledge", "Reconcile native metadata acknowledgement of an exact committed pre-effect cancellation without source changes") .ok::>(g), + op("get", "/sessions/{sessionID}/rewind/constructions", "v1.session.constructionInventory", "List unpublished construction stages and discards that still owe an unlink (`discard pending`); listing grants no discard authority") + .ok::>(g), + op("post", "/sessions/{sessionID}/rewind/constructions/discard/review", "v1.session.constructionDiscardReview", "Owner only: review one construction stage read-only and return its confirmation fingerprint") + .body::(g) + .ok::>(g) + .error::(g, 403, "ForbiddenError: delegated, browser, peer or model callers"), + op("post", "/sessions/{sessionID}/rewind/constructions/discard/confirm", "v1.session.constructionDiscardConfirm", "Owner only: discard one fingerprint-confirmed construction stage after fencing its activity; a repeated request ID resumes or returns its receipt") + .body::(g) + .ok::>(g) + .error::(g, 403, "ForbiddenError: delegated, browser, peer or model callers"), + op("get", "/sessions/{sessionID}/rewind/constructions/discard/requests/{requestID}", "v1.session.constructionDiscardLookup", "Look up a construction discard receipt without acting") + .ok::>(g), op("post", "/sessions/{sessionID}/rewind/restores/{activityID}/acknowledge", "v1.session.snapshotRestoreAcknowledge", "Acknowledge the immutable ordinary restore intent after its paired Session commit without replaying source files") .ok::>(g), op("post", "/sessions/{sessionID}/rewind/preview", "v1.session.rewindPreview", "Review a rewind without changing files or the active conversation") diff --git a/crates/cyber-server/src/http/sessions.rs b/crates/cyber-server/src/http/sessions.rs index b8e72f6f..f40296bf 100644 --- a/crates/cyber-server/src/http/sessions.rs +++ b/crates/cyber-server/src/http/sessions.rs @@ -415,6 +415,22 @@ pub fn routes() -> Router { &format!("{s}/rewind/preparations/{{activity_id}}/requests/{{request_id}}/acknowledge"), post(snapshot_preparation_acknowledge), ) + .route( + &format!("{s}/rewind/constructions"), + get(construction_inventory), + ) + .route( + &format!("{s}/rewind/constructions/discard/review"), + post(construction_discard_review), + ) + .route( + &format!("{s}/rewind/constructions/discard/confirm"), + post(construction_discard_confirm), + ) + .route( + &format!("{s}/rewind/constructions/discard/requests/{{request_id}}"), + get(construction_discard_lookup), + ) .route(&format!("{s}/rewind/confirm"), post(rewind_confirm)) .route(&format!("{s}/revert/stage"), post(stage)) .route(&format!("{s}/revert/clear"), post(clear)) @@ -1482,6 +1498,81 @@ async fn snapshot_preparation_acknowledge( .await?, })) } +/// Construction discard is the local owner's alone. The main listener already +/// requires the owner credential; requests that present another identity (a +/// peer or relay bearer, a peer attachment, a browser, an MCP client label) are +/// refused before any work. Model tools never reach this route. +fn owner_only(headers: &axum::http::HeaderMap) -> Result<()> { + let bearer = headers + .get(axum::http::header::AUTHORIZATION) + .is_some_and(|value| !value.as_bytes().starts_with(b"Basic ")); + let browser = + headers.contains_key(axum::http::header::ORIGIN) || headers.contains_key("sec-fetch-mode"); + let delegated = headers.contains_key("x-cyber-attach") + || headers + .get("x-cyber-client") + .is_some_and(|value| value.as_bytes().starts_with(b"mcp:")); + if bearer || browser || delegated { + return Err(ApiError::forbidden( + "Construction evidence discard is reserved for the authenticated local owner", + ) + .with_reason("owner_only")); + } + Ok(()) +} +async fn construction_inventory( + State(state): State, + Path(id): Path, +) -> Result>> { + Ok(Json(Data { + data: state.runtime.construction_inventory(&id).await?, + })) +} +async fn construction_discard_review( + State(state): State, + Path(id): Path, + headers: axum::http::HeaderMap, + Json(selection): Json, +) -> Result>> { + owner_only(&headers)?; + Ok(Json(Data { + data: state + .runtime + .construction_discard_review(&id, &selection) + .await?, + })) +} +async fn construction_discard_confirm( + State(state): State, + Path(id): Path, + headers: axum::http::HeaderMap, + Json(confirmation): Json, +) -> Result>> { + owner_only(&headers)?; + Ok(Json(Data { + data: state + .runtime + .construction_discard_confirm(&id, &confirmation) + .await?, + })) +} +async fn construction_discard_lookup( + State(state): State, + Path((id, request)): Path<(String, String)>, +) -> Result>> { + Ok(Json(Data { + data: state + .runtime + .construction_discard_lookup(&id, &request) + .await? + .ok_or_else(|| { + ApiError::not_found( + "ConstructionDiscardNotFoundError", + "No construction discard request with this ID", + ) + })?, + })) +} async fn rewind_preview( State(state): State, Path(id): Path, diff --git a/crates/cyber-server/src/runtime/construction_discard.rs b/crates/cyber-server/src/runtime/construction_discard.rs new file mode 100644 index 00000000..8176f134 --- /dev/null +++ b/crates/cyber-server/src/runtime/construction_discard.rs @@ -0,0 +1,577 @@ +//! Owner-only discard of construction evidence (`snapshots-checkpoints` → Owner-only +//! discard of construction evidence). A construction stage is a private file a +//! constructor flushed but never published: a checkout claim stage +//! (`preparing_*`), a checkout acknowledgement stage (`ack_preparing_*`) or a +//! file-copy cancellation-record stage (`tmp_*` beside `preparation.json`). +//! +//! Review is read-only and returns a fingerprint over the stage's native identity, +//! digest, fences, Location state and the Session revision. Confirmation re-fences +//! the owner activity, records a durable intent in the Session's history, moves the +//! stage with a no-replace rename into a private `discarded//` slot of its +//! namespace and unlinks it there. Each request ID has one receipt; a retry resumes +//! the frozen plan and a lookup never acts. +use super::{Runtime, RuntimeError, SessionInfo, activity}; +use cyber_core::construction_discard::{self as native, Place, StageEvidence}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::path::PathBuf; + +mod confirm; +pub use confirm::spawn_retry; + +/// Durable intent and completion records of one discard request. +pub const DISCARDED: &str = "session.snapshot.construction_discarded.1"; +/// The only actor this revision admits. +pub const LOCAL_OWNER: &str = "local_owner"; +const LISTING_LIMIT: usize = 4096; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ConstructionStageKind { + CheckoutClaim, + CheckoutAcknowledgement, + CancellationRecord, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ConstructionLocation { + Present, + Removed, +} + +/// One listed stage. Listing grants no discard authority. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +pub struct ConstructionStageEntry { + pub name: String, + pub kind: ConstructionStageKind, + /// The constructing activity; absent when the name has no derivable owner. + pub activity_id: Option, + pub location: ConstructionLocation, +} + +/// A reviewed stage, frozen into the discard receipt. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ConstructionStage { + pub name: String, + pub kind: ConstructionStageKind, + pub activity_id: String, + pub session_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub worktree_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub journal_id: Option, + pub evidence: StageEvidence, + /// Operations that refuse while this stage exists. + pub fences: Vec, + pub location: ConstructionLocation, + /// The private directory that holds the stage. + pub source: PathBuf, + /// The namespace whose `discarded/` quarantine receives it. + pub namespace: PathBuf, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ConstructionDiscardSelection { + /// The exact stage name, from the construction listing. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stage: Option, + /// An activity with exactly one stage. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub activity_id: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +pub struct ConstructionDiscardReview { + pub session_id: String, + pub session_sequence: i64, + pub stage: ConstructionStage, + pub confirmation: String, + pub warning: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ConstructionDiscardConfirmation { + /// The reviewed stage name; one stage per confirmation. + pub stage: String, + pub confirmation: String, + pub request_id: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ConstructionDiscardStatus { + /// Recorded before any filesystem change; the plan is frozen. + Intent, + /// Moved into the quarantine, unlink not yet done (`discard pending`). + Pending, + /// The stage is gone. + Completed, + /// A different file holds the name; nothing was deleted. + Changed, +} + +/// The audit receipt of one request, as last recorded. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ConstructionDiscardReceipt { + pub request_id: String, + pub session_id: String, + pub confirmation: String, + pub stage: ConstructionStage, + pub actor: String, + pub recorded_ms: i64, + pub status: ConstructionDiscardStatus, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub detail: Option, +} + +impl ConstructionDiscardReceipt { + /// Still owes its unlink: listed and reported as `discard pending`. + pub fn pending(&self) -> bool { + matches!( + self.status, + ConstructionDiscardStatus::Intent | ConstructionDiscardStatus::Pending + ) + } +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +pub struct ConstructionInventory { + pub stages: Vec, + /// Requests whose stage is not unlinked yet (`discard pending`). + pub pending: Vec, +} + +/// A native stage as a host observed it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NativeConstructionStage { + pub name: String, + pub kind: ConstructionStageKind, + pub activity_id: Option, + pub worktree_id: Option, + pub journal_id: Option, + pub evidence: StageEvidence, + pub source: PathBuf, + pub namespace: PathBuf, +} + +/// Why a host refused to fence a stage. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ConstructionFenceError { + /// A live holder (constructor or worker lifetime) still owns it. + Busy(String), + Refused(String), +} + +/// Exclusive native ownership of one stage, held from fencing through its move. +pub trait ConstructionFence: Send { + /// Move the stage into `discarded//` of its namespace without replacing anything. + fn quarantine(&mut self, key: &str) -> Result<(), String>; +} + +pub(super) fn validate_event(data: &serde_json::Value) -> Result<(), String> { + let receipt: ConstructionDiscardReceipt = + serde_json::from_value(data.clone()).map_err(|error| error.to_string())?; + if receipt.actor != LOCAL_OWNER + || receipt.request_id.is_empty() + || receipt.request_id.len() > 256 + || !native::valid_component(&receipt.stage.name) + { + return Err("Invalid construction discard receipt".into()); + } + Ok(()) +} + +pub(super) fn quarantine_key(session: &str, request: &str) -> String { + use sha2::{Digest, Sha256}; + let bytes = serde_json::to_vec(&("construction-discard-v1", session, request)) + .expect("strings serialize"); + format!("{:x}", Sha256::digest(bytes)) +} + +fn location_state(info: &SessionInfo) -> ConstructionLocation { + match std::fs::symlink_metadata(&info.directory) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => ConstructionLocation::Removed, + _ => ConstructionLocation::Present, + } +} + +fn kind_of(name: &str) -> Option { + if name.starts_with("ack_preparing_") { + Some(ConstructionStageKind::CheckoutAcknowledgement) + } else if name.starts_with("preparing_") { + Some(ConstructionStageKind::CheckoutClaim) + } else if name.starts_with("tmp_") { + Some(ConstructionStageKind::CancellationRecord) + } else { + None + } +} + +fn fences(stage: &NativeConstructionStage, activity: &str) -> Vec { + match stage.kind { + ConstructionStageKind::CheckoutClaim => vec![ + "managed worktree removal".into(), + "checkout metadata retirement".into(), + format!("new checkout claims by {activity}"), + ], + ConstructionStageKind::CheckoutAcknowledgement => vec![ + format!("managed worktree removal until {activity}'s acknowledgement is verified"), + "checkout metadata retirement".into(), + ], + ConstructionStageKind::CancellationRecord => vec![format!( + "reclamation of journal {}", + stage.journal_id.as_deref().unwrap_or("unknown") + )], + } +} + +fn conflict(message: impl Into) -> RuntimeError { + RuntimeError::Conflict(message.into()) +} + +/// The latest record of every snapshot activity of one Session. +pub(super) fn session_activities( + db: &rusqlite::Connection, + session: &str, +) -> Result, cyber_store::StoreError> { + let mut query = db.prepare( + "SELECT aggregate_id,data FROM event e WHERE type=?2 AND json_extract(data,'$.session_id')=?1 \ + AND json_extract(data,'$.snapshot_worker')=1 \ + AND NOT EXISTS(SELECT 1 FROM event n WHERE n.aggregate_id=e.aggregate_id AND n.seq>e.seq) \ + ORDER BY aggregate_id LIMIT 4097", + )?; + let rows = query.query_map([session, activity::CHANGED], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) + })?; + let mut found = BTreeMap::new(); + for row in rows { + let (id, data) = row?; + let record: activity::Record = serde_json::from_str(&data).map_err(|_| { + cyber_store::StoreError::InvalidAppend("Invalid snapshot activity".into()) + })?; + found.insert(id, record); + } + if found.len() > LISTING_LIMIT { + return Err(cyber_store::StoreError::InvalidAppend( + "Snapshot activity limit exceeded".into(), + )); + } + Ok(found) +} + +/// The origin of an activity whose cancellation recorded a journal binding. +fn cancellation_origin(record: &activity::Record) -> Option<&super::SnapshotOrigin> { + record + .snapshot_preparation_receipt + .as_ref() + .and_then(|receipt| receipt.origin.as_ref()) +} + +impl Runtime { + pub(super) async fn construction_activities( + &self, + session: &str, + ) -> Result, RuntimeError> { + let session = session.to_owned(); + Ok(self + .inner + .store + .read(move |db| session_activities(db, &session))?) + } + + /// Read-only inventory of this Session's construction stages and of its + /// discards that still owe an unlink. + pub async fn construction_inventory( + &self, + session: &str, + ) -> Result { + let info = self.session_info(session).await?; + let location = location_state(&info); + let mut stages: Vec = self + .inner + .tools + .snapshot_checkout_constructions(&info) + .map_err(conflict)? + .into_iter() + .map(|stage| ConstructionStageEntry { + kind: match stage.kind { + cyber_core::worktrees::SnapshotConstructionKind::CheckoutClaim => { + ConstructionStageKind::CheckoutClaim + } + cyber_core::worktrees::SnapshotConstructionKind::CheckoutAcknowledgement => { + ConstructionStageKind::CheckoutAcknowledgement + } + }, + name: stage.name, + activity_id: stage.owner_id, + location, + }) + .collect(); + for (activity, record) in self.construction_activities(session).await? { + let Some(origin) = cancellation_origin(&record) else { + continue; + }; + for name in self + .inner + .options + .snapshots + .cancellation_stages(origin.clone()) + .await + .map_err(conflict)? + { + stages.push(ConstructionStageEntry { + name, + kind: ConstructionStageKind::CancellationRecord, + activity_id: Some(activity.clone()), + location, + }); + } + } + let pending = self + .construction_receipts(Some(session)) + .await? + .into_iter() + .filter(ConstructionDiscardReceipt::pending) + .collect(); + Ok(ConstructionInventory { stages, pending }) + } + + /// Resolve the selection to exactly one stage name. + async fn select_stage( + &self, + session: &str, + selection: &ConstructionDiscardSelection, + ) -> Result { + match (&selection.stage, &selection.activity_id) { + (Some(stage), None) => Ok(stage.clone()), + (None, Some(activity)) => { + let names: Vec = self + .construction_inventory(session) + .await? + .stages + .into_iter() + .filter(|stage| stage.activity_id.as_deref() == Some(activity)) + .map(|stage| stage.name) + .collect(); + match names.as_slice() { + [name] => Ok(name.clone()), + [] => Err(conflict(format!( + "Activity {activity} has no construction stage" + ))), + _ => Err(conflict(format!( + "Activity {activity} has {} construction stages; review one stage per confirmation: {}", + names.len(), + names.join(", ") + ))), + } + } + _ => Err(RuntimeError::Invalid( + "Name exactly one construction stage or one activity".into(), + )), + } + } + + /// Observe one stage natively, without opening it for writing or locking it. + pub(super) async fn native_stage( + &self, + info: &SessionInfo, + activities: &BTreeMap, + name: &str, + ) -> Result { + if !native::valid_component(name) { + return Err(RuntimeError::Invalid( + "Invalid construction stage name".into(), + )); + } + let missing = || conflict(format!("No construction stage {name} for this Session")); + match kind_of(name).ok_or_else(missing)? { + ConstructionStageKind::CancellationRecord => { + for origin in activities.values().filter_map(cancellation_origin) { + if let Some(stage) = self + .inner + .options + .snapshots + .cancellation_stage(origin.clone(), name.to_owned()) + .await + .map_err(conflict)? + { + return Ok(stage); + } + } + Err(missing()) + } + _ => self + .inner + .tools + .snapshot_construction_stage(info, name) + .map_err(conflict)? + .ok_or_else(missing), + } + } + + /// The reviewed stage, with its owner proven to be a snapshot activity of this Session. + pub(super) async fn reviewed_stage( + &self, + info: &SessionInfo, + name: &str, + ) -> Result<(ConstructionStage, BTreeMap), RuntimeError> { + let activities = self.construction_activities(&info.id).await?; + let native = self.native_stage(info, &activities, name).await?; + let activity = native.activity_id.clone().ok_or_else(|| { + conflict(format!( + "Construction stage {name} has no derivable owner; it stays listed and fenced" + )) + })?; + if !activities.contains_key(&activity) { + return Err(conflict(format!( + "Construction stage {name} names {activity}, which is not a snapshot activity of this Session" + ))); + } + let location = location_state(info); + if location == ConstructionLocation::Removed && info.worktree_id.is_some() { + return Err(conflict( + "The managed checkout of this removed Location cannot be verified; its evidence stays fenced", + )); + } + let stage = ConstructionStage { + fences: fences(&native, &activity), + name: native.name, + kind: native.kind, + activity_id: activity, + session_id: info.id.clone(), + worktree_id: native.worktree_id, + journal_id: native.journal_id, + evidence: native.evidence, + location, + source: native.source, + namespace: native.namespace, + }; + Ok((stage, activities)) + } + + pub(super) fn discard_fingerprint( + session: &str, + sequence: i64, + stage: &ConstructionStage, + ) -> Result { + use sha2::{Digest, Sha256}; + let bytes = + serde_json::to_vec(&("construction-discard-review-v1", session, sequence, stage)) + .map_err(|error| RuntimeError::Invalid(error.to_string()))?; + Ok(format!("{:x}", Sha256::digest(bytes))) + } + + /// Read-only review of one stage with its confirmation fingerprint. + pub async fn construction_discard_review( + &self, + session: &str, + selection: &ConstructionDiscardSelection, + ) -> Result { + let name = self.select_stage(session, selection).await?; + let handle = self.inner.handle(session).await?; + let (info, sequence) = { + let state = handle.state.lock().await; + (state.info.clone(), state.last_seq) + }; + let (stage, _) = self.reviewed_stage(&info, &name).await?; + let confirmation = Self::discard_fingerprint(session, sequence, &stage)?; + Ok(ConstructionDiscardReview { + session_id: session.into(), + session_sequence: sequence, + stage, + confirmation, + warning: + "Discards only this unpublished construction stage after fencing its activity. \ + Restore journals, payload images, published claims, acknowledgements and \ + cancellation records are never touched; the managed worktree is not removed." + .into(), + }) + } + + /// Every recorded receipt, latest record per request; one Session or all. + pub(super) async fn construction_receipts( + &self, + session: Option<&str>, + ) -> Result, RuntimeError> { + let session = session.map(str::to_owned); + Ok(self.inner.store.read(move |db| { + let mut query = db.prepare( + "SELECT data FROM event e WHERE type=?1 AND (?2 IS NULL OR aggregate_id=?2) \ + AND NOT EXISTS(SELECT 1 FROM event n WHERE n.aggregate_id=e.aggregate_id AND n.type=e.type \ + AND json_extract(n.data,'$.request_id')=json_extract(e.data,'$.request_id') AND n.seq>e.seq) \ + ORDER BY aggregate_id,seq LIMIT 4097", + )?; + let rows = query.query_map(rusqlite::params![DISCARDED, session], |row| { + row.get::<_, String>(0) + })?; + let mut found = vec![]; + for row in rows { + let receipt: ConstructionDiscardReceipt = serde_json::from_str(&row?) + .map_err(|_| cyber_store::StoreError::InvalidAppend("Invalid discard receipt".into()))?; + found.push(receipt); + } + Ok(found) + })?) + } + + /// The receipt of one request as last recorded, without acting. + pub async fn construction_discard_lookup( + &self, + session: &str, + request: &str, + ) -> Result, RuntimeError> { + super::snapshot_recovery::validate_request_id(request)?; + self.session_info(session).await?; + self.discard_receipt(session, request) + } + + /// Store-only lookup; safe while the Session lock is held. + pub(super) fn discard_receipt( + &self, + session: &str, + request: &str, + ) -> Result, RuntimeError> { + let (session, request) = (session.to_owned(), request.to_owned()); + Ok(self.inner.store.read(move |db| { + use rusqlite::OptionalExtension; + let data: Option = db + .query_row( + "SELECT data FROM event WHERE aggregate_id=?1 AND type=?2 \ + AND json_extract(data,'$.request_id')=?3 ORDER BY seq DESC LIMIT 1", + rusqlite::params![session, DISCARDED, request], + |row| row.get(0), + ) + .optional()?; + data.map(|data| { + serde_json::from_str(&data).map_err(|_| { + cyber_store::StoreError::InvalidAppend("Invalid discard receipt".into()) + }) + }) + .transpose() + })?) + } +} + +/// Where the frozen stage is now. Paths come from the receipt; identities are +/// compared before anything is reported as the reviewed stage. +pub(super) fn locate(stage: &ConstructionStage, key: &str) -> Result { + native::locate_at( + &stage.source, + &stage.namespace, + &stage.name, + key, + &stage.evidence, + ) + .map_err(|error| error.to_string()) +} + +/// Unlink the frozen stage from its quarantine slot when it still has the reviewed identity. +pub(super) fn unlink(stage: &ConstructionStage, key: &str) -> Result { + native::unlink_at(&stage.namespace, key, &stage.name, &stage.evidence) + .map_err(|error| error.to_string()) +} diff --git a/crates/cyber-server/src/runtime/construction_discard/confirm.rs b/crates/cyber-server/src/runtime/construction_discard/confirm.rs new file mode 100644 index 00000000..a9436598 --- /dev/null +++ b/crates/cyber-server/src/runtime/construction_discard/confirm.rs @@ -0,0 +1,392 @@ +//! Confirmation, resumption and maintenance of construction discards. +//! +//! Order under the Session lock: runtime fences (idle, no Drain, no background +//! work, no admitted snapshot worker, no unresolved preparation), the unchanged +//! review fingerprint, the owner activity's lifetime lock and the native stage +//! fence, then the durable intent. Only after the intent commits is the stage +//! moved into its quarantine slot and unlinked; the completion is recorded last. +use super::{ + ConstructionDiscardConfirmation, ConstructionDiscardReceipt, ConstructionDiscardStatus, + ConstructionFence, ConstructionFenceError, ConstructionLocation, ConstructionStage, + ConstructionStageKind, DISCARDED, LOCAL_OWNER, NativeConstructionStage, conflict, + quarantine_key, +}; +use crate::runtime::{Handle, Runtime, RuntimeError, SessionState, activity, events::event}; +use cyber_core::construction_discard::Place; +use std::collections::BTreeMap; +use std::sync::{Arc, PoisonError, atomic::Ordering}; + +/// Retries a pending unlink about a minute after start, then hourly, forever. +pub fn spawn_retry(runtime: Runtime) -> tokio::task::JoinHandle<()> { + tokio::spawn(async move { + tokio::time::sleep(first_retry_delay()).await; + loop { + if let Err(error) = runtime.retry_construction_discards().await { + cyber_core::log::warn( + "snapshots", + "construction discard retry failed", + serde_json::json!({"error": error.to_string()}), + ); + } + tokio::time::sleep(std::time::Duration::from_secs(3600)).await; + } + }) +} + +/// A minute; debug-build process tests may shorten it with +/// `CYBER_TEST_DISCARD_RETRY_DELAY_MS`. Release builds ignore the variable. +fn first_retry_delay() -> std::time::Duration { + #[cfg(debug_assertions)] + if let Some(milliseconds) = std::env::var("CYBER_TEST_DISCARD_RETRY_DELAY_MS") + .ok() + .and_then(|value| value.parse().ok()) + { + return std::time::Duration::from_millis(milliseconds); + } + std::time::Duration::from_secs(60) +} + +/// Marks the Session as running snapshot work for the whole confirmation. +struct Admission(Arc); +impl Admission { + fn take(handle: &Arc, session: &str) -> Result { + handle + .snapshot_active + .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) + .map_err(|_| RuntimeError::Busy(session.into()))?; + Ok(Self(handle.clone())) + } +} +impl Drop for Admission { + fn drop(&mut self) { + self.0.snapshot_active.store(false, Ordering::SeqCst); + } +} + +/// Native ownership retained from fencing through the move. +struct Fenced { + _lifetime: Option>, + stage: Box, +} + +fn fence_error(session: &str, error: ConstructionFenceError) -> RuntimeError { + match error { + ConstructionFenceError::Busy(message) => RuntimeError::Conflict(format!( + "busy: {message} (Session {session}); the stage stays fenced" + )), + ConstructionFenceError::Refused(message) => RuntimeError::Conflict(message), + } +} + +/// Only a held lifetime lock is a live holder; anything else refuses as it is. +fn lifetime_error(error: String) -> ConstructionFenceError { + if error == "Snapshot worker is still active" { + ConstructionFenceError::Busy(error) + } else { + ConstructionFenceError::Refused(error) + } +} + +fn now_ms() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_millis() as i64) +} + +fn unresolved_preparation( + db: &rusqlite::Connection, + session: &str, +) -> Result { + use rusqlite::OptionalExtension; + Ok(db + .query_row( + "SELECT 1 FROM event e WHERE type=?2 AND json_extract(data,'$.session_id')=?1 \ + AND json_extract(data,'$.snapshot_worker')=1 AND json_extract(data,'$.status')<>'settled' \ + AND NOT EXISTS(SELECT 1 FROM event n WHERE n.aggregate_id=e.aggregate_id AND n.seq>e.seq) LIMIT 1", + [session, activity::CHANGED], + |_| Ok(()), + ) + .optional()? + .is_some()) +} + +impl Runtime { + /// Confirm a reviewed discard, or resume the request with this ID. + pub async fn construction_discard_confirm( + &self, + session: &str, + confirmation: &ConstructionDiscardConfirmation, + ) -> Result { + crate::runtime::snapshot_recovery::validate_request_id(&confirmation.request_id)?; + if !cyber_core::construction_discard::valid_key(&confirmation.confirmation) { + return Err(RuntimeError::Invalid("Invalid discard fingerprint".into())); + } + if let Some(receipt) = self + .construction_discard_lookup(session, &confirmation.request_id) + .await? + { + if receipt.confirmation != confirmation.confirmation + || receipt.stage.name != confirmation.stage + { + return Err(conflict("Discard request content changed")); + } + return self.resume_construction_discard(receipt).await; + } + let _lifecycle = self.memory_mutation_lease().await?; + let handle = self.inner.handle(session).await?; + let mut state = handle.state.lock().await; + let _admission = self.discard_fences(&handle, &state).await?; + let (stage, activities) = self + .reviewed_stage(&state.info, &confirmation.stage) + .await?; + if Self::discard_fingerprint(session, state.last_seq, &stage)? != confirmation.confirmation + { + return Err(conflict( + "stale: the construction stage or Session changed since review; review again", + )); + } + let fenced = self.fence_stage(&state, &activities, &stage).await?; + let receipt = ConstructionDiscardReceipt { + request_id: confirmation.request_id.clone(), + session_id: session.into(), + confirmation: confirmation.confirmation.clone(), + stage, + actor: LOCAL_OWNER.into(), + recorded_ms: now_ms(), + status: ConstructionDiscardStatus::Intent, + detail: None, + }; + self.inner + .commit_locked(&mut state, vec![event(DISCARDED, &receipt)])?; + self.execute_discard(&mut state, fenced, receipt).await + } + + /// Runtime fences, checked with the Session lock held. + async fn discard_fences( + &self, + handle: &Arc, + state: &SessionState, + ) -> Result { + let session = state.info.id.as_str(); + self.inner.ensure_idle(session)?; + self.ensure_no_background(session)?; + state.ensure_worktree_ready()?; + if self + .inner + .activities + .lock() + .unwrap_or_else(PoisonError::into_inner) + .values() + .any(|control| control.source == session) + { + return Err(RuntimeError::Busy(session.into())); + } + let admission = Admission::take(handle, session)?; + let source = session.to_owned(); + if self + .inner + .store + .read(move |db| unresolved_preparation(db, &source))? + { + return Err(conflict( + "The Session has an unresolved snapshot preparation; cancel or recover it before discarding construction evidence", + )); + } + Ok(admission) + } + + /// Acquire the owner activity's lifetime lock and the native stage fence. + async fn fence_stage( + &self, + state: &SessionState, + activities: &BTreeMap, + stage: &ConstructionStage, + ) -> Result { + let session = state.info.id.as_str(); + let record = activities + .get(&stage.activity_id) + .ok_or_else(|| conflict("Construction stage owner changed"))?; + let native = NativeConstructionStage { + name: stage.name.clone(), + kind: stage.kind, + activity_id: Some(stage.activity_id.clone()), + worktree_id: stage.worktree_id.clone(), + journal_id: stage.journal_id.clone(), + evidence: stage.evidence.clone(), + source: stage.source.clone(), + namespace: stage.namespace.clone(), + }; + if stage.kind == ConstructionStageKind::CancellationRecord { + let origin = super::cancellation_origin(record) + .ok_or_else(|| conflict("Cancellation record owner changed"))? + .clone(); + let fence = self + .inner + .options + .snapshots + .fence_cancellation_stage(origin, native) + .await + .map_err(|error| fence_error(session, error))?; + return Ok(Fenced { + _lifetime: None, + stage: fence, + }); + } + let lifetime = match (&record.snapshot_lifetime, stage.location) { + (Some(binding), ConstructionLocation::Present) => Some( + self.inner + .options + .snapshots + .lock_worker(binding.clone()) + .await + .map_err(|error| fence_error(session, lifetime_error(error)))?, + ), + _ => None, + }; + let fence = self + .inner + .tools + .fence_snapshot_construction(&state.info, &native) + .map_err(|error| fence_error(session, error))?; + Ok(Fenced { + _lifetime: lifetime, + stage: fence, + }) + } + + /// Move, unlink and record the completion of an intent already committed. + async fn execute_discard( + &self, + state: &mut SessionState, + fenced: Fenced, + receipt: ConstructionDiscardReceipt, + ) -> Result { + let key = quarantine_key(&receipt.session_id, &receipt.request_id); + let stage = receipt.stage.clone(); + let moved = tokio::task::spawn_blocking(move || { + let mut fenced = fenced; + crate::runtime::process_cut::pause("construction-discard-intent-committed"); + fenced.stage.quarantine(&key)?; + drop(fenced); + crate::runtime::process_cut::pause("construction-discard-quarantined"); + let place = super::unlink(&stage, &key); + crate::runtime::process_cut::pause("construction-discard-unlinked"); + Ok::<_, String>(place) + }) + .await + .map_err(|_| conflict("Construction discard interrupted; repeat the confirmation with the same request ID"))? + .map_err(|error| { + conflict(format!( + "Construction discard intent recorded but the stage was not moved: {error}; \ + repeat the confirmation with the same request ID" + )) + })?; + self.complete_discard(state, receipt, moved) + } + + fn complete_discard( + &self, + state: &mut SessionState, + mut receipt: ConstructionDiscardReceipt, + place: Result, + ) -> Result { + let (status, detail) = match place { + Ok(Place::Gone) => (ConstructionDiscardStatus::Completed, None), + Ok(Place::Changed(detail)) => (ConstructionDiscardStatus::Changed, Some(detail)), + Ok(Place::Quarantined | Place::Source) => ( + ConstructionDiscardStatus::Pending, + Some("The stage is still present".into()), + ), + Err(error) => (ConstructionDiscardStatus::Pending, Some(error)), + }; + if receipt.status == status && receipt.detail == detail { + return Ok(receipt); + } + receipt.status = status; + receipt.detail = detail; + receipt.recorded_ms = now_ms(); + self.inner + .commit_locked(state, vec![event(DISCARDED, &receipt)])?; + Ok(receipt) + } + + /// Continue a recorded request from wherever its stage is now. + async fn resume_construction_discard( + &self, + receipt: ConstructionDiscardReceipt, + ) -> Result { + if !receipt.pending() { + return Ok(receipt); + } + let handle = self.inner.handle(&receipt.session_id).await?; + let mut state = handle.state.lock().await; + let latest = self.discard_receipt(&receipt.session_id, &receipt.request_id)?; + let Some(current) = latest.clone().filter(ConstructionDiscardReceipt::pending) else { + return latest.ok_or_else(|| conflict("Discard receipt disappeared")); + }; + let key = quarantine_key(¤t.session_id, ¤t.request_id); + let stage = current.stage.clone(); + let place = tokio::task::spawn_blocking(move || super::locate(&stage, &key)) + .await + .map_err(|_| conflict("Construction discard resumption interrupted"))?; + match place { + Ok(Place::Source) => self.refence_and_execute(&handle, &mut state, current).await, + Ok(Place::Quarantined) => { + let key = quarantine_key(¤t.session_id, ¤t.request_id); + let stage = current.stage.clone(); + let unlinked = tokio::task::spawn_blocking(move || super::unlink(&stage, &key)) + .await + .map_err(|_| conflict("Construction discard unlink interrupted"))?; + self.complete_discard(&mut state, current, unlinked) + } + other => self.complete_discard(&mut state, current, other), + } + } + + /// The stage never moved: fence it again exactly as reviewed before moving it. + async fn refence_and_execute( + &self, + handle: &Arc, + state: &mut SessionState, + receipt: ConstructionDiscardReceipt, + ) -> Result { + let _lifecycle = self.memory_mutation_lease().await?; + let _admission = self.discard_fences(handle, state).await?; + let activities = self.construction_activities(&receipt.session_id).await?; + let fenced = self.fence_stage(state, &activities, &receipt.stage).await?; + self.execute_discard(state, fenced, receipt).await + } + + /// Maintenance: finish every request whose stage left its namespace but was not + /// unlinked. A stage that never moved waits for the owner's repeated confirmation. + pub async fn retry_construction_discards(&self) -> Result { + let mut finished = 0; + for receipt in self.construction_receipts(None).await? { + if !receipt.pending() { + continue; + } + match self.retry_one(receipt).await { + Ok(done) => finished += usize::from(done), + Err(error) => cyber_core::log::warn( + "snapshots", + "construction discard stays pending", + serde_json::json!({"error": error.to_string()}), + ), + } + } + Ok(finished) + } + + /// Finish one moved stage; a stage that never moved is left for the owner. + async fn retry_one(&self, receipt: ConstructionDiscardReceipt) -> Result { + let key = quarantine_key(&receipt.session_id, &receipt.request_id); + let stage = receipt.stage.clone(); + let place = tokio::task::spawn_blocking(move || super::locate(&stage, &key)) + .await + .map_err(|_| conflict("Construction discard retry interrupted"))?; + if matches!(place, Ok(Place::Source)) { + return Ok(false); + } + Ok(!self.resume_construction_discard(receipt).await?.pending()) + } +} diff --git a/crates/cyber-server/src/runtime/events.rs b/crates/cyber-server/src/runtime/events.rs index f1062bce..ecba213d 100644 --- a/crates/cyber-server/src/runtime/events.rs +++ b/crates/cyber-server/src/runtime/events.rs @@ -69,6 +69,7 @@ const ALL: &[&str] = &[ super::admission_authority::FENCED, super::activity::CHANGED, super::snapshot_preparation::CANCELLED, + super::construction_discard::DISCARDED, super::child_ownership::CHANGED, super::subtree_stop::SETTLED, super::subtree_stop::STARTED, @@ -617,6 +618,12 @@ pub fn registry() -> EventRegistry { super::snapshot_preparation::validate_event, ) .expect("valid snapshot preparation cancellation receipt"); + registry + .register_with( + super::construction_discard::DISCARDED, + super::construction_discard::validate_event, + ) + .expect("valid construction discard receipt"); registry .register_with(MESSAGING_UPDATED, |data| { serde_json::from_value::(data.clone()) diff --git a/crates/cyber-server/src/runtime/host.rs b/crates/cyber-server/src/runtime/host.rs index 30e6e7cc..5e60cef8 100644 --- a/crates/cyber-server/src/runtime/host.rs +++ b/crates/cyber-server/src/runtime/host.rs @@ -1059,6 +1059,29 @@ pub trait ToolHost: Send + Sync { Ok(vec![]) } + /// Read-only native review of one checkout claim or acknowledgement stage of this + /// Session's managed checkout; `None` when it has none by that name. Nothing is + /// opened for writing, locked or adopted. + fn snapshot_construction_stage( + &self, + _info: &SessionInfo, + _name: &str, + ) -> Result, String> { + Ok(None) + } + + /// Fence one reviewed checkout stage for an owner-confirmed discard: its + /// constructor lock is held exclusively and its published records are checked. + fn fence_snapshot_construction( + &self, + _info: &SessionInfo, + _stage: &super::NativeConstructionStage, + ) -> Result, super::ConstructionFenceError> { + Err(super::ConstructionFenceError::Refused( + "Checkout construction discard is unavailable on this host".into(), + )) + } + /// Reacquire only original snapshot evidence, without creating or settling claims. /// The caller retains the matching lifetime lock independently. fn reacquire_snapshot_location( @@ -1713,6 +1736,36 @@ pub trait Snapshots: Send + Sync { Err("Native snapshot acknowledgement reconciliation is unavailable".into()) }) } + /// Names of the file-copy cancellation-record stages retained beside the + /// journal of `origin`. Inventory only; it grants no discard authority. + fn cancellation_stages( + &self, + _origin: super::SnapshotOrigin, + ) -> BoxFuture<'_, Result, String>> { + Box::pin(async { Ok(vec![]) }) + } + /// Read-only native review of one cancellation-record stage of `origin`'s journal. + fn cancellation_stage( + &self, + _origin: super::SnapshotOrigin, + _name: String, + ) -> BoxFuture<'_, Result, String>> { + Box::pin(async { Ok(None) }) + } + /// Fence one reviewed cancellation-record stage: the namespace lock and the + /// owner's lifetime lock are held and its published record is checked. + fn fence_cancellation_stage( + &self, + _origin: super::SnapshotOrigin, + _stage: super::NativeConstructionStage, + ) -> BoxFuture<'_, Result, super::ConstructionFenceError>> + { + Box::pin(async { + Err(super::ConstructionFenceError::Refused( + "Cancellation-record discard is unavailable on this host".into(), + )) + }) + } /// Only synchronous filesystem hosts retaining runtime-issued worker ownership. fn owned_restore_available(&self, _directory: &str) -> bool { false diff --git a/crates/cyber-server/src/runtime/mod.rs b/crates/cyber-server/src/runtime/mod.rs index adb7381c..1527b0c9 100644 --- a/crates/cyber-server/src/runtime/mod.rs +++ b/crates/cyber-server/src/runtime/mod.rs @@ -135,6 +135,7 @@ pub use memory::{ MemoryRecoveryRequestStatus, MemoryRequestStatus, MemoryWrite, MemoryWriteOwner, memory_http_request_id, }; +pub mod construction_discard; pub mod deferred_tools; mod model; mod requests; @@ -142,6 +143,12 @@ mod rewind; mod rewind_preview; mod snapshot_lifetime; mod snapshot_preparation; +pub use construction_discard::{ + ConstructionDiscardConfirmation, ConstructionDiscardReceipt, ConstructionDiscardReview, + ConstructionDiscardSelection, ConstructionDiscardStatus, ConstructionFence, + ConstructionFenceError, ConstructionInventory, ConstructionLocation, ConstructionStage, + ConstructionStageEntry, ConstructionStageKind, NativeConstructionStage, +}; pub use snapshot_preparation::{ SnapshotPreparation, SnapshotPreparationConfirmation, SnapshotPreparationReceipt, SnapshotPreparationReview, diff --git a/crates/cyber-server/tests/http.rs b/crates/cyber-server/tests/http.rs index b4a940b6..a8704c8a 100644 --- a/crates/cyber-server/tests/http.rs +++ b/crates/cyber-server/tests/http.rs @@ -286,6 +286,57 @@ async fn errors_are_tagged() { ); } +/// `snapshots-checkpoints` → Owner-only discard of construction evidence: listing is +/// read-only; review and confirmation refuse every caller that presents another +/// identity than the local owner (`403`) before any work, and a lookup never acts. +#[tokio::test] +async fn construction_discard_is_owner_only_and_listing_is_read_only() { + let h = Harness::new(Setup::default()); + let api = Api::new(&h); + let (_, created) = api.post("/sessions", json!({})).await; + let id = created["data"]["id"].as_str().unwrap().to_string(); + let base = format!("/sessions/{id}/rewind/constructions"); + let (status, listing) = api.get(&base).await; + assert_eq!(status, StatusCode::OK, "{listing}"); + assert_eq!(listing["data"], json!({"stages": [], "pending": []})); + let stage = format!("preparing_6_op_one_{}", "0".repeat(26)); + let review = json!({"stage": stage}); + let confirm = json!({"stage": stage, "confirmation": "a".repeat(64), "request_id": "one"}); + for header in [ + ("authorization", "Bearer relay-token"), + ("x-cyber-attach", "att_one"), + ("origin", "http://localhost:5173"), + ("sec-fetch-mode", "cors"), + ("x-cyber-client", "mcp:model"), + ] { + for (path, body) in [("review", &review), ("confirm", &confirm)] { + let (status, body, _) = api + .call( + Method::POST, + &format!("{base}/discard/{path}"), + Some(body.clone()), + &[header], + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{header:?} {path}: {body}"); + assert_eq!(body["_tag"], "ForbiddenError"); + } + } + // The owner reaches the runtime, which finds no such stage. + let (status, body) = api.post(&format!("{base}/discard/review"), review).await; + assert_eq!(status, StatusCode::CONFLICT, "{body}"); + let (status, body) = api + .post( + &format!("{base}/discard/confirm"), + json!({"stage": stage, "confirmation": "not-a-fingerprint", "request_id": "one"}), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); + let (status, body) = api.get(&format!("{base}/discard/requests/one")).await; + assert_eq!(status, StatusCode::NOT_FOUND, "{body}"); + assert_eq!(body["_tag"], "ConstructionDiscardNotFoundError"); +} + #[tokio::test] async fn renaming_cleans_bounds_and_requires_a_title() { let h = Harness::new(Setup::default()); diff --git a/crates/cyber-tools/src/host.rs b/crates/cyber-tools/src/host.rs index e90788aa..dacdf62f 100644 --- a/crates/cyber-tools/src/host.rs +++ b/crates/cyber-tools/src/host.rs @@ -1468,6 +1468,86 @@ impl ToolHost for BuiltinHost { } } + fn snapshot_construction_stage( + &self, + info: &cyber_server::runtime::SessionInfo, + name: &str, + ) -> Result, String> { + let Some(worktree) = info.worktree_id.as_deref() else { + return Ok(None); + }; + let review = match cyber_core::worktrees::Repository::review_snapshot_construction( + std::path::Path::new(&info.directory), + worktree, + name, + ) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), + result => result.map_err(|error| error.to_string())?, + }; + Ok( + review.map(|review| cyber_server::runtime::NativeConstructionStage { + name: review.stage.name, + kind: match review.stage.kind { + cyber_core::worktrees::SnapshotConstructionKind::CheckoutClaim => { + cyber_server::runtime::ConstructionStageKind::CheckoutClaim + } + cyber_core::worktrees::SnapshotConstructionKind::CheckoutAcknowledgement => { + cyber_server::runtime::ConstructionStageKind::CheckoutAcknowledgement + } + }, + activity_id: review.stage.owner_id, + worktree_id: Some(review.stage.worktree_id), + journal_id: None, + evidence: review.evidence, + source: review.source, + namespace: review.namespace, + }), + ) + } + + fn fence_snapshot_construction( + &self, + info: &cyber_server::runtime::SessionInfo, + stage: &cyber_server::runtime::NativeConstructionStage, + ) -> Result< + Box, + cyber_server::runtime::ConstructionFenceError, + > { + use cyber_server::runtime::ConstructionFenceError; + let refused = |message: &str| ConstructionFenceError::Refused(message.into()); + let worktree = info + .worktree_id + .as_deref() + .ok_or_else(|| refused("This Session has no managed checkout"))?; + let owner = stage + .activity_id + .as_deref() + .ok_or_else(|| refused("Construction stage name has no derivable owner"))?; + let reviewed = self + .snapshot_construction_stage(info, &stage.name) + .map_err(|error| refused(&error))?; + if reviewed.as_ref().is_some_and(|reviewed| { + reviewed.source != stage.source || reviewed.namespace != stage.namespace + }) { + return Err(refused("Checkout construction stage moved since review")); + } + cyber_core::worktrees::Repository::fence_snapshot_construction( + std::path::Path::new(&info.directory), + worktree, + &stage.name, + owner, + &stage.evidence, + ) + .map(|fence| { + Box::new(CheckoutConstruction(fence)) + as Box + }) + .map_err(|error| match error.kind() { + std::io::ErrorKind::WouldBlock => ConstructionFenceError::Busy(error.to_string()), + _ => ConstructionFenceError::Refused(error.to_string()), + }) + } + fn reacquire_snapshot_location( &self, info: &cyber_server::runtime::SessionInfo, @@ -3035,3 +3115,11 @@ impl BuiltinHost { }) } } + +/// A fenced checkout construction stage, held until it is moved or dropped. +struct CheckoutConstruction(cyber_core::worktrees::CheckoutConstructionFence); +impl cyber_server::runtime::ConstructionFence for CheckoutConstruction { + fn quarantine(&mut self, key: &str) -> Result<(), String> { + self.0.quarantine(key).map_err(|error| error.to_string()) + } +} diff --git a/sdk/openapi.json b/sdk/openapi.json index 7191712c..cc26ee43 100644 --- a/sdk/openapi.json +++ b/sdk/openapi.json @@ -8261,6 +8261,341 @@ "data" ] }, + "Data_ConstructionInventory": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/ConstructionInventory" + } + }, + "required": [ + "data" + ] + }, + "ConstructionInventory": { + "type": "object", + "properties": { + "stages": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ConstructionStageEntry" + } + }, + "pending": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ConstructionDiscardReceipt" + }, + "description": "Requests whose stage is not unlinked yet (`discard pending`)." + } + }, + "required": [ + "stages", + "pending" + ] + }, + "ConstructionStageEntry": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "kind": { + "$ref": "#/components/schemas/ConstructionStageKind" + }, + "activity_id": { + "type": [ + "string", + "null" + ], + "description": "The constructing activity; absent when the name has no derivable owner." + }, + "location": { + "$ref": "#/components/schemas/ConstructionLocation" + } + }, + "required": [ + "name", + "kind", + "location" + ], + "description": "One listed stage. Listing grants no discard authority." + }, + "ConstructionStageKind": { + "type": "string", + "enum": [ + "checkout_claim", + "checkout_acknowledgement", + "cancellation_record" + ] + }, + "ConstructionLocation": { + "type": "string", + "enum": [ + "present", + "removed" + ] + }, + "ConstructionDiscardReceipt": { + "type": "object", + "additionalProperties": false, + "properties": { + "request_id": { + "type": "string" + }, + "session_id": { + "type": "string" + }, + "confirmation": { + "type": "string" + }, + "stage": { + "$ref": "#/components/schemas/ConstructionStage" + }, + "actor": { + "type": "string" + }, + "recorded_ms": { + "type": "integer", + "format": "int64" + }, + "status": { + "$ref": "#/components/schemas/ConstructionDiscardStatus" + }, + "detail": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "request_id", + "session_id", + "confirmation", + "stage", + "actor", + "recorded_ms", + "status" + ], + "description": "The audit receipt of one request, as last recorded." + }, + "ConstructionStage": { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "kind": { + "$ref": "#/components/schemas/ConstructionStageKind" + }, + "activity_id": { + "type": "string" + }, + "session_id": { + "type": "string" + }, + "worktree_id": { + "type": [ + "string", + "null" + ] + }, + "journal_id": { + "type": [ + "string", + "null" + ] + }, + "evidence": { + "$ref": "#/components/schemas/StageEvidence" + }, + "fences": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Operations that refuse while this stage exists." + }, + "location": { + "$ref": "#/components/schemas/ConstructionLocation" + }, + "source": { + "type": "string", + "description": "The private directory that holds the stage." + }, + "namespace": { + "type": "string", + "description": "The namespace whose `discarded/` quarantine receives it." + } + }, + "required": [ + "name", + "kind", + "activity_id", + "session_id", + "evidence", + "fences", + "location", + "source", + "namespace" + ], + "description": "A reviewed stage, frozen into the discard receipt." + }, + "StageEvidence": { + "type": "object", + "additionalProperties": false, + "properties": { + "device": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "inode": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "size": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "modified_ns": { + "type": "integer", + "format": "int64", + "description": "Modification time in nanoseconds since the Unix epoch." + }, + "sha256": { + "type": "string", + "description": "Lowercase hex SHA-256 of the stage bytes." + } + }, + "required": [ + "device", + "inode", + "size", + "modified_ns", + "sha256" + ], + "description": "Native identity and contents of one stage at review." + }, + "ConstructionDiscardStatus": { + "oneOf": [ + { + "type": "string", + "const": "intent", + "description": "Recorded before any filesystem change; the plan is frozen." + }, + { + "type": "string", + "const": "pending", + "description": "Moved into the quarantine, unlink not yet done (`discard pending`)." + }, + { + "type": "string", + "const": "completed", + "description": "The stage is gone." + }, + { + "type": "string", + "const": "changed", + "description": "A different file holds the name; nothing was deleted." + } + ] + }, + "ConstructionDiscardSelection": { + "type": "object", + "additionalProperties": false, + "properties": { + "stage": { + "type": [ + "string", + "null" + ], + "description": "The exact stage name, from the construction listing." + }, + "activity_id": { + "type": [ + "string", + "null" + ], + "description": "An activity with exactly one stage." + } + } + }, + "Data_ConstructionDiscardReview": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/ConstructionDiscardReview" + } + }, + "required": [ + "data" + ] + }, + "ConstructionDiscardReview": { + "type": "object", + "properties": { + "session_id": { + "type": "string" + }, + "session_sequence": { + "type": "integer", + "format": "int64" + }, + "stage": { + "$ref": "#/components/schemas/ConstructionStage" + }, + "confirmation": { + "type": "string" + }, + "warning": { + "type": "string" + } + }, + "required": [ + "session_id", + "session_sequence", + "stage", + "confirmation", + "warning" + ] + }, + "ConstructionDiscardConfirmation": { + "type": "object", + "additionalProperties": false, + "properties": { + "stage": { + "type": "string", + "description": "The reviewed stage name; one stage per confirmation." + }, + "confirmation": { + "type": "string" + }, + "request_id": { + "type": "string" + } + }, + "required": [ + "stage", + "confirmation", + "request_id" + ] + }, + "Data_ConstructionDiscardReceipt": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/ConstructionDiscardReceipt" + } + }, + "required": [ + "data" + ] + }, "RewindSelection": { "type": "object", "additionalProperties": false, @@ -26766,6 +27101,234 @@ } } }, + "/api/v1/sessions/{sessionID}/rewind/constructions": { + "get": { + "operationId": "v1.session.constructionInventory", + "summary": "List unpublished construction stages and discards that still owe an unlink (`discard pending`); listing grants no discard authority", + "tags": [ + "session" + ], + "parameters": [ + { + "name": "sessionID", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Data_ConstructionInventory" + } + } + } + }, + "default": { + "description": "Tagged error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + } + }, + "/api/v1/sessions/{sessionID}/rewind/constructions/discard/review": { + "post": { + "operationId": "v1.session.constructionDiscardReview", + "summary": "Owner only: review one construction stage read-only and return its confirmation fingerprint", + "tags": [ + "session" + ], + "parameters": [ + { + "name": "sessionID", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Data_ConstructionDiscardReview" + } + } + } + }, + "403": { + "description": "ForbiddenError: delegated, browser, peer or model callers", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "default": { + "description": "Tagged error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConstructionDiscardSelection" + } + } + } + } + } + }, + "/api/v1/sessions/{sessionID}/rewind/constructions/discard/confirm": { + "post": { + "operationId": "v1.session.constructionDiscardConfirm", + "summary": "Owner only: discard one fingerprint-confirmed construction stage after fencing its activity; a repeated request ID resumes or returns its receipt", + "tags": [ + "session" + ], + "parameters": [ + { + "name": "sessionID", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Data_ConstructionDiscardReceipt" + } + } + } + }, + "403": { + "description": "ForbiddenError: delegated, browser, peer or model callers", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + }, + "default": { + "description": "Tagged error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConstructionDiscardConfirmation" + } + } + } + } + } + }, + "/api/v1/sessions/{sessionID}/rewind/constructions/discard/requests/{requestID}": { + "get": { + "operationId": "v1.session.constructionDiscardLookup", + "summary": "Look up a construction discard receipt without acting", + "tags": [ + "session" + ], + "parameters": [ + { + "name": "sessionID", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "requestID", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Data_ConstructionDiscardReceipt" + } + } + } + }, + "default": { + "description": "Tagged error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorBody" + } + } + } + } + } + } + }, "/api/v1/sessions/{sessionID}/rewind/restores/{activityID}/acknowledge": { "post": { "operationId": "v1.session.snapshotRestoreAcknowledge", diff --git a/sdk/typescript/src/generated/operations.ts b/sdk/typescript/src/generated/operations.ts index 7577ab53..d23f677d 100644 --- a/sdk/typescript/src/generated/operations.ts +++ b/sdk/typescript/src/generated/operations.ts @@ -1215,6 +1215,30 @@ export interface Operations { body: undefined; response: void; }; + "v1.session.constructionDiscardConfirm": { + path: { sessionID: string }; + query: Record; + body: S.ConstructionDiscardConfirmation; + response: S.ConstructionDiscardReceipt; + }; + "v1.session.constructionDiscardLookup": { + path: { sessionID: string; requestID: string }; + query: Record; + body: undefined; + response: S.ConstructionDiscardReceipt; + }; + "v1.session.constructionDiscardReview": { + path: { sessionID: string }; + query: Record; + body: S.ConstructionDiscardSelection; + response: S.ConstructionDiscardReview; + }; + "v1.session.constructionInventory": { + path: { sessionID: string }; + query: Record; + body: undefined; + response: S.ConstructionInventory; + }; "v1.session.context": { path: { sessionID: string }; query: { @@ -4136,6 +4160,54 @@ export const operations = { unwrap: false, stream: false, }, + "v1.session.constructionDiscardConfirm": { + tag: "session", + name: "constructionDiscardConfirm", + method: "POST", + path: "/api/v1/sessions/{sessionID}/rewind/constructions/discard/confirm", + pathParams: ["sessionID"], + query: [], + body: "required", + located: false, + unwrap: true, + stream: false, + }, + "v1.session.constructionDiscardLookup": { + tag: "session", + name: "constructionDiscardLookup", + method: "GET", + path: "/api/v1/sessions/{sessionID}/rewind/constructions/discard/requests/{requestID}", + pathParams: ["sessionID", "requestID"], + query: [], + body: "none", + located: false, + unwrap: true, + stream: false, + }, + "v1.session.constructionDiscardReview": { + tag: "session", + name: "constructionDiscardReview", + method: "POST", + path: "/api/v1/sessions/{sessionID}/rewind/constructions/discard/review", + pathParams: ["sessionID"], + query: [], + body: "required", + located: false, + unwrap: true, + stream: false, + }, + "v1.session.constructionInventory": { + tag: "session", + name: "constructionInventory", + method: "GET", + path: "/api/v1/sessions/{sessionID}/rewind/constructions", + pathParams: ["sessionID"], + query: [], + body: "none", + located: false, + unwrap: true, + stream: false, + }, "v1.session.context": { tag: "session", name: "context", @@ -6246,6 +6318,18 @@ export function createGroups(caller: Caller) { /** Revoke this Session's native grant (`POST /api/v1/sessions/{sessionID}/computer/stop`) */ computerStop: (sessionID: string, options?: RequestOptions): Promise => caller.call("v1.session.computerStop", { path: { sessionID } }, options), + /** Owner only: discard one fingerprint-confirmed construction stage after fencing its activity; a repeated request ID resumes or returns its receipt (`POST /api/v1/sessions/{sessionID}/rewind/constructions/discard/confirm`) */ + constructionDiscardConfirm: (sessionID: string, body: Operations["v1.session.constructionDiscardConfirm"]["body"], options?: RequestOptions): Promise => + caller.call("v1.session.constructionDiscardConfirm", { path: { sessionID }, body }, options), + /** Look up a construction discard receipt without acting (`GET /api/v1/sessions/{sessionID}/rewind/constructions/discard/requests/{requestID}`) */ + constructionDiscardLookup: (sessionID: string, requestID: string, options?: RequestOptions): Promise => + caller.call("v1.session.constructionDiscardLookup", { path: { sessionID, requestID } }, options), + /** Owner only: review one construction stage read-only and return its confirmation fingerprint (`POST /api/v1/sessions/{sessionID}/rewind/constructions/discard/review`) */ + constructionDiscardReview: (sessionID: string, body: Operations["v1.session.constructionDiscardReview"]["body"], options?: RequestOptions): Promise => + caller.call("v1.session.constructionDiscardReview", { path: { sessionID }, body }, options), + /** List unpublished construction stages and discards that still owe an unlink (`discard pending`); listing grants no discard authority (`GET /api/v1/sessions/{sessionID}/rewind/constructions`) */ + constructionInventory: (sessionID: string, options?: RequestOptions): Promise => + caller.call("v1.session.constructionInventory", { path: { sessionID } }, options), /** Inspect recorded context and estimates. Use include_content to return baseline, summary and task text. (`GET /api/v1/sessions/{sessionID}/context`) */ context: (sessionID: string, query?: Operations["v1.session.context"]["query"], options?: RequestOptions): Promise => caller.call("v1.session.context", { path: { sessionID }, query }, options), diff --git a/sdk/typescript/src/generated/types.ts b/sdk/typescript/src/generated/types.ts index e833f4de..dcb8aff1 100644 --- a/sdk/typescript/src/generated/types.ts +++ b/sdk/typescript/src/generated/types.ts @@ -697,6 +697,79 @@ export type Configured = { source: string; }; +export type ConstructionDiscardConfirmation = { + /** The reviewed stage name; one stage per confirmation. */ + stage: string; + confirmation: string; + request_id: string; +}; + +/** The audit receipt of one request, as last recorded. */ +export type ConstructionDiscardReceipt = { + request_id: string; + session_id: string; + confirmation: string; + stage: ConstructionStage; + actor: string; + recorded_ms: number; + status: ConstructionDiscardStatus; + detail?: string | null; +}; + +export type ConstructionDiscardReview = { + session_id: string; + session_sequence: number; + stage: ConstructionStage; + confirmation: string; + warning: string; +}; + +export type ConstructionDiscardSelection = { + /** The exact stage name, from the construction listing. */ + stage?: string | null; + /** An activity with exactly one stage. */ + activity_id?: string | null; +}; + +export type ConstructionDiscardStatus = "intent" | "pending" | "completed" | "changed"; + +export type ConstructionInventory = { + stages: ConstructionStageEntry[]; + /** Requests whose stage is not unlinked yet (`discard pending`). */ + pending: ConstructionDiscardReceipt[]; +}; + +export type ConstructionLocation = "present" | "removed"; + +/** A reviewed stage, frozen into the discard receipt. */ +export type ConstructionStage = { + name: string; + kind: ConstructionStageKind; + activity_id: string; + session_id: string; + worktree_id?: string | null; + journal_id?: string | null; + evidence: StageEvidence; + /** Operations that refuse while this stage exists. */ + fences: string[]; + location: ConstructionLocation; + /** The private directory that holds the stage. */ + source: string; + /** The namespace whose `discarded/` quarantine receives it. */ + namespace: string; +}; + +/** One listed stage. Listing grants no discard authority. */ +export type ConstructionStageEntry = { + name: string; + kind: ConstructionStageKind; + /** The constructing activity; absent when the name has no derivable owner. */ + activity_id?: string | null; + location: ConstructionLocation; +}; + +export type ConstructionStageKind = "checkout_claim" | "checkout_acknowledgement" | "cancellation_record"; + /** One part of a message. Tool results travel in user messages. */ export type Content = { text: string; @@ -1032,6 +1105,18 @@ export type Data_ComputerStatus = { data: ComputerStatus; }; +export type Data_ConstructionDiscardReceipt = { + data: ConstructionDiscardReceipt; +}; + +export type Data_ConstructionDiscardReview = { + data: ConstructionDiscardReview; +}; + +export type Data_ConstructionInventory = { + data: ConstructionInventory; +}; + export type Data_CreatedTeam = { data: CreatedTeam; }; @@ -5266,6 +5351,17 @@ export type SpawnedMember = { branch?: string | null; }; +/** Native identity and contents of one stage at review. */ +export type StageEvidence = { + device: number; + inode: number; + size: number; + /** Modification time in nanoseconds since the Unix epoch. */ + modified_ns: number; + /** Lowercase hex SHA-256 of the stage bytes. */ + sha256: string; +}; + export type StartBody = { /** The owner Session: agents become its children and run under its Mode. */ session_id: string; From ab3904c181fc3217ddb22d58c82b58103665faef Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 12:00:13 -0400 Subject: [PATCH 3/8] Add recovery-discard CLI, doctor check and TUI command hints cyber sessions recovery-discard lists, reviews and confirms one stage; recovery-discard-request looks a receipt up. sessions recovery, the TUI recovery panels and cyber doctor show construction evidence and discard pending requests with the exact command; the TUI has no discard action. --- .../src/commands/discard_recovery.rs | 387 ++++++++++++++++++ crates/cyber-cli/src/commands/doctor.rs | 63 +++ crates/cyber-cli/src/commands/mod.rs | 1 + .../src/commands/preparation_recovery.rs | 19 +- crates/cyber-cli/src/commands/recovery.rs | 1 + crates/cyber-cli/src/commands/sessions.rs | 14 +- .../src/preparation_recovery_tests.rs | 7 +- .../src/preparation_recovery_view.rs | 8 +- crates/cyber-tui/src/recovery.rs | 10 +- crates/cyber-tui/src/recovery_client.rs | 12 +- crates/cyber-tui/src/recovery_tests.rs | 99 ++++- crates/cyber-tui/src/recovery_view.rs | 27 +- docs/cli.md | 34 ++ 13 files changed, 646 insertions(+), 36 deletions(-) create mode 100644 crates/cyber-cli/src/commands/discard_recovery.rs diff --git a/crates/cyber-cli/src/commands/discard_recovery.rs b/crates/cyber-cli/src/commands/discard_recovery.rs new file mode 100644 index 00000000..e3cc5053 --- /dev/null +++ b/crates/cyber-cli/src/commands/discard_recovery.rs @@ -0,0 +1,387 @@ +//! `cyber sessions recovery-discard`: the local owner's two-step discard of one +//! unpublished construction stage. Listing and review never change anything; a +//! confirmation names the reviewed stage, its fingerprint and a stable request ID. +use super::{ + recovery::{data, fingerprint, request_id}, + sessions::{api, clean, encode, session_id}, +}; +use crate::{cli::GlobalArgs, error::CliError, output}; +use clap::Args; +use cyber_client::Client; +use cyber_server::runtime::{ + ConstructionDiscardConfirmation, ConstructionDiscardReceipt, ConstructionDiscardReview, + ConstructionDiscardSelection, ConstructionDiscardStatus, ConstructionInventory, + ConstructionLocation, ConstructionStageKind, +}; +use serde_json::json; + +#[derive(Debug, Args)] +pub struct DiscardArgs { + /// Session ID, exact title or unique ID prefix. + session: String, + /// Exact construction stage name from the listing; omit to list stages and pending discards. + #[arg(value_parser = stage_name, conflicts_with = "activity")] + stage: Option, + /// Review the only construction stage of this snapshot activity instead of naming it. + #[arg(long, value_parser = activity_id)] + activity: Option, + /// Discard only the reviewed stage; requires the stage name and --request-id. + #[arg(long, value_parser = fingerprint, requires_all = ["stage", "request_id"])] + confirm: Option, + /// Stable request identity; repeat it to resume after an interruption or a lost reply. + #[arg(long, value_parser = request_id, requires = "confirm")] + request_id: Option, +} + +#[derive(Debug, Args)] +pub struct DiscardRequestArgs { + /// Session ID, exact title or unique ID prefix. + session: String, + /// Exact request ID used to confirm the discard. + #[arg(value_parser = request_id)] + request_id: String, +} + +fn stage_name(value: &str) -> Result { + if cyber_core::construction_discard::valid_component(value) + && ["preparing_", "ack_preparing_", "tmp_"] + .iter() + .any(|prefix| value.starts_with(prefix)) + { + Ok(value.into()) + } else { + Err("expected an exact construction stage name from the recovery-discard listing".into()) + } +} + +fn activity_id(value: &str) -> Result { + if value.starts_with("op_") + && value.len() <= 256 + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') + { + Ok(value.into()) + } else { + Err("expected an exact snapshot activity ID".into()) + } +} + +/// The exact command that reviews `stage`, quoted for a shell. +pub(super) fn command(session: &str, stage: &str) -> String { + format!( + "cyber sessions recovery-discard {} {}", + shell_words::quote(session), + shell_words::quote(stage) + ) +} + +fn hint(session: &str, request: &str) -> String { + format!( + "Look up or resume it with cyber sessions recovery-discard-request {} {}, or repeat the same confirmation; do not choose a new request ID", + shell_words::quote(session), + shell_words::quote(request) + ) +} + +pub async fn run(client: &Client, args: DiscardArgs, global: &GlobalArgs) -> Result<(), CliError> { + let session = session_id(client, &args.session).await?; + let base = format!("/sessions/{}/rewind/constructions", encode(&session)); + if args.stage.is_none() && args.activity.is_none() { + let inventory: ConstructionInventory = data(client.get(&base).await.map_err(api)?)?; + return list_output(&inventory, &session, global); + } + if let (Some(confirmation), Some(stage)) = (args.confirm, &args.stage) { + let request_id = args + .request_id + .ok_or_else(|| CliError::usage("Discard confirmation requires --request-id"))?; + let lookup = hint(&session, &request_id); + let body = ConstructionDiscardConfirmation { + stage: stage.clone(), + confirmation, + request_id, + }; + let reply = client + .post(&format!("{base}/discard/confirm"), json!(&body)) + .await + .map_err(|error| api(error).with_hint(&lookup))?; + let receipt = receipt_response(reply, &session, &body)?; + return receipt_output(&receipt, global); + } + let selection = ConstructionDiscardSelection { + stage: args.stage, + activity_id: args.activity, + }; + let review: ConstructionDiscardReview = data( + client + .post(&format!("{base}/discard/review"), json!(&selection)) + .await + .map_err(api)?, + )?; + if review.session_id != session + || selection + .stage + .as_ref() + .is_some_and(|stage| *stage != review.stage.name) + { + return Err(CliError::runtime( + "Discard review does not match the selected Session and stage", + )); + } + review_output(&review, global) +} + +pub async fn request( + client: &Client, + args: DiscardRequestArgs, + global: &GlobalArgs, +) -> Result<(), CliError> { + let session = session_id(client, &args.session).await?; + let path = format!( + "/sessions/{}/rewind/constructions/discard/requests/{}", + encode(&session), + encode(&args.request_id) + ); + let receipt: ConstructionDiscardReceipt = data(client.get(&path).await.map_err(api)?)?; + if receipt.session_id != session || receipt.request_id != args.request_id { + return Err(CliError::runtime( + "Discard receipt does not match the selected Session and request", + )); + } + receipt_output(&receipt, global) +} + +fn receipt_response( + reply: serde_json::Value, + session: &str, + body: &ConstructionDiscardConfirmation, +) -> Result { + let receipt: ConstructionDiscardReceipt = data(reply)?; + if receipt.session_id != session + || receipt.request_id != body.request_id + || receipt.confirmation != body.confirmation + || receipt.stage.name != body.stage + { + return Err(CliError::runtime( + "Discard receipt differs from the confirmed stage, fingerprint or request", + ) + .with_hint(hint(session, &body.request_id))); + } + Ok(receipt) +} + +fn kind_name(kind: ConstructionStageKind) -> &'static str { + match kind { + ConstructionStageKind::CheckoutClaim => "checkout claim stage", + ConstructionStageKind::CheckoutAcknowledgement => "checkout acknowledgement stage", + ConstructionStageKind::CancellationRecord => "cancellation-record stage", + } +} + +fn location_note(location: ConstructionLocation) -> &'static str { + match location { + ConstructionLocation::Present => "", + ConstructionLocation::Removed => " · Location removed", + } +} + +fn list_output( + inventory: &ConstructionInventory, + session: &str, + global: &GlobalArgs, +) -> Result<(), CliError> { + if output::is_json(global.format) { + return output::json(inventory); + } + if inventory.stages.is_empty() && inventory.pending.is_empty() { + println!("No construction evidence."); + } + for stage in &inventory.stages { + println!( + "{} · {} · owner {}{}", + clean(&stage.name), + kind_name(stage.kind), + stage + .activity_id + .as_deref() + .map(clean) + .unwrap_or_else(|| "unknown (refused)".into()), + location_note(stage.location) + ); + println!(" review: {}", command(session, &stage.name)); + } + for receipt in &inventory.pending { + println!( + "discard pending: {} · request {:?} · {}", + clean(&receipt.stage.name), + receipt.request_id, + pending_note(receipt) + ); + } + println!( + "Listing is not discard authority. Review one stage; a live constructor, a published record or a busy Session refuses." + ); + Ok(()) +} + +fn pending_note(receipt: &ConstructionDiscardReceipt) -> String { + match (&receipt.status, &receipt.detail) { + (ConstructionDiscardStatus::Intent, _) => { + "interrupted before completion; repeat the confirmation with the same request ID".into() + } + (_, Some(detail)) => format!("unlink retried by maintenance: {}", clean(detail)), + _ => "unlink retried by maintenance".into(), + } +} + +fn review_output(review: &ConstructionDiscardReview, global: &GlobalArgs) -> Result<(), CliError> { + if output::is_json(global.format) { + return output::json(review); + } + let stage = &review.stage; + println!("Construction discard review: {}", clean(&stage.name)); + println!( + "Kind: {} · owner activity {} · Session {} (sequence {}){}", + kind_name(stage.kind), + clean(&stage.activity_id), + clean(&review.session_id), + review.session_sequence, + location_note(stage.location) + ); + println!( + "Identity: device {} inode {} · {} bytes · modified {} ns · sha256 {}", + stage.evidence.device, + stage.evidence.inode, + stage.evidence.size, + stage.evidence.modified_ns, + clean(&stage.evidence.sha256) + ); + println!("Fences: {}", clean(&stage.fences.join("; "))); + println!("{}", clean(&review.warning)); + println!( + "Nothing changed. To discard this stage, repeat with --confirm {} --request-id ", + clean(&review.confirmation) + ); + Ok(()) +} + +fn receipt_output( + receipt: &ConstructionDiscardReceipt, + global: &GlobalArgs, +) -> Result<(), CliError> { + if output::is_json(global.format) { + return output::json(receipt); + } + let status = match receipt.status { + ConstructionDiscardStatus::Completed => "discarded", + ConstructionDiscardStatus::Pending => "discard pending (unlink retried by maintenance)", + ConstructionDiscardStatus::Intent => { + "discard pending (interrupted; repeat the confirmation with the same request ID)" + } + ConstructionDiscardStatus::Changed => "not discarded: the stage changed", + }; + println!( + "{}: {} · request {:?} · by {}", + status, + clean(&receipt.stage.name), + receipt.request_id, + clean(&receipt.actor) + ); + if let Some(detail) = &receipt.detail { + println!("{}", clean(detail)); + } + println!( + "Restore journals, payload images and published records are untouched; the managed worktree was not removed." + ); + Ok(()) +} + +/// Best-effort text pointer from `sessions recovery` to construction evidence and +/// pending discards. The journal listing already succeeded, so a failed lookup is +/// reported on stderr and never fails the command. +pub(super) async fn construction_hint(client: &Client, session: &str) { + let path = format!("/sessions/{}/rewind/constructions", encode(session)); + let inventory: Result = match client.get(&path).await { + Ok(reply) => data(reply), + Err(error) => Err(api(error)), + }; + match inventory { + Ok(inventory) => { + for stage in &inventory.stages { + println!( + "Construction evidence {} ({}): discard it with {}", + clean(&stage.name), + kind_name(stage.kind), + command(session, &stage.name) + ); + } + for receipt in &inventory.pending { + println!( + "discard pending: {} · request {:?} · {}", + clean(&receipt.stage.name), + receipt.request_id, + pending_note(receipt) + ); + } + } + Err(error) => eprintln!( + "Construction evidence listing unavailable: {}", + clean(&error.message) + ), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use clap::Parser; + + #[test] + fn unreviewed_or_malformed_discards_fail_before_startup() { + let hash = "a".repeat(64); + let stage = "preparing_10_op_fixture_01JABCDEFGHJKMNPQRSTVWXYZ0"; + for tail in [ + vec!["--confirm", &hash, "--request-id", "one"], + vec![stage, "--confirm", &hash], + vec![stage, "--request-id", "one"], + vec![stage, "--confirm", "yes", "--request-id", "one"], + vec!["../preparing_x"], + vec!["intent.json"], + vec![stage, "--activity", "op_one"], + vec![ + "--activity", + "op_one", + "--confirm", + &hash, + "--request-id", + "one", + ], + ] { + let mut args = vec!["cyber", "sessions", "recovery-discard", "ses_one"]; + args.extend(tail); + assert!(crate::cli::Cli::try_parse_from(&args).is_err(), "{args:?}"); + } + for tail in [ + vec![], + vec![stage], + vec!["--activity", "op_one"], + vec![stage, "--confirm", &hash, "--request-id", "one / #?%"], + ] { + let mut args = vec!["cyber", "sessions", "recovery-discard", "ses_one"]; + args.extend(tail); + crate::cli::Cli::try_parse_from(args).unwrap(); + } + crate::cli::Cli::try_parse_from([ + "cyber", + "sessions", + "recovery-discard-request", + "ses_one", + "one", + ]) + .unwrap(); + assert_eq!( + command("ses_one", stage), + format!("cyber sessions recovery-discard ses_one {stage}") + ); + } +} diff --git a/crates/cyber-cli/src/commands/doctor.rs b/crates/cyber-cli/src/commands/doctor.rs index 51cb1f8b..1fe26462 100644 --- a/crates/cyber-cli/src/commands/doctor.rs +++ b/crates/cyber-cli/src/commands/doctor.rs @@ -48,6 +48,7 @@ pub fn run(ctx: &Context, global: &GlobalArgs) -> Result<(), CliError> { checks.extend(lsp_checks(ctx, &config)); checks.extend(rt.block_on(catalog_checks(ctx, &config))); checks.push(database(ctx)); + checks.push(construction_discards(ctx)); checks.push(sandbox()); checks.push(tool("git", &["--version"], Status::Fail)); checks.push(tool("rg", &["--version"], Status::Warn)); @@ -355,6 +356,68 @@ fn database(ctx: &Context) -> Check { } } +/// Owner-confirmed construction discards (`snapshots-checkpoints` → Owner-only discard +/// of construction evidence): receipts are kept forever; a stage moved into its +/// quarantine but not yet unlinked is `discard pending` until maintenance removes it. +fn construction_discards(ctx: &Context) -> Check { + const NAME: &str = "construction discards"; + let DatabaseLocation::File(path) = ctx.database() else { + return check(NAME, Status::Pass, "in memory"); + }; + if !path.exists() { + return check(NAME, Status::Pass, "none"); + } + match discard_receipts(&path) { + Ok(receipts) => discard_check(&receipts), + Err(error) => check(NAME, Status::Warn, format!("unavailable: {error}")), + } +} + +fn discard_receipts( + path: &std::path::Path, +) -> rusqlite::Result> { + let db = + rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?; + let mut query = db.prepare( + "SELECT data FROM event e WHERE type=?1 AND NOT EXISTS(SELECT 1 FROM event n \ + WHERE n.aggregate_id=e.aggregate_id AND n.type=e.type \ + AND json_extract(n.data,'$.request_id')=json_extract(e.data,'$.request_id') AND n.seq>e.seq) \ + ORDER BY aggregate_id,seq LIMIT 4097", + )?; + let rows = query.query_map( + [cyber_server::runtime::construction_discard::DISCARDED], + |row| row.get::<_, String>(0), + )?; + let mut receipts = vec![]; + for row in rows { + if let Ok(receipt) = serde_json::from_str(&row?) { + receipts.push(receipt); + } + } + Ok(receipts) +} + +fn discard_check(receipts: &[cyber_server::runtime::ConstructionDiscardReceipt]) -> Check { + let pending: Vec = receipts + .iter() + .filter(|receipt| receipt.pending()) + .map(|receipt| { + format!( + "discard pending: {} (Session {}, request {:?})", + receipt.stage.name, receipt.session_id, receipt.request_id + ) + }) + .collect(); + if pending.is_empty() { + return check( + "construction discards", + Status::Pass, + format!("{} receipt(s), none pending", receipts.len()), + ); + } + check("construction discards", Status::Warn, pending.join("; ")) +} + fn sandbox() -> Check { if cyber_sandbox::available() { return check("sandbox", Status::Pass, "OS enforcement available"); diff --git a/crates/cyber-cli/src/commands/mod.rs b/crates/cyber-cli/src/commands/mod.rs index ed3edab4..7dcc69d2 100644 --- a/crates/cyber-cli/src/commands/mod.rs +++ b/crates/cyber-cli/src/commands/mod.rs @@ -8,6 +8,7 @@ pub mod collab; pub mod computer; pub mod db; pub mod debug; +mod discard_recovery; pub mod doctor; pub mod eval; pub mod exec; diff --git a/crates/cyber-cli/src/commands/preparation_recovery.rs b/crates/cyber-cli/src/commands/preparation_recovery.rs index c01242cd..e35c69d6 100644 --- a/crates/cyber-cli/src/commands/preparation_recovery.rs +++ b/crates/cyber-cli/src/commands/preparation_recovery.rs @@ -131,7 +131,7 @@ pub async fn run( let base = format!("/sessions/{}/rewind/preparations", encode(&session)); let Some(activity) = args.activity else { let list: Vec = data(client.get(&base).await.map_err(api)?)?; - return list_output(&list, global); + return list_output(&list, &session, global); }; let base = format!("{base}/{}", encode(&activity)); if let Some(confirmation) = args.confirm { @@ -190,7 +190,11 @@ pub async fn request( .map_err(|error| error.with_hint(&lookup))?; receipt_output(&receipt, global, args.acknowledge) } -fn list_output(list: &[SnapshotPreparation], global: &GlobalArgs) -> Result<(), CliError> { +fn list_output( + list: &[SnapshotPreparation], + session: &str, + global: &GlobalArgs, +) -> Result<(), CliError> { if output::is_json(global.format) { return output::json(&list); } @@ -205,7 +209,7 @@ fn list_output(list: &[SnapshotPreparation], global: &GlobalArgs) -> Result<(), item.lifetime_available ); for stage in &item.checkout_constructions { - println!(" {}", construction_line(stage)); + println!(" {}", construction_line(session, stage)); } } println!( @@ -214,10 +218,11 @@ fn list_output(list: &[SnapshotPreparation], global: &GlobalArgs) -> Result<(), Ok(()) } /// One unresolved checkout construction stage, with what the operator can do. -pub(super) fn construction_line(stage: &str) -> String { +pub(super) fn construction_line(session: &str, stage: &str) -> String { format!( - "unresolved checkout construction evidence {}: the worker died before publishing its claim or acknowledgement. Cancelling this preparation restores prompt admission; the stage stays fenced (worktree removal refuses) until construction recovery is available.", - clean(stage) + "unresolved checkout construction evidence {}: the worker died before publishing its claim or acknowledgement. Cancelling this preparation restores prompt admission; the stage stays fenced (worktree removal refuses) until the owner discards it with {}", + clean(stage), + super::discard_recovery::command(session, stage) ) } /// Best-effort text-only pointer from journal recovery to unresolved @@ -246,7 +251,7 @@ fn print_unresolved(list: &[SnapshotPreparation], session: &str) { shell_words::quote(session) ); for stage in list.iter().flat_map(|item| &item.checkout_constructions) { - println!(" {}", construction_line(stage)); + println!(" {}", construction_line(session, stage)); } } fn review_output(review: &SnapshotPreparationReview, global: &GlobalArgs) -> Result<(), CliError> { diff --git a/crates/cyber-cli/src/commands/recovery.rs b/crates/cyber-cli/src/commands/recovery.rs index 3a4b0978..a226dc5a 100644 --- a/crates/cyber-cli/src/commands/recovery.rs +++ b/crates/cyber-cli/src/commands/recovery.rs @@ -154,6 +154,7 @@ pub async fn run(client: &Client, args: RecoveryArgs, global: &GlobalArgs) -> Re list(&journals, global)?; if !output::is_json(global.format) { super::preparation_recovery::unresolved_hint(client, &id).await; + super::discard_recovery::construction_hint(client, &id).await; } return Ok(()); }; diff --git a/crates/cyber-cli/src/commands/sessions.rs b/crates/cyber-cli/src/commands/sessions.rs index 19df637d..ae341a69 100644 --- a/crates/cyber-cli/src/commands/sessions.rs +++ b/crates/cyber-cli/src/commands/sessions.rs @@ -84,6 +84,10 @@ pub enum SessionsCmd { RecoveryPreparation(super::preparation_recovery::PreparationArgs), /// Look up a committed preparation cancellation; optionally reconcile its native metadata. RecoveryPreparationRequest(super::preparation_recovery::RequestArgs), + /// List, review or discard one unpublished construction stage (local owner only). + RecoveryDiscard(super::discard_recovery::DiscardArgs), + /// Look up a construction discard request by its request ID, without acting. + RecoveryDiscardRequest(super::discard_recovery::DiscardRequestArgs), /// Set or remove a branch label. Label { /// ID, exact title or unique ID prefix. @@ -210,7 +214,9 @@ async fn dispatch(client: &Client, cmd: SessionsCmd, global: &GlobalArgs) -> Res recovery @ (SessionsCmd::Recovery(_) | SessionsCmd::RecoveryRequest(_) | SessionsCmd::RecoveryPreparation(_) - | SessionsCmd::RecoveryPreparationRequest(_)) => { + | SessionsCmd::RecoveryPreparationRequest(_) + | SessionsCmd::RecoveryDiscard(_) + | SessionsCmd::RecoveryDiscardRequest(_)) => { dispatch_recovery(client, recovery, global).await } SessionsCmd::Other(_) => unreachable!("handled before connecting"), @@ -232,6 +238,12 @@ async fn dispatch_recovery( SessionsCmd::RecoveryPreparationRequest(args) => { super::preparation_recovery::request(client, args, global).await } + SessionsCmd::RecoveryDiscard(args) => { + super::discard_recovery::run(client, args, global).await + } + SessionsCmd::RecoveryDiscardRequest(args) => { + super::discard_recovery::request(client, args, global).await + } _ => unreachable!("only recovery commands are dispatched here"), } } diff --git a/crates/cyber-tui/src/preparation_recovery_tests.rs b/crates/cyber-tui/src/preparation_recovery_tests.rs index c378efef..3c738ecf 100644 --- a/crates/cyber-tui/src/preparation_recovery_tests.rs +++ b/crates/cyber-tui/src/preparation_recovery_tests.rs @@ -61,7 +61,7 @@ fn open(app: &mut App) { &mut Default::default(), req, Ok(rewind::Reply::Recovery(Box::new( - recovery::Reply::Journals(vec![]), + recovery::Reply::Journals(vec![], Default::default()), ))), ); let req = request(app.recovery_key(KeyCode::Char('p'))); @@ -263,7 +263,7 @@ fn interrupted_checkout_construction_is_listed_as_unresolved_fenced_evidence() { &mut Default::default(), req, Ok(rewind::Reply::Recovery(Box::new( - recovery::Reply::Journals(vec![]), + recovery::Reply::Journals(vec![], Default::default()), ))), ); let journals = recovery::lines(&app); @@ -290,7 +290,8 @@ fn interrupted_checkout_construction_is_listed_as_unresolved_fenced_evidence() { assert!( shown.iter().any(|line| line.contains(&stage) && line.contains("Unresolved checkout construction evidence") - && line.contains("worktree removal refuses")), + && line.contains("worktree removal refuses") + && line.contains(&format!("cyber sessions recovery-discard ses_one {stage}"))), "{shown:#?}" ); assert_eq!(app.composer.text(), "owner draft"); diff --git a/crates/cyber-tui/src/preparation_recovery_view.rs b/crates/cyber-tui/src/preparation_recovery_view.rs index 0724bd4e..09a6e18c 100644 --- a/crates/cyber-tui/src/preparation_recovery_view.rs +++ b/crates/cyber-tui/src/preparation_recovery_view.rs @@ -22,13 +22,13 @@ pub fn lines(app: &App) -> Vec> { ))); } match view.phase { - Phase::Candidates => candidates(view, &mut lines), + Phase::Candidates => candidates(&app.session.id, view, &mut lines), Phase::Review => review(view, &mut lines), Phase::Outcome => outcome(view, &mut lines), } lines } -fn candidates(view: &View, lines: &mut Vec>) { +fn candidates(session: &str, view: &View, lines: &mut Vec>) { lines.push(Line::from( "↑/↓ select · Enter discovers a committed receipt before review · R reloads", )); @@ -53,7 +53,9 @@ fn candidates(view: &View, lines: &mut Vec>) { ))); for stage in &candidate.checkout_constructions { lines.push(Line::from(format!( - " Unresolved checkout construction evidence {stage:?}: cancelling restores prompt admission; the stage stays fenced and worktree removal refuses until construction recovery exists." + " Unresolved checkout construction evidence {stage:?}: cancelling restores prompt admission; the stage stays fenced and worktree removal refuses until the owner discards it with: cyber sessions recovery-discard {} {}", + crate::messaging::clean(session), + crate::messaging::clean(stage) ))); } } diff --git a/crates/cyber-tui/src/recovery.rs b/crates/cyber-tui/src/recovery.rs index 60dbe7b2..27cf9053 100644 --- a/crates/cyber-tui/src/recovery.rs +++ b/crates/cyber-tui/src/recovery.rs @@ -35,6 +35,8 @@ pub struct View { pub preparation: preparation::View, pub discovered: bool, pub journals: Vec, + /// Construction evidence and pending discards; the TUI only shows the CLI command. + pub constructions: cyber_server::runtime::ConstructionInventory, pub requests: Vec, pub selected: usize, pub journal: Option, @@ -55,7 +57,10 @@ pub enum Command { #[derive(Debug, Clone)] pub enum Reply { Preparation(Box), - Journals(Vec), + Journals( + Vec, + Box, + ), Requests(Vec), Review(Box), Outcome(Box), @@ -299,8 +304,9 @@ fn accept(view: &mut View, request: &rewind::Request, reply: Reply) -> Result<() return Err("Foreign recovery command".into()); }; match (command, reply) { - (Command::List, Reply::Journals(journals)) => { + (Command::List, Reply::Journals(journals, constructions)) => { view.journals = journals; + view.constructions = *constructions; view.phase = Phase::Journals; view.selected = 0; } diff --git a/crates/cyber-tui/src/recovery_client.rs b/crates/cyber-tui/src/recovery_client.rs index d62d2f0d..17de539b 100644 --- a/crates/cyber-tui/src/recovery_client.rs +++ b/crates/cyber-tui/src/recovery_client.rs @@ -47,7 +47,17 @@ pub async fn perform( if journals.len() > 4096 { return Err("Recovery journal limit exceeded".into()); } - Ok(Reply::Journals(journals)) + // Best effort: construction evidence is shown, never acted on, here. + let constructions = client + .get(&format!( + "/sessions/{}/rewind/constructions", + segment(&request.session) + )) + .await + .ok() + .and_then(|reply| data(reply).ok()) + .unwrap_or_default(); + Ok(Reply::Journals(journals, Box::new(constructions))) } Command::Discover(journal) => { let requests: Vec = data( diff --git a/crates/cyber-tui/src/recovery_tests.rs b/crates/cyber-tui/src/recovery_tests.rs index a13fe7e2..aa9c7cfd 100644 --- a/crates/cyber-tui/src/recovery_tests.rs +++ b/crates/cyber-tui/src/recovery_tests.rs @@ -53,9 +53,13 @@ fn recovery_drops_stale_generations_and_foreign_sessions_without_changing_drafts let mut app = app(); let old = request(app.open_snapshot_recovery()); let current = request(app.open_snapshot_recovery()); - deliver(&mut app, old, Reply::Journals(vec![])); + deliver(&mut app, old, Reply::Journals(vec![], Default::default())); assert!(app.rewind.recovery.busy); - deliver(&mut app, current.clone(), Reply::Journals(vec![])); + deliver( + &mut app, + current.clone(), + Reply::Journals(vec![], Default::default()), + ); assert!(!app.rewind.recovery.busy); app.set_session(Session { id: "ses_foreign".into(), @@ -63,7 +67,11 @@ fn recovery_drops_stale_generations_and_foreign_sessions_without_changing_drafts ..Default::default() }); app.composer.set_text("foreign draft"); - deliver(&mut app, current, Reply::Journals(vec![])); + deliver( + &mut app, + current, + Reply::Journals(vec![], Default::default()), + ); assert_eq!(app.composer.text(), "foreign draft"); assert_ne!(app.rewind.phase, rewind::Phase::Recovery); } @@ -71,7 +79,11 @@ fn recovery_drops_stale_generations_and_foreign_sessions_without_changing_drafts fn ambiguous_confirmation_retains_exact_lookup_and_never_reuses_enter_to_mutate() { let mut app = app(); let initial = request(app.open_snapshot_recovery()); - deliver(&mut app, initial, Reply::Journals(vec![])); + deliver( + &mut app, + initial, + Reply::Journals(vec![], Default::default()), + ); app.rewind.recovery.phase = Phase::Requests; app.rewind.recovery.discovered = true; app.rewind.recovery.journal = Some("restore_one".into()); @@ -117,13 +129,16 @@ fn failed_discovery_does_not_license_a_fresh_attempt() { deliver( &mut app, load, - Reply::Journals(vec![SnapshotRecovery { - id: "restore_one".into(), - filesystem_complete: false, - paths: vec![], - applied: vec![], - location_removed: false, - }]), + Reply::Journals( + vec![SnapshotRecovery { + id: "restore_one".into(), + filesystem_complete: false, + paths: vec![], + applied: vec![], + location_removed: false, + }], + Default::default(), + ), ); let discovery = request(app.recovery_key(KeyCode::Enter)); deliver(&mut app, discovery, Reply::Requests(vec![])); @@ -463,13 +478,16 @@ fn a_removed_location_journal_is_listed_read_only() { deliver( &mut app, load, - Reply::Journals(vec![SnapshotRecovery { - id: "restore_one".into(), - filesystem_complete: true, - paths: vec!["a.txt".into()], - applied: vec!["a.txt".into()], - location_removed: true, - }]), + Reply::Journals( + vec![SnapshotRecovery { + id: "restore_one".into(), + filesystem_complete: true, + paths: vec!["a.txt".into()], + applied: vec!["a.txt".into()], + location_removed: true, + }], + Default::default(), + ), ); let shown = lines(&app) .iter() @@ -486,3 +504,48 @@ fn a_removed_location_journal_is_listed_read_only() { assert!(app.recovery_key(KeyCode::Char('b')).is_empty()); assert_eq!(app.composer.text(), "owner draft"); } + +/// Owner decision 2026-11-15 (`snapshots-checkpoints` → Owner-only discard of +/// construction evidence: "Terminal recovery panel points to the command"): the +/// panel lists construction evidence and pending discards with the exact CLI +/// command, and no key discards anything. +#[test] +fn construction_evidence_is_listed_with_the_cli_command_only() { + use cyber_server::runtime::{ + ConstructionInventory, ConstructionLocation, ConstructionStageEntry, ConstructionStageKind, + }; + let mut app = app(); + let load = request(app.open_snapshot_recovery()); + let stage = format!("preparing_6_op_one_{}", "0".repeat(26)); + deliver( + &mut app, + load, + Reply::Journals( + vec![], + Box::new(ConstructionInventory { + stages: vec![ConstructionStageEntry { + name: stage.clone(), + kind: ConstructionStageKind::CheckoutClaim, + activity_id: Some("op_one".into()), + location: ConstructionLocation::Present, + }], + pending: vec![], + }), + ), + ); + let shown = lines(&app) + .iter() + .map(ToString::to_string) + .collect::>() + .join("\n"); + assert!( + shown.contains(&format!( + "discard with: cyber sessions recovery-discard ses_one {stage}" + )), + "{shown}" + ); + for key in [KeyCode::Enter, KeyCode::Char('d'), KeyCode::Char('x')] { + assert!(app.recovery_key(key).is_empty(), "{key:?}"); + } + assert_eq!(app.composer.text(), "owner draft"); +} diff --git a/crates/cyber-tui/src/recovery_view.rs b/crates/cyber-tui/src/recovery_view.rs index 733a41cf..18fb01c9 100644 --- a/crates/cyber-tui/src/recovery_view.rs +++ b/crates/cyber-tui/src/recovery_view.rs @@ -25,7 +25,10 @@ pub fn lines(app: &App) -> Vec> { } match view.phase { Phase::Preparation => unreachable!(), - Phase::Journals => journals(view, &mut lines), + Phase::Journals => { + journals(view, &mut lines); + constructions(&app.session.id, view, &mut lines); + } Phase::Requests => requests(view, &mut lines), Phase::Review => review(view, &mut lines), Phase::Outcome => outcome(view, &mut lines), @@ -63,6 +66,28 @@ fn journals(view: &View, lines: &mut Vec>) { ))); } } +/// Construction evidence is listed with the exact CLI command that reviews it; +/// discarding stays a CLI/API action in this revision. +fn constructions(session: &str, view: &View, lines: &mut Vec>) { + for stage in &view.constructions.stages { + lines.push(Line::from(format!( + "Construction evidence {} · owner {} · discard with: cyber sessions recovery-discard {} {}", + clean(&stage.name), + clean(stage.activity_id.as_deref().unwrap_or("unknown")), + clean(session), + clean(&stage.name) + ))); + } + for receipt in &view.constructions.pending { + lines.push(Line::from(format!( + "discard pending: {} · request {:?} · cyber sessions recovery-discard-request {} {}", + clean(&receipt.stage.name), + receipt.request_id, + clean(session), + clean(&receipt.request_id) + ))); + } +} fn requests(view: &View, lines: &mut Vec>) { lines.push(Line::from(format!( "Journal: {}", diff --git a/docs/cli.md b/docs/cli.md index cf31df76..0f8162a7 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -322,6 +322,8 @@ cyber sessions [OPTIONS] - [`recovery-request`](#cyber-sessions-recovery-request): Look up a retained recovery request; optionally reconcile its native acknowledgement - [`recovery-preparation`](#cyber-sessions-recovery-preparation): Review or cancel an exited snapshot preparation before source effects were admitted - [`recovery-preparation-request`](#cyber-sessions-recovery-preparation-request): Look up a committed preparation cancellation; optionally reconcile its native metadata +- [`recovery-discard`](#cyber-sessions-recovery-discard): List, review or discard one unpublished construction stage (local owner only) +- [`recovery-discard-request`](#cyber-sessions-recovery-discard-request): Look up a construction discard request by its request ID, without acting - [`label`](#cyber-sessions-label): Set or remove a branch label - [`export`](#cyber-sessions-export): Write a Session as JSON (default), Markdown (--format md) or one self-contained HTML page (--format html): its info, messages, tool calls, goals and workflow runs - [`import`](#cyber-sessions-import): Import a JSON export (`cyber sessions export`) as a new Session in this Location, with fresh IDs and its attachments, which are verified before anything is written @@ -499,6 +501,38 @@ cyber sessions recovery-preparation-request [OPTIONS] [STAGE] +``` + +**Arguments:** + +- ``: Session ID, exact title or unique ID prefix. +- `[STAGE]`: Exact construction stage name from the listing; omit to list stages and pending discards. + +**Options:** + +- `--activity `: Review the only construction stage of this snapshot activity instead of naming it. +- `--confirm `: Discard only the reviewed stage; requires the stage name and --request-id. +- `--request-id `: Stable request identity; repeat it to resume after an interruption or a lost reply. + +## `cyber sessions recovery-discard-request` + +Look up a construction discard request by its request ID, without acting + +```text +cyber sessions recovery-discard-request [OPTIONS] +``` + +**Arguments:** + +- ``: Session ID, exact title or unique ID prefix. +- ``: Exact request ID used to confirm the discard. + ## `cyber sessions label` Set or remove a branch label From f782ca43fba92205b90b66185c40e669c56ca929 Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 12:00:13 -0400 Subject: [PATCH 4/8] Test construction discard through real process death A SIGKILLed claim stage refuses discard while its preparation is unresolved and for a stale review, then is discarded and worktree removal is admitted. A cut table kills the service after the intent, after the quarantine move and after the unlink; each request resumes, maintenance finishes a moved stage and doctor reports it as pending meanwhile. --- .github/workflows/non-git-snapshot-proof.yml | 10 + crates/cyber-cli/tests/branches_cli.rs | 6 + .../tests/support/construction_discard.rs | 381 ++++++++++++++++++ 3 files changed, 397 insertions(+) create mode 100644 crates/cyber-cli/tests/support/construction_discard.rs diff --git a/.github/workflows/non-git-snapshot-proof.yml b/.github/workflows/non-git-snapshot-proof.yml index 665848ac..b18e7e49 100644 --- a/.github/workflows/non-git-snapshot-proof.yml +++ b/.github/workflows/non-git-snapshot-proof.yml @@ -183,6 +183,15 @@ jobs: set -euo pipefail mkdir -p "$TMPDIR" cargo test --locked -p cyber-cli --features native-git-acceptance --test branches_cli preparation_ -- --nocapture --test-threads=1 2>&1 | tee preparation-client-proof.log + - name: Owner-only construction evidence discard and its process-death cuts + if: ${{ !cancelled() && (runner.os != 'Linux' || steps.sandbox.outcome == 'success') }} + env: + TMPDIR: /tmp/c${{ github.run_number }} + shell: bash + run: | + set -euo pipefail + mkdir -p "$TMPDIR" + cargo test --locked -p cyber-cli --features native-git-acceptance --test branches_cli construction_discard:: -- --nocapture --test-threads=1 2>&1 | tee construction-discard-proof.log - name: Prepared cancellation metadata retirement if: ${{ !cancelled() && (runner.os != 'Linux' || steps.sandbox.outcome == 'success') }} env: @@ -282,6 +291,7 @@ jobs: fallback-collection-proof.log git-cli-recovery-proof.log preparation-client-proof.log + construction-discard-proof.log preparation-retirement-proof.log paired-retirement-proof.log zero-payload-retirement-proof.log diff --git a/crates/cyber-cli/tests/branches_cli.rs b/crates/cyber-cli/tests/branches_cli.rs index 7790d4fe..9afb5334 100644 --- a/crates/cyber-cli/tests/branches_cli.rs +++ b/crates/cyber-cli/tests/branches_cli.rs @@ -10,6 +10,12 @@ use std::time::Duration; use serde_json::{Value, json}; +#[cfg(all( + feature = "native-git-acceptance", + any(target_os = "macos", target_os = "linux") +))] +#[path = "support/construction_discard.rs"] +mod construction_discard; #[cfg(any(target_os = "macos", target_os = "linux"))] #[path = "support/ordinary_cuts.rs"] mod ordinary_cuts; diff --git a/crates/cyber-cli/tests/support/construction_discard.rs b/crates/cyber-cli/tests/support/construction_discard.rs new file mode 100644 index 00000000..19104082 --- /dev/null +++ b/crates/cyber-cli/tests/support/construction_discard.rs @@ -0,0 +1,381 @@ +//! Owner-only discard of checkout construction evidence through the real binary +//! (`snapshots-checkpoints` → Owner-only discard of construction evidence): a real +//! SIGKILL leaves a flushed, unpublished claim stage; the discard refuses while the +//! preparation is unresolved and for a stale fingerprint, and worktree removal is +//! admitted only after the stage is discarded. A second table kills the service +//! between the durable intent, the quarantine move and the unlink. +use super::*; + +const CUTS: [(&str, Place); 3] = [ + ("construction-discard-intent-committed", Place::Source), + ("construction-discard-quarantined", Place::Quarantined), + ("construction-discard-unlinked", Place::Gone), +]; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Place { + Source, + Quarantined, + Gone, +} + +struct Fixture { + _model: scripted_model::ScriptedModel, + env: Env, + session: String, + activity: String, + stage: PathBuf, + name: String, +} + +impl Fixture { + /// A managed checkout whose claim stage survived a real kill of its constructor. + fn new() -> Self { + let model = scripted_model::ScriptedModel::start(reply); + let (env, session) = managed_git_fixture(&model); + std::fs::write(env.directory.join("tracked"), "before").unwrap(); + env.exec(Some(&session), "before snapshot"); + let first = env.user_ids(&session)[0].clone(); + std::fs::write(env.directory.join("tracked"), "after").unwrap(); + env.exec(Some(&session), "after snapshot"); + kill_at_claim_stage(&env, &session, &first); + let (stage, activity) = retained_claim_stage(&env); + let name = stage.file_name().unwrap().to_str().unwrap().to_owned(); + Self { + _model: model, + env, + session, + activity, + stage, + name, + } + } + + fn cancel_preparation(&self) { + let review = json(&self.env.cyber(&[ + "sessions", + "recovery-preparation", + &self.session, + &self.activity, + "--format", + "json", + ])); + json(&self.env.cyber(&[ + "sessions", + "recovery-preparation", + &self.session, + &self.activity, + "--confirm", + review["confirmation"].as_str().unwrap(), + "--request-id", + "cancel-before-discard", + "--format", + "json", + ])); + } + + fn review(&self) -> Value { + json(&self.env.cyber(&[ + "sessions", + "recovery-discard", + &self.session, + &self.name, + "--format", + "json", + ])) + } + + fn confirm(&self, fingerprint: &str, request: &str) -> Output { + self.env.cyber(&[ + "sessions", + "recovery-discard", + &self.session, + &self.name, + "--confirm", + fingerprint, + "--request-id", + request, + "--format", + "json", + ]) + } + + fn lookup(&self, request: &str) -> Value { + json(&self.env.cyber(&[ + "sessions", + "recovery-discard-request", + &self.session, + request, + "--format", + "json", + ])) + } + + fn listing(&self) -> Value { + json(&self.env.cyber(&[ + "sessions", + "recovery-discard", + &self.session, + "--format", + "json", + ])) + } + + fn quarantine(&self) -> PathBuf { + self.stage + .parent() + .unwrap() + .parent() + .unwrap() + .join("discarded") + } + + /// Where the stage is: its activity directory, the quarantine, or nowhere. + fn place(&self) -> Place { + let quarantined = std::fs::read_dir(self.quarantine()) + .into_iter() + .flatten() + .flat_map(|slot| std::fs::read_dir(slot.unwrap().path()).unwrap()) + .any(|entry| entry.unwrap().file_name().to_str() == Some(self.name.as_str())); + match (self.stage.exists(), quarantined) { + (true, false) => Place::Source, + (false, true) => Place::Quarantined, + (false, false) => Place::Gone, + (true, true) => panic!("stage both in place and quarantined"), + } + } + + fn assert_completed(&self, receipt: &Value, request: &str) { + assert_eq!(receipt["status"], "completed", "{receipt}"); + assert_eq!(receipt["request_id"], request); + assert_eq!(receipt["actor"], "local_owner"); + assert_eq!(receipt["stage"]["name"], self.name.as_str()); + assert_eq!(receipt["stage"]["activity_id"], self.activity.as_str()); + assert_eq!(self.place(), Place::Gone); + assert!( + std::fs::read_dir(self.quarantine()) + .map(|mut entries| entries.next().is_none()) + .unwrap_or(true), + "quarantine slot retained" + ); + assert_eq!(self.listing()["pending"], json!([])); + } + + /// Even a forced removal (the fixture's checkout has local edits) refuses + /// while the stage remains. + fn assert_removal_fenced(&self) { + let refused = self + .env + .cyber(&["api", "DELETE", "/worktrees/managed?force=true"]); + let text = exits(&refused, 1); + assert!(text.contains("same-owner unknown constructor"), "{text}"); + assert!(text.contains(&self.name), "{text}"); + assert!(self.env.directory.exists()); + } + + fn assert_removal_admitted(&mut self) { + exits( + &self + .env + .cyber(&["api", "DELETE", "/worktrees/managed?force=true"]), + 0, + ); + assert!(!self.env.directory.exists()); + // Later commands (and the fixture's service shutdown) run from the repository. + self.env.directory = self.env.root.join("repo"); + } +} + +fn sha256(bytes: &[u8]) -> String { + use sha2::Digest; + format!("{:x}", sha2::Sha256::digest(bytes)) +} + +/// The stage is listed with its command and reviewed read-only; an unresolved +/// preparation refuses the confirmation. Returns the (soon stale) review. +fn listed_reviewed_and_refused_while_unresolved(fixture: &Fixture, bytes: &[u8]) -> Value { + let listed = fixture.listing(); + assert_eq!(listed["stages"][0]["name"], fixture.name.as_str()); + assert_eq!(listed["stages"][0]["kind"], "checkout_claim"); + assert_eq!( + listed["stages"][0]["activity_id"], + fixture.activity.as_str() + ); + let text = exits( + &fixture + .env + .cyber(&["sessions", "recovery", &fixture.session]), + 0, + ); + assert!(text.contains("cyber sessions recovery-discard"), "{text}"); + let early = fixture.review(); + assert_eq!(early["stage"]["kind"], "checkout_claim"); + assert_eq!(early["stage"]["location"], "present"); + assert_eq!(early["stage"]["evidence"]["sha256"], sha256(bytes)); + assert_eq!(early["stage"]["evidence"]["size"], bytes.len()); + assert_eq!(std::fs::read(&fixture.stage).unwrap(), bytes); + let refused = fixture.confirm(early["confirmation"].as_str().unwrap(), "early"); + let text = exits(&refused, 1); + assert!(text.contains("unresolved snapshot preparation"), "{text}"); + assert_eq!(std::fs::read(&fixture.stage).unwrap(), bytes); + fixture.assert_removal_fenced(); + early +} + +/// A later Turn changes the Session revision: the early review is stale and +/// nothing is recorded or changed. +fn stale_review_refuses(fixture: &Fixture, early: &Value, bytes: &[u8]) { + fixture + .env + .exec(Some(&fixture.session), "after cancellation"); + assert_eq!(std::fs::read(&fixture.stage).unwrap(), bytes); + let stale = fixture.confirm(early["confirmation"].as_str().unwrap(), "stale"); + let text = exits(&stale, 1); + assert!(text.contains("stale"), "{text}"); + assert_eq!(std::fs::read(&fixture.stage).unwrap(), bytes); + let missing = fixture.env.cyber(&[ + "sessions", + "recovery-discard-request", + &fixture.session, + "stale", + ]); + exits(&missing, 1); + fixture.assert_removal_fenced(); +} + +#[test] +fn discarding_a_killed_claim_stage_is_fenced_receipted_and_admits_worktree_removal() { + let mut fixture = Fixture::new(); + let bytes = std::fs::read(&fixture.stage).unwrap(); + let early = listed_reviewed_and_refused_while_unresolved(&fixture, &bytes); + fixture.cancel_preparation(); + stale_review_refuses(&fixture, &early, &bytes); + let review = fixture.review(); + let fingerprint = review["confirmation"].as_str().unwrap(); + let receipt = json(&fixture.confirm(fingerprint, "discard-claim")); + fixture.assert_completed(&receipt, "discard-claim"); + // A retry and a lookup return the receipt and touch nothing else. + assert_eq!( + json(&fixture.confirm(fingerprint, "discard-claim")), + receipt + ); + assert_eq!(fixture.lookup("discard-claim"), receipt); + let history = json(&fixture.env.cyber(&[ + "api", + "GET", + &format!("/sessions/{}/history?limit=500", fixture.session), + ])); + assert!( + history + .to_string() + .contains("session.snapshot.construction_discarded.1"), + "{history}" + ); + fixture.assert_removal_admitted(); +} + +/// Kill the service at `point` inside a confirmed discard. +fn kill_at_discard(fixture: &Fixture, fingerprint: &str, request: &str, point: &str) { + exits(&fixture.env.cyber(&["service", "stop"]), 0); + let marker = fixture.env.root.join(format!("{point}.marker")); + let log = fixture.env.root.join(format!("{point}.log")); + let output = std::fs::File::create(&log).unwrap(); + let mut confirm = fixture + .env + .command(&[ + "sessions", + "recovery-discard", + &fixture.session, + &fixture.name, + "--confirm", + fingerprint, + "--request-id", + request, + "--format", + "json", + ]) + .env("CYBER_TEST_PROCESS_CUT", point) + .env("CYBER_TEST_PROCESS_CUT_MARKER", &marker) + .stdout(output.try_clone().unwrap()) + .stderr(output) + .spawn() + .unwrap(); + let deadline = std::time::Instant::now() + Duration::from_secs(120); + while !marker.exists() { + if confirm.try_wait().unwrap().is_some() || std::time::Instant::now() >= deadline { + let _ = confirm.kill(); + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + kill_registered_service(&fixture.env) + })); + panic!( + "discard cut {point} was never reached: {}", + std::fs::read_to_string(&log).unwrap_or_default() + ); + } + std::thread::sleep(Duration::from_millis(5)); + } + kill_registered_service(&fixture.env); + assert!(!confirm.wait().unwrap().success()); +} + +#[test] +fn discard_resumes_after_real_process_death_between_intent_quarantine_and_unlink() { + for (point, expected) in CUTS { + let mut fixture = Fixture::new(); + fixture.cancel_preparation(); + let review = fixture.review(); + let fingerprint = review["confirmation"].as_str().unwrap(); + let request = format!("cut-{point}"); + kill_at_discard(&fixture, fingerprint, &request, point); + assert_eq!(fixture.place(), expected, "{point}"); + // The intent was durable before any filesystem change. + let intent = fixture.lookup(&request); + assert_eq!(intent["status"], "intent", "{point}: {intent}"); + assert_eq!(intent["stage"], review["stage"], "{point}"); + let pending = fixture.listing()["pending"].clone(); + assert_eq!(pending[0]["request_id"], request.as_str(), "{point}"); + let doctor = fixture.env.cyber(&["doctor", "--format", "json"]); + let doctor: Value = serde_json::from_slice(&doctor.stdout).unwrap(); + let check = doctor["checks"] + .as_array() + .unwrap() + .iter() + .find(|check| check["check"] == "construction discards") + .unwrap(); + assert!( + check["detail"] + .as_str() + .unwrap() + .contains("discard pending"), + "{point}: {check}" + ); + if expected == Place::Source { + // Nothing moved yet: removal stays fenced until the discard completes. + fixture.assert_removal_fenced(); + } + if expected == Place::Quarantined { + // Maintenance finishes a moved stage on its own, with no owner action. + exits(&fixture.env.cyber(&["service", "stop"]), 0); + let started = fixture + .env + .command(&["sessions", "recovery-discard", &fixture.session]) + .env("CYBER_TEST_DISCARD_RETRY_DELAY_MS", "50") + .output() + .unwrap(); + exits(&started, 0); + let deadline = std::time::Instant::now() + Duration::from_secs(60); + while fixture.lookup(&request)["status"] != "completed" { + assert!( + std::time::Instant::now() < deadline, + "maintenance never retried" + ); + std::thread::sleep(Duration::from_millis(50)); + } + } + // The same request resumes its frozen plan; a new review is not needed. + let receipt = json(&fixture.confirm(fingerprint, &request)); + fixture.assert_completed(&receipt, &request); + assert_eq!(fixture.lookup(&request), receipt, "{point}"); + fixture.assert_removal_admitted(); + } +} From 099aeac6685b9bd451dcaa3b549f3e0f63d856a1 Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 12:00:13 -0400 Subject: [PATCH 5/8] Document construction evidence discard and record implementation notes --- docs/rewind.md | 92 ++++++++++++++++--- .../design.md | 67 +++++++++++++- .../proposal.md | 11 ++- .../specs/snapshots-checkpoints/spec.md | 6 ++ .../tasks.md | 10 +- 5 files changed, 163 insertions(+), 23 deletions(-) diff --git a/docs/rewind.md b/docs/rewind.md index 67e11a48..d82cbc0c 100644 --- a/docs/rewind.md +++ b/docs/rewind.md @@ -530,19 +530,85 @@ points to the unresolved preparation, and `recovery-preparation` lists the stage under its activity (JSON `checkout_constructions`); the TUI recovery panel (**C**, then **P**) shows the same line. Cancelling that pre-effect preparation restores prompt admission. The stage itself is fenced by design: it is never adopted as a -claim, it is not deleted, and removing the worktree refuses with a +claim, nothing deletes it automatically, and removing the worktree refuses with a `same-owner unknown constructor` error naming it. An interrupted acknowledgement -stage behaves the same way for metadata retirement. Cleaning up construction -evidence needs a separate recovery protocol that does not exist yet; do not delete -the stage by hand to force removal. - -Recovery clients show a stage only under the preparation whose activity owns it. -A stage with a malformed name, an acknowledgement stage whose owner has no listed -preparation, and any stage after its preparation was cancelled (the default -listing drops cancelled candidates; the TUI history view still shows them) appear -only in the worktree removal or metadata retirement refusal, which always names -them. The name inventory is advisory: if it cannot be read, the listing still -returns its preparations without stage names. +stage behaves the same way for metadata retirement. Only the owner's explicit +discard (below) removes construction evidence; do not delete the stage by hand. + +Recovery clients show a checkout stage under the preparation whose activity owns +it while that preparation is unresolved. Every stage, including one whose +preparation was cancelled, a cancellation-record stage and one with a malformed +name, is listed by `cyber sessions recovery-discard ` (and in the text of +`cyber sessions recovery` and the TUI recovery panel, with the exact discard +command). The preparation listing's name inventory is advisory: if it cannot be +read, the listing still returns its preparations without stage names. + +### Discarding construction evidence (local owner only) + +A construction stage is a private file a constructor flushed but never published: a +checkout claim stage (`preparing_*`), a checkout acknowledgement stage +(`ack_preparing_*`) or a file-copy cancellation-record stage (`tmp_*` beside a +journal's `preparation.json`). The local owner can discard exactly one reviewed stage +per confirmation: + +```sh +cyber sessions recovery-discard ses_example +cyber sessions recovery-discard ses_example preparing_10_op_example_01J... +cyber sessions recovery-discard ses_example preparing_10_op_example_01J... \ + --confirm --request-id discard-one +cyber sessions recovery-discard-request ses_example discard-one +``` + +The first command lists the stages (kind, owner activity, Location state) and every +`discard pending` request; `--activity ` reviews the only stage of an activity. +Review is read-only: it reports the stage's kind, owner activity, device and inode, +size, modification time, SHA-256 (stages over 1 MiB, links and special files are +refused), the operations it fences and whether the Location is present or removed, +plus a fingerprint over all of that and the Session revision. + +Confirmation refuses, leaving every stage, journal and record unchanged, when: + +- the fingerprint is stale (the stage or the Session changed since review); +- the Session is not idle, has background work or an admitted snapshot worker, or + still has an unresolved snapshot preparation (cancel it first); +- the stage's constructor lock or the activity's snapshot lifetime lock is still + held (`busy:`), or the snapshot namespace is busy; +- the stage name has no derivable owner, or its owner is not a snapshot activity of + the Session; +- a claim stage's activity already published a claim; an acknowledgement stage's + claim has no `.snapshot-ack` published from another stage yet, or a + cancellation-record stage's journal has no `preparation.json` yet (run + `recovery-preparation-request --acknowledge` once first); +- the caller is not the authenticated local owner (`403`): a bearer or peer + identity, a peer attachment, a browser, an MCP client label or a model tool; +- the Session is a managed checkout whose Location was removed. + +Restore journals, payload images and every published claim, acknowledgement and +cancellation record are never discarded by this command, and it never removes the +worktree. Once the last stage is gone, worktree removal and metadata retirement are +admitted again. + +A confirmed discard first records a `session.snapshot.construction_discarded.1` +intent in the Session's history, then moves the stage with a no-replace rename into +a private `discarded//` directory of the same namespace, flushes it and unlinks +it there; the receipt is completed last. Every step re-checks the reviewed identity: +a file that differs is reported (`changed`) and never deleted. Repeating the +confirmation with the same request ID resumes an interrupted discard or returns the +receipt; `recovery-discard-request` (or +`GET .../rewind/constructions/discard/requests/`) only reads it. A stage +that was moved but not unlinked is `discard pending`: maintenance retries the unlink +a minute after start and then hourly without a time limit, `cyber doctor` and the +recovery listings report it, and file-copy stages count toward the snapshot storage +cap until removed. Receipts are never removed by retention. + +The API equivalents are `GET /sessions//rewind/constructions`, +`POST /sessions//rewind/constructions/discard/review` (`{"stage": ...}` or +`{"activity_id": ...}`), `POST .../discard/confirm` +(`{"stage", "confirmation", "request_id"}`) and +`GET .../discard/requests/`; the SDK exposes `constructionInventory`, +`constructionDiscardReview`, `constructionDiscardConfirm` and +`constructionDiscardLookup` on `client.session`. The TUI only shows the command in +this revision. Confirm only a reviewed fingerprint and retain your stable cancellation ID: @@ -565,5 +631,5 @@ Cancellation preserves files, transcript, retained intents, private payloads and independent process/checkout uncertainty. Older receipts can remain inspectable without gaining newer native acknowledgement authority. If source effects may have been admitted, use the journal's keep/rollback review instead. No force-clear -or evidence deletion option exists. The TUI preparation path and remaining partial +option exists; construction stages are discarded only as described above. The TUI preparation path and remaining partial constructor/native-platform acceptance are still unfinished. diff --git a/openspec/changes/add-construction-evidence-discard/design.md b/openspec/changes/add-construction-evidence-discard/design.md index 3582f2c8..90b17022 100644 --- a/openspec/changes/add-construction-evidence-discard/design.md +++ b/openspec/changes/add-construction-evidence-discard/design.md @@ -1,6 +1,7 @@ ## Context -Status: **approved by the owner 2026-11-15** (open questions answered below). No implementation exists yet; nothing here is enabled. +Status: **approved by the owner 2026-11-15** (open questions answered below); +implemented 2026-11-16 with the clarifications in "Implementation notes". Construction evidence is any private stage a constructor flushed but did not publish: checkout claim stages (`preparing___…`), acknowledgement stages @@ -103,3 +104,67 @@ a later decision. - **Failed unlink:** periodic maintenance retries unlinking `discarded//` indefinitely. It is never dropped silently: `doctor` and recovery listings report it as `discard pending`, and its bytes count toward the snapshot cap until removed. + +## Implementation notes (2026-11-16) + +These pin down choices the approved text left open. Where a note is stricter than the +text, the stricter rule is implemented; none widens discard authority. + +- **Surfaces and names.** CLI `cyber sessions recovery-discard [ | + --activity ] [--confirm --request-id ]` and + `cyber sessions recovery-discard-request ` (the + `recovery-` naming of the other recovery commands). A read-only + `GET .../rewind/constructions` lists stages (cancellation-record stages had no + listing) and `discard pending` requests; `sessions recovery` text, the TUI journal + panel and the TUI preparation panel show each stage with the exact CLI command. +- **Owner only.** The main listener already requires the owner credential and peers + have their own listener without these routes. The review and confirm handlers also + refuse (`403`, reason `owner_only`) a request presenting a bearer token, a peer + attachment (`X-Cyber-Attach`), a browser (`Origin` or `Sec-Fetch-Mode`) or an MCP + client label (`X-Cyber-Client: mcp:*`). No model tool exists. +- **Owner derivation.** Claim and acknowledgement stages: the owner parsed from the + name. Cancellation-record stages (`tmp_*` in a journal directory): the stage counts + only when its complete bytes are the cancellation receipt of exactly the origin that + owns the journal; any other journal file is not construction evidence and is never + touched. The owner must be a snapshot activity of the reviewed Session. +- **Published records.** With rename publication a record published *from* a stage + cannot coexist with it, so the bullet is enforced as: a claim stage refuses while a + claim `.lock` exists for its activity; an acknowledgement stage refuses until a + `.snapshot-ack` published from another stage exists (receipt reconciliation has run + once); a cancellation-record stage refuses until its journal's `preparation.json` + exists (the same rule: `recovery-preparation-request --acknowledge` has run once). +- **Liveness.** Exclusive, non-blocking: the stage's own constructor lock (claim and + acknowledgement stages are held locked by their constructor from creation through + publication), the activity's snapshot lifetime lock (`workers/`) and, for + cancellation-record stages, the snapshot namespace lock. A held lock refuses as + `409` (`busy:`). +- **Session fences.** Idle, no Drain, no background job or delegation, no admitted + snapshot or binary worker, and no snapshot activity of the Session that is not + settled (the owner activity's preparation must be cancelled first). +- **Quarantine.** `/cyber-worktree-activity/discarded//` for checkout + stages and `/snapshot/global//discarded//` for + cancellation-record stages, both 0700, where `` is a SHA-256 of the Session and + request ID. The stage is moved with a no-replace rename and unlinked only when its + device, inode, size, modification time and digest still match the receipt. +- **Receipt.** `session.snapshot.construction_discarded.1` events on the Session + aggregate: `intent` before any filesystem change, then `completed`, `pending` (moved, + not unlinked) or `changed` (another file holds the name; nothing deleted). The + latest event per request ID is the receipt. Lookup never acts; a repeated confirm + with the same request ID resumes the frozen plan (re-fencing first when the stage + never moved). +- **Maintenance.** A runtime task retries every request whose stage left its namespace + but was not unlinked, a minute after start and then hourly, with no time limit. A + request interrupted before the move waits for the owner's repeated confirmation. + `cyber doctor` reports every `discard pending` request. +- **Snapshot cap.** Quarantined cancellation-record bytes live in the snapshot + namespace and count toward its cap. Quarantined checkout stages live in the + repository's private Git metadata, outside the snapshot store; they are reported as + `discard pending` but are not counted (open for the owner). +- **Removed Location.** Supported for cancellation-record stages, which are found + from the activity's recorded origin (Location path, root, namespace and journal + identities) when the directory is gone. A managed Session whose Location was + removed refuses: its registration cannot be verified without the checkout, and its + checkout stages are not discoverable (open for the owner). +- **Bounds.** Stages over 1 MiB, links, special files and multi-link files are refused + at review. Platforms without the native primitives (Windows) refuse. + diff --git a/openspec/changes/add-construction-evidence-discard/proposal.md b/openspec/changes/add-construction-evidence-discard/proposal.md index ba1df666..e044f377 100644 --- a/openspec/changes/add-construction-evidence-discard/proposal.md +++ b/openspec/changes/add-construction-evidence-discard/proposal.md @@ -22,10 +22,12 @@ path, model tool or remote client cleanup authority. - The same command covers the construction stages and stale Location metadata left for a Session whose Location directory was removed, but never deletes restore journals, payload images or published claims/acknowledgements. -- Surfaces: `POST /api/v1/sessions/{id}/rewind/constructions/discard/review`, +- Surfaces: `GET /api/v1/sessions/{id}/rewind/constructions` (read-only listing of + stages and `discard pending` requests), `POST .../rewind/constructions/discard/review`, `.../discard/confirm`, `GET .../discard/requests/{request_id}`; SDK methods; - `cyber sessions recovery-discard`; the TUI recovery panel (**C**/**P**) under an - explicit key with a typed confirmation. + `cyber sessions recovery-discard` and `cyber sessions recovery-discard-request`. The + TUI recovery panel lists the evidence and shows the exact CLI command; it has no + discard action in this revision (owner decision 2026-11-15). - No change to automatic maintenance, reclamation or worktree removal: they keep refusing while any construction evidence remains. @@ -33,6 +35,7 @@ path, model tool or remote client cleanup authority. `crates/cyber-core` (worktree activity stages), `crates/cyber-snapshot` (cancellation record stages), `crates/cyber-server` (runtime command, events, HTTP/OpenAPI), -`sdk/`, `crates/cyber-cli`, `crates/cyber-tui`, `docs/rewind.md`. A new durable event +`sdk/`, `crates/cyber-cli` (including `cyber doctor`), `crates/cyber-tui`, +`docs/rewind.md`. A new durable event `session.snapshot.construction_discarded.1`. Security-relevant: it is the first path allowed to delete fenced recovery evidence, so it needs owner approval before any code. diff --git a/openspec/changes/add-construction-evidence-discard/specs/snapshots-checkpoints/spec.md b/openspec/changes/add-construction-evidence-discard/specs/snapshots-checkpoints/spec.md index f55e9c66..4271d9f8 100644 --- a/openspec/changes/add-construction-evidence-discard/specs/snapshots-checkpoints/spec.md +++ b/openspec/changes/add-construction-evidence-discard/specs/snapshots-checkpoints/spec.md @@ -37,6 +37,12 @@ - **THEN** the system SHALL retry the unlink without a time limit and SHALL NOT drop the entry silently - **AND** doctor and recovery listings SHALL report it as `discard pending` and its bytes SHALL count toward the snapshot storage cap until removed +#### Scenario: Construction evidence is listed with its command +- **GIVEN** a Session with construction stages or a discard that is still pending +- **WHEN** the owner lists its recovery evidence +- **THEN** the system SHALL list each stage with its kind, owner activity and Location state and each pending discard as `discard pending` +- **AND** listing SHALL NOT grant discard authority or change anything + #### Scenario: Terminal recovery panel points to the command - **GIVEN** a Session with construction evidence - **WHEN** the owner opens the terminal recovery panel diff --git a/openspec/changes/add-construction-evidence-discard/tasks.md b/openspec/changes/add-construction-evidence-discard/tasks.md index 229b637d..5ca4f609 100644 --- a/openspec/changes/add-construction-evidence-discard/tasks.md +++ b/openspec/changes/add-construction-evidence-discard/tasks.md @@ -1,4 +1,4 @@ -Status: approved by the owner 2026-11-15; implementation not started. +Status: approved by the owner 2026-11-15; implemented 2026-11-16 (design.md, "Implementation notes"). ## 1. Review @@ -6,7 +6,7 @@ Status: approved by the owner 2026-11-15; implementation not started. ## 2. Implementation (after approval) -- [ ] 2.1 Read-only stage review (identity, digest, fences, Location state) and fingerprint, for claim, acknowledgement and cancellation-record stages. -- [ ] 2.2 Confirm with the fencing order in design.md, durable intent, no-replace quarantine rename, unlink and completed receipt; resume and lookup by `request_id`. -- [ ] 2.3 HTTP routes, OpenAPI, SDK, `cyber sessions recovery-discard`, TUI entry, `docs/rewind.md`. -- [ ] 2.4 Tests: refusal for every case in "What still refuses"; real process death between intent, rename and unlink; stale fingerprint; removed Location; worktree removal admitted only after discard. +- [x] 2.1 Read-only stage review (identity, digest, fences, Location state) and fingerprint, for claim, acknowledgement and cancellation-record stages. Evidence: `cyber_core::construction_discard::observe` (no-follow, non-blocking, regular single-link file, 1 MiB bound, SHA-256), `Repository::review_snapshot_construction` (claim/ack), `cyber-snapshot` `copy::discard::stage` (cancellation records bound to their exact origin), `Runtime::construction_discard_review` and the read-only `construction_inventory` listing. +- [x] 2.2 Confirm with the fencing order in design.md, durable intent, no-replace quarantine rename, unlink and completed receipt; resume and lookup by `request_id`. Evidence: `crates/cyber-server/src/runtime/construction_discard/confirm.rs` (Session fences, fingerprint, lifetime and stage locks, `session.snapshot.construction_discarded.1` intent/completion, resume from the frozen plan, hourly maintenance retry), `cyber_core::construction_discard::{quarantine, unlink, locate}`. +- [x] 2.3 HTTP routes, OpenAPI, SDK, `cyber sessions recovery-discard`, TUI entry, `docs/rewind.md`. Evidence: `/rewind/constructions` routes with the owner-only guard, regenerated `sdk/openapi.json` and TypeScript SDK (`constructionInventory`, `constructionDiscardReview`, `constructionDiscardConfirm`, `constructionDiscardLookup`), `recovery-discard`/`recovery-discard-request` in `docs/cli.md`, `cyber doctor` check, the TUI recovery panels show the exact command, `docs/rewind.md` "Discarding construction evidence". +- [x] 2.4 Tests: refusal for every case in "What still refuses"; real process death between intent, rename and unlink; stale fingerprint; removed Location; worktree removal admitted only after discard. Evidence: `cyber-cli/tests/support/construction_discard.rs` (real SIGKILL claim stage; unresolved preparation, stale fingerprint, removal fenced then admitted; kill table at `construction-discard-intent-committed`, `-quarantined`, `-unlinked` with resume, maintenance retry and doctor `discard pending`), `cyber-server/tests/http.rs` (owner-only `403` for bearer, peer attachment, browser and MCP callers), `cyber-core` `construction_discard` and `activity::snapshot::discard` tests (live constructor, published claim, unreconciled acknowledgement, malformed names, links/FIFOs/aliases/oversized, changed and foreign files never deleted), `cyber-snapshot` `copy::discard` tests (busy namespace and lifetime, unreconciled cancellation, foreign journal files untouched, removed Location, snapshot-cap accounting), TUI panel test. From aaa8597e80263a2dcf26f2211b52a5be122a4477 Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 12:05:53 -0400 Subject: [PATCH 6/8] Refuse a discard confirmation that names an activity instead of the reviewed stage --- crates/cyber-cli/src/commands/discard_recovery.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/cyber-cli/src/commands/discard_recovery.rs b/crates/cyber-cli/src/commands/discard_recovery.rs index e3cc5053..7950fca4 100644 --- a/crates/cyber-cli/src/commands/discard_recovery.rs +++ b/crates/cyber-cli/src/commands/discard_recovery.rs @@ -26,7 +26,12 @@ pub struct DiscardArgs { #[arg(long, value_parser = activity_id)] activity: Option, /// Discard only the reviewed stage; requires the stage name and --request-id. - #[arg(long, value_parser = fingerprint, requires_all = ["stage", "request_id"])] + #[arg( + long, + value_parser = fingerprint, + requires_all = ["stage", "request_id"], + conflicts_with = "activity" + )] confirm: Option, /// Stable request identity; repeat it to resume after an interruption or a lost reply. #[arg(long, value_parser = request_id, requires = "confirm")] @@ -91,7 +96,11 @@ pub async fn run(client: &Client, args: DiscardArgs, global: &GlobalArgs) -> Res let inventory: ConstructionInventory = data(client.get(&base).await.map_err(api)?)?; return list_output(&inventory, &session, global); } - if let (Some(confirmation), Some(stage)) = (args.confirm, &args.stage) { + if let Some(confirmation) = args.confirm { + let stage = args + .stage + .as_ref() + .ok_or_else(|| CliError::usage("Discard confirmation names the reviewed stage"))?; let request_id = args .request_id .ok_or_else(|| CliError::usage("Discard confirmation requires --request-id"))?; From 20734f45450570d11ffa24e55411adcf6a656224 Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 16:47:21 -0400 Subject: [PATCH 7/8] Fix discard CI: Unix-only helpers, doctor check list, compressed upgrade fixture The two path helpers are only used by the Unix implementation and broke the Windows -D warnings build. The doctor JSON test now expects the new construction discards check. The upgrade test archive is compressed at the fastest level, since a stored debug binary on Linux CI now exceeds the upgrader's 512 MiB download cap. --- crates/cyber-cli/tests/cli.rs | 1 + crates/cyber-cli/tests/upgrade_cli.rs | 12 +++++++----- crates/cyber-core/src/construction_discard.rs | 2 ++ 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/cyber-cli/tests/cli.rs b/crates/cyber-cli/tests/cli.rs index 7cd48788..a06f1c5b 100644 --- a/crates/cyber-cli/tests/cli.rs +++ b/crates/cyber-cli/tests/cli.rs @@ -1440,6 +1440,7 @@ fn doctor_reports_every_check_as_json() { "catalog", "credentials", "database", + "construction discards", "sandbox", "git", "rg", diff --git a/crates/cyber-cli/tests/upgrade_cli.rs b/crates/cyber-cli/tests/upgrade_cli.rs index aeffce02..f63c5df7 100644 --- a/crates/cyber-cli/tests/upgrade_cli.rs +++ b/crates/cyber-cli/tests/upgrade_cli.rs @@ -330,16 +330,18 @@ impl Release { ]; if self.target.contains("windows") { let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); - let stored = zip::write::SimpleFileOptions::default() - .compression_method(zip::CompressionMethod::Stored); + let deflated = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated) + .compression_level(Some(1)); for (name, body) in members { - zip.start_file(name, stored).unwrap(); + zip.start_file(name, deflated).unwrap(); zip.write_all(body).unwrap(); } return zip.finish().unwrap().into_inner(); } - // Stored, not compressed: deflating a debug binary unoptimized takes half a minute. - let gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::none()); + // Compressed at the fastest level: a debug binary stored uncompressed can exceed the + // upgrader's 512 MiB download cap. miniz_oxide is optimized in dev builds, so this is quick. + let gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); let mut tar = tar::Builder::new(gz); for (name, body) in members { let mut header = tar::Header::new_gnu(); diff --git a/crates/cyber-core/src/construction_discard.rs b/crates/cyber-core/src/construction_discard.rs index 3be84736..bee298ce 100644 --- a/crates/cyber-core/src/construction_discard.rs +++ b/crates/cyber-core/src/construction_discard.rs @@ -52,6 +52,7 @@ pub struct Pending { pub size: u64, } +#[cfg(unix)] fn invalid(message: impl Into) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message.into()) } @@ -74,6 +75,7 @@ pub fn valid_key(key: &str) -> bool { .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) } +#[cfg(unix)] fn require_component(name: &str) -> io::Result<()> { if valid_component(name) { Ok(()) From 6393e08beeeb30c662144a7ecc61d168e0843372 Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 20:16:10 -0400 Subject: [PATCH 8/8] Strip debug sections from the upgrade test's stand-in release binary On Linux CI the debug binary with line tables is larger than the upgrader's per-member archive limit, so compression alone did not keep the fixture valid. A stripped copy still runs, which the test needs to check that the next start removes cyber.old. --- crates/cyber-cli/tests/upgrade_cli.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/crates/cyber-cli/tests/upgrade_cli.rs b/crates/cyber-cli/tests/upgrade_cli.rs index f63c5df7..d03ac5ee 100644 --- a/crates/cyber-cli/tests/upgrade_cli.rs +++ b/crates/cyber-cli/tests/upgrade_cli.rs @@ -441,13 +441,34 @@ fn dry_run_names_the_plan_and_downloads_nothing() { assert_eq!(entries, 1, "no temporary or .old file"); } +/// The test binary without debug sections, so it stays under the upgrader's archive +/// limits: a debug build with line tables is larger than a release archive may be. +/// It still runs, which the test needs for the cleanup on the next start. +fn runnable_release_binary() -> Vec { + let source = Path::new(env!("CARGO_BIN_EXE_cyber")); + if cfg!(windows) { + // Debug information lives in the separate .pdb on Windows. + return std::fs::read(source).unwrap(); + } + let dir = tempfile::tempdir().unwrap(); + let copy = dir.path().join("cyber"); + std::fs::copy(source, ©).unwrap(); + let stripped = std::process::Command::new("strip") + .arg("-S") + .arg(©) + .status() + .is_ok_and(|status| status.success()); + assert!(stripped, "strip -S failed on the test binary"); + std::fs::read(©).unwrap() +} + #[test] fn script_upgrade_replaces_the_binary_after_verification() { let release = Release::new(); release.env.stub.manifest("stable", NEXT); // The real binary with a marker appended stands in for the next release: it still // runs, and its digest tells it apart from the installed copy. - let mut next = std::fs::read(env!("CARGO_BIN_EXE_cyber")).unwrap(); + let mut next = runnable_release_binary(); next.extend_from_slice(b"\ncyber release 9.9.9\n"); release.publish(NEXT, NEXT, &release.archive(&next, b"helper 9.9.9"));