Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(instructions): repair legacy marker orphan tails
AkitaOnRails635cc85e8025
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3e98794e..635d0ffe 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### 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.- Project creation now emits a warning when the same project name alreadyexists in another workspace, helping catch accidental cross-workspacemisroutes while preserving legal id-namespaced homonyms.diff --git a/crates/ai-memory-cli/src/commands/install_instructions.rs b/crates/ai-memory-cli/src/commands/install_instructions.rsindex c63d9eba..8834e63d 100644--- a/crates/ai-memory-cli/src/commands/install_instructions.rs+++ b/crates/ai-memory-cli/src/commands/install_instructions.rs@@ -29,6 +29,11 @@ use crate::config::Config;// block this subcommand writes. Single source of truth.use ai_memory_core::{MARKER_END, MARKER_START, find_marker_line, full_block};+const LEGACY_ORPHAN_TAIL_LF: &str =+ "` markers without\ndisturbing the rest of the file.\n<!-- ai-memory:end -->\n";+const LEGACY_ORPHAN_TAIL_CRLF: &str =+ "` markers without\r\ndisturbing the rest of the file.\r\n<!-- ai-memory:end -->\r\n";+/// Run the `install-instructions` subcommand.////// # Errors@@ -171,15 +176,18 @@ fn merge_instructions_block(existing: &str, block: &str) -> String {let end_idx = end_pos + MARKER_END.len();// Consume a trailing newline after the end marker if present// so we don't accumulate blank lines on every re-run.- let after_end = if existing.as_bytes().get(end_idx).copied() == Some(b'\n') {+ let after_end = if existing.as_bytes().get(end_idx..end_idx + 2) == Some(b"\r\n") {+ end_idx + 2+ } else if existing.as_bytes().get(end_idx).copied() == Some(b'\n') {end_idx + 1} else {end_idx};+ let tail = strip_legacy_orphan_tail(block, &existing[after_end..]);let mut out = String::with_capacity(existing.len() + block.len());out.push_str(&existing[..start_idx]);out.push_str(block);- out.push_str(&existing[after_end..]);+ out.push_str(tail);return out;}// No prior block — append. If the file already ends with a@@ -196,6 +204,44 @@ fn merge_instructions_block(existing: &str, block: &str) -> String {out}+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;+ }+ legacy_orphan_tail(block)+ .and_then(|orphan| tail.strip_prefix(orphan))+ .unwrap_or(tail)+}++fn legacy_orphan_tail(block: &str) -> Option<&str> {+ let real_start = find_marker_line(block, MARKER_START, 0)?;+ let real_end = find_marker_line(block, MARKER_END, real_start + MARKER_START.len())?;+ let mut search_from = real_start + MARKER_START.len();+ while let Some(rel) = block[search_from..real_end].find(MARKER_END) {+ let inline = search_from + rel;+ if find_marker_line(block, MARKER_END, inline) != Some(inline) {+ let orphan_start = inline + MARKER_END.len();+ let orphan_end = consume_line_ending(block, real_end + MARKER_END.len());+ return Some(&block[orphan_start..orphan_end]);+ }+ search_from = inline + MARKER_END.len();+ }+ None+}++fn consume_line_ending(s: &str, idx: usize) -> usize {+ if s.as_bytes().get(idx..idx + 2) == Some(b"\r\n") {+ idx + 2+ } else if s.as_bytes().get(idx).copied() == Some(b'\n') {+ idx + 1+ } else {+ idx+ }+}+#[cfg(test)]mod tests {use super::*;@@ -262,6 +308,30 @@ mod tests {assert_eq!(second.matches(MARKER_END).count(), 2);}+ #[test]+ fn merge_repairs_exact_legacy_orphan_tail() {+ let block = full_block();+ let legacy_corrupt = format!("# Title\n\n{block}{LEGACY_ORPHAN_TAIL_LF}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();+ let legacy_corrupt = format!("# Title\r\n\r\n{block}{LEGACY_ORPHAN_TAIL_CRLF}More\r\n");+ let out = merge_instructions_block(&legacy_corrupt, &block);+ assert_eq!(out, format!("# Title\r\n\r\n{block}More\r\n"));+ }++ #[test]+ fn merge_consumes_crlf_after_end_marker() {+ let original = format!("# Title\r\n\r\n{MARKER_START}\r\nOLD\r\n{MARKER_END}\r\nMore\r\n");+ let block = format!("{MARKER_START}\nNEW\n{MARKER_END}\n");+ let out = merge_instructions_block(&original, &block);+ assert_eq!(out, format!("# Title\r\n\r\n{block}More\r\n"));+ }+/// The real shipped block round-trips cleanly through a refresh.#[test]fn merge_idempotent_with_real_block() {diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex 75cfa5b2..1f7f3feb 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -22,6 +22,11 @@ use anyhow::{Context, Result};use std::io::IsTerminal;use std::path::{Path, PathBuf};+const LEGACY_ORPHAN_TAIL_LF: &str =+ "` markers without\ndisturbing the rest of the file.\n<!-- ai-memory:end -->\n";+const LEGACY_ORPHAN_TAIL_CRLF: &str =+ "` markers without\r\ndisturbing the rest of the file.\r\n<!-- ai-memory:end -->\r\n";+/// One rewrite operation to apply to a config file.#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum RewriteOp {@@ -490,13 +495,15 @@ fn strip_instructions_block(content: &str) -> (String, bool) {};let end = end_pos + MARKER_END.len();// Consume a trailing newline after the end marker if present.- let after = if content.as_bytes().get(end).copied() == Some(b'\n') {+ let after = if content.as_bytes().get(end..end + 2) == Some(b"\r\n") {+ end + 2+ } else if content.as_bytes().get(end).copied() == Some(b'\n') {end + 1} else {end};let mut head = content[..start].to_string();- let tail = &content[after..];+ let tail = strip_legacy_orphan_tail(&content[after..]);// When the block sat at EOF, install added a blank-line separator// before it; drop that artifact so install→uninstall round-trips.if tail.is_empty() && head.ends_with("\n\n") {@@ -505,6 +512,12 @@ fn strip_instructions_block(content: &str) -> (String, bool) {(format!("{head}{tail}"), true)}+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)+}+/// True when a hook command string was written by ai-memory. Legacy script/// commands carry the unconditional `AI_MEMORY_HOOK_URL=` env prefix; native/// commands invoke the `ai-memory hook --event ... --server-url ...` subcommand.@@ -905,6 +918,23 @@ mod tests {);}+ #[test]+ fn strip_consumes_crlf_after_end_marker() {+ let content = format!("# Top\r\n\r\n{MARKER_START}\r\nBODY\r\n{MARKER_END}\r\nMore\r\n");+ let (stripped, found) = strip_instructions_block(&content);+ assert!(found);+ assert_eq!(stripped, "# Top\r\n\r\nMore\r\n");+ }++ #[test]+ fn strip_removes_exact_legacy_orphan_tail() {+ let content =+ format!("# Top\n\n{MARKER_START}\nBODY\n{MARKER_END}\n{LEGACY_ORPHAN_TAIL_LF}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_snippet.rs b/crates/ai-memory-core/src/routing_snippet.rsindex c709f382..8938fb6f 100644--- a/crates/ai-memory-core/src/routing_snippet.rs+++ b/crates/ai-memory-core/src/routing_snippet.rs@@ -115,6 +115,10 @@ pub fn full_block() -> String {/// `None` when no line-anchored occurrence exists.#[must_use]pub fn find_marker_line(haystack: &str, marker: &str, from: usize) -> Option<usize> {+ if marker.is_empty() || from > haystack.len() || !haystack.is_char_boundary(from) {+ return None;+ }+let mut idx = from;while let Some(rel) = haystack[idx..].find(marker) {let pos = idx + rel;@@ -157,6 +161,13 @@ mod tests {assert!(find_marker_line("no markers here\n", MARKER_END, 0).is_none());}+ #[test]+ fn find_marker_line_rejects_invalid_search_inputs() {+ assert!(find_marker_line(MARKER_END, "", 0).is_none());+ assert!(find_marker_line(MARKER_END, MARKER_END, MARKER_END.len() + 1).is_none());+ assert!(find_marker_line("é\n", MARKER_END, 1).is_none());+ }+/// Option-2 guard: the canonical block must not embed the markers/// anywhere but as the real delimiters, so the agent-driven install/// path (which never runs the CLI matcher) stays safe too.diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 06fcaa31..4f523182 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -2852,8 +2852,9 @@ mod tests {"snippet must tell agents to refresh managed skill files");assert!(- snippet.contains(ai_memory_core::MARKER_START)- && snippet.contains(ai_memory_core::MARKER_END),+ snippet.contains("start/end HTML-comment markers")+ && ai_memory_core::full_block().contains(ai_memory_core::MARKER_START)+ && ai_memory_core::full_block().contains(ai_memory_core::MARKER_END),"snippet must preserve marker replacement guidance");}