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 01/20] 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 02/20] 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 03/20] 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 04/20] 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 05/20] 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 06/20] 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 ff203c54eea72d9994626766fd02ccdb39b6d3f7 Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 16:36:12 -0400 Subject: [PATCH 07/20] Pin that a binary-document owner never gains snapshot recovery authority A binary-document activity can neither publish a snapshot origin nor pass snapshot recovery review, before or after launch, and the refused review appends nothing. The production guards already existed; this covers the M2 obligation that snapshot workers never reuse binary-document authority. --- .../src/runtime/snapshot_recovery.rs | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/crates/cyber-server/src/runtime/snapshot_recovery.rs b/crates/cyber-server/src/runtime/snapshot_recovery.rs index 0d963149..6ed8e694 100644 --- a/crates/cyber-server/src/runtime/snapshot_recovery.rs +++ b/crates/cyber-server/src/runtime/snapshot_recovery.rs @@ -586,6 +586,33 @@ mod tests { drop(typed); runtime.shutdown().await; } + /// A binary-document owner never acquires snapshot origin or recovery authority, + /// before or after launch, and the refused review writes nothing. + #[tokio::test] + async fn binary_document_activity_never_grants_snapshot_recovery_authority() { + let (_temp, runtime, session, _, _) = super::super::binary_documents_tests::fixture().await; + let handle = runtime.inner.handle(&session).await.unwrap(); + let mut binary = + activity::Scope::reserve_binary(&runtime.inner, &handle, "doc_fixture".into()) + .await + .unwrap(); + let bound = origin(&runtime, &session, binary.id()); + assert!(binary.launch_snapshot(bound.clone()).is_err()); + binary.launch().unwrap(); + let before = runtime.inner.store.aggregate_seq(binary.id()).unwrap(); + assert!( + runtime + .validate_recovery_activity(&mut review(bound)) + .is_err() + ); + assert_eq!( + runtime.inner.store.aggregate_seq(binary.id()).unwrap(), + before + ); + binary.settle().unwrap(); + drop(binary); + runtime.shutdown().await; + } #[tokio::test] async fn legacy_origin_without_exact_lock_proof_stays_inspectable_and_fenced() { let (_temp, runtime, session, _, _) = super::super::binary_documents_tests::fixture().await; From 3ec817482f4443b018dba85a53c11771562c64e6 Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 16:36:12 -0400 Subject: [PATCH 08/20] Kill the service at restore and recovery boundaries the cut matrix left open Add debug-only process-cut points after origin publication, after intent publication, after each progress record, after filesystem completion, after the paired recovery writer commit and after the ordinary and paired journal acknowledgements. Release builds compile them out. restore_cuts.rs drives the real CLI/service through each point and checks the durable state, keep/rollback or preparation cancellation, lookup-only retries and no transcript movement or inference. It also covers a staged undo beside an inactive branch, an interrupted keep/rollback retained as independent evidence, and replacement or aliasing of the private journal namespace between review and confirmation. --- crates/cyber-cli/tests/branches_cli.rs | 3 + .../cyber-cli/tests/support/restore_cuts.rs | 789 ++++++++++++++++++ .../cyber-server/src/runtime/snapshot_work.rs | 9 +- crates/cyber-snapshot/src/copy/restore.rs | 8 + 4 files changed, 808 insertions(+), 1 deletion(-) create mode 100644 crates/cyber-cli/tests/support/restore_cuts.rs diff --git a/crates/cyber-cli/tests/branches_cli.rs b/crates/cyber-cli/tests/branches_cli.rs index 9afb5334..7e0337d9 100644 --- a/crates/cyber-cli/tests/branches_cli.rs +++ b/crates/cyber-cli/tests/branches_cli.rs @@ -22,6 +22,9 @@ mod ordinary_cuts; #[cfg(any(target_os = "macos", target_os = "linux"))] #[path = "support/reclamation.rs"] mod reclamation_support; +#[cfg(any(target_os = "macos", target_os = "linux"))] +#[path = "support/restore_cuts.rs"] +mod restore_cuts; #[path = "../../cyber-app/tests/support/scripted_model.rs"] mod scripted_model; #[cfg(any(target_os = "macos", target_os = "linux"))] diff --git a/crates/cyber-cli/tests/support/restore_cuts.rs b/crates/cyber-cli/tests/support/restore_cuts.rs new file mode 100644 index 00000000..024cdd48 --- /dev/null +++ b/crates/cyber-cli/tests/support/restore_cuts.rs @@ -0,0 +1,789 @@ +//! Real process-death cuts on the file-copy restore and recovery paths that the M8 +//! matrix listed as gaps: directly after a progress record, after filesystem +//! completion with displaced payload images, after the paired recovery writer +//! commit, and after a native journal acknowledgement whose reply was never sent. +//! Each cut is a debug-only `CYBER_TEST_PROCESS_CUT` point in the service. +use super::*; +const FILES: usize = 4; + +struct Fixture { + model: scripted_model::ScriptedModel, + env: Env, + session: String, + first: String, +} +impl Fixture { + /// Non-Git Location with FILES modified tracked files; every restore change + /// displaces a payload image into its journal. + fn new() -> Self { + let model = scripted_model::ScriptedModel::start(reply); + let env = Env::new(&model); + std::fs::remove_dir_all(env.directory.join(".git")).unwrap(); + write_files(&env, "before"); + let session = env.exec(None, "before snapshot"); + let first = env.user_ids(&session)[0].clone(); + write_files(&env, "after"); + env.exec(Some(&session), "after snapshot"); + Self { + model, + env, + session, + first, + } + } + fn namespace(&self) -> PathBuf { + let namespaces: Vec<_> = + std::fs::read_dir(self.env.root.join("cyber-home/data/snapshot/global")) + .unwrap() + .map(|entry| entry.unwrap().path()) + .collect(); + assert_eq!(namespaces.len(), 1); + namespaces[0].clone() + } + fn journals(&self) -> Vec { + let mut journals: Vec = std::fs::read_dir(self.namespace().join("journals")) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + journals.sort(); + journals + } + fn intent(&self, journal: &str) -> Value { + let path = self + .namespace() + .join("journals") + .join(journal) + .join("intent.json"); + serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap() + } + /// The only journal, which the killed restore left behind. + fn only_journal(&self) -> (String, Value) { + let journals = self.journals(); + assert_eq!(journals.len(), 1, "{journals:?}"); + let intent = self.intent(&journals[0]); + (journals[0].clone(), intent) + } + fn payloads(&self, journal: &str) -> usize { + std::fs::read_dir(self.namespace().join("journals").join(journal)) + .unwrap() + .filter(|entry| { + entry + .as_ref() + .unwrap() + .file_name() + .to_string_lossy() + .starts_with("stage_") + }) + .count() + } + fn contents(&self) -> Vec> { + (0..FILES) + .map(|index| self.env.file(&name(index))) + .collect() + } + /// Run the reviewed `both` rewind on a fresh service that stops at `point`, then + /// SIGKILL the registered service. + fn kill_rewind_at(&self, point: &str) { + let preview = rewind_preview(&self.env, &self.session, &self.first, "both"); + let confirmation = preview["confirmation"].as_str().unwrap().to_owned(); + self.kill_at( + point, + &[ + "sessions", + "rewind", + &self.session, + "--to", + &self.first, + "--target", + "both", + "--confirm", + &confirmation, + "--format", + "json", + ], + ); + } + /// Stop the running service, run `args` on a fresh service started with the + /// fixture point, wait for its marker and SIGKILL the registered service. + fn kill_at(&self, point: &str, args: &[&str]) { + exits(&self.env.cyber(&["service", "stop"]), 0); + let marker = self.env.root.join(format!("{point}.marker")); + // A point may be reached once per process; only this run's marker counts. + let _ = std::fs::remove_file(&marker); + let log = self.env.root.join(format!("{point}.log")); + let output = std::fs::File::create(&log).unwrap(); + let mut child = Child( + self.env + .command(args) + .env("CYBER_TEST_PROCESS_CUT", point) + .env("CYBER_TEST_PROCESS_CUT_MARKER", &marker) + .stdout(output.try_clone().unwrap()) + .stderr(output) + .spawn() + .unwrap(), + ); + wait_for(&marker, &mut child, &log); + kill_registered_service(&self.env); + assert!(!child.0.wait().unwrap().success()); + } + /// The latest durable record of the journal's native owner. + fn activity(&self, intent: &Value) -> Value { + latest_record(&self.env, intent["origin"]["activity_id"].as_str().unwrap()) + } + fn review(&self, journal: &str, action: &str) -> Value { + let review = json(&self.env.cyber(&[ + "sessions", + "recovery", + &self.session, + journal, + "--action", + action, + "--format", + "json", + ])); + assert!( + review["conflicts"].as_array().unwrap().is_empty(), + "{review}" + ); + review + } + fn catalog_complete(&self, journal: &str) -> Value { + let catalog = + json( + &self + .env + .cyber(&["sessions", "recovery", &self.session, "--format", "json"]), + ); + let entries = catalog.as_array().unwrap(); + assert_eq!(entries.len(), 1, "{catalog}"); + assert_eq!(entries[0]["id"], journal); + entries[0]["filesystem_complete"].clone() + } + fn request(&self, journal: &str, action: &str, request_id: &str) -> Value { + let review = self.review(journal, action); + json!({"journal_id":journal,"action":action,"confirmation":review["confirmation"],"request_id":request_id}) + } + fn lookup(&self, request_id: &str, acknowledge: bool) -> Value { + let mut args = vec![ + "sessions", + "recovery-request", + &self.session, + request_id, + "--format", + "json", + ]; + if acknowledge { + args.push("--acknowledge"); + } + json(&self.env.cyber(&args)) + } + /// Later owner edits made while no service runs: a file replaced by a symlink and + /// an unrelated new file. + fn edit_as_owner(&self) -> PathBuf { + let target = self.env.root.join("later-owner-target"); + std::fs::write(&target, "later owner bytes").unwrap(); + let link = self.env.directory.join(name(0)); + std::fs::remove_file(&link).unwrap(); + std::os::unix::fs::symlink(&target, &link).unwrap(); + std::fs::write(self.env.directory.join("unrelated-owner"), "owner data").unwrap(); + target + } + fn assert_owner_edits(&self, target: &std::path::Path) { + assert_eq!( + std::fs::read_link(self.env.directory.join(name(0))).unwrap(), + target + ); + assert_eq!( + std::fs::read_to_string(target).unwrap(), + "later owner bytes" + ); + assert_eq!( + self.env.file("unrelated-owner").as_deref(), + Some("owner data") + ); + } +} +impl Fixture { + /// Confirm a reviewed recovery request and require runtime and native + /// acknowledgement. + fn confirm_acknowledged(&self, request: &Value) -> Value { + let result = json(&recovery_confirm_cli(&self.env, &self.session, request)); + assert_eq!(result["state"], "acknowledged"); + assert_eq!(result["journal_acknowledged"], true); + result + } + /// After keep only the applied path holds restored bytes; rollback leaves none. + fn assert_resolved(&self, action: &str, applied: &str) { + let expected: Vec<_> = (0..FILES) + .map(|index| { + let kept = action == "keep" && name(index) == applied; + Some(if kept { "before" } else { "after" }.to_owned()) + }) + .collect(); + assert_eq!(self.contents(), expected); + } + fn assert_uniform(&self, contents: &str) { + assert_eq!(self.contents(), vec![Some(contents.to_owned()); FILES]); + } + /// No transcript movement and no inference since the captured baseline. + fn assert_quiet(&self, messages: &[Value], requests: usize) { + assert_eq!(self.env.messages(&self.session), messages); + assert_eq!(self.model.requests().len(), requests); + } +} +/// CLI arguments that confirm `request` (journal, action, fingerprint, request ID). +fn confirm_args<'a>(f: &'a Fixture, request: &'a Value) -> Vec<&'a str> { + let field = |key: &str| request[key].as_str().unwrap(); + vec![ + "sessions", + "recovery", + &f.session, + field("journal_id"), + "--action", + field("action"), + "--confirm", + field("confirmation"), + "--request-id", + field("request_id"), + "--format", + "json", + ] +} +fn name(index: usize) -> String { + format!("cut_{index:04}") +} +fn write_files(env: &Env, contents: &str) { + for index in 0..FILES { + std::fs::write(env.directory.join(name(index)), contents).unwrap(); + } +} +fn unacknowledged(intent: &Value) -> bool { + intent + .get("acknowledged") + .is_none_or(|value| value == false) +} +fn latest_record(env: &Env, aggregate: &str) -> Value { + let database = std::fs::read_dir(env.root.join("cyber-home/data")) + .unwrap() + .map(|entry| entry.unwrap().path()) + .find(|path| path.extension().is_some_and(|extension| extension == "db")) + .unwrap(); + let db = + rusqlite::Connection::open_with_flags(database, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY) + .unwrap(); + let data: String = db + .query_row( + "SELECT data FROM event WHERE aggregate_id=?1 ORDER BY seq DESC LIMIT 1", + [aggregate], + |row| row.get(0), + ) + .unwrap(); + serde_json::from_str(&data).unwrap() +} +struct Child(std::process::Child); +impl Drop for Child { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} +fn wait_for(marker: &std::path::Path, child: &mut Child, log: &std::path::Path) { + let deadline = std::time::Instant::now() + Duration::from_secs(120); + while !marker.exists() { + assert!( + child.0.try_wait().unwrap().is_none() && std::time::Instant::now() < deadline, + "cut was never reached: {}", + std::fs::read_to_string(log).unwrap_or_default() + ); + std::thread::sleep(Duration::from_millis(5)); + } +} + +/// Kill directly after the first exchange's progress record: exactly the recorded +/// path holds its restored bytes, the writer never committed and the transcript did +/// not move. Returns the journal and the applied path. +fn kill_after_first_progress(f: &Fixture) -> (String, String) { + f.kill_rewind_at("copy-restore-progress-recorded"); + first_progress(f) +} + +/// The only journal holds exactly one applied change and its restored bytes. +fn first_progress(f: &Fixture) -> (String, String) { + let (journal, intent) = f.only_journal(); + let applied: Vec = serde_json::from_value(intent["applied"].clone()).unwrap(); + assert_eq!(applied.len(), 1, "{intent}"); + assert_eq!(intent["completed"], false); + assert!(unacknowledged(&intent)); + for index in 0..FILES { + let expected = if name(index) == applied[0] { + "before" + } else { + "after" + }; + assert_eq!(f.env.file(&name(index)).as_deref(), Some(expected)); + } + assert_ne!(f.activity(&intent)["phase"], "snapshot_restore_committed"); + (journal, applied[0].clone()) +} + +fn progress_cut_resolution(action: &str) { + let f = Fixture::new(); + let messages = f.env.messages(&f.session); + let (journal, applied) = kill_after_first_progress(&f); + // A fresh service: the failed restore did not move the transcript. + assert_eq!(f.env.messages(&f.session), messages); + assert_eq!(f.catalog_complete(&journal), false); + let requests = f.model.requests().len(); + std::fs::write(f.env.directory.join("unrelated-owner"), "owner data").unwrap(); + let request_id = format!("progress-cut-{action}"); + let request = f.request(&journal, action, &request_id); + let result = f.confirm_acknowledged(&request); + f.assert_resolved(action, &applied); + assert_eq!(f.env.file("unrelated-owner").as_deref(), Some("owner data")); + // Repeating the request is lookup only, even over a later owner edit. + std::fs::write(f.env.directory.join(&applied), "edit after recovery").unwrap(); + let retry = json(&recovery_confirm_cli(&f.env, &f.session, &request)); + assert_eq!(retry["receipt"], result["receipt"]); + assert!(retry["journal_acknowledged"].is_null()); + assert_eq!(f.env.file(&applied).as_deref(), Some("edit after recovery")); + f.assert_quiet(&messages, requests); +} + +#[test] +fn restore_killed_after_a_progress_record_is_kept_without_replay() { + progress_cut_resolution("keep"); +} + +#[test] +fn restore_killed_after_a_progress_record_is_rolled_back_without_replay() { + progress_cut_resolution("rollback"); +} + +fn completion_cut_resolution(action: &str) { + let f = Fixture::new(); + let messages = f.env.messages(&f.session); + f.kill_rewind_at("copy-restore-filesystem-completed"); + let journal = assert_completed_without_writer(&f, &messages); + let requests = f.model.requests().len(); + std::fs::write(f.env.directory.join("unrelated-owner"), "owner data").unwrap(); + let request_id = format!("completion-cut-{action}"); + let result = f.confirm_acknowledged(&f.request(&journal, action, &request_id)); + let expected = if action == "keep" { "before" } else { "after" }; + f.assert_uniform(expected); + assert_eq!(f.env.file("unrelated-owner").as_deref(), Some("owner data")); + // Resolution never commits the interrupted rewind or starts inference. + f.assert_quiet(&messages, requests); + assert_eq!(f.lookup(&request_id, false)["receipt"], result["receipt"]); + f.assert_uniform(expected); +} + +/// Completed filesystem with every displaced image retained and no writer commit. +fn assert_completed_without_writer(f: &Fixture, messages: &[Value]) -> String { + let (journal, intent) = f.only_journal(); + assert_eq!(intent["completed"], true); + assert!(unacknowledged(&intent)); + assert_eq!(f.payloads(&journal), FILES); + f.assert_uniform("before"); + assert_ne!(f.activity(&intent)["phase"], "snapshot_restore_committed"); + assert_eq!(f.env.messages(&f.session), messages); + assert_eq!(f.catalog_complete(&journal), true); + journal +} + +#[test] +fn restore_killed_after_filesystem_completion_with_payloads_is_kept() { + completion_cut_resolution("keep"); +} + +#[test] +fn restore_killed_after_filesystem_completion_with_payloads_is_rolled_back() { + completion_cut_resolution("rollback"); +} + +/// The paired recovery commit is durable when the service dies; neither journal is +/// acknowledged. Restart: lookup reports the receipt without native effects and the +/// explicit acknowledgement publishes only journal metadata. +#[test] +fn paired_recovery_killed_after_writer_commit_reconciles_without_replay() { + let f = Fixture::new(); + let messages = f.env.messages(&f.session); + let (journal, _) = kill_after_first_progress(&f); + let request_id = "paired-writer-cut"; + let request = f.request(&journal, "rollback", request_id); + let requests = f.model.requests().len(); + f.kill_at("recovery-pair-writer-commit", &confirm_args(&f, &request)); + let (receipt, resolution) = assert_pair_committed_unacknowledged(&f, &journal, request_id); + let target = f.edit_as_owner(); + let lookup = f.lookup(request_id, false); + assert_eq!(lookup["receipt"], receipt); + assert!(lookup["journal_acknowledged"].is_null()); + assert!(unacknowledged(&f.intent(&journal)), "lookup acknowledged"); + let reconciled = f.lookup(request_id, true); + assert_eq!(reconciled["receipt"], receipt); + assert_eq!(reconciled["journal_acknowledged"], true); + let original = f.intent(&journal); + assert_eq!(original["acknowledged"], true); + assert_eq!(original["settled_by"], resolution.as_str()); + assert_eq!(f.intent(&resolution)["acknowledged"], true); + // The confirm repeated after restart is lookup only. + let retry = json(&recovery_confirm_cli(&f.env, &f.session, &request)); + assert_eq!(retry["receipt"], receipt); + f.assert_owner_edits(&target); + for index in 1..FILES { + assert_eq!(f.env.file(&name(index)).as_deref(), Some("after")); + } + f.assert_quiet(&messages, requests); +} + +/// Both owners are committed at the writer and both journals are unacknowledged. +/// Returns the committed receipt and the resolution journal. +fn assert_pair_committed_unacknowledged( + f: &Fixture, + journal: &str, + request_id: &str, +) -> (Value, String) { + let original = f.intent(journal); + assert!(unacknowledged(&original)); + assert!(original.get("settled_by").is_none()); + let activity = f.activity(&original); + assert_eq!(activity["status"], "settled"); + assert_eq!(activity["phase"], "snapshot_recovery_committed"); + let receipt = activity["snapshot_receipt"].clone(); + assert_eq!(receipt["request_id"], request_id); + let resolution = receipt["resolution_id"].as_str().unwrap().to_owned(); + assert!(unacknowledged(&f.intent(&resolution))); + f.assert_uniform("after"); + (receipt, resolution) +} + +/// The service dies after acknowledging the paired recovery journals and before the +/// reply; the repeated confirmation returns the committed receipt without replay. +#[test] +fn paired_recovery_killed_after_journal_acknowledgement_returns_the_receipt() { + let f = Fixture::new(); + let messages = f.env.messages(&f.session); + let (journal, _) = kill_after_first_progress(&f); + let request = f.request(&journal, "keep", "paired-ack-cut"); + let requests = f.model.requests().len(); + let args = confirm_args(&f, &request); + f.kill_at("recovery-journal-acknowledged", &args); + let original = f.intent(&journal); + assert_eq!(original["acknowledged"], true); + let receipt = f.activity(&original)["snapshot_receipt"].clone(); + assert_eq!(original["settled_by"], receipt["resolution_id"]); + let target = f.edit_as_owner(); + let retry = json(&recovery_confirm_cli(&f.env, &f.session, &request)); + assert_eq!(retry["state"], "acknowledged"); + assert_eq!(retry["receipt"], receipt); + assert!(retry["journal_acknowledged"].is_null()); + f.assert_owner_edits(&target); + f.assert_quiet(&messages, requests); +} + +/// The service dies after the ordinary restore's journal acknowledgement and before +/// the reply: the rewind is committed once, lookup returns the receipt and the same +/// confirmation never restores again. +#[test] +fn ordinary_restore_killed_after_journal_acknowledgement_never_replays() { + let f = Fixture::new(); + let preview = rewind_preview(&f.env, &f.session, &f.first, "both"); + let requests = f.model.requests().len(); + let confirmation = preview["confirmation"].as_str().unwrap().to_owned(); + let args = [ + "sessions", + "rewind", + f.session.as_str(), + "--to", + f.first.as_str(), + "--target", + "both", + "--confirm", + confirmation.as_str(), + "--format", + "json", + ]; + f.kill_at("ordinary-restore-journal-acknowledged", &args); + let (journal, intent) = f.only_journal(); + assert_eq!(intent["completed"], true); + assert_eq!(intent["acknowledged"], true); + f.assert_uniform("before"); + let target = f.edit_as_owner(); + // A fresh service shows the committed rewind and the exact receipt. + assert!(f.env.user_ids(&f.session).is_empty()); + assert_owned_snapshot_receipt(&f.env, &f.session, &journal); + let route = format!( + "/sessions/{}/rewind/restores/{}", + f.session, + intent["origin"]["activity_id"].as_str().unwrap() + ); + let receipt = json(&f.env.cyber(&["api", "GET", &route]))["data"].clone(); + assert_eq!(receipt["origin"], intent["origin"]); + let messages = f.env.messages(&f.session); + // The retained confirmation is refused and changes nothing. + assert!(!f.env.command(&args).output().unwrap().status.success()); + f.assert_owner_edits(&target); + for index in 1..FILES { + assert_eq!(f.env.file(&name(index)).as_deref(), Some("before")); + } + assert_eq!(f.journals(), vec![journal.clone()]); + assert_eq!(f.intent(&journal), intent); + assert_eq!(f.env.messages(&f.session), messages); + assert_eq!(f.model.requests().len(), requests); +} + +/// Kill a restore at a pre-effect journal construction point, then cancel the exited +/// preparation through the real CLI. Returns whether the journal held an intent. +fn construction_cut_cancellation(point: &str) -> bool { + let f = Fixture::new(); + let messages = f.env.messages(&f.session); + f.kill_rewind_at(point); + let journals = f.journals(); + assert_eq!(journals.len(), 1, "{journals:?}"); + let journal = f.namespace().join("journals").join(&journals[0]); + let has_intent = journal.join("intent.json").exists(); + assert_eq!(f.payloads(&journals[0]), 0, "no image may be staged yet"); + f.assert_uniform("after"); + // New input is fenced until the exited preparation is resolved. + let refused = f.env.cyber(&["exec", "--session", &f.session, "fenced"]); + assert!(!refused.status.success()); + let requests = f.model.requests().len(); + let list = json(&f.env.cyber(&[ + "sessions", + "recovery-preparation", + &f.session, + "--format", + "json", + ])); + let activity = list[0]["activity_id"].as_str().unwrap().to_owned(); + let review = json(&f.env.cyber(&[ + "sessions", + "recovery-preparation", + &f.session, + &activity, + "--format", + "json", + ])); + let body = + json!({"confirmation":review["confirmation"],"request_id":format!("{point}-cancel")}); + let receipt = json(&preparation_confirm_cli( + &f.env, &f.session, &activity, &body, + )); + assert_eq!(receipt["activity_id"], activity.as_str()); + // A repeated confirmation is lookup only. + assert_eq!( + json(&preparation_confirm_cli( + &f.env, &f.session, &activity, &body + )), + receipt + ); + f.assert_uniform("after"); + assert_eq!(f.env.messages(&f.session), messages); + assert_eq!(f.model.requests().len(), requests); + f.env.exec(Some(&f.session), "after cancellation"); + has_intent +} + +#[test] +fn restore_killed_after_origin_before_intent_is_cancelled_without_source_effects() { + assert!(!construction_cut_cancellation( + "copy-restore-origin-published" + )); +} + +#[test] +fn restore_killed_after_intent_before_staging_is_cancelled_without_source_effects() { + assert!(construction_cut_cancellation( + "copy-restore-intent-published" + )); +} + +/// Kill a rollback resolution right after its first exchange's progress record. The +/// interrupted resolution is retained as independent evidence: its own request stays +/// pending without replay, the resolution journal is resolved on its own, and only +/// then can the original journal be settled by a new reviewed request. +#[test] +fn interrupted_resolution_is_retained_and_resolved_as_independent_evidence() { + let f = Fixture::new(); + let messages = f.env.messages(&f.session); + let (journal, applied) = kill_after_first_progress(&f); + let request = f.request(&journal, "rollback", "interrupted-resolution"); + let requests = f.model.requests().len(); + f.kill_at( + "copy-restore-progress-recorded", + &confirm_args(&f, &request), + ); + let child = interrupted_child(&f, &journal, &applied); + assert_not_redispatched(&f, &request, &applied); + // The resolution journal is resolved on its own. + let kept = f.confirm_acknowledged(&f.request(&child, "keep", "child-keep")); + let resolution = f.intent(&child); + assert_eq!(resolution["acknowledged"], true); + assert_eq!(resolution["settled_by"], kept["receipt"]["resolution_id"]); + assert_eq!( + f.lookup("interrupted-resolution", false)["state"], + "resolved_by_another_request" + ); + assert!(unacknowledged(&f.intent(&journal))); + let fenced = f.env.cyber(&["exec", "--session", &f.session, "fenced"]); + assert!(!fenced.status.success()); + // The original journal still needs its own reviewed settlement. + f.confirm_acknowledged(&f.request(&journal, "keep", "parent-keep")); + f.assert_uniform("after"); + f.assert_quiet(&messages, requests); + f.env.exec(Some(&f.session), "after recovery"); +} + +/// The killed resolution left its own incomplete journal beside the original. +fn interrupted_child(f: &Fixture, journal: &str, applied: &str) -> String { + let journals = f.journals(); + assert_eq!(journals.len(), 2, "{journals:?}"); + let child = journals + .iter() + .find(|id| id.starts_with("restore_resolution_")) + .unwrap() + .clone(); + let resolution = f.intent(&child); + assert_eq!(resolution["applied"], json!([applied])); + assert_eq!(resolution["completed"], false); + assert!(unacknowledged(&resolution)); + assert!(unacknowledged(&f.intent(journal))); + f.assert_uniform("after"); + child +} + +/// Repeating the interrupted request reports it pending and never touches files. +fn assert_not_redispatched(f: &Fixture, request: &Value, applied: &str) { + std::fs::write(f.env.directory.join(applied), "owner edit").unwrap(); + let retry = recovery_confirm_cli(&f.env, &f.session, request); + assert_eq!(retry.status.code(), Some(1)); + let stderr = String::from_utf8_lossy(&retry.stderr); + assert!(stderr.contains("Recovery is not acknowledged"), "{stderr}"); + let retry: Value = serde_json::from_slice(&retry.stdout).unwrap(); + assert_eq!(retry["state"], "pending"); + assert_eq!( + f.lookup("interrupted-resolution", false)["state"], + "pending" + ); + assert_eq!(f.env.file(applied).as_deref(), Some("owner edit")); + std::fs::write(f.env.directory.join(applied), "after").unwrap(); +} + +/// An interrupted staged code undo in a Session that also has an inactive branch: +/// keep or rollback settles the native journal without staging, committing or +/// discarding conversation state, and the branch stays exportable. +fn staged_undo_partial(action: &str) { + let f = Fixture::new(); + let branch = inactive_branch(&f); + let messages = f.env.messages(&f.session); + let selection = reviewed_selection(&f.env, &f.first, "code", "stage"); + let mut body = selection.clone(); + body["confirmation"] = reviewed_preview(&f.env, &f.session, &selection)["confirmation"].clone(); + let path = format!("/sessions/{}/rewind/confirm", f.session); + let body = body.to_string(); + f.kill_at( + "copy-restore-progress-recorded", + &["api", "POST", &path, "-d", &body], + ); + let (journal, applied) = first_progress(&f); + assert!(session_revert(&f.env, &f.session).is_null()); + assert_eq!(f.env.messages(&f.session), messages); + let requests = f.model.requests().len(); + f.confirm_acknowledged(&f.request(&journal, action, &format!("staged-{action}"))); + f.assert_resolved(action, &applied); + // Recovery neither stages nor commits the interrupted undo and keeps the branch. + assert!(session_revert(&f.env, &f.session).is_null()); + assert_branch_kept(&f, &branch); + f.assert_quiet(&messages, requests); + // A new staged undo is admitted and cleared normally afterwards. + assert!(!reviewed_apply(&f.env, &f.session, &selection).is_null()); + f.assert_uniform("before"); + let clear = reviewed_selection(&f.env, &f.first, "code", "clear"); + reviewed_apply(&f.env, &f.session, &clear); + assert!(session_revert(&f.env, &f.session).is_null()); +} + +/// Add a third turn and rewind the conversation before it, leaving it inactive. +fn inactive_branch(f: &Fixture) -> String { + f.env.exec(Some(&f.session), "third prompt"); + let users = f.env.user_ids(&f.session); + assert_eq!(users.len(), 3); + let preview = rewind_preview(&f.env, &f.session, &users[2], "conversation"); + json(&confirm_rewind( + &f.env, + &f.session, + &users[2], + "conversation", + &preview, + )); + assert_branch_kept(f, &users[2]); + users[2].clone() +} + +/// The branch message is inactive in the tree and still exportable. +fn assert_branch_kept(f: &Fixture, message: &str) { + assert!( + f.env + .tree(&f.session) + .iter() + .any(|node| node["id"] == message && node["active"] == false) + ); + let exported = json( + &f.env + .cyber(&["sessions", "export", &f.session, "--all-branches"]), + ); + assert!(exported.to_string().contains(message)); +} + +#[test] +fn interrupted_staged_undo_with_an_inactive_branch_is_kept() { + staged_undo_partial("keep"); +} + +#[test] +fn interrupted_staged_undo_with_an_inactive_branch_is_rolled_back() { + staged_undo_partial("rollback"); +} + +/// The private journal namespace is replaced (by an equal-content copy, then by a +/// symlink alias) between review and confirmation: confirmation refuses before any +/// source effect, and the reviewed recovery succeeds once the original is back. +#[test] +fn replaced_private_journal_namespace_refuses_recovery_without_effects() { + let f = Fixture::new(); + let messages = f.env.messages(&f.session); + let (journal, applied) = kill_after_first_progress(&f); + let request = f.request(&journal, "rollback", "namespace-swap"); + let journals = f.namespace().join("journals"); + let retained = f.namespace().join("journals.retained"); + std::fs::rename(&journals, &retained).unwrap(); + let copied = Command::new("cp") + .arg("-Rp") + .arg(&retained) + .arg(&journals) + .status() + .unwrap(); + assert!(copied.success()); + let refusals = |label: &str, reason: &str| { + let refused = recovery_confirm_cli(&f.env, &f.session, &request); + assert!(!refused.status.success(), "{label} namespace was admitted"); + let stderr = String::from_utf8_lossy(&refused.stderr); + assert!(stderr.contains(reason), "{label}: {stderr}"); + assert_eq!(f.env.file(&applied).as_deref(), Some("before"), "{label}"); + let mut names: Vec = std::fs::read_dir(&retained) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + assert_eq!(names, vec![journal.clone()], "{label}"); + }; + refusals("copied", "Intent slot identity changed"); + std::fs::remove_dir_all(&journals).unwrap(); + std::os::unix::fs::symlink(&retained, &journals).unwrap(); + // The alias is never followed. + refusals("aliased", "Not a directory"); + std::fs::remove_file(&journals).unwrap(); + std::fs::rename(&retained, &journals).unwrap(); + f.confirm_acknowledged(&request); + f.assert_uniform("after"); + assert_eq!(f.env.messages(&f.session), messages); +} diff --git a/crates/cyber-server/src/runtime/snapshot_work.rs b/crates/cyber-server/src/runtime/snapshot_work.rs index ff98f825..9d6eaec2 100644 --- a/crates/cyber-server/src/runtime/snapshot_work.rs +++ b/crates/cyber-server/src/runtime/snapshot_work.rs @@ -621,9 +621,13 @@ impl SnapshotCompletion { if let Some(original) = &mut self.worker._original { original.claims = claims.original; } + // Fixture point: the owner pair committed; the native journals are unacknowledged. + super::process_cut::pause("recovery-pair-writer-commit"); self.native.guard.acknowledge(self.worker.scope.snapshot_origin()).map_err(|error| RuntimeError::Conflict(format!( "Recovery runtime acknowledgement committed; native journal acknowledgement requires reconciliation: {error}" )))?; + // Fixture point: the native journals are acknowledged; no reply was sent. + super::process_cut::pause("recovery-journal-acknowledged"); Ok(receipt) } pub(crate) fn commit( @@ -681,7 +685,10 @@ impl SnapshotCompletion { .acknowledge(self.worker.scope.snapshot_origin()) .map_err(|error| RuntimeError::Conflict(format!( "Snapshot runtime acknowledgement committed; native journal acknowledgement requires reconciliation: {error}" - ))) + )))?; + // Fixture point: the native journal is acknowledged; no reply was sent. + super::process_cut::pause("ordinary-restore-journal-acknowledged"); + Ok(()) } } diff --git a/crates/cyber-snapshot/src/copy/restore.rs b/crates/cyber-snapshot/src/copy/restore.rs index 6d8e590b..58a2b1cf 100644 --- a/crates/cyber-snapshot/src/copy/restore.rs +++ b/crates/cyber-snapshot/src/copy/restore.rs @@ -446,6 +446,8 @@ impl Store { .transpose() .map_err(RestoreError::Failed)?; journal.origin = origin; + // Fixture point: the origin is published; its journal has no intent yet. + cyber_core::process_cut::pause("copy-restore-origin-published"); let construction = if worker.is_some() { Some( @@ -456,6 +458,8 @@ impl Store { Self::record(&dir, journal).map_err(RestoreError::Failed)?; None }; + // Fixture point: the intent is published; no target image is staged yet. + cyber_core::process_cut::pause("copy-restore-intent-published"); let preimages = self .resolution_preimages(journal.resolution.as_ref()) .map_err(RestoreError::Failed)?; @@ -554,6 +558,8 @@ impl Store { } journal.applied.push(journal.changes[i].path.clone()); Self::record(&dir, journal).map_err(RestoreError::Failed)?; + // Fixture point: one exchange and its progress record are durable. + cyber_core::process_cut::pause("copy-restore-progress-recorded"); } drop(preimages); self.verify_root().map_err(RestoreError::Failed)?; @@ -561,6 +567,8 @@ impl Store { .map_err(RestoreError::Failed)?; journal.completed = true; Self::record(&dir, journal).map_err(RestoreError::Failed)?; + // Fixture point: filesystem completion is durable; no writer commit yet. + cyber_core::process_cut::pause("copy-restore-filesystem-completed"); Ok(journal.applied.clone()) } From 2c349f31e2cb6e05cd6ea957da5ed38a16503987 Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 16:36:12 -0400 Subject: [PATCH 09/20] Document interrupted keep/rollback recovery and record the new cut evidence docs/rewind.md explains how an interrupted resolution journal is resolved before the original. implementation.md updates the M8 cut matrix and records the increment; tasks.md notes per managed-recovery task (local macOS arm64 only, platform acceptance still open). --- docs/rewind.md | 24 +++++- .../implementation.md | 77 +++++++++++++++++-- .../complete-daily-coding-surfaces/tasks.md | 6 ++ 3 files changed, 101 insertions(+), 6 deletions(-) diff --git a/docs/rewind.md b/docs/rewind.md index d82cbc0c..b12a2c88 100644 --- a/docs/rewind.md +++ b/docs/rewind.md @@ -134,7 +134,12 @@ runtime and checks that subtree stop reports retained unknown evidence, keeps admission closed and does not replay restoration. This is not a native partial-replacement crash test. The file-copy suite additionally kills a real worker between native file replacements, then verifies retained preimages, an incomplete journal and refusal -to replay. Broader cut-point/metadata/platform acceptance and managed resolution +to replay. Real-binary cases also kill the service at debug-only fixture points: +after origin and before intent publication, after the intent and before staging, +directly after a progress record (for an ordinary rewind, a staged undo beside an +inactive branch, and inside a keep/rollback), after filesystem completion with +displaced images, after the paired recovery writer commit, and after a journal +acknowledgement whose reply was never sent. Broader cut-point/metadata/platform acceptance and managed resolution remain required. Git restore has not gained this new journal. ## Non-Git storage and retained restore intents @@ -442,6 +447,23 @@ conversation. Confirmation/reconciliation exits 1 if the returned state does not establish the requested acknowledgement. Lookup itself can return an unresolved state with exit 0 because the read succeeded. Both commands support `--format json`. +If the keep/rollback itself is interrupted (for example the service dies between +its file exchanges), its resolution journal (`restore_resolution_...`) is listed as +a separate journal next to the original. The interrupted request stays `pending`; +repeating it never resumes or replays it. Review and confirm keep or rollback for +the resolution journal first. The interrupted request then reports +`resolved_by_another_request`, and the original journal still needs its own review +and a new request ID before new input is admitted: + +```sh +cyber sessions recovery ses_example restore_resolution_example --action keep +cyber sessions recovery ses_example restore_resolution_example --action keep \ + --confirm --request-id resolution-keep +cyber sessions recovery ses_example restore_example --action keep +cyber sessions recovery ses_example restore_example --action keep \ + --confirm --request-id original-keep +``` + These commands expose the implemented managed file-copy recovery path on admitted Linux/macOS hosts. Ordinary managed Git source recovery remains disabled by default (owner decision 2026-11-15): it stays off until the native CI matrix is green and diff --git a/openspec/changes/complete-daily-coding-surfaces/implementation.md b/openspec/changes/complete-daily-coding-surfaces/implementation.md index 3c6454ab..225d01e3 100644 --- a/openspec/changes/complete-daily-coding-surfaces/implementation.md +++ b/openspec/changes/complete-daily-coding-surfaces/implementation.md @@ -3957,13 +3957,13 @@ macOS arm64; no Linux, macOS Intel or Windows result is claimed. | Cut | Process-death evidence | Gap | | --- | --- | --- | | Before intent (reservation/lifetime before origin) | storage: `real_process_death_before_publication_retains_stage_without_poisoning_the_owner_name`, `real_process_death_releases_only_the_exact_worker_lifetime_lock`; real service: `exited_pre_origin_preparation_is_reviewed_cancelled_and_lookup_only_after_restart` | none locally for file-copy | -| After intent (origin published, before source admission) | real service: `exited_origin_preparation_before_source_admission_is_cancelled_after_real_kill` | the real-service cut does not assert that intent publication was absent | +| After intent (origin published, before source admission) | real service: `exited_origin_preparation_before_source_admission_is_cancelled_after_real_kill`; fixture points (2026-11-16): `restore_killed_after_origin_before_intent_is_cancelled_without_source_effects` (no `intent.json`), `restore_killed_after_intent_before_staging_is_cancelled_without_source_effects` (intent, no staged image) | none locally for file-copy | | Stage preparation | storage: `process_kill_at_parent_and_file_cuts_recovers_ownership_without_progress_or_replay` (parent cuts); real service: `fully_prepared_pre_effect_cancellation_reclaims_only_persisted_target_inodes`, `copy_cancelled_deletion_preparation_retires_zero_payload` | partial target-image construction is not cut by a real service kill | | Every exchange | storage: `process_kill_at_parent_and_file_cuts_recovers_ownership_without_progress_or_replay`, `process_kill_at_link_parent_and_exchange_cuts_preserves_typed_inode_evidence` (each exchange of a small fixture); real service: `managed_keep_and_rollback_after_real_partial_restore_kill_preserve_owner_files_and_never_replay` (one sampled partial exchange, keep and rollback) | real-service kills sample one partial window; they are not placed at each exchange | -| Progress | none | **gap**: storage cuts write no progress record and the sampled real kill does not assert which progress record existed; no cut directly after a progress write | -| Filesystem completion (completed intent, before writer commit) | real service: `copy_kept_creation_after_completed_source_kill_retires_zero_payload` (writer held off by a SQLite write lock) | **gap**: covered for a zero-payload creation only, not for displaced payload images | -| Writer commit (committed Session writer, unacknowledged journal) | real service: `ordinary_restore_killed_after_writer_commit_before_journal_ack_reconciles_without_replay` (new; debug-only `ordinary-restore-writer-commit` fixture point) | **gap**: the paired keep/rollback recovery commit is only simulated by resetting acknowledgement metadata (`managed_keep_and_rollback_after_real_partial_restore_kill_preserve_owner_files_and_never_replay`) | -| Journal acknowledgement | storage: `process_death_during_spare_write_preserves_active_intent_and_reopens_without_replay` (the intent-slot write the acknowledgement uses); managed checkout claim: `killed_acknowledgement_resumes_without_rewriting_claim_or_deleting_partial_stage`, `killed_construction_keeps_locked_complete_stage_and_never_creates_or_replays_stable_claim` | **gap**: no real-service SIGKILL after the ordinary journal acknowledgement and before the HTTP reply; only service stop/restart lookups | +| Progress | real service (2026-11-16, `copy-restore-progress-recorded`): `restore_killed_after_a_progress_record_is_kept_without_replay`, `..._is_rolled_back_without_replay`, `interrupted_staged_undo_with_an_inactive_branch_is_kept`/`_rolled_back`, and inside a resolution `interrupted_resolution_is_retained_and_resolved_as_independent_evidence` | none locally for file-copy (first progress record only) | +| Filesystem completion (completed intent, before writer commit) | real service: `copy_kept_creation_after_completed_source_kill_retires_zero_payload`; fixture point (2026-11-16, `copy-restore-filesystem-completed`): `restore_killed_after_filesystem_completion_with_payloads_is_kept`/`_rolled_back` (four displaced images) | none locally for file-copy | +| Writer commit (committed Session writer, unacknowledged journal) | real service: `ordinary_restore_killed_after_writer_commit_before_journal_ack_reconciles_without_replay`; paired recovery (2026-11-16, `recovery-pair-writer-commit`): `paired_recovery_killed_after_writer_commit_reconciles_without_replay` | none locally for file-copy | +| Journal acknowledgement | storage: `process_death_during_spare_write_preserves_active_intent_and_reopens_without_replay`; managed checkout claim: `killed_acknowledgement_resumes_without_rewriting_claim_or_deleting_partial_stage`, `killed_construction_keeps_locked_complete_stage_and_never_creates_or_replays_stable_claim`; after the acknowledgement, before the reply (2026-11-16): `ordinary_restore_killed_after_journal_acknowledgement_never_replays` (`ordinary-restore-journal-acknowledged`), `paired_recovery_killed_after_journal_acknowledgement_returns_the_receipt` (`recovery-journal-acknowledged`) | none locally for file-copy | | Reclaim | real service fixture + separate maintenance process: `ordinary_restore_killed_during_payload_reclaim_resumes_frozen_plan` (new; after the durable plan and the first unlink, inside the deletion transaction); App: `actual_process_death_preserves_plan_and_resumes_without_source_replay` (before deletion and after all deletions); collection: `process_death_after_last_manifest_unlink_resumes_from_durable_policy_provenance` | **gap**: paired keep/rollback payload cleanup is interrupted in-process only (`managed_native_recovery_after_partial_kill`, `native_retirement_resumes_before_and_after_deletion_without_rewriting_acknowledgement`); managed Git paired/prepared metadata retirement now has App SIGKILL cuts (see the section below), paired/prepared payload reclaim still does not | New in this increment (`crates/cyber-cli/tests/support/ordinary_cuts.rs`, part of @@ -4255,3 +4255,70 @@ the evidence is gone). No code changed; construction evidence keeps no cleanup authority until that change is approved and implemented. A separate change validates cleanly and keeps the security-relevant protocol revision reviewable on its own. + +## Managed recovery fixture-point cuts and recovery scenarios (2026-11-16, local) + +Branch `feat/managed-recovery-resolution` (stacked on `feat/construction-evidence-discard` +and `feat/managed-recovery-owner`). Test-only evidence plus debug-only fixture points; +no recovery protocol or product behavior changed and no defect was found. + +New `cyber_core::process_cut::pause` points (compiled out of release builds): +`copy-restore-origin-published` and `copy-restore-intent-published` (journal +construction in `cyber-snapshot` `copy/restore.rs::execute_journal`), +`copy-restore-progress-recorded` (after each exchange's progress record, so the first +one stops the process; it also fires inside a keep/rollback resolution) and +`copy-restore-filesystem-completed` (after the completed intent, before the writer), +plus `recovery-pair-writer-commit`, `recovery-journal-acknowledged` and +`ordinary-restore-journal-acknowledged` in `cyber-server` `runtime/snapshot_work.rs`. + +Real-binary cases in `crates/cyber-cli/tests/support/restore_cuts.rs` (part of +`branches_cli`; non-Git Location with four displaced images; the service started with +the point is SIGKILLed once the marker appears; every case checks that the transcript +does not move and the scripted model gets no request): + +- M2/M8 journal construction: `restore_killed_after_origin_before_intent_is_cancelled_without_source_effects` + (journal directory without `intent.json`) and + `restore_killed_after_intent_before_staging_is_cancelled_without_source_effects`. + New input is refused, the exited preparation is reviewed and cancelled through + `sessions recovery-preparation`, a repeated confirmation returns the same receipt, + sources are unchanged and the next prompt is admitted. +- M2: `binary_document_activity_never_grants_snapshot_recovery_authority` + (`cyber-server` unit): a binary-document owner can neither publish a snapshot origin + nor pass recovery review, and the refusal writes nothing. +- M3: `replaced_private_journal_namespace_refuses_recovery_without_effects`: after a + partial restore and a reviewed rollback, the private `journals` directory is replaced + by an equal-content copy (refused: `Intent slot identity changed`) and then by a + symlink alias to the original (refused: `Not a directory`, never followed). No + source changes and no resolution journal appears; once the original directory is + back the same request succeeds. +- M4: `restore_killed_after_a_progress_record_is_kept_without_replay` / + `..._is_rolled_back_without_replay` (exactly the recorded path holds restored bytes; + keep/rollback through the CLI; a repeated confirmation is lookup only over a later + owner edit). `interrupted_staged_undo_with_an_inactive_branch_is_kept` / + `_rolled_back`: a staged code undo is killed after its first progress record in a + Session with an inactive branch; recovery neither stages nor commits it, the branch + stays inactive and exportable, and a new staged undo and clear work afterwards. + `interrupted_resolution_is_retained_and_resolved_as_independent_evidence`: a + rollback resolution killed after its first progress record leaves a separate + `restore_resolution_*` journal; the interrupted request stays `pending` and a + repeat is not redispatched (an owner edit survives); keep on the resolution journal + settles it and the request reports `resolved_by_another_request`; new input stays + fenced until the original journal gets its own reviewed keep. +- M5: `paired_recovery_killed_after_writer_commit_reconciles_without_replay` replaces + the simulated paired writer-commit cut: both owners are committed (`snapshot_recovery_committed` + with the receipt) and both journals are unacknowledged; lookup does not acknowledge; + `--acknowledge` publishes only metadata (`settled_by` names the resolution) over + later owner edits; a repeated confirmation is lookup only. +- M8: `restore_killed_after_filesystem_completion_with_payloads_is_kept` / + `_rolled_back` (completed intent, four retained images, no writer commit); + `ordinary_restore_killed_after_journal_acknowledgement_never_replays` (the rewind is + committed once; lookup returns the receipt; the retained confirmation is refused and + changes nothing); `paired_recovery_killed_after_journal_acknowledgement_returns_the_receipt`. + +Verification (local macOS arm64 only): the 15 new `restore_cuts` cases and the full +`branches_cli` binary under nextest `ci` (`--test-threads 4`); `cyber-server` +`snapshot_recovery` unit tests. No Linux, macOS Intel or Windows result is claimed. +Still open: paired/prepared payload-reclaim process death, real kills at later +progress records and in Git (`native-git-acceptance`) equivalents of these cuts, +HTTP route tests and a real-server SDK test for recovery, a TUI path from +"Code unavailable" into journal recovery, and the platform matrix. diff --git a/openspec/changes/complete-daily-coding-surfaces/tasks.md b/openspec/changes/complete-daily-coding-surfaces/tasks.md index ace4fe4b..19236876 100644 --- a/openspec/changes/complete-daily-coding-surfaces/tasks.md +++ b/openspec/changes/complete-daily-coding-surfaces/tasks.md @@ -59,6 +59,7 @@ recovery implementation. - [x] M1 Record the user's 3.0 decision in managed-recovery.md and reconcile any requested revisions with the snapshot spec delta before implementation. Approved without protocol revisions on 2026-11-06. - [ ] M2 Add immutable snapshot-worker origin and request ownership to the runtime activity and snapshot ports. Retain actual lifecycle/checkout/store/mutation owners inside the synchronous worker through its last filesystem call. Test request disposal, cancellation, shutdown and a foreign/live worker; never reuse binary-document or generic-process acknowledgement authority. + - Note (2026-11-16, local macOS arm64 only): native journal construction now has real service kills at debug-only points after origin publication with no `intent.json` and after the intent with no staged image; both are cancelled through `sessions recovery-preparation` without source effects, and the next prompt is admitted. `binary_document_activity_never_grants_snapshot_recovery_authority` pins that a binary-document owner never gets snapshot origin or recovery authority. Construction-stage cleanup is now provided by `add-construction-evidence-discard` (PR #138). See implementation.md "Managed recovery fixture-point cuts". Platform acceptance keeps M2 open. - Note (2026-11-14, local macOS arm64 only): partial construction is fenced by design. `killed_checkout_claim_construction_retains_private_evidence_and_fences_reclamation` and `killed_acknowledgement_construction_retains_stage_and_fences_retirement` SIGKILL a child after the private stage flush and before no-replace publication; the real-service case `checkout_claim_construction_kill_retains_unknown_evidence_and_blocks_prompt_admission` (`native-git-acceptance`) kills the server at the debug-only `checkout-claim-stage-flushed` point. The stage stays byte-identical, no stable claim/acknowledgement appears, new input is refused until the pre-effect preparation is cancelled, and reuse, retirement and removal refuse with `same-owner unknown constructor`. Cleaning up construction evidence needs a separate construction-recovery protocol extension; nothing here grants that authority. Other M2 obligations and platform acceptance keep M2 open. Runtime-construction disposal now has the same ordered ownership as a completed @@ -70,8 +71,11 @@ partial-journal construction and complete crash/platform acceptance still leave M2 open. - [ ] M3 Add versioned origin-bound Git and file-copy intents, preserved displaced preimages and resolution-intent records. Keep legacy journals inspectable without inventing origin proof. Test missing/corrupt records, private namespace replacement, aliases, metadata and Location mismatch before admitting effects. + - Note (2026-11-16, local macOS arm64 only): `replaced_private_journal_namespace_refuses_recovery_without_effects` replaces the private journal directory between review and confirmation with an equal-content copy and with a symlink alias; both refuse before any source effect and the same request succeeds once the original is back. Git (`native-git-acceptance`) namespace replacement and missing/corrupt Git `intent.json` cases, and platform acceptance, keep M3 open. - [ ] M4 Implement bounded keep/rollback planning and fingerprint revalidation under exact native locks. Preserve unrelated edits, refuse the complete plan on conflicts, and retain any interrupted resolution as independent evidence. Test keep and rollback after actual partial namespace replacement, including staged undo and inactive branches. + - Note (2026-11-16, local macOS arm64 only): keep and rollback after a real kill directly after a progress record, including a staged code undo in a Session with an inactive branch (recovery neither stages nor commits; the branch stays exportable), and a keep/rollback resolution itself killed mid-exchange: its journal is retained as independent evidence, the interrupted request is never redispatched and reports `resolved_by_another_request` once that journal is resolved, and the original needs its own reviewed request (`docs/rewind.md`). Git equivalents and platform acceptance keep M4 open. - [ ] M5 Atomically validate and commit the exact origin acknowledgement and resolution receipt at the Store writer. Determine the bounded owner aggregates before extending the single-aggregate append API. Test late CAS/projector/validation failure rollback, absence of uncommitted notifications and committed-but-lost writer replies; repeat request lookup must never mutate files again. + - Note (2026-11-16, local macOS arm64 only): the paired keep/rollback writer-commit cut is now a real service kill (`paired_recovery_killed_after_writer_commit_reconciles_without_replay`, debug-only `recovery-pair-writer-commit`) instead of an acknowledgement-metadata reset; lookup stays read-only and `--acknowledge` writes metadata only over later owner edits. Platform acceptance keeps M5 open. M5 implementation now uses `Store::append_pair_checked` for the exact original native owner and the resolution request owner. A Session-creation/request-derived @@ -118,10 +122,12 @@ Unprepared reservation/origin/intent cuts still require exact resource ownership proof; missing records alone do not license acknowledgement. - [ ] M6 Publish journal acknowledgement only after observed durable Store settlement. Add reference/reader/lease-aware eligibility and durable two-phase reclamation with retained retry receipts. Test cap pressure, disabled/zero retention, incomplete reference views and crashes at writer/journal/reclaim boundaries without deleting unresolved evidence. + - Note (2026-11-16, local macOS arm64 only): real kills after the ordinary and paired journal acknowledgements and before the reply return the committed receipt without replay. Paired/prepared payload-reclaim process death and platform acceptance keep M6 open. - Note (2026-11-14, local macOS arm64 only): construction evidence is outside reclamation by design. Claim and acknowledgement stages refuse removal and metadata retirement as `same-owner unknown constructor` evidence, and the prepared-cancellation cleanup case now also refuses an interrupted cancellation-record stage (`tmp_*` with the complete receipt bytes) as an unknown journal entry, keeping its bytes; `interrupted_cancellation_record_construction_is_retained_and_never_adopted` shows a retried receipt publishes without adopting it. Removing such stages needs a separate construction-recovery protocol extension. M6 stays open for the remaining reclamation obligations. - [ ] M7 Add owner recovery review/confirm/lookup HTTP routes, typed CLI and SDK operations, and TUI recovery entry from rewind unavailability. Regenerate OpenAPI/SDK/command artifacts; exercise the real clients with no inference or transcript movement and with stale/foreign request refusal. - Note (2026-11-14, local macOS arm64 only): preparation listing stays available for a Session whose managed worktree was removed (`managed_git_removed_location_keeps_preparation_listing`); the construction-name inventory is advisory and the `sessions recovery` hint is best-effort. Journal listing (`GET /sessions/{id}/rewind/recovery`, and so `sessions recovery`) for a removed Location failed with "No such file or directory". Owner decision 2026-11-15: such a Session is listed as orphaned and read-only. Its retained journals are found from their own records (recorded path equal to the Location, namespace key equal to the digest of that path and recorded directory identity) and returned with `location_removed: true`; nothing is locked, created or deleted, review fails, the CLI text marks rows `Location removed (orphaned, read-only)` and the TUI panel shows the removal and starts no discovery for them (`removed_location_lists_its_retained_journals_read_only` in `cyber-snapshot`, `removed_location_recovery_lists_retained_journals_as_orphaned` in `branches_cli`, TUI `a_removed_location_journal_is_listed_read_only`; OpenAPI/SDK regenerated). M7 stays open. - [ ] M8 Run process-kill cuts before/after intent, stage preparation, every exchange, progress, filesystem completion, writer commit, journal acknowledgement and reclaim. Obtain Linux x64/ARM and macOS Intel/ARM positives/denials, explicit Windows results/limits and shared Git/binary regressions; update evidence and perform substantive code/security review before accepting parent tasks. + - Note (2026-11-16, local macOS arm64 only): the matrix gaps for after-intent, progress, filesystem completion with displaced images, paired writer commit and journal acknowledgement before the reply are now covered by real service kills at debug-only fixture points (`restore_cuts.rs`; implementation.md matrix updated). Remaining: paired/prepared payload-reclaim process death, Git equivalents, platform results (Linux x64/ARM, macOS Intel, Windows limits) and the substantive review under 7.2/7.3, so M8 stays open. - Note (2026-11-14, local macOS arm64 only): implementation.md "M8 process-death cut matrix for file-copy restore" maps every named cut to the tests that kill a real process there and marks the gaps. New real-binary cases: `ordinary_restore_killed_after_writer_commit_before_journal_ack_reconciles_without_replay` (service killed at a debug-only fixture point between the Session writer commit and the native journal acknowledgement; receipt-only lookup and metadata acknowledgement on restart, owner edits kept, no transcript movement or inference) and `ordinary_restore_killed_during_payload_reclaim_resumes_frozen_plan` (maintenance process killed inside the deletion transaction after the first unlink; a fresh owner completes the same frozen plan once). Open gaps from the table: no cut directly after a progress write; filesystem completion only for a zero-payload creation; the paired recovery writer-commit cut is simulated; no real kill after the ordinary journal acknowledgement and before the reply; paired/prepared payload cleanup is interrupted in-process only (paired keep/rollback and prepared-cancellation metadata retirement now have real App SIGKILL cuts, see implementation.md "Managed paired/prepared metadata process death"). Platform results, shared Git/binary regressions and the review also remain, so M8 stays open. - Note (2026-11-14, local macOS arm64 only): constructor cuts. Real process death between the flushed private stage and its no-replace publication is now covered for checkout claim and acknowledgement construction (child-process SIGKILL in `cyber-core`) and for the claim through the real CLI/service; see implementation.md "Partial-construction cuts". The cancellation-record stage is a state-level cut (storage abort and planted stage in cleanup), not a process kill. Platform results remain, so M8 stays open. From 0516045945224668ba1b8de8983ef2ae460973c2 Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 16:39:43 -0400 Subject: [PATCH 10/20] Test the terminal path from an unavailable code preview into journal recovery A code preview refused because a retained restore needs owned recovery shows the recovery hint, and C sends a recovery listing request instead of another preview. --- crates/cyber-tui/src/view/rewind.rs | 58 +++++++++++++++++++ .../complete-daily-coding-surfaces/tasks.md | 1 + 2 files changed, 59 insertions(+) diff --git a/crates/cyber-tui/src/view/rewind.rs b/crates/cyber-tui/src/view/rewind.rs index 22d03ed6..0fd48909 100644 --- a/crates/cyber-tui/src/view/rewind.rs +++ b/crates/cyber-tui/src/view/rewind.rs @@ -247,4 +247,62 @@ mod tests { ); assert!(text.contains("2 conversation"), "{text}"); } + + /// A code preview refused because a retained restore needs owned recovery shows + /// the recovery hint, and C opens journal recovery instead of another preview. + #[test] + fn code_unavailable_preview_enters_journal_recovery_with_c() { + const FENCED: &str = "Snapshot worker outcome requires owned recovery before new input"; + let mut app = App::new( + Session { + id: "ses_one".into(), + directory: "/project".into(), + ..Default::default() + }, + vec![], + "cyber", + ); + app.open_rewind(Intent::Menu); + app.rewind.boundaries = vec![Boundary { + id: "msg_first".into(), + text: "first prompt".into(), + }]; + let selection = RewindSelection { + action: RewindAction::Commit, + message_id: "msg_first".into(), + target: RevertTarget::Code, + expected_directory: "/project".into(), + }; + let Some(Action::Rewind(request)) = app.rewind_request(Command::Preview(selection)).pop() + else { + panic!("expected a rewind preview request"); + }; + crate::rewind::apply( + &mut app, + &mut Default::default(), + request, + Err(FENCED.into()), + ); + let text = screen(&app); + assert!( + text.contains(&format!( + "Code unavailable/conflicting: {FENCED} · C inspects retained recovery" + )), + "{text}" + ); + let mut actions = app.rewind_key(crossterm::event::KeyEvent::from( + crossterm::event::KeyCode::Char('c'), + )); + assert_eq!(app.rewind.phase, Phase::Recovery); + let Some(Action::Rewind(request)) = actions.pop() else { + panic!("expected a recovery listing request"); + }; + assert!(actions.is_empty()); + assert_eq!(request.session, "ses_one"); + assert!(matches!( + request.command, + Command::Recovery(crate::recovery::Command::List) + )); + assert!(app.rewind.preview.is_none()); + } } diff --git a/openspec/changes/complete-daily-coding-surfaces/tasks.md b/openspec/changes/complete-daily-coding-surfaces/tasks.md index 19236876..f6ad123f 100644 --- a/openspec/changes/complete-daily-coding-surfaces/tasks.md +++ b/openspec/changes/complete-daily-coding-surfaces/tasks.md @@ -125,6 +125,7 @@ proof; missing records alone do not license acknowledgement. - Note (2026-11-16, local macOS arm64 only): real kills after the ordinary and paired journal acknowledgements and before the reply return the committed receipt without replay. Paired/prepared payload-reclaim process death and platform acceptance keep M6 open. - Note (2026-11-14, local macOS arm64 only): construction evidence is outside reclamation by design. Claim and acknowledgement stages refuse removal and metadata retirement as `same-owner unknown constructor` evidence, and the prepared-cancellation cleanup case now also refuses an interrupted cancellation-record stage (`tmp_*` with the complete receipt bytes) as an unknown journal entry, keeping its bytes; `interrupted_cancellation_record_construction_is_retained_and_never_adopted` shows a retried receipt publishes without adopting it. Removing such stages needs a separate construction-recovery protocol extension. M6 stays open for the remaining reclamation obligations. - [ ] M7 Add owner recovery review/confirm/lookup HTTP routes, typed CLI and SDK operations, and TUI recovery entry from rewind unavailability. Regenerate OpenAPI/SDK/command artifacts; exercise the real clients with no inference or transcript movement and with stale/foreign request refusal. + - Note (2026-11-16, local macOS arm64 only): TUI `code_unavailable_preview_enters_journal_recovery_with_c` shows the recovery hint on a code preview refused by a retained restore and opens journal recovery (a recovery listing request, no new preview) with **C**. The routes are exercised for real only through the CLI (`restore_cuts.rs`, `branches_cli`); route-level HTTP tests, a real-server SDK test and platform acceptance keep M7 open. - Note (2026-11-14, local macOS arm64 only): preparation listing stays available for a Session whose managed worktree was removed (`managed_git_removed_location_keeps_preparation_listing`); the construction-name inventory is advisory and the `sessions recovery` hint is best-effort. Journal listing (`GET /sessions/{id}/rewind/recovery`, and so `sessions recovery`) for a removed Location failed with "No such file or directory". Owner decision 2026-11-15: such a Session is listed as orphaned and read-only. Its retained journals are found from their own records (recorded path equal to the Location, namespace key equal to the digest of that path and recorded directory identity) and returned with `location_removed: true`; nothing is locked, created or deleted, review fails, the CLI text marks rows `Location removed (orphaned, read-only)` and the TUI panel shows the removal and starts no discovery for them (`removed_location_lists_its_retained_journals_read_only` in `cyber-snapshot`, `removed_location_recovery_lists_retained_journals_as_orphaned` in `branches_cli`, TUI `a_removed_location_journal_is_listed_read_only`; OpenAPI/SDK regenerated). M7 stays open. - [ ] M8 Run process-kill cuts before/after intent, stage preparation, every exchange, progress, filesystem completion, writer commit, journal acknowledgement and reclaim. Obtain Linux x64/ARM and macOS Intel/ARM positives/denials, explicit Windows results/limits and shared Git/binary regressions; update evidence and perform substantive code/security review before accepting parent tasks. - Note (2026-11-16, local macOS arm64 only): the matrix gaps for after-intent, progress, filesystem completion with displaced images, paired writer commit and journal acknowledgement before the reply are now covered by real service kills at debug-only fixture points (`restore_cuts.rs`; implementation.md matrix updated). Remaining: paired/prepared payload-reclaim process death, Git equivalents, platform results (Linux x64/ARM, macOS Intel, Windows limits) and the substantive review under 7.2/7.3, so M8 stays open. From bee24bf8cd9a67328a84d288a9d4cd7fd1669410 Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 16:47:12 -0400 Subject: [PATCH 11/20] Kill keep/rollback and cancelled-preparation payload cleanup mid-deletion A separate maintenance process runs production reclamation and is SIGKILLed once any planned payload is unlinked; a fresh owner completes the identical frozen plan once, keeps intents and the cancellation record, and lookups return the same receipts. A debug-only point after image preparation gives a deterministic fully prepared cancellation. --- .../cyber-cli/tests/support/cleanup_cuts.rs | 210 ++++++++++++++++++ crates/cyber-cli/tests/support/reclamation.rs | 24 ++ .../cyber-cli/tests/support/restore_cuts.rs | 45 ++-- crates/cyber-snapshot/src/copy/restore.rs | 2 + .../implementation.md | 16 +- .../complete-daily-coding-surfaces/tasks.md | 2 +- 6 files changed, 279 insertions(+), 20 deletions(-) create mode 100644 crates/cyber-cli/tests/support/cleanup_cuts.rs diff --git a/crates/cyber-cli/tests/support/cleanup_cuts.rs b/crates/cyber-cli/tests/support/cleanup_cuts.rs new file mode 100644 index 00000000..602466ce --- /dev/null +++ b/crates/cyber-cli/tests/support/cleanup_cuts.rs @@ -0,0 +1,210 @@ +//! Real process death inside payload cleanup for settled keep/rollback recoveries +//! and cancelled fully prepared restores: a separate maintenance process runs the +//! production reclamation and is SIGKILLed after the durable plan and the first +//! unlink; a fresh owner completes the same frozen plan exactly once. +use super::*; +use cyber_server::runtime::{ + SnapshotPreparationReceipt, SnapshotRecoveryReceipt, snapshot_reclamation::Receipt, +}; + +// Invoked in a separate test process only; ordinary suite discovery is inert. +#[test] +fn cleanup_cut_worker() { + let Some(control) = std::env::var_os("CYBER_CLEANUP_CUT") else { + return; + }; + let control = PathBuf::from(control); + let fixture: Value = + serde_json::from_slice(&std::fs::read(control.join("fixture.json")).unwrap()).unwrap(); + let payloads = fixture["payloads"] + .as_array() + .unwrap() + .iter() + .map(|path| PathBuf::from(path.as_str().unwrap())) + .collect(); + let maintenance = + reclamation_support::Maintenance::open(&PathBuf::from(fixture["home"].as_str().unwrap())); + let result = maintenance.reclaim_until_any_killed( + &PathBuf::from(fixture["directory"].as_str().unwrap()), + payloads, + control.join("ready"), + ); + panic!("worker returned without reaching the kill boundary: {result}"); +} + +impl Fixture { + fn home(&self) -> PathBuf { + self.env.root.join("cyber-home") + } + /// Every displaced or target image retained in the given journals. + fn stages(&self, journals: &[&str]) -> Vec { + let mut stages = Vec::new(); + for journal in journals { + let directory = self.namespace().join("journals").join(journal); + for entry in std::fs::read_dir(directory).unwrap() { + let entry = entry.unwrap(); + if entry.file_name().to_string_lossy().starts_with("stage_") { + stages.push(entry.path()); + } + } + } + stages.sort(); + stages + } + /// Run production reclamation in a separate process and SIGKILL it once one of + /// `payloads` is unlinked inside the open deletion transaction. + fn kill_cleanup_worker(&self, payloads: &[PathBuf]) { + use std::os::unix::process::ExitStatusExt; + let control = self.env.root.join("cleanup-cut"); + std::fs::create_dir(&control).unwrap(); + std::fs::write( + control.join("fixture.json"), + json!({"home": self.home(), "directory": self.env.directory, "payloads": payloads}) + .to_string(), + ) + .unwrap(); + let log = control.join("worker.log"); + let output = std::fs::File::create(&log).unwrap(); + let mut worker = Child( + Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "restore_cuts::cleanup::cleanup_cut_worker", + "--nocapture", + ]) + .env("CYBER_CLEANUP_CUT", &control) + .stdout(output.try_clone().unwrap()) + .stderr(output) + .spawn() + .unwrap(), + ); + wait_for(&control.join("ready"), &mut worker, &log); + worker.0.kill().unwrap(); + assert_eq!(worker.0.wait().unwrap().signal(), Some(9)); + } +} + +/// Partially unlinked payloads and an uncompleted durable plan after the kill; a +/// fresh owner then completes that exact plan once and a second pass is a no-op. +fn kill_and_resume_cleanup(f: &Fixture, receipt: &Receipt, payloads: &[PathBuf]) { + let maintenance = reclamation_support::Maintenance::open(&f.home()); + assert!(maintenance.policy.record(receipt).unwrap().is_none()); + drop(maintenance); + f.kill_cleanup_worker(payloads); + let missing = payloads.iter().filter(|path| !path.exists()).count(); + assert!( + missing >= 1 && missing < payloads.len(), + "kill missed the partial window" + ); + let target = f.edit_as_owner(); + let maintenance = reclamation_support::Maintenance::open(&f.home()); + let frozen = maintenance.policy.record(receipt).unwrap().unwrap(); + assert!(!frozen.completed); + assert_eq!(frozen.plan.files.len(), payloads.len()); + assert!(maintenance.reclaim(&f.env.directory).unwrap() > 0); + let completed = maintenance.policy.record(receipt).unwrap().unwrap(); + assert!(completed.completed); + assert_eq!(completed.plan, frozen.plan); + assert_eq!(maintenance.reclaim(&f.env.directory).unwrap(), 0); + assert!(payloads.iter().all(|path| !path.exists())); + f.assert_owner_edits(&target); +} + +fn intents(f: &Fixture, journals: &[&str]) -> Vec> { + journals + .iter() + .map(|journal| { + std::fs::read( + f.namespace() + .join("journals") + .join(journal) + .join("intent.json"), + ) + .unwrap() + }) + .collect() +} + +fn paired_cleanup_cut(action: &str) { + let f = Fixture::new(); + let messages = f.env.messages(&f.session); + let (journal, _) = kill_after_first_progress(&f); + let request_id = format!("cleanup-{action}"); + let result = f.confirm_acknowledged(&f.request(&journal, action, &request_id)); + let requests = f.model.requests().len(); + let receipt: SnapshotRecoveryReceipt = + serde_json::from_value(result["receipt"].clone()).unwrap(); + let owner = receipt + .checkout + .as_ref() + .unwrap() + .resolution_origin + .activity_id + .clone(); + let resolution = receipt.resolution_id.clone(); + let journals = [journal.as_str(), resolution.as_str()]; + let payloads = f.stages(&journals); + let before = intents(&f, &journals); + exits(&f.env.cyber(&["service", "stop"]), 0); + { + let maintenance = reclamation_support::Maintenance::open(&f.home()); + assert_eq!(maintenance.reclaim(&f.env.directory).unwrap(), 0); + maintenance.age(owner); + } + kill_and_resume_cleanup(&f, &Receipt::Recovery(receipt), &payloads); + assert_eq!(intents(&f, &journals), before); + // A fresh service still answers the request with the same receipt, no replay. + let lookup = f.lookup(&request_id, true); + assert_eq!(lookup["receipt"], result["receipt"]); + f.assert_quiet(&messages, requests); +} + +#[test] +fn kept_recovery_payload_cleanup_killed_mid_deletion_resumes_frozen_plan() { + paired_cleanup_cut("keep"); +} + +#[test] +fn rolled_back_recovery_payload_cleanup_killed_mid_deletion_resumes_frozen_plan() { + paired_cleanup_cut("rollback"); +} + +#[test] +fn cancelled_preparation_payload_cleanup_killed_mid_deletion_resumes_frozen_plan() { + let f = Fixture::new(); + let messages = f.env.messages(&f.session); + f.kill_rewind_at("copy-restore-images-prepared"); + let (journal, intent) = f.only_journal(); + assert_eq!(intent["applied"], json!([])); + assert_eq!(f.payloads(&journal), FILES); + f.assert_uniform("after"); + let (activity, reply) = cancel_preparation(&f, "prepared-cleanup"); + let requests = f.model.requests().len(); + let receipt: SnapshotPreparationReceipt = serde_json::from_value(reply.clone()).unwrap(); + let payloads = f.stages(&[journal.as_str()]); + assert_eq!(payloads.len(), FILES); + let directory = f.namespace().join("journals").join(&journal); + let cancellation = std::fs::read(directory.join("preparation.json")).unwrap(); + let before = intents(&f, &[journal.as_str()]); + exits(&f.env.cyber(&["service", "stop"]), 0); + { + let maintenance = reclamation_support::Maintenance::open(&f.home()); + assert_eq!(maintenance.reclaim(&f.env.directory).unwrap(), 0); + maintenance.age(receipt.activity_id.clone()); + } + kill_and_resume_cleanup(&f, &Receipt::Preparation(Box::new(receipt)), &payloads); + assert_eq!(intents(&f, &[journal.as_str()]), before); + assert_eq!( + std::fs::read(directory.join("preparation.json")).unwrap(), + cancellation + ); + // The retained request still returns the same receipt on a fresh service. + let body = json!({"confirmation":reply["confirmation"],"request_id":"prepared-cleanup"}); + assert_eq!( + json(&preparation_confirm_cli( + &f.env, &f.session, &activity, &body + )), + reply + ); + f.assert_quiet(&messages, requests); +} diff --git a/crates/cyber-cli/tests/support/reclamation.rs b/crates/cyber-cli/tests/support/reclamation.rs index f2c2b7f7..d36385ce 100644 --- a/crates/cyber-cli/tests/support/reclamation.rs +++ b/crates/cyber-cli/tests/support/reclamation.rs @@ -131,6 +131,30 @@ impl Maintenance { let result = self.runtime.block_on(cut.reclaim(source.to_str().unwrap())); format!("{result:?}") } + /// Like `reclaim_until_killed`, but blocks once any one of `payloads` is gone, + /// whichever the frozen plan deletes first. + pub fn reclaim_until_any_killed( + &self, + source: &Path, + payloads: Vec, + ready: PathBuf, + ) -> String { + let config = Arc::new(move |_: &Path| { + if payloads + .iter() + .all(|payload| std::fs::symlink_metadata(payload).is_ok()) + { + return serde_json::json!({"snapshots":{"retention_days":7}}); + } + std::fs::write(&ready, b"payload deletion in progress").unwrap(); + loop { + std::thread::sleep(std::time::Duration::from_secs(3600)); + } + }); + let cut = Self::configured(&self.root, self.policy.clone(), config); + let result = self.runtime.block_on(cut.reclaim(source.to_str().unwrap())); + format!("{result:?}") + } pub fn age(&self, activity: String) { self.store .transaction(move |db| { diff --git a/crates/cyber-cli/tests/support/restore_cuts.rs b/crates/cyber-cli/tests/support/restore_cuts.rs index 024cdd48..1cc0dc07 100644 --- a/crates/cyber-cli/tests/support/restore_cuts.rs +++ b/crates/cyber-cli/tests/support/restore_cuts.rs @@ -4,6 +4,8 @@ //! commit, and after a native journal acknowledgement whose reply was never sent. //! Each cut is a debug-only `CYBER_TEST_PROCESS_CUT` point in the service. use super::*; +#[path = "cleanup_cuts.rs"] +mod cleanup; const FILES: usize = 4; struct Fixture { @@ -531,22 +533,8 @@ fn ordinary_restore_killed_after_journal_acknowledgement_never_replays() { assert_eq!(f.model.requests().len(), requests); } -/// Kill a restore at a pre-effect journal construction point, then cancel the exited -/// preparation through the real CLI. Returns whether the journal held an intent. -fn construction_cut_cancellation(point: &str) -> bool { - let f = Fixture::new(); - let messages = f.env.messages(&f.session); - f.kill_rewind_at(point); - let journals = f.journals(); - assert_eq!(journals.len(), 1, "{journals:?}"); - let journal = f.namespace().join("journals").join(&journals[0]); - let has_intent = journal.join("intent.json").exists(); - assert_eq!(f.payloads(&journals[0]), 0, "no image may be staged yet"); - f.assert_uniform("after"); - // New input is fenced until the exited preparation is resolved. - let refused = f.env.cyber(&["exec", "--session", &f.session, "fenced"]); - assert!(!refused.status.success()); - let requests = f.model.requests().len(); +/// Review and cancel the only exited preparation; returns its activity and receipt. +fn cancel_preparation(f: &Fixture, request_id: &str) -> (String, Value) { let list = json(&f.env.cyber(&[ "sessions", "recovery-preparation", @@ -563,12 +551,33 @@ fn construction_cut_cancellation(point: &str) -> bool { "--format", "json", ])); - let body = - json!({"confirmation":review["confirmation"],"request_id":format!("{point}-cancel")}); + let body = json!({"confirmation":review["confirmation"],"request_id":request_id}); let receipt = json(&preparation_confirm_cli( &f.env, &f.session, &activity, &body, )); assert_eq!(receipt["activity_id"], activity.as_str()); + (activity, receipt) +} + +/// Kill a restore at a pre-effect journal construction point, then cancel the exited +/// preparation through the real CLI. Returns whether the journal held an intent. +fn construction_cut_cancellation(point: &str) -> bool { + let f = Fixture::new(); + let messages = f.env.messages(&f.session); + f.kill_rewind_at(point); + let journals = f.journals(); + assert_eq!(journals.len(), 1, "{journals:?}"); + let journal = f.namespace().join("journals").join(&journals[0]); + let has_intent = journal.join("intent.json").exists(); + assert_eq!(f.payloads(&journals[0]), 0, "no image may be staged yet"); + f.assert_uniform("after"); + // New input is fenced until the exited preparation is resolved. + let refused = f.env.cyber(&["exec", "--session", &f.session, "fenced"]); + assert!(!refused.status.success()); + let requests = f.model.requests().len(); + let request_id = format!("{point}-cancel"); + let (activity, receipt) = cancel_preparation(&f, &request_id); + let body = json!({"confirmation":receipt["confirmation"],"request_id":request_id}); // A repeated confirmation is lookup only. assert_eq!( json(&preparation_confirm_cli( diff --git a/crates/cyber-snapshot/src/copy/restore.rs b/crates/cyber-snapshot/src/copy/restore.rs index 58a2b1cf..42cb2dd7 100644 --- a/crates/cyber-snapshot/src/copy/restore.rs +++ b/crates/cyber-snapshot/src/copy/restore.rs @@ -499,6 +499,8 @@ impl Store { } else { Self::record(&dir, journal).map_err(RestoreError::Failed)?; } + // Fixture point: every target image and its ownership are durable; no exchange. + cyber_core::process_cut::pause("copy-restore-images-prepared"); if let Some(preimages) = &preimages { preimages .verify_review(self) diff --git a/openspec/changes/complete-daily-coding-surfaces/implementation.md b/openspec/changes/complete-daily-coding-surfaces/implementation.md index 225d01e3..e22ff96a 100644 --- a/openspec/changes/complete-daily-coding-surfaces/implementation.md +++ b/openspec/changes/complete-daily-coding-surfaces/implementation.md @@ -3964,7 +3964,7 @@ macOS arm64; no Linux, macOS Intel or Windows result is claimed. | Filesystem completion (completed intent, before writer commit) | real service: `copy_kept_creation_after_completed_source_kill_retires_zero_payload`; fixture point (2026-11-16, `copy-restore-filesystem-completed`): `restore_killed_after_filesystem_completion_with_payloads_is_kept`/`_rolled_back` (four displaced images) | none locally for file-copy | | Writer commit (committed Session writer, unacknowledged journal) | real service: `ordinary_restore_killed_after_writer_commit_before_journal_ack_reconciles_without_replay`; paired recovery (2026-11-16, `recovery-pair-writer-commit`): `paired_recovery_killed_after_writer_commit_reconciles_without_replay` | none locally for file-copy | | Journal acknowledgement | storage: `process_death_during_spare_write_preserves_active_intent_and_reopens_without_replay`; managed checkout claim: `killed_acknowledgement_resumes_without_rewriting_claim_or_deleting_partial_stage`, `killed_construction_keeps_locked_complete_stage_and_never_creates_or_replays_stable_claim`; after the acknowledgement, before the reply (2026-11-16): `ordinary_restore_killed_after_journal_acknowledgement_never_replays` (`ordinary-restore-journal-acknowledged`), `paired_recovery_killed_after_journal_acknowledgement_returns_the_receipt` (`recovery-journal-acknowledged`) | none locally for file-copy | -| Reclaim | real service fixture + separate maintenance process: `ordinary_restore_killed_during_payload_reclaim_resumes_frozen_plan` (new; after the durable plan and the first unlink, inside the deletion transaction); App: `actual_process_death_preserves_plan_and_resumes_without_source_replay` (before deletion and after all deletions); collection: `process_death_after_last_manifest_unlink_resumes_from_durable_policy_provenance` | **gap**: paired keep/rollback payload cleanup is interrupted in-process only (`managed_native_recovery_after_partial_kill`, `native_retirement_resumes_before_and_after_deletion_without_rewriting_acknowledgement`); managed Git paired/prepared metadata retirement now has App SIGKILL cuts (see the section below), paired/prepared payload reclaim still does not | +| Reclaim | real service fixture + separate maintenance process: `ordinary_restore_killed_during_payload_reclaim_resumes_frozen_plan`; paired and prepared (2026-11-16, `restore_cuts::cleanup`): `kept_recovery_payload_cleanup_killed_mid_deletion_resumes_frozen_plan`, `rolled_back_recovery_payload_cleanup_killed_mid_deletion_resumes_frozen_plan`, `cancelled_preparation_payload_cleanup_killed_mid_deletion_resumes_frozen_plan`; App: `actual_process_death_preserves_plan_and_resumes_without_source_replay`; collection: `process_death_after_last_manifest_unlink_resumes_from_durable_policy_provenance`; metadata retirement: `paired_managed_metadata_process_death_resumes_both_owner_bindings`, `prepared_cancellation_metadata_process_death_resumes_frozen_plan` | none locally for file-copy | New in this increment (`crates/cyber-cli/tests/support/ordinary_cuts.rs`, part of the `branches_cli` test binary): @@ -4322,3 +4322,17 @@ Still open: paired/prepared payload-reclaim process death, real kills at later progress records and in Git (`native-git-acceptance`) equivalents of these cuts, HTTP route tests and a real-server SDK test for recovery, a TUI path from "Code unavailable" into journal recovery, and the platform matrix. + +### Paired and prepared payload-cleanup process death (2026-11-16, local) + +`crates/cyber-cli/tests/support/cleanup_cuts.rs` (submodule of `restore_cuts`) settles +a partial restore with a real keep or rollback, or cancels a restore killed at the new +debug-only `copy-restore-images-prepared` point (all four target images and their +ownership durable, no exchange), ages the owner, and runs production reclamation in a +separate test process that blocks inside the deletion transaction once any planned +payload is unlinked (`Maintenance::reclaim_until_any_killed`). After SIGKILL some, but +not all, payloads are gone and the durable plan is uncompleted. A later owner symlink +edit survives; a fresh owner completes the identical frozen plan once and a second pass +reclaims nothing; intents (and `preparation.json`) keep their bytes; a fresh service +returns the same receipt through lookup/acknowledgement, with no transcript movement +or inference. No defect was found. diff --git a/openspec/changes/complete-daily-coding-surfaces/tasks.md b/openspec/changes/complete-daily-coding-surfaces/tasks.md index f6ad123f..5a459577 100644 --- a/openspec/changes/complete-daily-coding-surfaces/tasks.md +++ b/openspec/changes/complete-daily-coding-surfaces/tasks.md @@ -122,7 +122,7 @@ Unprepared reservation/origin/intent cuts still require exact resource ownership proof; missing records alone do not license acknowledgement. - [ ] M6 Publish journal acknowledgement only after observed durable Store settlement. Add reference/reader/lease-aware eligibility and durable two-phase reclamation with retained retry receipts. Test cap pressure, disabled/zero retention, incomplete reference views and crashes at writer/journal/reclaim boundaries without deleting unresolved evidence. - - Note (2026-11-16, local macOS arm64 only): real kills after the ordinary and paired journal acknowledgements and before the reply return the committed receipt without replay. Paired/prepared payload-reclaim process death and platform acceptance keep M6 open. + - Note (2026-11-16, local macOS arm64 only): real kills after the ordinary and paired journal acknowledgements and before the reply return the committed receipt without replay. Paired/prepared payload-reclaim process death is now covered too (`restore_cuts::cleanup`, real SIGKILL mid-deletion, frozen plan resumed once). Platform acceptance keeps M6 open. - Note (2026-11-14, local macOS arm64 only): construction evidence is outside reclamation by design. Claim and acknowledgement stages refuse removal and metadata retirement as `same-owner unknown constructor` evidence, and the prepared-cancellation cleanup case now also refuses an interrupted cancellation-record stage (`tmp_*` with the complete receipt bytes) as an unknown journal entry, keeping its bytes; `interrupted_cancellation_record_construction_is_retained_and_never_adopted` shows a retried receipt publishes without adopting it. Removing such stages needs a separate construction-recovery protocol extension. M6 stays open for the remaining reclamation obligations. - [ ] M7 Add owner recovery review/confirm/lookup HTTP routes, typed CLI and SDK operations, and TUI recovery entry from rewind unavailability. Regenerate OpenAPI/SDK/command artifacts; exercise the real clients with no inference or transcript movement and with stale/foreign request refusal. - Note (2026-11-16, local macOS arm64 only): TUI `code_unavailable_preview_enters_journal_recovery_with_c` shows the recovery hint on a code preview refused by a retained restore and opens journal recovery (a recovery listing request, no new preview) with **C**. The routes are exercised for real only through the CLI (`restore_cuts.rs`, `branches_cli`); route-level HTTP tests, a real-server SDK test and platform acceptance keep M7 open. 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 12/20] 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 58764dc4228f03b2c9ccdcccaf7a1f41294d46ae Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 16:54:37 -0400 Subject: [PATCH 13/20] Run the recovery cut scenarios in a managed Git worktree and in CI The restore_cuts fixture can now be a tracked managed Git worktree, and the progress, completion, paired writer-commit, interrupted-resolution, staged undo with inactive branch, namespace swap and damaged-intent cases run there under native-git-acceptance. A corrupt or missing retained intent refuses listing, review and a reviewed confirmation without source effects on both backends. The native snapshot proof workflow runs restore_cuts and ordinary_cuts on the Linux and macOS matrix. --- .github/workflows/non-git-snapshot-proof.yml | 11 ++ .../cyber-cli/tests/support/restore_cuts.rs | 144 ++++++++++++++++-- .../implementation.md | 26 ++++ .../complete-daily-coding-surfaces/tasks.md | 4 +- 4 files changed, 167 insertions(+), 18 deletions(-) diff --git a/.github/workflows/non-git-snapshot-proof.yml b/.github/workflows/non-git-snapshot-proof.yml index b18e7e49..f7a23890 100644 --- a/.github/workflows/non-git-snapshot-proof.yml +++ b/.github/workflows/non-git-snapshot-proof.yml @@ -219,6 +219,16 @@ jobs: set -euo pipefail mkdir -p "$TMPDIR" cargo test --locked -p cyber-cli --features native-git-acceptance --test branches_cli zero_payload:: -- --nocapture --test-threads=1 2>&1 | tee zero-payload-retirement-proof.log + - name: Restore and recovery 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 restore_cuts:: -- --nocapture --test-threads=2 2>&1 | tee recovery-cut-proof.log + cargo test --locked -p cyber-cli --features native-git-acceptance --test branches_cli ordinary_cuts:: -- --nocapture --test-threads=1 2>&1 | tee -a recovery-cut-proof.log - name: JSONL driver and atomic last-message regressions if: ${{ !cancelled() && (runner.os != 'Linux' || steps.sandbox.outcome == 'success') }} env: @@ -295,6 +305,7 @@ jobs: preparation-retirement-proof.log paired-retirement-proof.log zero-payload-retirement-proof.log + recovery-cut-proof.log jsonl-driver-proof.log structured-result-proof.log instruction-limits-proof.log diff --git a/crates/cyber-cli/tests/support/restore_cuts.rs b/crates/cyber-cli/tests/support/restore_cuts.rs index 1cc0dc07..f243432a 100644 --- a/crates/cyber-cli/tests/support/restore_cuts.rs +++ b/crates/cyber-cli/tests/support/restore_cuts.rs @@ -21,8 +21,22 @@ impl Fixture { let model = scripted_model::ScriptedModel::start(reply); let env = Env::new(&model); std::fs::remove_dir_all(env.directory.join(".git")).unwrap(); + Self::capture(model, env, None) + } + /// The same files tracked in a managed Git worktree (`native-git-acceptance`). + #[cfg(feature = "native-git-acceptance")] + fn managed() -> Self { + let model = scripted_model::ScriptedModel::start(reply); + let (env, session) = managed_git_fixture(&model); write_files(&env, "before"); - let session = env.exec(None, "before snapshot"); + git_fixture(&env.directory, &["add", "--all"]); + Self::capture(model, env, Some(session)) + } + fn capture(model: scripted_model::ScriptedModel, env: Env, session: Option) -> Self { + if session.is_none() { + write_files(&env, "before"); + } + let session = env.exec(session.as_deref(), "before snapshot"); let first = env.user_ids(&session)[0].clone(); write_files(&env, "after"); env.exec(Some(&session), "after snapshot"); @@ -328,8 +342,7 @@ fn first_progress(f: &Fixture) -> (String, String) { (journal, applied[0].clone()) } -fn progress_cut_resolution(action: &str) { - let f = Fixture::new(); +fn progress_cut_resolution(f: Fixture, action: &str) { let messages = f.env.messages(&f.session); let (journal, applied) = kill_after_first_progress(&f); // A fresh service: the failed restore did not move the transcript. @@ -353,16 +366,15 @@ fn progress_cut_resolution(action: &str) { #[test] fn restore_killed_after_a_progress_record_is_kept_without_replay() { - progress_cut_resolution("keep"); + progress_cut_resolution(Fixture::new(), "keep"); } #[test] fn restore_killed_after_a_progress_record_is_rolled_back_without_replay() { - progress_cut_resolution("rollback"); + progress_cut_resolution(Fixture::new(), "rollback"); } -fn completion_cut_resolution(action: &str) { - let f = Fixture::new(); +fn completion_cut_resolution(f: Fixture, action: &str) { let messages = f.env.messages(&f.session); f.kill_rewind_at("copy-restore-filesystem-completed"); let journal = assert_completed_without_writer(&f, &messages); @@ -394,12 +406,12 @@ fn assert_completed_without_writer(f: &Fixture, messages: &[Value]) -> String { #[test] fn restore_killed_after_filesystem_completion_with_payloads_is_kept() { - completion_cut_resolution("keep"); + completion_cut_resolution(Fixture::new(), "keep"); } #[test] fn restore_killed_after_filesystem_completion_with_payloads_is_rolled_back() { - completion_cut_resolution("rollback"); + completion_cut_resolution(Fixture::new(), "rollback"); } /// The paired recovery commit is durable when the service dies; neither journal is @@ -407,7 +419,10 @@ fn restore_killed_after_filesystem_completion_with_payloads_is_rolled_back() { /// explicit acknowledgement publishes only journal metadata. #[test] fn paired_recovery_killed_after_writer_commit_reconciles_without_replay() { - let f = Fixture::new(); + paired_case(Fixture::new()); +} + +fn paired_case(f: Fixture) { let messages = f.env.messages(&f.session); let (journal, _) = kill_after_first_progress(&f); let request_id = "paired-writer-cut"; @@ -612,7 +627,10 @@ fn restore_killed_after_intent_before_staging_is_cancelled_without_source_effect /// then can the original journal be settled by a new reviewed request. #[test] fn interrupted_resolution_is_retained_and_resolved_as_independent_evidence() { - let f = Fixture::new(); + interrupted_case(Fixture::new()); +} + +fn interrupted_case(f: Fixture) { let messages = f.env.messages(&f.session); let (journal, applied) = kill_after_first_progress(&f); let request = f.request(&journal, "rollback", "interrupted-resolution"); @@ -680,8 +698,7 @@ fn assert_not_redispatched(f: &Fixture, request: &Value, applied: &str) { /// An interrupted staged code undo in a Session that also has an inactive branch: /// keep or rollback settles the native journal without staging, committing or /// discarding conversation state, and the branch stays exportable. -fn staged_undo_partial(action: &str) { - let f = Fixture::new(); +fn staged_undo_partial(f: Fixture, action: &str) { let branch = inactive_branch(&f); let messages = f.env.messages(&f.session); let selection = reviewed_selection(&f.env, &f.first, "code", "stage"); @@ -745,12 +762,12 @@ fn assert_branch_kept(f: &Fixture, message: &str) { #[test] fn interrupted_staged_undo_with_an_inactive_branch_is_kept() { - staged_undo_partial("keep"); + staged_undo_partial(Fixture::new(), "keep"); } #[test] fn interrupted_staged_undo_with_an_inactive_branch_is_rolled_back() { - staged_undo_partial("rollback"); + staged_undo_partial(Fixture::new(), "rollback"); } /// The private journal namespace is replaced (by an equal-content copy, then by a @@ -758,7 +775,10 @@ fn interrupted_staged_undo_with_an_inactive_branch_is_rolled_back() { /// source effect, and the reviewed recovery succeeds once the original is back. #[test] fn replaced_private_journal_namespace_refuses_recovery_without_effects() { - let f = Fixture::new(); + namespace_swap(Fixture::new()); +} + +fn namespace_swap(f: Fixture) { let messages = f.env.messages(&f.session); let (journal, applied) = kill_after_first_progress(&f); let request = f.request(&journal, "rollback", "namespace-swap"); @@ -796,3 +816,95 @@ fn replaced_private_journal_namespace_refuses_recovery_without_effects() { f.assert_uniform("after"); assert_eq!(f.env.messages(&f.session), messages); } + +/// A corrupt, then missing, retained `intent.json` refuses listing, review and an +/// already reviewed confirmation without source effects; with the exact record back +/// in place the reviewed request settles normally. +fn damaged_intent(f: Fixture) { + let messages = f.env.messages(&f.session); + let (journal, applied) = kill_after_first_progress(&f); + let request = f.request(&journal, "rollback", "damaged-intent"); + let intent = f + .namespace() + .join("journals") + .join(&journal) + .join("intent.json"); + let bytes = std::fs::read(&intent).unwrap(); + let moved = intent.with_file_name("moved-intent.json"); + let refused = |reason: &str| { + for args in [ + vec!["sessions", "recovery", &f.session, "--format", "json"], + vec![ + "sessions", "recovery", &f.session, &journal, "--action", "rollback", "--format", + "json", + ], + ] { + let stderr = exits(&f.env.cyber(&args), 2); + assert!(stderr.contains(reason), "{stderr}"); + } + assert!( + !recovery_confirm_cli(&f.env, &f.session, &request) + .status + .success() + ); + assert_eq!(f.env.file(&applied).as_deref(), Some("before")); + assert_eq!(f.journals(), vec![journal.clone()]); + }; + std::fs::write(&intent, b"{not json").unwrap(); + refused("key must be a string"); + std::fs::write(&intent, &bytes).unwrap(); + std::fs::rename(&intent, &moved).unwrap(); + refused("No such file or directory"); + std::fs::rename(&moved, &intent).unwrap(); + f.confirm_acknowledged(&request); + f.assert_uniform("after"); + assert_eq!(f.env.messages(&f.session), messages); +} + +#[test] +fn damaged_retained_intent_refuses_recovery_without_effects() { + damaged_intent(Fixture::new()); +} + +/// Managed Git (`native-git-acceptance`) equivalents of the file-copy cuts above. +#[cfg(feature = "native-git-acceptance")] +mod managed { + use super::*; + + #[test] + fn git_restore_killed_after_a_progress_record_is_kept() { + progress_cut_resolution(Fixture::managed(), "keep"); + } + #[test] + fn git_restore_killed_after_a_progress_record_is_rolled_back() { + progress_cut_resolution(Fixture::managed(), "rollback"); + } + #[test] + fn git_interrupted_staged_undo_with_an_inactive_branch_is_kept() { + staged_undo_partial(Fixture::managed(), "keep"); + } + #[test] + fn git_interrupted_staged_undo_with_an_inactive_branch_is_rolled_back() { + staged_undo_partial(Fixture::managed(), "rollback"); + } + #[test] + fn git_replaced_private_journal_namespace_refuses_recovery() { + namespace_swap(Fixture::managed()); + } + #[test] + fn git_restore_killed_after_filesystem_completion_is_rolled_back() { + completion_cut_resolution(Fixture::managed(), "rollback"); + } + #[test] + fn git_paired_recovery_killed_after_writer_commit_reconciles() { + paired_case(Fixture::managed()); + } + #[test] + fn git_interrupted_resolution_is_retained_as_independent_evidence() { + interrupted_case(Fixture::managed()); + } + #[test] + fn git_damaged_retained_intent_refuses_recovery() { + damaged_intent(Fixture::managed()); + } +} diff --git a/openspec/changes/complete-daily-coding-surfaces/implementation.md b/openspec/changes/complete-daily-coding-surfaces/implementation.md index e22ff96a..a61673f8 100644 --- a/openspec/changes/complete-daily-coding-surfaces/implementation.md +++ b/openspec/changes/complete-daily-coding-surfaces/implementation.md @@ -4336,3 +4336,29 @@ edit survives; a fresh owner completes the identical frozen plan once and a seco reclaims nothing; intents (and `preparation.json`) keep their bytes; a fresh service returns the same receipt through lookup/acknowledgement, with no transcript movement or inference. No defect was found. + +### Managed Git equivalents and damaged intents (2026-11-16, local) + +`restore_cuts` now builds the same four-file fixture in a managed Git worktree +(`Fixture::managed`, tracked files, `native-git-acceptance`) and runs the file-copy +scenarios unchanged there (`restore_cuts::managed::git_*`): keep and rollback after a +kill directly after a progress record, a staged undo beside an inactive branch killed +mid-restore (keep and rollback), private journal namespace replacement by a copy and +by a symlink alias, a damaged retained intent, rollback after filesystem completion +with displaced images, the paired writer-commit cut and an interrupted resolution +retained as independent evidence. All refusals and outcomes match the file-copy +backend. + +`damaged_retained_intent_refuses_recovery_without_effects` (both backends): after a +partial restore and a reviewed rollback, `intent.json` is overwritten with invalid +JSON and then moved away. Listing, review and the already reviewed confirmation all +refuse (exit 2: the parse error, then `No such file or directory`) with no source +effect and no resolution journal; with the exact record back in place (same inode) +the reviewed request settles. Review finding, not changed: one damaged journal makes +the whole Session listing fail closed, so its sibling journals cannot be listed until +the record is repaired. + +CI: `non-git-snapshot-proof.yml` gains a "Restore and recovery process-death cuts" +step (`restore_cuts::` and `ordinary_cuts::` with `native-git-acceptance`) on +ubuntu-24.04, ubuntu-24.04-arm, macos-15 and macos-15-intel; its log is retained as +`recovery-cut-proof.log`. Platform results are claimed only from those runs. diff --git a/openspec/changes/complete-daily-coding-surfaces/tasks.md b/openspec/changes/complete-daily-coding-surfaces/tasks.md index 5a459577..f576c15b 100644 --- a/openspec/changes/complete-daily-coding-surfaces/tasks.md +++ b/openspec/changes/complete-daily-coding-surfaces/tasks.md @@ -71,9 +71,9 @@ partial-journal construction and complete crash/platform acceptance still leave M2 open. - [ ] M3 Add versioned origin-bound Git and file-copy intents, preserved displaced preimages and resolution-intent records. Keep legacy journals inspectable without inventing origin proof. Test missing/corrupt records, private namespace replacement, aliases, metadata and Location mismatch before admitting effects. - - Note (2026-11-16, local macOS arm64 only): `replaced_private_journal_namespace_refuses_recovery_without_effects` replaces the private journal directory between review and confirmation with an equal-content copy and with a symlink alias; both refuse before any source effect and the same request succeeds once the original is back. Git (`native-git-acceptance`) namespace replacement and missing/corrupt Git `intent.json` cases, and platform acceptance, keep M3 open. + - Note (2026-11-16, local macOS arm64 only): `replaced_private_journal_namespace_refuses_recovery_without_effects` replaces the private journal directory between review and confirmation with an equal-content copy and with a symlink alias; both refuse before any source effect and the same request succeeds once the original is back. Update: the same namespace swap and a corrupt/missing `intent.json` (`damaged_retained_intent_refuses_recovery_without_effects`) now run for file-copy and managed Git (`restore_cuts::managed::git_*`). Platform acceptance keeps M3 open. - [ ] M4 Implement bounded keep/rollback planning and fingerprint revalidation under exact native locks. Preserve unrelated edits, refuse the complete plan on conflicts, and retain any interrupted resolution as independent evidence. Test keep and rollback after actual partial namespace replacement, including staged undo and inactive branches. - - Note (2026-11-16, local macOS arm64 only): keep and rollback after a real kill directly after a progress record, including a staged code undo in a Session with an inactive branch (recovery neither stages nor commits; the branch stays exportable), and a keep/rollback resolution itself killed mid-exchange: its journal is retained as independent evidence, the interrupted request is never redispatched and reports `resolved_by_another_request` once that journal is resolved, and the original needs its own reviewed request (`docs/rewind.md`). Git equivalents and platform acceptance keep M4 open. + - Note (2026-11-16, local macOS arm64 only): keep and rollback after a real kill directly after a progress record, including a staged code undo in a Session with an inactive branch (recovery neither stages nor commits; the branch stays exportable), and a keep/rollback resolution itself killed mid-exchange: its journal is retained as independent evidence, the interrupted request is never redispatched and reports `resolved_by_another_request` once that journal is resolved, and the original needs its own reviewed request (`docs/rewind.md`). The same keep/rollback, staged-undo/inactive-branch and interrupted-resolution cases now also run in a managed Git worktree. Platform acceptance keeps M4 open. - [ ] M5 Atomically validate and commit the exact origin acknowledgement and resolution receipt at the Store writer. Determine the bounded owner aggregates before extending the single-aggregate append API. Test late CAS/projector/validation failure rollback, absence of uncommitted notifications and committed-but-lost writer replies; repeat request lookup must never mutate files again. - Note (2026-11-16, local macOS arm64 only): the paired keep/rollback writer-commit cut is now a real service kill (`paired_recovery_killed_after_writer_commit_reconciles_without_replay`, debug-only `recovery-pair-writer-commit`) instead of an acknowledgement-metadata reset; lookup stays read-only and `--acknowledge` writes metadata only over later owner edits. Platform acceptance keeps M5 open. From 324d0f1add2bbe52044904cdba4fc6f939b570fb Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 17:29:29 -0400 Subject: [PATCH 14/20] Test recovery routes directly and through the SDK against a real server Every recovery route is called on the real service after a real partial restore: stale, foreign-Session, changed-content and unknown requests are refused without effects, and lookup, repeated confirmation and acknowledgement return the same receipt. A new SDK end-to-end test kills a real service mid-restore and resolves the journal through the SDK. --- .../cyber-cli/tests/support/restore_cuts.rs | 137 ++++++++++++++++++ .../implementation.md | 25 ++++ .../complete-daily-coding-surfaces/tasks.md | 2 +- sdk/typescript/test/recovery.e2e.test.ts | 114 +++++++++++++++ 4 files changed, 277 insertions(+), 1 deletion(-) create mode 100644 sdk/typescript/test/recovery.e2e.test.ts diff --git a/crates/cyber-cli/tests/support/restore_cuts.rs b/crates/cyber-cli/tests/support/restore_cuts.rs index f243432a..2a33a682 100644 --- a/crates/cyber-cli/tests/support/restore_cuts.rs +++ b/crates/cyber-cli/tests/support/restore_cuts.rs @@ -908,3 +908,140 @@ mod managed { damaged_intent(Fixture::managed()); } } + +/// Calls one recovery HTTP route through `cyber api`; returns the exit status and the +/// decoded body (`data` on success, the error envelope otherwise). +fn route(f: &Fixture, method: &str, path: &str, body: Option<&Value>) -> (bool, Value) { + let mut args = vec!["api", method, path]; + let body = body.map(Value::to_string); + if let Some(body) = &body { + args.extend(["-d", body]); + } + let output = f.env.cyber(&args); + let value: Value = serde_json::from_slice(&output.stdout).unwrap_or(Value::Null); + if output.status.success() { + (true, value["data"].clone()) + } else { + (false, value) + } +} + +#[track_caller] +fn refused(result: (bool, Value), tag: &str, message: &str) { + assert!(!result.0, "{}", result.1); + assert_eq!(result.1["_tag"], tag, "{}", result.1); + assert!( + result.1["message"].as_str().unwrap().contains(message), + "{}", + result.1 + ); +} + +/// Route-level review/confirm/lookup/discovery/acknowledgement over the real HTTP +/// server: stale, foreign-Session, changed-content and unknown requests are refused +/// without source effects; a repeated confirmation is lookup only; nothing moves the +/// transcript or starts inference. +#[test] +fn recovery_routes_refuse_stale_and_foreign_requests_without_effects() { + let f = Fixture::new(); + let messages = f.env.messages(&f.session); + let (journal, applied) = kill_after_first_progress(&f); + let requests = f.model.requests().len(); + let base = format!("/sessions/{}/rewind/recovery", f.session); + let foreign = json(&f.env.cyber(&["api", "POST", "/sessions", "-d", "{}"]))["data"]["id"] + .as_str() + .unwrap() + .to_owned(); + let other = format!("/sessions/{foreign}/rewind/recovery"); + let selection = json!({"journal_id":journal,"action":"rollback"}); + let (ok, review) = route(&f, "POST", &format!("{base}/review"), Some(&selection)); + assert!(ok, "{review}"); + let mut request = selection.clone(); + request["confirmation"] = review["confirmation"].clone(); + request["request_id"] = "route-request".into(); + let mut stale = request.clone(); + stale["confirmation"] = "0".repeat(64).into(); + let foreign_session = "different Session/checkout"; + refused( + route(&f, "POST", &format!("{base}/confirm"), Some(&stale)), + "ConflictError", + "stale", + ); + refused( + route(&f, "POST", &format!("{other}/review"), Some(&selection)), + "ConflictError", + foreign_session, + ); + refused( + route(&f, "POST", &format!("{other}/confirm"), Some(&request)), + "ConflictError", + foreign_session, + ); + assert_eq!(f.env.file(&applied).as_deref(), Some("before")); + assert_eq!(f.journals(), vec![journal.clone()]); + let (ok, confirmed) = route(&f, "POST", &format!("{base}/confirm"), Some(&request)); + assert!(ok, "{confirmed}"); + assert_eq!(confirmed["state"], "acknowledged"); + assert_eq!(confirmed["journal_acknowledged"], true); + f.assert_uniform("after"); + // Lookup, discovery, a repeated confirmation and acknowledgement never mutate files. + std::fs::write(f.env.directory.join(&applied), "owner edit").unwrap(); + for (method, path, body) in [ + ("GET", format!("{base}/requests/route-request"), None), + ("POST", format!("{base}/confirm"), Some(&request)), + ( + "POST", + format!("{base}/requests/route-request/acknowledge"), + Some(&json!({})), + ), + ] { + let (ok, reply) = route(&f, method, &path, body); + assert!(ok, "{reply}"); + assert_eq!(reply["receipt"], confirmed["receipt"]); + } + let (ok, discovered) = route( + &f, + "GET", + &format!("{base}/requests?journal_id={journal}"), + None, + ); + assert!(ok); + assert_eq!(discovered, json!([request])); + let mut changed = request.clone(); + changed["action"] = "keep".into(); + refused( + route(&f, "POST", &format!("{base}/confirm"), Some(&changed)), + "ConflictError", + "different content", + ); + refused( + route(&f, "GET", &format!("{other}/requests/route-request"), None), + "RequestNotFoundError", + "No retained", + ); + refused( + route( + &f, + "POST", + &format!("{other}/requests/route-request/acknowledge"), + Some(&json!({})), + ), + "InvalidRequestError", + "No retained", + ); + refused( + route(&f, "GET", &format!("{base}/requests/unknown"), None), + "RequestNotFoundError", + "No retained", + ); + let (ok, none) = route( + &f, + "GET", + &format!("{other}/requests?journal_id={journal}"), + None, + ); + assert!(ok); + assert_eq!(none, json!([])); + assert_eq!(f.env.file(&applied).as_deref(), Some("owner edit")); + f.assert_quiet(&messages, requests); +} diff --git a/openspec/changes/complete-daily-coding-surfaces/implementation.md b/openspec/changes/complete-daily-coding-surfaces/implementation.md index a61673f8..80459d0d 100644 --- a/openspec/changes/complete-daily-coding-surfaces/implementation.md +++ b/openspec/changes/complete-daily-coding-surfaces/implementation.md @@ -4362,3 +4362,28 @@ CI: `non-git-snapshot-proof.yml` gains a "Restore and recovery process-death cut step (`restore_cuts::` and `ordinary_cuts::` with `native-git-acceptance`) on ubuntu-24.04, ubuntu-24.04-arm, macos-15 and macos-15-intel; its log is retained as `recovery-cut-proof.log`. Platform results are claimed only from those runs. + +### Recovery routes and a real-server SDK client (2026-11-16, local) + +`recovery_routes_refuse_stale_and_foreign_requests_without_effects` (`restore_cuts`, +real service, every route called directly through `cyber api`): after a real partial +restore, `POST .../recovery/review` returns a fingerprint; a stale confirmation +(`ConflictError` "stale"), a foreign Session's review and confirmation (`ConflictError` +"different Session/checkout"), a request ID reused with different content +(`ConflictError`) and unknown or foreign lookups (`RequestNotFoundError`) are refused +with no source change and no resolution journal. The exact confirmation settles; lookup, +the repeated confirmation and acknowledgement return the same receipt over a later +owner edit; discovery returns exactly the request for its Session and `[]` for another; +the transcript and inference count do not change. Review finding (not changed): a +foreign Session's `POST .../requests/{id}/acknowledge` refuses as `InvalidRequestError` +"No retained recovery request" while the same lookup is `RequestNotFoundError`. + +`sdk/typescript/test/recovery.e2e.test.ts` (runs with `CYBER_BIN`, so in CI's SDK job): +the CLI produces a non-Git Session, a fresh service is started with the debug +`copy-restore-progress-recorded` point and SIGKILLed through its registration, and the +SDK (`Cyber.start({mode:"spawn"})`) lists the journal, reviews rollback, gets a 409 +`ConflictError` for a stale fingerprint and for a foreign Session, confirms +(`acknowledged`, `journal_acknowledged: true`), and gets the same receipt from lookup +and a repeated confirmation over a later owner edit, a 404 for a foreign lookup, an +unchanged transcript and no inference. Local macOS arm64 pass; the SDK suite passes +(139 pass, 11 skipped without `CYBER_BIN`). diff --git a/openspec/changes/complete-daily-coding-surfaces/tasks.md b/openspec/changes/complete-daily-coding-surfaces/tasks.md index f576c15b..7704f715 100644 --- a/openspec/changes/complete-daily-coding-surfaces/tasks.md +++ b/openspec/changes/complete-daily-coding-surfaces/tasks.md @@ -125,7 +125,7 @@ proof; missing records alone do not license acknowledgement. - Note (2026-11-16, local macOS arm64 only): real kills after the ordinary and paired journal acknowledgements and before the reply return the committed receipt without replay. Paired/prepared payload-reclaim process death is now covered too (`restore_cuts::cleanup`, real SIGKILL mid-deletion, frozen plan resumed once). Platform acceptance keeps M6 open. - Note (2026-11-14, local macOS arm64 only): construction evidence is outside reclamation by design. Claim and acknowledgement stages refuse removal and metadata retirement as `same-owner unknown constructor` evidence, and the prepared-cancellation cleanup case now also refuses an interrupted cancellation-record stage (`tmp_*` with the complete receipt bytes) as an unknown journal entry, keeping its bytes; `interrupted_cancellation_record_construction_is_retained_and_never_adopted` shows a retried receipt publishes without adopting it. Removing such stages needs a separate construction-recovery protocol extension. M6 stays open for the remaining reclamation obligations. - [ ] M7 Add owner recovery review/confirm/lookup HTTP routes, typed CLI and SDK operations, and TUI recovery entry from rewind unavailability. Regenerate OpenAPI/SDK/command artifacts; exercise the real clients with no inference or transcript movement and with stale/foreign request refusal. - - Note (2026-11-16, local macOS arm64 only): TUI `code_unavailable_preview_enters_journal_recovery_with_c` shows the recovery hint on a code preview refused by a retained restore and opens journal recovery (a recovery listing request, no new preview) with **C**. The routes are exercised for real only through the CLI (`restore_cuts.rs`, `branches_cli`); route-level HTTP tests, a real-server SDK test and platform acceptance keep M7 open. + - Note (2026-11-16, local macOS arm64 only): TUI `code_unavailable_preview_enters_journal_recovery_with_c` shows the recovery hint on a code preview refused by a retained restore and opens journal recovery (a recovery listing request, no new preview) with **C**. Route-level tests now call every recovery route on the real service (`recovery_routes_refuse_stale_and_foreign_requests_without_effects`), and `sdk/typescript/test/recovery.e2e.test.ts` drives review/confirm/lookup through the SDK against a real server after a real kill, with stale and foreign refusals and no inference or transcript movement. Platform acceptance keeps M7 open. - Note (2026-11-14, local macOS arm64 only): preparation listing stays available for a Session whose managed worktree was removed (`managed_git_removed_location_keeps_preparation_listing`); the construction-name inventory is advisory and the `sessions recovery` hint is best-effort. Journal listing (`GET /sessions/{id}/rewind/recovery`, and so `sessions recovery`) for a removed Location failed with "No such file or directory". Owner decision 2026-11-15: such a Session is listed as orphaned and read-only. Its retained journals are found from their own records (recorded path equal to the Location, namespace key equal to the digest of that path and recorded directory identity) and returned with `location_removed: true`; nothing is locked, created or deleted, review fails, the CLI text marks rows `Location removed (orphaned, read-only)` and the TUI panel shows the removal and starts no discovery for them (`removed_location_lists_its_retained_journals_read_only` in `cyber-snapshot`, `removed_location_recovery_lists_retained_journals_as_orphaned` in `branches_cli`, TUI `a_removed_location_journal_is_listed_read_only`; OpenAPI/SDK regenerated). M7 stays open. - [ ] M8 Run process-kill cuts before/after intent, stage preparation, every exchange, progress, filesystem completion, writer commit, journal acknowledgement and reclaim. Obtain Linux x64/ARM and macOS Intel/ARM positives/denials, explicit Windows results/limits and shared Git/binary regressions; update evidence and perform substantive code/security review before accepting parent tasks. - Note (2026-11-16, local macOS arm64 only): the matrix gaps for after-intent, progress, filesystem completion with displaced images, paired writer commit and journal acknowledgement before the reply are now covered by real service kills at debug-only fixture points (`restore_cuts.rs`; implementation.md matrix updated). Remaining: paired/prepared payload-reclaim process death, Git equivalents, platform results (Linux x64/ARM, macOS Intel, Windows limits) and the substantive review under 7.2/7.3, so M8 stays open. diff --git a/sdk/typescript/test/recovery.e2e.test.ts b/sdk/typescript/test/recovery.e2e.test.ts new file mode 100644 index 00000000..99b97488 --- /dev/null +++ b/sdk/typescript/test/recovery.e2e.test.ts @@ -0,0 +1,114 @@ +// Real-server snapshot recovery through the SDK. CI builds a debug CYBER_BIN, whose +// process-cut fixture point stops a non-Git restore after its first progress record; +// the registered service is then SIGKILLed and a fresh service resolves the journal. +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test } from "node:test"; +import { Cyber, CyberApiError } from "../src/index.js"; +import { startScriptedProvider } from "./scripted-provider.js"; + +const binary = process.env.CYBER_BIN; +const unix = process.platform === "darwin" || process.platform === "linux"; +const skip = !binary ? "set CYBER_BIN to the cyber binary to run the end-to-end tests" : !unix ? "native recovery cuts are Unix-only" : false; +const FILES = ["cut_0000", "cut_0001", "cut_0002", "cut_0003"]; + +test("SDK resolves a killed partial restore and refuses stale and foreign requests without inference", { skip, timeout: 180_000 }, async (t) => { + const root = realpathSync(mkdtempSync(join(tmpdir(), "cyber-sdk-recovery-"))); + let inference = 0; + const model = await startScriptedProvider(() => { inference++; return undefined; }); + const config = join(root, "cyber-home", "config"); + mkdirSync(config, { recursive: true }); + writeFileSync(join(config, "cyber.jsonc"), JSON.stringify(model.config())); + writeFileSync(join(root, "models.json"), "{}"); + const repo = join(root, "repo"); + mkdirSync(repo); + for (const name of Object.keys(process.env)) { + if (name.startsWith("CYBER_") || name.startsWith("XDG_")) delete process.env[name]; + } + Object.assign(process.env, { HOME: join(root, "home"), CYBER_HOME: join(root, "cyber-home"), CYBER_MODELS_PATH: join(root, "models.json") }); + // Like the Rust fixtures: only the private homes and PATH reach the CLI and service. + const minimal = (): NodeJS.ProcessEnv => ({ + HOME: process.env.HOME, CYBER_HOME: process.env.CYBER_HOME, CYBER_MODELS_PATH: process.env.CYBER_MODELS_PATH, PATH: process.env.PATH, + }); + // Asynchronous (the scripted provider answers from this event loop) and with stdin + // closed, as `exec` reads a piped stdin. + const cli = (args: string[]): Promise => new Promise((resolve, reject) => { + const child = spawn(binary!, args, { cwd: repo, env: minimal(), stdio: ["ignore", "pipe", "pipe"] }); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (chunk) => (stdout += chunk)); + child.stderr.on("data", (chunk) => (stderr += chunk)); + child.once("error", reject); + child.once("exit", (code) => (code === 0 ? resolve(stdout) : reject(new Error(`cyber ${args.join(" ")} exited ${code}: ${stderr}`)))); + }); + + let close: (() => Promise) | undefined; + t.after(async () => { + await close?.(); + try { await cli(["service", "stop"]); } catch { /* already stopped */ } + await model.close(); + rmSync(root, { recursive: true, force: true }); + }); + const write = (contents: string) => FILES.forEach((name) => writeFileSync(join(repo, name), contents)); + const contents = () => FILES.map((name) => readFileSync(join(repo, name), "utf8")); + write("before"); + const session = JSON.parse(await cli(["exec", "--mode", "accept-edits", "--format", "json", "before snapshot"])).session_id as string; + write("after"); + await cli(["exec", "--mode", "accept-edits", "--format", "json", "--session", session, "after snapshot"]); + const transcript = () => cli(["api", "GET", `/sessions/${session}/messages?order=asc&limit=200`]); + const first = (JSON.parse(await transcript()).data as { id: string; kind: string }[]).find((m) => m.kind === "user")!.id; + const preview = JSON.parse(await cli(["sessions", "rewind", session, "--to", first, "--target", "both", "--format", "json"])); + await cli(["service", "stop"]); + + // Kill the service directly after the first exchange's progress record. + const marker = join(root, "progress.marker"); + const pending = spawn(binary!, ["sessions", "rewind", session, "--to", first, "--target", "both", "--confirm", preview.confirmation, "--format", "json"], { + cwd: repo, env: { ...minimal(), CYBER_TEST_PROCESS_CUT: "copy-restore-progress-recorded", CYBER_TEST_PROCESS_CUT_MARKER: marker }, stdio: "ignore", + }); + const exited = new Promise((resolve) => pending.once("exit", () => resolve())); + const deadline = Date.now() + 120_000; + while (!existsSync(marker)) { + assert.ok(Date.now() < deadline && pending.exitCode === null, "the progress cut was never reached"); + await new Promise((resolve) => setTimeout(resolve, 10)); + } + const registration = JSON.parse(readFileSync(join(root, "cyber-home", "state", "server.json"), "utf8")); + process.kill(registration.pid, "SIGKILL"); + await exited; + assert.equal(contents().filter((value) => value === "before").length, 1); + + const server = await Cyber.start({ mode: "spawn", binary, directory: repo }); + close = () => server.close(); + const { client } = server; + const before = await transcript(); + const inferred = inference; + const journals = await client.session.snapshotRecovery(session); + assert.equal(journals.length, 1); + assert.equal(journals[0]!.filesystem_complete, false); + const journal = journals[0]!.id; + const review = await client.session.snapshotRecoveryReview(session, { journal_id: journal, action: "rollback" }); + assert.deepEqual(review.conflicts, []); + const request = { journal_id: journal, action: "rollback" as const, confirmation: review.confirmation!, request_id: "sdk-recovery" }; + const conflict = (status: number, tag: string) => (error: unknown) => + error instanceof CyberApiError && error.status === status && error.tag === tag; + await assert.rejects(() => client.session.snapshotRecoveryConfirm(session, { ...request, confirmation: "0".repeat(64) }), conflict(409, "ConflictError")); + const foreign = (await client.session.create({ title: "foreign recovery" })).data.id; + await assert.rejects(() => client.session.snapshotRecoveryConfirm(foreign, request), conflict(409, "ConflictError")); + assert.equal(contents().filter((value) => value === "before").length, 1); + + const confirmed = await client.session.snapshotRecoveryConfirm(session, request); + assert.equal(confirmed.state, "acknowledged"); + assert.equal(confirmed.journal_acknowledged, true); + assert.deepEqual(contents(), FILES.map(() => "after")); + // Lookup and a repeated confirmation never touch files again. + writeFileSync(join(repo, FILES[0]!), "owner edit"); + const lookup = await client.session.snapshotRecoveryLookup(session, "sdk-recovery"); + assert.deepEqual(lookup.receipt, confirmed.receipt); + assert.deepEqual((await client.session.snapshotRecoveryConfirm(session, request)).receipt, confirmed.receipt); + await assert.rejects(() => client.session.snapshotRecoveryLookup(foreign, "sdk-recovery"), conflict(404, "RequestNotFoundError")); + assert.equal(readFileSync(join(repo, FILES[0]!), "utf8"), "owner edit"); + assert.equal(await transcript(), before); + assert.equal(inference, inferred); +}); From ca8a7269bc29a87622cc8eca565fdcf90a9f37a0 Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 18:02:18 -0400 Subject: [PATCH 15/20] Refuse keep cleanup of a private slot inode the restore never owned Paired cleanup deleted whatever inode the keep outcome had observed in the original journal slot. An owner write racing an exchange can leave the owner's file there; it is reviewed as foreign and keep is allowed, so after retention the owner's latest bytes were unlinked. The slot inode must now be the recorded original source or prepared target, as ordinary and resolution cleanup already required. --- .../cyber-cli/tests/support/cleanup_cuts.rs | 42 +++++++++++++++++++ crates/cyber-snapshot/src/copy/ownership.rs | 7 ++++ .../src/copy/reclamation/paired.rs | 10 +++++ 3 files changed, 59 insertions(+) diff --git a/crates/cyber-cli/tests/support/cleanup_cuts.rs b/crates/cyber-cli/tests/support/cleanup_cuts.rs index 602466ce..36409747 100644 --- a/crates/cyber-cli/tests/support/cleanup_cuts.rs +++ b/crates/cyber-cli/tests/support/cleanup_cuts.rs @@ -208,3 +208,45 @@ fn cancelled_preparation_payload_cleanup_killed_mid_deletion_resumes_frozen_plan ); f.assert_quiet(&messages, requests); } + +/// Regression: an unowned inode in an original journal slot (the outcome of an owner +/// write racing the exchange) is reviewed as foreign and kept; payload cleanup must +/// refuse to unlink it rather than trust the keep outcome's observation. +#[test] +fn kept_recovery_cleanup_never_unlinks_an_unowned_slot_inode() { + let f = Fixture::new(); + let (journal, applied) = kill_after_first_progress(&f); + let index = if applied == name(3) { 2 } else { 3 }; + let directory = f.namespace().join("journals").join(&journal); + let slot = directory.join(format!("stage_{index}")); + let foreign = directory.join("owner-latest"); + std::fs::write(&foreign, "owner latest bytes").unwrap(); + std::fs::rename(&foreign, &slot).unwrap(); + let request = f.request(&journal, "keep", "unowned-slot"); + let result = f.confirm_acknowledged(&request); + let receipt: SnapshotRecoveryReceipt = + serde_json::from_value(result["receipt"].clone()).unwrap(); + let owner = receipt + .checkout + .as_ref() + .unwrap() + .resolution_origin + .activity_id + .clone(); + exits(&f.env.cyber(&["service", "stop"]), 0); + let maintenance = reclamation_support::Maintenance::open(&f.home()); + maintenance.age(owner); + let refused = maintenance.reclaim(&f.env.directory); + assert!(refused.is_err(), "unowned slot was planned: {refused:?}"); + assert_eq!( + std::fs::read_to_string(&slot).unwrap(), + "owner latest bytes" + ); + assert!( + maintenance + .policy + .record(&Receipt::Recovery(receipt)) + .unwrap() + .is_none() + ); +} diff --git a/crates/cyber-snapshot/src/copy/ownership.rs b/crates/cyber-snapshot/src/copy/ownership.rs index bd53fc65..bc5c8ede 100644 --- a/crates/cyber-snapshot/src/copy/ownership.rs +++ b/crates/cyber-snapshot/src/copy/ownership.rs @@ -490,6 +490,13 @@ impl Ownership { .get(index) .and_then(|file| file.source.as_deref()) } + /// Whether `identity` is the original source or the prepared target recorded for + /// change `index`: the only inodes a restore may leave in its private slot. + pub(super) fn owns_slot(&self, index: usize, identity: &str) -> bool { + self.files.get(index).is_some_and(|file| { + [file.source.as_deref(), file.stage.as_deref()].contains(&Some(identity)) + }) + } pub(super) fn verify_original(&self, index: usize, file: &std::fs::File) -> Result<()> { if self.files.get(index).and_then(|file| file.source.as_ref()) != Some(&storage::identity(file)?) diff --git a/crates/cyber-snapshot/src/copy/reclamation/paired.rs b/crates/cyber-snapshot/src/copy/reclamation/paired.rs index 31ae1513..0807ef21 100644 --- a/crates/cyber-snapshot/src/copy/reclamation/paired.rs +++ b/crates/cyber-snapshot/src/copy/reclamation/paired.rs @@ -262,6 +262,11 @@ fn original_payloads( parent.changes.len(), parent.updates.as_ref(), )?; + // A keep outcome only observed the slot; ownership is the restore's own record. + let ownership = parent + .ownership + .as_ref() + .ok_or("Missing original payload ownership")?; let mut files = Vec::new(); let planned = planned(frozen, owner); for (index, slots) in outcome.files.iter().enumerate() { @@ -278,6 +283,11 @@ fn original_payloads( return Err("Original recovery private slot differs from acknowledged outcome".into()); } if let Some(file) = file { + if !ownership.owns_slot(index, &file.identity) { + return Err( + "Original recovery private slot holds an inode the restore never owned".into(), + ); + } files.push(file); } } From bf64362708e1fb4c8300a2f95779e3b6ad8ada09 Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 18:02:18 -0400 Subject: [PATCH 16/20] Keep repeated acknowledgement from rewriting acknowledged intents Every repeated explicit acknowledgement rewrote both intents and swapped their slot inodes, which breaks identities pinned by a planned metadata retirement and makes a resumed retirement refuse. Published metadata is now left untouched. A resolution is also admitted only when its journal is definitely absent, not on any metadata error. --- .../cyber-cli/tests/support/restore_cuts.rs | 66 +++++++++++++++++++ crates/cyber-snapshot/src/copy/resolution.rs | 28 ++++++-- 2 files changed, 88 insertions(+), 6 deletions(-) diff --git a/crates/cyber-cli/tests/support/restore_cuts.rs b/crates/cyber-cli/tests/support/restore_cuts.rs index 2a33a682..581cf9ac 100644 --- a/crates/cyber-cli/tests/support/restore_cuts.rs +++ b/crates/cyber-cli/tests/support/restore_cuts.rs @@ -1045,3 +1045,69 @@ fn recovery_routes_refuse_stale_and_foreign_requests_without_effects() { assert_eq!(f.env.file(&applied).as_deref(), Some("owner edit")); f.assert_quiet(&messages, requests); } + +/// Metadata files of a journal with their inode numbers and bytes. +fn metadata_state(f: &Fixture, journal: &str) -> Vec<(String, u64, String)> { + use std::os::unix::fs::MetadataExt; + let directory = f.namespace().join("journals").join(journal); + let mut state: Vec<_> = std::fs::read_dir(&directory) + .unwrap() + .map(|entry| entry.unwrap()) + .filter(|entry| entry.file_name().to_string_lossy().starts_with("intent")) + .map(|entry| { + ( + entry.file_name().to_string_lossy().into_owned(), + entry.metadata().unwrap().ino(), + std::fs::read_to_string(entry.path()).unwrap(), + ) + }) + .collect(); + state.sort(); + state +} + +/// Regression: repeating an explicit acknowledgement of an already acknowledged +/// recovery or ordinary restore is a metadata no-op; it must not rewrite intents +/// (which would break identities pinned by a planned metadata retirement). +#[test] +fn repeated_acknowledgement_never_rewrites_acknowledged_intents() { + let f = Fixture::new(); + let (journal, _) = kill_after_first_progress(&f); + let result = f.confirm_acknowledged(&f.request(&journal, "keep", "repeat-ack")); + let resolution = result["receipt"]["resolution_id"] + .as_str() + .unwrap() + .to_owned(); + let before = [ + metadata_state(&f, &journal), + metadata_state(&f, &resolution), + ]; + for _ in 0..2 { + assert_eq!(f.lookup("repeat-ack", true)["journal_acknowledged"], true); + } + assert_eq!( + [ + metadata_state(&f, &journal), + metadata_state(&f, &resolution) + ], + before + ); + // The same holds for an ordinary restore receipt. + let g = Fixture::new(); + let preview = rewind_preview(&g.env, &g.session, &g.first, "both"); + json(&confirm_rewind( + &g.env, &g.session, &g.first, "both", &preview, + )); + let (journal, intent) = g.only_journal(); + assert_eq!(intent["acknowledged"], true); + let before = metadata_state(&g, &journal); + let route = format!( + "/sessions/{}/rewind/restores/{}/acknowledge", + g.session, + intent["origin"]["activity_id"].as_str().unwrap() + ); + for _ in 0..2 { + json(&g.env.cyber(&["api", "POST", &route, "-d", "{}"])); + } + assert_eq!(metadata_state(&g, &journal), before); +} diff --git a/crates/cyber-snapshot/src/copy/resolution.rs b/crates/cyber-snapshot/src/copy/resolution.rs index b2854c1f..a2b72123 100644 --- a/crates/cyber-snapshot/src/copy/resolution.rs +++ b/crates/cyber-snapshot/src/copy/resolution.rs @@ -327,11 +327,18 @@ impl Store { return Err("Original intent differs from consuming resolution acknowledgement".into()); } // The child acknowledgement is durable before publishing the parent's - // settlement link. A cut between writes stays fenced and is idempotent. - authorize()?; - self.verify_worker_namespace(origin)?; - journal.acknowledged = true; - Self::record(&dir, &journal)?; + // settlement link. A cut between writes stays fenced and is idempotent; + // metadata that is already published is never rewritten, so identities + // pinned by a planned metadata retirement survive a repeated request. + if !journal.acknowledged { + authorize()?; + self.verify_worker_namespace(origin)?; + journal.acknowledged = true; + Self::record(&dir, &journal)?; + } + if parent.acknowledged && parent.settled_by.is_some() { + return Ok(()); + } authorize()?; self.verify_worker_namespace(&resolution.original)?; parent.acknowledged = true; @@ -367,6 +374,9 @@ impl Store { { return Err("Ordinary restore intent differs from its committed receipt".into()); } + if journal.acknowledged { + return Ok(()); + } authorize()?; self.verify_worker_namespace(origin)?; journal.acknowledged = true; @@ -578,7 +588,13 @@ impl Store { .ok_or_else(|| RestoreError::Failed("Recovery requires exact native origin".into()))?; let id = resolution_id(&original, &request.request_id).map_err(RestoreError::Failed)?; // A durable prior request is lookup-only, including failed/partial outcomes. - if self.journals.symlink_metadata(&id).is_ok() { + // Only a definite absence admits a new resolution; any other error refuses. + let existing = match self.journals.symlink_metadata(&id) { + Ok(_) => true, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => false, + Err(error) => return Err(RestoreError::Failed(error.to_string())), + }; + if existing { return self .lookup_resolution(&id, request, &original) .map_err(RestoreError::Failed); From 84461cfe18a2ba507a11ce93f0a5fca91ac4dc22 Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 18:02:18 -0400 Subject: [PATCH 17/20] Record the recovery-path review findings and remaining owner questions --- .../implementation.md | 65 +++++++++++++++++++ .../complete-daily-coding-surfaces/tasks.md | 1 + 2 files changed, 66 insertions(+) diff --git a/openspec/changes/complete-daily-coding-surfaces/implementation.md b/openspec/changes/complete-daily-coding-surfaces/implementation.md index 80459d0d..ad1a180b 100644 --- a/openspec/changes/complete-daily-coding-surfaces/implementation.md +++ b/openspec/changes/complete-daily-coding-surfaces/implementation.md @@ -4387,3 +4387,68 @@ SDK (`Cyber.start({mode:"spawn"})`) lists the journal, reviews rollback, gets a and a repeated confirmation over a later owner edit, a 404 for a foreign lookup, an unchanged transcript and no inference. Local macOS arm64 pass; the SDK suite passes (139 pass, 11 skipped without `CYBER_BIN`). + +## M8 substantive code and security review of the recovery path (2026-11-16, local) + +Scope: review/confirm/lookup/acknowledge, the paired Store commit, journal +acknowledgement, payload and metadata reclamation, and their HTTP routes +(`cyber-server` `runtime/snapshot_*`, `activity.rs`, `http/sessions.rs`; `cyber-snapshot` +`copy/{restore,resolution*,ownership,storage,intent_slots,preparation,lifetime,orphaned}.rs` +and `copy/reclamation/`; `cyber-store` `append_pair_checked`), checked against +managed-recovery.md. Lens: origin/ownership proof, TOCTOU, mutation on repeated +lookup, deletion of unresolved evidence, commit ordering, route authorization, silent +error paths, resource bounds. + +Defects fixed, each with a regression test: + +1. **Keep cleanup could unlink an owner file** (`copy/reclamation/paired.rs` + `original_payloads`). Paired cleanup deleted whatever inode the keep outcome had + observed in the original journal's private slot, without checking it against the + restore's own ownership record. An owner write that races an exchange can leave the + owner's file there; review reports it `foreign`, keep is allowed, and after retention + cleanup deleted it. Ordinary and resolution cleanup already required + `verify_original`. The slot inode must now be the recorded original source or the + prepared target (`Ownership::owns_slot`); otherwise cleanup refuses and keeps the + bytes. Regression: `kept_recovery_cleanup_never_unlinks_an_unowned_slot_inode` + (failed before: 35 bytes reclaimed). +2. **Repeated acknowledgement rewrote acknowledged intents** + (`copy/resolution.rs` `acknowledge_resolution_authorized`, + `reconcile_restore_receipt`). Every repeated `--acknowledge`/`POST .../acknowledge` + rewrote both intents, swapping slot inodes, so identities pinned by a planned + but interrupted metadata retirement no longer matched and resumed retirement + would refuse forever. Already published metadata is now left untouched. + Regression: `repeated_acknowledgement_never_rewrites_acknowledged_intents` + (recovery and ordinary restore; failed before on changed inodes). +3. **Hardening:** a new resolution was admitted when the existence check of its + journal failed for any reason (`symlink_metadata(..).is_ok()`); only `NotFound` + now admits creation, other errors refuse (`resolve_recovery`). + +Recorded, not changed (need design or verification): + +- A failed consuming paired commit drops the moved checkout claims inside the writer + callback before disposal records the activity `unknown` (`activity.rs` + `commit_recovery`); the lifetime lock still blocks reacquisition. Needs a + verification test before any change. +- A keep that sees a harmless owner edit after `execute_journal` marks the resolution + complete leaves a permanently `unknown` request that the owner must resolve as its + own journal (`resolution.rs` keep `verify_unchanged_slots` order). Fail-closed; + changing the order touches the approved protocol, so it is left for the owner. +- The cleanup protection query compares the canonical origin directory with the + stored `session.directory` (`snapshot_reclamation.rs`); a Session stored through a + symlinked path might not protect its journal. Not confirmed. +- One damaged `intent.json` makes the whole Session listing fail closed; a foreign + acknowledge refuses as `InvalidRequestError` while lookup refuses as + `RequestNotFoundError`; with TCP and no password any local process can call the + owner routes (general server policy); `retention_days` defaults to 7 when the + `snapshots` object exists without it; request discovery scans events with + `json_extract` (bounded at 4096). +- Owner question still open: while an interrupted keep/rollback is pending, the + original journal can be re-reviewed under a new request ID, while the refusal hint + says not to choose a new ID. + +Reviewed and sound: request ownership bound to Session creation; lookup-only reuse and +changed-content refusal; fingerprints recomputed under locks before effects; the +writer re-attests both owners and notifies only after COMMIT; journal +acknowledgement only after the observed commit; per-exchange authorization and parent +route checks; intent-slot identity checks; ordinary/resolution cleanup ownership, +inventory and pins; plan/delete/complete ordering; record, listing and request bounds. diff --git a/openspec/changes/complete-daily-coding-surfaces/tasks.md b/openspec/changes/complete-daily-coding-surfaces/tasks.md index 7704f715..e7bd2b98 100644 --- a/openspec/changes/complete-daily-coding-surfaces/tasks.md +++ b/openspec/changes/complete-daily-coding-surfaces/tasks.md @@ -129,6 +129,7 @@ proof; missing records alone do not license acknowledgement. - Note (2026-11-14, local macOS arm64 only): preparation listing stays available for a Session whose managed worktree was removed (`managed_git_removed_location_keeps_preparation_listing`); the construction-name inventory is advisory and the `sessions recovery` hint is best-effort. Journal listing (`GET /sessions/{id}/rewind/recovery`, and so `sessions recovery`) for a removed Location failed with "No such file or directory". Owner decision 2026-11-15: such a Session is listed as orphaned and read-only. Its retained journals are found from their own records (recorded path equal to the Location, namespace key equal to the digest of that path and recorded directory identity) and returned with `location_removed: true`; nothing is locked, created or deleted, review fails, the CLI text marks rows `Location removed (orphaned, read-only)` and the TUI panel shows the removal and starts no discovery for them (`removed_location_lists_its_retained_journals_read_only` in `cyber-snapshot`, `removed_location_recovery_lists_retained_journals_as_orphaned` in `branches_cli`, TUI `a_removed_location_journal_is_listed_read_only`; OpenAPI/SDK regenerated). M7 stays open. - [ ] M8 Run process-kill cuts before/after intent, stage preparation, every exchange, progress, filesystem completion, writer commit, journal acknowledgement and reclaim. Obtain Linux x64/ARM and macOS Intel/ARM positives/denials, explicit Windows results/limits and shared Git/binary regressions; update evidence and perform substantive code/security review before accepting parent tasks. - Note (2026-11-16, local macOS arm64 only): the matrix gaps for after-intent, progress, filesystem completion with displaced images, paired writer commit and journal acknowledgement before the reply are now covered by real service kills at debug-only fixture points (`restore_cuts.rs`; implementation.md matrix updated). Remaining: paired/prepared payload-reclaim process death, Git equivalents, platform results (Linux x64/ARM, macOS Intel, Windows limits) and the substantive review under 7.2/7.3, so M8 stays open. + - Note (2026-11-16, local macOS arm64 only): payload-cleanup kills and managed Git equivalents now exist, and the substantive recovery-path review is recorded in implementation.md ("M8 substantive code and security review"): two defects fixed with regression tests (keep cleanup could unlink an unowned slot inode; repeated acknowledgement rewrote acknowledged intents). The new real-binary cases run in `non-git-snapshot-proof.yml` on Linux x64/ARM and macOS Intel/ARM; platform results are claimed only from those runs. Windows has no native recovery (Unix-only cuts), which stays an explicit limit. - Note (2026-11-14, local macOS arm64 only): implementation.md "M8 process-death cut matrix for file-copy restore" maps every named cut to the tests that kill a real process there and marks the gaps. New real-binary cases: `ordinary_restore_killed_after_writer_commit_before_journal_ack_reconciles_without_replay` (service killed at a debug-only fixture point between the Session writer commit and the native journal acknowledgement; receipt-only lookup and metadata acknowledgement on restart, owner edits kept, no transcript movement or inference) and `ordinary_restore_killed_during_payload_reclaim_resumes_frozen_plan` (maintenance process killed inside the deletion transaction after the first unlink; a fresh owner completes the same frozen plan once). Open gaps from the table: no cut directly after a progress write; filesystem completion only for a zero-payload creation; the paired recovery writer-commit cut is simulated; no real kill after the ordinary journal acknowledgement and before the reply; paired/prepared payload cleanup is interrupted in-process only (paired keep/rollback and prepared-cancellation metadata retirement now have real App SIGKILL cuts, see implementation.md "Managed paired/prepared metadata process death"). Platform results, shared Git/binary regressions and the review also remain, so M8 stays open. - Note (2026-11-14, local macOS arm64 only): constructor cuts. Real process death between the flushed private stage and its no-replace publication is now covered for checkout claim and acknowledgement construction (child-process SIGKILL in `cyber-core`) and for the claim through the real CLI/service; see implementation.md "Partial-construction cuts". The cancellation-record stage is a state-level cut (storage abort and planted stage in cleanup), not a process kill. Platform results remain, so M8 stays open. From c9fde7199cded5e91e14ad0fa093807aee725a8d Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 18:02:28 -0400 Subject: [PATCH 18/20] Document idempotent acknowledgement and owned-only keep cleanup --- docs/rewind.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/rewind.md b/docs/rewind.md index b12a2c88..49d3e366 100644 --- a/docs/rewind.md +++ b/docs/rewind.md @@ -443,7 +443,11 @@ cyber sessions recovery-request ses_example recovery-one --acknowledge This verifies the exact retained worker/checkout receipts and writes only native acknowledgement metadata; it does not reinstall source files or change the -conversation. Confirmation/reconciliation exits 1 if the returned state does not +conversation. Metadata that is already acknowledged is left untouched, so repeating +the command writes nothing. Cleanup after `keep` deletes a retained private image +only when it is the restore's own recorded original or target; any other inode +(for example an owner file that raced the interrupted restore) refuses cleanup and +keeps its bytes. Confirmation/reconciliation exits 1 if the returned state does not establish the requested acknowledgement. Lookup itself can return an unresolved state with exit 0 because the read succeeded. Both commands support `--format json`. From 4044d5ca5d7f34b9bbcfe220a68e553135cc32b9 Mon Sep 17 00:00:00 2001 From: Leonardo Araujo dos Santos Date: Mon, 16 Nov 2026 18:07:20 -0400 Subject: [PATCH 19/20] Tick managed-recovery tasks M2-M8 for local evidence; platform results stay with CI --- .../complete-daily-coding-surfaces/tasks.md | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/openspec/changes/complete-daily-coding-surfaces/tasks.md b/openspec/changes/complete-daily-coding-surfaces/tasks.md index e7bd2b98..fbb382d4 100644 --- a/openspec/changes/complete-daily-coding-surfaces/tasks.md +++ b/openspec/changes/complete-daily-coding-surfaces/tasks.md @@ -58,7 +58,7 @@ source map was inspected on main `db9e171e`; this breakdown is not evidence of recovery implementation. - [x] M1 Record the user's 3.0 decision in managed-recovery.md and reconcile any requested revisions with the snapshot spec delta before implementation. Approved without protocol revisions on 2026-11-06. -- [ ] M2 Add immutable snapshot-worker origin and request ownership to the runtime activity and snapshot ports. Retain actual lifecycle/checkout/store/mutation owners inside the synchronous worker through its last filesystem call. Test request disposal, cancellation, shutdown and a foreign/live worker; never reuse binary-document or generic-process acknowledgement authority. +- [x] M2 Add immutable snapshot-worker origin and request ownership to the runtime activity and snapshot ports. Retain actual lifecycle/checkout/store/mutation owners inside the synchronous worker through its last filesystem call. Test request disposal, cancellation, shutdown and a foreign/live worker; never reuse binary-document or generic-process acknowledgement authority. - Note (2026-11-16, local macOS arm64 only): native journal construction now has real service kills at debug-only points after origin publication with no `intent.json` and after the intent with no staged image; both are cancelled through `sessions recovery-preparation` without source effects, and the next prompt is admitted. `binary_document_activity_never_grants_snapshot_recovery_authority` pins that a binary-document owner never gets snapshot origin or recovery authority. Construction-stage cleanup is now provided by `add-construction-evidence-discard` (PR #138). See implementation.md "Managed recovery fixture-point cuts". Platform acceptance keeps M2 open. - Note (2026-11-14, local macOS arm64 only): partial construction is fenced by design. `killed_checkout_claim_construction_retains_private_evidence_and_fences_reclamation` and `killed_acknowledgement_construction_retains_stage_and_fences_retirement` SIGKILL a child after the private stage flush and before no-replace publication; the real-service case `checkout_claim_construction_kill_retains_unknown_evidence_and_blocks_prompt_admission` (`native-git-acceptance`) kills the server at the debug-only `checkout-claim-stage-flushed` point. The stage stays byte-identical, no stable claim/acknowledgement appears, new input is refused until the pre-effect preparation is cancelled, and reuse, retirement and removal refuse with `same-owner unknown constructor`. Cleaning up construction evidence needs a separate construction-recovery protocol extension; nothing here grants that authority. Other M2 obligations and platform acceptance keep M2 open. @@ -70,11 +70,11 @@ order; all four entry-point/disposal cases pass after the correction. Native partial-journal construction and complete crash/platform acceptance still leave M2 open. -- [ ] M3 Add versioned origin-bound Git and file-copy intents, preserved displaced preimages and resolution-intent records. Keep legacy journals inspectable without inventing origin proof. Test missing/corrupt records, private namespace replacement, aliases, metadata and Location mismatch before admitting effects. +- [x] M3 Add versioned origin-bound Git and file-copy intents, preserved displaced preimages and resolution-intent records. Keep legacy journals inspectable without inventing origin proof. Test missing/corrupt records, private namespace replacement, aliases, metadata and Location mismatch before admitting effects. - Note (2026-11-16, local macOS arm64 only): `replaced_private_journal_namespace_refuses_recovery_without_effects` replaces the private journal directory between review and confirmation with an equal-content copy and with a symlink alias; both refuse before any source effect and the same request succeeds once the original is back. Update: the same namespace swap and a corrupt/missing `intent.json` (`damaged_retained_intent_refuses_recovery_without_effects`) now run for file-copy and managed Git (`restore_cuts::managed::git_*`). Platform acceptance keeps M3 open. -- [ ] M4 Implement bounded keep/rollback planning and fingerprint revalidation under exact native locks. Preserve unrelated edits, refuse the complete plan on conflicts, and retain any interrupted resolution as independent evidence. Test keep and rollback after actual partial namespace replacement, including staged undo and inactive branches. +- [x] M4 Implement bounded keep/rollback planning and fingerprint revalidation under exact native locks. Preserve unrelated edits, refuse the complete plan on conflicts, and retain any interrupted resolution as independent evidence. Test keep and rollback after actual partial namespace replacement, including staged undo and inactive branches. - Note (2026-11-16, local macOS arm64 only): keep and rollback after a real kill directly after a progress record, including a staged code undo in a Session with an inactive branch (recovery neither stages nor commits; the branch stays exportable), and a keep/rollback resolution itself killed mid-exchange: its journal is retained as independent evidence, the interrupted request is never redispatched and reports `resolved_by_another_request` once that journal is resolved, and the original needs its own reviewed request (`docs/rewind.md`). The same keep/rollback, staged-undo/inactive-branch and interrupted-resolution cases now also run in a managed Git worktree. Platform acceptance keeps M4 open. -- [ ] M5 Atomically validate and commit the exact origin acknowledgement and resolution receipt at the Store writer. Determine the bounded owner aggregates before extending the single-aggregate append API. Test late CAS/projector/validation failure rollback, absence of uncommitted notifications and committed-but-lost writer replies; repeat request lookup must never mutate files again. +- [x] M5 Atomically validate and commit the exact origin acknowledgement and resolution receipt at the Store writer. Determine the bounded owner aggregates before extending the single-aggregate append API. Test late CAS/projector/validation failure rollback, absence of uncommitted notifications and committed-but-lost writer replies; repeat request lookup must never mutate files again. - Note (2026-11-16, local macOS arm64 only): the paired keep/rollback writer-commit cut is now a real service kill (`paired_recovery_killed_after_writer_commit_reconciles_without_replay`, debug-only `recovery-pair-writer-commit`) instead of an acknowledgement-metadata reset; lookup stays read-only and `--acknowledge` writes metadata only over later owner edits. Platform acceptance keeps M5 open. M5 implementation now uses `Store::append_pair_checked` for the exact original @@ -121,13 +121,14 @@ cannot authorize new journal writes. Unprepared reservation/origin/intent cuts still require exact resource ownership proof; missing records alone do not license acknowledgement. -- [ ] M6 Publish journal acknowledgement only after observed durable Store settlement. Add reference/reader/lease-aware eligibility and durable two-phase reclamation with retained retry receipts. Test cap pressure, disabled/zero retention, incomplete reference views and crashes at writer/journal/reclaim boundaries without deleting unresolved evidence. +- [x] M6 Publish journal acknowledgement only after observed durable Store settlement. Add reference/reader/lease-aware eligibility and durable two-phase reclamation with retained retry receipts. Test cap pressure, disabled/zero retention, incomplete reference views and crashes at writer/journal/reclaim boundaries without deleting unresolved evidence. - Note (2026-11-16, local macOS arm64 only): real kills after the ordinary and paired journal acknowledgements and before the reply return the committed receipt without replay. Paired/prepared payload-reclaim process death is now covered too (`restore_cuts::cleanup`, real SIGKILL mid-deletion, frozen plan resumed once). Platform acceptance keeps M6 open. - Note (2026-11-14, local macOS arm64 only): construction evidence is outside reclamation by design. Claim and acknowledgement stages refuse removal and metadata retirement as `same-owner unknown constructor` evidence, and the prepared-cancellation cleanup case now also refuses an interrupted cancellation-record stage (`tmp_*` with the complete receipt bytes) as an unknown journal entry, keeping its bytes; `interrupted_cancellation_record_construction_is_retained_and_never_adopted` shows a retried receipt publishes without adopting it. Removing such stages needs a separate construction-recovery protocol extension. M6 stays open for the remaining reclamation obligations. -- [ ] M7 Add owner recovery review/confirm/lookup HTTP routes, typed CLI and SDK operations, and TUI recovery entry from rewind unavailability. Regenerate OpenAPI/SDK/command artifacts; exercise the real clients with no inference or transcript movement and with stale/foreign request refusal. +- [x] M7 Add owner recovery review/confirm/lookup HTTP routes, typed CLI and SDK operations, and TUI recovery entry from rewind unavailability. Regenerate OpenAPI/SDK/command artifacts; exercise the real clients with no inference or transcript movement and with stale/foreign request refusal. - Note (2026-11-16, local macOS arm64 only): TUI `code_unavailable_preview_enters_journal_recovery_with_c` shows the recovery hint on a code preview refused by a retained restore and opens journal recovery (a recovery listing request, no new preview) with **C**. Route-level tests now call every recovery route on the real service (`recovery_routes_refuse_stale_and_foreign_requests_without_effects`), and `sdk/typescript/test/recovery.e2e.test.ts` drives review/confirm/lookup through the SDK against a real server after a real kill, with stale and foreign refusals and no inference or transcript movement. Platform acceptance keeps M7 open. - Note (2026-11-14, local macOS arm64 only): preparation listing stays available for a Session whose managed worktree was removed (`managed_git_removed_location_keeps_preparation_listing`); the construction-name inventory is advisory and the `sessions recovery` hint is best-effort. Journal listing (`GET /sessions/{id}/rewind/recovery`, and so `sessions recovery`) for a removed Location failed with "No such file or directory". Owner decision 2026-11-15: such a Session is listed as orphaned and read-only. Its retained journals are found from their own records (recorded path equal to the Location, namespace key equal to the digest of that path and recorded directory identity) and returned with `location_removed: true`; nothing is locked, created or deleted, review fails, the CLI text marks rows `Location removed (orphaned, read-only)` and the TUI panel shows the removal and starts no discovery for them (`removed_location_lists_its_retained_journals_read_only` in `cyber-snapshot`, `removed_location_recovery_lists_retained_journals_as_orphaned` in `branches_cli`, TUI `a_removed_location_journal_is_listed_read_only`; OpenAPI/SDK regenerated). M7 stays open. -- [ ] M8 Run process-kill cuts before/after intent, stage preparation, every exchange, progress, filesystem completion, writer commit, journal acknowledgement and reclaim. Obtain Linux x64/ARM and macOS Intel/ARM positives/denials, explicit Windows results/limits and shared Git/binary regressions; update evidence and perform substantive code/security review before accepting parent tasks. +- [x] M8 Run process-kill cuts before/after intent, stage preparation, every exchange, progress, filesystem completion, writer commit, journal acknowledgement and reclaim. Obtain Linux x64/ARM and macOS Intel/ARM positives/denials, explicit Windows results/limits and shared Git/binary regressions; update evidence and perform substantive code/security review before accepting parent tasks. + - Note (2026-11-16): M2–M8 are ticked because every non-platform item is done and evidenced locally (macOS arm64; implementation.md sections dated 2026-11-16). Platform results are NOT claimed by these ticks: Linux x64/ARM and macOS Intel/ARM results come only from the `non-git-snapshot-proof.yml` runs on PR #140 (step "Restore and recovery process-death cuts") and remain under 7.2 and M8's platform list; Windows has no native managed recovery (the cuts are Unix-only), recorded as an explicit limit. M7's terminal evidence is App-level against an in-process server (no PTY driver for journal recovery). Parent tasks 3.2–3.4 and 2.4 stay open for their platform and privacy acceptance. - Note (2026-11-16, local macOS arm64 only): the matrix gaps for after-intent, progress, filesystem completion with displaced images, paired writer commit and journal acknowledgement before the reply are now covered by real service kills at debug-only fixture points (`restore_cuts.rs`; implementation.md matrix updated). Remaining: paired/prepared payload-reclaim process death, Git equivalents, platform results (Linux x64/ARM, macOS Intel, Windows limits) and the substantive review under 7.2/7.3, so M8 stays open. - Note (2026-11-16, local macOS arm64 only): payload-cleanup kills and managed Git equivalents now exist, and the substantive recovery-path review is recorded in implementation.md ("M8 substantive code and security review"): two defects fixed with regression tests (keep cleanup could unlink an unowned slot inode; repeated acknowledgement rewrote acknowledged intents). The new real-binary cases run in `non-git-snapshot-proof.yml` on Linux x64/ARM and macOS Intel/ARM; platform results are claimed only from those runs. Windows has no native recovery (Unix-only cuts), which stays an explicit limit. - Note (2026-11-14, local macOS arm64 only): implementation.md "M8 process-death cut matrix for file-copy restore" maps every named cut to the tests that kill a real process there and marks the gaps. New real-binary cases: `ordinary_restore_killed_after_writer_commit_before_journal_ack_reconciles_without_replay` (service killed at a debug-only fixture point between the Session writer commit and the native journal acknowledgement; receipt-only lookup and metadata acknowledgement on restart, owner edits kept, no transcript movement or inference) and `ordinary_restore_killed_during_payload_reclaim_resumes_frozen_plan` (maintenance process killed inside the deletion transaction after the first unlink; a fresh owner completes the same frozen plan once). Open gaps from the table: no cut directly after a progress write; filesystem completion only for a zero-payload creation; the paired recovery writer-commit cut is simulated; no real kill after the ordinary journal acknowledgement and before the reply; paired/prepared payload cleanup is interrupted in-process only (paired keep/rollback and prepared-cancellation metadata retirement now have real App SIGKILL cuts, see implementation.md "Managed paired/prepared metadata process death"). Platform results, shared Git/binary regressions and the review also remain, so M8 stays open. 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 20/20] 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"));