Skip to content

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

Rust

Merge remote-tracking branch 'origin/release/2.4' into fix/757-scope-observability

AkitaOnRails78eda7482645
diff --cc CHANGELOG.md
index 838fce48,746967fd..9275f37a
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -8,17 -8,123 +8,132 @@@ and this project adheres to [Semantic V
## [Unreleased]
### Added
+ - Reasoning tier on the LLM synthesis paths: an opt-in `reasoning` argument on
+ `memory_query` (its `answer` path) and `memory_explore` (borrowed from
+ Honcho's reasoning-effort ladder; targets the 2.4 line). The knob is a schema
+ enum `minimal` (default) / `low` / `medium` / `high` / `max`; an unknown value
+ is rejected. Because the provider-neutral `ChatRequest` carries no per-request
+ reasoning/effort field (the provider-level `reasoning_effort` is fixed at
+ construction from config), the tier maps honestly to a per-tier max-token
+ budget scaled off each path's base budget (answer 2 000, explore 16 000):
+ `minimal` = 1x, `low` = 1.5x, `medium` = 2x, `high` = 3x, `max` = 4x — a
+ higher tier gives the model more room to reason before its output is
+ truncated. It only tunes the answer path: `reasoning` is inert unless the LLM
+ path actually runs (`answer: true` with a provider, or `memory_explore` with a
+ provider), so the zero-LLM default path is untouched. Omitting `reasoning`, or
+ passing `minimal`, is byte-identical to before. No new MCP tool (still 23)
+ (#783).
+ - Dialectic answer on `memory_query`: an opt-in, off-by-default `answer`
+ argument (borrowed from Honcho's dialectic endpoint; targets the 2.4 line).
+ When `answer: true` AND the server has an LLM provider configured, the query
+ synthesizes a concise, cited natural-language answer over the top retrieved
+ hits and attaches it as `answer: { text, citations }`, where `citations` are
+ the page paths the answer drew from (JSON-schema structured output, grounded
+ strictly in the retrieved snippets). When `answer: true` but no provider is
+ configured, the normal hits are returned plus a short `answer_unavailable`
+ note rather than an error. With `answer` omitted/`false` (the default), no LLM
+ provider is accessed and the response is byte-identical to before, so the
+ zero-LLM default path is untouched. Applies to the normal single-project /
+ `scopes` search; `global` and `as_of` queries ignore it. Honest caveat: the
+ feature is new and its answer quality is not yet eval-validated — treat the
+ synthesized answer as a convenience over the same hits and still open the
+ cited pages before acting (#782).
+ - "Pin before search": `memory_query` gained an opt-in `pin_first` argument and
+ `memory_briefing` now carries a bounded `pinned` list (default off/absent;
+ targets the 2.4 line). Pinned pages previously earned only a small post-RRF
+ authority bump; they were never surfaced *ahead of* the search, and the
+ briefing never listed them by the `pinned` column. With `pin_first: true`, a
+ single-project `memory_query` prepends the project's bounded pinned latest
+ pages (newest first, cap 10) ahead of the fused hits, deduped by page id so a
+ pinned page that also matches the query appears once (marked `pinned: true`),
+ and re-truncates to the requested limit; `scopes`, `global`, and `as_of`
+ queries ignore it. A project-scoped `memory_briefing` snapshot now includes a
+ bounded `pinned` list of pinned latest pages (distinct from the `_slots/`
+ path-prefixed `slots`) so SessionStart hot-context can show standing context.
+ Both are backed by the new `ReaderPool::list_pinned_pages`; default off/empty
+ is byte-identical to the previous query ordering and briefing shape (#780).
+ - `memory_read_page` gained an opt-in related-pages graph walk (default false;
+ targets the 2.4 line). Passing `include_related: true` adds a `related` array
+ of the pages reachable from the read page through the link graph — a bounded
+ breadth-first walk that reuses the single-hop link primitive per node,
+ following both outgoing links and incoming back-links out to `related_depth`
+ hops (default 1, hard-capped at 3). Each entry carries its
+ path/title/kind/workspace/project plus the hop `depth` and edge `direction`
+ (`link`/`backlink`) it was reached by; the walk is cross-project aware,
+ dedup- and cycle-safe via a global visited set, and bounded by a total-node
+ cap. Default-off behaviour is byte-identical to the previous single-page
+ response (no `related` field) (#775).
+ - `memory_query` gained an opt-in `include_superseded` argument (default false;
+ targets the 2.4 line). When set, project and explicit-scope searches also
+ return superseded (older) page versions across the FTS/entity/vector/graph
+ streams, each hit labelled `superseded: true` so callers can tell historical
+ versions from the current one; the current version is never marked. Default-off
+ behaviour is byte-identical to the previous latest-only retrieval, and
+ `global=true` and `as_of` time-travel are unaffected (#773).
+- `memory_status` now reports which project answered: a `scope` object with
+ `workspace`, `project`, and `resolved_by` (`explicit`, `session`,
+ `shared_slot`, `startup_seed`, `default`, or `default_after_mismatch`). An
+ unscoped call from a static MCP client, whose transport session id is not a
+ lifecycle-hook session id, returned plausible counts for a project it never
+ named, with nothing in the response to question them; `resolved_by` now makes
+ that visible. The server also logs a warning whenever an unscoped MCP read is
+ resolved by the startup seed or by the default after a session mismatch,
- rather than by the caller's own hook session (#757).
++ rather than by the caller's own hook session (#757, #774).
+
+ ### Changed
+ - `memory_consolidate` accepts an omitted `session_id`. Omitting the field (or
+ sending `null`) no longer fails deserialization with `missing field
+ session_id`; the tool consolidates the latest completed session in the
+ resolved project — the same default `memory_auto_improve` and
+ `memory_read_session_observations` already use. Pass an explicit UUID to
+ target a specific session, and `dry_run=true` for the cheap admission
+ preflight. A project with no completed session now fails as
+ `no completed session in <scope>` instead of a deserialization error.
+ - A consolidation LLM call that fails on a transient provider error (`429`, any
+ `5xx`, a transport timeout or connect failure) is retried twice, two seconds
+ apart, before the failure is reported — the same bounded policy `bootstrap`
+ already applies to its chunks. Deterministic failures (auth, schema, a
+ malformed-request `4xx`, unparseable or truncated output) are still reported
+ on the first attempt, since retrying them only burns another call.
### Fixed
+ - `ai-memory serve` no longer hard-fails to take its single-instance lock on a
+ transient error under load. Acquiring the serve lock now retries `open` and
+ `try_lock_exclusive` a few times with a short (~25ms) backoff when they hit a
+ transient failure (EMFILE/ENFILE fd exhaustion, EINTR), mirroring
+ `acquire_drain_lock`. A genuinely contended lock (`WouldBlock`, another server
+ holds it) is never retried and still refuses startup immediately. The
+ serve-lock tests also assert with the concrete errno so any remaining
+ environmental flake is diagnosable rather than silent (#745).
+ - GitHub Copilot completion requests now select the model-advertised API
+ endpoint from `/models`: existing Chat Completions remains preferred when
+ available, while Responses-only models use `/responses`. Responses requests
+ preserve strict JSON Schema structured-output constraints and report empty,
+ refused, or rejected output without silently downgrading the contract. A model
+ the `/models` catalogue does not enumerate (enterprise/custom deployments,
+ aliases, a model newer than the list) falls back to Chat Completions with a
+ warning instead of erroring, matching the graceful fallback already used when
+ `/models` is unavailable. As a related behavior change, a Copilot chat
+ completion that returns empty content now reports `UnexpectedShape` rather
+ than yielding an empty string. (#761)
+ - The V62 page-ingestion-window migration no longer runs its backfill inside a
+ single migration transaction, which on a large store ran for hours and grew
+ the WAL to roughly the size of the database with no progress. V62 is now
+ DDL-only (the two columns plus their index); the window backfill moved to a
+ chunked, resumable, WAL-bounded boot-path step that processes pages in bounded
+ batches, checkpoints the WAL (`TRUNCATE`) between each, and logs progress. The
+ end state is byte-identical to the original V62, the step resumes rather than
+ restarts if interrupted, and it is a fast no-op on a store that already applied
+ the original V62. Because that reshape changes the migration's checksum, the
+ runner now intentionally tolerates a divergent checksum on an already-applied
+ migration (`abort_divergent = false`) so correctly-migrated stores still open;
+ the schema-ahead guard (`abort_missing`) is unchanged (#776).
+ - Page writes now refuse git-reserved and non-portable page paths (a `.git`
+ component or an 8.3 `git~1`..`git~4` alias, Windows-reserved names and
+ characters) on every write funnel, including MCP `memory_write_page` and
+ consolidation `apply_batch`; reads of already-stored pages stay tolerant so
+ a bad row never breaks a listing. The git-reserved check is byte-safe and no
+ longer panics on a 5-byte multibyte path component (#781).
- The generated OpenCode and OpenCode 2 plugins now forward a subagent session's
`parentID` as the `agent_id` marker, so `[capture] drop_subagent_captures` can
recognize and drop OpenCode subagent sessions. Previously both plugins emitted
diff --cc crates/ai-memory-mcp/src/server.rs
index 0522f1f7,6efc69cb..17ad2a2d
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@@ -9608,77 -10075,59 +10136,130 @@@ mod tests
assert!(text.contains("\"pages_latest\": 1"));
}
+ /// A scope that does not resolve is caller input, not a server fault: the
+ /// tool must answer with `invalid params` (`-32602`) instead of an opaque
+ /// internal error (`-32603`), and keep the message callers already match on.
+ #[tokio::test]
+ async fn memory_status_reports_an_unknown_project_as_invalid_params() {
+ let (_tmp, _store, server, _ws, _pj) = setup_server().await;
+ let err = server
+ .memory_status(
+ Parameters(StatusArgs {
+ project: Some("caminhar".into()),
+ workspace: Some("default".into()),
+ }),
+ OptionalParts(test_parts_default()),
+ )
+ .await
+ .expect_err("an unknown project must be rejected");
+ assert_eq!(err.code, rmcp::model::ErrorCode::INVALID_PARAMS);
+ assert_eq!(
+ err.message, "project 'caminhar' not found in workspace 'default'",
+ "the scope message must not change"
+ );
+ }
+
+ /// The classification is by error class, not by tool: a malformed scope
+ /// argument is `invalid params` (the not-found half is covered by the tool
+ /// test above), while a missing writer handle or an underlying store
+ /// failure stay internal errors — the caller cannot fix those by changing
+ /// the request.
+ #[test]
+ fn scope_error_keeps_internal_failures_internal() {
+ use ai_memory_store::ScopeResolutionError;
+
+ for err in [
+ ScopeResolutionError::WorkspaceProjectPairRequired,
+ ScopeResolutionError::ScopeProjectEmpty,
+ ] {
+ assert_eq!(
+ AiMemoryServer::scope_error(err).code,
+ rmcp::model::ErrorCode::INVALID_PARAMS,
+ );
+ }
+
+ for err in [
+ ScopeResolutionError::WriterRequired,
+ ScopeResolutionError::Store("disk on fire".into()),
+ ] {
+ assert_eq!(
+ AiMemoryServer::scope_error(err).code,
+ rmcp::model::ErrorCode::INTERNAL_ERROR,
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn memory_status_names_the_project_that_answered() {
+ // #757: a static MCP client's transport session id is not a hook
+ // session id, so its unscoped read cannot follow the caller's cwd. The
+ // counts must say whose they are, or they read as plausible and wrong.
+ let (_tmp, store, server, ws, _pj) = setup_server().await;
+ let neighbour = store
+ .writer
+ .get_or_create_project(ws, "neighbour", None)
+ .await
+ .unwrap();
+ let hook_session = ai_memory_core::ActorKey {
+ user: None,
+ session_id: Some("hook-session".into()),
+ };
+ let pointer = ActiveProject::new();
+ pointer.set_for(&hook_session, ws, neighbour, false);
+ let server = server.with_active_project(pointer);
+
+ let status = |session: &'static str, workspace: Option<&str>, project: Option<&str>| {
+ let mut parts = test_parts_default();
+ parts
+ .headers
+ .insert("mcp-session-id", session.parse().unwrap());
+ let args = StatusArgs {
+ workspace: workspace.map(str::to_owned),
+ project: project.map(str::to_owned),
+ };
+ let server = &server;
+ async move {
+ let result = server
+ .memory_status(Parameters(args), OptionalParts(parts))
+ .await
+ .unwrap();
+ let text = result
+ .content
+ .first()
+ .and_then(|c| c.as_text())
+ .map(|t| t.text.clone())
+ .unwrap();
+ serde_json::from_str::<serde_json::Value>(&text).unwrap()["scope"].clone()
+ }
+ };
+
+ assert_eq!(
+ status("hook-session", None, None).await,
+ serde_json::json!({
+ "workspace": "default",
+ "project": "neighbour",
+ "resolved_by": "session",
+ })
+ );
+ assert_eq!(
+ status("transport-session", None, None).await,
+ serde_json::json!({
+ "workspace": "default",
+ "project": "scratch",
+ "resolved_by": "default_after_mismatch",
+ }),
+ "a static client falls back to the server default and says so"
+ );
+ assert_eq!(
+ status("transport-session", Some("default"), Some("neighbour")).await,
+ serde_json::json!({
+ "workspace": "default",
+ "project": "neighbour",
+ "resolved_by": "explicit",
+ })
+ );
+ }
+
#[tokio::test]
async fn memory_briefing_returns_structured_snapshot() {
let (_tmp, _store, server, _ws, _pj) = setup_server().await;
diff --cc docs/ARCHITECTURE.md
index 93be6dce,7a0f3e94..81414be0
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@@ -369,13 -369,13 +369,13 @@@ invariants below
| Tool | Hint | Purpose |
|---|---|---|
- | `memory_query` | read-only | FTS5 + entity-match + graph RRF + optional vector RRF search, followed by bounded kind/tier/pinned/tag authority adjustment and raw fallback. Bumps access counters for page hits. Defaults to the current project; default-scoped calls also union the reserved `_global` preferences scope as `global_scope_hits`; `scopes` searches named sibling projects; `global=true` searches every project at once (each hit annotated with its workspace + project). With `AI_MEMORY_RERANKER=llm`, project/scopes candidate pools are fused before at most one final LLM relevance pass; query/title/snippet data is bounded and JSON-encoded, and any timeout, provider error, invalid/incomplete score set, or four-call concurrency saturation preserves the adjusted order. The distinct `global=true` FTS-only ranker and supplemental global-preference hits are not reranked. `explain=true` attaches per-hit `score_details` (per-stream ranks, matched entities, raw FTS/cosine/entity inverse-frequency scores, RRF contributions, graph provenance including the typed edge kind (`causes`/`fixes`/`contradicts`) a neighbour was reached by, the page's evidence count, authority multiplier, and optional rerank score) to project/scopes hits plus a top-level `streams_active` list. The global FTS-only ranker reports its active stream without per-hit details. `include_expired=true` also returns TTL-expired pages. |
+ | `memory_query` | read-only | FTS5 + entity-match + graph RRF + optional vector RRF search, followed by bounded kind/tier/pinned/tag authority adjustment and raw fallback. Bumps access counters for page hits. Defaults to the current project; default-scoped calls also union the reserved `_global` preferences scope as `global_scope_hits`; `scopes` searches named sibling projects; `global=true` searches every project at once (each hit annotated with its workspace + project). With `AI_MEMORY_RERANKER=llm`, project/scopes candidate pools are fused before at most one final LLM relevance pass; query/title/snippet data is bounded and JSON-encoded, and any timeout, provider error, invalid/incomplete score set, or four-call concurrency saturation preserves the adjusted order. The distinct `global=true` FTS-only ranker and supplemental global-preference hits are not reranked. `explain=true` attaches per-hit `score_details` (per-stream ranks, matched entities, raw FTS/cosine/entity inverse-frequency scores, RRF contributions, graph provenance including the typed edge kind (`causes`/`fixes`/`contradicts`) a neighbour was reached by, the page's evidence count, authority multiplier, and optional rerank score) to project/scopes hits plus a top-level `streams_active` list. The global FTS-only ranker reports its active stream without per-hit details. `include_expired=true` also returns TTL-expired pages. `include_superseded=true` also returns superseded (non-latest) page versions across the FTS/entity/vector/graph streams, each hit labelled `superseded: true` (the current version is never marked); default-off is byte-identical to the latest-only behaviour, and `global=true` / `as_of` are unaffected. `pin_first=true` prepends the project's bounded pinned latest pages (`ReaderPool::list_pinned_pages`, cap 10) ahead of the fused hits, deduped by page id (a pinned page that also matches appears once, marked `pinned: true`) and re-truncated to the requested limit; it applies to single-project searches (default or `workspace`+`project`), is ignored on `scopes`/`global`/`as_of`, and default-off is byte-identical. `answer=true` (opt-in, off by default) additionally synthesizes a cited natural-language answer over the top hits via the configured LLM provider (`complete_structured`, JSON-schema `{ answer, citations }`), attached as `answer: { text, citations }`; with no provider configured it returns the hits plus an `answer_unavailable` note instead of erroring, and with `answer` unset/`false` no provider is accessed and the response is byte-identical (invariant #13). It applies to the normal single-project/`scopes` path; `global`/`as_of` ignore it. Answer quality is not yet eval-validated. An optional `reasoning` tier (`minimal` (default) / `low` / `medium` / `high` / `max`) tunes the synthesis effort: `ChatRequest` carries no per-request reasoning field (the provider-level `reasoning_effort` is fixed at construction from config), so the tier maps to a per-tier max-token budget scaled off the path's base (answer base 2 000; `minimal` = 1x = byte-identical, `low` 1.5x, `medium` 2x, `high` 3x, `max` 4x). The tier is inert unless the `answer` LLM path runs (invariant #13); an unknown value is rejected by the schema (invariant #7). |
| `memory_recent` | read-only | Most-recently-updated `is_latest=1` pages. |
- | `memory_read_page` | read-only | Fetch the FULL body of a single wiki page by `path` or by top FTS5 hit for a `query`; optional `workspace` + `project` targets a named sibling workspace/project. Use when an agent needs more than the 24-word snippets from `memory_query`. |
+ | `memory_read_page` | read-only | Fetch the FULL body of a single wiki page by `path` or by top FTS5 hit for a `query`; optional `workspace` + `project` targets a named sibling workspace/project. Use when an agent needs more than the 24-word snippets from `memory_query`. `include_related=true` also walks the link graph outward from the page (bounded BFS reusing the `page_links` primitive per node: default 1 hop, hard cap 3, global visited set for dedup/cycle-safety, total-node cap 50, cross-project aware) and returns a `related` array of reachable pages, each labelled with its `depth` (hop distance) and `direction` (`link`/`backlink`); default-off is byte-identical (no `related` field). |
| `memory_read_session_observations` | read-only | Page through ONE session's raw hook observations (`ObservationRecord` with full sanitized body, capped per row by `body_max_chars`), restricted to the rows that landed in the resolved scope and to sessions the caller may see; `total` and `elided_other_scope` report the in-scope count and the rows the session left in another project. `session_id` omitted reads the latest completed visible session. |
-| `memory_status` | read-only | Counts, paths, version. |
+| `memory_status` | read-only | Counts, paths, version, plus the `scope` that answered: `workspace`, `project`, and `resolved_by` (`explicit`, `session`, `shared_slot`, `startup_seed`, `default`, `default_after_mismatch`). Unscoped reads resolved by `startup_seed` or `default_after_mismatch` also log a server warning. |
- | `memory_briefing` | read-only | Structured counts/activity/rules/slots/recent snapshot. Opt-in `settled_first: true` leads with up to 8 of the project's highest-standing `rule`/`decision` pages, ordered by evidence count then recency; off by default. |
- | `memory_explore` | read-only | LLM prose digest over the briefing snapshot, degrading to JSON without a provider. |
+ | `memory_briefing` | read-only | Structured counts/activity/rules/slots/recent snapshot. Project-scoped snapshots also carry a bounded `pinned` list (up to 10) of the project's pinned latest pages (`pinned = 1`, newest first) as standing SessionStart hot-context — distinct from `slots`, which is keyed by the `_slots/` path prefix; empty and omitted from JSON when the project has no pins, so the default shape is unchanged. Opt-in `settled_first: true` leads with up to 8 of the project's highest-standing `rule`/`decision` pages, ordered by evidence count then recency; off by default. |
+ | `memory_explore` | read-only | LLM prose digest over the briefing snapshot, degrading to JSON without a provider. An optional `reasoning` tier (`minimal` (default) / `low` / `medium` / `high` / `max`) scales the digest's max-token budget off its base (16 000; same 1x/1.5x/2x/3x/4x mapping as `memory_query`); inert on the no-provider briefing-only path, and `minimal` is byte-identical. |
| `memory_handoff_begin` | destructive | Open an owner-scoped handoff for the next agent; `shared=true` deliberately publishes it to the project. Optional `workspace` + `project` targets a named sibling workspace/project. |
| `memory_handoff_list` | read-only | List open own/shared handoffs with inspectable body and identity fields; does not claim or expire. Root-only `any_owner=true` recovers across operators. Optional `workspace` + `project` targets a named sibling workspace/project. |
| `memory_handoff_accept` | destructive | Fetch + ack an open own/shared handoff. Pass `handoff_id` from `memory_handoff_list` to claim that exact row; omitting it still claims the latest eligible open handoff (automatic handoffs are cwd-matched). Root-only `any_owner=true` recovers across operators. Optional `workspace` + `project` targets a named sibling workspace/project. |