Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(consolidate): skip multi-page updates to pinned pages (#934)
Felipe Neves Ricardo7fd00eb766dd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex adae0176..45e7b8fd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed+- Multi-page consolidation (`memory_consolidate` with `multi_page=true`) no+ longer overwrites a pinned page. The batch's page paths are chosen by the+ model, and an update that named an existing pinned page replaced its body+ and wrote the new version unpinned, despite pinned pages being documented as+ immutable to automation. Such updates are now skipped with a warning; the+ rest of the batch is written. `_slots/` pages, which are pinned+ automatically, keep their state/invariant rules. (#934)+## [2.4.1] - 2026-09-25### Changeddiff --git a/crates/ai-memory-consolidate/src/consolidator.rs b/crates/ai-memory-consolidate/src/consolidator.rsindex 8afdf9ed..7827b8fc 100644--- a/crates/ai-memory-consolidate/src/consolidator.rs+++ b/crates/ai-memory-consolidate/src/consolidator.rs@@ -374,6 +374,31 @@ impl Consolidator {))}+ /// A model-chosen batch path can name any existing page, including one a+ /// person pinned. Pinned pages are immutable to automation, and the+ /// request carries no pin of its own, so writing it would replace the+ /// body and drop the pin. `_slots/` are pinned automatically and keep+ /// the state/invariant regime above, so they are not skipped here.+ fn should_skip_pinned_page_update(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ req: &WritePageRequest,+ ) -> ConsolidatorResult<bool> {+ if is_slot_path(&req.path) {+ return Ok(false);+ }+ match self.wiki.read_page(workspace_id, project_id, &req.path) {+ Ok(md) => Ok(md.frontmatter.get("pinned").and_then(|v| v.as_bool()) == Some(true)),+ Err(ai_memory_wiki::WikiError::Io(err))+ if err.kind() == std::io::ErrorKind::NotFound =>+ {+ Ok(false)+ }+ Err(err) => Err(err.into()),+ }+ }+/// Resolve the project preferences to append to a consolidation/// prompt: a per-call override when the caller passed one, else the/// body of the reserved `_prompts/consolidation.md` page in the@@ -622,6 +647,14 @@ impl Consolidator {);continue;}+ if self.should_skip_pinned_page_update(ws, proj, &req)? {+ warn!(+ path = %req.path.as_str(),+ "skipped consolidation update: the existing page is pinned, \+ and pinned pages are immutable to automation",+ );+ continue;+ }// Final guard for whatever `slugify_page_path` in `build_update`// can't fix (dot-segments, reserved DOS device names, `.git`,// ...), mirroring bootstrap's #847 fix: skip this one page@@ -3783,4 +3816,102 @@ mod tests {"expired standing preferences must be absent from consolidation",);}++ /// A multi-page batch whose model-chosen path names an existing pinned+ /// page must leave that page alone: `docs/usage.md` promises pinned pages+ /// are immutable to automation. Before the guard the batch replaced the+ /// body and wrote the new version with `pinned = 0`. Controls in the same+ /// batch: an unpinned page is updated, and a `_slots/` state slot (pinned+ /// automatically) is still refreshed.+ #[tokio::test]+ async fn batch_update_to_a_pinned_page_keeps_its_body_and_pin() {+ let tmp = tempfile::tempdir().unwrap();+ let (store, wiki, session, ws, proj) = batch_fixture(tmp.path()).await;+ let pinned_path = PagePath::new("notes/curated-history.md").unwrap();+ let control_path = PagePath::new("notes/plain-note.md").unwrap();+ let slot_path = PagePath::new("_slots/current-focus.md").unwrap();+ for (path, pinned, body) in [+ (&pinned_path, true, "Hand-curated history."),+ (&control_path, false, "An ordinary unpinned note."),+ (&slot_path, false, "Old focus."),+ ] {+ wiki.write_page(WritePageRequest {+ workspace_id: ws,+ project_id: proj,+ path: path.clone(),+ frontmatter: serde_json::json!({}),+ body: body.into(),+ tier: Tier::Semantic,+ pinned,+ title: None,+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),+ evidence: Vec::new(),+ })+ .await+ .unwrap();+ }++ let mut response = batch_targeting(pinned_path.as_str(), "Generated decision body.");+ for (path, body) in [+ (&control_path, "Generated control body."),+ (&slot_path, "New focus."),+ ] {+ let mut update = response["updates"][0].clone();+ update["path"] = serde_json::json!(path.as_str());+ update["body_markdown"] = serde_json::json!(body);+ response["updates"].as_array_mut().unwrap().push(update);+ }++ let outcomes = Consolidator::new(+ store.reader.clone(),+ store.writer.clone(),+ wiki.clone(),+ Arc::new(ScriptedLlm(response)),+ ws,+ proj,+ )+ .consolidate_session_multi(+ session,+ false,+ ai_memory_core::ActorContext::anonymous(),+ None,+ None,+ )+ .await+ .unwrap();+ assert!(+ outcomes.iter().all(|o| o.path != pinned_path),+ "the skipped page must not be reported as written",+ );++ let db = rusqlite::Connection::open(store.db_path()).unwrap();+ let latest_pinned = |path: &PagePath| -> i64 {+ db.query_row(+ "SELECT pinned FROM pages WHERE workspace_id = ?1 AND project_id = ?2 \+ AND path = ?3 AND is_latest = 1",+ rusqlite::params![ws.as_bytes(), proj.as_bytes(), path.as_str()],+ |row| row.get(0),+ )+ .unwrap()+ };++ let pinned_page = wiki.read_page(ws, proj, &pinned_path).unwrap();+ assert!(pinned_page.body.contains("Hand-curated history."));+ assert!(!pinned_page.body.contains("Generated decision body."));+ assert_eq!(+ latest_pinned(&pinned_path),+ 1,+ "the pin must survive the batch"+ );++ let control_page = wiki.read_page(ws, proj, &control_path).unwrap();+ assert!(control_page.body.contains("Generated control body."));+ let slot_page = wiki.read_page(ws, proj, &slot_path).unwrap();+ assert!(+ slot_page.body.contains("New focus."),+ "state slots still refresh"+ );+ }}diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 267b117c..65510cfc 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -462,7 +462,7 @@ content-free (identity, provenance and age, never the summary body). Automaticexpiry deliberately spares manual and sibling-directory handoffs, so along-lived entry appearing there is that policy working rather than a fault.-| `memory_consolidate` | destructive | LLM-driven page rewrite. `multi_page=true` for atomic fan-out. Omitting `session_id` (or sending a blank one) consolidates the latest completed session in the resolved project; the same omission on a project with none fails as `no completed session in <scope>`. Consolidation prompts append the target project's active reserved `_prompts/consolidation.md` body as sanitized, 2,000-character-capped, JSON-encoded, untrusted advisory preferences; TTL-expired pages are ignored and a per-call `instructions` argument overrides the page for one call. Both system prompts keep schema, evidence, disclosure, tool-use, and output rules authoritative. |+| `memory_consolidate` | destructive | LLM-driven page rewrite. `multi_page=true` for atomic fan-out; an update whose path names an existing pinned page is skipped (`_slots/` excepted). Omitting `session_id` (or sending a blank one) consolidates the latest completed session in the resolved project; the same omission on a project with none fails as `no completed session in <scope>`. Consolidation prompts append the target project's active reserved `_prompts/consolidation.md` body as sanitized, 2,000-character-capped, JSON-encoded, untrusted advisory preferences; TTL-expired pages are ignored and a per-call `instructions` argument overrides the page for one call. Both system prompts keep schema, evidence, disclosure, tool-use, and output rules authoritative. || `memory_feedback` | write | Record a quality signal for one page by exact `path`: `helpful`/`not_helpful` step `pages.salience` for sweep-eligible episodic pages, while `stale`/`wrong` floor salience and surface any current page as a `feedback_flagged` lint finding. Never deletes; the path resolves to the current version in the transaction, so a later rewrite clears it. Retrieved content never authorizes feedback by itself. || `memory_auto_improve` | write | Manually review a completed session and apply or stage validated wiki edits through the auto-improvement approval path. Without a session ID, selects the newest completed session with no persisted auto-improvement run so repeated calls advance through preflight skips; an explicit ID remains rerunnable. The server also schedules review for new sessions; `[auto_improve] require_approval = true` leaves proposals pending for manual review. || `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. |diff --git a/docs/usage.md b/docs/usage.mdindex 2ab55183..71e5e10f 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -525,9 +525,12 @@ pull requests). Three facts frame how such a record and ai-memory interact:repo moves. Details and bounds in [`docs/marker-file.md`](marker-file.md).3. **Wiki pages marked `pinned: true` are immutable to automation.**- Retention decay and curation skip them, and the auto-improvement- apply path hard-refuses to rewrite them (the proposal is recorded as- a conflict with the reason). Unpinning is the explicit opt-out.+ Retention decay and curation skip them, multi-page consolidation+ skips any update whose path names one (with a warning in the server+ log; `_slots/` keep their own state/invariant regime), and the+ auto-improvement apply path hard-refuses to rewrite them (the proposal+ is recorded as a conflict with the reason). Unpinning is the explicit+ opt-out.For a project without a repo-side record, decisions go *in* the wiki, andthe managed durable-pages Agent Skill teaches agents the recipe: