From d665db60d7102fe9f2dcb9e2b8f44f4f930e5c52 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Thu, 1 Oct 2026 12:13:59 -0500 Subject: [PATCH 1/4] wip(LF): secure uncommitted work before hive restructure (NOT_RUN, untested) Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/daemon.rs | 26 +- src/diff_gate.rs | 531 +++++++++++++++++++++++++++++ src/isolation/root_of_trust.rs | 57 +++- src/lib.rs | 1 + src/main.rs | 2 + src/models.rs | 10 + src/ratify.rs | 140 ++++---- tests/test_ratifier_branch_only.rs | 358 +++++++++++++++++++ 9 files changed, 1062 insertions(+), 65 deletions(-) create mode 100644 src/diff_gate.rs create mode 100644 tests/test_ratifier_branch_only.rs diff --git a/README.md b/README.md index e72d7e7..5a55d71 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ Configuration is persisted locally to `~/.config/sovereign/operator.toml` and sh 2. **Propose**: Autonomous generation of atomic improvement proposals in isolated sandbox worktrees (`/tmp/spark-rsi-sandbox/`). 3. **Verify**: Strict validation enforcing the unslop standard, zero plaintext disk secrets, compilation (`cargo check`), and test suites (`cargo test`). 4. **Balance**: Mojo-compiled SIMD tensor kernel evaluating Drive vs. Humanity balance vectors on Grace Blackwell GB10 hardware. -5. **Ratify**: Applies verified patches, commits to git under your configured operator identity, and records lessons in Cortex memory. +5. **Ratify**: Never commits to the target's default branch. Builds the candidate commit off to the side, runs the protected-file checks on the real git diff (path normalization; `..`, symlinks, submodules, deletions and anything outside the declared `ratify_roots` refused), then creates a review branch `rsi/` and a PR-ready patch under `/patches/`. A human opens and merges the pull request. --- diff --git a/src/daemon.rs b/src/daemon.rs index 17edc2d..77e8726 100644 --- a/src/daemon.rs +++ b/src/daemon.rs @@ -174,9 +174,31 @@ impl RsiEngine { let sandbox_base = Path::new(&config.sandbox_root); for mut candidate in candidates { + // Declared-target gate before anything is staged: normalized path, + // no `..`, inside the declared roots, not a root-of-trust file. + if let Err(e) = + crate::diff_gate::check_declared_target(&candidate.target_file, &config.ratify_roots) + { + let _ = ledger.append_block( + BlockType::Evaluation, + format!("Declared target refused: {}", e), + vec![], + ); + continue; + } + // Tier Governance: Check candidate tier and boundaries let tier = crate::meta::TierGovernance::classify_proposal(&candidate); if tier == crate::meta::CandidateTier::Tier2Engine { + if config.operator_key_hex.is_none() { + // Engine changes need operator authorization; no key means no authorization. + let _ = ledger.append_block( + BlockType::Evaluation, + "Tier 2 candidate refused: no operator key configured".to_string(), + vec![], + ); + continue; + } if let Err(e) = crate::meta::TierGovernance::validate_tier2_candidate_boundaries( &candidate.target_file, ) { @@ -499,11 +521,13 @@ impl RsiEngine { maybe_ledger_block = Some(prom_blk); maybe_generation = Some(gen_info); - // 12. Ratify proposal, commit to git, and record in Cortex memory tied to ledger hash + // 12. Ratify proposal onto a review branch + patch (never the default branch), and record in Cortex memory tied to ledger hash let rat = Ratifier::ratify_proposal( proposal, maybe_invariants.as_ref().unwrap(), repo_path, + &config.ratify_roots, + &Path::new(&config.rsi_root).join("patches"), Some(&prom_hash), &config.cortex_url, &config.cortex_space, diff --git a/src/diff_gate.rs b/src/diff_gate.rs new file mode 100644 index 0000000..7cd6404 --- /dev/null +++ b/src/diff_gate.rs @@ -0,0 +1,531 @@ +//! Real-diff gate for the ratifier. +//! +//! The ratifier never trusts the file name a proposal declares. It builds the +//! candidate commit off to the side (temporary index, no checkout, no branch +//! moved), asks git for the actual changed entries between the base commit and +//! the candidate commit, and runs every protected-file check on that real list. +//! +//! Rules, all fail closed: +//! - a path must be relative, non-empty, valid UTF-8, without `\`, NUL, `..`, +//! or a `.git` component; +//! - a path must sit inside one of the declared roots; +//! - a changed entry must be a regular file (mode 100644 or 100755) on both +//! sides; symlinks (120000) and submodules (160000) are refused; +//! - the real changed set must be exactly the declared target file; +//! - `RootOfTrust::validate_declared_files` and +//! `SecurityLayer::evaluate_candidate` run on the real paths and real patch. +//! +//! There is no flag, tier, or environment variable that skips these checks. + +use crate::evaluator::SecurityLayer; +use crate::isolation::RootOfTrust; +use std::path::Path; +use std::process::{Command, Stdio}; + +/// The tier the ratifier evaluates at. Root-of-trust files need tier 2; the +/// ratifier never grants it, so protected files always need a human change. +pub const RATIFIER_TIER: u8 = 1; + +/// Roots a proposal may touch when the config does not say otherwise. +pub const DEFAULT_RATIFY_ROOTS: &[&str] = &["README.md", "CONTRIBUTING.md", "docs", "src"]; + +pub fn default_ratify_roots() -> Vec { + DEFAULT_RATIFY_ROOTS.iter().map(|s| s.to_string()).collect() +} + +/// Normalizes a repository-relative path and refuses anything that could +/// point outside the repository or into git's own metadata. +pub fn normalize_repo_path(raw: &str) -> Result { + if raw.is_empty() { + return Err("empty path".to_string()); + } + if raw.contains('\0') { + return Err(format!("path contains NUL: {:?}", raw)); + } + if raw.contains('\\') { + return Err(format!("path contains backslash: {:?}", raw)); + } + if raw.starts_with('/') { + return Err(format!("absolute path refused: {:?}", raw)); + } + let mut parts: Vec<&str> = Vec::new(); + for comp in raw.split('/') { + match comp { + "" | "." => continue, + ".." => return Err(format!("parent-directory component refused: {:?}", raw)), + c if c.eq_ignore_ascii_case(".git") => { + return Err(format!("git metadata path refused: {:?}", raw)) + } + c => parts.push(c), + } + } + if parts.is_empty() { + return Err(format!("path names the repository root: {:?}", raw)); + } + Ok(parts.join("/")) +} + +/// True when `path` (already normalized) equals a root or sits below it, +/// compared whole component by whole component. +pub fn within_roots(path: &str, roots: &[String]) -> bool { + let p: Vec<&str> = path.split('/').collect(); + roots.iter().any(|root| match normalize_repo_path(root) { + Ok(r) => { + let r: Vec<&str> = r.split('/').collect(); + p.len() >= r.len() && p[..r.len()] == r[..] + } + Err(_) => false, + }) +} + +/// Checks a declared target before anything is staged or written. +pub fn check_declared_target(target_file: &str, roots: &[String]) -> Result { + let normalized = normalize_repo_path(target_file)?; + if !within_roots(&normalized, roots) { + return Err(format!( + "target {:?} is outside the declared roots {:?}", + normalized, roots + )); + } + RootOfTrust::assert_patch_permitted(&normalized, RATIFIER_TIER)?; + Ok(normalized) +} + +/// One changed entry reported by `git diff-tree --raw`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ChangedEntry { + pub old_mode: String, + pub new_mode: String, + pub status: char, + pub path: String, +} + +fn git(repo: &Path) -> Command { + let mut c = Command::new("git"); + c.arg("-C").arg(repo); + // A repo-local hook or config must not run code during ratification. + c.args(["-c", "core.hooksPath=/dev/null"]); + c +} + +fn run(mut cmd: Command, what: &str) -> Result { + let out = cmd + .stdin(Stdio::null()) + .output() + .map_err(|e| format!("{}: {}", what, e))?; + if !out.status.success() { + return Err(format!( + "{} failed: {}", + what, + String::from_utf8_lossy(&out.stderr).trim() + )); + } + Ok(String::from_utf8_lossy(&out.stdout).trim_end().to_string()) +} + +/// Parses `git diff-tree -r -z --raw --no-renames` output. +pub fn parse_raw_diff(raw: &[u8]) -> Result, String> { + let mut entries = Vec::new(); + let mut fields = raw.split(|b| *b == 0).filter(|f| !f.is_empty()); + while let Some(meta) = fields.next() { + let meta = std::str::from_utf8(meta).map_err(|_| "non-UTF-8 diff header".to_string())?; + let meta = meta + .strip_prefix(':') + .ok_or_else(|| format!("unexpected diff header {:?}", meta))?; + let cols: Vec<&str> = meta.split(' ').collect(); + if cols.len() != 5 { + return Err(format!("unexpected diff header {:?}", meta)); + } + let status = cols[4] + .chars() + .next() + .ok_or_else(|| "empty diff status".to_string())?; + let path = fields + .next() + .ok_or_else(|| "diff entry without a path".to_string())?; + let path = std::str::from_utf8(path) + .map_err(|_| "non-UTF-8 path in diff".to_string())? + .to_string(); + entries.push(ChangedEntry { + old_mode: cols[0].to_string(), + new_mode: cols[1].to_string(), + status, + path, + }); + } + Ok(entries) +} + +/// Asks git for the real changed entries between two commits. +pub fn real_diff(repo: &Path, base: &str, head: &str) -> Result, String> { + let out = git(repo) + .args(["diff-tree", "-r", "-z", "--raw", "--no-renames", base, head]) + .stdin(Stdio::null()) + .output() + .map_err(|e| format!("git diff-tree: {}", e))?; + if !out.status.success() { + return Err(format!( + "git diff-tree failed: {}", + String::from_utf8_lossy(&out.stderr).trim() + )); + } + parse_raw_diff(&out.stdout) +} + +/// Unified diff text of the real change, used for the content checks. +pub fn real_patch_text(repo: &Path, base: &str, head: &str) -> Result { + let mut c = git(repo); + c.args(["diff", "--no-ext-diff", "--no-textconv", "--no-color", base, head]); + run(c, "git diff") +} + +fn is_regular_mode(mode: &str) -> bool { + mode == "100644" || mode == "100755" +} + +/// Every check on the real diff. Returns the list of violations; empty means pass. +pub fn check_real_diff( + entries: &[ChangedEntry], + patch_text: &str, + declared_target: &str, + roots: &[String], +) -> Vec { + let mut violations = Vec::new(); + if entries.is_empty() { + violations.push("real diff is empty; nothing to propose".to_string()); + } + let mut real_paths = Vec::new(); + for e in entries { + let normalized = match normalize_repo_path(&e.path) { + Ok(p) => p, + Err(err) => { + violations.push(format!("real diff path refused: {}", err)); + continue; + } + }; + if normalized != e.path { + violations.push(format!("real diff path is not canonical: {:?}", e.path)); + } + if !within_roots(&normalized, roots) { + violations.push(format!( + "real diff touches {:?}, outside the declared roots {:?}", + normalized, roots + )); + } + let old_ok = e.old_mode == "000000" || is_regular_mode(&e.old_mode); + let new_ok = e.new_mode == "000000" || is_regular_mode(&e.new_mode); + if !old_ok || !new_ok { + violations.push(format!( + "real diff entry {:?} is not a regular file (mode {} -> {}); symlinks and submodules are refused", + normalized, e.old_mode, e.new_mode + )); + } + if e.new_mode == "000000" || e.status == 'D' { + violations.push(format!("real diff deletes {:?}; deletions are refused", normalized)); + } + real_paths.push(normalized); + } + if real_paths.len() != 1 || real_paths[0] != declared_target { + violations.push(format!( + "real diff paths {:?} differ from the declared target {:?}", + real_paths, declared_target + )); + } + if let Err(errs) = RootOfTrust::validate_declared_files(&real_paths, RATIFIER_TIER) { + violations.extend(errs); + } + // Content checks look at what the change adds, not at unchanged context lines. + let added: String = patch_text + .lines() + .filter(|l| l.starts_with('+') && !l.starts_with("+++")) + .map(|l| format!("{}\n", &l[1..])) + .collect(); + let sec = SecurityLayer::evaluate_candidate(&real_paths, &added, RATIFIER_TIER); + if !sec.passed { + violations.extend(sec.violations); + } + violations +} + +/// The candidate built off to the side. +#[derive(Debug, Clone)] +pub struct StagedCandidate { + pub base: String, + pub commit: String, + pub entries: Vec, + pub patch_text: String, +} + +/// Builds the candidate commit with a temporary index. Nothing in the working +/// tree, the real index, or any branch changes. The commit object is left +/// unreferenced until the caller decides to create a review branch. +pub fn stage_candidate_commit( + repo: &Path, + target_path: &str, + contents: &[u8], + author_name: &str, + author_email: &str, + message: &str, +) -> Result { + let mut c = git(repo); + c.args(["rev-parse", "--verify", "--quiet", "HEAD^{commit}"]); + let base = run(c, "resolve base commit")?; + if base.is_empty() { + return Err("target repository has no base commit".to_string()); + } + + // Keep the existing executable bit; refuse a symlink or submodule target, + // and refuse a target whose parent directory is a symlink in the base tree. + let mut mode = "100644".to_string(); + let parts: Vec<&str> = target_path.split('/').collect(); + for i in 1..=parts.len() { + let prefix = parts[..i].join("/"); + let mut c = git(repo); + c.args(["ls-tree", "-z", &base, "--", &prefix]); + let listing = run(c, "inspect base tree")?; + if let Some(entry) = listing.split('\0').find(|l| !l.is_empty()) { + let entry_mode = entry.split(' ').next().unwrap_or(""); + if entry_mode == "120000" || entry_mode == "160000" { + return Err(format!( + "{:?} is a symlink or submodule in the base tree; refused", + prefix + )); + } + if i == parts.len() && is_regular_mode(entry_mode) { + mode = entry_mode.to_string(); + } + } + } + + let tmp = tempfile::tempdir().map_err(|e| format!("temp index dir: {}", e))?; + let index = tmp.path().join("index"); + + let mut c = git(repo); + c.env("GIT_INDEX_FILE", &index).args(["read-tree", &base]); + run(c, "read base tree into temporary index")?; + + let mut child = git(repo) + .args(["hash-object", "-w", "--no-filters", "--stdin"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| format!("git hash-object: {}", e))?; + { + use std::io::Write; + let mut stdin = child.stdin.take().ok_or("hash-object stdin")?; + stdin + .write_all(contents) + .map_err(|e| format!("write blob: {}", e))?; + } + let out = child + .wait_with_output() + .map_err(|e| format!("git hash-object: {}", e))?; + if !out.status.success() { + return Err(format!( + "git hash-object failed: {}", + String::from_utf8_lossy(&out.stderr).trim() + )); + } + let blob = String::from_utf8_lossy(&out.stdout).trim().to_string(); + + let mut c = git(repo); + c.env("GIT_INDEX_FILE", &index).args([ + "update-index", + "--add", + "--cacheinfo", + &format!("{},{},{}", mode, blob, target_path), + ]); + run(c, "add blob to temporary index")?; + + let mut c = git(repo); + c.env("GIT_INDEX_FILE", &index).args(["write-tree"]); + let tree = run(c, "write candidate tree")?; + + let mut c = git(repo); + c.env("GIT_AUTHOR_NAME", author_name) + .env("GIT_AUTHOR_EMAIL", author_email) + .env("GIT_COMMITTER_NAME", author_name) + .env("GIT_COMMITTER_EMAIL", author_email) + .args(["commit-tree", &tree, "-p", &base, "-m", message]); + let commit = run(c, "create candidate commit")?; + + let entries = real_diff(repo, &base, &commit)?; + let patch_text = real_patch_text(repo, &base, &commit)?; + Ok(StagedCandidate { + base, + commit, + entries, + patch_text, + }) +} + +/// Branch names the ratifier must never write to. +pub fn default_branch_names(repo: &Path) -> Vec { + let mut names = vec!["main".to_string(), "master".to_string()]; + let mut c = git(repo); + c.args(["symbolic-ref", "--quiet", "--short", "HEAD"]); + if let Ok(h) = run(c, "current branch") { + if !h.is_empty() { + names.push(h); + } + } + let mut c = git(repo); + c.args(["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"]); + if let Ok(h) = run(c, "origin default branch") { + if let Some(b) = h.strip_prefix("origin/") { + names.push(b.to_string()); + } + } + let mut c = git(repo); + c.args(["config", "--get", "init.defaultBranch"]); + if let Ok(h) = run(c, "init.defaultBranch") { + if !h.is_empty() { + names.push(h); + } + } + names +} + +/// Review branch name for a proposal id. Only `[A-Za-z0-9_-]` ids are accepted. +pub fn review_branch_name(proposal_id: &str) -> Result { + if proposal_id.is_empty() + || proposal_id.len() > 100 + || !proposal_id + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') + { + return Err(format!( + "proposal id {:?} is not usable in a branch name", + proposal_id + )); + } + Ok(format!("rsi/{}", proposal_id)) +} + +/// Creates the review branch at `commit`. Refuses to touch a default branch, +/// and refuses to move a branch that already exists (create-only update). +pub fn create_review_branch(repo: &Path, branch: &str, commit: &str) -> Result<(), String> { + let short = branch.trim_start_matches("refs/heads/"); + if default_branch_names(repo).iter().any(|d| d == short) { + return Err(format!("refusing to write default branch {:?}", short)); + } + let full = format!("refs/heads/{}", short); + let mut c = git(repo); + c.args(["check-ref-format", &full]); + run(c, "check branch name")?; + let mut c = git(repo); + // Empty old value: the ref must not exist yet. + c.args(["update-ref", "-m", "rsi: review branch", &full, commit, ""]); + run(c, "create review branch")?; + Ok(()) +} + +/// Mailbox-format patch of the review commit, ready for a PR or `git am`. +pub fn format_patch(repo: &Path, commit: &str) -> Result { + let mut c = git(repo); + c.args(["format-patch", "-1", "--stdout", "--no-color", commit]); + run(c, "format patch") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn roots() -> Vec { + default_ratify_roots() + } + + #[test] + fn normalization_rejects_escape_forms() { + assert_eq!(normalize_repo_path("./docs//a.md").unwrap(), "docs/a.md"); + assert!(normalize_repo_path("../x").is_err()); + assert!(normalize_repo_path("docs/../Cargo.toml").is_err()); + assert!(normalize_repo_path("/etc/passwd").is_err()); + assert!(normalize_repo_path("docs\\..\\Cargo.toml").is_err()); + assert!(normalize_repo_path(".git/hooks/pre-commit").is_err()); + assert!(normalize_repo_path("docs/.GIT/config").is_err()); + assert!(normalize_repo_path("docs/a\0b").is_err()); + assert!(normalize_repo_path("./").is_err()); + assert!(normalize_repo_path("").is_err()); + } + + #[test] + fn roots_match_whole_components_only() { + assert!(within_roots("docs/a.md", &roots())); + assert!(within_roots("README.md", &roots())); + assert!(!within_roots("docsx/a.md", &roots())); + assert!(!within_roots("README.md.bak", &roots())); + assert!(!within_roots("Cargo.toml", &roots())); + assert!(!within_roots(".github/workflows/ci.yml", &roots())); + } + + #[test] + fn declared_target_check_refuses_protected_and_outside() { + assert!(check_declared_target("README.md", &roots()).is_ok()); + assert!(check_declared_target("Cargo.toml", &roots()).is_err()); + assert!(check_declared_target("src/isolation/root_of_trust.rs", &roots()).is_err()); + assert!(check_declared_target("src/../Cargo.toml", &roots()).is_err()); + assert!(check_declared_target("scripts/run.sh", &roots()).is_err()); + } + + #[test] + fn raw_diff_parser_reads_modes_and_paths() { + let raw = b":100644 120000 aaaa bbbb T\0docs/link\0:000000 100644 0000 cccc A\0docs/new.md\0"; + let e = parse_raw_diff(raw).unwrap(); + assert_eq!(e.len(), 2); + assert_eq!(e[0].new_mode, "120000"); + assert_eq!(e[0].path, "docs/link"); + assert_eq!(e[1].status, 'A'); + } + + #[test] + fn real_diff_check_catches_symlink_and_extra_files() { + let link = vec![ChangedEntry { + old_mode: "000000".into(), + new_mode: "120000".into(), + status: 'A', + path: "docs/link".into(), + }]; + assert!(!check_real_diff(&link, "", "docs/link", &roots()).is_empty()); + + let extra = vec![ + ChangedEntry { + old_mode: "100644".into(), + new_mode: "100644".into(), + status: 'M', + path: "README.md".into(), + }, + ChangedEntry { + old_mode: "100644".into(), + new_mode: "100644".into(), + status: 'M', + path: "Cargo.toml".into(), + }, + ]; + let v = check_real_diff(&extra, "", "README.md", &roots()); + assert!(v.iter().any(|m| m.contains("Cargo.toml"))); + } + + #[test] + fn real_diff_check_alone_refuses_protected_file() { + // Even if the declared check were skipped and roots listed it. + let roots = vec!["Cargo.toml".to_string()]; + let e = vec![ChangedEntry { + old_mode: "100644".into(), + new_mode: "100644".into(), + status: 'M', + path: "Cargo.toml".into(), + }]; + let v = check_real_diff(&e, "", "Cargo.toml", &roots); + assert!(v.iter().any(|m| m.contains("protected")), "{:?}", v); + } + + #[test] + fn branch_names_are_sanitized() { + assert_eq!(review_branch_name("prop-abc").unwrap(), "rsi/prop-abc"); + assert!(review_branch_name("../main").is_err()); + assert!(review_branch_name("a b").is_err()); + assert!(review_branch_name("").is_err()); + } +} diff --git a/src/isolation/root_of_trust.rs b/src/isolation/root_of_trust.rs index 82795d1..095956b 100644 --- a/src/isolation/root_of_trust.rs +++ b/src/isolation/root_of_trust.rs @@ -23,13 +23,46 @@ impl RootOfTrust { ".rsi/holdouts", ]; + /// Lexical normalization: drops leading `/`, `.` and empty components and + /// resolves `..`. A path that climbs above the repository root, or holds a + /// backslash or NUL, comes back as `..` so callers fail closed. pub fn normalize_path(path: &str) -> String { - let p = path.trim_start_matches("./").trim_start_matches('/'); - p.to_string() + match Self::normalize_strict(path) { + Ok(p) => p, + Err(_) => "..".to_string(), + } + } + + /// Strict normalization. Refuses backslashes, NUL, and any `..` that climbs + /// above the repository root. + pub fn normalize_strict(path: &str) -> Result { + if path.contains('\\') || path.contains('\0') { + return Err(format!("path {:?} contains a backslash or NUL", path)); + } + let mut stack: Vec<&str> = Vec::new(); + for comp in path.split('/') { + match comp { + "" | "." => {} + ".." => { + if stack.pop().is_none() { + return Err(format!("path {:?} climbs above the repository root", path)); + } + } + c => stack.push(c), + } + } + Ok(stack.join("/")) } pub fn is_protected_path(path: &str) -> bool { - let normalized = Self::normalize_path(path); + let normalized = match Self::normalize_strict(path) { + Ok(p) => p, + // Anything that cannot be normalized is treated as protected. + Err(_) => return true, + }; + if normalized.is_empty() { + return true; + } let path_obj = Path::new(&normalized); for protected in Self::PROTECTED_PATHS { @@ -42,7 +75,9 @@ impl RootOfTrust { } pub fn assert_patch_permitted(target_file: &str, tier: u8) -> Result<(), String> { - let normalized = Self::normalize_path(target_file); + let normalized = Self::normalize_strict(target_file).map_err(|e| { + format!("SECURITY VIOLATION: {}", e) + })?; if Self::is_protected_path(&normalized) && tier < 2 { return Err(format!( "SECURITY VIOLATION: Target path '{}' is a protected root-of-trust file. Required tier: >= 2, candidate tier: {}", @@ -100,6 +135,20 @@ mod tests { assert!(RootOfTrust::assert_patch_permitted("src/isolation/root_of_trust.rs", 2).is_ok()); } + #[test] + fn test_dotdot_and_escape_forms_cannot_bypass_protection() { + // Before the fix these normalized to themselves and were not protected. + assert!(RootOfTrust::is_protected_path("src/../Cargo.toml")); + assert!(RootOfTrust::is_protected_path("docs/../.github/workflows/ci.yml")); + assert!(RootOfTrust::is_protected_path("src//isolation/container.rs")); + assert!(RootOfTrust::is_protected_path("../outside.rs")); + assert!(RootOfTrust::is_protected_path("src\\isolation\\container.rs")); + assert!(RootOfTrust::assert_patch_permitted("src/../Cargo.toml", 0).is_err()); + // Climbing out of the repository is refused even at tier 2. + assert!(RootOfTrust::assert_patch_permitted("../../etc/passwd", 2).is_err()); + assert!(RootOfTrust::assert_patch_permitted("docs/../README.md", 0).is_ok()); + } + #[test] fn test_validate_declared_files_batch() { let valid = vec!["src/observe.rs".to_string(), "README.md".to_string()]; diff --git a/src/lib.rs b/src/lib.rs index 5b76fdd..cfbb025 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ pub mod balance; pub mod canary_observation; pub mod config; pub mod daemon; +pub mod diff_gate; pub mod evaluator; pub mod graph; pub mod isolation; diff --git a/src/main.rs b/src/main.rs index b1d7e81..347c547 100644 --- a/src/main.rs +++ b/src/main.rs @@ -364,6 +364,7 @@ async fn main() -> Result<(), Box> { canary_target: 5000, operator_key_hex: None, non_inferiority_margin: None, + ratify_roots: spark_rsi::diff_gate::default_ratify_roots(), }; let result = RsiEngine::run_cycle(&config).await?; println!("{}", serde_json::to_string_pretty(&result)?); @@ -392,6 +393,7 @@ async fn main() -> Result<(), Box> { canary_target: 5000, operator_key_hex: None, non_inferiority_margin: None, + ratify_roots: spark_rsi::diff_gate::default_ratify_roots(), }; RsiEngine::run_daemon(config).await?; } diff --git a/src/models.rs b/src/models.rs index e40d14b..64d1792 100644 --- a/src/models.rs +++ b/src/models.rs @@ -80,6 +80,12 @@ pub struct BalanceVerdict { pub struct RatificationRecord { pub proposal_id: String, pub commit_hash: Option, + /// Review branch holding the candidate commit. Never the default branch. + #[serde(default)] + pub branch: Option, + /// PR-ready patch (git format-patch) of the candidate commit. + #[serde(default)] + pub patch_path: Option, pub author: String, pub cortex_receipt_id: Option, pub cortex_recorded: bool, @@ -114,6 +120,9 @@ pub struct RsiConfig { pub operator_key_hex: Option, #[serde(default)] pub non_inferiority_margin: Option, + /// Repository-relative roots a proposal may change. Anything else is refused. + #[serde(default = "crate::diff_gate::default_ratify_roots")] + pub ratify_roots: Vec, } fn default_max_url() -> String { @@ -150,6 +159,7 @@ impl Default for RsiConfig { canary_target: 5000, operator_key_hex: None, non_inferiority_margin: None, + ratify_roots: crate::diff_gate::default_ratify_roots(), } } } diff --git a/src/ratify.rs b/src/ratify.rs index 743d51d..f8d6dcc 100644 --- a/src/ratify.rs +++ b/src/ratify.rs @@ -1,19 +1,30 @@ use crate::config::SovereignConfig; +use crate::diff_gate; use crate::models::{ImprovementProposal, InvariantReport, RatificationRecord}; use reqwest::Client; use serde_json::json; use std::fs; use std::path::Path; -use std::process::Command; use uuid::Uuid; pub struct Ratifier; impl Ratifier { + /// Turns an admitted proposal into a review branch plus a PR-ready patch. + /// + /// The ratifier never commits to the target's default branch and never + /// touches its working tree or index. It builds the candidate commit with + /// a temporary index, runs every protected-file check on the REAL git diff + /// of that commit, and only if all checks pass creates `rsi/` + /// (create-only) and writes `/.patch`. A human + /// opens and merges the pull request. + #[allow(clippy::too_many_arguments)] pub async fn ratify_proposal( proposal: &ImprovementProposal, invariants: &InvariantReport, target_repo: &Path, + ratify_roots: &[String], + patch_dir: &Path, ledger_block_hash: Option<&str>, cortex_url: &str, cortex_space: &str, @@ -22,68 +33,75 @@ impl Ratifier { let config = SovereignConfig::load(); let author_str = config.author_string(); - if !invariants.passed { - return Ok(RatificationRecord { - proposal_id: proposal.id.clone(), - commit_hash: None, - author: author_str, - cortex_receipt_id: None, - cortex_recorded: false, - timestamp: now, - status: "Rejected".to_string(), - message: format!("Invariant checks failed: {:?}", invariants.notes), - }); - } + let rejected = |message: String| RatificationRecord { + proposal_id: proposal.id.clone(), + commit_hash: None, + branch: None, + patch_path: None, + author: author_str.clone(), + cortex_receipt_id: None, + cortex_recorded: false, + timestamp: now.clone(), + status: "Rejected".to_string(), + message, + }; - // 1. Apply patch to target file in repository - let target_file_path = target_repo.join(&proposal.target_file); - if let Some(parent) = target_file_path.parent() { - let _ = fs::create_dir_all(parent); + if !invariants.passed { + return Ok(rejected(format!( + "Invariant checks failed: {:?}", + invariants.notes + ))); } - fs::write(&target_file_path, &proposal.proposed_patch) - .map_err(|e| format!("Failed to apply patch to {:?}: {}", target_file_path, e))?; + // 1. Declared target: normalized, inside the declared roots, not protected. + let target = match diff_gate::check_declared_target(&proposal.target_file, ratify_roots) { + Ok(t) => t, + Err(e) => return Ok(rejected(format!("Declared target refused: {}", e))), + }; + let branch = match diff_gate::review_branch_name(&proposal.id) { + Ok(b) => b, + Err(e) => return Ok(rejected(e)), + }; - // 2. Commit to git using dynamic operator profile + // 2. Build the candidate commit off to the side. No branch moves. let commit_msg = format!("rsi: {} ({})", proposal.title, proposal.id); - let _ = Command::new("git") - .arg("-C") - .arg(target_repo) - .args(["add", &proposal.target_file]) - .output(); + let staged = match diff_gate::stage_candidate_commit( + target_repo, + &target, + proposal.proposed_patch.as_bytes(), + &config.operator.name, + &config.operator.email, + &commit_msg, + ) { + Ok(s) => s, + Err(e) => return Ok(rejected(format!("Candidate commit refused: {}", e))), + }; - let commit_out = Command::new("git") - .arg("-C") - .arg(target_repo) - .args([ - "-c", - &format!("user.name={}", config.operator.name), - "-c", - &format!("user.email={}", config.operator.email), - "commit", - "-m", - &commit_msg, - ]) - .output(); + // 3. Protected-file checks on the REAL diff, not the declared name. + let violations = + diff_gate::check_real_diff(&staged.entries, &staged.patch_text, &target, ratify_roots); + if !violations.is_empty() { + return Ok(rejected(format!( + "Real diff refused: {}", + violations.join("; ") + ))); + } - let commit_hash = match commit_out { - Ok(out) if out.status.success() => { - let rev = Command::new("git") - .arg("-C") - .arg(target_repo) - .args(["rev-parse", "--short", "HEAD"]) - .output() - .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()) - .ok(); - rev - } - _ => None, - }; + // 4. Review branch (create-only, never a default branch) and patch file. + if let Err(e) = diff_gate::create_review_branch(target_repo, &branch, &staged.commit) { + return Ok(rejected(format!("Review branch refused: {}", e))); + } + let patch = diff_gate::format_patch(target_repo, &staged.commit)?; + fs::create_dir_all(patch_dir) + .map_err(|e| format!("Failed to create patch dir {:?}: {}", patch_dir, e))?; + let patch_path = patch_dir.join(format!("{}.patch", proposal.id)); + fs::write(&patch_path, format!("{}\n", patch)) + .map_err(|e| format!("Failed to write patch {:?}: {}", patch_path, e))?; - // 3. Record lesson in Cortex memory + // 5. Record lesson in Cortex memory, tied to the review commit. let (cortex_receipt_id, cortex_recorded) = Self::record_cortex_lesson( proposal, - commit_hash.as_deref(), + Some(&staged.commit), ledger_block_hash, cortex_url, cortex_space, @@ -92,15 +110,19 @@ impl Ratifier { Ok(RatificationRecord { proposal_id: proposal.id.clone(), - commit_hash, - author: author_str, + commit_hash: Some(staged.commit.clone()), + branch: Some(branch.clone()), + patch_path: Some(patch_path.display().to_string()), + author: author_str.clone(), cortex_receipt_id, cortex_recorded, - timestamp: now, - status: "Ratified".to_string(), + timestamp: now.clone(), + status: "ProposedForReview".to_string(), message: format!( - "Proposal '{}' ratified and committed to git.", - proposal.title + "Proposal '{}' is on review branch {} with patch {}. The default branch is unchanged; a human merges it.", + proposal.title, + branch, + patch_path.display() ), }) } diff --git a/tests/test_ratifier_branch_only.rs b/tests/test_ratifier_branch_only.rs new file mode 100644 index 0000000..9a0ce52 --- /dev/null +++ b/tests/test_ratifier_branch_only.rs @@ -0,0 +1,358 @@ +//! The ratifier must never commit to the target's default branch. It builds a +//! review branch and a PR-ready patch, and runs the protected-file checks on +//! the REAL git diff. Each test below is a bypass attempt or a realistic fault. + +use spark_rsi::diff_gate::default_ratify_roots; +use spark_rsi::models::{ImprovementProposal, InvariantReport, ProposalKind}; +use spark_rsi::Ratifier; +use std::path::Path; +use std::process::Command; + +const DEAD_CORTEX: &str = "http://127.0.0.1:9"; + +fn git(repo: &Path, args: &[&str]) -> String { + let out = Command::new("git") + .arg("-C") + .arg(repo) + .args(args) + .output() + .expect("git runs"); + assert!( + out.status.success(), + "git {:?} failed: {}", + args, + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).trim().to_string() +} + +fn git_ok(repo: &Path, args: &[&str]) -> bool { + Command::new("git") + .arg("-C") + .arg(repo) + .args(args) + .output() + .map(|o| o.status.success()) + .unwrap_or(false) +} + +/// A target repository on `main` with a README, a docs file, and a Cargo.toml. +fn make_repo() -> tempfile::TempDir { + let tmp = tempfile::tempdir().unwrap(); + let repo = tmp.path(); + git(repo, &["init", "-q", "-b", "main"]); + git(repo, &["config", "user.name", "Test"]); + git(repo, &["config", "user.email", "test@example.invalid"]); + std::fs::write(repo.join("README.md"), "Fast \u{2014} and small.\n").unwrap(); + std::fs::create_dir_all(repo.join("docs")).unwrap(); + std::fs::write(repo.join("docs/guide.md"), "guide\n").unwrap(); + std::fs::write(repo.join("Cargo.toml"), "[package]\nname = \"t\"\n").unwrap(); + git(repo, &["add", "."]); + git(repo, &["commit", "-q", "-m", "initial"]); + tmp +} + +fn proposal(id: &str, target: &str, content: &str) -> ImprovementProposal { + ImprovementProposal { + id: id.to_string(), + title: "test proposal".to_string(), + description: "test".to_string(), + target_file: target.to_string(), + proposed_patch: content.to_string(), + kind: ProposalKind::UnslopSanitization, + created_at: "now".to_string(), + sandbox_path: None, + operator_signature: None, + } +} + +fn passed() -> InvariantReport { + InvariantReport { + passed: true, + unslop_clean: true, + em_dash_detected: 0, + en_dash_detected: 0, + forbidden_buzzwords_detected: vec![], + antithesis_tropes_detected: vec![], + zero_disk_secrets_clean: true, + secret_leaks: vec![], + compilation_passed: true, + compilation_error: None, + tests_passed: true, + test_output_summary: None, + notes: vec![], + } +} + +struct Snapshot { + head: String, + main: String, + status: String, + branches: String, + readme: Vec, +} + +fn snapshot(repo: &Path) -> Snapshot { + Snapshot { + head: git(repo, &["rev-parse", "HEAD"]), + main: git(repo, &["rev-parse", "refs/heads/main"]), + status: git(repo, &["status", "--porcelain", "--untracked-files=all"]), + branches: git(repo, &["for-each-ref", "--format=%(refname) %(objectname)"]), + readme: std::fs::read(repo.join("README.md")).unwrap_or_default(), + } +} + +fn assert_untouched(repo: &Path, before: &Snapshot) { + let after = snapshot(repo); + assert_eq!(before.head, after.head, "HEAD moved"); + assert_eq!(before.main, after.main, "default branch moved"); + assert_eq!(before.status, after.status, "working tree or index changed"); + assert_eq!(before.readme, after.readme, "working tree file changed"); +} + +async fn ratify( + repo: &Path, + patch_dir: &Path, + p: &ImprovementProposal, + roots: &[String], +) -> spark_rsi::models::RatificationRecord { + Ratifier::ratify_proposal( + p, + &passed(), + repo, + roots, + patch_dir, + Some("ledger-hash"), + DEAD_CORTEX, + "test", + ) + .await + .expect("ratifier returns a record") +} + +#[tokio::test] +async fn ratifier_makes_review_branch_and_patch_never_default_branch() { + let tmp = make_repo(); + let repo = tmp.path(); + let patches = tempfile::tempdir().unwrap(); + let before = snapshot(repo); + + let p = proposal("prop-good1", "README.md", "Fast, and small.\n"); + let rec = ratify(repo, patches.path(), &p, &default_ratify_roots()).await; + + assert_eq!(rec.status, "ProposedForReview", "{}", rec.message); + assert_untouched(repo, &before); + + let branch = rec.branch.clone().unwrap(); + assert_eq!(branch, "rsi/prop-good1"); + let tip = git(repo, &["rev-parse", &format!("refs/heads/{}", branch)]); + assert_eq!(Some(tip.clone()), rec.commit_hash); + assert_eq!(git(repo, &["rev-parse", &format!("{}^", tip)]), before.main); + assert_eq!( + git(repo, &["diff", "--name-only", "main", &tip]), + "README.md" + ); + + let patch = std::fs::read_to_string(rec.patch_path.unwrap()).unwrap(); + assert!(patch.contains("Subject: [PATCH] rsi: test proposal (prop-good1)")); + assert!(patch.contains("+Fast, and small.")); + // The patch applies cleanly to the untouched default branch. + let check = tempfile::NamedTempFile::new().unwrap(); + std::fs::write(check.path(), &patch).unwrap(); + assert!(git_ok( + repo, + &["apply", "--check", check.path().to_str().unwrap()] + )); +} + +#[tokio::test] +async fn dotdot_target_cannot_reach_protected_file() { + let tmp = make_repo(); + let repo = tmp.path(); + let patches = tempfile::tempdir().unwrap(); + let before = snapshot(repo); + for target in [ + "docs/../Cargo.toml", + "../outside.txt", + "/etc/passwd", + "docs\\..\\Cargo.toml", + ".git/hooks/post-commit", + "docs/./../.git/config", + ] { + let p = proposal("prop-dotdot", target, "pwned\n"); + let rec = ratify(repo, patches.path(), &p, &default_ratify_roots()).await; + assert_eq!(rec.status, "Rejected", "target {:?} was accepted", target); + assert!(rec.branch.is_none()); + } + assert_untouched(repo, &before); + assert_eq!(before.branches, snapshot(repo).branches, "a branch was created"); +} + +#[tokio::test] +async fn protected_file_refused_even_when_listed_as_root() { + let tmp = make_repo(); + let repo = tmp.path(); + let patches = tempfile::tempdir().unwrap(); + let before = snapshot(repo); + // A misconfigured root list cannot open a root-of-trust file. + let roots = vec!["Cargo.toml".to_string(), ".github".to_string()]; + for target in ["Cargo.toml", ".github/workflows/ci.yml"] { + let p = proposal("prop-prot", target, "[package]\nname = \"evil\"\n"); + let rec = ratify(repo, patches.path(), &p, &roots).await; + assert_eq!(rec.status, "Rejected", "{}", target); + assert!(rec.message.contains("protected"), "{}", rec.message); + } + assert_untouched(repo, &before); +} + +#[tokio::test] +async fn target_outside_declared_roots_refused() { + let tmp = make_repo(); + let repo = tmp.path(); + let patches = tempfile::tempdir().unwrap(); + let before = snapshot(repo); + for target in ["scripts/install.sh", "docsx/a.md", "README.md.orig"] { + let p = proposal("prop-out", target, "echo hi\n"); + let rec = ratify(repo, patches.path(), &p, &default_ratify_roots()).await; + assert_eq!(rec.status, "Rejected", "{}", target); + assert!(rec.message.contains("outside the declared roots"), "{}", rec.message); + } + assert_untouched(repo, &before); +} + +#[cfg(unix)] +#[tokio::test] +async fn symlink_in_base_tree_refused() { + let tmp = make_repo(); + let repo = tmp.path(); + let patches = tempfile::tempdir().unwrap(); + // docs/link -> ../Cargo.toml, and docs/sub -> ../.github (symlinked directory) + std::os::unix::fs::symlink("../Cargo.toml", repo.join("docs/link")).unwrap(); + std::fs::create_dir_all(repo.join(".github/workflows")).unwrap(); + std::fs::write(repo.join(".github/workflows/ci.yml"), "on: push\n").unwrap(); + std::os::unix::fs::symlink("../.github", repo.join("docs/sub")).unwrap(); + git(repo, &["add", "."]); + git(repo, &["commit", "-q", "-m", "links"]); + let before = snapshot(repo); + + for target in ["docs/link", "docs/sub/workflows/ci.yml"] { + let p = proposal("prop-link", target, "evil\n"); + let rec = ratify(repo, patches.path(), &p, &default_ratify_roots()).await; + assert_eq!(rec.status, "Rejected", "{}", target); + assert!(rec.message.contains("symlink"), "{}", rec.message); + } + assert_untouched(repo, &before); + assert_eq!( + std::fs::read_to_string(repo.join("Cargo.toml")).unwrap(), + "[package]\nname = \"t\"\n" + ); +} + +#[tokio::test] +async fn secret_in_real_diff_refused() { + let tmp = make_repo(); + let repo = tmp.path(); + let patches = tempfile::tempdir().unwrap(); + let before = snapshot(repo); + let key = ["AKIA", "ABCDEFGHIJKLMNOP"].join(""); + let p = proposal("prop-secret", "docs/guide.md", &format!("guide\nkey={}\n", key)); + let rec = ratify(repo, patches.path(), &p, &default_ratify_roots()).await; + assert_eq!(rec.status, "Rejected"); + assert!(rec.message.contains("secret"), "{}", rec.message); + assert_untouched(repo, &before); +} + +#[tokio::test] +async fn network_primitive_in_real_diff_refused() { + let tmp = make_repo(); + let repo = tmp.path(); + let patches = tempfile::tempdir().unwrap(); + let p = proposal( + "prop-net", + "src/lib.rs", + "pub fn f() { let _ = std::net::TcpStream::connect(\"1.2.3.4:80\"); }\n", + ); + let rec = ratify(repo, patches.path(), &p, &default_ratify_roots()).await; + assert_eq!(rec.status, "Rejected"); + assert!(rec.message.contains("network"), "{}", rec.message); +} + +#[tokio::test] +async fn unchanged_content_is_not_a_proposal() { + let tmp = make_repo(); + let repo = tmp.path(); + let patches = tempfile::tempdir().unwrap(); + let p = proposal("prop-same", "docs/guide.md", "guide\n"); + let rec = ratify(repo, patches.path(), &p, &default_ratify_roots()).await; + assert_eq!(rec.status, "Rejected"); + assert!(rec.message.contains("empty"), "{}", rec.message); +} + +#[tokio::test] +async fn current_branch_named_like_review_branch_is_never_written() { + let tmp = make_repo(); + let repo = tmp.path(); + let patches = tempfile::tempdir().unwrap(); + // The checked-out (default) branch has the review branch's name. + git(repo, &["checkout", "-q", "-b", "rsi/prop-clash"]); + let tip = git(repo, &["rev-parse", "HEAD"]); + let p = proposal("prop-clash", "README.md", "changed\n"); + let rec = ratify(repo, patches.path(), &p, &default_ratify_roots()).await; + assert_eq!(rec.status, "Rejected", "{}", rec.message); + assert!(rec.message.contains("default branch"), "{}", rec.message); + assert_eq!(git(repo, &["rev-parse", "refs/heads/rsi/prop-clash"]), tip); +} + +#[tokio::test] +async fn existing_review_branch_is_not_moved() { + let tmp = make_repo(); + let repo = tmp.path(); + let patches = tempfile::tempdir().unwrap(); + let main = git(repo, &["rev-parse", "main"]); + git(repo, &["branch", "rsi/prop-dup", &main]); + let p = proposal("prop-dup", "README.md", "changed\n"); + let rec = ratify(repo, patches.path(), &p, &default_ratify_roots()).await; + assert_eq!(rec.status, "Rejected", "{}", rec.message); + assert_eq!(git(repo, &["rev-parse", "refs/heads/rsi/prop-dup"]), main); +} + +#[tokio::test] +async fn hostile_proposal_id_cannot_name_a_branch() { + let tmp = make_repo(); + let repo = tmp.path(); + let patches = tempfile::tempdir().unwrap(); + let before = snapshot(repo); + for id in ["../main", "x/../../main", "a b", ""] { + let p = proposal(id, "README.md", "changed\n"); + let rec = ratify(repo, patches.path(), &p, &default_ratify_roots()).await; + assert_eq!(rec.status, "Rejected", "id {:?}", id); + } + assert_untouched(repo, &before); + assert_eq!(before.branches, snapshot(repo).branches); +} + +#[tokio::test] +async fn failed_invariants_never_touch_git() { + let tmp = make_repo(); + let repo = tmp.path(); + let patches = tempfile::tempdir().unwrap(); + let before = snapshot(repo); + let mut inv = passed(); + inv.passed = false; + let p = proposal("prop-inv", "README.md", "changed\n"); + let rec = Ratifier::ratify_proposal( + &p, + &inv, + repo, + &default_ratify_roots(), + patches.path(), + None, + DEAD_CORTEX, + "test", + ) + .await + .unwrap(); + assert_eq!(rec.status, "Rejected"); + assert_untouched(repo, &before); + assert_eq!(before.branches, snapshot(repo).branches); +} From d291bb41e02bda540a649b6c6cad5cae4d67150f Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Thu, 1 Oct 2026 12:33:35 -0500 Subject: [PATCH 2/4] crumbs: seed per RFC-0001 Seeded .crumb files with ~/.local/bin/crumb seed. .crumb.local stays ignored. No code changes. Co-Authored-By: Claude Opus 5.5 --- .crumb | 65 +++++++++++++++++++++++++++++++++ .gitignore | 1 + analysis/.crumb | 23 ++++++++++++ analysis/notebooks/.crumb | 20 +++++++++++ docs/.crumb | 19 ++++++++++ examples/.crumb | 20 +++++++++++ mojo/.crumb | 19 ++++++++++ scripts/.crumb | 20 +++++++++++ src/.crumb | 72 +++++++++++++++++++++++++++++++++++++ src/actor/.crumb | 20 +++++++++++ src/bin/.crumb | 19 ++++++++++ src/evaluator/.crumb | 27 ++++++++++++++ src/evaluator/layers/.crumb | 25 +++++++++++++ src/graph/.crumb | 19 ++++++++++ src/isolation/.crumb | 23 ++++++++++++ src/ledger/.crumb | 24 +++++++++++++ src/meta/.crumb | 23 ++++++++++++ src/propose/.crumb | 24 +++++++++++++ src/soak/.crumb | 21 +++++++++++ src/supervisor/.crumb | 21 +++++++++++ tests/.crumb | 30 ++++++++++++++++ tools/.crumb | 19 ++++++++++ 22 files changed, 554 insertions(+) create mode 100644 .crumb create mode 100644 analysis/.crumb create mode 100644 analysis/notebooks/.crumb create mode 100644 docs/.crumb create mode 100644 examples/.crumb create mode 100644 mojo/.crumb create mode 100644 scripts/.crumb create mode 100644 src/.crumb create mode 100644 src/actor/.crumb create mode 100644 src/bin/.crumb create mode 100644 src/evaluator/.crumb create mode 100644 src/evaluator/layers/.crumb create mode 100644 src/graph/.crumb create mode 100644 src/isolation/.crumb create mode 100644 src/ledger/.crumb create mode 100644 src/meta/.crumb create mode 100644 src/propose/.crumb create mode 100644 src/soak/.crumb create mode 100644 src/supervisor/.crumb create mode 100644 tests/.crumb create mode 100644 tools/.crumb diff --git a/.crumb b/.crumb new file mode 100644 index 0000000..7ec46bf --- /dev/null +++ b/.crumb @@ -0,0 +1,65 @@ +{ + "schema_version": "1.0.0", + "name": "spark-rsi", + "layer": "root", + "purpose": "Repository root spark-rsi. Purpose not yet described by a human.", + "below": [ + { + "name": "analysis", + "role": "" + }, + { + "name": "docs", + "role": "" + }, + { + "name": "examples", + "role": "" + }, + { + "name": "mojo", + "role": "" + }, + { + "name": "scripts", + "role": "" + }, + { + "name": "src", + "role": "" + }, + { + "name": "tests", + "role": "" + }, + { + "name": "tools", + "role": "" + } + ], + "extensions": { + "seed": { + "purpose_auto": "Repository root spark-rsi. Purpose not yet described by a human.", + "files": [ + "AGENTS.md", + "AGENT_CODE_OF_CONDUCT.md", + "CONSTITUTION.md", + "CONTRIBUTING.md", + "COVENANT.md", + "Cargo.lock", + "Cargo.toml", + "LICENSE", + "README.md", + "SECURITY.md", + "agent.json", + "llms.txt" + ], + "git": { + "remote": "git@github.com:aien-dev/spark-rsi.git", + "branch": "hardening/LF-ratifier-branch-only", + "head": "d665db6" + } + }, + "owner_lane": "" + } +} diff --git a/.gitignore b/.gitignore index 7a0b582..ce6c160 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ Cargo.lock *.log mojo/*_bin .rsi/ +.crumb.local diff --git a/analysis/.crumb b/analysis/.crumb new file mode 100644 index 0000000..ec05bf2 --- /dev/null +++ b/analysis/.crumb @@ -0,0 +1,23 @@ +{ + "schema_version": "1.0.0", + "name": "analysis", + "layer": "analysis", + "purpose": "Directory analysis. Purpose not yet described by a human.", + "above": { + "name": "spark-rsi", + "path": ".." + }, + "below": [ + { + "name": "notebooks", + "role": "" + } + ], + "extensions": { + "seed": { + "purpose_auto": "Directory analysis. Purpose not yet described by a human.", + "files": [] + }, + "owner_lane": "" + } +} diff --git a/analysis/notebooks/.crumb b/analysis/notebooks/.crumb new file mode 100644 index 0000000..0b4eac3 --- /dev/null +++ b/analysis/notebooks/.crumb @@ -0,0 +1,20 @@ +{ + "schema_version": "1.0.0", + "name": "analysis/notebooks", + "layer": "analysis/notebooks", + "purpose": "Directory analysis/notebooks. Purpose not yet described by a human.", + "above": { + "name": "analysis", + "path": ".." + }, + "extensions": { + "seed": { + "purpose_auto": "Directory analysis/notebooks. Purpose not yet described by a human.", + "files": [ + "evaluator_distributions.ipynb", + "rsi_capability_tracker.ipynb" + ] + }, + "owner_lane": "" + } +} diff --git a/docs/.crumb b/docs/.crumb new file mode 100644 index 0000000..a76ae99 --- /dev/null +++ b/docs/.crumb @@ -0,0 +1,19 @@ +{ + "schema_version": "1.0.0", + "name": "docs", + "layer": "docs", + "purpose": "Directory docs. Purpose not yet described by a human.", + "above": { + "name": "spark-rsi", + "path": ".." + }, + "extensions": { + "seed": { + "purpose_auto": "Directory docs. Purpose not yet described by a human.", + "files": [ + "PHILOSOPHY.md" + ] + }, + "owner_lane": "" + } +} diff --git a/examples/.crumb b/examples/.crumb new file mode 100644 index 0000000..9615920 --- /dev/null +++ b/examples/.crumb @@ -0,0 +1,20 @@ +{ + "schema_version": "1.0.0", + "name": "examples", + "layer": "examples", + "purpose": "Directory examples. Purpose not yet described by a human.", + "above": { + "name": "spark-rsi", + "path": ".." + }, + "extensions": { + "seed": { + "purpose_auto": "Directory examples. Purpose not yet described by a human.", + "files": [ + "init_holdouts.rs", + "seed_ledger.rs" + ] + }, + "owner_lane": "" + } +} diff --git a/mojo/.crumb b/mojo/.crumb new file mode 100644 index 0000000..31155a3 --- /dev/null +++ b/mojo/.crumb @@ -0,0 +1,19 @@ +{ + "schema_version": "1.0.0", + "name": "mojo", + "layer": "mojo", + "purpose": "Directory mojo. Purpose not yet described by a human.", + "above": { + "name": "spark-rsi", + "path": ".." + }, + "extensions": { + "seed": { + "purpose_auto": "Directory mojo. Purpose not yet described by a human.", + "files": [ + "balance.mojo" + ] + }, + "owner_lane": "" + } +} diff --git a/scripts/.crumb b/scripts/.crumb new file mode 100644 index 0000000..6ffca1b --- /dev/null +++ b/scripts/.crumb @@ -0,0 +1,20 @@ +{ + "schema_version": "1.0.0", + "name": "scripts", + "layer": "scripts", + "purpose": "Directory scripts. Purpose not yet described by a human.", + "above": { + "name": "spark-rsi", + "path": ".." + }, + "extensions": { + "seed": { + "purpose_auto": "Directory scripts. Purpose not yet described by a human.", + "files": [ + "drive_aien_code.py", + "prompt_ipc.txt" + ] + }, + "owner_lane": "" + } +} diff --git a/src/.crumb b/src/.crumb new file mode 100644 index 0000000..a416b86 --- /dev/null +++ b/src/.crumb @@ -0,0 +1,72 @@ +{ + "schema_version": "1.0.0", + "name": "src", + "layer": "src", + "purpose": "Directory src. Purpose not yet described by a human.", + "above": { + "name": "spark-rsi", + "path": ".." + }, + "below": [ + { + "name": "actor", + "role": "" + }, + { + "name": "bin", + "role": "" + }, + { + "name": "evaluator", + "role": "" + }, + { + "name": "graph", + "role": "" + }, + { + "name": "isolation", + "role": "" + }, + { + "name": "ledger", + "role": "" + }, + { + "name": "meta", + "role": "" + }, + { + "name": "propose", + "role": "" + }, + { + "name": "soak", + "role": "" + }, + { + "name": "supervisor", + "role": "" + } + ], + "extensions": { + "seed": { + "purpose_auto": "Directory src. Purpose not yet described by a human.", + "files": [ + "balance.rs", + "canary_observation.rs", + "config.rs", + "daemon.rs", + "diff_gate.rs", + "lib.rs", + "main.rs", + "models.rs", + "observe.rs", + "ratify.rs", + "safety_envelope.rs", + "verifier.rs" + ] + }, + "owner_lane": "" + } +} diff --git a/src/actor/.crumb b/src/actor/.crumb new file mode 100644 index 0000000..d5864dd --- /dev/null +++ b/src/actor/.crumb @@ -0,0 +1,20 @@ +{ + "schema_version": "1.0.0", + "name": "src/actor", + "layer": "src/actor", + "purpose": "Directory src/actor. Purpose not yet described by a human.", + "above": { + "name": "src", + "path": ".." + }, + "extensions": { + "seed": { + "purpose_auto": "Directory src/actor. Purpose not yet described by a human.", + "files": [ + "judge.rs", + "mod.rs" + ] + }, + "owner_lane": "" + } +} diff --git a/src/bin/.crumb b/src/bin/.crumb new file mode 100644 index 0000000..1722d02 --- /dev/null +++ b/src/bin/.crumb @@ -0,0 +1,19 @@ +{ + "schema_version": "1.0.0", + "name": "src/bin", + "layer": "src/bin", + "purpose": "Directory src/bin. Purpose not yet described by a human.", + "above": { + "name": "src", + "path": ".." + }, + "extensions": { + "seed": { + "purpose_auto": "Directory src/bin. Purpose not yet described by a human.", + "files": [ + "supervisor.rs" + ] + }, + "owner_lane": "" + } +} diff --git a/src/evaluator/.crumb b/src/evaluator/.crumb new file mode 100644 index 0000000..1788293 --- /dev/null +++ b/src/evaluator/.crumb @@ -0,0 +1,27 @@ +{ + "schema_version": "1.0.0", + "name": "src/evaluator", + "layer": "src/evaluator", + "purpose": "Directory src/evaluator. Purpose not yet described by a human.", + "above": { + "name": "src", + "path": ".." + }, + "below": [ + { + "name": "layers", + "role": "" + } + ], + "extensions": { + "seed": { + "purpose_auto": "Directory src/evaluator. Purpose not yet described by a human.", + "files": [ + "metrics.rs", + "mod.rs", + "stats.rs" + ] + }, + "owner_lane": "" + } +} diff --git a/src/evaluator/layers/.crumb b/src/evaluator/layers/.crumb new file mode 100644 index 0000000..3150b33 --- /dev/null +++ b/src/evaluator/layers/.crumb @@ -0,0 +1,25 @@ +{ + "schema_version": "1.0.0", + "name": "src/evaluator/layers", + "layer": "src/evaluator/layers", + "purpose": "Directory src/evaluator/layers. Purpose not yet described by a human.", + "above": { + "name": "src/evaluator", + "path": ".." + }, + "extensions": { + "seed": { + "purpose_auto": "Directory src/evaluator/layers. Purpose not yet described by a human.", + "files": [ + "correctness.rs", + "longitudinal_replay.rs", + "mod.rs", + "performance.rs", + "resource_efficiency.rs", + "security.rs", + "style.rs" + ] + }, + "owner_lane": "" + } +} diff --git a/src/graph/.crumb b/src/graph/.crumb new file mode 100644 index 0000000..150ee40 --- /dev/null +++ b/src/graph/.crumb @@ -0,0 +1,19 @@ +{ + "schema_version": "1.0.0", + "name": "src/graph", + "layer": "src/graph", + "purpose": "Directory src/graph. Purpose not yet described by a human.", + "above": { + "name": "src", + "path": ".." + }, + "extensions": { + "seed": { + "purpose_auto": "Directory src/graph. Purpose not yet described by a human.", + "files": [ + "mod.rs" + ] + }, + "owner_lane": "" + } +} diff --git a/src/isolation/.crumb b/src/isolation/.crumb new file mode 100644 index 0000000..57c153b --- /dev/null +++ b/src/isolation/.crumb @@ -0,0 +1,23 @@ +{ + "schema_version": "1.0.0", + "name": "src/isolation", + "layer": "src/isolation", + "purpose": "Directory src/isolation. Purpose not yet described by a human.", + "above": { + "name": "src", + "path": ".." + }, + "extensions": { + "seed": { + "purpose_auto": "Directory src/isolation. Purpose not yet described by a human.", + "files": [ + "container.rs", + "manifest.rs", + "mod.rs", + "rollback.rs", + "root_of_trust.rs" + ] + }, + "owner_lane": "" + } +} diff --git a/src/ledger/.crumb b/src/ledger/.crumb new file mode 100644 index 0000000..afe1d6c --- /dev/null +++ b/src/ledger/.crumb @@ -0,0 +1,24 @@ +{ + "schema_version": "1.0.0", + "name": "src/ledger", + "layer": "src/ledger", + "purpose": "Directory src/ledger. Purpose not yet described by a human.", + "above": { + "name": "src", + "path": ".." + }, + "extensions": { + "seed": { + "purpose_auto": "Directory src/ledger. Purpose not yet described by a human.", + "files": [ + "blob.rs", + "db.rs", + "merkle.rs", + "mod.rs", + "record.rs", + "schema.rs" + ] + }, + "owner_lane": "" + } +} diff --git a/src/meta/.crumb b/src/meta/.crumb new file mode 100644 index 0000000..f13f60e --- /dev/null +++ b/src/meta/.crumb @@ -0,0 +1,23 @@ +{ + "schema_version": "1.0.0", + "name": "src/meta", + "layer": "src/meta", + "purpose": "Directory src/meta. Purpose not yet described by a human.", + "above": { + "name": "src", + "path": ".." + }, + "extensions": { + "seed": { + "purpose_auto": "Directory src/meta. Purpose not yet described by a human.", + "files": [ + "ab_fork.rs", + "benchmark_suite.rs", + "mod.rs", + "three_criteria.rs", + "tier.rs" + ] + }, + "owner_lane": "" + } +} diff --git a/src/propose/.crumb b/src/propose/.crumb new file mode 100644 index 0000000..624787e --- /dev/null +++ b/src/propose/.crumb @@ -0,0 +1,24 @@ +{ + "schema_version": "1.0.0", + "name": "src/propose", + "layer": "src/propose", + "purpose": "Directory src/propose. Purpose not yet described by a human.", + "above": { + "name": "src", + "path": ".." + }, + "extensions": { + "seed": { + "purpose_auto": "Directory src/propose. Purpose not yet described by a human.", + "files": [ + "cortex.rs", + "diagnose.rs", + "hypothesis.rs", + "kernel_autotune.rs", + "max_client.rs", + "mod.rs" + ] + }, + "owner_lane": "" + } +} diff --git a/src/soak/.crumb b/src/soak/.crumb new file mode 100644 index 0000000..1d9927b --- /dev/null +++ b/src/soak/.crumb @@ -0,0 +1,21 @@ +{ + "schema_version": "1.0.0", + "name": "src/soak", + "layer": "src/soak", + "purpose": "Directory src/soak. Purpose not yet described by a human.", + "above": { + "name": "src", + "path": ".." + }, + "extensions": { + "seed": { + "purpose_auto": "Directory src/soak. Purpose not yet described by a human.", + "files": [ + "manifest.rs", + "mod.rs", + "runner.rs" + ] + }, + "owner_lane": "" + } +} diff --git a/src/supervisor/.crumb b/src/supervisor/.crumb new file mode 100644 index 0000000..0cac4d8 --- /dev/null +++ b/src/supervisor/.crumb @@ -0,0 +1,21 @@ +{ + "schema_version": "1.0.0", + "name": "src/supervisor", + "layer": "src/supervisor", + "purpose": "Directory src/supervisor. Purpose not yet described by a human.", + "above": { + "name": "src", + "path": ".." + }, + "extensions": { + "seed": { + "purpose_auto": "Directory src/supervisor. Purpose not yet described by a human.", + "files": [ + "daemon.rs", + "ipc.rs", + "mod.rs" + ] + }, + "owner_lane": "" + } +} diff --git a/tests/.crumb b/tests/.crumb new file mode 100644 index 0000000..1509008 --- /dev/null +++ b/tests/.crumb @@ -0,0 +1,30 @@ +{ + "schema_version": "1.0.0", + "name": "tests", + "layer": "tests", + "purpose": "Directory tests. Purpose not yet described by a human.", + "above": { + "name": "spark-rsi", + "path": ".." + }, + "extensions": { + "seed": { + "purpose_auto": "Directory tests. Purpose not yet described by a human.", + "files": [ + "integration_tests.rs", + "safety_envelope_tests.rs", + "test_adversarial_containment.rs", + "test_capability_graph_and_hypothesis.rs", + "test_cryptographic_improvement_ledger.rs", + "test_host_supervisor_ipc.rs", + "test_max_inference_and_diagnosis.rs", + "test_meta_improvement_governance.rs", + "test_no_synthetic_trust_inputs.rs", + "test_objective_evaluator.rs", + "test_ratifier_branch_only.rs", + "test_soak_run.rs" + ] + }, + "owner_lane": "" + } +} diff --git a/tools/.crumb b/tools/.crumb new file mode 100644 index 0000000..7c8ccda --- /dev/null +++ b/tools/.crumb @@ -0,0 +1,19 @@ +{ + "schema_version": "1.0.0", + "name": "tools", + "layer": "tools", + "purpose": "Directory tools. Purpose not yet described by a human.", + "above": { + "name": "spark-rsi", + "path": ".." + }, + "extensions": { + "seed": { + "purpose_auto": "Directory tools. Purpose not yet described by a human.", + "files": [ + "build_and_run_notebooks.py" + ] + }, + "owner_lane": "" + } +} From d22a8f2666ca587ca6c3f353fd26959b1d7a4817 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Thu, 1 Oct 2026 12:33:49 -0500 Subject: [PATCH 3/4] style: cargo fmt (formatting only, no logic change) rustfmt on the four PR files the earlier runner rewrote in place. Every rewritten file is part of this PR; nothing outside the PR was touched. Co-Authored-By: Claude Opus 5.5 --- src/daemon.rs | 9 +++++---- src/diff_gate.rs | 24 ++++++++++++++++++++---- src/isolation/root_of_trust.rs | 17 +++++++++++------ tests/test_ratifier_branch_only.rs | 18 +++++++++++++++--- 4 files changed, 51 insertions(+), 17 deletions(-) diff --git a/src/daemon.rs b/src/daemon.rs index 77e8726..a1651ac 100644 --- a/src/daemon.rs +++ b/src/daemon.rs @@ -176,9 +176,10 @@ impl RsiEngine { for mut candidate in candidates { // Declared-target gate before anything is staged: normalized path, // no `..`, inside the declared roots, not a root-of-trust file. - if let Err(e) = - crate::diff_gate::check_declared_target(&candidate.target_file, &config.ratify_roots) - { + if let Err(e) = crate::diff_gate::check_declared_target( + &candidate.target_file, + &config.ratify_roots, + ) { let _ = ledger.append_block( BlockType::Evaluation, format!("Declared target refused: {}", e), @@ -190,7 +191,7 @@ impl RsiEngine { // Tier Governance: Check candidate tier and boundaries let tier = crate::meta::TierGovernance::classify_proposal(&candidate); if tier == crate::meta::CandidateTier::Tier2Engine { - if config.operator_key_hex.is_none() { + if config.operator_key_hex.is_none() { // Engine changes need operator authorization; no key means no authorization. let _ = ledger.append_block( BlockType::Evaluation, diff --git a/src/diff_gate.rs b/src/diff_gate.rs index 7cd6404..75c0ee3 100644 --- a/src/diff_gate.rs +++ b/src/diff_gate.rs @@ -175,7 +175,14 @@ pub fn real_diff(repo: &Path, base: &str, head: &str) -> Result Result { let mut c = git(repo); - c.args(["diff", "--no-ext-diff", "--no-textconv", "--no-color", base, head]); + c.args([ + "diff", + "--no-ext-diff", + "--no-textconv", + "--no-color", + base, + head, + ]); run(c, "git diff") } @@ -221,7 +228,10 @@ pub fn check_real_diff( )); } if e.new_mode == "000000" || e.status == 'D' { - violations.push(format!("real diff deletes {:?}; deletions are refused", normalized)); + violations.push(format!( + "real diff deletes {:?}; deletions are refused", + normalized + )); } real_paths.push(normalized); } @@ -371,7 +381,12 @@ pub fn default_branch_names(repo: &Path) -> Vec { } } let mut c = git(repo); - c.args(["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"]); + c.args([ + "symbolic-ref", + "--quiet", + "--short", + "refs/remotes/origin/HEAD", + ]); if let Ok(h) = run(c, "origin default branch") { if let Some(b) = h.strip_prefix("origin/") { names.push(b.to_string()); @@ -471,7 +486,8 @@ mod tests { #[test] fn raw_diff_parser_reads_modes_and_paths() { - let raw = b":100644 120000 aaaa bbbb T\0docs/link\0:000000 100644 0000 cccc A\0docs/new.md\0"; + let raw = + b":100644 120000 aaaa bbbb T\0docs/link\0:000000 100644 0000 cccc A\0docs/new.md\0"; let e = parse_raw_diff(raw).unwrap(); assert_eq!(e.len(), 2); assert_eq!(e[0].new_mode, "120000"); diff --git a/src/isolation/root_of_trust.rs b/src/isolation/root_of_trust.rs index 095956b..5648a27 100644 --- a/src/isolation/root_of_trust.rs +++ b/src/isolation/root_of_trust.rs @@ -75,9 +75,8 @@ impl RootOfTrust { } pub fn assert_patch_permitted(target_file: &str, tier: u8) -> Result<(), String> { - let normalized = Self::normalize_strict(target_file).map_err(|e| { - format!("SECURITY VIOLATION: {}", e) - })?; + let normalized = Self::normalize_strict(target_file) + .map_err(|e| format!("SECURITY VIOLATION: {}", e))?; if Self::is_protected_path(&normalized) && tier < 2 { return Err(format!( "SECURITY VIOLATION: Target path '{}' is a protected root-of-trust file. Required tier: >= 2, candidate tier: {}", @@ -139,10 +138,16 @@ mod tests { fn test_dotdot_and_escape_forms_cannot_bypass_protection() { // Before the fix these normalized to themselves and were not protected. assert!(RootOfTrust::is_protected_path("src/../Cargo.toml")); - assert!(RootOfTrust::is_protected_path("docs/../.github/workflows/ci.yml")); - assert!(RootOfTrust::is_protected_path("src//isolation/container.rs")); + assert!(RootOfTrust::is_protected_path( + "docs/../.github/workflows/ci.yml" + )); + assert!(RootOfTrust::is_protected_path( + "src//isolation/container.rs" + )); assert!(RootOfTrust::is_protected_path("../outside.rs")); - assert!(RootOfTrust::is_protected_path("src\\isolation\\container.rs")); + assert!(RootOfTrust::is_protected_path( + "src\\isolation\\container.rs" + )); assert!(RootOfTrust::assert_patch_permitted("src/../Cargo.toml", 0).is_err()); // Climbing out of the repository is refused even at tier 2. assert!(RootOfTrust::assert_patch_permitted("../../etc/passwd", 2).is_err()); diff --git a/tests/test_ratifier_branch_only.rs b/tests/test_ratifier_branch_only.rs index 9a0ce52..fa48d58 100644 --- a/tests/test_ratifier_branch_only.rs +++ b/tests/test_ratifier_branch_only.rs @@ -185,7 +185,11 @@ async fn dotdot_target_cannot_reach_protected_file() { assert!(rec.branch.is_none()); } assert_untouched(repo, &before); - assert_eq!(before.branches, snapshot(repo).branches, "a branch was created"); + assert_eq!( + before.branches, + snapshot(repo).branches, + "a branch was created" + ); } #[tokio::test] @@ -215,7 +219,11 @@ async fn target_outside_declared_roots_refused() { let p = proposal("prop-out", target, "echo hi\n"); let rec = ratify(repo, patches.path(), &p, &default_ratify_roots()).await; assert_eq!(rec.status, "Rejected", "{}", target); - assert!(rec.message.contains("outside the declared roots"), "{}", rec.message); + assert!( + rec.message.contains("outside the declared roots"), + "{}", + rec.message + ); } assert_untouched(repo, &before); } @@ -255,7 +263,11 @@ async fn secret_in_real_diff_refused() { let patches = tempfile::tempdir().unwrap(); let before = snapshot(repo); let key = ["AKIA", "ABCDEFGHIJKLMNOP"].join(""); - let p = proposal("prop-secret", "docs/guide.md", &format!("guide\nkey={}\n", key)); + let p = proposal( + "prop-secret", + "docs/guide.md", + &format!("guide\nkey={}\n", key), + ); let rec = ratify(repo, patches.path(), &p, &default_ratify_roots()).await; assert_eq!(rec.status, "Rejected"); assert!(rec.message.contains("secret"), "{}", rec.message); From c97d2fced32a65537f7d9a7adae91da765a9a1e4 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Thu, 1 Oct 2026 12:34:24 -0500 Subject: [PATCH 4/4] test(diff_gate): prove the gate runs RootOfTrust itself, not only via SecurityLayer Inspector mutant S3 survived: removing the direct RootOfTrust::validate_declared_files call in check_real_diff failed no test, because SecurityLayer::evaluate_candidate also refuses protected files and the old test only looked for the word "protected". The new test uses a protected file inside a default root (src/isolation/container.rs) and requires both the gate's own unwrapped "SECURITY VIOLATION:" entry and the SecurityLayer's "Root-of-trust violation:" entry. With S3 applied the first is missing and the test fails. NOT_RUN: written, not compiled or run by the builder; the forge runs it. Co-Authored-By: Claude Opus 5.5 --- src/diff_gate.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/diff_gate.rs b/src/diff_gate.rs index 75c0ee3..3ce90e2 100644 --- a/src/diff_gate.rs +++ b/src/diff_gate.rs @@ -537,6 +537,40 @@ mod tests { assert!(v.iter().any(|m| m.contains("protected")), "{:?}", v); } + #[test] + fn real_diff_check_runs_root_of_trust_itself_not_only_via_security_layer() { + // A protected file inside a default root ("src"). Both the gate's own + // RootOfTrust call and the SecurityLayer must refuse it, independently. + // The SecurityLayer wraps its finding as "Root-of-trust violation: ..."; + // the gate's direct call reports "SECURITY VIOLATION: ..." unwrapped. + // Removing the direct RootOfTrust call in check_real_diff fails this test. + let path = "src/isolation/container.rs"; + assert!(within_roots(path, &roots())); + let e = vec![ChangedEntry { + old_mode: "100644".into(), + new_mode: "100644".into(), + status: 'M', + path: path.into(), + }]; + let v = check_real_diff(&e, "", path, &roots()); + let direct: Vec<&String> = v + .iter() + .filter(|m| m.starts_with("SECURITY VIOLATION:") && m.contains(path)) + .collect(); + assert_eq!( + direct.len(), + 1, + "gate's own root-of-trust refusal missing: {:?}", + v + ); + assert!( + v.iter() + .any(|m| m.starts_with("Root-of-trust violation:") && m.contains(path)), + "security layer refusal missing: {:?}", + v + ); + } + #[test] fn branch_names_are_sanitized() { assert_eq!(review_branch_name("prop-abc").unwrap(), "rsi/prop-abc");