Skip to content

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

Rust

apply_shared: fix EXDEV on relative paths; refresh CLAUDE.md

AkitaOnRails4ca3c6a31799
diff --git a/.gitignore b/.gitignore
index 53627586..4e43c35c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -30,3 +30,6 @@ perf.data*
.ai-jail
.claude/
evals/runs/
+
+# ai-memory atomic-write backups (apply_atomic in apply_shared.rs)
+*.bak-*
diff --git a/CLAUDE.md b/CLAUDE.md
index fc233d0f..84ff6b0f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -145,3 +145,56 @@ The current execution plan is at
[`/home/akitaonrails/.claude/plans/cuddly-moseying-karp.md`](/home/akitaonrails/.claude/plans/cuddly-moseying-karp.md)
(local to the maintainer's `~/.claude/`).
Live progress is tracked via the TaskList tool inside Claude Code sessions.
+
+<!-- ai-memory:start -->
+## Long-term memory (ai-memory)
+
+This project uses [ai-memory](https://github.com/akitaonrails/ai-memory)
+for cross-session continuity. **Lifecycle hooks already capture every
+prompt + tool call automatically.** You never need to manually write
+notes; the SessionStart hook auto-fetches pending handoffs and the
+SessionEnd hook auto-consolidates. Just *use* the read tools.
+
+### When to reach for each tool
+
+The user can express any of the intents below in plain English —
+match the intent to the tool. They do not need to name the tool.
+
+| User says / situation | Tool |
+|---|---|
+| "have we discussed X?" / "search memory for Y" / before proposing architecture | `memory_query` |
+| "what's been going on" / "show recent activity" (light) | `memory_recent` |
+| "is ai-memory healthy?" / "how big is the wiki?" | `memory_status` |
+| "give me the stats" / structured snapshot for the agent to consume | `memory_briefing` |
+| "catch me up" / "I've been away" / "what's important right now?" / open-ended exploration | `memory_explore` |
+| "where did we leave off?" / first turn of a new session | `memory_handoff_accept` |
+| "save context for the next session" / wrapping up | `memory_handoff_begin` |
+| "consolidate this session" / "compile what we learned" (usually automatic) | `memory_consolidate` |
+| "audit the wiki" / "find contradictions" / "what rules should we add?" | `memory_lint` |
+| "prune old pages" / "memory cleanup" | `memory_forget_sweep` |
+
+`memory_explore` is the right default for the "I want to know what's
+going on" use case — it returns a prose digest whose verbosity
+scales automatically to how long it's been since the last activity
+(< 1 h → one line; > 30 days → full catchup).
+
+### When you write a project rule, write it here
+
+If you're about to write a durable project rule ("always X", "never
+Y", "all PRs must …"), this file (CLAUDE.md / AGENTS.md) is where
+the rule belongs. ai-memory's lint pass surfaces the same hint
+automatically when a `kind: rule` page lands in `_rules/`.
+
+### Refreshing this snippet
+
+This block is maintained by ai-memory. To re-sync it with the
+latest binary's recommended copy (e.g. when new tools ship), run:
+
+```
+ai-memory install-instructions
+```
+
+It's idempotent: re-runs replace the block bracketed by
+`<!-- ai-memory:start -->` / `<!-- ai-memory:end -->` markers
+without disturbing the rest of the file.
+<!-- ai-memory:end -->
diff --git a/CLAUDE.md.bak-1779496975 b/CLAUDE.md.bak-1779496975
deleted file mode 100644
index fc233d0f..00000000
--- a/CLAUDE.md.bak-1779496975
+++ /dev/null
@@ -1,147 +0,0 @@
-# CLAUDE.md — ai-memory project directives
-
-> Read this every session before touching code. The long-form research and
-> design specs live under [`docs/`](docs/); this file is the operating rules.
-
-## What this project is
-
-A self-contained Rust binary providing long-term memory for AI coding agents
-(Claude Code, OpenAI Codex, OpenCode) over the Model Context Protocol.
-Storage = markdown-in-git wiki (source of truth) + SQLite (derived index).
-Capture = automatic via agent lifecycle hooks, never manual `write_note`.
-Consolidation = Karpathy "LLM Wiki" pattern with versioned supersession.
-
-Read [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) first for the
-operational summary. Read [`docs/design-decisions.md`](docs/design-decisions.md)
-for the full v1 spec. Read [`docs/research-karpathy-llm-wiki.md`](docs/research-karpathy-llm-wiki.md)
-for what "Karpathy-faithful" means in practice.
-
-## Stack (do not deviate without updating `docs/design-decisions.md` §4)
-
-- **Runtime:** Rust 1.95 (pinned in `rust-toolchain.toml`), edition 2024,
- resolver 3, async via `tokio`.
-- **MCP:** `rmcp` (official `modelcontextprotocol/rust-sdk`).
-- **Store:** `rusqlite` + `refinery` migrations, FTS5 in v1, `sqlite-vec` in
- v0.2. **One file**, one writer actor, one read pool.
-- **Wiki:** markdown on disk, `notify-debouncer-full` watcher with heartbeat
- + reconciliation, `git2` for versioning.
-- **HTTP:** `axum` for hook ingress + MCP HTTP/SSE.
-- **LLM:** typed clients per provider (Anthropic, OpenAI, OpenAI-compat) via
- `reqwest`. **Never** a generic gateway like LiteLLM (cognee #2840 lesson).
-- **Config:** `figment`, one read at startup, passed by `&Arc<Config>`.
-- **Logging:** `tracing` with module filters; never let the appender's own
- module log at INFO+ (agentmemory #519 lesson).
-
-## Repository layout
-
-```
-crates/
- ai-memory-core/ # domain types, errors. NO IO.
- ai-memory-store/ # SQLite, single-writer actor, migrations.
- ai-memory-wiki/ # markdown read/write, watcher, git.
- ai-memory-mcp/ # rmcp transport + tool router.
- ai-memory-hooks/ # hook payload schemas + HTTP ingress.
- ai-memory-llm/ # LlmProvider trait + 3 impls.
- ai-memory-consolidate/ # Karpathy ingest/query/lint pipeline.
- ai-memory-cli/ # `ai-memory` binary entry point.
-hooks/ # vendored hook scripts per agent.
-docker/ # Dockerfile + compose.
-docs/ # research + design (DO NOT delete).
-tests/ # workspace integration tests.
-```
-
-## Workflow rules
-
-1. **Milestone by milestone.** Do not start M(n+1) until every "Done when"
- bullet in M(n) passes. See [`docs/design-decisions.md`](docs/design-decisions.md)
- for the milestone list. No mixing.
-2. **No dead code, no half-built features.** If a feature is not finished,
- it does not land. If you must stub something, document it as `M(n) TODO`
- in the relevant module's doc-comment with the milestone number.
-3. **Tests before claiming done.** Every milestone requires:
- - `cargo fmt --all -- --check` (no diffs)
- - `cargo clippy --workspace --all-targets -- -D warnings` (no warnings)
- - `cargo test --workspace` (all green)
- - Manual exercise of the new feature against a real agent CLI when applicable.
-4. **Document the why in code, not the what.** No comments restating the line
- above; only comments explaining a constraint, an incident, or a non-obvious
- invariant.
-5. **Add a unit test before the implementation, not after.** Especially for
- parsers, ID derivation, and any retention/decay math.
-6. **Don't refactor outside the milestone.** Touch only what the current
- milestone requires; resist scope creep.
-
-## Cross-cutting invariants (carved in, never violated)
-
-These come straight from issue-tracker research on agentmemory, basic-memory
-and cognee — every one of them is in `docs/design-decisions.md` §14 with
-issue citations. **Treat any code review that violates one of these as a
-blocking issue:**
-
-1. One config-read path. No `std::env::var` outside `Config::load()`.
-2. Single-writer SQLite actor. All writes through one `mpsc` channel.
-3. Indexes commit in the same transaction as the data. No
- background-task-indexing-after-return.
-4. Typed `(WorkspaceId, ProjectId, PagePath)` identity in every layer.
-5. Hooks are fire-and-forget. Sub-second timeouts. Return 202 immediately.
-6. Privacy strip is a typed boundary (`RawHookPayload → Sanitized<Observation>`).
-7. JSON-schema structured outputs only. No XML, no `instructor`-style wrapping.
-8. `{provider, model, dim}` stored next to every embedding. Refuse on mismatch.
-9. Live-process check (`sysinfo`) before any destructive op.
-10. Atomic file writes (tmp + rename + fsync). Watcher ignores own writes.
-11. Default data dir is an absolute canonical platform path.
- Logged loudly on startup.
-12. No global singletons / `lazy_static` configs.
-13. Zero-LLM default path. LLM features opt-in via env.
-14. Tracing subscribers explicitly filter their own module.
-
-## Mistakes documented in the research — do NOT repeat
-
-- [`docs/issues-agentmemory.md`](docs/issues-agentmemory.md): install/ops
- landmines (iii-engine sidecar, distroless volumes, cwd-relative paths).
-- [`docs/issues-basic-memory.md`](docs/issues-basic-memory.md): file watcher
- pain, manual-capture friction, multi-workspace retrofit.
-- [`docs/issues-cognee.md`](docs/issues-cognee.md): LiteLLM/instructor wire
- drift, multi-store sync bugs, dependency landmines.
-
-When in doubt about a design decision, search those files for the keyword.
-
-## Quick commands
-
-```bash
-# Build everything.
-cargo build --workspace
-
-# Lint + format + test (run before every commit).
-cargo fmt --all -- --check
-cargo clippy --workspace --all-targets -- -D warnings
-cargo test --workspace
-
-# Auto-format.
-cargo fmt --all
-
-# Exercise the binary.
-./target/debug/ai-memory --version
-./target/debug/ai-memory init
-AI_MEMORY_DATA_DIR=/tmp/x ./target/debug/ai-memory init
-./target/debug/ai-memory status --json
-
-# CI parity (requires cargo-deny + cargo-audit installed).
-cargo install cargo-deny cargo-audit
-cargo deny check
-cargo audit
-```
-
-## What this project is NOT (v1 non-goals)
-
-See [`docs/design-decisions.md`](docs/design-decisions.md) §13 for the full
-list. Highlights: no multi-tenant auth, no web UI, no Postgres backend in v1,
-no alternative vector backends, no remote sync (use `git remote` on the wiki
-dir), no multimodal.
-
-## Plan & status
-
-The current execution plan is at
-[`/home/akitaonrails/.claude/plans/cuddly-moseying-karp.md`](/home/akitaonrails/.claude/plans/cuddly-moseying-karp.md)
-(local to the maintainer's `~/.claude/`).
-Live progress is tracked via the TaskList tool inside Claude Code sessions.
diff --git a/crates/ai-memory-cli/src/commands/apply_shared.rs b/crates/ai-memory-cli/src/commands/apply_shared.rs
index c5e42408..f3f6ac6e 100644
--- a/crates/ai-memory-cli/src/commands/apply_shared.rs
+++ b/crates/ai-memory-cli/src/commands/apply_shared.rs
@@ -104,19 +104,25 @@ fn backup_path_for(path: &Path) -> PathBuf {
PathBuf::from(bak)
}
-/// Tempfile + rename atomic write. Sibling tempfile so the rename
-/// is on the same filesystem (avoids cross-mount EXDEV).
+/// Tempfile + rename atomic write. The tempfile MUST land in the
+/// same directory as the target so `rename(2)` stays intra-filesystem
+/// — otherwise we get EXDEV ("Invalid cross-device link").
+///
+/// This used to fall back to `tempfile()` (i.e. `$TMPDIR`, typically
+/// `/tmp` on tmpfs) when the target had no parent component, but
+/// that breaks any relative path like `CLAUDE.md` whose parent is
+/// `""` (empty) — the project lives on a different filesystem than
+/// `/tmp` in just about every realistic setup. Treat empty parent
+/// as `.` (current directory) instead.
fn write_atomic(path: &Path, content: &str) -> Result<()> {
- let parent = path.parent().filter(|p| !p.as_os_str().is_empty());
- let mut tmp = match parent {
- Some(p) => tempfile::Builder::new()
- .prefix(".ai-memory-apply-tmp.")
- .tempfile_in(p),
- None => tempfile::Builder::new()
- .prefix(".ai-memory-apply-tmp.")
- .tempfile(),
- }
- .with_context(|| format!("creating tempfile next to {}", path.display()))?;
+ let parent = match path.parent() {
+ Some(p) if !p.as_os_str().is_empty() => p,
+ _ => Path::new("."),
+ };
+ let mut tmp = tempfile::Builder::new()
+ .prefix(".ai-memory-apply-tmp.")
+ .tempfile_in(parent)
+ .with_context(|| format!("creating tempfile next to {}", path.display()))?;
tmp.write_all(content.as_bytes())
.context("writing tempfile content")?;
tmp.as_file().sync_data().context("fsync tempfile")?;