Skip to content

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

Rust

fix(admin): harden contamination audit scope

AkitaOnRails2634b90715d6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a4b58362..7daef384 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]
+### Added
+- `GET /admin/audit-contamination` (and `ai-memory audit-contamination`) — a
+ read-only, SQL-only structural cross-project contamination audit. Flags
+ sessions whose `cwd` longest-prefix-resolves to a different project than the
+ one they landed in (the auto-scope-bleed signature, resolved with the same
+ prefix logic the runtime uses) and observations whose project disagrees with
+ their owning session (a regression tripwire that should stay empty on a
+ healthy DB). Optional `?workspace=&project=` scope; reports only, never
+ mutates, so it is safe to run on any cadence. Purely semantic mislandings
+ (no cwd/session anomaly) are out of scope by design.
+
## [1.0.11] - 2026-06-15
### Added
@@ -102,17 +113,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
instance running scope-guard. `rename-project` is unaffected (it runs no
admission chain).
-### Added
-- `GET /admin/audit-contamination` (and `ai-memory audit-contamination`) — a
- read-only, SQL-only structural cross-project contamination audit. Flags
- sessions whose `cwd` longest-prefix-resolves to a different project than the
- one they landed in (the auto-scope-bleed signature, resolved with the same
- prefix logic the runtime uses) and observations whose project disagrees with
- their owning session (a regression tripwire that should stay empty on a
- healthy DB). Optional `?workspace=&project=` scope; reports only, never
- mutates, so it is safe to run on any cadence. Purely semantic mislandings
- (no cwd/session anomaly) are out of scope by design.
-
## [1.0.6] - 2026-06-14
### Changed
diff --git a/README.md b/README.md
index 786a4c64..6a5020f5 100644
--- a/README.md
+++ b/README.md
@@ -88,8 +88,9 @@ priors are at the [bottom](#influences-and-prior-art).
[`[auto_scope]` modes](docs/auto-scope.md) for per-user or
session-aware current-project routing.
- **Thin-client CLI.** `ai-memory status`, `bootstrap`, `checkpoints`,
- `restore-page`, `purge-project`, `rename-project`, `move-project`, `lint`,
- `curator`, `auto-improve`, `pending-writes`, `embed`, `forget-sweep`, `backup` are
+ `restore-page`, `purge-project`, `rename-project`, `move-project`,
+ `audit-contamination`, `lint`, `curator`, `auto-improve`, `pending-writes`,
+ `embed`, `forget-sweep`, `backup` are
all HTTP clients of the running server - never touch SQLite or
wiki files directly. `status` also reports passive LLM/embedding
provider health from the last real provider call. Server is the
diff --git a/crates/ai-memory-cli/src/commands/audit_contamination.rs b/crates/ai-memory-cli/src/commands/audit_contamination.rs
index 8573b3dc..cc2cfa95 100644
--- a/crates/ai-memory-cli/src/commands/audit_contamination.rs
+++ b/crates/ai-memory-cli/src/commands/audit_contamination.rs
@@ -4,7 +4,7 @@
//! server and renders the report as human text or JSON. Read-only — the server
//! only reports, never mutates; remediation is a separate operator step.
-use anyhow::Result;
+use anyhow::{Result, bail};
use serde::{Deserialize, Serialize};
use crate::cli::AuditContaminationArgs;
@@ -51,12 +51,7 @@ struct Finding {
/// response can't be parsed.
pub async fn run(config: &Config, args: AuditContaminationArgs) -> Result<()> {
let ep = ServerEndpoint::from_config(config);
- // Both workspace+project scope the audit to one landed bucket; either alone
- // is ignored (a partial scope is meaningless) — audit everything instead.
- let query: Vec<(&str, &str)> = match (args.workspace.as_deref(), args.project.as_deref()) {
- (Some(ws), Some(proj)) => vec![("workspace", ws), ("project", proj)],
- _ => Vec::new(),
- };
+ let query = scope_query(&args)?;
let report: Report = get_json(&ep, "/admin/audit-contamination", &query).await?;
if args.json {
@@ -101,3 +96,39 @@ pub async fn run(config: &Config, args: AuditContaminationArgs) -> Result<()> {
}
Ok(())
}
+
+fn scope_query(args: &AuditContaminationArgs) -> Result<Vec<(&str, &str)>> {
+ match (args.workspace.as_deref(), args.project.as_deref()) {
+ (Some(ws), Some(proj)) => Ok(vec![("workspace", ws), ("project", proj)]),
+ (None, None) => Ok(Vec::new()),
+ _ => bail!("--workspace and --project must be provided together"),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn args(workspace: Option<&str>, project: Option<&str>) -> AuditContaminationArgs {
+ AuditContaminationArgs {
+ workspace: workspace.map(str::to_string),
+ project: project.map(str::to_string),
+ json: false,
+ }
+ }
+
+ #[test]
+ fn scope_query_rejects_partial_scope() {
+ assert!(scope_query(&args(Some("default"), None)).is_err());
+ assert!(scope_query(&args(None, Some("ai-memory"))).is_err());
+ }
+
+ #[test]
+ fn scope_query_accepts_global_or_complete_scope() {
+ assert!(scope_query(&args(None, None)).unwrap().is_empty());
+ assert_eq!(
+ scope_query(&args(Some("default"), Some("ai-memory"))).unwrap(),
+ vec![("workspace", "default"), ("project", "ai-memory")]
+ );
+ }
+}
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 76e4273a..b178cda6 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -314,6 +314,7 @@ fn default_auto_improve_pending_path() -> String {
/// - `POST /admin/auto-improve`
/// - `POST /admin/curator`
/// - `GET /admin/status`
+/// - `GET /admin/audit-contamination`
/// - `GET /admin/search`
/// - `GET /admin/read-page`
/// - `POST /admin/reorg`
@@ -526,11 +527,22 @@ async fn handle_audit_contamination(
State(state): State<Arc<AdminState>>,
Query(q): Query<AuditContaminationQuery>,
) -> impl IntoResponse {
- let scope = match (q.workspace.as_deref(), q.project.as_deref()) {
+ let scope = match (
+ trimmed_opt(q.workspace.as_deref()),
+ trimmed_opt(q.project.as_deref()),
+ ) {
(Some(ws), Some(proj)) => match lookup_ws_proj_no_create(&state, ws, proj).await {
Ok(ids) => Some(ids),
Err(e) => return e,
},
+ (Some(_), None) | (None, Some(_)) => {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({
+ "error": "workspace and project must be provided together"
+ })),
+ );
+ }
_ => None,
};
match state.reader.audit_contamination(scope).await {
@@ -4513,6 +4525,32 @@ mod tests {
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
+ #[tokio::test]
+ async fn audit_contamination_partial_scope_fails_closed() {
+ let (_tmp, router) = read_page_test_router();
+
+ for uri in [
+ "/admin/audit-contamination?workspace=default",
+ "/admin/audit-contamination?project=ai-memory",
+ ] {
+ let resp = router
+ .clone()
+ .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
+ .await
+ .unwrap();
+
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{uri}");
+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert!(
+ json["error"]
+ .as_str()
+ .unwrap_or_default()
+ .contains("workspace and project must be provided together")
+ );
+ }
+ }
+
#[tokio::test]
async fn auto_improve_auto_approves_by_default_and_uses_concrete_operations() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 85b9e2db..dc18178d 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -3334,9 +3334,8 @@ impl ReaderPool {
/// - **CHECK A** (`session_wrong_bucket`): a session whose `cwd`
/// longest-prefix-resolves to a *different* project than the one it landed
/// in — the direct signature of the auto-scope bleed bug. Resolved with the
- /// SAME [`Self::find_project_by_cwd_prefix`] the runtime uses, so the audit
- /// never claims a session a live resolve would not (exact prefix + cwd
- /// safety parity).
+ /// same prefix and cwd-safety rules as [`Self::find_project_by_cwd_prefix`],
+ /// so the audit never claims a session a live resolve would not.
/// - **CHECK B** (`observation_session_drift`): an observation whose
/// `project_id` disagrees with its owning session's. On a healthy DB this
/// is always empty, so a non-empty result is a regression alarm.
@@ -3360,11 +3359,18 @@ impl ReaderPool {
None => Vec::new(),
};
- // Phase 1 (one connection): CHECK B findings + the candidate session
- // list that Phase 2 resolves with the runtime cwd resolver.
+ // One connection: CHECK B findings + the candidate session list + the
+ // valid repo_path prefixes used to resolve CHECK A. Loading prefixes
+ // once avoids a reader query per historical session while preserving the
+ // same path boundary and safety rules as the runtime resolver.
type Candidate = (String, WorkspaceId, ProjectId, String, String, String);
+ type Prefix = (WorkspaceId, ProjectId, String, String);
let sp_b = scope_params.clone();
- let (mut findings, candidates): (Vec<ContaminationFinding>, Vec<Candidate>) = self
+ let (mut findings, candidates, prefixes): (
+ Vec<ContaminationFinding>,
+ Vec<Candidate>,
+ Vec<Prefix>,
+ ) = self
.with_conn(move |conn| {
let mut findings: Vec<ContaminationFinding> = Vec::new();
@@ -3445,16 +3451,78 @@ impl ReaderPool {
}
}
- Ok((findings, candidates))
+ let mut p_sql = String::from(
+ "SELECT workspace_id, id, name, repo_path \
+ FROM projects \
+ WHERE repo_path IS NOT NULL \
+ AND length(repo_path) > 1 \
+ AND repo_path NOT LIKE '%/' \
+ AND repo_path NOT LIKE '%\\%%' ESCAPE '\\' \
+ AND repo_path NOT LIKE '%\\_%' ESCAPE '\\'",
+ );
+ if scoped {
+ p_sql.push_str(" AND workspace_id = ?");
+ }
+ p_sql.push_str(" ORDER BY length(repo_path) DESC");
+ let mut prefixes: Vec<Prefix> = Vec::new();
+ {
+ let mut stmt = conn.prepare(&p_sql)?;
+ if scoped {
+ let rows = stmt.query_map(params_from_iter(scope_params.iter().take(1)), |row| {
+ Ok((
+ row.get::<_, Vec<u8>>(0)?,
+ row.get::<_, Vec<u8>>(1)?,
+ row.get::<_, String>(2)?,
+ row.get::<_, String>(3)?,
+ ))
+ })?;
+ for r in rows {
+ let (ws_b, proj_b, name, repo_path) = r?;
+ prefixes.push((
+ WorkspaceId::from_slice(&ws_b)?,
+ ProjectId::from_slice(&proj_b)?,
+ name,
+ repo_path,
+ ));
+ }
+ } else {
+ let rows = stmt.query_map([], |row| {
+ Ok((
+ row.get::<_, Vec<u8>>(0)?,
+ row.get::<_, Vec<u8>>(1)?,
+ row.get::<_, String>(2)?,
+ row.get::<_, String>(3)?,
+ ))
+ })?;
+ for r in rows {
+ let (ws_b, proj_b, name, repo_path) = r?;
+ prefixes.push((
+ WorkspaceId::from_slice(&ws_b)?,
+ ProjectId::from_slice(&proj_b)?,
+ name,
+ repo_path,
+ ));
+ }
+ }
+ }
+
+ Ok((findings, candidates, prefixes))
})
.await?;
- // Phase 2 — CHECK A: resolve each session's cwd with the runtime
- // resolver and flag a bucket mismatch.
+ // CHECK A: resolve each session's cwd against preloaded valid prefixes
+ // and flag a bucket mismatch.
for (id, ws, landed_proj, landed_ws_name, landed_proj_name, cwd) in candidates {
- if let Some((resolved_proj, resolved_name)) =
- self.find_project_by_cwd_prefix(ws, cwd.clone()).await?
- && resolved_proj != landed_proj
+ let cwd_norm = cwd.trim_end_matches('/').to_string();
+ if !is_safe_cwd_for_prefix_match(&cwd_norm) {
+ continue;
+ }
+ let resolved = prefixes.iter().find(|(prefix_ws, _, _, repo_path)| {
+ *prefix_ws == ws
+ && (cwd_norm == *repo_path || cwd_norm.starts_with(&format!("{repo_path}/")))
+ });
+ if let Some((_, resolved_proj, resolved_name, _)) = resolved
+ && *resolved_proj != landed_proj
{
findings.push(ContaminationFinding {
check: "session_wrong_bucket",
@@ -3463,7 +3531,7 @@ impl ReaderPool {
entity_id: id,
landed_workspace: landed_ws_name,
landed_project: landed_proj_name,
- expected_project: Some(resolved_name),
+ expected_project: Some(resolved_name.clone()),
cwd: Some(cwd),
session_id: None,
});
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 14e47152..5f31b059 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -261,8 +261,8 @@ forget-sweep lint auto-improve
curator pending-writes embed
generate-auth-token setup-agent bootstrap
install-instructions reorg purge-project
-rename-project move-project uninstall
-auth user
+rename-project move-project audit-contamination
+uninstall auth user
```
Run `ai-memory --help` for the full tree.
diff --git a/docs/install.md b/docs/install.md
index 01ab3a0b..be2fb6a2 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -887,7 +887,7 @@ Two ways to invoke a subcommand against the docker deploy:
```bash
# A) Against the running container (stateful: status, search, backup,
-# checkpoints, restore-page, forget-sweep, lint, embed).
+# checkpoints, restore-page, audit-contamination, forget-sweep, lint, embed).
docker exec ai-memory ai-memory status --json
docker exec ai-memory ai-memory search "karpathy"
docker exec ai-memory ai-memory backup --to /data/snapshot.tar.gz
@@ -909,6 +909,7 @@ docker run --rm akitaonrails/ai-memory:latest --help # full subcommand tree
| `write-page` | `docker exec` | Manual page write (atomic + indexed) |
| `backup --to` / `restore --from` | `docker exec` | Snapshot or restore the data dir |
| `checkpoints` / `restore-page` | `docker exec` | List wiki git checkpoints or restore one markdown page and reindex it |
+| `audit-contamination` | `docker exec` | Read-only structural audit for likely cross-project contamination |
| `forget-sweep` / `lint` / `embed` | `docker exec` | Manual maintenance; sweep + lint also run on the server schedule by default |
| `commit -m "…"` | `docker exec` | Stage + commit the wiki tree |
| `reset --confirm` | `docker exec` | Wipe data (refuses while siblings alive) |