Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(admin): add read-only cross-project contamination audit
Djalma Júnior9e35a4146582
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 403b2de5..a4b58362 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -102,6 +102,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0instance running scope-guard. `rename-project` is unaffected (it runs noadmission 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### Changeddiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 8f42da08..bbfede30 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -31,6 +31,10 @@ pub enum Command {Init(InitArgs),/// Print runtime status (counts, paths, version).Status(StatusArgs),+ /// Audit the store for likely cross-project contamination (read-only,+ /// SQL-only). Flags sessions whose cwd resolves to a different project and+ /// observations whose project disagrees with their session.+ AuditContamination(AuditContaminationArgs),/// Full-text search the wiki via FTS5.Search(SearchArgs),/// Fetch and display the full body of a wiki page.@@ -567,6 +571,20 @@ pub struct StatusArgs {pub json: bool,}+/// Arguments for `audit-contamination`.+#[derive(Debug, Args)]+pub struct AuditContaminationArgs {+ /// Restrict the audit to one workspace (use together with `--project`).+ #[arg(long)]+ pub workspace: Option<String>,+ /// Restrict the audit to one project (use together with `--workspace`).+ #[arg(long)]+ pub project: Option<String>,+ /// Emit the report as JSON instead of human-readable text.+ #[arg(long)]+ pub json: bool,+}+/// Arguments for `search`.#[derive(Debug, Args)]pub struct SearchArgs {diff --git a/crates/ai-memory-cli/src/commands/audit_contamination.rs b/crates/ai-memory-cli/src/commands/audit_contamination.rsnew file mode 100644index 00000000..8573b3dc--- /dev/null+++ b/crates/ai-memory-cli/src/commands/audit_contamination.rs@@ -0,0 +1,103 @@+//! `ai-memory audit-contamination` — structural cross-project contamination audit.+//!+//! Thin HTTP client. Calls `GET /admin/audit-contamination` on the configured+//! 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 serde::{Deserialize, Serialize};++use crate::cli::AuditContaminationArgs;+use crate::config::Config;+use crate::http_client::{ServerEndpoint, get_json};++/// Server-shaped response. Mirrors `ai_memory_store::ContaminationReport`.+#[derive(Debug, Default, Deserialize, Serialize)]+struct Report {+ #[serde(default)]+ summary: Summary,+ #[serde(default)]+ findings: Vec<Finding>,+}++#[derive(Debug, Default, Deserialize, Serialize)]+struct Summary {+ #[serde(default)]+ sessions_misbucketed: usize,+ #[serde(default)]+ observations_drifted: usize,+}++#[derive(Debug, Deserialize, Serialize)]+struct Finding {+ check: String,+ confidence: String,+ entity_kind: String,+ entity_id: String,+ landed_workspace: String,+ landed_project: String,+ #[serde(default)]+ expected_project: Option<String>,+ #[serde(default)]+ cwd: Option<String>,+ #[serde(default)]+ session_id: Option<String>,+}++/// Run the `audit-contamination` subcommand.+///+/// # Errors+/// Returns an error if the server is unreachable, returns non-2xx, or the+/// 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 report: Report = get_json(&ep, "/admin/audit-contamination", &query).await?;++ if args.json {+ println!("{}", serde_json::to_string_pretty(&report)?);+ return Ok(());+ }++ if report.findings.is_empty() {+ println!("No structural contamination found (sessions + observations consistent).");+ return Ok(());+ }+ println!(+ "Contamination audit: {} session(s) mis-bucketed, {} observation(s) drifted.",+ report.summary.sessions_misbucketed, report.summary.observations_drifted+ );+ for f in &report.findings {+ let expected = f.expected_project.as_deref().unwrap_or("?");+ match f.check.as_str() {+ "session_wrong_bucket" => println!(+ " [{}] session {} landed in {}/{} but its cwd ({}) resolves to project {}",+ f.confidence,+ f.entity_id,+ f.landed_workspace,+ f.landed_project,+ f.cwd.as_deref().unwrap_or("?"),+ expected,+ ),+ "observation_session_drift" => println!(+ " [{}] observation {} in {}/{} but its session ({}) is in project {}",+ f.confidence,+ f.entity_id,+ f.landed_workspace,+ f.landed_project,+ f.session_id.as_deref().unwrap_or("?"),+ expected,+ ),+ other => println!(+ " [{}] {} {} in {}/{}",+ f.confidence, other, f.entity_id, f.landed_workspace, f.landed_project+ ),+ }+ }+ Ok(())+}diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rsindex c13029a9..9e4a5c05 100644--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@ -5,6 +5,7 @@ use anyhow::{Context, Result, anyhow, bail};use crate::config::Config;pub mod apply_shared;+pub mod audit_contamination;pub mod auth;pub mod auto_improve;pub mod backup;diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rsindex 825da088..be9a1dab 100644--- a/crates/ai-memory-cli/src/main.rs+++ b/crates/ai-memory-cli/src/main.rs@@ -56,6 +56,9 @@ async fn main() -> Result<()> {match command {Command::Init(args) => commands::init::run(&config, args, config_path.as_deref()),Command::Status(args) => commands::status::run(&config, args).await,+ Command::AuditContamination(args) => {+ commands::audit_contamination::run(&config, args).await+ }Command::Search(args) => commands::search::run(&config, args).await,Command::ReadPage(args) => commands::read_page::run(&config, args).await,Command::WritePage(args) => commands::write_page::run(&config, args).await,diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex 6741c337..76e4273a 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -354,6 +354,10 @@ pub fn admin_router(state: AdminState) -> Router {post(handle_pending_write_reject),).route("/admin/status", get(handle_status))+ .route(+ "/admin/audit-contamination",+ get(handle_audit_contamination),+ ).route("/admin/search", get(handle_search)).route("/admin/read-page", get(handle_read_page)).route("/admin/reorg", post(handle_reorg))@@ -504,6 +508,43 @@ async fn build_backup_tarball_file(state: &AdminState) -> anyhow::Result<tokio::// status// ---------------------------------------------------------------------+/// Query string for `GET /admin/audit-contamination`. Supplying BOTH+/// `workspace` and `project` scopes the audit to that one landed bucket;+/// omit both to audit every project.+#[derive(Deserialize)]+struct AuditContaminationQuery {+ workspace: Option<String>,+ project: Option<String>,+}++/// `GET /admin/audit-contamination` — read-only structural contamination audit+/// (see [`ai_memory_store::ReaderPool::audit_contamination`]). Reports likely+/// cross-project mislandings (a session whose cwd resolves elsewhere; an+/// observation whose project disagrees with its session); never mutates, so it+/// is safe to run on any cadence (e.g. a cron probe alerting on non-zero counts).+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()) {+ (Some(ws), Some(proj)) => match lookup_ws_proj_no_create(&state, ws, proj).await {+ Ok(ids) => Some(ids),+ Err(e) => return e,+ },+ _ => None,+ };+ match state.reader.audit_contamination(scope).await {+ Ok(report) => (+ StatusCode::OK,+ Json(serde_json::to_value(&report).unwrap_or_else(|_| serde_json::json!({}))),+ ),+ Err(e) => (+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(serde_json::json!({ "error": e.to_string() })),+ ),+ }+}+/// JSON response body for `GET /admin/status`. The CLI's `status`/// subcommand renders this either as JSON (`--json`) or as a small/// human-friendly text block.@@ -5661,6 +5702,7 @@ mod tests {}),),("GET", "/admin/status", serde_json::Value::Null),+ ("GET", "/admin/audit-contamination", serde_json::Value::Null),("GET", "/admin/search?q=test", serde_json::Value::Null),("GET",diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 6f0b712c..93ea36a8 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -35,7 +35,8 @@ pub use decay::{DecayParams, retention_score};pub use error::{StoreError, StoreResult};pub use ops::{EmbeddingWrite, MoveSummary, PurgeSummary, ReorgSummary};pub use reader::{- ActivityWindow, AutoImproveCandidateSession, BriefingPage, BriefingSnapshot, DecayCandidate,+ ActivityWindow, AutoImproveCandidateSession, BriefingPage, BriefingSnapshot,+ ContaminationFinding, ContaminationReport, ContaminationSummary, DecayCandidate,DerivedIndexStatus, EmbeddingTripleCount, HealthDetail, HealthPage, ObservationHit, PageAuthor,PageHit, PageHitWithMeta, PageLinks, PageMeta, PageSummary, ProjectSummary, ReaderPool,ReindexTargetStatus, RelatedPage, ScopeRow, StatusCounts, StoredEmbedding, StoredPageBody,diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex c2d247f7..85b9e2db 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -124,6 +124,55 @@ pub struct StatusCounts {pub observations: u64,}+/// One likely cross-project contamination finding from+/// [`ReaderPool::audit_contamination`]. Advisory only — it flags STRUCTURAL+/// mislandings (an entity whose identity disagrees with the bucket it landed+/// in). Purely semantic contamination (a page whose topic belongs elsewhere+/// with no cwd/session anomaly) is not detectable structurally.+#[derive(Debug, Clone, Serialize)]+pub struct ContaminationFinding {+ /// Heuristic that fired: `session_wrong_bucket` | `observation_session_drift`.+ pub check: &'static str,+ /// Confidence — `high` for both structural checks.+ pub confidence: &'static str,+ /// Entity kind: `session` | `observation`.+ pub entity_kind: &'static str,+ /// Entity id (lowercase hex of the 16-byte UUID).+ pub entity_id: String,+ /// Workspace name the entity actually landed in.+ pub landed_workspace: String,+ /// Project name the entity actually landed in.+ pub landed_project: String,+ /// Project the evidence says it belongs to (resolved cwd project for CHECK A,+ /// the owning session's project for CHECK B).+ #[serde(skip_serializing_if = "Option::is_none")]+ pub expected_project: Option<String>,+ /// Originating session cwd — the prefix-resolution evidence (CHECK A).+ #[serde(skip_serializing_if = "Option::is_none")]+ pub cwd: Option<String>,+ /// Owning session id (lowercase hex) — the drift evidence (CHECK B).+ #[serde(skip_serializing_if = "Option::is_none")]+ pub session_id: Option<String>,+}++/// Per-check counts for an [`ReaderPool::audit_contamination`] run.+#[derive(Debug, Clone, Default, Serialize)]+pub struct ContaminationSummary {+ /// Sessions whose cwd prefix-resolves to a different project (CHECK A).+ pub sessions_misbucketed: usize,+ /// Observations whose project disagrees with their session (CHECK B).+ pub observations_drifted: usize,+}++/// Result of [`ReaderPool::audit_contamination`] — advisory, never mutates.+#[derive(Debug, Clone, Default, Serialize)]+pub struct ContaminationReport {+ /// Per-check counts.+ pub summary: ContaminationSummary,+ /// Individual findings.+ pub findings: Vec<ContaminationFinding>,+}+/// Counts that must all be zero before `ai-memory reindex` rebuilds the/// derived SQLite store from wiki files.#[derive(Debug, Clone, Default, Serialize)]@@ -3279,6 +3328,161 @@ impl ReaderPool {.await}+ /// Structural cross-project contamination audit (cheap, SQL-only, no LLM).+ ///+ /// Two HIGH-precision heuristics:+ /// - **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).+ /// - **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.+ ///+ /// Detects only contamination with a STRUCTURAL trace; purely semantic+ /// mislandings (topic-level, no cwd/session anomaly) are not detectable.+ /// `scope` restricts findings to the given landed `(workspace, project)`.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn audit_contamination(+ &self,+ scope: Option<(WorkspaceId, ProjectId)>,+ ) -> StoreResult<ContaminationReport> {+ let scoped = scope.is_some();+ let scope_params: Vec<Value> = match &scope {+ Some((ws, proj)) => vec![+ Value::Blob(ws.as_bytes().to_vec()),+ Value::Blob(proj.as_bytes().to_vec()),+ ],+ None => Vec::new(),+ };++ // Phase 1 (one connection): CHECK B findings + the candidate session+ // list that Phase 2 resolves with the runtime cwd resolver.+ type Candidate = (String, WorkspaceId, ProjectId, String, String, String);+ let sp_b = scope_params.clone();+ let (mut findings, candidates): (Vec<ContaminationFinding>, Vec<Candidate>) = self+ .with_conn(move |conn| {+ let mut findings: Vec<ContaminationFinding> = Vec::new();++ // CHECK B — observation drifted from its owning session.+ let mut b_sql = String::from(+ "SELECT lower(hex(o.id)), lower(hex(o.session_id)), wl.name, pl.name, pe.name \+ FROM observations o \+ JOIN sessions s ON s.id = o.session_id \+ JOIN workspaces wl ON wl.id = o.workspace_id \+ JOIN projects pl ON pl.id = o.project_id \+ JOIN projects pe ON pe.id = s.project_id \+ WHERE o.project_id != s.project_id",+ );+ if scoped {+ b_sql.push_str(" AND o.workspace_id = ? AND o.project_id = ?");+ }+ {+ let mut stmt = conn.prepare(&b_sql)?;+ let rows = stmt.query_map(params_from_iter(sp_b.iter()), |row| {+ Ok((+ row.get::<_, String>(0)?,+ row.get::<_, String>(1)?,+ row.get::<_, String>(2)?,+ row.get::<_, String>(3)?,+ row.get::<_, String>(4)?,+ ))+ })?;+ for r in rows {+ let (id, sess, lws, lproj, eproj) = r?;+ findings.push(ContaminationFinding {+ check: "observation_session_drift",+ confidence: "high",+ entity_kind: "observation",+ entity_id: id,+ landed_workspace: lws,+ landed_project: lproj,+ expected_project: Some(eproj),+ cwd: None,+ session_id: Some(sess),+ });+ }+ }++ // Candidate sessions (cwd present) — resolved outside the conn.+ let mut s_sql = String::from(+ "SELECT lower(hex(s.id)), s.workspace_id, s.project_id, wl.name, pl.name, s.cwd \+ FROM sessions s \+ JOIN workspaces wl ON wl.id = s.workspace_id \+ JOIN projects pl ON pl.id = s.project_id \+ WHERE s.cwd IS NOT NULL",+ );+ if scoped {+ s_sql.push_str(" AND s.workspace_id = ? AND s.project_id = ?");+ }+ let mut candidates: Vec<Candidate> = Vec::new();+ {+ let mut stmt = conn.prepare(&s_sql)?;+ let rows = stmt.query_map(params_from_iter(scope_params.iter()), |row| {+ Ok((+ row.get::<_, String>(0)?,+ row.get::<_, Vec<u8>>(1)?,+ row.get::<_, Vec<u8>>(2)?,+ row.get::<_, String>(3)?,+ row.get::<_, String>(4)?,+ row.get::<_, String>(5)?,+ ))+ })?;+ for r in rows {+ let (id, ws_b, proj_b, lws, lproj, cwd) = r?;+ candidates.push((+ id,+ WorkspaceId::from_slice(&ws_b)?,+ ProjectId::from_slice(&proj_b)?,+ lws,+ lproj,+ cwd,+ ));+ }+ }++ Ok((findings, candidates))+ })+ .await?;++ // Phase 2 — CHECK A: resolve each session's cwd with the runtime+ // resolver 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+ {+ findings.push(ContaminationFinding {+ check: "session_wrong_bucket",+ confidence: "high",+ entity_kind: "session",+ entity_id: id,+ landed_workspace: landed_ws_name,+ landed_project: landed_proj_name,+ expected_project: Some(resolved_name),+ cwd: Some(cwd),+ session_id: None,+ });+ }+ }++ let summary = ContaminationSummary {+ sessions_misbucketed: findings+ .iter()+ .filter(|f| f.check == "session_wrong_bucket")+ .count(),+ observations_drifted: findings+ .iter()+ .filter(|f| f.check == "observation_session_drift")+ .count(),+ };+ Ok(ContaminationReport { summary, findings })+ }+/// Return aggregate counts for the `status` view.////// # Errorsdiff --git a/crates/ai-memory-store/tests/audit_contamination.rs b/crates/ai-memory-store/tests/audit_contamination.rsnew file mode 100644index 00000000..f5297521--- /dev/null+++ b/crates/ai-memory-store/tests/audit_contamination.rs@@ -0,0 +1,162 @@+//! Integration tests for the structural cross-project contamination audit.+//!+//! Seeds a DB with both contamination signatures (a session whose cwd resolves+//! to a different project, and an observation whose project disagrees with its+//! session) plus clean controls, then asserts `audit_contamination` flags+//! exactly the contaminated rows.++use ai_memory_core::{ProjectId, WorkspaceId};+use ai_memory_store::Store;+use rusqlite::{Connection, params};++fn id(n: u8) -> [u8; 16] {+ let mut b = [0u8; 16];+ b[15] = n;+ b+}++/// Seed the fixture directly via SQL so we control every (ws, proj, cwd) — the+/// writer would derive some of these and we need the deliberate mismatch.+fn seed(db_path: &std::path::Path) {+ let conn = Connection::open(db_path).unwrap();+ let now = 1_700_000_000_000_i64;+ let (ws, a, b) = (id(1), id(2), id(3));+ let (sess_wrong, sess_clean) = (id(10), id(11));+ let (obs_drift, obs_clean) = (id(20), id(21));++ conn.execute(+ "INSERT INTO workspaces (id, name, created_at) VALUES (?1, ?2, ?3)",+ params![&ws[..], "auditws", now],+ )+ .unwrap();+ for (pid, name, rp) in [(&a, "proj-a", "/w/a"), (&b, "proj-b", "/w/b")] {+ conn.execute(+ "INSERT INTO projects (id, workspace_id, name, repo_path, created_at) \+ VALUES (?1, ?2, ?3, ?4, ?5)",+ params![&pid[..], &ws[..], name, rp, now],+ )+ .unwrap();+ }+ // CHECK A: session landed in proj-a but its cwd is under proj-b's repo_path.+ conn.execute(+ "INSERT INTO sessions (id, workspace_id, project_id, agent_kind, cwd, started_at) \+ VALUES (?1, ?2, ?3, 'claude-code', ?4, ?5)",+ params![&sess_wrong[..], &ws[..], &a[..], "/w/b/sub", now],+ )+ .unwrap();+ // Clean: session in proj-b, cwd under proj-b → resolves to its own bucket.+ conn.execute(+ "INSERT INTO sessions (id, workspace_id, project_id, agent_kind, cwd, started_at) \+ VALUES (?1, ?2, ?3, 'claude-code', ?4, ?5)",+ params![&sess_clean[..], &ws[..], &b[..], "/w/b", now],+ )+ .unwrap();+ // CHECK B: observation tagged proj-b but its session (sess_wrong) is in proj-a.+ conn.execute(+ "INSERT INTO observations \+ (id, session_id, workspace_id, project_id, kind, title, body, created_at) \+ VALUES (?1, ?2, ?3, ?4, 'note', 't', 'x', ?5)",+ params![&obs_drift[..], &sess_wrong[..], &ws[..], &b[..], now],+ )+ .unwrap();+ // Clean: observation in proj-a, session in proj-a → no drift.+ conn.execute(+ "INSERT INTO observations \+ (id, session_id, workspace_id, project_id, kind, title, body, created_at) \+ VALUES (?1, ?2, ?3, ?4, 'note', 't', 'x', ?5)",+ params![&obs_clean[..], &sess_wrong[..], &ws[..], &a[..], now],+ )+ .unwrap();+}++#[tokio::test]+async fn audit_flags_wrong_bucket_session_and_drifted_observation() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ seed(store.db_path());++ let report = store.reader.audit_contamination(None).await.unwrap();++ assert_eq!(+ report.summary.sessions_misbucketed, 1,+ "exactly the wrong-bucket session is flagged (clean one is not)"+ );+ assert_eq!(+ report.summary.observations_drifted, 1,+ "exactly the drifted observation is flagged (clean one is not)"+ );++ let a = report+ .findings+ .iter()+ .find(|f| f.check == "session_wrong_bucket")+ .expect("CHECK A finding present");+ assert_eq!(a.confidence, "high");+ assert_eq!(a.entity_kind, "session");+ assert_eq!(a.landed_project, "proj-a");+ assert_eq!(a.expected_project.as_deref(), Some("proj-b"));+ assert_eq!(a.cwd.as_deref(), Some("/w/b/sub"));++ let b = report+ .findings+ .iter()+ .find(|f| f.check == "observation_session_drift")+ .expect("CHECK B finding present");+ assert_eq!(b.entity_kind, "observation");+ assert_eq!(b.landed_project, "proj-b");+ assert_eq!(b.expected_project.as_deref(), Some("proj-a"));+}++#[tokio::test]+async fn audit_clean_db_returns_no_findings() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ // A single clean project + session in its own bucket.+ let conn = Connection::open(store.db_path()).unwrap();+ let now = 1_700_000_000_000_i64;+ let (ws, p, s) = (id(1), id(2), id(3));+ conn.execute(+ "INSERT INTO workspaces (id, name, created_at) VALUES (?1, 'w', ?2)",+ params![&ws[..], now],+ )+ .unwrap();+ conn.execute(+ "INSERT INTO projects (id, workspace_id, name, repo_path, created_at) \+ VALUES (?1, ?2, 'p', '/w/p', ?3)",+ params![&p[..], &ws[..], now],+ )+ .unwrap();+ conn.execute(+ "INSERT INTO sessions (id, workspace_id, project_id, agent_kind, cwd, started_at) \+ VALUES (?1, ?2, ?3, 'claude-code', '/w/p', ?4)",+ params![&s[..], &ws[..], &p[..], now],+ )+ .unwrap();+ drop(conn);++ let report = store.reader.audit_contamination(None).await.unwrap();+ assert_eq!(report.summary.sessions_misbucketed, 0);+ assert_eq!(report.summary.observations_drifted, 0);+ assert!(report.findings.is_empty());+}++#[tokio::test]+async fn audit_scope_restricts_to_landed_bucket() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ seed(store.db_path());+ let (ws, a) = (id(1), id(2));++ // Scoped to proj-a: the wrong-bucket session (landed in A) is in scope; the+ // drifted observation (landed in B) is out of scope.+ let scope = Some((+ WorkspaceId::from_slice(&ws).unwrap(),+ ProjectId::from_slice(&a).unwrap(),+ ));+ let report = store.reader.audit_contamination(scope).await.unwrap();+ assert_eq!(report.summary.sessions_misbucketed, 1);+ assert_eq!(+ report.summary.observations_drifted, 0,+ "the drifted obs landed in proj-b, outside the proj-a scope"+ );+}