Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/9a7a9717e92c00a8 # aien-sovereign-core-mv 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#303 (code only) closed derived `9a7a9717e92c00a8` #303 Imported from GitHub aien-dev/aien-sovereign-core-mv#303 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `37039ec0c6c25e2c2660db88b822225e70457d85` · Head `6ece4850b01fe4cbf3d717d97dec5ebc414af7d0` ### Apply it ``` git checkout -b patch-9a7a9717e92c00a8 37039ec0c6c25e2c2660db88b822225e70457d85 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/9a7a9717e92c00a8.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 303 6ece4850b01fe4cbf3d717d97dec5ebc414af7d0 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":303,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/303","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:44Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index 02035558..e5303da7 100644 --- a/.crumb +++ b/.crumb @@ -77,14 +77,14 @@ } ], "children_root": "sha256:c5269f93385287c09996ff41f0247f72de9237a2317f47c94c51273d6a0acef1", - "compiled_at": "2026-10-08T01:03:32Z", + "compiled_at": "2026-10-08T01:28:53Z", "compiler": "crumb-compile/1", - "digest": "sha256:05a58e3c29a88c25f0cc5a31f5c1dccec1f79342ce811f9ba19e4b02ad3a0c81", + "digest": "sha256:ea64f7c95d6eca019466b3b261437d356abeb107239c8122ad75ab3066858305", "evidence_files": 186, "evidence_root": "sha256:fbe849218d18dc4b21a74410fdd8f7d98431a1d0123a0c69264386f770da4db4", - "files": 1332, - "generated_at_commit": "65edba04eb654df6123345163631cacae780d7e6", - "source_tree": "sha256:791727683d76080cfff2b5c6b8946ca8ab870f8e80433815c0eee897e700a0fb" + "files": 1339, + "generated_at_commit": "7eaaf015cbb5c7738be049b18af482b7e834905f", + "source_tree": "sha256:c78cf9015d54e19fb3b4eac8d872b684b0f7a2cab97ef8e607af4cd04caf1483" } }, "history": [], diff --git a/Cargo.lock b/Cargo.lock index 98f1095c..7559144a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -44,6 +44,19 @@ dependencies = [ "tempfile", ] +[[package]] +name = "aien-allen-memory" +version = "0.1.0" +dependencies = [ + "aien-allen", + "aien-allen-memory", + "ring", + "serde", + "serde_json", + "sha2 0.10.9", + "tempfile", +] + [[package]] name = "aien-allen-profile" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 6207d830..8a1019ba 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -43,6 +43,7 @@ members = [ "crates/aien-dual-observation", "crates/aien-allen", "crates/aien-allen-profile", + "crates/aien-allen-memory", "tools/aien-test", "crates/aien-drive", ] diff --git a/crates/aien-allen-memory/.crumb b/crates/aien-allen-memory/.crumb new file mode 100644 index 00000000..1dee7b1a --- /dev/null +++ b/crates/aien-allen-memory/.crumb @@ -0,0 +1,19 @@ +{ + "extensions": { + "generated": { + "children": [], + "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "compiled_at": "2026-10-08T01:13:33Z", + "compiler": "crumb-compile/1", + "digest": "sha256:6c37f78b1de14405138ced998758a131ea3d061f11ac588faaa4f343a6417dee", + "evidence_files": 0, + "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "files": 7, + "generated_at_commit": "a5bf83850bd2661d926085d2f434440e1dcc2fc1", + "source_tree": "sha256:45e8c817ff29f2a37b008750bd40bdd24a30b54712b5b7e90734d05ac7ccaddf" + } + }, + "name": "aien-allen-memory", + "purpose": "ALLEN scoped memory store: scopes enforced at recall, inspect/correct/export, key-destroying forget, host goal records (arch#159).", + "schema_version": "1.0.0" +} diff --git a/crates/aien-allen-memory/Cargo.toml b/crates/aien-allen-memory/Cargo.toml new file mode 100644 index 00000000..fa484216 --- /dev/null +++ b/crates/aien-allen-memory/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "aien-allen-memory" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true +description = "ALLEN scoped memory store: scopes enforced at recall, inspect/correct/export, key-destroying forget, host goal records (arch#159)" + +[dependencies] +aien-allen = { path = "../aien-allen" } +ring = "0.17" +sha2 = "0.10" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" + +[features] +# Test seam: lets a test stop a write at a named step (simulated crash). +# Enabled only by the dev-dependency below, never by a daemon build. +fault-injection = [] + +[dev-dependencies] +tempfile = "3.10" +aien-allen-memory = { path = ".", features = ["fault-injection"] } diff --git a/crates/aien-allen-memory/RETENTION.md b/crates/aien-allen-memory/RETENTION.md new file mode 100644 index 00000000..89b8fb32 --- /dev/null +++ b/crates/aien-allen-memory/RETENTION.md @@ -0,0 +1,108 @@ +# What forget does, and what it does not do + +Crate `aien-allen-memory`, tracking aien-dev/aien-architecture#159. + +## The claim, stated narrowly + +After `forget`, the item is **unreadable in the memory store**. That is the whole +claim. It is not a claim that the content is erased from the machine, from +other systems, or from anything that already received it. + +## How it works + +Each item version is encrypted (ChaCha20-Poly1305) under its own random 32-byte +key. The ciphertext lives in `log/` and stays there. The key lives in +`keys/-v.key` (file mode 0600, folder 0700). + +Forget runs in this order: + +1. Write an intent marker in `pending/` (item id or scope only). +2. Overwrite each key file with zeros, fsync, delete it, fsync the keys folder. +3. Append a Forget record to `log/` (item id, scope, time; no content). +4. Remove the marker. + +A crash between steps leaves the item unreadable to this API (a marker exists, so +recall skips it). `inspect` reports `forgotten (key removal pending)` while the +key file is still there and `forgotten (key missing, record pending)` once it is +gone; after the record is appended it reports `forgotten`. A crash after step 1 +but before step 2 finishes leaves the key on disk until the next open completes +steps 2 to 4. A missing key on an item nobody asked to forget is +reported as `Unresolved: key missing`, never as live and never as forgotten. + +A correction destroys the superseded version's key the same way. + +## What forget keeps + +- The Forget record keeps metadata: item id, scope, time. It never holds content. +- The Put and Correct records keep their ciphertext. Without the key it cannot + be read, but it is still on disk. + +## What forget does NOT reach + +- Daemon logs and transcripts. +- The daemon generation record (the sovereign-core #301 ledger records of model turns). +- The agent chat archive. +- Persona and compose task reports. +- Model context that was already sent: a model that saw the text before the + forget keeps whatever it kept. +- Cortex entries. +- Any copy of the plaintext the owner made, including `export` output. +- Backups or snapshots that include `keys/` taken before the forget. +- Filesystem journal blocks or SSD remapped (wear-levelled) blocks that may still + hold the old key bytes. Zeroing a file does not promise the physical cells are + overwritten. + +## Restore and backups + +- A restore from a backup taken AFTER the forget cannot bring the content back: + the key was already gone. +- A backup taken BEFORE the forget that includes `keys/` CAN bring back the key. + Recommendation: back up `log/` only and leave `keys/` out, or re-forget after + the restore. The store helps: every open runs `reapply_forgets()`, which + destroys the key of any item that has a Forget record, and of any superseded + version. This only works while the log is intact and newer than the forget. + A restore that also rolls `log/` back to before the forget removes the Forget + record, so nothing remembers it; this crate cannot detect that (NOT_PROVED). +- Keys are not wrapped by a master key. Whoever can read `keys/` and `log/` can + read live content. The protection is scope separation in the API and access + to the folder, not secrecy from the machine's owner. + +## Integrity limits + +- The hash chain is unkeyed. Anyone who can write the store folder as the same + user can rebuild a valid chain, and removing the newest records (tail + truncation) is not detected. The chain catches accidents and clumsy edits, not + a same-user attacker. Encryption binds each ciphertext to agent, root, item, + version, scope and kind, so moving or relabelling a ciphertext is refused, but + a writer who also holds the key can forge content. +- Key files are opened without following symlinks and a symlinked key or folder + is refused; the keys folder is tightened to 0700 on open. +- Open also sweeps keys that no record refers to (leftovers of a crashed write) + and stale temporary files. This assumes a single writer. +- Changing or forgetting an item needs a grant for the item's scope (or the + owner-facing `InspectAll`). + +## Scopes + +`personal`, `work`, `project:`. Recall takes a `ScopeGrant` for exactly one +scope, built by the daemon from the request's authorised context. A scope named +inside a query string, a model reply or a task is only search text and never +widens a grant. `InspectAll` exists for the owner-facing inspect command. + +## Standing goals + +Items of kind `goal` are "host goal records, not subject intents". The host never +writes SubjectState. A real subject intent needs an aienos ADR 0018 amendment. + +## Other limits + +- Writers take an exclusive lock (flock on `lock` in the store folder) per + operation. Only an open that gets the lock sweeps orphan keys, removes stale + temp files and finishes pending forgets; an open that does not (or + `open_read_only`) changes nothing. flock covers processes on one machine, not + network filesystems. Single writer per store is otherwise assumed. A second writer racing the same record + number loses cleanly (`Conflict`); key files of a crashed put may be left + behind and are harmless (no ciphertext refers to them). +- The store needs a filesystem that supports hard links. +- Timestamps are informational. Nothing orders or trusts them. +- Not wired into the daemon or CLI yet. diff --git a/crates/aien-allen-memory/src/lib.rs b/crates/aien-allen-memory/src/lib.rs new file mode 100644 index 00000000..4d4e97ec --- /dev/null +++ b/crates/aien-allen-memory/src/lib.rs @@ -0,0 +1,23 @@ +//! ALLEN scoped memory store (aien-architecture#159). +//! +//! A SEPARATE record store `.allen-memory/`, bound to the engaged ALLEN +//! identity (`aien_allen::Resolved`: agent + root; no second identity exists +//! here). Content is encrypted per item version; `forget` destroys the key. +//! +//! ENFORCED in code: scope separation at recall (a [`ScopeGrant`] names exactly +//! one scope and there is no scope-string path), the identity binding, +//! crash-safe appends, key destruction order, refusal of damaged or foreign +//! stores. NOT claimed: erasure everywhere. See RETENTION.md. +//! +//! Standing goals here are "host goal records, not subject intents": the host +//! never writes SubjectState (that needs an aienos ADR 0018 amendment). +pub mod refusal; +pub mod schema; +pub mod store; + +pub use refusal::MemoryRefusal; +pub use schema::{Kind, Scope, GOAL_LABEL, MEMORY_SCHEMA}; +pub use store::{ + memory_dir, Authority, ForgetTarget, GoalList, GoalView, InspectAll, ItemStatus, ItemView, + Memory, Recall, RecallLimits, ScopeGrant, Step, +}; diff --git a/crates/aien-allen-memory/src/refusal.rs b/crates/aien-allen-memory/src/refusal.rs new file mode 100644 index 00000000..f26c3d57 --- /dev/null +++ b/crates/aien-allen-memory/src/refusal.rs @@ -0,0 +1,77 @@ +//! Every way a memory operation can say no, in plain words. +use std::fmt; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum MemoryRefusal { + /// ALLEN is not engaged: there is no identity to attach memory to. + NotEngaged, + /// A stored record names another agent or root than the engaged identity. + ForeignMemory(String), + /// A stored file is damaged, has an unknown schema or field, is oversize, or breaks the chain. + Damaged(String), + /// A requested value is not allowed. + Invalid(String), + UnknownItem(String), + /// The item was forgotten (or a forget is pending); it cannot be changed. + ItemForgotten(String), + NotAGoal(String), + /// The caller's grant is for a different scope than the item's. + ScopeMismatch(String), + /// Nothing matched a forget request. + NothingToForget, + /// The item's key is missing or damaged, so its content cannot be read. + KeyUnavailable(String), + /// The ciphertext or the record data it is bound to was changed. + Tampered(String), + /// Another writer appended first. + Conflict, + Io(String), + /// Test seam only (feature `fault-injection`): the write was stopped on purpose. + Crashed(String), +} + +impl MemoryRefusal { + pub fn code(&self) -> &'static str { + use MemoryRefusal::*; + match self { + NotEngaged => "not_engaged", + ForeignMemory(_) => "foreign_memory", + Damaged(_) => "damaged", + Invalid(_) => "invalid", + UnknownItem(_) => "unknown_item", + ItemForgotten(_) => "item_forgotten", + NotAGoal(_) => "not_a_goal", + ScopeMismatch(_) => "scope_mismatch", + NothingToForget => "nothing_to_forget", + KeyUnavailable(_) => "key_unavailable", + Tampered(_) => "tampered", + Conflict => "conflict", + Io(_) => "io", + Crashed(_) => "crashed", + } + } +} + +impl fmt::Display for MemoryRefusal { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + use MemoryRefusal::*; + match self { + NotEngaged => write!(f, "ALLEN is not engaged on this machine, so there is no identity to attach memory to. Nothing was changed."), + ForeignMemory(w) => write!(f, "The saved memory belongs to a different ALLEN identity ({w}). It was not used or changed."), + Damaged(w) => write!(f, "The saved memory is damaged or not understood ({w}). It was not replaced; ask the operator to inspect the memory folder."), + Invalid(w) => write!(f, "Not allowed: {w}. Nothing was changed."), + UnknownItem(i) => write!(f, "There is no memory item {i}. Nothing was changed."), + ItemForgotten(i) => write!(f, "Item {i} was forgotten (or is being forgotten) and cannot be changed."), + NotAGoal(i) => write!(f, "Item {i} is not a goal. Nothing was changed."), + ScopeMismatch(i) => write!(f, "Your access covers a different scope than {i}. Nothing was changed."), + NothingToForget => write!(f, "No live memory matched. Nothing was forgotten."), + KeyUnavailable(i) => write!(f, "The key for item {i} is missing or damaged, so its content cannot be read."), + Tampered(i) => write!(f, "Item {i} failed its integrity check (ciphertext or bound data changed). It was not used."), + Conflict => write!(f, "Another writer changed the memory first. Nothing was changed; try again."), + Io(w) => write!(f, "Could not read or write the memory store: {w}."), + Crashed(w) => write!(f, "write stopped on purpose (test): {w}"), + } + } +} + +impl std::error::Error for MemoryRefusal {} diff --git a/crates/aien-allen-memory/src/schema.rs b/crates/aien-allen-memory/src/schema.rs new file mode 100644 index 00000000..0e5a65c3 --- /dev/null +++ b/crates/aien-allen-memory/src/schema.rs @@ -0,0 +1,264 @@ +//! Schema `aien.allen.memory/1`. Every struct read from disk denies unknown +//! fields. The log holds ciphertext only; plaintext never reaches `log/`. +use crate::refusal::MemoryRefusal as R; +use serde::{Deserialize, Serialize}; +use std::fmt; + +pub const MEMORY_SCHEMA: &str = "aien.allen.memory/1"; +/// Printed with every standing goal. A host goal is not a SubjectState intent. +pub const GOAL_LABEL: &str = "host goal record, not a subject intent"; +pub const MAX_TEXT_BYTES: usize = 2048; +pub const MAX_RECORD_BYTES: u64 = 8 * 1024; +pub const MAX_RECORDS: u64 = 100_000; +pub const GENESIS_PREV: &str = "0000000000000000000000000000000000000000000000000000000000000000"; +pub const TAG_LEN: usize = 16; +pub const NONCE_LEN: usize = 12; + +/// `personal`, `work`, or `project:` with name `^[a-z0-9_.-]{1,48}$`. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(try_from = "String", into = "String")] +pub enum Scope { + Personal, + Work, + Project(String), +} + +impl Scope { + pub fn parse(s: &str) -> Result { + match s { + "personal" => Ok(Scope::Personal), + "work" => Ok(Scope::Work), + _ => match s.strip_prefix("project:") { + Some(n) + if (1..=48).contains(&n.len()) + && n.bytes().all(|b| { + b.is_ascii_lowercase() + || b.is_ascii_digit() + || b == b'_' + || b == b'.' + || b == b'-' + }) => + { + Ok(Scope::Project(n.to_string())) + } + _ => Err(R::Invalid(format!( + "scope \"{s}\" (use personal, work or project: with name of 1 to 48 of a-z 0-9 _ . -)" + ))), + }, + } + } +} + +impl fmt::Display for Scope { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Scope::Personal => f.write_str("personal"), + Scope::Work => f.write_str("work"), + Scope::Project(n) => write!(f, "project:{n}"), + } + } +} + +impl TryFrom for Scope { + type Error = String; + fn try_from(s: String) -> Result { + Scope::parse(&s).map_err(|e| e.to_string()) + } +} + +impl From for String { + fn from(s: Scope) -> String { + s.to_string() + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Kind { + Fact, + Preference, + Goal, +} + +impl Kind { + pub fn as_str(self) -> &'static str { + match self { + Kind::Fact => "fact", + Kind::Preference => "preference", + Kind::Goal => "goal", + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Record { + pub schema: String, + pub agent: String, + pub root: String, + pub seq: u64, + pub prev_sha256: String, + pub at: String, + pub op: Op, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)] +pub enum Op { + Put { + item: String, + scope: Scope, + kind: Kind, + version: u32, + ciphertext: String, + nonce: String, + key_id: String, + }, + Correct { + item: String, + supersedes_version: u32, + version: u32, + ciphertext: String, + nonce: String, + key_id: String, + }, + /// Metadata only: item id and scope. The content key is already destroyed. + ForgetItem { + item: String, + scope: Scope, + }, + ForgetScope { + scope: Scope, + }, + GoalClose { + item: String, + }, +} + +pub fn is_hex(s: &str, len: Option) -> bool { + len.is_none_or(|l| s.len() == l) + && !s.is_empty() + && s.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +pub fn unhex(s: &str) -> Option> { + if !s.len().is_multiple_of(2) || !s.is_ascii() { + return None; + } + (0..s.len() / 2) + .map(|i| u8::from_str_radix(&s[2 * i..2 * i + 2], 16).ok()) + .collect() +} + +pub fn key_id(item: &str, version: u32) -> String { + format!("{item}-v{version}") +} + +fn check_blob(item: &str, version: u32, ct: &str, nonce: &str, kid: &str) -> Result<(), String> { + if !is_hex(item, Some(32)) { + return Err("item id is not 32 hex characters".into()); + } + if version == 0 { + return Err("version 0".into()); + } + if !is_hex(nonce, Some(NONCE_LEN * 2)) { + return Err("bad nonce".into()); + } + if !is_hex(ct, None) + || !ct.len().is_multiple_of(2) + || ct.len() < TAG_LEN * 2 + || ct.len() > (MAX_TEXT_BYTES + TAG_LEN) * 2 + { + return Err("bad ciphertext size".into()); + } + if kid != key_id(item, version) { + return Err("key_id does not match item and version".into()); + } + Ok(()) +} + +impl Record { + pub fn validate(&self) -> Result<(), String> { + if self.schema != MEMORY_SCHEMA { + return Err(format!("unknown schema \"{}\"", self.schema)); + } + if !is_hex(&self.agent, Some(64)) || !is_hex(&self.root, Some(64)) { + return Err("agent or root is not 64 hex characters".into()); + } + if !is_hex(&self.prev_sha256, Some(64)) { + return Err("prev_sha256 is not 64 hex characters".into()); + } + if self.at.len() != 20 || !self.at.is_ascii() || self.seq == 0 { + return Err("bad timestamp or sequence".into()); + } + match &self.op { + Op::Put { + item, + version, + ciphertext, + nonce, + key_id, + .. + } => { + if *version != 1 { + return Err("put must be version 1".into()); + } + check_blob(item, *version, ciphertext, nonce, key_id) + } + Op::Correct { + item, + supersedes_version, + version, + ciphertext, + nonce, + key_id, + } => { + if *supersedes_version == 0 || *version != supersedes_version.saturating_add(1) { + return Err("correct must supersede the previous version by one".into()); + } + check_blob(item, *version, ciphertext, nonce, key_id) + } + Op::ForgetItem { item, .. } | Op::GoalClose { item } => { + if is_hex(item, Some(32)) { + Ok(()) + } else { + Err("item id is not 32 hex characters".into()) + } + } + Op::ForgetScope { .. } => Ok(()), + } + } +} + +/// The intent written before keys are destroyed (see RETENTION.md). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "snake_case")] +pub enum Marker { + Item(String), + Scope(Scope), +} + +/// UTC `YYYY-MM-DDTHH:MM:SSZ` from the system clock (informational only). +pub fn now_utc() -> String { + let secs = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0); + let (days, rem) = (secs.div_euclid(86400), secs.rem_euclid(86400)); + let z = days + 719468; + let era = z.div_euclid(146097); + let doe = z.rem_euclid(146097); + let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + i64::from(m <= 2); + format!( + "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", + rem / 3600, + rem % 3600 / 60, + rem % 60 + ) +} diff --git a/crates/aien-allen-memory/src/store.rs b/crates/aien-allen-memory/src/store.rs new file mode 100644 index 00000000..d8848577 --- /dev/null +++ b/crates/aien-allen-memory/src/store.rs @@ -0,0 +1,1333 @@ +//! The store `.allen-memory/`: +//! log/ `l<20 digits>.json` immutable hash-chained records (ciphertext only) +//! keys/ `-v.key`, 32 random bytes, mode 0600 (dir 0700) +//! pending/ forget intent markers (item id or scope only) +//! Append order: temp file, fsync, `hard_link` (fails if the number exists: +//! a lost race), fsync dir, remove temp. A crash leaves the old head or the +//! new head. Anything unexpected in `log/` is a refusal, never skipped. +use crate::refusal::MemoryRefusal as R; +use crate::schema::*; +use aien_allen::{hex, Resolved}; +use ring::aead::{Aad, LessSafeKey, Nonce, UnboundKey, CHACHA20_POLY1305}; +use ring::rand::{SecureRandom, SystemRandom}; +use serde::Serialize; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// `.allen-memory`, beside `.allen-binding`. +pub fn memory_dir(home: &Path) -> PathBuf { + let mut n = home.as_os_str().to_owned(); + n.push(".allen-memory"); + PathBuf::from(n) +} + +/// Named points in a write, for crash injection (feature `fault-injection`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Step { + KeyWritten, + TempCreated, + TempWritten, + TempSynced, + Linked, + DirSynced, + TempRemoved, + MarkerWritten, + KeyZeroed, + KeyUnlinked, + KeysDestroyed, + ForgetRecorded, + MarkerRemoved, + SupersededKeyDestroyed, +} + +#[cfg(feature = "fault-injection")] +type Hook = std::sync::Arc bool + Send + Sync>; + +/// The right to read ONE scope. Built by the daemon from the request's +/// authorised context. There is no constructor from text found in a query, +/// a model reply or a task, and no "all" value. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ScopeGrant { + scope: Scope, +} + +impl ScopeGrant { + pub fn new(scope: Scope) -> ScopeGrant { + ScopeGrant { scope } + } + pub fn scope(&self) -> &Scope { + &self.scope + } +} + +/// Owner-facing inspect across all scopes. Only `inspect_all` and +/// `goals_all` take it; recall and export never do. (Type-level discipline: +/// the crate cannot stop a caller from constructing it. UNVERIFIED beyond that.) +#[derive(Debug, Clone, Copy)] +pub struct InspectAll(()); + +/// Who is asking to change an item: a grant for one scope, or the owner. +#[derive(Clone, Copy)] +pub enum Authority<'a> { + Scope(&'a ScopeGrant), + Owner(&'a InspectAll), +} + +impl<'a> From<&'a ScopeGrant> for Authority<'a> { + fn from(g: &'a ScopeGrant) -> Self { + Authority::Scope(g) + } +} + +impl<'a> From<&'a InspectAll> for Authority<'a> { + fn from(g: &'a InspectAll) -> Self { + Authority::Owner(g) + } +} + +impl Authority<'_> { + fn check(&self, item: &str, scope: &Scope) -> Result<(), R> { + match self { + Authority::Owner(_) => Ok(()), + Authority::Scope(g) if g.scope == *scope => Ok(()), + Authority::Scope(_) => Err(R::ScopeMismatch(item.to_string())), + } + } +} + +impl InspectAll { + pub fn owner() -> InspectAll { + InspectAll(()) + } +} + +#[derive(Debug, Clone, Copy)] +pub struct RecallLimits { + pub max_items: usize, + pub max_bytes: usize, +} + +impl Default for RecallLimits { + fn default() -> Self { + RecallLimits { + max_items: 16, + max_bytes: 4096, + } + } +} + +pub enum ForgetTarget { + Item(String), + Scope(Scope), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ItemStatus { + Live, + Corrected, + Closed, + Forgotten, + /// Intent recorded, record not yet appended. `key_missing` says whether the key is already gone. + ForgottenPending { + key_missing: bool, + }, + Unresolved(String), +} + +impl ItemStatus { + pub fn text(&self) -> String { + match self { + ItemStatus::Live => "live".into(), + ItemStatus::Corrected => "corrected".into(), + ItemStatus::Closed => "closed".into(), + ItemStatus::Forgotten => "forgotten".into(), + ItemStatus::ForgottenPending { key_missing: true } => { + "forgotten (key missing, record pending)".into() + } + ItemStatus::ForgottenPending { key_missing: false } => { + "forgotten (key removal pending)".into() + } + ItemStatus::Unresolved(w) => format!("Unresolved: {w}"), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct ItemView { + pub item: String, + pub scope: String, + pub kind: Kind, + pub version: u32, + pub created: String, + pub state: String, + /// Present only for live and closed items. Forgotten items never show content. + pub text: Option, + /// Set on goals: "host goal record, not a subject intent". + pub label: Option<&'static str>, + #[serde(skip)] + pub status: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Recall { + pub scope: Scope, + pub items: Vec, + /// Items left out because of the count or byte limit. + pub omitted: usize, + /// Items in this scope whose key is missing (never treated as live). + pub unresolved: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct GoalView { + pub item: String, + pub scope: String, + pub text: String, + pub created: String, + /// `open` or `closed`. + pub state: &'static str, + pub label: &'static str, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct GoalList { + pub label: &'static str, + pub goals: Vec, +} + +struct Ver { + version: u32, + at: String, + ciphertext: Vec, + nonce: [u8; NONCE_LEN], +} + +struct Item { + scope: Scope, + kind: Kind, + created_seq: u64, + versions: Vec, + forgotten: bool, + closed: bool, +} + +impl Item { + fn current(&self) -> &Ver { + self.versions.last().expect("an item has a version") + } +} + +struct Replay { + items: BTreeMap, + head_seq: u64, + head_sha: String, +} + +pub struct Memory { + read_only: bool, + dir: PathBuf, + agent: [u8; 32], + root: [u8; 32], + #[cfg(feature = "fault-injection")] + hook: Option, +} + +fn io(what: &str, e: std::io::Error) -> R { + R::Io(format!("{what}: {e}")) +} + +fn sha_hex(b: &[u8]) -> String { + hex(&Sha256::digest(b)) +} + +fn log_name(n: u64) -> String { + format!("l{n:020}.json") +} + +fn parse_log_name(s: &str) -> Option { + let d = s.strip_prefix('l')?.strip_suffix(".json")?; + if d.len() != 20 || !d.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + d.parse().ok().filter(|n| *n >= 1) +} + +fn sync_dir(p: &Path) -> Result<(), R> { + std::fs::File::open(p) + .and_then(|d| d.sync_all()) + .map_err(|e| io("sync dir", e)) +} + +fn rand_hex(n: usize) -> Result { + let mut b = vec![0u8; n]; + SystemRandom::new() + .fill(&mut b) + .map_err(|_| R::Io("random source failed".into()))?; + Ok(hex(&b)) +} + +impl Memory { + /// Open the store for the engaged identity. `None` (not engaged) is refused. + /// Verifies the whole log, finishes any pending forget, and re-destroys keys + /// of forgotten or superseded versions (see [`Memory::reapply_forgets`]). + pub fn open(home: &Path, engaged: Option<&Resolved>) -> Result { + Memory::at(memory_dir(home), engaged) + } + + pub fn at(dir: PathBuf, engaged: Option<&Resolved>) -> Result { + let r = engaged.ok_or(R::NotEngaged)?; + let m = Memory { + read_only: false, + dir, + agent: r.agent, + root: r.root, + #[cfg(feature = "fault-injection")] + hook: None, + }; + m.recover()?; + Ok(m) + } + + /// Reopen with a crash hook installed AFTER recovery (test seam). + #[cfg(feature = "fault-injection")] + pub fn with_fault_hook(mut self, hook: Hook) -> Memory { + self.hook = Some(hook); + self + } + + /// Open without recovery, sweeping or writing: safe beside a running writer. + pub fn open_read_only(home: &Path, engaged: Option<&Resolved>) -> Result { + let r = engaged.ok_or(R::NotEngaged)?; + let m = Memory { + read_only: true, + dir: memory_dir(home), + agent: r.agent, + root: r.root, + #[cfg(feature = "fault-injection")] + hook: None, + }; + m.check_layout()?; + m.replay()?; + Ok(m) + } + + /// Exclusive writer lock (flock on `/lock`), held until dropped. + fn lock(&self) -> Result { + if self.read_only { + return Err(R::Invalid("this memory was opened read-only".into())); + } + let f = self.lock_file()?; + f.lock().map_err(|e| io("lock", e))?; + Ok(f) + } + + fn lock_file(&self) -> Result { + std::fs::create_dir_all(&self.dir).map_err(|e| io("create store folder", e))?; + std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(self.dir.join("lock")) + .map_err(|e| io("open lock", e)) + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + fn after(&self, step: Step) -> Result<(), R> { + #[cfg(feature = "fault-injection")] + if let Some(h) = &self.hook { + if h(step) { + return Err(R::Crashed(format!("{step:?}"))); + } + } + let _ = step; + Ok(()) + } + + fn log_dir(&self) -> PathBuf { + self.dir.join("log") + } + fn keys_dir(&self) -> PathBuf { + self.dir.join("keys") + } + fn pending_dir(&self) -> PathBuf { + self.dir.join("pending") + } + fn key_path(&self, kid: &str) -> PathBuf { + self.keys_dir().join(format!("{kid}.key")) + } + + // ---------- reading the log ---------- + + fn replay(&self) -> Result { + let mut rp = Replay { + items: BTreeMap::new(), + head_seq: 0, + head_sha: GENESIS_PREV.to_string(), + }; + let rd = match std::fs::read_dir(self.log_dir()) { + Ok(rd) => rd, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(rp), + Err(e) => return Err(io("read memory log", e)), + }; + let mut nums = Vec::new(); + for ent in rd { + let ent = ent.map_err(|e| io("read memory log", e))?; + let name = ent.file_name().to_string_lossy().into_owned(); + if name.starts_with(".tmp-") { + continue; // a crashed writer's leftover + } + match parse_log_name(&name) { + Some(n) => nums.push(n), + None => return Err(R::Damaged(format!("unexpected file \"{name}\""))), + } + } + nums.sort_unstable(); + if nums.len() as u64 > MAX_RECORDS { + return Err(R::Damaged("too many records".into())); + } + for (i, n) in nums.iter().enumerate() { + if *n != i as u64 + 1 { + return Err(R::Damaged(format!( + "records are not contiguous (found {n} where {} was expected)", + i + 1 + ))); + } + } + let (agent, root) = (hex(&self.agent), hex(&self.root)); + for n in nums { + let path = self.log_dir().join(log_name(n)); + let meta = std::fs::metadata(&path).map_err(|e| io("stat record", e))?; + if meta.len() > MAX_RECORD_BYTES { + return Err(R::Damaged(format!("record {n} is {} bytes", meta.len()))); + } + let bytes = std::fs::read(&path).map_err(|e| io("read record", e))?; + let rec: Record = serde_json::from_slice(&bytes) + .map_err(|e| R::Damaged(format!("record {n}: {e}")))?; + rec.validate() + .map_err(|e| R::Damaged(format!("record {n}: {e}")))?; + if rec.agent != agent || rec.root != root { + return Err(R::ForeignMemory(format!( + "record {n} names agent {}", + &rec.agent[..8] + ))); + } + if rec.seq != n { + return Err(R::Damaged(format!("record {n} says it is {}", rec.seq))); + } + if rec.prev_sha256 != rp.head_sha { + return Err(R::Damaged(format!("record {n} breaks the hash chain"))); + } + apply(&mut rp, &rec).map_err(|e| R::Damaged(format!("record {n}: {e}")))?; + rp.head_seq = n; + rp.head_sha = sha_hex(&bytes); + } + Ok(rp) + } + + fn markers(&self) -> Result, R> { + let rd = match std::fs::read_dir(self.pending_dir()) { + Ok(rd) => rd, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(e) => return Err(io("read pending", e)), + }; + let mut out = Vec::new(); + for ent in rd { + let ent = ent.map_err(|e| io("read pending", e))?; + let name = ent.file_name().to_string_lossy().into_owned(); + if name.starts_with(".tmp-") { + let _ = std::fs::remove_file(ent.path()); + continue; + } + let bytes = std::fs::read(ent.path()).map_err(|e| io("read marker", e))?; + if bytes.len() > 512 { + return Err(R::Damaged(format!("marker {name} is oversize"))); + } + let m: Marker = serde_json::from_slice(&bytes) + .map_err(|e| R::Damaged(format!("marker {name}: {e}")))?; + out.push((ent.path(), m)); + } + out.sort_by(|a, b| a.0.cmp(&b.0)); + Ok(out) + } + + fn marker_covers(markers: &[(PathBuf, Marker)], id: &str, it: &Item) -> bool { + markers.iter().any(|(_, m)| match m { + Marker::Item(i) => i == id, + Marker::Scope(s) => *s == it.scope, + }) + } + + // ---------- crypto and keys ---------- + + fn aad(&self, item: &str, version: u32, scope: &Scope, kind: Kind) -> Vec { + format!( + "{MEMORY_SCHEMA}|{}|{}|{item}|{version}|{scope}|{}", + hex(&self.agent), + hex(&self.root), + kind.as_str() + ) + .into_bytes() + } + + fn make_key(&self, kid: &str) -> Result<[u8; 32], R> { + let mut key = [0u8; 32]; + SystemRandom::new() + .fill(&mut key) + .map_err(|_| R::Io("random source failed".into()))?; + self.ensure_dirs()?; + // A key file for a version that is not in the log yet can only be an + // orphan of a crashed write (single writer): destroy it, then create. + self.destroy_key(kid)?; + let mut oo = std::fs::OpenOptions::new(); + oo.write(true).create_new(true); + { + use std::os::unix::fs::OpenOptionsExt; + oo.mode(0o600); + } + let mut f = oo + .open(self.key_path(kid)) + .map_err(|e| io("create key", e))?; + f.write_all(&key).map_err(|e| io("write key", e))?; + f.sync_all().map_err(|e| io("fsync key", e))?; + drop(f); + sync_dir(&self.keys_dir())?; + self.after(Step::KeyWritten)?; + Ok(key) + } + + fn seal(&self, key: &[u8; 32], aad: &[u8], text: &str) -> Result<(String, String), R> { + let mut nonce = [0u8; NONCE_LEN]; + SystemRandom::new() + .fill(&mut nonce) + .map_err(|_| R::Io("random source failed".into()))?; + let k = LessSafeKey::new( + UnboundKey::new(&CHACHA20_POLY1305, key).map_err(|_| R::Io("bad key".into()))?, + ); + let mut buf = text.as_bytes().to_vec(); + k.seal_in_place_append_tag( + Nonce::assume_unique_for_key(nonce), + Aad::from(aad), + &mut buf, + ) + .map_err(|_| R::Io("seal failed".into()))?; + Ok((hex(&buf), hex(&nonce))) + } + + /// Err(Ok(status)) shapes are avoided: returns the plaintext or an `ItemStatus::Unresolved` reason. + fn read_text(&self, id: &str, it: &Item, v: &Ver) -> Result { + let kid = key_id(id, v.version); + let key = match read_key(&self.key_path(&kid)) { + Ok(k) if k.len() == 32 => k, + Ok(_) => return Err(ItemStatus::Unresolved("key damaged".into())), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + return Err(ItemStatus::Unresolved("key missing".into())) + } + Err(_) => return Err(ItemStatus::Unresolved("key unreadable".into())), + }; + let k = LessSafeKey::new( + UnboundKey::new(&CHACHA20_POLY1305, &key) + .map_err(|_| ItemStatus::Unresolved("key damaged".into()))?, + ); + let aad = self.aad(id, v.version, &it.scope, it.kind); + let mut buf = v.ciphertext.clone(); + match k.open_in_place( + Nonce::assume_unique_for_key(v.nonce), + Aad::from(&aad[..]), + &mut buf, + ) { + Ok(p) => String::from_utf8(p.to_vec()) + .map_err(|_| ItemStatus::Unresolved("cannot decrypt".into())), + Err(_) => Err(ItemStatus::Unresolved("cannot decrypt".into())), + } + } + + /// Overwrite with zeros, fsync, unlink. Returns whether a file existed. + fn destroy_key(&self, kid: &str) -> Result { + let p = self.key_path(kid); + let (mut f, len) = match open_regular(&p, true) { + Ok(f) => { + let len = f.metadata().map_err(|e| io("stat key", e))?.len() as usize; + (f, len) + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false), + Err(e) => { + return Err(R::Damaged(format!( + "key file {kid} is not a plain file ({e}); refusing to touch it" + ))) + } + }; + { + f.write_all(&vec![0u8; len]) + .map_err(|e| io("zero key", e))?; + f.sync_all().map_err(|e| io("fsync key", e))?; + } + self.after(Step::KeyZeroed)?; + std::fs::remove_file(&p).map_err(|e| io("unlink key", e))?; + self.after(Step::KeyUnlinked)?; + Ok(true) + } + + fn destroy_keys(&self, kids: &[String]) -> Result { + let mut n = 0; + for k in kids { + if self.destroy_key(k)? { + n += 1; + } + } + if self.keys_dir().exists() { + sync_dir(&self.keys_dir())?; + } + self.after(Step::KeysDestroyed)?; + Ok(n) + } + + fn all_kids(id: &str, it: &Item) -> Vec { + it.versions.iter().map(|v| key_id(id, v.version)).collect() + } + + // ---------- writing ---------- + + fn ensure_dirs(&self) -> Result<(), R> { + for (sub, mode) in [("log", 0o755), ("keys", 0o700), ("pending", 0o755)] { + let p = self.dir.join(sub); + if p.exists() { + continue; + } + std::fs::create_dir_all(&p).map_err(|e| io("create folder", e))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(mode)) + .map_err(|e| io("set folder mode", e))?; + } + let _ = mode; + sync_dir(&self.dir)?; + if let Some(parent) = self.dir.parent() { + sync_dir(parent)?; + } + } + Ok(()) + } + + fn append(&self, rp: &Replay, op: Op) -> Result<(), R> { + if rp.head_seq >= MAX_RECORDS { + return Err(R::Invalid("the memory log is full".into())); + } + self.ensure_dirs()?; + let rec = Record { + schema: MEMORY_SCHEMA.into(), + agent: hex(&self.agent), + root: hex(&self.root), + seq: rp.head_seq + 1, + prev_sha256: rp.head_sha.clone(), + at: now_utc(), + op, + }; + let bytes = serde_json::to_vec(&rec).map_err(|e| R::Io(format!("serialize: {e}")))?; + if bytes.len() as u64 > MAX_RECORD_BYTES { + return Err(R::Invalid("record too large".into())); + } + static COUNTER: AtomicU64 = AtomicU64::new(0); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let tmp = self.log_dir().join(format!( + ".tmp-{}-{}-{nanos}", + std::process::id(), + COUNTER.fetch_add(1, Ordering::SeqCst) + )); + let r = self.append_steps(&tmp, &self.log_dir().join(log_name(rec.seq)), &bytes); + match &r { + Err(R::Crashed(_)) | Ok(()) => {} + Err(_) => { + let _ = std::fs::remove_file(&tmp); + } + } + r + } + + fn append_steps(&self, tmp: &Path, dst: &Path, bytes: &[u8]) -> Result<(), R> { + let mut oo = std::fs::OpenOptions::new(); + oo.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + oo.mode(0o600); + } + let mut f = oo.open(tmp).map_err(|e| io("create temp", e))?; + self.after(Step::TempCreated)?; + f.write_all(bytes).map_err(|e| io("write", e))?; + self.after(Step::TempWritten)?; + f.sync_all().map_err(|e| io("fsync", e))?; + drop(f); + self.after(Step::TempSynced)?; + match std::fs::hard_link(tmp, dst) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { + let _ = std::fs::remove_file(tmp); + return Err(R::Conflict); + } + Err(e) => return Err(io("link record", e)), + } + self.after(Step::Linked)?; + sync_dir(&self.log_dir())?; + self.after(Step::DirSynced)?; + std::fs::remove_file(tmp).map_err(|e| io("remove temp", e))?; + self.after(Step::TempRemoved)?; + Ok(()) + } + + fn write_marker(&self, m: &Marker) -> Result { + self.ensure_dirs()?; + let name = format!("forget-{}.json", rand_hex(8)?); + let (tmp, dst) = ( + self.pending_dir().join(format!(".tmp-{name}")), + self.pending_dir().join(&name), + ); + let mut oo = std::fs::OpenOptions::new(); + oo.write(true).create(true).truncate(true); + { + use std::os::unix::fs::OpenOptionsExt; + oo.mode(0o600); + } + let mut f = oo.open(&tmp).map_err(|e| io("create marker", e))?; + f.write_all(&serde_json::to_vec(m).map_err(|e| R::Io(e.to_string()))?) + .map_err(|e| io("write marker", e))?; + f.sync_all().map_err(|e| io("fsync marker", e))?; + drop(f); + std::fs::rename(&tmp, &dst).map_err(|e| io("rename marker", e))?; + sync_dir(&self.pending_dir())?; + self.after(Step::MarkerWritten)?; + Ok(dst) + } + + fn remove_marker(&self, p: &Path) -> Result<(), R> { + std::fs::remove_file(p).map_err(|e| io("remove marker", e))?; + sync_dir(&self.pending_dir())?; + self.after(Step::MarkerRemoved) + } + + // ---------- recovery ---------- + + /// Destroy any key whose item has a Forget record, any key of a + /// superseded version, and any orphan key no record refers to. Idempotent; returns how many key files it removed. + /// Run on every open, so restoring an old copy of `keys/` cannot bring + /// forgotten content back once the log is intact. + pub fn reapply_forgets(&self) -> Result { + let _g = self.lock()?; + self.reapply_inner() + } + + fn reapply_inner(&self) -> Result { + let rp = self.replay()?; + let mut keep = std::collections::BTreeSet::new(); + for (id, it) in &rp.items { + if !it.forgotten { + keep.insert(key_id(id, it.current().version)); + } + } + let rd = match std::fs::read_dir(self.keys_dir()) { + Ok(rd) => rd, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0), + Err(e) => return Err(io("read keys folder", e)), + }; + let mut kids = Vec::new(); + for ent in rd { + let name = ent + .map_err(|e| io("read keys folder", e))? + .file_name() + .to_string_lossy() + .into_owned(); + if let Some(kid) = name.strip_suffix(".key") { + if !keep.contains(kid) { + kids.push(kid.to_string()); + } + } + } + kids.sort(); + self.destroy_keys(&kids) + } + + fn check_layout(&self) -> Result<(), R> { + check_dir(&self.dir, false)?; + check_dir(&self.log_dir(), false)?; + check_dir(&self.keys_dir(), true)?; + check_dir(&self.pending_dir(), false) + } + + fn recover(&self) -> Result<(), R> { + self.check_layout()?; + // Sweeping and finishing forgets need the writer lock. If another process + // holds it, it may be mid-write: only verify, change nothing. + let _guard = match self.lock_file() { + Ok(f) if f.try_lock().is_ok() => f, + _ => { + self.replay()?; + return Ok(()); + } + }; + // Leftovers of a crashed append (single writer: none can be in flight now). + if let Ok(rd) = std::fs::read_dir(self.log_dir()) { + for ent in rd.flatten() { + if ent.file_name().to_string_lossy().starts_with(".tmp-") { + let _ = std::fs::remove_file(ent.path()); + } + } + } + // Finish interrupted forgets: destroy keys, append the record, drop the marker. + for (path, m) in self.markers()? { + let rp = self.replay()?; + let mut kids = Vec::new(); + let mut need_record: Vec<(String, Scope)> = Vec::new(); + for (id, it) in &rp.items { + let hit = match &m { + Marker::Item(i) => i == id, + Marker::Scope(s) => *s == it.scope, + }; + if hit { + kids.extend(Memory::all_kids(id, it)); + if !it.forgotten { + need_record.push((id.clone(), it.scope.clone())); + } + } + } + if self.keys_dir().exists() { + self.destroy_keys(&kids)?; + } + match &m { + Marker::Scope(s) if !need_record.is_empty() => { + self.append(&rp, Op::ForgetScope { scope: s.clone() })?; + } + Marker::Item(i) if !need_record.is_empty() => { + self.append( + &rp, + Op::ForgetItem { + item: i.clone(), + scope: need_record[0].1.clone(), + }, + )?; + } + _ => {} + } + self.remove_marker(&path)?; + } + self.replay()?; // verify the log even when nothing is pending + self.reapply_inner()?; + Ok(()) + } + + // ---------- public operations ---------- + + fn check_text(text: &str) -> Result<(), R> { + if text.trim().is_empty() { + return Err(R::Invalid("empty content".into())); + } + if text.len() > MAX_TEXT_BYTES { + return Err(R::Invalid(format!( + "content is {} bytes (limit {MAX_TEXT_BYTES})", + text.len() + ))); + } + Ok(()) + } + + /// Store a new item; returns its id. + pub fn put(&self, scope: Scope, kind: Kind, text: &str) -> Result { + Memory::check_text(text)?; + let _g = self.lock()?; + let rp = self.replay()?; + let item = rand_hex(16)?; + let kid = key_id(&item, 1); + let key = self.make_key(&kid)?; + let (ciphertext, nonce) = self.seal(&key, &self.aad(&item, 1, &scope, kind), text)?; + self.append( + &rp, + Op::Put { + item: item.clone(), + scope, + kind, + version: 1, + ciphertext, + nonce, + key_id: kid, + }, + )?; + Ok(item) + } + + /// Write a new version and destroy the superseded version's key. + pub fn correct<'a>( + &self, + auth: impl Into>, + item: &str, + text: &str, + ) -> Result { + Memory::check_text(text)?; + let _g = self.lock()?; + let rp = self.replay()?; + let it = rp + .items + .get(item) + .ok_or_else(|| R::UnknownItem(item.into()))?; + auth.into().check(item, &it.scope)?; + let markers = self.markers()?; + if it.forgotten || Memory::marker_covers(&markers, item, it) { + return Err(R::ItemForgotten(item.into())); + } + let old = it.current().version; + let new = old + 1; + let kid = key_id(item, new); + let key = self.make_key(&kid)?; + let (ciphertext, nonce) = + self.seal(&key, &self.aad(item, new, &it.scope, it.kind), text)?; + self.append( + &rp, + Op::Correct { + item: item.into(), + supersedes_version: old, + version: new, + ciphertext, + nonce, + key_id: kid, + }, + )?; + self.destroy_keys(&[key_id(item, old)])?; + self.after(Step::SupersededKeyDestroyed)?; + Ok(new) + } + + /// Forget an item or a whole scope. Order: intent marker, destroy keys + /// (zero, fsync, unlink, fsync dir), append Forget record, drop marker. + /// Returns the ids forgotten. + pub fn forget<'a>( + &self, + auth: impl Into>, + target: ForgetTarget, + ) -> Result, R> { + let _g = self.lock()?; + let rp = self.replay()?; + let auth = auth.into(); + let (marker, ids, op) = match &target { + ForgetTarget::Item(i) => { + let it = rp.items.get(i).ok_or_else(|| R::UnknownItem(i.clone()))?; + auth.check(i, &it.scope)?; + if it.forgotten { + return Err(R::NothingToForget); + } + ( + Marker::Item(i.clone()), + vec![i.clone()], + Op::ForgetItem { + item: i.clone(), + scope: it.scope.clone(), + }, + ) + } + ForgetTarget::Scope(s) => { + auth.check("(scope)", s)?; + let ids: Vec = rp + .items + .iter() + .filter(|(_, it)| it.scope == *s && !it.forgotten) + .map(|(i, _)| i.clone()) + .collect(); + if ids.is_empty() { + return Err(R::NothingToForget); + } + ( + Marker::Scope(s.clone()), + ids, + Op::ForgetScope { scope: s.clone() }, + ) + } + }; + let kids: Vec = ids + .iter() + .flat_map(|i| Memory::all_kids(i, &rp.items[i])) + .collect(); + let mpath = self.write_marker(&marker)?; + if self.keys_dir().exists() { + self.destroy_keys(&kids)?; + } + self.append(&rp, op)?; + self.after(Step::ForgetRecorded)?; + self.remove_marker(&mpath)?; + Ok(ids) + } + + /// Mark a goal closed. Its content stays readable (the key is kept). + pub fn close_goal<'a>(&self, auth: impl Into>, item: &str) -> Result<(), R> { + let _g = self.lock()?; + let rp = self.replay()?; + let it = rp + .items + .get(item) + .ok_or_else(|| R::UnknownItem(item.into()))?; + auth.into().check(item, &it.scope)?; + if it.kind != Kind::Goal { + return Err(R::NotAGoal(item.into())); + } + if it.forgotten { + return Err(R::ItemForgotten(item.into())); + } + if it.closed { + return Err(R::Invalid("goal is already closed".into())); + } + self.append(&rp, Op::GoalClose { item: item.into() }) + } + + fn views(&self, only: Option<&Scope>) -> Result, R> { + let rp = self.replay()?; + let markers = self.markers()?; + let mut order: Vec<(&String, &Item)> = rp + .items + .iter() + .filter(|(_, it)| only.is_none_or(|s| *s == it.scope)) + .collect(); + order.sort_by(|a, b| (a.1.created_seq, a.0).cmp(&(b.1.created_seq, b.0))); + let mut out = Vec::new(); + for (id, it) in order { + let label = (it.kind == Kind::Goal).then_some(GOAL_LABEL); + let mk = |v: &Ver, st: ItemStatus, text: Option| ItemView { + item: id.clone(), + scope: it.scope.to_string(), + kind: it.kind, + version: v.version, + created: v.at.clone(), + state: st.text(), + text, + label, + status: Some(st), + }; + let cur = it.current(); + if it.forgotten { + out.push(mk(cur, ItemStatus::Forgotten, None)); + continue; + } + for v in &it.versions[..it.versions.len() - 1] { + out.push(mk(v, ItemStatus::Corrected, None)); + } + if Memory::marker_covers(&markers, id, it) { + let gone = !self.key_path(&key_id(id, cur.version)).exists(); + out.push(mk( + cur, + ItemStatus::ForgottenPending { key_missing: gone }, + None, + )); + continue; + } + match self.read_text(id, it, cur) { + Ok(t) => { + let st = if it.closed { + ItemStatus::Closed + } else { + ItemStatus::Live + }; + out.push(mk(cur, st, Some(t))); + } + Err(st) => out.push(mk(cur, st, None)), + } + } + Ok(out) + } + + /// Owner-facing: every item in one scope, with its state. + pub fn inspect(&self, grant: &ScopeGrant) -> Result, R> { + self.views(Some(&grant.scope)) + } + + /// Owner-facing: every item in every scope. + pub fn inspect_all(&self, _all: &InspectAll) -> Result, R> { + self.views(None) + } + + /// Context assembly. Returns only items in the granted scope whose content + /// is live (open goals included, closed goals excluded). `query`, if given, + /// is a case-insensitive substring filter on the plaintext; it can never + /// widen the scope. Deterministic order (creation order, then id), bounded + /// by `limits`. A missing key is listed in `unresolved`; a failed integrity + /// check is an error. + pub fn recall( + &self, + grant: &ScopeGrant, + query: Option<&str>, + limits: &RecallLimits, + ) -> Result { + let rp = self.replay()?; + let markers = self.markers()?; + let mut order: Vec<(&String, &Item)> = rp + .items + .iter() + .filter(|(_, it)| it.scope == grant.scope && !it.forgotten && !it.closed) + .collect(); + order.sort_by(|a, b| (a.1.created_seq, a.0).cmp(&(b.1.created_seq, b.0))); + let q = query.map(|q| q.to_lowercase()); + let mut rc = Recall { + scope: grant.scope.clone(), + items: Vec::new(), + omitted: 0, + unresolved: Vec::new(), + }; + let (mut bytes, mut full) = (0usize, false); + for (id, it) in order { + if Memory::marker_covers(&markers, id, it) { + continue; + } + let cur = it.current(); + let text = match self.read_text(id, it, cur) { + Ok(t) => t, + Err(ItemStatus::Unresolved(w)) if w == "cannot decrypt" => { + return Err(R::Tampered(id.clone())) + } + Err(_) => { + rc.unresolved.push(id.clone()); + continue; + } + }; + if q.as_ref().is_some_and(|q| !text.to_lowercase().contains(q)) { + continue; + } + if full || rc.items.len() >= limits.max_items || bytes + text.len() > limits.max_bytes { + full = true; + rc.omitted += 1; + continue; + } + bytes += text.len(); + rc.items.push(ItemView { + item: id.clone(), + scope: it.scope.to_string(), + kind: it.kind, + version: cur.version, + created: cur.at.clone(), + state: ItemStatus::Live.text(), + text: Some(text), + label: (it.kind == Kind::Goal).then_some(GOAL_LABEL), + status: Some(ItemStatus::Live), + }); + } + Ok(rc) + } + + /// JSON of the live (and closed) items' plaintext in one scope, for the owner. + pub fn export(&self, grant: &ScopeGrant) -> Result { + let items: Vec = self + .views(Some(&grant.scope))? + .into_iter() + .filter(|v| matches!(v.status, Some(ItemStatus::Live | ItemStatus::Closed))) + .collect(); + serde_json::to_string_pretty(&serde_json::json!({ + "schema": "aien.allen.memory.export/1", + "scope": grant.scope.to_string(), + "items": items, + })) + .map_err(|e| R::Io(e.to_string())) + } + + fn goal_list(&self, only: Option<&Scope>) -> Result { + let goals = self + .views(only)? + .into_iter() + .filter(|v| { + v.kind == Kind::Goal + && matches!(v.status, Some(ItemStatus::Live | ItemStatus::Closed)) + }) + .map(|v| GoalView { + item: v.item, + scope: v.scope, + text: v.text.unwrap_or_default(), + created: v.created, + state: if v.status == Some(ItemStatus::Closed) { + "closed" + } else { + "open" + }, + label: GOAL_LABEL, + }) + .collect(); + Ok(GoalList { + label: GOAL_LABEL, + goals, + }) + } + + /// Host standing goals in one scope. Not subject intents. + pub fn goals(&self, grant: &ScopeGrant) -> Result { + self.goal_list(Some(&grant.scope)) + } + + /// Host standing goals in every scope (owner-facing). + pub fn goals_all(&self, _all: &InspectAll) -> Result { + self.goal_list(None) + } +} + +fn apply(rp: &mut Replay, rec: &Record) -> Result<(), String> { + let nonce_of = |s: &str| -> Result<[u8; NONCE_LEN], String> { + unhex(s) + .and_then(|v| v.try_into().ok()) + .ok_or_else(|| "bad nonce".to_string()) + }; + let ct_of = |s: &str| unhex(s).ok_or_else(|| "bad ciphertext".to_string()); + match &rec.op { + Op::Put { + item, + scope, + kind, + version, + ciphertext, + nonce, + .. + } => { + if rp.items.contains_key(item) { + return Err("item put twice".into()); + } + rp.items.insert( + item.clone(), + Item { + scope: scope.clone(), + kind: *kind, + created_seq: rec.seq, + versions: vec![Ver { + version: *version, + at: rec.at.clone(), + ciphertext: ct_of(ciphertext)?, + nonce: nonce_of(nonce)?, + }], + forgotten: false, + closed: false, + }, + ); + } + Op::Correct { + item, + supersedes_version, + version, + ciphertext, + nonce, + .. + } => { + let it = rp.items.get_mut(item).ok_or("correct of unknown item")?; + if it.forgotten || it.current().version != *supersedes_version { + return Err("correct does not follow the current version".into()); + } + it.versions.push(Ver { + version: *version, + at: rec.at.clone(), + ciphertext: ct_of(ciphertext)?, + nonce: nonce_of(nonce)?, + }); + } + Op::ForgetItem { item, scope } => { + let it = rp.items.get_mut(item).ok_or("forget of unknown item")?; + if it.scope != *scope { + return Err("forget names the wrong scope".into()); + } + it.forgotten = true; + } + Op::ForgetScope { scope } => { + for it in rp.items.values_mut().filter(|i| i.scope == *scope) { + it.forgotten = true; + } + } + Op::GoalClose { item } => { + let it = rp.items.get_mut(item).ok_or("close of unknown item")?; + if it.kind != Kind::Goal || it.forgotten { + return Err("close of a non-goal or forgotten item".into()); + } + it.closed = true; + } + } + Ok(()) +} + +/// Open an existing regular file without following a symlink: lstat must say +/// "regular file" and the opened handle must be the same inode (no swap race). +fn open_regular(path: &Path, write: bool) -> std::io::Result { + open_regular_with(path, write, || {}) +} + +/// `between` runs after the lstat and before the open (test seam for the swap race). +fn open_regular_with( + path: &Path, + write: bool, + between: impl FnOnce(), +) -> std::io::Result { + use std::os::unix::fs::MetadataExt; + let bad = |w: &str| std::io::Error::new(std::io::ErrorKind::PermissionDenied, w.to_string()); + let l = std::fs::symlink_metadata(path)?; + if !l.file_type().is_file() { + return Err(bad("not a regular file")); + } + between(); + let f = std::fs::OpenOptions::new() + .read(true) + .write(write) + .open(path)?; + let m = f.metadata()?; + if m.dev() != l.dev() || m.ino() != l.ino() { + return Err(bad("file changed while opening")); + } + Ok(f) +} + +fn read_key(path: &Path) -> std::io::Result> { + use std::io::Read; + let mut b = Vec::new(); + open_regular(path, false)?.take(65).read_to_end(&mut b)?; + Ok(b) +} + +/// A real directory (not a symlink), mode 0700 when `private`; looser modes +/// are tightened. +fn check_dir(p: &Path, private: bool) -> Result<(), R> { + use std::os::unix::fs::PermissionsExt; + let m = match std::fs::symlink_metadata(p) { + Ok(m) => m, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(e) => return Err(io("stat folder", e)), + }; + if !m.file_type().is_dir() { + return Err(R::Damaged(format!( + "{} is not a plain folder (symlink or file)", + p.display() + ))); + } + if private && m.permissions().mode() & 0o077 != 0 { + std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o700)) + .map_err(|e| io("tighten folder mode", e))?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn open_regular_refuses_a_file_swapped_between_lstat_and_open() { + let d = std::env::temp_dir().join(format!("aienmem-swap-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + let (a, b) = (d.join("a"), d.join("b")); + std::fs::write(&a, b"original").unwrap(); + std::fs::write(&b, b"other inode").unwrap(); + let r = open_regular_with(&a, false, || { + std::fs::rename(&b, &a).unwrap(); // a now names a different inode + }); + assert_eq!(r.unwrap_err().kind(), std::io::ErrorKind::PermissionDenied); + // no swap: opens fine; symlink: refused + std::fs::write(d.join("c"), b"x").unwrap(); + assert!(open_regular(&d.join("c"), false).is_ok()); + std::os::unix::fs::symlink(d.join("c"), d.join("l")).unwrap(); + assert!(open_regular(&d.join("l"), false).is_err()); + let _ = std::fs::remove_dir_all(&d); + } +} diff --git a/crates/aien-allen-memory/tests/memory_test.rs b/crates/aien-allen-memory/tests/memory_test.rs new file mode 100644 index 00000000..0f8698de --- /dev/null +++ b/crates/aien-allen-memory/tests/memory_test.rs @@ -0,0 +1,1088 @@ +//! HOST FIXTURE tests: identities are made-up byte arrays standing in for a +//! `Resolved` value; no real ALLEN subject, no daemon, no model is involved. +use aien_allen::Resolved; +use aien_allen_memory::*; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + +fn resolved(n: u8) -> Resolved { + Resolved { + agent: [n; 32], + root: [n.wrapping_add(100); 32], + head_id: [0; 32], + head_seq: 1, + lineage: [0; 32], + chain_verified: false, + adopted: false, + } +} + +struct Fx { + _t: tempfile::TempDir, + home: PathBuf, +} + +fn fx() -> Fx { + let t = tempfile::tempdir().unwrap(); + let home = t.path().join("home"); + Fx { _t: t, home } +} + +impl Fx { + fn open(&self) -> Memory { + Memory::open(&self.home, Some(&resolved(1))).unwrap() + } + fn dir(&self) -> PathBuf { + memory_dir(&self.home) + } +} + +fn g(s: &str) -> ScopeGrant { + ScopeGrant::new(Scope::parse(s).unwrap()) +} +fn lim() -> RecallLimits { + RecallLimits::default() +} +fn texts(r: &Recall) -> Vec { + r.items.iter().map(|i| i.text.clone().unwrap()).collect() +} +fn files(dir: &Path) -> Vec { + let mut v: Vec = match std::fs::read_dir(dir) { + Ok(rd) => rd.map(|e| e.unwrap().path()).collect(), + Err(_) => vec![], + }; + v.sort(); + v +} +fn key_files(fx: &Fx) -> Vec { + files(&fx.dir().join("keys")) +} +fn last_record(fx: &Fx) -> PathBuf { + files(&fx.dir().join("log")).pop().unwrap() +} +fn copy_dir(a: &Path, b: &Path) { + std::fs::create_dir_all(b).unwrap(); + for f in files(a) { + std::fs::copy(&f, b.join(f.file_name().unwrap())).unwrap(); + } +} +fn edit_last(fx: &Fx, f: impl FnOnce(&mut serde_json::Value)) { + let p = last_record(fx); + let mut v: serde_json::Value = serde_json::from_slice(&std::fs::read(&p).unwrap()).unwrap(); + f(&mut v); + std::fs::write(&p, serde_json::to_vec(&v).unwrap()).unwrap(); +} + +// ---------- scopes ---------- + +#[test] +fn scope_names_are_validated() { + for ok in ["personal", "work", "project:a", "project:my-proj_1.x"] { + assert!(Scope::parse(ok).is_ok(), "{ok}"); + } + for bad in [ + "", + "all", + "*", + "project:", + "project:A", + "project:a b", + "Personal", + &format!("project:{}", "x".repeat(49)), + ] { + assert!(Scope::parse(bad).is_err(), "{bad}"); + } +} + +#[test] +fn put_and_recall_per_scope_with_no_leakage() { + let f = fx(); + let m = f.open(); + m.put(Scope::Personal, Kind::Fact, "p-secret").unwrap(); + m.put(Scope::Work, Kind::Fact, "w-note").unwrap(); + m.put( + Scope::parse("project:a").unwrap(), + Kind::Preference, + "a-pref", + ) + .unwrap(); + m.put(Scope::parse("project:b").unwrap(), Kind::Fact, "b-fact") + .unwrap(); + assert_eq!( + texts(&m.recall(&g("personal"), None, &lim()).unwrap()), + ["p-secret"] + ); + assert_eq!( + texts(&m.recall(&g("work"), None, &lim()).unwrap()), + ["w-note"] + ); + assert_eq!( + texts(&m.recall(&g("project:a"), None, &lim()).unwrap()), + ["a-pref"] + ); + assert_eq!( + texts(&m.recall(&g("project:b"), None, &lim()).unwrap()), + ["b-fact"] + ); + // project:a never answers for project:b and "project" alone is not a scope + assert!(m + .recall(&g("project:c"), None, &lim()) + .unwrap() + .items + .is_empty()); + for s in ["personal", "work", "project:a", "project:b"] { + let r = m.recall(&g(s), None, &lim()).unwrap(); + assert!(r.items.iter().all(|i| i.scope == s)); + } +} + +#[test] +fn caller_claimed_scope_in_query_text_is_ignored() { + let f = fx(); + let m = f.open(); + m.put(Scope::Personal, Kind::Fact, "my passport number is 1234") + .unwrap(); + m.put(Scope::Work, Kind::Fact, "standup at nine").unwrap(); + for q in [ + "scope=personal", + "scope=personal passport", + "personal", + "passport", + "{\"scope\":\"personal\"}", + ] { + let r = m.recall(&g("work"), Some(q), &lim()).unwrap(); + assert!(r.items.iter().all(|i| i.scope == "work"), "{q}"); + assert!(texts(&r).iter().all(|t| !t.contains("passport")), "{q}"); + } + // The only way to read personal is a grant built by the caller of the API. + assert_eq!( + m.recall(&g("personal"), Some("passport"), &lim()) + .unwrap() + .items + .len(), + 1 + ); +} + +#[test] +fn plaintext_is_never_on_disk() { + let f = fx(); + let m = f.open(); + m.put(Scope::Work, Kind::Fact, "UNIQUEPLAINTEXTMARKER") + .unwrap(); + for d in ["log", "keys", "pending"] { + for p in files(&f.dir().join(d)) { + let b = std::fs::read(&p).unwrap(); + assert!(!String::from_utf8_lossy(&b).contains("UNIQUEPLAINTEXTMARKER")); + } + } +} + +#[cfg(unix)] +#[test] +fn key_files_are_private() { + use std::os::unix::fs::PermissionsExt; + let f = fx(); + f.open().put(Scope::Work, Kind::Fact, "x").unwrap(); + let dm = std::fs::metadata(f.dir().join("keys")) + .unwrap() + .permissions() + .mode() + & 0o777; + assert_eq!(dm, 0o700); + for k in key_files(&f) { + assert_eq!( + std::fs::metadata(&k).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } +} + +#[test] +fn reopen_keeps_live_items() { + let f = fx(); + let id = f.open().put(Scope::Work, Kind::Fact, "kept").unwrap(); + let m = f.open(); + let r = m.recall(&g("work"), None, &lim()).unwrap(); + assert_eq!(texts(&r), ["kept"]); + assert_eq!(r.items[0].item, id); +} + +#[test] +fn recall_is_deterministic_and_bounded() { + let f = fx(); + let m = f.open(); + for i in 0..6 { + m.put(Scope::Work, Kind::Fact, &format!("note-{i}")) + .unwrap(); + } + let a = m + .recall( + &g("work"), + None, + &RecallLimits { + max_items: 3, + max_bytes: 4096, + }, + ) + .unwrap(); + let b = m + .recall( + &g("work"), + None, + &RecallLimits { + max_items: 3, + max_bytes: 4096, + }, + ) + .unwrap(); + assert_eq!(texts(&a), ["note-0", "note-1", "note-2"]); + assert_eq!(a, b); + assert_eq!(a.omitted, 3); + let c = m + .recall( + &g("work"), + None, + &RecallLimits { + max_items: 10, + max_bytes: 14, + }, + ) + .unwrap(); + assert_eq!(texts(&c), ["note-0", "note-1"]); + assert_eq!(c.omitted, 4); +} + +#[test] +fn oversize_and_empty_content_refused() { + let f = fx(); + let m = f.open(); + assert!(matches!( + m.put(Scope::Work, Kind::Fact, &"x".repeat(2049)), + Err(MemoryRefusal::Invalid(_)) + )); + assert!(matches!( + m.put(Scope::Work, Kind::Fact, " "), + Err(MemoryRefusal::Invalid(_)) + )); +} + +// ---------- inspect / correct ---------- + +#[test] +fn inspect_lists_states_and_content() { + let f = fx(); + let m = f.open(); + let a = m.put(Scope::Work, Kind::Fact, "one").unwrap(); + m.put(Scope::Personal, Kind::Fact, "other scope").unwrap(); + m.correct(&InspectAll::owner(), &a, "one-v2").unwrap(); + let v = m.inspect(&g("work")).unwrap(); + assert_eq!(v.len(), 2); + assert_eq!( + (v[0].version, v[0].state.as_str(), v[0].text.clone()), + (1, "corrected", None) + ); + assert_eq!( + (v[1].version, v[1].state.as_str(), v[1].text.as_deref()), + (2, "live", Some("one-v2")) + ); + assert_eq!(m.inspect_all(&InspectAll::owner()).unwrap().len(), 3); +} + +#[test] +fn correct_destroys_the_old_key() { + let f = fx(); + let m = f.open(); + let a = m.put(Scope::Work, Kind::Fact, "wrong").unwrap(); + assert_eq!(key_files(&f).len(), 1); + let old = key_files(&f)[0].clone(); + assert_eq!(m.correct(&InspectAll::owner(), &a, "right").unwrap(), 2); + assert!(!old.exists()); + assert_eq!(key_files(&f).len(), 1); + assert_eq!( + texts(&m.recall(&g("work"), None, &lim()).unwrap()), + ["right"] + ); + // an old key restored from a backup is destroyed again on open + let (kd, bk) = (f.dir().join("keys"), f.dir().join("bk")); + copy_dir(&kd, &bk); + std::fs::write(&old, [7u8; 32]).unwrap(); + let m = f.open(); + assert!(!old.exists()); + assert_eq!( + texts(&m.recall(&g("work"), None, &lim()).unwrap()), + ["right"] + ); +} + +#[test] +fn correct_of_unknown_or_forgotten_item_refused() { + let f = fx(); + let m = f.open(); + assert!(matches!( + m.correct(&InspectAll::owner(), &"0".repeat(32), "x"), + Err(MemoryRefusal::UnknownItem(_)) + )); + let a = m.put(Scope::Work, Kind::Fact, "x").unwrap(); + m.forget(&InspectAll::owner(), ForgetTarget::Item(a.clone())) + .unwrap(); + assert!(matches!( + m.correct(&InspectAll::owner(), &a, "y"), + Err(MemoryRefusal::ItemForgotten(_)) + )); +} + +// ---------- forget ---------- + +#[test] +fn forget_item_removes_content_but_not_the_ciphertext() { + let f = fx(); + let m = f.open(); + let a = m.put(Scope::Work, Kind::Fact, "gone soon").unwrap(); + let keep = m.put(Scope::Work, Kind::Fact, "stays").unwrap(); + let rec = last_record(&f); + let _ = rec; + let log_before = files(&f.dir().join("log")).len(); + assert_eq!( + m.forget(&InspectAll::owner(), ForgetTarget::Item(a.clone())) + .unwrap(), + vec![a.clone()] + ); + assert_eq!( + texts(&m.recall(&g("work"), None, &lim()).unwrap()), + ["stays"] + ); + let v = m.inspect(&g("work")).unwrap(); + let fa = v.iter().find(|i| i.item == a).unwrap(); + assert_eq!((fa.state.as_str(), fa.text.clone()), ("forgotten", None)); + assert!(v.iter().any(|i| i.item == keep && i.text.is_some())); + // the stored ciphertext is still in the log; the key is not + assert_eq!(files(&f.dir().join("log")).len(), log_before + 1); + assert_eq!(key_files(&f).len(), 1); + assert!(files(&f.dir().join("pending")).is_empty()); + // the Forget record holds metadata only + let fr = std::fs::read_to_string(last_record(&f)).unwrap(); + assert!(fr.contains("forget_item") && fr.contains(&a) && !fr.contains("gone soon")); + assert!(matches!( + m.forget(&InspectAll::owner(), ForgetTarget::Item(a)), + Err(MemoryRefusal::NothingToForget) + )); +} + +#[test] +fn forget_scope_only_touches_that_scope() { + let f = fx(); + let m = f.open(); + let p = Scope::parse("project:a").unwrap(); + m.put(p.clone(), Kind::Fact, "a1").unwrap(); + m.put(p.clone(), Kind::Goal, "a-goal").unwrap(); + m.put(Scope::parse("project:b").unwrap(), Kind::Fact, "b1") + .unwrap(); + m.put(Scope::Work, Kind::Fact, "w1").unwrap(); + assert_eq!( + m.forget(&InspectAll::owner(), ForgetTarget::Scope(p)) + .unwrap() + .len(), + 2 + ); + assert!(m + .recall(&g("project:a"), None, &lim()) + .unwrap() + .items + .is_empty()); + assert!(m + .inspect(&g("project:a")) + .unwrap() + .iter() + .all(|i| i.text.is_none() && i.state == "forgotten")); + assert_eq!( + texts(&m.recall(&g("project:b"), None, &lim()).unwrap()), + ["b1"] + ); + assert_eq!(texts(&m.recall(&g("work"), None, &lim()).unwrap()), ["w1"]); + assert_eq!(key_files(&f).len(), 2); + assert!(matches!( + m.forget(&InspectAll::owner(), ForgetTarget::Scope(Scope::Personal)), + Err(MemoryRefusal::NothingToForget) + )); + // a later put in a forgotten scope is a new, live item + m.put(Scope::parse("project:a").unwrap(), Kind::Fact, "a-new") + .unwrap(); + assert_eq!( + texts(&m.recall(&g("project:a"), None, &lim()).unwrap()), + ["a-new"] + ); +} + +type Case = (&'static str, Box); + +fn once(step: Step) -> (Arc bool + Send + Sync>, Arc) { + let fired = Arc::new(AtomicBool::new(false)); + let f2 = fired.clone(); + ( + Arc::new(move |s| s == step && !f2.swap(true, Ordering::SeqCst)), + fired, + ) +} + +const FORGET_STEPS: [Step; 13] = [ + Step::MarkerWritten, + Step::KeyZeroed, + Step::KeyUnlinked, + Step::KeysDestroyed, + Step::TempCreated, + Step::TempWritten, + Step::TempSynced, + Step::Linked, + Step::DirSynced, + Step::TempRemoved, + Step::ForgetRecorded, + Step::MarkerRemoved, + Step::MarkerRemoved, // repeated on purpose: harmless duplicate +]; + +#[test] +fn crash_at_every_forget_step_never_resurrects_and_reopen_finishes() { + for scope_target in [false, true] { + for step in FORGET_STEPS { + let f = fx(); + let m = f.open(); + let a = m.put(Scope::Work, Kind::Fact, "doomed").unwrap(); + m.put(Scope::Personal, Kind::Fact, "bystander").unwrap(); + let (hook, fired) = once(step); + let m = m.with_fault_hook(hook); + let t = if scope_target { + ForgetTarget::Scope(Scope::Work) + } else { + ForgetTarget::Item(a.clone()) + }; + let r = m.forget(&InspectAll::owner(), t); + assert!(fired.load(Ordering::SeqCst), "{step:?} never reached"); + assert!( + matches!(r, Err(MemoryRefusal::Crashed(_))), + "{step:?}: {r:?}" + ); + // same process view: no content ever, and a pending state is named + let v = m.inspect(&g("work")).unwrap(); + assert!( + v.iter().all(|i| i.text.is_none()) || step == Step::MarkerWritten, + "{step:?}" + ); + if matches!( + step, + Step::KeyUnlinked + | Step::KeysDestroyed + | Step::TempCreated + | Step::TempWritten + | Step::TempSynced + ) { + assert_eq!( + v[0].state, "forgotten (key missing, record pending)", + "{step:?}" + ); + } + // restart: recovery completes the forget + let m = f.open(); + let v = m.inspect(&g("work")).unwrap(); + assert_eq!(v.len(), 1, "{step:?}"); + assert_eq!( + (v[0].state.as_str(), v[0].text.clone()), + ("forgotten", None), + "{step:?}" + ); + assert!(m.recall(&g("work"), None, &lim()).unwrap().items.is_empty()); + assert_eq!( + texts(&m.recall(&g("personal"), None, &lim()).unwrap()), + ["bystander"] + ); + assert_eq!(key_files(&f).len(), 1, "{step:?}"); + assert!(files(&f.dir().join("pending")).is_empty(), "{step:?}"); + // forgetting twice is not possible, and the chain is intact for new writes + assert!(matches!( + m.forget(&InspectAll::owner(), ForgetTarget::Item(a.clone())), + Err(MemoryRefusal::NothingToForget) + )); + m.put(Scope::Work, Kind::Fact, "after").unwrap(); + } + } +} + +#[test] +fn crash_at_every_put_step_leaves_a_clean_store() { + for step in [ + Step::KeyWritten, + Step::TempCreated, + Step::TempWritten, + Step::TempSynced, + Step::Linked, + Step::DirSynced, + Step::TempRemoved, + ] { + let f = fx(); + let m = f.open(); + m.put(Scope::Work, Kind::Fact, "first").unwrap(); + let (hook, fired) = once(step); + let m = m.with_fault_hook(hook); + assert!(matches!( + m.put(Scope::Work, Kind::Fact, "second"), + Err(MemoryRefusal::Crashed(_)) + )); + assert!(fired.load(Ordering::SeqCst)); + let m = f.open(); + let got = texts(&m.recall(&g("work"), None, &lim()).unwrap()); + let record_exists = matches!(step, Step::Linked | Step::DirSynced | Step::TempRemoved); + assert_eq!( + got, + if record_exists { + vec!["first", "second"] + } else { + vec!["first"] + }, + "{step:?}" + ); + m.put(Scope::Work, Kind::Fact, "third").unwrap(); + assert_eq!( + m.recall(&g("work"), None, &lim()).unwrap().items.len(), + got.len() + 1 + ); + } +} + +#[test] +fn restoring_old_keys_after_forget_cannot_resurrect_content() { + let f = fx(); + let m = f.open(); + let a = m.put(Scope::Work, Kind::Fact, "restorable?").unwrap(); + let bk = f.dir().join("keys-backup"); + copy_dir(&f.dir().join("keys"), &bk); // backup taken BEFORE the forget + m.forget(&InspectAll::owner(), ForgetTarget::Item(a)) + .unwrap(); + assert!(key_files(&f).is_empty()); + // restore the pre-forget keys over the live store + for k in files(&bk) { + std::fs::copy(&k, f.dir().join("keys").join(k.file_name().unwrap())).unwrap(); + } + assert_eq!(key_files(&f).len(), 1); + // without recovery the old key would decrypt; reapply_forgets destroys it + assert_eq!(m.reapply_forgets().unwrap(), 1); + assert!(key_files(&f).is_empty()); + // same through a restart + for k in files(&bk) { + std::fs::copy(&k, f.dir().join("keys").join(k.file_name().unwrap())).unwrap(); + } + let m = f.open(); + assert!(key_files(&f).is_empty()); + assert!(m.recall(&g("work"), None, &lim()).unwrap().items.is_empty()); + assert!(m + .inspect(&g("work")) + .unwrap() + .iter() + .all(|i| i.text.is_none())); +} + +#[test] +fn missing_key_for_a_never_forgotten_item_is_unresolved() { + let f = fx(); + let m = f.open(); + let a = m.put(Scope::Work, Kind::Fact, "lost key").unwrap(); + m.put(Scope::Work, Kind::Fact, "fine").unwrap(); + std::fs::remove_file(&key_files(&f)[0]).unwrap(); + let v = m.inspect(&g("work")).unwrap(); + let bad: Vec<_> = v + .iter() + .filter(|i| i.state == "Unresolved: key missing") + .collect(); + assert_eq!(bad.len(), 1); + assert!(bad[0].text.is_none()); + let r = m.recall(&g("work"), None, &lim()).unwrap(); + assert_eq!(r.items.len(), 1); + assert_eq!(r.unresolved.len(), 1); + // reopening does not "complete a forget" nobody asked for + let m = f.open(); + assert_eq!( + m.inspect(&g("work")) + .unwrap() + .iter() + .filter(|i| i.state.starts_with("Unresolved")) + .count(), + 1 + ); + let _ = a; +} + +// ---------- identity, damage, tamper ---------- + +#[test] +fn not_engaged_and_foreign_identity_refused() { + let f = fx(); + assert_eq!( + Memory::open(&f.home, None).err(), + Some(MemoryRefusal::NotEngaged) + ); + f.open().put(Scope::Work, Kind::Fact, "mine").unwrap(); + let other = Memory::open(&f.home, Some(&resolved(2))); + assert!(matches!(other, Err(MemoryRefusal::ForeignMemory(_)))); + // same agent, different root is foreign too + let mut r = resolved(1); + r.root = [9; 32]; + assert!(matches!( + Memory::open(&f.home, Some(&r)), + Err(MemoryRefusal::ForeignMemory(_)) + )); + // nothing was changed by the refusals + assert_eq!( + texts(&f.open().recall(&g("work"), None, &lim()).unwrap()), + ["mine"] + ); +} + +#[test] +fn damaged_unknown_and_oversize_records_are_refused_not_replaced() { + let cases: Vec = vec![ + ( + "garbage", + Box::new(|f| std::fs::write(last_record(f), b"{nope").unwrap()), + ), + ( + "unknown schema", + Box::new(|f| edit_last(f, |v| v["schema"] = "aien.allen.memory/2".into())), + ), + ( + "unknown field", + Box::new(|f| edit_last(f, |v| v["extra"] = 1.into())), + ), + ( + "unknown op field", + Box::new(|f| edit_last(f, |v| v["op"]["note"] = "x".into())), + ), + ( + "oversize", + Box::new(|f| std::fs::write(last_record(f), vec![b' '; 9000]).unwrap()), + ), + ( + "stray file", + Box::new(|f| std::fs::write(f.dir().join("log").join("readme.txt"), b"x").unwrap()), + ), + ( + "gap", + Box::new(|f| { + std::fs::rename( + last_record(f), + f.dir().join("log").join("l00000000000000000009.json"), + ) + .unwrap(); + }), + ), + ( + "chain break", + Box::new(|f| edit_last(f, |v| v["prev_sha256"] = "1".repeat(64).into())), + ), + ( + "bad scope", + Box::new(|f| edit_last(f, |v| v["op"]["scope"] = "everything".into())), + ), + ]; + for (name, damage) in cases { + let f = fx(); + let m = f.open(); + m.put(Scope::Work, Kind::Fact, "one").unwrap(); + m.put(Scope::Work, Kind::Fact, "two").unwrap(); + damage(&f); + let before: Vec<_> = files(&f.dir().join("log")); + let r = Memory::open(&f.home, Some(&resolved(1))); + assert!( + matches!(r, Err(MemoryRefusal::Damaged(_))), + "{name}: {:?}", + r.err() + ); + assert_eq!( + before, + files(&f.dir().join("log")), + "{name}: store was changed" + ); + } +} + +#[test] +fn tampered_ciphertext_or_bound_data_is_refused() { + // ciphertext flipped + let f = fx(); + let m = f.open(); + m.put(Scope::Work, Kind::Fact, "authentic").unwrap(); + edit_last(&f, |v| { + let c = v["op"]["ciphertext"].as_str().unwrap().to_string(); + let flip = if c.starts_with('0') { "1" } else { "0" }; + v["op"]["ciphertext"] = format!("{flip}{}", &c[1..]).into(); + }); + let m = f.open(); + assert!(matches!( + m.recall(&g("work"), None, &lim()), + Err(MemoryRefusal::Tampered(_)) + )); + assert!(m.inspect(&g("work")).unwrap()[0] + .state + .starts_with("Unresolved")); + // scope relabelled (AAD binds the scope) + let f = fx(); + let m = f.open(); + m.put(Scope::Work, Kind::Fact, "authentic").unwrap(); + edit_last(&f, |v| v["op"]["scope"] = "personal".into()); + let m = f.open(); + assert!(matches!( + m.recall(&g("personal"), None, &lim()), + Err(MemoryRefusal::Tampered(_)) + )); + assert!(m.recall(&g("work"), None, &lim()).unwrap().items.is_empty()); +} + +#[test] +fn ciphertext_cannot_be_moved_to_another_item() { + let f = fx(); + let m = f.open(); + m.put(Scope::Work, Kind::Fact, "first").unwrap(); + let a = std::fs::read_to_string(last_record(&f)).unwrap(); + let a: serde_json::Value = serde_json::from_str(&a).unwrap(); + m.put(Scope::Work, Kind::Fact, "second").unwrap(); + edit_last(&f, |v| { + v["op"]["ciphertext"] = a["op"]["ciphertext"].clone(); + v["op"]["nonce"] = a["op"]["nonce"].clone(); + }); + let m = f.open(); + assert!(matches!( + m.recall(&g("work"), None, &lim()), + Err(MemoryRefusal::Tampered(_)) + )); +} + +// ---------- export and goals ---------- + +#[test] +fn export_has_live_plaintext_of_one_scope_only() { + let f = fx(); + let m = f.open(); + let a = m.put(Scope::Work, Kind::Fact, "export me").unwrap(); + let b = m.put(Scope::Work, Kind::Fact, "forgotten one").unwrap(); + m.put(Scope::Personal, Kind::Fact, "not in work export") + .unwrap(); + m.forget(&InspectAll::owner(), ForgetTarget::Item(b)) + .unwrap(); + let j = m.export(&g("work")).unwrap(); + let v: serde_json::Value = serde_json::from_str(&j).unwrap(); + assert_eq!(v["scope"], "work"); + assert_eq!(v["items"].as_array().unwrap().len(), 1); + assert_eq!(v["items"][0]["item"], a.as_str()); + assert_eq!(v["items"][0]["text"], "export me"); + assert!(!j.contains("forgotten one") && !j.contains("not in work export")); +} + +#[test] +fn host_goals_open_close_and_are_labelled() { + let f = fx(); + let m = f.open(); + let a = m + .put(Scope::Work, Kind::Goal, "ship the memory crate") + .unwrap(); + let b = m.put(Scope::Work, Kind::Goal, "second goal").unwrap(); + m.put(Scope::Work, Kind::Fact, "not a goal").unwrap(); + m.put(Scope::Personal, Kind::Goal, "personal goal").unwrap(); + let l = m.goals(&g("work")).unwrap(); + assert_eq!(l.label, "host goal record, not a subject intent"); + assert_eq!(l.goals.len(), 2); + assert!(l + .goals + .iter() + .all(|x| x.state == "open" && x.label == GOAL_LABEL && x.scope == "work")); + m.close_goal(&InspectAll::owner(), &a).unwrap(); + let l = m.goals(&g("work")).unwrap(); + assert_eq!( + l.goals.iter().find(|x| x.item == a).unwrap().state, + "closed" + ); + assert_eq!( + l.goals.iter().find(|x| x.item == a).unwrap().text, + "ship the memory crate" + ); + // closed goals are not offered to context assembly + let r = m.recall(&g("work"), None, &lim()).unwrap(); + assert!(texts(&r).iter().all(|t| t != "ship the memory crate")); + let open_goal = r.items.iter().find(|i| i.item == b).unwrap(); + assert_eq!(open_goal.label, Some(GOAL_LABEL)); + assert_eq!(m.goals_all(&InspectAll::owner()).unwrap().goals.len(), 3); + assert!(matches!( + m.close_goal(&InspectAll::owner(), &a), + Err(MemoryRefusal::Invalid(_)) + )); + let fact = m + .inspect(&g("work")) + .unwrap() + .into_iter() + .find(|i| i.kind == Kind::Fact) + .unwrap(); + assert!(matches!( + m.close_goal(&InspectAll::owner(), &fact.item), + Err(MemoryRefusal::NotAGoal(_)) + )); + // survives restart; forgetting a goal removes it from the list + let m = f.open(); + assert_eq!(m.goals(&g("work")).unwrap().goals.len(), 2); + m.forget(&InspectAll::owner(), ForgetTarget::Item(b)) + .unwrap(); + assert_eq!(m.goals(&g("work")).unwrap().goals.len(), 1); +} + +#[test] +fn no_memory_or_goal_field_leaks_into_the_profile_schema() { + // This crate does not depend on aien-allen-profile and never reads or writes .allen-profile. + let f = fx(); + f.open().put(Scope::Work, Kind::Goal, "g").unwrap(); + assert!(!f.home.with_file_name("home.allen-profile").exists()); + assert!(f.home.with_file_name("home.allen-memory").exists()); +} + +// ---------- review fixes ---------- + +#[test] +fn crash_at_every_correct_step_leaves_no_orphan_and_retry_works() { + for step in [ + Step::KeyWritten, + Step::TempCreated, + Step::TempWritten, + Step::TempSynced, + Step::Linked, + Step::DirSynced, + Step::TempRemoved, + Step::KeyZeroed, + Step::KeyUnlinked, + Step::KeysDestroyed, + Step::SupersededKeyDestroyed, + ] { + let f = fx(); + let m = f.open(); + let a = m.put(Scope::Work, Kind::Fact, "old").unwrap(); + let (hook, fired) = once(step); + let m = m.with_fault_hook(hook); + let r = m.correct(&InspectAll::owner(), &a, "new"); + assert!(fired.load(Ordering::SeqCst), "{step:?} never reached"); + assert!( + matches!(r, Err(MemoryRefusal::Crashed(_))), + "{step:?}: {r:?}" + ); + let m = f.open(); + let applied = !matches!( + step, + Step::KeyWritten | Step::TempCreated | Step::TempWritten | Step::TempSynced + ); + let expect = if applied { "new" } else { "old" }; + assert_eq!( + texts(&m.recall(&g("work"), None, &lim()).unwrap()), + [expect], + "{step:?}" + ); + // exactly one key remains: no orphan, no superseded key + assert_eq!(key_files(&f).len(), 1, "{step:?}"); + let before = m.recall(&g("work"), None, &lim()).unwrap().items[0].version; + // the retry must succeed (this failed forever with "File exists" before) + let v = m.correct(&InspectAll::owner(), &a, "retry").unwrap(); + assert_eq!(v, before + 1, "{step:?}"); + assert_eq!( + texts(&m.recall(&g("work"), None, &lim()).unwrap()), + ["retry"], + "{step:?}" + ); + assert_eq!(key_files(&f).len(), 1, "{step:?}"); + } +} + +#[test] +fn correct_retry_works_even_without_reopen_after_orphan_key() { + let f = fx(); + let m = f.open(); + let a = m.put(Scope::Work, Kind::Fact, "old").unwrap(); + let (hook, _) = once(Step::KeyWritten); + let m = m.with_fault_hook(hook); + assert!(m.correct(&InspectAll::owner(), &a, "new").is_err()); + assert_eq!(key_files(&f).len(), 2); // old + orphan + assert_eq!(m.correct(&InspectAll::owner(), &a, "new").unwrap(), 2); + assert_eq!(texts(&m.recall(&g("work"), None, &lim()).unwrap()), ["new"]); + assert_eq!(key_files(&f).len(), 1); +} + +#[test] +fn orphan_key_of_a_crashed_put_is_swept_on_open() { + let f = fx(); + let m = f.open(); + let (hook, _) = once(Step::KeyWritten); + let m = m.with_fault_hook(hook); + assert!(m.put(Scope::Work, Kind::Fact, "x").is_err()); + assert_eq!(key_files(&f).len(), 1); + f.open(); + assert!(key_files(&f).is_empty()); +} + +#[test] +fn changes_need_a_grant_for_the_items_scope() { + let f = fx(); + let m = f.open(); + let w = m.put(Scope::Work, Kind::Goal, "work goal").unwrap(); + let p = m.put(Scope::Personal, Kind::Fact, "personal fact").unwrap(); + let work = g("work"); + assert!(matches!( + m.correct(&work, &p, "x"), + Err(MemoryRefusal::ScopeMismatch(_)) + )); + assert!(matches!( + m.close_goal(&g("personal"), &w), + Err(MemoryRefusal::ScopeMismatch(_)) + )); + assert!(matches!( + m.forget(&work, ForgetTarget::Item(p.clone())), + Err(MemoryRefusal::ScopeMismatch(_)) + )); + assert!(matches!( + m.forget(&work, ForgetTarget::Scope(Scope::Personal)), + Err(MemoryRefusal::ScopeMismatch(_)) + )); + // nothing changed + assert_eq!( + texts(&m.recall(&g("personal"), None, &lim()).unwrap()), + ["personal fact"] + ); + assert_eq!(key_files(&f).len(), 2); + // the matching grant works + assert_eq!(m.correct(&work, &w, "work goal v2").unwrap(), 2); + m.close_goal(&work, &w).unwrap(); + assert_eq!( + m.forget(&work, ForgetTarget::Scope(Scope::Work)) + .unwrap() + .len(), + 1 + ); +} + +#[test] +fn kind_is_bound_into_the_encryption() { + let f = fx(); + let m = f.open(); + m.put(Scope::Work, Kind::Fact, "a fact").unwrap(); + edit_last(&f, |v| v["op"]["kind"] = "goal".into()); + let m = f.open(); + assert!(matches!( + m.recall(&g("work"), None, &lim()), + Err(MemoryRefusal::Tampered(_)) + )); +} + +#[cfg(unix)] +#[test] +fn symlinked_key_is_refused_and_its_target_is_never_zeroed() { + use std::os::unix::fs::symlink; + let f = fx(); + let m = f.open(); + let a = m.put(Scope::Work, Kind::Fact, "x").unwrap(); + let k = key_files(&f)[0].clone(); + let target = f.dir().join("precious"); + std::fs::write(&target, b"precious bytes").unwrap(); + std::fs::remove_file(&k).unwrap(); + symlink(&target, &k).unwrap(); + let v = m.inspect(&g("work")).unwrap(); + assert!(v[0].state.starts_with("Unresolved"), "{}", v[0].state); + let r = m.forget(&InspectAll::owner(), ForgetTarget::Item(a)); + assert!(matches!(r, Err(MemoryRefusal::Damaged(_))), "{r:?}"); + assert_eq!(std::fs::read(&target).unwrap(), b"precious bytes"); + // reopening refuses too, and still does not touch the target + assert!(Memory::open(&f.home, Some(&resolved(1))).is_err()); + assert_eq!(std::fs::read(&target).unwrap(), b"precious bytes"); +} + +#[cfg(unix)] +#[test] +fn symlinked_keys_folder_is_refused_and_loose_modes_are_tightened() { + use std::os::unix::fs::{symlink, PermissionsExt}; + let f = fx(); + f.open().put(Scope::Work, Kind::Fact, "x").unwrap(); + let keys = f.dir().join("keys"); + std::fs::set_permissions(&keys, std::fs::Permissions::from_mode(0o755)).unwrap(); + f.open(); + assert_eq!( + std::fs::metadata(&keys).unwrap().permissions().mode() & 0o777, + 0o700 + ); + let moved = f.dir().join("keys-real"); + std::fs::rename(&keys, &moved).unwrap(); + symlink(&moved, &keys).unwrap(); + assert!(matches!( + Memory::open(&f.home, Some(&resolved(1))), + Err(MemoryRefusal::Damaged(_)) + )); +} + +#[cfg(unix)] +#[test] +fn marker_files_are_private() { + use std::os::unix::fs::PermissionsExt; + let f = fx(); + let m = f.open(); + let a = m.put(Scope::Work, Kind::Fact, "x").unwrap(); + let (hook, _) = once(Step::MarkerWritten); + let m = m.with_fault_hook(hook); + assert!(m + .forget(&InspectAll::owner(), ForgetTarget::Item(a)) + .is_err()); + let ms = files(&f.dir().join("pending")); + assert_eq!(ms.len(), 1); + assert_eq!( + std::fs::metadata(&ms[0]).unwrap().permissions().mode() & 0o777, + 0o600 + ); +} + +#[test] +fn stale_temp_files_in_the_log_are_removed_on_open() { + let f = fx(); + f.open().put(Scope::Work, Kind::Fact, "x").unwrap(); + let stale = f.dir().join("log").join(".tmp-123-0-456"); + std::fs::write(&stale, b"half a record").unwrap(); + let m = f.open(); + assert!(!stale.exists()); + assert_eq!(texts(&m.recall(&g("work"), None, &lim()).unwrap()), ["x"]); + // an unexpected non-temp name is still a refusal + std::fs::write(f.dir().join("log").join("notes.txt"), b"x").unwrap(); + assert!(matches!( + Memory::open(&f.home, Some(&resolved(1))), + Err(MemoryRefusal::Damaged(_)) + )); +} + +#[test] +fn read_only_open_and_open_during_a_held_writer_lock_do_not_sweep() { + let f = fx(); + let m = f.open(); + m.put(Scope::Work, Kind::Fact, "x").unwrap(); + let orphan = f + .dir() + .join("keys") + .join(format!("{}-v1.key", "ab".repeat(16))); + std::fs::write(&orphan, [1u8; 32]).unwrap(); + let stale = f.dir().join("log").join(".tmp-9-9-9"); + std::fs::write(&stale, b"in flight").unwrap(); + // another process holds the writer lock (simulated by a second handle) + let lock = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(f.dir().join("lock")) + .unwrap(); + lock.lock().unwrap(); + let ro = Memory::open_read_only(&f.home, Some(&resolved(1))).unwrap(); + assert_eq!(texts(&ro.recall(&g("work"), None, &lim()).unwrap()), ["x"]); + assert!(orphan.exists() && stale.exists()); + assert!(ro.put(Scope::Work, Kind::Fact, "no").is_err()); + let m2 = f.open(); // lock busy: verifies only + assert!(orphan.exists() && stale.exists()); + assert_eq!(texts(&m2.recall(&g("work"), None, &lim()).unwrap()), ["x"]); + lock.unlock().unwrap(); + drop(lock); + // lock free again: a normal open sweeps + f.open(); + assert!(!orphan.exists() && !stale.exists()); +} ```