use std::borrow::Borrow;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use super::{StateStore, durable::fsync_barrier, locking::StateLock};
#[cfg(all(test, target_os = "linux"))]
use super::locking::unescape_octal;
#[cfg(test)]
use super::locking::{STATE_LOCK_SERIAL, is_network_fs, network_lock_advisory};
#[derive(Debug, Error)]
pub enum StateError {
#[error("registry error: {0}")]
StateStore(String),
#[error("lock error: {0}")]
Lock(String),
#[error("{0}")]
ReadOnly(String),
}
type Result<T> = std::result::Result<T, StateError>;
type History = bool;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RecordKind {
File,
#[default]
Dir,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ArtifactKey {
pub target: String,
pub source: String,
pub artifact: String,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ManifestEntryKind {
#[default]
File,
Link,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct ArtifactRecord {
pub version: u32,
pub key: ArtifactKey,
#[serde(default)]
pub source: String,
pub commit: String,
pub digest: String,
pub projected_at: String,
pub layout: String,
#[serde(default)]
pub kind: RecordKind,
pub allow_symlinks: bool,
pub preserve_executable: bool,
pub files: Vec<ManifestFile>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub directories: Option<Vec<DirectoryStamp>>,
#[serde(default)]
pub linked: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub history: History,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub worktree_admin_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mirror_key: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cache_git_root: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub vars_digest: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub deploy_root: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub layout_separator: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub link_target: Option<String>,
}
pub struct NewHistoryRecord {
pub worktree_admin_id: String,
pub mirror_key: String,
pub cache_git_root: String,
}
pub struct NewArtifactRecord<'a> {
pub key: ArtifactKey,
pub underlying_source: &'a str,
pub commit: &'a str,
pub digest: String,
pub layout: String,
pub kind: RecordKind,
pub allow_symlinks: bool,
pub preserve_executable: bool,
pub files: Vec<ManifestFile>,
pub history: Option<NewHistoryRecord>,
pub vars_digest: Option<String>,
pub deploy_root: Option<String>,
pub layout_separator: Option<String>,
}
impl ArtifactRecord {
#[must_use]
pub fn source_name(&self) -> &str {
if self.source.is_empty() {
&self.key.source
} else {
&self.source
}
}
#[must_use]
pub fn projected(p: NewArtifactRecord<'_>) -> Self {
let NewArtifactRecord {
key,
underlying_source,
commit,
digest,
layout,
kind,
allow_symlinks,
preserve_executable,
files,
history,
vars_digest,
deploy_root,
layout_separator,
} = p;
let (history, worktree_admin_id, mirror_key, cache_git_root) = match history {
Some(NewHistoryRecord {
worktree_admin_id,
mirror_key,
cache_git_root,
}) => (
true,
Some(worktree_admin_id),
Some(mirror_key),
Some(cache_git_root),
),
None => (false, None, None, None),
};
Self {
version: 1,
key,
source: underlying_source.to_owned(),
commit: commit.to_owned(),
digest,
projected_at: chrono::Utc::now().to_rfc3339(),
layout,
kind,
allow_symlinks,
preserve_executable,
files,
directories: None,
linked: false,
history,
worktree_admin_id,
mirror_key,
cache_git_root,
vars_digest,
deploy_root,
layout_separator,
link_target: None,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct DirectoryStamp {
pub path: PathBuf,
pub device: u64,
pub inode: u64,
pub mtime_secs: i64,
pub mtime_nanos: i64,
}
impl DirectoryStamp {
pub(crate) fn new(path: PathBuf, meta: &std::fs::Metadata) -> Self {
use std::os::unix::fs::MetadataExt as _;
Self {
path,
device: meta.dev(),
inode: meta.ino(),
mtime_secs: meta.mtime(),
mtime_nanos: meta.mtime_nsec(),
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct ManifestFile {
pub path: PathBuf,
#[serde(default, skip_serializing_if = "is_file_entry")]
pub kind: ManifestEntryKind,
pub size: u64,
pub mtime: u64,
pub blake3: String,
}
fn is_file_entry(kind: impl Borrow<ManifestEntryKind>) -> bool {
matches!(kind.borrow(), ManifestEntryKind::File)
}
pub use crate::sync::model::ScannedFile;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Ejection {
pub source: String,
pub artifact: String,
pub ejected_at: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct HookState {
pub hook_id: String,
pub last_success: std::collections::BTreeSet<String>,
}
pub use crate::digest::Digest;
pub fn ejected_index(
registry: &dyn StateStore,
records: &[ArtifactRecord],
) -> Result<std::collections::HashSet<(String, String, String)>> {
let targets: std::collections::BTreeSet<&str> =
records.iter().map(|r| r.key.target.as_str()).collect();
let mut index = std::collections::HashSet::new();
for target in targets {
for entry in registry.ejections(target)? {
index.insert((target.to_owned(), entry.source, entry.artifact));
}
}
Ok(index)
}
pub struct FileStateStore {
pub(super) state_root: PathBuf,
pub(super) journal_root: PathBuf,
pub(super) lock_timeout: std::time::Duration,
pub(super) on_lock_wait: fn(),
}
const META_VERSION: u32 = 1;
#[derive(Serialize, Deserialize)]
struct TargetMeta {
version: u32,
#[serde(default)]
ejected: Vec<Ejection>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
hooks: Vec<HookState>,
}
impl Default for TargetMeta {
fn default() -> Self {
Self {
version: META_VERSION,
ejected: Vec::new(),
hooks: Vec::new(),
}
}
}
impl FileStateStore {
pub fn open(state_root: PathBuf) -> Result<Self> {
let journal_root = state_root.join("locks");
Ok(Self {
state_root,
journal_root,
lock_timeout: super::locking::DEFAULT_LOCK_TIMEOUT,
on_lock_wait: || {},
})
}
#[must_use]
pub fn with_lock_timeout(mut self, lock_timeout: std::time::Duration) -> Self {
self.lock_timeout = lock_timeout;
self
}
#[must_use]
pub fn on_lock_wait(mut self, on_lock_wait: fn()) -> Self {
self.on_lock_wait = on_lock_wait;
self
}
#[must_use]
pub fn state_root(&self) -> &Path {
&self.state_root
}
fn record_path(&self, key: &ArtifactKey) -> PathBuf {
self.state_root
.join("targets")
.join(&key.target)
.join("artifacts")
.join(&key.source)
.join(format!("{}.toml", key.artifact))
}
fn meta_path(&self, target: &str) -> PathBuf {
self.state_root
.join("targets")
.join(target)
.join("meta.toml")
}
fn read_meta(&self, target: &str) -> Result<TargetMeta> {
let path = self.meta_path(target);
match std::fs::read_to_string(&path) {
Ok(text) => toml::from_str(&text)
.map_err(|e| StateError::StateStore(format!("parse meta {}: {e}", path.display()))),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(TargetMeta::default()),
Err(e) => Err(StateError::StateStore(format!(
"read meta {}: {e}",
path.display()
))),
}
}
fn write_meta(&self, target: &str, mut meta: TargetMeta) -> Result<()> {
meta.version = META_VERSION;
let serialized = toml::to_string(&meta)
.map_err(|e| StateError::StateStore(format!("serialize meta: {e}")))?;
atomic_write(&self.meta_path(target), &serialized)
}
#[cfg(test)]
pub(crate) fn save_hook_state(&self, target: &str, hooks: &[HookState]) -> Result<()> {
let mut meta = self.read_meta(target)?;
meta.hooks = hooks.to_vec();
self.write_meta(target, meta)
}
}
#[must_use]
pub fn readonly_root_error(root: &Path) -> StateError {
StateError::ReadOnly(format!(
"state root {} is read-only: a frozen sync cannot write here",
root.display()
))
}
fn read_record(path: &Path) -> Result<ArtifactRecord> {
let text = std::fs::read_to_string(path)
.map_err(|e| StateError::StateStore(format!("read record {}: {e}", path.display())))?;
toml::from_str(&text)
.map_err(|e| StateError::StateStore(format!("parse record {}: {e}", path.display())))
}
fn atomic_write(path: &Path, contents: &str) -> Result<()> {
atomic_write_with(path, contents, fsync_barrier)
}
fn atomic_write_with(
path: &Path,
contents: &str,
sync: impl FnOnce(&std::fs::File) -> std::io::Result<()>,
) -> Result<()> {
let parent = path
.parent()
.ok_or_else(|| StateError::StateStore(format!("path has no parent: {}", path.display())))?;
std::fs::create_dir_all(parent)
.map_err(|e| StateError::StateStore(format!("create dir {}: {e}", parent.display())))?;
let file_name = path.file_name().and_then(|n| n.to_str()).ok_or_else(|| {
StateError::StateStore(format!("path has no file name: {}", path.display()))
})?;
let tmp = parent.join(format!(".{file_name}.tmp"));
{
use std::io::Write as _;
let mut handle = std::fs::File::create(&tmp)
.map_err(|e| StateError::StateStore(format!("create temp {}: {e}", tmp.display())))?;
handle
.write_all(contents.as_bytes())
.map_err(|e| StateError::StateStore(format!("write temp {}: {e}", tmp.display())))?;
sync(&handle)
.map_err(|e| StateError::StateStore(format!("fsync temp {}: {e}", tmp.display())))?;
}
std::fs::rename(&tmp, path).map_err(|e| {
let _ = std::fs::remove_file(&tmp);
StateError::StateStore(format!(
"rename {} -> {}: {e}",
tmp.display(),
path.display()
))
})
}
fn collect_records(artifacts_dir: &Path, out: &mut Vec<ArtifactRecord>) -> Result<()> {
let source_dirs = match std::fs::read_dir(artifacts_dir) {
Ok(rd) => rd,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(e) => {
return Err(StateError::StateStore(format!(
"read dir {}: {e}",
artifacts_dir.display()
)));
}
};
for source in source_dirs {
let source = source.map_err(|e| {
StateError::StateStore(format!("read entry in {}: {e}", artifacts_dir.display()))
})?;
if !source.file_type().is_ok_and(|t| t.is_dir()) {
continue;
}
collect_records_under(&source.path(), out)?;
}
Ok(())
}
fn collect_records_under(dir: &Path, out: &mut Vec<ArtifactRecord>) -> Result<()> {
let entries = std::fs::read_dir(dir)
.map_err(|e| StateError::StateStore(format!("read dir {}: {e}", dir.display())))?;
for entry in entries {
let entry = entry
.map_err(|e| StateError::StateStore(format!("read entry in {}: {e}", dir.display())))?;
let path = entry.path();
if entry.file_type().is_ok_and(|t| t.is_dir()) {
collect_records_under(&path, out)?;
} else if path.extension().is_some_and(|ext| ext == "toml") {
out.push(read_record(&path)?);
}
}
Ok(())
}
fn sort_records(records: &mut [ArtifactRecord]) {
records.sort_by(|a, b| {
(&a.key.target, &a.key.source, &a.key.artifact).cmp(&(
&b.key.target,
&b.key.source,
&b.key.artifact,
))
});
}
impl StateStore for FileStateStore {
fn artifact(&self, key: &ArtifactKey) -> Result<Option<ArtifactRecord>> {
let path = self.record_path(key);
if path.exists() {
Ok(Some(read_record(&path)?))
} else {
Ok(None)
}
}
fn put_artifact(&self, record: &ArtifactRecord) -> Result<()> {
let path = self.record_path(&record.key);
let serialized = toml::to_string(record)
.map_err(|e| StateError::StateStore(format!("serialize record: {e}")))?;
atomic_write(&path, &serialized)
}
fn put_artifact_journaled(&self, record: &ArtifactRecord, journal_dir: &Path) -> Result<()> {
#[cfg(target_os = "macos")]
{
use std::os::unix::fs::MetadataExt as _;
let path = self.record_path(&record.key);
let parent = path.parent().expect("record path has parent");
std::fs::create_dir_all(parent).map_err(|e| {
StateError::StateStore(format!("create dir {}: {e}", parent.display()))
})?;
let same_device = std::fs::metadata(parent)
.and_then(|record_meta| {
std::fs::metadata(journal_dir)
.map(|journal_meta| record_meta.dev() == journal_meta.dev())
})
.unwrap_or(false);
if same_device {
let serialized = toml::to_string(record)
.map_err(|e| StateError::StateStore(format!("serialize record: {e}")))?;
return atomic_write_with(&path, &serialized, super::sync_to_device);
}
}
#[cfg(not(target_os = "macos"))]
let _ = journal_dir;
self.put_artifact(record)
}
fn remove_artifact(&self, key: &ArtifactKey) -> Result<()> {
let path = self.record_path(key);
match std::fs::remove_file(&path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(StateError::StateStore(format!(
"remove record {}: {e}",
path.display()
))),
}
}
fn target_artifacts(&self, target: &str) -> Result<Vec<ArtifactRecord>> {
let artifacts_dir = self
.state_root
.join("targets")
.join(target)
.join("artifacts");
let mut records = Vec::new();
collect_records(&artifacts_dir, &mut records)?;
sort_records(&mut records);
Ok(records)
}
fn all_artifacts(&self) -> Result<Vec<ArtifactRecord>> {
let targets_dir = self.state_root.join("targets");
let target_dirs = match std::fs::read_dir(&targets_dir) {
Ok(rd) => rd,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => {
return Err(StateError::StateStore(format!(
"read dir {}: {e}",
targets_dir.display()
)));
}
};
let mut records = Vec::new();
for target in target_dirs {
let target = target.map_err(|e| {
StateError::StateStore(format!("read entry in {}: {e}", targets_dir.display()))
})?;
if !target.file_type().is_ok_and(|t| t.is_dir()) {
continue;
}
collect_records(&target.path().join("artifacts"), &mut records)?;
}
sort_records(&mut records);
Ok(records)
}
fn ejections(&self, target: &str) -> Result<Vec<Ejection>> {
Ok(self.read_meta(target)?.ejected)
}
fn save_ejections(&self, target: &str, ejected: &[Ejection]) -> Result<()> {
let mut meta = self.read_meta(target)?;
meta.ejected = ejected.to_vec();
self.write_meta(target, meta)
}
fn hook_state(&self, target: &str) -> Result<Vec<HookState>> {
Ok(self.read_meta(target)?.hooks)
}
fn record_hook_success(
&self,
target: &str,
hook_id: &str,
digest_set: &std::collections::BTreeSet<String>,
) -> Result<()> {
let mut meta = self.read_meta(target)?;
match meta.hooks.iter_mut().find(|hook| hook.hook_id == hook_id) {
Some(existing) => existing.last_success.clone_from(digest_set),
None => meta.hooks.push(HookState {
hook_id: hook_id.to_owned(),
last_success: digest_set.clone(),
}),
}
self.write_meta(target, meta)
}
fn acquire_lock(&self) -> Result<StateLock> {
self.acquire_state_lock()
}
fn journal_root(&self) -> PathBuf {
self.journal_root.clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sync::state::ProjectId;
use std::time::{Duration, Instant};
use tempfile::TempDir;
#[test]
fn failed_flush_does_not_publish_the_new_record() {
let dir = TempDir::new().expect("state");
let path = dir.path().join("record.toml");
std::fs::write(&path, "old record").expect("seed");
let result = atomic_write_with(&path, "new record", |file| {
assert_eq!(file.metadata()?.len(), 10);
assert_eq!(std::fs::read_to_string(&path)?, "old record");
Err(std::io::Error::other("injected flush failure"))
});
assert!(
result
.expect_err("flush must fail")
.to_string()
.contains("injected flush failure")
);
assert_eq!(std::fs::read_to_string(&path).expect("read"), "old record");
}
#[test]
fn digest_requires_strict_sixty_four_hex_body() {
use std::str::FromStr as _;
let hex = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
assert!(
Digest::from_str(&format!("blake3:{hex}")).is_ok(),
"a strict 64-hex blake3 body must parse"
);
assert!(
Digest::from_str(&format!("sha256:{hex}")).is_ok(),
"the unified Digest now also accepts sha256"
);
assert!(
Digest::from_str("blake3:abc").is_err(),
"a short body must be rejected (the unified Digest is strict)"
);
assert!(
Digest::from_str("blake3:").is_err(),
"an empty body must be rejected"
);
}
#[test]
fn linked_record_round_trips_with_sentinels_and_empty_files() {
let rec = ArtifactRecord {
version: 1,
key: ArtifactKey {
target: "vscode".to_owned(),
source: "local-overlay".to_owned(),
artifact: "snippets".to_owned(),
},
source: "local-overlay".to_owned(),
commit: "link".to_owned(),
digest: "link:".to_owned(),
projected_at: "2026-06-08T12:00:00Z".to_owned(),
layout: "flat".to_owned(),
kind: RecordKind::Dir,
allow_symlinks: false,
preserve_executable: true,
files: vec![],
directories: None,
linked: true,
history: false,
worktree_admin_id: None,
mirror_key: None,
cache_git_root: None,
vars_digest: None,
deploy_root: None,
layout_separator: None,
link_target: None,
};
let toml = toml::to_string(&rec).expect("serialize linked record");
let back: ArtifactRecord = toml::from_str(&toml).expect("deserialize linked record");
assert_eq!(
back, rec,
"a linked record must round-trip field-for-field through TOML"
);
assert!(back.linked, "linked flag must survive serde");
assert!(
back.files.is_empty(),
"a linked record carries no manifest files"
);
assert_eq!(back.commit, "link", "sentinel commit must round-trip");
assert_eq!(back.digest, "link:", "sentinel digest must round-trip");
}
#[test]
fn record_without_linked_field_deserializes_as_not_linked() {
let legacy = r#"
version = 1
commit = "def456789abc123"
digest = "blake3:d4e5f6"
projected_at = "2026-01-31T12:34:56Z"
layout = "flat"
allow_symlinks = false
preserve_executable = true
files = []
[key]
target = "vscode"
source = "company-configs"
artifact = "snippets"
"#;
let rec: ArtifactRecord =
toml::from_str(legacy).expect("legacy record without `linked` must still parse");
assert!(
!rec.linked,
"a record predating the linked marker must default to linked = false"
);
}
#[test]
fn record_round_trips_underlying_source_distinct_from_identity() {
let rec = ArtifactRecord {
version: 1,
key: ArtifactKey {
target: "dest".to_owned(),
source: "nvim".to_owned(),
artifact: "init".to_owned(),
},
source: "dotfiles".to_owned(),
commit: "def456789abc123".to_owned(),
digest: "blake3:d4e5f6".to_owned(),
projected_at: "2026-01-31T12:34:56Z".to_owned(),
layout: "by-source".to_owned(),
kind: RecordKind::Dir,
allow_symlinks: false,
preserve_executable: true,
files: vec![],
directories: None,
linked: false,
history: false,
worktree_admin_id: None,
mirror_key: None,
cache_git_root: None,
vars_digest: None,
deploy_root: None,
layout_separator: None,
link_target: None,
};
let toml = toml::to_string(&rec).expect("serialize aliased record");
let back: ArtifactRecord = toml::from_str(&toml).expect("deserialize aliased record");
assert_eq!(
back, rec,
"an aliased record must round-trip field-for-field through TOML"
);
assert_eq!(
back.key.source, "nvim",
"key.source carries the binding IDENTITY (the `as`)"
);
assert_eq!(
back.source, "dotfiles",
"the new `source` field carries the UNDERLYING source name, distinct from identity"
);
}
#[test]
fn record_without_source_field_deserializes_with_default_source() {
let legacy = r#"
version = 1
commit = "def456789abc123"
digest = "blake3:d4e5f6"
projected_at = "2026-01-31T12:34:56Z"
layout = "flat"
allow_symlinks = false
preserve_executable = true
files = []
[key]
target = "vscode"
source = "company-configs"
artifact = "snippets"
"#;
let rec: ArtifactRecord =
toml::from_str(legacy).expect("legacy record without `source` must still parse");
assert_eq!(
rec.source, "",
"a record predating the underlying-source field must default to an empty `source`"
);
}
#[test]
fn record_kind_defaults_to_dir() {
assert_eq!(
RecordKind::default(),
RecordKind::Dir,
"an unspecified record kind must default to a directory tree (the legacy shape)"
);
}
#[test]
fn record_without_kind_field_deserializes_as_dir() {
let legacy = r#"
version = 1
commit = "def456789abc123"
digest = "blake3:d4e5f6"
projected_at = "2026-01-31T12:34:56Z"
layout = "flat"
allow_symlinks = false
preserve_executable = true
files = []
[key]
target = "vscode"
source = "company-configs"
artifact = "snippets"
"#;
let rec: ArtifactRecord =
toml::from_str(legacy).expect("legacy record without `kind` must still parse");
assert_eq!(
rec.kind,
RecordKind::Dir,
"a record predating the kind field must default to RecordKind::Dir"
);
}
#[test]
fn file_kind_record_round_trips_as_lowercase_file() {
let rec = ArtifactRecord {
version: 1,
key: ArtifactKey {
target: "dest".to_owned(),
source: "agents-src".to_owned(),
artifact: "CLAUDE.md".to_owned(),
},
source: "agents-src".to_owned(),
commit: "def456789abc123".to_owned(),
digest: "blake3:d4e5f6".to_owned(),
projected_at: "2026-01-31T12:34:56Z".to_owned(),
layout: "flat".to_owned(),
kind: RecordKind::File,
allow_symlinks: false,
preserve_executable: true,
files: vec![],
directories: None,
linked: false,
history: false,
worktree_admin_id: None,
mirror_key: None,
cache_git_root: None,
vars_digest: None,
deploy_root: None,
layout_separator: None,
link_target: None,
};
let toml = toml::to_string(&rec).expect("serialize file-kind record");
assert!(
toml.contains("kind = \"file\""),
"a file-kind record must serialize the lowercase tag `kind = \"file\"`, got:\n{toml}"
);
let back: ArtifactRecord = toml::from_str(&toml).expect("deserialize file-kind record");
assert_eq!(
back.kind,
RecordKind::File,
"a file-kind record must round-trip its kind through serde"
);
assert_eq!(
back, rec,
"a file-kind record must round-trip field-for-field"
);
}
#[test]
fn dir_kind_record_serializes_as_lowercase_dir() {
let rec = ArtifactRecord {
version: 1,
key: ArtifactKey {
target: "dest".to_owned(),
source: "dotfiles".to_owned(),
artifact: "nvim".to_owned(),
},
source: "dotfiles".to_owned(),
commit: "def456789abc123".to_owned(),
digest: "blake3:d4e5f6".to_owned(),
projected_at: "2026-01-31T12:34:56Z".to_owned(),
layout: "by-source".to_owned(),
kind: RecordKind::Dir,
allow_symlinks: false,
preserve_executable: true,
files: vec![],
directories: None,
linked: false,
history: false,
worktree_admin_id: None,
mirror_key: None,
cache_git_root: None,
vars_digest: None,
deploy_root: None,
layout_separator: None,
link_target: None,
};
let toml = toml::to_string(&rec).expect("serialize dir-kind record");
assert!(
toml.contains("kind = \"dir\""),
"a dir-kind record must serialize the lowercase tag `kind = \"dir\"`, got:\n{toml}"
);
let back: ArtifactRecord = toml::from_str(&toml).expect("deserialize dir-kind record");
assert_eq!(
back.kind,
RecordKind::Dir,
"a dir-kind record must round-trip its kind through serde"
);
}
#[test]
fn projected_threads_file_kind_from_projected_record() {
let projected = NewArtifactRecord {
key: ArtifactKey {
target: "dest".to_owned(),
source: "agents-src".to_owned(),
artifact: "CLAUDE.md".to_owned(),
},
underlying_source: "agents-src",
commit: "def456789abc123",
digest: "blake3:d4e5f6".to_owned(),
layout: "flat".to_owned(),
kind: RecordKind::File,
allow_symlinks: false,
preserve_executable: true,
files: vec![],
history: None,
vars_digest: None,
deploy_root: None,
layout_separator: None,
};
let rec = ArtifactRecord::projected(projected);
assert_eq!(
rec.kind,
RecordKind::File,
"projected() must carry the kind from the NewArtifactRecord verbatim"
);
}
fn vars_digest_record(vars_digest: Option<&str>) -> ArtifactRecord {
ArtifactRecord {
version: 1,
key: ArtifactKey {
target: "vscode".to_owned(),
source: "company-configs".to_owned(),
artifact: "snippets".to_owned(),
},
source: "company-configs".to_owned(),
commit: "def456789abc123".to_owned(),
digest: "blake3:d4e5f6".to_owned(),
projected_at: "2026-01-31T12:34:56Z".to_owned(),
layout: "flat".to_owned(),
kind: RecordKind::Dir,
allow_symlinks: false,
preserve_executable: true,
files: vec![],
directories: None,
linked: false,
history: false,
worktree_admin_id: None,
mirror_key: None,
cache_git_root: None,
vars_digest: vars_digest.map(str::to_owned),
deploy_root: None,
layout_separator: None,
link_target: None,
}
}
#[test]
fn feature_free_record_serializes_without_vars_digest_key() {
let rec = vars_digest_record(None);
let toml = toml::to_string(&rec).expect("serialize feature-free record");
assert!(
!toml.contains("vars_digest"),
"a record whose vars_digest is None must omit the key entirely (skip_serializing_if), \
so feature-free records stay byte-identical to the pre-feature format (INV-8), got:\n{toml}"
);
let back: ArtifactRecord = toml::from_str(&toml).expect("deserialize feature-free record");
assert_eq!(
back, rec,
"a None vars_digest must round-trip field-for-field through TOML"
);
assert_eq!(
back.vars_digest, None,
"a record with no vars_digest key must deserialize back to None"
);
}
#[test]
fn templated_record_round_trips_vars_digest() {
let rec = vars_digest_record(Some("blake3:abc123"));
let toml = toml::to_string(&rec).expect("serialize templated record");
assert!(
toml.contains("vars_digest"),
"a record whose vars_digest is Some(..) must serialize the key, got:\n{toml}"
);
let back: ArtifactRecord = toml::from_str(&toml).expect("deserialize templated record");
assert_eq!(
back, rec,
"a Some(vars_digest) record must round-trip field-for-field through TOML"
);
assert_eq!(
back.vars_digest.as_deref(),
Some("blake3:abc123"),
"the vars_digest value must survive serde"
);
}
#[test]
fn record_without_vars_digest_field_deserializes_as_none() {
let legacy = r#"
version = 1
commit = "def456789abc123"
digest = "blake3:d4e5f6"
projected_at = "2026-01-31T12:34:56Z"
layout = "flat"
allow_symlinks = false
preserve_executable = true
files = []
[key]
target = "vscode"
source = "company-configs"
artifact = "snippets"
"#;
let rec: ArtifactRecord =
toml::from_str(legacy).expect("legacy record without `vars_digest` must still parse");
assert_eq!(
rec.vars_digest, None,
"a record predating the vars-digest field must default to None"
);
}
#[test]
fn record_persists_deploy_root_through_toml_round_trip() {
let stored = r#"
version = 1
source = "nvim-src"
commit = "def456789abc123"
digest = "blake3:d4e5f6"
projected_at = "2026-01-31T12:34:56Z"
layout = "by-source"
allow_symlinks = false
preserve_executable = true
files = []
deploy_root = "/home/alice/.config/nvim"
[key]
target = "home"
source = "nvim"
artifact = "init"
"#;
let rec: ArtifactRecord =
toml::from_str(stored).expect("a record carrying deploy_root must deserialize");
let round_tripped = toml::to_string(&rec).expect("re-serialize record");
assert!(
round_tripped.contains("deploy_root"),
"a record's persisted deploy_root must survive a TOML round-trip (the field is dropped \
until CLIFF-DEPLOYROOT-007 adds it), got:\n{round_tripped}"
);
assert!(
round_tripped.contains("/home/alice/.config/nvim"),
"the expanded absolute deploy root value must survive the round-trip, got:\n{round_tripped}"
);
}
#[test]
fn deploy_root_snapshots_targets_expanded_path() {
let target = crate::config::Config::parse(
"version = 1\n\n[targets.home]\npath = \"~/.config/nvim\"\n",
)
.expect("minimal config parses")
.targets
.remove("home")
.expect("target `home` present");
let expanded = target.expanded_path();
let expanded_str = expanded.to_string_lossy().into_owned();
assert!(
expanded.is_absolute() && !expanded_str.contains('~'),
"premise: a `~/`-target must expand to an absolute tilde-free path (home resolved), got {expanded_str}"
);
assert_ne!(
expanded_str, "~/.config/nvim",
"premise: expanded_path must actually expand the tilde, not echo the raw config path"
);
let stored = format!(
"version = 1\n\
source = \"nvim-src\"\n\
commit = \"def456789abc123\"\n\
digest = \"blake3:d4e5f6\"\n\
projected_at = \"2026-01-31T12:34:56Z\"\n\
layout = \"by-source\"\n\
allow_symlinks = false\n\
preserve_executable = true\n\
files = []\n\
deploy_root = \"{expanded_str}\"\n\n\
[key]\n\
target = \"home\"\n\
source = \"nvim\"\n\
artifact = \"init\"\n"
);
let rec: ArtifactRecord =
toml::from_str(&stored).expect("record with expanded deploy_root must deserialize");
let round_tripped = toml::to_string(&rec).expect("re-serialize record");
let value: toml::Value =
toml::from_str(&round_tripped).expect("re-parse serialized record as a table");
let persisted = value
.get("deploy_root")
.and_then(toml::Value::as_str)
.expect("re-serialized record must expose a deploy_root string");
assert_eq!(
persisted, expanded_str,
"the persisted deploy root must equal the target's expanded absolute path (post tilde expansion)"
);
}
#[test]
fn legacy_record_without_deploy_root_still_loads() {
let legacy = r#"
version = 1
commit = "def456789abc123"
digest = "blake3:d4e5f6"
projected_at = "2026-01-31T12:34:56Z"
layout = "flat"
allow_symlinks = false
preserve_executable = true
files = []
[key]
target = "vscode"
source = "company-configs"
artifact = "snippets"
"#;
let rec: ArtifactRecord =
toml::from_str(legacy).expect("legacy record without `deploy_root` must still parse");
assert_eq!(
rec.key.artifact, "snippets",
"a record predating the deploy-root field must load with its other fields intact"
);
}
#[test]
fn known_network_fstype_yields_a_single_line_lock_advisory() {
for fstype in ["nfs", "smbfs", "cifs"] {
let advisory = network_lock_advisory(fstype).unwrap_or_else(|| {
panic!("a known network fstype ({fstype}) must yield a lock advisory")
});
let lower = advisory.to_lowercase();
assert!(
lower.contains("lock"),
"the {fstype} advisory must be about locking, got: {advisory:?}"
);
assert!(
lower.contains("network") || lower.contains("nfs") || lower.contains("smb"),
"the {fstype} advisory must name the network-filesystem limitation, got: {advisory:?}"
);
assert!(
!advisory.trim_end().contains('\n'),
"the advisory must be a single line, got: {advisory:?}"
);
}
}
#[test]
fn local_fstype_yields_no_lock_advisory() {
for fstype in ["apfs", "ext4", "xfs", "btrfs", "tmpfs"] {
assert_eq!(
network_lock_advisory(fstype),
None,
"a local fstype ({fstype}) must not trigger the network lock advisory"
);
}
}
#[test]
fn local_temp_dir_is_not_falsely_flagged_as_network() {
let dir = TempDir::new().expect("temp state root");
assert!(
!is_network_fs(dir.path()),
"the real detection call on a real local path must not misfire — the local temp dir \
every test uses must never be classified as a network filesystem"
);
}
#[cfg(target_os = "linux")]
#[test]
fn unescape_octal_reassembles_multibyte_utf8_mount_points() {
assert_eq!(
unescape_octal(r"/mnt/caf\303\251"),
"/mnt/café",
"octal-escaped multi-byte UTF-8 bytes must reassemble, not decode byte-by-byte as Latin-1"
);
assert_eq!(
unescape_octal(r"/mnt/space\040dir"),
"/mnt/space dir",
"single-byte ASCII escapes must still round-trip"
);
}
fn record(target: &str, source: &str, artifact: &str) -> ArtifactRecord {
ArtifactRecord {
version: 1,
key: ArtifactKey {
target: target.to_owned(),
source: source.to_owned(),
artifact: artifact.to_owned(),
},
source: source.to_owned(),
commit: "def456789abc123".to_owned(),
digest: "blake3:d4e5f6".to_owned(),
projected_at: "2026-01-31T12:34:56Z".to_owned(),
layout: "flat".to_owned(),
kind: RecordKind::Dir,
allow_symlinks: false,
preserve_executable: true,
files: vec![ManifestFile {
path: PathBuf::from("python.json"),
kind: crate::sync::state::ManifestEntryKind::File,
size: 12345,
mtime: 1_738_329_296,
blake3: "9e8d7c6b5a4f3e2d".to_owned(),
}],
directories: None,
linked: false,
history: false,
worktree_admin_id: None,
mirror_key: None,
cache_git_root: None,
vars_digest: None,
deploy_root: None,
layout_separator: None,
link_target: None,
}
}
fn registry() -> (TempDir, FileStateStore) {
let dir = TempDir::new().expect("temp state root");
let reg = FileStateStore::open(dir.path().to_path_buf()).expect("open registry");
(dir, reg)
}
#[test]
fn project_id_is_blake3_of_canonical_root_first_sixteen_hex() {
let dir = TempDir::new().expect("temp project root");
let canonical = dir.path().canonicalize().expect("canonicalize root");
let expected = blake3::hash(canonical.to_string_lossy().as_bytes());
let id = ProjectId::for_path(dir.path()).expect("project id");
assert_eq!(
id.as_str(),
&expected.to_hex()[..16],
"project id must be the first 16 hex chars of blake3(canonical root)"
);
}
#[test]
fn project_id_is_deterministic_for_same_canonical_path() {
let dir = TempDir::new().expect("temp project root");
let first = ProjectId::for_path(dir.path()).expect("first id");
let second = ProjectId::for_path(dir.path()).expect("second id");
assert_eq!(first, second, "same canonical path => same project id");
}
#[test]
fn get_on_absent_key_is_none() {
let (_dir, reg) = registry();
let key = ArtifactKey {
target: "vscode".to_owned(),
source: "company-configs".to_owned(),
artifact: "snippets".to_owned(),
};
let got = reg
.artifact(&key)
.expect("get must not error on absent key");
assert!(got.is_none(), "absent key yields Ok(None)");
}
#[test]
fn put_then_get_round_trips_the_record() {
let (_dir, reg) = registry();
let rec = record("vscode", "company-configs", "snippets");
reg.put_artifact(&rec).expect("put record");
let got = reg
.artifact(&rec.key)
.expect("get record")
.expect("record present");
assert_eq!(got, rec, "get must return the exact record that was put");
}
#[test]
fn put_writes_record_at_target_source_artifact_path() {
let (dir, reg) = registry();
let rec = record("vscode", "company-configs", "snippets");
reg.put_artifact(&rec).expect("put record");
let expected = dir
.path()
.join("targets")
.join("vscode")
.join("artifacts")
.join("company-configs")
.join("snippets.toml");
assert!(
expected.is_file(),
"record must land at <root>/targets/<target>/artifacts/<source>/<artifact>.toml, expected {}",
expected.display()
);
assert_eq!(
reg.artifact(&rec.key)
.expect("get record")
.expect("record present"),
rec,
"the record written at that path must round-trip back through get"
);
}
#[test]
fn put_creates_missing_parent_directories() {
let (dir, reg) = registry();
assert!(
!dir.path().join("targets").exists(),
"targets dir absent before first put (premise)"
);
let rec = record("vscode", "company-configs", "snippets");
reg.put_artifact(&rec).expect("put must create parent dirs");
let expected = dir
.path()
.join("targets")
.join("vscode")
.join("artifacts")
.join("company-configs")
.join("snippets.toml");
assert!(
expected.is_file(),
"put must create the full parent chain and write the file at {}",
expected.display()
);
assert_eq!(
reg.artifact(&rec.key)
.expect("get record")
.expect("record present"),
rec,
"record written into freshly created dirs must round-trip"
);
}
#[test]
fn remove_deletes_the_record() {
let (_dir, reg) = registry();
let rec = record("vscode", "company-configs", "snippets");
reg.put_artifact(&rec).expect("put record");
reg.remove_artifact(&rec.key).expect("remove record");
assert!(
reg.artifact(&rec.key).expect("get after remove").is_none(),
"removed record must no longer be found"
);
}
#[test]
fn put_leaves_no_temp_file() {
let (dir, reg) = registry();
reg.put_artifact(&record("vscode", "company-configs", "snippets"))
.expect("put record");
let artifact_dir = dir
.path()
.join("targets")
.join("vscode")
.join("artifacts")
.join("company-configs");
let entries: Vec<PathBuf> = std::fs::read_dir(&artifact_dir)
.expect("artifact dir must exist after put")
.map(|e| e.expect("dir entry").path())
.collect();
assert_eq!(
entries,
vec![artifact_dir.join("snippets.toml")],
"atomic write must leave only <artifact>.toml — no temp/.tmp leftover, found {entries:?}"
);
}
fn contains_artifact(records: &[ArtifactRecord], source: &str, artifact: &str) -> bool {
records.iter().any(|r| {
r.key.source == source && r.key.artifact == artifact && r.commit == "def456789abc123"
})
}
#[test]
fn list_target_returns_only_records_under_that_target() {
let (_dir, reg) = registry();
reg.put_artifact(&record("vscode", "company-configs", "snippets"))
.expect("put a");
reg.put_artifact(&record("vscode", "dotfiles", "settings"))
.expect("put b");
reg.put_artifact(&record("nvim", "dotfiles", "init"))
.expect("put c");
let vscode = reg.target_artifacts("vscode").expect("list vscode");
assert_eq!(vscode.len(), 2, "two records under vscode");
assert!(
vscode.iter().all(|r| r.key.target == "vscode"),
"list_target must not leak other targets"
);
assert!(
contains_artifact(&vscode, "company-configs", "snippets"),
"vscode list must contain company-configs/snippets"
);
assert!(
contains_artifact(&vscode, "dotfiles", "settings"),
"vscode list must contain dotfiles/settings"
);
assert!(
!contains_artifact(&vscode, "dotfiles", "init"),
"vscode list must exclude the nvim-only dotfiles/init record"
);
}
#[test]
fn list_target_on_absent_target_is_empty() {
let (_dir, reg) = registry();
let records = reg
.target_artifacts("never-projected")
.expect("listing an absent target must not error");
assert_eq!(records, vec![], "absent target dir => empty record list");
}
#[test]
fn list_all_returns_records_across_all_targets() {
let (_dir, reg) = registry();
reg.put_artifact(&record("vscode", "company-configs", "snippets"))
.expect("put vscode");
reg.put_artifact(&record("nvim", "dotfiles", "init"))
.expect("put nvim");
let all = reg.all_artifacts().expect("list all");
assert_eq!(all.len(), 2, "records from every target appear");
assert!(
all.iter().any(|r| r.key.target == "vscode"
&& r.key.source == "company-configs"
&& r.key.artifact == "snippets"),
"vscode company-configs/snippets present in list_all"
);
assert!(
all.iter().any(|r| r.key.target == "nvim"
&& r.key.source == "dotfiles"
&& r.key.artifact == "init"),
"nvim dotfiles/init present in list_all"
);
}
#[test]
fn list_target_orders_records_by_source_then_artifact() {
let (_dir, reg) = registry();
reg.put_artifact(&record("home", "second", "COPY.md"))
.expect("put second");
reg.put_artifact(&record("home", "dotfiles", "READER.md"))
.expect("put dotfiles");
let keys: Vec<(String, String)> = reg
.target_artifacts("home")
.expect("list home")
.into_iter()
.map(|r| (r.key.source, r.key.artifact))
.collect();
assert_eq!(
keys,
vec![
("dotfiles".to_owned(), "READER.md".to_owned()),
("second".to_owned(), "COPY.md".to_owned()),
],
"list_target must order by (source, artifact), independent of filesystem read_dir order"
);
}
#[test]
fn list_all_orders_records_by_target_then_source_then_artifact() {
let (_dir, reg) = registry();
reg.put_artifact(&record("nvim", "dotfiles", "init"))
.expect("put nvim");
reg.put_artifact(&record("home", "second", "COPY.md"))
.expect("put home second");
reg.put_artifact(&record("home", "dotfiles", "READER.md"))
.expect("put home dotfiles");
let keys: Vec<(String, String, String)> = reg
.all_artifacts()
.expect("list all")
.into_iter()
.map(|r| (r.key.target, r.key.source, r.key.artifact))
.collect();
assert_eq!(
keys,
vec![
(
"home".to_owned(),
"dotfiles".to_owned(),
"READER.md".to_owned()
),
("home".to_owned(), "second".to_owned(), "COPY.md".to_owned()),
("nvim".to_owned(), "dotfiles".to_owned(), "init".to_owned()),
],
"list_all must order by (target, source, artifact), independent of read_dir order"
);
}
#[test]
fn load_ejected_on_missing_meta_is_empty() {
let (_dir, reg) = registry();
let ejected = reg
.ejections("vscode")
.expect("missing meta must not error");
assert!(ejected.is_empty(), "no meta file => empty ejected list");
}
#[test]
fn save_then_load_ejected_round_trips() {
let (_dir, reg) = registry();
let entries = vec![
Ejection {
source: "company-configs".to_owned(),
artifact: "snippets".to_owned(),
ejected_at: "2026-01-31T14:00:00Z".to_owned(),
},
Ejection {
source: "dotfiles".to_owned(),
artifact: "old-config".to_owned(),
ejected_at: "2026-01-30T10:00:00Z".to_owned(),
},
];
reg.save_ejections("vscode", &entries)
.expect("save ejected");
let loaded = reg.ejections("vscode").expect("load ejected");
assert_eq!(
loaded, entries,
"load_ejected must return every saved entry, in order, field-for-field"
);
}
#[test]
fn save_ejected_writes_meta_at_target_path() {
let (dir, reg) = registry();
let entries = vec![Ejection {
source: "company-configs".to_owned(),
artifact: "snippets".to_owned(),
ejected_at: "2026-01-31T14:00:00Z".to_owned(),
}];
reg.save_ejections("vscode", &entries)
.expect("save ejected");
let expected = dir.path().join("targets").join("vscode").join("meta.toml");
assert!(
expected.is_file(),
"ejected meta must land at <root>/targets/<target>/meta.toml, expected {}",
expected.display()
);
}
#[test]
fn lock_exclusive_succeeds_when_unheld() {
let (_dir, reg) = registry();
let guard = reg.acquire_lock();
assert!(guard.is_ok(), "first exclusive lock must succeed");
}
#[test]
fn lock_exclusive_creates_lock_file_at_locks_state_lock() {
let (dir, reg) = registry();
let _held = reg.acquire_lock().expect("first lock acquired");
let expected = dir.path().join("locks").join("state.lock");
assert!(
expected.is_file(),
"lock_exclusive must create <root>/locks/state.lock, expected {}",
expected.display()
);
}
#[test]
fn second_exclusive_lock_fails_while_first_held() {
let dir = TempDir::new().expect("temp state root");
let first = FileStateStore::open(dir.path().to_path_buf()).expect("open first registry");
let second = FileStateStore::open(dir.path().to_path_buf())
.expect("open second registry")
.with_lock_timeout(Duration::ZERO);
let _held = first
.acquire_lock()
.expect("first instance acquires the lock");
let blocked = second.acquire_lock();
let err = blocked.expect_err(
"a second FileStateStore on the same state_root must fail to lock while the first holds it",
);
let msg = err.to_string();
assert!(
msg.contains("phora") && (msg.contains("state.lock") || msg.contains("lock held")),
"lock-held error must mention another phora process / state.lock, got: {msg}"
);
}
#[test]
fn lock_is_released_after_guard_dropped() {
let _serial = STATE_LOCK_SERIAL
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let dir = TempDir::new().expect("temp state root");
let first = FileStateStore::open(dir.path().to_path_buf()).expect("open first registry");
let second = FileStateStore::open(dir.path().to_path_buf()).expect("open second registry");
{
let _held = first
.acquire_lock()
.expect("first instance acquires the lock");
}
let reacquired = second.acquire_lock();
assert!(
reacquired.is_ok(),
"dropping the guard must release the OS lock so another instance can acquire it, got: {:?}",
reacquired.err()
);
}
#[test]
fn contended_lock_is_acquired_once_the_holder_releases_it() {
let _serial = STATE_LOCK_SERIAL
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let dir = TempDir::new().expect("temp state root");
let first = FileStateStore::open(dir.path().to_path_buf()).expect("open first registry");
let second = FileStateStore::open(dir.path().to_path_buf())
.expect("open second registry")
.with_lock_timeout(Duration::from_secs(5));
let (held_tx, held_rx) = std::sync::mpsc::channel();
let holder = std::thread::spawn(move || {
let guard = first.acquire_lock().expect("holder acquires the lock");
held_tx.send(()).expect("signal held");
std::thread::sleep(Duration::from_millis(200));
drop(guard);
});
held_rx.recv().expect("holder holds the lock");
let started = Instant::now();
let acquired = second.acquire_lock();
let waited = started.elapsed();
holder.join().expect("holder thread");
assert!(
acquired.is_ok(),
"a waiting acquisition must succeed once the holder releases, got: {:?}",
acquired.err()
);
assert!(
waited >= Duration::from_millis(100) && waited < Duration::from_secs(5),
"acquisition must wait for the release, not the deadline; waited {waited:?}"
);
}
#[test]
fn contended_lock_gives_up_at_the_deadline() {
let dir = TempDir::new().expect("temp state root");
let first = FileStateStore::open(dir.path().to_path_buf()).expect("open first registry");
let second = FileStateStore::open(dir.path().to_path_buf())
.expect("open second registry")
.with_lock_timeout(Duration::from_millis(300));
let _held = first
.acquire_lock()
.expect("first instance acquires the lock");
let started = Instant::now();
let err = second
.acquire_lock()
.expect_err("a lock held past the deadline must not be acquired");
let waited = started.elapsed();
assert!(
matches!(&err, StateError::Lock(msg) if msg.contains("state.lock held")),
"deadline expiry must be the contended-lock error, got: {err:?}"
);
assert!(
waited >= Duration::from_millis(300) && waited < Duration::from_secs(2),
"acquisition must give up at roughly the deadline; waited {waited:?}"
);
}
#[test]
fn zero_lock_timeout_fails_without_waiting() {
let dir = TempDir::new().expect("temp state root");
let first = FileStateStore::open(dir.path().to_path_buf()).expect("open first registry");
let second = FileStateStore::open(dir.path().to_path_buf())
.expect("open second registry")
.with_lock_timeout(Duration::ZERO);
let _held = first
.acquire_lock()
.expect("first instance acquires the lock");
let started = Instant::now();
let err = second
.acquire_lock()
.expect_err("a zero timeout must not acquire a held lock");
let waited = started.elapsed();
assert_eq!(
err.to_string(),
StateError::Lock(
"another phora process is running for this project (state.lock held)".to_owned()
)
.to_string(),
"a zero timeout keeps the fail-fast message"
);
assert!(
waited < Duration::from_millis(50),
"a zero timeout must fail before the first backoff; waited {waited:?}"
);
}
fn digest_set(digests: &[&str]) -> std::collections::BTreeSet<String> {
digests.iter().map(|d| (*d).to_owned()).collect()
}
#[test]
fn save_then_load_hook_state_round_trips() {
let (_dir, reg) = registry();
let states = vec![HookState {
hook_id: "vscode#0".to_owned(),
last_success: digest_set(&["blake3:aaa", "blake3:bbb"]),
}];
reg.save_hook_state("vscode", &states)
.expect("save hook state");
let loaded = reg.hook_state("vscode").expect("load hook state");
assert_eq!(
loaded, states,
"load_hook_state must return every saved hook record, field-for-field"
);
}
#[test]
fn load_hook_state_on_missing_target_is_empty() {
let (_dir, reg) = registry();
let states = reg
.hook_state("never-synced")
.expect("missing hook state must not error");
assert!(
states.is_empty(),
"a target with no recorded hook run yields an empty hook-state list"
);
}
#[test]
fn record_hook_success_merges_and_leaves_other_hooks_untouched() {
let (_dir, reg) = registry();
reg.save_hook_state(
"vscode",
&[
HookState {
hook_id: "vscode#0".to_owned(),
last_success: digest_set(&["blake3:aaa"]),
},
HookState {
hook_id: "vscode#1".to_owned(),
last_success: digest_set(&["blake3:bbb"]),
},
],
)
.expect("seed two hook records");
reg.record_hook_success("vscode", "vscode#0", &digest_set(&["blake3:ccc"]))
.expect("record success only for the hook that exited 0");
let loaded = reg.hook_state("vscode").expect("load hook state");
let succeeded = loaded
.iter()
.find(|s| s.hook_id == "vscode#0")
.expect("succeeded hook present");
let untouched = loaded
.iter()
.find(|s| s.hook_id == "vscode#1")
.expect("the hook that never succeeded must still be present");
assert_eq!(
succeeded.last_success,
digest_set(&["blake3:ccc"]),
"the succeeded hook's last-success set advances to the current digest-set"
);
assert_eq!(
untouched.last_success,
digest_set(&["blake3:bbb"]),
"a hook not recorded keeps its prior set, so it re-fires next sync (INV-4)"
);
}
#[test]
fn record_hook_success_creates_record_for_first_success() {
let (_dir, reg) = registry();
reg.record_hook_success("vscode", "vscode#0", &digest_set(&["blake3:aaa"]))
.expect("record first-ever success");
let loaded = reg.hook_state("vscode").expect("load hook state");
assert_eq!(
loaded,
vec![HookState {
hook_id: "vscode#0".to_owned(),
last_success: digest_set(&["blake3:aaa"]),
}],
"first success for a hook with no prior record creates exactly that record"
);
}
#[test]
fn hook_state_and_ejected_meta_coexist_for_same_target() {
let (_dir, reg) = registry();
let ejected = vec![Ejection {
source: "company-configs".to_owned(),
artifact: "snippets".to_owned(),
ejected_at: "2026-06-13T10:00:00Z".to_owned(),
}];
let hooks = vec![HookState {
hook_id: "vscode#0".to_owned(),
last_success: digest_set(&["blake3:aaa"]),
}];
reg.save_ejections("vscode", &ejected)
.expect("save ejected");
reg.save_hook_state("vscode", &hooks)
.expect("save hook state");
assert_eq!(
reg.ejections("vscode").expect("load ejected"),
ejected,
"saving hook state must not clobber existing ejected entries"
);
assert_eq!(
reg.hook_state("vscode").expect("load hook state"),
hooks,
"hook state must persist alongside ejected entries"
);
}
#[test]
fn hook_free_target_meta_serializes_byte_identical_to_pre_feature() {
let (dir, reg) = registry();
let ejected = vec![Ejection {
source: "company-configs".to_owned(),
artifact: "snippets".to_owned(),
ejected_at: "2026-01-31T14:00:00Z".to_owned(),
}];
reg.save_ejections("vscode", &ejected)
.expect("save ejected");
let meta_path = dir.path().join("targets").join("vscode").join("meta.toml");
let written = std::fs::read_to_string(&meta_path).expect("read meta.toml");
let expected = "\
version = 1
[[ejected]]
source = \"company-configs\"
artifact = \"snippets\"
ejected_at = \"2026-01-31T14:00:00Z\"
";
assert_eq!(
written, expected,
"a hook-free target's meta.toml must serialize byte-identically to the pre-feature format (INV-8)"
);
}
}