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
aien-sovereign-core-mv / crates / spark-crumbs / tests / local_state.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! core#924: `.crumb.local` notes through the real `spark-crumbs` binary |
| 17 | //! (separate processes) and the library (threads in this process). |
| 18 | //! |
| 19 | //! - concurrent writers lose no update (flock-serialised read-modify-write); |
| 20 | //! - malformed, unreadable or unwritable state is an error, never "no peers" |
| 21 | //! and never a success line; |
| 22 | //! - every worker gets its own identity, so peers see each other. |
| 23 | |
| 24 | use std::path::{Path, PathBuf}; |
| 25 | use std::process::{Command, Output}; |
| 26 | use std::sync::{Arc, Barrier}; |
| 27 | |
| 28 | const BIN: &str = env!("CARGO_BIN_EXE_spark-crumbs"); |
| 29 | |
| 30 | struct Scratch(PathBuf); |
| 31 | |
| 32 | impl Scratch { |
| 33 | fn new(tag: &str) -> Self { |
| 34 | let p = std::env::temp_dir().join(format!( |
| 35 | "spark-crumbs-{}-{}-{}", |
| 36 | tag, |
| 37 | std::process::id(), |
| 38 | uuid::Uuid::new_v4().simple() |
| 39 | )); |
| 40 | std::fs::create_dir_all(&p).expect("scratch dir"); |
| 41 | Scratch(p) |
| 42 | } |
| 43 | fn dir(&self, name: &str) -> PathBuf { |
| 44 | let d = self.0.join(name); |
| 45 | std::fs::create_dir_all(&d).expect("work dir"); |
| 46 | d |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | impl Drop for Scratch { |
| 51 | fn drop(&mut self) { |
| 52 | restore_modes(&self.0); |
| 53 | let _ = std::fs::remove_dir_all(&self.0); |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | #[cfg(unix)] |
| 58 | fn restore_modes(root: &Path) { |
| 59 | use std::os::unix::fs::PermissionsExt; |
| 60 | let _ = std::fs::set_permissions(root, std::fs::Permissions::from_mode(0o755)); |
| 61 | if let Ok(entries) = std::fs::read_dir(root) { |
| 62 | for e in entries.flatten() { |
| 63 | let p = e.path(); |
| 64 | let mode = if p.is_dir() { 0o755 } else { 0o644 }; |
| 65 | let _ = std::fs::set_permissions(&p, std::fs::Permissions::from_mode(mode)); |
| 66 | if p.is_dir() { |
| 67 | restore_modes(&p); |
| 68 | } |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | #[cfg(not(unix))] |
| 74 | fn restore_modes(_root: &Path) {} |
| 75 | |
| 76 | /// The binary with a clean identity environment and a HOME that holds no |
| 77 | /// workspace, so a record never bubbles into the scratch parent. |
| 78 | fn cli(home: &Path) -> Command { |
| 79 | let mut c = Command::new(BIN); |
| 80 | for k in [ |
| 81 | "AIEN_AGENT_ID", |
| 82 | "AIEN_AGENT_NAME", |
| 83 | "AIEN_SESSION_ID", |
| 84 | "HERMES_SESSION_ID", |
| 85 | ] { |
| 86 | c.env_remove(k); |
| 87 | } |
| 88 | c.env("HOME", home).env("NO_COLOR", "1"); |
| 89 | c |
| 90 | } |
| 91 | |
| 92 | fn local_json(dir: &Path) -> serde_json::Value { |
| 93 | let text = std::fs::read_to_string(dir.join(".crumb.local")).expect("read .crumb.local"); |
| 94 | serde_json::from_str(&text).expect("parse .crumb.local") |
| 95 | } |
| 96 | |
| 97 | fn count(dir: &Path, field: &str) -> usize { |
| 98 | local_json(dir)[field] |
| 99 | .as_array() |
| 100 | .map(|a| a.len()) |
| 101 | .unwrap_or(0) |
| 102 | } |
| 103 | |
| 104 | fn show(o: &Output) -> String { |
| 105 | format!( |
| 106 | "status {:?}\nstdout {}\nstderr {}", |
| 107 | o.status.code(), |
| 108 | String::from_utf8_lossy(&o.stdout), |
| 109 | String::from_utf8_lossy(&o.stderr) |
| 110 | ) |
| 111 | } |
| 112 | |
| 113 | /// N threads and M processes each append K history entries at once. Every |
| 114 | /// entry must survive: the total is exactly (N + M) * K (under the cap of 50). |
| 115 | #[test] |
| 116 | fn concurrent_records_from_threads_and_processes_lose_no_update() { |
| 117 | const N: usize = 4; // threads |
| 118 | const M: usize = 4; // concurrent process lanes |
| 119 | const K: usize = 6; // entries per writer |
| 120 | let s = Scratch::new("race-history"); |
| 121 | let dir = s.dir("work"); |
| 122 | let home = s.0.join("no-home"); |
| 123 | let barrier = Arc::new(Barrier::new(N + M)); |
| 124 | let mut handles = Vec::new(); |
| 125 | for t in 0..N { |
| 126 | let (dir, barrier) = (dir.clone(), barrier.clone()); |
| 127 | handles.push(std::thread::spawn(move || { |
| 128 | barrier.wait(); |
| 129 | for k in 0..K { |
| 130 | spark_crumbs::record_crumb_action( |
| 131 | &dir, |
| 132 | &format!("thread{t}"), |
| 133 | &format!("s{t}"), |
| 134 | "edit", |
| 135 | "f.rs", |
| 136 | &format!("t{t}k{k}"), |
| 137 | "v", |
| 138 | ) |
| 139 | .expect("record"); |
| 140 | } |
| 141 | })); |
| 142 | } |
| 143 | for m in 0..M { |
| 144 | let (dir, barrier, home) = (dir.clone(), barrier.clone(), home.clone()); |
| 145 | handles.push(std::thread::spawn(move || { |
| 146 | barrier.wait(); |
| 147 | for k in 0..K { |
| 148 | let o = cli(&home) |
| 149 | .args(["record", dir.to_str().unwrap()]) |
| 150 | .args(["--agent", &format!("proc{m}")]) |
| 151 | .args(["--action", "edit", "--target", "f.rs"]) |
| 152 | .args(["--intent", &format!("p{m}k{k}"), "--vector", "v"]) |
| 153 | .output() |
| 154 | .expect("spawn spark-crumbs"); |
| 155 | assert!(o.status.success(), "record failed: {}", show(&o)); |
| 156 | } |
| 157 | })); |
| 158 | } |
| 159 | for h in handles { |
| 160 | h.join().expect("writer"); |
| 161 | } |
| 162 | let got = count(&dir, "history"); |
| 163 | println!("RACE history expected {} got {}", (N + M) * K, got); |
| 164 | assert_eq!(got, (N + M) * K, "lost {} updates", (N + M) * K - got); |
| 165 | } |
| 166 | |
| 167 | /// The same for whispers (cap 30). |
| 168 | #[test] |
| 169 | fn concurrent_whispers_from_threads_and_processes_lose_no_update() { |
| 170 | const N: usize = 3; |
| 171 | const M: usize = 3; |
| 172 | const K: usize = 5; |
| 173 | let s = Scratch::new("race-whisper"); |
| 174 | let dir = s.dir("work"); |
| 175 | let home = s.0.join("no-home"); |
| 176 | let barrier = Arc::new(Barrier::new(N + M)); |
| 177 | let mut handles = Vec::new(); |
| 178 | for t in 0..N { |
| 179 | let (dir, barrier) = (dir.clone(), barrier.clone()); |
| 180 | handles.push(std::thread::spawn(move || { |
| 181 | barrier.wait(); |
| 182 | for k in 0..K { |
| 183 | spark_crumbs::add_crumb_whisper( |
| 184 | &dir, |
| 185 | &format!("thread{t}"), |
| 186 | &format!("whisper t{t} k{k}"), |
| 187 | None, |
| 188 | ) |
| 189 | .expect("whisper"); |
| 190 | } |
| 191 | })); |
| 192 | } |
| 193 | for m in 0..M { |
| 194 | let (dir, barrier, home) = (dir.clone(), barrier.clone(), home.clone()); |
| 195 | handles.push(std::thread::spawn(move || { |
| 196 | barrier.wait(); |
| 197 | for k in 0..K { |
| 198 | let o = cli(&home) |
| 199 | .args(["whisper", dir.to_str().unwrap()]) |
| 200 | .args(["--agent", &format!("proc{m}")]) |
| 201 | .args(["--message", &format!("whisper p{m} k{k}")]) |
| 202 | .output() |
| 203 | .expect("spawn spark-crumbs"); |
| 204 | assert!(o.status.success(), "whisper failed: {}", show(&o)); |
| 205 | } |
| 206 | })); |
| 207 | } |
| 208 | for h in handles { |
| 209 | h.join().expect("writer"); |
| 210 | } |
| 211 | let got = count(&dir, "whispers"); |
| 212 | println!("RACE whispers expected {} got {}", (N + M) * K, got); |
| 213 | assert_eq!(got, (N + M) * K, "lost {} updates", (N + M) * K - got); |
| 214 | } |
| 215 | |
| 216 | /// A malformed `.crumb.local` is an error: the write fails visibly and the |
| 217 | /// file is left as found, and sniff does not report "no peers". |
| 218 | #[test] |
| 219 | fn malformed_local_state_is_an_error_and_is_not_overwritten() { |
| 220 | let s = Scratch::new("malformed"); |
| 221 | let dir = s.dir("work"); |
| 222 | let home = s.0.join("no-home"); |
| 223 | let garbage = "{ \"history\": [ not json"; |
| 224 | std::fs::write(dir.join(".crumb.local"), garbage).unwrap(); |
| 225 | |
| 226 | let w = cli(&home) |
| 227 | .args(["whisper", dir.to_str().unwrap(), "--agent", "a1"]) |
| 228 | .args(["--message", "hello"]) |
| 229 | .output() |
| 230 | .unwrap(); |
| 231 | let after = std::fs::read_to_string(dir.join(".crumb.local")).unwrap(); |
| 232 | println!( |
| 233 | "MALFORMED whisper exit {:?} file_preserved {}", |
| 234 | w.status.code(), |
| 235 | after == garbage |
| 236 | ); |
| 237 | assert!( |
| 238 | !w.status.success(), |
| 239 | "whisper reported success: {}", |
| 240 | show(&w) |
| 241 | ); |
| 242 | assert_eq!(after, garbage, "malformed state was overwritten"); |
| 243 | |
| 244 | let sn = cli(&home) |
| 245 | .args(["sniff", dir.to_str().unwrap(), "--agent", "a2"]) |
| 246 | .output() |
| 247 | .unwrap(); |
| 248 | println!("MALFORMED sniff exit {:?}", sn.status.code()); |
| 249 | assert!( |
| 250 | !sn.status.success(), |
| 251 | "sniff hid malformed state: {}", |
| 252 | show(&sn) |
| 253 | ); |
| 254 | } |
| 255 | |
| 256 | /// An unreadable `.crumb.local` (mode 000) is an error for writers and readers. |
| 257 | #[cfg(unix)] |
| 258 | #[test] |
| 259 | fn unreadable_local_state_is_an_error() { |
| 260 | use std::os::unix::fs::PermissionsExt; |
| 261 | let s = Scratch::new("unreadable"); |
| 262 | let dir = s.dir("work"); |
| 263 | let home = s.0.join("no-home"); |
| 264 | let local = dir.join(".crumb.local"); |
| 265 | std::fs::write(&local, "{\"history\":[],\"whispers\":[]}").unwrap(); |
| 266 | std::fs::set_permissions(&local, std::fs::Permissions::from_mode(0o000)).unwrap(); |
| 267 | if std::fs::read(&local).is_ok() { |
| 268 | eprintln!("SKIP: running with privileges that ignore mode 000"); |
| 269 | return; |
| 270 | } |
| 271 | let w = cli(&home) |
| 272 | .args(["whisper", dir.to_str().unwrap(), "--agent", "a1"]) |
| 273 | .args(["--message", "hello"]) |
| 274 | .output() |
| 275 | .unwrap(); |
| 276 | println!("UNREADABLE whisper exit {:?}", w.status.code()); |
| 277 | assert!( |
| 278 | !w.status.success(), |
| 279 | "whisper reported success: {}", |
| 280 | show(&w) |
| 281 | ); |
| 282 | let sn = cli(&home) |
| 283 | .args(["sniff", dir.to_str().unwrap(), "--agent", "a2"]) |
| 284 | .output() |
| 285 | .unwrap(); |
| 286 | println!("UNREADABLE sniff exit {:?}", sn.status.code()); |
| 287 | assert!( |
| 288 | !sn.status.success(), |
| 289 | "sniff hid unreadable state: {}", |
| 290 | show(&sn) |
| 291 | ); |
| 292 | } |
| 293 | |
| 294 | /// A directory that cannot be written: the save error is surfaced (non-zero |
| 295 | /// exit, no success line). |
| 296 | #[cfg(unix)] |
| 297 | #[test] |
| 298 | fn unwritable_directory_save_error_is_surfaced() { |
| 299 | use std::os::unix::fs::PermissionsExt; |
| 300 | let s = Scratch::new("unwritable"); |
| 301 | let dir = s.dir("work"); |
| 302 | let home = s.0.join("no-home"); |
| 303 | std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o555)).unwrap(); |
| 304 | if std::fs::write(dir.join("probe"), "x").is_ok() { |
| 305 | eprintln!("SKIP: running with privileges that ignore mode 555"); |
| 306 | return; |
| 307 | } |
| 308 | let w = cli(&home) |
| 309 | .args(["whisper", dir.to_str().unwrap(), "--agent", "a1"]) |
| 310 | .args(["--message", "hello"]) |
| 311 | .output() |
| 312 | .unwrap(); |
| 313 | let stdout = String::from_utf8_lossy(&w.stdout).to_string(); |
| 314 | println!( |
| 315 | "UNWRITABLE whisper exit {:?} printed_success {}", |
| 316 | w.status.code(), |
| 317 | stdout.contains("Planted whisper") |
| 318 | ); |
| 319 | assert!( |
| 320 | !w.status.success(), |
| 321 | "whisper reported success: {}", |
| 322 | show(&w) |
| 323 | ); |
| 324 | assert!(!stdout.contains("Planted whisper"), "success line printed"); |
| 325 | let r = cli(&home) |
| 326 | .args(["record", dir.to_str().unwrap(), "--agent", "a1"]) |
| 327 | .args([ |
| 328 | "--action", "edit", "--target", "f", "--intent", "i", "--vector", "v", |
| 329 | ]) |
| 330 | .output() |
| 331 | .unwrap(); |
| 332 | println!("UNWRITABLE record exit {:?}", r.status.code()); |
| 333 | assert!(!r.status.success(), "record reported success: {}", show(&r)); |
| 334 | } |
| 335 | |
| 336 | /// Two workers started with no explicit `--agent` get distinct identities from |
| 337 | /// their environment and see each other's records in sniff. Workers with no |
| 338 | /// identity environment at all still get distinct, generated ids. The shared |
| 339 | /// constants never appear. |
| 340 | #[test] |
| 341 | fn two_workers_get_distinct_ids_and_see_each_other() { |
| 342 | let s = Scratch::new("identity"); |
| 343 | let dir = s.dir("work"); |
| 344 | let home = s.0.join("no-home"); |
| 345 | std::fs::write(dir.join("shared.rs"), "fn main() {}\n").unwrap(); |
| 346 | let target = dir.join("shared.rs"); |
| 347 | let worker = |session: &str| { |
| 348 | let mut c = cli(&home); |
| 349 | c.env("AIEN_AGENT_NAME", "worker") |
| 350 | .env("AIEN_SESSION_ID", session); |
| 351 | c |
| 352 | }; |
| 353 | for (session, intent) in [("s1", "edit by s1"), ("s2", "edit by s2")] { |
| 354 | let o = worker(session) |
| 355 | .args(["record", dir.to_str().unwrap()]) |
| 356 | .args(["--action", "edit", "--target", "shared.rs"]) |
| 357 | .args(["--intent", intent, "--vector", "v"]) |
| 358 | .output() |
| 359 | .unwrap(); |
| 360 | assert!(o.status.success(), "record: {}", show(&o)); |
| 361 | } |
| 362 | let sniff_as = |session: &str| { |
| 363 | let o = worker(session) |
| 364 | .args(["sniff", target.to_str().unwrap()]) |
| 365 | .output() |
| 366 | .unwrap(); |
| 367 | String::from_utf8_lossy(&o.stdout).to_string() |
| 368 | }; |
| 369 | let seen_by_s1 = sniff_as("s1"); |
| 370 | let seen_by_s2 = sniff_as("s2"); |
| 371 | println!( |
| 372 | "IDENTITY s1_sees_s2 {} s2_sees_s1 {}", |
| 373 | seen_by_s1.contains("edit by s2"), |
| 374 | seen_by_s2.contains("edit by s1") |
| 375 | ); |
| 376 | assert!( |
| 377 | seen_by_s1.contains("edit by s2"), |
| 378 | "s1 did not see s2:\n{seen_by_s1}" |
| 379 | ); |
| 380 | assert!( |
| 381 | seen_by_s2.contains("edit by s1"), |
| 382 | "s2 did not see s1:\n{seen_by_s2}" |
| 383 | ); |
| 384 | assert!( |
| 385 | !seen_by_s1.contains("edit by s1"), |
| 386 | "s1 saw itself:\n{seen_by_s1}" |
| 387 | ); |
| 388 | |
| 389 | // No identity environment: each process generates its own id. |
| 390 | let anon = s.dir("anon"); |
| 391 | for _ in 0..2 { |
| 392 | let o = cli(&home) |
| 393 | .args(["record", anon.to_str().unwrap()]) |
| 394 | .args([ |
| 395 | "--action", "edit", "--target", "x", "--intent", "i", "--vector", "v", |
| 396 | ]) |
| 397 | .output() |
| 398 | .unwrap(); |
| 399 | assert!(o.status.success(), "record: {}", show(&o)); |
| 400 | } |
| 401 | let v = local_json(&dir); |
| 402 | let a = local_json(&anon); |
| 403 | let mut ids: Vec<String> = Vec::new(); |
| 404 | let mut sessions: Vec<String> = Vec::new(); |
| 405 | for item in v["history"] |
| 406 | .as_array() |
| 407 | .unwrap() |
| 408 | .iter() |
| 409 | .chain(a["history"].as_array().unwrap()) |
| 410 | { |
| 411 | ids.push(item["agent_id"].as_str().unwrap().to_string()); |
| 412 | sessions.push(item["session_id"].as_str().unwrap().to_string()); |
| 413 | } |
| 414 | println!("IDENTITY ids {:?} sessions {:?}", ids, sessions); |
| 415 | assert_eq!(ids.len(), 4); |
| 416 | let mut unique = ids.clone(); |
| 417 | unique.sort(); |
| 418 | unique.dedup(); |
| 419 | assert_eq!(unique.len(), 4, "identities collide: {ids:?}"); |
| 420 | for id in &ids { |
| 421 | assert_ne!(id, "AIEN"); |
| 422 | } |
| 423 | for s in &sessions { |
| 424 | assert!( |
| 425 | s != "active-session" && s != "cli-session", |
| 426 | "constant session {s}" |
| 427 | ); |
| 428 | } |
| 429 | } |
| 430 | |
| 431 | /// An explicit `--agent` naming a shared constant is refused, so the CLI |
| 432 | /// cannot reintroduce the identity that hid peers. |
| 433 | #[test] |
| 434 | fn shared_constant_agent_is_refused() { |
| 435 | let s = Scratch::new("constant"); |
| 436 | let dir = s.dir("work"); |
| 437 | let home = s.0.join("no-home"); |
| 438 | for args in [ |
| 439 | vec![ |
| 440 | "whisper", |
| 441 | dir.to_str().unwrap(), |
| 442 | "--agent", |
| 443 | "AIEN", |
| 444 | "--message", |
| 445 | "m", |
| 446 | ], |
| 447 | vec!["sniff", dir.to_str().unwrap(), "--agent", "AIEN"], |
| 448 | ] { |
| 449 | let o = cli(&home).args(&args).output().unwrap(); |
| 450 | assert!(!o.status.success(), "accepted AIEN: {}", show(&o)); |
| 451 | } |
| 452 | let o = cli(&home) |
| 453 | .env("AIEN_AGENT_ID", "AIEN") |
| 454 | .args(["whisper", dir.to_str().unwrap(), "--message", "m"]) |
| 455 | .output() |
| 456 | .unwrap(); |
| 457 | assert!( |
| 458 | !o.status.success(), |
| 459 | "accepted AIEN_AGENT_ID=AIEN: {}", |
| 460 | show(&o) |
| 461 | ); |
| 462 | assert!(!dir.join(".crumb.local").exists()); |
| 463 | } |
| 464 | |
| 465 | /// `cli(home)` with the child's umask set to `mask` before exec, so the test |
| 466 | /// does not depend on the umask of whoever runs it. |
| 467 | #[cfg(unix)] |
| 468 | fn cli_with_umask(home: &Path, mask: u32) -> Command { |
| 469 | use std::os::unix::process::CommandExt; |
| 470 | let mut c = cli(home); |
| 471 | // SAFETY: umask is async-signal-safe and touches only the child. |
| 472 | unsafe { |
| 473 | c.pre_exec(move || { |
| 474 | libc::umask(mask as libc::mode_t); |
| 475 | Ok(()) |
| 476 | }); |
| 477 | } |
| 478 | c |
| 479 | } |
| 480 | |
| 481 | #[cfg(unix)] |
| 482 | fn mode_of(p: &Path) -> u32 { |
| 483 | use std::os::unix::fs::PermissionsExt; |
| 484 | std::fs::metadata(p).expect("stat").permissions().mode() & 0o7777 |
| 485 | } |
| 486 | |
| 487 | /// Replacing `.crumb.local` keeps the existing file's permissions: a private |
| 488 | /// 0600 file stays 0600 under umask 022 (before core#924 review fix it became |
| 489 | /// 0644), and its content is extended, not lost. A file with group access |
| 490 | /// keeps exactly that mode, and a new file gets the umask default. |
| 491 | #[cfg(unix)] |
| 492 | #[test] |
| 493 | fn replacement_keeps_the_existing_file_mode_under_umask_022() { |
| 494 | use std::os::unix::fs::PermissionsExt; |
| 495 | let s = Scratch::new("mode"); |
| 496 | let home = s.0.join("no-home"); |
| 497 | for (name, mode) in [("private", 0o600u32), ("group", 0o640), ("ro-owner", 0o400)] { |
| 498 | let dir = s.dir(name); |
| 499 | let local = dir.join(".crumb.local"); |
| 500 | std::fs::write( |
| 501 | &local, |
| 502 | "{\"history\":[],\"whispers\":[{\"whisper_id\":\"w0\",\"from_agent\":\"old\",\ |
| 503 | \"timestamp\":\"2026-11-06T00:00:00Z\",\"target_file\":null,\"message\":\"kept\"}]}", |
| 504 | ) |
| 505 | .unwrap(); |
| 506 | std::fs::set_permissions(&local, std::fs::Permissions::from_mode(mode)).unwrap(); |
| 507 | for (verb, extra) in [ |
| 508 | ("whisper", vec!["--message", "private note"]), |
| 509 | ( |
| 510 | "record", |
| 511 | vec![ |
| 512 | "--action", "edit", "--target", "f", "--intent", "i", "--vector", "v", |
| 513 | ], |
| 514 | ), |
| 515 | ] { |
| 516 | let o = cli_with_umask(&home, 0o022) |
| 517 | .args([verb, dir.to_str().unwrap(), "--agent", "owner-1"]) |
| 518 | .args(&extra) |
| 519 | .output() |
| 520 | .unwrap(); |
| 521 | assert!(o.status.success(), "{verb} on {name}: {}", show(&o)); |
| 522 | println!( |
| 523 | "MODE {name} {verb} before {:o} after {:o}", |
| 524 | mode, |
| 525 | mode_of(&local) |
| 526 | ); |
| 527 | assert_eq!(mode_of(&local), mode, "{verb} changed the mode of {name}"); |
| 528 | } |
| 529 | let v = local_json(&dir); |
| 530 | let msgs: Vec<&str> = v["whispers"] |
| 531 | .as_array() |
| 532 | .unwrap() |
| 533 | .iter() |
| 534 | .map(|w| w["message"].as_str().unwrap()) |
| 535 | .collect(); |
| 536 | assert_eq!(msgs, ["kept", "private note"], "{name}: content"); |
| 537 | assert_eq!(count(&dir, "history"), 1, "{name}: history"); |
| 538 | // No temp file with a wider mode is left behind. |
| 539 | let leftovers: Vec<_> = std::fs::read_dir(&dir) |
| 540 | .unwrap() |
| 541 | .flatten() |
| 542 | .filter(|e| { |
| 543 | e.file_name() |
| 544 | .to_string_lossy() |
| 545 | .starts_with(".crumb.local.tmp-") |
| 546 | }) |
| 547 | .collect(); |
| 548 | assert!(leftovers.is_empty(), "{name}: temp files left"); |
| 549 | } |
| 550 | // A new file: the default 0644 masked by the umask. |
| 551 | for (mask, want) in [(0o022u32, 0o644u32), (0o077, 0o600), (0o027, 0o640)] { |
| 552 | let dir = s.dir(&format!("new-{mask:o}")); |
| 553 | let o = cli_with_umask(&home, mask) |
| 554 | .args(["whisper", dir.to_str().unwrap(), "--agent", "owner-1"]) |
| 555 | .args(["--message", "first"]) |
| 556 | .output() |
| 557 | .unwrap(); |
| 558 | assert!(o.status.success(), "new file: {}", show(&o)); |
| 559 | let got = mode_of(&dir.join(".crumb.local")); |
| 560 | println!("MODE new umask {mask:03o} -> {got:o}"); |
| 561 | assert_eq!(got, want, "new file under umask {mask:03o}"); |
| 562 | } |
| 563 | } |
| 564 | |
| 565 | /// Raw `system.posix_acl_access` bytes of `p` (not following a final |
| 566 | /// symlink); `None` when it has no access ACL. |
| 567 | #[cfg(target_os = "linux")] |
| 568 | fn access_acl_bytes(p: &Path) -> Option<Vec<u8>> { |
| 569 | use std::os::unix::ffi::OsStrExt; |
| 570 | let c = std::ffi::CString::new(p.as_os_str().as_bytes()).unwrap(); |
| 571 | let name = c"system.posix_acl_access"; |
| 572 | let mut buf = vec![0u8; 4096]; |
| 573 | // SAFETY: NUL-terminated strings, buffer of the given length. |
| 574 | let n = unsafe { |
| 575 | libc::lgetxattr( |
| 576 | c.as_ptr(), |
| 577 | name.as_ptr(), |
| 578 | buf.as_mut_ptr().cast(), |
| 579 | buf.len(), |
| 580 | ) |
| 581 | }; |
| 582 | if n < 0 { |
| 583 | let e = std::io::Error::last_os_error(); |
| 584 | assert_eq!( |
| 585 | e.raw_os_error(), |
| 586 | Some(libc::ENODATA), |
| 587 | "lgetxattr {p:?}: {e}" |
| 588 | ); |
| 589 | return None; |
| 590 | } |
| 591 | buf.truncate(n as usize); |
| 592 | Some(buf) |
| 593 | } |
| 594 | |
| 595 | /// `getfacl -cpn` text of `p` (no header, numeric ids, effective-rights |
| 596 | /// comments included), or `None` when getfacl is not installed. |
| 597 | #[cfg(target_os = "linux")] |
| 598 | fn getfacl_text(p: &Path) -> Option<String> { |
| 599 | let o = Command::new("getfacl") |
| 600 | .args(["-cpn"]) |
| 601 | .arg(p) |
| 602 | .output() |
| 603 | .ok()?; |
| 604 | assert!(o.status.success(), "getfacl {p:?}: {}", show(&o)); |
| 605 | Some(String::from_utf8(o.stdout).unwrap()) |
| 606 | } |
| 607 | |
| 608 | /// `setfacl args... p`; `false` (the caller prints NOT_RUN) when setfacl is |
| 609 | /// missing or the filesystem refuses ACLs. |
| 610 | #[cfg(target_os = "linux")] |
| 611 | fn setfacl(args: &[&str], p: &Path) -> bool { |
| 612 | match Command::new("setfacl").args(args).arg(p).output() { |
| 613 | Ok(o) if o.status.success() => true, |
| 614 | Ok(o) => { |
| 615 | println!("NOT_RUN: setfacl {args:?} failed: {}", show(&o)); |
| 616 | false |
| 617 | } |
| 618 | Err(e) => { |
| 619 | println!("NOT_RUN: setfacl unavailable: {e}"); |
| 620 | false |
| 621 | } |
| 622 | } |
| 623 | } |
| 624 | |
| 625 | #[cfg(target_os = "linux")] |
| 626 | const SEEDED_LOCAL: &str = |
| 627 | "{\"history\":[],\"whispers\":[{\"whisper_id\":\"w0\",\"from_agent\":\"old\",\ |
| 628 | \"timestamp\":\"2026-11-06T00:00:00Z\",\"target_file\":null,\"message\":\"kept\"}]}"; |
| 629 | |
| 630 | #[cfg(target_os = "linux")] |
| 631 | fn whisper_then_record(home: &Path, dir: &Path, mut after_each: impl FnMut(&str)) { |
| 632 | for (verb, extra) in [ |
| 633 | ("whisper", vec!["--message", "private note"]), |
| 634 | ( |
| 635 | "record", |
| 636 | vec![ |
| 637 | "--action", "edit", "--target", "f", "--intent", "i", "--vector", "v", |
| 638 | ], |
| 639 | ), |
| 640 | ] { |
| 641 | let o = cli_with_umask(home, 0o022) |
| 642 | .args([verb, dir.to_str().unwrap(), "--agent", "owner-1"]) |
| 643 | .args(&extra) |
| 644 | .output() |
| 645 | .unwrap(); |
| 646 | assert!(o.status.success(), "{verb}: {}", show(&o)); |
| 647 | after_each(verb); |
| 648 | } |
| 649 | let v = local_json(dir); |
| 650 | let msgs: Vec<&str> = v["whispers"] |
| 651 | .as_array() |
| 652 | .unwrap() |
| 653 | .iter() |
| 654 | .map(|w| w["message"].as_str().unwrap()) |
| 655 | .collect(); |
| 656 | assert_eq!(msgs, ["kept", "private note"], "content"); |
| 657 | assert_eq!(count(dir, "history"), 1, "history"); |
| 658 | } |
| 659 | |
| 660 | /// Replacing `.crumb.local` keeps its POSIX access ACL exactly. Before the |
| 661 | /// core#924 re-review fix, a file with `user:65534:r--, group::---, |
| 662 | /// mask::r--` came back as `group::r--` with the named user gone: the group |
| 663 | /// gained read through the mask while the mode stayed 0640. |
| 664 | #[cfg(target_os = "linux")] |
| 665 | #[test] |
| 666 | fn replacement_keeps_the_existing_access_acl() { |
| 667 | use std::os::unix::fs::PermissionsExt; |
| 668 | let s = Scratch::new("acl"); |
| 669 | let home = s.0.join("no-home"); |
| 670 | let dir = s.dir("acl"); |
| 671 | let local = dir.join(".crumb.local"); |
| 672 | std::fs::write(&local, SEEDED_LOCAL).unwrap(); |
| 673 | std::fs::set_permissions(&local, std::fs::Permissions::from_mode(0o600)).unwrap(); |
| 674 | if !setfacl(&["-m", "u:65534:r--,g::---,m::r--,o::---"], &local) { |
| 675 | println!("NOT_RUN replacement_keeps_the_existing_access_acl"); |
| 676 | return; |
| 677 | } |
| 678 | let acl_before = access_acl_bytes(&local).expect("fixture has an access ACL"); |
| 679 | let text_before = getfacl_text(&local); |
| 680 | if let Some(t) = &text_before { |
| 681 | for line in [ |
| 682 | "user::rw-", |
| 683 | "user:65534:r--", |
| 684 | "group::---", |
| 685 | "mask::r--", |
| 686 | "other::---", |
| 687 | ] { |
| 688 | assert!(t.lines().any(|l| l == line), "fixture lacks {line}: {t}"); |
| 689 | } |
| 690 | } else { |
| 691 | println!("getfacl not installed: comparing xattr bytes only"); |
| 692 | } |
| 693 | let mode_before = mode_of(&local); |
| 694 | assert_eq!(mode_before, 0o640, "mask r-- shows as group bits"); |
| 695 | whisper_then_record(&home, &dir, |verb| { |
| 696 | let acl_after = access_acl_bytes(&local); |
| 697 | let text_after = getfacl_text(&local); |
| 698 | println!( |
| 699 | "ACL {verb} mode {:o} xattr {} bytes, getfacl after:\n{}", |
| 700 | mode_of(&local), |
| 701 | acl_after.as_ref().map_or(0, |a| a.len()), |
| 702 | text_after.as_deref().unwrap_or("(getfacl not installed)") |
| 703 | ); |
| 704 | assert_eq!( |
| 705 | acl_after.as_ref(), |
| 706 | Some(&acl_before), |
| 707 | "{verb} changed the ACL" |
| 708 | ); |
| 709 | assert_eq!(text_after, text_before, "{verb} changed the effective ACL"); |
| 710 | assert_eq!(mode_of(&local), mode_before, "{verb} changed the mode"); |
| 711 | }); |
| 712 | } |
| 713 | |
| 714 | /// A directory default ACL does not leak onto a replaced file that had no |
| 715 | /// ACL: the temp file inherits one when created, and it is removed before |
| 716 | /// the rename, so the file keeps exactly its mode and no named entries. |
| 717 | #[cfg(target_os = "linux")] |
| 718 | #[test] |
| 719 | fn replacement_does_not_inherit_the_directory_default_acl() { |
| 720 | use std::os::unix::fs::PermissionsExt; |
| 721 | let s = Scratch::new("acl-default"); |
| 722 | let home = s.0.join("no-home"); |
| 723 | let dir = s.dir("acl-default"); |
| 724 | let local = dir.join(".crumb.local"); |
| 725 | std::fs::write(&local, SEEDED_LOCAL).unwrap(); |
| 726 | std::fs::set_permissions(&local, std::fs::Permissions::from_mode(0o600)).unwrap(); |
| 727 | if !setfacl(&["-d", "-m", "u:65534:rwx,g::r-x,o::r-x"], &dir) { |
| 728 | println!("NOT_RUN replacement_does_not_inherit_the_directory_default_acl"); |
| 729 | return; |
| 730 | } |
| 731 | assert_eq!(access_acl_bytes(&local), None, "fixture file has no ACL"); |
| 732 | whisper_then_record(&home, &dir, |verb| { |
| 733 | let text = getfacl_text(&local); |
| 734 | println!( |
| 735 | "DEFAULT-ACL {verb} mode {:o} getfacl after:\n{}", |
| 736 | mode_of(&local), |
| 737 | text.as_deref().unwrap_or("(getfacl not installed)") |
| 738 | ); |
| 739 | assert_eq!(access_acl_bytes(&local), None, "{verb} left an access ACL"); |
| 740 | assert_eq!(mode_of(&local), 0o600, "{verb} changed the mode"); |
| 741 | if let Some(t) = text { |
| 742 | assert!(!t.contains("65534"), "{verb} granted a named user: {t}"); |
| 743 | } |
| 744 | }); |
| 745 | } |
| 746 | |
| 747 | /// Identity variables are validated as given, never trimmed: surrounding |
| 748 | /// whitespace, whitespace-only and non-UTF-8 values are an error (exit 1) and |
| 749 | /// nothing is written. Before the fix ' worker-1 ' was stored as 'worker-1', |
| 750 | /// aliasing a real worker so sniff hid it as self-activity. |
| 751 | #[cfg(unix)] |
| 752 | #[test] |
| 753 | fn malformed_identity_env_is_rejected_and_nothing_is_written() { |
| 754 | use std::ffi::OsStr; |
| 755 | use std::os::unix::ffi::OsStrExt; |
| 756 | let s = Scratch::new("identity-reject"); |
| 757 | let home = s.0.join("no-home"); |
| 758 | let non_utf8 = OsStr::from_bytes(b"worker-\xff"); |
| 759 | let cases: Vec<(&str, Vec<(&str, &OsStr)>)> = vec![ |
| 760 | ("id-both", vec![("AIEN_AGENT_ID", OsStr::new(" worker-1 "))]), |
| 761 | ( |
| 762 | "id-trailing", |
| 763 | vec![("AIEN_AGENT_ID", OsStr::new("worker-1 "))], |
| 764 | ), |
| 765 | ("id-tab", vec![("AIEN_AGENT_ID", OsStr::new("\tworker-1"))]), |
| 766 | ( |
| 767 | "id-newline", |
| 768 | vec![("AIEN_AGENT_ID", OsStr::new("worker-1\n"))], |
| 769 | ), |
| 770 | ("id-blank", vec![("AIEN_AGENT_ID", OsStr::new(" "))]), |
| 771 | ("id-non-utf8", vec![("AIEN_AGENT_ID", non_utf8)]), |
| 772 | ( |
| 773 | "session-padded", |
| 774 | vec![ |
| 775 | ("AIEN_AGENT_ID", OsStr::new("worker-1")), |
| 776 | ("AIEN_SESSION_ID", OsStr::new(" s1")), |
| 777 | ], |
| 778 | ), |
| 779 | ( |
| 780 | "name-padded", |
| 781 | vec![ |
| 782 | ("AIEN_AGENT_NAME", OsStr::new("worker ")), |
| 783 | ("AIEN_SESSION_ID", OsStr::new("s1")), |
| 784 | ], |
| 785 | ), |
| 786 | ( |
| 787 | "aien-session-padded", |
| 788 | vec![ |
| 789 | ("AIEN_AGENT_NAME", OsStr::new("worker")), |
| 790 | ("AIEN_SESSION_ID", OsStr::new("s1 ")), |
| 791 | ], |
| 792 | ), |
| 793 | ( |
| 794 | "hermes-session-padded", |
| 795 | vec![("HERMES_SESSION_ID", OsStr::new(" local-abc"))], |
| 796 | ), |
| 797 | ]; |
| 798 | for (name, env) in &cases { |
| 799 | let dir = s.dir(name); |
| 800 | std::fs::write(dir.join("shared.rs"), "").unwrap(); |
| 801 | for args in [ |
| 802 | vec![ |
| 803 | "record", |
| 804 | dir.to_str().unwrap(), |
| 805 | "--action", |
| 806 | "edit", |
| 807 | "--target", |
| 808 | "shared.rs", |
| 809 | "--intent", |
| 810 | "i", |
| 811 | "--vector", |
| 812 | "v", |
| 813 | ], |
| 814 | vec!["whisper", dir.to_str().unwrap(), "--message", "m"], |
| 815 | ] { |
| 816 | let mut c = cli(&home); |
| 817 | for (k, v) in env { |
| 818 | c.env(k, v); |
| 819 | } |
| 820 | let o = c.args(&args).output().unwrap(); |
| 821 | println!( |
| 822 | "IDENTITY-REJECT {name} {} exit {:?}", |
| 823 | args[0], |
| 824 | o.status.code() |
| 825 | ); |
| 826 | assert_eq!( |
| 827 | o.status.code(), |
| 828 | Some(1), |
| 829 | "{name} {} accepted: {}", |
| 830 | args[0], |
| 831 | show(&o) |
| 832 | ); |
| 833 | assert!( |
| 834 | String::from_utf8_lossy(&o.stderr).contains("agent identity"), |
| 835 | "{name}: {}", |
| 836 | show(&o) |
| 837 | ); |
| 838 | } |
| 839 | let mut entries: Vec<String> = std::fs::read_dir(&dir) |
| 840 | .unwrap() |
| 841 | .flatten() |
| 842 | .map(|e| e.file_name().to_string_lossy().to_string()) |
| 843 | .collect(); |
| 844 | entries.sort(); |
| 845 | assert_eq!(entries, ["shared.rs"], "{name}: something was written"); |
| 846 | } |
| 847 | } |
| 848 | |
| 849 | /// Valid identity variables are stored byte for byte; a variable set to the |
| 850 | /// empty string counts as unset (the next source is used), as documented. |
| 851 | #[test] |
| 852 | fn valid_identity_env_is_stored_byte_for_byte() { |
| 853 | let s = Scratch::new("identity-exact"); |
| 854 | let home = s.0.join("no-home"); |
| 855 | let cases = [ |
| 856 | ( |
| 857 | "explicit", |
| 858 | vec![ |
| 859 | ("AIEN_AGENT_ID", "Worker-1.x_y@host"), |
| 860 | ("AIEN_SESSION_ID", "Sess_1.a@b-2"), |
| 861 | ], |
| 862 | "Worker-1.x_y@host", |
| 863 | "Sess_1.a@b-2", |
| 864 | ), |
| 865 | ( |
| 866 | "composed", |
| 867 | vec![ |
| 868 | ("AIEN_AGENT_NAME", "Lane_A"), |
| 869 | ("AIEN_SESSION_ID", "20261106_233000_ab12"), |
| 870 | ], |
| 871 | "Lane_A.20261106_233000_ab12", |
| 872 | "20261106_233000_ab12", |
| 873 | ), |
| 874 | ( |
| 875 | "empty-id-is-unset", |
| 876 | vec![ |
| 877 | ("AIEN_AGENT_ID", ""), |
| 878 | ("AIEN_AGENT_NAME", "worker"), |
| 879 | ("AIEN_SESSION_ID", "s1"), |
| 880 | ], |
| 881 | "worker.s1", |
| 882 | "s1", |
| 883 | ), |
| 884 | ( |
| 885 | "empty-session-falls-to-hermes", |
| 886 | vec![ |
| 887 | ("AIEN_AGENT_NAME", "worker"), |
| 888 | ("AIEN_SESSION_ID", ""), |
| 889 | ("HERMES_SESSION_ID", "local-abc"), |
| 890 | ], |
| 891 | "worker.local-abc", |
| 892 | "local-abc", |
| 893 | ), |
| 894 | ]; |
| 895 | for (name, env, want_id, want_session) in &cases { |
| 896 | let dir = s.dir(name); |
| 897 | let mut c = cli(&home); |
| 898 | for (k, v) in env { |
| 899 | c.env(k, v); |
| 900 | } |
| 901 | let o = c |
| 902 | .args(["record", dir.to_str().unwrap()]) |
| 903 | .args([ |
| 904 | "--action", "edit", "--target", "f", "--intent", "i", "--vector", "v", |
| 905 | ]) |
| 906 | .output() |
| 907 | .unwrap(); |
| 908 | assert!(o.status.success(), "{name}: {}", show(&o)); |
| 909 | let v = local_json(&dir); |
| 910 | let item = &v["history"][0]; |
| 911 | println!( |
| 912 | "IDENTITY-EXACT {name} agent_id {} session_id {}", |
| 913 | item["agent_id"], item["session_id"] |
| 914 | ); |
| 915 | assert_eq!( |
| 916 | item["agent_id"].as_str().unwrap().as_bytes(), |
| 917 | want_id.as_bytes(), |
| 918 | "{name}" |
| 919 | ); |
| 920 | assert_eq!( |
| 921 | item["session_id"].as_str().unwrap().as_bytes(), |
| 922 | want_session.as_bytes(), |
| 923 | "{name}" |
| 924 | ); |
| 925 | } |
| 926 | } |
| 927 | |
| 928 | /// `show` prints its card, including the ".crumb.local unavailable" line, and |
| 929 | /// exits 1 when `.crumb.local` cannot be loaded, as the help promises. |
| 930 | #[test] |
| 931 | fn show_exits_1_on_a_local_state_error() { |
| 932 | let s = Scratch::new("show"); |
| 933 | let home = s.0.join("no-home"); |
| 934 | let good = s.dir("good"); |
| 935 | let o = cli(&home) |
| 936 | .args(["show", good.to_str().unwrap()]) |
| 937 | .output() |
| 938 | .unwrap(); |
| 939 | assert!(o.status.success(), "show on clean dir: {}", show(&o)); |
| 940 | let bad = s.dir("bad"); |
| 941 | std::fs::write(bad.join(".crumb.local"), "{ broken").unwrap(); |
| 942 | let o = cli(&home) |
| 943 | .args(["show", bad.to_str().unwrap()]) |
| 944 | .output() |
| 945 | .unwrap(); |
| 946 | println!("SHOW malformed exit {:?}", o.status.code()); |
| 947 | assert_eq!(o.status.code(), Some(1), "show hid the error: {}", show(&o)); |
| 948 | assert!( |
| 949 | String::from_utf8_lossy(&o.stdout).contains(".crumb.local unavailable"), |
| 950 | "{}", |
| 951 | show(&o) |
| 952 | ); |
| 953 | assert_eq!( |
| 954 | std::fs::read_to_string(bad.join(".crumb.local")).unwrap(), |
| 955 | "{ broken" |
| 956 | ); |
| 957 | } |