Skip to content

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

Rust

audit fixes (M18 part 2): payload + MCP error-path tests + render_shared

AkitaOnRails45c4dd4c8204
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 192d34ae..f4389e86 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -10,9 +10,9 @@
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
-use serde_json::json;
use crate::cli::{AgentChoice, InstallHooksArgs};
+use crate::commands::render_shared::build_claude_code_payload;
use crate::config::Config;
/// Run the `install-hooks` subcommand.
@@ -102,66 +102,15 @@ fn repo_root_guess() -> Option<PathBuf> {
.and_then(|p| p.parent()?.parent()?.parent().map(Path::to_path_buf))
}
-/// The seven Claude Code hook events ai-memory wires up, paired with
-/// the vendored script filename. Used by both `install-hooks` and
-/// `setup-agent`.
-pub(crate) const CLAUDE_CODE_EVENTS: [(&str, &str); 7] = [
- ("SessionStart", "session-start.sh"),
- ("UserPromptSubmit", "user-prompt-submit.sh"),
- ("PreToolUse", "pre-tool-use.sh"),
- ("PostToolUse", "post-tool-use.sh"),
- ("PreCompact", "pre-compact.sh"),
- ("Stop", "stop.sh"),
- ("SessionEnd", "session-end.sh"),
-];
-
-/// Build the Claude Code settings-fragment JSON for the given paths.
-///
-/// `emit_root` is the directory the JSON snippet will reference as
-/// the home of the hook scripts. It does NOT need to exist on the
-/// filesystem this binary is running on — that's exactly the docker
-/// case where `setup-agent` writes to a mounted volume and emits
-/// host-side paths.
-///
-/// `auth_token`, when set, lands in each hook's `env` block as
-/// `AI_MEMORY_AUTH_TOKEN`, which the shell scripts forward as
-/// `Authorization: Bearer …` to the server.
-pub(crate) fn build_claude_code_payload(
- emit_root: &Path,
- server_url: &str,
- auth_token: Option<&str>,
-) -> serde_json::Value {
- let mut hooks_block = serde_json::Map::new();
- for (event, script) in CLAUDE_CODE_EVENTS {
- let abs = emit_root.join(script);
- let mut env = serde_json::Map::new();
- env.insert(
- "AI_MEMORY_HOOK_URL".into(),
- serde_json::Value::String(server_url.to_string()),
- );
- if let Some(t) = auth_token {
- env.insert(
- "AI_MEMORY_AUTH_TOKEN".into(),
- serde_json::Value::String(t.to_string()),
- );
- }
- hooks_block.insert(
- event.into(),
- json!([{
- "command": abs.to_string_lossy().into_owned(),
- "env": env,
- }]),
- );
- }
- json!({ "hooks": hooks_block })
-}
+// CLAUDE_CODE_EVENTS + build_claude_code_payload now live in
+// `super::render_shared`, shared with `setup-agent`.
fn render_claude_code(hooks_dir: &Path, server_url: &str, auth_token: Option<&str>) -> Result<()> {
// Soft check: warn (don't bail) if a script is missing. The user
// may be running this command inside docker against a host path
// that exists only on the host's filesystem — bailing would
// sabotage the docker-only flow `setup-agent` enables.
- for (_, script) in CLAUDE_CODE_EVENTS {
+ for (_, script) in super::render_shared::CLAUDE_CODE_EVENTS {
let abs = hooks_dir.join(script);
if !abs.exists() {
eprintln!(
diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rs
index 37c6f555..6ccb6f20 100644
--- a/crates/ai-memory-cli/src/commands/install_mcp.rs
+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs
@@ -19,6 +19,7 @@ use anyhow::Result;
use serde_json::json;
use crate::cli::{InstallMcpArgs, McpClient};
+use crate::commands::render_shared::bearer_header_value as bearer_header_value_shared;
use crate::config::Config;
/// Run the `install-mcp` subcommand.
@@ -41,11 +42,12 @@ pub fn run(_config: &Config, args: InstallMcpArgs) -> Result<()> {
Ok(())
}
-/// Render an `Authorization: Bearer <token>` header value if a token
-/// is set; returns `None` otherwise. Centralised so every renderer
-/// makes the same choice.
+/// Thin shim so the renderers can call `bearer_header_value(args)`
+/// without spelling out `args.auth_token.as_deref()` every time.
+/// Delegates to the shared `render_shared::bearer_header_value` which
+/// takes a raw `Option<&str>` so other commands can call it too.
fn bearer_header_value(args: &InstallMcpArgs) -> Option<String> {
- args.auth_token.as_deref().map(|t| format!("Bearer {t}"))
+ bearer_header_value_shared(args.auth_token.as_deref())
}
fn render_claude_code(args: &InstallMcpArgs) -> Result<String> {
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index a9aafdd5..5172afb7 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -10,6 +10,7 @@ pub mod install_hooks;
pub mod install_mcp;
pub mod lint;
pub mod llm_test;
+pub mod render_shared;
pub mod reset;
pub mod restore;
pub mod search;
diff --git a/crates/ai-memory-cli/src/commands/render_shared.rs b/crates/ai-memory-cli/src/commands/render_shared.rs
new file mode 100644
index 00000000..0c7a6167
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@ -0,0 +1,161 @@
+//! Shared rendering helpers for the install-* / setup-agent commands.
+//!
+//! These three subcommands (`install-hooks`, `install-mcp`,
+//! `setup-agent`) all emit configuration snippets that share two
+//! pieces of state:
+//!
+//! 1. The seven Claude Code lifecycle-hook events ai-memory wires
+//! up — kept in sync between hook-bundle generation (setup-agent)
+//! and JSON-config rendering (install-hooks).
+//! 2. The optional `Authorization: Bearer <token>` header used by
+//! both MCP client configs (install-mcp) and hook env blocks
+//! (install-hooks / setup-agent).
+//!
+//! Each subcommand still owns its per-client output formatting (the
+//! commentary that frames the JSON snippet differs from client to
+//! client and is the part that makes the printout readable). What
+//! lives here is only the *data* both consume.
+
+use std::path::Path;
+
+use serde_json::json;
+
+/// Claude Code lifecycle events ai-memory hooks. Each pair is
+/// `(event-name-in-Claude-Code-settings, hook-script-filename)`.
+///
+/// Adding a hook event means updating this list AND adding the
+/// matching `hooks/{claude-code,codex,opencode}/<filename>` script —
+/// the e2e test + the generator in `bin/regen-hooks` (if added) both
+/// key off this constant.
+pub(crate) const CLAUDE_CODE_EVENTS: [(&str, &str); 7] = [
+ ("SessionStart", "session-start.sh"),
+ ("UserPromptSubmit", "user-prompt-submit.sh"),
+ ("PreToolUse", "pre-tool-use.sh"),
+ ("PostToolUse", "post-tool-use.sh"),
+ ("PreCompact", "pre-compact.sh"),
+ ("Stop", "stop.sh"),
+ ("SessionEnd", "session-end.sh"),
+];
+
+/// Format an `Authorization: Bearer <token>` header value, or `None`
+/// when no token is supplied. Used by every MCP client renderer in
+/// `install-mcp` and every hook-config renderer that wants to
+/// embed an auth token.
+///
+/// Centralised because the prefix is `Bearer` per RFC 7235 / OAuth
+/// 2.1 / the MCP spec — if anyone ever decides to support a
+/// different scheme (e.g. `DPoP`) this is the one place that
+/// changes.
+#[must_use]
+pub(crate) fn bearer_header_value(token: Option<&str>) -> Option<String> {
+ token.map(|t| format!("Bearer {t}"))
+}
+
+/// Build the Claude Code `settings.json` fragment that wires the
+/// seven hooks. Used by both:
+/// - `install-hooks --agent claude-code` (script paths are
+/// wherever the user told us via `--hooks-dir`)
+/// - `setup-agent --agent claude-code` (script paths are where
+/// `--host-prefix` says they'll live on the host)
+///
+/// `emit_root` is the directory that will contain `*.sh`; it is
+/// expected to be an absolute path on the system that will run the
+/// agent CLI. This function does NOT verify the path exists on the
+/// local filesystem — that decision belongs to the caller because
+/// the docker case legitimately renders host paths that don't yet
+/// exist in the container.
+///
+/// `auth_token`, when set, lands in each hook's `env` block as
+/// `AI_MEMORY_AUTH_TOKEN`, which the shell scripts forward as
+/// `Authorization: Bearer …` to the server.
+#[must_use]
+pub(crate) fn build_claude_code_payload(
+ emit_root: &Path,
+ server_url: &str,
+ auth_token: Option<&str>,
+) -> serde_json::Value {
+ let mut hooks_block = serde_json::Map::new();
+ for (event, script) in CLAUDE_CODE_EVENTS {
+ let abs = emit_root.join(script);
+ let mut env = serde_json::Map::new();
+ env.insert("AI_MEMORY_HOOK_URL".into(), json!(server_url));
+ if let Some(t) = auth_token {
+ env.insert("AI_MEMORY_AUTH_TOKEN".into(), json!(t));
+ }
+ hooks_block.insert(
+ event.into(),
+ json!([{
+ "command": abs.to_string_lossy().into_owned(),
+ "env": env,
+ }]),
+ );
+ }
+ json!({ "hooks": hooks_block })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::path::PathBuf;
+
+ #[test]
+ fn bearer_header_is_none_when_no_token() {
+ assert!(bearer_header_value(None).is_none());
+ }
+
+ #[test]
+ fn bearer_header_prefixes_with_bearer() {
+ let h = bearer_header_value(Some("abc123")).unwrap();
+ assert_eq!(h, "Bearer abc123");
+ }
+
+ #[test]
+ fn claude_code_payload_has_seven_events() {
+ let root = PathBuf::from("/host/hooks/claude-code");
+ let v = build_claude_code_payload(&root, "http://localhost:49374", None);
+ let hooks = v.get("hooks").and_then(|h| h.as_object()).unwrap();
+ assert_eq!(hooks.len(), 7);
+ for (event, _) in CLAUDE_CODE_EVENTS {
+ assert!(hooks.contains_key(event), "missing event {event}");
+ }
+ }
+
+ #[test]
+ fn claude_code_payload_embeds_auth_token_when_provided() {
+ let root = PathBuf::from("/host/hooks/claude-code");
+ let v = build_claude_code_payload(&root, "http://localhost:49374", Some("tok"));
+ let session_start = v
+ .pointer("/hooks/SessionStart/0/env/AI_MEMORY_AUTH_TOKEN")
+ .and_then(|s| s.as_str())
+ .unwrap();
+ assert_eq!(session_start, "tok");
+ }
+
+ #[test]
+ fn claude_code_payload_omits_auth_token_when_absent() {
+ let root = PathBuf::from("/host/hooks/claude-code");
+ let v = build_claude_code_payload(&root, "http://localhost:49374", None);
+ // The env block exists (HOOK_URL is always there) but
+ // AI_MEMORY_AUTH_TOKEN is absent.
+ let env = v
+ .pointer("/hooks/SessionStart/0/env")
+ .and_then(|e| e.as_object())
+ .unwrap();
+ assert!(env.contains_key("AI_MEMORY_HOOK_URL"));
+ assert!(!env.contains_key("AI_MEMORY_AUTH_TOKEN"));
+ }
+
+ #[test]
+ fn claude_code_payload_emits_absolute_paths() {
+ let root = PathBuf::from("/home/user/.ai-memory/hooks/claude-code");
+ let v = build_claude_code_payload(&root, "http://localhost:49374", None);
+ let cmd = v
+ .pointer("/hooks/SessionStart/0/command")
+ .and_then(|s| s.as_str())
+ .unwrap();
+ assert_eq!(
+ cmd,
+ "/home/user/.ai-memory/hooks/claude-code/session-start.sh"
+ );
+ }
+}
diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rs
index 167091c4..45a50eaa 100644
--- a/crates/ai-memory-cli/src/commands/setup_agent.rs
+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs
@@ -35,7 +35,7 @@ use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use crate::cli::{AgentChoice, SetupAgentArgs};
-use crate::commands::install_hooks::{CLAUDE_CODE_EVENTS, build_claude_code_payload};
+use crate::commands::render_shared::{CLAUDE_CODE_EVENTS, build_claude_code_payload};
use crate::config::Config;
/// Run the `setup-agent` subcommand.
diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rs
index b8c961e5..9a795415 100644
--- a/crates/ai-memory-hooks/src/payload.rs
+++ b/crates/ai-memory-hooks/src/payload.rs
@@ -229,4 +229,120 @@ mod tests {
assert_eq!(env.cwd.as_deref(), Some("/tmp/x"));
assert_eq!(env.title_hint.as_deref(), Some("claude-sonnet-4-6"));
}
+
+ /// Alternative agent-name spellings all map to the same canonical
+ /// AgentKind. The hook scripts and the test e2e shim send slightly
+ /// different strings for historical reasons; this asserts we
+ /// remain forgiving.
+ #[test]
+ fn agent_name_aliases_all_map_correctly() {
+ assert_eq!(parse_agent("claude-code"), AgentKind::ClaudeCode);
+ assert_eq!(parse_agent("claude_code"), AgentKind::ClaudeCode);
+ assert_eq!(parse_agent("claude"), AgentKind::ClaudeCode);
+ assert_eq!(parse_agent("codex"), AgentKind::Codex);
+ assert_eq!(parse_agent("opencode"), AgentKind::OpenCode);
+ assert_eq!(parse_agent("open-code"), AgentKind::OpenCode);
+ // Anything else is `Other`. Critical for the hook router:
+ // a typo in the query string must not crash, it just gets
+ // attributed to the catch-all bucket.
+ assert_eq!(parse_agent(""), AgentKind::Other);
+ assert_eq!(parse_agent("CLAUDE-CODE"), AgentKind::Other); // case-sensitive on purpose
+ assert_eq!(parse_agent("gemini-cli"), AgentKind::Other);
+ assert_eq!(parse_agent("../../etc/passwd"), AgentKind::Other);
+ }
+
+ /// An empty body is legitimate (some hook events carry no
+ /// payload). Envelope extraction must produce sane defaults
+ /// rather than panicking.
+ #[test]
+ fn envelope_tolerates_empty_body() {
+ let q = HookQuery {
+ event: "stop".into(),
+ agent: Some("claude-code".into()),
+ };
+ let env = HookEnvelope::from_query_and_body(q, serde_json::json!({}));
+ assert_eq!(env.event, HookEvent::Stop);
+ assert!(env.session_id.is_none());
+ assert!(env.cwd.is_none());
+ assert!(env.title_hint.is_none());
+ assert!(env.body_excerpt.is_none());
+ }
+
+ /// Body is well-formed JSON but the expected `session_id` /
+ /// `cwd` keys are missing — extraction returns None per key.
+ #[test]
+ fn envelope_missing_expected_fields() {
+ let q = HookQuery {
+ event: "user-prompt".into(),
+ agent: Some("claude-code".into()),
+ };
+ let raw = serde_json::json!({ "garbage": 42 });
+ let env = HookEnvelope::from_query_and_body(q, raw);
+ assert_eq!(env.event, HookEvent::UserPrompt);
+ assert!(env.session_id.is_none());
+ assert!(env.cwd.is_none());
+ }
+
+ /// Body is a JSON primitive (string / null / number) rather
+ /// than an object. The extractors must short-circuit cleanly.
+ /// This guards against an upstream that POSTs a stringified
+ /// payload by mistake.
+ #[test]
+ fn envelope_accepts_non_object_body() {
+ let q = HookQuery {
+ event: "post-tool-use".into(),
+ agent: Some("claude-code".into()),
+ };
+ for raw in [
+ serde_json::json!(null),
+ serde_json::json!("a stringy payload"),
+ serde_json::json!(42),
+ serde_json::json!([1, 2, 3]),
+ ] {
+ let env = HookEnvelope::from_query_and_body(q.clone(), raw);
+ assert!(
+ env.session_id.is_none(),
+ "no session_id from non-object body"
+ );
+ assert!(env.cwd.is_none(), "no cwd from non-object body");
+ }
+ }
+
+ /// Empty `agent` query param maps to Other (rather than panic
+ /// or default to ClaudeCode). The hook router uses this for the
+ /// attribution column, so we want it consistent.
+ #[test]
+ fn missing_agent_query_param_maps_to_other() {
+ let q = HookQuery {
+ event: "session-end".into(),
+ agent: None,
+ };
+ let env = HookEnvelope::from_query_and_body(q, serde_json::json!({}));
+ assert_eq!(env.agent, AgentKind::Other);
+ }
+
+ /// Title-hint extraction must truncate at the first newline (the
+ /// "first line" rule used everywhere in the wiki log + handoff
+ /// surfaces) and cap at 80 chars to keep observation titles
+ /// scannable in the log.md heading.
+ #[test]
+ fn user_prompt_title_truncates_at_newline_and_at_max_chars() {
+ let q = HookQuery {
+ event: "user-prompt".into(),
+ agent: Some("claude-code".into()),
+ };
+ // Multi-line prompt → title is the first line only.
+ let env = HookEnvelope::from_query_and_body(
+ q.clone(),
+ serde_json::json!({ "prompt": "first line\nsecond line should be lost" }),
+ );
+ assert_eq!(env.title_hint.as_deref(), Some("first line"));
+
+ // Very long single line → truncated with ellipsis.
+ let long = "x".repeat(200);
+ let env = HookEnvelope::from_query_and_body(q, serde_json::json!({ "prompt": long }));
+ let title = env.title_hint.unwrap();
+ assert!(title.chars().count() <= 80);
+ assert!(title.ends_with('…'));
+ }
}
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 77d02648..50cb14c3 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -646,4 +646,124 @@ mod tests {
.unwrap();
assert!(again_text.contains("\"handoff\": null"));
}
+
+ // ----------------------------------------------------------------
+ // Error / mis-configured paths — caught at the tool boundary so the
+ // agent sees a clean McpError instead of a panic.
+ // ----------------------------------------------------------------
+
+ /// `memory_consolidate` is opt-in via the LLM provider. With no
+ /// consolidator wired, the tool must reject the call with a
+ /// clear "not configured" error — not panic.
+ #[tokio::test]
+ async fn memory_consolidate_without_provider_errors_cleanly() {
+ let (_tmp, _store, server, _ws, _pj) = setup_server().await;
+ let err = server
+ .memory_consolidate(Parameters(ConsolidateArgs {
+ session_id: "00000000-0000-0000-0000-000000000000".into(),
+ dry_run: Some(true),
+ multi_page: Some(false),
+ }))
+ .await
+ .expect_err("must reject when no consolidator is configured");
+ let msg = format!("{err:?}");
+ assert!(
+ msg.contains("not configured"),
+ "error should mention configuration: {msg}",
+ );
+ }
+
+ /// `memory_lint` reads the wiki to build its candidate set. With
+ /// no wiki wired, it must error cleanly.
+ #[tokio::test]
+ async fn memory_lint_without_wiki_errors_cleanly() {
+ let (_tmp, _store, server, _ws, _pj) = setup_server().await;
+ let err = server
+ .memory_lint(Parameters(LintArgs {
+ dry_run: Some(true),
+ }))
+ .await
+ .expect_err("must reject when wiki is not attached");
+ let msg = format!("{err:?}");
+ // The exact phrasing isn't load-bearing; we just need
+ // SOMETHING that names the missing dependency so the agent's
+ // model has a chance of choosing a different tool.
+ assert!(
+ msg.contains("wiki") || msg.contains("not configured"),
+ "error should explain the missing wiki: {msg}",
+ );
+ }
+
+ /// `memory_handoff_accept` with no pending handoff returns a
+ /// happy-path `{"handoff": null}` payload (NOT an error). This
+ /// is the documented contract — the agent can call accept on
+ /// every session-start without worrying about empty-queue errors.
+ #[tokio::test]
+ async fn memory_handoff_accept_when_none_pending_returns_null() {
+ let (_tmp, _store, server, _ws, _pj) = setup_server().await;
+ let result = server
+ .memory_handoff_accept(Parameters(HandoffAcceptArgs { cwd: None }))
+ .await
+ .expect("empty-queue must be Ok, not Err");
+ let text = result
+ .content
+ .first()
+ .and_then(|c| c.as_text())
+ .map(|t| t.text.clone())
+ .unwrap();
+ assert!(
+ text.contains("\"handoff\": null"),
+ "expected handoff=null in: {text}",
+ );
+ }
+
+ /// `memory_query` clamps `limit` into [1, 100]. Anyone sending
+ /// limit=10000 (DoS attempt or accidental overflow) gets the
+ /// max instead of an unbounded scan.
+ #[tokio::test]
+ async fn memory_query_clamps_outlandish_limit() {
+ let (_tmp, _store, server, _ws, _pj) = setup_server().await;
+ // The clamp is internal; the test verifies the call succeeds
+ // with a sane response. (We don't have 10k pages, so the
+ // hit count is small — we just need NOT to error.)
+ let result = server
+ .memory_query(Parameters(QueryArgs {
+ query: "Karpathy".into(),
+ limit: Some(99_999),
+ }))
+ .await
+ .expect("oversized limit should be clamped, not refused");
+ let text = result
+ .content
+ .first()
+ .and_then(|c| c.as_text())
+ .map(|t| t.text.clone())
+ .unwrap();
+ // Returns valid JSON even on huge limit.
+ let _: serde_json::Value = serde_json::from_str(&text).unwrap();
+ }
+
+ /// `memory_query` with malformed FTS5 must return a clean
+ /// McpError (NOT panic, NOT bare SQLite error). The FTS5
+ /// tokenizer treats `-` as a NOT operator and some characters
+ /// as syntax; an unbalanced quote is the simplest reproducer.
+ #[tokio::test]
+ async fn memory_query_malformed_fts5_returns_error() {
+ let (_tmp, _store, server, _ws, _pj) = setup_server().await;
+ let err = server
+ .memory_query(Parameters(QueryArgs {
+ query: "\"unbalanced".into(),
+ limit: Some(10),
+ }))
+ .await;
+ // Either a tidy 0-hit Ok (FTS5 is occasionally lenient) or
+ // an Err — both are acceptable. A panic is not.
+ if let Err(e) = err {
+ let msg = format!("{e:?}");
+ assert!(
+ !msg.is_empty(),
+ "error must carry diagnostic text for the agent",
+ );
+ }
+ }
}
diff --git a/docs/v0.3-roadmap.md b/docs/v0.3-roadmap.md
new file mode 100644
index 00000000..72651678
--- /dev/null
+++ b/docs/v0.3-roadmap.md
@@ -0,0 +1,112 @@
+# v0.3 roadmap
+
+Captured items deferred from v0.2 and ideas surfaced post-M10.
+Nothing here is committed to a milestone yet; this is a parking lot.
+
+## Bigger features
+
+### Rule-vs-fact disambiguation in consolidation
+
+**Problem.** Users sometimes type durable project rules into the
+agent — "don't forget to never add a new function without a unit
+test", "we always run lint before merging", "memory mustn't store
+PII". These end up as ordinary observations in ai-memory. But they'd
+be more useful as instructions in the project's `CLAUDE.md` /
+`AGENTS.md`, because:
+
+- Rules need to fire on every relevant action; ai-memory queries
+ fire when the agent thinks to call them.
+- Project-instruction files are checked into version control and
+ visible to the whole team.
+
+**Sketch.** Extend the consolidator's structured-output schema to
+classify each surfaced observation into `{decision, fact, rule,
+gotcha}`. Rule-tagged items land in a separate page
+`wiki/_rules/uncommitted.md` AND surface a lint finding:
+
+> "This rule isn't in your project's CLAUDE.md — consider adding it
+> there so the agent sees it on every turn, not just when it
+> searches memory."
+
+Detection heuristics: starts with `always`, `never`, `don't`,
+`remember to`, `before X always`, `as a rule`, or contains
+`(rule|policy|convention)`. Easy, ~50 lines plus the lint surface.
+
+The output is a *suggestion only* — ai-memory never auto-edits a
+user's CLAUDE.md / AGENTS.md / project instructions file.
+
+### Bootstrap an existing project's history into the wiki
+
+**Problem.** Today ai-memory starts empty for any project. For
+existing projects with months of decisions in `git log`, `docs/`,
+`README.md`, code comments — that's a lot of warm context the user
+already paid for once, and we throw it away.
+
+**Sketch.** A `ai-memory bootstrap` one-shot subcommand. Inputs:
+
+- `git log --oneline -p` filtered to commits with substantive
+ messages (e.g. > 100 chars body, conventional-commit prefix, or
+ matching `^(feat|fix|refactor|design):`).
+- README + `docs/*.md` + `CLAUDE.md` if present.
+- Module-level doc-comments from the codebase (`find . -name
+ "*.rs" | xargs head -30`, language-aware).
+
+LLM consolidates these into:
+
+- `wiki/concepts/<topic>.md` per recurring theme
+- `wiki/decisions/0001-…md` per ADR-shaped commit
+- A bootstrap handoff page summarising "what I learned about this
+ project"
+
+Bootstrap pages get `tier: bootstrap` in their frontmatter so the
+lint pass treats them as lower-confidence than session-grown pages,
+and they participate normally in the decay sweep.
+
+**Risk.** LLM-fabricated detail polluting the wiki. Mitigations:
+the user reviews + commits the wiki tree before keeping (it's a git
+repo); bootstrap pages are explicitly tagged so a `forget-sweep` can
+target them; the LLM is instructed to mark uncertain claims with a
+`(needs verification)` suffix.
+
+### CI matrix tightening
+
+Currently `ci.yml` runs fmt + clippy + test + cargo-deny + cargo-
+audit + gitleaks on `ubuntu-latest` only. Worth adding:
+
+- macOS runner (catches stat / SELinux-label assumptions)
+- A `cargo build --release` step so we don't ship code that fails
+ release-mode optimisation
+- A docker-build smoke step that confirms `docker run --rm
+ $IMAGE --version` works after every push
+
+## Smaller polish
+
+### Hook scripts as a generated artefact
+
+The 21 hook scripts live in `hooks/*/*.sh` as files. There's no
+regenerator. The shape is identical across agents (only
+`agent=open-code` vs `agent=codex` etc. differs). A `bin/regen-hooks`
+script that templates them from `CLAUDE_CODE_EVENTS` + a per-agent
+name would let us add a new event in one place.
+
+### Consolidator prompt templating
+
+Both `build_batch_request` and `build_request` in
+`crates/ai-memory-consolidate/src/consolidator.rs` `push_str` their
+way to a prompt. Constants are fine for two prompts. If the count
+grows to four+ a small templating helper would earn its keep.
+
+### `Handoff` field grouping
+
+The struct has 16 public fields. The audit suggested grouping into
+nested sub-structs. Not urgent; would force accessor churn across
+the codebase for no operational win. Revisit if/when adding a 17th
+field.
+
+### `cargo install ai-memory` + `mise use -g github:akitaonrails/ai-memory`
+
+Today the only install paths are docker + `git clone + cargo
+build`. ai-jail ships a release-binary GitHub Actions workflow that
+publishes to crates.io + GitHub Releases (tar.gz + sha256 per OS
+target). Mirror that pattern for users who want a host-side binary
+without the rust toolchain.