Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(consolidate): make relations a fixed object so typed edges work on strict providers (#630)
AkitaOnRailsbab47adb9204
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 158469ae..35ada4d6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,6 +25,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0snapshot.### Fixed+- Typed edges (`relations`) now actually work on OpenAI-family providers+ (#630). `ConsolidatedPage.relations` was an open map+ (`BTreeMap<String, Vec<String>>`), which the strict structured-output+ normalizer closes to `additionalProperties: false` — OpenAI strict mode+ cannot express arbitrary-key maps — so the model was structurally unable to+ emit any `causes`/`fixes`/`contradicts` edge on `openai`, `openai-oauth`,+ `copilot`, `opencode`, or `openai-compat`; the 2.0 typed-edges feature was+ silently dead there. `relations` is now a fixed three-field object+ (`causes`/`fixes`/`contradicts`), which strict mode expresses and which+ serializes to the identical `relations:` frontmatter — no migration, no+ downstream change. A schema guard pins the fixed shape.- `finalize-session --agent hermes` (and `claude-desktop`, `crush`, `other`)is accepted again (#623). These agents are captured and stored, but`finalize-session` reused the install-oriented agent enum — which isdiff --git a/crates/ai-memory-consolidate/prompts/batch_consolidate_system.md b/crates/ai-memory-consolidate/prompts/batch_consolidate_system.mdindex a8f8b90e..abbdc154 100644--- a/crates/ai-memory-consolidate/prompts/batch_consolidate_system.md+++ b/crates/ai-memory-consolidate/prompts/batch_consolidate_system.md@@ -109,7 +109,7 @@ A page may declare typed edges to EXISTING pages via `relations`paths). Declare one only when the session's evidence states therelationship 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+(`contradicts`). Leave the list empty in the normal case; neverinvent relations to fill it.## Output formatdiff --git a/crates/ai-memory-consolidate/src/consolidator.rs b/crates/ai-memory-consolidate/src/consolidator.rsindex b47f94d2..f250cbbe 100644--- a/crates/ai-memory-consolidate/src/consolidator.rs+++ b/crates/ai-memory-consolidate/src/consolidator.rs@@ -1284,13 +1284,10 @@ fn build_frontmatter(// 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)| {+ .non_empty()+ .map(|(relation, targets)| {(- key.clone(),+ relation.as_str().to_string(),serde_json::Value::Array(targets.iter()@@ -1405,6 +1402,7 @@ const SYSTEM_PROMPT: &str = include_str!("../prompts/single_consolidate_system.m#[cfg(test)]mod tests {use super::*;+ use crate::types::Relations;use ai_memory_core::{ObservationId, ObservationKind, ProjectId, SessionId, WorkspaceId};use jiff::Timestamp;@@ -1782,7 +1780,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(),+ relations: Relations::default(),};let session_id = SessionId::new();let frontmatter = build_frontmatter(&page, session_id, AgentKind::Codex);@@ -1820,28 +1818,50 @@ 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.+ /// Only non-empty, closed-vocabulary edges reach `relations:` frontmatter.+ /// The vocabulary is now enforced by the `Relations` type (#630) — there is+ /// no field for an invented `blames:`, so a bogus edge kind is unrepresentable+ /// rather than filtered — and an empty kind is omitted.#[test]- fn relations_frontmatter_keeps_only_the_vocabulary() {- let mut page = ConsolidatedPage {+ fn relations_frontmatter_keeps_only_non_empty_vocabulary() {+ let page = ConsolidatedPage {title: "T".into(),body_markdown: "b".into(),tags: vec![],summary: None,- relations: std::collections::BTreeMap::new(),+ relations: Relations {+ fixes: vec!["gotchas/g.md".into()],+ causes: vec![], // empty -> omitted+ contradicts: vec![],+ },};- 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");}+ /// #630: the `relations` schema must be a FIXED object with named fields,+ /// not an open `additionalProperties` map — otherwise OpenAI strict mode+ /// closes it and the model can never emit an edge on any OpenAI-family+ /// provider. Pin the shape so a revert to `BTreeMap` fails here.+ #[test]+ fn relations_schema_is_a_fixed_object_not_an_open_map() {+ let schema = serde_json::to_value(schemars::schema_for!(Relations)).unwrap();+ let props = schema["properties"]+ .as_object()+ .expect("relations must be a fixed object with named properties, not an open map");+ assert!(props.contains_key("causes"));+ assert!(props.contains_key("fixes"));+ assert!(props.contains_key("contradicts"));+ // An open map renders `additionalProperties` as a *schema object*; a+ // fixed struct renders it as absent or `false`. It must not be a schema.+ assert!(+ !schema["additionalProperties"].is_object(),+ "relations must not carry a schema-valued additionalProperties (open map)"+ );+ }+#[test]fn pages_without_relations_omit_the_key() {let page = ConsolidatedPage {@@ -1849,7 +1869,7 @@ mod tests {body_markdown: "b".into(),tags: vec![],summary: None,- relations: std::collections::BTreeMap::new(),+ relations: Relations::default(),};let fm = build_frontmatter(&page, SessionId::new(), AgentKind::ClaudeCode);assert!(fm.get("relations").is_none());diff --git a/crates/ai-memory-consolidate/src/types.rs b/crates/ai-memory-consolidate/src/types.rsindex f8a87c9e..2e2ce706 100644--- a/crates/ai-memory-consolidate/src/types.rs+++ b/crates/ai-memory-consolidate/src/types.rs@@ -22,13 +22,58 @@ 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>>,+ /// Typed edges to existing pages (2.0 item 3). One field per+ /// closed-vocabulary relation kind; values are wiki paths of the target+ /// pages. Only declare a relation when the session's evidence states it+ /// plainly — all-empty is the normal case.+ #[serde(default)]+ pub relations: Relations,+}++/// Typed edges emitted by consolidation, one field per closed relation+/// kind (`causes` / `fixes` / `contradicts`).+///+/// This is a **fixed-shape object, not an open map**, deliberately (#630).+/// An open `BTreeMap` renders as a JSON-Schema `additionalProperties` map,+/// which OpenAI's strict structured-output mode cannot express — the strict+/// normaliser closes it to `additionalProperties: false`, so the model was+/// structurally unable to ever emit a relation on every OpenAI-family+/// provider (the edges silently never appeared). Three named array fields+/// are strict-expressible and serialise to the same `relations:` frontmatter+/// object the wiki write boundary already parses, so nothing downstream+/// changes.+#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]+pub struct Relations {+ /// Wiki paths this page describes a cause of.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub causes: Vec<String>,+ /// Wiki paths whose described problem this page fixes.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub fixes: Vec<String>,+ /// Wiki paths this page contradicts (the lint pass surfaces these).+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub contradicts: Vec<String>,+}++impl Relations {+ /// Whether no relation of any kind is declared (the normal case).+ #[must_use]+ pub fn is_empty(&self) -> bool {+ self.causes.is_empty() && self.fixes.is_empty() && self.contradicts.is_empty()+ }++ /// The `(relation, targets)` pairs that are non-empty, in vocabulary+ /// order — what the write boundary turns into typed links.+ pub fn non_empty(&self) -> impl Iterator<Item = (ai_memory_core::Relation, &[String])> {+ [+ (ai_memory_core::Relation::Causes, &self.causes),+ (ai_memory_core::Relation::Fixes, &self.fixes),+ (ai_memory_core::Relation::Contradicts, &self.contradicts),+ ]+ .into_iter()+ .filter(|(_, targets)| !targets.is_empty())+ .map(|(rel, targets)| (rel, targets.as_slice()))+ }}/// Semantic classification of one consolidated page. Surfaced into