Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

feat(capture): add allowlist mode so unmarked repos capture nothing (#475)

Fabio Akitaf99a60f0d367
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4c90947b..4c0f977d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
test asserting the field set so a future change cannot quietly add captured
text. A newer CLI against an older server renders the rest of `status` and
omits the section rather than failing to parse.
+- `install-hooks --capture-mode allowlist` inverts capture scope: a repository
+ with no `.ai-memory.toml` marker emits no lifecycle event at all — prompts,
+ tool calls and session boundaries alike — dropped in the hook process before
+ anything reaches the local spool or the wire. Previously the marker could
+ only narrow what an already-captured repository sent, so forgetting one
+ captured *more*; under this mode forgetting one captures less (#446).
+
+ The gate is deliberately independent of the per-event capture policy, which
+ runs only for tool events: expressing it as a capture disposition would have
+ left prompt text spooling from a repository the CLI reported as opted out.
+ The mode is stored once per install rather than baked into each agent's hook
+ command, so every agent honours it and a bare `--apply` — including the
+ refresh inside `upgrade` — cannot revert it. `--check-capture` now reports
+ `capture_mode`, `marker_present` and `admits_capture` so an opt-out can be
+ verified without sending anything. Default behaviour is unchanged, and
+ `--capture-mode denylist` restores it.
### Docs
- Documented the order of magnitude reported for lifecycle-hook overhead,
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 118cad86..35011b2e 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -1499,6 +1499,28 @@ pub struct LlmTestArgs {
/// resolves its project from the main git repo root (collapsing
/// subdirectories and worktrees) without a per-repo `.ai-memory.toml`
/// marker. A marker's own `project_strategy` still wins.
+/// Which way capture fails when a repository has no `.ai-memory.toml`
+/// marker (#446).
+#[derive(Copy, Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
+pub enum CaptureModeArg {
+ /// Capture unless a marker excludes it — the historical default.
+ Denylist,
+ /// Capture only repositories that carry a marker. A repository without
+ /// one emits no lifecycle events at all.
+ Allowlist,
+}
+
+impl CaptureModeArg {
+ /// The policy value this flag selects.
+ #[must_use]
+ pub const fn mode(self) -> ai_memory_hooks::CaptureMode {
+ match self {
+ Self::Denylist => ai_memory_hooks::CaptureMode::Denylist,
+ Self::Allowlist => ai_memory_hooks::CaptureMode::Allowlist,
+ }
+ }
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum ProjectStrategyArg {
/// `project = basename(cwd)` — the default; bakes nothing.
@@ -1544,6 +1566,12 @@ pub struct HookArgs {
/// Inspect capture policy without spooling, draining, or contacting the server.
#[arg(long)]
pub check_capture: bool,
+ /// Capture failure mode baked in by `install-hooks --capture-mode`.
+ /// Under `allowlist`, a repository with no `.ai-memory.toml` marker emits
+ /// no lifecycle event at all — the event is dropped before it can reach
+ /// the local spool or the wire.
+ #[arg(long, value_enum)]
+ pub capture_mode: Option<CaptureModeArg>,
/// Opt in to assistant/Stop capture: on a Claude Code `stop` event, attach a
/// sanitized, capped excerpt of the assistant's final turn as the Stop body.
/// Baked onto the native `stop` command by
@@ -1629,6 +1657,14 @@ pub struct InstallHooksArgs {
/// without this flag removes it (idempotent). Default off.
#[arg(long)]
pub capture_assistant: bool,
+ /// Persist the capture failure mode for this install (#446). Under
+ /// `allowlist`, a repository with no `.ai-memory.toml` marker emits no
+ /// lifecycle event at all, for every agent. Stored in the data dir, so a
+ /// later bare `--apply` — including the auto-refresh inside `upgrade` —
+ /// cannot regenerate it away. Omitting the flag leaves the stored mode
+ /// untouched; `--capture-mode denylist` restores the default.
+ #[arg(long, value_enum)]
+ pub capture_mode: Option<CaptureModeArg>,
/// Do not install Claude Code's `UserPromptSubmit` capture hook. Prompt
/// text is then excluded before it can enter the local spool or wire.
/// A bare `--apply` re-run preserves an existing opt-out; use
diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rs
index 955659d4..da4c518f 100644
--- a/crates/ai-memory-cli/src/commands/hook.rs
+++ b/crates/ai-memory-cli/src/commands/hook.rs
@@ -18,7 +18,9 @@ use std::time::Duration;
use ai_memory_core::{AgentKind, ManagedRunId, SessionId};
use ai_memory_hooks::capture_policy::metadata_only_body;
-use ai_memory_hooks::{CaptureDisposition, HookEvent, PolicyState};
+use ai_memory_hooks::{
+ CaptureDisposition, CaptureMode, HookEvent, PolicyState, repository_admits_capture,
+};
use ai_memory_llm::OidcToken;
use crate::cli::HookArgs;
@@ -484,9 +486,24 @@ where
inspection_cwd.as_deref().unwrap_or(""),
)
});
+ // Precedence: an explicit flag (tests, one-off runs) wins; otherwise the
+ // persisted per-install mode; otherwise the historical default.
+ let capture_mode = args.capture_mode.map_or_else(
+ || persisted_capture_mode(&resolve_data_dir(data_dir.as_deref())),
+ crate::cli::CaptureModeArg::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.
+ let marker_present = policy_cwd
+ .as_deref()
+ .is_some_and(|cwd| crate::marker::find_marker(cwd).is_some());
+ let admits_capture = repository_admits_capture(capture_mode, marker_present);
if args.check_capture {
let protocol = decision.as_ref().map(|decision| decision.protocol());
let output = serde_json::json!({
+ "capture_mode": capture_mode,
+ "marker_present": marker_present,
+ "admits_capture": admits_capture,
"version": protocol.map_or(1, |protocol| protocol.version()),
"policy_state": protocol.map_or(PolicyState::Inactive, |protocol| protocol.policy_state()),
"tool_family": protocol.map_or(ai_memory_hooks::ToolFamily::Unknown, |protocol| protocol.tool_family()),
@@ -497,6 +514,15 @@ where
writeln!(stdout, "{output}")?;
return Ok(());
}
+ // #446: under allowlist mode a repository that never opted in emits
+ // nothing. This sits outside the `tool_event` path on purpose — `decision`
+ // is `None` for UserPromptSubmit, SessionStart/End and Stop, so gating via
+ // `CaptureDisposition` alone would still spool prompt text from an
+ // opted-out repository while reporting it as excluded.
+ if !admits_capture {
+ write_success_response(stdout, agent_kind, hook_event)?;
+ return Ok(());
+ }
if let Some(decision) = decision {
match decision.protocol().disposition() {
CaptureDisposition::Drop => {
@@ -767,6 +793,26 @@ fn canonical_capture_cwd(cwd: &str) -> String {
.unwrap_or_else(|| cwd.to_owned())
}
+/// File under the data dir holding the per-install capture mode (#446).
+///
+/// Deliberately a standalone file rather than a flag baked into each agent's
+/// hook command: the mode then covers every agent and every render path at
+/// once, and `install-hooks --apply` cannot regenerate it away. The reporter's
+/// binding requirement was that the protection survive an upgrade — here it
+/// does so by construction rather than by preservation logic that a new render
+/// path could forget.
+pub(crate) const CAPTURE_MODE_FILE: &str = "capture-mode";
+
+/// 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.
+fn persisted_capture_mode(data_dir: &Path) -> CaptureMode {
+ match std::fs::read_to_string(data_dir.join(CAPTURE_MODE_FILE)) {
+ Ok(text) if text.trim().eq_ignore_ascii_case("allowlist") => CaptureMode::Allowlist,
+ _ => CaptureMode::Denylist,
+ }
+}
+
fn is_tool_event(event: &str) -> bool {
matches!(
event.to_ascii_lowercase().replace(['-', '_'], "").as_str(),
@@ -799,6 +845,50 @@ fn resolve_data_dir(data_dir: Option<&Path>) -> PathBuf {
mod tests {
use super::*;
+ /// The regression this whole change exists for. `inspect` runs only for
+ /// tool events, so a gate expressed through `CaptureDisposition` would
+ /// leave prompt bodies spooling from a repository that never opted in —
+ /// reporting it as excluded while writing the text to disk. Pin the fact
+ /// that the gate is event-independent.
+ #[test]
+ fn allowlist_gate_covers_events_that_never_reach_capture_policy() {
+ for event in ["user-prompt-submit", "session-start", "session-end", "stop"] {
+ assert!(
+ !is_tool_event(event),
+ "{event} must not be a tool event, or this test proves nothing"
+ );
+ }
+ // With no marker present, allowlist mode admits none of them.
+ assert!(!repository_admits_capture(CaptureMode::Allowlist, false));
+ }
+
+ #[test]
+ fn persisted_mode_defaults_to_denylist_when_absent() {
+ let tmp = tempfile::tempdir().unwrap();
+ assert_eq!(
+ persisted_capture_mode(tmp.path()),
+ CaptureMode::Denylist,
+ "a missing file must not change existing installs"
+ );
+ }
+
+ #[test]
+ fn persisted_mode_reads_allowlist() {
+ let tmp = tempfile::tempdir().unwrap();
+ std::fs::write(tmp.path().join(CAPTURE_MODE_FILE), "allowlist\n").unwrap();
+ assert_eq!(persisted_capture_mode(tmp.path()), CaptureMode::Allowlist);
+ }
+
+ #[test]
+ fn unreadable_or_unknown_mode_falls_back_to_denylist_not_allowlist() {
+ // Failing "closed" here would be a denial of service: a corrupt file
+ // would silently stop all capture. Tightening is the operator's
+ // explicit choice, so garbage must read as the historical default.
+ let tmp = tempfile::tempdir().unwrap();
+ std::fs::write(tmp.path().join(CAPTURE_MODE_FILE), "\u{0}not-a-mode").unwrap();
+ assert_eq!(persisted_capture_mode(tmp.path()), CaptureMode::Denylist);
+ }
+
fn devin_hook_args(event: &str) -> HookArgs {
HookArgs {
event: event.into(),
@@ -808,6 +898,7 @@ mod tests {
project_strategy: None,
check_capture: false,
capture_assistant: false,
+ capture_mode: None,
}
}
@@ -1450,6 +1541,7 @@ mod tests {
project_strategy: None,
check_capture: false,
capture_assistant: false,
+ capture_mode: None,
};
run_with_payload(
@@ -1492,6 +1584,7 @@ mod tests {
project_strategy: None,
check_capture: false,
capture_assistant: false,
+ capture_mode: None,
};
run_with_payload(
@@ -1533,6 +1626,7 @@ mod tests {
project_strategy: None,
check_capture: false,
capture_assistant: false,
+ capture_mode: None,
};
run_with_payload(Some(data_dir), args, "{}".into(), &mut stdout, |_path| {
@@ -1560,6 +1654,7 @@ mod tests {
project_strategy: None,
check_capture: false,
capture_assistant: false,
+ capture_mode: None,
};
run_with_payload(
@@ -1777,7 +1872,30 @@ mod tests {
let mut stdout = Vec::new();
run_with_payload(Some(data_dir.clone()), args, serde_json::json!({"cwd":tmp.path(),"tool_name":"Edit","tool_input":{"path":"SENTINEL"}}).to_string(), &mut stdout, |_| Err(std::io::Error::other("must not spawn"))).await.unwrap();
let output: serde_json::Value = serde_json::from_slice(&stdout).unwrap();
- assert_eq!(output.as_object().unwrap().len(), 6);
+ // Pin the exact key set, not just its size: `--check-capture` is how an
+ // operator verifies an opt-out, so a field silently appearing or
+ // vanishing here is a defect in its own right.
+ let mut keys: Vec<&str> = output
+ .as_object()
+ .unwrap()
+ .keys()
+ .map(String::as_str)
+ .collect();
+ keys.sort_unstable();
+ assert_eq!(
+ keys,
+ [
+ "admits_capture",
+ "capture_mode",
+ "disposition",
+ "extraction_state",
+ "marker_present",
+ "path_count",
+ "policy_state",
+ "tool_family",
+ "version",
+ ]
+ );
assert_eq!(hook_spool::spool_len(&hook_spool::spool_dir(&data_dir)), 0);
assert!(!String::from_utf8(stdout).unwrap().contains("SENTINEL"));
}
@@ -1901,6 +2019,7 @@ mod tests {
project_strategy: None,
check_capture: false,
capture_assistant: false,
+ capture_mode: None,
}
}
@@ -1913,6 +2032,7 @@ mod tests {
project_strategy: None,
check_capture: false,
capture_assistant: false,
+ capture_mode: None,
}
}
@@ -1925,6 +2045,7 @@ mod tests {
project_strategy: None,
check_capture: false,
capture_assistant: false,
+ capture_mode: None,
}
}
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 67849dfe..43276d49 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -19,7 +19,7 @@ use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
-use crate::cli::{AgentChoice, InstallHooksArgs, McpClient, ProjectStrategyArg};
+use crate::cli::{AgentChoice, CaptureModeArg, InstallHooksArgs, McpClient, ProjectStrategyArg};
use crate::commands::apply_shared::{ApplyOutcome, apply_atomic, mutate_json, mutate_toml};
use crate::commands::install_mcp;
use crate::commands::openclaw_plugin;
@@ -367,6 +367,14 @@ pub fn run(config: &Config, mut args: InstallHooksArgs) -> Result<()> {
);
}
if args.apply {
+ // #446: settle the capture failure mode before any agent-specific
+ // work, and say which mode is in force. A protection the operator
+ // cannot see is one they cannot trust.
+ let capture_mode = persist_capture_mode(&config.data_dir, args.capture_mode)?;
+ println!("capture mode: {capture_mode}");
+ if capture_mode == "allowlist" {
+ println!(" repositories without a .ai-memory.toml marker emit no lifecycle events");
+ }
// Preserve a project-strategy an earlier `--apply` baked when this run
// did not pass `--project-strategy`. Without this, a bare re-apply —
// notably the auto-refresh in `ai-memory upgrade` — re-renders the hook
@@ -586,6 +594,32 @@ fn install_project_strategy(args: &InstallHooksArgs) -> Option<ProjectStrategyAr
.and_then(|existing| baked_project_strategy(args.agent, existing))
}
+/// Settle and persist the capture failure mode (#446), returning the mode now
+/// in force.
+///
+/// An explicit flag writes the file. Omitting the flag *reads* the stored
+/// value rather than defaulting to it, so a bare `--apply` — including the
+/// auto-refresh inside `ai-memory upgrade` — can never quietly downgrade an
+/// existing opt-in back to capture-by-default.
+fn persist_capture_mode(data_dir: &Path, requested: Option<CaptureModeArg>) -> Result<String> {
+ let path = data_dir.join(crate::commands::hook::CAPTURE_MODE_FILE);
+ let Some(requested) = requested else {
+ return Ok(match fs::read_to_string(&path) {
+ Ok(text) if text.trim().eq_ignore_ascii_case("allowlist") => "allowlist".to_string(),
+ _ => "denylist".to_string(),
+ });
+ };
+ let value = match requested {
+ CaptureModeArg::Allowlist => "allowlist",
+ CaptureModeArg::Denylist => "denylist",
+ };
+ fs::create_dir_all(data_dir)
+ .with_context(|| format!("creating data dir {}", data_dir.display()))?;
+ fs::write(&path, format!("{value}\n"))
+ .with_context(|| format!("writing {}", path.display()))?;
+ Ok(value.to_string())
+}
+
/// Whether the Claude Code install should include its prompt-capture hook.
/// Explicit flags win. A bare apply preserves the state of an existing
/// ai-memory install so `upgrade` cannot silently restore a privacy opt-out.
@@ -4586,6 +4620,47 @@ fn render_kiro_cli_v3(
#[cfg(test)]
mod tests {
use super::*;
+
+ /// #446's binding requirement: "a protection that disappears on upgrade
+ /// without saying so is worse than no protection". A bare `--apply` — what
+ /// `ai-memory upgrade` runs — must leave an existing opt-in alone.
+ #[test]
+ fn bare_apply_preserves_an_existing_allowlist_optin() {
+ let tmp = tempfile::tempdir().unwrap();
+ let mode = persist_capture_mode(tmp.path(), Some(CaptureModeArg::Allowlist)).unwrap();
+ assert_eq!(mode, "allowlist");
+
+ // The upgrade path: no flag at all.
+ let after = persist_capture_mode(tmp.path(), None).unwrap();
+ assert_eq!(
+ after, "allowlist",
+ "a bare re-apply must not revert the opt-in"
+ );
+ assert_eq!(
+ fs::read_to_string(tmp.path().join(crate::commands::hook::CAPTURE_MODE_FILE))
+ .unwrap()
+ .trim(),
+ "allowlist"
+ );
+ }
+
+ #[test]
+ fn absent_file_reports_the_historical_default() {
+ let tmp = tempfile::tempdir().unwrap();
+ assert_eq!(persist_capture_mode(tmp.path(), None).unwrap(), "denylist");
+ }
+
+ #[test]
+ fn explicit_denylist_downgrades_an_earlier_optin() {
+ // The opt-in must be reversible, or operators cannot undo a mistake.
+ let tmp = tempfile::tempdir().unwrap();
+ persist_capture_mode(tmp.path(), Some(CaptureModeArg::Allowlist)).unwrap();
+ assert_eq!(
+ persist_capture_mode(tmp.path(), Some(CaptureModeArg::Denylist)).unwrap(),
+ "denylist"
+ );
+ assert_eq!(persist_capture_mode(tmp.path(), None).unwrap(), "denylist");
+ }
use crate::cli::ProjectStrategyArg;
use crate::commands::render_shared::KIRO_CLI_V2_SESSION_START_MAX_OUTPUT;
use std::collections::BTreeMap;
@@ -4908,6 +4983,7 @@ mod tests {
agent: AgentChoice::OpenCode,
capture_assistant: false,
no_capture_prompts: false,
+ capture_mode: None,
capture_prompts: false,
hooks_dir: None,
server_url: None,
@@ -6544,6 +6620,7 @@ model = "gpt-5"
agent: AgentChoice::Omp,
capture_assistant: false,
no_capture_prompts: false,
+ capture_mode: None,
capture_prompts: false,
hooks_dir: None,
server_url: Some("http://127.0.0.1:49374".into()),
@@ -6576,6 +6653,7 @@ model = "gpt-5"
agent: AgentChoice::Pi,
capture_assistant: false,
no_capture_prompts: false,
+ capture_mode: None,
capture_prompts: false,
hooks_dir: None,
server_url: Some("http://127.0.0.1:49374".into()),
@@ -6942,6 +7020,7 @@ model = "gpt-5"
agent: AgentChoice::Codex,
capture_assistant: false,
no_capture_prompts: false,
+ capture_mode: None,
capture_prompts: false,
hooks_dir: Some(hooks_tmp.path().to_path_buf()),
server_url: Some("http://127.0.0.1:49374".to_string()),
@@ -7428,6 +7507,7 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessio
agent: AgentChoice::ClaudeCode,
capture_assistant: false,
no_capture_prompts: false,
+ capture_mode: None,
capture_prompts: false,
hooks_dir: Some(hooks_tmp.path().to_path_buf()),
server_url: Some("http://127.0.0.1:49374".to_string()),
@@ -7502,6 +7582,7 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessio
agent: AgentChoice::ClaudeCode,
config_file: Some(config_path.clone()),
no_capture_prompts: true,
+ capture_mode: None,
..default_hook_args()
};
apply_to_claude_code_settings_in(
@@ -7987,6 +8068,7 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessio
agent: AgentChoice::Devin,
capture_assistant: false,
no_capture_prompts: false,
+ capture_mode: None,
capture_prompts: false,
hooks_dir: Some(hooks_tmp.path().to_path_buf()),
server_url: Some("http://127.0.0.1:49374".to_string()),
@@ -8053,6 +8135,7 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessio
agent: AgentChoice::Devin,
capture_assistant: false,
no_capture_prompts: false,
+ capture_mode: None,
capture_prompts: false,
hooks_dir: Some(hooks_tmp.path().to_path_buf()),
server_url: Some("http://127.0.0.1:49374".to_string()),
@@ -8108,6 +8191,7 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessio
agent: AgentChoice::Devin,
capture_assistant: false,
no_capture_prompts: false,
+ capture_mode: None,
capture_prompts: false,
hooks_dir: Some(hooks_tmp.path().to_path_buf()),
server_url: Some("http://127.0.0.1:49374".to_string()),
@@ -8156,6 +8240,7 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessio
agent: AgentChoice::Devin,
capture_assistant: false,
no_capture_prompts: false,
+ capture_mode: None,
capture_prompts: false,
hooks_dir: Some(hooks_tmp.path().to_path_buf()),
server_url: Some("http://127.0.0.1:49374".to_string()),
@@ -8229,6 +8314,7 @@ command = "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kimi-code/sessio
agent: AgentChoice::Devin,
capture_assistant: false,
no_capture_prompts: false,
+ capture_mode: None,
capture_prompts: false,
hooks_dir: Some(hooks_tmp.path().to_path_buf()),
server_url: Some("http://127.0.0.1:49374".to_string()),
diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rs
index 5e3a3757..e93babc2 100644
--- a/crates/ai-memory-hooks/src/capture_policy.rs
+++ b/crates/ai-memory-hooks/src/capture_policy.rs
@@ -28,6 +28,41 @@ pub struct CaptureConfig {
pub ignore_paths: Vec<String>,
}
+/// Whether a repository is captured unless excluded, or only when it opts in.
+///
+/// This is the failure-mode switch requested in #446. Under [`Self::Denylist`]
+/// — the historical behaviour and still the default — a repository with no
+/// marker is captured, so forgetting a marker leaks. Under
+/// [`Self::Allowlist`] the same omission captures nothing.
+#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
+#[serde(rename_all = "kebab-case")]
+pub enum CaptureMode {
+ /// Absence of a marker means capture normally.
+ #[default]
+ Denylist,
+ /// Absence of a marker means capture nothing at all.
+ Allowlist,
+}
+
+/// Whether this repository may emit *any* lifecycle event, decided before the
+/// per-event policy in [`CapturePolicy::inspect`] and before anything is
+/// spooled.
+///
+/// Deliberately independent of the event kind. `inspect` is reached only for
+/// tool events (`is_tool_event` in the CLI hook), so a gate expressed through
+/// [`CaptureDisposition`] alone would leave `UserPromptSubmit`,
+/// `SessionStart`/`SessionEnd`, and `Stop` bodies flowing while reporting the
+/// repository as opted out — the precise false guarantee #446 is about. Prompt
+/// text is the field that issue cares about most, so this must gate every
+/// event or it gates nothing that matters.
+#[must_use]
+pub const fn repository_admits_capture(mode: CaptureMode, marker_present: bool) -> bool {
+ match mode {
+ CaptureMode::Denylist => true,
+ CaptureMode::Allowlist => marker_present,
+ }
+}
+
/// Typed result of marker discovery and parsing, supplied by the IO-owning caller.
pub enum CaptureSource<'a> {
/// No nearest marker exists.
@@ -923,6 +958,24 @@ fn char_equal(left: char, right: char, insensitive: bool) -> bool {
#[cfg(test)]
mod tests {
use super::*;
+
+ #[test]
+ fn denylist_admits_every_repository() {
+ assert!(repository_admits_capture(CaptureMode::Denylist, false));
+ assert!(repository_admits_capture(CaptureMode::Denylist, true));
+ }
+
+ #[test]
+ fn allowlist_admits_only_a_marked_repository() {
+ assert!(!repository_admits_capture(CaptureMode::Allowlist, false));
+ assert!(repository_admits_capture(CaptureMode::Allowlist, true));
+ }
+
+ #[test]
+ fn default_mode_is_the_historical_one() {
+ // A new field must not silently tighten capture for existing installs.
+ assert_eq!(CaptureMode::default(), CaptureMode::Denylist);
+ }
#[test]
fn fixture_vectors() {
let fixture: Value =
diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rs
index 2afe17c8..4204a054 100644
--- a/crates/ai-memory-hooks/src/lib.rs
+++ b/crates/ai-memory-hooks/src/lib.rs
@@ -39,8 +39,9 @@ pub use assistant_capture::{
ClientAssistantTransform, strip_assistant_message_raw, transform_for_client,
};
pub use capture_policy::{
- CaptureConfig, CaptureDecision, CaptureDisposition, CapturePolicy, CaptureProtocol,
- CaptureSource, ExtractionState, PolicyState, ToolFamily,
+ CaptureConfig, CaptureDecision, CaptureDisposition, CaptureMode, CapturePolicy,
+ CaptureProtocol, CaptureSource, ExtractionState, PolicyState, ToolFamily,
+ repository_admits_capture,
};
pub use payload::{
HookEnvelope, HookEvent, NOTIFICATION_EXCERPT_MAX_BYTES, POST_COMPACTION_EXCERPT_MAX_BYTES,
diff --git a/docs/install.md b/docs/install.md
index 0be07008..58b2869f 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -476,6 +476,45 @@ it would break continuity. Disabling prompt capture reduces session summaries
and recall quality because user intent is no longer part of the observation
stream; tool and session-boundary capture continues unchanged.
+**Capture only repositories that opt in.** The controls above narrow *what* is
+captured; this one narrows *where*. By default a repository with no
+`.ai-memory.toml` marker is still captured, so a machine that works across many
+checkouts captures every new one automatically — forgetting a marker means
+capturing more, not less. Allowlist mode inverts that:
+
+```bash
+ai-memory install-hooks --apply --capture-mode allowlist
+```
+
+A repository without a marker then emits **no lifecycle event at all** — not a
+trimmed one. The event is dropped in the hook process before it can reach the
+local spool or the wire, so nothing is written to disk for a repository that
+never opted in. Opting a repository in is just placing a `.ai-memory.toml`
+marker in it, which is the same file that already configures routing and
+`ignore_paths`.
+
+Unlike the flags above, this is not per-agent: the mode is stored once in the
+data directory and every agent's hook honours it. That also means a later bare
+`install-hooks --apply` — including the auto-refresh inside `ai-memory upgrade`
+— leaves it alone by construction rather than by re-detecting it. Every
+`--apply` prints the mode in force. Return to the default with
+`--capture-mode denylist`.
+
+Verify it on any repository without changing anything:
+
+```bash
+printf '{"cwd":"%s"}' "$PWD" | ai-memory hook --event user-prompt-submit \
+ --agent claude-code --server-url "$AI_MEMORY_SERVER_URL" --check-capture
+```
+
+`--check-capture` inspects policy without spooling, draining, or contacting the
+server, and needs a JSON payload naming the directory to test. In the output,
+`"admits_capture": false` means that repository captures nothing;
+`"marker_present"` shows whether a marker was found by the upward walk.
+
+Note the trade: recall is lost for every repository you do not mark, and a
+repository you *intended* to capture stays silent until you add its marker.
+
Some agent harnesses attach the assistant's final turn to their `Stop` event —
Claude Code sends it as a raw `last_assistant_message`. By default that text is
never persisted: the native hook binary strips the raw field before it can reach
diff --git a/docs/marker-file.md b/docs/marker-file.md
index 33f558f9..6ccaa1c7 100644
--- a/docs/marker-file.md
+++ b/docs/marker-file.md
@@ -127,6 +127,29 @@ always stored regardless. This is per-project on purpose: there is no
server-global switch, so opting one noisy project in never sheds subagent
captures for the others on a shared instance.
+## Allowlist mode: the marker as an opt-in
+
+By default this file is optional — a repository without one is still captured,
+and the marker only *narrows* what is taken. An install can invert that:
+
+```bash
+ai-memory install-hooks --apply --capture-mode allowlist
+```
+
+Under allowlist mode the presence of a `.ai-memory.toml` **is** the opt-in. A
+repository without one emits no lifecycle event at all — prompts, tool calls
+and session boundaries alike — dropped in the hook process before anything
+reaches the local spool or the wire. No extra key is needed: an existing marker
+already opts its repository in, whatever else it configures.
+
+This changes what forgetting the file costs. Under the default, forgetting
+means a repository is captured that you may not have intended; under allowlist
+mode it means a repository stays silent that you may have wanted. Pick the
+direction whose failure you would rather explain.
+
+The mode is stored per install rather than per agent, and a later bare
+`install-hooks --apply` (including an upgrade refresh) leaves it in place.
+
## Capture exclusions
Use the exact per-repository shape `[capture]` plus `ignore_paths = [...]`