Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(cli): resolve Claude Code @imports from the importing file
Gabriel Alencar315e1216ce3e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 53f77b46..f70c4e35 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,15 @@ version in [`docs/changelog/`](docs/changelog/):## [Unreleased]### Fixed+- Fixed `install-instructions` treating a line that is exactly `@AGENTS.md` as+ proof that Claude Code loads the `AGENTS.md` being written. Claude Code+ resolves `@path` from the file that contains the import, including in the+ middle of a sentence, expands `~/` from the home directory, and ignores+ imports inside code spans and fenced blocks. `@AGENTS.md` in+ `.claude/CLAUDE.md` loads `.claude/AGENTS.md`, a fenced `@AGENTS.md` loads+ nothing, and `@AGENTS.md` in a parent directory loads that directory's file.+ The note now compares the resolved path with the file being written and+ names the import that reaches it. (#1298)- Fixed the thin-client commands ignoring a custom `bind`, which could writeinto the wrong store. `server_url` defaulted to `http://127.0.0.1:49374`and was never derived from `bind`, so `ai-memory --data-dir X status` (anddiff --git a/crates/ai-memory-cli/src/commands/install_instructions.rs b/crates/ai-memory-cli/src/commands/install_instructions.rsindex f2f27db6..65b5d4e5 100644--- a/crates/ai-memory-cli/src/commands/install_instructions.rs+++ b/crates/ai-memory-cli/src/commands/install_instructions.rs@@ -13,7 +13,7 @@//! file. Idempotent via HTML-comment markers so re-running picks up//! whatever the snippet evolves into without duplicating the block.-use std::path::PathBuf;+use std::path::{Component, Path, PathBuf};use anyhow::{Context, Result};@@ -167,16 +167,18 @@ fn resolve_targets(explicit: Option<&std::path::PathBuf>) -> Result<Vec<std::pat}/// A note for when the block goes only into `AGENTS.md` but Claude Code will-/// not read that file (#1297). Claude Code 2.1.277 and later reads+/// not read that file (#1297, #1298). Claude Code 2.1.277 and later reads/// `AGENTS.md` only when no `CLAUDE.md`, `.claude/CLAUDE.md` or/// `CLAUDE.local.md` exists in the working directory or above it; when one-/// does, it reads those instead. The block then reaches Claude Code only if one-/// of them imports `@AGENTS.md`. The user file `~/.claude/CLAUDE.md` does not-/// count.+/// does, it reads those instead. The block still reaches Claude Code when one+/// of those files imports the `AGENTS.md` being written. `@path` resolves from+/// the importing file (`~/` from the home directory), including mid-sentence;+/// code spans and fenced blocks are not imports. The user file+/// `~/.claude/CLAUDE.md` does not count.fn claude_code_skips_agents_md(targets: &[PathBuf],- cwd: &std::path::Path,- home: Option<&std::path::Path>,+ cwd: &Path,+ home: Option<&Path>,) -> Option<String> {let named = |name: &str| {targets@@ -186,6 +188,8 @@ fn claude_code_skips_agents_md(if !named("AGENTS.md") || named("CLAUDE.md") {return None;}+ let agents = written_agents_files(targets, cwd);+ let first_agents = agents.first()?;let mut found = Vec::new();for dir in cwd.ancestors() {for name in ["CLAUDE.md", "CLAUDE.local.md", ".claude/CLAUDE.md"] {@@ -198,22 +202,321 @@ fn claude_code_skips_agents_md(}}}- let imports_agents_md = |path: &PathBuf| {- std::fs::read_to_string(path)- .is_ok_and(|text| text.lines().any(|line| line.trim() == "@AGENTS.md"))- };let first = found.first()?;- if found.iter().any(imports_agents_md) {+ if found+ .iter()+ .any(|path| file_imports_written_agents(path, &agents, home))+ {return None;}+ let import = suggested_agents_import(first, first_agents);Some(format!("note: {} exists, so Claude Code reads it instead of AGENTS.md and will not see \- this block. Add a bare `@AGENTS.md` line to a CLAUDE.md there, or set Claude \+ this block. Add `{import}` to that file, or set Claude \Code's Project instructions to `claude-md-and-agents-md`.",- first.display()+ first.display(),))}+fn written_agents_files(targets: &[PathBuf], cwd: &Path) -> Vec<PathBuf> {+ targets+ .iter()+ .filter(|target| target.file_name().and_then(|name| name.to_str()) == Some("AGENTS.md"))+ .map(|target| {+ if target.is_absolute() {+ target.clone()+ } else {+ cwd.join(target)+ }+ })+ .collect()+}++fn file_imports_written_agents(path: &Path, agents: &[PathBuf], home: Option<&Path>) -> bool {+ let Ok(text) = std::fs::read_to_string(path) else {+ return false;+ };+ claude_import_paths(&text).into_iter().any(|raw| {+ let resolved = resolve_claude_import(&raw, path, home);+ agents.iter().any(|target| paths_match(&resolved, target))+ })+}++/// `@path` relative to the importing file, so `.claude/CLAUDE.md` needs+/// `@../AGENTS.md` and a parent file needs `@app/AGENTS.md`.+fn suggested_agents_import(importer: &Path, agents: &Path) -> String {+ let from = importer.parent().unwrap_or(importer);+ format!("@{}", slash_relative(from, agents))+}++fn resolve_claude_import(raw: &str, importer: &Path, home: Option<&Path>) -> PathBuf {+ let base = importer.parent().unwrap_or(importer);+ if let Some(rest) = home_relative(raw)+ && let Some(home) = home+ {+ return if rest.is_empty() {+ home.to_path_buf()+ } else {+ home.join(rest)+ };+ }+ let path = Path::new(raw);+ if path.is_absolute() {+ path.to_path_buf()+ } else {+ base.join(path)+ }+}++fn home_relative(raw: &str) -> Option<&str> {+ if raw == "~" {+ Some("")+ } else {+ raw.strip_prefix("~/").or_else(|| raw.strip_prefix("~\\"))+ }+}++fn paths_match(left: &Path, right: &Path) -> bool {+ match (std::fs::canonicalize(left), std::fs::canonicalize(right)) {+ (Ok(left), Ok(right)) => left == right,+ // One side may not exist yet (`.claude/AGENTS.md` when only the+ // project file does). Fold `.` and `..` without requiring either file.+ _ => lexical_normalize(left) == lexical_normalize(right),+ }+}++/// Fold `.` and `..` without touching the filesystem. A `..` that would climb+/// past the root stays at the root; import paths are absolute by the time+/// they reach here, so this does not consult the process cwd.+fn lexical_normalize(path: &Path) -> PathBuf {+ let mut stack: Vec<Component<'_>> = Vec::new();+ for component in path.components() {+ match component {+ Component::CurDir => {}+ Component::ParentDir => match stack.last() {+ Some(Component::Normal(_)) => {+ stack.pop();+ }+ Some(Component::RootDir | Component::Prefix(_)) => {}+ _ => stack.push(component),+ },+ other => stack.push(other),+ }+ }+ stack.into_iter().collect()+}++fn slash_relative(from_dir: &Path, target: &Path) -> String {+ let from = lexical_normalize(from_dir);+ let to = lexical_normalize(target);+ let from_comps: Vec<Component<'_>> = from.components().collect();+ let to_comps: Vec<Component<'_>> = to.components().collect();+ let mut shared = 0;+ while shared < from_comps.len()+ && shared < to_comps.len()+ && from_comps[shared] == to_comps[shared]+ {+ shared += 1;+ }+ let root_left =+ |component: &Component<'_>| matches!(component, Component::Prefix(_) | Component::RootDir);+ if from_comps.iter().skip(shared).any(root_left) || to_comps.iter().skip(shared).any(root_left)+ {+ return forward_slashes(&to);+ }+ let mut parts = Vec::new();+ for _ in from_comps.iter().skip(shared) {+ parts.push("..".to_string());+ }+ for component in to_comps.iter().skip(shared) {+ if let Component::Normal(part) = component {+ parts.push(part.to_string_lossy().into_owned());+ }+ }+ if parts.is_empty() {+ forward_slashes(&to)+ } else {+ parts.join("/")+ }+}++fn forward_slashes(path: &Path) -> String {+ let mut out = String::new();+ for component in path.components() {+ match component {+ Component::Prefix(prefix) => out.push_str(&prefix.as_os_str().to_string_lossy()),+ Component::RootDir => {+ if !out.ends_with('/') {+ out.push('/');+ }+ }+ Component::CurDir => push_slash_part(&mut out, "."),+ Component::ParentDir => push_slash_part(&mut out, ".."),+ Component::Normal(part) => push_slash_part(&mut out, &part.to_string_lossy()),+ }+ }+ out+}++fn push_slash_part(out: &mut String, part: &str) {+ if !out.is_empty() && !out.ends_with(['/', ':']) {+ out.push('/');+ }+ out.push_str(part);+}++/// `@path` tokens Claude Code would import. Relative paths are not resolved+/// here; the caller joins them onto the importing file. Fenced blocks and+/// code spans are skipped, and a path ends at the first unescaped space. A+/// backtick run with no closer is literal text, matching CommonMark.+fn claude_import_paths(text: &str) -> Vec<String> {+ let mut paths = Vec::new();+ let mut prose = String::new();+ let mut fence: Option<(u8, usize)> = None;+ for line in text.split_inclusive('\n') {+ let body = line.trim_end_matches(['\n', '\r']);+ if let Some((tick, len)) = fence {+ if fence_close(body, tick, len) {+ fence = None;+ }+ continue;+ }+ if let Some(opened) = fence_open(body) {+ scan_import_prose(&prose, &mut paths);+ prose.clear();+ fence = Some(opened);+ continue;+ }+ prose.push_str(line);+ }+ scan_import_prose(&prose, &mut paths);+ paths+}++fn fence_open(line: &str) -> Option<(u8, usize)> {+ let bytes = line.as_bytes();+ let mut i = 0;+ while i < bytes.len() && i < 3 && bytes[i] == b' ' {+ i += 1;+ }+ if i >= bytes.len() {+ return None;+ }+ let tick = bytes[i];+ if tick != b'`' && tick != b'~' {+ return None;+ }+ let start = i;+ while i < bytes.len() && bytes[i] == tick {+ i += 1;+ }+ let len = i - start;+ if len < 3 || (tick == b'`' && line[i..].contains('`')) {+ return None;+ }+ Some((tick, len))+}++fn fence_close(line: &str, tick: u8, min_len: usize) -> bool {+ let bytes = line.as_bytes();+ let mut i = 0;+ while i < bytes.len() && i < 3 && bytes[i] == b' ' {+ i += 1;+ }+ let start = i;+ while i < bytes.len() && bytes[i] == tick {+ i += 1;+ }+ i - start >= min_len && line[i..].trim().is_empty()+}++fn scan_import_prose(text: &str, paths: &mut Vec<String>) {+ let bytes = text.as_bytes();+ let mut i = 0;+ while i < bytes.len() {+ if bytes[i] == b'`' && (i == 0 || bytes[i - 1] != b'`') {+ let len = byte_run_len(bytes, i, b'`');+ if let Some(end) = find_exact_run(bytes, i + len, b'`', len) {+ i = end;+ continue;+ }+ i += len;+ continue;+ }+ if bytes[i] == b'@' && import_boundary(bytes, i) {+ let (path, next) = read_import_path(text, i + 1);+ if import_path_ok(&path) {+ paths.push(path);+ }+ i = next.max(i + 1);+ continue;+ }+ i += 1;+ }+}++fn import_boundary(bytes: &[u8], at: usize) -> bool {+ if at == 0 {+ return true;+ }+ let prev = bytes[at - 1];+ if prev == b'"' || prev == b'\'' {+ return false;+ }+ !prev.is_ascii_alphanumeric()+ && !matches!(prev, b'_' | b'-' | b'.' | b'/' | b'\\' | b'@' | b'~')+}++fn import_path_ok(path: &str) -> bool {+ !path.is_empty() && !path.starts_with(['"', '\''])+}++fn read_import_path(line: &str, start: usize) -> (String, usize) {+ let bytes = line.as_bytes();+ let mut i = start;+ let mut out = String::new();+ while i < bytes.len() {+ if bytes[i] == b'\\'+ && let Some(next) = bytes.get(i + 1).copied()+ && (next == b' ' || next == b'\\')+ {+ out.push(next as char);+ i += 2;+ continue;+ }+ if bytes[i].is_ascii_whitespace() {+ break;+ }+ let Some(ch) = line[i..].chars().next() else {+ break;+ };+ out.push(ch);+ i += ch.len_utf8();+ }+ (out, i)+}++fn byte_run_len(bytes: &[u8], start: usize, tick: u8) -> usize {+ let mut i = start;+ while i < bytes.len() && bytes[i] == tick {+ i += 1;+ }+ i - start+}++/// Index just past a run of exactly `len` `tick` bytes that is not part of a+/// longer run. A longer run must not close a shorter span.+fn find_exact_run(bytes: &[u8], mut from: usize, tick: u8, len: usize) -> Option<usize> {+ while from < bytes.len() {+ let run_start = bytes[from] == tick && (from == 0 || bytes[from - 1] != tick);+ if run_start && byte_run_len(bytes, from, tick) == len {+ return Some(from + len);+ }+ from += 1;+ }+ None+}+fn skill_args_from_instruction_args(args: &InstallInstructionsArgs,targets: &[PathBuf],@@ -340,6 +643,160 @@ fn consume_line_ending(s: &str, idx: usize) -> usize {mod tests {use super::*;+ /// #1298, measured against Claude Code 2.1.300. `@path` resolves from the+ /// importing file, including mid-sentence, and a fenced `@AGENTS.md` is+ /// not an import. Two of these are silent misses on the exact-line check+ /// and two are false notes; the parent-directory row is the third miss.+ #[test]+ fn claude_code_agents_import_matches_five_measured_cases() {+ struct Case<'a> {+ label: &'a str,+ /// Working directory, relative to the temp root. `.` is the root.+ cwd: &'a str,+ agents: &'a str,+ files: &'a [(&'a str, &'a str)],+ expect_note: bool,+ /// Import the note should tell the user to add, when it warns.+ import_hint: Option<&'a str>,+ }+ const FENCED: &str = "```\[email protected]\n```\n";+ let beside = [(".claude/CLAUDE.md", "@AGENTS.md\n")];+ let parent_import = [(".claude/CLAUDE.md", "@../AGENTS.md\n")];+ let mid_sentence = [("CLAUDE.local.md", "See @AGENTS.md for the team rules.\n")];+ let fenced = [("CLAUDE.local.md", FENCED)];+ let parent_dir = [("CLAUDE.local.md", "@AGENTS.md\n")];+ let cases = [+ Case {+ label: ".claude/CLAUDE.md @AGENTS.md resolves beside the importer",+ cwd: ".",+ agents: "AGENTS.md",+ files: &beside,+ expect_note: true,+ import_hint: Some("`@../AGENTS.md`"),+ },+ Case {+ label: ".claude/CLAUDE.md @../AGENTS.md loads the project file",+ cwd: ".",+ agents: "AGENTS.md",+ files: &parent_import,+ expect_note: false,+ import_hint: None,+ },+ Case {+ label: "mid-sentence @AGENTS.md is an import",+ cwd: ".",+ agents: "AGENTS.md",+ files: &mid_sentence,+ expect_note: false,+ import_hint: None,+ },+ Case {+ label: "fenced @AGENTS.md is not an import",+ cwd: ".",+ agents: "AGENTS.md",+ files: &fenced,+ expect_note: true,+ import_hint: Some("`@AGENTS.md`"),+ },+ Case {+ label: "parent @AGENTS.md resolves to the parent file, not app/AGENTS.md",+ cwd: "app",+ agents: "app/AGENTS.md",+ files: &parent_dir,+ expect_note: true,+ import_hint: Some("`@app/AGENTS.md`"),+ },+ ];+ let home = tempfile::tempdir().unwrap();+ for case in cases {+ let root = tempfile::tempdir().unwrap();+ for (rel, body) in case.files {+ let path = root.path().join(rel);+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::write(&path, body).unwrap();+ }+ let cwd = root.path().join(case.cwd);+ let agents = root.path().join(case.agents);+ std::fs::create_dir_all(agents.parent().unwrap()).unwrap();+ if !agents.is_file() {+ std::fs::write(&agents, "# agents\n").unwrap();+ }+ let note =+ claude_code_skips_agents_md(std::slice::from_ref(&agents), &cwd, Some(home.path()));+ if case.expect_note {+ let note = note.unwrap_or_else(|| panic!("{}: expected a note", case.label));+ assert!(+ note.contains("so Claude Code reads it instead of AGENTS.md"),+ "{}: {note}",+ case.label+ );+ if let Some(hint) = case.import_hint {+ let shown = hint.replace('/', std::path::MAIN_SEPARATOR_STR);+ assert!(+ note.contains(hint) || note.contains(&shown),+ "{}: note {note} does not name {hint}",+ case.label+ );+ }+ } else {+ assert!(+ note.is_none(),+ "{}: unexpected note: {}",+ case.label,+ note.unwrap_or_default()+ );+ }+ }+ }++ /// Code spans are not imports, and `~/` resolves from the home directory+ /// rather than from the importing file (#1298).+ #[test]+ fn claude_code_import_skips_code_spans_and_expands_home() {+ let root = tempfile::tempdir().unwrap();+ let agents = root.path().join("AGENTS.md");+ std::fs::write(&agents, "# agents\n").unwrap();+ std::fs::write(+ root.path().join("CLAUDE.local.md"),+ "See `@AGENTS.md` for the syntax.\n",+ )+ .unwrap();+ let unrelated_home = tempfile::tempdir().unwrap();+ let note = claude_code_skips_agents_md(+ std::slice::from_ref(&agents),+ root.path(),+ Some(unrelated_home.path()),+ );+ assert!(+ note.as_deref()+ .is_some_and(|text| text.contains("`@AGENTS.md`")),+ "a code span is not an import: {}",+ note.unwrap_or_default()+ );++ let home = tempfile::tempdir().unwrap();+ let project = home.path().join("proj");+ std::fs::create_dir_all(&project).unwrap();+ let agents = project.join("AGENTS.md");+ std::fs::write(&agents, "# agents\n").unwrap();+ std::fs::write(project.join("CLAUDE.local.md"), "@~/proj/AGENTS.md\n").unwrap();+ let note =+ claude_code_skips_agents_md(std::slice::from_ref(&agents), &project, Some(home.path()));+ assert!(+ note.is_none(),+ "home import of the written file should suppress the note: {}",+ note.unwrap_or_default()+ );++ std::fs::write(project.join("CLAUDE.local.md"), "@~/other/AGENTS.md\n").unwrap();+ let note =+ claude_code_skips_agents_md(std::slice::from_ref(&agents), &project, Some(home.path()));+ assert!(+ note.is_some(),+ "a home import of a different file still leaves AGENTS.md unloaded"+ );+ }+#[test]fn merge_appends_to_empty_file() {let out = merge_instructions_block("", "BLOCK\n");diff --git a/docs/usage.md b/docs/usage.mdindex 193e3d90..485c5b2e 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -379,8 +379,11 @@ leaves adherence to whether the agent does. See[Claude Code memory](https://code.claude.com/docs/en/memory#agents-md).`install-instructions` prints a note when it writes only `AGENTS.md` while a`CLAUDE.local.md`, `.claude/CLAUDE.md` or `CLAUDE.md` in the directory or above-it would make Claude Code read that file instead, unless one of them already-imports `@AGENTS.md`.+it would make Claude Code read that file instead, unless one of them imports+the `AGENTS.md` being written. The import is resolved from the file that+contains it (`@AGENTS.md` in `.claude/CLAUDE.md` points at `.claude/AGENTS.md`;+that file needs `@../AGENTS.md`), `~/` expands from the home directory, and an+`@path` inside a code span or fenced block does not count.To refresh only the managed Agent Skills: