Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
test: stop test suites leaking temp directories
AkitaOnRailsa74de3b36c70
diff --git a/companions/ai-memory-importer/src/main.rs b/companions/ai-memory-importer/src/main.rsindex 2a96a70c..98f0093f 100644--- a/companions/ai-memory-importer/src/main.rs+++ b/companions/ai-memory-importer/src/main.rs@@ -1965,7 +1965,8 @@ mod tests {#[test]fn sanitized_redaction_markers_survive_utf8_byte_caps_in_bodies_and_titles() {- let root = tempdir().unwrap().keep();+ let tmp = tempdir().unwrap();+ let root = tmp.path();for (role, cap) in [("user", MAX_USER_MESSAGE_BYTES),("assistant", MAX_EXTENSION_MESSAGE_BYTES),@@ -1976,7 +1977,7 @@ mod tests {{"role":role, "content":format!("{prefix}abcdefghijklmnop\u{1b}[0m\u{202e}")},{"role":"assistant", "content":format!("{} token=abcdefghijklmnop", "x".repeat(145))}]});- let file = write_conversation(&root, source);+ let file = write_conversation(root, source);let plan = plan_external_conversation(&file, "w", DEFAULT_SERVER_URL).unwrap();for event in &plan.events {ai_memory_client::check_body(&event.body).unwrap();diff --git a/companions/ai-memory-relay/tests/relay.rs b/companions/ai-memory-relay/tests/relay.rsindex 0cdb7529..ddff93e9 100644--- a/companions/ai-memory-relay/tests/relay.rs+++ b/companions/ai-memory-relay/tests/relay.rs@@ -28,13 +28,29 @@ mod queue_under_test;// ---------------------------------------------------------------- fixtures-/// A kept sandbox. The path is printed so a failure points at the evidence.-fn fixture(name: &str) -> PathBuf {- let root = tempfile::TempDir::new().unwrap().keep();- let root = root.join(name);- std::fs::create_dir_all(&root).unwrap();- println!("fixture {name}: {}", root.display());- root+/// A sandbox path that owns its temp dir, so the tree is removed when the test+/// ends instead of accumulating in the system temp directory.+struct Sandbox {+ _guard: tempfile::TempDir,+ path: PathBuf,+}++impl std::ops::Deref for Sandbox {+ type Target = PathBuf;++ fn deref(&self) -> &PathBuf {+ &self.path+ }+}++fn fixture(name: &str) -> Sandbox {+ let guard = tempfile::TempDir::new().unwrap();+ let path = guard.path().join(name);+ std::fs::create_dir_all(&path).unwrap();+ Sandbox {+ _guard: guard,+ path,+ }}fn queue_dir(root: &Path) -> PathBuf {@@ -1393,7 +1409,7 @@ CREATE TABLE IF NOT EXISTS session_agent();"#;-fn v1_fixture(name: &str) -> PathBuf {+fn v1_fixture(name: &str) -> Sandbox {let root = fixture(name);let dir = queue_dir(&root);std::fs::create_dir(&dir).unwrap();@@ -1419,7 +1435,10 @@ fn v1_fixture(name: &str) -> PathBuf {use std::os::unix::fs::PermissionsExt;std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();}- dir+ Sandbox {+ _guard: root._guard,+ path: dir,+ }}fn snapshot(conn: &rusqlite::Connection) -> Vec<String> {@@ -1658,7 +1677,8 @@ fn journal_reclassification_busy_preserves_committed_migration_and_retries_same_fn classification_read_failures_display_the_sqlite_cause_once_and_preserve_foreign_bytes() {for malformed_file in [false, true] {let dir = if malformed_file {- let dir = fsguard::prepare_queue_dir(&queue_dir(&fixture("invalid-sqlite"))).unwrap();+ let sandbox = fixture("invalid-sqlite");+ let dir = fsguard::prepare_queue_dir(&queue_dir(&sandbox)).unwrap();let path = dir.join("relay.sqlite");fsguard::create_private_file(&path).unwrap();std::fs::OpenOptions::new()@@ -1667,7 +1687,10 @@ fn classification_read_failures_display_the_sqlite_cause_once_and_preserve_forei.unwrap().write_all(b"not a SQLite database").unwrap();- dir+ Sandbox {+ _guard: sandbox._guard,+ path: dir,+ }} else {let dir = v1_fixture("missing-meta");let conn = rusqlite::Connection::open(dir.join("relay.sqlite")).unwrap();@@ -1826,7 +1849,12 @@ fn fresh_queue_init_and_v1_reopens_work_across_processes() {let dir = if legacy {v1_fixture("process-reopen")} else {- fsguard::prepare_queue_dir(&queue_dir(&fixture("process-init"))).unwrap()+ let sandbox = fixture("process-init");+ let path = fsguard::prepare_queue_dir(&queue_dir(&sandbox)).unwrap();+ Sandbox {+ _guard: sandbox._guard,+ path,+ }};let before = legacy.then(|| snapshot(&rusqlite::Connection::open(dir.join("relay.sqlite")).unwrap()));diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rsindex 14948f1d..230baafe 100644--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@ -3132,10 +3132,8 @@ check(markedButEmpty.disposition === "keep", "allowlist-marker-present-empty-caplet Some(()) = node_strip_types_available() else {return;};- // `keep()` cancels delete-on-drop: the emitted modules are the- // evidence, so they stay on disk for inspection after the run.- let temp = tempfile::tempdir().unwrap().keep();- eprintln!("capture-owner gate modules retained at {}", temp.display());+ let guard = tempfile::tempdir().unwrap();+ let temp = guard.path().to_path_buf();const HARNESS: &str = r#"import { closeSync, mkdirSync, opendirSync, openSync, readFileSync as readMarkerText, readSync, readdirSync, statSync, writeFileSync } from "node:fs";import { basename, dirname, join, resolve } from "node:path";import { homedir } from "node:os";diff --git a/crates/ai-memory-cli/tests/suite/e2e_support.rs b/crates/ai-memory-cli/tests/suite/e2e_support.rsindex 07c8faa7..6a6f6e9f 100644--- a/crates/ai-memory-cli/tests/suite/e2e_support.rs+++ b/crates/ai-memory-cli/tests/suite/e2e_support.rs@@ -258,7 +258,8 @@ mod slow {async fn start_serve_moves_off_a_port_taken_before_the_bind() {use std::io::{Read as _, Write as _};- let root = tempfile::tempdir().unwrap().keep();+ let guard = tempfile::tempdir().unwrap();+ let root = guard.path().to_path_buf();let taken = TcpListener::bind("127.0.0.1:0").unwrap();let busy = taken.local_addr().unwrap().port();std::thread::spawn(move || {@@ -285,7 +286,8 @@ mod slow {#[tokio::test]#[should_panic(expected = "serve exited")]async fn start_serve_reports_an_early_exit() {- let root = tempfile::tempdir().unwrap().keep();+ let guard = tempfile::tempdir().unwrap();+ let root = guard.path().to_path_buf();start_serve(&reqwest::Client::new(), &root.join("serve.log"), |port| {let mut cmd = serve(&root, port);cmd.arg("--no-such-flag");diff --git a/crates/ai-memory-cli/tests/suite/external_capture.rs b/crates/ai-memory-cli/tests/suite/external_capture.rsindex 5a9ce30b..12fb068b 100644--- a/crates/ai-memory-cli/tests/suite/external_capture.rs+++ b/crates/ai-memory-cli/tests/suite/external_capture.rs@@ -47,7 +47,8 @@ fn hook(root: &Path, agent: &str, event: &str, owner: Option<&str>, check: bool)#[test]fn external_capture_owner_suppresses_only_the_opted_in_process() {for owner in [None, Some(""), Some(" \t\n"), Some("orchestrator-a")] {- let tmp = tempfile::tempdir().unwrap().keep();+ let guard = tempfile::tempdir().unwrap();+ let tmp = guard.path().to_path_buf();let output = hook(tmp.as_path(),"claude-code",@@ -75,7 +76,8 @@ fn external_capture_owner_suppresses_only_the_opted_in_process() {#[test]fn external_devin_end_still_clears_native_identity() {- let root = tempfile::tempdir().unwrap().keep();+ let guard = tempfile::tempdir().unwrap();+ let root = guard.path().to_path_buf();let state = root.join("data/hook-state/devin-session-id");std::fs::create_dir_all(state.parent().unwrap()).unwrap();std::fs::write(&state, "completed-execution").unwrap();@@ -92,7 +94,8 @@ fn external_devin_end_still_clears_native_identity() {#[test]fn capture_inspection_reports_external_ownership_without_side_effects() {- let tmp = tempfile::tempdir().unwrap().keep();+ let guard = tempfile::tempdir().unwrap();+ let tmp = guard.path().to_path_buf();std::fs::write(tmp.join(".ai-memory.toml"),"workspace = \"demo\"\nproject = \"app\"\n",@@ -136,6 +139,8 @@ mod slow {root: PathBuf,client: reqwest::Client,base: String,+ // Last field: drops after the server has stopped using the tree.+ _guard: tempfile::TempDir,}fn command(root: &Path) -> Command {@@ -163,7 +168,8 @@ mod slow {impl Fixture {async fn start() -> Self {- let root = tempfile::tempdir().unwrap().keep();+ let guard = tempfile::tempdir().unwrap();+ let root = guard.path().to_path_buf();for dir in ["home", "data", "project"] {std::fs::create_dir(root.as_path().join(dir)).unwrap();}@@ -201,6 +207,7 @@ mod slow {root,client,base,+ _guard: guard,}}diff --git a/crates/ai-memory-cli/tests/suite/external_capture_powershell.rs b/crates/ai-memory-cli/tests/suite/external_capture_powershell.rsindex 5d8f411a..b429e78f 100644--- a/crates/ai-memory-cli/tests/suite/external_capture_powershell.rs+++ b/crates/ai-memory-cli/tests/suite/external_capture_powershell.rs@@ -67,12 +67,9 @@ Invoke-AiMemoryHook -Event 'session-start' -Agent 'claude-code' -FetchHandoff}/// Run the helper once under `owner`. `None` leaves the variable unset.- ///- /// The sandbox is kept, not dropped: these fixtures are small, recoverable- /// and worth reading after a CI failure, and nothing here should delete a- /// tree on its own.fn run(owner: Option<&str>) -> Run {- let tmp = tempfile::tempdir().unwrap().keep();+ let sandbox = tempfile::tempdir().unwrap();+ let tmp = sandbox.path().to_path_buf();let driver = tmp.join("driver.ps1");let log = tmp.join("requests.log");std::fs::write(&driver, DRIVER).unwrap();diff --git a/crates/ai-memory-cli/tests/suite/external_capture_ts.rs b/crates/ai-memory-cli/tests/suite/external_capture_ts.rsindex c01e1f7d..d4c0f034 100644--- a/crates/ai-memory-cli/tests/suite/external_capture_ts.rs+++ b/crates/ai-memory-cli/tests/suite/external_capture_ts.rs@@ -25,7 +25,7 @@/// Slow tier: three process spawns per case (CLI render plus one Node run).mod slow_generated_runtime {- use std::path::{Path, PathBuf};+ use std::path::Path;use std::process::Command;use serde_json::Value;@@ -221,23 +221,13 @@ console.log(JSON.stringify({ events, handoffs, unmarked, system: transformed.sys.collect()}- /// Retained fixture root: `keep()` hands back the path and cancels the- /// delete-on-drop, so the generated plugin stays inspectable after a run.- fn fixture_root() -> PathBuf {- let dir = tempfile::tempdir().expect("fixture root").keep();- eprintln!(- "generated-plugin runtime fixture retained at {}",- dir.display()- );- dir- }-#[test]fn generated_plugin_stops_capture_for_an_external_owner_but_still_fetches_context() {if !node_strip_types_available() {return;}- let dir = fixture_root();+ let guard = tempfile::tempdir().expect("fixture root");+ let dir = guard.path().to_path_buf();let mut port = free_port();write_fixture(&dir, port);@@ -286,7 +276,8 @@ console.log(JSON.stringify({ events, handoffs, unmarked, system: transformed.sysif !node_strip_types_available() {return;}- let dir = fixture_root();+ let guard = tempfile::tempdir().expect("fixture root");+ let dir = guard.path().to_path_buf();let taken = std::net::TcpListener::bind("127.0.0.1:0").unwrap();let busy = taken.local_addr().unwrap().port();let mut port = busy;diff --git a/crates/ai-memory-cli/tests/suite/packaging.rs b/crates/ai-memory-cli/tests/suite/packaging.rsindex 4c0a2e23..6ab9c3ff 100644--- a/crates/ai-memory-cli/tests/suite/packaging.rs+++ b/crates/ai-memory-cli/tests/suite/packaging.rs@@ -1566,14 +1566,14 @@ struct PrePushFixture {cygpath: Option<PathBuf>,hook_toplevel: String,fixture_toplevel: String,+ _guard: tempfile::TempDir,}#[cfg(any(unix, windows))]impl PrePushFixture {fn new() -> Option<Self> {- // `keep()`: the sandbox is the evidence behind a failure, so it outlives- // the test rather than being deleted on drop.- let root = sandbox_root(tempfile::tempdir().unwrap().keep());+ let guard = tempfile::tempdir().unwrap();+ let root = sandbox_root(guard.path().to_path_buf());assert!(!root.starts_with(repo_root()),"the sandbox must live outside this checkout, got {}",@@ -1635,6 +1635,7 @@ impl PrePushFixture {system_config,hook_toplevel: String::new(),fixture_toplevel: String::new(),+ _guard: guard,};fixture.git(&fixture.hook_repo, &["init", "-q"]);fixture.git(&fixture.fixture_repo, &["init", "-q"]);diff --git a/crates/ai-memory-consolidate/src/auto_improve.rs b/crates/ai-memory-consolidate/src/auto_improve.rsindex 95437a43..84025092 100644--- a/crates/ai-memory-consolidate/src/auto_improve.rs+++ b/crates/ai-memory-consolidate/src/auto_improve.rs@@ -2385,10 +2385,10 @@ mod tests {}#[cfg(unix)]- fn write_eval_script(body: &str) -> String {+ fn write_eval_script(body: &str) -> (tempfile::TempDir, String) {use std::os::unix::fs::PermissionsExt;- let dir = tempfile::TempDir::new().unwrap().keep();- let path = dir.join("eval.sh");+ let dir = tempfile::TempDir::new().unwrap();+ let path = dir.path().join("eval.sh");std::fs::write(&path, body).unwrap();let mut perms = std::fs::metadata(&path).unwrap().permissions();perms.set_mode(0o755);@@ -2397,13 +2397,14 @@ mod tests {// temp file directly. Some Linux filesystems can briefly report// ETXTBSY for direct exec under parallel tests even after write(2)// returns and the file handle has been dropped.- format!("sh {}", path.display())+ let command = format!("sh {}", path.display());+ (dir, command)}#[cfg(windows)]- fn write_eval_script(body: &str) -> String {- let dir = tempfile::TempDir::new().unwrap().keep();- let path = dir.join("eval.ps1");+ fn write_eval_script(body: &str) -> (tempfile::TempDir, String) {+ let dir = tempfile::TempDir::new().unwrap();+ let path = dir.path().join("eval.ps1");let body = match body {"#!/bin/sh\ncat >/dev/null\nprintf '%s' '{\"score_before\":0.72,\"score_after\":0.76,\"passed\":true}'\n" => {"$null = [Console]::In.ReadToEnd()\n[Console]::Out.Write('{\"score_before\":0.72,\"score_after\":0.76,\"passed\":true}')\n"@@ -2436,11 +2437,12 @@ mod tests {other => panic!("unmapped eval script fixture for Windows: {other:?}"),};std::fs::write(&path, body).unwrap();- format!(+ let command = format!("{} -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File {}",ai_memory_test_support::powershell_exe(),path.display()- )+ );+ (dir, command)}#[tokio::test]@@ -2464,7 +2466,7 @@ mod tests {#[tokio::test]async fn passing_eval_allows_proposal_and_records_evidence() {- let script = write_eval_script(+ let (_eval_dir, script) = write_eval_script("#!/bin/sh\ncat >/dev/null\nprintf '%s' '{\"score_before\":0.72,\"score_after\":0.76,\"passed\":true}'\n",);let mut proposals = vec![proposal("_rules/test.md", "rule", 0.9)];@@ -2491,7 +2493,7 @@ mod tests {#[cfg(unix)]#[tokio::test]async fn structured_eval_records_server_observation() {- let command = write_eval_script(+ let (_eval_dir, command) = write_eval_script("#!/bin/sh\ncat >/dev/null\nprintf '%s' '{\"passed\":true,\"score_before\":0.72,\"score_after\":0.76,\"run_id\":\"caller-run\",\"eval_id\":\"caller-eval\",\"checker_invocation_digest\":\"caller-digest\",\"after_body_sha256\":\"caller-body\"}'\n",);let candidate = proposal("_rules/test.md", "rule", 0.9);@@ -2552,7 +2554,7 @@ mod tests {#[tokio::test]async fn failing_eval_filters_and_records_rejection() {- let script = write_eval_script(+ let (_eval_dir, script) = write_eval_script("#!/bin/sh\ncat >/dev/null\nprintf '%s' '{\"score_before\":0.72,\"score_after\":0.70,\"passed\":true}'\n",);let mut proposals = vec![proposal("procedures/test.md", "procedure", 0.9)];@@ -2583,7 +2585,7 @@ mod tests {#[tokio::test]async fn eval_reports_rejected_when_scorer_returns_false() {- let script = write_eval_script(+ let (_eval_dir, script) = write_eval_script("#!/bin/sh\ncat >/dev/null\nprintf '%s' '{\"passed\":false,\"reason\":\"structure check failed\"}'\n",);let mut proposals = vec![proposal("procedures/test.md", "procedure", 0.9)];@@ -2675,7 +2677,7 @@ mod tests {"eval_gate_timeout",),];- for (command, expected_reason) in cases {+ for ((_eval_dir, command), expected_reason) in cases {let mut cfg = eval_cfg(command);cfg.timeout_secs = if cfg!(windows) { 8 } else { 1 };let mut proposals = vec![proposal("_rules/test.md", "rule", 0.9)];@@ -2712,7 +2714,7 @@ mod tests {#[tokio::test]async fn eval_timeout_covers_blocked_stdin_write() {- let script = write_eval_script("#!/bin/sh\nsleep 5\n");+ let (_eval_dir, script) = write_eval_script("#!/bin/sh\nsleep 5\n");let mut cfg = eval_cfg(script);cfg.timeout_secs = 1;let mut proposal = proposal("_rules/test.md", "rule", 0.9);@@ -2750,7 +2752,7 @@ mod tests {// One zero-padded printf writes the 70,000 bytes at once. A shell loop// printing one byte per iteration took longer than the gate's 2s// timeout on a loaded machine, which failed the test as a timeout.- let script = write_eval_script("#!/bin/sh\nprintf '%070000d' 0\n");+ let (_eval_dir, script) = write_eval_script("#!/bin/sh\nprintf '%070000d' 0\n");let mut proposals = vec![proposal("_rules/test.md", "rule", 0.9)];let mut rejected = Vec::new();let mut warnings = Vec::new();@@ -2808,7 +2810,7 @@ mod tests {#[tokio::test]async fn non_targeted_proposal_bypasses_eval() {- let script = write_eval_script("#!/bin/sh\nexit 7\n");+ let (_eval_dir, script) = write_eval_script("#!/bin/sh\nexit 7\n");let mut proposals = vec![proposal("gotchas/test.md", "gotcha", 0.9)];let mut rejected = Vec::new();let mut warnings = Vec::new();