AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
About Files History Releases Proposed changes Issues For developers
feat(aien-cli): approval floors, operator policy and agent-write rollback (#667)
merged 2bf4e18756793a4f #689 · opened 2026-10-19 22:35 UTC · closed 2026-10-20 06:35 UTC · merged 2026-10-20 06:35 UTC
Imported from GitHub aien-dev/aien-sovereign-core-mv#689, by drakestapleton
Labels: ready-to-merge
Base 0722802043c08c38ec6c21b0700bb30dff02114e · Head 2a2fb8ae03645dae61651d430e856c64ed01b140
Merged on GitHub as 16288198a67139c567e538d8c297c09bdb3fb97a ; reachable from main 007ac4ac5ee5edc6f79f411b1706752293604044 (observed 2026-11-18T16:35:46Z)
drakestapleton wrote on 2026-10-19 22:35 UTC
Implements #667 (parent aien-architecture#267).
aien-cli checks every tool request in one fixed order (crates/aien-cli/src/approval.rs):
Four floors that hold in every approval mode, including yolo and off: catastrophic commands (wiping a system root, raw disk writes or formats, a fork bomb, killing every process), deleting or rewriting the runtime's own files (binary, approval policy, checkpoint store, session journals), sudo fed a password on stdin, and the operator's own deny patterns.
The existing SafetyEngine denials.
The mode (AIEN_APPROVAL_MODE: manual (default), smart, yolo, off), the operator allowlist, whether a person is present (unattended runs deny anything that needs a decision), the danger patterns, then the decision: a guardian model in smart mode behind a breaker that opens after 3 failures, else the person.
Policy file ~/basecamp/approval-policy.json (mode, deny, allow regexes); a pattern that does not compile, or a file that does not parse, denies everything until fixed. /approval shows the active settings. The dispatcher asks once (the old second prompts in run_command and write_to_file are gone).
Agent-write ledger and rollback (crates/aien-cli/src/checkpoint.rs): one snapshot per turn in a content-addressed store (~/basecamp/checkpoints) and a hash-chained ledger of the agent's own writes. /rollback [turn] [session] restores only files the agent wrote, and only where they still hold what the agent left; files the operator changed are kept and listed. /checkpoints lists turns.
Tests: unit tests in approval.rs and checkpoint.rs plus two through the real dispatcher in tools.rs (operator_deny_pattern_blocks_a_real_command_in_every_mode with a no-pattern negative control, rollback_through_the_dispatcher_spares_operator_edits). Not yet run against a live model.
Mechanism after Hermes Agent (Nous Research, MIT licence, commit 5480918 ), re-implemented from reading; no code copied. Handoff: Spark ~/handoffs/2026-10-19-sc-667.md. Crumbs recompiled after rebasing on main.
github-advanced-security[bot] reviewed (COMMENTED) on 2026-10-19 22:45 UTC
github-advanced-security[bot] commented on crates/aien-cli/src/commands.rs line 67 on 2026-10-19 22:45 UTC
CodeQL / Cleartext logging of sensitive information
This operation writes active_session_id(...) to a log file.
Show more details
github-advanced-security[bot] commented on crates/aien-cli/src/commands.rs line 79 on 2026-10-19 22:45 UTC
CodeQL / Cleartext logging of sensitive information
This operation writes active_session_id(...) to a log file.
Show more details
github-advanced-security[bot] commented on crates/aien-cli/src/commands.rs line 84 on 2026-10-19 22:45 UTC
CodeQL / Cleartext logging of sensitive information
This operation writes active_session_id(...) to a log file.
Show more details
Apply it
git checkout -b patch-2bf4e18756793a4f 0722802043c08c38ec6c21b0700bb30dff02114e
curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/2bf4e18756793a4f .patch | git am
Raw patch (mbox) · Diff
Provenance
This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:
github-import 1
aien-dev/aien-sovereign-core-mv
689
2a2fb8ae03645dae61651d430e856c64ed01b140
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":689,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/689","export_sha256":"d815604dc795b494a931d4c9d256159461266bed51d6da460421ed1d94dab90f ","imported_utc":"2026-11-18T16:35:46Z"}
Changes
diff --git a/.crumb b/.crumb
index 83227efd ..947aa2ab 100644
--- a/.crumb
+++ b/.crumb
@@ -82,8 +82,8 @@
"purpose": "ALLEN persona profile v1: versioned, user-editable profile bound to the engaged ALLEN identity; "
},
{
- "digest": "900f4064ea9d0505cd3318c02ba6386aa3602d3a5bf1f2d22e2ff83356c87101 ",
- "last_commit": "6a487931 ",
+ "digest": "ba3a04bc2644d6fea87246faa8cd1cdfb8b02120463ebe04c31f4864b073b6e6 ",
+ "last_commit": "99d2a66e ",
"name": "crates/aien-cli",
"purpose": ""
},
@@ -118,15 +118,15 @@
"purpose": "Local CI sandbox exec contract (C8), aien-run user/caches install, Forgejo trigger hook, health "
}
],
- "children_root": "sha256:a4e72965d3cdeb51e334eb03fda7c5400691396c9f47ea52e37120418c63fcf7 ",
- "compiled_at": "2026-10-20T04:23:27Z",
+ "children_root": "sha256:491c7194c27af7c991c76d6afba8e7054c6a73aadc5972f2656bad9ed40808bd ",
+ "compiled_at": "2026-10-20T05:32:37Z",
"compiler": "crumb-compile/1",
- "digest": "sha256:68519231bf7d3f99f0ad49ede0d8994c50e573621e70504d845afd874eafa59d ",
+ "digest": "sha256:5ed9066fcef909fd146e555a8b3e4088faf82ecfc70d110fbb6c54533a3842b9 ",
"evidence_files": 1578,
"evidence_root": "sha256:135e27a1a0704c4a8371cd2c1eb555f2b5beec61c212949b029a5457418a7160 ",
- "files": 5892,
- "generated_at_commit": "6a48793134a1e1e892f14ad92bf1759edef3b3cc ",
- "source_tree": "sha256:1730c3dceb72b350e7ba37262648f564e5f57ceec0938513178bbab2191ab1fe "
+ "files": 5894,
+ "generated_at_commit": "b99a1a5e1e59b63f1d46d6bbbc0c2b4304df080b ",
+ "source_tree": "sha256:a006ae34ae8b2e52d855fb244497e868df1a6ce4d02935c3e86fd566039e07eb "
}
},
"history": [],
diff --git a/README.md b/README.md
index c592b572 ..a3a538a6 100644
--- a/README.md
+++ b/README.md
@@ -43,6 +43,14 @@ Installing a release (state on 2026-10-11, from `install.sh` and the dry-run art
- No public release exists. The public release key is not pinned yet (`AIEN_RELEASE_SIGNER` is empty until the key ceremony in [docs/release/KEY_CEREMONY.md](docs/release/KEY_CEREMONY.md)), so nothing can install as `release`. v0.1.0 and v0.1.1 are internal test releases. The release gate (`scripts/check-release-candidate.sh`) fails on current main (omega.lock differs from the CAND-4 manifest), see [#414](https://github.com/aien-spark/aien-sovereign-core/issues/414).
- After an install, follow [docs/FIRST_RUN.md](docs/FIRST_RUN.md): create the desk key (`aien compose desk-key --create 1`; `aien start` refuses without it), provision the model, start, record an objective. Objective records default to a durable per-user folder (`~/.local/state/aien-runtime/provenance`), not `/tmp`. The installer does not provision a model. `aien harness` is not shipped in this release and exits with a refusal.
+## Agent CLI: approval floors and rollback
+
+`aien-cli` checks every tool request in one fixed order (issue #667). Four floors come first and hold in every approval mode, including `yolo` and `off`: a list of catastrophic commands (wiping a system root, formatting or writing a raw disk, a fork bomb, killing every process), deleting or rewriting the runtime's own files (its binary, the approval policy, the checkpoint store, session journals), `sudo` fed a password on stdin, and the operator's own deny patterns. Only then come the existing policy denials, the mode (`AIEN_APPROVAL_MODE`: `manual`, `smart`, `yolo`, `off`), the operator's allowlist, whether a person is present (unattended runs deny anything that needs a decision), the dangerous-command patterns, and the decision itself (a guardian model in `smart` mode, behind a breaker that opens after 3 failures, else the person). Deny and allow patterns live in `~/basecamp/approval-policy.json` (`{"mode": "...", "deny": [regex...], "allow": [regex...]}`); a pattern that does not compile, or a file that does not parse, denies everything until fixed. `/approval` shows the active settings.
+
+Every file the agent writes in a chat session is recorded: one snapshot of the directory per turn in a shared content-addressed store (`~/basecamp/checkpoints`), plus a hash-chained ledger of the agent's own writes. `/rollback [turn] [session]` puts back only the files the agent wrote, and only where they still hold what the agent left; files the operator changed are kept and listed. `/checkpoints` lists the turns. Shown on the host by unit and dispatcher tests; not yet run against a live model.
+
+Mechanism after Hermes Agent (Nous Research, MIT licence, commit 5480918 ), re-implemented from reading; no code copied.
+
## Contributing
Read [CONSTITUTION.md](CONSTITUTION.md) and [AGENTS.md](AGENTS.md) before opening a pull request. Changes ship on a branch with verification proof: the commands you ran and their output. Prefer work that moves capability into the C repositories over new Rust here. Contact: aien@aienos.com.
diff --git a/crates/aien-cli/.crumb b/crates/aien-cli/.crumb
index 07d2e8f1 ..219f4e30 100644
--- a/crates/aien-cli/.crumb
+++ b/crates/aien-cli/.crumb
@@ -34,21 +34,21 @@
"generated": {
"children": [
{
- "digest": "aa8fc578887a4c0264210550eec423a365ed50be602b0d05de3e5e366bb247b1 ",
- "last_commit": "81fabb49 ",
+ "digest": "19e9fad9e283ee2e17c48f12c402e5cf83ca52dbd9bbb319485068f26d76800d ",
+ "last_commit": "68fd6c3f ",
"name": "src",
"purpose": ""
}
],
- "children_root": "sha256:d899a1cffc601e03179ff1691ca5edecffa47a6b576d76330fe3c4af62cfcfd0 ",
- "compiled_at": "2026-10-20T02:10:08Z",
+ "children_root": "sha256:399633e0ce9dc75d9d585caf138fd1efa2ce901c8c01032af9f571feb7e1d0d7 ",
+ "compiled_at": "2026-10-20T04:18:42Z",
"compiler": "crumb-compile/1",
- "digest": "sha256:900f4064ea9d0505cd3318c02ba6386aa3602d3a5bf1f2d22e2ff83356c87101 ",
+ "digest": "sha256:ba3a04bc2644d6fea87246faa8cd1cdfb8b02120463ebe04c31f4864b073b6e6 ",
"evidence_files": 0,
"evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ",
- "files": 41,
- "generated_at_commit": "81fabb49ac42c8ad8c1cdd9b646899c85a10a31b ",
- "source_tree": "sha256:8b445d6138c494d8bedf4d652c5fa40ee914ddea55fa526aefa68b5988e91e04 "
+ "files": 43,
+ "generated_at_commit": "68fd6c3fa879edd4bec0534502b3d56c750fc5dd ",
+ "source_tree": "sha256:d1f9b32da309414709532e7b7ac5f3f3f2ec7165c8ff446e6943002ae1c6d5bf "
}
},
"history": [
diff --git a/crates/aien-cli/src/.crumb b/crates/aien-cli/src/.crumb
index 53c96bf9 ..c49dd1e4 100644
--- a/crates/aien-cli/src/.crumb
+++ b/crates/aien-cli/src/.crumb
@@ -64,14 +64,14 @@
"generated": {
"children": [],
"children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ",
- "compiled_at": "2026-10-20T02:10:08Z",
+ "compiled_at": "2026-10-20T04:18:42Z",
"compiler": "crumb-compile/1",
- "digest": "sha256:aa8fc578887a4c0264210550eec423a365ed50be602b0d05de3e5e366bb247b1 ",
+ "digest": "sha256:19e9fad9e283ee2e17c48f12c402e5cf83ca52dbd9bbb319485068f26d76800d ",
"evidence_files": 0,
"evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 ",
- "files": 29,
- "generated_at_commit": "81fabb49ac42c8ad8c1cdd9b646899c85a10a31b ",
- "source_tree": "sha256:19469782a1ea0fb8579038fae15fc97fd3a7ca402de8c1123dd2264394d9aee1 "
+ "files": 31,
+ "generated_at_commit": "68fd6c3fa879edd4bec0534502b3d56c750fc5dd ",
+ "source_tree": "sha256:9b388e0335059ac0ca172452a5230df2fa55b4633a8b5717de545b26ad0f3647 "
}
},
"history": [
diff --git a/crates/aien-cli/src/approval.rs b/crates/aien-cli/src/approval.rs
new file mode 100644
index 00000000 ..8a5ed7b7
--- /dev/null
+++ b/crates/aien-cli/src/approval.rs
@@ -0,0 +1,1534 @@
+//! Approval floors ordered above every mode (sc#667).
+//!
+//! One ordering rule the chat loop cannot skip. For every tool request:
+//!
+//! 1. **Floors**, unconditional in every mode including `yolo` and `off`:
+//! a hardline command list, deletion or rewrite of the runtime's own files
+//! (binary, approval policy, checkpoint store, session journals), `sudo`
+//! fed a password through stdin, and the operator's own deny patterns.
+//! 2. **Policy deny** from the existing nine-tier `SafetyEngine` (confinement,
+//! vault rules). A mode loosens questions, never a denial.
+//! 3. **Mode**: `yolo` and `off` allow what is left.
+//! 4. **Permanent allowlist** from the operator's policy file.
+//! 5. **Presence**: with no person present, anything that still needs a
+//! decision is denied (unattended defaults to deny).
+//! 6. **Dangerous patterns** and the engine's own questions decide whether a
+//! decision is needed at all.
+//! 7. **Decision**: in `smart` mode a guardian model answers approve, deny or
+//! escalate behind a circuit breaker; otherwise, or on escalate, the person.
+//!
+//! The functions in the pure section take values and return values: no
+//! clock, disk, environment or terminal. The edges (policy file, presence,
+//! runtime paths, the prompt and the guardian model) sit at the bottom and in
+//! `tools.rs`, so the pure part can move to Omega as a semantic identity
+//! (ADR 0024).
+//!
+//! Prior art: Hermes Agent, Nous Research, MIT licence, commit 5480918
+//! (read 2026-10-18), `tools/approval_floors.py`, `tools/approval.py`,
+//! `tools/approval_smart.py`. Mechanism re-implemented from reading; no code
+//! copied.
+
+use regex::Regex;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use std::path::{Component, Path, PathBuf};
+
+use crate::safety::{is_high_risk_command, is_high_risk_path, SafetyDecision};
+
+// ---------------------------------------------------------------------------
+// Pure part
+// ---------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum ApprovalMode {
+ /// Ask the person whenever a decision is needed (the default).
+ Manual,
+ /// Ask the guardian model first; it may approve, deny or escalate.
+ Smart,
+ /// Approve everything the floors and the policy denials leave.
+ Yolo,
+ /// Approvals switched off; same effect as `Yolo`. Floors still hold.
+ Off,
+}
+
+#[cfg(test)]
+pub const ALL_MODES: [ApprovalMode; 4] = [
+ ApprovalMode::Manual,
+ ApprovalMode::Smart,
+ ApprovalMode::Yolo,
+ ApprovalMode::Off,
+];
+
+impl ApprovalMode {
+ pub fn parse(text: &str) -> Option<Self> {
+ match text.trim().to_ascii_lowercase().as_str() {
+ "manual" | "ask" => Some(Self::Manual),
+ "smart" | "guardian" => Some(Self::Smart),
+ "yolo" => Some(Self::Yolo),
+ "off" => Some(Self::Off),
+ _ => None,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Presence {
+ Person,
+ Unattended,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Floor {
+ Hardline,
+ RuntimeSelfDelete,
+ SudoPipedPassword,
+ OperatorDeny,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Stage {
+ Floor(Floor),
+ PolicyDeny,
+ Mode,
+ Allowlist,
+ Presence,
+ Clear,
+ Guardian,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub enum Verdict {
+ Allow {
+ by: Stage,
+ },
+ Deny {
+ by: Stage,
+ reason: String,
+ },
+ /// Smart mode with a closed breaker: the edge asks the guardian, then
+ /// calls [`after_guardian`].
+ AskGuardian {
+ reason: String,
+ },
+ AskPerson {
+ reason: String,
+ },
+}
+
+/// The operator's policy file as written on disk.
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
+pub struct OperatorPolicy {
+ #[serde(default)]
+ pub mode: Option<ApprovalMode>,
+ /// Regular expressions; a match on the request's subject denies it in
+ /// every mode.
+ #[serde(default)]
+ pub deny: Vec<String>,
+ /// Regular expressions; a match skips the question (never a floor).
+ #[serde(default)]
+ pub allow: Vec<String>,
+}
+
+/// Compiled policy. Fail closed: a deny pattern that does not compile, or a
+/// policy file that does not parse, denies every request with the reason.
+#[derive(Debug, Clone, Default)]
+pub struct CompiledPolicy {
+ pub mode: Option<ApprovalMode>,
+ deny: Vec<Regex>,
+ allow: Vec<Regex>,
+ broken: Option<String>,
+ pub warnings: Vec<String>,
+}
+
+impl CompiledPolicy {
+ pub fn compile(policy: &OperatorPolicy) -> Self {
+ let mut out = CompiledPolicy {
+ mode: policy.mode,
+ ..Default::default()
+ };
+ for (i, pattern) in policy.deny.iter().enumerate() {
+ match Regex::new(pattern) {
+ Ok(re) => out.deny.push(re),
+ Err(err) => {
+ out.broken = Some(format!(
+ "operator deny pattern {} ({:?}) does not compile: {}",
+ i + 1,
+ pattern,
+ err
+ ));
+ }
+ }
+ }
+ for (i, pattern) in policy.allow.iter().enumerate() {
+ match Regex::new(pattern) {
+ Ok(re) => out.allow.push(re),
+ // An allow pattern that does not compile grants nothing.
+ Err(err) => out.warnings.push(format!(
+ "operator allow pattern {} ({:?}) ignored: {}",
+ i + 1,
+ pattern,
+ err
+ )),
+ }
+ }
+ out
+ }
+
+ /// Why every request is being denied, when the policy is broken.
+ pub fn broken(&self) -> Option<&str> {
+ self.broken.as_deref()
+ }
+
+ /// The policy file exists but cannot be read or parsed.
+ pub fn unreadable(reason: String) -> Self {
+ CompiledPolicy {
+ broken: Some(format!("approval policy unreadable: {}", reason)),
+ ..Default::default()
+ }
+ }
+}
+
+/// Values the edge measures once per session.
+#[derive(Debug, Clone, Default)]
+pub struct RuntimeFacts {
+ /// Files and directories the agent must never delete or rewrite.
+ pub protected: Vec<PathBuf>,
+ /// Expansion for `~` and `$HOME` in commands.
+ pub home: PathBuf,
+ /// Base for relative paths when a request names no `cwd`.
+ pub cwd: PathBuf,
+}
+
+/// One tool request at the gate.
+pub struct Gate<'a> {
+ pub tool: &'a str,
+ pub args: &'a Value,
+ /// What the existing nine-tier `SafetyEngine` said.
+ pub base: &'a SafetyDecision,
+ pub mode: ApprovalMode,
+ pub presence: Presence,
+ pub policy: &'a CompiledPolicy,
+ pub facts: &'a RuntimeFacts,
+ /// A guardian is configured and its breaker is closed.
+ pub guardian_ready: bool,
+}
+
+/// The ordering rule. Floors first, every mode.
+pub fn decide(gate: &Gate) -> Verdict {
+ if let Some((floor, reason)) = check_floors(gate.tool, gate.args, gate.policy, gate.facts) {
+ return Verdict::Deny {
+ by: Stage::Floor(floor),
+ reason,
+ };
+ }
+ if let SafetyDecision::Deny(reason) = gate.base {
+ return Verdict::Deny {
+ by: Stage::PolicyDeny,
+ reason: reason.clone(),
+ };
+ }
+ if matches!(gate.mode, ApprovalMode::Yolo | ApprovalMode::Off) {
+ return Verdict::Allow { by: Stage::Mode };
+ }
+ let subject = subject(gate.tool, gate.args);
+ if gate
+ .policy
+ .allow
+ .iter()
+ .any(|re| matches_subject(re, &subject))
+ {
+ return Verdict::Allow {
+ by: Stage::Allowlist,
+ };
+ }
+ let reason = match needs_decision(gate.tool, gate.args, gate.base) {
+ None => return Verdict::Allow { by: Stage::Clear },
+ Some(reason) => reason,
+ };
+ if gate.presence == Presence::Unattended {
+ return Verdict::Deny {
+ by: Stage::Presence,
+ reason: format!("no person present to approve, unattended default is deny: {reason}"),
+ };
+ }
+ if gate.mode == ApprovalMode::Smart && gate.guardian_ready {
+ return Verdict::AskGuardian { reason };
+ }
+ Verdict::AskPerson { reason }
+}
+
+/// What the guardian model answered.
+#[derive(Debug, Clone, PartialEq)]
+pub enum GuardianAnswer {
+ Approve,
+ Deny(String),
+ Escalate,
+ /// Timeout, transport error or an answer that did not parse.
+ Failed(String),
+}
+
+/// Second half of [`decide`] after an `AskGuardian` verdict.
+pub fn after_guardian(answer: &GuardianAnswer, reason: String) -> Verdict {
+ match answer {
+ GuardianAnswer::Approve => Verdict::Allow {
+ by: Stage::Guardian,
+ },
+ GuardianAnswer::Deny(why) => Verdict::Deny {
+ by: Stage::Guardian,
+ reason: format!("guardian denied: {why}"),
+ },
+ GuardianAnswer::Escalate | GuardianAnswer::Failed(_) => Verdict::AskPerson { reason },
+ }
+}
+
+/// Read the guardian's reply. Only the first word counts; anything else is a
+/// failure, which escalates to the person and counts against the breaker.
+pub fn parse_guardian_reply(text: &str) -> GuardianAnswer {
+ let trimmed = text.trim();
+ let first = trimmed
+ .split_whitespace()
+ .next()
+ .unwrap_or("")
+ .trim_matches(|c: char| !c.is_ascii_alphabetic())
+ .to_ascii_uppercase();
+ match first.as_str() {
+ "APPROVE" => GuardianAnswer::Approve,
+ "DENY" => GuardianAnswer::Deny(trimmed.chars().take(200).collect()),
+ "ESCALATE" => GuardianAnswer::Escalate,
+ _ => GuardianAnswer::Failed(format!(
+ "unparseable guardian reply: {:?}",
+ trimmed.chars().take(80).collect::<String>()
+ )),
+ }
+}
+
+/// Circuit breaker in front of the guardian model. After `threshold`
+/// consecutive failures it opens and stays open for the session, so a broken
+/// or slow guardian costs at most `threshold` calls; every request then goes
+/// to the person.
+#[derive(Debug, Clone, PartialEq)]
+pub struct GuardianBreaker {
+ threshold: u32,
+ consecutive_failures: u32,
+ open: bool,
+}
+
+impl GuardianBreaker {
+ pub fn new(threshold: u32) -> Self {
+ Self {
+ threshold: threshold.max(1),
+ consecutive_failures: 0,
+ open: false,
+ }
+ }
+
+ pub fn is_closed(&self) -> bool {
+ !self.open
+ }
+
+ pub fn record(&mut self, answer: &GuardianAnswer) {
+ if matches!(answer, GuardianAnswer::Failed(_)) {
+ self.consecutive_failures += 1;
+ if self.consecutive_failures >= self.threshold {
+ self.open = true;
+ }
+ } else {
+ self.consecutive_failures = 0;
+ }
+ }
+}
+
+impl Default for GuardianBreaker {
+ fn default() -> Self {
+ Self::new(3)
+ }
+}
+
+/// The text a request is matched against: the command for `run_command`,
+/// the path for file tools, otherwise the tool name and its arguments.
+pub fn subject(tool: &str, args: &Value) -> String {
+ match tool {
+ "run_command" => command_of(args).to_string(),
+ "view_file"
+ | "write_to_file"
+ | "create_file"
+ | "replace_file_content"
+ | "edit_file"
+ | "list_dir"
+ | "list_directory"
+ | "create_dir" => path_of(args).to_string(),
+ _ => format!("{} {}", tool, args),
+ }
+}
+
+fn command_of(args: &Value) -> &str {
+ args.get("command")
+ .or_else(|| args.get("CommandLine"))
+ .and_then(Value::as_str)
+ .unwrap_or("")
+}
+
+fn path_of(args: &Value) -> &str {
+ args.get("path")
+ .or_else(|| args.get("target_file"))
+ .or_else(|| args.get("TargetFile"))
+ .or_else(|| args.get("AbsolutePath"))
+ .or_else(|| args.get("directory_path"))
+ .or_else(|| args.get("DirectoryPath"))
+ .and_then(Value::as_str)
+ .unwrap_or("")
+}
+
+fn cwd_of<'a>(args: &'a Value, facts: &'a RuntimeFacts) -> PathBuf {
+ match args
+ .get("cwd")
+ .or_else(|| args.get("Cwd"))
+ .and_then(Value::as_str)
+ {
+ Some(c) if !c.is_empty() => lexical_abs(c, &facts.home, &facts.cwd),
+ _ => facts.cwd.clone(),
+ }
+}
+
+fn matches_subject(re: &Regex, subject: &str) -> bool {
+ re.is_match(subject) || re.is_match(&normalize_command(subject))
+}
+
+/// Quotes and backslashes removed, whitespace collapsed, lower case.
+/// Closes the cheap spellings that slip past a plain substring match
+/// (`r''m -rf /`, `rm -rf /`, `RM -RF /`).
+pub fn normalize_command(cmd: &str) -> String {
+ strip_quotes(cmd).to_lowercase()
+}
+
+/// Split a shell line into simple commands on `;`, `&&`, `||`, `|`, `&`,
+/// newlines, `$(`, `(`, `)` and backticks. Returns each segment and whether
+/// it receives a pipe from the previous one.
+fn segments(normalized: &str) -> Vec<(String, bool)> {
+ let mut out = Vec::new();
+ let mut current = String::new();
+ let mut piped_next = false;
+ let mut piped_current = false;
+ let chars: Vec<char> = normalized.chars().collect();
+ let mut i = 0;
+ while i < chars.len() {
+ let c = chars[i];
+ let next = chars.get(i + 1).copied();
+ let boundary = match (c, next) {
+ ('&', Some('&')) | ('|', Some('|')) => {
+ i += 1;
+ true
+ }
+ ('|', _) => {
+ piped_next = true;
+ true
+ }
+ ('$', Some('(')) => {
+ i += 1;
+ true
+ }
+ (';' | '&' | '\n' | '`' | '(' | ')' | '{' | '}', _) => true,
+ _ => false,
+ };
+ if boundary {
+ if !current.trim().is_empty() {
+ out.push((current.trim().to_string(), piped_current));
+ }
+ current.clear();
+ piped_current = piped_next;
+ piped_next = false;
+ } else {
+ current.push(c);
+ }
+ i += 1;
+ }
+ if !current.trim().is_empty() {
+ out.push((current.trim().to_string(), piped_current));
+ }
+ out
+}
+
+/// Wrappers that run the next word as the real command.
+const WRAPPERS: [&str; 9] = [
+ "sudo", "env", "nice", "nohup", "time", "command", "exec", "busybox", "doas",
+];
+
+/// Strip wrappers and `NAME=value` assignments; return the real command's
+/// base name and its arguments.
+fn real_command(tokens: &[&str]) -> Option<(String, Vec<String>)> {
+ let mut i = 0;
+ while i < tokens.len() {
+ let t = tokens[i];
+ let base = t.rsplit('/').next().unwrap_or(t);
+ if WRAPPERS.contains(&base) {
+ i += 1;
+ // Skip the wrapper's own flags (and a numeric niceness).
+ while i < tokens.len()
+ && (tokens[i].starts_with('-') || tokens[i].parse::<i64>().is_ok())
+ {
+ i += 1;
+ }
+ continue;
+ }
+ if t.contains('=') && !t.starts_with('-') && !t.starts_with('/') {
+ i += 1;
+ continue;
+ }
+ let args = tokens[i + 1..].iter().map(|s| s.to_string()).collect();
+ return Some((base.to_string(), args));
+ }
+ None
+}
+
+const CRITICAL_ROOTS: [&str; 16] = [
+ "/", "/*", "~", "~/", "~/*", "$home", "${home}", "/home", "/root", "/etc", "/usr", "/boot",
+ "/var", "/bin", "/lib", "/sbin",
+];
+
+fn is_critical_target(arg: &str) -> bool {
+ let trimmed = if arg.len() > 1 {
+ arg.trim_end_matches('/')
+ } else {
+ arg
+ };
+ let trimmed = if trimmed.is_empty() { "/" } else { trimmed };
+ CRITICAL_ROOTS.contains(&trimmed)
+ || CRITICAL_ROOTS.contains(&arg)
+ || matches!(trimmed, "/home/*" | "/root/*" | "$home/*" | "${home}/*")
+}
+
+fn has_short_flag(args: &[String], flag: char) -> bool {
+ args.iter()
+ .any(|a| a.starts_with('-') && !a.starts_with("--") && a[1..].contains(flag))
+}
+
+const RAW_DISKS: [&str; 8] = [
+ "/dev/sd",
+ "/dev/nvme",
+ "/dev/mmcblk",
+ "/dev/vd",
+ "/dev/hd",
+ "/dev/xvd",
+ "/dev/disk",
+ "/dev/mapper/",
+];
+
+fn names_raw_disk(arg: &str) -> bool {
+ RAW_DISKS.iter().any(|d| arg.starts_with(d))
+}
+
+/// Floor 1: commands nothing may approve.
+pub fn hardline(cmd: &str) -> Option<String> {
+ let norm = normalize_command(cmd);
+ let squeezed: String = norm.chars().filter(|c| !c.is_whitespace()).collect();
+ if squeezed.contains(":(){:|:&};:") {
+ return Some("fork bomb".into());
+ }
+ if norm.contains("--no-preserve-root") {
+ return Some("rm --no-preserve-root".into());
+ }
+ for disk in RAW_DISKS {
+ if squeezed.contains(&format!(">{disk}")) {
+ return Some(format!("redirect onto raw disk {disk}*"));
+ }
+ }
+ for (segment, _) in segments(&norm) {
+ let tokens: Vec<&str> = segment.split_whitespace().collect();
+ let Some((name, args)) = real_command(&tokens) else {
+ continue;
+ };
+ let targets: Vec<&String> = args.iter().filter(|a| !a.starts_with('-')).collect();
+ match name.as_str() {
+ "rm" => {
+ let recursive =
+ has_short_flag(&args, 'r') || args.iter().any(|a| a == "--recursive");
+ if recursive {
+ if let Some(t) = targets.iter().find(|t| is_critical_target(t)) {
+ return Some(format!("recursive delete of {t}"));
+ }
+ }
+ }
+ "chmod" | "chown" | "chgrp" => {
+ // Arguments are lower case here, so `-R` reads as `-r`.
+ let recursive =
+ has_short_flag(&args, 'r') || args.iter().any(|a| a == "--recursive");
+ if recursive && targets.iter().any(|t| is_critical_target(t)) {
+ return Some(format!("recursive {name} of a system root"));
+ }
+ }
+ n if n.starts_with("mkfs") || n == "wipefs" || n == "mkswap" => {
+ if args.iter().any(|a| names_raw_disk(a)) {
+ return Some(format!("{n} on a raw disk"));
+ }
+ }
+ "dd" => {
+ if args
+ .iter()
+ .any(|a| a.strip_prefix("of=").is_some_and(names_raw_disk))
+ {
+ return Some("dd onto a raw disk".into());
+ }
+ }
+ "shred" => {
+ if args.iter().any(|a| names_raw_disk(a)) {
+ return Some("shred of a raw disk".into());
+ }
+ }
+ "kill" if args.iter().any(|a| a == "1" || a == "-1") => {
+ return Some("kill of init or of every process".into());
+ }
+ _ => {}
+ }
+ }
+ None
+}
+
+/// Floor 3: `sudo` reading a password from stdin (`-S`, `--stdin`, or a pipe
+/// into sudo). A password in a command line ends up in history and logs.
+pub fn sudo_piped_password(cmd: &str) -> Option<String> {
+ // Case matters here: `sudo -S` reads stdin, `sudo -s` opens a shell.
+ let stripped = strip_quotes(cmd);
+ for (segment, piped_in) in segments(&stripped) {
+ let tokens: Vec<&str> = segment.split_whitespace().collect();
+ let Some(pos) = tokens
+ .iter()
+ .position(|t| t.rsplit('/').next().map(str::to_lowercase).as_deref() == Some("sudo"))
+ else {
+ continue;
+ };
+ let flags: Vec<&str> = tokens[pos + 1..]
+ .iter()
+ .take_while(|t| t.starts_with('-'))
+ .copied()
+ .collect();
+ if flags.contains(&"--stdin")
+ || flags
+ .iter()
+ .any(|f| !f.starts_with("--") && f[1..].contains('S'))
+ {
+ return Some("sudo -S reads a password from stdin".into());
+ }
+ if segment.contains("<<") {
+ return Some("sudo fed through a here-document or here-string".into());
+ }
+ if piped_in && pos == 0 {
+ return Some("password piped into sudo".into());
+ }
+ }
+ None
+}
+
+/// Quotes and backslashes removed, whitespace collapsed, case kept.
+fn strip_quotes(cmd: &str) -> String {
+ let stripped: String = cmd
+ .replace("\\\n", " ")
+ .chars()
+ .filter(|c| !matches!(c, '\'' | '"' | '\\'))
+ .collect();
+ stripped.split_whitespace().collect::<Vec<_>>().join(" ")
+}
+
+/// Lexical absolute path: `~` and `$HOME` expanded, relative joined to
+/// `base`, `.` and `..` folded. No disk access.
+pub fn lexical_abs(path: &str, home: &Path, base: &Path) -> PathBuf {
+ let expanded = if path == "~" || path == "$home" || path == "$HOME" {
+ home.to_path_buf()
+ } else if let Some(rest) = path
+ .strip_prefix("~/")
+ .or_else(|| path.strip_prefix("$HOME/"))
+ .or_else(|| path.strip_prefix("$home/"))
+ .or_else(|| path.strip_prefix("${HOME}/"))
+ {
+ home.join(rest)
+ } else {
+ PathBuf::from(path)
+ };
+ let joined = if expanded.is_relative() {
+ base.join(expanded)
+ } else {
+ expanded
+ };
+ let mut out = PathBuf::new();
+ for comp in joined.components() {
+ match comp {
+ Component::ParentDir => {
+ out.pop();
+ }
+ Component::CurDir => {}
+ other => out.push(other.as_os_str()),
+ }
+ }
+ out
+}
+
+fn is_protected(path: &Path, facts: &RuntimeFacts) -> Option<PathBuf> {
+ facts
+ .protected
+ .iter()
+ // The path is inside a protected entry, or a protected entry is
+ // inside the path (deleting a parent deletes the runtime too).
+ .find(|p| path.starts_with(p) || (p.starts_with(path) && path != Path::new("")))
+ .cloned()
+}
+
+const MUTATING: [&str; 16] = [
+ "rm", "rmdir", "mv", "shred", "truncate", "unlink", "cp", "ln", "chmod", "chown", "tee", "dd",
+ "install", "rsync", "find", "sed",
+];
+
+/// Floor 2: the agent deleting or rewriting the runtime itself.
+pub fn runtime_self_delete(tool: &str, args: &Value, facts: &RuntimeFacts) -> Option<String> {
+ if facts.protected.is_empty() {
+ return None;
+ }
+ match tool {
+ "write_to_file" | "create_file" | "replace_file_content" | "edit_file" | "create_dir" => {
+ let raw = path_of(args);
+ if raw.is_empty() {
+ return None;
+ }
+ let p = lexical_abs(raw, &facts.home, &facts.cwd);
+ // Creating something *above* a protected path is harmless for a
+ // file write; only writes inside a protected entry count here.
+ let hit = facts.protected.iter().find(|r| p.starts_with(r))?;
+ Some(format!(
+ "{} would rewrite the runtime's own file {}",
+ tool,
+ hit.display()
+ ))
+ }
+ "run_command" => {
+ let cwd = cwd_of(args, facts);
+ let original = command_of(args);
+ // Paths are case-sensitive: segment the quote-stripped original,
+ // compare verbs in lower case.
+ let stripped: String = original
+ .chars()
+ .filter(|c| !matches!(c, '\'' | '"' | '\\'))
+ .collect();
+ for (segment, _) in segments(&stripped) {
+ let tokens: Vec<&str> = segment.split_whitespace().collect();
+ let redirect_targets: Vec<&str> = tokens
+ .iter()
+ .enumerate()
+ .filter_map(|(i, t)| {
+ if let Some(rest) = t.find('>').map(|i| t[i..].trim_start_matches('>')) {
+ if rest.is_empty() {
+ tokens.get(i + 1).copied()
+ } else {
+ Some(rest)
+ }
+ } else {
+ None
+ }
+ })
+ .collect();
+ for t in &redirect_targets {
+ let p = lexical_abs(t, &facts.home, &cwd);
+ if let Some(hit) = facts.protected.iter().find(|r| p.starts_with(r)) {
+ return Some(format!(
+ "shell redirect would overwrite the runtime's own file {}",
+ hit.display()
+ ));
+ }
+ }
+ let lowered: Vec<String> = tokens.iter().map(|t| t.to_lowercase()).collect();
+ let lowered_refs: Vec<&str> = lowered.iter().map(String::as_str).collect();
+ let Some((name, _)) = real_command(&lowered_refs) else {
+ continue;
+ };
+ if !MUTATING.contains(&name.as_str()) {
+ continue;
+ }
+ // `sed` only mutates with -i; `find` only with -delete/-exec.
+ if name == "sed" && !lowered.iter().any(|t| t.starts_with("-i")) {
+ continue;
+ }
+ if name == "find" && !lowered.iter().any(|t| t == "-delete" || t == "-exec") {
+ continue;
+ }
+ // Deleting a parent deletes the runtime too, so deleting
+ // verbs (and the source side of `mv`) also match a parent of
+ // a protected entry. Other verbs must point inside one.
+ let operands: Vec<&str> = tokens
+ .iter()
+ .skip_while(|t| t.to_lowercase().rsplit('/').next() != Some(name.as_str()))
+ .skip(1)
+ .filter(|t| !t.starts_with('-'))
+ .copied()
+ .collect();
+ for (i, t) in operands.iter().enumerate() {
+ let deleting =
+ matches!(name.as_str(), "rm" | "rmdir" | "shred" | "unlink" | "find")
+ || (name == "mv" && i + 1 < operands.len());
+ let p = lexical_abs(t, &facts.home, &cwd);
+ let hit = if deleting {
+ is_protected(&p, facts)
+ } else {
+ facts.protected.iter().find(|r| p.starts_with(r)).cloned()
+ };
+ if let Some(hit) = hit {
+ return Some(format!(
+ "{} would delete or rewrite the runtime's own file {}",
+ name,
+ hit.display()
+ ));
+ }
+ }
+ }
+ None
+ }
+ _ => None,
+ }
+}
+
+/// All four floors. Order only changes the reason given; every floor denies.
+pub fn check_floors(
+ tool: &str,
+ args: &Value,
+ policy: &CompiledPolicy,
+ facts: &RuntimeFacts,
+) -> Option<(Floor, String)> {
+ if let Some(broken) = &policy.broken {
+ return Some((Floor::OperatorDeny, broken.clone()));
+ }
+ if tool == "run_command" {
+ let cmd = command_of(args);
+ if let Some(why) = hardline(cmd) {
+ return Some((Floor::Hardline, format!("hardline floor: {why}")));
+ }
+ if let Some(why) = sudo_piped_password(cmd) {
+ return Some((Floor::SudoPipedPassword, format!("sudo floor: {why}")));
+ }
+ }
+ if let Some(why) = runtime_self_delete(tool, args, facts) {
+ return Some((Floor::RuntimeSelfDelete, format!("runtime floor: {why}")));
+ }
+ let subject = subject(tool, args);
+ if let Some(re) = policy.deny.iter().find(|re| matches_subject(re, &subject)) {
+ return Some((
+ Floor::OperatorDeny,
+ format!("operator deny pattern {:?} matched", re.as_str()),
+ ));
+ }
+ None
+}
+
+/// Does this request need a decision (person or guardian)? `None` = clear.
+fn needs_decision(tool: &str, args: &Value, base: &SafetyDecision) -> Option<String> {
+ if let SafetyDecision::AskUser(reason) = base {
+ return Some(reason.clone());
+ }
+ match tool {
+ "run_command" if is_high_risk_command(command_of(args)) => {
+ Some("dangerous command pattern".into())
+ }
+ "write_to_file" | "create_file" | "replace_file_content" | "edit_file"
+ if is_high_risk_path(path_of(args)) =>
+ {
+ Some("write to an operating system path".into())
+ }
+ _ => None,
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Edges: policy file, presence, mode, runtime facts
+// ---------------------------------------------------------------------------
+
+/// `$AIEN_APPROVAL_POLICY`, else `~/basecamp/approval-policy.json`.
+pub fn policy_path(home: &Path) -> PathBuf {
+ std::env::var_os("AIEN_APPROVAL_POLICY")
+ .map(PathBuf::from)
+ .unwrap_or_else(|| home.join("basecamp/approval-policy.json"))
+}
+
+/// Missing file = empty policy. Unreadable or unparseable = deny everything.
+pub fn load_policy(path: &Path) -> CompiledPolicy {
+ match std::fs::read_to_string(path) {
+ Ok(text) => match serde_json::from_str::<OperatorPolicy>(&text) {
+ Ok(policy) => CompiledPolicy::compile(&policy),
+ Err(err) => CompiledPolicy::unreadable(format!("{}: {}", path.display(), err)),
+ },
+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => CompiledPolicy::default(),
+ Err(err) => CompiledPolicy::unreadable(format!("{}: {}", path.display(), err)),
+ }
+}
+
+/// `$AIEN_APPROVAL_MODE`, else the policy file's mode, else manual. An
+/// unknown word in the variable falls back to manual (the strictest).
+pub fn resolve_mode(policy: &CompiledPolicy) -> ApprovalMode {
+ match std::env::var("AIEN_APPROVAL_MODE") {
+ Ok(v) => ApprovalMode::parse(&v).unwrap_or(ApprovalMode::Manual),
+ Err(_) => policy.mode.unwrap_or(ApprovalMode::Manual),
+ }
+}
+
+/// A person is present when stdin is a terminal and `AIEN_UNATTENDED` is not
+/// set to a true value.
+pub fn resolve_presence() -> Presence {
+ use std::io::IsTerminal;
+ let flagged = std::env::var("AIEN_UNATTENDED")
+ .map(|v| matches!(v.trim(), "1" | "true" | "yes"))
+ .unwrap_or(false);
+ if !flagged && std::io::stdin().is_terminal() {
+ Presence::Person
+ } else {
+ Presence::Unattended
+ }
+}
+
+/// The runtime's own files: this binary, the policy file, the checkpoint
+/// store and the session journals.
+pub fn runtime_facts(home: &Path, policy_file: &Path) -> RuntimeFacts {
+ let cwd = std::env::current_dir().unwrap_or_else(|_| home.to_path_buf());
+ let mut protected = vec![
+ lexical_abs(&policy_file.to_string_lossy(), home, &cwd),
+ crate::checkpoint::store_root(home),
+ home.join("basecamp/sessions"),
+ ];
+ if let Ok(exe) = std::env::current_exe() {
+ protected.push(exe);
+ }
+ RuntimeFacts {
+ protected,
+ home: home.to_path_buf(),
+ cwd,
+ }
+}
+
+/// Everything the gate needs from the environment, read once per request so
+/// an operator's edit to the policy file applies at once.
+#[derive(Debug, Clone)]
+pub struct GateContext {
+ pub mode: ApprovalMode,
+ pub presence: Presence,
+ pub policy: CompiledPolicy,
+ pub facts: RuntimeFacts,
+}
+
+impl GateContext {
+ pub fn from_env() -> Self {
+ let home = crate::platform::PlatformContext::detect().home_dir;
+ let path = policy_path(&home);
+ let policy = load_policy(&path);
+ Self {
+ mode: resolve_mode(&policy),
+ presence: resolve_presence(),
+ facts: runtime_facts(&home, &path),
+ policy,
+ }
+ }
+}
+
+fn breaker() -> &'static std::sync::Mutex<GuardianBreaker> {
+ static BREAKER: std::sync::OnceLock<std::sync::Mutex<GuardianBreaker>> =
+ std::sync::OnceLock::new();
+ BREAKER.get_or_init(|| std::sync::Mutex::new(GuardianBreaker::default()))
+}
+
+pub fn guardian_ready() -> bool {
+ breaker().lock().map(|b| b.is_closed()).unwrap_or(false)
+}
+
+pub fn record_guardian(answer: &GuardianAnswer) {
+ if let Ok(mut b) = breaker().lock() {
+ b.record(answer);
+ }
+}
+
+pub const GUARDIAN_PROMPT: &str = "You are the approval guardian for an agent's tool request on the operator's machine. \
+Answer with exactly one word first: APPROVE if the request is routine and reversible, DENY if it would destroy data, \
+leak secrets or harm the machine, ESCALATE if a person should decide. After the word you may give one short reason.";
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn facts() -> RuntimeFacts {
+ RuntimeFacts {
+ protected: vec![
+ PathBuf::from("/home/op/basecamp/approval-policy.json"),
+ PathBuf::from("/home/op/basecamp/checkpoints"),
+ PathBuf::from("/home/op/basecamp/sessions"),
+ PathBuf::from("/opt/aien/bin/aien-cli"),
+ ],
+ home: PathBuf::from("/home/op"),
+ cwd: PathBuf::from("/home/op/work"),
+ }
+ }
+
+ fn policy(deny: &[&str], allow: &[&str]) -> CompiledPolicy {
+ CompiledPolicy::compile(&OperatorPolicy {
+ mode: None,
+ deny: deny.iter().map(|s| s.to_string()).collect(),
+ allow: allow.iter().map(|s| s.to_string()).collect(),
+ })
+ }
+
+ fn run(
+ tool: &str,
+ args: &Value,
+ base: &SafetyDecision,
+ mode: ApprovalMode,
+ presence: Presence,
+ policy: &CompiledPolicy,
+ ) -> Verdict {
+ decide(&Gate {
+ tool,
+ args,
+ base,
+ mode,
+ presence,
+ policy,
+ facts: &facts(),
+ guardian_ready: true,
+ })
+ }
+
+ fn cmd(c: &str) -> Value {
+ json!({"command": c, "cwd": "/home/op/work"})
+ }
+
+ // Acceptance: an operator deny pattern blocks a command in every mode,
+ // one test per mode, with a person present and unattended.
+ fn operator_deny_blocks(mode: ApprovalMode) {
+ let pol = policy(&[r"git\s+push"], &[r".*"]);
+ for presence in [Presence::Person, Presence::Unattended] {
+ let v = run(
+ "run_command",
+ &cmd("git push origin main"),
+ &SafetyDecision::Allow,
+ mode,
+ presence,
+ &pol,
+ );
+ assert!(
+ matches!(
+ v,
+ Verdict::Deny {
+ by: Stage::Floor(Floor::OperatorDeny),
+ ..
+ }
+ ),
+ "mode {mode:?} presence {presence:?}: {v:?}"
+ );
+ }
+ // Negative control: the same mode and policy let an unmatched command through.
+ let v = run(
+ "run_command",
+ &cmd("git status"),
+ &SafetyDecision::Allow,
+ mode,
+ Presence::Person,
+ &pol,
+ );
+ assert!(matches!(v, Verdict::Allow { .. }), "mode {mode:?}: {v:?}");
+ }
+
+ #[test]
+ fn operator_deny_blocks_in_manual_mode() {
+ operator_deny_blocks(ApprovalMode::Manual);
+ }
+
+ #[test]
+ fn operator_deny_blocks_in_smart_mode() {
+ operator_deny_blocks(ApprovalMode::Smart);
+ }
+
+ #[test]
+ fn operator_deny_blocks_in_yolo_mode() {
+ operator_deny_blocks(ApprovalMode::Yolo);
+ }
+
+ #[test]
+ fn operator_deny_blocks_in_off_mode() {
+ operator_deny_blocks(ApprovalMode::Off);
+ }
+
+ #[test]
+ fn operator_deny_outranks_the_allowlist_and_spelling_tricks() {
+ let pol = policy(&[r"git push"], &[r"^git push"]);
+ for spelling in ["git push", "git push", "g''it push", "GIT PUSH --force"] {
+ let v = run(
+ "run_command",
+ &cmd(spelling),
+ &SafetyDecision::Allow,
+ ApprovalMode::Yolo,
+ Presence::Person,
+ &pol,
+ );
+ assert!(
+ matches!(
+ v,
+ Verdict::Deny {
+ by: Stage::Floor(Floor::OperatorDeny),
+ ..
+ }
+ ),
+ "{spelling}: {v:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn operator_deny_covers_file_tools_by_path() {
+ let pol = policy(&[r"/secrets/"], &[]);
+ let v = run(
+ "write_to_file",
+ &json!({"path": "/home/op/work/secrets/a.txt", "content": "x"}),
+ &SafetyDecision::Allow,
+ ApprovalMode::Off,
+ Presence::Person,
+ &pol,
+ );
+ assert!(
+ matches!(
+ v,
+ Verdict::Deny {
+ by: Stage::Floor(Floor::OperatorDeny),
+ ..
+ }
+ ),
+ "{v:?}"
+ );
+ }
+
+ #[test]
+ fn broken_policy_fails_closed_in_every_mode() {
+ let pol = policy(&["(unclosed"], &[]);
+ let unreadable = CompiledPolicy::unreadable("bad json".into());
+ for mode in ALL_MODES {
+ for p in [&pol, &unreadable] {
+ let v = run(
+ "view_file",
+ &json!({"path": "/home/op/work/a"}),
+ &SafetyDecision::Allow,
+ mode,
+ Presence::Person,
+ p,
+ );
+ assert!(
+ matches!(
+ v,
+ Verdict::Deny {
+ by: Stage::Floor(Floor::OperatorDeny),
+ ..
+ }
+ ),
+ "{v:?}"
+ );
+ }
+ }
+ // A broken allow pattern grants nothing and is reported.
+ let pol = policy(&[], &["(unclosed"]);
+ assert_eq!(pol.warnings.len(), 1);
+ }
+
+ #[test]
+ fn hardline_floor_holds_in_every_mode() {
+ let pol = policy(&[], &[r".*"]);
+ let bad = [
+ "rm -rf /",
+ "rm -rf /*",
+ "sudo rm -fr ~",
+ "rm -r -f $HOME",
+ "cd /tmp && rm -Rf /home/",
+ "r''m -rf /",
+ "rm --recursive --force /etc",
+ "rm -rf --no-preserve-root /x",
+ "mkfs.ext4 /dev/nvme0n1p2",
+ "dd if=/dev/zero of=/dev/sda bs=1M",
+ "echo x > /dev/sda",
+ ":(){ :|:& };:",
+ "kill -9 -1",
+ "chmod -R 777 /",
+ "nice -n 10 rm -rf /usr",
+ "X=1 rm -rf /boot",
+ ];
+ for mode in ALL_MODES {
+ for c in bad {
+ let v = run(
+ "run_command",
+ &cmd(c),
+ &SafetyDecision::Allow,
+ mode,
+ Presence::Person,
+ &pol,
+ );
+ assert!(
+ matches!(
+ v,
+ Verdict::Deny {
+ by: Stage::Floor(Floor::Hardline),
+ ..
+ }
+ ),
+ "{mode:?} {c}: {v:?}"
+ );
+ }
+ }
+ }
+
+ #[test]
+ fn hardline_negative_controls_pass() {
+ for c in [
+ "rm -rf /tmp/build",
+ "rm -rf ./target",
+ "rm -rf ~/work/old",
+ "rm /home/op/a.txt",
+ "dd if=/dev/zero of=/tmp/disk.img bs=1M count=10",
+ "mkfs.ext4 /tmp/disk.img",
+ "kill -9 4242",
+ "chmod -R 755 ./bin",
+ "echo hi > /dev/null",
+ "cargo test",
+ ] {
+ assert_eq!(hardline(c), None, "{c}");
+ }
+ }
+
+ #[test]
+ fn sudo_password_floor_holds_in_every_mode() {
+ let pol = policy(&[], &[r".*"]);
+ for mode in ALL_MODES {
+ for c in [
+ "echo hunter2 | sudo -S apt install x",
+ "sudo -S true <<< hunter2",
+ "sudo --stdin ls",
+ "printf pw | sudo ls",
+ "sudo -kS ls",
+ ] {
+ let v = run(
+ "run_command",
+ &cmd(c),
+ &SafetyDecision::Allow,
+ mode,
+ Presence::Person,
+ &pol,
+ );
+ assert!(
+ matches!(
+ v,
+ Verdict::Deny {
+ by: Stage::Floor(Floor::SudoPipedPassword),
+ ..
+ }
+ ),
+ "{mode:?} {c}: {v:?}"
+ );
+ }
+ }
+ // Negative controls: plain sudo, and sudo -s (a shell, lower case).
+ for c in ["sudo ls /root", "sudo -s", "sudo -u op ls | grep x"] {
+ assert_eq!(sudo_piped_password(c), None, "{c}");
+ }
+ }
+
+ #[test]
+ fn runtime_floor_holds_in_every_mode() {
+ let pol = policy(&[], &[r".*"]);
+ let cases = [
+ ("run_command", cmd("rm -rf ~/basecamp/checkpoints")),
+ ("run_command", cmd("rm -rf /home/op/basecamp")),
+ (
+ "run_command",
+ cmd("cd /tmp; mv /opt/aien/bin/aien-cli /tmp/x"),
+ ),
+ (
+ "run_command",
+ cmd("echo '{}' > ~/basecamp/approval-policy.json"),
+ ),
+ (
+ "run_command",
+ json!({"command": "rm -r sessions", "cwd": "/home/op/basecamp"}),
+ ),
+ (
+ "run_command",
+ cmd("sed -i s/deny/x/ /home/op/basecamp/approval-policy.json"),
+ ),
+ (
+ "run_command",
+ cmd("find /home/op/basecamp/sessions -delete"),
+ ),
+ (
+ "write_to_file",
+ json!({"path": "/home/op/basecamp/approval-policy.json", "content": "{}"}),
+ ),
+ (
+ "replace_file_content",
+ json!({"path": "../basecamp/checkpoints/ledger/s.jsonl", "target": "a", "replacement": "b"}),
+ ),
+ ];
+ for mode in ALL_MODES {
+ for (tool, args) in &cases {
+ let v = run(
+ tool,
+ args,
+ &SafetyDecision::Allow,
+ mode,
+ Presence::Person,
+ &pol,
+ );
+ assert!(
+ matches!(
+ v,
+ Verdict::Deny {
+ by: Stage::Floor(Floor::RuntimeSelfDelete),
+ ..
+ }
+ ),
+ "{mode:?} {tool} {args}: {v:?}"
+ );
+ }
+ }
+ // Negative controls: reading the runtime's files and writing beside them.
+ let f = facts();
+ for (tool, args) in [
+ ("run_command", cmd("cat ~/basecamp/approval-policy.json")),
+ ("run_command", cmd("ls /home/op/basecamp/sessions")),
+ ("run_command", cmd("rm -rf /home/op/basecamp/other")),
+ (
+ "write_to_file",
+ json!({"path": "/home/op/basecamp/notes.md", "content": "x"}),
+ ),
+ ] {
+ assert_eq!(runtime_self_delete(tool, &args, &f), None, "{tool} {args}");
+ }
+ }
+
+ #[test]
+ fn floors_come_before_mode_order_is_load_bearing() {
+ // The policy-engine denial also survives yolo and off.
+ let pol = policy(&[], &[]);
+ for mode in ALL_MODES {
+ let v = run(
+ "write_to_file",
+ &json!({"path": "/home/op/work/.env"}),
+ &SafetyDecision::Deny("vault".into()),
+ mode,
+ Presence::Person,
+ &pol,
+ );
+ assert_eq!(
+ v,
+ Verdict::Deny {
+ by: Stage::PolicyDeny,
+ reason: "vault".into()
+ }
+ );
+ }
+ }
+
+ #[test]
+ fn modes_after_the_floors() {
+ let pol = policy(&[], &[]);
+ let ask = SafetyDecision::AskUser("q".into());
+ let a = cmd("make deploy");
+ assert_eq!(
+ run(
+ "run_command",
+ &a,
+ &ask,
+ ApprovalMode::Yolo,
+ Presence::Unattended,
+ &pol
+ ),
+ Verdict::Allow { by: Stage::Mode }
+ );
+ assert_eq!(
+ run(
+ "run_command",
+ &a,
+ &ask,
+ ApprovalMode::Off,
+ Presence::Person,
+ &pol
+ ),
+ Verdict::Allow { by: Stage::Mode }
+ );
+ assert_eq!(
+ run(
+ "run_command",
+ &a,
+ &ask,
+ ApprovalMode::Manual,
+ Presence::Person,
+ &pol
+ ),
+ Verdict::AskPerson { reason: "q".into() }
+ );
+ assert_eq!(
+ run(
+ "run_command",
+ &a,
+ &ask,
+ ApprovalMode::Smart,
+ Presence::Person,
+ &pol
+ ),
+ Verdict::AskGuardian { reason: "q".into() }
+ );
+ }
+
+ #[test]
+ fn unattended_defaults_to_deny_but_clear_requests_pass() {
+ let pol = policy(&[], &[]);
+ for mode in [ApprovalMode::Manual, ApprovalMode::Smart] {
+ let v = run(
+ "run_command",
+ &cmd("shutdown -h now"),
+ &SafetyDecision::Allow,
+ mode,
+ Presence::Unattended,
+ &pol,
+ );
+ assert!(
+ matches!(
+ v,
+ Verdict::Deny {
+ by: Stage::Presence,
+ ..
+ }
+ ),
+ "{v:?}"
+ );
+ let v = run(
+ "run_command",
+ &cmd("cargo test"),
+ &SafetyDecision::Allow,
+ mode,
+ Presence::Unattended,
+ &pol,
+ );
+ assert_eq!(v, Verdict::Allow { by: Stage::Clear });
+ }
+ }
+
+ #[test]
+ fn allowlist_skips_the_question_not_a_floor() {
+ let pol = policy(&[], &[r"^shutdown -h now$"]);
+ let v = run(
+ "run_command",
+ &cmd("shutdown -h now"),
+ &SafetyDecision::Allow,
+ ApprovalMode::Manual,
+ Presence::Unattended,
+ &pol,
+ );
+ assert_eq!(
+ v,
+ Verdict::Allow {
+ by: Stage::Allowlist
+ }
+ );
+ let v = run(
+ "run_command",
+ &cmd("rm -rf /"),
+ &SafetyDecision::Allow,
+ ApprovalMode::Manual,
+ Presence::Person,
+ &policy(&[], &[r".*"]),
+ );
+ assert!(matches!(
+ v,
+ Verdict::Deny {
+ by: Stage::Floor(Floor::Hardline),
+ ..
+ }
+ ));
+ }
+
+ #[test]
+ fn guardian_answers_and_breaker() {
+ assert_eq!(parse_guardian_reply("APPROVE"), GuardianAnswer::Approve);
+ assert_eq!(
+ parse_guardian_reply(" escalate: unsure"),
+ GuardianAnswer::Escalate
+ );
+ assert!(matches!(
+ parse_guardian_reply("DENY wipes data"),
+ GuardianAnswer::Deny(_)
+ ));
+ assert!(matches!(
+ parse_guardian_reply("Sure, go ahead"),
+ GuardianAnswer::Failed(_)
+ ));
+
+ assert_eq!(
+ after_guardian(&GuardianAnswer::Approve, "r".into()),
+ Verdict::Allow {
+ by: Stage::Guardian
+ }
+ );
+ assert!(matches!(
+ after_guardian(&GuardianAnswer::Deny("x".into()), "r".into()),
+ Verdict::Deny {
+ by: Stage::Guardian,
+ ..
+ }
+ ));
+ for a in [GuardianAnswer::Escalate, GuardianAnswer::Failed("t".into())] {
+ assert_eq!(
+ after_guardian(&a, "r".into()),
+ Verdict::AskPerson { reason: "r".into() }
+ );
+ }
+
+ let mut b = GuardianBreaker::new(3);
+ let fail = GuardianAnswer::Failed("timeout".into());
+ b.record(&fail);
+ b.record(&fail);
+ b.record(&GuardianAnswer::Escalate); // a real answer resets the count
+ b.record(&fail);
+ b.record(&fail);
+ assert!(b.is_closed());
+ b.record(&fail);
+ assert!(!b.is_closed());
+ b.record(&GuardianAnswer::Approve); // stays open for the session
+ assert!(!b.is_closed());
+
+ // An open breaker sends smart mode to the person.
+ let pol = policy(&[], &[]);
+ let v = decide(&Gate {
+ tool: "run_command",
+ args: &cmd("make deploy"),
+ base: &SafetyDecision::AskUser("q".into()),
+ mode: ApprovalMode::Smart,
+ presence: Presence::Person,
+ policy: &pol,
+ facts: &facts(),
+ guardian_ready: b.is_closed(),
+ });
+ assert_eq!(v, Verdict::AskPerson { reason: "q".into() });
+ }
+
+ #[test]
+ fn decide_is_deterministic() {
+ let pol = policy(&["x"], &["y"]);
+ let a = cmd("echo y");
+ let first = run(
+ "run_command",
+ &a,
+ &SafetyDecision::Allow,
+ ApprovalMode::Manual,
+ Presence::Person,
+ &pol,
+ );
+ for _ in 0..10 {
+ assert_eq!(
+ run(
+ "run_command",
+ &a,
+ &SafetyDecision::Allow,
+ ApprovalMode::Manual,
+ Presence::Person,
+ &pol
+ ),
+ first
+ );
+ }
+ }
+}
diff --git a/crates/aien-cli/src/checkpoint.rs b/crates/aien-cli/src/checkpoint.rs
new file mode 100644
index 00000000 ..2861d18b
--- /dev/null
+++ b/crates/aien-cli/src/checkpoint.rs
@@ -0,0 +1,867 @@
+//! File checkpoints and the agent-write ledger (sc#667).
+//!
+//! One shared content-addressed store under `~/basecamp/checkpoints`:
+//!
+//! - `objects/ab/cdef...`: file contents named by their SHA-256, shared by
+//! every session (the same bytes are stored once).
+//! - `snapshots/<id>.json`: one snapshot per directory per turn, taken just
+//! before the agent's first write into that directory in that turn.
+//! - `ledger/<session>.jsonl`: every write the agent's file tools made, with
+//! the content hash before and after, hash-chained line to line.
+//!
+//! A rollback restores only paths in the ledger, and only where the file
+//! still holds what the agent left. A file the operator edited after the
+//! agent is a conflict and is kept; files the operator edited that the agent
+//! never wrote are reported as spared and never touched.
+//!
+//! The pure part (hashing, the chain, the rollback planner) takes values and
+//! returns values, so it can move to Omega (ADR 0024). The store is the edge.
+//!
+//! Prior art: Hermes Agent, Nous Research, MIT licence, commit 5480918
+//! (read 2026-10-18), `tools/checkpoint_manager.py`. Hermes keeps a shared
+//! bare git store; this is our own content-addressed store with the same
+//! shape (shared objects, per-directory per-turn snapshots, agent ledger).
+//! Mechanism re-implemented from reading; no code copied.
+
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+use std::collections::{BTreeMap, BTreeSet, HashSet};
+use std::fs;
+use std::io::Write;
+use std::path::{Path, PathBuf};
+use std::sync::{Mutex, OnceLock};
+
+pub type Hash = String;
+
+/// Directory snapshot bounds: files bigger than this, or past this count,
+/// are listed as skipped. The written file's own prior content is always
+/// kept, whatever its size.
+pub const SNAPSHOT_MAX_FILE_BYTES: u64 = 2 * 1024 * 1024;
+pub const SNAPSHOT_MAX_FILES: usize = 512;
+
+const GENESIS: &str = "genesis";
+
+// ---------------------------------------------------------------------------
+// Pure part
+// ---------------------------------------------------------------------------
+
+pub fn hash_bytes(bytes: &[u8]) -> Hash {
+ hex::encode(Sha256::digest(bytes))
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Snapshot {
+ pub session: String,
+ pub turn: u64,
+ pub dir: String,
+ /// File name (not path) to content hash, regular files only.
+ pub files: BTreeMap<String, Hash>,
+ pub skipped: Vec<String>,
+}
+
+impl Snapshot {
+ /// Content address of the snapshot itself.
+ pub fn id(&self) -> Hash {
+ hash_bytes(&serde_json::to_vec(self).unwrap_or_default())
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct LedgerEntry {
+ pub seq: u64,
+ pub turn: u64,
+ pub tool: String,
+ pub path: String,
+ /// `None` = the file did not exist.
+ pub before: Option<Hash>,
+ pub after: Option<Hash>,
+ /// Snapshot of the directory for this turn.
+ pub snapshot: Hash,
+ /// Hash of the previous ledger line, `genesis` for the first.
+ pub prev: Hash,
+}
+
+/// Serialize an entry as one ledger line (without the newline) and return
+/// the hash the next entry must carry as `prev`.
+pub fn ledger_line(entry: &LedgerEntry) -> (String, Hash) {
+ let line = serde_json::to_string(entry).unwrap_or_default();
+ let next = hash_bytes(line.as_bytes());
+ (line, next)
+}
+
+/// Parse and verify a ledger file. A torn last line (crash mid-append) is
+/// dropped; a broken chain anywhere else is refused, so a rollback never runs
+/// on a ledger someone edited. Returns the entries and the next `prev`.
+pub fn read_ledger(text: &str) -> Result<(Vec<LedgerEntry>, Hash), String> {
+ let mut entries = Vec::new();
+ let mut prev = GENESIS.to_string();
+ let lines: Vec<&str> = text.split('\n').collect();
+ // `text` ends with '\n' when the last append finished, so the last piece
+ // is empty; anything else there is a torn line.
+ let complete = lines.len().saturating_sub(1);
+ for (i, line) in lines.iter().take(complete).enumerate() {
+ let entry: LedgerEntry = serde_json::from_str(line)
+ .map_err(|e| format!("ledger line {} is damaged: {}", i + 1, e))?;
+ if entry.prev != prev {
+ return Err(format!("ledger chain broken at line {}", i + 1));
+ }
+ if entry.seq != i as u64 {
+ return Err(format!("ledger sequence broken at line {}", i + 1));
+ }
+ prev = hash_bytes(line.as_bytes());
+ entries.push(entry);
+ }
+ Ok((entries, prev))
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub enum RollbackStep {
+ /// Put the agent's starting content back (`None` = remove the file the
+ /// agent created).
+ Restore { path: String, to: Option<Hash> },
+ /// The file already holds its starting content.
+ AlreadyThere { path: String },
+ /// Someone changed the file after the agent; it is kept as it is.
+ Conflict {
+ path: String,
+ agent_left: Option<Hash>,
+ found: Option<Hash>,
+ },
+}
+
+/// Plan the rollback of every agent write in turns `>= from_turn`.
+/// `current` holds the present hash of every ledger path (`None` = absent).
+/// A path missing from `current` is treated as absent.
+pub fn plan_rollback(
+ entries: &[LedgerEntry],
+ from_turn: u64,
+ current: &BTreeMap<String, Option<Hash>>,
+) -> Vec<RollbackStep> {
+ let mut by_path: BTreeMap<&str, Vec<&LedgerEntry>> = BTreeMap::new();
+ for e in entries.iter().filter(|e| e.turn >= from_turn) {
+ by_path.entry(e.path.as_str()).or_default().push(e);
+ }
+ let mut steps = Vec::new();
+ for (path, mut writes) in by_path {
+ writes.sort_by_key(|e| e.seq);
+ let start = writes[0].before.clone();
+ let left = writes[writes.len() - 1].after.clone();
+ let found = current.get(path).cloned().flatten();
+ let path = path.to_string();
+ if found == start {
+ steps.push(RollbackStep::AlreadyThere { path });
+ } else if found == left {
+ steps.push(RollbackStep::Restore { path, to: start });
+ } else {
+ steps.push(RollbackStep::Conflict {
+ path,
+ agent_left: left,
+ found,
+ });
+ }
+ }
+ steps
+}
+
+/// Files in the snapshotted directories that changed since the snapshot and
+/// that the agent never wrote: the operator's edits, left alone. `current`
+/// maps full paths in those directories to their present hash.
+pub fn spared_operator_edits(
+ snapshots: &[Snapshot],
+ agent_paths: &BTreeSet<String>,
+ current: &BTreeMap<String, Option<Hash>>,
+) -> Vec<String> {
+ let mut spared = BTreeSet::new();
+ for snap in snapshots {
+ let dir = Path::new(&snap.dir);
+ for (name, hash) in &snap.files {
+ let full = dir.join(name).to_string_lossy().into_owned();
+ if agent_paths.contains(&full) {
+ continue;
+ }
+ if current.get(&full).cloned().flatten().as_ref() != Some(hash) {
+ spared.insert(full);
+ }
+ }
+ for full in current.keys() {
+ let p = Path::new(full);
+ if p.parent() == Some(dir)
+ && !agent_paths.contains(full)
+ && p.file_name().and_then(|n| n.to_str()).is_some_and(|n| {
+ !snap.files.contains_key(n) && !snap.skipped.iter().any(|s| s == n)
+ })
+ {
+ spared.insert(full.clone());
+ }
+ }
+ }
+ spared.into_iter().collect()
+}
+
+// ---------------------------------------------------------------------------
+// Edge: the on-disk store
+// ---------------------------------------------------------------------------
+
+pub fn store_root(home: &Path) -> PathBuf {
+ home.join("basecamp/checkpoints")
+}
+
+#[derive(Debug, Clone)]
+pub struct CheckpointStore {
+ root: PathBuf,
+}
+
+impl CheckpointStore {
+ pub fn new(root: PathBuf) -> Self {
+ Self { root }
+ }
+
+ fn object_path(&self, hash: &str) -> PathBuf {
+ let (a, b) = hash.split_at(2.min(hash.len()));
+ self.root.join("objects").join(a).join(b)
+ }
+
+ pub fn put_blob(&self, bytes: &[u8]) -> Result<Hash, String> {
+ let hash = hash_bytes(bytes);
+ let path = self.object_path(&hash);
+ if !path.exists() {
+ write_atomic(&path, bytes)?;
+ }
+ Ok(hash)
+ }
+
+ /// Read a blob and check it still hashes to its name.
+ pub fn get_blob(&self, hash: &str) -> Result<Vec<u8>, String> {
+ let bytes = fs::read(self.object_path(hash))
+ .map_err(|e| format!("checkpoint object {hash} unreadable: {e}"))?;
+ if hash_bytes(&bytes) != hash {
+ return Err(format!("checkpoint object {hash} is damaged"));
+ }
+ Ok(bytes)
+ }
+
+ fn ledger_path(&self, session: &str) -> PathBuf {
+ self.root.join("ledger").join(format!("{session}.jsonl"))
+ }
+
+ pub fn load_ledger(&self, session: &str) -> Result<(Vec<LedgerEntry>, Hash), String> {
+ match fs::read_to_string(self.ledger_path(session)) {
+ Ok(text) => read_ledger(&text),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok((Vec::new(), GENESIS.into())),
+ Err(e) => Err(format!("ledger unreadable: {e}")),
+ }
+ }
+
+ fn append_ledger(&self, session: &str, line: &str) -> Result<(), String> {
+ let path = self.ledger_path(session);
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent).map_err(|e| e.to_string())?;
+ }
+ let mut f = fs::OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(&path)
+ .map_err(|e| format!("ledger open failed: {e}"))?;
+ f.write_all(format!("{line}\n").as_bytes())
+ .and_then(|_| f.sync_all())
+ .map_err(|e| format!("ledger append failed: {e}"))
+ }
+
+ fn snapshot_path(&self, id: &str) -> PathBuf {
+ self.root.join("snapshots").join(format!("{id}.json"))
+ }
+
+ pub fn load_snapshot(&self, id: &str) -> Result<Snapshot, String> {
+ let bytes = fs::read(self.snapshot_path(id)).map_err(|e| e.to_string())?;
+ let snap: Snapshot = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?;
+ if snap.id() != id {
+ return Err(format!("snapshot {id} is damaged"));
+ }
+ Ok(snap)
+ }
+
+ /// Snapshot the regular files directly inside `dir`.
+ fn take_snapshot(&self, session: &str, turn: u64, dir: &Path) -> Result<Hash, String> {
+ let mut files = BTreeMap::new();
+ let mut skipped = Vec::new();
+ if let Ok(rd) = fs::read_dir(dir) {
+ let mut names: Vec<(String, PathBuf)> = rd
+ .flatten()
+ .filter(|e| e.file_type().map(|t| t.is_file()).unwrap_or(false))
+ .map(|e| (e.file_name().to_string_lossy().into_owned(), e.path()))
+ .collect();
+ names.sort();
+ for (name, path) in names {
+ let size = fs::metadata(&path).map(|m| m.len()).unwrap_or(u64::MAX);
+ if files.len() >= SNAPSHOT_MAX_FILES || size > SNAPSHOT_MAX_FILE_BYTES {
+ skipped.push(name);
+ continue;
+ }
+ match fs::read(&path) {
+ Ok(bytes) => {
+ files.insert(name, self.put_blob(&bytes)?);
+ }
+ Err(_) => skipped.push(name),
+ }
+ }
+ }
+ let snap = Snapshot {
+ session: session.to_string(),
+ turn,
+ dir: dir.to_string_lossy().into_owned(),
+ files,
+ skipped,
+ };
+ let id = snap.id();
+ let path = self.snapshot_path(&id);
+ if !path.exists() {
+ write_atomic(&path, &serde_json::to_vec(&snap).unwrap_or_default())?;
+ }
+ Ok(id)
+ }
+
+ /// Plan and apply the rollback of `session`'s agent writes in turns
+ /// `>= from_turn`.
+ pub fn rollback(&self, session: &str, from_turn: u64) -> Result<RollbackReport, String> {
+ let (entries, _) = self.load_ledger(session)?;
+ let agent_paths: BTreeSet<String> = entries
+ .iter()
+ .filter(|e| e.turn >= from_turn)
+ .map(|e| e.path.clone())
+ .collect();
+ let mut current = BTreeMap::new();
+ for p in &agent_paths {
+ current.insert(p.clone(), current_hash(Path::new(p)));
+ }
+ let steps = plan_rollback(&entries, from_turn, ¤t);
+
+ // Spared files are worked out before anything is restored.
+ let mut snap_ids = BTreeSet::new();
+ for e in entries.iter().filter(|e| e.turn >= from_turn) {
+ snap_ids.insert(e.snapshot.clone());
+ }
+ let mut snapshots = Vec::new();
+ for id in &snap_ids {
+ snapshots.push(self.load_snapshot(id)?);
+ }
+ let mut dir_state = BTreeMap::new();
+ for snap in &snapshots {
+ if let Ok(rd) = fs::read_dir(&snap.dir) {
+ for e in rd.flatten() {
+ if e.file_type().map(|t| t.is_file()).unwrap_or(false) {
+ let p = e.path();
+ dir_state.insert(p.to_string_lossy().into_owned(), current_hash(&p));
+ }
+ }
+ }
+ }
+ let spared = spared_operator_edits(&snapshots, &agent_paths, &dir_state);
+
+ let mut report = RollbackReport {
+ from_turn,
+ spared,
+ ..Default::default()
+ };
+ for step in steps {
+ match step {
+ RollbackStep::Restore { path, to: Some(h) } => {
+ let bytes = self.get_blob(&h)?;
+ write_atomic(Path::new(&path), &bytes)?;
+ report.restored.push(path);
+ }
+ RollbackStep::Restore { path, to: None } => {
+ fs::remove_file(&path).map_err(|e| format!("remove {path}: {e}"))?;
+ report.removed.push(path);
+ }
+ RollbackStep::AlreadyThere { path } => report.unchanged.push(path),
+ RollbackStep::Conflict { path, .. } => report.conflicts.push(path),
+ }
+ }
+ Ok(report)
+ }
+}
+
+#[derive(Debug, Clone, Default, PartialEq)]
+pub struct RollbackReport {
+ pub from_turn: u64,
+ /// Agent-written files put back to their starting content.
+ pub restored: Vec<String>,
+ /// Files the agent created, removed again.
+ pub removed: Vec<String>,
+ /// Agent-written files already at their starting content.
+ pub unchanged: Vec<String>,
+ /// Agent-written files someone changed afterwards: kept as found.
+ pub conflicts: Vec<String>,
+ /// Files in the same directories the operator changed: never touched.
+ pub spared: Vec<String>,
+}
+
+fn current_hash(path: &Path) -> Option<Hash> {
+ fs::read(path).ok().map(|b| hash_bytes(&b))
+}
+
+fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> {
+ let parent = path.parent().unwrap_or(Path::new("."));
+ fs::create_dir_all(parent).map_err(|e| format!("create {}: {e}", parent.display()))?;
+ let tmp = parent.join(format!(
+ ".{}.aien-tmp-{}",
+ path.file_name().and_then(|n| n.to_str()).unwrap_or("f"),
+ std::process::id()
+ ));
+ let mut f = fs::File::create(&tmp).map_err(|e| format!("create {}: {e}", tmp.display()))?;
+ f.write_all(bytes)
+ .and_then(|_| f.sync_all())
+ .map_err(|e| format!("write {}: {e}", tmp.display()))?;
+ fs::rename(&tmp, path).map_err(|e| format!("rename onto {}: {e}", path.display()))
+}
+
+/// One chat session's view of the store: turn counter, which directories
+/// are already snapshotted this turn, and the ledger chain head.
+#[derive(Debug)]
+pub struct Session {
+ pub store: CheckpointStore,
+ pub id: String,
+ pub turn: u64,
+ /// Record only writes under this directory (`None` = every write).
+ pub scope: Option<PathBuf>,
+ snapshotted: HashSet<(u64, PathBuf)>,
+ turn_snapshots: BTreeMap<PathBuf, Hash>,
+ next_seq: u64,
+ prev: Hash,
+}
+
+/// What `before_write` captured; handed back to `after_write`.
+#[derive(Debug, Clone)]
+pub struct Pending {
+ path: PathBuf,
+ before: Option<Hash>,
+ snapshot: Hash,
+}
+
+impl Session {
+ pub fn open(store: CheckpointStore, id: &str) -> Result<Self, String> {
+ let (entries, prev) = store.load_ledger(id)?;
+ let turn = entries.last().map(|e| e.turn).unwrap_or(0);
+ Ok(Self {
+ store,
+ id: id.to_string(),
+ turn,
+ scope: None,
+ snapshotted: HashSet::new(),
+ turn_snapshots: BTreeMap::new(),
+ next_seq: entries.len() as u64,
+ prev,
+ })
+ }
+
+ pub fn begin_turn(&mut self) -> u64 {
+ self.turn += 1;
+ self.turn_snapshots.clear();
+ self.turn
+ }
+
+ /// Call before an agent write to `path` (absolute). Snapshots the
+ /// directory once this turn and keeps the file's prior content.
+ pub fn before_write(&mut self, path: &Path) -> Result<Pending, String> {
+ let dir = path.parent().unwrap_or(Path::new("/")).to_path_buf();
+ let key = (self.turn, dir.clone());
+ if !self.snapshotted.contains(&key) {
+ let id = self.store.take_snapshot(&self.id, self.turn, &dir)?;
+ self.snapshotted.insert(key);
+ self.turn_snapshots.insert(dir.clone(), id);
+ }
+ let snapshot = self.turn_snapshots.get(&dir).cloned().unwrap_or_default();
+ let before = match fs::read(path) {
+ Ok(bytes) => Some(self.store.put_blob(&bytes)?),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
+ Err(e) => {
+ return Err(format!(
+ "cannot read {} before writing: {e}",
+ path.display()
+ ))
+ }
+ };
+ Ok(Pending {
+ path: path.to_path_buf(),
+ before,
+ snapshot,
+ })
+ }
+
+ /// Call after the write; appends one ledger line.
+ pub fn after_write(&mut self, pending: Pending, tool: &str) -> Result<(), String> {
+ let after = match fs::read(&pending.path) {
+ Ok(bytes) => Some(self.store.put_blob(&bytes)?),
+ Err(_) => None,
+ };
+ if after == pending.before {
+ return Ok(());
+ }
+ let entry = LedgerEntry {
+ seq: self.next_seq,
+ turn: self.turn,
+ tool: tool.to_string(),
+ path: pending.path.to_string_lossy().into_owned(),
+ before: pending.before,
+ after,
+ snapshot: pending.snapshot,
+ prev: self.prev.clone(),
+ };
+ let (line, next) = ledger_line(&entry);
+ self.store.append_ledger(&self.id, &line)?;
+ self.next_seq += 1;
+ self.prev = next;
+ Ok(())
+ }
+
+ /// Turns with agent writes, newest last, with their file counts.
+ pub fn turns(&self) -> Result<Vec<(u64, usize)>, String> {
+ let (entries, _) = self.store.load_ledger(&self.id)?;
+ let mut by_turn: BTreeMap<u64, BTreeSet<&str>> = BTreeMap::new();
+ for e in &entries {
+ by_turn.entry(e.turn).or_default().insert(e.path.as_str());
+ }
+ Ok(by_turn.into_iter().map(|(t, p)| (t, p.len())).collect())
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Edge: the process's active session (set by the chat loop)
+// ---------------------------------------------------------------------------
+
+fn active() -> &'static Mutex<Option<Session>> {
+ static ACTIVE: OnceLock<Mutex<Option<Session>>> = OnceLock::new();
+ ACTIVE.get_or_init(|| Mutex::new(None))
+}
+
+/// Start recording agent writes for this session. Without this call (tests,
+/// other entry points) the file tools record nothing.
+pub fn start_session(home: &Path, session_id: &str) -> Result<(), String> {
+ let session = Session::open(CheckpointStore::new(store_root(home)), session_id)?;
+ *active().lock().map_err(|_| "checkpoint lock poisoned")? = Some(session);
+ Ok(())
+}
+
+/// Stop recording (tests and shutdown).
+#[allow(dead_code)]
+pub fn stop_session() {
+ if let Ok(mut guard) = active().lock() {
+ *guard = None;
+ }
+}
+
+/// Start a session that records only writes under `scope`.
+#[allow(dead_code)]
+pub fn start_scoped_session(home: &Path, session_id: &str, scope: PathBuf) -> Result<(), String> {
+ let mut session = Session::open(CheckpointStore::new(store_root(home)), session_id)?;
+ session.scope = Some(scope);
+ *active().lock().map_err(|_| "checkpoint lock poisoned")? = Some(session);
+ Ok(())
+}
+
+pub fn begin_turn() {
+ if let Ok(mut guard) = active().lock() {
+ if let Some(s) = guard.as_mut() {
+ s.begin_turn();
+ }
+ }
+}
+
+pub fn active_ledger_name() -> Option<String> {
+ active().lock().ok()?.as_ref().map(|s| s.id.clone())
+}
+
+/// Run `write` as a recorded agent write of `path`. If the prior content
+/// cannot be kept the write is refused, because it could not be rolled back.
+/// If the ledger append fails after the write, the error is returned beside
+/// the result so the caller can show it.
+pub fn record_agent_write<T>(
+ path: &Path,
+ tool: &str,
+ write: impl FnOnce() -> T,
+) -> Result<(T, Option<String>), String> {
+ let mut guard = active()
+ .lock()
+ .map_err(|_| "checkpoint lock poisoned".to_string())?;
+ let Some(session) = guard
+ .as_mut()
+ .filter(|s| s.scope.as_ref().is_none_or(|d| path.starts_with(d)))
+ else {
+ return Ok((write(), None));
+ };
+ let pending = session
+ .before_write(path)
+ .map_err(|e| format!("CHECKPOINT REFUSAL: {e}"))?;
+ let out = write();
+ let warn = session.after_write(pending, tool).err();
+ Ok((out, warn))
+}
+
+/// The session `session` names, or else the active one.
+fn session_or_active(session: Option<&str>) -> Result<String, String> {
+ match session {
+ Some(s) => Ok(s.to_string()),
+ None => active_ledger_name()
+ .ok_or_else(|| "no active session; name one: /checkpoints <session-id>".to_string()),
+ }
+}
+
+/// Turns (turn number, file writes) of an active session or of `session`.
+/// The session id is deliberately not in the result: callers that print the
+/// turns do not print the id (sc#689, cleartext logging of a session id).
+pub fn list_turns(home: &Path, session: Option<&str>) -> Result<Vec<(u64, usize)>, String> {
+ let id = session_or_active(session)?;
+ let s = Session::open(CheckpointStore::new(store_root(home)), &id)?;
+ s.turns()
+}
+
+/// Roll back `session` (default: the active one) from `turn` (default: its
+/// last turn with agent writes). Returns the report only; see `list_turns`.
+pub fn rollback(
+ home: &Path,
+ turn: Option<u64>,
+ session: Option<&str>,
+) -> Result<RollbackReport, String> {
+ let id = session_or_active(session)?;
+ let turns = list_turns(home, Some(id.as_str()))?;
+ let Some(last) = turns.last().map(|(t, _)| *t) else {
+ return Err(format!("session {id} has no agent writes to roll back"));
+ };
+ let from = turn.unwrap_or(last);
+ let store = CheckpointStore::new(store_root(home));
+ // Hold the active session lock so no agent write lands mid-rollback.
+ let _guard = active().lock();
+ store.rollback(&id, from)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn entry(
+ seq: u64,
+ turn: u64,
+ path: &str,
+ before: Option<&str>,
+ after: Option<&str>,
+ ) -> LedgerEntry {
+ LedgerEntry {
+ seq,
+ turn,
+ tool: "write_to_file".into(),
+ path: path.into(),
+ before: before.map(String::from),
+ after: after.map(String::from),
+ snapshot: "s".into(),
+ prev: String::new(),
+ }
+ }
+
+ #[test]
+ fn planner_restores_only_what_still_holds_the_agents_bytes() {
+ let entries = vec![
+ entry(0, 1, "/w/a", Some("a0"), Some("a1")),
+ entry(1, 2, "/w/a", Some("a1"), Some("a2")),
+ entry(2, 2, "/w/new", None, Some("n1")),
+ entry(3, 2, "/w/b", Some("b0"), Some("b1")),
+ entry(4, 2, "/w/c", Some("c0"), Some("c1")),
+ ];
+ let current: BTreeMap<String, Option<Hash>> = [
+ ("/w/a", Some("a2")),
+ ("/w/new", Some("n1")),
+ ("/w/b", Some("operator")), // operator edited after the agent
+ ("/w/c", Some("c0")), // already back
+ ]
+ .into_iter()
+ .map(|(k, v)| (k.to_string(), v.map(String::from)))
+ .collect();
+ let steps = plan_rollback(&entries, 2, ¤t);
+ assert_eq!(
+ steps,
+ vec![
+ RollbackStep::Restore {
+ path: "/w/a".into(),
+ to: Some("a1".into())
+ },
+ RollbackStep::Conflict {
+ path: "/w/b".into(),
+ agent_left: Some("b1".into()),
+ found: Some("operator".into())
+ },
+ RollbackStep::AlreadyThere {
+ path: "/w/c".into()
+ },
+ RollbackStep::Restore {
+ path: "/w/new".into(),
+ to: None
+ },
+ ]
+ );
+ // From turn 1, /w/a goes back to its turn-1 start.
+ let steps = plan_rollback(&entries, 1, ¤t);
+ assert_eq!(
+ steps[0],
+ RollbackStep::Restore {
+ path: "/w/a".into(),
+ to: Some("a0".into())
+ }
+ );
+ }
+
+ #[test]
+ fn ledger_chain_detects_edits_and_drops_a_torn_tail() {
+ let mut text = String::new();
+ let mut prev = GENESIS.to_string();
+ for seq in 0..3 {
+ let mut e = entry(seq, 1, "/w/a", Some("x"), Some("y"));
+ e.prev = prev.clone();
+ let (line, next) = ledger_line(&e);
+ text.push_str(&line);
+ text.push('\n');
+ prev = next;
+ }
+ let (entries, head) = read_ledger(&text).unwrap();
+ assert_eq!(entries.len(), 3);
+ assert_eq!(head, prev);
+
+ let torn = format!("{text}{{\"seq\":3,\"tu");
+ assert_eq!(read_ledger(&torn).unwrap().0.len(), 3);
+
+ let edited = text.replacen("\"/w/a\"", "\"/w/z\"", 1);
+ assert!(read_ledger(&edited).is_err());
+ let dropped: String = text.lines().skip(1).map(|l| format!("{l}\n")).collect();
+ assert!(read_ledger(&dropped).is_err());
+ }
+
+ /// Acceptance: after mixed operator and agent edits, a rollback restores
+ /// only the agent's files.
+ #[test]
+ fn rollback_after_mixed_edits_restores_only_the_agents_files() {
+ let tmp = tempfile::tempdir().unwrap();
+ let work = tmp.path().join("work");
+ fs::create_dir_all(&work).unwrap();
+ let store = CheckpointStore::new(tmp.path().join("checkpoints"));
+ let mut s = Session::open(store.clone(), "s1").unwrap();
+
+ let agent_file = work.join("agent.rs");
+ let shared = work.join("shared.rs");
+ let operator_file = work.join("operator.md");
+ let created = work.join("created.txt");
+ fs::write(&agent_file, "agent v0").unwrap();
+ fs::write(&shared, "shared v0").unwrap();
+ fs::write(&operator_file, "operator v0").unwrap();
+
+ // Turn 1: the agent writes two files and creates one.
+ s.begin_turn();
+ for (p, text) in [
+ (&agent_file, "agent v1"),
+ (&shared, "shared v1"),
+ (&created, "new"),
+ ] {
+ let pending = s.before_write(p).unwrap();
+ fs::write(p, text).unwrap();
+ s.after_write(pending, "write_to_file").unwrap();
+ }
+ // The operator edits a file the agent never touched, edits a file the
+ // agent wrote, and adds a new file of their own.
+ fs::write(&operator_file, "operator v1").unwrap();
+ fs::write(&shared, "shared operator fix").unwrap();
+ let operator_new = work.join("operator-new.md");
+ fs::write(&operator_new, "mine").unwrap();
+
+ let report = store.rollback("s1", 1).unwrap();
+ assert_eq!(fs::read_to_string(&agent_file).unwrap(), "agent v0");
+ assert!(!created.exists());
+ assert_eq!(fs::read_to_string(&operator_file).unwrap(), "operator v1");
+ assert_eq!(fs::read_to_string(&shared).unwrap(), "shared operator fix");
+ assert_eq!(fs::read_to_string(&operator_new).unwrap(), "mine");
+ let s = |p: &Path| p.to_string_lossy().into_owned();
+ assert_eq!(report.restored, vec![s(&agent_file)]);
+ assert_eq!(report.removed, vec![s(&created)]);
+ assert_eq!(report.conflicts, vec![s(&shared)]);
+ assert_eq!(report.spared, vec![s(&operator_new), s(&operator_file)]);
+
+ // A second rollback changes nothing.
+ let again = store.rollback("s1", 1).unwrap();
+ assert!(again.restored.is_empty() && again.removed.is_empty());
+ assert_eq!(fs::read_to_string(&operator_file).unwrap(), "operator v1");
+ }
+
+ /// Negative control: restoring the whole directory snapshot (what a
+ /// plain checkpoint does) would destroy the operator's edit; the ledger
+ /// is what prevents it.
+ #[test]
+ fn negative_control_snapshot_alone_would_revert_operator_edits() {
+ let tmp = tempfile::tempdir().unwrap();
+ let work = tmp.path().join("work");
+ fs::create_dir_all(&work).unwrap();
+ let store = CheckpointStore::new(tmp.path().join("checkpoints"));
+ let mut s = Session::open(store.clone(), "s2").unwrap();
+ let agent_file = work.join("a.txt");
+ let operator_file = work.join("o.txt");
+ fs::write(&agent_file, "a0").unwrap();
+ fs::write(&operator_file, "o0").unwrap();
+ s.begin_turn();
+ let pending = s.before_write(&agent_file).unwrap();
+ fs::write(&agent_file, "a1").unwrap();
+ s.after_write(pending, "write_to_file").unwrap();
+ fs::write(&operator_file, "o1").unwrap();
+
+ let (entries, _) = store.load_ledger("s2").unwrap();
+ let snap = store.load_snapshot(&entries[0].snapshot).unwrap();
+ // The snapshot holds the operator file's old content ...
+ assert_eq!(snap.files.get("o.txt"), Some(&hash_bytes(b"o0")));
+ // ... but the ledger never names it, so rollback leaves it.
+ assert!(entries
+ .iter()
+ .all(|e| e.path != operator_file.to_string_lossy()));
+ store.rollback("s2", 1).unwrap();
+ assert_eq!(fs::read_to_string(&operator_file).unwrap(), "o1");
+ assert_eq!(fs::read_to_string(&agent_file).unwrap(), "a0");
+ }
+
+ #[test]
+ fn one_snapshot_per_directory_per_turn_and_shared_objects() {
+ let tmp = tempfile::tempdir().unwrap();
+ let work = tmp.path().join("work");
+ fs::create_dir_all(&work).unwrap();
+ let store = CheckpointStore::new(tmp.path().join("checkpoints"));
+ let mut s = Session::open(store.clone(), "s3").unwrap();
+ s.begin_turn();
+ for i in 0..3 {
+ let p = work.join(format!("f{i}"));
+ let pending = s.before_write(&p).unwrap();
+ fs::write(&p, "same bytes").unwrap();
+ s.after_write(pending, "write_to_file").unwrap();
+ }
+ let snaps = fs::read_dir(tmp.path().join("checkpoints/snapshots"))
+ .unwrap()
+ .count();
+ assert_eq!(snaps, 1);
+ s.begin_turn();
+ let p = work.join("f0");
+ let pending = s.before_write(&p).unwrap();
+ fs::write(&p, "turn two").unwrap();
+ s.after_write(pending, "write_to_file").unwrap();
+ let snaps = fs::read_dir(tmp.path().join("checkpoints/snapshots"))
+ .unwrap()
+ .count();
+ assert_eq!(snaps, 2);
+ // "same bytes" is stored once.
+ assert!(store.get_blob(&hash_bytes(b"same bytes")).is_ok());
+
+ // A reopened session continues the chain and the turn count.
+ let reopened = Session::open(store.clone(), "s3").unwrap();
+ assert_eq!(reopened.turn, 2);
+ assert_eq!(reopened.turns().unwrap(), vec![(1, 3), (2, 1)]);
+ }
+
+ #[test]
+ fn a_damaged_object_stops_the_restore() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = CheckpointStore::new(tmp.path().join("checkpoints"));
+ let h = store.put_blob(b"good").unwrap();
+ fs::write(store.object_path(&h), b"evil").unwrap();
+ assert!(store.get_blob(&h).is_err());
+ }
+}
diff --git a/crates/aien-cli/src/commands.rs b/crates/aien-cli/src/commands.rs
index cb13d0f0 ..3bd55663 100644
--- a/crates/aien-cli/src/commands.rs
+++ b/crates/aien-cli/src/commands.rs
@@ -42,6 +42,77 @@ pub async fn handle_slash_command(cmd: &str) -> bool {
println!("{}", "Exiting AIEN. The Spark desk remains ours.".cyan());
std::process::exit(0);
}
+ "/rollback" => {
+ // sc#667: undo the agent's own file writes from a turn on; the
+ // operator's edits are never touched.
+ let home = crate::platform::PlatformContext::detect().home_dir;
+ let turn = parts.get(1).and_then(|t| t.parse::<u64>().ok());
+ let session = parts.get(if turn.is_some() { 2 } else { 1 }).copied();
+ match crate::checkpoint::rollback(&home, turn, session) {
+ Ok(r) => {
+ println!(
+ "{}",
+ format!("Rolled back from turn {}", r.from_turn)
+ .cyan()
+ .bold()
+ );
+ for (label, paths) in [
+ ("restored", &r.restored),
+ ("removed (the agent created it)", &r.removed),
+ ("already as it was", &r.unchanged),
+ ("KEPT: changed after the agent wrote it", &r.conflicts),
+ ("spared: your own edits, not touched", &r.spared),
+ ] {
+ for p in paths {
+ println!(" {}: {}", label, p);
+ }
+ }
+ }
+ Err(e) => println!("{}", format!("Rollback refused: {}", e).red()),
+ }
+ true
+ }
+ "/checkpoints" => {
+ let home = crate::platform::PlatformContext::detect().home_dir;
+ match crate::checkpoint::list_turns(&home, parts.get(1).copied()) {
+ Ok(turns) if turns.is_empty() => {
+ println!("No agent file writes recorded in that session.")
+ }
+ Ok(turns) => {
+ println!("{}", "Agent writes by turn".cyan());
+ for (t, n) in turns {
+ println!(" turn {}: {} file(s)", t, n);
+ }
+ }
+ Err(e) => println!("{}", e.red()),
+ }
+ true
+ }
+ "/approval" => {
+ let ctx = crate::approval::GateContext::from_env();
+ println!("{}", "Approval gate (sc#667)".cyan().bold());
+ println!(
+ " mode: {:?} person present: {}",
+ ctx.mode,
+ ctx.presence == crate::approval::Presence::Person
+ );
+ println!(
+ " policy file: {}",
+ crate::approval::policy_path(&crate::platform::PlatformContext::detect().home_dir)
+ .display()
+ );
+ if let Some(why) = ctx.policy.broken() {
+ println!(
+ " {}",
+ format!("EVERY REQUEST IS DENIED: {}", why).red().bold()
+ );
+ }
+ for w in &ctx.policy.warnings {
+ println!(" {}", w.yellow());
+ }
+ println!(" floors (every mode): hardline commands, runtime files, sudo password on stdin, your deny patterns");
+ true
+ }
"/clear" => {
print!("{esc}[2J{esc}[1;1H", esc = 27 as char);
let _ = std::io::stdout().flush();
@@ -58,6 +129,11 @@ pub async fn handle_slash_command(cmd: &str) -> bool {
/subagents [list|view|run] Recursive contextual subagents hierarchy
/goal [list|new|done] Manage project goals & milestone lattices"
);
+ println!(" /rollback [turn] [session] Undo the agent's own file writes from a turn on (your edits are kept)");
+ println!(" /checkpoints [session] List turns with agent file writes");
+ println!(
+ " /approval Show approval mode, presence and the policy file"
+ );
println!(" /rules Inspect active repository & directory rules (AGENTS.md, GEMINI.md)");
println!(" /walkthrough [save] Display live architecture map & roadmap (or save to WALKTHROUGH.md)");
println!(" /nest Execute the Agent Nesting Ritual (grounding, threat check, peer wind, scent)");
diff --git a/crates/aien-cli/src/main.rs b/crates/aien-cli/src/main.rs
index 98ab173a ..e822a635 100644
--- a/crates/aien-cli/src/main.rs
+++ b/crates/aien-cli/src/main.rs
@@ -1,5 +1,7 @@
#![allow(clippy::type_complexity, clippy::needless_range_loop)]
mod allen;
+mod approval;
+mod checkpoint;
mod client;
mod commands;
pub mod compaction;
@@ -239,6 +241,7 @@ async fn main() {
let platform = crate::platform::PlatformContext::detect();
let sessions_dir = platform.home_dir.join("basecamp/sessions");
let _ = fs::create_dir_all(&sessions_dir);
+ start_checkpoints(&platform.home_dir, &session_id);
// Mandatory Nesting Ritual: Circle, Check Wind, Leave Scent, Flatten Terrain
let nesting = perform_nesting_ritual(&session_id, true).await;
@@ -317,6 +320,7 @@ async fn main() {
let hook_registry = crate::hooks::HookRegistry::default_sovereign_registry();
let _ = hook_registry.run_pre_turn(&mut user_turn).await;
+ crate::checkpoint::begin_turn();
messages.push(json!({"role": "user", "content": user_turn}));
report_compaction(&compactor.compact_if_needed(&mut messages));
@@ -390,6 +394,8 @@ async fn run_single_prompt(prompt: &str) {
let platform = crate::platform::PlatformContext::detect();
let sessions_dir = platform.home_dir.join("basecamp/sessions");
let _ = fs::create_dir_all(&sessions_dir);
+ start_checkpoints(&platform.home_dir, &session_id);
+ crate::checkpoint::begin_turn();
// Mandatory Nesting Ritual: Required at startup across all modes
let nesting = perform_nesting_ritual(&session_id, true).await;
@@ -640,3 +646,16 @@ fn report_compaction(report: &crate::compaction::CompactionReport) {
),
}
}
+
+/// sc#667: record the agent's file writes so `/rollback` can undo them
+/// without touching the operator's own edits. A store that cannot open is
+/// reported; the session still runs, with writes refused only if a later
+/// snapshot fails.
+fn start_checkpoints(home: &std::path::Path, session_id: &str) {
+ if let Err(err) = crate::checkpoint::start_session(home, session_id) {
+ eprintln!(
+ "{}",
+ format!("Checkpoints off for this session: {}", err).yellow()
+ );
+ }
+}
diff --git a/crates/aien-cli/src/tools.rs b/crates/aien-cli/src/tools.rs
index 2ebdd6f9 ..447d2f69 100644
--- a/crates/aien-cli/src/tools.rs
+++ b/crates/aien-cli/src/tools.rs
@@ -11,14 +11,16 @@ use crate::crumbs::{
format_dir_crumb_tui, leave_dir_whisper, load_or_init_dir_crumb, record_directory_crumb,
save_dir_crumb, sniff_dir_crumb, CrumbPurpose,
};
-use crate::safety::{
- contains_unmasked_secret, is_high_risk_command, is_high_risk_path, is_secret_leak_path,
-};
+use crate::safety::{contains_unmasked_secret, is_secret_leak_path};
use crate::ui::{print_safety_prompt, print_tool_done, print_tool_start};
use crate::vault::{redact_secrets, vault_dispatch_tool};
use chrono::Utc;
pub fn dispatch_tool(name: &str, args: &Value) -> Value {
+ dispatch_tool_with(name, args, &crate::approval::GateContext::from_env())
+}
+
+pub fn dispatch_tool_with(name: &str, args: &Value, ctx: &crate::approval::GateContext) -> Value {
let start = Instant::now();
let summary = match name {
"run_command" => args.get("command").and_then(Value::as_str).unwrap_or(""),
@@ -72,26 +74,13 @@ pub fn dispatch_tool(name: &str, args: &Value) -> Value {
_ => "",
};
- // 1. Antigravity-style 9-tier Safety Engine Evaluation
- let safety_engine = crate::safety::SafetyEngine::default_sovereign_engine();
- match safety_engine.evaluate(name, args) {
- crate::safety::SafetyDecision::Deny(reason) => {
- let res =
- serde_json::json!({"error": format!("SECURITY DENIAL [SafetyEngine]: {}", reason)});
- print_tool_start(name, summary);
- print_tool_done(name, start.elapsed().as_millis(), false);
- return res;
- }
- crate::safety::SafetyDecision::AskUser(reason) => {
- println!("{}", format!("⚠️ SAFETY GATE: {}", reason).yellow().bold());
- if !print_safety_prompt(&format!("Tool: '{}' with summary: '{}'", name, summary)) {
- let res = serde_json::json!({"error": "Operation aborted by operator safety gate"});
- print_tool_start(name, summary);
- print_tool_done(name, start.elapsed().as_millis(), false);
- return res;
- }
- }
- crate::safety::SafetyDecision::Allow => {}
+ // 1. The approval gate (sc#667): floors first in every mode, then the
+ // nine-tier SafetyEngine's denials, mode, allowlist, presence, danger,
+ // guardian and person. See approval.rs for the ordering rule.
+ if let Err(res) = gate_tool(name, args, summary, ctx) {
+ print_tool_start(name, summary);
+ print_tool_done(name, start.elapsed().as_millis(), false);
+ return res;
}
print_tool_start(name, summary);
@@ -121,18 +110,9 @@ pub fn dispatch_tool(name: &str, args: &Value) -> Value {
.and_then(Value::as_str)
.unwrap_or(".");
- if is_high_risk_command(cmd) {
- if !print_safety_prompt(cmd) {
- (
- json!({"error": "Operation aborted by user safety gate"}),
- false,
- )
- } else {
- exec_command(cmd, cwd)
- }
- } else {
- exec_command(cmd, cwd)
- }
+ // The approval gate decided before this point (sc#667); a second
+ // prompt here would re-ask the person and override yolo/off.
+ exec_command(cmd, cwd)
}
"view_file" => {
let path = args
@@ -188,17 +168,12 @@ pub fn dispatch_tool(name: &str, args: &Value) -> Value {
json!({"error": format!("REJECTED BY SOVEREIGN VAULT POLICY: {}. Never commit or write plaintext keys into files. Use 'atlas-vault add <KEY>'.", reason)}),
false,
)
- } else if is_high_risk_path(path) {
- if !print_safety_prompt(path) {
- (
- json!({"error": "Write to system path aborted by user safety gate"}),
- false,
- )
- } else {
- exec_write_file(path, content, overwrite, intent, vector)
- }
} else {
- exec_write_file(path, content, overwrite, intent, vector)
+ // System paths were already put to the person by the
+ // approval gate (sc#667); one decision, never two.
+ recorded_write("write_to_file", path, || {
+ exec_write_file(path, content, overwrite, intent, vector)
+ })
}
}
"replace_file_content" | "edit_file" => {
@@ -240,7 +215,9 @@ pub fn dispatch_tool(name: &str, args: &Value) -> Value {
false,
)
} else {
- exec_replace_file(path, target, replacement, intent, vector)
+ recorded_write("replace_file_content", path, || {
+ exec_replace_file(path, target, replacement, intent, vector)
+ })
}
}
"list_dir" | "list_directory" => {
@@ -576,6 +553,91 @@ fn exec_view_file(path: &str, start_line: usize, end_line: usize) -> (Value, boo
}
}
+/// Run the approval gate for one request. `Err` carries the tool result to
+/// hand back to the model when the request does not run.
+fn gate_tool(
+ name: &str,
+ args: &Value,
+ summary: &str,
+ ctx: &crate::approval::GateContext,
+) -> Result<(), Value> {
+ use crate::approval::{after_guardian, decide, Gate, Verdict};
+ let base = crate::safety::SafetyEngine::default_sovereign_engine().evaluate(name, args);
+ let mut verdict = decide(&Gate {
+ tool: name,
+ args,
+ base: &base,
+ mode: ctx.mode,
+ presence: ctx.presence,
+ policy: &ctx.policy,
+ facts: &ctx.facts,
+ guardian_ready: crate::approval::guardian_ready(),
+ });
+ if let Verdict::AskGuardian { reason } = verdict {
+ let answer = ask_guardian(name, summary, &reason);
+ crate::approval::record_guardian(&answer);
+ verdict = after_guardian(&answer, reason);
+ }
+ match verdict {
+ Verdict::Allow { .. } => Ok(()),
+ Verdict::Deny { by, reason } => Err(json!({
+ "error": format!("SECURITY DENIAL [{:?}]: {}", by, reason)
+ })),
+ Verdict::AskGuardian { .. } => unreachable!("guardian answered above"),
+ Verdict::AskPerson { reason } => {
+ println!("{}", format!("⚠️ SAFETY GATE: {}", reason).yellow().bold());
+ if print_safety_prompt(&format!("Tool: '{}' with summary: '{}'", name, summary)) {
+ Ok(())
+ } else {
+ Err(json!({"error": "Operation aborted by operator safety gate"}))
+ }
+ }
+ }
+}
+
+/// Ask the guardian model (smart mode). Any transport failure, timeout or
+/// unparseable reply is `Failed`, which escalates to the person and counts
+/// against the breaker.
+fn ask_guardian(name: &str, summary: &str, reason: &str) -> crate::approval::GuardianAnswer {
+ use crate::approval::GuardianAnswer;
+ let Ok(handle) = tokio::runtime::Handle::try_current() else {
+ return GuardianAnswer::Failed("no async runtime for the guardian".into());
+ };
+ let messages = vec![
+ json!({"role": "system", "content": crate::approval::GUARDIAN_PROMPT}),
+ json!({"role": "user", "content": format!(
+ "tool: {name}\nrequest: {}\nflagged because: {reason}",
+ redact_secrets(summary)
+ )}),
+ ];
+ let client = crate::client::ChatClient::new(None, None);
+ let reply = tokio::task::block_in_place(|| {
+ handle.block_on(client.stream_turn_with_limit(&messages, false, 32))
+ });
+ match reply {
+ Ok(text) => crate::approval::parse_guardian_reply(&text),
+ Err(err) => GuardianAnswer::Failed(err),
+ }
+}
+
+/// Run a file tool's write as a recorded agent write (sc#667): prior content
+/// kept, one ledger line after. Without an active chat session this is a
+/// plain call.
+fn recorded_write(tool: &str, path: &str, write: impl FnOnce() -> (Value, bool)) -> (Value, bool) {
+ let home = crate::platform::PlatformContext::detect().home_dir;
+ let cwd = std::env::current_dir().unwrap_or_else(|_| home.clone());
+ let abs = crate::approval::lexical_abs(path, &home, &cwd);
+ match crate::checkpoint::record_agent_write(&abs, tool, write) {
+ Ok(((mut res, ok), warning)) => {
+ if let (Some(w), Some(obj)) = (warning, res.as_object_mut()) {
+ obj.insert("checkpoint_warning".into(), json!(w));
+ }
+ (res, ok)
+ }
+ Err(refusal) => (json!({"error": refusal}), false),
+ }
+}
+
fn exec_write_file(
path: &str,
content: &str,
@@ -1215,4 +1277,113 @@ mod tests {
let _ = std::fs::remove_file(path);
});
}
+
+ fn gate_ctx(
+ mode: crate::approval::ApprovalMode,
+ deny: &[&str],
+ ) -> crate::approval::GateContext {
+ use crate::approval::*;
+ GateContext {
+ mode,
+ presence: Presence::Person,
+ policy: CompiledPolicy::compile(&OperatorPolicy {
+ mode: None,
+ deny: deny.iter().map(|s| s.to_string()).collect(),
+ allow: Vec::new(),
+ }),
+ facts: RuntimeFacts {
+ protected: Vec::new(),
+ home: std::path::PathBuf::from("/tmp"),
+ cwd: std::path::PathBuf::from("/tmp"),
+ },
+ }
+ }
+
+ /// sc#667 acceptance through the real dispatcher: an operator deny
+ /// pattern stops a real command in every mode; without the pattern the
+ /// same command runs (negative control).
+ #[test]
+ fn operator_deny_pattern_blocks_a_real_command_in_every_mode() {
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ runtime.block_on(async {
+ for mode in crate::approval::ALL_MODES {
+ let dir = tempfile::Builder::new()
+ .prefix("aien-sc667-deny-")
+ .tempdir_in("/tmp")
+ .unwrap();
+ let marker = dir.path().join("marker");
+ let args = json!({
+ "command": format!("touch {}", marker.display()),
+ "cwd": dir.path().to_string_lossy(),
+ });
+ let res =
+ dispatch_tool_with("run_command", &args, &gate_ctx(mode, &[r"touch .*marker"]));
+ let err = res.get("error").and_then(Value::as_str).unwrap_or("");
+ assert!(err.contains("OperatorDeny"), "{mode:?}: {res}");
+ assert!(!marker.exists(), "{mode:?}: command ran despite the floor");
+
+ let res = dispatch_tool_with("run_command", &args, &gate_ctx(mode, &[]));
+ assert!(res.get("error").is_none(), "{mode:?}: {res}");
+ assert!(marker.exists(), "{mode:?}: control command did not run");
+ }
+ });
+ }
+
+ /// sc#667 acceptance through the real dispatcher: agent writes go to the
+ /// ledger; a rollback after mixed operator and agent edits restores only
+ /// the agent's files.
+ #[test]
+ fn rollback_through_the_dispatcher_spares_operator_edits() {
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ runtime.block_on(async {
+ let home = tempfile::tempdir().unwrap();
+ let work = tempfile::Builder::new()
+ .prefix("aien-sc667-work-")
+ .tempdir_in("/tmp")
+ .unwrap();
+ let work = work.path().canonicalize().unwrap();
+ let agent_file = work.join("agent.txt");
+ let created = work.join("created.txt");
+ let operator_file = work.join("operator.txt");
+ std::fs::write(&agent_file, "original").unwrap();
+ std::fs::write(&operator_file, "operator v0").unwrap();
+
+ let session = format!("sc667-dispatch-{}", std::process::id());
+ crate::checkpoint::start_scoped_session(home.path(), &session, work.clone()).unwrap();
+ crate::checkpoint::begin_turn();
+ let ctx = gate_ctx(crate::approval::ApprovalMode::Manual, &[]);
+ for (p, text) in [(&agent_file, "agent edit"), (&created, "agent new")] {
+ let args = json!({"path": p.to_string_lossy(), "content": text, "overwrite": true});
+ let res = dispatch_tool_with("write_to_file", &args, &ctx);
+ assert!(res.get("error").is_none(), "{res}");
+ }
+ let args = json!({
+ "path": agent_file.to_string_lossy(),
+ "target": "edit",
+ "replacement": "edit twice",
+ });
+ let res = dispatch_tool_with("replace_file_content", &args, &ctx);
+ assert!(res.get("error").is_none(), "{res}");
+ crate::checkpoint::stop_session();
+
+ std::fs::write(&operator_file, "operator v1").unwrap();
+
+ let report = crate::checkpoint::rollback(home.path(), Some(1), Some(&session)).unwrap();
+ assert_eq!(std::fs::read_to_string(&agent_file).unwrap(), "original");
+ assert!(!created.exists());
+ assert_eq!(
+ std::fs::read_to_string(&operator_file).unwrap(),
+ "operator v1"
+ );
+ assert!(report
+ .spared
+ .contains(&operator_file.to_string_lossy().into_owned()));
+ });
+ }
}