Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(links): typed relation edges - causes / fixes / contradicts
AkitaOnRails7d6a59665fb5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 095d853f..a1b5ca91 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- Pages can declare typed relation edges in `relations:` frontmatter —+ a closed `causes` / `fixes` / `contradicts` vocabulary riding the+ existing `links.link_type` column (no schema migration). Declared+ `contradicts` edges surface as zero-LLM `contradiction` lint findings+ (including stale declarations whose target no longer resolves), and+ the session-end consolidation prompt may emit relations under the+ same schema-constrained vocabulary. See `docs/typed-edges.md`.- `ai-memory export-okf --project <p> -o <bundle.tar.gz>` and`POST /admin/export-okf` — stream one project's wiki as a validatedOKF v0.2 bundle with a freshly generated index; a non-conformant pagediff --git a/README.md b/README.mdindex 1bab0702..5ab37b53 100644--- a/README.md+++ b/README.md@@ -345,6 +345,7 @@ diagram, crate breakdown, schema notes, and invariants.- [`docs/research-2026-landscape.md`](docs/research-2026-landscape.md) - how the field looks and where we sit in it.- [`docs/ROADMAP-2.0.md`](docs/ROADMAP-2.0.md) - the plan for the 2.0 release, one item at a time.- [`docs/okf.md`](docs/okf.md) - the wiki is natively an Open Knowledge Format (OKF v0.2) bundle; design and field mapping.+- [`docs/typed-edges.md`](docs/typed-edges.md) - typed relation edges (`causes` / `fixes` / `contradicts`) and how lint uses them.- [`docs/MIGRATION-2.0.md`](docs/MIGRATION-2.0.md) - upgrading an existing store to 2.0: the backup-gated automatic migration and how to restore.- [`docs/benchmarks/`](docs/benchmarks/README.md) - published retrieval-quality numbers with provenance, reproducible from the in-repo harness.- [`docs/ROADMAP-2.0.md`](docs/ROADMAP-2.0.md) - the 2.0 plan.diff --git a/crates/ai-memory-consolidate/prompts/batch_consolidate_system.md b/crates/ai-memory-consolidate/prompts/batch_consolidate_system.mdindex 940815f3..a8f8b90e 100644--- a/crates/ai-memory-consolidate/prompts/batch_consolidate_system.md+++ b/crates/ai-memory-consolidate/prompts/batch_consolidate_system.md@@ -104,6 +104,14 @@ session summary when the session yields reusable insight;otherwise return only the session page. Schema and requiredkeys are enumerated in the user message.+A page may declare typed edges to EXISTING pages via `relations`+(keys limited to `causes`, `fixes`, `contradicts`; values are wiki+paths). Declare one only when the session's evidence states the+relationship plainly — e.g. a fix landed for a documented gotcha+(`fixes`), or new evidence disagrees with a stored decision+(`contradicts`). Omit the key entirely in the normal case; never+invent relations to fill it.+## Output format- Reply with ONE JSON object, nothing else. NO prose preamble,diff --git a/crates/ai-memory-consolidate/src/consolidator.rs b/crates/ai-memory-consolidate/src/consolidator.rsindex 379687f8..ce815eac 100644--- a/crates/ai-memory-consolidate/src/consolidator.rs+++ b/crates/ai-memory-consolidate/src/consolidator.rs@@ -1259,6 +1259,30 @@ fn build_frontmatter(if let Some(summary) = usable_summary(page.summary.as_deref(), &page.title) {map.insert("summary".into(), serde_json::Value::String(summary));}+ // Typed edges (2.0 item 3): only vocabulary keys survive — an LLM+ // inventing `blames:` must not mint a new edge kind. The wiki write+ // boundary parses this frontmatter into typed links.+ let relations: serde_json::Map<String, serde_json::Value> = page+ .relations+ .iter()+ .filter(|(key, targets)| {+ ai_memory_core::Relation::parse(key).is_some() && !targets.is_empty()+ })+ .map(|(key, targets)| {+ (+ key.clone(),+ serde_json::Value::Array(+ targets+ .iter()+ .map(|t| serde_json::Value::String(t.clone()))+ .collect(),+ ),+ )+ })+ .collect();+ if !relations.is_empty() {+ map.insert("relations".into(), serde_json::Value::Object(relations));+ }map.insert("consolidated".into(), serde_json::Value::Bool(true));serde_json::Value::Object(map)}@@ -1738,6 +1762,7 @@ mod tests {body_markdown: "Body prose.".into(),tags: Vec::new(),summary: Some("Bounded the queue so backpressure is testable.".into()),+ relations: std::collections::BTreeMap::new(),};let session_id = SessionId::new();let frontmatter = build_frontmatter(&page, session_id, AgentKind::Codex);@@ -1775,6 +1800,41 @@ mod tests {assert!(SYSTEM_PROMPT.contains("ONE line of plain prose"));}+ /// Only the closed vocabulary survives into `relations:` frontmatter+ /// — an LLM inventing `blames:` must not mint a new edge kind.+ #[test]+ fn relations_frontmatter_keeps_only_the_vocabulary() {+ let mut page = ConsolidatedPage {+ title: "T".into(),+ body_markdown: "b".into(),+ tags: vec![],+ summary: None,+ relations: std::collections::BTreeMap::new(),+ };+ page.relations+ .insert("fixes".into(), vec!["gotchas/g.md".into()]);+ page.relations+ .insert("blames".into(), vec!["notes/x.md".into()]);+ page.relations.insert("causes".into(), vec![]);+ let fm = build_frontmatter(&page, SessionId::new(), AgentKind::ClaudeCode);+ let relations = fm["relations"].as_object().unwrap();+ assert_eq!(relations.len(), 1, "{relations:?}");+ assert_eq!(relations["fixes"][0], "gotchas/g.md");+ }++ #[test]+ fn pages_without_relations_omit_the_key() {+ let page = ConsolidatedPage {+ title: "T".into(),+ body_markdown: "b".into(),+ tags: vec![],+ summary: None,+ relations: std::collections::BTreeMap::new(),+ };+ let fm = build_frontmatter(&page, SessionId::new(), AgentKind::ClaudeCode);+ assert!(fm.get("relations").is_none());+ }+#[test]fn slot_update_defaults_to_state_frontmatter() {let update = crate::types::ConsolidatedPageUpdate {diff --git a/crates/ai-memory-consolidate/src/lint.rs b/crates/ai-memory-consolidate/src/lint.rsindex 94e0634d..9a194247 100644--- a/crates/ai-memory-consolidate/src/lint.rs+++ b/crates/ai-memory-consolidate/src/lint.rs@@ -210,6 +210,32 @@ pub async fn run_lint(});}+ // Declared contradictions (typed `contradicts` edges, 2.0 item 3):+ // an author or the consolidator explicitly said two pages disagree —+ // the highest-signal zero-LLM contradiction finding possible.+ for edge in reader.contradiction_edges(workspace_id, project_id).await? {+ let message = if edge.resolved {+ format!(+ "Page {} declares it contradicts {} — reconcile them or \+ supersede the outdated one",+ edge.from_path, edge.to_path,+ )+ } else {+ format!(+ "Page {} declares it contradicts {}, which does not resolve \+ to a page (deleted or renamed) — the declaration is stale",+ edge.from_path, edge.to_path,+ )+ };+ findings.push(LintFinding {+ kind: "contradiction".into(),+ severity: "warning".into(),+ message,+ pages: vec![edge.from_path, edge.to_path],+ detail: None,+ });+ }+// Explicit `stale` / `wrong` feedback (memory_feedback). An agent or// user asserting a page is outdated or incorrect is the highest-signal// finding the zero-LLM path can produce — it came from a human/agentdiff --git a/crates/ai-memory-consolidate/src/types.rs b/crates/ai-memory-consolidate/src/types.rsindex 9d21d817..f8a87c9e 100644--- a/crates/ai-memory-consolidate/src/types.rs+++ b/crates/ai-memory-consolidate/src/types.rs@@ -22,6 +22,13 @@ pub struct ConsolidatedPage {/// outputs still deserialise.#[serde(default)]pub summary: Option<String>,+ /// Typed edges to existing pages (2.0 item 3). Keys are the closed+ /// vocabulary `causes` / `fixes` / `contradicts`; values are wiki+ /// paths of the target pages. Only declare a relation when the+ /// session's evidence states it plainly — an empty map is the+ /// normal case. Unknown keys are dropped at the write boundary.+ #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]+ pub relations: std::collections::BTreeMap<String, Vec<String>>,}/// Semantic classification of one consolidated page. Surfaced intodiff --git a/crates/ai-memory-consolidate/tests/typed_edges.rs b/crates/ai-memory-consolidate/tests/typed_edges.rsnew file mode 100644index 00000000..7efc1313--- /dev/null+++ b/crates/ai-memory-consolidate/tests/typed_edges.rs@@ -0,0 +1,182 @@+//! Typed relation edges, end to end (2.0 item 3, docs/okf.md):+//! a page declaring `relations:` frontmatter produces typed rows in the+//! links table through the real wiki write path, and a declared+//! `contradicts` edge surfaces as a rule-based lint finding with no LLM+//! involved.++use ai_memory_consolidate::{LintOptions, run_lint};+use ai_memory_core::{PagePath, ProjectId, Tier, WorkspaceId};+use ai_memory_store::Store;+use ai_memory_wiki::{Wiki, WritePageRequest};+use tempfile::TempDir;++async fn scope(store: &Store) -> (WorkspaceId, ProjectId) {+ let ws = store.writer.get_or_create_workspace("w").await.unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "p", None)+ .await+ .unwrap();+ (ws, proj)+}++fn req(+ ws: WorkspaceId,+ proj: ProjectId,+ path: &str,+ body: &str,+ fm: serde_json::Value,+) -> WritePageRequest {+ WritePageRequest {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new(path).unwrap(),+ frontmatter: fm,+ body: body.into(),+ tier: Tier::Semantic,+ pinned: false,+ title: None,+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),+ }+}++#[tokio::test]+async fn declared_relations_become_typed_link_rows() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj) = scope(&store).await;+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();++ wiki.write_page(req(+ ws,+ proj,+ "gotchas/linker.md",+ "the gotcha",+ serde_json::json!({}),+ ))+ .await+ .unwrap();+ wiki.write_page(req(+ ws,+ proj,+ "notes/fix-log.md",+ "how it was fixed, see [[gotchas/linker.md]]",+ serde_json::json!({"relations": {"fixes": ["gotchas/linker.md"]}}),+ ))+ .await+ .unwrap();++ // Raw rows: one typed edge and one plain reference to the same+ // target coexist (link_type joins the key).+ let db = rusqlite::Connection::open(tmp.path().join("db").join("memory.sqlite")).unwrap();+ let rows: Vec<(String, i64)> = db+ .prepare(+ "SELECT link_type, to_page_id IS NOT NULL FROM links \+ WHERE to_path = 'gotchas/linker.md' ORDER BY link_type",+ )+ .unwrap()+ .query_map([], |r| Ok((r.get(0)?, r.get(1)?)))+ .unwrap()+ .collect::<Result<_, _>>()+ .unwrap();+ assert_eq!(+ rows,+ vec![("fixes".to_string(), 1), ("references".to_string(), 1)],+ "typed edge and plain reference must both exist, both resolved"+ );+}++#[tokio::test]+async fn a_declared_contradiction_is_a_lint_finding_without_an_llm() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj) = scope(&store).await;+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();++ wiki.write_page(req(+ ws,+ proj,+ "decisions/0001.md",+ "we deploy on Fridays",+ serde_json::json!({}),+ ))+ .await+ .unwrap();+ wiki.write_page(req(+ ws,+ proj,+ "notes/new-evidence.md",+ "we stopped deploying on Fridays",+ serde_json::json!({"relations": {"contradicts": ["decisions/0001.md"]}}),+ ))+ .await+ .unwrap();++ let report = run_lint(+ &store.reader,+ &wiki,+ None,+ ws,+ proj,+ LintOptions {+ dry_run: true,+ use_llm: false,+ decay_lambda: 0.02,+ },+ )+ .await+ .unwrap();++ let finding = report+ .findings+ .iter()+ .find(|f| f.kind == "contradiction")+ .expect("declared contradicts must produce a lint finding");+ assert!(finding.message.contains("notes/new-evidence.md"));+ assert!(finding.message.contains("decisions/0001.md"));+ assert_eq!(+ finding.pages,+ vec!["notes/new-evidence.md", "decisions/0001.md"]+ );+}++#[tokio::test]+async fn a_contradiction_to_a_deleted_page_reports_the_stale_declaration() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj) = scope(&store).await;+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();++ wiki.write_page(req(+ ws,+ proj,+ "notes/orphan-claim.md",+ "contradicts something gone",+ serde_json::json!({"relations": {"contradicts": ["decisions/vanished.md"]}}),+ ))+ .await+ .unwrap();++ let report = run_lint(+ &store.reader,+ &wiki,+ None,+ ws,+ proj,+ LintOptions {+ dry_run: true,+ use_llm: false,+ decay_lambda: 0.02,+ },+ )+ .await+ .unwrap();+ let finding = report+ .findings+ .iter()+ .find(|f| f.kind == "contradiction")+ .expect("unresolved contradicts still lints");+ assert!(finding.message.contains("does not resolve"));+}diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rsindex 56c20a56..0d87814a 100644--- a/crates/ai-memory-core/src/lib.rs+++ b/crates/ai-memory-core/src/lib.rs@@ -61,7 +61,7 @@ pub use ids::{};pub use observation::{NewObservation, NewSession, Observation, ObservationKind};pub use page::{- FeedbackKind, LinkTarget, MAX_ENTITIES_PER_PAGE, MAX_ENTITY_LEN, NewPage, Page, Tier,+ FeedbackKind, LinkTarget, MAX_ENTITIES_PER_PAGE, MAX_ENTITY_LEN, NewPage, Page, Relation, Tier,normalize_entities, normalize_entity,};pub use routing_snippet::{MARKER_END, MARKER_START, SNIPPET_BODY, find_marker_line, full_block};diff --git a/crates/ai-memory-core/src/page.rs b/crates/ai-memory-core/src/page.rsindex 2e6d080f..ded6fe04 100644--- a/crates/ai-memory-core/src/page.rs+++ b/crates/ai-memory-core/src/page.rs@@ -167,6 +167,50 @@ pub struct LinkTarget {pub project: Option<String>,/// Wiki path within the target project (root-relative).pub path: PagePath,+ /// Typed relation carried by this edge; `None` = a plain reference.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub relation: Option<Relation>,+}++/// The closed typed-edge vocabulary (2.0 item 3). Declared in a page's+/// `relations:` frontmatter; anything outside this set stays a plain+/// reference. Closed on purpose: a free-text relation column becomes an+/// unqueryable folksonomy, and `contradicts` feeds the lint pass.+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum Relation {+ /// The source page describes a cause of the target.+ Causes,+ /// The source page fixes the problem the target describes.+ Fixes,+ /// The source page contradicts the target (lint surfaces these).+ Contradicts,+}++impl Relation {+ /// Stored `links.link_type` value.+ #[must_use]+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Causes => "causes",+ Self::Fixes => "fixes",+ Self::Contradicts => "contradicts",+ }+ }++ /// Parse a frontmatter `relations:` key. Unknown names → `None`.+ #[must_use]+ pub fn parse(s: &str) -> Option<Self> {+ match s {+ "causes" => Some(Self::Causes),+ "fixes" => Some(Self::Fixes),+ "contradicts" => Some(Self::Contradicts),+ _ => None,+ }+ }++ /// Every relation, for schema/docs enumeration.+ pub const ALL: [Self; 3] = [Self::Causes, Self::Fixes, Self::Contradicts];}impl LinkTarget {@@ -177,6 +221,7 @@ impl LinkTarget {workspace: None,project: None,path,+ relation: None,}}diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex f25f51be..8c6ab7d5 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -57,13 +57,14 @@ pub use ops::{pub use reader::{ActivityWindow, AgentSessionCount, AuditEvent, AuditLogFilter, AutoImproveCandidateSession,BriefPageBody, BriefingPage, BriefingSnapshot, ClientActivity, ContaminationFinding,- ContaminationReport, ContaminationSummary, DecayCandidate, DecayTombstone, DerivedIndexStatus,- EmbeddingTripleCount, FeedbackFinding, GraphVia, HealthDetail, HealthPage, ObservationHit,- ObservationOrder, ObservationPage, ObservationPageResult, ObservationRecord, OpenSession,- PageAuthor, PageHit, PageHitWithMeta, PageLinks, PageMeta, PageSummary, ProjectSummary,- ReaderPool, ReindexTargetStatus, RelatedPage, RrfContributions, ScopeRow, SearchExplain,- SessionDependentRows, SessionEndDisposition, SessionSummary, StatusCounts, StorageStatus,- StoredEmbedding, StoredPageBody, WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,+ ContaminationReport, ContaminationSummary, ContradictionEdge, DecayCandidate, DecayTombstone,+ DerivedIndexStatus, EmbeddingTripleCount, FeedbackFinding, GraphVia, HealthDetail, HealthPage,+ ObservationHit, ObservationOrder, ObservationPage, ObservationPageResult, ObservationRecord,+ OpenSession, PageAuthor, PageHit, PageHitWithMeta, PageLinks, PageMeta, PageSummary,+ ProjectSummary, ReaderPool, ReindexTargetStatus, RelatedPage, RrfContributions, ScopeRow,+ SearchExplain, SessionDependentRows, SessionEndDisposition, SessionSummary, StatusCounts,+ StorageStatus, StoredEmbedding, StoredPageBody, WorkspaceScopeRow, WorkspaceSummary,+ f32_vec_to_bytes,};pub use scope::{ResolvedScope, ScopeName, ScopeResolutionError, ScopeResolver, WORKSPACE_PROJECT_PAIR_REQUIRED,@@ -1882,11 +1883,13 @@ mod tests {workspace: None,project: Some("infra".into()),path: PagePath::new("runbooks/02.md").unwrap(),+ relation: None,},LinkTarget {workspace: None,project: Some("nope".into()),path: PagePath::new("ghost.md").unwrap(),+ relation: None,},];store.writer.upsert_page(dep).await.unwrap();diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex b9b07f06..2aa3a9e9 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -898,10 +898,14 @@ fn replace_links_in_tx(let mut seen = BTreeSet::new();for link in &page.links {+ // The relation joins the dedupe key (and the table's PK): a+ // typed edge and a plain reference to the same target are two+ // different rows, mirroring `link_type` in the schema.let key = (link.workspace.clone(),link.project.clone(),link.path.as_str().to_string(),+ link.relation,);if !seen.insert(key) {continue;@@ -911,13 +915,15 @@ fn replace_links_in_tx(tx.execute("INSERT INTO links \(from_page_id, to_page_id, to_workspace, to_project, to_path, link_type) \- VALUES (?1, ?2, ?3, ?4, ?5, 'references')",+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)",params![from_page_id.as_bytes(),to_page_blob,link.workspace,link.project,link.path.as_str(),+ link.relation+ .map_or("references", ai_memory_core::Relation::as_str),],)?;}@@ -6208,6 +6214,7 @@ pub(crate) mod tests {workspace: None,project: Some("infra".into()),path: PagePath::new("runbooks/02.md").unwrap(),+ relation: None,}];let source_id = upsert_page(&mut conn, &source).unwrap();diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 44df4433..0b3541df 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -1261,6 +1261,21 @@ pub struct CrossProjectEdge {pub to_path: String,}+/// One typed `contradicts` edge between two latest pages, surfaced as a+/// lint finding (2.0 item 3): the declaration IS the signal — no LLM+/// needed to notice that two pages disagree once an author or the+/// consolidator said so.+#[derive(Debug, Clone, Serialize)]+pub struct ContradictionEdge {+ /// Wiki path of the page declaring the contradiction.+ pub from_path: String,+ /// Wiki path of the contradicted page (as declared; the target may+ /// be unresolved, in which case `resolved` is false).+ pub to_path: String,+ /// Whether the target currently resolves to a latest page.+ pub resolved: bool,+}+/// An unresolved cross-project link — a declared dependency on another/// project's page that does not resolve. Surfaced by `memory_lint`.#[derive(Debug, Clone, Serialize)]@@ -5586,6 +5601,41 @@ impl ReaderPool {.await}+ /// Typed `contradicts` edges declared by latest pages of one project+ /// (docs/okf.md relations vocabulary). Each row feeds one rule-based+ /// lint finding.+ ///+ /// # Errors+ /// Propagates SQL errors from the read pool.+ pub async fn contradiction_edges(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ ) -> StoreResult<Vec<ContradictionEdge>> {+ self.with_conn(move |conn| {+ let mut stmt = conn.prepare(+ "SELECT fp.path, l.to_path, l.to_page_id IS NOT NULL AS resolved FROM links l JOIN pages fp ON fp.id = l.from_page_id AND fp.workspace_id = ?1 AND fp.project_id = ?2 AND fp.is_latest = 1 WHERE l.link_type = 'contradicts' ORDER BY fp.path, l.to_path",+ )?;+ let rows = stmt.query_map(+ params![workspace_id.as_bytes(), project_id.as_bytes()],+ |row| {+ let resolved: i64 = row.get(2)?;+ Ok(ContradictionEdge {+ from_path: row.get(0)?,+ to_path: row.get(1)?,+ resolved: resolved != 0,+ })+ },+ )?;+ let mut out = Vec::new();+ for r in rows {+ out.push(r?);+ }+ Ok(out)+ })+ .await+ }+/// Resolved cross-project edges (links whose endpoints are in different/// projects). When `scope` is `Some((ws, proj))`, only edges that touch/// that project (as source or target) are returned; `None` returns thediff --git a/crates/ai-memory-wiki/src/markdown.rs b/crates/ai-memory-wiki/src/markdown.rsindex 6fc5fa18..4c1c2cd2 100644--- a/crates/ai-memory-wiki/src/markdown.rs+++ b/crates/ai-memory-wiki/src/markdown.rs@@ -138,11 +138,89 @@ pub fn extract_links(body: &str, page_path: &PagePath) -> Vec<LinkTarget> {workspace,project,path,+ relation: None,})}).collect()}+/// Body wikilinks plus typed `relations:` frontmatter edges — the full+/// outgoing link set every page-write path stores. One entry point so a+/// new writer cannot forget the typed half.+pub fn extract_all_links(+ frontmatter: &serde_json::Value,+ body: &str,+ page_path: &PagePath,+) -> Vec<LinkTarget> {+ let mut links = extract_links(body, page_path);+ links.extend(extract_relation_links(frontmatter));+ links+}++/// Extract typed relation edges from a page's `relations:` frontmatter+/// (2.0 item 3):+///+/// ```yaml+/// relations:+/// fixes: ["gotchas/build.md"]+/// contradicts: ["decisions/0007.md", "other-project:notes/x.md"]+/// ```+///+/// Values use the same target grammar as wikilinks (`path`,+/// `project:path`, `workspace/project:path`). Keys outside the closed+/// [`Relation`] vocabulary are skipped (a typo must not silently mint a+/// new edge kind); malformed paths are skipped likewise.+pub fn extract_relation_links(frontmatter: &serde_json::Value) -> Vec<LinkTarget> {+ let Some(relations) = frontmatter.get("relations").and_then(|v| v.as_object()) else {+ return Vec::new();+ };+ let mut out = Vec::new();+ for (key, targets) in relations {+ let Some(relation) = ai_memory_core::Relation::parse(key) else {+ tracing::warn!(key, "unknown relation key in frontmatter; skipping");+ continue;+ };+ let Some(list) = targets.as_array() else {+ continue;+ };+ for target in list.iter().filter_map(|v| v.as_str()) {+ let (workspace, project, raw_path) = match target.split_once(':') {+ None => (None, None, target),+ Some((scope, path)) => match scope.split_once('/') {+ None => (None, Some(scope.to_string()), path),+ Some((ws, proj)) => (Some(ws.to_string()), Some(proj.to_string()), path),+ },+ };+ // Same terminal normalization as wikilinks: extension-less+ // targets gain `.md`; anything with a non-md extension is+ // not a page and is skipped.+ let raw_path = raw_path.trim();+ let last = raw_path.rsplit_once('/').map_or(raw_path, |(_, s)| s);+ let normalized = if last.contains('.') {+ if raw_path.ends_with(".md") {+ raw_path.to_string()+ } else {+ tracing::warn!(target, "relation target is not a page; skipping");+ continue;+ }+ } else {+ format!("{raw_path}.md")+ };+ let Ok(path) = PagePath::new(normalized) else {+ tracing::warn!(target, "unparseable relation target; skipping");+ continue;+ };+ out.push(LinkTarget {+ workspace,+ project,+ path,+ relation: Some(relation),+ });+ }+ }+ out+}+/// Split an optional `[workspace/]project:` scope qualifier off the front/// of a wikilink target. Returns `(workspace, project, path_part)`. URL and/// scheme-prefixed targets carry no scope (the `:` belongs to the scheme);@@ -307,6 +385,74 @@ mod tests {PagePath::new("notes/here.md").unwrap()}+ #[test]+ fn relations_frontmatter_becomes_typed_edges() {+ let fm = serde_json::json!({+ "relations": {+ "fixes": ["gotchas/build.md", "concepts/writer"],+ "contradicts": ["other-proj:decisions/0007.md"],+ "causes": ["ws/proj:notes/x.md"],+ }+ });+ let mut links = extract_relation_links(&fm);+ links.sort();+ assert_eq!(links.len(), 4);+ let fixes: Vec<_> = links+ .iter()+ .filter(|l| l.relation == Some(ai_memory_core::Relation::Fixes))+ .collect();+ assert_eq!(fixes.len(), 2);+ // extension-less target gains .md+ assert!(+ fixes+ .iter()+ .any(|l| l.path.as_str() == "concepts/writer.md")+ );+ let contra = links+ .iter()+ .find(|l| l.relation == Some(ai_memory_core::Relation::Contradicts))+ .unwrap();+ assert_eq!(contra.project.as_deref(), Some("other-proj"));+ let causes = links+ .iter()+ .find(|l| l.relation == Some(ai_memory_core::Relation::Causes))+ .unwrap();+ assert_eq!(causes.workspace.as_deref(), Some("ws"));+ assert_eq!(causes.project.as_deref(), Some("proj"));+ }++ #[test]+ fn unknown_relation_keys_and_bad_targets_are_skipped() {+ let fm = serde_json::json!({+ "relations": {+ "blames": ["notes/a.md"],+ "fixes": ["../escape.md", "notes/data.json", "notes/ok.md"],+ }+ });+ let links = extract_relation_links(&fm);+ assert_eq!(links.len(), 1, "{links:?}");+ assert_eq!(links[0].path.as_str(), "notes/ok.md");+ }++ #[test]+ fn pages_without_relations_extract_nothing() {+ assert!(extract_relation_links(&serde_json::json!({})).is_empty());+ assert!(extract_relation_links(&serde_json::json!({"relations": "not a map"})).is_empty());+ }++ #[test]+ fn extract_all_links_merges_body_and_frontmatter() {+ let fm = serde_json::json!({"relations": {"fixes": ["gotchas/g.md"]}});+ let links = extract_all_links(&fm, "see [[notes/n.md]]", &page());+ assert_eq!(links.len(), 2);+ assert!(links.iter().any(|l| l.relation.is_none()));+ assert!(+ links+ .iter()+ .any(|l| l.relation == Some(ai_memory_core::Relation::Fixes))+ );+ }+#[test]fn extract_links_bare_wikilink_is_local() {let links = extract_links("see [[decisions/0001.md]] and [[other]]", &page());diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rsindex 1099f1ec..907a77c3 100644--- a/crates/ai-memory-wiki/src/wiki.rs+++ b/crates/ai-memory-wiki/src/wiki.rs@@ -19,7 +19,7 @@ use crate::admission::{AdmissionChain, AdmissionContext, AdmissionOp};use crate::atomic;use crate::error::{WikiError, WikiResult};use crate::git::{Checkpoint, GitAdapter};-use crate::markdown::{Markdown, derive_title, emit, extract_links, parse};+use crate::markdown::{Markdown, derive_title, emit, parse};use crate::watcher::is_pending_path;/// Summary of a [`Wiki::reindex_all`] run.@@ -544,7 +544,7 @@ impl Wiki {})?;let md = parse(&raw)?;let title = derive_title(&md.frontmatter, &md.body, &path);- let links = extract_links(&md.body, &path);+ let links = crate::markdown::extract_all_links(&md.frontmatter, &md.body, &path);let meta = derive_index_metadata(&path, &md.frontmatter)?;let _guard = self.mutation_lock.read().await;@@ -1202,7 +1202,8 @@ impl Wiki {markdown.body = self.sanitizer.scrub(&markdown.body);scrub_frontmatter_strings(&mut markdown.frontmatter, &self.sanitizer);let title = self.sanitizer.scrub(&detail.summary.title);- let links = extract_links(&markdown.body, &path);+ let links =+ crate::markdown::extract_all_links(&markdown.frontmatter, &markdown.body, &path);let expires_at = parse_expires_at(&path, &markdown.frontmatter)?;let entities = parse_entities(&path, &markdown.frontmatter)?;let emitted = emit(&markdown)?;@@ -1312,7 +1313,7 @@ impl Wiki {}let md = self.read_page(workspace_id, project_id, &path)?;let title = derive_title(&md.frontmatter, &md.body, &path);- let links = extract_links(&md.body, &path);+ let links = crate::markdown::extract_all_links(&md.frontmatter, &md.body, &path);// Markdown is the source of truth: preserve explicit tier/pinned// metadata on reindex instead of forcing every page back to semantic.let meta = derive_index_metadata(&path, &md.frontmatter)?;@@ -1610,7 +1611,11 @@ impl Wiki {tier: req.tier,frontmatter_json: req.frontmatter.clone(),pinned: req.pinned,- links: extract_links(&req.body, &req.path),+ links: crate::markdown::extract_all_links(+ &req.frontmatter,+ &req.body,+ &req.path,+ ),author_id: req.author_id,expires_at: parse_expires_at(&req.path, &req.frontmatter)?,entities: parse_entities(&req.path, &req.frontmatter)?,@@ -1754,7 +1759,8 @@ impl Wiki {.clone().map(|t| self.sanitizer.scrub(&t)).unwrap_or_else(|| derive_title(&markdown.frontmatter, &markdown.body, &path));- let links = extract_links(&markdown.body, &path);+ let links =+ crate::markdown::extract_all_links(&markdown.frontmatter, &markdown.body, &path);let expires_at = parse_expires_at(&path, &markdown.frontmatter)?;let entities = parse_entities(&path, &markdown.frontmatter)?;diff --git a/docs/typed-edges.md b/docs/typed-edges.mdnew file mode 100644index 00000000..a5b0b6bc--- /dev/null+++ b/docs/typed-edges.md@@ -0,0 +1,58 @@+# Typed relation edges++Pages can declare *typed* edges to other pages — not just "these are+related" but *how*:++```yaml+---+title: Fixed the linker OOM+relations:+ fixes: ["gotchas/linker-oom.md"]+ contradicts: ["decisions/0007-static-linking.md"]+---+```++## The vocabulary (closed)++| relation | meaning |+|---|---|+| `causes` | this page describes a cause of the target |+| `fixes` | this page fixes the problem the target describes |+| `contradicts` | this page disagrees with the target |++The set is deliberately closed: a free-text relation column turns into+an unqueryable folksonomy. Keys outside the vocabulary are skipped at+the write boundary (with a warning) — a typo cannot mint a new edge+kind. Targets use the same grammar as wikilinks: `path`,+`project:path`, or `workspace/project:path`; extension-less targets+gain `.md`.++## What typed edges do++- **`contradicts` feeds lint.** A declared contradiction is the+ highest-signal zero-LLM finding possible — someone (or the+ consolidator) explicitly said two pages disagree. `memory_lint`+ reports each edge as a `contradiction` finding until the pages are+ reconciled, including the case where the target no longer resolves+ (a stale declaration).+- **They participate in the retrieval graph** as ordinary edges. No+ relation-specific ranking weight is applied — the LongMemEval+ harness showed no basis for one yet; the data is stored so a future+ change can be measured rather than guessed.+- **Backlinks stay clean.** A typed edge and a plain `[[wikilink]]`+ to the same target coexist as distinct rows (`links.link_type`), but+ page-link listings deduplicate.++## Who writes them++- **You**, in any page's frontmatter (the wiki files are plain+ markdown — edit and `reindex`, or let the watcher pick it up).+- **The consolidator**, sparingly: the session-end prompt may declare+ a relation when the session's evidence states it plainly (a fix+ landed for a documented gotcha; new evidence contradicts a stored+ decision). The output is JSON-schema constrained and filtered to the+ vocabulary again at the write boundary.++Storage detail: edges ride the existing `links.link_type` column+(default `references`), so this needed no schema migration and old+stores need no rewrite.