Skip to content

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

Rust

Merge main into release/2.5

AkitaOnRails4829c14d438f
diff --cc .github/workflows/ci.yml
index 2f7709e6,5ee25bd2..57fa4846
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@@ -75,18 -75,19 +75,31 @@@ jobs
# block that fails to compile (e.g. an indented shell example rustdoc
# reads as Rust) shipped unnoticed. Run them explicitly.
- run: cargo test --workspace --doc
+ - uses: astral-sh/setup-uv@bec219d24cd3e171d82865faccec33120bb574f4 # v10.1.0
+ with:
+ enable-cache: false
+ - name: Build the external lifecycle relay
+ env:
+ CARGO_TARGET_DIR: ${{ github.workspace }}/target
+ run: cargo build --locked --manifest-path companions/ai-memory-relay/Cargo.toml
+ - name: External lifecycle delivery against the real server
+ run: >
+ uv run --no-project python tests/e2e/external_relay_smoke.py
+ --ai-memory-bin "${{ github.workspace }}/target/debug/ai-memory"
+ --relay-bin "${{ github.workspace }}/target/debug/ai-memory-relay"
+ # The capture policy every generated OpenCode/OMP/Pi/OpenClaw plugin
+ # embeds is TypeScript; only Node can execute it against the shared
+ # capture-policy fixture. The test is ignored locally, where Node is not
+ # a build requirement.
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ if: matrix.os == 'ubuntu-latest'
+ with:
+ node-version: "24"
+ - name: Generated capture-policy TypeScript runtime evidence
+ if: matrix.os == 'ubuntu-latest'
+ # `--workspace` reuses the test binaries built above instead of
+ # re-resolving features for one package.
+ run: cargo test --workspace --lib -- --ignored --exact commands::render_shared::tests::generated_capture_policy_v1_node_runtime_evidence
- name: Vendored tailwind.css is current
if: matrix.os == 'ubuntu-latest'
run: git diff --exit-code -- crates/ai-memory-web/static/tailwind.css
diff --cc CHANGELOG.md
index 67df893b,ffc3a8c5..ee4d85fc
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -8,636 -8,422 +8,1050 @@@ and this project adheres to [Semantic V
## [Unreleased]
### Added
+- `install-skills --agent hermes` (and the `hermes` entry in
+ `memory_install_self_routing`'s `target_hints`) installs the managed routing
+ skills into Hermes Agent's `.hermes/skills` (project) or `~/.hermes/skills`
+ (global) family, completing Hermes routing support alongside its lifecycle
+ hooks (#933). (#942)
+- `[search.fts] stopwords` (env `AI_MEMORY_SEARCH_FTS_STOPWORDS`, CSV) makes
+ the stopword filter for bare natural-language FTS queries configurable,
+ so a non-English install can list its own function words (e.g. Portuguese
+ `de`, `que`, `em`) instead of having them match nearly every page and skew
+ the FTS side of hybrid ranking. Absent keeps today's English list, so
+ nothing changes on upgrade; `[]` disables the filter. Entries match
+ queries case-insensitively (Unicode) but keep diacritics, so list both
+ `nao` and `não` if users type both. Option A from #953, proposed by
+ @rntjr. (#956)
+- `docs/jev-reranker-adapter.md` gains a choice-contrastive variant of the
+ Jev reranker adapter
+ (`docs/examples/jev-reranker-adapter/jev_rerank_shim_choice.py`): one
+ `choice` question over the whole candidate list instead of one rubric
+ `score` per candidate, choice probability mapped to `relevance`. The
+ example asks for the specific page that contains the answer, and not to
+ pick an index, catalog, or summary when a more specific page answers.
+ On the same live golden set and 35B backend the choice shape measured
+ hit@1 0.778 / NDCG@10 0.893 at 0.75 s mean rerank latency versus 0.636 /
+ 0.833 at 2.2 s for the rubric adapter, and it is the shape in which
+ replay-trained small judges hold their quality (4B: 0.808 vs 0.596).
+ Safe because the reranker leg is sort-only; the rubric-adapter caveat
+ on absolute relevance semantics is scoped to consumers that read
+ absolute values.
+- `ai-memory reclaim-ledger-versions` drops the superseded versions of the raw
+ hook event ledger that the pre-2.1.1 indexer left behind (#660), and nothing
+ else. It reports what it would remove and changes nothing unless
+ `--confirm`; `--drop-latest` also removes each ledger's live row, and
+ `--compact` rebuilds the FTS index and `VACUUM`s to return the freed bytes.
+ A path is only a candidate when its *content* is a hook ledger, so a real
+ page named `log-2026-09.md` keeps its whole version chain, and only
+ `is_latest=0 AND superseded_at IS NULL` rows are eligible, so decay-owned
+ rows stay with `forget-sweep`. Derived FTS/entity/vector/link rows go with
+ the page through the existing cascades, and the FTS delete trigger is stood
+ down for the bulk delete and restored from its own `sqlite_master` DDL
+ afterwards, so the cleanup does not re-tokenize tens of gigabytes of ledger
+ body one row at a time. (#914)
+- `identity = "…"` in `.ai-memory.toml` pins the repository identity a
+ checkout's captures route by, outranking `project` and the git remote — see
+ [marker-file.md](docs/marker-file.md#repository-identity). (#708)
+- The builtin web UI has a root-only `/web/pending` page to triage pending
+ auto-improvement proposals. It lists the proposals of all projects, with a
+ project filter and a sort, and shows the rationale and the proposed body.
+ Approve and reject post to the existing
+ `/admin/pending-writes/{id}/approve|reject` routes with the session cookie
+ and the CSRF header, so admission, audit, and attribution stay the same.
+ `ai-memory-web` adds no write route. (#855)
+- Inert per-project-authorization schema and the `authorize_project` choke
+ point (first slice of #708). A new `project_grants` table
+ (`(workspace, project, user) -> read|write`) and a `projects.access_mode`
+ column (`open` | `restricted`, default `open`) are added additively — every
+ existing project stays `open`, so there is no behaviour change. The typed
+ `authorize_project` gate (consulted by `ScopeResolver` read/write resolution
+ and, as defense in depth, by the writer actor) short-circuits `open`
+ projects and single-user/loopback deployments to ALLOW, and degrades to open
+ when grants cannot be read (never a lockout). A `restricted` project with
+ zero grants still admits root and the creator. Because nothing sets
+ `restricted` yet, this is a pure pass-through; enforcing `restricted` across
+ the unscoped-read and raw-id bypass classes plus the root-only management
+ surface (setting `restricted`, issuing grants) follow in a later slice. (#708)
+- Per-project authorization is enforced (third slice of #708, completing
+ [`design-per-project-authz.md`](docs/design-per-project-authz.md)). A
+ `restricted` project admits root, its creator and grant holders; `open`, the
+ default and what every existing project stays after upgrading, admits any
+ authenticated user exactly as before. Every surface attaches the choke point
+ for database users — MCP tools, hook routes and captures, the web UI and
+ `/api/v1` — and read-shaped tools that mutate (delete, feedback, sweep, lint,
+ auto-improve, handoff accept/cancel, message pop/cancel) need `write`.
+ Unscoped reads — search, listings, the graph and the workspace overview —
+ leave out projects a user may not read, filtered in the query before
+ `LIMIT`; managed-run, workstream and session-id entry points authorize the
+ project the id resolves to. A refusal is a 403 naming the project and the
+ level needed, never an empty result. Installs with no database users, and
+ the root token, are never checked. (#708)
+- `projects.created_by` (V69) records the database user whose call created a
+ project, and the choke point derives "creator" from it, so a creator keeps
+ their project if it is later restricted, without a grant. Projects that
+ predate it have no recorded creator. (#708)
+- Root-only management of access and grants:
+ `ai-memory project access --workspace W --project P --mode open|restricted`
+ (`POST /admin/projects/access`) — restricting names the page authors it now
+ refuses and grants nobody automatically;
+ `ai-memory user grant --user U --workspace W --project P --level read|write`,
+ `ai-memory user revoke …`, `ai-memory user grants [--user U]` and
+ `ai-memory project grants --workspace W --project P`
+ (`POST /admin/users/{username}/grant|revoke`,
+ `GET /admin/users/{username}/grants`, `GET /admin/projects/grants`). Every
+ grant, level change and revoke is recorded in `audit_log`
+ (`grant_access` / `revoke_access`). (#708)
+- `[auth] new_projects_restricted` (`AI_MEMORY_AUTH__NEW_PROJECTS_RESTRICTED`),
+ default `false`: when set, every project created from then on starts
+ `restricted`. The reserved `scratch` project and the global preferences scope
+ always start open; the global scope cannot be restricted. (#708)
+- Cross-project messages respect access: sending into a restricted project's
+ inbox, popping it and cancelling its outbox need `write` on it; listing needs
+ `read`. (#708)
+- Native `ai-memory upgrade` for GitHub-release installs (Linux/macOS
+ tarballs and Windows x86_64 zip): downloads the matching release archive,
+ verifies the `.sha256` sidecar, replaces the on-disk binary (and a sibling
+ `hooks/` tree when present), then re-runs `install-hooks --apply` for staged
+ agents. Windows uses rename-aside self-replace (running `.exe` → `.old`,
+ promote `.new`) because the mapped image cannot be overwritten in place.
+ Refuses package-managed paths (Homebrew/AUR/`/usr`), containers, and
+ unwritable prefixes; the Docker wrapper's `upgrade` path is unchanged. Pin
+ with `--version` / force a re-download with `--force`. Optional
+ `AI_MEMORY_RELEASE_BASE_URL` / `release_base_url` overrides the Releases
+ base for mirrors and hermetic tests (loaded via `Config`, not ad-hoc env).
+ Downloads refuse bodies over 128 MiB (Content-Length and streamed cap).
+ (#801, #802)
+- `ai-memory run` accepts a repeatable `--env KEY=VALUE` and an `--env-file
+ <path>` (blank lines and `#` comments skipped) to pass extra environment
+ into the spawned harness — e.g. a per-account `CLAUDE_CONFIG_DIR` for
+ callers who previously had to wrap the launch in `env KEY=VAL harness`.
+ Both flags are wrapper-owned like `--yolo`/`--executable` and must precede
+ the harness name; a `--env` entry overrides a same-key `--env-file` line.
+ The resolved environment reaches the spawned process, ai-memory's own
+ native-session resolution, first-launch auto-wire and the global Crush
+ config the managed context packet is layered onto, so the session store,
+ hooks and MCP all follow a `CLAUDE_CONFIG_DIR`-style override, and
+ auto-wire warns when the override puts Pi and OMP in one extensions
+ directory. See `docs/managed-workstreams.md`. (#820)
+- `contradiction_band_min` / `contradiction_band_max` config keys (env:
+ `AI_MEMORY_CONTRADICTION_BAND_MIN` / `AI_MEMORY_CONTRADICTION_BAND_MAX`)
+ make `memory_lint`'s A5 zero-LLM contradiction-detection cosine-similarity
+ band configurable, defaulting to the historical fixed `0.4`–`0.75`. The
+ band is a fixed absolute cosine value, but background similarity is
+ corpus-dependent: on a single-language or single-domain store, unrelated
+ pages already sit above the general-purpose floor, so the default band
+ measures domain proximity more than conflict and produces noisy findings.
+ Raising `contradiction_band_min` trims that noise. Rejected at config load
+ unless `0.0 <= contradiction_band_min < contradiction_band_max <= 1.0` and
+ both are finite. (#853)
+- Fedora users can install prebuilt x86_64 and aarch64 RPMs from GitHub
+ Releases, with the existing native systemd service assets. (#858)
+- `embedding_query_prefix` / `embedding_document_prefix` config keys (env:
+ `AI_MEMORY_EMBEDDING_QUERY_PREFIX` / `AI_MEMORY_EMBEDDING_DOCUMENT_PREFIX`)
+ for the `openai` and `openai-compat` embedders: an optional string
+ prepended to query / document text before the existing truncation, so
+ truncation still bounds the whole input. Asymmetric embedding models need
+ a query-side instruction their publisher specifies; the OpenAI-compatible
+ `/v1/embeddings` wire format has no field for it.
+ `nvidia/Nemotron-3-Embed-1B-BF16` and base E5 models use a simple
+ `"query: "` / `"passage: "` pair; instruction-tuned E5 variants and
+ Qwen3-Embedding instead need a task-instruction string on the query side
+ only (documents stay plain). Empty by default — no behaviour change when
+ unset, and not trimmed (nor is a present-but-empty env-var override, which
+ now clears a `config.toml` value), so a publisher's trailing space is
+ preserved. A non-empty `embedding_document_prefix` is folded into the
+ stored embedding identity (`Embedder::model_identity`), so a document
+ prefix change makes retrieval, backfill, and cleanup treat existing pages
+ as stale and re-embed them automatically — an empty prefix keeps the
+ pre-existing identity, so upgrading installs need no migration, and a
+ query-only prefix change never needs a rebuild. See
+ `docs/llm-providers.md`. (#859)
+- Added the optional `ai-memory-relay` companion for external lifecycle events.
+ It queues events locally and sends ordered batches through the public hook API,
+ using stable event identities for retries. The package has its own workspace
+ and does not change the server's capture or storage defaults. (#823)
+- `auto_improve.patchable_page_prefixes` makes the folders whose page bodies the
+ reviewer reads configurable, defaulting to the historical `_rules/` and
+ `procedures/`. Only those two folders' contents were ever sent; every other
+ page reached the model as a single title line, so a project keeping its
+ durable knowledge in `decisions/` or `gotchas/` — with no `_rules/` pages at
+ all — sent no page bodies, and the reviewer re-proposed invariants that were
+ already written down, at high confidence, indefinitely. Existing configs are
+ unchanged. (#834)
+- `ai-memory finalize-session --reopen --session-id <uuid>` re-finalizes a
+ session that already ended, for agents without a true session-end event
+ (Antigravity CLI, Kiro, ZCode, Pool) whose conversation continued after a
+ first manual finalize: the discovery step now accepts `include_ended=true`
+ on `GET /admin/open-sessions` for an exact session id (rejected without
+ one, so reopening stays exact-id-only and never a bulk operation), and the
+ server's normal session-end path re-runs over the new observations
+ (updated summary page via supersession, new handoff, opt-in
+ consolidation). Re-running with nothing new since the first end remains a
+ harmless no-op. The default finalize behavior is unchanged: ended sessions
+ stay invisible unless `--reopen` is passed. (#836)
+- Added per-execution `AI_MEMORY_CAPTURE_OWNER` context for external lifecycle
+ producers. Updated native hooks, script bundles and generated integrations
+ suppress capture while preserving supported handoff delivery and MCP recall.
+ Documented producer provenance and stable retries through the existing hook
+ ingestion API, without changing its schema or standalone defaults. (#821)
+- Builtin `/web` login and change-password pages for human password sessions:
+ unauthenticated browser GETs to the wiki redirect to `{web_slug}/login`
+ (not bare JSON 401), forms call existing `POST /auth/login` /
+ `/auth/password` / `/auth/logout`, and `--web-ui-dir` custom SPAs stay
+ unchanged. (#811)
+- `[consolidation] input_token_safety_margin` (float, default `0.8`, validated
+ to `(0.0, 1.0]`) scales the approximate char-count input budget. The
+ `max_input_tokens` budget uses a flat chars-per-token heuristic that
+ under-budgets denser corpora — pt-BR text and source code tokenize at fewer
+ chars per token than English and could overshoot a provider's real input
+ limit by ~40%. The default tightens the common case modestly while leaving
+ such corpora headroom; lower it further for a mostly non-English or code
+ corpus. `max_input_tokens` is now documented as an approximate heuristic in
+ the config reference. (#884)
+- `docs/jev-reranker-adapter.md` documents a stdlib-only adapter
+ (`docs/examples/jev-reranker-adapter/jev_rerank_shim.py`) that serves the
+ `AI_MEMORY_RERANKER=llm` request leg from a Jev `/v1/systemone` judge
+ endpoint while reverse-proxying consolidation/lint/bootstrap traffic to
+ the configured provider unchanged. In the contributor's own 102-query
+ golden-set benchmark the judge matched the hosted reranker's
+ hit@1/MRR/NDCG@10 (0.778/0.838/0.873 vs 0.778/0.840/0.875) at 0.205 s
+ mean latency instead of 20.2 s — in that run the hosted mean sat on the
+ server's 20 s completion timeout, which made the reranker stall every
+ query before falling back. (#873)
+- MCP tool calls from OpenCode 2 (2.0.4+) are routed by the native session id
+ the client sends in `params._meta["ai.opencode/sessionID"]`, ahead of the
+ `Mcp-Session-Id` transport header, which OpenCode shares across every
+ session in a directory. Concurrent OpenCode sessions in different projects
+ no longer read each other's active project; explicit `workspace`/`project`
+ arguments still win and `X-Memory-Actor-Session-Id` keeps precedence. (#864)
+- OpenCode 2 turn checkpoints: every completed root turn
+ (`session.execution.succeeded`, `.failed` or `.interrupted`, OpenCode
+ 2.0.10+) now refreshes `sessions/<id>.md` and the session's automatic
+ handoff without ending the native session, because OpenCode 2's shared
+ service outlives the CLI and closing a terminal is not a session end. The
+ checkpoint is deterministic (no LLM call), is written in the session's own
+ scope, keeps one open baton per live session (refreshed in place, audited as
+ `refresh_handoff`), and never touches a session that already ended. Child
+ sessions neither claim startup context nor publish batons. (#865)
+- `install-hooks --agent opencode2 --capture-assistant` extends the
+ assistant/Stop capture double opt-in to OpenCode 2: the plugin forwards the
+ last completed assistant text through the native hook's sanitizer before it
+ reaches the spool or the wire. The captured excerpt continues the work in
+ the next session's automatic handoff; it is not rendered into the
+ git-tracked session page. (#865)
+- `install-hooks --agent hermes` (alias `hermes-agent`) and
+ `setup-agent --agent hermes` for **Hermes Agent** (Nous Research). Hermes
+ splits a configured hook `command` with `shlex.split` and runs it with **no
+ shell**, with the event JSON on stdin, so the generated block invokes the
+ native `hook` subcommand directly — the same shape Zero and ZCode use, and no
+ `.sh`/`.ps1` bundle is staged. Two events are wired, `pre_tool_call` and
+ `post_tool_call`, whose payload (`tool_name` / `tool_input`) is the envelope
+ the router already mapped for `agent=hermes`; this is what finally gives
+ Hermes sessions tool observations. `~/.hermes/config.yaml` is printed, never
+ written: it is YAML the operator also edits, and Hermes gates user hooks
+ behind its own acceptance prompt (`hooks_auto_accept`). Session lifecycle
+ stays with the ai-memory memory-provider plugin, so a hook-driven
+ `session-end` cannot double-close a session. (#623 follow-up, #933)
+ - `docs/llm-providers.md` now has a dedicated OpenRouter subsection and a
+ matching row in the recommended-defaults table. The wiring
+ (`openai-compat` + `AI_MEMORY_LLM_BASE_URL=https://openrouter.ai/api/v1`)
+ and the `HTTP-Referer` / `X-Title` app-attribution headers were already
+ shipped, and `docker/.env.production.example` already ships an OpenRouter
+ default, but the provider-facing doc mentioned OpenRouter only inside the
+ generic `openai-compat` row. The new subsection covers a full working
+ env-file, the `openai-compat` embedder path (with a note to verify any
+ provider's `/v1/embeddings` endpoint before relying on it), a pointer to
+ `docs/llm-provider-comparison.md` for model selection, and a security /
+ gotchas block (auth-token requirement for non-loopback binds, env-file
+ hygiene, cheap-model consolidation drift, `:free`-tier shared-pool
+ limits, reasoning-model incompatibility). (#949)
+ - `docs/backup.md` documents the remote-git-mirror backup pattern for a
+ single-user install: what to include, what to exclude (derived SQLite index,
+ models cache, logs, secrets), how to schedule with a `systemd --user` timer,
+ how to restore, and the security posture per `SECURITY.md`, including a
+ "what ends up in your wiki" section that names the exposure (sanitized
+ prompts, tool I/O, page bodies) and lists encrypted-archive alternatives
+ (`age`, `restic`, `borg`, `git-crypt`) for cases where a private mirror
+ repo is not enough. A worked example ships under `docs/examples/backup/`
+ (snapshot script, `.service` and `.timer` unit files, `.gitignore` for
+ the mirror repo). Pointers added from `docs/deploy.md#backups`,
+ `docs/airgapped-install.md`, and the README docs table. The on-box
+ `ai-memory backup --to <tarball>` command
+ (`docs/lifecycle-ops.md#backup`) is unchanged. (#950)
+### Changed
+- `ai-memory purge-session` without `--confirm` now previews what a confirmed
+ purge would delete before refusing, the same way `purge-project` does (#945):
+ `Would purge session from <ws>/<proj>: N observations, N handoffs, N pages,
+ N auto-improve runs.` (the session id itself is never printed). The server
+ takes a new `dry_run` field on `POST /admin/purge-session` that always wins
+ over `confirm`. It only counts; no delete, wiki file removal, webhook,
+ audit row or checkpoint runs. `POST /admin/purge-session`'s confirmed
+ report also gains two new fields, always present on both the preview and
+ the confirmed response: `collateral_observations_deleted` and
+ `collateral_handoffs_denulled`, counting what the purge cascades into
+ *other* projects through this session's own id. The CLI still exits
+ non-zero without `--confirm`; against an older server, or if the preview
+ times out, it prints only the existing refusal. (#957)
+- `POST /admin/delete-workspace` takes a `dry_run` field that always wins
+ over `force` and previews what a confirmed delete would remove, with the
+ same 404/409 a confirmed delete gives. It only counts: no admission call,
+ directory removal, mirror dispatch or checkpoint. The preview and the
+ confirmed response now also report `sessions_deleted`,
+ `observations_deleted`, `handoffs_deleted` and `embeddings_deleted`
+ (previously only projects, pages, workstreams and managed runs), plus
+ `collateral_observations_deleted` and `collateral_handoffs_denulled` for
+ rows in *other* workspaces reached through this workspace's sessions.
+ `merge-workspace` is unaffected. There is no CLI subcommand, so this is
+ HTTP-only. (#963)
+- `ai-memory purge-project` without `--confirm` now previews what a confirmed
+ purge would delete before refusing: `Would purge <ws>/<proj>: N pages, N
+ sessions, N observations, …`, with the same 404/409 a real purge gives.
+ Before, the counts only appeared after the rows were gone. The server takes
+ a new `dry_run` field on `POST /admin/purge-project` that always wins over
+ `confirm`. It only counts; no delete, wiki removal, webhook, audit row or
+ checkpoint runs. The preview and the confirmed report also count what the
+ purge cascades into *other* projects through this project's sessions
+ (`collateral_observations_deleted`, `collateral_handoffs_denulled`). The
+ CLI still exits non-zero without `--confirm`; against an older server, or
+ if the preview times out, it prints only the existing refusal. (#945)
+- Captures from a checkout with no declared `project` and a git remote now route
+ by the repository's identity — the normalised `upstream` remote, else `origin`
+ — instead of the folder name (`projects.identity`, V70). Two unrelated
+ repositories sharing a folder name now get two projects (the second named
+ after its owner, e.g. `orgb-api`); one repository cloned into differently
+ named folders converges on one project, the first to claim the identity —
+ an existing second project keeps its history but stops receiving captures.
+ Existing projects are claimed in place, so upgrading moves no memory, and a
+ user who may not write to a project cannot claim its identity. Checkouts
+ that declare `project` in their marker route by name exactly as before. Every
+ hook client (native, shell, PowerShell, TypeScript) resolves the identity
+ host-side and sends it as `identity` / `identity_src`; credentials in a remote
+ URL never leave the machine. (#708)
+- A capture into a project its author may not write is dropped server-side
+ and counted as `dropped_unauthorized` in status, never stored. The native
+ hook client treats a 403 from the server as final and drops the event
+ instead of retrying it. (#708)
+- Grok Build CLI shows a pending handoff, and an opted-in `[briefing]`, as
+ `PostToolUse` `additionalContext` on the first tool of a session.
+ `SessionStart` and `UserPromptSubmit` still do not accept the handoff (Grok
+ discards that stdout); a session that never calls a tool leaves the handoff
+ open for `memory_handoff_accept`. The note is clipped to 10,000 characters
+ (Grok's own cap). Because Grok reuses one session id across a
+ SessionEnd→restart, `memory_handoff_accept` now reopens an already-ended
+ receiver session (clears `ended_at`) instead of rejecting it — but only for
+ agents that reuse their session id across a restart (Grok); for every other
+ agent an ended session stays final, so a lifecycle-only receiver still cannot
+ reclaim after it released and ended. The reopen also only happens after the
+ exactly-once claim guard, so a session that already took a baton still cannot
+ take another (the multi-session claim-once invariant is preserved).
+ Delivery of this PostToolUse handoff is exempt from `AI_MEMORY_CAPTURE_OWNER`
+ capture suppression, like the other context-delivery events. (#840)
+- The generated OpenCode 2 plugin binds to the OpenCode 2.0.10+ event and hook
+ API (`session.execution.*`, `session.text.ended`, `session.moved`, the
+ `context` hook). Startup context is claimed once per root session and
+ retained on every later model request; content-only tool results are
+ captured; each location instance owns its own queue, spool state and
+ cleanup; an explicit `session.moved` rebinds the live session to its new
+ directory so its later end lands there. Checked against OpenCode 2.0.14. (#865)
+- Quieted the default server log: the reconciliation-pass summary that fired
+ every 30 s regardless of activity dropped from `info` to `debug`, and the
+ default log filter now pins the external `rmcp` MCP SDK to `warn` (its
+ per-request lifecycle logging at `info` was the other half of a near-empty
+ server's log). Both are restorable through `log_level` (e.g.
+ `"info,rmcp=info"` or `"debug"`) or `RUST_LOG`; the `tracing_appender=warn`
+ feedback-loop guard stays non-overridable. (#894)
+
### Fixed
+- A Kiro v3 resume that falls back to the default session store drops
+ `KIRO_HOME` from the child, but auto-wire still installed hooks and MCP
+ under `KIRO_HOME`; it now wires the default home that resume reads. (#820)
+- `ai-memory run` auto-wired only the first config home per agent and
+ version: its sentinel ignored where hooks and MCP were installed, so a second
+ account (another exported `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, ...) was
+ skipped. The sentinel now also keys on the resolved hook and MCP config
+ paths. The Codex MCP entry ignored `CODEX_HOME`: `install-mcp` and auto-wire
+ now write `$CODEX_HOME/config.toml`, matching `hooks.json`; `uninstall`
+ sweeps the legacy `~/.codex/config.toml` too, and `install-hooks` still
+ infers the server URL and token from it until the entry is rewritten. (#820)
+- Corrected OMP's install and session paths for named profiles. Hooks and
+ `mcp.json` now use the profile's agent directory and ignore
+ `PI_CODING_AGENT_DIR`. Profile selection follows `--profile`, then
+ `OMP_PROFILE`, then the legacy `PI_PROFILE`. Names are trimmed and
+ validated; empty environment values, whitespace-only names and `default`
+ select the default profile. Returning to the default profile also drops
+ an agent directory inherited from a named parent profile.
+ `PI_CONFIG_DIR` changes the `.omp` root relative to the user's home.
+ On Linux and macOS, `run omp`, `backfill` and `doctor` read sessions from
+ `$XDG_DATA_HOME/omp/sessions` (or `omp/profiles/<name>/sessions` under
+ `$XDG_DATA_HOME`) when the corresponding OMP directory exists and the agent
+ directory has not been relocated. `run omp` also honors
+ `PI_CODING_AGENT_SESSION_DIR` and a leading native `--profile`.
+ Uninstall checks the active and default profiles plus the legacy `.omp`
+ locations, and an invalid OMP profile no longer stops cleanup for other
+ agents. (#820)
+- A whitespace-only `KIMI_CODE_HOME`, `KIRO_HOME` or `GROK_HOME` pointed
+ installs at a blank-named directory under the working directory, and a
+ whitespace-only relocation variable did the same for `ai-memory run`'s
+ native session import. Blank now counts as unset everywhere, as it already
+ did for the `CLAUDE_CONFIG_DIR`, `CODEX_HOME` and `PI_CODING_AGENT_DIR`
+ installers, and `ai-memory run` drops such a value from the harness it
+ launches so the harness uses its default home as well. Crush's managed
+ context likewise read a whitespace-only `CRUSH_GLOBAL_CONFIG` or
+ `XDG_CONFIG_HOME` as a directory, and now falls back to the default global
+ config. (#820)
+- Native `ai-memory upgrade` no longer refuses every Linux install by probing
+ the running executable for write (Linux `ETXTBSY`); it only requires the
+ parent directory to be writable for rename-based replace. (#802)
+- A managed Crush launch with a context packet dropped the `CRUSH.md` and
+ `AGENTS.md` Crush loads by default: Crush only adds them while
+ `global_context_paths` is empty, and the packet filled it. The launcher now
+ adds them first when the user's config lists none, and no longer refuses to
+ start over a global `crush.json` Crush accepts (an empty file, `null`, or
+ `null` options), read from the path cleaned as Crush cleans it. The global
+ `crushrc` beside that config, which Crush stopped reading once the config
+ dir moved, is now sourced from its own directory as well. (#820)
+- Two fresh managed Crush launches on one store could import each other's
+ transcript: Crush has no hooks to link its session, and after exit `ai-memory
+ run` took the newest session there. A fresh launch now claims only the one
+ top-level session created while it ran and imports nothing, with a warning,
+ when another launch created one too; its title and sub-agent sessions are no
+ longer taken for the conversation, and in a data directory outside the
+ project only a session that edited a file in the project is claimed. (#820)
+- `ai-memory run crush`, `backfill` and `doctor` looked for Crush sessions only
+ in `<cwd>/.crush/crush.db`, so a launch from a project subdirectory, or a
+ project whose Crush config sets `options.data_directory`, imported nothing.
+ They now find the store as Crush does: `options.data_directory` from Crush's
+ JSON configs, else the closest `.crush` up to the git worktree root (not one
+ directly in the home), else `<cwd>/.crush`. (#820)
+- Native `ai-memory upgrade` accepts release archives whose entries are
+ `./`-prefixed (`tar -C … -czf … .` as in `release.yml`), instead of
+ rejecting `Component::CurDir` as an unsafe path. (#802)
+- `ai-memory uninstall` left `ai-memory run`'s auto-wire sentinels in
+ `<data_dir>/autowire-state/`, so after the hooks were removed the next
+ managed launch of that harness on the same binary version skipped wiring and
+ captured nothing. Removing hooks or MCP (a full uninstall, `--only hooks` or
+ `--only mcp`) now deletes every sentinel and lists them in the dry-run plan.
+ `--only mcp`, `--only instructions` and `--only skills` also no longer delete
+ the stored hook bearer that the still-installed hooks read. (#820)
+- Native `ai-memory upgrade` treats Linuxbrew (`/home/linuxbrew/.linuxbrew/`)
+ as package-managed and refuses self-replace there. (#802)
+- Native `ai-memory upgrade` container refusal now uses the shared
+ `running_in_container` helper (`AI_MEMORY_IN_CONTAINER`, `/.dockerenv`,
+ `/run/.containerenv` / Podman), matching staged-hooks detection. (#802)
+- Parallel OpenCode 2 sessions in one directory no longer receive each
+ other's context. Each completed turn's checkpoint retired the automatic
+ handoffs of every other live session there, and the next session to start
+ was handed the handoff of a session still in use (mid-turn, or seconds after
+ its last turn). A checkpoint now spares other live sessions' handoffs; a
+ starting session receives a live session's handoff only once that session
+ has captured nothing for ten minutes, re-checked inside the claim; and the
+ claim retires older handoffs of quiet sessions but not of one in use.
+ (#883)
+- `memory_query`'s vector stream called the generic `Embedder::embed`
+ instead of `embed_query` on the configured embedder, so a
+ query/document-asymmetric embedder (Google's task-typed embeddings, or
+ the new query/document prefixes above) embedded the search query on the
+ document side instead of the query side. Indexed writes are unchanged;
+ only the query-side helper moves onto the query task. (#859, #861)
+- A manual `memory_consolidate` now reconciles the session's durable
+ consolidation job row. The MCP handler wrote the page directly through the
+ consolidator without touching `session_consolidation_jobs`, so a session
+ whose automatic SessionEnd job had reached the terminal `failed` state (that
+ the worker never re-claims) kept showing `failed` even though the operator
+ had just consolidated it. After a successful, non-dry consolidate the handler
+ flips a `failed`/`pending`/`superseded` row for the session to `completed`; a
+ live `running` lease is never touched, so a concurrent automatic worker
+ attempt is left to settle its own row. (#890)
+- Tool-family labels no longer leak into automatic handoffs and session-page
+ titles, and the file-activity handoff warning fires again. Every closed-tool
+ agent stores a call's title as `tool file` / `tool non-file` / … (a partition
+ of the calls, not a tool name); these were surfacing verbatim as `Tools used:
+ tool file, tool non-file` in handoffs and, for a session whose only non-prompt
+ observation was such a call, as the page title. The same spelling meant the
+ "session ended without a normal stop while working with files" heuristic —
+ which only matched the bare `file` spelling of the minority reserved-protocol
+ path — never fired for a real session. A shared recognizer now maps both
+ spellings, drops the labels from the handoff tool list and the title fallback,
+ and drives the file-activity warning from either. (#895)
+- Generated rule slugs (`_rules/<slug>.md`) now fold Latin diacritics to ASCII
+ instead of turning each accented letter into a hyphen: `estável` slugs as
+ `estavel` (was `est-vel`) and `retenção` as `retencao` (was `reten-o`). Long
+ titles are also truncated at a word boundary (the last hyphen inside the
+ 60-char budget) rather than mid-word. Uses the icu_normalizer NFD
+ decomposition ai-memory-core already depends on; no new dependency. (#886)
+- Multi-page consolidation now stores page paths with a `.md` extension.
+ The LLM returns a bare path for a non-rule page (`decisions/smart-model-luna`),
+ and the shared path sanitizer passed it through verbatim, so the page landed
+ extensionless and read back as a non-portable wiki path. The sanitizer now
+ appends `.md` to the filename component when it is missing (idempotent,
+ case-insensitive), fixing the non-rule consolidation, bootstrap, and
+ auto-improve front doors at once. (#885)
+- `ai-memory run`'s auto-wire no longer overwrites an installed session-aware
+ Claude Code MCP bridge with the static HTTP registration. The auto-wire
+ sentinel is keyed by client version, so the MCP step re-ran on every upgrade
+ and replaced the `ai-memory` entry wholesale; a user who had run `install-mcp
+ --client claude-code --session-aware` lost the bridge on the next `ai-memory
+ run` after an upgrade, silently disabling `[auto_scope] per_session` for their
+ MCP calls. Auto-wire now detects an existing session-aware bridge and keeps
+ it. (#888)
+- After a managed launch, `ai-memory run` imported the newest native session
+ in the checkout even when a hook in the launched harness had linked the
+ run's own session, so a concurrent launch in the same checkout could hand it
+ another transcript. The server now records when a session is linked during
+ a run (schema migration V67, adding `managed_runs.native_session_linked_at`)
+ and reports it in the run status, and the launcher imports that session
+ when this checkout's store holds it (a process the child starts inherits
+ the run id; OpenCode is checked by the session's recorded directory). An
+ older server reports no link and keeps the previous behavior. (#820)
+- On Windows, OpenCode 1 and 2 sessions are found again from their checkout:
+ OpenCode records a session's directory with forward slashes
+ (`C:/Users/me/repo`), so matching only the backslash checkout path found
+ none. `ai-memory doctor` reported `0 local` for OpenCode while it captured
+ sessions there, and `ai-memory run` / `show` could neither discover nor list
+ a native OpenCode session to resume. (#882)
+- Grok Build CLI hooks capture on Windows again. Grok evaluates
+ `~/.grok/hooks/*.json` commands with PowerShell, as Codex does (#515), so
+ the double-quoted executable path in command position parsed as a string
+ expression and every hook exited 1 with a ParserError: sessions ran with
+ the hook installed and nothing was captured. The Windows command now
+ carries PowerShell's `&` call operator for Grok too; re-run
+ `ai-memory install-hooks --agent grok --apply` to rewrite an existing
+ install. (#887)
+- The Linux/macOS Docker wrapper now keeps its native host client in
+ `${XDG_DATA_HOME:-~/.local/share}/ai-memory/native-runner` instead of
+ `~/.cache/ai-memory/native-runner`. `ai-memory run` auto-wires hooks whose
+ command is that client's path (Claude Code, Codex, Kimi Code, Command Code,
+ Kiro CLI v3, Grok, Antigravity CLI), so flushing `~/.cache` left every hook of
+ those harnesses pointing at a missing binary. The wrapper also keeps the
+ release's `hooks/` bundle beside the client, so auto-wire no longer fails
+ with "could not locate hooks directory" for script-based harnesses on a host
+ where `install-hooks` never ran. (#874)
+- Fixed pre-push installation from linked worktrees and preserved the managed
+ block's position during reinstallation. Configured `core.hooksPath` overrides
+ and ambiguous markers are rejected without replacing the existing hook. The
+ block now keeps its shell options and `SSL_CERT_FILE` inside its subshell and
+ propagates a failure explicitly, so user hook commands after it keep their
+ own semantics and a failing test run still blocks the push. (#824)
+- Isolated the pre-push test process from Git's repository environment and
+ global/system configuration so fixture commands use their own repositories.
+ Existing installations need to run `scripts/install-git-hooks.sh` again. (#824)
+- A Windows service running as `LocalSystem` over a user-owned data
+ directory no longer breaks the wiki git history silently. libgit2's
+ dubious-ownership guard (CVE-2022-24765) fails every wiki commit with
+ `code=Owner` when the process account does not own the repository, but
+ the failure was WARN-only, so capture and search kept working while no
+ wiki checkpoint was ever committed. The startup baseline checkpoint now
+ surfaces an owner-check failure at ERROR with the remedy (run the
+ service as the owning user), and `docs/windows.md` Scenario E documents
+ running the service under a `<serviceaccount>`, corrects the claim that
+ only the data directory is account-sensitive, and notes the WinSW
+ error-1069 / stale-password gotcha for Microsoft-account / PIN / Hello
+ users. The owner check itself is deliberately left enabled. (#872)
+- A Windows folder no longer splits into two projects. The hook router
+ derived a project's *name* from the cwd after
+ `normalize_project_path_key` had ASCII-lowercased the whole
+ drive-letter/UNC path — basename included — so a session in
+ `D:\...\Default Project` was captured under `default project` while the
+ CLI (which keeps the raw basename) used `Default Project`. Because
+ `get_or_create_project` matches names case-sensitively, one folder
+ minted two projects. The router now takes the name from the raw cwd; the
+ cache key and cwd-prefix match keep the case-folded path, so #806 handoff
+ stickiness is unaffected. (#871)
+- Auto-improve review no longer stages a proposal whose LLM-produced page
+ path contains a Windows-illegal character (e.g. a `:` copied from a
+ conventional-commit subject). That path passed the deliberately tolerant
+ `PagePath::new` and only failed later at `ensure_portable` when the
+ proposal was approved, so the learning loop queued work that could not
+ be applied. Paths are now sanitized the same way bootstrap (#847) and
+ per-session consolidation (#848) already sanitize theirs, before
+ validation; a path that is still unportable after sanitizing is rejected
+ instead of staged. (#850)
+- Omitted `temperature` for `gpt-6-*` models in the `codex`,
+ `openai-oauth`, `copilot` and `openai` providers. Codex answered GPT-6
+ requests that carried `temperature` with `400 Unsupported parameter:
+ temperature`, which broke consolidation, lint and bootstrap on a
+ provider or fallback configured with `gpt-6-luna`, `gpt-6-sol` or
+ `gpt-6-astra`. The `openai` provider now also sends
+ `max_completion_tokens` for GPT-6 and no longer applies its local
+ 16,384-token cap to it, matching `gpt-5*`. (#851)
+- `memory_message_pop` and `memory_message_list` no longer return a silent
+ empty result when the inbox scope was *inferred* rather than named. A caller
+ with no explicit `workspace`/`project` and no forwarded hook-session id
+ resolves the shared active-project slot (whichever project published last),
+ so two same-operator agents can have a no-scope pop land on a different inbox
+ than the on-start notice / `memory_briefing` counted — "you have mail"
+ followed by an empty fetch, with no way to tell it was the wrong inbox. An
+ empty read from an inferred scope now reports the `resolved_scope`
+ (workspace + project), the `scope_source`, and a hint to re-run with explicit
+ scope; an explicitly-scoped or session-bound empty read is unchanged. No
+ message is lost — the mis-scoped pop consumes nothing. (#854)
+- `companions/ai-memory-macos/build.sh` no longer fails on machines whose
+ active developer directory is Command Line Tools only: SwiftUI `@State`
+ needs the `SwiftUIMacros` plugin shipped with full Xcode, so the script
+ now exports `DEVELOPER_DIR` to Xcode (or a caller-set path) before
+ `swift build`, with a clear error when no macOS platform is present. (#849)
+- `ai-memory serve` no longer leaked file descriptors from half-open HTTP
+ connections until `EMFILE`, breaking the healthcheck (an unauthenticated
+ availability/DoS). A hook or MCP client whose peer died without sending FIN
+ (laptop sleep, a VPN/Tailscale flap, an abrupt kill) left its accepted
+ socket `ESTABLISHED` forever, since the OS default has TCP keepalive off —
+ each dead peer leaked one fd, exhausting the 1024-fd default in roughly 2-3
+ days of normal churn. Accepted connections now get TCP keepalive via
+ `socket2`, tunable with the new `tcp_keepalive_secs` config key (default
+ 60s; `AI_MEMORY_TCP_KEEPALIVE_SECS=0` disables keepalive). This closes the
+ half-open-socket half of the fd leak; the rmcp session-table half was
+ already fixed in 2.4.0 by the rmcp 2.x bump. (#792)
+- `ai-memory bootstrap` no longer returns a 500 when the LLM emits a page
+ path containing a Windows-illegal character (e.g. a `:` copied verbatim
+ from a conventional-commit subject like `build(sandbox): orchestrate`).
+ Such a path passed the deliberately tolerant `PagePath::new` and only
+ failed later at `ensure_portable` inside the atomic wiki write batch,
+ which aborted every page in the run, not just the offending one. Bad
+ paths are now sanitized (illegal characters replaced with `-`, directory
+ shape preserved) before validation, so the run and its other pages
+ survive; a path `ensure_portable` still rejects after sanitizing is
+ skipped with a warning instead of failing the batch. (#847)
+- Per-session consolidation (`consolidate_session_multi`) had the same
+ Windows-illegal-path defect as `ai-memory bootstrap` (#847): an
+ LLM-produced page path containing a character like `:` passed the
+ deliberately tolerant `PagePath::new` and only failed later at
+ `ensure_portable` inside the atomic wiki write batch, losing every other
+ page from that session's consolidation run. The path is now sanitized
+ the same way bootstrap's is, consistently across rule-routing, per-user
+ slot placement, and the session-anchor comparison, before validation;
+ a path `ensure_portable` still rejects after sanitizing is skipped with
+ a warning instead of failing the batch. (#848)
+- The Windows release checksum (`ai-memory-windows-x86_64.zip.sha256`) is now
+ written with a LF terminator instead of CRLF. `Out-File`'s Windows line
+ ending made `sha256sum -c` fail with `No such file or directory` — the CR
+ is read as part of the filename — on the WSL2 and Git Bash paths where that
+ is the natural command, and placed a stray byte in the release body's
+ checksum block, which concatenates every platform's file. The zip's smoke
+ test now requires LF rather than tolerating either, so the format the
+ release claims is the format it ships. (#838)
+- `purge-session` now removes every page version the session owns at
+ `sessions/<id>.md` (including versions written before OKF sources existed
+ and summaries of sessions that never recorded a summary pointer), while a
+ manual page at the same path survives. (#862)
+- Shell hooks no longer pin a CPU core for minutes on a large payload. The
+ `hooks/_lib.sh` extractors for `cwd`/`workspacePaths`/`workspace_roots`,
+ the session id, and Antigravity's `invocationNum` located each key with
+ `${payload#*"key"}`, which is quadratic in the payload size under dash and
+ bash: a 200 KB Cursor `postToolUse` event spent minutes in
+ `ai_memory_extract_cwd`, and concurrent hooks stayed at 100% CPU before
+ ever reaching the POST. A shared `ai_memory_after_key` helper now finds the
+ first occurrence with one linear `awk` pass (about 50 ms at 200 KB) and
+ feeds the unchanged `sed` parsing, so the extracted values are the same as
+ before. (#870)
+- The generated TypeScript integrations (OpenCode 1 and 2, OMP, Pi,
+ OpenClaw) no longer flash a console window on Windows for every captured
+ event: their `git` lookups set `windowsHide`. The repo-root project lookup
+ behind those spawns is memoized per cwd instead of running two synchronous
+ `git` processes on every event. (#863)
+- A `SessionEnd` whose resolved scope drifted from its session (a
+ `.ai-memory.toml` appeared under the running session) was refused as a
+ foreign-scope end and stranded the session open forever. It now ends the
+ session when owner and agent match and the event comes from the session's
+ own (normalized) cwd; a different cwd, operator or agent is still refused. (#865)
+- Generated TypeScript integrations no longer overwrite each other's spooled
+ events written in the same millisecond, and a host that tears its capture
+ state down cancels still-pending deliveries after the drain budget instead
+ of waiting out each request's timeout. (#865)
+- Shell hooks on macOS no longer corrupt non-ASCII characters in the query
+ string. `/bin/sh` there is bash 3.2, which sign-extends bytes >= 0x80, so
+ `ai_memory_url_encode` sent `é` as `%FFFFFFFFFFFFFFC3%FFFFFFFFFFFFFFA9`
+ instead of `%C3%A9`. An accented cwd reached the server as a different
+ path, and Cursor events and the session-start handoff lookup both use the
+ query `cwd`. (#877)
+ - `memory_query` now returns `global_scope_hits` (standing `_global` user/team
+ preferences) for a single-project query whose project is named explicitly
+ with `workspace`+`project`, not only when scope is omitted. The routing
+ doctrine tells static MCP clients to pass `workspace`+`project` on every call,
+ which set the old gate's "no named scope" condition to false, so those clients
+ never received global preferences despite the documented contract. The union
+ now keys on single-project resolution (`scopes` empty); only an explicit
+ multi-`scopes` set opts out, and `global=true`/`as_of` are unaffected. The
+ reserved-scope union is still keyed strictly to `_global` and never leaks
+ another project's pages. (#930)
+ - A page file rewritten under `wiki/<ws>/<project>/` (the OKF import path)
+ now gets its new version embedded the same way a brand-new file does.
+ The watcher's `reindex_page` upserted the new version and stopped —
+ embedding only ever ran on the `write_page` API path — so a rewrite left
+ hybrid search silently degraded to FTS-only ranking for that page until
+ someone ran `ai-memory embed` by hand. (#958)
+ - `[capture] ignore_paths` now covers shell commands. Shell tools (`Bash`,
+ `shell`, `execute_bash`, `terminal`, …) were classified as non-file and always
+ kept, so `cat docs/adr/*.md` stored the ignored file's full text in the
+ observation body. The native `ai-memory hook` now splits the command line
+ lexically and drops the event when an argument, resolved from the event's
+ `cwd`, matches an ignored pattern or is a glob that can reach one. Variables,
+ command substitution and commands that name no path are not followed. The
+ marker-file reference also documents excluding large tool results that Claude
+ Code saves and re-reads from `~/.claude/projects/**/tool-results/**`. (#946)
+ - The generated OpenCode, OMP, Pi and OpenClaw integrations now apply the same
+ lexical shell-command `ignore_paths` matching as the native hook, so a `bash`
+ call such as `cat docs/adr/0001.md` is dropped there too instead of being
+ captured. Both matchers now also recognize OpenClaw's and Devin's `exec` shell
+ tool, resolve relative arguments from a shell tool's `workdir` (OpenCode
+ `bash`, OpenClaw `exec`, Codex `shell`) instead of the event cwd, and treat
+ `dir/**` as covering `dir` itself when `dir` holds a glob (`docs/a?r/**`), as
+ the generated plugins already did. Refresh or reinstall generated plugins to
+ pick it up. (#948)
+ - Grok Build CLI tool observations are no longer stored with an empty body.
+ Grok posts Claude Code's snake_case tool fields (`tool_name` / `tool_input` /
+ `tool_use_id`), but it was missing from both `closed_tool_agent` and the
+ tool-metadata agent match, so every `PostToolUse` body extraction returned
+ nothing while the observation itself was still captured. Grok now shares the
+ Claude Code tool mapping, so tool family, outcome and output land in the
+ body. (#931)
+ - `ai-memory bootstrap` on a repository small enough for one chunk no longer
+ asks the provider for 64K output tokens. The output cap was keyed on the
+ number of chunks, so the only chunk of a small repo got the one-shot cap
+ meant for `--chunk-input-tokens 0`, and every such run failed on a
+ 64K-context model. Under chunking (the default) every call now asks for up
+ to 16K; only `--chunk-input-tokens 0` keeps 64K. The `--max-input-tokens`
+ help no longer claims its 150K default leaves room for 64K of output in a
+ 200K window. (#928)
+ - `ai-memory bootstrap` now leaves headroom for its own token estimate. It
+ counts bytes ÷ 4, which undercounts non-English text and source code (about
+ 40% on Portuguese mixed with code, as measured for consolidation), and it
+ filled `--max-input-tokens` and `--chunk-input-tokens` to the last estimated
+ token, so a chunk sized to fit a model's window could overflow it on input
+ alone. Prunes and chunks now fill 80% of each budget by the estimate, the
+ same default consolidation uses; a run may plan more chunks than before.
+ (#937)
+ - The `bootstrap.md` manifest no longer shows bare `---` separators when a
+ chunk returns no rationale. Empty rationales are dropped before the
+ per-chunk ones are joined, and a run where no chunk returned one says so.
+ (#939)
+ - Multi-page consolidation (`memory_consolidate` with `multi_page=true`) no
+ longer overwrites a pinned page. The batch's page paths are chosen by the
+ model, and an update that named an existing pinned page replaced its body
+ and wrote the new version unpinned, despite pinned pages being documented as
+ immutable to automation. Such updates are now skipped with a warning; the
+ rest of the batch is written. `_slots/` pages, which are pinned
+ automatically, keep their state/invariant rules. (#934)
+ - Session consolidation no longer writes a page title that already exists
+ in the project. A colliding session title gets a deterministic
+ `(session <8-char-id>)` suffix (stable for the same session, distinct
+ across sessions) and a matching leading H1 is retitled with it. The
+ consolidator prompt tells the model to name THIS session rather than a
+ generic harness-run phrase and not to reuse listed titles; that wording
+ is compact enough that the advertised 6000-token input floor still
+ projects observation bodies instead of dropping them. (#926)
+ - The web page view now links a `[[wikilink]]` on a line indented four
+ spaces that is not code. A nested list item written with four spaces
+ (`- Decisions:` then ` - see [[decisions/auth]]`) or a paragraph's
+ continuation line showed the wikilink as literal text, although the
+ engine indexed it and listed the page in the target's backlinks. The
+ preprocessor now skips exactly the code blocks and inline code the
+ renderer's parser reads as code. (#955)
+
+ ## [2.4.1] - 2026-09-25
+
+ ### Changed
+ - Quieted the default server log: the reconciliation-pass summary that fired
+ every 30 s regardless of activity dropped from `info` to `debug`, and the
+ default log filter now pins the external `rmcp` MCP SDK to `warn` (its
+ per-request lifecycle logging at `info` was the other half of a near-empty
+ server's log). Both are restorable through `log_level` (e.g.
+ `"info,rmcp=info"` or `"debug"`) or `RUST_LOG`; the `tracing_appender=warn`
+ feedback-loop guard stays non-overridable. (#894)
+ - An unauthenticated non-loopback bind is now announced on stderr at startup
+ independent of the log filter (a direct `eprintln!`, not a filterable
+ `tracing` warning), so `RUST_LOG=error` or a container's quiet log no longer
+ hides it. The refuse path for a non-loopback unauthenticated host bind is
+ unchanged — this only makes the existing warning reliably visible. (#903)
+
+ ### Fixed
+ - `ai-memory restore --force` no longer deletes the live `wiki/` and `db/`
+ before the tarball has been read. The archive is now extracted and
+ validated into a staging directory beside the data, the restored store is
+ opened there so pending migrations run and the snapshot is verified, and
+ only then are the live directories swapped out by rename (reversed if a
+ move fails). A truncated or corrupt tarball, an entry outside the allowed
+ layout, or a snapshot the current binary cannot open — a backup taken by
+ a newer release, say — previously left an empty or half-extracted data
+ dir with nothing to fall back to; it now leaves the existing data exactly
+ as it was. (#923)
+ - OMP (OpenClaw) tool calls are recorded again. OMP was missing from the
+ closed-tool-agent set, so its tool events fell through the OpenCode-only
+ legacy body reader and produced an empty excerpt — nothing reached session
+ pages, handoffs, or consolidation. OMP now renders through the Pi tool
+ schema like the other closed-tool agents (only `output` is kept as the
+ excerpt; `args`/`details` stay excluded, still through the sanitizer). (#913)
+ - A page whose `expires_at` is a bare date (`2026-10-01`) now gets an OKF
+ `stale_after` that names the instant the TTL expires it
+ (`2026-10-01T23:59:59.999999Z`) instead of the date copied verbatim. OKF
+ v0.2 requires every timestamp to carry an explicit UTC offset, and read a
+ bare date as the start of that day, a day earlier than ai-memory's
+ end-of-day TTL. An RFC 3339 `expires_at` is still carried unchanged.
+ Pages already written that way are repaired in place when `serve`
+ starts: index row and file, with the same version row, `updated_at`,
+ `generated.at` and body, in one wiki commit, and nothing to do on later
+ starts. (#917)
+ - `ai-memory backfill` stamps each imported session and observation with the
+ transcript's own event time instead of the moment it was imported, so a
+ transcript from weeks ago no longer looks like it just happened. An event
+ without a valid timestamp inherits the nearest one, and the session's start
+ and end are the earliest and latest event times. The `/hook` body accepts a
+ top-level RFC 3339 `occurred_at`; it must be positive and no more than five
+ minutes in the future, and anything missing, malformed or out of bounds
+ falls back to "now" instead of failing the hook. Because an imported
+ session now ends in the past, it can sit below the auto-improve watermark
+ and the experience-pass anchor (no automatic review until a newer session
+ moves them), an opt-in observation retention window can prune its older
+ observations right after import, and the "most recently active project"
+ fallback after a restart may not pick a project that was just backfilled.
+ (#919)
+ - The default log filter's `rmcp=warn` cap (#894) no longer raises rmcp
+ above a quieter `log_level`. A target directive beats the global level
+ either way, so with `log_level = "error"` or `"off"` the cap re-enabled the
+ SDK's warnings the operator had silenced; it now only applies when
+ `log_level` is louder than `warn`. (#896)
+ - A session with no usable prompt is titled `Session <id>` rather than
+ `stop` or `session-end`. Once #895 skipped tool-family labels in the title
+ fallback, the next candidate in a real session was the kind name the router
+ stores for an untitled lifecycle event. (#897)
+ - A wiki page with CRLF line endings is parsed as having frontmatter again.
+ `markdown::parse` only matched the fence lines with a bare `\n`, so a page
+ a Windows editor saved, or one `core.autocrlf=true` checked out, was treated
+ as body-only: `reindex`/the watcher indexed it without its `tier`,
+ `pinned`, `expires_at` and `entities` (a pinned page became decay-eligible),
+ the title came from the filename, and the one-shot OKF file pass wrote a
+ second frontmatter block above the authored one. The parser now accepts
+ `---\r\n` fences and leaves the body's line endings untouched. (#908)
+ - Rule slugs that hit the 60-character cap keep every whole word that fits.
+ The word-boundary cut from #886 only looked for a hyphen before position 60,
+ so a slug whose first 60 characters ended exactly on a word dropped that
+ word, and a hyphen early in the title (a short first word before one long
+ token) collapsed the slug to that single word. The cut now counts a hyphen
+ at position 60 and ignores one in the first half, falling back to the hard
+ cut at 60. (#886, #910)
+ - On Windows, `ai-memory run` recognises an OpenCode session as belonging
+ to the current checkout again. `native_session_in_checkout` (#880) compared
+ the stored `directory` with the backslash `cwd` exactly, while OpenCode
+ stores forward slashes (#891), so the check never matched there; it now uses
+ the same two spellings as the other OpenCode lookups (#882). (#906)
+ - A manual `memory_consolidate` now reconciles the session's durable
+ consolidation job row. The MCP handler wrote the page directly through the
+ consolidator without touching `session_consolidation_jobs`, so a session
+ whose automatic SessionEnd job had reached the terminal `failed` state (that
+ the worker never re-claims) kept showing `failed` even though the operator
+ had just consolidated it. After a successful, non-dry consolidate the handler
+ flips a `failed`/`pending`/`superseded` row for the session to `completed`; a
+ live `running` lease is never touched, so a concurrent automatic worker
+ attempt is left to settle its own row. (#890)
+ - Tool-family labels no longer leak into automatic handoffs and session-page
+ titles, and the file-activity handoff warning fires again. Every closed-tool
+ agent stores a call's title as `tool file` / `tool non-file` / … (a partition
+ of the calls, not a tool name); these were surfacing verbatim as `Tools used:
+ tool file, tool non-file` in handoffs and, for a session whose only non-prompt
+ observation was such a call, as the page title. The same spelling meant the
+ "session ended without a normal stop while working with files" heuristic —
+ which only matched the bare `file` spelling of the minority reserved-protocol
+ path — never fired for a real session. A shared recognizer now maps both
+ spellings, drops the labels from the handoff tool list and the title fallback,
+ and drives the file-activity warning from either. (#895)
+ - Generated rule slugs (`_rules/<slug>.md`) now fold Latin diacritics to ASCII
+ instead of turning each accented letter into a hyphen: `estável` slugs as
+ `estavel` (was `est-vel`) and `retenção` as `retencao` (was `reten-o`). Long
+ titles are also truncated at a word boundary (the last hyphen inside the
+ 60-char budget) rather than mid-word. Uses the icu_normalizer NFD
+ decomposition ai-memory-core already depends on; no new dependency. (#886)
+ - Multi-page consolidation now stores page paths with a `.md` extension.
+ The LLM returns a bare path for a non-rule page (`decisions/smart-model-luna`),
+ and the shared path sanitizer passed it through verbatim, so the page landed
+ extensionless and read back as a non-portable wiki path. The sanitizer now
+ appends `.md` to the filename component when it is missing (idempotent,
+ case-insensitive), fixing the non-rule consolidation, bootstrap, and
+ auto-improve front doors at once. (#885)
+ - `ai-memory run`'s auto-wire no longer overwrites an installed session-aware
+ Claude Code MCP bridge with the static HTTP registration. The auto-wire
+ sentinel is keyed by client version, so the MCP step re-ran on every upgrade
+ and replaced the `ai-memory` entry wholesale; a user who had run `install-mcp
+ --client claude-code --session-aware` lost the bridge on the next `ai-memory
+ run` after an upgrade, silently disabling `[auto_scope] per_session` for their
+ MCP calls. Auto-wire now detects an existing session-aware bridge and keeps
+ it. (#888)
+ - After a managed launch, `ai-memory run` imported the newest native session
+ in the checkout even when a hook in the launched harness had linked the
+ run's own session, so a concurrent launch in the same checkout could hand it
+ another transcript. The server now records when a session is linked during
+ a run (schema migration V67, adding `managed_runs.native_session_linked_at`)
+ and reports it in the run status, and the launcher imports that session
+ when this checkout's store holds it (a process the child starts inherits
+ the run id; OpenCode is checked by the session's recorded directory). An
+ older server reports no link and keeps the previous behavior. (#820)
+ - On Windows, OpenCode 1 and 2 sessions are found again from their checkout:
+ OpenCode records a session's directory with forward slashes
+ (`C:/Users/me/repo`), so matching only the backslash checkout path found
+ none. `ai-memory doctor` reported `0 local` for OpenCode while it captured
+ sessions there, and `ai-memory run` / `show` could neither discover nor list
+ a native OpenCode session to resume. (#882)
+ - Grok Build CLI hooks capture on Windows again. Grok evaluates
+ `~/.grok/hooks/*.json` commands with PowerShell, as Codex does (#515), so
+ the double-quoted executable path in command position parsed as a string
+ expression and every hook exited 1 with a ParserError: sessions ran with
+ the hook installed and nothing was captured. The Windows command now
+ carries PowerShell's `&` call operator for Grok too; re-run
+ `ai-memory install-hooks --agent grok --apply` to rewrite an existing
+ install. (#887)
+ - The Linux/macOS Docker wrapper now keeps its native host client in
+ `${XDG_DATA_HOME:-~/.local/share}/ai-memory/native-runner` instead of
+ `~/.cache/ai-memory/native-runner`. `ai-memory run` auto-wires hooks whose
+ command is that client's path (Claude Code, Codex, Kimi Code, Command Code,
+ Kiro CLI v3, Grok, Antigravity CLI), so flushing `~/.cache` left every hook of
+ those harnesses pointing at a missing binary. The wrapper also keeps the
+ release's `hooks/` bundle beside the client, so auto-wire no longer fails
+ with "could not locate hooks directory" for script-based harnesses on a host
+ where `install-hooks` never ran. (#874)
+ - Fixed pre-push installation from linked worktrees and preserved the managed
+ block's position during reinstallation. Configured `core.hooksPath` overrides
+ and ambiguous markers are rejected without replacing the existing hook. The
+ block now keeps its shell options and `SSL_CERT_FILE` inside its subshell and
+ propagates a failure explicitly, so user hook commands after it keep their
+ own semantics and a failing test run still blocks the push. (#824)
+ - Isolated the pre-push test process from Git's repository environment and
+ global/system configuration so fixture commands use their own repositories.
+ Existing installations need to run `scripts/install-git-hooks.sh` again. (#824)
+ - `memory_query` now embeds the search text with `embed_query` rather than
+ the generic `embed()` method. Google's embedder implements `embed()` as
+ `embed_document` (`RETRIEVAL_DOCUMENT`), the same task type used when
+ indexing wiki pages, so hybrid search compared a document vector to
+ document vectors and the vector stream could not separate query from
+ passage. Indexed writes are unchanged; only the query-side helper moves
+ onto `RETRIEVAL_QUERY`. Symmetric embedders (OpenAI, Voyage, local) keep
+ the same vector they already returned from `embed()`. (#861)
+ - A Windows service running as `LocalSystem` over a user-owned data
+ directory no longer breaks the wiki git history silently. libgit2's
+ dubious-ownership guard (CVE-2022-24765) fails every wiki commit with
+ `code=Owner` when the process account does not own the repository, but
+ the failure was WARN-only, so capture and search kept working while no
+ wiki checkpoint was ever committed. The startup baseline checkpoint now
+ surfaces an owner-check failure at ERROR with the remedy (run the
+ service as the owning user), and `docs/windows.md` Scenario E documents
+ running the service under a `<serviceaccount>`, corrects the claim that
+ only the data directory is account-sensitive, and notes the WinSW
+ error-1069 / stale-password gotcha for Microsoft-account / PIN / Hello
+ users. The owner check itself is deliberately left enabled. (#872)
+ - A Windows folder no longer splits into two projects. The hook router
+ derived a project's *name* from the cwd after
+ `normalize_project_path_key` had ASCII-lowercased the whole
+ drive-letter/UNC path — basename included — so a session in
+ `D:\...\Default Project` was captured under `default project` while the
+ CLI (which keeps the raw basename) used `Default Project`. Because
+ `get_or_create_project` matches names case-sensitively, one folder
+ minted two projects. The router now takes the name from the raw cwd; the
+ cache key and cwd-prefix match keep the case-folded path, so #806 handoff
+ stickiness is unaffected. (#871)
+ - Auto-improve review no longer stages a proposal whose LLM-produced page
+ path contains a Windows-illegal character (e.g. a `:` copied from a
+ conventional-commit subject). That path passed the deliberately tolerant
+ `PagePath::new` and only failed later at `ensure_portable` when the
+ proposal was approved, so the learning loop queued work that could not
+ be applied. Paths are now sanitized the same way bootstrap (#847) and
+ per-session consolidation (#848) already sanitize theirs, before
+ validation; a path that is still unportable after sanitizing is rejected
+ instead of staged. (#850)
+ - Omitted `temperature` for `gpt-6-*` models in the `codex`,
+ `openai-oauth`, `copilot` and `openai` providers. Codex answered GPT-6
+ requests that carried `temperature` with `400 Unsupported parameter:
+ temperature`, which broke consolidation, lint and bootstrap on a
+ provider or fallback configured with `gpt-6-luna`, `gpt-6-sol` or
+ `gpt-6-astra`. The `openai` provider now also sends
+ `max_completion_tokens` for GPT-6 and no longer applies its local
+ 16,384-token cap to it, matching `gpt-5*`. (#851)
+ - `memory_message_pop` and `memory_message_list` no longer return a silent
+ empty result when the inbox scope was *inferred* rather than named. A caller
+ with no explicit `workspace`/`project` and no forwarded hook-session id
+ resolves the shared active-project slot (whichever project published last),
+ so two same-operator agents can have a no-scope pop land on a different inbox
+ than the on-start notice / `memory_briefing` counted — "you have mail"
+ followed by an empty fetch, with no way to tell it was the wrong inbox. An
+ empty read from an inferred scope now reports the `resolved_scope`
+ (workspace + project), the `scope_source`, and a hint to re-run with explicit
+ scope; an explicitly-scoped or session-bound empty read is unchanged. No
+ message is lost — the mis-scoped pop consumes nothing. (#854)
+ - `companions/ai-memory-macos/build.sh` no longer fails on machines whose
+ active developer directory is Command Line Tools only: SwiftUI `@State`
+ needs the `SwiftUIMacros` plugin shipped with full Xcode, so the script
+ now exports `DEVELOPER_DIR` to Xcode (or a caller-set path) before
+ `swift build`, with a clear error when no macOS platform is present. (#849)
+ - `ai-memory serve` no longer leaked file descriptors from half-open HTTP
+ connections until `EMFILE`, breaking the healthcheck (an unauthenticated
+ availability/DoS). A hook or MCP client whose peer died without sending FIN
+ (laptop sleep, a VPN/Tailscale flap, an abrupt kill) left its accepted
+ socket `ESTABLISHED` forever, since the OS default has TCP keepalive off —
+ each dead peer leaked one fd, exhausting the 1024-fd default in roughly 2-3
+ days of normal churn. Accepted connections now get TCP keepalive via
+ `socket2`, tunable with the new `tcp_keepalive_secs` config key (default
+ 60s; `AI_MEMORY_TCP_KEEPALIVE_SECS=0` disables keepalive). This closes the
+ half-open-socket half of the fd leak; the rmcp session-table half was
+ already fixed in 2.4.0 by the rmcp 2.x bump. (#792)
+ - `ai-memory bootstrap` no longer returns a 500 when the LLM emits a page
+ path containing a Windows-illegal character (e.g. a `:` copied verbatim
+ from a conventional-commit subject like `build(sandbox): orchestrate`).
+ Such a path passed the deliberately tolerant `PagePath::new` and only
+ failed later at `ensure_portable` inside the atomic wiki write batch,
+ which aborted every page in the run, not just the offending one. Bad
+ paths are now sanitized (illegal characters replaced with `-`, directory
+ shape preserved) before validation, so the run and its other pages
+ survive; a path `ensure_portable` still rejects after sanitizing is
+ skipped with a warning instead of failing the batch. (#847)
+ - Per-session consolidation (`consolidate_session_multi`) had the same
+ Windows-illegal-path defect as `ai-memory bootstrap` (#847): an
+ LLM-produced page path containing a character like `:` passed the
+ deliberately tolerant `PagePath::new` and only failed later at
+ `ensure_portable` inside the atomic wiki write batch, losing every other
+ page from that session's consolidation run. The path is now sanitized
+ the same way bootstrap's is, consistently across rule-routing, per-user
+ slot placement, and the session-anchor comparison, before validation;
+ a path `ensure_portable` still rejects after sanitizing is skipped with
+ a warning instead of failing the batch. (#848)
+ - The Windows release checksum (`ai-memory-windows-x86_64.zip.sha256`) is now
+ written with a LF terminator instead of CRLF. `Out-File`'s Windows line
+ ending made `sha256sum -c` fail with `No such file or directory` — the CR
+ is read as part of the filename — on the WSL2 and Git Bash paths where that
+ is the natural command, and placed a stray byte in the release body's
+ checksum block, which concatenates every platform's file. The zip's smoke
+ test now requires LF rather than tolerating either, so the format the
+ release claims is the format it ships. (#838)
+ - `purge-session` now removes every page version the session owns at
+ `sessions/<id>.md` (including versions written before OKF sources existed
+ and summaries of sessions that never recorded a summary pointer), while a
+ manual page at the same path survives. (#862)
+ - Shell hooks no longer pin a CPU core for minutes on a large payload. The
+ `hooks/_lib.sh` extractors for `cwd`/`workspacePaths`/`workspace_roots`,
+ the session id, and Antigravity's `invocationNum` located each key with
+ `${payload#*"key"}`, which is quadratic in the payload size under dash and
+ bash: a 200 KB Cursor `postToolUse` event spent minutes in
+ `ai_memory_extract_cwd`, and concurrent hooks stayed at 100% CPU before
+ ever reaching the POST. A shared `ai_memory_after_key` helper now finds the
+ first occurrence with one linear `awk` pass (about 50 ms at 200 KB) and
+ feeds the unchanged `sed` parsing, so the extracted values are the same as
+ before. (#870)
+ - The generated TypeScript integrations (OpenCode 1 and 2, OMP, Pi,
+ OpenClaw) no longer flash a console window on Windows for every captured
+ event: their `git` lookups set `windowsHide`. The repo-root project lookup
+ behind those spawns is memoized per cwd instead of running two synchronous
+ `git` processes on every event. (#863)
+ - Shell hooks on macOS no longer corrupt non-ASCII characters in the query
+ string. `/bin/sh` there is bash 3.2, which sign-extends bytes >= 0x80, so
+ `ai_memory_url_encode` sent `é` as `%FFFFFFFFFFFFFFC3%FFFFFFFFFFFFFFA9`
+ instead of `%C3%A9`. An accented cwd reached the server as a different
+ path, and Cursor events and the session-start handoff lookup both use the
+ query `cwd`. (#877)
+ - Link extraction no longer mints a permanently unresolved row from a
+ directory target. A `relations:` value whose final component is empty
+ (`sessions/`) had the extension appended to nothing and was stored as the
+ literal `sessions/.md`; the same target in a body link or wikilink
+ (`[notes/](notes/)`) stayed extension-less. No page path can match either —
+ page paths carry `.md` and `latest_page_id_for_link` matches exactly — so
+ both sat in `links` with `to_page_id = NULL` and were visible only as
+ `unresolved:` in `ai-memory status`. Both routes now skip a directory
+ target, or a stem-less `.md`, with the existing warning. (#915)
## [2.4.0] - 2026-09-21
diff --cc crates/ai-memory-cli/src/commands/backfill.rs
index e8a3aede,2565f2ef..0c1b3b93
--- a/crates/ai-memory-cli/src/commands/backfill.rs
+++ b/crates/ai-memory-cli/src/commands/backfill.rs
@@@ -40,11 -40,11 +40,11 @@@ use serde::{Deserialize, Serialize}
use ai_memory_core::{NewWorkstreamEvent, WorkstreamEventKind};
use ai_memory_workstream::{
- ManagedHarness, build_launch_plan, export_transcript, list_native_sessions,
- wait_for_transcript_flush,
+ LaunchRoots, ManagedHarness, build_launch_plan_with_env, export_transcript,
+ list_native_sessions, wait_for_transcript_flush,
};
- use super::doctor::SCANNED_HARNESSES;
+ use super::doctor::{SCANNED_HARNESSES, relocated_session_dir};
use super::run;
use crate::config::Config;
use crate::http_client::{ServerEndpoint, get_json, post_json};
diff --cc crates/ai-memory-cli/src/commands/render_shared.rs
index 15681494,719bc1b2..595a9d17
--- a/crates/ai-memory-cli/src/commands/render_shared.rs
+++ b/crates/ai-memory-cli/src/commands/render_shared.rs
@@@ -283,17 -268,20 +283,28 @@@ function captureConfig(cwd: string | un
return { state: "invalid", patterns: [], base: candidateBase };
}
}
- function captureGlob(pattern: string, candidate: string, insensitive: boolean, budget: { work: number }): boolean | undefined { const p = [...pattern]; const c = [...candidate]; const eq = (a: string, b: string) => insensitive && a.charCodeAt(0) < 128 && b.charCodeAt(0) < 128 ? a.toLowerCase() === b.toLowerCase() : a === b; const previous = new Array<boolean>(p.length + 1).fill(false); previous[0] = true; for (let j = 1; j <= p.length; j++) previous[j] = p[j - 1] === "*" && p[j] !== "*" && previous[j - 1]; for (const ch of c) { const current = new Array<boolean>(p.length + 1).fill(false); for (let j = 1; j <= p.length; j++) { if (++budget.work > CAPTURE_MAX_WORK) return undefined; const x = p[j - 1]; current[j] = x === "*" && p[j] === "*" ? false : x === "*" && j >= 2 && p[j - 2] === "*" ? current[j - 2] || previous[j] : x === "*" ? current[j - 1] || (ch !== "/" && previous[j]) : x === "?" ? ch !== "/" && previous[j - 1] : eq(x, ch) && previous[j - 1]; } for (let j = 0; j <= p.length; j++) previous[j] = current[j]; } return previous[p.length]; }
- function captureTool(payload: Record<string, unknown>): { family: CaptureProtocol["tool_family"]; paths?: string[]; extraction: CaptureProtocol["extraction_state"]; callID?: string } { const name = typeof payload.tool === "string" ? payload.tool.toLowerCase() : ""; const args = payload.args as Record<string, unknown> | undefined; const call = ["tool_use_id","toolUseId","tool_call_id","toolCallId","call_id","callId","callID"].map((k) => payload[k]).find((v): v is string => typeof v === "string" && /^[A-Za-z0-9_.-]{1,128}$/.test(v)); if (["search","grep","glob","find","list","ls","list_files","read_dir"].includes(name)) return { family: "search-list", extraction: "not-applicable", callID: call }; if (["bash","shell","execute","run_command","web_search"].includes(name)) return { family: "non-file", extraction: "extracted", callID: call }; if (!["read","write","edit","apply_patch","notebookedit","notebook_edit","create_file","delete_file","rename_file","move_file","multi_edit","multiedit","replace","replace_all"].includes(name)) return { family: "unknown", extraction: "extracted", callID: call }; const direct = (o: any): string[] | undefined => { if (!o || typeof o !== "object") return undefined; const r: string[] = []; for (const k of ["file_path","filePath","path","absolute_path","AbsolutePath","notebook_path"]) if (k in o) { if (typeof o[k] !== "string") return undefined; r.push(o[k]); } if ("paths" in o) { if (!Array.isArray(o.paths) || o.paths.some((x: unknown) => typeof x !== "string")) return undefined; r.push(...o.paths); } return r.length && r.length <= CAPTURE_MAX_CANDIDATES ? r : undefined; }; let paths = direct(args); if (["multi_edit","multiedit","replace_all"].includes(name)) { const entries = args?.edits ?? args?.replacements; if (!Array.isArray(entries) || !entries.length || entries.length > CAPTURE_MAX_CANDIDATES) paths = undefined; else { paths = paths ?? []; for (const entry of entries) { const more = direct(entry); if (!more || paths.length + more.length > CAPTURE_MAX_CANDIDATES) { paths = undefined; break; } paths.push(...more); } } } if (!paths || paths.some((p) => !p.trim() || [...p].length > CAPTURE_MAX_PATH_CHARS)) return { family: "file", extraction: "missing-or-malformed", callID: call }; return { family: "file", paths, extraction: "extracted", callID: call }; }
+ function captureGlob(pattern: string, candidate: string, insensitive: boolean, budget: { work: number }): boolean | undefined { const p = [...pattern]; const c = [...candidate]; const previous = new Array<boolean>(p.length + 1).fill(false); previous[0] = true; for (let j = 1; j <= p.length; j++) previous[j] = p[j - 1] === "*" && p[j] !== "*" && previous[j - 1]; for (const ch of c) { const current = new Array<boolean>(p.length + 1).fill(false); for (let j = 1; j <= p.length; j++) { if (++budget.work > CAPTURE_MAX_WORK) return undefined; const x = p[j - 1]; current[j] = x === "*" && p[j] === "*" ? false : x === "*" && j >= 2 && p[j - 2] === "*" ? current[j - 2] || previous[j] : x === "*" ? current[j - 1] || (ch !== "/" && previous[j]) : x === "?" ? ch !== "/" && previous[j - 1] : captureCharEq(x, ch, insensitive) && previous[j - 1]; } for (let j = 0; j <= p.length; j++) previous[j] = current[j]; } return previous[p.length]; }
+ function captureCharEq(a: string, b: string, insensitive: boolean): boolean { return insensitive && a.charCodeAt(0) < 128 && b.charCodeAt(0) < 128 ? a.toLowerCase() === b.toLowerCase() : a === b; }
+ function captureLiteralPrefix(path: string): string { const glob = path.search(/[*?]/); if (glob < 0) return path; const slash = path.lastIndexOf("/", glob); if (slash < 0) return ""; const head = path.slice(0, slash + 1); const trimmed = head.slice(0, -1); return trimmed && !trimmed.endsWith(":") ? trimmed : head; }
+ function captureStartsWith(path: string, prefix: string, insensitive: boolean): boolean { const p = path[Symbol.iterator](); for (const x of prefix) { const c = p.next(); if (c.done || !captureCharEq(x, c.value, insensitive)) return false; } return true; }
+ function captureGlobReaches(glob: string, prefix: string, insensitive: boolean, budget: { work: number }): boolean | undefined { const target = prefix.replace(/\/+$/, ""); const depth = target.split("/").filter(Boolean).length; if (!depth) return true; let seen = 0; let offset = 0; for (const part of glob.split("/")) { offset += part.length; if (part && ++seen === depth) return captureGlob(glob.slice(0, offset), target, insensitive, budget); offset++; } return false; }
+ function captureShellCommand(args: Record<string, unknown> | undefined): string | undefined { if (!args || typeof args !== "object" || Array.isArray(args)) return undefined; const value = "command" in args ? args.command : args.cmd; if (typeof value === "string") return value; if (Array.isArray(value) && value.every((x) => typeof x === "string")) return value.join(" "); return undefined; }
+ function captureShellWords(command: string): string[] { const special = (c: string) => /\s/.test(c) || "|&;<>()".includes(c); const chars = [...command]; const words: string[] = []; let word = ""; let inWord = false; let quote = ""; for (let i = 0; i < chars.length; i++) { const c = chars[i]; const next = chars[i + 1]; if (quote) { if (c === quote) quote = ""; else if (quote === '"' && c === "\\" && (next === '"' || next === "\\")) { word += next; i++; } else word += c; } else if (c === "'" || c === '"') { quote = c; inWord = true; } else if (c === "\\" && next !== undefined && (special(next) || next === "'" || next === '"' || next === "\\")) { word += next; i++; inWord = true; } else if (special(c)) { if (inWord) words.push(word); word = ""; inWord = false; } else { word += c; inWord = true; } } if (inWord) words.push(word); return words; }
+ function captureShellArguments(word: string): string[] { const out = word.startsWith("-") ? [] : [word]; const eq = word.indexOf("="); if (eq >= 0) out.push(word.slice(eq + 1)); return out.filter((argument) => argument.trim() !== ""); }
+ // Lexical only, like the native hook: nothing is expanded or executed, so
+ // variables, command substitution, and `cd` state are not followed. A tool's
+ // own `workdir` replaces the event cwd for relative arguments.
+ function captureMatchCommand(command: string, config: CaptureConfig, workdir?: string): boolean | undefined { const budget = { work: 0 }; const home = homedir(); const base = workdir === undefined ? config.base : /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(workdir) ? workdir : config.base && captureJoin(config.base, workdir); for (const word of captureShellWords(command)) for (const argument of captureShellArguments(word)) { const expanded = argument.startsWith("~/") ? captureJoin(home, argument.slice(2)) : argument; if ([...expanded].length > CAPTURE_MAX_PATH_CHARS) continue; const absolute = /^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(expanded); if (!absolute && !base) continue; const candidate = captureNormalize(absolute ? expanded : captureJoin(base, expanded)); if (!candidate) continue; const glob = /[*?]/.test(candidate.path); for (const pattern of config.patterns) { if (candidate.windows !== pattern.windows) continue; const under = captureStartsWith(candidate.path, pattern.prefix, pattern.windows); if (!under && !glob) continue; if (under) { const directory = pattern.directory ? captureGlob(pattern.directory, candidate.path, pattern.windows, budget) : false; if (directory !== false) return directory; const match = captureGlob(pattern.path, candidate.path, pattern.windows, budget); if (match !== false) return match; } if (glob) { const reaches = captureGlobReaches(candidate.path, pattern.prefix, pattern.windows, budget); if (reaches !== false) return reaches; } } } return false; }
+ function captureTool(payload: Record<string, unknown>): { family: CaptureProtocol["tool_family"]; paths?: string[]; extraction: CaptureProtocol["extraction_state"]; callID?: string; command?: string; workdir?: string } { const name = typeof payload.tool === "string" ? payload.tool.toLowerCase() : ""; const args = payload.args as Record<string, unknown> | undefined; const call = ["tool_use_id","toolUseId","tool_call_id","toolCallId","call_id","callId","callID"].map((k) => payload[k]).find((v): v is string => typeof v === "string" && /^[A-Za-z0-9_.-]{1,128}$/.test(v)); if (["search","grep","glob","find","list","ls","list_files","read_dir"].includes(name)) return { family: "search-list", extraction: "not-applicable", callID: call }; if (["bash","shell","shell_command","exec","execute","run_command","web_search","terminal","execute_bash","execute_cmd"].includes(name)) return { family: "non-file", extraction: "extracted", callID: call, command: captureShellCommand(args), workdir: typeof args?.workdir === "string" && args.workdir.trim() ? args.workdir : undefined }; if (!["read","write","edit","apply_patch","notebookedit","notebook_edit","create_file","delete_file","rename_file","move_file","multi_edit","multiedit","replace","replace_all"].includes(name)) return { family: "unknown", extraction: "extracted", callID: call }; const direct = (o: any): string[] | undefined => { if (!o || typeof o !== "object") return undefined; const r: string[] = []; for (const k of ["file_path","filePath","path","absolute_path","AbsolutePath","notebook_path"]) if (k in o) { if (typeof o[k] !== "string") return undefined; r.push(o[k]); } if ("paths" in o) { if (!Array.isArray(o.paths) || o.paths.some((x: unknown) => typeof x !== "string")) return undefined; r.push(...o.paths); } return r.length && r.length <= CAPTURE_MAX_CANDIDATES ? r : undefined; }; let paths = direct(args); if (["multi_edit","multiedit","replace_all"].includes(name)) { const entries = args?.edits ?? args?.replacements; if (!Array.isArray(entries) || !entries.length || entries.length > CAPTURE_MAX_CANDIDATES) paths = undefined; else { paths = paths ?? []; for (const entry of entries) { const more = direct(entry); if (!more || paths.length + more.length > CAPTURE_MAX_CANDIDATES) { paths = undefined; break; } paths.push(...more); } } } if (!paths || paths.some((p) => !p.trim() || [...p].length > CAPTURE_MAX_PATH_CHARS)) return { family: "file", extraction: "missing-or-malformed", callID: call }; return { family: "file", paths, extraction: "extracted", callID: call }; }
-function capturePolicy(payload: Record<string, unknown>, cwd: string | undefined): { disposition: CaptureDisposition; protocol?: CaptureProtocol; payload: Record<string, unknown> } { const markerPresent = !!findMarker(cwd); if (CAPTURE_MODE === "allowlist" && !markerPresent) return { disposition: "drop", payload }; const config = captureConfig(cwd); const tool = captureTool(payload); let disposition: CaptureDisposition = "keep"; if (config.state === "invalid" && tool.family === "file") disposition = "metadata-only"; else if (config.state === "active" && tool.family === "search-list") disposition = "drop"; else if (config.state === "active" && tool.family === "file") { if (!tool.paths) disposition = "metadata-only"; else { const candidates = tool.paths.map((p) => captureNormalize(/^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(p) ? p : captureJoin(config.base, p))); if (candidates.some((p) => !p)) disposition = "metadata-only"; else { const budget = { work: 0 }; captureMatch: for (const candidate of candidates as { path: string; windows: boolean }[]) for (const pattern of config.patterns) { if (candidate.windows !== pattern.windows) continue; if (pattern.directory && captureGlob(pattern.directory, candidate.path, pattern.windows, budget)) { disposition = "drop"; break captureMatch; } const match = captureGlob(pattern.path, candidate.path, pattern.windows, budget); if (match === undefined) { disposition = "metadata-only"; break; } if (match) { disposition = "drop"; break captureMatch; } } } } } else if (config.state === "active" && tool.family === "non-file" && tool.command !== undefined && captureMatchCommand(tool.command, config, tool.workdir) !== false) disposition = "drop"; if (config.state === "inactive") return { disposition, payload }; const protocol: CaptureProtocol = { version: CAPTURE_POLICY_V1, disposition, policy_state: config.state, tool_family: tool.family, path_count: tool.paths?.length ?? 0, extraction_state: tool.extraction }; if (disposition === "metadata-only") { const session = payload.sessionID ?? payload.sessionId ?? payload.session_id; const routing = typeof payload.cwd === "string" ? payload.cwd : cwd; return { disposition, protocol, payload: { ...(typeof session === "string" ? { session_id: session } : {}), ...(typeof routing === "string" ? { cwd: routing } : {}), tool_family: tool.family, tool_name: tool.family, ...(tool.callID ? { tool_call_id: tool.callID } : {}), _ai_memory_capture: protocol } }; } if (disposition === "keep") return { disposition, protocol, payload: { ...payload, _ai_memory_capture: protocol } }; return { disposition, protocol, payload }; }
+// An external lifecycle owner (`AI_MEMORY_CAPTURE_OWNER`, any value that is
+// non-empty after trimming) takes over capture for this process: the gate runs
+// before the capture-policy marker scan, so no disposition work, no marker read
+// by this policy, and no queue write, spool write, or capture POST downstream.
+// It does not reach the consumer's own routing work (`applyMarkerParams` runs
+// earlier in postHook), and context delivery (`fetchHandoff`) is a separate
+// path that stays live.
+function captureOwnedExternally(): boolean { const owner = typeof process === "undefined" ? undefined : process.env?.AI_MEMORY_CAPTURE_OWNER; return typeof owner === "string" && owner.trim() !== ""; }
- function capturePolicy(payload: Record<string, unknown>, cwd: string | undefined): { disposition: CaptureDisposition; protocol?: CaptureProtocol; payload: Record<string, unknown> } { if (captureOwnedExternally()) return { disposition: "drop", payload }; const markerPresent = !!findMarker(cwd); if (CAPTURE_MODE === "allowlist" && !markerPresent) return { disposition: "drop", payload }; const config = captureConfig(cwd); const tool = captureTool(payload); let disposition: CaptureDisposition = "keep"; if (config.state === "invalid" && tool.family === "file") disposition = "metadata-only"; else if (config.state === "active" && tool.family === "search-list") disposition = "drop"; else if (config.state === "active" && tool.family === "file") { if (!tool.paths) disposition = "metadata-only"; else { const candidates = tool.paths.map((p) => captureNormalize(/^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(p) ? p : captureJoin(config.base, p))); if (candidates.some((p) => !p)) disposition = "metadata-only"; else { const budget = { work: 0 }; captureMatch: for (const candidate of candidates as { path: string; windows: boolean }[]) for (const pattern of config.patterns) { if (candidate.windows !== pattern.windows) continue; if (pattern.directory && captureGlob(pattern.directory, candidate.path, pattern.windows, budget)) { disposition = "drop"; break captureMatch; } const match = captureGlob(pattern.path, candidate.path, pattern.windows, budget); if (match === undefined) { disposition = "metadata-only"; break; } if (match) { disposition = "drop"; break captureMatch; } } } } } if (config.state === "inactive") return { disposition, payload }; const protocol: CaptureProtocol = { version: CAPTURE_POLICY_V1, disposition, policy_state: config.state, tool_family: tool.family, path_count: tool.paths?.length ?? 0, extraction_state: tool.extraction }; if (disposition === "metadata-only") { const session = payload.sessionID ?? payload.sessionId ?? payload.session_id; const routing = typeof payload.cwd === "string" ? payload.cwd : cwd; return { disposition, protocol, payload: { ...(typeof session === "string" ? { session_id: session } : {}), ...(typeof routing === "string" ? { cwd: routing } : {}), tool_family: tool.family, tool_name: tool.family, ...(tool.callID ? { tool_call_id: tool.callID } : {}), _ai_memory_capture: protocol } }; } if (disposition === "keep") return { disposition, protocol, payload: { ...payload, _ai_memory_capture: protocol } }; return { disposition, protocol, payload }; }
++function capturePolicy(payload: Record<string, unknown>, cwd: string | undefined): { disposition: CaptureDisposition; protocol?: CaptureProtocol; payload: Record<string, unknown> } { if (captureOwnedExternally()) return { disposition: "drop", payload }; const markerPresent = !!findMarker(cwd); if (CAPTURE_MODE === "allowlist" && !markerPresent) return { disposition: "drop", payload }; const config = captureConfig(cwd); const tool = captureTool(payload); let disposition: CaptureDisposition = "keep"; if (config.state === "invalid" && tool.family === "file") disposition = "metadata-only"; else if (config.state === "active" && tool.family === "search-list") disposition = "drop"; else if (config.state === "active" && tool.family === "file") { if (!tool.paths) disposition = "metadata-only"; else { const candidates = tool.paths.map((p) => captureNormalize(/^(?:\/|\\\\|[A-Za-z]:[\\/])/.test(p) ? p : captureJoin(config.base, p))); if (candidates.some((p) => !p)) disposition = "metadata-only"; else { const budget = { work: 0 }; captureMatch: for (const candidate of candidates as { path: string; windows: boolean }[]) for (const pattern of config.patterns) { if (candidate.windows !== pattern.windows) continue; if (pattern.directory && captureGlob(pattern.directory, candidate.path, pattern.windows, budget)) { disposition = "drop"; break captureMatch; } const match = captureGlob(pattern.path, candidate.path, pattern.windows, budget); if (match === undefined) { disposition = "metadata-only"; break; } if (match) { disposition = "drop"; break captureMatch; } } } } } else if (config.state === "active" && tool.family === "non-file" && tool.command !== undefined && captureMatchCommand(tool.command, config, tool.workdir) !== false) disposition = "drop"; if (config.state === "inactive") return { disposition, payload }; const protocol: CaptureProtocol = { version: CAPTURE_POLICY_V1, disposition, policy_state: config.state, tool_family: tool.family, path_count: tool.paths?.length ?? 0, extraction_state: tool.extraction }; if (disposition === "metadata-only") { const session = payload.sessionID ?? payload.sessionId ?? payload.session_id; const routing = typeof payload.cwd === "string" ? payload.cwd : cwd; return { disposition, protocol, payload: { ...(typeof session === "string" ? { session_id: session } : {}), ...(typeof routing === "string" ? { cwd: routing } : {}), tool_family: tool.family, tool_name: tool.family, ...(tool.callID ? { tool_call_id: tool.callID } : {}), _ai_memory_capture: protocol } }; } if (disposition === "keep") return { disposition, protocol, payload: { ...payload, _ai_memory_capture: protocol } }; return { disposition, protocol, payload }; }
"##;
TEMPLATE.replace("__AI_MEMORY_CAPTURE_MODE__", capture_mode)
}
@@@ -2232,15 -2068,21 +2243,17 @@@ mod tests
assert_eq!(h, "Bearer abc123");
}
- /// Manual Node-required runtime evidence for the exact TypeScript emitted by
+ /// Node-required runtime evidence for the exact TypeScript emitted by
/// `ts_capture_policy_v1`. This deliberately executes the emitted source,
- /// rather than maintaining a JavaScript copy in the test suite.
+ /// rather than maintaining a JavaScript copy in the test suite. Ignored
+ /// because Node is not a build requirement; the Linux CI test job installs
+ /// Node and runs it explicitly, so a missing Node fails instead of skipping.
#[test]
- #[ignore = "manual Node-required generated TypeScript runtime evidence"]
+ #[ignore = "needs Node >= 22.6; CI runs it with --ignored"]
fn generated_capture_policy_v1_node_runtime_evidence() {
- let strip_types = Command::new("node")
- .args(["--experimental-strip-types", "--version"])
- .output();
- assert!(
- strip_types.is_ok_and(|output| output.status.success()),
- "Node runtime evidence needs node with --experimental-strip-types (Node >= 22.6)"
- );
+ let Some(()) = node_strip_types_available() else {
+ return;
+ };
let temp = tempfile::tempdir().unwrap();
let module = temp.path().join("capture-policy-runtime-evidence.ts");
diff --cc crates/ai-memory-hooks/src/router.rs
index 18f4ead2,9d5f8dde..1ebd3491
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@@ -3291,26 -2981,24 +3294,35 @@@ async fn process_authorized
// between them would leave an ended session whose successor has
// nothing to pick up. A managed run and an admission refusal both take
// the second arm, ending the session with no handoff at all.
- let handoff_id = match handoff {
- Some(handoff) => Some(
- state
- .writer
- .end_admitted_session_with_handoff(
- admitted.clone(),
- Some(page_id),
- handoff,
- env.occurred_at_micros(),
- )
- .await?,
- ),
- None => {
- state
- .writer
- .end_admitted_session(admitted.clone(), Some(page_id), env.occurred_at_micros())
- .await?;
- None
+ let handoff_id = if turn_checkpoint {
+ match handoff {
+ Some(handoff) => state.writer.checkpoint_session_handoff(handoff).await?,
+ None => None,
+ }
+ } else {
+ match handoff {
+ Some(handoff) => Some(
+ state
+ .writer
- .end_admitted_session_with_handoff(admitted.clone(), Some(page_id), handoff)
++ .end_admitted_session_with_handoff(
++ admitted.clone(),
++ Some(page_id),
++ handoff,
++ env.occurred_at_micros(),
++ )
+ .await?,
+ ),
+ None => {
+ state
+ .writer
- .end_admitted_session(admitted.clone(), Some(page_id))
++ .end_admitted_session(
++ admitted.clone(),
++ Some(page_id),
++ env.occurred_at_micros(),
++ )
+ .await?;
+ None
+ }
}
};
if handoff_id.is_some()
@@@ -4089,624 -3740,114 +4101,626 @@@ mod tests
}
/// Build a minimal `HookState` backed by a real on-disk store.
- async fn make_state(tmp: &TempDir) -> HookState {
- let store = Store::open(tmp.path()).unwrap();
- let ws = store
+ /// A capture is a write, so it needs `write`.
+ ///
+ /// Captures wrote observations into whichever repository a working
+ /// directory resolved to, with no grant check at all — the one mutating
+ /// path that checked nothing. The refusal has to be silent at the HTTP
+ /// layer (the handler answered 202 long before the repository was known),
+ /// so what this pins is the part that matters: nothing is stored, and the
+ /// drop is counted where an operator can see it.
+ #[tokio::test]
+ async fn a_capture_needs_writer_on_the_repository_it_lands_in() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ // Grants only decide anything in a restricted project.
+ state
.writer
- .get_or_create_workspace("default")
+ .set_new_project_mode(ai_memory_store::AccessMode::Restricted)
.await
.unwrap();
- let proj = store
- .writer
- .get_or_create_project(ws, "scratch", None)
+ let cwd = tmp.path().to_path_buf();
+
+ // Which repository a capture lands in is resolved from the cwd, not
+ // from the server's baked project, so ask the resolver rather than
+ // assuming: a grant on the wrong repository would make this test pass
+ // for the wrong reason.
+ let probe = SessionId::new().to_string();
+ capture_as(&state, &cwd, &probe, None).await.unwrap();
+ let landed = state
+ .reader
+ .observations_for_session(probe.parse().unwrap())
.await
- .unwrap();
- let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
- let sanitizer = Sanitizer::default();
- HookState {
- ingest_metrics: Arc::new(ai_memory_core::IngestMetrics::default()),
- workspace_id: ws,
- project_id: proj,
- writer: store.writer.clone(),
- reader: store.reader.clone(),
- wiki,
- consolidator: None,
- sanitizer,
- project_cache: Arc::new(tokio::sync::Mutex::new(ProjectCacheStore::default())),
- active_project: ActiveProject::new(),
- consolidate_on_session_end: false,
- session_consolidation_notify: None,
- capture_assistant_enabled: false,
- subagent_sessions: Arc::new(tokio::sync::Mutex::new(SubagentSessionSet::default())),
- ingest_rate: Arc::new(tokio::sync::Mutex::new(IngestRateLimiter::disabled())),
- home_dir: None,
- trusted_proxy_identity: false,
- ingest_semaphore: Arc::new(tokio::sync::Semaphore::new(
- DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT,
- )),
- ingest_gates: IngestGates::default(),
- per_user_slots: false,
- mid_session_routing: MidSessionRouting::default(),
+ .unwrap()[0]
+ .project_id;
+
+ let reader = user_holding(
+ &state,
+ "ray",
+ landed,
+ Some(ai_memory_store::GrantLevel::Read),
+ )
+ .await;
+ let writer = user_holding(
+ &state,
+ "wren",
+ landed,
+ Some(ai_memory_store::GrantLevel::Write),
+ )
+ .await;
+ let stranger = user_holding(&state, "sam", landed, None).await;
+
+ // A read-only grant, and no grant at all, are both refused.
+ for (who, user) in [("reader", reader), ("stranger", stranger)] {
+ let session = SessionId::new().to_string();
+ let err = capture_as(&state, &cwd, &session, Some(user))
+ .await
+ .expect_err("{who} must not be able to capture");
+ assert!(
+ err.downcast_ref::<CaptureNotAuthorized>().is_some(),
+ "{who}: the refusal must be the terminal kind, not a generic failure: {err}"
+ );
+ let stored = state
+ .reader
+ .observations_for_session(session.parse().unwrap())
+ .await
+ .unwrap();
+ assert!(stored.is_empty(), "{who} stored an observation anyway");
}
- }
- async fn seed_checkpoint_observation(state: &HookState, title: &str) -> SessionId {
- let session_id = SessionId::new();
- state
- .writer
- .begin_session(NewSession {
- occurred_at: None,
- id: session_id,
- workspace_id: state.workspace_id,
- project_id: state.project_id,
- agent_kind: AgentKind::ClaudeCode,
- cwd: None,
- actor_user: None,
- })
+ // Counted where an operator looks, and not confused with a policy drop.
+ let snap = state.ingest_metrics.snapshot();
+ assert_eq!(
+ snap.dropped_unauthorized, 0,
+ "the router records it, not this layer"
+ );
+
+ // A writer's capture lands, exactly as before.
+ let session = SessionId::new().to_string();
+ capture_as(&state, &cwd, &session, Some(writer))
.await
- .unwrap();
- state
- .writer
- .insert_observation_ingest(
- Sanitized::new(
- NewObservation {
- occurred_at: None,
- session_id,
- workspace_id: state.workspace_id,
- project_id: state.project_id,
- kind: ObservationKind::UserPrompt,
- extension: None,
- source_event: None,
- title: title.into(),
- body: "state that must survive compaction".into(),
- importance: 8,
- },
- &state.sanitizer,
- ),
- format!("checkpoint-fixture-{session_id}"),
- )
+ .expect("a writer may capture");
+ let stored = state
+ .reader
+ .observations_for_session(session.parse().unwrap())
.await
.unwrap();
- session_id
+ assert_eq!(stored.len(), 1, "the writer's capture must be stored");
}
- /// Regression: a configured-but-failing LLM used to make PreCompact
- /// strictly worse than no LLM at all. `consolidate_or_synth` propagated the
- /// provider error, the caller only warned, and the rule-based page a
- /// zero-LLM install would have written never happened, so compaction threw
- /// the session's working state away with nothing on disk.
+ /// An unauthorized batch item is CONSUMED, never left to be retried.
+ ///
+ /// This is the half that could have become a retry loop. The batch ack
+ /// tells the client which items to drop from its spool; reporting an
+ /// unauthorized item as not-accepted would leave it there to be re-sent
+ /// until its attempt budget ran out, and every attempt would be refused
+ /// for the same reason. It also stalls every item behind it. So it is
+ /// acked like any other policy drop, and simply not stored.
#[tokio::test]
- async fn checkpoint_falls_back_to_rule_based_page_when_the_provider_rejects_the_prompt() {
+ async fn an_unauthorized_batch_item_is_consumed_rather_than_retried() {
let tmp = TempDir::new().unwrap();
- let mut state = make_state(&tmp).await;
- state.consolidator = Some(Arc::new(Consolidator::new(
- state.reader.clone(),
- state.writer.clone(),
- state.wiki.clone(),
- Arc::new(ContextOverflowLlm),
- state.workspace_id,
- state.project_id,
- )));
-
- let session_id = seed_checkpoint_observation(&state, "keep-this-working-state").await;
+ let state = make_state(&tmp).await;
+ // Grants only decide anything in a restricted project.
+ state
+ .writer
+ .set_new_project_mode(ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let cwd = tmp.path().to_path_buf();
- consolidate_or_synth(
+ let probe = SessionId::new().to_string();
+ capture_as(&state, &cwd, &probe, None).await.unwrap();
+ let landed = state
+ .reader
+ .observations_for_session(probe.parse().unwrap())
+ .await
+ .unwrap()[0]
+ .project_id;
+ let reader = user_holding(
&state,
- session_id,
- state.workspace_id,
- state.project_id,
- AgentKind::ClaudeCode,
- "pre-compact",
+ "ray",
+ landed,
+ Some(ai_memory_store::GrantLevel::Read),
+ )
+ .await;
+
+ let session = SessionId::new().to_string();
+ let items = vec![HookBatchItem {
+ url: "http://h/hook?event=user-prompt-submit&agent=claude-code".into(),
+ body: serde_json::json!({
+ "session_id": session,
+ "cwd": cwd.to_string_lossy(),
+ "prompt": "hello",
+ }),
+ }];
+ let before = state.ingest_metrics.snapshot().dropped_unauthorized;
+ let response = handle_hook_batch(
+ State(Arc::new(state.clone())),
+ None,
+ Some(axum::Extension(ai_memory_core::AuthLevel::User)),
+ Some(axum::Extension(ai_memory_core::AuthorizedViewer(reader))),
+ HeaderMap::new(),
+ Json(items),
+ )
+ .await
+ .into_response();
+ assert_eq!(response.status(), StatusCode::OK);
+ let body = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let ack: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(
+ ack["accepted"], 1,
+ "the client must be told to drop it, or it will re-send it forever: {ack}"
+ );
+
+ let stored = state
+ .reader
+ .observations_for_session(session.parse().unwrap())
+ .await
+ .unwrap();
+ assert!(stored.is_empty(), "an acked item must still not be stored");
+ assert_eq!(
+ state.ingest_metrics.snapshot().dropped_unauthorized,
+ before + 1,
+ "the drop must be visible to an operator"
+ );
+ }
+
+ /// With no viewer, captures behave exactly as they always have.
+ ///
+ /// `None` is what the `AuthorizedViewer` marker yields for root and on an
+ /// install with no database users.
+ #[tokio::test]
+ async fn a_capture_with_no_viewer_is_untouched_by_the_check() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let session = SessionId::new().to_string();
+ capture_as(&state, tmp.path(), &session, None)
+ .await
+ .expect("no viewer must not change capture");
+ let stored = state
+ .reader
+ .observations_for_session(session.parse().unwrap())
+ .await
+ .unwrap();
+ assert_eq!(stored.len(), 1);
+ }
+
+ /// A capture that opens a new project records the user capturing as its
+ /// creator.
+ ///
+ /// The hook path creates a project before it checks access, so without a
+ /// creator the first capture from a new checkout would create a restricted
+ /// row and then be refused on it — and so would every capture after it,
+ /// since nobody would ever hold a grant on it. The choke point admits the
+ /// creator without one; a second user reaching the same row finds it
+ /// existing and is checked like anyone else.
+ #[tokio::test]
+ async fn a_capture_opening_a_new_project_admits_its_creator() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ // Grants only decide anything in a restricted project.
+ state
+ .writer
+ .set_new_project_mode(ai_memory_store::AccessMode::Restricted)
+ .await
+ .unwrap();
+ let repo = tmp.path().join("fresh-checkout");
+ std::fs::create_dir_all(&repo).unwrap();
+ let cora = user_holding(&state, "cora", state.project_id, None).await;
+ let dan = user_holding(&state, "dan", state.project_id, None).await;
+
+ let first = SessionId::new().to_string();
+ capture_as(&state, &repo, &first, Some(cora))
+ .await
+ .expect("the capture that creates a repository must be kept");
+ let stored = state
+ .reader
+ .observations_for_session(first.parse().unwrap())
+ .await
+ .unwrap();
+ assert_eq!(stored.len(), 1);
+ let created = stored[0].project_id;
+ assert_ne!(created, state.project_id);
+ assert!(
+ state
+ .reader
+ .grants_for(cora, created)
+ .await
+ .unwrap()
+ .is_empty(),
+ "the creator needs no grant"
+ );
+ assert!(
+ state
+ .reader
+ .authorize_project(
+ stored[0].workspace_id,
+ created,
+ ai_memory_store::ProjectPrincipal::user(cora),
+ true,
+ ai_memory_store::ProjectAccess::Write,
+ )
+ .await
+ .unwrap()
+ .is_ok(),
+ "the creator is admitted"
+ );
+
+ let second = SessionId::new().to_string();
+ capture_as(&state, &repo, &second, Some(cora))
+ .await
+ .expect("and so must every capture after it");
+
+ let intruder = SessionId::new().to_string();
+ let refused = capture_as(&state, &repo, &intruder, Some(dan)).await;
+ assert!(
+ refused.is_err_and(|e| e.is::<CaptureNotAuthorized>()),
+ "a second user must not inherit the creator's repository"
+ );
+ assert!(
+ state
+ .reader
+ .observations_for_session(intruder.parse().unwrap())
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert!(
+ state
+ .reader
+ .grants_for(dan, created)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ }
+
+ /// Session start routes by the same identity a capture does, so its
+ /// handoff and briefing come from the project the captures land in. Same
+ /// validation: a rung that routes by name, or a malformed value, is `None`.
+ #[test]
+ fn handoff_query_accepts_identity_on_the_same_terms_as_a_capture() {
+ let query = |identity: &str, source: &str| HandoffQuery {
+ identity: Some(identity.to_owned()),
+ identity_src: Some(source.to_owned()),
+ ..Default::default()
+ };
+ let got = query("github.com/orga/api", "git_remote")
+ .repository_identity()
+ .unwrap();
+ assert_eq!(got.identity, "github.com/orga/api");
+ assert!(
+ query("github.com/orga/api", "manifest")
+ .repository_identity()
+ .is_none()
+ );
+ assert!(
+ query("GitHub.com/Orga/API", "git_remote")
+ .repository_identity()
+ .is_none()
+ );
+ assert!(HandoffQuery::default().repository_identity().is_none());
+ }
+
+ /// A capture that carries the repository identity its client resolved.
+ async fn capture_with_identity(
+ state: &HookState,
+ cwd: &std::path::Path,
+ session: &str,
+ identity: Option<(&str, &str)>,
+ ) -> ProjectId {
+ let env = HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: "user-prompt-submit".into(),
+ agent: Some("claude-code".into()),
+ identity: identity.map(|(identity, _)| identity.to_owned()),
+ identity_src: identity.map(|(_, source)| source.to_owned()),
+ ..Default::default()
+ },
+ serde_json::json!({
+ "session_id": session,
+ "cwd": cwd.to_string_lossy(),
+ "prompt": "hello",
+ }),
+ );
+ process_authorized(
+ state,
+ env,
+ None,
+ ai_memory_core::AuthLevel::User,
+ Vec::new(),
+ None,
+ )
+ .await
+ .unwrap();
+ state
+ .reader
+ .observations_for_session(session.parse().unwrap())
+ .await
+ .unwrap()[0]
+ .project_id
+ }
+
+ /// #708's collision, end to end: two unrelated repositories both checked
+ /// out as `api/` used to land in one project. With the client's identity
+ /// they land in two, and the same repository under a different folder name
+ /// lands back in its own. The two `api/` checkouts share a folder name and
+ /// nothing else, so the path-keyed project cache must not answer for both.
+ #[tokio::test]
+ async fn two_api_checkouts_with_different_remotes_get_two_projects() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let org_a = tmp.path().join("org-a").join("api");
+ let org_b = tmp.path().join("org-b").join("api");
+ let clone = tmp.path().join("elsewhere").join("acme-api");
+ for dir in [&org_a, &org_b, &clone] {
+ std::fs::create_dir_all(dir).unwrap();
+ }
+ let a = capture_with_identity(
+ &state,
+ &org_a,
+ &SessionId::new().to_string(),
+ Some(("github.com/orga/api", "git_remote")),
+ )
+ .await;
+ let b = capture_with_identity(
+ &state,
+ &org_b,
+ &SessionId::new().to_string(),
+ Some(("github.com/orgb/api", "git_remote")),
+ )
+ .await;
+ assert_ne!(a, b, "unrelated repositories must not share a project");
+ assert_eq!(
+ state
+ .reader
+ .project_name_by_id(state.workspace_id, b)
+ .await
+ .unwrap(),
+ Some("orgb-api".to_owned())
+ );
+ let again = capture_with_identity(
+ &state,
+ &clone,
+ &SessionId::new().to_string(),
+ Some(("github.com/orga/api", "git_remote")),
+ )
+ .await;
+ assert_eq!(again, a, "one repository, one project, whatever the folder");
+
+ // A client that sends nothing, or a rung that routes by name, keeps
+ // today's routing: the folder name.
+ let plain = tmp.path().join("plain").join("api");
+ std::fs::create_dir_all(&plain).unwrap();
+ let by_name =
+ capture_with_identity(&state, &plain, &SessionId::new().to_string(), None).await;
+ assert_eq!(
+ by_name, a,
+ "no identity routes by the folder name, as before"
+ );
+ let declared = capture_with_identity(
+ &state,
+ &plain,
+ &SessionId::new().to_string(),
+ Some(("github.com/orgc/api", "manifest")),
+ )
+ .await;
+ assert_eq!(declared, a, "a manifest identity is ignored on the wire");
+ }
+
+ /// Two machines sharing one server can hold unrelated repositories at the
+ /// same path (`~/src/api` on each). The project cache is keyed by path, so
+ /// without the identity in its key whichever resolved first would answer
+ /// for both, and the second machine's captures would land in the first's
+ /// project.
+ #[tokio::test]
+ async fn one_path_with_two_remotes_is_two_projects() {
+ let tmp = TempDir::new().unwrap();
+ let state = make_state(&tmp).await;
+ let shared = tmp.path().join("src").join("api");
+ std::fs::create_dir_all(&shared).unwrap();
+
+ let first = capture_with_identity(
+ &state,
+ &shared,
+ &SessionId::new().to_string(),
+ Some(("github.com/orga/api", "git_remote")),
+ )
+ .await;
+ let second = capture_with_identity(
+ &state,
+ &shared,
+ &SessionId::new().to_string(),
+ Some(("github.com/orgb/api", "git_remote")),
+ )
+ .await;
+ assert_ne!(first, second, "the cache answered for the wrong repository");
+
+ // Control: the same repository at that path keeps resolving to its own.
+ let again = capture_with_identity(
+ &state,
+ &shared,
+ &SessionId::new().to_string(),
+ Some(("github.com/orga/api", "git_remote")),
+ )
+ .await;
+ assert_eq!(again, first);
+ }
+
+ /// A capture, with the viewer it is authenticated as.
+ async fn capture_as(
+ state: &HookState,
+ cwd: &std::path::Path,
+ session: &str,
+ viewer: Option<ai_memory_core::UserId>,
+ ) -> anyhow::Result<()> {
+ let env = HookEnvelope::from_query_and_body(
+ HookQuery {
+ event: "user-prompt-submit".into(),
+ agent: Some("claude-code".into()),
+ ..Default::default()
+ },
+ serde_json::json!({
+ "session_id": session,
+ "cwd": cwd.to_string_lossy(),
+ "prompt": "hello",
+ }),
+ );
+ process_authorized(
+ state,
+ env,
+ None,
+ ai_memory_core::AuthLevel::User,
+ Vec::new(),
+ viewer,
+ )
+ .await
+ }
+
+ /// A user holding `role` on the capture fixture's repository.
+ ///
+ /// Uses the real grant API rather than raw SQL, so the test exercises the
+ /// same path an operator's `ai-memory user grant` call takes.
+ async fn user_holding(
+ state: &HookState,
+ username: &str,
+ repository: ProjectId,
+ role: Option<ai_memory_store::GrantLevel>,
+ ) -> ai_memory_core::UserId {
+ let id = state
+ .writer
+ .create_human_user(
+ ai_memory_core::NewUser {
+ username: username.to_owned(),
+ name: None,
+ email: None,
+ },
+ ai_memory_core::UserRole::User,
+ None,
+ false,
+ )
+ .await
+ .unwrap();
+ if let Some(role) = role {
+ state
+ .writer
+ .grant_memory(id, repository, role, None)
+ .await
+ .unwrap();
+ }
+ id
+ }
+
+ async fn make_state(tmp: &TempDir) -> HookState {
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let sanitizer = Sanitizer::default();
+ HookState {
+ ingest_metrics: Arc::new(ai_memory_core::IngestMetrics::default()),
+ workspace_id: ws,
+ project_id: proj,
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ wiki,
+ consolidator: None,
+ sanitizer,
+ project_cache: Arc::new(tokio::sync::Mutex::new(ProjectCacheStore::default())),
+ active_project: ActiveProject::new(),
+ consolidate_on_session_end: false,
+ session_consolidation_notify: None,
+ capture_assistant_enabled: false,
+ subagent_sessions: Arc::new(tokio::sync::Mutex::new(SubagentSessionSet::default())),
+ ingest_rate: Arc::new(tokio::sync::Mutex::new(IngestRateLimiter::disabled())),
+ home_dir: None,
+ trusted_proxy_identity: false,
+ ingest_semaphore: Arc::new(tokio::sync::Semaphore::new(
+ DEFAULT_HOOK_INGEST_MAX_IN_FLIGHT,
+ )),
+ ingest_gates: IngestGates::default(),
+ per_user_slots: false,
+ mid_session_routing: MidSessionRouting::default(),
+ }
+ }
+
+ async fn seed_checkpoint_observation(state: &HookState, title: &str) -> SessionId {
+ let session_id = SessionId::new();
+ state
+ .writer
+ .begin_session(NewSession {
++ occurred_at: None,
+ id: session_id,
+ workspace_id: state.workspace_id,
+ project_id: state.project_id,
+ agent_kind: AgentKind::ClaudeCode,
+ cwd: None,
+ actor_user: None,
+ })
+ .await
+ .unwrap();
+ state
+ .writer
+ .insert_observation_ingest(
+ Sanitized::new(
+ NewObservation {
++ occurred_at: None,
+ session_id,
+ workspace_id: state.workspace_id,
+ project_id: state.project_id,
+ kind: ObservationKind::UserPrompt,
+ extension: None,
+ source_event: None,
+ title: title.into(),
+ body: "state that must survive compaction".into(),
+ importance: 8,
+ },
+ &state.sanitizer,
+ ),
+ format!("checkpoint-fixture-{session_id}"),
+ )
+ .await
+ .unwrap();
+ session_id
+ }
+
+ /// Regression: a configured-but-failing LLM used to make PreCompact
+ /// strictly worse than no LLM at all. `consolidate_or_synth` propagated the
+ /// provider error, the caller only warned, and the rule-based page a
+ /// zero-LLM install would have written never happened, so compaction threw
+ /// the session's working state away with nothing on disk.
+ #[tokio::test]
+ async fn checkpoint_falls_back_to_rule_based_page_when_the_provider_rejects_the_prompt() {
+ let tmp = TempDir::new().unwrap();
+ let mut state = make_state(&tmp).await;
+ state.consolidator = Some(Arc::new(Consolidator::new(
+ state.reader.clone(),
+ state.writer.clone(),
+ state.wiki.clone(),
+ Arc::new(ContextOverflowLlm),
+ state.workspace_id,
+ state.project_id,
+ )));
+
+ let session_id = seed_checkpoint_observation(&state, "keep-this-working-state").await;
+
+ consolidate_or_synth(
+ &state,
+ session_id,
+ state.workspace_id,
+ state.project_id,
+ AgentKind::ClaudeCode,
+ "pre-compact",
ai_memory_core::ActorContext::anonymous(),
)
.await
diff --cc crates/ai-memory-mcp/src/server.rs
index ea89cf1e,91b858f6..fed28e68
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@@ -2754,29 -2572,31 +2757,32 @@@ impl AiMemoryServer
// Default-scoped queries (no workspace/project/scopes/global args)
// also union the reserved `_global` preferences scope, so standing
// user/team context travels into every project without the caller
- // knowing a magic project name (issue #154). Explicit scoping means
- // the caller asked for exactly those scopes — leave it alone. One
- // extra scoped search when the scope exists; zero cost when it
- // doesn't.
- let default_scoped = args.scopes.is_empty()
- && args
- .workspace
- .as_deref()
- .is_none_or(|s| s.trim().is_empty())
- && args.project.as_deref().is_none_or(|s| s.trim().is_empty());
- let global_scope_hits = if default_scoped {
+ // knowing a magic project name (issue #154). This unions for any query
+ // that resolves to a single project — whether the project is left
+ // implicit (active-project pointer) or named explicitly with
+ // `workspace`+`project`. Naming the current project is exactly what the
+ // static-client routing doctrine tells callers to do, so gating the
+ // union on absent `workspace`/`project` silently denied global
+ // preferences to every static client (#930). Only an explicit,
+ // deliberately-narrowed multi-scope set (`scopes`) opts out — the
+ // caller asked for exactly those scopes. One extra scoped search when
+ // the reserved scope exists; zero cost when it doesn't.
+ let single_project_scoped = args.scopes.is_empty();
+ let global_scope_hits = if single_project_scoped {
match ai_memory_store::lookup_global_scope(&self.reader).await {
Ok(Some(scope)) => {
- // If the current project IS the reserved scope (e.g. the
- // actor's active-project pointer lands there after a
- // global write), `hits` already covers it — don't search
- // it twice.
+ // If the project this query resolves to IS the reserved
+ // scope (e.g. the caller named it, or the actor's
+ // active-project pointer lands there after a global write),
+ // `hits` already covers it — don't search it twice. Resolve
+ // through the query's own `workspace`/`project` so a named
+ // project is compared, not the active-project default.
let current = self
.effective_ids_for_read_args_with_actor(
- None,
- None,
+ args.workspace.as_deref(),
+ args.project.as_deref(),
&aps_actor,
+ Self::viewer_from_parts(Some(&parts)),
)
.await?;
if current == scope.as_tuple() {
diff --cc crates/ai-memory-store/src/lib.rs
index f0044438,4d9685ee..a5cb4edf
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@@ -54,21 -52,16 +54,21 @@@ pub use decay::
salience_after_feedback,
};
pub use error::{StoreError, StoreResult};
+pub use grants::{GrantFilter, GrantListing, GrantOutcome, ProjectGrant};
pub use maintenance::MaintenanceJob;
pub use ops::{
- AdmittedSession, BootstrapChunkRecord, CompactSummary, Compaction, DeleteWorkspaceSummary,
- EmbedOutcome, EmbeddingWrite, EntityBackfillSummary, HookSessionAdmission, IdentityResolution,
- IngestObservationOutcome, LifecycleOnlyEndOutcome, MAX_PENDING_INBOX_MESSAGES,
- MoveSessionSummary, MoveSummary, ObservationPruneOutcome, OkfMigratedPage,
- PAGE_WINDOW_BACKFILL_BATCH, PageWindowBackfillSummary, PagesMode, PurgeMode,
- PurgeSessionSummary, PurgeSummary, ReorgSummary, backfill_entity_index, backfill_page_windows,
- backfill_page_windows_in_batches, purge_session, record_embed_failure,
+ AdmittedSession, BootstrapChunkRecord, CompactSummary, Compaction, DateOnlyTtlPage,
+ DeleteWorkspaceSummary, EmbedOutcome, EmbeddingWrite, EntityBackfillSummary,
- HookSessionAdmission, IngestObservationOutcome, LifecycleOnlyEndOutcome,
++ HookSessionAdmission, IdentityResolution, IngestObservationOutcome, LifecycleOnlyEndOutcome,
+ MAX_PENDING_INBOX_MESSAGES, MoveSessionSummary, MoveSummary, ObservationPruneOutcome,
- OkfMigratedPage, PAGE_WINDOW_BACKFILL_BATCH, PageWindowBackfillSummary, PagesMode,
++ OkfMigratedPage, PAGE_WINDOW_BACKFILL_BATCH, PageWindowBackfillSummary, PagesMode, PurgeMode,
+ PurgeSessionSummary, PurgeSummary, ReorgSummary, StaleAfterRepair, backfill_entity_index,
+ backfill_page_windows, backfill_page_windows_in_batches, purge_session, record_embed_failure,
};
+pub use project_authz::{
+ AccessMode, GrantLevel, ProjectAccess, ProjectAuthz, ProjectPrincipal,
+ RESTRICTED_PROJECT_FORBIDDEN, authorize_project, resolve_project_authz,
+};
pub use reader::{
ActivityWindow, AgentSessionCount, AuditEvent, AuditLogFilter, AutoImproveCandidateSession,
AutoImproveParkedClaim, BriefPageBody, BriefingPage, BriefingSnapshot, ClientActivity,
diff --cc crates/ai-memory-store/src/ops.rs
index bdfcb151,a8b68c0d..193ac27c
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@@ -2044,35 -1814,21 +2134,39 @@@ pub fn admit_hook_session_event
if !owner_filter.admits(session.actor_user.as_deref()) {
return Err(StoreError::SessionCollision);
}
+ // `now` is also the ingest-key TTL clock above; started_at honors
+ // the caller's original event time (backfill) and only falls
+ // back to it when absent (live capture).
+ let started_at = session.occurred_at.unwrap_or(now);
tx.execute(
"INSERT INTO sessions (id, workspace_id, project_id, agent_kind, cwd, started_at, actor_user) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
- params![session.id.as_bytes(), session.workspace_id.as_bytes(), session.project_id.as_bytes(), session.agent_kind.as_str(), session.cwd.as_ref().map(|p| p.to_string_lossy().into_owned()), now, session.actor_user.as_deref()],
+ params![session.id.as_bytes(), session.workspace_id.as_bytes(), session.project_id.as_bytes(), session.agent_kind.as_str(), session.cwd.as_ref().map(|p| p.to_string_lossy().into_owned()), started_at, session.actor_user.as_deref()],
)?;
- (session.actor_user.clone(), None, 0)
+ (
+ session.actor_user.clone(),
+ None,
+ 0,
+ None,
+ (session.workspace_id, session.project_id),
+ )
}
};
+ let (workspace_id, project_id) = scope;
+ let rescoped;
+ let obs = if (obs.workspace_id, obs.project_id) == scope {
+ obs
+ } else {
+ rescoped = NewObservation {
+ workspace_id,
+ project_id,
+ ..obs.clone()
+ };
+ &rescoped
+ };
let guard = AdmittedSession {
session_id: session.id,
- workspace_id: session.workspace_id,
- project_id: session.project_id,
+ workspace_id,
+ project_id,
agent_kind: session.agent_kind,
owner,
};
diff --cc crates/ai-memory-wiki/src/wiki.rs
index 8a30f313,fe77491d..b529cd8f
--- a/crates/ai-memory-wiki/src/wiki.rs
+++ b/crates/ai-memory-wiki/src/wiki.rs
@@@ -2219,23 -2325,98 +2337,103 @@@ impl Wiki
// tool reply still happens "indexes commit in the same
// transaction" (basic-memory #763 lesson): no fire-and-forget
// background embedding.
- if let Some(embedder) = &self.embedder {
- match embedder.embed_document(&final_body).await {
+ self.embed_page_version(page_id, &final_body, abstract_text.as_deref())
+ .await?;
+
+ // Non-blocking webhooks fire-and-forget only after the page has landed
+ // on disk and the DB/index write has succeeded. They observe the final
+ // persisted page and cannot mutate or reject it.
+ if let (Some(chain), Some(ctx)) = (&self.admission_chain, &resolved_ctx) {
+ chain.dispatch_async(
+ Some(path_for_dispatch.as_str()),
+ &frontmatter_for_dispatch,
+ &final_body,
+ ctx,
+ );
+ }
+ Ok(page_id)
+ }
+
+ /// Embed `body` (and its L0 `abstract:` line, if present) into
+ /// `page_id`'s vectors, when an embedder is configured.
+ ///
+ /// Shared by [`Wiki::write_page`] (every version written through the
+ /// API) and [`Wiki::reindex_page_locked`] (external file writes and
+ /// rewrites picked up by the watcher), so a page version becomes
+ /// hybrid-searchable through the same mechanism regardless of which path
+ /// produced it. Before this was pulled out, only `write_page` embedded —
+ /// a watcher-driven rewrite got a new page id (the supersession chain
+ /// worked) but no embedding until a manual `ai-memory embed` (issue
+ /// #929): hybrid search silently fell back to FTS-only ranking for
+ /// every rewritten page.
+ ///
+ /// Best-effort: an embedder failure is logged and recorded via
+ /// `record_embed_failure` but never propagated, so a working page write
+ /// is never undone by an embedding hiccup.
+ ///
+ /// # Errors
+ /// Returns [`WikiError`] only for a store error while persisting a
+ /// successfully computed vector; provider/embedder failures are caught
+ /// and recorded instead.
+ async fn embed_page_version(
+ &self,
+ page_id: PageId,
+ body: &str,
+ abstract_text: Option<&str>,
+ ) -> WikiResult<()> {
+ let Some(embedder) = &self.embedder else {
+ return Ok(());
+ };
+ match embedder.embed_document(body).await {
+ Ok(vec) => {
+ let bytes = f32_vec_to_bytes(&vec);
+ self.writer
+ .store_embedding(
+ page_id,
+ bytes,
+ embedder.provider().to_string(),
- embedder.model().to_string(),
++ // Not `.model()`: a configured document prefix must land
++ // under a distinct stored identity so a prefix change is
++ // never silently mixed with vectors embedded under a
++ // different (or no) prefix. See `Embedder::model_identity`.
++ embedder.model_identity(),
+ embedder.dim(),
+ )
+ .await?;
+ }
+ Err(e) => {
+ tracing::warn!(error = %e, path = %page_id, "embedding failed; page indexed without it");
+ // The warning alone dies with the container. Record it so
+ // the page is attributable later (#528); best-effort,
+ // because failing to note a failure must not fail the
+ // write that already succeeded.
+ let _ = self
+ .writer
+ .record_embed_failure(
+ page_id,
+ ai_memory_store::EmbedOutcome::Failed,
+ Some(e.to_string()),
+ )
+ .await;
+ }
+ }
+ // L0 abstract: the frontmatter `abstract:` line is embedded on
+ // its own so the opt-in abstract stream can rank on the sharp
+ // one-line summary. A page rewritten without the key has its
+ // stale abstract row removed, mirroring the body row's
+ // replace-on-write semantics.
+ match abstract_text {
+ Some(abstract_text) => match embedder.embed_document(abstract_text).await {
Ok(vec) => {
- let bytes = f32_vec_to_bytes(&vec);
self.writer
- .store_embedding(
+ .store_abstract_embeddings(vec![ai_memory_store::EmbeddingWrite {
page_id,
- bytes,
- embedder.provider().to_string(),
- // Not `.model()`: a configured document prefix
- // must land under a distinct stored identity so
- // a prefix change is never silently mixed with
- // vectors embedded under a different (or no)
- // prefix. See `Embedder::model_identity`.
- embedder.model_identity(),
- embedder.dim(),
- )
+ vector_bytes: f32_vec_to_bytes(&vec),
+ provider: embedder.provider().to_string(),
- model: embedder.model().to_string(),
++ // See the body-embedding write above.
++ model: embedder.model_identity(),
+ dim: embedder.dim(),
+ }])
.await?;
}
Err(e) => {
diff --cc docs/lifecycle-ops.md
index e79bf586,2983cdf0..739c9cfe
--- a/docs/lifecycle-ops.md
+++ b/docs/lifecycle-ops.md
@@@ -17,10 -17,9 +17,10 @@@ on a homelab box where mistakes are har
| `move-project --confirm` | ✅ yes | source only in the merge case (a `Reject`-policy `purge_project` webhook can still abort the source teardown leaving everything intact) | no | Fresh destination → lossless **true move** (re-stamp `workspace_id`, keep `project_id`, rename the dir): sessions/observations/handoffs + history all survive. Destination with a same-named project → **copy+purge merge**: only latest pages migrate. |
| `move-session <id> --to --confirm` | ✅ yes | no | yes (move it back) | Re-stamps one session (or every session touching `--from-project`) into another project: `sessions`, `observations`, its `handoffs`, consolidation jobs, auto-improve runs/claims and its `sessions/<id>.md` page, one transaction per session; the page file moves with it (`--pages move`, default) or is retired for regeneration. Without `--confirm` it is a real dry run (rolled back). Refuses with `409` an open session or a pending consolidation job unless `--force`. |
| `backup --to` | ✅ yes | no | n/a | Streams a gzipped tarball from the server's online `sqlite3 .backup` plus the wiki tree. Safe alongside the live writer. |
+| `reclaim-ledger-versions` | ✅ yes | superseded pre-#660 ledger page *versions* only | no (the latest page version stays) | Dry-run by default; needs `--confirm` to delete. Online through the writer actor, safe alongside the live writer. Content-gated: only non-latest, non-decay `log.md`/`log-YYYY-MM.md` versions whose body opens with a ledger hook entry are removed; a real page that merely shares the name is untouched. `--compact` additionally rebuilds FTS and `VACUUM`s to reclaim the freed bytes. |
| `checkpoints` | ✅ yes | no | n/a | Lists recent wiki git checkpoints. Read-only. |
| `restore-page --path --from` | ✅ yes | overwrites one markdown page version | yes (restore another checkpoint) | Restores one page from wiki git history, reindexes it into SQLite, and writes a post-restore checkpoint. Does not restore DB-only state. |
- | `restore --from <tarball>` | ❌ **stop the server first** | overwrites the data dir | no (without prior backup) | Refuses if any sibling `ai-memory` process is alive (sysinfo guard). |
+ | `restore --from <tarball>` | ❌ **stop the server first** | overwrites the data dir | no (without prior backup) | Refuses if any sibling `ai-memory` process is alive (sysinfo guard). Stages and verifies the archive before swapping it in, so a failed restore leaves `wiki/` and `db/` as they were. |
| `reset --confirm` | ❌ **stop the server first** | yes, all data | no | Refuses if any sibling `ai-memory` process is alive (sysinfo guard). |
| `reindex` | ❌ **stop the server first** | no wiki wipe; requires a clean DB | only with prior DB backup | Rebuilds pages/links/FTS from `wiki/` using `_meta.md` manifests. Refuses if SQLite already has rows so stale DB-only state cannot survive silently. |
diff --cc docs/security-boundaries.md
index 59fb21ec,00dadc30..935d8d42
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@@ -23,14 -23,11 +23,15 @@@ boundary not yet built
| # | Boundary | Enforcing code | Adversarial test(s) | Coverage |
|---|----------|----------------|---------------------|----------|
| 1 | Per-project isolation (3-tuple) | `ai-memory-store/src/scope.rs` `ScopeResolver::resolve_read_args`/`resolve_write_args`, no-create `lookup_existing_scope`; reader queries filter by `(workspace_id, project_id)` | `store` `scope.rs` read-resolution table tests; `tests/suite/multi_session.rs` | STRONG |
+ | 1b | Reserved `_global` scope union never leaks a foreign project (#930) | `ai-memory-mcp/src/server.rs` `memory_query` — the union runs for single-project queries (`scopes` empty) and searches **only** `lookup_global_scope`'s reserved `(workspace_id, project_id)`, never an arbitrary project; the double-search guard resolves the *queried* project (named or active) so it can't be tricked into skipping | `server.rs` `global_union_never_leaks_a_foreign_projects_pages` (a third real project's page must not surface via the union; reserved page must), `single_project_query_unions_global_scope_and_multi_scope_skips_it` | STRONG |
| 2 | Workspace isolation | same as #1; same-named project → distinct ids per workspace | `scope.rs` cross-workspace resolution rows; `multi_scope` dedup/validate | STRONG |
| 3 | Multi-user auth ladder | `ai-memory-core/src/actor.rs` `AuthLevel::authorize`; `ai-memory-mcp/src/auth.rs` middleware; `admin.rs` `require_root_for_multiuser_admin` / `require_root` | `admin.rs` `multiuser_admin_routes_reject_db_user_tier` / `…reject_anonymous` / `create_user_as_user_tier_returns_403`; `auth.rs` unknown-bearer 401; `actor.rs` `skip_admission_chain_rejects_db_users` | STRONG |
+| 3b | Browser triage of pending writes (#855) | `ai-memory-web/src/routes/pending.rs` `require_admin` (`AuthLevel::authorize(Capability::Admin, distinguishes_operators)`, trusted-proxy flag from `WebMountSpec`) gates `GET {web_slug}/pending`; `html_auth.rs` `AdminRequired` keeps a non-root 403 off the change-password redirect; decisions post to the existing `/admin/pending-writes/{id}/approve\|reject` behind `require_dual_auth` (session + CSRF) and `require_root_for_multiuser_admin`. `ai-memory-web` has no write route | `ai-memory-web` `tests/suite/pending.rs` — anonymous refused (401, login redirect), DB user refused (403, no proposal text, no redirect), trusted-proxy flag reaches the gate, single-operator control admits, POSTs to `/pending*` refused, project filter keys do not collide on `/` in names, projects past the 500-row read cap stay counted and reachable; `ai-memory-mcp` `tests/suite/admin_pending_writes_session.rs` — anonymous and DB-user sessions refused, root session without a matching CSRF header refused (each leaves the proposal pending and no file), root approval keeps `auto_improve_proposal_id`/`auto_improve_run_id` and records the approver, root reject writes no file (each proven to fail with its guard removed) | STRONG |
| 4 | Handoff single-claim / no-steal | `ai-memory-store/src/ops.rs` `accept_handoff_in_transaction` (metadata `state='open'` guard + atomic CAS) | `multi_session.rs` `a_second_accept_cannot_steal_an_accepted_handoff`; `handoff_ownership.rs` `another_operator_cannot_claim_the_handoff` | STRONG |
| 4b | Handoff owner-scoped recovery (`any_owner` admin gate) | `ai-memory-mcp/src/server.rs` `require_admin_capability` on `memory_handoff_accept`/`_cancel` `any_owner` | `handoff_admission.rs` — cancel gate + **accept gate** (adversarial: non-admin `any_owner` accept refused) | STRONG |
+| 4c | Turn-checkpoint baton is owner+scope-bound | `ai-memory-store/src/ops.rs` `checkpoint_session_handoff` — reads the session's own `(workspace, project, owner_user)` from `sessions WHERE id=?1 AND ended_at IS NULL`, refuses on scope/owner mismatch, refreshes only that session's own `state='open'` baton (id preserved), returns `None` when the session already ended | `ops.rs` `checkpoint_session_handoff_refreshes_only_the_live_sessions_own_baton` (#865) | STRONG |
+| 4d | Native session rebind / drifted-end is owner+agent+cwd CAS | `ai-memory-store/src/ops.rs` — `session.moved` rebind gated on `agent==OpenCode` + `ended_at IS NULL` + lexical `normalize_cwd(stored)==normalize_cwd(from)`; `expire_same_cwd_auto_handoffs` AND-gated on `owner_user IS ?4 AND id IS NOT ?5` and on the source not being another still-open session (row 4e, #883); drifted `SessionEnd` ends only same owner+agent+cwd | `ops.rs` `native_move_rebinds_live_session_only_from_its_current_cwd`, `native_move_rejects_foreign_owner_and_ignores_completed_replay`, `drifted_session_end_ends_only_the_same_actor_agent_and_cwd` (#865) | STRONG |
+| 4e | A live session's baton stays its own until the session is quiet | `ai-memory-store/src/ops.rs` - `expire_same_cwd_auto_handoffs` spares batons of other open sessions; `accept_handoff_in_transaction(.., busy_since)` re-checks inside the claim that the source is not an open session with observations after the cutoff, and its sweep `expire_superseded_auto_handoffs(.., busy_since)` spares a busy open session's baton (every open session's when `None`, the explicit MCP accept); `reader.rs` `startup_handoff` selects with the same cutoff; `ai-memory-hooks/src/router.rs` `LIVE_BATON_QUIET_PERIOD` | `multi_session.rs` `parallel_live_sessions_keep_their_own_checkpoint_batons`, `startup_claim_rechecks_the_source_and_sweeps_only_quiet_open_batons`; `router.rs` `opencode_parallel_live_batons_are_owned_and_wait_for_quiet` - each fails with its guard removed | STRONG |
| 5a | Pages shared: `author_id` is never a read filter (invariant #16) | `ai-memory-store/src/reader.rs` `search_pages`/`page_body_by_ids` — `author_id` is an attribution JOIN only, never a WHERE term | `multi_session.rs` — a page with a **non-null** `author_id` (operator A) is readable by operator B in the same project | STRONG |
| 5b | Page supersession (loser stays reachable) | `ai-memory-store/src/ops.rs` `upsert_page_in_tx` — demote `is_latest=0` (never delete) + `supersedes` chain | `multi_session.rs` `concurrent_writes_to_one_path_supersede_rather_than_destroy`; `retrieval_superseded.rs` | STRONG |
| 6 | Active-project pointer (PerActor, no clobber) | `ai-memory-core/src/active_project.rs` `set_for`/`lookup_for` (fail-closed on `Mismatch`) | `active_project.rs` `parallel_harnesses_of_one_user_keep_separate_pointers`, `two_operators_never_read_each_others_pointer`, `a_session_mismatch_fails_closed_once_anything_has_been_keyed` | STRONG |
@@@ -41,17 -37,15 +42,18 @@@
| 8c | Messaging: pop-exactly-once | `ai-memory-store/src/ops.rs` `pop_message_in_transaction` atomic CAS `WHERE state='pending'` | `agent_messages.rs` — sequential **and** `tokio::join!` concurrent double-pop yields exactly one `Some` | STRONG |
| 8d | Messaging: inferred-scope read is diagnosed (#854) | `scope.rs` `is_inferred`; `server.rs` `inferred_scope_hint` on empty pop/list | `agent_messages_briefing.rs` `no_scope_pop_that_misses_the_mail_is_diagnosed_not_a_silent_null` | STRONG |
| 9 | Scope resolution fail-closed | `ai-memory-store/src/scope.rs` no-create `lookup_existing_*`; create only via `create_explicit_scope` | `scope.rs` no-auto-create + `unscoped_write_with_unresolvable_coordinate_errors` | STRONG |
-| 10 | Destructive-op live-process refusal + confirm flags (invariant #9) | `ai-memory-cli/src/commands/process_guard.rs` `sibling_processes` + confirm flags in `reset`/`restore`/`reindex`/`uninstall --purge-data`/`purge_project` | `admin_purge.rs` confirm→400; `removal.rs` — injected live-sibling makes each destructive command bail before touching the data dir | STRONG |
-| 10b | Session purge is scope+owner-bound (no cross-session/project over-delete) | `ai-memory-store/src/ops.rs` `purge_session` — selection scoped to `(workspace_id, project_id)` and keyed on this session's own `summary_page_id` **or** `path='sessions/<sid>.md'` + `json_extract(frontmatter_json,'$.session_id')=<sid>` (frontmatter owner, not the recursive latest-chain); `in_scope==0 → NotFound` fail-closed; whole op in one transaction | `ops.rs` `purge_session_leaves_a_sibling_session_in_the_same_project_intact`, `…refuses_a_session_from_another_project_and_deletes_nothing`, `…refuses_a_session_from_another_workspace`, `…does_not_delete_an_identically_pathed_page_in_another_project`, `…removes_older_summary_versions_without_deleting_prior_manual_page` (#862) | STRONG |
+| 10 | Destructive-op live-process refusal + confirm flags (invariant #9); `purge-project`'s `dry_run` always wins over `confirm` so a preview request can never become destructive | `ai-memory-cli/src/commands/process_guard.rs` `sibling_processes` + confirm flags in `reset`/`restore`/`reindex`/`uninstall --purge-data`/`purge_project`; `admin.rs` `handle_purge_project` checks `req.dry_run` unconditionally, before `req.confirm`, mirroring `reclaim-ledger-versions` | `admin_purge.rs` confirm→400; `removal.rs` — injected live-sibling makes each destructive command bail before touching the data dir; `admin_purge.rs` `purge_project_confirm_true_and_dry_run_true_still_only_previews` — `{"confirm": true, "dry_run": true}` deletes nothing (the regression this row now also covers); `ops.rs` `purge_project_dry_run_changes_nothing` — every project-scoped row count, the `purged_scopes` tombstone, and the `audit_log` row are identical before/after a `PurgeMode::Preview` run; `ops.rs` `purge_project_counts_collateral_damage_in_another_project` and `admin_purge.rs` `purge_project_dry_run_and_confirmed_purge_both_report_collateral_damage_in_another_project` — a purge of project P collaterally deletes an observation, and orphans a handoff's session reference, in a *different* project Q (via `sessions` cascading out of P), and both the preview and the confirmed report count it | STRONG |
+| 10b | Session purge is scope+owner-bound (no cross-session/project over-delete); `purge-session`'s `dry_run` always wins over `confirm`, same as `purge-project` | `ai-memory-store/src/ops.rs` `purge_session` — selection scoped to `(workspace_id, project_id)` and keyed on this session's own `summary_page_id` **or** `path='sessions/<sid>.md'` + `json_extract(frontmatter_json,'$.session_id')=<sid>` (frontmatter owner, not the recursive latest-chain); `in_scope==0 → NotFound` fail-closed; whole op in one transaction; `admin.rs` `handle_purge_session` checks `req.dry_run` unconditionally, before `req.confirm` | `ops.rs` `purge_session_leaves_a_sibling_session_in_the_same_project_intact`, `…refuses_a_session_from_another_project_and_deletes_nothing`, `…refuses_a_session_from_another_workspace`, `…does_not_delete_an_identically_pathed_page_in_another_project`, `…removes_older_summary_versions_without_deleting_prior_manual_page` (#862); `admin_purge.rs` `purge_session_confirm_true_and_dry_run_true_still_only_previews` — `{"confirm": true, "dry_run": true}` deletes nothing; `ops.rs` `purge_session_dry_run_changes_nothing` — every table a session purge touches, the `purged_sessions` tombstone, and the `audit_log` row are identical before/after a `PurgeMode::Preview` run; `ops.rs` `purge_session_counts_collateral_damage_in_another_project` and `admin_purge.rs` `purge_session_dry_run_and_confirmed_purge_both_report_collateral_damage_in_another_project` — purging session S collaterally deletes an observation, and orphans a handoff's session reference, in a *different* project (via `S`'s own id cascading), and both the preview and the confirmed report count it; `admin_purge.rs` `purge_session_dry_run_refuses_a_session_outside_its_named_scope` — the same session previewed under a different real project (same workspace) or a different real workspace whose project shares the name both 404 with no counts in the body, with the session's own scope as the 200 control | STRONG |
+| 10c | Ledger reclaim is content-gated, not filename-gated (invariant #16) | `ai-memory-store/src/ops.rs` `reclaim_ledger_versions` — a candidate row must pass `ai_memory_core::log_ledger::body_opens_with_log_ledger` on its own `body`, and only `is_latest=0 AND superseded_at IS NULL` rows are eligible, so decay-owned rows stay with `forget-sweep`; confirm gate in `admin.rs` `handle_reclaim_ledger_versions` | `reclaim_ledger_versions.rs` `a_prose_page_wearing_the_ledger_name_keeps_its_whole_version_chain`, `an_ordinary_page_chain_in_another_project_is_untouched`, `a_decay_tombstone_stays_with_the_sweep_that_owns_it`; `admin_reclaim_ledger_versions.rs` `deleting_without_confirm_is_refused_and_changes_nothing` (with dry-run and confirmed controls) | STRONG |
+| 10d | Workspace delete's own row counts are scope-bound to `workspace_id` (a workspace's *own* rows are never over- or under-counted by a sibling workspace's), its cross-workspace observation/handoff cascade is reported by both preview and confirm rather than prevented (same as `purge-project` one level down), the non-empty guard fails closed without `force`, and `delete-workspace`'s `dry_run` always wins | `ai-memory-store/src/ops.rs` `delete_workspace` — every direct count and the `DELETE FROM workspaces` itself are scoped by `workspace_id = ?1`; the two `collateral_*` counts are scoped by `workspace_id != ?1` so a row is counted as one or the other but never both; `projects_deleted > 0 && !force → WorkspaceNotEmpty` fail-closed, and a missing workspace is `NotFound`, both checked identically under `PurgeMode::Preview` and `PurgeMode::Commit`; whole op in one transaction; `admin.rs` `handle_delete_workspace` checks `req.dry_run` unconditionally, before building the confirmed path, mirroring `reclaim-ledger-versions`/`purge-project`; root-only gate is the shared `/admin/*` multi-user auth ladder, not a separate check | `admin_move.rs` `delete_workspace_dry_run_never_counts_a_different_workspaces_rows` — previewing workspace A counts only its own project/page/session/observation/handoff rows, not workspace B's (which holds two like-named projects and its own full row set), and a session living in B that stamps an observation directly into A is counted in A's own `observations_deleted`, never in `collateral_observations_deleted` (the two counts are mutually exclusive by construction); `admin_move.rs` `delete_workspace_force_true_and_dry_run_true_still_only_previews` — `{"force": true, "dry_run": true}` deletes nothing; `ops.rs` `delete_workspace_dry_run_changes_nothing` — every table's row count, including `workspaces` itself and the `purged_scopes` tombstone (the two tables a confirmed delete's own transaction writes to), is identical before/after a `PurgeMode::Preview` run; `ops.rs` `delete_workspace_dry_run_and_confirmed_delete_both_report_collateral_damage_in_another_workspace` and `admin_move.rs` of the same name — deleting workspace W collaterally deletes an observation, and orphans a handoff's session reference, in a *different* workspace (via `sessions` cascading out of W), and both the preview and the confirmed response count it identically — the cascade itself is reported, not blocked, by either; `admin_move.rs` `delete_workspace_dry_run_refuses_non_empty_without_force` / `delete_workspace_dry_run_nonexistent_workspace_returns_404` — same `409`/`404` a confirmed delete would give; `admin.rs` `multiuser_delete_workspace_dry_run_rejects_db_user_and_anonymous` — root reaches the preview handler (404 control), DB user gets 403, anonymous gets 401 | STRONG |
| 11a | Hook backpressure (202/429) + bounded fan-out (invariant #5) | `ai-memory-hooks/src/router.rs` semaphore→429, 202 immediately, `MAX_HOOK_BATCH_ITEMS`, bounded LRU limiter | `router.rs` `handle_hook_returns_429_when_ingest_saturated`, `ingest_rate_limiter_is_bounded` | STRONG |
- | 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn) | `capture_policy.rs` per-agent `…honors_exclusions` tests | STRONG |
+ | 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn), including shell commands whose arguments name an ignored path (`match_command`); generated OpenCode/OMP/Pi/OpenClaw integrations mirror it in `render_shared.rs` `ts_capture_policy_v1` (`captureMatchCommand`) | `capture_policy.rs` per-agent `…honors_exclusions` tests, `shell_fixture_vectors` (shared `capture-policy.json` `shell` drop/keep vectors: tool aliases incl. OpenClaw/Devin `exec`, `workdir`, glob directories, Windows paths), `shell_tool_shapes_of_every_adapter_honor_exclusions`, `fixture_vectors` (incl. TS-adapter `bash`/`exec` vectors); `router.rs` `capture_protocol_shell_decisions_survive_server_reinspection`; `hook.rs` `shell_command_reading_an_ignored_path_is_dropped_before_spool`; `render_shared.rs` `generated_capture_policy_v1_node_runtime_evidence` (runs the same fixture sections against the emitted TypeScript; `#[ignore]` locally, run with `--ignored` under Node 24 by the Linux CI test job) | STRONG |
| 11c | Capture hook ≤200ms budget (invariant #5) | `hooks/_lib.sh` capture path `curl --max-time 0.2` (context-fetch 1.0s and background drain 2.0s are separate, larger-budget paths) | none (shell-script timeout; hard to unit-test) — watch on any capture-path change | WATCH |
| 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401 | STRONG |
-| 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-store/src/workstream.rs` `link_native_session` stamps `native_session_linked_at` on its own run only, both `finish` updates drop the stamp when the session changes, `run_status` reports it; `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a linked session only when `ai-memory-workstream` `native_session_in_checkout` holds it for this checkout (OpenCode by recorded directory), and never falls back to a link it set aside | `multi_session.rs` `a_session_linked_by_one_managed_run_is_not_another_runs`; `run.rs` `a_session_linked_during_the_run_wins_over_discovery` (concurrent newer session, another checkout's link refused, no fallback to it, unlinked control); `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout |
-| 14 | Client-supplied event time is bounded and self-scoped (#919) | `ai-memory-hooks/src/payload.rs` `HookEnvelope::occurred_at_micros` — a `/hook` caller's optional `occurred_at` must be `> 0` and `<= now + 5min`; it only sets the caller's *own* admitted session's `started_at`/`ended_at`/`created_at`, never another session/project/user, and the ingest dedup `seen_at`/TTL stays on `now` | `payload.rs` `occurred_at_micros_rejects_a_far_future_timestamp`, `…_rejects_non_positive_values`, `…_rejects_garbage_strings` | MEDIUM — self-scoped numeric bound; no cross-tenant surface (a client already controls its own content) |
-| — | Per-project authorization (#708) | proposal only — `docs/design-per-project-authz.md` (`authorize_project` choke point + unscoped-read/raw-id bypass classes) | none yet — the design's "Verification plan" tests (authz matrix, unscoped-read-leak, raw-id-authz, ship-inert) land WITH the code | FUTURE |
+| 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-store/src/workstream.rs` `link_native_session` stamps `native_session_linked_at` on its own run only, both `finish` updates drop the stamp when the session changes, `run_status` reports it; `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a linked session only when `ai-memory-workstream` `native_session_in_checkout` holds it for this checkout (OpenCode by recorded directory), never falls back to a link it set aside, and turns an `AmbiguousNativeSession` into a warning with nothing imported; `ai-memory-workstream/src/transcript.rs` `discover_crush` claims only the one top-level session created (or, with `--continue`, touched) during the run, and in a data directory outside the project only one that edited a file in it | `multi_session.rs` `a_session_linked_by_one_managed_run_is_not_another_runs`; `run.rs` `a_session_linked_during_the_run_wins_over_discovery` (concurrent newer session, another checkout's link refused, no fallback to it, unlinked control); `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run`; `run.rs` `ambiguous_crush_discovery_keeps_the_run`; `transcript.rs` `crush_discovery_claims_only_the_session_the_run_created`, `crush_discovery_in_a_shared_store_claims_only_an_edit_here` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout; Crush, which has no hooks, relies on that discovery alone and claims nothing when it is ambiguous |
+| 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are never taken from a caller (only derived from already-authorized hits), so there is no page-id entry point to guard | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository`; `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (18 tests) or the SQL filter (9 tests) neutralized | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them |
+| 14b | Repository identity routing (#708) | `ai-memory-store/src/ops.rs` `resolve_project_by_identity` — one transaction; an identity already on a project is never overwritten; an unclaimed project is claimed only when the capturing user may write it (the choke point's `resolve_project_authz` on the same transaction), otherwise it is returned unclaimed; a different identity under the same name splits into a new project with no shared `repo_path`; `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity too; `ai-memory-core/src/repository_identity.rs` strips credentials from remote URLs client-side, and the server accepts only the routing rungs (`explicit`, `git_remote`) from the wire | `tests/suite/identity_resolution.rs` `an_outsider_cannot_take_an_unclaimed_projects_identity` (control: `an_existing_project_is_claimed_in_place`), `two_unrelated_repositories_with_one_folder_name_stay_apart`, `a_created_or_split_project_admits_its_creator`; `router.rs` `one_path_with_two_remotes_is_two_projects`, `two_api_checkouts_with_different_remotes_get_two_projects` (a manifest rung on the wire is ignored); `repository_identity.rs` credential and normalisation tables — the claim guard and the cache key each proven to fail their test when removed | STRONG — first claimant wins: in a restricted workspace a user who creates a project under a remote identity first holds it until root grants others |
++| 14c | Client-supplied event time is bounded and self-scoped (#919) | `ai-memory-hooks/src/payload.rs` `HookEnvelope::occurred_at_micros` — a `/hook` caller's optional `occurred_at` must be `> 0` and `<= now + 5min`; it only sets the caller's *own* admitted session's `started_at`/`ended_at`/`created_at`, never another session/project/user, and the ingest dedup `seen_at`/TTL stays on `now` | `payload.rs` `occurred_at_micros_rejects_a_far_future_timestamp`, `…_rejects_non_positive_values`, `…_rejects_garbage_strings` | MEDIUM — self-scoped numeric bound; no cross-tenant surface (a client already controls its own content) |
## Keeping this current (the standing protocol)