Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(auto-improve): enforce the pinned-page invariant at the apply point
AkitaOnRails7a713a903c26
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b6780d61..5c2f0876 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed+- The documented auto-improvement safety invariant "never rewrite pinned+ pages" is now enforced in code, not just in the reviewer prompt: the+ apply path — shared by manual approval and `require_approval = false`+ auto-apply — refuses `update` proposals whose target page is pinned,+ recording the proposal as a conflict with an explicit reason. Unpinning+ the page is the explicit way to allow a rewrite ([#157]).++### Added+- Architectural-decision guidance ([#157]): the managed durable-pages+ Agent Skill now teaches agents to record architectural decisions as+ pinned wiki pages under `decisions/<slug>.md` with ADR structure+ (Status / Context / Decision / Consequences, rejected alternatives+ included) and to supersede with a new page instead of editing history.+ `docs/usage.md` gains an ADR section clarifying that ai-memory never+ touches repository files (a `docs/adr/` tree managed by hand or by an+ external ADR MCP server is outside its write surface) and how the two+ coexist.+## [1.11.0] - 2026-07-09### Fixeddiff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.mdindex c59a8d00..2ae95f9b 100644--- a/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-durable-pages/SKILL.md@@ -31,6 +31,28 @@ Delete only by exact path. If the user gives a vague title or topic, first resolDefault to the current project. Pass workspace and project together only when the user explicitly names a different project. Never pass scope arguments for phrases like this project, here, we, or our work.+## Architectural decisions get ADR structure and a pin++When the user asks to record an architectural decision (a chosen approach, a rejected alternative, a standing trade-off), write it as a durable page under `decisions/<short-slug>.md` with `pinned: true` and this structure in the body:++```markdown+# <Decision title>++**Status:** accepted <!-- proposed | accepted | superseded by [[decisions/other]] -->++## Context+What situation forced a decision; the constraints that mattered.++## Decision+What was decided, stated as a fact.++## Consequences+What becomes easier, what becomes harder, what was given up.+Rejected alternatives and WHY, so future sessions don't re-propose them.+```++Pinned pages are exempt from retention decay and curation, and the auto-improvement path refuses to rewrite them — the record stays immutable unless a human unpins it. To supersede a decision, write a NEW page and set the old page's status line to `superseded by [[decisions/<new>]]`; never edit the old decision's substance. Note: ai-memory never touches files in the project repository — a `docs/adr/` directory managed there (by hand or by another tool) is outside ai-memory entirely; these wiki ADRs complement it for cross-session retrieval.+## Standing user/team preferences go to the global scopeWhen the fact is a standing preference that should apply to EVERY project — technology choices ("always use pnpm workspaces"), code style ("prefer composition over inheritance"), personal conventions ("never `--force` without asking") — call `memory_write_page` with `scope: "global"` instead of the current project. The page lands in the reserved `_global` scope, and default memory reads surface it in every project as `global_scope_hits`. `scope: "global"` cannot be combined with workspace/project arguments. Use it only for genuinely cross-project preferences; project-specific rules stay in the project (or its instruction file, per the section above).diff --git a/crates/ai-memory-store/src/auto_improve.rs b/crates/ai-memory-store/src/auto_improve.rsindex 72e3887c..f4d93c58 100644--- a/crates/ai-memory-store/src/auto_improve.rs+++ b/crates/ai-memory-store/src/auto_improve.rs@@ -601,9 +601,10 @@ pub fn stage_run(proposal.target_path)));}- (AutoImproveProposalOperation::Update, Some((id, body_hash, updated_at))) => {- (Some(id), Some(bytes32(body_hash)?), Some(updated_at))- }+ (+ AutoImproveProposalOperation::Update,+ Some((id, body_hash, updated_at, _pinned, _fm)),+ ) => (Some(id), Some(bytes32(body_hash)?), Some(updated_at)),(AutoImproveProposalOperation::Update, None) => {return Err(StoreError::InvalidState(format!("update proposal target does not exist: {}",@@ -851,10 +852,38 @@ pub fn approve_proposal(}let current = latest_target_snapshot(&tx, input.workspace_id, input.project_id, &target_path)?;+ // Hard enforcement of the documented safety invariant: pinned pages are+ // never rewritten by the auto-improvement path (issue #157). The check+ // lives HERE — the single point every apply flows through, manual+ // approval and require_approval=false auto-apply alike — so no index+ // window, prompt phrasing, or approval policy can bypass it. Unpinning+ // the page first is the explicit way to allow the rewrite.+ if current+ .as_ref()+ .is_some_and(|(_, _, _, pinned, frontmatter)| {+ pinned_refusal_applies(&target_path, *pinned, frontmatter)+ })+ {+ const REASON: &str =+ "target page is pinned; pinned pages are never rewritten by auto-improvement";+ insert_rejection_for_proposal_in_tx(&tx, input.proposal_id, REASON, now)?;+ mark_decision_in_tx(&tx, input, "conflict", None, Some(REASON), now)?;+ insert_event_in_tx(+ &tx,+ input.proposal_id,+ "conflict",+ &input.actor,+ input.author_id,+ &serde_json::json!({ "reason": REASON }),+ now,+ )?;+ tx.commit()?;+ return Ok(ApproveAutoImproveProposalResult::Conflict);+ }let conflict = match AutoImproveProposalOperation::from_str(&operation)? {AutoImproveProposalOperation::Create => current.is_some(),AutoImproveProposalOperation::Update => match current {- Some((id, body_hash, updated_at)) => {+ Some((id, body_hash, updated_at, _pinned, _fm)) => {Some(id.as_bytes().to_vec()) != staged_page_id|| Some(body_hash) != staged_body_hash|| Some(updated_at) != staged_updated_at@@ -940,10 +969,10 @@ fn latest_target_snapshot(workspace_id: WorkspaceId,project_id: ProjectId,target_path: &str,-) -> StoreResult<Option<(PageId, Vec<u8>, i64)>> {+) -> StoreResult<Option<(PageId, Vec<u8>, i64, bool, String)>> {let row = tx.query_row(- "SELECT id, body_sha256, updated_at FROM pages \+ "SELECT id, body_sha256, updated_at, pinned, frontmatter_json FROM pages \WHERE workspace_id = ?1 AND project_id = ?2 AND path = ?3 AND is_latest = 1",params![workspace_id.as_bytes(), project_id.as_bytes(), target_path],|row| {@@ -951,6 +980,8 @@ fn latest_target_snapshot(PageId::from_slice(&row.get::<_, Vec<u8>>(0)?).map_err(to_sql_err)?,row.get::<_, Vec<u8>>(1)?,row.get::<_, i64>(2)?,+ row.get::<_, bool>(3)?,+ row.get::<_, String>(4)?,))},)@@ -958,6 +989,31 @@ fn latest_target_snapshot(Ok(row)}+/// Whether the pinned-target refusal applies (issue #157). Pinned pages+/// are never rewritten by auto-improvement — with one sanctioned+/// exception: NON-invariant memory slots under `_slots/` (e.g.+/// `current-focus`, a state slot) are always pinned by the slot regime+/// and are exactly the pages auto-improvement is SUPPOSED to refresh.+/// Slots whose frontmatter declares `slot_kind: "invariant"` stay+/// protected, matching the documented safety invariant ("never rewrite+/// pinned pages or invariant slots").+fn pinned_refusal_applies(target_path: &str, pinned: bool, frontmatter_json: &str) -> bool {+ if !pinned {+ return false;+ }+ if !target_path.starts_with("_slots/") {+ return true;+ }+ serde_json::from_str::<serde_json::Value>(frontmatter_json)+ .ok()+ .and_then(|fm| {+ fm.get("slot_kind")+ .and_then(serde_json::Value::as_str)+ .map(|kind| kind.eq_ignore_ascii_case("invariant"))+ })+ .unwrap_or(false)+}+fn insert_event_in_tx(tx: &rusqlite::Transaction<'_>,proposal_id: AutoImproveProposalId,@@ -1200,3 +1256,44 @@ pub(crate) fn opt_bytes32(bytes: Option<Vec<u8>>) -> StoreResult<Option<[u8; 32]pub(crate) fn to_sql_err<E: std::error::Error + Send + Sync + 'static>(err: E) -> rusqlite::Error {rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Blob, Box::new(err))}++#[cfg(test)]+mod tests {+ use super::*;++ // Issue #157: pinned pages are refused; the sanctioned exception is+ // NON-invariant `_slots/` pages (the slot regime pins everything, and+ // state slots like current-focus are exactly what auto-improvement is+ // supposed to refresh). Invariant slots stay protected.+ #[test]+ fn pinned_refusal_spares_state_slots_but_not_invariant_slots() {+ // Regular pinned page: refused.+ assert!(pinned_refusal_applies("decisions/adr-0001.md", true, "{}"));+ // Unpinned: never refused.+ assert!(!pinned_refusal_applies(+ "decisions/adr-0001.md",+ false,+ "{}"+ ));+ // State slot (default kind): allowed.+ assert!(!pinned_refusal_applies(+ "_slots/current-focus.md",+ true,+ "{}"+ ));+ assert!(!pinned_refusal_applies(+ "_slots/current-focus.md",+ true,+ r#"{"slot_kind": "state"}"#+ ));+ // Invariant slot: refused.+ assert!(pinned_refusal_applies(+ "_slots/never-force-push.md",+ true,+ r#"{"slot_kind": "invariant"}"#+ ));+ // Malformed frontmatter on a slot: treated as state (allowed) —+ // the slot regime owns those pages either way.+ assert!(!pinned_refusal_applies("_slots/x.md", true, "not-json"));+ }+}diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 30f3bfea..a4faa7dc 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -219,6 +219,116 @@ mod tests {.unwrap_or(0)}+ // Issue #157: the documented safety invariant "pinned pages are never+ // rewritten by auto-improvement" is enforced at the single apply point+ // every flow shares (manual approval AND require_approval=false+ // auto-apply), so no prompt phrasing or approval policy can bypass it.+ #[tokio::test]+ async fn approve_refuses_update_proposals_against_pinned_pages() {+ 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, "app", None)+ .await+ .unwrap();++ // A pinned decision record and an unpinned sibling.+ let mut pinned = sample_page(ws, proj, "decisions/adr-0001.md", "immutable decision");+ pinned.pinned = true;+ store.writer.upsert_page(pinned).await.unwrap();+ store+ .writer+ .upsert_page(sample_page(ws, proj, "notes/mutable.md", "old body"))+ .await+ .unwrap();++ let staged = store+ .writer+ .stage_auto_improve_run(stage_input(+ ws,+ proj,+ vec![+ proposal(+ "decisions/adr-0001.md",+ AutoImproveProposalOperation::Update,+ "rewritten decision",+ ),+ proposal(+ "notes/mutable.md",+ AutoImproveProposalOperation::Update,+ "new body",+ ),+ ],+ ))+ .await+ .unwrap();+ let actor = ActorContext::default();++ // Pinned target: refused as a conflict, nothing written.+ let approve = |proposal_id, path: &str, body: &str| ApproveAutoImproveProposal {+ workspace_id: ws,+ project_id: proj,+ proposal_id,+ page: sample_page(ws, proj, path, body),+ actor: actor.clone(),+ author_id: None,+ checkpoint: None,+ };+ assert_eq!(+ store+ .writer+ .approve_auto_improve_proposal(approve(+ staged.proposal_ids[0],+ "decisions/adr-0001.md",+ "rewritten decision",+ ))+ .await+ .unwrap(),+ ApproveAutoImproveProposalResult::Conflict,+ "pinned target must be refused"+ );+ let detail = store+ .reader+ .auto_improve_proposal_detail(ws, proj, staged.proposal_ids[0])+ .await+ .unwrap()+ .unwrap();+ assert!(+ detail+ .decision_reason+ .as_deref()+ .is_some_and(|r| r.contains("pinned")),+ "decision reason must say WHY: {:?}",+ detail.decision_reason+ );+ let (_, body_hash, _) = latest_snapshot(store.db_path(), ws, proj, "decisions/adr-0001.md");+ assert_eq!(+ body_hash,+ sha256("immutable decision"),+ "pinned body untouched"+ );++ // Unpinned sibling still approves normally.+ assert!(matches!(+ store+ .writer+ .approve_auto_improve_proposal(approve(+ staged.proposal_ids[1],+ "notes/mutable.md",+ "new body",+ ))+ .await+ .unwrap(),+ ApproveAutoImproveProposalResult::Approved { .. }+ ));+ }+#[tokio::test]async fn auto_improve_migration_and_stage_persist_reopen_list_detail_scope() {let tmp = TempDir::new().unwrap();diff --git a/docs/usage.md b/docs/usage.mdindex 1b619048..013976ec 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -287,3 +287,31 @@ rule looks durable enough to copy into `CLAUDE.md` or `AGENTS.md`.ai-memory never edits the rules file on its own. The lint suggestion isthe whole workflow: copy the rule if it should apply every turn, ignoreit if it was temporary context.++## Architecture Decision Records (ADRs)++Two facts frame how ADRs and ai-memory interact:++1. **ai-memory never touches files in your repository.** Its wiki lives+ in the server's data dir; the background jobs (consolidation,+ curation, retention decay, auto-improvement) read and write wiki+ pages only. A `docs/adr/` directory in the repo — maintained by hand+ or by a dedicated ADR tool/MCP server (e.g.+ [joshrotenberg/adrs](https://github.com/joshrotenberg/adrs)) — is+ categorically outside ai-memory's write surface. Run both side by+ side without ceremony: the ADR tool owns the canonical log, ai-memory+ owns cross-session recall.++2. **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.++For decisions recorded *in* the wiki, the managed durable-pages Agent+Skill teaches agents the recipe: `decisions/<slug>.md`, ADR structure+(Status / Context / Decision / Consequences, including rejected+alternatives), `pinned: true`, and supersede-by-new-page instead of+editing history. Ask an agent to "record this as an architectural+decision" and the skill does the rest; the structured shape also+retrieves noticeably better through `memory_query` than free-form+prose.