Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
doctor: warn when [capture] is invalid, based on policy state not parse-only
Maxsuel Einstein3039163b0e7d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4ce62d08..713fbf80 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed+- `ai-memory doctor` now warns when the nearest `.ai-memory.toml`'s+ `[capture]` section is invalid. This fails closed today — every file and+ shell tool event is reduced to metadata until the marker is fixed, nothing+ leaks — but nothing surfaced that it had happened, so an operator could+ believe `ignore_paths` was excluding paths it no longer was. The check is+ based on the same resolution state the live hook path uses (not just+ whether the TOML parses), so it also catches a `[capture]` table that+ parses fine but is still rejected at compile time, e.g. an unsupported glob+ character in `ignore_paths`.+## [2.5.2] - 2026-10-01### Addeddiff --git a/crates/ai-memory-cli/src/commands/doctor.rs b/crates/ai-memory-cli/src/commands/doctor.rsindex a1c240b9..139c0136 100644--- a/crates/ai-memory-cli/src/commands/doctor.rs+++ b/crates/ai-memory-cli/src/commands/doctor.rs@@ -116,6 +116,18 @@ struct DoctorReport {rows: Vec<CoverageRow>,/// The agent kinds (kebab form) flagged as uncaptured, for quick scripting.uncaptured: Vec<String>,+ /// Set when the nearest `.ai-memory.toml`'s `[capture]` section is+ /// `PolicyState::Invalid`. This fails CLOSED (every file/shell tool event+ /// is reduced to metadata until the marker is fixed; nothing leaks), but+ /// with no other signal anywhere that the marker stopped working as+ /// configured, so `doctor` is the one place that surfaces it.+ marker_capture_problem: Option<MarkerCaptureProblem>,+}++#[derive(Debug, Clone, Serialize)]+struct MarkerCaptureProblem {+ marker_path: String,+ reason: String,}/// Fold the raw per-harness local scans and the server's captured counts into@@ -290,6 +302,15 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {.map(|r| r.agent.clone()).collect();+ let marker_capture_problem = cwd.to_str().and_then(|cwd| {+ super::hook_capture::capture_config_problem(cwd).map(|(marker_path, reason)| {+ MarkerCaptureProblem {+ marker_path: marker_path.display().to_string(),+ reason,+ }+ })+ });+let report = DoctorReport {workspace,project,@@ -297,6 +318,7 @@ pub async fn run(config: &Config, args: crate::cli::DoctorArgs) -> Result<()> {since_days: args.since_days,rows,uncaptured,+ marker_capture_problem,};if args.json {@@ -318,6 +340,16 @@ fn render_human(report: &DoctorReport) {println!(" recent window: last {} days\n", report.since_days);}+ if let Some(problem) = &report.marker_capture_problem {+ println!(+ "⚠ {} has an invalid `[capture]` section: {}\n \+ It fails closed — file and shell tool content is reduced to metadata there, \+ nothing leaks — but its `ignore_paths` exclusions are NOT applying while it stays \+ invalid. Fix the TOML and re-run `ai-memory doctor` to confirm.\n",+ problem.marker_path, problem.reason+ );+ }+if report.rows.is_empty() {println!(" No local harness sessions found for this project and nothing captured yet.");return;diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rsindex 98ce8413..3d953b9d 100644--- a/crates/ai-memory-cli/src/commands/hook_capture.rs+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs@@ -16,7 +16,9 @@ use crate::marker::{repo_root_project,};use ai_memory_hooks::capture_policy::MAX_MARKER_BYTES;-use ai_memory_hooks::{CaptureConfig, CapturePolicy, CaptureSource};+use ai_memory_hooks::{+ CaptureConfig, CapturePolicy, CaptureSource, PolicyState, describe_invalid_capture_config,+};/// Resolve the nearest marker's capture policy without changing routing parsing./// Root-level marker keys are intentionally ignored here; only `[capture]` is strict.@@ -45,36 +47,97 @@ pub fn capture_policy(cwd: &str) -> CapturePolicy {}fn read_capture_config(marker: &Path) -> Result<CaptureConfig, ()> {+ read_capture_config_verbose(marker).map_err(|_reason| ())+}++/// Same parse as [`read_capture_config`], but keeps the failure reason+/// instead of collapsing it to `()`. The hot hook path only needs "did this+/// parse" and discards the reason; diagnostics (`ai-memory doctor`) need it.+/// Note this only covers the TOML-parse / `[capture]`-shape stage — a config+/// that parses fine here can still be rejected later at compile time (see+/// [`ai_memory_hooks::describe_invalid_capture_config`]).+fn read_capture_config_verbose(marker: &Path) -> Result<CaptureConfig, String> {let mut bytes = Vec::with_capacity(MAX_MARKER_BYTES + 1);std::fs::File::open(marker)- .map_err(|_| ())?+ .map_err(|e| format!("could not open marker file: {e}"))?.take((MAX_MARKER_BYTES + 1) as u64).read_to_end(&mut bytes)- .map_err(|_| ())?;+ .map_err(|e| format!("could not read marker file: {e}"))?;if bytes.len() > MAX_MARKER_BYTES {- return Err(());+ return Err(format!(+ "marker file is larger than the {MAX_MARKER_BYTES}-byte capture-config limit"+ ));}- let text = String::from_utf8(bytes).map_err(|_| ())?;- let document = text.parse::<toml_edit::DocumentMut>().map_err(|_| ())?;+ let text =+ String::from_utf8(bytes).map_err(|e| format!("marker file is not valid UTF-8: {e}"))?;+ let document = text+ .parse::<toml_edit::DocumentMut>()+ .map_err(|e| format!("invalid TOML: {e}"))?;let Some(capture) = document.get("capture") else {return Ok(CaptureConfig::default());};- let table = capture.as_table().ok_or(())?;- if table.iter().any(|(key, _)| key != "ignore_paths") {- return Err(());+ let table = capture+ .as_table()+ .ok_or_else(|| "`[capture]` must be a table".to_owned())?;+ if let Some((key, _)) = table.iter().find(|(key, _)| *key != "ignore_paths") {+ return Err(format!(+ "`[capture]` has an unsupported key `{key}` (only `ignore_paths` is allowed)"+ ));}let ignore_paths = match table.get("ignore_paths") {None => Vec::new(),- Some(item) => item- .as_array()- .ok_or(())?- .iter()- .map(|value| value.as_str().map(str::to_owned).ok_or(()))- .collect::<Result<Vec<_>, _>>()?,+ Some(item) => {+ item.as_array()+ .ok_or_else(|| "`[capture].ignore_paths` must be an array".to_owned())?+ .iter()+ .map(|value| {+ value.as_str().map(str::to_owned).ok_or_else(|| {+ "`[capture].ignore_paths` must contain only strings".to_owned()+ })+ })+ .collect::<Result<Vec<_>, _>>()?+ }};Ok(CaptureConfig { ignore_paths })}+/// Diagnostic for `ai-memory doctor`: does the nearest `.ai-memory.toml`'s+/// `[capture]` section actually resolve into an active policy?+///+/// Bases the check on [`capture_policy`]'s own resolution state -- the exact+/// state the live hook path uses -- rather than a parse-only check, because a+/// `[capture]` table can parse as valid TOML and still be rejected later at+/// compile time (too many patterns, an unsupported glob character, a `~/`+/// pattern with no home directory to expand it...), which a parse-only check+/// would miss entirely.+///+/// Returns `None` when there is no marker, or the marker's capture config+/// resolves (absent, empty, or a valid active policy). Returns+/// `Some((marker_path, reason))` when a marker exists and its `[capture]`+/// table is [`PolicyState::Invalid`] -- which fails CLOSED (every file and+/// shell tool event is reduced to metadata until the marker is fixed;+/// nothing leaks) but with no other signal anywhere that it happened.+pub fn capture_config_problem(cwd: &str) -> Option<(PathBuf, String)> {+ let marker = find_marker(cwd)?;+ if capture_policy(cwd).state() != PolicyState::Invalid {+ return None;+ }+ let marker_dir = marker.parent().and_then(Path::to_str).unwrap_or(cwd);+ let home = home_dir();+ let reason = match read_capture_config_verbose(&marker) {+ Err(reason) => reason,+ Ok(config) => describe_invalid_capture_config(+ &config,+ marker_dir,+ home.as_deref().and_then(Path::to_str),+ )+ .unwrap_or_else(|| {+ "the `[capture]` table did not resolve into an active policy".to_owned()+ }),+ };+ Some((marker, reason))+}+/// First top-level `cwd` string in the payload (parity with/// `ai_memory_extract_cwd`: take the top-level value, ignore nested/// `cwd` fields in tool payloads).@@ -1367,4 +1430,84 @@ drop_subagent_captures = "true"assert!(qs.contains("&project=pinned"), "{qs}");assert!(qs.contains("&project_strategy=repo-root"), "{qs}");}++ #[test]+ fn capture_config_problem_is_none_without_a_marker() {+ let tmp = tempfile::TempDir::new().unwrap();+ assert!(capture_config_problem(tmp.path().to_str().unwrap()).is_none());+ }++ #[test]+ fn capture_config_problem_is_none_for_a_well_formed_capture_table() {+ let tmp = tempfile::TempDir::new().unwrap();+ std::fs::write(+ tmp.path().join(".ai-memory.toml"),+ "project = \"ok\"\n\n[capture]\nignore_paths = [\"**/.env\"]\n",+ )+ .unwrap();+ assert!(capture_config_problem(tmp.path().to_str().unwrap()).is_none());+ }++ /// The exact failure mode found in practice: a dropped `#` turns a+ /// wrapped comment into a stray token right after a `[capture]` header,+ /// which is invalid TOML.+ #[test]+ fn capture_config_problem_reports_a_toml_syntax_error() {+ let tmp = tempfile::TempDir::new().unwrap();+ let marker = tmp.path().join(".ai-memory.toml");+ std::fs::write(+ &marker,+ "project = \"example\"\n\n\+ [capture] this used to be a comment, now it is a stray token\n\+ project_strategy = \"repo-root\"\n\n\+ [capture]\nignore_paths = [\"**/.env\"]\n",+ )+ .unwrap();+ let (reported_marker, reason) =+ capture_config_problem(tmp.path().to_str().unwrap()).expect("malformed TOML");+ assert_eq!(reported_marker, marker);+ assert!(reason.contains("invalid TOML"), "{reason}");+ }++ #[test]+ fn capture_config_problem_reports_an_unsupported_capture_key() {+ let tmp = tempfile::TempDir::new().unwrap();+ std::fs::write(+ tmp.path().join(".ai-memory.toml"),+ "[capture]\nallowlist = [\"**\"]\n",+ )+ .unwrap();+ let (_, reason) =+ capture_config_problem(tmp.path().to_str().unwrap()).expect("unsupported key");+ assert!(reason.contains("allowlist"), "{reason}");+ }++ /// The gap the parse-only check missed: a `[capture]` table that is+ /// perfectly valid TOML, and a `[capture]` shape `read_capture_config`+ /// accepts, but whose `ignore_paths` entry `compile` itself rejects (an+ /// unsupported glob character). `capture_policy(cwd).state()` must still+ /// catch this as `Invalid` even though the TOML parse alone would not.+ #[test]+ fn capture_config_problem_reports_a_pattern_compile_failure() {+ let tmp = tempfile::TempDir::new().unwrap();+ std::fs::write(+ tmp.path().join(".ai-memory.toml"),+ "[capture]\nignore_paths = [\"secrets/{a,b}\"]\n",+ )+ .unwrap();+ let (_, reason) = capture_config_problem(tmp.path().to_str().unwrap())+ .expect("a rejected glob must still surface as a problem");+ assert!(reason.contains("secrets/{a,b}"), "{reason}");+ assert!(reason.contains("unsupported glob character"), "{reason}");+ }++ #[test]+ fn read_capture_config_and_verbose_agree_on_success() {+ let tmp = tempfile::TempDir::new().unwrap();+ let marker = tmp.path().join(".ai-memory.toml");+ std::fs::write(&marker, "[capture]\nignore_paths = [\"**/*.pem\"]\n").unwrap();+ let terse = read_capture_config(&marker).expect("valid marker parses");+ let verbose = read_capture_config_verbose(&marker).expect("valid marker parses");+ assert_eq!(terse.ignore_paths, verbose.ignore_paths);+ }}diff --git a/crates/ai-memory-hooks/src/capture_policy.rs b/crates/ai-memory-hooks/src/capture_policy.rsindex 766f2fc3..55a72c29 100644--- a/crates/ai-memory-hooks/src/capture_policy.rs+++ b/crates/ai-memory-hooks/src/capture_policy.rs@@ -437,6 +437,19 @@ impl CaptureDecision {}impl CapturePolicy {+ /// This policy's resolution state: whether a marker was absent, parsed+ /// into an active pattern set, or present but rejected (bad TOML, a+ /// `[capture]` shape `read_capture_config` doesn't accept, or a pattern+ /// `compile` rejects, e.g. an unsupported glob). `Invalid` already fails+ /// closed in [`Self::inspect`] — this accessor exists for diagnostics+ /// (`ai-memory doctor`) that want to say *why* without re-deriving it+ /// from scratch or trusting a parse-only check that misses the+ /// `compile`-rejected case.+ #[must_use]+ pub const fn state(&self) -> PolicyState {+ self.state+ }+/// Resolves a marker config atomically. Empty parsed configuration is inactive./// `home_dir` is required only when at least one pattern starts with `~/`.#[must_use]@@ -462,7 +475,7 @@ impl CapturePolicy {patterns,home: home_dir.and_then(|dir| normalize_root(dir).ok()),},- Err(()) => Self {+ Err(_) => Self {state: PolicyState::Invalid,patterns: Vec::new(),home: None,@@ -1042,11 +1055,14 @@ fn compile(config: &CaptureConfig,marker_dir: &str,home_dir: Option<&str>,-) -> Result<Vec<CompiledPattern>, ()> {+) -> Result<Vec<CompiledPattern>, String> {if config.ignore_paths.len() > MAX_IGNORE_PATTERNS {- return Err(());+ return Err(format!(+ "`ignore_paths` has more than {MAX_IGNORE_PATTERNS} entries"+ ));}- let marker = normalize_root(marker_dir).map_err(|_| ())?;+ let marker = normalize_root(marker_dir)+ .map_err(|_| "the repository path could not be normalized".to_owned())?;let needs_home = config.ignore_paths.iter()@@ -1055,7 +1071,10 @@ fn compile(Some(home_dir.and_then(|dir| normalize_root(dir).ok())- .ok_or(())?,+ .ok_or_else(|| {+ "a pattern starts with '~/' but no home directory is available to expand it"+ .to_owned()+ })?,)} else {None@@ -1064,16 +1083,22 @@ fn compile(.ignore_paths.iter().map(|source| {- validate_glob(source)?;+ validate_glob(source)+ .map_err(|reason| format!("ignore_paths entry {source:?} {reason}"))?;let expanded = if let Some(rest) = source.strip_prefix("~/") {- join(home.as_deref().ok_or(())?, rest)+ join(+ home.as_deref().expect("needs_home found this pattern"),+ rest,+ )} else if is_absolute(source) {source.clone()} else {join(&marker, source)};let flavor = flavor_of(&expanded);- let path = normalize_segments(&expanded).ok_or(())?;+ let path = normalize_segments(&expanded).ok_or_else(|| {+ format!("ignore_paths entry {source:?} could not be normalized into a path")+ })?;Ok(CompiledPattern {literal_prefix: literal_prefix(&path).into(),directory_base: path.strip_suffix("/**").map(|base| {@@ -1089,20 +1114,59 @@ fn compile(}).collect()}-fn validate_glob(pattern: &str) -> Result<(), ()> {- if pattern.trim().is_empty()- || pattern.chars().count() > MAX_IGNORE_PATTERN_CHARS- || pattern.contains(['!', '{', '}', '[', ']', '(', ')', '|', '^', '$', '%'])- || pattern.contains("${")- || pattern.contains("***")- || pattern- .replace('\\', "/")- .split('/')- .any(|segment| segment == "..")- || (pattern.starts_with('~') && !pattern.starts_with("~/"))- || is_drive_relative(pattern)++/// Diagnostic twin of the compile step [`CapturePolicy::resolve`] runs: a+/// `[capture]` table can parse as valid TOML and still fail here (too many+/// patterns, an unsupported glob character, a `..` segment, a `~/` pattern+/// with no home directory to expand it...), which is exactly the gap a+/// parse-only check (e.g. `read_capture_config_verbose`) misses. `None`+/// means this config would compile into an active policy; `Some(reason)`+/// names the first rejected pattern and why.+#[must_use]+pub fn describe_invalid_capture_config(+ config: &CaptureConfig,+ marker_dir: &str,+ home_dir: Option<&str>,+) -> Option<String> {+ if config.ignore_paths.is_empty() {+ return None;+ }+ compile(config, marker_dir, home_dir).err()+}+fn validate_glob(pattern: &str) -> Result<(), String> {+ if pattern.trim().is_empty() {+ return Err("is empty".to_owned());+ }+ if pattern.chars().count() > MAX_IGNORE_PATTERN_CHARS {+ return Err(format!(+ "is longer than {MAX_IGNORE_PATTERN_CHARS} characters"+ ));+ }+ if pattern.contains(['!', '{', '}', '[', ']', '(', ')', '|', '^', '$', '%']) {+ return Err(+ "contains an unsupported glob character (one of ! { } [ ] ( ) | ^ $ %)".to_owned(),+ );+ }+ if pattern.contains("${") {+ return Err("contains a shell-style variable expansion (${...})".to_owned());+ }+ if pattern.contains("***") {+ return Err("contains three or more consecutive '*'".to_owned());+ }+ if pattern+ .replace('\\', "/")+ .split('/')+ .any(|segment| segment == ".."){- return Err(());+ return Err("contains a '..' path segment".to_owned());+ }+ if pattern.starts_with('~') && !pattern.starts_with("~/") {+ return Err(+ "starts with '~' but not '~/' (only home-relative '~/...' is supported)".to_owned(),+ );+ }+ if is_drive_relative(pattern) {+ return Err("is drive-relative (e.g. 'C:foo' without a path separator)".to_owned());}Ok(())}@@ -1286,6 +1350,83 @@ mod tests {// A new field must not silently tighten capture for existing installs.assert_eq!(CaptureMode::default(), CaptureMode::Denylist);}++ #[test]+ fn state_reports_active_for_a_valid_config() {+ let policy = CapturePolicy::resolve(+ CaptureSource::Parsed(&CaptureConfig {+ ignore_paths: vec!["secret/**".into()],+ }),+ "/repo",+ None,+ );+ assert_eq!(policy.state(), PolicyState::Active);+ }++ #[test]+ fn state_reports_inactive_for_an_absent_marker() {+ let policy = CapturePolicy::resolve(CaptureSource::Absent, "/repo", None);+ assert_eq!(policy.state(), PolicyState::Inactive);+ }++ #[test]+ fn state_reports_inactive_for_an_empty_ignore_paths() {+ let policy = CapturePolicy::resolve(+ CaptureSource::Parsed(&CaptureConfig {+ ignore_paths: Vec::new(),+ }),+ "/repo",+ None,+ );+ assert_eq!(policy.state(), PolicyState::Inactive);+ }++ #[test]+ fn state_reports_invalid_for_a_parse_failure() {+ let policy = CapturePolicy::resolve(CaptureSource::Invalid, "/repo", None);+ assert_eq!(policy.state(), PolicyState::Invalid);+ }++ #[test]+ fn state_reports_invalid_for_a_config_that_parses_but_does_not_compile() {+ // This is exactly the gap a parse-only check misses: valid TOML,+ // valid `[capture]` shape, but a pattern `compile` itself rejects.+ let policy = CapturePolicy::resolve(+ CaptureSource::Parsed(&CaptureConfig {+ ignore_paths: vec!["secrets/{a,b}".into()],+ }),+ "/repo",+ None,+ );+ assert_eq!(policy.state(), PolicyState::Invalid);+ }++ #[test]+ fn describe_invalid_capture_config_is_none_when_it_would_compile() {+ let config = CaptureConfig {+ ignore_paths: vec!["secret/**".into()],+ };+ assert!(describe_invalid_capture_config(&config, "/repo", None).is_none());+ }++ #[test]+ fn describe_invalid_capture_config_names_the_rejected_pattern() {+ let config = CaptureConfig {+ ignore_paths: vec!["ok/**".into(), "secrets/{a,b}".into()],+ };+ let reason = describe_invalid_capture_config(&config, "/repo", None)+ .expect("a rejected glob must produce a reason");+ assert!(reason.contains("secrets/{a,b}"), "{reason}");+ assert!(reason.contains("unsupported glob character"), "{reason}");+ }++ #[test]+ fn describe_invalid_capture_config_is_none_for_an_empty_config() {+ let config = CaptureConfig {+ ignore_paths: Vec::new(),+ };+ assert!(describe_invalid_capture_config(&config, "/repo", None).is_none());+ }#[test]fn fixture_vectors() {let fixture: Value =diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rsindex 5c9e6bc0..12f99e3e 100644--- a/crates/ai-memory-hooks/src/lib.rs+++ b/crates/ai-memory-hooks/src/lib.rs@@ -47,7 +47,7 @@ pub use assistant_capture::{pub use capture_policy::{CaptureConfig, CaptureDecision, CaptureDisposition, CaptureMode, CapturePolicy,CaptureProtocol, CaptureSource, ExtractionState, PolicyState, ToolFamily,- repository_admits_capture,+ describe_invalid_capture_config, repository_admits_capture,};pub use payload::{HookEnvelope, HookEvent, NOTIFICATION_EXCERPT_MAX_BYTES, POST_COMPACTION_EXCERPT_MAX_BYTES,