Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(audit-P2): tighten routing and raw-fallback guidance
AkitaOnRailsf64e8105aa0a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 635d0ffe..dbe84e88 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,22 +10,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed- `ai-memory install-instructions` and `ai-memory uninstall --only instructions`now match only line-anchored routing markers, handle CRLF marker lines, and- repair the exact orphan-tail shape left by older refreshes when the snippet- body mentioned an end marker inline.+ repair one or more exact orphan-tail copies left by older refreshes when the+ snippet body mentioned an end marker inline ([#161]).- Project creation now emits a warning when the same project name alreadyexists in another workspace, helping catch accidental cross-workspace- misroutes while preserving legal id-namespaced homonyms.+ misroutes while preserving legal id-namespaced homonyms ([#160]).- `memory_query` now runs the raw-observation fallback for explicit `scopes`requests when compiled wiki pages miss, so scoped cross-project searches canstill surface bounded raw session matches without falling back to the current- project.-- Upgraded `crossbeam-epoch` to the RUSTSEC-2026-0204 fixed release.+ project ([#159]).+- Upgraded `crossbeam-epoch` to the RUSTSEC-2026-0204 fixed release ([#162]).- Fixed the Docker wrapper on macOS with rootless Docker so host-configcommands (`install-mcp`, `install-hooks`, `install-instructions`, andrelated setup/removal commands) keep the `-u 0:0` mapping needed to write- bind-mounted agent configuration as the invoking host user.+ bind-mounted agent configuration as the invoking host user ([#162]).- Stabilized the Windows uninstall purge-preview regression test against- verbatim temp-path spelling.+ verbatim temp-path spelling ([#162]).## [1.11.1] - 2026-07-09diff --git a/README.md b/README.mdindex be9d0c3d..7b95f1dd 100644--- a/README.md+++ b/README.md@@ -599,7 +599,7 @@ One Rust binary runs an MCP/HTTP server and owns one data directory:Hooks POST observations to the server. The server serializes writesthrough one SQLite writer, compiles session observations into markdownpages, and serves retrieval through FTS5, graph-neighbor RRF, optional-vector RRF, and bounded raw-observation fallback.+vector RRF, and bounded raw-observation fallback for non-global searches.See [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) for the data-flowdiagram, crate breakdown, schema notes, and invariants.diff --git a/crates/ai-memory-cli/src/commands/install_instructions.rs b/crates/ai-memory-cli/src/commands/install_instructions.rsindex 8834e63d..e3ee47aa 100644--- a/crates/ai-memory-cli/src/commands/install_instructions.rs+++ b/crates/ai-memory-cli/src/commands/install_instructions.rs@@ -205,15 +205,22 @@ fn merge_instructions_block(existing: &str, block: &str) -> String {}fn strip_legacy_orphan_tail<'a>(block: &str, tail: &'a str) -> &'a str {- if let Some(rest) = tail.strip_prefix(LEGACY_ORPHAN_TAIL_LF) {- return rest;- }- if let Some(rest) = tail.strip_prefix(LEGACY_ORPHAN_TAIL_CRLF) {- return rest;+ let dynamic_orphan = legacy_orphan_tail(block);+ let mut rest = tail;+ loop {+ if let Some(stripped) = rest.strip_prefix(LEGACY_ORPHAN_TAIL_LF) {+ rest = stripped;+ } else if let Some(stripped) = rest.strip_prefix(LEGACY_ORPHAN_TAIL_CRLF) {+ rest = stripped;+ } else if let Some(orphan) = dynamic_orphan+ && !orphan.is_empty()+ && let Some(stripped) = rest.strip_prefix(orphan)+ {+ rest = stripped;+ } else {+ return rest;+ }}- legacy_orphan_tail(block)- .and_then(|orphan| tail.strip_prefix(orphan))- .unwrap_or(tail)}fn legacy_orphan_tail(block: &str) -> Option<&str> {@@ -316,6 +323,16 @@ mod tests {assert_eq!(out, format!("# Title\n\n{block}More notes.\n"));}+ #[test]+ fn merge_repairs_repeated_legacy_orphan_tails() {+ let block = full_block();+ let legacy_corrupt = format!(+ "# Title\n\n{block}{LEGACY_ORPHAN_TAIL_LF}{LEGACY_ORPHAN_TAIL_CRLF}More notes.\n"+ );+ let out = merge_instructions_block(&legacy_corrupt, &block);+ assert_eq!(out, format!("# Title\n\n{block}More notes.\n"));+ }+#[test]fn merge_repairs_exact_legacy_orphan_tail_crlf_variant() {let block = full_block();diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex 1f7f3feb..04dcc891 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -513,9 +513,16 @@ fn strip_instructions_block(content: &str) -> (String, bool) {}fn strip_legacy_orphan_tail(tail: &str) -> &str {- tail.strip_prefix(LEGACY_ORPHAN_TAIL_LF)- .or_else(|| tail.strip_prefix(LEGACY_ORPHAN_TAIL_CRLF))- .unwrap_or(tail)+ let mut rest = tail;+ loop {+ if let Some(stripped) = rest.strip_prefix(LEGACY_ORPHAN_TAIL_LF) {+ rest = stripped;+ } else if let Some(stripped) = rest.strip_prefix(LEGACY_ORPHAN_TAIL_CRLF) {+ rest = stripped;+ } else {+ return rest;+ }+ }}/// True when a hook command string was written by ai-memory. Legacy script@@ -935,6 +942,16 @@ mod tests {assert_eq!(stripped, "# Top\n\nMore\n");}+ #[test]+ fn strip_removes_repeated_legacy_orphan_tails() {+ let content = format!(+ "# Top\n\n{MARKER_START}\nBODY\n{MARKER_END}\n{LEGACY_ORPHAN_TAIL_LF}{LEGACY_ORPHAN_TAIL_CRLF}More\n"+ );+ let (stripped, found) = strip_instructions_block(&content);+ assert!(found);+ assert_eq!(stripped, "# Top\n\nMore\n");+ }+#[test]fn strip_instructions_preserves_surrounding_content() {let content = format!("# Top\n\n{MARKER_START}\nBODY\n{MARKER_END}\n\nMore notes.\n");diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-routing-install/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-routing-install/SKILL.mdindex c5d14b1e..2755cbda 100644--- a/crates/ai-memory-core/src/routing_skills/ai-memory-routing-install/SKILL.md+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-routing-install/SKILL.md@@ -19,7 +19,7 @@ The always-loaded instruction block is owned by ai-memory only between these mar- Start marker: `<!-- ai-memory:start -->`- End marker: `<!-- ai-memory:end -->`-Refresh must replace the first complete marker-bounded block in place, preserving unrelated content before and after it. If no complete block exists, append the canonical block with one blank line of separation. Never edit unrelated instructions while refreshing ai-memory routing.+Refresh must replace the first complete marker-bounded block whose start and end delimiters appear alone on their own lines, preserving unrelated content before and after it. Ignore inline mentions of marker strings inside prose or code; they are not delimiters. If no complete line-delimited block exists, append the canonical block with one blank line of separation. Never edit unrelated instructions while refreshing ai-memory routing.## Managed skill markerdiff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 4f523182..d5740cd9 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -1067,8 +1067,10 @@ impl AiMemoryServer {self}- /// Search the compiled wiki via FTS5/vector/graph retrieval. Falls back- /// to bounded raw observation search when no compiled page matches.+ /// Search the compiled wiki via FTS5/vector/graph retrieval. Default,+ /// explicit project, and explicit `scopes` searches fall back to bounded+ /// raw observation search when no compiled page matches; `global=true`+ /// searches compiled wiki pages across projects only.#[tool(description = "Search the project's long-term memory wiki — \prior sessions, decisions, gotchas, architecture notes captured \by ai-memory across earlier runs. Call this BEFORE proposing \@@ -1077,8 +1079,10 @@ impl AiMemoryServer {FTS5 + graph RRF + (when configured) vector RRF re-ranking. \Returns up to `limit` pages with HTML-marked snippets and a rank \score (lower rank = better match). Only latest page versions. \- If compiled wiki search misses, `raw_hits` contains bounded raw \- observation fallback matches. Default-scoped calls also return \+ If compiled wiki search misses in default/project/`scopes` mode, \+ `raw_hits` contains bounded raw observation fallback matches; \+ `global=true` searches compiled wiki pages only and returns no raw \+ fallback. Default-scoped calls also return \`global_scope_hits`: standing user/team preferences from the \reserved `_global` scope that apply across projects. Set \`global=true` to search EVERY \@@ -2309,8 +2313,9 @@ impl AiMemoryServer {asks to install or refresh ai-memory routing in this project. \After calling, use your Write/Edit tool to preserve non-ai-memory \user content: replace only an existing `<!-- ai-memory:start -->` \- / `<!-- ai-memory:end -->` block or append `markered_block` with \- one blank line, then write every `managed_skills` item beneath \+ / `<!-- ai-memory:end -->` block whose delimiters appear alone on \+ their own lines, or append `markered_block` with one blank line, \+ then write every `managed_skills` item beneath \the chosen skill root using its `relative_path`. This tool is \read-only and is the source of truth for the snippet and skills. \Skill files are ai-memory-managed only when they contain the \@@ -2361,7 +2366,7 @@ impl AiMemoryServer {},"notes": ["Pick the filename matching your own agent identity.",- "If the target file already contains <!-- ai-memory:start --> / <!-- ai-memory:end -->, replace ONLY that block in place; preserve every other line.",+ "If the target file already contains <!-- ai-memory:start --> / <!-- ai-memory:end --> delimiters alone on their own lines, replace ONLY that line-delimited block in place; ignore inline mentions and preserve every other line.","If the file doesn't exist, create it with just the markered_block (plus a trailing newline).","If the file exists but has no ai-memory markers, append the markered_block with one blank line of separation from existing content.","Install each managed_skills item under the selected skill root from target_hints using its relative_path, for example .claude/skills/<relative_path> or .agents/skills/<relative_path>.",diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex e1d922bb..962c1c3a 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -80,9 +80,11 @@ from hook paths.rejected candidates/rejection-buffer entries rather than wiki writes.6. `memory_query` answers via FTS5 + link-neighbour RRF; when anembedder is configured, vector cosine over `page_embeddings` joins- the same RRF. If compiled wiki pages miss entirely, bounded raw- observation FTS returns fallback `raw_hits`. Page hits bump- `access_count` + `last_accessed_at` - the M8 reinforcement term.+ the same RRF. If compiled wiki pages miss entirely in default,+ explicit project, or explicit `scopes` mode, bounded raw observation+ FTS returns fallback `raw_hits`; `global=true` searches compiled wiki+ pages across projects only. Page hits bump `access_count` ++ `last_accessed_at` - the M8 reinforcement term.7. The forget sweep runs on demand and on the server's `[maintenance]`schedule: pages with `retention < cold_threshold` are soft-deleted;soft-deletions older than `hard_delete_after_days` with no subsequentdiff --git a/docs/install.md b/docs/install.mdindex 9c3f580a..2c4a6b53 100644--- a/docs/install.md+++ b/docs/install.md@@ -1029,13 +1029,13 @@ default:1. A slim instruction block in `CLAUDE.md`, `AGENTS.md`, or the file passed with`--target`. The block is bounded by `<!-- ai-memory:start -->` and- `<!-- ai-memory:end -->`.+ `<!-- ai-memory:end -->` delimiters that appear alone on their own lines.2. Managed ai-memory Agent Skills containing the detailed tool-routing guidance.Re-running the command is safe. If a project still has the old long ai-memory-block between those markers, the refresh replaces that block in place with the-slim snippet, leaves unrelated instructions before and after it alone, and-writes a timestamped `.bak-*` backup before changing an existing file.+block between line-anchored markers, the refresh replaces that block in place+with the slim snippet, leaves unrelated instructions before and after it alone,+and writes a timestamped `.bak-*` backup before changing an existing file.Managed skill files contain an ai-memory ownership marker; same-name user skillswithout that marker are preserved unless you explicitly force replacement.`install-instructions --print` previews only the instruction snippet; rundiff --git a/docs/usage.md b/docs/usage.mdindex 013976ec..0a60aa5b 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -78,10 +78,11 @@ The agent calls `memory_install_self_routing` and receives the slim`markered_block`, marker strings, rules-file hints, managed skill payloads,skill target hints, and overwrite guidance. It then uses its normal file-edittool to preserve unrelated user content, replace or append the-`<!-- ai-memory:start -->` / `<!-- ai-memory:end -->` block, and write each-managed skill below the selected skill root. Skill files are ai-memory-managed-only when they contain the managed marker, so unmanaged same-name skills should-not be overwritten unless the human explicitly forces replacement.+`<!-- ai-memory:start -->` / `<!-- ai-memory:end -->` block only when the+marker delimiters appear alone on their own lines, and write each managed skill+below the selected skill root. Skill files are ai-memory-managed only when they+contain the managed marker, so unmanaged same-name skills should not be+overwritten unless the human explicitly forces replacement.From a terminal: