Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(capture): honor allowlist capture mode in backfill and run-ledger imports
AkitaOnRailsf6abd645f8dc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3191b00e..d36ebd75 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -38,7 +38,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0them. Both now apply the same decision as the live hook to every importedtool call and its result: an excluded call is not imported at all, one thepolicy cannot prove safe keeps only its tool family, and prompts and- assistant messages are imported as before. Results recorded without an id+ assistant messages are imported as before, and under allowlist capture+ mode a checkout without a marker imports nothing. Results recorded without an idlinking them to their call take the strictest decision of their turn.(GHSA-gcpc-88hm-3xqr)- Fixed a web page open in the operator's browser being able to act on andiff --git a/crates/ai-memory-cli/src/commands/backfill.rs b/crates/ai-memory-cli/src/commands/backfill.rsindex 5cbf5265..950bcc10 100644--- a/crates/ai-memory-cli/src/commands/backfill.rs+++ b/crates/ai-memory-cli/src/commands/backfill.rs@@ -93,6 +93,9 @@ struct BackfillReport {/// True when the store was already populated (or `--force` off) and nothing/// was imported.skipped_non_empty: bool,+ /// True when this install's capture mode admits nothing from this+ /// checkout (allowlist mode without a marker), so nothing was imported.+ skipped_not_admitted: bool,/// True for a `--dry-run` (planning only, no import).dry_run: bool,}@@ -191,7 +194,11 @@ async fn backfill_endpoint(/// are returned, including in JSON mode.pub async fn run(config: &Config, args: crate::cli::BackfillArgs) -> Result<()> {let cwd = std::env::current_dir().context("resolving the current working directory")?;+ run_in(config, args, cwd).await+}+/// [`run`] for the checkout at `cwd`.+async fn run_in(config: &Config, args: crate::cli::BackfillArgs, cwd: PathBuf) -> Result<()> {// The automatic (SessionStart-spawned) path honors the opt-out and records// that it has been attempted for this checkout, so it runs at most once per// machine regardless of outcome. Manual runs ignore both.@@ -205,8 +212,6 @@ pub async fn run(config: &Config, args: crate::cli::BackfillArgs) -> Result<()>let (workspace, project) =super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;let home = run::native_home(config).context("locating the local harness session stores")?;- let endpoint = backfill_endpoint(config, &args).await?;-let mut report = BackfillReport {workspace: workspace.clone(),project: project.clone(),@@ -214,6 +219,17 @@ pub async fn run(config: &Config, args: crate::cli::BackfillArgs) -> Result<()>..BackfillReport::default()};+ // The live hook's admission gate and `[capture] ignore_paths`, applied to+ // the import as the hook applies them to live events. A checkout the hook+ // would emit nothing for (allowlist capture mode without a marker) imports+ // nothing, before the server is contacted at all.+ let capture = TranscriptCapture::for_checkout(&config.data_dir, &cwd);+ if !capture.admits_capture() {+ report.skipped_not_admitted = true;+ return finish(&args, &report);+ }+ let endpoint = backfill_endpoint(config, &args).await?;+// Emptiness gate. Only bootstrap a brand-new store; an established project// is never retro-imported (that would duplicate hook-captured history).if !args.force {@@ -238,10 +254,6 @@ pub async fn run(config: &Config, args: crate::cli::BackfillArgs) -> Result<()>return finish(&args, &report);}- // The checkout's `[capture] ignore_paths`, applied to every imported tool- // call as the live hook applies it.- let capture = TranscriptCapture::for_checkout(&cwd);-// Import each selected session, oldest-first so the imported history reads// chronologically, until the total-events circuit breaker trips.for session in selected.into_iter().rev() {@@ -801,6 +813,13 @@ fn finish(args: &crate::cli::BackfillArgs, report: &BackfillReport) -> Result<()if args.quiet {return Ok(());}+ if report.skipped_not_admitted {+ println!(+ "ai-memory: capture mode is allowlist and this checkout has no .ai-memory.toml marker opting in (or its marker is unreadable) — nothing to backfill for {}/{}.",+ report.workspace, report.project+ );+ return Ok(());+ }if report.skipped_non_empty {println!("ai-memory: {}/{} already has captured sessions — nothing to backfill (use --force to import anyway).",@@ -1268,7 +1287,7 @@ mod tests {native_session_id: sid.into(),updated_at: SystemTime::now(),};- let capture = TranscriptCapture::for_checkout(repo.path());+ let capture = TranscriptCapture::for_checkout(home.path(), repo.path());import_one(&endpoint,"ws",@@ -1308,6 +1327,78 @@ mod tests {}}+ /// Allowlist capture mode (#446) makes an unmarked checkout emit nothing+ /// from the live hook, so a manual backfill of it must not contact the+ /// server at all. Controls: the same checkout with a marker, and the same+ /// unmarked checkout under the default denylist mode, both proceed to the+ /// server.+ #[tokio::test]+ async fn allowlist_mode_backfills_nothing_from_an_unmarked_checkout() {+ use axum::{Router, extract::Request};+ use std::sync::{Arc, Mutex};++ let requests = Arc::new(Mutex::new(Vec::<String>::new()));+ let seen = requests.clone();+ let app = Router::new().fallback(move |request: Request| {+ let seen = seen.clone();+ async move {+ seen.lock().unwrap().push(request.uri().path().to_owned());+ axum::Json(serde_json::json!({ "by_agent": [], "accepted": 0 }))+ }+ });+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });++ let attempt = |mode: Option<&'static str>, marked: bool| {+ let requests = requests.clone();+ async move {+ let home = tempfile::tempdir().unwrap();+ let data_dir = tempfile::tempdir().unwrap();+ let repo = tempfile::tempdir().unwrap();+ if let Some(mode) = mode {+ std::fs::write(+ data_dir.path().join(super::super::hook::CAPTURE_MODE_FILE),+ mode,+ )+ .unwrap();+ }+ if marked {+ std::fs::write(repo.path().join(".ai-memory.toml"), "[capture]\n").unwrap();+ }+ let mut config =+ crate::config::Config::load(None, Some(home.path().to_path_buf())).unwrap();+ config.data_dir = data_dir.path().to_path_buf();+ config.home_dir = Some(home.path().to_string_lossy().into_owned());+ config.server_url = format!("http://{address}");+ config.auth.bearer_token = None;+ let mut args = spawned_args(None, None);+ args.auto = false;+ args.workspace = Some("ws".into());+ args.project = Some("proj".into());+ requests.lock().unwrap().clear();+ run_in(&config, args, repo.path().to_path_buf())+ .await+ .unwrap();+ requests.lock().unwrap().clone()+ }+ };++ assert!(+ attempt(Some("allowlist\n"), false).await.is_empty(),+ "allowlist + unmarked checkout must not reach the server"+ );+ assert!(+ !attempt(Some("allowlist\n"), true).await.is_empty(),+ "control: a marked checkout proceeds under allowlist"+ );+ assert!(+ !attempt(None, false).await.is_empty(),+ "control: denylist (default) is unchanged"+ );+ server.abort();+ }+fn spawned_args(server_url: Option<&str>,server_profile: Option<&str>,diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex 020ad638..bec48478 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -767,14 +767,8 @@ wherecrate::cli::CaptureModeArg::mode,);let route = resolve_hook_route(&dd, policy_cwd.as_deref(), || std::env::current_dir().ok());- // Marker presence is the opt-in signal under allowlist mode. Resolved from- // the same upward walk the policy uses, so opting in needs no new file.- let marker_present = policy_cwd- .as_deref()- .is_some_and(|cwd| crate::marker::find_marker(cwd).is_some());- let routing_valid = policy_cwd- .as_deref()- .is_none_or(|cwd| crate::marker::routing_selection(cwd).is_ok());+ let marker_present = marker_present(policy_cwd.as_deref());+ let routing_valid = routing_valid(policy_cwd.as_deref());let admits_capture = repository_admits_capture(capture_mode, marker_present);if args.check_capture {let protocol = decision.as_ref().map(|decision| decision.protocol());@@ -1406,6 +1400,27 @@ pub(crate) fn lexical_capture_cwd(cwd: &str) -> String {/// path could forget.pub(crate) const CAPTURE_MODE_FILE: &str = "capture-mode";+/// Marker presence is the opt-in signal under allowlist mode. Resolved from+/// the same upward walk the policy uses, so opting in needs no new file.+fn marker_present(cwd: Option<&str>) -> bool {+ cwd.is_some_and(|cwd| crate::marker::find_marker(cwd).is_some())+}++/// An unreadable routing marker emits nothing rather than guess a scope.+fn routing_valid(cwd: Option<&str>) -> bool {+ cwd.is_none_or(|cwd| crate::marker::routing_selection(cwd).is_ok())+}++/// The hook's repository admission gate (#446) for a transcript import from+/// the checkout at `cwd`: this install's persisted capture mode, the marker+/// opt-in, and a readable routing marker. `backfill` and the `ai-memory run`+/// ledger import nothing — prompts included — from a checkout the live hook+/// would emit nothing for.+pub(crate) fn checkout_admits_capture(data_dir: &Path, cwd: &str) -> bool {+ repository_admits_capture(persisted_capture_mode(data_dir), marker_present(Some(cwd)))+ && routing_valid(Some(cwd))+}+/// Read the persisted capture mode. Anything unreadable, absent, or/// unrecognised means the historical default: this file can only ever tighten/// capture, never silently loosen it below what the operator already had.diff --git a/crates/ai-memory-cli/src/commands/run.rs b/crates/ai-memory-cli/src/commands/run.rsindex 12e8b5b2..1ebe71f4 100644--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@ -1251,7 +1251,7 @@ async fn run_once_with_wiring(checkpoint,Some(exit_code),&privacy,- &TranscriptCapture::for_checkout(&repository.cwd),+ &TranscriptCapture::for_checkout(&config.data_dir, &repository.cwd),).await{@@ -8775,7 +8775,7 @@ mod tests {Default::default(),Some(0),&sanitizer,- &TranscriptCapture::for_checkout(home.path()),+ &TranscriptCapture::for_checkout(home.path(), home.path()),).await.is_err(),@@ -8802,7 +8802,7 @@ mod tests {Default::default(),Some(0),&sanitizer,- &TranscriptCapture::for_checkout(home.path()),+ &TranscriptCapture::for_checkout(home.path(), home.path()),).await.is_err(),@@ -8818,7 +8818,7 @@ mod tests {Default::default(),Some(0),&sanitizer,- &TranscriptCapture::for_checkout(home.path()),+ &TranscriptCapture::for_checkout(home.path(), home.path()),).await.unwrap(),@@ -8919,7 +8919,7 @@ mod tests {Default::default(),Some(0),&Sanitizer::builtin(),- &TranscriptCapture::for_checkout(repo.path()),+ &TranscriptCapture::for_checkout(home.path(), repo.path()),).await.unwrap();@@ -8937,6 +8937,117 @@ mod tests {);}+ /// Allowlist capture mode (#446): the live hook emits nothing from an+ /// unmarked checkout, so its run ledger upload carries no events — no+ /// prompt, no tool content — while still finishing the run. A marked+ /// checkout under allowlist and an unmarked one under the default denylist+ /// upload the transcript as before.+ #[tokio::test]+ async fn ledger_upload_under_allowlist_mode_carries_nothing_from_an_unmarked_checkout() {+ let requests = Arc::new(std::sync::Mutex::new(Vec::<FinishManagedRunRequest>::new()));+ let captured = requests.clone();+ let app = Router::new().route(+ "/workstream/runs/{id}/finish",+ post(+ move |axum::Json(request): axum::Json<FinishManagedRunRequest>| {+ let captured = captured.clone();+ async move {+ let imported_events = request.events.len();+ captured.lock().unwrap().push(request);+ axum::Json(FinishManagedRunResponse {+ imported_events,+ latest_sequence: 1,+ })+ }+ },+ ),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ let home = tempfile::tempdir().unwrap();+ let config = launch_config(home.path(), home.path(), address);+ let endpoint = ServerEndpoint::from_config_resolving_auth(&config).await;+ let allowlist = tempfile::tempdir().unwrap();+ std::fs::write(+ allowlist.path().join(super::super::hook::CAPTURE_MODE_FILE),+ "allowlist\n",+ )+ .unwrap();+ let denylist = tempfile::tempdir().unwrap();+ let unmarked = tempfile::tempdir().unwrap();+ let marked = tempfile::tempdir().unwrap();+ std::fs::write(marked.path().join(".ai-memory.toml"), "[capture]\n").unwrap();+ let transcript = || ExportedTranscript {+ native_session_id: "sid-1".into(),+ source_cursor: Some("cursor".into()),+ events: vec![+ ai_memory_core::NewWorkstreamEvent {+ event_id: "prompt".into(),+ agent: AgentKind::ClaudeCode,+ native_session_id: "sid-1".into(),+ source_record_id: None,+ kind: ai_memory_core::WorkstreamEventKind::Message,+ role: Some("user".into()),+ content: "PROMPTSENTINEL".into(),+ occurred_at: None,+ metadata: serde_json::json!({}),+ },+ ai_memory_core::NewWorkstreamEvent {+ event_id: "tool".into(),+ agent: AgentKind::ClaudeCode,+ native_session_id: "sid-1".into(),+ source_record_id: None,+ kind: ai_memory_core::WorkstreamEventKind::ToolCall,+ role: Some("assistant".into()),+ content: "Bash: {\"command\":\"echo TOOLSENTINEL\"}".into(),+ occurred_at: None,+ metadata: serde_json::json!({"tool": "Bash"}),+ },+ ],+ losses: Vec::new(),+ };+ let upload = |data_dir: &Path, repo: &Path| {+ let capture = TranscriptCapture::for_checkout(data_dir, repo);+ let endpoint = &endpoint;+ let requests = requests.clone();+ async move {+ requests.lock().unwrap().clear();+ import_batches(+ endpoint,+ "/workstream/runs/test",+ transcript(),+ Default::default(),+ Some(0),+ &Sanitizer::builtin(),+ &capture,+ )+ .await+ .unwrap();+ serde_json::to_string(&*requests.lock().unwrap()).unwrap()+ }+ };++ let refused = upload(allowlist.path(), unmarked.path()).await;+ assert!(!refused.contains("SENTINEL"), "{refused}");+ assert!(+ requests.lock().unwrap()[0].complete,+ "the run still finishes, with no events"+ );+ assert!(requests.lock().unwrap()[0].events.is_empty());+ for (data_dir, repo, label) in [+ (allowlist.path(), marked.path(), "marked under allowlist"),+ (denylist.path(), unmarked.path(), "unmarked under denylist"),+ ] {+ let kept = upload(data_dir, repo).await;+ assert!(+ kept.contains("PROMPTSENTINEL") && kept.contains("TOOLSENTINEL"),+ "control {label}: {kept}"+ );+ }+ server.abort();+ }+#[tokio::test]async fn native_identity_run_status_and_expected_refuse_before_discovery() {let home = tempfile::tempdir().unwrap();diff --git a/crates/ai-memory-cli/src/commands/transcript_capture.rs b/crates/ai-memory-cli/src/commands/transcript_capture.rsindex 245539c2..6230d6f9 100644--- a/crates/ai-memory-cli/src/commands/transcript_capture.rs+++ b/crates/ai-memory-cli/src/commands/transcript_capture.rs@@ -18,7 +18,7 @@ use ai_memory_hooks::{};use serde_json::Value;-use super::hook::{lexical_capture_cwd, tool_location_routing_cwd};+use super::hook::{checkout_admits_capture, lexical_capture_cwd, tool_location_routing_cwd};use super::hook_capture::capture_policy;/// What an import does with one transcript event.@@ -60,25 +60,36 @@ impl EventCapture {/// The capture policy of the checkout a transcript was recorded in.pub(crate) struct TranscriptCapture {+ admitted: bool,policy: CapturePolicy,cwd: String,inspection_cwd: String,}impl TranscriptCapture {- /// Resolve the nearest marker's policy for `cwd`, exactly as the live hook- /// does for an event reporting that cwd.- pub(crate) fn for_checkout(cwd: &Path) -> Self {+ /// Resolve the live hook's admission gate (this install's capture mode+ /// under `data_dir`) and the nearest marker's policy for `cwd`, exactly as+ /// the hook does for an event reporting that cwd.+ pub(crate) fn for_checkout(data_dir: &Path, cwd: &Path) -> Self {let cwd = cwd.to_string_lossy().into_owned();Self {+ admitted: checkout_admits_capture(data_dir, &cwd),policy: capture_policy(&cwd),inspection_cwd: lexical_capture_cwd(&cwd),cwd,}}- /// One decision per event, in transcript order. Messages are always kept,- /// as live prompt capture keeps them.+ /// Whether the live hook would emit anything at all from this checkout.+ /// Under allowlist capture mode an unmarked checkout admits nothing.+ pub(crate) const fn admits_capture(&self) -> bool {+ self.admitted+ }++ /// One decision per event, in transcript order. A checkout the hook's+ /// admission gate refuses drops every event, prompts included, as the+ /// live hook emits none. Otherwise messages are kept, as live prompt+ /// capture keeps them.////// A result answers the call with the same native id. Some adapters record/// no id, so a result without a matching call takes the strictest decision@@ -88,6 +99,9 @@ impl TranscriptCapture {/// dropped under a policy, since nothing proves it missed every ignored/// path.pub(crate) fn decide(&self, events: &[NewWorkstreamEvent]) -> Vec<EventCapture> {+ if !self.admitted {+ return vec![EventCapture::Drop; events.len()];+ }let mut by_id: HashMap<&str, EventCapture> = HashMap::new();let mut turn: Vec<EventCapture> = Vec::new();let mut out = Vec::with_capacity(events.len());@@ -309,7 +323,7 @@ mod tests {#[test]fn an_excluded_read_drops_its_call_and_result_by_id() {let repo = checkout(Some("docs/adr/**"));- let capture = TranscriptCapture::for_checkout(repo.path());+ let capture = TranscriptCapture::for_checkout(repo.path(), repo.path());let events = [event(WorkstreamEventKind::Message, "user", "read both", json!({})),read_call(&repo.path().join("docs/adr/1.md"), Some("adr")),@@ -329,7 +343,7 @@ mod tests {#[test]fn id_less_results_take_the_strictest_call_of_their_turn() {let repo = checkout(Some("docs/adr/**"));- let capture = TranscriptCapture::for_checkout(repo.path());+ let capture = TranscriptCapture::for_checkout(repo.path(), repo.path());let events = [event(WorkstreamEventKind::Message, "user", "turn one", json!({})),read_call(&repo.path().join("docs/adr/1.md"), None),@@ -351,7 +365,7 @@ mod tests {#[test]fn unrecoverable_arguments_and_orphan_results_fail_closed_under_a_policy() {let repo = checkout(Some("docs/adr/**"));- let capture = TranscriptCapture::for_checkout(repo.path());+ let capture = TranscriptCapture::for_checkout(repo.path(), repo.path());let truncated_shell = event(WorkstreamEventKind::ToolCall,"assistant",@@ -379,7 +393,7 @@ mod tests {#[test]fn without_a_policy_every_event_is_kept() {let repo = checkout(None);- let capture = TranscriptCapture::for_checkout(repo.path());+ let capture = TranscriptCapture::for_checkout(repo.path(), repo.path());let events = [read_call(&repo.path().join("docs/adr/1.md"), None),result("ADR text", None),@@ -394,7 +408,7 @@ mod tests {fn a_call_into_another_checkout_honors_its_policy() {let source = checkout(None);let other = checkout(Some("private/**"));- let capture = TranscriptCapture::for_checkout(source.path());+ let capture = TranscriptCapture::for_checkout(source.path(), source.path());let events = [read_call(&other.path().join("private/key.txt"), Some("a")),result("private", Some("a")),@@ -407,10 +421,59 @@ mod tests {);}+ /// Under allowlist capture mode the live hook emits nothing — prompts+ /// included — from a checkout without a marker; an import drops every+ /// event there. A marked checkout and the default denylist mode keep them.+ #[test]+ fn allowlist_mode_admits_nothing_from_an_unmarked_checkout() {+ let allowlist = tempfile::tempdir().unwrap();+ std::fs::write(+ allowlist.path().join(super::super::hook::CAPTURE_MODE_FILE),+ "allowlist\n",+ )+ .unwrap();+ let denylist = tempfile::tempdir().unwrap();+ let unmarked = checkout(None);+ let marked = checkout(Some("docs/adr/**"));+ let events = |repo: &Path| {+ vec![+ event(WorkstreamEventKind::Message, "user", "a prompt", json!({})),+ read_call(&repo.join("src/lib.rs"), Some("pub")),+ result("public code", Some("pub")),+ event(WorkstreamEventKind::Message, "assistant", "done", json!({})),+ ]+ };++ let refused = TranscriptCapture::for_checkout(allowlist.path(), unmarked.path());+ assert!(!refused.admits_capture());+ assert_eq!(+ kinds(&refused.decide(&events(unmarked.path()))),+ ["drop", "drop", "drop", "drop"]+ );+ assert!(+ refused+ .filter_ledger_events(events(unmarked.path()))+ .is_empty()+ );++ let opted_in = TranscriptCapture::for_checkout(allowlist.path(), marked.path());+ assert!(opted_in.admits_capture());+ assert_eq!(+ kinds(&opted_in.decide(&events(marked.path()))),+ ["keep", "keep", "keep", "keep"]+ );+ let default = TranscriptCapture::for_checkout(denylist.path(), unmarked.path());+ assert!(default.admits_capture());+ assert_eq!(+ kinds(&default.decide(&events(unmarked.path()))),+ ["keep", "keep", "keep", "keep"]+ );+ }+#[test]fn ledger_events_are_dropped_or_stripped_before_upload() {let repo = checkout(Some("docs/adr/**"));- let capture = TranscriptCapture::for_checkout(repo.path());+ let capture = TranscriptCapture::for_checkout(repo.path(), repo.path());let malformed = event(WorkstreamEventKind::ToolCall,"assistant",diff --git a/docs/design-boot-backfill.md b/docs/design-boot-backfill.mdindex e1ea8cfa..b228955e 100644--- a/docs/design-boot-backfill.md+++ b/docs/design-boot-backfill.md@@ -194,7 +194,11 @@ Retroactive text is exactly as untrusted as live hook text, since it is old modecall is dropped under a policy. Kept events carry no protocol: their body is anormalized transcript record, not the native payload the server's re-inspectionreads, and the server never receives the ignore patterns. The `ai-memory run` ledger- applies the same decisions before its segments are uploaded.+ applies the same decisions before its segments are uploaded. Both also apply the+ hook's repository admission gate (`checkout_admits_capture`): under allowlist capture+ mode a checkout without a marker imports nothing, prompts included, exactly as the+ live hook emits nothing there; a manual `ai-memory backfill` says so and stops before+ contacting the server.- **Emptiness + lease** prevent a backfill from overwriting or racing an establishedproject's real history.- **Multi-user posture.** On a shared server, default-on retro-import of a long localdiff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.mdindex 81f6a814..662f344b 100644--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@ -445,7 +445,9 @@ resume, continue, session, or fork selector.decision table: an excluded tool call and its result never enter theledger, one the policy cannot prove safe keeps only its tool family, and aresult whose call was imported by an earlier run is dropped under a- policy. Messages are unaffected. Each delivered+ policy. Messages are unaffected. Under allowlist capture mode a checkout+ without a marker uploads no events at all, as the live hook emits none+ there; the run still finishes. Each deliveredworkstream packet begins with a versioned origin marker. If Claude Codepersists that packet and its `Read` tool returns it, the Claude transcriptnormalizer excludes the marked result instead of feeding delivered historydiff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 82037fc9..b87e302e 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -66,7 +66,7 @@ means the boundary is not built yet.| 10e | Reconcile-tombstone of a disk-deleted page is opt-in, soft, scope-bound, and false-positive-guarded (invariant #16, #929 delete-half) | `ai-memory-wiki/src/watcher.rs` — off by default (`[maintenance] reconcile_tombstones_deleted_pages`); a page is tombstoned only after its file is observed missing on two consecutive passes (streak resets if the path's `PageId` changed), re-verified against the live filesystem immediately before acting, with reserved/indexed-but-unwalked paths (`bootstrap.md`, `_meta.md`, `_pending/`, `sessions/*.md`) excluded and a circuit breaker that skips a whole scope when `> max(3, 50%)` of its pages look missing or a non-partial walk finds nothing; `ai-memory-store/src/ops.rs` `soft_delete_for_reconcile_if_latest` is a soft tombstone (`is_latest=0` + `superseded_at`, decay's shape) through the single writer actor in one transaction — never a filesystem write — scoped to the page's own `(workspace_id, project_id)` | `watcher.rs` `reconcile_delete_disabled_by_default_never_tombstones_a_missing_page`, `reconcile_delete_cross_project_isolation` (project A's deletion never tombstones project B's same-path page), `reconcile_tombstone_refuses_a_stale_latest_id`, `reconcile_tombstone_refuses_when_the_file_still_exists`, `reconcile_tombstone_never_touches_the_filesystem`; `ops.rs` `reconcile_tombstone_resurrects_instead_of_orphaning_on_recreate` | STRONG || 10f | Session-time repair is scope-bound (no cross-project timestamp rewrite) | `ai-memory-store/src/ops.rs` `repair_session_times` — every candidate is read back and updated with `WHERE id=? AND workspace_id=? AND project_id=?`; a row outside that 3-tuple is reported `NotFound` and untouched, same code path as an id that does not exist at all; `ai-memory-mcp/src/admin.rs` `handle_repair_session_times` passes the caller's `(workspace, project)` straight through, never the candidate's own | `ops.rs` `repair_session_times_does_not_touch_a_session_of_another_project` (control: sibling session in-scope repaired in the same batch); `admin_repair_session_times.rs` `cross_project_session_is_not_found_and_untouched`; both bite-checked by dropping the `project_id` filter | STRONG || 11a | Hook backpressure (202/429) + bounded fan-out (invariant #5) | `ai-memory-hooks/src/router.rs` semaphore→429, 202 immediately, `MAX_HOOK_BATCH_ITEMS`, bounded LRU limiter; batch acknowledgements retain only processed indices and classify terminal drops without consuming capacity | `router.rs` `handle_hook_returns_429_when_ingest_saturated`, `ingest_rate_limiter_is_bounded`; `router.rs` `handle_hook_batch_skips_rate_limited_first_item_and_accepts_later_source`, `handle_hook_batch_reports_failed_index_after_rate_limited_skip`, `handle_hook_batch_drops_subagent_events_before_capacity_check` (each asserts result indices and includes an accepted control) | STRONG |-| 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn), including shell commands whose arguments name an ignored path (`match_command`; argv elements matched whole and tokenized); an invalid marker makes file and shell calls metadata-only; an active one makes a shell call metadata-only when a word uses unquoted brace expansion or a bracket class (`has_unevaluated_expansion`), and either makes tools that read back an earlier command's output metadata-only (`reads_earlier_output`: `BashOutput`, `TaskOutput`, `write_stdin`, `process`, `read_bash`/`write_bash` and PowerShell twins); the server admits a metadata-only shell or unknown-family body only under an active or invalid marker, with no paths and an `extracted` state (`router.rs` `metadata_protocol_is_legal`), and its own re-inspection strips an older client's keep for either; a Gemini `read_many_files` literal entry is also read as `entry/**` (`glob_matches_below`), and Copilot CLI's runtime `view`/`create`/`str_replace_editor` are file tools for that agent only (`agent_family`); generated OpenCode/OMP/Pi/OpenClaw integrations mirror it in `render_shared.rs` `ts_capture_policy_v1` (`captureMatchCommand`, `captureUnevaluatedExpansion`, `captureGlobBelow`, the `reader` flag). Candidate/argument flavor (`Flavor::Posix` vs `Flavor::Windows`, used to pick which `ignore_paths` patterns even apply) is derived from the **host** (the cwd), never from the candidate string alone — a POSIX-host candidate spelled with a leading `//` is collapsed to a single `/` before flavor detection (`normalize_candidate`; TS `captureNormalize`'s `windowsHost` parameter, sourced from `captureHostWindows(cwd)`), fixing GHSA-vh98 (a `//`-prefixed candidate used to self-classify as `Flavor::Windows` regardless of host, matching zero POSIX patterns and being captured instead of dropped); a genuine Windows/UNC host (cwd itself windows-flavored) is unaffected; `hook.rs` `--check-capture` preflight uses the same capture policy before any spool or spawn; transcript imports (`ai-memory backfill`, including the automatic first-boot run, and the `ai-memory run` ledger upload) apply the same decision table through `commands/transcript_capture.rs`: each recorded tool call is rebuilt in its agent's hook shape (`capture_policy.rs` `tool_call_payload`) and inspected by the checkout's policy, and by a reroute destination's policy too; a Drop removes the call and its result (paired by native id, else the strictest call of the turn; a call-less result drops under a policy), metadata-only posts the hook's metadata-only body with its protocol (backfill) or a withheld placeholder (ledger), and a shell call whose recorded arguments cannot be parsed drops (GHSA-gcpc-88hm-3xqr) | `capture_policy.rs` per-agent `…honors_exclusions` tests, `shell_fixture_vectors` (shared `capture-policy.json` `shell` drop/keep vectors: tool aliases incl. OpenClaw/Devin `exec` and `PowerShell`, `workdir`, glob directories, Windows paths, and a POSIX-host leading-`//` command via `/{root}/docs/adr/x.md`), `shell_tool_shapes_of_every_adapter_honor_exclusions`, `claude_code_powershell_honors_ignored_paths_on_a_windows_host` (#1186: Windows-spelled and `-Param:value` paths drop, public-path and `git status` controls kept, invalid marker metadata-only), `gemini_cli_shell_and_read_many_files_honor_ignored_paths` (Gemini `run_shell_command` incl. `dir_path`/`directory`, and `read_many_files` globs via `match_globs`: excluded literal, mixed public+excluded, `docs/*`, recursive `**` and case-variant entries drop, an `exclude` list cannot rescue them, unsupported glob syntax and malformed lists are metadata-only, public entries kept, POSIX and Windows hosts) and `globstar_reaches_lets_double_star_span_any_depth`, `fixture_vectors` (incl. TS-adapter `bash`/`exec` vectors, and `normalization`'s leading-`//` POSIX vectors alongside the kept Windows-cwd UNC vectors as the no-regression control); `shell_matching_is_off_when_inactive_and_fails_closed_when_invalid_or_over_budget`; `router.rs` `capture_protocol_shell_decisions_survive_server_reinspection`, `capture_protocol_invalid_marker_shell_is_metadata_only` (active metadata-only shell admitted for an unevaluated expansion, inactive refused, older client's invalid-marker keep stripped, commandless control kept), `capture_protocol_unparseable_marker_strips_shell_events` (server fallback for an unparseable marker), `capture_protocol_invalid_shell_metadata_claim_must_be_canonical` (a stripped shell claim with a path count or non-`extracted` state is refused); `capture_policy.rs` `invalid_marker_strips_shell_calls_with_unparseable_commands`, `long_bash_lc_script_in_argv_is_not_dropped_by_the_match_budget`, **`a_leading_double_slash_candidate_does_not_escape_posix_ignore_paths_via_flavor_mismatch`** (GHSA-vh98 adversarial: attempts the `//repo/secret/...` violation on a POSIX host, proves it now drops, with a plain-single-slash control and a Windows-hosted genuine-UNC control both still correct — fails on the pre-fix code); `hook.rs` `shell_command_reading_an_ignored_path_is_dropped_before_spool`, `gemini_cli_shell_and_read_many_files_exclusions_drop_before_spool` (pre- and post-tool events with an excluded path are never spooled; public controls spool with their family); `capture_policy.rs` `read_many_files_directory_entries_cannot_reach_ignored_paths` (shared `read_many_files_directories` vectors: `docs`, `.`, `./`, `docs/`, case and `..` variants drop; `src`, `README.md`, `docs/adrx` kept), `output_reader_tools_are_metadata_only_only_under_a_policy` (active and invalid strip, inactive and an unrelated unknown tool keep), `copilot_cli_runtime_file_tools_are_scoped_to_copilot`, `unevaluated_shell_expansions_respect_quoting`, the shell fixture's brace/class vectors (quoted, escaped, `${…}`, `{}`, `[ … ]`, `HEAD@{1}` controls kept); `router.rs` `capture_protocol_active_keep_of_unprovable_output_is_stripped`; `hook.rs` `excluded_content_cannot_reach_the_spool_through_unevaluated_tool_shapes` (directory entries and Copilot `view`/`create` never spool, readers and brace shells spool without content, public controls spool with it); `render_shared.rs` `generated_capture_policy_v1_node_runtime_evidence` (runs the same fixture sections, including the GHSA-vh98 and Gemini `read_many_files`/`run_shell_command` vectors, plus unsupported-glob, empty-list and recursive-`**` checks, against the emitted TypeScript; `#[ignore]` locally, run with `--ignored` under Node 24 by the Linux CI test job); `hook.rs` `check_capture_refuses_partial_scope_and_excluded_content` (ignored-path and partial-scope violations refused, complete public-path control passes), `check_capture_bounds_marker_hints_and_refuses_oversized_scope` (513-byte hints refused, 512-byte control passes; native routing preserved); **`backfill.rs` `backfill_never_posts_tool_content_the_capture_policy_excludes`** (planted Claude transcript: the excluded read's call and output never reach `/hook/batch`, a malformed read posts only the metadata-only body, public read control posted) and **`run.rs` `ledger_upload_drops_tool_content_the_capture_policy_excludes`** (excluded call and output absent from the finish request, public control present, cursor still advances), both failing with the guard removed; `transcript_capture.rs` `an_excluded_read_drops_its_call_and_result_by_id`, `id_less_results_take_the_strictest_call_of_their_turn`, `unrecoverable_arguments_and_orphan_results_fail_closed_under_a_policy`, `a_call_into_another_checkout_honors_its_policy`, `ledger_events_are_dropped_or_stripped_before_upload`, `without_a_policy_every_event_is_kept` (control); `capture_policy.rs` `tool_call_payload_reaches_the_live_decision_for_every_supported_agent` | STRONG with listed residuals. Matching is lexical by design, so these stay open: shell variables (`$VAR`, `FILE=… sh -c 'cat $FILE'`) and command substitution, a `cd` inside the command, symlinks (paths are never resolved on disk), a recursive search of a parent directory (`grep -r x docs`, `rg x`) through a shell, and tools the matcher does not list, which keep their current unknown-tool behavior. Transcript imports add: assistant prose quoting an excluded file is kept (as live prompt/assistant capture keeps it), harnesses whose hook schema the matcher does not read (Crush, Kimi Code) keep their tool events as live capture would, and id-less adapters over-drop a whole turn's results when one call is excluded; `ai-memory run` and a manual `ai-memory backfill` do not consult the allowlist capture mode. Mitigation: allowlist capture mode (`install-hooks --capture-mode allowlist`) for sensitive projects |+| 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn), including shell commands whose arguments name an ignored path (`match_command`; argv elements matched whole and tokenized); an invalid marker makes file and shell calls metadata-only; an active one makes a shell call metadata-only when a word uses unquoted brace expansion or a bracket class (`has_unevaluated_expansion`), and either makes tools that read back an earlier command's output metadata-only (`reads_earlier_output`: `BashOutput`, `TaskOutput`, `write_stdin`, `process`, `read_bash`/`write_bash` and PowerShell twins); the server admits a metadata-only shell or unknown-family body only under an active or invalid marker, with no paths and an `extracted` state (`router.rs` `metadata_protocol_is_legal`), and its own re-inspection strips an older client's keep for either; a Gemini `read_many_files` literal entry is also read as `entry/**` (`glob_matches_below`), and Copilot CLI's runtime `view`/`create`/`str_replace_editor` are file tools for that agent only (`agent_family`); generated OpenCode/OMP/Pi/OpenClaw integrations mirror it in `render_shared.rs` `ts_capture_policy_v1` (`captureMatchCommand`, `captureUnevaluatedExpansion`, `captureGlobBelow`, the `reader` flag). Candidate/argument flavor (`Flavor::Posix` vs `Flavor::Windows`, used to pick which `ignore_paths` patterns even apply) is derived from the **host** (the cwd), never from the candidate string alone — a POSIX-host candidate spelled with a leading `//` is collapsed to a single `/` before flavor detection (`normalize_candidate`; TS `captureNormalize`'s `windowsHost` parameter, sourced from `captureHostWindows(cwd)`), fixing GHSA-vh98 (a `//`-prefixed candidate used to self-classify as `Flavor::Windows` regardless of host, matching zero POSIX patterns and being captured instead of dropped); a genuine Windows/UNC host (cwd itself windows-flavored) is unaffected; `hook.rs` `--check-capture` preflight uses the same capture policy before any spool or spawn; transcript imports (`ai-memory backfill`, including the automatic first-boot run, and the `ai-memory run` ledger upload) apply the same decision table through `commands/transcript_capture.rs`: each recorded tool call is rebuilt in its agent's hook shape (`capture_policy.rs` `tool_call_payload`) and inspected by the checkout's policy, and by a reroute destination's policy too; a Drop removes the call and its result (paired by native id, else the strictest call of the turn; a call-less result drops under a policy), metadata-only posts the hook's metadata-only body with its protocol (backfill) or a withheld placeholder (ledger), and a shell call whose recorded arguments cannot be parsed drops; both imports also apply the hook's repository admission gate (`hook.rs` `checkout_admits_capture`: persisted capture mode, marker opt-in, readable routing marker — the same helpers the hook's own gate uses), so under allowlist mode an unmarked checkout imports nothing, prompts included: `backfill` stops before contacting the server and the run ledger finishes with no events (GHSA-gcpc-88hm-3xqr) | `capture_policy.rs` per-agent `…honors_exclusions` tests, `shell_fixture_vectors` (shared `capture-policy.json` `shell` drop/keep vectors: tool aliases incl. OpenClaw/Devin `exec` and `PowerShell`, `workdir`, glob directories, Windows paths, and a POSIX-host leading-`//` command via `/{root}/docs/adr/x.md`), `shell_tool_shapes_of_every_adapter_honor_exclusions`, `claude_code_powershell_honors_ignored_paths_on_a_windows_host` (#1186: Windows-spelled and `-Param:value` paths drop, public-path and `git status` controls kept, invalid marker metadata-only), `gemini_cli_shell_and_read_many_files_honor_ignored_paths` (Gemini `run_shell_command` incl. `dir_path`/`directory`, and `read_many_files` globs via `match_globs`: excluded literal, mixed public+excluded, `docs/*`, recursive `**` and case-variant entries drop, an `exclude` list cannot rescue them, unsupported glob syntax and malformed lists are metadata-only, public entries kept, POSIX and Windows hosts) and `globstar_reaches_lets_double_star_span_any_depth`, `fixture_vectors` (incl. TS-adapter `bash`/`exec` vectors, and `normalization`'s leading-`//` POSIX vectors alongside the kept Windows-cwd UNC vectors as the no-regression control); `shell_matching_is_off_when_inactive_and_fails_closed_when_invalid_or_over_budget`; `router.rs` `capture_protocol_shell_decisions_survive_server_reinspection`, `capture_protocol_invalid_marker_shell_is_metadata_only` (active metadata-only shell admitted for an unevaluated expansion, inactive refused, older client's invalid-marker keep stripped, commandless control kept), `capture_protocol_unparseable_marker_strips_shell_events` (server fallback for an unparseable marker), `capture_protocol_invalid_shell_metadata_claim_must_be_canonical` (a stripped shell claim with a path count or non-`extracted` state is refused); `capture_policy.rs` `invalid_marker_strips_shell_calls_with_unparseable_commands`, `long_bash_lc_script_in_argv_is_not_dropped_by_the_match_budget`, **`a_leading_double_slash_candidate_does_not_escape_posix_ignore_paths_via_flavor_mismatch`** (GHSA-vh98 adversarial: attempts the `//repo/secret/...` violation on a POSIX host, proves it now drops, with a plain-single-slash control and a Windows-hosted genuine-UNC control both still correct — fails on the pre-fix code); `hook.rs` `shell_command_reading_an_ignored_path_is_dropped_before_spool`, `gemini_cli_shell_and_read_many_files_exclusions_drop_before_spool` (pre- and post-tool events with an excluded path are never spooled; public controls spool with their family); `capture_policy.rs` `read_many_files_directory_entries_cannot_reach_ignored_paths` (shared `read_many_files_directories` vectors: `docs`, `.`, `./`, `docs/`, case and `..` variants drop; `src`, `README.md`, `docs/adrx` kept), `output_reader_tools_are_metadata_only_only_under_a_policy` (active and invalid strip, inactive and an unrelated unknown tool keep), `copilot_cli_runtime_file_tools_are_scoped_to_copilot`, `unevaluated_shell_expansions_respect_quoting`, the shell fixture's brace/class vectors (quoted, escaped, `${…}`, `{}`, `[ … ]`, `HEAD@{1}` controls kept); `router.rs` `capture_protocol_active_keep_of_unprovable_output_is_stripped`; `hook.rs` `excluded_content_cannot_reach_the_spool_through_unevaluated_tool_shapes` (directory entries and Copilot `view`/`create` never spool, readers and brace shells spool without content, public controls spool with it); `render_shared.rs` `generated_capture_policy_v1_node_runtime_evidence` (runs the same fixture sections, including the GHSA-vh98 and Gemini `read_many_files`/`run_shell_command` vectors, plus unsupported-glob, empty-list and recursive-`**` checks, against the emitted TypeScript; `#[ignore]` locally, run with `--ignored` under Node 24 by the Linux CI test job); `hook.rs` `check_capture_refuses_partial_scope_and_excluded_content` (ignored-path and partial-scope violations refused, complete public-path control passes), `check_capture_bounds_marker_hints_and_refuses_oversized_scope` (513-byte hints refused, 512-byte control passes; native routing preserved); **`backfill.rs` `backfill_never_posts_tool_content_the_capture_policy_excludes`** (planted Claude transcript: the excluded read's call and output never reach `/hook/batch`, a malformed read posts only the metadata-only body, public read control posted) and **`run.rs` `ledger_upload_drops_tool_content_the_capture_policy_excludes`** (excluded call and output absent from the finish request, public control present, cursor still advances), both failing with the guard removed; `transcript_capture.rs` `an_excluded_read_drops_its_call_and_result_by_id`, `id_less_results_take_the_strictest_call_of_their_turn`, `unrecoverable_arguments_and_orphan_results_fail_closed_under_a_policy`, `a_call_into_another_checkout_honors_its_policy`, `ledger_events_are_dropped_or_stripped_before_upload`, `without_a_policy_every_event_is_kept` (control); `capture_policy.rs` `tool_call_payload_reaches_the_live_decision_for_every_supported_agent`; **`backfill.rs` `allowlist_mode_backfills_nothing_from_an_unmarked_checkout`** (no request reaches the server; marked-checkout and denylist controls do), **`run.rs` `ledger_upload_under_allowlist_mode_carries_nothing_from_an_unmarked_checkout`** (finish carries no prompt or tool content; marked and denylist controls upload both), `transcript_capture.rs` `allowlist_mode_admits_nothing_from_an_unmarked_checkout`, all failing with the admission gate removed | STRONG with listed residuals. Matching is lexical by design, so these stay open: shell variables (`$VAR`, `FILE=… sh -c 'cat $FILE'`) and command substitution, a `cd` inside the command, symlinks (paths are never resolved on disk), a recursive search of a parent directory (`grep -r x docs`, `rg x`) through a shell, and tools the matcher does not list, which keep their current unknown-tool behavior. Transcript imports add: assistant prose quoting an excluded file is kept (as live prompt/assistant capture keeps it), harnesses whose hook schema the matcher does not read (Crush, Kimi Code) keep their tool events as live capture would, and id-less adapters over-drop a whole turn's results when one call is excluded; a metadata-only import keeps an `event_id` (ledger) and `ingest_key` (backfill) derived from a SHA-256 of the original content plus session and record ids, left in place because those ids are the retry-dedupe keys and a content-free id would merge distinct events — it only confirms a guess of low-entropy content. Mitigation: allowlist capture mode (`install-hooks --capture-mode allowlist`) for sensitive projects || 11c | Capture hook ≤200ms budget (invariant #5) | `hooks/_lib.sh` capture path `curl --max-time 0.2` (context-fetch 1.0s and background drain 2.0s are separate, larger-budget paths) | none (shell-script timeout; hard to unit-test) — watch on any capture-path change | WATCH || 11d | Hook server-profile routing: a marker-selected server gets only its own capture and its own token (#992) | `ai-memory-cli/src/server_profiles.rs` `resolve` (validated `ProfileName`, strict `servers.toml` parse, `roots` required once two profiles exist, component-wise root match) and `marker.rs` `find_server_selection` (inherited down the tree, any value shape counts); `commands/hook.rs` `resolve_hook_route` drops a `Rejected` route before spool, handoff and backfill, and hands the drainer no live token for a profile route; `commands/hook_spool.rs` `static_retry_token` (a profile entry retries only with its own stored token), the loopback reroot skip, and chunk splitting on `profile`; generated TS `captureServerRouted` drops a routed repository and gates `fetchHandoff`; `hooks/_lib.sh` `ai_memory_server_routed` (flag refused by `ai_memory_post_hook`/`ai_memory_get_handoff`) and `hooks/lib/ai-memory-hook.ps1` `Test-AiMemoryServerRouted` drop it in the script hooks; `--check-capture` refuses a rejected server-profile selection without printing its token or URL | `hook.rs` `each_repository_spools_to_its_own_profile_with_its_own_token`, `a_selection_that_does_not_resolve_emits_nothing` (unknown / tokenless / outside roots / roots required / invalid name, plus a resolving control), `session_start_handoff_comes_from_the_profile_server_only`, `a_repository_without_a_server_key_keeps_the_install_default`; `hook_spool.rs` `a_profile_entry_is_never_retried_with_the_install_live_token` (server B accepts exactly the install's live token and must still not get it), `a_profile_entry_recovers_with_its_own_rotated_token` (control), `a_profile_entry_on_a_dead_loopback_port_is_not_rerouted_to_the_default`, `profile_and_default_entries_at_one_address_ride_separate_batches`; `server_profiles.rs` roots/registry/name tests; `marker.rs` `nested_markers_without_server_inherit_the_ancestor_selection`; `install_hooks.rs` `generated_integrations_fail_closed_on_a_server_profile_marker`, `openclaw_plugin.rs` `openclaw_plugin_fails_closed_on_a_server_profile_marker`, and the `server-routed-*` checks in `generated_capture_policy_v1_node_runtime_evidence`; `hook.rs` `an_event_without_a_payload_cwd_routes_by_the_process_cwd`, `a_refused_route_prints_nothing_for_kimi_user_prompts`; `hook_spool.rs` `a_profile_entry_is_not_retried_with_a_token_issued_for_a_new_url`; `server_profiles.rs` `changing_the_url_without_a_token_discards_the_old_token`, `omitted_roots_keep_the_registered_ones`; `marker.rs` `outside_home_the_walk_reaches_a_marker_above_the_checkout_root`, `encoding_noise_cannot_hide_a_server_key`, `an_unreadable_marker_is_a_refused_selection`; `backfill.rs` `a_spawned_backfill_authenticates_like_the_hook_that_spawned_it`; `tests/hooks/test_lib.sh` "server profiles (#992)" section; `hook.rs` `a_mixed_spool_drains_each_event_only_to_its_own_server` (two token-gated servers, one spool, one drain: each server receives exactly its own event with exactly its own bearer); `tests/suite/server_profiles.rs` (the built binary: `server add` → `hook` spools to the profile with its token, unknown profile spools nothing, `uninstall` removes the tokens; `two_real_servers_each_receive_only_their_own_repository` runs two real `ai-memory serve` children with different root tokens and checks on each server which repository landed there); `ai-memory-hooks` `powershell_server_routed.rs` `server_routed_guard_mirrors_the_native_walk` (runs `Test-AiMemoryServerRouted` under real PowerShell: inherited, BOM, look-alike keys, the `$HOME` boundary with its control, past a checkout root outside home, current directory); `hook.rs` `a_selection_that_does_not_resolve_emits_nothing` (rejected routes refuse preflight; resolved profile control passes); `tests/hooks/test_lib.sh` and `powershell_home.rs` `a_trailing_separator_on_home_keeps_the_walk_boundary` (a `$HOME` ending in `/` or `\` keeps both script walks at home: a `server` marker above it routes nothing, with a root-home control that does) | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` || 11e | Native self-upgrade archive confinement (#1025) | `ai-memory-cli/src/commands/upgrade.rs` normalizes every tar/zip path, rejects links and special entries, extracts only the binary and `hooks/`, accepts only the exact non-runtime support layout emitted by `release.yml`, and caps both entry count and declared expanded bytes before writing | `upgrade.rs` `release_workflow_support_assets_are_exact_and_ignored` (shipped support paths admitted, near-miss docs/packaging/template paths refused), `extracts_archive_built_like_release_yml` and `extracts_zip_happy_path_with_hooks` (real workflow-shaped archives succeed but support assets are not written), `validate_rejects_path_traversal`, `zip_extract_rejects_path_traversal`, `tar_extract_rejects_declared_expansion_past_limit`, with binary/hooks extraction as the legitimate control | STRONG |