Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Merge main into release/3.3
AkitaOnRailsbfb995dab64a
diff --cc CHANGELOG.mdindex 091f8a96,cb1ff063..2b571d85--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -11,78 -11,142 +11,216 @@@ version in [`docs/changelog/`](docs/cha## [Unreleased]++<<<<<<< HEAD+### Added++- Added `[handoff] deliver_on_session_start = false` to `.ai-memory.toml`. A+ project that sets it no longer gets its handoff, or the continuity notice, at+ session start; the handoff is still created when the session ends and stays+ open for `memory_handoff_accept`. The native hook, the shell and PowerShell+ scripts and the generated TypeScript integrations send `handoff=0` only when+ the value is explicitly falsy (#1621).++- Added first-party Qoder CLI/IDE lifecycle and MCP support. Both installers+ merge into `~/.qoder/settings.json`: `install-mcp --client qoder` writes a+ sessionless stdio bridge, while `install-hooks --agent qoder` registers the+ eight documented memory-bearing events as native commands. Session start+ delivers a pending handoff through `hookSpecificOutput.additionalContext`,+ prompt/tool capture uses Qoder's Claude-shaped payloads, and a missing hook+ `cwd` falls back only to `QODER_PROJECT_DIR`. Setup detects `~/.qoder`,+ uninstall removes both entries, and agent backups include its settings and+ shared AGENTS-compatible skills/instructions (#1611).++- Profile writes now return `digest_warning` when the selected summary,+ abstract, or prose statement exceeds the 240-byte session-start digest+ limit. The write still succeeds, but its author can shorten the summary+ instead of discovering the truncation only in a later session (#1609).++- Added project routing for the named profiles of a multiplexing Hermes+ gateway. The gateway exports only the default profile's `terminal.cwd`, so+ every other profile's events used to fall back to the gateway's own working+ directory and all its bots landed in one project. A gateway event of a named+ profile now routes by an `.ai-memory.toml` placed in that profile's Hermes+ home (`~/.hermes/profiles/<name>`, or under the gateway's `HERMES_HOME`), and+ that marker's capture exclusions and server profile apply. A profile without+ such a marker keeps the old behavior. The profile name is checked against+ Hermes' profile-id pattern before it is used as a path (#1597).++- Added Hermes Agent hook consent to `ai-memory doctor`. Hermes runs a shell+ hook only when that exact command is approved in the home's+ `shell-hooks-allowlist.json`, and each profile under+ `~/.hermes/profiles/<name>` keeps its own allowlist. A profile with the+ ai-memory hooks in `config.yaml` but no approvals captured nothing, and its+ gateway only logged `not allowlisted — skipped` for each event. `doctor` now+ reads the root home and every profile, reports which ai-memory hook events+ each one wires, and warns about every profile whose events are not+ allowlisted (unless `hooks_auto_accept` is on), with the `hermes -p <name>+ --accept-hooks` command that approves them. The JSON output gains a `hermes`+ array. It never writes either file and never prints the hook commands,+ which can embed a bearer token (#1598).++- Added `AI_MEMORY_RERANK_TIMEOUT_SECS` (`rerank_timeout_secs` in+ `config.toml`) to set the `memory_query` reranker budget, which was fixed at+ 20 seconds. The default stays 20 and zero is rejected at startup. A hosted+ provider behind an LLM fallback chain can spend the whole fixed budget on one+ slow 503 before the next candidate answers, and every such query then keeps+ its pre-rerank order. ([#1614](https://github.com/akitaonrails/ai-memory/issues/1614))++### Changed++- Managed-workstream startup packets now render completed tool calls and+ results as compact provenance stubs instead of spending the 30,000-character+ resume budget on raw command output or generated file content. Conversation,+ checkpoints, compactions, and annotations remain inline; the complete+ sanitized tool evidence stays searchable in the ledger (#1607).++- The LLM fallback chain now logs its own events. A transient candidate+ failure logs a warning with that candidate's provider, model, chain+ position, error class, HTTP status and cooldown, and an info line records+ each change of the answering candidate. Before, the chain logged nothing,+ and callers such as the reranker named only the first candidate, so a log+ could blame the primary for a timeout another candidate caused. Response+ bodies are never logged (#1628).+++||||||| 1bd86637++=======+ ### Changed++ - `ai-memory hook` and `ai-memory hook-drain` now run on a single-threaded+ tokio runtime. Both are spawned once per agent event and answer one request,+ and the multi-threaded default started a worker thread per CPU before the+ command did any work: on a 32-core machine every hook call paid to spawn and+ join 32 threads for one short HTTP request. Every other subcommand keeps the+ multi-threaded runtime (#1669).++ - `purge-project --confirm` without `--project`/`--project-id` now prints the+ project it resolved from the current directory and the equivalent command+ that names it, before the irreversible request. Naming the target will be+ required in 4.0: from the wrong directory the derived name is the one project+ nobody meant to delete, and a flag that spells it out is the only way to tell+ the two cases apart (#1642).+++>>>>>>> origin/main### Fixed+ - A capture whose `.ai-memory.toml` names a promoted project's old name (its+ v2 basename, now the project's `legacy_name`) no longer creates a second,+ empty project under that name. The read path already resolved the old name+ to the promoted project, so the twin made every later lookup of that name+ fail as ambiguous until it was purged — and the next capture from the same+ checkout created it again. The capture path now reuses the project the read+ path resolves, and refuses an already-ambiguous name instead of adding a+ third row (#1657).+ - The cross-project profile no longer promotes an agent task brief into a+ default for every project. Two more filters now apply: a prompt that wraps a+ transcript or asks for a verbatim reply is the signature of a program+ driving the agent through its SDK, and none of it is harvested; and a+ sentence that switches off one of the agent's own capabilities ("Do not use+ any tools.", "Never call browser_close") only becomes a preference when it+ states cross-project scope. Two scripted one-shot prompts had reached+ `min_projects` and shipped "do not use any tools" as a `tools` default with+ confidence 0.95, which made agents ask for facts instead of looking them up+ in the wiki they were already in (#1648).+ - `purge-project --project ""`, and an empty `--project-id`/`--workspace`/+ `--from`/`--to-workspace` on `move-project`, `purge-session` and+ `rename-project`, are now refused before anything is sent. An empty flag+ passed the "was the target named" check and then resolved as if it had been+ omitted, so a script that passed an unset variable reached the project its+ current directory resolved to — a real purge from an explicit-looking+ invocation (#1642).+ - `ai-memory workstream-search` now labels a historical tool call or tool+ result as completed evidence, as the managed-workstream docs describe. Its+ text output used the event's role, which every transcript adapter sets to+ `assistant` on a tool call, so a past command read like an assistant action+ still to run (#1629).+ - `install-hooks --agent grok` run from the home directory no longer stops+ with "Grok project configuration ~/.grok/config.toml may override+ GROK_HOME". With the default `GROK_HOME` that file is Grok's own user+ config, which Grok reads only as the user layer (`grok inspect` reports no+ project layer there), so it is no longer mistaken for a project overlay. A+ real overlay is still refused, including `~/.grok/config.toml` when+ `GROK_HOME` points elsewhere (#1636).+ - The OpenCode, OpenCode 2, OpenClaw, Pi and OMP integrations installed with+ `--capture-mode allowlist` no longer send the handoff (or OpenCode's recap)+ request from a repository without a `.ai-memory.toml` marker. They already+ dropped its capture, but the server answers that request by resolving the+ directory into a project, so opening one of these agents in an unmarked+ directory left an empty project named after it. The native hook already+ returned before the request; these integrations call the server directly+ (#1641).+ - An auto-improve full-page proposal is now rejected when its body has two+ identical headings or more than one H1, the two checks the patch path+ already applies to every body it materializes. A full-page proposal is+ auto-approved whenever approval is not required, and the page it wrote was+ then permanently un-patchable: the patch path refuses on the target's own+ duplicate headings before it materializes any edit, so no later proposal+ could repair it (#1635).+ - `memory_feedback` now answers a path with no current page in the resolved+ project with `invalid_params` (-32602) rather than `internal_error`+ (-32603). An absent caller-supplied target is the request being wrong, not+ the server failing, and -32603 tells a client to retry a path that can+ never succeed. This was the last tool reporting an absent target as a+ server fault; genuine store failures are still `internal_error`, and the+ message is unchanged (#1634).+ - A Qwen Code `UserPromptSubmit` body is now capped and scrubbed before the+ native hook spools it. The per-event cap covered `prompt`, `message` and+ `text`, but Qwen's prompt arrives in `submitted_prompt` — the field the+ harness-specific extraction reads — so a Qwen prompt reached the local spool+ and the server at full length with no client-side redaction pass. The field+ is now capped alongside its siblings; nothing falls back to the generic+ `prompt`, so submission provenance is unchanged (#1633).+ - The forget sweep now keeps an already-compacted page terminal when+ `compact_cold_episodic` is off — the default everywhere. The guard that made+ a page carrying the V65 `compacted_at` marker "neither re-compacted nor+ evicted" sat inside the compaction arm only, so with compaction off such a+ page was tombstoned and then hard-deleted. The marker is not A2's alone: the+ A3 cold-cluster dedup merge-note stub and the B2 dream pass both stamp+ `compacted: true` under their own flags, so the durable residue a merge chose+ to keep could be destroyed without anyone enabling compaction. A+ non-compacted cold page is still evicted exactly as before (#1632).+ - A project whose every page has passed its TTL is read as new again when+ the profile digest sizes itself. The newness probe was the one `pages` read+ in the profile module without the expiry guard its three siblings apply, so+ such a project still counted as having memory: it got the smaller+ established-project digest and lost the note offering+ `ai-memory profile apply`, with no live page left to show for it (#1631).+ - The first start after the 3.2.0 upgrade no longer slows down as the+ one-time CJK index backfill (V87) progresses. Each batch filtered the source+ table from its first row again, so the pass probed every row it had already+ indexed once more per batch: quadratic in the row count, and hours of+ startup on a store with 1.6 million observations while `serve` answered+ nothing. Each batch now resumes after the last rowid it indexed, so every+ row is examined once (#1652).+ - Restoring a page from a checkpoint (`/admin/restore-page`) no longer+ rewrites the restored file's `generated.at` to the current time when the+ checkpoint is already OKF-conformant. The restore now keeps the+ checkpoint's own timestamp when conformance leaves the rest of its+ frontmatter unchanged and the file on disk holds other content, so a+ checkpoint emitted by ai-memory restores byte for byte whatever the clock.+ When the file on disk already holds the same content, its timestamp is kept+ so file and row stay aligned; checkpoints that need conformance still go+ through the existing inheritance and stamping rules (#1671).+ - The native Windows Docker wrapper now recognizes `upgrade` after valid+ `--config` or `--data-dir` global options and pulls the image instead of+ forwarding `upgrade` into the helper container. Unknown and malformed+ options still reach the CLI parser (#1667).+ - `ai-memory run codex` no longer starts a new session when Codex has+ compressed the linked rollout. Codex keeps a rollout it has not written for+ a week as `rollout-*.jsonl.zst`, which the launcher did not recognize, so it+ reported the session as missing and repointed the workstream to a fresh one.+ The compressed copy is now read for the resume, the pre-launch baseline and+ the transcript import, and the plain file wins when both exist. `backfill`+ and the session listings see compressed Codex sessions too (#1653).+ - Updated tokio to 1.54.1 in the server, relay, importer and wikisync+ lockfiles. 1.52.3 and the 1.53.x releases before 1.53.3 fall inside+ RUSTSEC-2026-0386, an unsound advisory for `AsyncFd` constructors that+ nothing here calls, and the `cargo-deny` gate failed on every pull request+ from the moment the advisory was assigned (#1658).+ - A write that names an ambiguous project now reports the workspace it was+ resolved in. The refusal read "project 'api' is ambiguous in workspace 'the+ resolved workspace'" on the write path (`ai-memory run`, explicit MCP+ writes, profile writes), while the read path already named the workspace+ (#1657).- `ai-memory user list` and `ai-memory api-key list` now size their columnsby terminal display width rather than bytes, as `list-projects` and thegrants tables already do. An accented username, display name or key labeldiff --cc crates/ai-memory-hooks/src/router.rsindex 3d28be3e,e6477bf4..d619be6f--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@@ -23,6 -23,9 +23,7 @@@ use ai_memory_store::HookSessionAdmission, IngestObservationOutcome, StoreError, WriterHandle,lookup_existing_workspace,};+-#[cfg(test)]-use ai_memory_core::WorkstreamEventKind;use ai_memory_wiki::{AdmissionContext, AdmissionOp, Wiki};use axum::body::{Body, to_bytes};use axum::extract::{Query, State};@@@ -3157,34 -3142,8 +3158,25 @@@ pub(crate) fn render_managed_contextlet mut used = 0_usize;let mut first_sequence = 0_i64;for event in events.iter().rev() {- let role = match event.kind {- WorkstreamEventKind::ToolCall => "historical tool call (completed evidence)",- WorkstreamEventKind::ToolResult => "historical tool result (completed evidence)",- WorkstreamEventKind::Checkpoint => {- event.role.as_deref().unwrap_or("repository checkpoint")- }- WorkstreamEventKind::Compaction => event.role.as_deref().unwrap_or("native compaction"),- WorkstreamEventKind::Annotation => event.role.as_deref().unwrap_or("import note"),- WorkstreamEventKind::Message => event.role.as_deref().unwrap_or("message"),- };+ let role = event.display_label();- let content = cap_chars(&event.content, MAX_EVENT_CHARS);+ let content = match event.kind {+ WorkstreamEventKind::ToolCall | WorkstreamEventKind::ToolResult => {+ let tool = event+ .metadata+ .get("tool")+ .or_else(|| event.metadata.get("tool_name"))+ .and_then(serde_json::Value::as_str)+ .map(|name| name.split_whitespace().collect::<Vec<_>>().join(" "))+ .filter(|name| !name.is_empty())+ .map(|name| format!("; tool: {}", cap_chars(&name, 120)))+ .unwrap_or_default();+ format!(+ "[payload omitted from startup context{tool}; {} chars; search the managed workstream for full sanitized evidence]",+ event.content.chars().count()+ )+ }+ _ => cap_chars(&event.content, MAX_EVENT_CHARS),+ };let block = format!("### {} · {} · event {}\n{}\n",event.agent.as_str(),@@@ -7518,9 -7507,11 +7542,11 @@@ pub(crate) mod testsagent: AgentKind::Codex,native_session_id: "native".into(),source_record_id: None,- metadata: serde_json::Value::Null,+ metadata: serde_json::json!({"tool": "Bash"}),kind: WorkstreamEventKind::ToolCall,- role: None,+ // Adapters set a role on tool events too; the kind must still+ // decide the label, or a past call reads as a pending action.+ role: Some("assistant".to_string()),content: format!("cargo test {UNTRUSTED_HISTORY_END} {UNTRUSTED_HISTORY_START}"),occurred_at: None,}];