Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(instructions): anchor marker matching to full lines so refresh is idempotent

Djalma Júniore233662f204f
diff --git a/crates/ai-memory-cli/src/commands/install_instructions.rs b/crates/ai-memory-cli/src/commands/install_instructions.rs
index 24bf1aa9..c63d9eba 100644
--- a/crates/ai-memory-cli/src/commands/install_instructions.rs
+++ b/crates/ai-memory-cli/src/commands/install_instructions.rs
@@ -27,7 +27,7 @@ use crate::config::Config;
// Markers + the snippet body live in `ai_memory_core::routing_snippet`
// so the `memory_install_self_routing` MCP tool can return the same
// block this subcommand writes. Single source of truth.
-use ai_memory_core::{MARKER_END, MARKER_START, full_block};
+use ai_memory_core::{MARKER_END, MARKER_START, find_marker_line, full_block};
/// Run the `install-instructions` subcommand.
///
@@ -161,10 +161,14 @@ fn infer_skills_agent_from_instruction_targets(targets: &[PathBuf]) -> InstallSk
/// `block` to the end of the file with a single blank-line
/// separator. The user's other content is never touched.
fn merge_instructions_block(existing: &str, block: &str) -> String {
- if let Some(start_idx) = existing.find(MARKER_START)
- && let Some(end_idx_rel) = existing[start_idx..].find(MARKER_END)
+ // Anchor on markers that occupy their own line so an inline mention of
+ // the marker strings (e.g. this block's own prose describing them)
+ // cannot be mistaken for the real end delimiter — which would truncate
+ // the block and leave an orphan tail on every refresh.
+ if let Some(start_idx) = find_marker_line(existing, MARKER_START, 0)
+ && let Some(end_pos) = find_marker_line(existing, MARKER_END, start_idx)
{
- let end_idx = start_idx + end_idx_rel + MARKER_END.len();
+ 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') {
@@ -240,6 +244,38 @@ mod tests {
assert_eq!(first, second, "second merge must be a no-op");
}
+ /// Regression: a block whose body *mentions* the end marker inline
+ /// (mid-line, as older snippets did between backticks) must not be
+ /// truncated at that mention. The naive `find` matched the inline
+ /// marker, cut early, and re-injected the tail on every refresh; the
+ /// line-anchored matcher must keep the double-run a true no-op.
+ #[test]
+ fn merge_ignores_inline_marker_mention_in_block() {
+ let block = format!(
+ "{MARKER_START}\nsee the `{MARKER_END}` marker inline\nreal body\n{MARKER_END}\n"
+ );
+ let first = merge_instructions_block("# Title\n", &block);
+ let second = merge_instructions_block(&first, &block);
+ assert_eq!(first, second, "double-run must be a no-op");
+ // One inline mention + one real delimiter — nothing accumulated.
+ assert_eq!(second.matches(MARKER_START).count(), 1);
+ assert_eq!(second.matches(MARKER_END).count(), 2);
+ }
+
+ /// The real shipped block round-trips cleanly through a refresh.
+ #[test]
+ fn merge_idempotent_with_real_block() {
+ let block = full_block();
+ let first = merge_instructions_block("# Title\n", &block);
+ let second = merge_instructions_block(&first, &block);
+ assert_eq!(first, second, "refresh of the real block must be a no-op");
+ assert_eq!(
+ second.matches(MARKER_END).count(),
+ block.matches(MARKER_END).count(),
+ "no orphaned end marker accumulated"
+ );
+ }
+
/// Defensive: existing file ends without trailing newline. We
/// should still produce well-formed output.
#[test]
diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rs
index 256c9574..75cfa5b2 100644
--- a/crates/ai-memory-cli/src/commands/uninstall.rs
+++ b/crates/ai-memory-cli/src/commands/uninstall.rs
@@ -17,7 +17,7 @@ use crate::config::Config;
use ai_memory_core::routing_skills::{
AGENTS_SKILL_DIR, CLAUDE_SKILL_DIR, MANAGED_MARKER, MANAGED_SKILLS, SKILLS_DIR,
};
-use ai_memory_core::{MARKER_END, MARKER_START};
+use ai_memory_core::{MARKER_END, MARKER_START, find_marker_line};
use anyhow::{Context, Result};
use std::io::IsTerminal;
use std::path::{Path, PathBuf};
@@ -478,13 +478,17 @@ fn print_docker_hint(data_purged: bool) {
/// `install_instructions::merge_instructions_block`: an install
/// followed by an uninstall round-trips to the original file.
fn strip_instructions_block(content: &str) -> (String, bool) {
- let Some(start) = content.find(MARKER_START) else {
+ // Line-anchored so an inline mention of the marker strings inside the
+ // managed block can't be matched as the real end delimiter (which would
+ // leave an orphan tail behind, breaking the install->uninstall
+ // round-trip).
+ let Some(start) = find_marker_line(content, MARKER_START, 0) else {
return (content.to_string(), false);
};
- let Some(end_rel) = content[start..].find(MARKER_END) else {
+ let Some(end_pos) = find_marker_line(content, MARKER_END, start) else {
return (content.to_string(), false);
};
- let end = start + end_rel + MARKER_END.len();
+ 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') {
end + 1
@@ -884,6 +888,23 @@ mod tests {
);
}
+ /// Regression: a managed block whose body mentions the end marker
+ /// inline must be stripped up to the REAL delimiter, not the inline
+ /// mention — otherwise an orphan tail survives the uninstall.
+ #[test]
+ fn strip_ignores_inline_marker_mention() {
+ let original = "# Title\n";
+ let block =
+ format!("{MARKER_START}\nsee the `{MARKER_END}` marker inline\nbody\n{MARKER_END}\n");
+ let installed = format!("{original}\n{block}");
+ let (stripped, found) = strip_instructions_block(&installed);
+ assert!(found);
+ assert_eq!(
+ stripped, original,
+ "no orphan tail after the real end marker"
+ );
+ }
+
#[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/lib.rs b/crates/ai-memory-core/src/lib.rs
index 2e339f88..c1430712 100644
--- a/crates/ai-memory-core/src/lib.rs
+++ b/crates/ai-memory-core/src/lib.rs
@@ -45,6 +45,6 @@ pub use ids::{
};
pub use observation::{NewObservation, NewSession, Observation, ObservationKind};
pub use page::{LinkTarget, NewPage, Page, Tier};
-pub use routing_snippet::{MARKER_END, MARKER_START, SNIPPET_BODY, full_block};
+pub use routing_snippet::{MARKER_END, MARKER_START, SNIPPET_BODY, find_marker_line, full_block};
pub use sanitize::{SanitizeConfig, Sanitized, Sanitizer};
pub use user::{MAX_EMAIL_LEN, MAX_USERNAME_LEN, NewUser, User, validate_email, validate_username};
diff --git a/crates/ai-memory-core/src/routing_snippet.rs b/crates/ai-memory-core/src/routing_snippet.rs
index 80791525..c709f382 100644
--- a/crates/ai-memory-core/src/routing_snippet.rs
+++ b/crates/ai-memory-core/src/routing_snippet.rs
@@ -90,9 +90,8 @@ latest binary's recommended copy:
`CLAUDE.md`; pass `--target AGENTS.md` for non-Claude agents or projects
that use `AGENTS.md` as the canonical instruction file).
-Both are idempotent: re-runs replace the block bracketed by
-`<!-- ai-memory:start -->` / `<!-- ai-memory:end -->` markers without
-disturbing the rest of the file.
+Both are idempotent: re-runs replace the block delimited by the ai-memory
+start/end HTML-comment markers, without disturbing the rest of the file.
"#;
/// Build the full markered block that should land in CLAUDE.md /
@@ -105,3 +104,67 @@ disturbing the rest of the file.
pub fn full_block() -> String {
format!("{MARKER_START}\n{}\n{MARKER_END}\n", SNIPPET_BODY.trim())
}
+
+/// Byte offset, at or after `from`, of an occurrence of `marker` that sits
+/// alone on its own line (only whitespace before it on the line and after
+/// it up to the newline). [`full_block`] always writes the real delimiters
+/// on their own lines, so this matches the true markers while skipping any
+/// inline mention of the marker strings — a marker quoted inside prose or
+/// code — which a naive [`str::find`] would hit first, truncating the
+/// managed block and leaving an orphan tail on every refresh. Returns
+/// `None` when no line-anchored occurrence exists.
+#[must_use]
+pub fn find_marker_line(haystack: &str, marker: &str, from: usize) -> Option<usize> {
+ let mut idx = from;
+ while let Some(rel) = haystack[idx..].find(marker) {
+ let pos = idx + rel;
+ let line_start = haystack[..pos].rfind('\n').map_or(0, |n| n + 1);
+ let before = &haystack[line_start..pos];
+ let after = haystack[pos + marker.len()..]
+ .split('\n')
+ .next()
+ .unwrap_or("");
+ if before.trim().is_empty() && after.trim().is_empty() {
+ return Some(pos);
+ }
+ idx = pos + marker.len();
+ }
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn find_marker_line_skips_inline_mention() {
+ let text = format!("a\nsee `{MARKER_END}` inline\n{MARKER_END}\nb\n");
+ let pos = find_marker_line(&text, MARKER_END, 0).unwrap();
+ let line_start = text[..pos].rfind('\n').map_or(0, |n| n + 1);
+ assert_eq!(
+ &text[line_start..pos],
+ "",
+ "matched marker must start its own line"
+ );
+ assert!(
+ text[pos + MARKER_END.len()..].starts_with('\n'),
+ "nothing may follow the marker on its line"
+ );
+ }
+
+ #[test]
+ fn find_marker_line_absent_returns_none() {
+ assert!(find_marker_line("no markers here\n", MARKER_END, 0).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.
+ #[test]
+ fn full_block_has_exactly_one_of_each_marker() {
+ let block = full_block();
+ assert_eq!(block.matches(MARKER_START).count(), 1);
+ assert_eq!(block.matches(MARKER_END).count(), 1);
+ assert!(block.trim_end().ends_with(MARKER_END));
+ }
+}