Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(lint): A5 zero-LLM contradiction detection via cosine-similarity band
AkitaOnRails4bf20d28ccbb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8fe30fda..9dae0ccc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- Zero-LLM contradiction detection surfaced through `memory_lint`+ (design-memory-aging.md bucket A5): the lint pass now flags likely-conflicting+ pages by cosine-similarity band. Cold knowledge pages (semantic / procedural)+ whose already-stored embeddings sit in the **0.4–0.75 cosine-similarity band** —+ "same topic, but not a near-duplicate", the shape of a likely contradiction+ (a pair ≥ 0.75 is A3 dedup territory; < 0.4 is unrelated) — get an advisory+ `contradiction` lint finding naming both pages, with timestamp-based+ resolution advice (the newer page supersedes on a timestamp basis; reconcile).+ It is fully **zero generative LLM**: it reads only existing embeddings and+ cosine (invariant #13), so with no embedder configured — or no embeddings for+ the configured `(provider, model, dim)` triple — it is a clean no-op, not an+ error, and never a provider call. It runs on the user-invoked `memory_lint`+ (MCP and admin) and is **advisory-only and non-destructive**: it emits a+ finding and never deletes, edits, or supersedes a page (invariant #16), and+ never persists an edge (the `links` table's `contradicts` edges are+ body-derived and rewritten on every page write, so a programmatic edge would+ be silently wiped) — hence **no new migration**, and no new MCP tool (still+ 23). The scan is bounded: one embeddings load over the already-bounded cold+ set, capped page and finding counts, deterministic ordering (invariant #2)+ (#813).- Cold-cluster dedup of near-duplicate episodic pages (design-memory-aging.mdbucket A3): the forget-sweep can now cluster near-duplicate cold episodicpages by embedding (cosine-distance DBSCAN with an adaptive k-distance eps,diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex a9d91472..4145b94e 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -1983,6 +1983,10 @@ async fn run_scheduled_lint_tick(dry_run: false,use_llm: false,decay_lambda,+ // The automatic scheduled lint stays rule-based: the A5+ // contradiction detector is on for the user-invoked+ // `memory_lint` / admin lint, not the background sweep.+ embedding: None,},).awaitdiff --git a/crates/ai-memory-consolidate/src/lint.rs b/crates/ai-memory-consolidate/src/lint.rsindex 76815245..7671c8a2 100644--- a/crates/ai-memory-consolidate/src/lint.rs+++ b/crates/ai-memory-consolidate/src/lint.rs@@ -17,7 +17,9 @@/// at compile time from `prompts/lint_system.md`.const LINT_SYSTEM_PROMPT: &str = include_str!("../prompts/lint_system.md");-use ai_memory_core::{PagePath, ProjectId, Tier, WorkspaceId};+use crate::EmbeddingCoord;+use crate::cold_cluster::cosine_distance;+use ai_memory_core::{PageId, PagePath, ProjectId, Tier, WorkspaceId};use ai_memory_llm::{ChatMessage, ChatRequest, LlmProvider, Role, complete_structured};use ai_memory_store::{DecayCandidate, ReaderPool};use ai_memory_wiki::{AdmissionContext, AdmissionOp, Wiki, WritePageRequest};@@ -129,7 +131,9 @@ pub fn stale_days_for(lambda: f64) -> f64 {/// A struct rather than three positional parameters: `false, false` at a/// call site said nothing about which switch was which, and the threshold/// input has to travel alongside them.-#[derive(Debug, Clone, Copy)]+///+/// Not `Copy`: the optional embedding coordinate carries owned strings.+#[derive(Debug, Clone)]pub struct LintOptions {/// When `true`, no `_lint/report.md` page is written (and no legacy/// dated reports are pruned).@@ -140,6 +144,14 @@ pub struct LintOptions {/// The operator's `[decay] lambda`. The stale threshold is derived from/// it — see [`stale_days_for`].pub decay_lambda: f64,+ /// The running embedder's `(provider, model, dim)` triple, or `None` when+ /// no embedder is configured. It drives the zero-LLM contradiction+ /// detector (A5): the detector loads already-stored vectors under this+ /// triple and flags pages in the 0.4–0.75 cosine-similarity band. `None`+ /// makes that pass a clean no-op. User-invoked lint paths supply it; the+ /// automatic scheduled lint passes `None` — detection is on for the+ /// user-invoked operation, not the background sweep.+ pub embedding: Option<EmbeddingCoord>,}impl Default for LintOptions {@@ -148,6 +160,7 @@ impl Default for LintOptions {dry_run: false,use_llm: true,decay_lambda: 0.02,+ embedding: None,}}}@@ -177,6 +190,7 @@ pub async fn run_lint(dry_run,use_llm,decay_lambda,+ embedding,} = options;let candidates = reader.decay_candidates(workspace_id, project_id).await?;let mut findings = rule_based_findings(&candidates, stale_days_for(decay_lambda));@@ -269,6 +283,32 @@ pub async fn run_lint(});}+ // Zero-LLM detected contradictions (A5): pages whose embeddings sit in the+ // 0.4–0.75 cosine-similarity band are "same topic, not a near-duplicate" —+ // the shape of a likely conflict. This DETECTS contradictions beside the+ // declared-`contradicts`-edge finding above, using only stored vectors and+ // cosine (invariant #13 — no provider call). It emits advisory findings+ // (invariant #16) and never persists an edge.+ //+ // Why no persistence / no migration: a `contradicts` edge would live in the+ // `links` table, but `links` rows are BODY-DERIVED — `replace_links_in_tx`+ // deletes and re-inserts every page's links from its `[[...]]` body on each+ // write. A programmatically inserted edge would be silently wiped on the+ // next rewrite of that page, a fragile, misleading persistence path. So A5+ // is a lint-time detector: no links writer, no schema change.+ match detected_contradiction_pass(+ reader,+ workspace_id,+ project_id,+ &candidates,+ embedding.as_ref(),+ )+ .await+ {+ Ok(mut extra) => findings.append(&mut extra),+ Err(e) => warn!(error = %e, "lint detected-contradiction pass failed"),+ }+if use_llm && let Some(provider) = llm {match contradiction_pass(provider.clone(),@@ -411,6 +451,165 @@ fn rule_based_findings(candidates: &[DecayCandidate], stale_days: f64) -> Vec<Liout}+// ── A5: zero-LLM contradiction detection (cosine-similarity band) ──────────++/// Lower edge (inclusive) of the likely-contradiction cosine-similarity band.+/// Below this two pages are simply unrelated (different topics).+const CONTRADICTION_SIM_LOW: f32 = 0.4;+/// Upper edge (exclusive) of the band. At or above this two pages are a+/// near-duplicate — A3 cold-cluster dedup's territory, not a contradiction.+/// The band (mcp-memory-service's heuristic) is "same topic, not a duplicate":+/// the shape of two pages that discuss the same thing while likely disagreeing.+const CONTRADICTION_SIM_HIGH: f32 = 0.75;+/// Cap on cold pages fed to the pairwise scan. The scan is O(N²) cosine ops, so+/// this bounds it hard on the already-bounded cold set (invariant #2 — one+/// embeddings load, no per-page N+1).+const CONTRADICTION_MAX_PAGES: usize = 60;+/// Cap on contradiction findings emitted, so a pathological corpus that lands+/// many pairs in the band cannot flood the advisory report.+const CONTRADICTION_MAX_FINDINGS: usize = 25;++/// Whether a cosine similarity falls in the likely-contradiction band.+#[must_use]+fn in_contradiction_band(similarity: f32) -> bool {+ (CONTRADICTION_SIM_LOW..CONTRADICTION_SIM_HIGH).contains(&similarity)+}++/// One page eligible for the band scan: its path, last-updated microseconds+/// (for the newer-wins advisory), and its stored embedding.+struct BandCandidate {+ path: String,+ updated_at_us: i64,+ vector: Vec<f32>,+}++/// Pure pairwise band scan over a bounded, deterministically-ordered set of+/// pages. Emits an advisory `contradiction` finding for each pair whose cosine+/// similarity is in `[0.4, 0.75)`, capped at `max_findings`.+///+/// Timestamp resolution is ADVISORY only: the message says the newer page+/// supersedes on a timestamp basis, but the lint never deletes or edits+/// anything (invariant #16). Pairs are visited in `(i, j)` order so the same+/// input always yields the same capped subset.+fn detected_contradiction_findings(+ pages: &[BandCandidate],+ max_findings: usize,+) -> Vec<LintFinding> {+ let mut findings = Vec::new();+ 'outer: for i in 0..pages.len() {+ for j in (i + 1)..pages.len() {+ let similarity = 1.0 - cosine_distance(&pages[i].vector, &pages[j].vector);+ if !in_contradiction_band(similarity) {+ continue;+ }+ let (a, b) = (&pages[i], &pages[j]);+ // Newer = larger updated_at_us. Ties resolve to `a` (the lexically+ // earlier path, since the caller sorts by path) for determinism.+ let (newer, older) = if a.updated_at_us >= b.updated_at_us {+ (a, b)+ } else {+ (b, a)+ };+ let newer_ts = Timestamp::from_microsecond(newer.updated_at_us)+ .map(|t| t.to_zoned(TimeZone::UTC).strftime("%Y-%m-%d").to_string())+ .unwrap_or_else(|_| "unknown".into());+ findings.push(LintFinding {+ kind: "contradiction".into(),+ severity: "info".into(),+ message: format!(+ "Pages {} and {} are similar (cosine {similarity:.2}) but not a \+ duplicate — likely conflicting. The newer page ({}, updated \+ {newer_ts}) supersedes {} on a timestamp basis; reconcile them.",+ a.path, b.path, newer.path, older.path,+ ),+ pages: vec![a.path.clone(), b.path.clone()],+ detail: None,+ });+ if findings.len() >= max_findings {+ break 'outer;+ }+ }+ }+ findings+}++/// Load stored embeddings for the bounded cold knowledge-page set and flag+/// pairs in the contradiction band.+///+/// A clean no-op (empty, never an error) when no embedder is configured+/// (`embedding` is `None`) or no stored vectors match the cold set — the+/// detector reads only already-stored embeddings and never calls a provider+/// (invariant #13).+async fn detected_contradiction_pass(+ reader: &ReaderPool,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ candidates: &[DecayCandidate],+ embedding: Option<&EmbeddingCoord>,+) -> Result<Vec<LintFinding>, LintError> {+ let Some(coord) = embedding else {+ return Ok(Vec::new());+ };++ // Bound the set BEFORE loading vectors. Contradictions matter on the+ // knowledge pages a user compounds (semantic / procedural), not session+ // logs or the lint report itself. "Coldest first" = fewest accesses, then+ // oldest update, so a large corpus is trimmed to its most-stale knowledge.+ let mut eligible: Vec<&DecayCandidate> = candidates+ .iter()+ .filter(|c| matches!(c.tier, Tier::Semantic | Tier::Procedural))+ .filter(|c| !c.path.as_str().starts_with("_lint/"))+ .collect();+ eligible.sort_by(|a, b| {+ a.access_count+ .cmp(&b.access_count)+ .then(a.updated_at_us.cmp(&b.updated_at_us))+ .then_with(|| a.path.as_str().cmp(b.path.as_str()))+ });+ eligible.truncate(CONTRADICTION_MAX_PAGES);+ if eligible.len() < 2 {+ return Ok(Vec::new());+ }++ let by_id: std::collections::HashMap<PageId, &DecayCandidate> =+ eligible.iter().map(|c| (c.id, *c)).collect();++ // One bounded embeddings load (invariant #2). Mismatched-triple rows are+ // skipped inside the store; a missing embedder yields no rows.+ let embeddings = reader+ .load_embeddings(+ workspace_id,+ project_id,+ coord.provider.clone(),+ coord.model.clone(),+ coord.dim,+ )+ .await?;++ let mut pages: Vec<BandCandidate> = Vec::new();+ for e in &embeddings {+ if let Some(c) = by_id.get(&e.id) {+ pages.push(BandCandidate {+ path: c.path.as_str().to_string(),+ updated_at_us: c.updated_at_us,+ vector: e.vector.clone(),+ });+ }+ }+ // No stored vectors for the cold set ⇒ clean no-op.+ if pages.len() < 2 {+ return Ok(Vec::new());+ }+ // Deterministic input order regardless of the DB row order load_embeddings+ // returned, so findings and the cap are reproducible.+ pages.sort_by(|a, b| a.path.cmp(&b.path));++ Ok(detected_contradiction_findings(+ &pages,+ CONTRADICTION_MAX_FINDINGS,+ ))+}+async fn contradiction_pass(provider: std::sync::Arc<dyn LlmProvider>,wiki: &Wiki,@@ -904,4 +1103,128 @@ mod tests {"rule-based stale finding must be present regardless of use_llm flag",);}++ // ── A5 zero-LLM detected contradictions (cosine-similarity band) ──────++ /// A pair whose similarity sits in the 0.4–0.75 band is a likely+ /// contradiction; a near-duplicate (≥0.75, A3's territory) and an+ /// unrelated pair (<0.4) are not.+ #[test]+ fn contradiction_band_predicate() {+ assert!(in_contradiction_band(0.6), "0.6 is the band's centre");+ assert!(in_contradiction_band(0.4), "0.4 is the inclusive low edge");+ assert!(+ !in_contradiction_band(0.75),+ "0.75 is a near-duplicate (A3 dedup), not a contradiction"+ );+ assert!(+ !in_contradiction_band(0.85),+ "0.85 is a near-duplicate, not a contradiction"+ );+ assert!(!in_contradiction_band(0.2), "0.2 is unrelated");+ assert!(!in_contradiction_band(1.0), "identical is a duplicate");+ }++ // Unit-length 2-D vectors: cosine similarity between them equals the dot+ // product, so a chosen second component pins the similarity exactly.+ fn band(path: &str, updated_at_us: i64, vector: Vec<f32>) -> BandCandidate {+ BandCandidate {+ path: path.to_string(),+ updated_at_us,+ vector,+ }+ }++ /// Two pages at cosine 0.6 ⇒ exactly one contradiction finding naming both,+ /// with newer-wins advice pointing at the more recently updated page.+ #[test]+ fn band_scan_flags_a_mid_band_pair_newer_wins() {+ let pages = vec![+ band("concepts/old-claim.md", 1_000, vec![1.0, 0.0]),+ // dot([1,0],[0.6,0.8]) = 0.6 — squarely in the band.+ band("concepts/new-claim.md", 9_000, vec![0.6, 0.8]),+ ];+ let findings = detected_contradiction_findings(&pages, CONTRADICTION_MAX_FINDINGS);+ assert_eq!(+ findings.len(),+ 1,+ "one band pair ⇒ one finding: {findings:?}"+ );+ let f = &findings[0];+ assert_eq!(f.kind, "contradiction");+ assert_eq!(f.severity, "info");+ assert_eq!(f.pages.len(), 2);+ assert!(f.pages.contains(&"concepts/old-claim.md".to_string()));+ assert!(f.pages.contains(&"concepts/new-claim.md".to_string()));+ // Newer (larger updated_at_us) supersedes on a timestamp basis.+ assert!(+ f.message.contains("concepts/new-claim.md") && f.message.contains("supersedes"),+ "newer page wins advisory: {}",+ f.message+ );+ }++ /// A near-duplicate pair (cosine ≈ 0.98) is A3 dedup territory, never a+ /// contradiction finding.+ #[test]+ fn band_scan_ignores_near_duplicates() {+ let pages = vec![+ band("concepts/a.md", 1, vec![1.0, 0.0]),+ // dot ≈ 0.98 — a near-duplicate, above the band.+ band("concepts/b.md", 2, vec![0.98, 0.199]),+ ];+ let findings = detected_contradiction_findings(&pages, CONTRADICTION_MAX_FINDINGS);+ assert!(+ findings.is_empty(),+ "near-duplicate must not be flagged as a contradiction: {findings:?}"+ );+ }++ /// An unrelated pair (cosine ≈ 0.2) is below the band, never flagged.+ #[test]+ fn band_scan_ignores_unrelated_pairs() {+ let pages = vec![+ band("concepts/a.md", 1, vec![1.0, 0.0]),+ band("concepts/b.md", 2, vec![0.2, 0.9798]),+ ];+ let findings = detected_contradiction_findings(&pages, CONTRADICTION_MAX_FINDINGS);+ assert!(+ findings.is_empty(),+ "unrelated pair not flagged: {findings:?}"+ );+ }++ /// Empty and single-page inputs produce nothing (no pair to compare).+ #[test]+ fn band_scan_handles_empty_and_single() {+ assert!(detected_contradiction_findings(&[], CONTRADICTION_MAX_FINDINGS).is_empty());+ let one = vec![band("concepts/a.md", 1, vec![1.0, 0.0])];+ assert!(detected_contradiction_findings(&one, CONTRADICTION_MAX_FINDINGS).is_empty());+ }++ /// The findings cap is honoured: two in-band pairs, cap of 1 ⇒ one finding.+ #[test]+ fn band_scan_respects_the_findings_cap() {+ // Three unit vectors at 0°, 55°, 110°. Adjacent pairs differ by 55°+ // (cos 55° ≈ 0.57 — in band); the 0°/110° pair differs by 110°+ // (cos ≈ -0.34 — out of band). So exactly two candidate findings.+ let a = (0.0_f64).to_radians();+ let b = (55.0_f64).to_radians();+ let c = (110.0_f64).to_radians();+ let pages = vec![+ band("concepts/a.md", 1, vec![a.cos() as f32, a.sin() as f32]),+ band("concepts/b.md", 2, vec![b.cos() as f32, b.sin() as f32]),+ band("concepts/c.md", 3, vec![c.cos() as f32, c.sin() as f32]),+ ];+ assert_eq!(+ detected_contradiction_findings(&pages, CONTRADICTION_MAX_FINDINGS).len(),+ 2,+ "two adjacent pairs are in band"+ );+ assert_eq!(+ detected_contradiction_findings(&pages, 1).len(),+ 1,+ "a cap of 1 truncates the two candidate pairs"+ );+ }}diff --git a/crates/ai-memory-consolidate/tests/suite/contradiction_lint.rs b/crates/ai-memory-consolidate/tests/suite/contradiction_lint.rsnew file mode 100644index 00000000..db7fcde6--- /dev/null+++ b/crates/ai-memory-consolidate/tests/suite/contradiction_lint.rs@@ -0,0 +1,277 @@+//! A5 zero-LLM contradiction detection, end to end through a real Store + Wiki.+//!+//! Invariants guarded (docs/design-memory-aging.md §A5):+//!+//! 1. **Band pair ⇒ finding.** Two cold pages whose embeddings sit in the+//! 0.4–0.75 cosine-similarity band produce one advisory `contradiction`+//! finding naming both paths, with newer-wins advice.+//! 2. **Near-duplicate ⇒ NOT a contradiction.** A pair at ≥0.75 is A3+//! dedup territory, never flagged here.+//! 3. **No embeddings ⇒ clean no-op** (never an error, never a provider call).+//! 4. **Advisory only (#16).** The detector writes no supersession and deletes+//! nothing; the source pages are untouched.+//!+//! Embeddings are seeded directly into `page_embeddings` with controlled unit+//! vectors so the cosine similarity between two pages is exact and the band+//! boundaries are testable — the synthetic bag-of-words embedder cannot pin a+//! similarity to a chosen value.++use ai_memory_consolidate::{EmbeddingCoord, LintOptions, run_lint};+use ai_memory_core::{ActorContext, PageId, PagePath, ProjectId, Tier, WorkspaceId};+use ai_memory_store::{Store, f32_vec_to_bytes};+use ai_memory_wiki::{Wiki, WritePageRequest};+use rusqlite::params;+use tempfile::TempDir;++const PROVIDER: &str = "test-embedder";+const MODEL: &str = "unit-2d";+const DIM: u32 = 2;++struct Fixture {+ tmp: TempDir,+ store: Store,+ wiki: Wiki,+ ws: WorkspaceId,+ proj: ProjectId,+}++async fn seed_fixture() -> Fixture {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone())+ .unwrap()+ .with_store_reader(store.reader.clone());+ Fixture {+ tmp,+ store,+ wiki,+ ws,+ proj,+ }+}++/// Write a semantic page (the tier the contradiction detector considers).+async fn write_semantic(fx: &Fixture, path: &str, body: &str) -> PageId {+ fx.wiki+ .write_page(WritePageRequest {+ workspace_id: fx.ws,+ project_id: fx.proj,+ path: PagePath::new(path).unwrap(),+ frontmatter: serde_json::json!({"title": path}),+ body: body.to_string(),+ tier: Tier::Semantic,+ pinned: false,+ title: Some(path.to_string()),+ admission_ctx: None,+ author_id: None,+ actor: ActorContext::anonymous(),+ evidence: Vec::new(),+ })+ .await+ .unwrap()+}++/// Insert a controlled embedding row for a page under our test triple.+fn seed_embedding(fx: &Fixture, page_id: PageId, vector: &[f32]) {+ let conn = rusqlite::Connection::open(fx.tmp.path().join("db/memory.sqlite")).unwrap();+ conn.pragma_update(None, "busy_timeout", 5_000).unwrap();+ conn.execute(+ "INSERT INTO page_embeddings (page_id, vector, provider, model, dim, created_at) \+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)",+ params![+ page_id.as_bytes(),+ f32_vec_to_bytes(vector),+ PROVIDER,+ MODEL,+ DIM,+ jiff::Timestamp::now().as_microsecond(),+ ],+ )+ .unwrap();+}++fn coord() -> Option<EmbeddingCoord> {+ Some(EmbeddingCoord {+ provider: PROVIDER.into(),+ model: MODEL.into(),+ dim: DIM,+ })+}++fn latest_page_count(fx: &Fixture) -> i64 {+ let conn = rusqlite::Connection::open(fx.tmp.path().join("db/memory.sqlite")).unwrap();+ conn.query_row(+ "SELECT COUNT(*) FROM pages \+ WHERE workspace_id = ?1 AND project_id = ?2 AND is_latest = 1",+ params![fx.ws.as_bytes(), fx.proj.as_bytes()],+ |row| row.get(0),+ )+ .unwrap()+}++fn options(embedding: Option<EmbeddingCoord>) -> LintOptions {+ LintOptions {+ // dry_run so the pass emits findings without writing a report page,+ // keeping the "nothing was mutated" assertion clean.+ dry_run: true,+ // No LLM in these tests — this is the zero-LLM detector.+ use_llm: false,+ decay_lambda: 0.02,+ embedding,+ }+}++/// Two cold pages in the band ⇒ one advisory contradiction finding naming+/// both, with newer-wins advice; nothing is deleted or rewritten.+#[tokio::test]+async fn band_pair_yields_advisory_contradiction() {+ let fx = seed_fixture().await;+ let old = write_semantic(&fx, "concepts/old-claim.md", "The retry budget is 3.").await;+ let new = write_semantic(&fx, "concepts/new-claim.md", "The retry budget is 5.").await;+ // dot([1,0],[0.6,0.8]) = 0.6 — squarely in the 0.4–0.75 band.+ seed_embedding(&fx, old, &[1.0, 0.0]);+ seed_embedding(&fx, new, &[0.6, 0.8]);+ // Make `new` the more recently updated page so it wins the timestamp advice.+ {+ let conn = rusqlite::Connection::open(fx.tmp.path().join("db/memory.sqlite")).unwrap();+ conn.execute(+ "UPDATE pages SET updated_at = updated_at + 1000000 \+ WHERE workspace_id = ?1 AND project_id = ?2 AND path = ?3 AND is_latest = 1",+ params![+ fx.ws.as_bytes(),+ fx.proj.as_bytes(),+ "concepts/new-claim.md"+ ],+ )+ .unwrap();+ }++ let before = latest_page_count(&fx);+ let report = run_lint(+ &fx.store.reader,+ &fx.wiki,+ None,+ fx.ws,+ fx.proj,+ options(coord()),+ )+ .await+ .unwrap();++ let contradictions: Vec<_> = report+ .findings+ .iter()+ .filter(|f| f.kind == "contradiction")+ .collect();+ assert_eq!(+ contradictions.len(),+ 1,+ "one band pair ⇒ one contradiction finding: {:?}",+ report.findings+ );+ let f = contradictions[0];+ assert_eq!(f.severity, "info", "detected contradictions are advisory");+ assert!(f.pages.contains(&"concepts/old-claim.md".to_string()));+ assert!(f.pages.contains(&"concepts/new-claim.md".to_string()));+ assert!(+ f.message.contains("concepts/new-claim.md") && f.message.contains("supersedes"),+ "newer page wins on a timestamp basis: {}",+ f.message+ );++ // Advisory (#16): nothing deleted or superseded.+ assert_eq!(+ latest_page_count(&fx),+ before,+ "the detector must not add, delete, or supersede any page"+ );+}++/// A near-duplicate pair (cosine ≈ 0.98) is A3's dedup job, not a+/// contradiction — the detector must stay silent.+#[tokio::test]+async fn near_duplicate_is_not_a_contradiction() {+ let fx = seed_fixture().await;+ let a = write_semantic(&fx, "concepts/a.md", "alpha").await;+ let b = write_semantic(&fx, "concepts/b.md", "beta").await;+ seed_embedding(&fx, a, &[1.0, 0.0]);+ // dot ≈ 0.98 — above the band.+ seed_embedding(&fx, b, &[0.98, 0.199]);++ let report = run_lint(+ &fx.store.reader,+ &fx.wiki,+ None,+ fx.ws,+ fx.proj,+ options(coord()),+ )+ .await+ .unwrap();++ assert!(+ !report.findings.iter().any(|f| f.kind == "contradiction"),+ "a near-duplicate must not be flagged as a contradiction: {:?}",+ report.findings+ );+}++/// No embeddings for the configured triple ⇒ the detector is a clean no-op+/// (not an error, no provider call). Also covers `embedding: None`.+#[tokio::test]+async fn no_embeddings_is_a_clean_no_op() {+ let fx = seed_fixture().await;+ write_semantic(&fx, "concepts/a.md", "The retry budget is 3.").await;+ write_semantic(&fx, "concepts/b.md", "The retry budget is 5.").await;+ // No embedding rows seeded at all.++ // A triple is configured, but there are no matching vectors → no-op.+ let with_coord = run_lint(+ &fx.store.reader,+ &fx.wiki,+ None,+ fx.ws,+ fx.proj,+ options(coord()),+ )+ .await+ .unwrap();+ assert!(+ !with_coord+ .findings+ .iter()+ .any(|f| f.kind == "contradiction"),+ "no embeddings ⇒ no contradiction findings: {:?}",+ with_coord.findings+ );++ // No embedder configured at all (embedding: None) → also a no-op.+ let without_coord = run_lint(+ &fx.store.reader,+ &fx.wiki,+ None,+ fx.ws,+ fx.proj,+ options(None),+ )+ .await+ .unwrap();+ assert!(+ !without_coord+ .findings+ .iter()+ .any(|f| f.kind == "contradiction"),+ "embedding: None ⇒ no contradiction findings: {:?}",+ without_coord.findings+ );+}diff --git a/crates/ai-memory-consolidate/tests/suite/lifecycle.rs b/crates/ai-memory-consolidate/tests/suite/lifecycle.rsindex d82a4c61..11cd582f 100644--- a/crates/ai-memory-consolidate/tests/suite/lifecycle.rs+++ b/crates/ai-memory-consolidate/tests/suite/lifecycle.rs@@ -429,6 +429,7 @@ async fn m8_retention_lifecycle_end_to_end() {dry_run: true,use_llm: true,decay_lambda: ai_memory_store::DecayParams::default().lambda,+ embedding: None,},).awaitdiff --git a/crates/ai-memory-consolidate/tests/suite/mod.rs b/crates/ai-memory-consolidate/tests/suite/mod.rsindex 1cf49841..083ac231 100644--- a/crates/ai-memory-consolidate/tests/suite/mod.rs+++ b/crates/ai-memory-consolidate/tests/suite/mod.rs@@ -6,6 +6,7 @@ mod abstract_backfill;mod access_breadth_sweep;mod cold_cluster_sweep;mod compaction_sweep;+mod contradiction_lint;mod embed_backfill;mod embeddings;mod entropy_experience;diff --git a/crates/ai-memory-consolidate/tests/suite/typed_edges.rs b/crates/ai-memory-consolidate/tests/suite/typed_edges.rsindex 1de37c6b..d48c5f1e 100644--- a/crates/ai-memory-consolidate/tests/suite/typed_edges.rs+++ b/crates/ai-memory-consolidate/tests/suite/typed_edges.rs@@ -125,6 +125,7 @@ async fn a_declared_contradiction_is_a_lint_finding_without_an_llm() {dry_run: true,use_llm: false,decay_lambda: 0.02,+ embedding: None,},).await@@ -170,6 +171,7 @@ async fn a_contradiction_to_a_deleted_page_reports_the_stale_declaration() {dry_run: true,use_llm: false,decay_lambda: 0.02,+ embedding: None,},).await@@ -235,8 +237,9 @@ async fn lint_supersedes_one_report_and_prunes_the_legacy_daily_pile() {dry_run: false,use_llm: false,decay_lambda: 0.02,+ embedding: None,};- let report = run_lint(&store.reader, &wiki, None, ws, proj, opts)+ let report = run_lint(&store.reader, &wiki, None, ws, proj, opts.clone()).await.unwrap();assert!(!report.findings.is_empty(), "the stale page must be found");@@ -257,7 +260,7 @@ async fn lint_supersedes_one_report_and_prunes_the_legacy_daily_pile() {// A second run with findings still present supersedes in place —// still exactly one latest lint page.- run_lint(&store.reader, &wiki, None, ws, proj, opts)+ run_lint(&store.reader, &wiki, None, ws, proj, opts.clone()).await.unwrap();let latest_count: i64 = db@@ -284,8 +287,9 @@ async fn a_clean_pass_removes_the_stale_report() {dry_run: false,use_llm: false,decay_lambda: 0.02,+ embedding: None,};- run_lint(&store.reader, &wiki, None, ws, proj, opts)+ run_lint(&store.reader, &wiki, None, ws, proj, opts.clone()).await.unwrap();@@ -300,7 +304,7 @@ async fn a_clean_pass_removes_the_stale_report() {).await.unwrap();- let report = run_lint(&store.reader, &wiki, None, ws, proj, opts)+ let report = run_lint(&store.reader, &wiki, None, ws, proj, opts.clone()).await.unwrap();assert!(report.findings.is_empty(), "nothing left to find");diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex 5e7b1d2a..fa00baa1 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -3442,6 +3442,16 @@ async fn handle_lint(dry_run: req.dry_run,use_llm: !req.no_llm,decay_lambda: state.decay_params.lambda,+ // Zero-LLM contradiction detection (A5) off the configured+ // embedder's triple; `None` ⇒ clean no-op.+ embedding: state+ .embedder+ .as_ref()+ .map(|e| ai_memory_consolidate::EmbeddingCoord {+ provider: e.provider().to_string(),+ model: e.model().to_string(),+ dim: e.dim(),+ }),},).awaitdiff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex b89384e5..a6dca955 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -3058,6 +3058,17 @@ impl AiMemoryServer {dry_run: args.dry_run.unwrap_or(false),use_llm: !args.no_llm.unwrap_or(false),decay_lambda: self.decay_params.lambda,+ // Drive the zero-LLM contradiction detector (A5) off the+ // configured embedder's triple; `None` when no embedder is+ // configured makes that pass a clean no-op.+ embedding: self+ .embedder+ .as_ref()+ .map(|e| ai_memory_consolidate::EmbeddingCoord {+ provider: e.provider().to_string(),+ model: e.model().to_string(),+ dim: e.dim(),+ }),},).awaitdiff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 4c1c49ff..5de6e7df 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -420,7 +420,7 @@ long-lived entry appearing there is that policy working rather than a fault.| `memory_write_page` | destructive | Write durable wiki knowledge when the user explicitly asks to remember/annotate it. `scope: "global"` writes into the reserved `_global` preferences scope; optional `expires_at` sets an RFC3339 or date-only TTL. || `memory_delete_page` | destructive | Delete a single page by exact `path`. Fires the admission chain (op=delete); idempotent. || `memory_forget_sweep` | destructive | Retention pass: evict cold pages through the wiki layer, purge aged tombstone ancestry, and hard-delete TTL-expired pages. `dry_run=true` for preview. |-| `memory_lint` | destructive | Rule-based + LLM contradiction findings → `wiki/_lint/`. |+| `memory_lint` | destructive | Rule-based + LLM contradiction findings → `wiki/_lint/`. Also runs a **zero-LLM contradiction detector** (design-memory-aging.md A5): cold semantic/procedural pages whose already-stored embeddings sit in the 0.4–0.75 cosine-similarity band ("same topic, not a near-duplicate" — ≥0.75 is A3 dedup, <0.4 unrelated) get an advisory `contradiction` finding with newer-wins timestamp advice. Bounded (one embeddings load over the capped cold set, capped findings, deterministic); a clean no-op with no embedder configured; advisory-only — never deletes/edits/supersedes a page and persists no edge (invariants #13, #16, #2), so no migration. || `memory_install_self_routing` | read-only | Return the canonical slim routing snippet plus managed Agent Skill payloads and target hints for CLAUDE.md / AGENTS.md installs. |`memory_briefing`, `memory_explore`, `memory_write_page`,