Skip to content

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

Rust

fix: harden config and opencode capture

AkitaOnRailsbb0932e48013
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 00000000..c784d61d
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,59 @@
+<!-- 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?" — and you see a `📥 ai-memory: pending handoff` block in your context | already done — answer from that block; do NOT re-call `memory_handoff_accept` |
+| "where did we leave off?" — and no such block is visible | `memory_handoff_accept` (rare; the SessionStart hook usually got there first) |
+| "save context for the next session" / wrapping up | `memory_handoff_begin` (terse summary; put detail in `open_questions` + `next_steps` bullets) |
+| "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 rules file (CLAUDE.md for Claude Code;
+AGENTS.md for Codex / OpenCode / Cursor / Gemini CLI; whichever
+convention your agent uses) is where it 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. Two ways to refresh it with
+the latest binary's recommended copy:
+
+- **From the agent** (no terminal needed): ask "refresh the ai-memory
+ routing in this project" — the agent calls
+ `memory_install_self_routing`, picks the right filename for itself
+ (Claude Code → `CLAUDE.md`; Codex / OpenCode / Cursor / Gemini →
+ `AGENTS.md`), and uses its Write / Edit tool to land the block.
+- **From the CLI**: `ai-memory install-instructions` (defaults to
+ `CLAUDE.md`; pass `--target AGENTS.md` for non-Claude agents).
+
+Both are 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/crates/ai-memory-cli/src/auth.rs b/crates/ai-memory-cli/src/auth.rs
index 23cecadf..6a78070f 100644
--- a/crates/ai-memory-cli/src/auth.rs
+++ b/crates/ai-memory-cli/src/auth.rs
@@ -380,6 +380,23 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK);
}
+ #[tokio::test]
+ async fn bearer_header_takes_precedence_over_cookie() {
+ let r = router_with_auth(Some("right-token"));
+ let resp = r
+ .oneshot(
+ Request::builder()
+ .uri("/probe")
+ .header("Authorization", "Bearer wrong-token")
+ .header("Cookie", "ai_memory_auth=right-token")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
+ }
+
#[tokio::test]
async fn cookie_with_wrong_token_fails() {
let r = router_with_auth(Some("right-token"));
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index cff09958..eac6872b 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -10,9 +10,9 @@ use clap::{Args, Parser, Subcommand};
pub struct Cli {
/// Override the data directory.
///
- /// Defaults to a platform path under `dirs::data_local_dir()`. Also
- /// settable via the `AI_MEMORY_DATA_DIR` environment variable.
- #[arg(long, env = "AI_MEMORY_DATA_DIR", global = true)]
+ /// Defaults to a platform path under `dirs::data_local_dir()`. The
+ /// config loader also honours `AI_MEMORY_DATA_DIR`.
+ #[arg(long, global = true)]
pub data_dir: Option<PathBuf>,
/// Path to an explicit config file (defaults to `<data_dir>/config.toml`).
@@ -105,8 +105,8 @@ pub struct ReorgArgs {
/// Arguments for `purge-project`.
#[derive(Debug, Args)]
pub struct PurgeProjectArgs {
- /// Workspace name. Defaults to "default".
- #[arg(long, default_value = "default")]
+ /// Workspace name. Defaults to `default`.
+ #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
pub workspace: String,
/// Project name. When omitted, auto-derived from the basename of
/// the current git repo root (or CWD if no git repo).
@@ -121,8 +121,8 @@ pub struct PurgeProjectArgs {
/// Arguments for `rename-project`.
#[derive(Debug, Args)]
pub struct RenameProjectArgs {
- /// Workspace name. Defaults to "default".
- #[arg(long, default_value = "default")]
+ /// Workspace name. Defaults to `default`.
+ #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
pub workspace: String,
/// Current project name. When omitted, auto-derives from the
/// basename of the current git repo root (or CWD) — handy when
@@ -168,7 +168,7 @@ pub struct BootstrapArgs {
pub repo_path: Option<PathBuf>,
/// Workspace name. Defaults to `default` (the single workspace
/// all hook-captured sessions land in today).
- #[arg(long, default_value = "default")]
+ #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
pub workspace: String,
/// Project name. When omitted, auto-derived from the basename of
/// the resolved repo path — same heuristic the hook router uses
@@ -242,11 +242,11 @@ pub struct SetupAgentArgs {
#[arg(long)]
pub host_prefix: Option<PathBuf>,
/// MCP / hook ingress URL the agent should POST to.
- #[arg(long, default_value = "http://127.0.0.1:49374")]
+ #[arg(long, default_value_t = crate::config::DEFAULT_SERVER_URL.to_string())]
pub server_url: String,
- /// Bearer token embedded into each hook's env block. Picked up
- /// from `AI_MEMORY_AUTH_TOKEN` if unset.
- #[arg(long, env = "AI_MEMORY_AUTH_TOKEN", hide_env_values = true)]
+ /// Bearer token embedded into each hook's env block. When omitted,
+ /// uses the token resolved by the config loader.
+ #[arg(long, hide_env_values = true)]
pub auth_token: Option<String>,
/// Source directory for the embedded hook bundle. Defaults to
/// `/usr/local/share/ai-memory/hooks` (the docker image's
@@ -288,7 +288,7 @@ pub struct SearchArgs {
/// FTS5 query string (e.g. `"karpathy wiki"` or `quick OR slow`).
pub query: String,
/// Workspace name. Defaults to `default`.
- #[arg(long, default_value = "default")]
+ #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
pub workspace: String,
/// Project name. When omitted, auto-derived from the current project.
#[arg(long)]
@@ -342,8 +342,8 @@ pub enum AgentChoice {
/// Google Gemini CLI — JSON-config hooks in `~/.gemini/settings.json`.
GeminiCli,
/// OpenCode (open-source coding agent) — TypeScript plugin hooks
- /// under `~/.config/opencode/plugins/`. Print-only for now; the
- /// plugin generator lands in a follow-up commit.
+ /// under `~/.config/opencode/plugins/`. `--apply` writes the plugin
+ /// file directly; restart OpenCode for it to load.
///
/// The `opencode` (no hyphen) alias matches both the staged hook
/// dir on disk (`~/.local/share/ai-memory/hooks/opencode/`) and
@@ -418,7 +418,7 @@ pub struct EmbedArgs {
#[arg(long)]
pub force: bool,
/// Workspace name (auto-created if absent).
- #[arg(long, default_value = "default")]
+ #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
pub workspace: String,
/// Project name. When omitted, auto-derived from the basename of
/// the current git repo root (or CWD if no git repo). Matches the
@@ -435,7 +435,7 @@ pub struct ForgetSweepArgs {
#[arg(long)]
pub dry_run: bool,
/// Workspace name (auto-created if absent).
- #[arg(long, default_value = "default")]
+ #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
pub workspace: String,
/// Project name. When omitted, auto-derived from the basename of
/// the current git repo root (or CWD if no git repo).
@@ -455,7 +455,7 @@ pub struct LintArgs {
#[arg(long)]
pub no_llm: bool,
/// Workspace name (auto-created if absent).
- #[arg(long, default_value = "default")]
+ #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
pub workspace: String,
/// Project name. When omitted, auto-derived from the basename of
/// the current git repo root (or CWD if no git repo).
@@ -476,10 +476,10 @@ pub struct LlmTestArgs {
#[arg(long)]
pub prompt: String,
/// Base URL override (required for openai-compat).
- #[arg(long, env = "LLM_BASE_URL")]
+ #[arg(long)]
pub base_url: Option<String>,
/// Optional API key override (otherwise pulled from env).
- #[arg(long, env = "LLM_API_KEY", hide_env_values = true)]
+ #[arg(long, hide_env_values = true)]
pub api_key: Option<String>,
}
@@ -491,24 +491,23 @@ pub struct InstallHooksArgs {
pub agent: AgentChoice,
/// Filesystem root that contains the vendored hook scripts (defaults
/// to the repo's `hooks/` if known, else `/usr/local/share/ai-memory/hooks`).
+ /// Ignored for OpenCode, whose integration is a generated TypeScript plugin.
#[arg(long)]
pub hooks_dir: Option<PathBuf>,
/// Server URL the hooks will POST to.
- #[arg(long, default_value = "http://127.0.0.1:49374")]
+ #[arg(long, default_value_t = crate::config::DEFAULT_SERVER_URL.to_string())]
pub server_url: String,
/// Bearer token to embed in the hook config's `env` block. When
/// set, every hook call carries `Authorization: Bearer <token>`,
/// matching what the server requires when AI_MEMORY_AUTH_TOKEN
/// is set there. Generate one with `ai-memory generate-auth-token`.
- #[arg(long, env = "AI_MEMORY_AUTH_TOKEN", hide_env_values = true)]
+ #[arg(long, hide_env_values = true)]
pub auth_token: Option<String>,
- /// **Mutate** ~/.claude/settings.json in place instead of just
- /// printing the snippet. Idempotent — replaces the seven hook
- /// entries (SessionStart, UserPromptSubmit, …) and preserves
- /// any other hook config the user has. Only supported for
- /// `--agent claude-code` today; Codex / OpenCode hook config
- /// formats are still in flux upstream, so they keep the print
- /// path. A timestamped backup is written next to the original.
+ /// **Mutate** the selected agent's hook config in place instead of
+ /// printing the snippet/plugin. Idempotent — replaces the ai-memory
+ /// hook entries or generated plugin and preserves unrelated config
+ /// where the agent format supports merging. A timestamped backup is
+ /// written next to the original before each modifying write.
#[arg(long)]
pub apply: bool,
/// Override the settings.json path (auto-detected as
@@ -524,7 +523,7 @@ pub struct InstallMcpArgs {
#[arg(long, value_enum, default_value_t = McpClient::ClaudeCode)]
pub client: McpClient,
/// MCP HTTP endpoint URL the client should connect to.
- #[arg(long, default_value = "http://127.0.0.1:49374/mcp")]
+ #[arg(long, default_value_t = crate::config::DEFAULT_MCP_URL.to_string())]
pub server_url: String,
/// Friendly name the client should show for this server entry.
#[arg(long, default_value = "ai-memory")]
@@ -532,8 +531,8 @@ pub struct InstallMcpArgs {
/// Bearer token to embed in the client config. When set, the
/// rendered snippet includes an `Authorization: Bearer <token>`
/// header so the client can authenticate against a server that
- /// requires it. Picked up from `AI_MEMORY_AUTH_TOKEN` if unset.
- #[arg(long, env = "AI_MEMORY_AUTH_TOKEN", hide_env_values = true)]
+ /// requires it. When omitted, uses the token resolved by the config loader.
+ #[arg(long, hide_env_values = true)]
pub auth_token: Option<String>,
/// **Mutate** the client's config file in place instead of just
/// printing the snippet. Idempotent: replaces any existing entry
@@ -570,10 +569,10 @@ pub struct ServeArgs {
#[arg(long)]
pub no_watcher: bool,
/// Workspace name (auto-created).
- #[arg(long, default_value = "default")]
+ #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
pub workspace: String,
/// Project name within the workspace (auto-created).
- #[arg(long, default_value = "scratch")]
+ #[arg(long, default_value_t = crate::config::DEFAULT_PROJECT.to_string())]
pub project: String,
/// Mount the read-only wiki browser at /web. Off by default. When
/// enabled, anyone who can reach the MCP endpoint can also browse
@@ -616,9 +615,9 @@ pub struct WritePageArgs {
#[arg(long)]
pub pinned: bool,
/// Workspace name (auto-created if absent).
- #[arg(long, default_value = "default")]
+ #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
pub workspace: String,
/// Project name within the workspace (auto-created if absent).
- #[arg(long, default_value = "scratch")]
+ #[arg(long, default_value_t = crate::config::DEFAULT_PROJECT.to_string())]
pub project: String,
}
diff --git a/crates/ai-memory-cli/src/commands/backup.rs b/crates/ai-memory-cli/src/commands/backup.rs
index bf0e81da..e9b187c1 100644
--- a/crates/ai-memory-cli/src/commands/backup.rs
+++ b/crates/ai-memory-cli/src/commands/backup.rs
@@ -17,8 +17,8 @@ use crate::http_client::{ServerEndpoint, post_bytes};
/// # Errors
/// Returns an error if the POST to `/admin/backup` fails, the server
/// returns a non-2xx status, or the output file cannot be written.
-pub async fn run(_config: &Config, args: BackupArgs) -> Result<()> {
- let endpoint = ServerEndpoint::from_env();
+pub async fn run(config: &Config, args: BackupArgs) -> Result<()> {
+ let endpoint = ServerEndpoint::from_config(config);
let bytes = post_bytes(&endpoint, "/admin/backup")
.await
.context("requesting backup from server")?;
diff --git a/crates/ai-memory-cli/src/commands/bootstrap.rs b/crates/ai-memory-cli/src/commands/bootstrap.rs
index e32aaa24..6e2afe81 100644
--- a/crates/ai-memory-cli/src/commands/bootstrap.rs
+++ b/crates/ai-memory-cli/src/commands/bootstrap.rs
@@ -25,11 +25,10 @@ use crate::http_client::{ServerEndpoint, post_json};
/// bundle to the server's `POST /admin/bootstrap` endpoint.
///
/// # Errors
-/// Bails when `AI_MEMORY_SERVER_URL` is unset, when the resolved repo
-/// path is not a git repo, when source collection fails, or when the
-/// server returns a non-2xx response.
-pub async fn run(_config: &Config, args: BootstrapArgs) -> Result<()> {
- let ep = ServerEndpoint::from_env();
+/// Bails when the resolved repo path cannot be inspected, when source
+/// collection fails, or when the server returns a non-2xx response.
+pub async fn run(config: &Config, args: BootstrapArgs) -> Result<()> {
+ let ep = ServerEndpoint::from_config(config);
info!(server = %ep.url, auth = ep.auth_token.is_some(), "bootstrap CLI configured");
// ---- repo path — auto-detect via libgit2, fall back to CWD ----
@@ -71,7 +70,7 @@ pub async fn run(_config: &Config, args: BootstrapArgs) -> Result<()> {
}
// ---- project — auto-derive from repo basename if absent -------
- let project = super::resolve_project_name(args.project.as_deref())?;
+ let project = super::resolve_project_name(config, args.project.as_deref())?;
info!(workspace = %args.workspace, project = %project, repo_path = %repo_path.display(), git = has_git, "bootstrap target");
// ---- collect sources locally ----------------------------------
diff --git a/crates/ai-memory-cli/src/commands/commit.rs b/crates/ai-memory-cli/src/commands/commit.rs
index f5ae68a3..9c262122 100644
--- a/crates/ai-memory-cli/src/commands/commit.rs
+++ b/crates/ai-memory-cli/src/commands/commit.rs
@@ -28,8 +28,8 @@ struct CommitResponse {
/// # Errors
/// Returns an error if the server is unreachable or returns a non-2xx
/// response.
-pub async fn run(_config: &Config, args: CommitArgs) -> Result<()> {
- let endpoint = ServerEndpoint::from_env();
+pub async fn run(config: &Config, args: CommitArgs) -> Result<()> {
+ let endpoint = ServerEndpoint::from_config(config);
let resp: CommitResponse = post_json(
&endpoint,
"/admin/commit",
diff --git a/crates/ai-memory-cli/src/commands/embed.rs b/crates/ai-memory-cli/src/commands/embed.rs
index 1cdb567d..57fd62db 100644
--- a/crates/ai-memory-cli/src/commands/embed.rs
+++ b/crates/ai-memory-cli/src/commands/embed.rs
@@ -25,9 +25,9 @@ struct EmbedRequest {
/// # Errors
/// Returns an error if the server is unreachable or returns a non-2xx
/// response.
-pub async fn run(_config: &Config, args: EmbedArgs) -> Result<()> {
- let endpoint = ServerEndpoint::from_env();
- let project = super::resolve_project_name(args.project.as_deref())?;
+pub async fn run(config: &Config, args: EmbedArgs) -> Result<()> {
+ let endpoint = ServerEndpoint::from_config(config);
+ let project = super::resolve_project_name(config, args.project.as_deref())?;
let report: serde_json::Value = post_json(
&endpoint,
"/admin/embed",
diff --git a/crates/ai-memory-cli/src/commands/forget_sweep.rs b/crates/ai-memory-cli/src/commands/forget_sweep.rs
index d10b782a..e58df434 100644
--- a/crates/ai-memory-cli/src/commands/forget_sweep.rs
+++ b/crates/ai-memory-cli/src/commands/forget_sweep.rs
@@ -23,9 +23,9 @@ struct ForgetSweepRequest {
/// # Errors
/// Returns an error if the server is unreachable or returns a non-2xx
/// response.
-pub async fn run(_config: &Config, args: ForgetSweepArgs) -> Result<()> {
- let endpoint = ServerEndpoint::from_env();
- let project = super::resolve_project_name(args.project.as_deref())?;
+pub async fn run(config: &Config, args: ForgetSweepArgs) -> Result<()> {
+ let endpoint = ServerEndpoint::from_config(config);
+ let project = super::resolve_project_name(config, args.project.as_deref())?;
let report: serde_json::Value = post_json(
&endpoint,
"/admin/forget-sweep",
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index fd79ffb4..84a789f3 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -32,7 +32,6 @@ use crate::config::Config;
/// # Errors
/// Returns an error if the hook script directory cannot be located.
pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {
- let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
let auth_token_owned = args
.auth_token
.clone()
@@ -40,21 +39,23 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {
let auth = auth_token_owned.as_deref();
if args.apply {
return match args.agent {
+ AgentChoice::OpenCode => apply_to_opencode_plugin(&args.server_url, auth, &args),
AgentChoice::ClaudeCode => {
+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
apply_to_claude_code_settings(&hooks_dir, &args.server_url, auth, &args)
}
AgentChoice::Codex => {
+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
apply_to_codex_settings(&hooks_dir, &args.server_url, auth, &args)
}
AgentChoice::Cursor => {
+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
apply_to_cursor_settings(&hooks_dir, &args.server_url, auth, &args)
}
AgentChoice::GeminiCli => {
+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
apply_to_gemini_settings(&hooks_dir, &args.server_url, auth, &args)
}
- AgentChoice::OpenCode => {
- apply_to_opencode_plugin(&hooks_dir, &args.server_url, auth, &args)
- }
AgentChoice::Openclaw => {
println!(
"OpenClaw does not support lifecycle hooks (only HTTP webhooks for \
@@ -72,11 +73,23 @@ pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {
};
}
match args.agent {
- AgentChoice::ClaudeCode => render_claude_code(&hooks_dir, &args.server_url, auth),
- AgentChoice::Codex => render_agent("codex", &hooks_dir, &args.server_url, auth),
- AgentChoice::Cursor => render_agent("cursor", &hooks_dir, &args.server_url, auth),
- AgentChoice::GeminiCli => render_agent("gemini-cli", &hooks_dir, &args.server_url, auth),
- AgentChoice::OpenCode => render_agent("opencode", &hooks_dir, &args.server_url, auth),
+ AgentChoice::OpenCode => render_opencode_plugin(&args.server_url, auth),
+ AgentChoice::ClaudeCode => {
+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
+ render_claude_code(&hooks_dir, &args.server_url, auth)
+ }
+ AgentChoice::Codex => {
+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
+ render_agent("codex", &hooks_dir, &args.server_url, auth)
+ }
+ AgentChoice::Cursor => {
+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
+ render_agent("cursor", &hooks_dir, &args.server_url, auth)
+ }
+ AgentChoice::GeminiCli => {
+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;
+ render_agent("gemini-cli", &hooks_dir, &args.server_url, auth)
+ }
AgentChoice::Openclaw => {
println!("OpenClaw does not expose lifecycle hooks — only HTTP webhooks.");
println!("ai-memory cannot wire automatic capture against OpenClaw today.");
@@ -390,26 +403,12 @@ fn merge_gemini_hooks(
/// Generate an OpenCode plugin at `~/.config/opencode/plugins/ai-memory.ts`.
///
-/// Unlike Claude Code / Codex / Cursor / Gemini, OpenCode's lifecycle
-/// hooks aren't JSON config — they're TypeScript modules under
-/// `~/.config/opencode/plugins/` (per
-/// <https://opencode.ai/docs/plugins/>). A plugin exports an
-/// async function returning a hooks object; the keys are
-/// dot-separated event names (`session.created`, `tool.execute.before`,
-/// etc.) and the values are async handlers.
-///
-/// Event mapping (OpenCode → ai-memory):
-/// session.created → session-start.sh
-/// session.idle → stop.sh
-/// session.compacted → pre-compact.sh
-/// tool.execute.before → pre-tool-use.sh
-/// tool.execute.after → post-tool-use.sh
-///
-/// OpenCode doesn't expose a `prompt-submit` equivalent or a
-/// `session.ended` event (idle is the closest). We forward what
-/// we can.
+/// OpenCode's integration surface is a TypeScript plugin, not a JSON
+/// hook table. The plugin posts normalized lifecycle payloads directly
+/// to `/hook` and injects pending handoffs through
+/// `experimental.chat.system.transform`, because plugin shell stdout is
+/// not prepended to the model context the way Claude Code hook stdout is.
fn apply_to_opencode_plugin(
- hooks_dir: &Path,
server_url: &str,
auth_token: Option<&str>,
args: &InstallHooksArgs,
@@ -423,83 +422,226 @@ fn apply_to_opencode_plugin(
.join("plugins")
.join("ai-memory.ts"),
};
- let staged = stage_hook_scripts(hooks_dir, "opencode")?;
- let script = |name: &str| staged.join(name).to_string_lossy().into_owned();
+ let body = build_opencode_plugin(server_url, auth_token);
+
+ let outcome = apply_atomic(&path, move |_existing| Ok(body.clone()))?;
+ println!(
+ "✓ {} {} ({})",
+ outcome.verb(),
+ path.display(),
+ match outcome {
+ ApplyOutcome::Created => "new plugin file",
+ ApplyOutcome::Updated => "backup written next to it",
+ ApplyOutcome::NoOp => "already up to date",
+ }
+ );
+ if !matches!(outcome, ApplyOutcome::NoOp) {
+ println!();
+ println!("OpenCode auto-loads plugins from ~/.config/opencode/plugins/ on next start.");
+ println!("If you're already inside an `opencode` session, restart it for the");
+ println!("new plugin to take effect.");
+ }
+ Ok(())
+}
+
+fn render_opencode_plugin(server_url: &str, auth_token: Option<&str>) -> Result<()> {
+ println!("// OpenCode plugin — write to ~/.config/opencode/plugins/ai-memory.ts");
+ println!("// Or re-run with `--apply` to install it automatically.");
+ println!("// Restart OpenCode after changing plugins; config is loaded at startup.");
+ println!();
+ println!("{}", build_opencode_plugin(server_url, auth_token));
+ Ok(())
+}
+
+fn build_opencode_plugin(server_url: &str, auth_token: Option<&str>) -> String {
let token_line = auth_token
- .map(|t| format!("const TOKEN = {};\n", ts_string_literal(t)))
- .unwrap_or_else(|| "const TOKEN = null;\n".to_string());
- let body = format!(
- r#"// Auto-generated by `ai-memory install-hooks --agent open-code --apply`.
+ .map(|t| format!("const TOKEN: string | null = {};\n", ts_string_literal(t)))
+ .unwrap_or_else(|| "const TOKEN: string | null = null;\n".to_string());
+ format!(
+ r#"// Auto-generated by `ai-memory install-hooks --agent opencode --apply`.
// Edit by re-running the command, not by hand — install-hooks
// will overwrite this file (with a `.bak-<ts>` backup) on each
// re-run.
import type {{ Plugin }} from "@opencode-ai/plugin";
-const SERVER = {server_literal};
+const SERVER = {server_literal}.replace(/\/+$/, "");
+const AGENT = "open-code";
{token_line}
-async function fire(
- $: any,
- script: string,
- event: string,
- payload: unknown,
-): Promise<void> {{
- // The hook scripts read JSON from stdin + AI_MEMORY_HOOK_URL/
- // AI_MEMORY_AUTH_TOKEN from env. Inline the env into the shell
- // command via POSIX `VAR=val cmd` syntax so we don't depend on
- // the runtime's env-passing semantics.
- const body = JSON.stringify({{
- hook_event_name: event,
- agent: "open-code",
- payload,
- }});
+
+function timeoutSignal(ms: number): AbortSignal | undefined {{
+ if (typeof AbortSignal === "undefined") return undefined;
+ const factory = (AbortSignal as unknown as {{ timeout?: (ms: number) => AbortSignal }}).timeout;
+ return factory ? factory(ms) : undefined;
+}}
+
+function authHeaders(): Record<string, string> {{
+ return TOKEN ? {{ Authorization: `Bearer ${{TOKEN}}` }} : {{}};
+}}
+
+function sessionID(input: unknown): string | undefined {{
+ const value = input as any;
+ return value?.sessionID ?? value?.sessionId ?? value?.session_id ?? value?.info?.id;
+}}
+
+function textFromParts(parts: unknown): string {{
+ if (!Array.isArray(parts)) return "";
+ return parts
+ .map((part: any) => {{
+ if (part?.type === "text" && typeof part.text === "string") return part.text;
+ if (part?.type === "subtask" && typeof part.prompt === "string") return part.prompt;
+ if (part?.type === "file" && typeof part.filename === "string") return `[file: ${{part.filename}}]`;
+ return "";
+ }})
+ .filter(Boolean)
+ .join("\n\n")
+ .trim();
+}}
+
+const sessionCwds = new Map<string, string>();
+const startedSessions = new Set<string>();
+const handoffChecked = new Set<string>();
+const preCompactLast = new Map<string, number>();
+
+function cwdFor(id: string | undefined, directory: string): string {{
+ return (id && sessionCwds.get(id)) || directory;
+}}
+
+function rememberCwd(id: string | undefined, cwd: string | undefined): void {{
+ if (id && cwd) sessionCwds.set(id, cwd);
+}}
+
+function startSession(id: string | undefined, cwd: string, extra: Record<string, unknown> = {{}}): void {{
+ if (!id || startedSessions.has(id)) return;
+ startedSessions.add(id);
+ rememberCwd(id, cwd);
+ postHook("session-start", {{ sessionID: id, cwd, ...extra }});
+}}
+
+function postPreCompact(id: string | undefined, directory: string): void {{
+ startSession(id, cwdFor(id, directory));
+ const key = id || "unknown";
+ const now = Date.now();
+ const last = preCompactLast.get(key) ?? 0;
+ if (now - last < 1000) return;
+ preCompactLast.set(key, now);
+ postHook("pre-compact", {{ sessionID: id, cwd: cwdFor(id, directory) }});
+}}
+
+function postHook(event: string, payload: Record<string, unknown>): void {{
+ const url = new URL(`${{SERVER}}/hook`);
+ url.searchParams.set("event", event);
+ url.searchParams.set("agent", AGENT);
try {{
- const authPrefix = TOKEN ? `AI_MEMORY_AUTH_TOKEN=${{TOKEN}} ` : "";
- await $`echo ${{body}} | env AI_MEMORY_HOOK_URL=${{SERVER}} ${{authPrefix}}${{script}}`
- .nothrow()
- .quiet();
+ void fetch(url, {{
+ method: "POST",
+ headers: {{ "Content-Type": "application/json", ...authHeaders() }},
+ body: JSON.stringify(payload),
+ signal: timeoutSignal(500),
+ }}).catch(() => undefined);
}} catch (_e) {{
// Fire-and-forget. Hooks must never block the agent.
}}
}}
-export const AiMemoryHooks: Plugin = async ({{ $ }}) => {{
+async function fetchHandoff(cwd: string): Promise<string | undefined> {{
+ const url = new URL(`${{SERVER}}/handoff`);
+ url.searchParams.set("agent", AGENT);
+ url.searchParams.set("cwd", cwd);
+ try {{
+ const response = await fetch(url, {{
+ headers: authHeaders(),
+ signal: timeoutSignal(1000),
+ }});
+ const text = (await response.text()).trim();
+ return text.length > 0 ? text : undefined;
+ }} catch (_e) {{
+ return undefined;
+ }}
+}}
+
+export const AiMemoryHooks: Plugin = async ({{ directory }}) => {{
return {{
- "session.created": async (input) => fire($, {session_start}, "session-start", input),
- "session.idle": async (input) => fire($, {stop}, "stop", input),
- "session.compacted": async (input) => fire($, {pre_compact}, "pre-compact", input),
- "tool.execute.before": async (input) => fire($, {pre_tool}, "pre-tool-use", input),
- "tool.execute.after": async (input) => fire($, {post_tool}, "post-tool-use", input),
+ event: async (input) => {{
+ const event = (input as any).event;
+ const properties = event?.properties ?? {{}};
+ if (event?.type === "session.created") {{
+ const info = properties.info ?? {{}};
+ const id = properties.sessionID ?? info.id;
+ const cwd = info.directory ?? directory;
+ startSession(id, cwd, {{
+ title: info.title,
+ projectID: info.projectID,
+ }});
+ }}
+ if (event?.type === "session.idle") {{
+ const id = properties.sessionID;
+ startSession(id, cwdFor(id, directory));
+ postHook("stop", {{ sessionID: id, cwd: cwdFor(id, directory) }});
+ }}
+ if (event?.type === "session.compacted") {{
+ const id = properties.sessionID;
+ postPreCompact(id, directory);
+ }}
+ }},
+ "chat.message": async (input, output) => {{
+ const id = sessionID(input);
+ const cwd = cwdFor(id, directory);
+ startSession(id, cwd, {{ agent: (input as any).agent, model: (input as any).model }});
+ postHook("user-prompt", {{
+ sessionID: id,
+ cwd,
+ agent: (input as any).agent,
+ model: (input as any).model,
+ messageID: (input as any).messageID,
+ prompt: textFromParts((output as any).parts),
+ }});
+ }},
+ "tool.execute.before": async (input, output) => {{
+ const id = sessionID(input);
+ startSession(id, cwdFor(id, directory));
+ postHook("pre-tool-use", {{
+ sessionID: id,
+ cwd: cwdFor(id, directory),
+ tool: (input as any).tool,
+ callID: (input as any).callID,
+ args: (output as any).args,
+ }});
+ }},
+ "tool.execute.after": async (input, output) => {{
+ const id = sessionID(input);
+ startSession(id, cwdFor(id, directory));
+ postHook("post-tool-use", {{
+ sessionID: id,
+ cwd: cwdFor(id, directory),
+ tool: (input as any).tool,
+ callID: (input as any).callID,
+ args: (input as any).args,
+ title: (output as any).title,
+ output: (output as any).output,
+ metadata: (output as any).metadata,
+ }});
+ }},
+ "experimental.session.compacting": async (input) => {{
+ const id = sessionID(input);
+ postPreCompact(id, directory);
+ }},
+ "experimental.chat.system.transform": async (input, output) => {{
+ const id = sessionID(input);
+ if (!id || handoffChecked.has(id)) return;
+ handoffChecked.add(id);
+ startSession(id, cwdFor(id, directory));
+ const handoff = await fetchHandoff(cwdFor(id, directory));
+ if (handoff) (output as any).system.push(handoff);
+ }},
}};
}};
+
+export default AiMemoryHooks;
"#,
server_literal = ts_string_literal(server_url),
token_line = token_line,
- session_start = ts_string_literal(&script("session-start.sh")),
- stop = ts_string_literal(&script("stop.sh")),
- pre_compact = ts_string_literal(&script("pre-compact.sh")),
- pre_tool = ts_string_literal(&script("pre-tool-use.sh")),
- post_tool = ts_string_literal(&script("post-tool-use.sh")),
- );
-
- let outcome = apply_atomic(&path, move |_existing| Ok(body.clone()))?;
- println!(
- "✓ {} {} ({})",
- outcome.verb(),
- path.display(),
- match outcome {
- ApplyOutcome::Created => "new plugin file",
- ApplyOutcome::Updated => "backup written next to it",
- ApplyOutcome::NoOp => "already up to date",
- }
- );
- if !matches!(outcome, ApplyOutcome::NoOp) {
- println!();
- println!("OpenCode auto-loads plugins from ~/.config/opencode/plugins/ on next start.");
- println!("If you're already inside an `opencode` session, restart it for the");
- println!("new plugin to take effect.");
- }
- Ok(())
+ )
}
/// Emit a TypeScript string literal containing `s`. Escapes
@@ -734,6 +876,51 @@ mod tests {
}
}
+ // ----------------------------------------------------------------
+ // OpenCode tests
+ // ----------------------------------------------------------------
+
+ #[test]
+ fn opencode_plugin_uses_real_plugin_hooks() {
+ let plugin = build_opencode_plugin("http://127.0.0.1:49374", Some("tok"));
+
+ assert!(plugin.contains("event: async (input)"));
+ assert!(plugin.contains(r#""chat.message": async"#));
+ assert!(plugin.contains(r#""tool.execute.before": async"#));
+ assert!(plugin.contains(r#""tool.execute.after": async"#));
+ assert!(plugin.contains(r#""experimental.chat.system.transform": async"#));
+ assert!(plugin.contains("export default AiMemoryHooks"));
+ assert!(plugin.contains("const startedSessions = new Set<string>();"));
+ assert!(plugin.contains("function startSession"));
+ assert!(plugin.contains("fetchHandoff"));
+ assert!(plugin.contains("postPreCompact"));
+ assert!(plugin.contains("postHook(\"session-start\""));
+ assert!(plugin.contains("postHook(\"user-prompt\""));
+ assert!(plugin.contains("Bearer ${TOKEN}"));
+ assert!(plugin.contains("tok"));
+ assert!(
+ !plugin.contains(r#""session.created": async"#),
+ "OpenCode bus events must be handled through the `event` hook"
+ );
+ }
+
+ #[test]
+ fn opencode_plugin_normalizes_payloads_without_legacy_wrapper() {
+ let plugin = build_opencode_plugin("http://127.0.0.1:49374/", None);
+
+ assert!(plugin.contains("const SERVER = \"http://127.0.0.1:49374/\".replace"));
+ assert!(plugin.contains("const TOKEN: string | null = null;"));
+ assert!(plugin.contains("sessionID: id,"));
+ assert!(plugin.contains("cwd,"));
+ assert!(plugin.contains("prompt: textFromParts"));
+ assert!(plugin.contains("output: (output as any).output"));
+ assert!(plugin.contains("if (typeof AbortSignal === \"undefined\")"));
+ assert!(
+ !plugin.contains("hook_event_name"),
+ "new plugin should send normalized top-level fields, not legacy wrappers"
+ );
+ }
+
// ----------------------------------------------------------------
// Cursor tests
// ----------------------------------------------------------------
diff --git a/crates/ai-memory-cli/src/commands/lint.rs b/crates/ai-memory-cli/src/commands/lint.rs
index 9db53cd4..4217cdca 100644
--- a/crates/ai-memory-cli/src/commands/lint.rs
+++ b/crates/ai-memory-cli/src/commands/lint.rs
@@ -21,9 +21,9 @@ struct LintRequest {
/// # Errors
/// Returns an error if the server is unreachable or returns a non-2xx
/// response.
-pub async fn run(_config: &Config, args: LintArgs) -> Result<()> {
- let endpoint = ServerEndpoint::from_env();
- let project = super::resolve_project_name(args.project.as_deref())?;
+pub async fn run(config: &Config, args: LintArgs) -> Result<()> {
+ let endpoint = ServerEndpoint::from_config(config);
+ let project = super::resolve_project_name(config, args.project.as_deref())?;
let report: serde_json::Value = post_json(
&endpoint,
"/admin/lint",
diff --git a/crates/ai-memory-cli/src/commands/llm_test.rs b/crates/ai-memory-cli/src/commands/llm_test.rs
index 01669fd7..8f1c4ab6 100644
--- a/crates/ai-memory-cli/src/commands/llm_test.rs
+++ b/crates/ai-memory-cli/src/commands/llm_test.rs
@@ -2,7 +2,6 @@
use ai_memory_llm::{ChatRequest, ProviderChoice, ProviderConfig, build_provider};
use anyhow::{Context, Result};
-use secrecy::SecretString;
use tracing::info;
use crate::cli::{LlmProviderChoice, LlmTestArgs};
@@ -13,16 +12,20 @@ use crate::config::Config;
/// # Errors
/// Returns an error if the provider cannot be constructed, the env
/// lacks the required keys, or the HTTP call fails.
-pub async fn run(_config: &Config, args: LlmTestArgs) -> Result<()> {
+pub async fn run(config: &Config, args: LlmTestArgs) -> Result<()> {
let provider = ProviderChoice::from(args.provider);
- let api_key = resolve_api_key(args.api_key, provider);
- let config = ProviderConfig {
+ let api_key = args
+ .api_key
+ .filter(|s| !s.is_empty())
+ .map(secrecy::SecretString::from)
+ .or_else(|| config.provider_api_key(provider));
+ let provider_config = ProviderConfig {
provider,
model: args.model,
api_key,
- base_url: args.base_url,
+ base_url: args.base_url.or_else(|| config.llm_test_base_url()),
};
- let client = build_provider(config).context("building LLM provider")?;
+ let client = build_provider(provider_config).context("building LLM provider")?;
info!(
provider = client.name(),
model = client.model(),
@@ -44,20 +47,6 @@ pub async fn run(_config: &Config, args: LlmTestArgs) -> Result<()> {
Ok(())
}
-fn resolve_api_key(explicit: Option<String>, provider: ProviderChoice) -> Option<SecretString> {
- if let Some(s) = explicit
- && !s.is_empty()
- {
- return Some(SecretString::from(s));
- }
- let env_name = match provider {
- ProviderChoice::Anthropic => "ANTHROPIC_API_KEY",
- ProviderChoice::OpenAi => "OPENAI_API_KEY",
- ProviderChoice::OpenAiCompat => "LLM_API_KEY",
- };
- std::env::var(env_name).ok().map(SecretString::from)
-}
-
impl From<LlmProviderChoice> for ProviderChoice {
fn from(value: LlmProviderChoice) -> Self {
match value {
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index 0da6f60a..08447fc0 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -2,6 +2,8 @@
use anyhow::{Context, Result, anyhow, bail};
+use crate::config::Config;
+
pub mod apply_shared;
pub mod backup;
pub mod bootstrap;
@@ -48,12 +50,12 @@ pub mod write_page;
/// auto-target the same project the user's interactive sessions
/// have been writing into. Dot-prefixed dirs are preserved
/// verbatim (`~/.config` → project `.config`).
-pub(crate) fn resolve_project_name(explicit: Option<&str>) -> Result<String> {
+pub(crate) fn resolve_project_name(config: &Config, explicit: Option<&str>) -> Result<String> {
if let Some(p) = explicit.filter(|s| !s.is_empty()) {
return Ok(p.to_string());
}
- if let Ok(host_cwd) = std::env::var("AI_MEMORY_HOST_CWD")
- && let Some(name) = std::path::Path::new(&host_cwd)
+ if let Some(host_cwd) = config.runtime_env.host_cwd()
+ && let Some(name) = std::path::Path::new(host_cwd)
.file_name()
.and_then(|s| s.to_str())
.filter(|s| !s.is_empty())
@@ -103,3 +105,32 @@ pub(crate) fn resolve_project_name(explicit: Option<&str>) -> Result<String> {
)
})
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::config::RuntimeEnv;
+
+ #[test]
+ fn resolve_project_name_prefers_explicit_value() {
+ let config = Config {
+ runtime_env: RuntimeEnv::with_host_cwd_for_tests("/host/ignored"),
+ ..Config::default()
+ };
+
+ assert_eq!(
+ resolve_project_name(&config, Some("explicit-project")).unwrap(),
+ "explicit-project"
+ );
+ }
+
+ #[test]
+ fn resolve_project_name_uses_host_cwd_basename() {
+ let config = Config {
+ runtime_env: RuntimeEnv::with_host_cwd_for_tests("/host/my-project"),
+ ..Config::default()
+ };
+
+ assert_eq!(resolve_project_name(&config, None).unwrap(), "my-project");
+ }
+}
diff --git a/crates/ai-memory-cli/src/commands/purge_project.rs b/crates/ai-memory-cli/src/commands/purge_project.rs
index e88c4e8c..cfe85ac7 100644
--- a/crates/ai-memory-cli/src/commands/purge_project.rs
+++ b/crates/ai-memory-cli/src/commands/purge_project.rs
@@ -24,8 +24,8 @@ struct PurgeProjectRequest {
/// # Errors
/// Returns an error when `--confirm` is absent, the server is unreachable,
/// or the server returns a non-2xx response.
-pub async fn run(_config: &Config, args: PurgeProjectArgs) -> Result<()> {
- let project = super::resolve_project_name(args.project.as_deref())?;
+pub async fn run(config: &Config, args: PurgeProjectArgs) -> Result<()> {
+ let project = super::resolve_project_name(config, args.project.as_deref())?;
if !args.confirm {
bail!(
@@ -37,7 +37,7 @@ pub async fn run(_config: &Config, args: PurgeProjectArgs) -> Result<()> {
);
}
- let endpoint = ServerEndpoint::from_env();
+ let endpoint = ServerEndpoint::from_config(config);
let report: serde_json::Value = post_json(
&endpoint,
"/admin/purge-project",
diff --git a/crates/ai-memory-cli/src/commands/rename_project.rs b/crates/ai-memory-cli/src/commands/rename_project.rs
index 5cfd1b5f..ba1cf388 100644
--- a/crates/ai-memory-cli/src/commands/rename_project.rs
+++ b/crates/ai-memory-cli/src/commands/rename_project.rs
@@ -15,9 +15,9 @@ use crate::http_client::{ServerEndpoint, post_json};
/// # Errors
/// Returns an error when the server is unreachable or returns a non-2xx
/// response (e.g. 404 workspace/project not found, 422 name taken or invalid).
-pub async fn run(_config: &Config, args: RenameProjectArgs) -> Result<()> {
- let endpoint = ServerEndpoint::from_env();
- let from = super::resolve_project_name(args.from.as_deref())?;
+pub async fn run(config: &Config, args: RenameProjectArgs) -> Result<()> {
+ let endpoint = ServerEndpoint::from_config(config);
+ let from = super::resolve_project_name(config, args.from.as_deref())?;
let body = serde_json::json!({
"workspace": args.workspace,
"from": from,
diff --git a/crates/ai-memory-cli/src/commands/reorg.rs b/crates/ai-memory-cli/src/commands/reorg.rs
index 34122b9d..b7745544 100644
--- a/crates/ai-memory-cli/src/commands/reorg.rs
+++ b/crates/ai-memory-cli/src/commands/reorg.rs
@@ -45,8 +45,8 @@ struct ReorgReport {
/// # Errors
/// Returns an error if the server is unreachable or returns a non-2xx
/// response.
-pub async fn run(_config: &Config, args: ReorgArgs) -> Result<()> {
- let endpoint = ServerEndpoint::from_env();
+pub async fn run(config: &Config, args: ReorgArgs) -> Result<()> {
+ let endpoint = ServerEndpoint::from_config(config);
let report: ReorgReport = post_json(
&endpoint,
"/admin/reorg",
diff --git a/crates/ai-memory-cli/src/commands/search.rs b/crates/ai-memory-cli/src/commands/search.rs
index dded818e..c21ea4f3 100644
--- a/crates/ai-memory-cli/src/commands/search.rs
+++ b/crates/ai-memory-cli/src/commands/search.rs
@@ -23,9 +23,9 @@ struct Hit {
///
/// # Errors
/// Returns an error if the server is unreachable or returns non-2xx.
-pub async fn run(_config: &Config, args: SearchArgs) -> Result<()> {
- let ep = ServerEndpoint::from_env();
- let project = super::resolve_project_name(args.project.as_deref())?;
+pub async fn run(config: &Config, args: SearchArgs) -> Result<()> {
+ let ep = ServerEndpoint::from_config(config);
+ let project = super::resolve_project_name(config, args.project.as_deref())?;
let limit_str = args.limit.to_string();
let hits: Vec<Hit> = get_json(
&ep,
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index 2b83d96e..78de7c54 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -3,11 +3,11 @@
use std::sync::Arc;
use ai_memory_consolidate::Consolidator;
-use ai_memory_core::Sanitizer;
+use ai_memory_core::{ActiveProject, ProjectId, Sanitizer, WorkspaceId};
use ai_memory_hooks::{HookState, hook_router};
-use ai_memory_llm::{build_embedder, build_provider, embedder_from_env, provider_from_env};
+use ai_memory_llm::{Embedder, LlmProvider, build_embedder, build_provider};
use ai_memory_mcp::{AdminState, AiMemoryServer, admin_router};
-use ai_memory_store::Store;
+use ai_memory_store::{ReaderPool, Store};
use ai_memory_web;
use ai_memory_wiki::{WatcherHandle, Wiki, migrations, run_wiki_migrations};
use anyhow::{Context, Result};
@@ -36,6 +36,12 @@ use crate::config::Config;
/// bodies into memory (audit critical #2).
const MAX_BODY_BYTES: usize = 10 * 1024 * 1024;
+struct ConsolidatorSetup {
+ server: AiMemoryServer,
+ consolidator: Option<Arc<Consolidator>>,
+ admin_llm: Option<Arc<dyn LlmProvider>>,
+}
+
/// Run the `serve` subcommand.
///
/// # Errors
@@ -70,50 +76,11 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
// operators discover misconfiguration immediately.
let sanitizer = Sanitizer::new(&config.sanitize)
.context("compiling sanitizer.extra_patterns from config")?;
- let mut wiki =
- Wiki::new(&config.data_dir, store.writer.clone())?.with_sanitizer(sanitizer.clone());
-
- // M9 — pluggable embedder. Refuse to start if any stored
- // embeddings disagree with the configured (provider, model, dim).
- let embedder = if let Some(cfg) = embedder_from_env()? {
- let mismatch = store
- .reader
- .embedding_meta_for_mismatch(cfg.provider.name().into(), cfg.model.clone(), cfg.dim)
- .await?;
- if !mismatch.is_empty() {
- anyhow::bail!(
- "embedding (provider, model, dim) mismatch with stored data: {:?} \
- — run `ai-memory embed --reembed` to migrate",
- mismatch
- );
- }
- let e = build_embedder(cfg).context("building embedder from env")?;
- info!(
- provider = e.provider(),
- model = e.model(),
- dim = e.dim(),
- "embedder enabled"
- );
- wiki = wiki.with_embedder(e.clone());
- Some(e)
- } else {
- info!("AI_MEMORY_EMBEDDING_PROVIDER unset; hybrid search disabled (FTS5-only)");
- None
- };
+ let wiki = Wiki::new(&config.data_dir, store.writer.clone())?.with_sanitizer(sanitizer.clone());
+ let (wiki, embedder) = configure_embedder(config, &store, wiki).await?;
// Keep the guard alive for the lifetime of `serve`.
- let _watcher = if args.no_watcher {
- info!("watcher disabled by --no-watcher");
- None
- } else {
- info!(
- root = %wiki.root().display(),
- workspace = %args.workspace,
- project = %args.project,
- "starting wiki watcher",
- );
- Some(WatcherHandle::start(wiki.clone())?)
- };
+ let _watcher = start_watcher(&args, &wiki)?;
// Shared between the MCP server and the hook router: the hook
// router publishes the cwd-resolved project on each event; the MCP
@@ -121,7 +88,7 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
// answers for the project the agent is actually in, not the static
// `--project` (issue #2). In stdio mode no hook router is built, so
// this stays empty and the baked-in default is used.
- let active_project = ai_memory_core::ActiveProject::new();
+ let active_project = ActiveProject::new();
let mut server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)
.with_wiki(wiki.clone())
.with_decay_params(config.decay)
@@ -130,36 +97,10 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
if let Some(e) = embedder.clone() {
server = server.with_embedder(e);
}
- // Build the consolidator (if LLM configured) once, then share the
- // Arc between the MCP server (for `memory_consolidate` + lint),
- // the hook router (for PreCompact checkpointing), and the admin
- // router (for `POST /admin/bootstrap`).
- let mut admin_llm: Option<Arc<dyn ai_memory_llm::LlmProvider>> = None;
- let consolidator: Option<Arc<Consolidator>> = if let Some(cfg) = provider_from_env()? {
- let llm = build_provider(cfg).context("building LLM provider from env")?;
- info!(
- provider = llm.name(),
- model = llm.model(),
- "memory_consolidate + PreCompact LLM checkpointing enabled",
- );
- let c = Arc::new(Consolidator::new(
- store.reader.clone(),
- store.writer.clone(),
- wiki.clone(),
- llm.clone(),
- ws,
- proj,
- ));
- server = server.with_consolidator_arc(wiki.clone(), llm.clone(), c.clone());
- admin_llm = Some(llm);
- Some(c)
- } else {
- info!(
- "AI_MEMORY_LLM_PROVIDER unset; memory_consolidate disabled, PreCompact \
- falls back to rule-based checkpoint, lint runs rule-based only"
- );
- None
- };
+ let consolidator_setup = configure_consolidator(config, server, &store, &wiki, ws, proj)?;
+ let server = consolidator_setup.server;
+ let consolidator = consolidator_setup.consolidator;
+ let admin_llm = consolidator_setup.admin_llm;
match args.transport {
TransportKind::Stdio => {
@@ -228,56 +169,15 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
bind: bind.clone(),
bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
});
- // Build the auth state. Precedence (highest first):
- // 1. AI_MEMORY_AUTH_TOKEN env var
- // 2. config.toml [auth].bearer_token
- // 3. neither → open mode (no auth)
- // Read env directly (not via figment) to match the pattern
- // used by AI_MEMORY_LLM_* in factory.rs — keeps the
- // operator's mental model simple.
- let token = std::env::var("AI_MEMORY_AUTH_TOKEN")
- .ok()
- .filter(|s| !s.is_empty())
- .or_else(|| config.auth.bearer_token.clone());
- let auth_state = Arc::new(AuthState::new(token));
+ let auth_state = Arc::new(AuthState::new(config.auth.bearer_token.clone()));
let auth_enabled = auth_state.enabled();
- let mut router = axum::Router::new()
+ let router = axum::Router::new()
.nest_service("/mcp", mcp_service)
.merge(hooks)
.merge(admin);
-
- // Register the web router BEFORE applying the bearer
- // middleware. In axum 0.8, `.layer()` only attaches to
- // routes registered before the call — nesting after the
- // layer would silently bypass auth for /web/*.
- if args.enable_web {
- let web_router = ai_memory_web::router(store.reader.clone(), wiki.clone());
- // Also accept the trailing-slash form. axum 0.8's
- // `nest("/web", ..)` matches `/web` (no slash) → inner
- // `route("/")` but doesn't match `/web/` (a browser's
- // default when the user types the bare prefix), so we
- // redirect that explicitly to keep both URLs working.
- router = router
- .route(
- "/web/",
- axum::routing::get(|| async {
- axum::response::Redirect::permanent("/web")
- }),
- )
- .nest("/web", web_router);
- info!("read-only wiki browser mounted at /web");
- }
-
- let router = router
- .layer(axum::middleware::from_fn_with_state(
- auth_state,
- require_bearer,
- ))
- .layer(axum::middleware::from_fn_with_state(
- Arc::new(config.allowed_hosts.clone()),
- require_allowed_host,
- ))
- .layer(DefaultBodyLimit::max(MAX_BODY_BYTES));
+ let router =
+ mount_web_router(router, args.enable_web, store.reader.clone(), wiki.clone());
+ let router = apply_http_layers(router, auth_state, config.allowed_hosts.clone());
let listener = tokio::net::TcpListener::bind(&bind)
.await
.with_context(|| format!("binding {bind}"))?;
@@ -311,6 +211,136 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
Ok(())
}
+async fn configure_embedder(
+ config: &Config,
+ store: &Store,
+ wiki: Wiki,
+) -> Result<(Wiki, Option<Arc<dyn Embedder>>)> {
+ // M9 — pluggable embedder. Refuse to start if any stored
+ // embeddings disagree with the configured (provider, model, dim).
+ let Some(cfg) = config.embedder_config()? else {
+ info!("AI_MEMORY_EMBEDDING_PROVIDER unset; hybrid search disabled (FTS5-only)");
+ return Ok((wiki, None));
+ };
+ let mismatch = store
+ .reader
+ .embedding_meta_for_mismatch(cfg.provider.name().into(), cfg.model.clone(), cfg.dim)
+ .await?;
+ if !mismatch.is_empty() {
+ anyhow::bail!(
+ "embedding (provider, model, dim) mismatch with stored data: {:?} \
+ — run `ai-memory embed --reembed` to migrate",
+ mismatch
+ );
+ }
+ let embedder = build_embedder(cfg).context("building embedder from config")?;
+ info!(
+ provider = embedder.provider(),
+ model = embedder.model(),
+ dim = embedder.dim(),
+ "embedder enabled"
+ );
+ Ok((wiki.with_embedder(embedder.clone()), Some(embedder)))
+}
+
+fn start_watcher(args: &ServeArgs, wiki: &Wiki) -> Result<Option<WatcherHandle>> {
+ if args.no_watcher {
+ info!("watcher disabled by --no-watcher");
+ return Ok(None);
+ }
+ info!(
+ root = %wiki.root().display(),
+ workspace = %args.workspace,
+ project = %args.project,
+ "starting wiki watcher",
+ );
+ Ok(Some(WatcherHandle::start(wiki.clone())?))
+}
+
+fn configure_consolidator(
+ config: &Config,
+ mut server: AiMemoryServer,
+ store: &Store,
+ wiki: &Wiki,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+) -> Result<ConsolidatorSetup> {
+ // Build the consolidator (if LLM configured) once, then share the
+ // Arc between the MCP server (for `memory_consolidate` + lint),
+ // the hook router (for PreCompact checkpointing), and the admin
+ // router (for `POST /admin/bootstrap`).
+ let Some(cfg) = config.llm_provider_config()? else {
+ info!(
+ "AI_MEMORY_LLM_PROVIDER unset; memory_consolidate disabled, PreCompact \
+ falls back to rule-based checkpoint, lint runs rule-based only"
+ );
+ return Ok(ConsolidatorSetup {
+ server,
+ consolidator: None,
+ admin_llm: None,
+ });
+ };
+ let llm = build_provider(cfg).context("building LLM provider from config")?;
+ info!(
+ provider = llm.name(),
+ model = llm.model(),
+ "memory_consolidate + PreCompact LLM checkpointing enabled",
+ );
+ let consolidator = Arc::new(Consolidator::new(
+ store.reader.clone(),
+ store.writer.clone(),
+ wiki.clone(),
+ llm.clone(),
+ workspace_id,
+ project_id,
+ ));
+ server = server.with_consolidator_arc(wiki.clone(), llm.clone(), consolidator.clone());
+ Ok(ConsolidatorSetup {
+ server,
+ consolidator: Some(consolidator),
+ admin_llm: Some(llm),
+ })
+}
+
+fn mount_web_router(
+ router: axum::Router,
+ enable_web: bool,
+ reader: ReaderPool,
+ wiki: Wiki,
+) -> axum::Router {
+ if !enable_web {
+ return router;
+ }
+ // Register the web router BEFORE applying the bearer middleware. In
+ // axum 0.8, `.layer()` only attaches to routes registered before the
+ // call; nesting after the layer would silently bypass auth for /web/*.
+ let web_router = ai_memory_web::router(reader, wiki);
+ info!("read-only wiki browser mounted at /web");
+ router
+ .route(
+ "/web/",
+ axum::routing::get(|| async { axum::response::Redirect::permanent("/web") }),
+ )
+ .nest("/web", web_router)
+}
+
+fn apply_http_layers(
+ router: axum::Router,
+ auth_state: Arc<AuthState>,
+ allowed_hosts: Vec<String>,
+) -> axum::Router {
+ router
+ .layer(axum::middleware::from_fn_with_state(
+ auth_state,
+ require_bearer,
+ ))
+ .layer(axum::middleware::from_fn_with_state(
+ Arc::new(allowed_hosts),
+ require_allowed_host,
+ ))
+ .layer(DefaultBodyLimit::max(MAX_BODY_BYTES))
+}
+
async fn require_allowed_host(
State(allowed_hosts): State<Arc<Vec<String>>>,
req: Request<Body>,
@@ -353,6 +383,9 @@ fn host_without_port(host: &str) -> &str {
#[cfg(test)]
mod tests {
use super::*;
+ use axum::http::Request;
+ use tempfile::TempDir;
+ use tower::ServiceExt;
#[test]
fn host_allowed_accepts_host_with_port() {
@@ -371,4 +404,30 @@ mod tests {
fn host_without_port_handles_ipv6_loopback() {
assert_eq!(host_without_port("[::1]:49374"), "::1");
}
+
+ #[tokio::test]
+ async fn web_routes_are_inside_auth_layer() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let router = mount_web_router(axum::Router::new(), true, store.reader.clone(), wiki);
+ let router = apply_http_layers(
+ router,
+ Arc::new(AuthState::new(Some("secret".to_string()))),
+ vec!["localhost".to_string()],
+ );
+
+ let resp = router
+ .oneshot(
+ Request::builder()
+ .uri("/web")
+ .header("Host", "localhost")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
+ }
}
diff --git a/crates/ai-memory-cli/src/commands/setup_agent.rs b/crates/ai-memory-cli/src/commands/setup_agent.rs
index cdb61022..daad3915 100644
--- a/crates/ai-memory-cli/src/commands/setup_agent.rs
+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs
@@ -49,12 +49,16 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {
auth_token: args.auth_token.or_else(|| config.auth.bearer_token.clone()),
..args
};
+ if matches!(args.agent, AgentChoice::OpenCode) {
+ emit_opencode_setup_hint(&args);
+ return Ok(());
+ }
let agent_sub = match args.agent {
AgentChoice::ClaudeCode => "claude-code",
AgentChoice::Codex => "codex",
AgentChoice::Cursor => "cursor",
AgentChoice::GeminiCli => "gemini-cli",
- AgentChoice::OpenCode => "opencode",
+ AgentChoice::OpenCode => unreachable!("opencode handled above"),
AgentChoice::Openclaw => {
anyhow::bail!(
"OpenClaw has no lifecycle hooks (only HTTP webhooks); \
@@ -115,12 +119,10 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {
match args.agent {
AgentChoice::ClaudeCode => emit_claude_code(&emit_root, &args)?,
- AgentChoice::Codex
- | AgentChoice::Cursor
- | AgentChoice::GeminiCli
- | AgentChoice::OpenCode => {
+ AgentChoice::Codex | AgentChoice::Cursor | AgentChoice::GeminiCli => {
emit_other(&emit_root, agent_sub, &args);
}
+ AgentChoice::OpenCode => unreachable!("opencode handled above"),
AgentChoice::Openclaw => {
// Unreachable — the early bail at the top of run()
// catches openclaw before we get here. Defensive
@@ -132,6 +134,21 @@ pub fn run(config: &Config, args: SetupAgentArgs) -> Result<()> {
Ok(())
}
+fn emit_opencode_setup_hint(args: &SetupAgentArgs) {
+ println!("# OpenCode uses a TypeScript plugin, not extracted shell scripts.");
+ println!("# Install it directly instead:");
+ println!("ai-memory install-hooks --agent opencode --apply \\");
+ if args.auth_token.is_some() {
+ println!(" --server-url {} \\", args.server_url);
+ println!(" --auth-token <token>");
+ } else {
+ println!(" --server-url {}", args.server_url);
+ println!(" # add --auth-token <token> if the server requires bearer auth");
+ }
+ println!();
+ println!("Also run `ai-memory install-mcp --client opencode` to wire MCP separately.");
+}
+
fn emit_claude_code(emit_root: &Path, args: &SetupAgentArgs) -> Result<()> {
let payload =
build_claude_code_payload(emit_root, &args.server_url, args.auth_token.as_deref());
@@ -153,11 +170,10 @@ fn emit_claude_code(emit_root: &Path, args: &SetupAgentArgs) -> Result<()> {
}
fn emit_other(emit_root: &Path, label: &str, args: &SetupAgentArgs) {
- // Codex + OpenCode hook configs vary by version; we just point at
- // the extracted scripts and let the user wire them up. Future
- // versions can render structured JSON/TOML once those formats
- // settle upstream.
- println!("# {label} hook scripts (manual wire-up — formats still evolving upstream)");
+ // These clients have hook surfaces, but their print-mode config
+ // snippets are intentionally conservative: apply-mode owns the
+ // exact merge/plugin generation where ai-memory knows the format.
+ println!("# {label} hook scripts (manual wire-up; use install-hooks --apply when available)");
println!("# Scripts located at: {}", emit_root.display());
println!("# Server URL: {}", args.server_url);
if args.auth_token.is_some() {
diff --git a/crates/ai-memory-cli/src/commands/status.rs b/crates/ai-memory-cli/src/commands/status.rs
index 0083d642..f7a16522 100644
--- a/crates/ai-memory-cli/src/commands/status.rs
+++ b/crates/ai-memory-cli/src/commands/status.rs
@@ -39,8 +39,8 @@ struct Counts {
/// # Errors
/// Returns an error if the server is unreachable, returns non-2xx, or
/// the response can't be parsed.
-pub async fn run(_config: &Config, args: StatusArgs) -> Result<()> {
- let ep = ServerEndpoint::from_env();
+pub async fn run(config: &Config, args: StatusArgs) -> Result<()> {
+ let ep = ServerEndpoint::from_config(config);
let report: Report = get_json(&ep, "/admin/status", &[]).await?;
if args.json {
diff --git a/crates/ai-memory-cli/src/commands/write_page.rs b/crates/ai-memory-cli/src/commands/write_page.rs
index e9ec3e68..bf45d547 100644
--- a/crates/ai-memory-cli/src/commands/write_page.rs
+++ b/crates/ai-memory-cli/src/commands/write_page.rs
@@ -37,7 +37,7 @@ struct WritePageResponseBody {
/// # Errors
/// Returns an error if stdin cannot be read (when `body == "-"`), or if
/// the POST to `/admin/write-page` fails.
-pub async fn run(_config: &Config, args: WritePageArgs) -> Result<()> {
+pub async fn run(config: &Config, args: WritePageArgs) -> Result<()> {
let body_text = if args.body == "-" {
let mut buf = String::new();
std::io::stdin()
@@ -53,7 +53,7 @@ pub async fn run(_config: &Config, args: WritePageArgs) -> Result<()> {
// for commands whose project arg is truly optional (no default).
let project = args.project.clone();
- let endpoint = ServerEndpoint::from_env();
+ let endpoint = ServerEndpoint::from_config(config);
let resp: WritePageResponseBody = post_json(
&endpoint,
"/admin/write-page",
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index 7934389e..b97b631a 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -8,22 +8,39 @@
use std::path::{Path, PathBuf};
+use ai_memory_llm::{
+ EmbedderChoice, EmbedderConfig, LlmError, LlmResult, ProviderChoice, ProviderConfig,
+};
use anyhow::{Context, Result};
use figment::{
Figment,
providers::{Env, Format, Serialized, Toml},
};
+use secrecy::SecretString;
use serde::{Deserialize, Serialize};
+/// Default HTTP bind address for the local single-user server.
+pub const DEFAULT_BIND: &str = "127.0.0.1:49374";
+
+/// Default base URL used by thin-client CLI subcommands.
+pub const DEFAULT_SERVER_URL: &str = "http://127.0.0.1:49374";
+
+/// Default MCP endpoint URL rendered for client integrations.
+pub const DEFAULT_MCP_URL: &str = "http://127.0.0.1:49374/mcp";
+
+/// Default workspace name used by the single-workspace v1 flow.
+pub const DEFAULT_WORKSPACE: &str = ai_memory_core::DEFAULT_WORKSPACE_NAME;
+
+/// Defensive project fallback used only when no cwd/project is available.
+pub const DEFAULT_PROJECT: &str = ai_memory_core::DEFAULT_PROJECT_NAME;
+
/// Top-level runtime configuration.
///
/// `deny_unknown_fields` is intentionally NOT set: figment's
/// `Env::prefixed("AI_MEMORY_")` pulls every env var with that prefix
-/// (including ones meant for the LLM/embedding factory:
-/// `AI_MEMORY_LLM_MODEL`, `AI_MEMORY_EMBEDDING_DIM`, …). Those keys are
-/// read directly via `std::env::var` in their own modules; they don't
-/// map into `Config` fields, but figment doesn't know that. Strict
-/// rejection here would crash on every deploy that uses LLM env vars.
+/// (including future keys not represented here yet). Strict rejection
+/// here would crash on harmless deploy-specific env vars before the
+/// rest of the config has a chance to validate what it actually uses.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
@@ -31,8 +48,24 @@ pub struct Config {
pub data_dir: PathBuf,
/// HTTP bind address used by `ai-memory serve`.
pub bind: String,
+ /// Base URL used by thin-client CLI commands to contact the running server.
+ pub server_url: String,
/// Per-subsystem log filter (overridable by `RUST_LOG`).
pub log_level: String,
+ /// Optional LLM provider (`anthropic`, `openai`, `openai-compat`).
+ pub llm_provider: Option<String>,
+ /// Optional LLM model override.
+ pub llm_model: Option<String>,
+ /// Optional LLM base URL override.
+ pub llm_base_url: Option<String>,
+ /// Optional embedding provider (`openai`, `voyage`).
+ pub embedding_provider: Option<String>,
+ /// Optional embedding model override.
+ pub embedding_model: Option<String>,
+ /// Optional embedding dimension override.
+ pub embedding_dim: Option<u32>,
+ /// Optional embedding base URL override.
+ pub embedding_base_url: Option<String>,
/// M8 retention-sweep parameters. The defaults give an ~80-day
/// "survival floor" for unused episodic content (above the cold
/// threshold), followed by ~180 days of soft-delete buffer before
@@ -61,6 +94,53 @@ pub struct Config {
/// can't be sequences without ugly escaping.
#[serde(deserialize_with = "deserialize_string_or_vec")]
pub allowed_hosts: Vec<String>,
+ /// Process-only env values that should never be written to config files.
+ #[serde(skip)]
+ pub runtime_env: RuntimeEnv,
+}
+
+/// Environment-only values captured once by [`Config::load`].
+#[derive(Debug, Clone, Default)]
+pub struct RuntimeEnv {
+ data_dir: Option<PathBuf>,
+ server_url: Option<String>,
+ auth_token: Option<String>,
+ host_cwd: Option<String>,
+ anthropic_api_key: Option<SecretString>,
+ openai_api_key: Option<SecretString>,
+ llm_api_key: Option<SecretString>,
+ llm_base_url: Option<String>,
+ voyage_api_key: Option<SecretString>,
+}
+
+impl RuntimeEnv {
+ fn from_process() -> Self {
+ Self {
+ data_dir: env_path("AI_MEMORY_DATA_DIR"),
+ server_url: env_string("AI_MEMORY_SERVER_URL"),
+ auth_token: env_string("AI_MEMORY_AUTH_TOKEN"),
+ host_cwd: env_string("AI_MEMORY_HOST_CWD"),
+ anthropic_api_key: env_secret("ANTHROPIC_API_KEY"),
+ openai_api_key: env_secret("OPENAI_API_KEY"),
+ llm_api_key: env_secret("LLM_API_KEY"),
+ llm_base_url: env_string("LLM_BASE_URL"),
+ voyage_api_key: env_secret("VOYAGE_API_KEY"),
+ }
+ }
+
+ /// Host cwd forwarded by the docker wrapper, if present.
+ #[must_use]
+ pub fn host_cwd(&self) -> Option<&str> {
+ self.host_cwd.as_deref()
+ }
+
+ #[cfg(test)]
+ pub fn with_host_cwd_for_tests(host_cwd: impl Into<String>) -> Self {
+ Self {
+ host_cwd: Some(host_cwd.into()),
+ ..Self::default()
+ }
+ }
}
/// Accept `Vec<String>` either as a real sequence (config.toml /
@@ -99,12 +179,21 @@ impl Default for Config {
fn default() -> Self {
Self {
data_dir: default_data_dir(),
- bind: "127.0.0.1:49374".into(),
+ bind: DEFAULT_BIND.into(),
+ server_url: DEFAULT_SERVER_URL.into(),
log_level: "info".into(),
+ llm_provider: None,
+ llm_model: None,
+ llm_base_url: None,
+ embedding_provider: None,
+ embedding_model: None,
+ embedding_dim: None,
+ embedding_base_url: None,
decay: ai_memory_store::DecayParams::default(),
sanitize: ai_memory_core::SanitizeConfig::default(),
auth: AuthSettings::default(),
allowed_hosts: vec!["localhost".into(), "127.0.0.1".into(), "::1".into()],
+ runtime_env: RuntimeEnv::default(),
}
}
}
@@ -116,9 +205,14 @@ impl Config {
/// Returns an error if the config file is malformed or any required
/// field is missing.
pub fn load(config_path: Option<&Path>, cli_data_dir: Option<PathBuf>) -> Result<Self> {
+ let runtime_env = RuntimeEnv::from_process();
+
// Figure out where the config file *would* live so we can read it
// before knowing the final data dir. CLI > env > default.
- let probe_data_dir = cli_data_dir.clone().unwrap_or_else(default_data_dir);
+ let probe_data_dir = cli_data_dir
+ .clone()
+ .or_else(|| runtime_env.data_dir.clone())
+ .unwrap_or_else(default_data_dir);
let resolved_config_path = config_path
.map(PathBuf::from)
.unwrap_or_else(|| probe_data_dir.join("config.toml"));
@@ -136,16 +230,163 @@ impl Config {
)
})?;
+ if let Some(token) = runtime_env.auth_token.clone() {
+ config.auth.bearer_token = Some(token);
+ }
+ if let Some(server_url) = runtime_env.server_url.clone() {
+ config.server_url = server_url;
+ }
+
// CLI override always wins (figment doesn't see it because clap has
- // already consumed the env var into `cli_data_dir`).
+ // already parsed the flag into `cli_data_dir`).
if let Some(dir) = cli_data_dir {
config.data_dir = dir;
+ } else if let Some(dir) = runtime_env.data_dir.clone() {
+ config.data_dir = dir;
}
config.data_dir = canonicalise_or_keep(&config.data_dir);
+ config.runtime_env = runtime_env;
Ok(config)
}
+
+ /// Whether the server URL came from config/env instead of the default.
+ #[must_use]
+ pub fn server_url_configured(&self) -> bool {
+ self.server_url != DEFAULT_SERVER_URL || self.runtime_env.server_url.is_some()
+ }
+
+ /// Build the configured LLM provider settings, if LLM support is enabled.
+ ///
+ /// # Errors
+ /// Returns [`LlmError::NotConfigured`] for unknown providers or missing
+ /// provider-specific required values.
+ pub fn llm_provider_config(&self) -> LlmResult<Option<ProviderConfig>> {
+ let Some(provider_raw) = non_empty(self.llm_provider.as_deref()) else {
+ return Ok(None);
+ };
+ let provider = match provider_raw {
+ "anthropic" => ProviderChoice::Anthropic,
+ "openai" => ProviderChoice::OpenAi,
+ "openai-compat" | "openai_compat" => ProviderChoice::OpenAiCompat,
+ other => {
+ return Err(LlmError::NotConfigured(format!(
+ "AI_MEMORY_LLM_PROVIDER={other} is not one of anthropic|openai|openai-compat"
+ )));
+ }
+ };
+ let model = match non_empty(self.llm_model.as_deref()) {
+ Some(s) => s.to_string(),
+ None => match provider {
+ ProviderChoice::Anthropic => "claude-sonnet-4-6".to_string(),
+ ProviderChoice::OpenAi => "gpt-4o-mini".to_string(),
+ ProviderChoice::OpenAiCompat => {
+ return Err(LlmError::NotConfigured(
+ "AI_MEMORY_LLM_MODEL must be set explicitly for openai-compat \
+ (no safe default for self-hosted / aggregator endpoints)"
+ .into(),
+ ));
+ }
+ },
+ };
+ Ok(Some(ProviderConfig {
+ provider,
+ model,
+ api_key: self.provider_api_key(provider),
+ base_url: self.llm_base_url.clone(),
+ }))
+ }
+
+ /// Build the configured embedder settings, if hybrid search is enabled.
+ ///
+ /// # Errors
+ /// Returns [`LlmError::NotConfigured`] for unknown providers, missing API
+ /// keys, or invalid dimensions.
+ pub fn embedder_config(&self) -> LlmResult<Option<EmbedderConfig>> {
+ let Some(provider_raw) = non_empty(self.embedding_provider.as_deref()) else {
+ return Ok(None);
+ };
+ let provider = match provider_raw {
+ "openai" => EmbedderChoice::OpenAi,
+ "voyage" => EmbedderChoice::Voyage,
+ other => {
+ return Err(LlmError::NotConfigured(format!(
+ "AI_MEMORY_EMBEDDING_PROVIDER={other} not one of openai|voyage"
+ )));
+ }
+ };
+ let model = match non_empty(self.embedding_model.as_deref()) {
+ Some(s) => s.to_string(),
+ None => match provider {
+ EmbedderChoice::OpenAi => "text-embedding-3-small".to_string(),
+ EmbedderChoice::Voyage => "voyage-3".to_string(),
+ },
+ };
+ let dim = self
+ .embedding_dim
+ .unwrap_or_else(|| ai_memory_llm::default_embedding_dim(provider, &model));
+ let api_key = match provider {
+ EmbedderChoice::OpenAi => self
+ .runtime_env
+ .openai_api_key
+ .clone()
+ .ok_or_else(|| LlmError::NotConfigured("OPENAI_API_KEY".into()))?,
+ EmbedderChoice::Voyage => self
+ .runtime_env
+ .voyage_api_key
+ .clone()
+ .ok_or_else(|| LlmError::NotConfigured("VOYAGE_API_KEY".into()))?,
+ };
+ Ok(Some(EmbedderConfig {
+ provider,
+ model,
+ dim,
+ api_key,
+ base_url: self.embedding_base_url.clone(),
+ }))
+ }
+
+ /// Resolve an API key for an explicit `llm-test` provider choice.
+ #[must_use]
+ pub fn provider_api_key(&self, provider: ProviderChoice) -> Option<SecretString> {
+ match provider {
+ ProviderChoice::Anthropic => self.runtime_env.anthropic_api_key.clone(),
+ ProviderChoice::OpenAi => self.runtime_env.openai_api_key.clone(),
+ ProviderChoice::OpenAiCompat => self.runtime_env.llm_api_key.clone(),
+ }
+ }
+
+ /// Base URL fallback for `llm-test --provider openai-compat`.
+ #[must_use]
+ pub fn llm_test_base_url(&self) -> Option<String> {
+ self.llm_base_url
+ .clone()
+ .or_else(|| self.runtime_env.llm_base_url.clone())
+ }
+}
+
+fn env_string(name: &str) -> Option<String> {
+ std::env::var(name).ok().and_then(|s| {
+ let trimmed = s.trim();
+ if trimmed.is_empty() {
+ None
+ } else {
+ Some(trimmed.to_string())
+ }
+ })
+}
+
+fn env_path(name: &str) -> Option<PathBuf> {
+ env_string(name).map(PathBuf::from)
+}
+
+fn env_secret(name: &str) -> Option<SecretString> {
+ env_string(name).map(SecretString::from)
+}
+
+fn non_empty(s: Option<&str>) -> Option<&str> {
+ s.map(str::trim).filter(|s| !s.is_empty())
}
fn default_data_dir() -> PathBuf {
@@ -177,7 +418,8 @@ mod tests {
fn defaults_have_canonical_endings() {
let cfg = Config::default();
assert!(cfg.data_dir.ends_with("ai-memory"));
- assert_eq!(cfg.bind, "127.0.0.1:49374");
+ assert_eq!(cfg.bind, DEFAULT_BIND);
+ assert_eq!(cfg.server_url, DEFAULT_SERVER_URL);
assert_eq!(cfg.log_level, "info");
}
diff --git a/crates/ai-memory-cli/src/http_client.rs b/crates/ai-memory-cli/src/http_client.rs
index 9addbd3c..af82181b 100644
--- a/crates/ai-memory-cli/src/http_client.rs
+++ b/crates/ai-memory-cli/src/http_client.rs
@@ -6,18 +6,16 @@
//!
//! ## Configuration
//!
-//! Two environment variables drive the client:
-//!
-//! - `AI_MEMORY_SERVER_URL` — base URL. Defaults to
-//! `http://127.0.0.1:49374` for the single-laptop case.
-//! - `AI_MEMORY_AUTH_TOKEN` — bearer token. Optional; only sent when
-//! non-empty. A loopback server with no token set accepts every
-//! request, so the default flow needs no credentials at all.
+//! [`crate::config::Config`] captures `AI_MEMORY_SERVER_URL` and
+//! `AI_MEMORY_AUTH_TOKEN` exactly once; this module only consumes the
+//! resolved values.
use anyhow::{Context, Result, bail};
use serde::Serialize;
use serde::de::DeserializeOwned;
+use crate::config::{Config, DEFAULT_SERVER_URL};
+
/// Resolved server target — base URL + optional bearer token.
#[derive(Debug, Clone)]
pub struct ServerEndpoint {
@@ -26,17 +24,17 @@ pub struct ServerEndpoint {
pub url: String,
/// Bearer token when present, else `None`.
pub auth_token: Option<String>,
+ url_configured: bool,
}
impl ServerEndpoint {
- /// Read the endpoint from `AI_MEMORY_SERVER_URL` +
- /// `AI_MEMORY_AUTH_TOKEN`. Both are optional; the URL defaults to
- /// loopback, the token defaults to unset.
+ /// Build the endpoint from the already-loaded process config.
#[must_use]
- pub fn from_env() -> Self {
- Self::from_pair(
- std::env::var("AI_MEMORY_SERVER_URL").ok(),
- std::env::var("AI_MEMORY_AUTH_TOKEN").ok(),
+ pub fn from_config(config: &Config) -> Self {
+ Self::from_pair_with_configured(
+ Some(config.server_url.clone()),
+ config.auth.bearer_token.clone(),
+ config.server_url_configured(),
)
}
@@ -47,14 +45,28 @@ impl ServerEndpoint {
/// trailing slashes are stripped. `token` is treated as absent when
/// `None` or empty.
#[must_use]
+ #[cfg(test)]
pub(crate) fn from_pair(url: Option<String>, token: Option<String>) -> Self {
+ let url_configured = url.as_deref().is_some_and(|s| !s.is_empty());
+ Self::from_pair_with_configured(url, token, url_configured)
+ }
+
+ fn from_pair_with_configured(
+ url: Option<String>,
+ token: Option<String>,
+ url_configured: bool,
+ ) -> Self {
let url = url
.filter(|s| !s.is_empty())
- .unwrap_or_else(|| "http://127.0.0.1:49374".to_string())
+ .unwrap_or_else(|| DEFAULT_SERVER_URL.to_string())
.trim_end_matches('/')
.to_string();
let auth_token = token.filter(|s| !s.is_empty());
- Self { url, auth_token }
+ Self {
+ url,
+ auth_token,
+ url_configured,
+ }
}
/// Apply auth header to a `reqwest::RequestBuilder` if a token is set.
@@ -124,10 +136,9 @@ pub async fn post_json<B: Serialize, T: DeserializeOwned>(
}
/// Turn a low-level reqwest connect/timeout error into a friendlier
-/// message that surfaces the env-var configuration. The common case
-/// is "Connection refused" — typically because `AI_MEMORY_SERVER_URL`
-/// is unset and the CLI defaulted to loopback on a host that has no
-/// local server running.
+/// message that surfaces the resolved server URL. The common case is
+/// "Connection refused" — typically because the CLI defaulted to
+/// loopback on a host that has no local server running.
fn augment_connect_error(
err: reqwest::Error,
endpoint: &ServerEndpoint,
@@ -150,10 +161,8 @@ fn augment_connect_error(
found
};
- let url_from_env = std::env::var("AI_MEMORY_SERVER_URL").is_ok_and(|v| !v.is_empty());
-
if chain_contains_refused {
- let hint = if url_from_env {
+ let hint = if endpoint.url_configured {
format!(
"\nAI_MEMORY_SERVER_URL is set to {} but nothing answered. \
Check the server is running, the port is reachable from \
diff --git a/crates/ai-memory-consolidate/src/bootstrap.rs b/crates/ai-memory-consolidate/src/bootstrap.rs
index 696d13c2..630f8b2e 100644
--- a/crates/ai-memory-consolidate/src/bootstrap.rs
+++ b/crates/ai-memory-consolidate/src/bootstrap.rs
@@ -305,7 +305,7 @@ impl Bootstrap {
}
let collected = sources.len();
- let (kept, dropped, est_tokens) = prune_to_budget(sources, cfg.max_input_tokens);
+ let (kept, dropped, est_tokens) = prune_sources_to_budget(sources, cfg.max_input_tokens);
info!(
collected,
kept = kept.len(),
@@ -719,7 +719,7 @@ fn collect_project_rules(repo_path: &Path) -> Result<Vec<BootstrapSource>, Boots
/// Drop lower-priority sources until estimated tokens fit under the
/// budget. Returns (kept, dropped_count, estimated_total_tokens).
-fn prune_to_budget(
+pub fn prune_sources_to_budget(
mut sources: Vec<BootstrapSource>,
budget: usize,
) -> (Vec<BootstrapSource>, usize, usize) {
@@ -948,7 +948,7 @@ mod tests {
label: "README".into(),
text: "important".to_string(),
};
- let (kept, dropped, _) = prune_to_budget(vec![big_header, readme], 1_500);
+ let (kept, dropped, _) = prune_sources_to_budget(vec![big_header, readme], 1_500);
assert_eq!(dropped, 1);
assert_eq!(kept.len(), 1);
assert_eq!(kept[0].kind, SourceKind::Readme);
@@ -966,7 +966,7 @@ mod tests {
label: "r".into(),
text: "shorter".into(),
};
- let (kept, dropped, _) = prune_to_budget(vec![s1, s2], 50_000);
+ let (kept, dropped, _) = prune_sources_to_budget(vec![s1, s2], 50_000);
assert_eq!(dropped, 0);
assert_eq!(kept.len(), 2);
}
diff --git a/crates/ai-memory-consolidate/src/consolidator.rs b/crates/ai-memory-consolidate/src/consolidator.rs
index 94d2185b..688b44b8 100644
--- a/crates/ai-memory-consolidate/src/consolidator.rs
+++ b/crates/ai-memory-consolidate/src/consolidator.rs
@@ -7,9 +7,7 @@
use std::sync::Arc;
-use ai_memory_core::{
- Observation, ObservationKind, PagePath, ProjectId, SessionId, Tier, WorkspaceId,
-};
+use ai_memory_core::{Observation, PagePath, ProjectId, SessionId, Tier, WorkspaceId};
use ai_memory_llm::{ChatMessage, ChatRequest, LlmError, LlmProvider, Role, complete_structured};
use ai_memory_store::{ReaderPool, WriterHandle};
use ai_memory_wiki::{Wiki, WritePageRequest};
@@ -542,10 +540,6 @@ fn short_id(s: &str) -> String {
s.chars().take(8).collect()
}
-/// Suppress the unused-variant lint for now; consumers will use
-/// [`ObservationKind`] via the observations parameter.
-const _OBSERVATION_KIND: Option<ObservationKind> = None;
-
/// System prompt for single-page consolidation. Loaded at compile
/// time from `prompts/single_consolidate_system.md`.
const SYSTEM_PROMPT: &str = include_str!("../prompts/single_consolidate_system.md");
diff --git a/crates/ai-memory-consolidate/src/lib.rs b/crates/ai-memory-consolidate/src/lib.rs
index d9ae4740..c028e898 100644
--- a/crates/ai-memory-consolidate/src/lib.rs
+++ b/crates/ai-memory-consolidate/src/lib.rs
@@ -16,7 +16,7 @@ pub mod types;
pub use bootstrap::{
Bootstrap, BootstrapConfig, BootstrapError, BootstrapOutcome, BootstrapSource, SourceCounts,
- SourceKind, collect_sources, discover_repo_root,
+ SourceKind, collect_sources, discover_repo_root, prune_sources_to_budget,
};
pub use consolidator::{
BATCH_SYSTEM_PROMPT, Consolidator, ConsolidatorError, ConsolidatorResult, build_batch_request,
diff --git a/crates/ai-memory-consolidate/src/sweep.rs b/crates/ai-memory-consolidate/src/sweep.rs
index 2a5ddfb1..58295082 100644
--- a/crates/ai-memory-consolidate/src/sweep.rs
+++ b/crates/ai-memory-consolidate/src/sweep.rs
@@ -81,13 +81,8 @@ pub async fn run_sweep(
if !is_decayable(c) {
continue;
}
- #[allow(clippy::cast_precision_loss)]
- let age_days = (now_us - c.updated_at_us) as f64 / US_PER_DAY;
- let days_since_access = c.last_accessed_at_us.map(|us| {
- #[allow(clippy::cast_precision_loss)]
- let raw = (now_us - us) as f64 / US_PER_DAY;
- raw.max(0.0)
- });
+ let age_days = elapsed_days(now_us, c.updated_at_us);
+ let days_since_access = c.last_accessed_at_us.map(|us| elapsed_days(now_us, us));
let score = retention_score(params, age_days, c.access_count, days_since_access);
if score < params.cold_threshold {
evicted.push(EvictedPage {
@@ -119,6 +114,12 @@ pub async fn run_sweep(
})
}
+fn elapsed_days(now_us: i64, then_us: i64) -> f64 {
+ #[allow(clippy::cast_precision_loss)]
+ let raw = (now_us - then_us) as f64 / US_PER_DAY;
+ raw.max(0.0)
+}
+
fn is_decayable(c: &DecayCandidate) -> bool {
if c.tier != Tier::Episodic {
return false;
@@ -197,4 +198,10 @@ mod tests {
};
assert!(is_decayable(&c));
}
+
+ #[test]
+ fn elapsed_days_clamps_future_timestamps() {
+ assert_eq!(elapsed_days(1_000, 2_000), 0.0);
+ assert!(elapsed_days(US_PER_DAY as i64, 0) >= 1.0);
+ }
}
diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rs
index 350970e7..98ec361c 100644
--- a/crates/ai-memory-core/src/ids.rs
+++ b/crates/ai-memory-core/src/ids.rs
@@ -232,6 +232,18 @@ mod tests {
assert_eq!(id, parsed);
}
+ #[test]
+ fn id_round_trips_through_bytes() {
+ let id = ProjectId::new();
+ assert_eq!(ProjectId::from_slice(id.as_bytes()).unwrap(), id);
+ }
+
+ #[test]
+ fn id_rejects_malformed_byte_lengths() {
+ assert!(PageId::from_slice(&[0_u8; 15]).is_err());
+ assert!(PageId::from_slice(&[0_u8; 17]).is_err());
+ }
+
#[test]
fn agent_kind_serde() {
let k = AgentKind::ClaudeCode;
diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rs
index fb3d285c..3e4d37e3 100644
--- a/crates/ai-memory-core/src/lib.rs
+++ b/crates/ai-memory-core/src/lib.rs
@@ -14,6 +14,12 @@ pub mod page;
pub mod routing_snippet;
pub mod sanitize;
+/// Default workspace name used by the single-workspace v1 flow.
+pub const DEFAULT_WORKSPACE_NAME: &str = "default";
+
+/// Defensive project fallback used only when no cwd/project is available.
+pub const DEFAULT_PROJECT_NAME: &str = "scratch";
+
pub use active_project::ActiveProject;
pub use error::{MemoryError, MemoryResult};
pub use handoff::{Handoff, HandoffState, NewHandoff};
diff --git a/crates/ai-memory-hooks/src/log.rs b/crates/ai-memory-hooks/src/log.rs
index f03ddc93..c8613e16 100644
--- a/crates/ai-memory-hooks/src/log.rs
+++ b/crates/ai-memory-hooks/src/log.rs
@@ -24,7 +24,7 @@ use std::io::Write;
use ai_memory_core::{ProjectId, WorkspaceId};
use ai_memory_wiki::Wiki;
-use jiff::{Timestamp, ToSpan, tz::TimeZone};
+use jiff::{Timestamp, tz::TimeZone};
use tracing::debug;
use crate::payload::HookEvent;
@@ -102,11 +102,6 @@ fn format_line(when: Timestamp, event: HookEvent, title: &str) -> String {
format!("## [{stamp}] {kind} | {one_line}\n")
}
-#[allow(dead_code)] // Helper kept for parity with the original Karpathy CLAUDE.md grep pattern.
-fn now() -> Timestamp {
- Timestamp::now() - 0.seconds()
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rs
index 980da82c..44137dbb 100644
--- a/crates/ai-memory-hooks/src/payload.rs
+++ b/crates/ai-memory-hooks/src/payload.rs
@@ -118,8 +118,37 @@ impl HookEnvelope {
// Codex `sessionId`. JSON keys are case-sensitive, so all three
// spellings must be listed or OpenCode tool events fail the
// "missing session_id" check in the router (issue #1).
- let session_id = extract_string(&raw, &["session_id", "sessionId", "sessionID", "session"]);
- let cwd = extract_string(&raw, &["cwd", "current_dir", "working_dir"]);
+ let session_id = extract_string(&raw, &["session_id", "sessionId", "sessionID", "session"])
+ .or_else(|| {
+ extract_string_path(
+ &raw,
+ &[
+ &["info", "id"],
+ &["properties", "sessionID"],
+ &["properties", "info", "id"],
+ &["event", "properties", "sessionID"],
+ &["event", "properties", "info", "id"],
+ &["payload", "info", "id"],
+ &["payload", "properties", "sessionID"],
+ &["payload", "properties", "info", "id"],
+ ],
+ )
+ });
+ let cwd = extract_string(&raw, &["cwd", "current_dir", "working_dir", "directory"])
+ .or_else(|| {
+ extract_string_path(
+ &raw,
+ &[
+ &["path", "cwd"],
+ &["info", "directory"],
+ &["properties", "info", "directory"],
+ &["event", "properties", "info", "directory"],
+ &["payload", "path", "cwd"],
+ &["payload", "info", "directory"],
+ &["payload", "properties", "info", "directory"],
+ ],
+ )
+ });
let title_hint = best_title_hint(event, &raw);
let body_excerpt = best_body_excerpt(event, &raw);
Self {
@@ -136,7 +165,20 @@ impl HookEnvelope {
fn extract_string(value: &serde_json::Value, keys: &[&str]) -> Option<String> {
for key in keys {
- if let Some(s) = value.get(*key).and_then(serde_json::Value::as_str)
+ for candidate in extraction_candidates(value) {
+ if let Some(s) = candidate.get(*key).and_then(serde_json::Value::as_str)
+ && !s.is_empty()
+ {
+ return Some(s.to_string());
+ }
+ }
+ }
+ None
+}
+
+fn extract_string_path(value: &serde_json::Value, paths: &[&[&str]]) -> Option<String> {
+ for path in paths {
+ if let Some(s) = value_at_path(value, path).and_then(serde_json::Value::as_str)
&& !s.is_empty()
{
return Some(s.to_string());
@@ -145,6 +187,44 @@ fn extract_string(value: &serde_json::Value, keys: &[&str]) -> Option<String> {
None
}
+fn value_at_path<'a>(
+ mut value: &'a serde_json::Value,
+ path: &[&str],
+) -> Option<&'a serde_json::Value> {
+ for segment in path {
+ value = value.get(*segment)?;
+ }
+ Some(value)
+}
+
+fn extraction_candidates(value: &serde_json::Value) -> Vec<&serde_json::Value> {
+ let mut out = Vec::new();
+ push_candidates(&mut out, value);
+ if let Some(payload) = value.get("payload") {
+ push_candidates(&mut out, payload);
+ }
+ if let Some(event) = value.get("event") {
+ push_candidates(&mut out, event);
+ }
+ out
+}
+
+fn push_candidates<'a>(out: &mut Vec<&'a serde_json::Value>, value: &'a serde_json::Value) {
+ out.push(value);
+ if let Some(properties) = value.get("properties") {
+ out.push(properties);
+ if let Some(info) = properties.get("info") {
+ out.push(info);
+ }
+ }
+ if let Some(info) = value.get("info") {
+ out.push(info);
+ }
+ if let Some(path) = value.get("path") {
+ out.push(path);
+ }
+}
+
fn best_title_hint(event: HookEvent, raw: &serde_json::Value) -> Option<String> {
match event {
HookEvent::SessionStart => extract_string(raw, &["model", "title"]),
@@ -190,8 +270,16 @@ fn truncate_excerpt(s: &str) -> String {
if s.len() <= MAX {
s.to_string()
} else {
- let mut buf = String::with_capacity(MAX + 1);
- buf.push_str(&s[..MAX]);
+ let mut buf = String::with_capacity(MAX + '…'.len_utf8());
+ let mut end = 0;
+ for (idx, ch) in s.char_indices() {
+ let next = idx + ch.len_utf8();
+ if next > MAX {
+ break;
+ }
+ end = next;
+ }
+ buf.push_str(&s[..end]);
buf.push('…');
buf
}
@@ -254,6 +342,67 @@ mod tests {
assert_eq!(env.session_id.as_deref(), Some("ses_abc123"));
}
+ /// Earlier OpenCode plugin generation wrapped the actual SDK hook
+ /// input under `payload`. Keep accepting that shape so users with
+ /// an old plugin don't silently lose project routing until they
+ /// restart with the fixed plugin.
+ #[test]
+ fn envelope_extracts_legacy_opencode_nested_payload() {
+ let q = HookQuery {
+ event: "post-tool-use".into(),
+ agent: Some("open-code".into()),
+ };
+ let raw = serde_json::json!({
+ "hook_event_name": "post-tool-use",
+ "agent": "open-code",
+ "payload": {
+ "sessionID": "ses_nested",
+ "cwd": "/home/user/ai-memory",
+ "tool": "bash",
+ "output": "tests passed"
+ }
+ });
+ let env = HookEnvelope::from_query_and_body(q, raw);
+ assert_eq!(env.session_id.as_deref(), Some("ses_nested"));
+ assert_eq!(env.cwd.as_deref(), Some("/home/user/ai-memory"));
+ assert_eq!(env.title_hint.as_deref(), Some("bash"));
+ assert!(
+ env.body_excerpt
+ .as_deref()
+ .is_some_and(|body| body.contains("tests passed")),
+ "post-tool body should include nested output: {:?}",
+ env.body_excerpt
+ );
+ }
+
+ /// OpenCode's plugin `event` hook receives bus events shaped like
+ /// `{ event: { type, properties } }`; session creation carries the
+ /// cwd as `properties.info.directory`.
+ #[test]
+ fn envelope_extracts_opencode_bus_event_session_info() {
+ let q = HookQuery {
+ event: "session-start".into(),
+ agent: Some("open-code".into()),
+ };
+ let raw = serde_json::json!({
+ "event": {
+ "type": "session.created",
+ "properties": {
+ "sessionID": "ses_bus",
+ "info": {
+ "id": "ses_bus",
+ "directory": "/home/user/ai-memory",
+ "title": "New session"
+ }
+ }
+ }
+ });
+ let env = HookEnvelope::from_query_and_body(q, raw);
+ assert_eq!(env.session_id.as_deref(), Some("ses_bus"));
+ assert_eq!(env.cwd.as_deref(), Some("/home/user/ai-memory"));
+ assert_eq!(env.title_hint.as_deref(), Some("New session"));
+ }
+
/// 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
@@ -369,4 +518,23 @@ mod tests {
assert!(title.chars().count() <= 80);
assert!(title.ends_with('…'));
}
+
+ #[test]
+ fn post_tool_excerpt_truncates_without_splitting_utf8() {
+ let q = HookQuery {
+ event: "post-tool-use".into(),
+ agent: Some("claude-code".into()),
+ };
+ let output = format!("{}é", "x".repeat(1_999));
+ let env = HookEnvelope::from_query_and_body(
+ q,
+ serde_json::json!({
+ "tool": "bash",
+ "result": output,
+ }),
+ );
+ let excerpt = env.body_excerpt.unwrap();
+ assert!(excerpt.ends_with('…'));
+ assert!(excerpt.starts_with("tool: bash\n---\n"));
+ }
}
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index e1e22f29..f1df717f 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -13,8 +13,8 @@ use std::sync::Arc;
use ai_memory_consolidate::Consolidator;
use ai_memory_core::{
- ActiveProject, AgentKind, Handoff, NewHandoff, NewObservation, NewSession, ObservationKind,
- ProjectId, Sanitized, Sanitizer, SessionId, WorkspaceId,
+ ActiveProject, AgentKind, DEFAULT_WORKSPACE_NAME, Handoff, NewHandoff, NewObservation,
+ NewSession, ObservationKind, ProjectId, Sanitized, Sanitizer, SessionId, WorkspaceId,
};
use ai_memory_store::WriterHandle;
use ai_memory_wiki::Wiki;
@@ -223,17 +223,22 @@ async fn resolve_project_ids(
return Ok(*ids);
}
}
- let project_name = std::path::Path::new(cwd)
+ let Some(project_name) = std::path::Path::new(cwd)
.file_name()
.and_then(|s| s.to_str())
.map(str::to_string)
.filter(|s| !s.is_empty())
+ else {
// Defensive: if basename derivation fails (e.g. cwd is "/"),
// fall back to the server defaults rather than hard-erroring.
- .ok_or_else(|| anyhow::anyhow!("could not derive project name from cwd {cwd:?}"))?;
+ state
+ .active_project
+ .set(state.workspace_id, state.project_id);
+ return Ok((state.workspace_id, state.project_id));
+ };
let ws = state
.writer
- .get_or_create_workspace("default".to_string())
+ .get_or_create_workspace(DEFAULT_WORKSPACE_NAME.to_string())
.await
.map_err(|e| anyhow::anyhow!("get_or_create_workspace: {e}"))?;
let proj = state
@@ -261,18 +266,18 @@ async fn process(state: &HookState, env: HookEnvelope) -> anyhow::Result<()> {
let session_id = resolve_session_id(&env)?;
let (ws, proj) = resolve_project_ids(state, env.cwd.as_deref()).await?;
- // Begin the session row if SessionStart, otherwise no-op (the
- // `INSERT OR IGNORE` makes this safe).
- if matches!(env.event, HookEvent::SessionStart) {
- let new_session = NewSession {
- id: session_id,
- workspace_id: ws,
- project_id: proj,
- agent_kind: env.agent,
- cwd: env.cwd.as_ref().map(std::path::PathBuf::from),
- };
- state.writer.begin_session(new_session).await?;
- }
+ // Hooks are fire-and-forget and may arrive out of order. Begin the
+ // session idempotently before every observation so a resumed agent
+ // session, or a prompt racing ahead of SessionStart, cannot trip the
+ // observations.session_id foreign key.
+ let new_session = NewSession {
+ id: session_id,
+ workspace_id: ws,
+ project_id: proj,
+ agent_kind: env.agent,
+ cwd: env.cwd.as_ref().map(std::path::PathBuf::from),
+ };
+ state.writer.begin_session(new_session).await?;
// Persist the observation row.
let kind = env.event.to_observation_kind();
@@ -623,6 +628,32 @@ mod tests {
assert!(state.active_project.get().is_none());
}
+ #[tokio::test]
+ async fn process_with_root_cwd_falls_back_to_state_defaults() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+
+ let (ws, proj) = resolve_project_ids(&state, Some("/")).await.unwrap();
+ assert_eq!(ws, state.workspace_id);
+ assert_eq!(proj, state.project_id);
+ assert_eq!(state.active_project.get(), Some((ws, proj)));
+ }
+
+ #[test]
+ fn resolve_session_id_hashes_agent_ids_deterministically() {
+ let env = HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: "post-tool-use".into(),
+ agent: Some("opencode".into()),
+ },
+ serde_json::json!({ "sessionID": "opencode-session-123" }),
+ );
+
+ let first = resolve_session_id(&env).unwrap();
+ let second = resolve_session_id(&env).unwrap();
+ assert_eq!(first, second);
+ }
+
/// A second call for the same cwd must hit the in-memory cache — no
/// additional `get_or_create_project` writes happen, proven by
/// inspecting the cache after both calls.
@@ -685,4 +716,28 @@ mod tests {
"routing must not use server-default project"
);
}
+
+ #[tokio::test]
+ async fn process_accepts_prompt_before_session_start() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+
+ let env = HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: "user-prompt".into(),
+ agent: Some("opencode".into()),
+ },
+ serde_json::json!({
+ "sessionID": "opencode-resumed-session",
+ "cwd": "/home/user/resumed-project",
+ "prompt": "continue",
+ }),
+ );
+
+ process(&state, env).await.unwrap();
+
+ let counts = state.reader.status_counts().await.unwrap();
+ assert_eq!(counts.sessions, 1);
+ assert_eq!(counts.observations, 1);
+ }
}
diff --git a/crates/ai-memory-llm/src/anthropic.rs b/crates/ai-memory-llm/src/anthropic.rs
index 953304a4..a2792dd5 100644
--- a/crates/ai-memory-llm/src/anthropic.rs
+++ b/crates/ai-memory-llm/src/anthropic.rs
@@ -10,6 +10,7 @@ use tracing::debug;
use crate::error::{LlmError, LlmResult};
use crate::provider::LlmProvider;
+use crate::text::truncate_with_ellipsis;
use crate::types::{ChatRequest, ChatResponse, Role, Usage};
/// Default Anthropic API base.
@@ -99,16 +100,8 @@ struct AnthropicResponse {
#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum AnthropicContent {
- Text {
- text: String,
- },
- ToolUse {
- #[allow(dead_code)]
- id: String,
- #[allow(dead_code)]
- name: String,
- input: serde_json::Value,
- },
+ Text { text: String },
+ ToolUse { input: serde_json::Value },
}
#[derive(Debug, Deserialize)]
@@ -230,17 +223,9 @@ impl AnthropicProvider {
let body = resp.text().await.unwrap_or_default();
return Err(LlmError::Provider {
status: status.as_u16(),
- body: truncate(&body, 1024),
+ body: truncate_with_ellipsis(&body, 1024),
});
}
resp.json::<R>().await.map_err(LlmError::from)
}
}
-
-fn truncate(s: &str, n: usize) -> String {
- if s.len() <= n {
- s.to_string()
- } else {
- format!("{}…", &s[..n])
- }
-}
diff --git a/crates/ai-memory-llm/src/embedding.rs b/crates/ai-memory-llm/src/embedding.rs
index 8607badb..cca7a066 100644
--- a/crates/ai-memory-llm/src/embedding.rs
+++ b/crates/ai-memory-llm/src/embedding.rs
@@ -20,6 +20,7 @@ use tracing::debug;
use crate::error::{LlmError, LlmResult};
use crate::openai::normalize_openai_base;
+use crate::text::truncate_with_ellipsis;
/// Provider-agnostic embedding API.
///
@@ -132,7 +133,7 @@ impl Embedder for OpenAiEmbedder {
let body = resp.text().await.unwrap_or_default();
return Err(LlmError::Provider {
status: status.as_u16(),
- body: truncate(&body, 1024),
+ body: truncate_with_ellipsis(&body, 1024),
});
}
let parsed: OpenAiEmbeddingResponse = resp.json().await?;
@@ -239,7 +240,7 @@ impl Embedder for VoyageEmbedder {
let body = resp.text().await.unwrap_or_default();
return Err(LlmError::Provider {
status: status.as_u16(),
- body: truncate(&body, 1024),
+ body: truncate_with_ellipsis(&body, 1024),
});
}
let parsed: VoyageResponse = resp.json().await?;
@@ -325,14 +326,6 @@ fn fnv1a(s: &str) -> u64 {
h
}
-fn truncate(s: &str, n: usize) -> String {
- if s.len() <= n {
- s.to_string()
- } else {
- format!("{}…", &s[..n])
- }
-}
-
/// Cosine similarity between two same-dim unit vectors. (= dot product
/// after normalisation.)
#[must_use]
diff --git a/crates/ai-memory-llm/src/factory.rs b/crates/ai-memory-llm/src/factory.rs
index 7c730447..754d77a4 100644
--- a/crates/ai-memory-llm/src/factory.rs
+++ b/crates/ai-memory-llm/src/factory.rs
@@ -38,74 +38,6 @@ pub struct ProviderConfig {
pub base_url: Option<String>,
}
-/// Build a [`ProviderConfig`] from the environment.
-///
-/// Reads `AI_MEMORY_LLM_PROVIDER`, `AI_MEMORY_LLM_MODEL`,
-/// `AI_MEMORY_LLM_BASE_URL`, and the appropriate API key
-/// (`ANTHROPIC_API_KEY` / `OPENAI_API_KEY` / `LLM_API_KEY`).
-/// Returns `Ok(None)` when `AI_MEMORY_LLM_PROVIDER` is unset — that
-/// is the canonical "no LLM features" path.
-///
-/// # Errors
-/// Returns [`LlmError::NotConfigured`] when the provider env var is
-/// set to an unknown value or when the model env var is missing.
-pub fn provider_from_env() -> LlmResult<Option<ProviderConfig>> {
- let provider = match std::env::var("AI_MEMORY_LLM_PROVIDER") {
- Ok(s) => match s.as_str() {
- "anthropic" => ProviderChoice::Anthropic,
- "openai" => ProviderChoice::OpenAi,
- "openai-compat" | "openai_compat" => ProviderChoice::OpenAiCompat,
- other => {
- return Err(LlmError::NotConfigured(format!(
- "AI_MEMORY_LLM_PROVIDER={other} is not one of anthropic|openai|openai-compat"
- )));
- }
- },
- Err(_) => return Ok(None),
- };
- // Sensible defaults per provider so the operator can set just the
- // provider env var and get a reasonable model. Override via
- // `AI_MEMORY_LLM_MODEL`. We pick the cheapest model that is still
- // smart enough to summarise a session into a coherent wiki page;
- // reasoning models are deliberately avoided in the defaults
- // because consolidation runs frequently and silently.
- let model = match std::env::var("AI_MEMORY_LLM_MODEL") {
- Ok(s) if !s.is_empty() => s,
- _ => match provider {
- ProviderChoice::Anthropic => "claude-sonnet-4-6".to_string(),
- ProviderChoice::OpenAi => "gpt-4o-mini".to_string(),
- // openai-compat covers Ollama / vLLM / LM Studio / OpenRouter.
- // What's available depends entirely on the user's setup, so
- // refuse to start without an explicit choice.
- ProviderChoice::OpenAiCompat => {
- return Err(LlmError::NotConfigured(
- "AI_MEMORY_LLM_MODEL must be set explicitly for openai-compat \
- (no safe default for self-hosted / aggregator endpoints)"
- .into(),
- ));
- }
- },
- };
- let base_url = std::env::var("AI_MEMORY_LLM_BASE_URL").ok();
- let api_key = match provider {
- ProviderChoice::Anthropic => std::env::var("ANTHROPIC_API_KEY")
- .ok()
- .map(secrecy::SecretString::from),
- ProviderChoice::OpenAi => std::env::var("OPENAI_API_KEY")
- .ok()
- .map(secrecy::SecretString::from),
- ProviderChoice::OpenAiCompat => std::env::var("LLM_API_KEY")
- .ok()
- .map(secrecy::SecretString::from),
- };
- Ok(Some(ProviderConfig {
- provider,
- model,
- api_key,
- base_url,
- }))
-}
-
/// Three embedders ship in v0.2.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EmbedderChoice {
@@ -167,68 +99,11 @@ pub fn build_embedder(config: EmbedderConfig) -> LlmResult<Arc<dyn Embedder>> {
Ok(arc)
}
-/// Read an `EmbedderConfig` from the environment.
-///
-/// Honours `AI_MEMORY_EMBEDDING_PROVIDER` (`openai` / `voyage`),
-/// `AI_MEMORY_EMBEDDING_MODEL`, `AI_MEMORY_EMBEDDING_DIM`,
-/// `AI_MEMORY_EMBEDDING_BASE_URL` (optional), and the appropriate
-/// API key env (`OPENAI_API_KEY` / `VOYAGE_API_KEY`).
-///
-/// Returns `Ok(None)` when `AI_MEMORY_EMBEDDING_PROVIDER` is unset —
-/// the canonical "no embeddings, FTS5 only" path.
-///
-/// # Errors
-/// Returns [`LlmError::NotConfigured`] when the provider value is
-/// unrecognised or when required env vars are missing.
-pub fn embedder_from_env() -> LlmResult<Option<EmbedderConfig>> {
- let provider = match std::env::var("AI_MEMORY_EMBEDDING_PROVIDER") {
- Ok(s) => match s.as_str() {
- "openai" => EmbedderChoice::OpenAi,
- "voyage" => EmbedderChoice::Voyage,
- other => {
- return Err(LlmError::NotConfigured(format!(
- "AI_MEMORY_EMBEDDING_PROVIDER={other} not one of openai|voyage"
- )));
- }
- },
- Err(_) => return Ok(None),
- };
- // Recommended embedder defaults; override via env. text-embedding-3-small
- // is the price/quality sweet spot for OpenAI; voyage-3 is Voyage's
- // current general-purpose model. Dim follows model when defaulted.
- let model = match std::env::var("AI_MEMORY_EMBEDDING_MODEL") {
- Ok(s) if !s.is_empty() => s,
- _ => match provider {
- EmbedderChoice::OpenAi => "text-embedding-3-small".to_string(),
- EmbedderChoice::Voyage => "voyage-3".to_string(),
- },
- };
- let dim: u32 = match std::env::var("AI_MEMORY_EMBEDDING_DIM") {
- Ok(s) if !s.is_empty() => s
- .parse()
- .map_err(|e| LlmError::NotConfigured(format!("AI_MEMORY_EMBEDDING_DIM: {e}")))?,
- _ => default_embedding_dim(provider, &model),
- };
- let base_url = std::env::var("AI_MEMORY_EMBEDDING_BASE_URL").ok();
- let api_key = match provider {
- EmbedderChoice::OpenAi => std::env::var("OPENAI_API_KEY")
- .map_err(|_| LlmError::NotConfigured("OPENAI_API_KEY".into()))?,
- EmbedderChoice::Voyage => std::env::var("VOYAGE_API_KEY")
- .map_err(|_| LlmError::NotConfigured("VOYAGE_API_KEY".into()))?,
- };
- Ok(Some(EmbedderConfig {
- provider,
- model,
- dim,
- api_key: SecretString::from(api_key),
- base_url,
- }))
-}
-
/// Default dim for known embedding models. Used when the operator
/// omits `AI_MEMORY_EMBEDDING_DIM`. Falls back to a model-family
/// default; unknown models still require an explicit dim.
-fn default_embedding_dim(provider: EmbedderChoice, model: &str) -> u32 {
+#[must_use]
+pub fn default_embedding_dim(provider: EmbedderChoice, model: &str) -> u32 {
match (provider, model) {
(EmbedderChoice::OpenAi, "text-embedding-3-small") => 1536,
(EmbedderChoice::OpenAi, "text-embedding-3-large") => 3072,
diff --git a/crates/ai-memory-llm/src/lib.rs b/crates/ai-memory-llm/src/lib.rs
index 1102b96b..0524aae2 100644
--- a/crates/ai-memory-llm/src/lib.rs
+++ b/crates/ai-memory-llm/src/lib.rs
@@ -28,12 +28,14 @@ pub mod openai_compat;
pub mod provider;
pub mod types;
+mod text;
+
pub use anthropic::AnthropicProvider;
pub use embedding::{Embedder, OpenAiEmbedder, SyntheticEmbedder, VoyageEmbedder, cosine};
pub use error::{LlmError, LlmResult};
pub use factory::{
EmbedderChoice, EmbedderConfig, ProviderChoice, ProviderConfig, build_embedder, build_provider,
- embedder_from_env, provider_from_env,
+ default_embedding_dim,
};
pub use openai::OpenAiProvider;
pub use openai_compat::OpenAiCompatProvider;
diff --git a/crates/ai-memory-llm/src/openai.rs b/crates/ai-memory-llm/src/openai.rs
index 5cc54b08..fff230b0 100644
--- a/crates/ai-memory-llm/src/openai.rs
+++ b/crates/ai-memory-llm/src/openai.rs
@@ -10,6 +10,7 @@ use tracing::debug;
use crate::error::{LlmError, LlmResult};
use crate::provider::LlmProvider;
+use crate::text::truncate_with_ellipsis;
use crate::types::{ChatRequest, ChatResponse, Role, Usage};
/// Default OpenAI API base.
@@ -242,21 +243,13 @@ impl OpenAiProvider {
let body = resp.text().await.unwrap_or_default();
return Err(LlmError::Provider {
status: status.as_u16(),
- body: truncate(&body, 1024),
+ body: truncate_with_ellipsis(&body, 1024),
});
}
resp.json::<OpenAiResponse>().await.map_err(LlmError::from)
}
}
-fn truncate(s: &str, n: usize) -> String {
- if s.len() <= n {
- s.to_string()
- } else {
- format!("{}…", &s[..n])
- }
-}
-
#[cfg(test)]
mod tests {
use super::normalize_openai_base;
diff --git a/crates/ai-memory-llm/src/openai_compat.rs b/crates/ai-memory-llm/src/openai_compat.rs
index d71273f2..c307de27 100644
--- a/crates/ai-memory-llm/src/openai_compat.rs
+++ b/crates/ai-memory-llm/src/openai_compat.rs
@@ -16,6 +16,7 @@ use tracing::debug;
use crate::error::{LlmError, LlmResult};
use crate::openai::OpenAiProvider;
use crate::provider::LlmProvider;
+use crate::text::{suffix_within_bytes, truncate_with_ellipsis};
use crate::types::{ChatRequest, ChatResponse};
// Compiled once. Matches <think>, <thinking>, <analysis>, <reasoning> blocks
@@ -115,9 +116,8 @@ impl LlmProvider for OpenAiCompatProvider {
// 4 KB tells the full story for any reasonable
// structured-output response. Includes head + tail
// because some failures truncate the closing brace.
- let head = truncate(&cleaned, 2000);
- let tail_start = cleaned.len().saturating_sub(2000);
- let tail = &cleaned[tail_start..];
+ let head = truncate_with_ellipsis(&cleaned, 2000);
+ let tail = suffix_within_bytes(&cleaned, 2000);
debug!(
head = %head,
tail = %tail,
@@ -176,14 +176,6 @@ fn first_json_object(s: &str) -> Option<&str> {
None
}
-fn truncate(s: &str, n: usize) -> String {
- if s.len() <= n {
- s.to_string()
- } else {
- format!("{}…", &s[..n])
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/ai-memory-llm/src/text.rs b/crates/ai-memory-llm/src/text.rs
new file mode 100644
index 00000000..d3b58cff
--- /dev/null
+++ b/crates/ai-memory-llm/src/text.rs
@@ -0,0 +1,56 @@
+//! Small text helpers shared by provider implementations.
+
+/// Truncate to at most `max_bytes` without splitting a UTF-8 codepoint.
+pub(crate) fn truncate_with_ellipsis(s: &str, max_bytes: usize) -> String {
+ if s.len() <= max_bytes {
+ return s.to_string();
+ }
+
+ let mut end = 0;
+ for (idx, ch) in s.char_indices() {
+ let next = idx + ch.len_utf8();
+ if next > max_bytes {
+ break;
+ }
+ end = next;
+ }
+ format!("{}…", &s[..end])
+}
+
+/// Return a suffix no longer than `max_bytes`, aligned to a UTF-8 boundary.
+pub(crate) fn suffix_within_bytes(s: &str, max_bytes: usize) -> &str {
+ if s.len() <= max_bytes {
+ return s;
+ }
+ let start = s
+ .char_indices()
+ .map(|(idx, _)| idx)
+ .find(|idx| s.len() - idx <= max_bytes)
+ .unwrap_or(s.len());
+ &s[start..]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn truncate_keeps_ascii_prefix() {
+ assert_eq!(truncate_with_ellipsis("abcdef", 3), "abc…");
+ assert_eq!(truncate_with_ellipsis("abc", 3), "abc");
+ }
+
+ #[test]
+ fn truncate_never_splits_utf8() {
+ let s = format!("{}é", "x".repeat(1023));
+ let truncated = truncate_with_ellipsis(&s, 1024);
+ assert!(truncated.ends_with('…'));
+ assert_eq!(truncated.chars().last(), Some('…'));
+ }
+
+ #[test]
+ fn suffix_never_splits_utf8() {
+ let s = format!("é{}", "x".repeat(1023));
+ assert_eq!(suffix_within_bytes(&s, 1024), "x".repeat(1023));
+ }
+}
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 14dc4292..9b7d6d19 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -25,10 +25,12 @@ use std::io::Seek;
use std::path::PathBuf;
use ai_memory_consolidate::{
- Bootstrap, BootstrapConfig, BootstrapOutcome, BootstrapSource, SourceCounts, run_lint,
- run_sweep,
+ Bootstrap, BootstrapConfig, BootstrapOutcome, BootstrapSource, SourceCounts,
+ prune_sources_to_budget, run_lint, run_sweep,
+};
+use ai_memory_core::{
+ DEFAULT_PROJECT_NAME, DEFAULT_WORKSPACE_NAME, PagePath, ProjectId, SessionId, Tier, WorkspaceId,
};
-use ai_memory_core::{PagePath, ProjectId, SessionId, Tier, WorkspaceId};
use ai_memory_llm::{Embedder, LlmProvider};
use ai_memory_store::{DecayParams, ReaderPool, StoreError, WriterHandle, f32_vec_to_bytes};
use ai_memory_wiki::{Wiki, WritePageRequest};
@@ -496,28 +498,9 @@ fn dry_run_outcome(
})),
));
}
- // Mirror the prune logic: sort by drop_priority desc, drop until
- // under budget. We replicate the constants here rather than
- // exposing prune_to_budget publicly (it's an implementation detail
- // of the consolidation pipeline).
- const CHARS_PER_TOKEN: usize = 4;
let collected = sources.len();
- let usable = max_input_tokens.saturating_sub(1_000);
- let mut sorted = sources;
- sorted.sort_by_key(|s| std::cmp::Reverse(s.kind.drop_priority()));
- let mut total: usize = sorted
- .iter()
- .map(|s| (s.label.len() + s.text.len() + 16).div_ceil(CHARS_PER_TOKEN))
- .sum();
- while total > usable && !sorted.is_empty() {
- let victim_tokens =
- (sorted[0].label.len() + sorted[0].text.len() + 16).div_ceil(CHARS_PER_TOKEN);
- total = total.saturating_sub(victim_tokens);
- sorted.remove(0);
- }
- let kept = &sorted;
- let dropped = collected - kept.len();
- let counts = SourceCounts::from_sources(kept);
+ let (kept, dropped, total) = prune_sources_to_budget(sources, max_input_tokens);
+ let counts = SourceCounts::from_sources(&kept);
let outcome = BootstrapOutcome {
sources_collected: collected,
sources_sent: kept.len(),
@@ -666,7 +649,11 @@ async fn handle_reorg(
State(state): State<Arc<AdminState>>,
Json(req): Json<ReorgRequest>,
) -> impl IntoResponse {
- let ws = match state.writer.get_or_create_workspace("default").await {
+ let ws = match state
+ .writer
+ .get_or_create_workspace(DEFAULT_WORKSPACE_NAME)
+ .await
+ {
Ok(id) => id,
Err(e) => {
return (
@@ -781,11 +768,11 @@ struct LintRequest {
}
fn default_workspace() -> String {
- "default".to_string()
+ DEFAULT_WORKSPACE_NAME.to_string()
}
fn default_project() -> String {
- "scratch".to_string()
+ DEFAULT_PROJECT_NAME.to_string()
}
async fn handle_lint(
diff --git a/crates/ai-memory-store/src/decay.rs b/crates/ai-memory-store/src/decay.rs
index 937056f7..e81c1f77 100644
--- a/crates/ai-memory-store/src/decay.rs
+++ b/crates/ai-memory-store/src/decay.rs
@@ -102,4 +102,20 @@ mod tests {
let stale = retention_score(&p, 100.0, 10, Some(120.0));
assert!(recent > stale, "recent {recent} vs stale {stale}");
}
+
+ #[test]
+ fn score_decreases_as_age_increases_without_access() {
+ let p = DecayParams::default();
+ let young = retention_score(&p, 10.0, 0, None);
+ let old = retention_score(&p, 20.0, 0, None);
+ assert!(young > old, "young {young} vs old {old}");
+ }
+
+ #[test]
+ fn score_increases_with_access_count_when_access_age_matches() {
+ let p = DecayParams::default();
+ let low = retention_score(&p, 100.0, 1, Some(5.0));
+ let high = retention_score(&p, 100.0, 20, Some(5.0));
+ assert!(high > low, "high {high} vs low {low}");
+ }
}
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index bac373dc..5475dffd 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -54,106 +54,9 @@ use crate::error::{StoreError, StoreResult};
///
/// Returns the id of the page row that should now be considered current.
pub fn upsert_page(conn: &mut Connection, page: &NewPage) -> StoreResult<PageId> {
- let body_sha256: [u8; 32] = {
- let mut hasher = Sha256::new();
- hasher.update(page.body.as_bytes());
- hasher.finalize().into()
- };
- let frontmatter_str = serde_json::to_string(&page.frontmatter_json)?;
let now = Timestamp::now().as_microsecond();
- let tier_str = page.tier.as_str();
-
let tx = conn.transaction()?;
-
- let existing: Option<(Vec<u8>, Vec<u8>)> = tx
- .query_row(
- "SELECT id, body_sha256 FROM pages \
- WHERE workspace_id = ?1 AND project_id = ?2 AND path = ?3 AND is_latest = 1",
- params![
- page.workspace_id.as_bytes(),
- page.project_id.as_bytes(),
- page.path.as_str(),
- ],
- |row| Ok((row.get(0)?, row.get(1)?)),
- )
- .optional()?;
-
- let result_id = if let Some((existing_id, existing_sha)) = existing {
- if existing_sha == body_sha256 {
- // Content unchanged; touch updated_at only and return existing id.
- tx.execute(
- "UPDATE pages SET updated_at = ?1 WHERE id = ?2",
- params![now, existing_id],
- )?;
- PageId::from_slice(&existing_id)?
- } else {
- let new_id = PageId::new();
- tx.execute(
- "UPDATE pages SET is_latest = 0 WHERE id = ?1",
- params![existing_id],
- )?;
- tx.execute(
- "INSERT INTO pages \
- (id, workspace_id, project_id, path, title, tier, body, body_sha256, \
- frontmatter_json, is_latest, supersedes, pinned, created_at, updated_at) \
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, 1, ?10, ?11, ?12, ?12)",
- params![
- new_id.as_bytes(),
- page.workspace_id.as_bytes(),
- page.project_id.as_bytes(),
- page.path.as_str(),
- page.title,
- tier_str,
- page.body,
- body_sha256.as_slice(),
- frontmatter_str,
- existing_id,
- i64::from(page.pinned),
- now,
- ],
- )?;
- audit(
- &tx,
- "supersede_page",
- Some(page.workspace_id.as_bytes()),
- Some(page.project_id.as_bytes()),
- Some(new_id.as_bytes()),
- now,
- )?;
- new_id
- }
- } else {
- let new_id = PageId::new();
- tx.execute(
- "INSERT INTO pages \
- (id, workspace_id, project_id, path, title, tier, body, body_sha256, \
- frontmatter_json, is_latest, pinned, created_at, updated_at) \
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, 1, ?10, ?11, ?11)",
- params![
- new_id.as_bytes(),
- page.workspace_id.as_bytes(),
- page.project_id.as_bytes(),
- page.path.as_str(),
- page.title,
- tier_str,
- page.body,
- body_sha256.as_slice(),
- frontmatter_str,
- i64::from(page.pinned),
- now,
- ],
- )?;
- audit(
- &tx,
- "create_page",
- Some(page.workspace_id.as_bytes()),
- Some(page.project_id.as_bytes()),
- Some(new_id.as_bytes()),
- now,
- )?;
- new_id
- };
-
+ let result_id = upsert_page_in_tx(&tx, page, now)?;
tx.commit()?;
Ok(result_id)
}
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index b01f6aa9..f90cbd85 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -1029,84 +1029,13 @@ impl ReaderPool {
JOIN projects p ON p.id = pg.project_id \
JOIN workspaces w ON w.id = pg.workspace_id \
LEFT JOIN pages sp ON sp.id = pg.supersedes \
- WHERE pg.path = ?1 AND pg.is_latest = 1 \
- LIMIT 1",
+ WHERE pg.path = ?1 AND pg.is_latest = 1 \
+ LIMIT 1",
params![path],
- |row| {
- let workspace_name: String = row.get(0)?;
- let project_name: String = row.get(1)?;
- let ws_id_bytes: Vec<u8> = row.get(2)?;
- let proj_id_bytes: Vec<u8> = row.get(3)?;
- let path: String = row.get(4)?;
- let title: String = row.get(5)?;
- let kind: String = row.get(6)?;
- let tier: String = row.get(7)?;
- let pinned: i64 = row.get(8)?;
- let created_us: i64 = row.get(9)?;
- let updated_us: i64 = row.get(10)?;
- let supersedes_path: Option<String> = row.get(11)?;
- Ok((
- workspace_name,
- project_name,
- ws_id_bytes,
- proj_id_bytes,
- path,
- title,
- kind,
- tier,
- pinned,
- created_us,
- updated_us,
- supersedes_path,
- ))
- },
+ page_meta_from_row,
)
.optional()?;
-
- let Some((
- workspace_name,
- project_name,
- ws_id_bytes,
- proj_id_bytes,
- path,
- title,
- kind,
- tier,
- pinned,
- created_us,
- updated_us,
- supersedes,
- )) = row_opt
- else {
- return Ok(None);
- };
-
- let workspace_id = WorkspaceId::from_slice(&ws_id_bytes)
- .map_err(|_| rusqlite::Error::IntegralValueOutOfRange(2, 0))?;
- let project_id = ProjectId::from_slice(&proj_id_bytes)
- .map_err(|_| rusqlite::Error::IntegralValueOutOfRange(3, 0))?;
-
- let created_at = jiff::Timestamp::from_microsecond(created_us)
- .map(|ts| ts.to_string())
- .unwrap_or_default();
- let updated_at = jiff::Timestamp::from_microsecond(updated_us)
- .map(|ts| ts.to_string())
- .unwrap_or_default();
-
- Ok(Some(PageMeta {
- workspace_name,
- project_name,
- workspace_id,
- project_id,
- path,
- title,
- kind,
- tier,
- pinned: pinned != 0,
- created_at,
- updated_at,
- supersedes,
- }))
+ row_opt.transpose()
})
.await
}
@@ -1232,84 +1161,13 @@ impl ReaderPool {
FROM pages pg \
JOIN projects p ON p.id = pg.project_id \
JOIN workspaces w ON w.id = pg.workspace_id \
- LEFT JOIN pages sp ON sp.id = pg.supersedes \
- WHERE w.name = ?1 AND p.name = ?2 AND pg.path = ?3 AND pg.is_latest = 1",
+ LEFT JOIN pages sp ON sp.id = pg.supersedes \
+ WHERE w.name = ?1 AND p.name = ?2 AND pg.path = ?3 AND pg.is_latest = 1",
params![workspace, project, page_path],
- |row| {
- let workspace_name: String = row.get(0)?;
- let project_name: String = row.get(1)?;
- let ws_id_bytes: Vec<u8> = row.get(2)?;
- let proj_id_bytes: Vec<u8> = row.get(3)?;
- let path: String = row.get(4)?;
- let title: String = row.get(5)?;
- let kind: String = row.get(6)?;
- let tier: String = row.get(7)?;
- let pinned: i64 = row.get(8)?;
- let created_us: i64 = row.get(9)?;
- let updated_us: i64 = row.get(10)?;
- let supersedes_path: Option<String> = row.get(11)?;
- Ok((
- workspace_name,
- project_name,
- ws_id_bytes,
- proj_id_bytes,
- path,
- title,
- kind,
- tier,
- pinned,
- created_us,
- updated_us,
- supersedes_path,
- ))
- },
+ page_meta_from_row,
)
.optional()?;
-
- let Some((
- workspace_name,
- project_name,
- ws_id_bytes,
- proj_id_bytes,
- path,
- title,
- kind,
- tier,
- pinned,
- created_us,
- updated_us,
- supersedes,
- )) = row_opt
- else {
- return Ok(None);
- };
-
- let workspace_id = WorkspaceId::from_slice(&ws_id_bytes)
- .map_err(|_| rusqlite::Error::IntegralValueOutOfRange(2, 0))?;
- let project_id = ProjectId::from_slice(&proj_id_bytes)
- .map_err(|_| rusqlite::Error::IntegralValueOutOfRange(3, 0))?;
-
- let created_at = jiff::Timestamp::from_microsecond(created_us)
- .map(|ts| ts.to_string())
- .unwrap_or_default();
- let updated_at = jiff::Timestamp::from_microsecond(updated_us)
- .map(|ts| ts.to_string())
- .unwrap_or_default();
-
- Ok(Some(PageMeta {
- workspace_name,
- project_name,
- workspace_id,
- project_id,
- path,
- title,
- kind,
- tier,
- pinned: pinned != 0,
- created_at,
- updated_at,
- supersedes,
- }))
+ row_opt.transpose()
})
.await
}
diff --git a/crates/ai-memory-wiki/src/markdown.rs b/crates/ai-memory-wiki/src/markdown.rs
index 7aaf223a..d544793a 100644
--- a/crates/ai-memory-wiki/src/markdown.rs
+++ b/crates/ai-memory-wiki/src/markdown.rs
@@ -113,6 +113,28 @@ mod tests {
assert_eq!(md.body, "The body.\n");
}
+ #[test]
+ fn parses_bom_prefixed_frontmatter() {
+ let src = "\u{FEFF}---\ntitle: Hello\n---\nBody\n";
+ let md = parse(src).unwrap();
+ assert_eq!(md.frontmatter["title"], "Hello");
+ assert_eq!(md.body, "Body\n");
+ }
+
+ #[test]
+ fn malformed_frontmatter_returns_error() {
+ let src = "---\ntitle: [unterminated\n---\nBody\n";
+ assert!(parse(src).is_err());
+ }
+
+ #[test]
+ fn unterminated_frontmatter_marker_is_body() {
+ let src = "---\ntitle: Hello\nBody\n";
+ let md = parse(src).unwrap();
+ assert!(md.frontmatter.is_null());
+ assert_eq!(md.body, src);
+ }
+
#[test]
fn parses_body_without_frontmatter() {
let src = "Just a body, no frontmatter.\n";
diff --git a/docs/install.md b/docs/install.md
index 4351c4f3..b44d764f 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -86,12 +86,12 @@ Claude Desktop, Gemini CLI, OpenClaw, pi) get MCP only - no
lifecycle hooks ship for them today. For the three flagship CLIs
(Claude Code, Codex, OpenCode), both are wired up.
-> **Two-step hook install pattern.** All three flagship CLIs use the
-> same shape: (1) `docker cp` the bundled scripts to your home dir,
+> **Two-step hook install pattern.** Claude Code and Codex use shell
+> hook scripts: (1) `docker cp` the bundled scripts to your home dir,
> (2) `docker run --rm install-hooks` to render the config snippet.
-> `docker cp` works on every docker setup (including rootless and
-> userns-remap); a `setup-agent` one-shot exists but has bind-mount
-> caveats — see [Bind mounts vs docker cp](#bind-mounts-vs-docker-cp).
+> OpenCode is different: it uses a TypeScript plugin generated by
+> `install-hooks --agent opencode`, so no shell-script extraction is
+> needed for that client.
### OpenAI Codex
@@ -119,14 +119,22 @@ docker run --rm akitaonrails/ai-memory:latest \
--server-url "http://homelab:49374/mcp" \
--auth-token "$TOKEN"
-docker cp ai-memory:/usr/local/share/ai-memory/hooks ~/.ai-memory/
+# Plugin — write to ~/.config/opencode/plugins/ai-memory.ts.
+# If you have the local wrapper installed, prefer `--apply`:
+ai-memory install-hooks --agent opencode --apply \
+ --server-url "http://homelab:49374" \
+ --auth-token "$TOKEN"
+
+# Docker-only preview path; redirect only if you want to write the file yourself:
docker run --rm akitaonrails/ai-memory:latest \
install-hooks --agent opencode \
- --hooks-dir ~/.ai-memory/hooks \
- --server-url "http://homelab:49374" \
- --auth-token "$TOKEN"
+ --server-url "http://homelab:49374" \
+ --auth-token "$TOKEN"
```
+Restart OpenCode after installing or changing the plugin; plugins are
+loaded at startup.
+
### Bind mounts vs docker cp
The `setup-agent` subcommand does the extract + render in one shot
@@ -205,8 +213,10 @@ docker run --rm akitaonrails/ai-memory:latest \
--auth-token "$TOKEN"
```
-The installer supports `--agent codex|opencode|claude-code` and
-`--to <dir>`; `--help` prints the full flag list.
+The curl script installer supports `--agent codex|claude-code` and
+`--to <dir>`; `--help` prints the full flag list. OpenCode does not
+need this script installer because `install-hooks --agent opencode`
+generates a TypeScript plugin instead.
This path is friction-free when:
- You have curl + bash but not docker
diff --git a/docs/mcp-install.md b/docs/mcp-install.md
index 9ad4352a..fa0bd852 100644
--- a/docs/mcp-install.md
+++ b/docs/mcp-install.md
@@ -20,8 +20,9 @@ This page documents how to register ai-memory as an MCP server with
the agent CLIs **that are not covered inline in the README**.
The three flagship clients - Claude Code, OpenAI Codex, OpenCode -
-have lifecycle-hook scripts under [`hooks/`](../hooks) and are
-covered in the [main README](../README.md#configure-your-agent-cli).
+have automatic capture integrations (shell hooks for Claude Code /
+Codex, a TypeScript plugin for OpenCode) and are covered in the
+[main README](../README.md#configure-your-agent-cli).
The clients on this page are **MCP-only**: they expose long-term
memory to their LLM via ai-memory's MCP tools (`memory_query`,
@@ -261,8 +262,8 @@ that *starts* the next one - to play nicely with ai-memory:
| Side | What's needed | Covered by |
|---|---|---|
-| **Ending side** | The `SessionEnd` hook must fire ai-memory's `/hook` endpoint. | Built-in for Claude Code / Codex / OpenCode via the scripts in `hooks/`. |
-| **Starting side** | Either (a) the `SessionStart` hook auto-injects the handoff via `/handoff`, OR (b) the model proactively calls `memory_handoff_accept` on first turn. | (a) is built-in for Claude Code / Codex / OpenCode. (b) works for any MCP-capable client if you nudge the model - see [the CLAUDE.md snippet](../README.md#nudging-the-agent-to-use-memory-proactively). |
+| **Ending side** | The agent must create a handoff, either through a true session-end hook or by calling `memory_handoff_begin`. | Built-in for Claude Code; Codex uses its stop/session hooks. OpenCode has no true session-end event, so ask it to call `memory_handoff_begin` before quitting when you need a handoff. |
+| **Starting side** | Either (a) the session-start/plugin path injects the handoff via `/handoff`, OR (b) the model proactively calls `memory_handoff_accept` on first turn. | (a) is built-in for Claude Code / Codex / OpenCode. (b) works for any MCP-capable client if you nudge the model - see [the CLAUDE.md snippet](../README.md#nudging-the-agent-to-use-memory-proactively). |
So a typical mixed workflow looks like:
diff --git a/scripts/install-hooks.sh b/scripts/install-hooks.sh
index 5392cde7..fd5ffcfc 100755
--- a/scripts/install-hooks.sh
+++ b/scripts/install-hooks.sh
@@ -10,7 +10,8 @@
# | bash -s -- --agent claude-code
#
# Options:
-# --agent <claude-code|codex|opencode> which agent (default: claude-code)
+# --agent <claude-code|codex|opencode> which agent (default: claude-code;
+# opencode prints a plugin hint)
# --to <dir> install root (default: $HOME/.ai-memory/hooks)
# --ref <git-ref> repo ref to pull from (default: main)
#
@@ -50,6 +51,13 @@ case "$AGENT" in
exit 64 ;;
esac
+if [[ "$AGENT" == "opencode" ]]; then
+ echo "OpenCode uses a generated TypeScript plugin, not shell hook scripts."
+ echo "Run: ai-memory install-hooks --agent opencode --apply"
+ echo "Then restart OpenCode so it loads ~/.config/opencode/plugins/ai-memory.ts."
+ exit 0
+fi
+
SCRIPTS=(
"session-start"
"user-prompt-submit"