Skip to content

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

Rust

fix(audit): harden integrated bug fixes

AkitaOnRailsd556c938ffdb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f09bdd0b..c73167ad 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,20 +13,33 @@ version in [`docs/changelog/`](docs/changelog/):
### Fixed
+- Fixed the PowerShell Docker wrapper leaving native managed commands without
+ the root bearer stored in a named volume. Native `install-hooks` now refreshes
+ a host copy under the user's local app-data directory once, and `run`,
+ `show`, `continue`, `resume`,
+ `workstreams`, and `rename-workstream` reuse it without starting a container;
+ explicit token and bind-mounted data-dir settings still take precedence
+ (#1603).
+- Fixed Antigravity print-mode managed runs recording no user prompt because
+ `agy --prompt` does not append to shared `history.jsonl`. When that history
+ yields no prompt, export now reads only explicit `USER_INPUT` records from
+ the conversation's bounded, containment-checked brain transcript (#1605).
+- Kept Claude Code's combined SessionStart context below its fixed 10,000
+ character inline limit. Profile and handoff sections are independently
+ bounded, must-see handoff/continuity/inbox notices take priority, and an
+ omitted managed ledger leaves a `workstream-search` pointer instead of
+ pushing the entire response into an unread file (#1606).
+
- Corrected the startup error for a gap in SQLite migration history. A
skipped earlier migration is now reported as missing from the history,
instead of claiming the store is newer than the binary. The store still
refuses to open until its migration history can be reviewed (#1612).
-### Fixed
-
- Fixed the POSIX Docker wrapper routing host commands into the helper
container when `--config` or `--data-dir` preceded the command. Managed
launches, MCP bridges and lifecycle hooks now retain their native host
route and complete argument list with either global-option syntax (#1602).
-### Fixed
-
- Fixed native transcript imports dropping a whole session when one JSONL
record exceeded the 1 MiB per-record cap, as a Claude Code screenshot in a
tool result does: `ai-memory backfill` imported nothing from the session,
@@ -43,10 +56,6 @@ version in [`docs/changelog/`](docs/changelog/):
many records they skipped on stderr, `backfill` also under `--quiet`
(#1613).
-## [3.2.1] - 2026-10-22
-
-### Fixed
-
- The `user grants` and `project grants` tables now measure terminal display
cells, so accented and double-width CJK workspace, project and user names
keep the `USERNAME` and `LEVEL` columns aligned.
@@ -150,18 +159,6 @@ version in [`docs/changelog/`](docs/changelog/):
The line now ends in `…` inside the same 240 bytes, and
`docs/cross-project-profile.md` states the limit next to `summary`.
(#1608)
-- Fixed a 3.2.0 regression that serialized local document embedding and
- dropped the vector stream from queries that raced a document embed: the
- local embedder's capacity was hardcoded to two slots (one document, one
- query), and a query finding both busy degraded instantly to lexical
- search. The scheduler is now sized from the CPU (half the available
- parallelism, clamped to between 2 and 6 slots, documents capped at
- capacity minus one so a slot stays query-reserved), and a query waits up
- to 250 ms for a slot before degrading. On the affected LongMemEval-S
- question set this restores query latency (p50/p95 66/87 ms vs 3.2.0's
- 118/295) and ingest throughput; the reported hit@5 delta (0.947 → 0.938)
- traces to rank-boundary questions that flip between identical runs, not
- a deterministic ranking change (#1580).
- `install-mcp --client freebuff --apply --auth-token` now stores the key in
`<data_dir>/auth-token`, where the hooks keep theirs, and writes the FreeBuff
entry with `--data-dir` and no token, as it already did for the Claude Code
@@ -183,60 +180,6 @@ version in [`docs/changelog/`](docs/changelog/):
apply path's own `toml_edit` writer; output for an ordinary name is
unchanged.
([#1594](https://github.com/akitaonrails/ai-memory/pull/1594))
-
-- Fixed `ai-memory run` (and `show`, `continue`, `resume`, `workstreams`,
- `rename-workstream`) failing on Windows Docker installs with "managed
- claude executable `claude` was not found in the host PATH": the PowerShell
- wrapper sent every subcommand into the Linux helper container, which has no
- host CLIs. It now intercepts the same six commands `bin/ai-memory` does and
- runs them through the native Windows client, resolved from
- `AI_MEMORY_NATIVE_BIN` or the documented
- `%LOCALAPPDATA%\Programs\ai-memory` install location, inheriting
- `AI_MEMORY_SERVER_URL` (an explicit value wins) and exiting with the
- child's code. A missing client fails with the documented installer command
- instead of entering the container; the POSIX wrapper's Git Bash refusal
- points at the same installer; and the missing-harness error's Docker
- advice is now OS-aware: on Windows it names the native-client installer
- rather than `ai-memory upgrade`, which in the `.ps1` wrapper only pulls
- the image. Managed launches keep the hook/MCP wiring rendered through the
- container (the wrapper sets `AI_MEMORY_RUN_AUTOWIRE=false` for the
- intercepted commands unless the operator set it). (#1545)
-
-- Corrected four statements in `SECURITY.md` that no longer matched the
- code, plus two clarifications in the same sections (#1561). The
- `AI_MEMORY_ALLOWED_HOSTS` default is `localhost`, `127.0.0.1`, and `::1`;
- request bodies are capped at 10 MB on `/mcp`, `/hook` and `/workstream/*`,
- 32 MB on `/admin/*`, and 2 MB elsewhere; the auth ladder is anonymous,
- root bearer, proxy-asserted user, and `aim_` database-user tokens (the
- server itself never validates OIDC tokens, and the doc no longer says it
- does); and the "no per-user or per-project ACLs" claim became the current
- truth about per-project access modes and grants, including that
- proxy-asserted identities are not subject to them. The bearer-check note
- now lists the routes that are public by design (`/healthz`, `/auth/login`,
- `/auth/recovery`, `/favicon.ico`, custom `/web` static assets).
-- Completed the egress inventory in `DATA_HANDLING.md` and documented the
- default first-start behavior it omitted (#1560). A default install now
- says plainly that the local embedder downloads its three model files
- (~87 MB, sha256-pinned) from `huggingface.co` in the background on first
- start, that nothing stored is sent, and how to avoid it
- (`embedding_provider = "none"` or offline pre-seeding). The export table
- gained the rows it was missing: the `llm_provider` pipeline (including
- the `codex`, `copilot` and `cursor` CLI-backed providers), the `copilot`
- embedding provider, and `[[admission_webhooks]]`, plus notes on
- `ai-memory upgrade`'s GitHub release query, the OAuth/OIDC login flows,
- and remote `server_url` topologies. `docs/airgapped-install.md`'s
- runtime summary was corrected to match.
-
-### Security
-- A malformed OAuth entry in `auth.json` no longer prints the stored value in
- its error. When a field held a value of the wrong type, such as a token
- written into `expires` by a hand edit or a provisioning script, the parse
- error quoted the token, and from there it reached terminals, CI logs and
- captured hook output. The error now names the type it found with the value
- replaced by `<redacted>`.
- ([#1565](https://github.com/akitaonrails/ai-memory/pull/1565))
-
-### Fixed
- Every command except `hook` and `mcp-bridge` now warns, naming the variable
but not its value, when `HTTPS_PROXY`, `HTTP_PROXY` or `ALL_PROXY` (or a
lower-case spelling) is set to something the HTTP client cannot use: bytes
@@ -246,49 +189,328 @@ version in [`docs/changelog/`](docs/changelog/):
time out on a network that blocks direct egress, or bypass a required proxy
where it does not, with nothing pointing at the proxy setting.
([#1565](https://github.com/akitaonrails/ai-memory/pull/1565))
-- `init`, `auth` and `auth enable` print paths on Windows without the `\\?\`
+- `init`, `auth` and `auth enable` print paths on Windows without the `\?# Changelog
+
+All notable changes to this project will be documented in this file.
+
+The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+
+This file holds the current major line. Earlier lines are archived per major
+version in [`docs/changelog/`](docs/changelog/):
+[2.x](docs/changelog/2.x.md), [1.x](docs/changelog/1.x.md) and [0.x](docs/changelog/0.x.md).
+
verbatim prefix of the canonical data dir, in their output and their errors,
as the hook and service commands already did, and so does the
`ai-memory starting` line every command logs. A path copied from those
messages now works in `cmd` and in scripts that look for it.
([#1565](https://github.com/akitaonrails/ai-memory/pull/1565))
-### Fixed
-
- Corrected the Docker rollback instructions to retag the prior digest and recreate the service without pulling the newer tag. ([#1585](https://github.com/akitaonrails/ai-memory/pull/1585))
-### Fixed
-
- Corrected Docker backup instructions to use an online server snapshot or stop the container before copying its data. ([#1586](https://github.com/akitaonrails/ai-memory/pull/1586))
-### Fixed
-
- Corrected the multi-user migration command to pass the pepper length with `--bytes`. ([#1587](https://github.com/akitaonrails/ai-memory/pull/1587))
+- Corrected the API smoke test to use the running server’s configured bearer instead of a newly generated token. ([#1588](https://github.com/akitaonrails/ai-memory/pull/1588))
+- Fixed restoring a page from a checkpoint leaving a pre-OKF file on disk.
+ `restore-page` wrote the checkpointed bytes verbatim while the three
+ sibling write paths conform theirs, and the row it indexes is conformed at
+ the store's write choke point either way — so only the file was left
+ behind. Restoring the pre-OKF checkpoint every migrated install carries
+ then broke `export-okf` for the whole project with "run the server once to
+ migrate", which the one-shot wiki migration never does again, and made
+ every `serve` boot re-archive the data dir once the migration archive was
+ deleted. The restore now conforms the file like the siblings do;
+ conformance is idempotent modulo `generated.at`, which it inherits from the
+ file on disk, so an already-conformant page still restores byte-exact.
+ ([#1595](https://github.com/akitaonrails/ai-memory/pull/1595))
+- Fixed `memory_query` skipping its raw-observation fallback (`raw_hits`)
+ whenever an embedder was configured, which the default local embeddings
+ are. The vector stream has no similarity floor, so an unrelated page
+ kept `hits` non-empty, and an observation from a session with no page
+ yet (still open, or ended without SessionEnd) could not be found, while
+ the same store with `embedding_provider = "none"` returned it. The
+ fallback now runs unless a page matched the query's own terms through
+ page FTS, the entity stream or the observation stream; page ranking is
+ unchanged (#1600).
+
+- An empty structured answer from a Responses-API model is now reported as
+ empty content rather than a JSON parse error. The `opencode`, `openai-oauth`
+ and `codex` paths defaulted a missing `output_text` to an empty string and
+ handed it to the parser, so the operator saw `serde: EOF while parsing a
+ value at line 1 column 0`, naming neither the model nor the cause.
+ ([#1529](https://github.com/akitaonrails/ai-memory/pull/1529))
+- Detected `core.hooksPath` when a git config set it on the same physical
+ line as the `[core]` section header, so `ai-memory-wikisync install-hook`
+ no longer writes a `.git/hooks/post-merge` that git would never run.
+ ([#1530](https://github.com/akitaonrails/ai-memory/pull/1530))
+- Counted a file's final line in `ai-memory-wikisync` diff summaries when it
+ does not end in a newline, so the `bytes/lines` figures no longer contradict
+ the `first difference at line N` printed beside them.
+ ([#1531](https://github.com/akitaonrails/ai-memory/pull/1531))
+- `ai-memory run` now refuses an `--env`/`--env-file` entry whose key carries
+ whitespace. `--env-file` lines are trimmed as a whole, not per half, so the
+ common dotenv spelling `KEY = value` produced a key with a trailing space —
+ an entry no shell or harness can read, so the override silently did nothing.
+ ([#1532](https://github.com/akitaonrails/ai-memory/pull/1532))
+- Discovered a repository page whose `--include` family names a bare top-level
+ page (`README.md`), which `ai-memory-wikisync sync` previously left out of the
+ repository side entirely, so a newly created one was never imported.
+ ([#1533](https://github.com/akitaonrails/ai-memory/pull/1533))
+- A Copilot `/responses` answer stopped by `max_output_tokens` is now reported
+ as a truncated response naming the model and its output-token count, instead
+ of an unexpected response shape reading "no error detail" — `error` is null
+ on an incomplete answer, so nothing explained the stop and the class implied
+ an unparseable reply rather than a `max_tokens` to raise.
+ ([#1534](https://github.com/akitaonrails/ai-memory/pull/1534))
+- Omitted TTL-expired pages from the page count in `memory_briefing` and
+ `memory_explore`. Every page list in a briefing already hid them, and the
+ project cards have since 3.1.x, so a project with an expired page reported
+ more latest pages than any list in the same response could show. The
+ all-versions total is unchanged, as is `ai-memory status`.
+ ([#1535](https://github.com/akitaonrails/ai-memory/pull/1535))
+
+- `memory_read_page` now reads a blank `path` or `query` as omitted, as its
+ sibling arguments already do. An empty or whitespace-only `query` searched
+ for an empty FTS expression and reported the inevitable miss as an internal
+ error (-32603), which a looping client reads as "retry"; an empty `path`
+ failed as "invalid path: empty path" and never tried the `query` passed
+ beside it. Both now reach the instructive "exactly one of `path` or `query`"
+ refusal, and a blank `path` beside a real `query` runs the search.
+ ([#1536](https://github.com/akitaonrails/ai-memory/pull/1536))
+- Reported a wiki page renamed away with an external tool, which arrives as a
+ rename event rather than a removal, so the next auto-commit drops it from the
+ tree instead of leaving a checkpoint naming a page that no longer exists.
+ ([#1537](https://github.com/akitaonrails/ai-memory/pull/1537))
+- Omitted TTL-expired pages from the 7- and 30-day activity counters in
+ `memory_briefing`. A page written with a short TTL made a project look
+ active while the brief's own recent-page list was empty, which is the
+ signal an agent uses to decide how much context to pull. Session and
+ observation counters have no TTL and are unchanged.
+ ([#1539](https://github.com/akitaonrails/ai-memory/pull/1539))
+
+- Kept literal `<mark>` tags from a page's own text out of search-result
+ markup, including balanced pairs that previously looked identical to SQLite
+ highlights. FTS now uses internal delimiters that sanitized page content
+ cannot forge, and only presentation boundaries turn them into HTML.
+ ([#1540](https://github.com/akitaonrails/ai-memory/pull/1540))
+- `install.ps1` now refuses a plain-http GitHub release base. The scheme check
+ sat inside a condition whose arms already implied https, so it could never
+ fire, and an `http://github.com/...` base matched neither arm and skipped it
+ entirely — while the archive and its checksum are fetched from that same
+ origin, so the checksum proved nothing against an on-path rewrite.
+ ([#1541](https://github.com/akitaonrails/ai-memory/pull/1541))
+- An unspaced-CJK search carrying `AND`, `NOT` or `NEAR` no longer returns the
+ pages the operator excluded. The auxiliary CJK stream discarded every boolean
+ operator and `OR`-joined the CJK runs it found, and because that stream is
+ unioned into the primary one, `東京 NOT 大阪` fused the 大阪-only pages back in
+ and ranked them as if they had been asked for. The stream now declines such a
+ query, so unspaced-CJK recall narrows to the pre-feature answer for it instead
+ of inverting; `OR` queries are unaffected.
+ ([#1542](https://github.com/akitaonrails/ai-memory/pull/1542))
+- An `openai-oauth` answer the Codex backend stopped at its output-token
+ budget is now a terminal truncation instead of a retryable `502`. The
+ streaming parser read `response.incomplete` as a provider fault, so the
+ fallback chain advanced to the next candidate and opened a circuit, and the
+ SessionEnd consolidation job kept re-sending the same prompt on its backoff
+ schedule, each attempt truncating again at the same budget.
+ ([#1543](https://github.com/akitaonrails/ai-memory/pull/1543))
+
+- `memory_read_page` now answers a missing read target with `invalid params`
+ (-32602) instead of an internal error (-32603). A page absent under the
+ resolved scope, and a query that matched nothing, are caller-fixable: the
+ store answered, there is simply nothing there, and a client reads -32603 as
+ "retry". `memory_status` and `memory_read_session_observations` already
+ answer -32602 for an unknown project or session. The messages and the
+ auto-resolved-scope hint are unchanged, and a genuine disk or store failure
+ on the same path still answers -32603.
+ ([#1544](https://github.com/akitaonrails/ai-memory/pull/1544))
+- An OpenCode subagent session's end no longer hands the next session a
+ sub-task baton. The generated plugin forwarded the session's `parentID` as
+ the `agent_id` subagent marker on `session.created` but not on
+ `session.deleted`, so the `session-end` request carried no marker, the
+ router did not recognize a child session, and it published a summary page
+ and an open handoff that the next root session in that checkout consumed.
+ ([#1546](https://github.com/akitaonrails/ai-memory/pull/1546))
+- `install-mcp --client opencode --flavor <dialect>` now writes the flavored
+ URL into the OpenCode entry. Both OpenCode entry builders read the server
+ URL directly instead of the flavored one, so the flag was silently dropped
+ for a client its own documentation names: a Vertex-routed install got a bare
+ URL and 400'd every `tools/list`. OpenCode installs that do not pass
+ `--flavor` are unchanged.
+ ([#1547](https://github.com/akitaonrails/ai-memory/pull/1547))
+
+- A `title:` or `body:` filter on an unspaced-CJK search now narrows the
+ auxiliary CJK stream too. The stream read `:` as a plain run separator and
+ dropped the qualifier, so its MATCH searched every indexed column including
+ the path, and because that stream is unioned into the primary one,
+ `title:支付服务` returned pages holding the term only in their body or path.
+ ([#1548](https://github.com/akitaonrails/ai-memory/pull/1548))
+- An Anthropic structured answer the model stopped at `max_tokens` is now a
+ terminal truncation instead of a successful result. The provider did not read
+ `stop_reason`, so a `tool_use` block holding only the JSON produced before the
+ budget ran out was returned as a complete answer: a consolidation or bootstrap
+ chunk could write a fraction of its pages and report success. On models that
+ reject a forced `tool_choice` the same stop reported "no tool_use block"
+ instead. Non-structured completions are unchanged — prose cut at the budget is
+ still returned.
+ ([#1549](https://github.com/akitaonrails/ai-memory/pull/1549))
+- Counted a page needing only an L0 abstract embedding in `ai-memory embed
+ --dry-run` and `/admin/embed`. A page whose body vector was already current
+ appeared in neither the would-embed nor the up-to-date total, so the dry run
+ reported no work for a scope where a live run writes abstract embeddings.
+ ([#1550](https://github.com/akitaonrails/ai-memory/pull/1550))
+
+- The PowerShell `session-start` hooks for Claude Code, Command Code and Devin
+ now wrap the handoff in the same `hookSpecificOutput` envelope their POSIX
+ peers emit. On Windows the baton was written as bare text, so the harness
+ logged "Hook output does not start with {, treating as plain text" on every
+ start and the handoff arrived unstructured instead of as `additionalContext`.
+ ([#1551](https://github.com/akitaonrails/ai-memory/pull/1551))
+- The Japanese iteration mark 々 (and the other letters of CJK Symbols and
+ Punctuation) now stay inside a CJK run. They terminated one, so a word like
+ 日々 was indexed as two single characters and searching it emitted a bare
+ `"日"` that matched every page containing 日 while 日々 itself was unfindable
+ as a unit. Indexing changes with this, so existing rows keep their old terms
+ until they are rewritten or the index is rebuilt by a compaction.
+ ([#1552](https://github.com/akitaonrails/ai-memory/pull/1552))
+- `memory_write_page` now refuses a relation target whose `project:` or
+ `workspace/project:` scope holds a character the link reader cannot parse,
+ such as a space in `my project:notes/x`. The write boundary used a looser
+ character class than the reader, so the colon stayed inside the page path on
+ read and the write created an edge to a path no page write can ever produce —
+ a `links` row that could never be resolved.
+ ([#1553](https://github.com/akitaonrails/ai-memory/pull/1553))
+
+- `memory_handoff_cancel` now answers a well-formed `handoff_id` that resolves
+ to nothing in scope with `invalid params` (-32602) instead of an internal
+ error (-32603). The lookup succeeded and found no row, so the id is the
+ caller's to fix, and a client reads -32603 as "retry". The same function
+ already answered a malformed id with -32602, and `memory_handoff_accept`
+ reports an unknown id as `{"handoff": null}`. The message is unchanged and
+ still identical for an absent id and for another operator's, so cancelling
+ reveals no more than before.
+ ([#1554](https://github.com/akitaonrails/ai-memory/pull/1554))
+- `ai-memory run` no longer loses a native session selector that sits behind a
+ non-UTF-8 argument. The scan over the forwarded arguments ended at the first
+ argument that was not valid UTF-8 instead of skipping it, so a run pinned with
+ an explicit `--session`/`--resume` kept no expected session id and fell back
+ to post-exit transcript discovery.
+ ([#1555](https://github.com/akitaonrails/ai-memory/pull/1555))
+- Dropped the merged-away page's `summary:` and `abstract:` from the merge
+ stub left behind by cold-cluster dedup and the dream pass. Retrieval
+ prefers a frontmatter summary over the body, so the brief and the
+ non-keyword hit lists described the stub as if it still held content that
+ had moved to the survivor. The pre-merge frontmatter stays reachable
+ through the supersession chain; compaction is unchanged.
+ ([#1556](https://github.com/akitaonrails/ai-memory/pull/1556))
+
+- The OKF migration now conforms a page nested under a project bundle whose
+ file is named `index.md`. Only the bundle root's own `index.md` is reserved,
+ but the skip matched on the basename at any depth, so the database row was
+ conformed while its file kept pre-OKF frontmatter — and markdown being the
+ source of truth, the next reindex de-conformed the page again.
+ ([#1557](https://github.com/akitaonrails/ai-memory/pull/1557))
+- A root Grok session no longer loses its handoff because a tool used one of
+ the subagent marker key names. The shell `post-tool-use` hook matched
+ `agent_id` and its siblings as substrings of the whole raw payload, so a key
+ of that name nested in `tool_input` or in a structured tool result, or a
+ blank top-level value, suppressed the fetch. The gate now reads top-level
+ keys with a non-empty string value, like the native router and the
+ PowerShell bundle already did.
+ ([#1558](https://github.com/akitaonrails/ai-memory/pull/1558))
+- `ai-memory list-projects` now sizes its columns by terminal display width
+ rather than bytes. Accented names no longer add phantom padding, and
+ double-width CJK project or workspace names no longer shift later columns.
+ ([#1559](https://github.com/akitaonrails/ai-memory/pull/1559))
+
+- A byte size just under a unit boundary now carries to the next unit instead
+ of printing a magnitude that unit cannot hold. The scaling loop stopped at
+ `value < 1024.0` while the result is rendered with one decimal, so a
+ database of 1 MiB minus six bytes made `ai-memory status` report
+ `1024.0 KiB on disk` rather than `1.0 MiB`; `reclaim-ledger-versions` could
+ likewise print `1024.0 KiB -> 1.0 MiB` for a six-byte difference.
+ ([#1562](https://github.com/akitaonrails/ai-memory/pull/1562))
+
+- A popped message can no longer pass its own text off as `ai-memory`'s. The
+ human rendering of `message pop` printed the sender's subject above the
+ security notice and the body between two literal fence lines, neither
+ escaped, so a newline in the subject forged lines in the provenance block
+ and an `---- end of body ----` line in the body closed the fence early. The
+ subject now renders on one line, body fence markers are neutralized, and
+ terminal control sequences are stripped; both JSON paths remain structural.
+ ([#1563](https://github.com/akitaonrails/ai-memory/pull/1563))
+
+### Security
+
+- A malformed OAuth entry in `auth.json` no longer prints the stored value in
+ its error. When a field held a value of the wrong type, such as a token
+ written into `expires` by a hand edit or a provisioning script, the parse
+ error quoted the token, and from there it reached terminals, CI logs and
+ captured hook output. The error now names the type it found with the value
+ replaced by `<redacted>`.
+ ([#1565](https://github.com/akitaonrails/ai-memory/pull/1565))
+
+## [3.2.1] - 2026-10-22
+
### Fixed
-- Corrected the API smoke test to use the running server’s configured bearer instead of a newly generated token. ([#1588](https://github.com/akitaonrails/ai-memory/pull/1588))
-- Fixed restoring a page from a checkpoint leaving a pre-OKF file on disk.
- `restore-page` wrote the checkpointed bytes verbatim while the three
- sibling write paths conform theirs, and the row it indexes is conformed at
- the store's write choke point either way — so only the file was left
- behind. Restoring the pre-OKF checkpoint every migrated install carries
- then broke `export-okf` for the whole project with "run the server once to
- migrate", which the one-shot wiki migration never does again, and made
- every `serve` boot re-archive the data dir once the migration archive was
- deleted. The restore now conforms the file like the siblings do;
- conformance is idempotent modulo `generated.at`, which it inherits from the
- file on disk, so an already-conformant page still restores byte-exact.
- ([#1595](https://github.com/akitaonrails/ai-memory/pull/1595))
-- Fixed `memory_query` skipping its raw-observation fallback (`raw_hits`)
- whenever an embedder was configured, which the default local embeddings
- are. The vector stream has no similarity floor, so an unrelated page
- kept `hits` non-empty, and an observation from a session with no page
- yet (still open, or ended without SessionEnd) could not be found, while
- the same store with `embedding_provider = "none"` returned it. The
- fallback now runs unless a page matched the query's own terms through
- page FTS, the entity stream or the observation stream; page ranking is
- unchanged (#1600).
+- Fixed a 3.2.0 regression that serialized local document embedding and
+ dropped the vector stream from queries that raced a document embed: the
+ local embedder's capacity was hardcoded to two slots (one document, one
+ query), and a query finding both busy degraded instantly to lexical
+ search. The scheduler is now sized from the CPU (half the available
+ parallelism, clamped to between 2 and 6 slots, documents capped at
+ capacity minus one so a slot stays query-reserved), and a query waits up
+ to 250 ms for a slot before degrading. On the affected LongMemEval-S
+ question set this restores query latency (p50/p95 66/87 ms vs 3.2.0's
+ 118/295) and ingest throughput; the reported hit@5 delta (0.947 → 0.938)
+ traces to rank-boundary questions that flip between identical runs, not
+ a deterministic ranking change (#1580).
+
+- Fixed `ai-memory run` (and `show`, `continue`, `resume`, `workstreams`,
+ `rename-workstream`) failing on Windows Docker installs with "managed
+ claude executable `claude` was not found in the host PATH": the PowerShell
+ wrapper sent every subcommand into the Linux helper container, which has no
+ host CLIs. It now intercepts the same six commands `bin/ai-memory` does and
+ runs them through the native Windows client, resolved from
+ `AI_MEMORY_NATIVE_BIN` or the documented
+ `%LOCALAPPDATA%\Programs\ai-memory` install location, inheriting
+ `AI_MEMORY_SERVER_URL` (an explicit value wins) and exiting with the
+ child's code. A missing client fails with the documented installer command
+ instead of entering the container; the POSIX wrapper's Git Bash refusal
+ points at the same installer; and the missing-harness error's Docker
+ advice is now OS-aware: on Windows it names the native-client installer
+ rather than `ai-memory upgrade`, which in the `.ps1` wrapper only pulls
+ the image. Managed launches keep the hook/MCP wiring rendered through the
+ container (the wrapper sets `AI_MEMORY_RUN_AUTOWIRE=false` for the
+ intercepted commands unless the operator set it). (#1545)
+
+- Corrected four statements in `SECURITY.md` that no longer matched the
+ code, plus two clarifications in the same sections (#1561). The
+ `AI_MEMORY_ALLOWED_HOSTS` default is `localhost`, `127.0.0.1`, and `::1`;
+ request bodies are capped at 10 MB on `/mcp`, `/hook` and `/workstream/*`,
+ 32 MB on `/admin/*`, and 2 MB elsewhere; the auth ladder is anonymous,
+ root bearer, proxy-asserted user, and `aim_` database-user tokens (the
+ server itself never validates OIDC tokens, and the doc no longer says it
+ does); and the "no per-user or per-project ACLs" claim became the current
+ truth about per-project access modes and grants, including that
+ proxy-asserted identities are not subject to them. The bearer-check note
+ now lists the routes that are public by design (`/healthz`, `/auth/login`,
+ `/auth/recovery`, `/favicon.ico`, custom `/web` static assets).
+- Completed the egress inventory in `DATA_HANDLING.md` and documented the
+ default first-start behavior it omitted (#1560). A default install now
+ says plainly that the local embedder downloads its three model files
+ (~87 MB, sha256-pinned) from `huggingface.co` in the background on first
+ start, that nothing stored is sent, and how to avoid it
+ (`embedding_provider = "none"` or offline pre-seeding). The export table
+ gained the rows it was missing: the `llm_provider` pipeline (including
+ the `codex`, `copilot` and `cursor` CLI-backed providers), the `copilot`
+ embedding provider, and `[[admission_webhooks]]`, plus notes on
+ `ai-memory upgrade`'s GitHub release query, the OAuth/OIDC login flows,
+ and remote `server_url` topologies. `docs/airgapped-install.md`'s
+ runtime summary was corrected to match.
## [3.2.0] - 2026-10-21
@@ -504,212 +726,6 @@ version in [`docs/changelog/`](docs/changelog/):
relay and wiki sync companions take the same `rustls-webpki` bump.
### Fixed
-- An empty structured answer from a Responses-API model is now reported as
- empty content rather than a JSON parse error. The `opencode`, `openai-oauth`
- and `codex` paths defaulted a missing `output_text` to an empty string and
- handed it to the parser, so the operator saw `serde: EOF while parsing a
- value at line 1 column 0`, naming neither the model nor the cause.
- ([#1529](https://github.com/akitaonrails/ai-memory/pull/1529))
-- Detected `core.hooksPath` when a git config set it on the same physical
- line as the `[core]` section header, so `ai-memory-wikisync install-hook`
- no longer writes a `.git/hooks/post-merge` that git would never run.
- ([#1530](https://github.com/akitaonrails/ai-memory/pull/1530))
-- Counted a file's final line in `ai-memory-wikisync` diff summaries when it
- does not end in a newline, so the `bytes/lines` figures no longer contradict
- the `first difference at line N` printed beside them.
- ([#1531](https://github.com/akitaonrails/ai-memory/pull/1531))
-- `ai-memory run` now refuses an `--env`/`--env-file` entry whose key carries
- whitespace. `--env-file` lines are trimmed as a whole, not per half, so the
- common dotenv spelling `KEY = value` produced a key with a trailing space —
- an entry no shell or harness can read, so the override silently did nothing.
- ([#1532](https://github.com/akitaonrails/ai-memory/pull/1532))
-- Discovered a repository page whose `--include` family names a bare top-level
- page (`README.md`), which `ai-memory-wikisync sync` previously left out of the
- repository side entirely, so a newly created one was never imported.
- ([#1533](https://github.com/akitaonrails/ai-memory/pull/1533))
-- A Copilot `/responses` answer stopped by `max_output_tokens` is now reported
- as a truncated response naming the model and its output-token count, instead
- of an unexpected response shape reading "no error detail" — `error` is null
- on an incomplete answer, so nothing explained the stop and the class implied
- an unparseable reply rather than a `max_tokens` to raise.
- ([#1534](https://github.com/akitaonrails/ai-memory/pull/1534))
-- Omitted TTL-expired pages from the page count in `memory_briefing` and
- `memory_explore`. Every page list in a briefing already hid them, and the
- project cards have since 3.1.x, so a project with an expired page reported
- more latest pages than any list in the same response could show. The
- all-versions total is unchanged, as is `ai-memory status`.
- ([#1535](https://github.com/akitaonrails/ai-memory/pull/1535))
-
-
-- `memory_read_page` now reads a blank `path` or `query` as omitted, as its
- sibling arguments already do. An empty or whitespace-only `query` searched
- for an empty FTS expression and reported the inevitable miss as an internal
- error (-32603), which a looping client reads as "retry"; an empty `path`
- failed as "invalid path: empty path" and never tried the `query` passed
- beside it. Both now reach the instructive "exactly one of `path` or `query`"
- refusal, and a blank `path` beside a real `query` runs the search.
- ([#1536](https://github.com/akitaonrails/ai-memory/pull/1536))
-- Reported a wiki page renamed away with an external tool, which arrives as a
- rename event rather than a removal, so the next auto-commit drops it from the
- tree instead of leaving a checkpoint naming a page that no longer exists.
- ([#1537](https://github.com/akitaonrails/ai-memory/pull/1537))
-- Omitted TTL-expired pages from the 7- and 30-day activity counters in
- `memory_briefing`. A page written with a short TTL made a project look
- active while the brief's own recent-page list was empty, which is the
- signal an agent uses to decide how much context to pull. Session and
- observation counters have no TTL and are unchanged.
- ([#1539](https://github.com/akitaonrails/ai-memory/pull/1539))
-
-- Kept a literal `<mark>` tag from a page's own text out of a search snippet's
- markup, so it no longer renders as an unbalanced opening tag that highlights
- the rest of the excerpt as if it were a query match.
- ([#1540](https://github.com/akitaonrails/ai-memory/pull/1540))
-- `install.ps1` now refuses a plain-http GitHub release base. The scheme check
- sat inside a condition whose arms already implied https, so it could never
- fire, and an `http://github.com/...` base matched neither arm and skipped it
- entirely — while the archive and its checksum are fetched from that same
- origin, so the checksum proved nothing against an on-path rewrite.
- ([#1541](https://github.com/akitaonrails/ai-memory/pull/1541))
-- An unspaced-CJK search carrying `AND`, `NOT` or `NEAR` no longer returns the
- pages the operator excluded. The auxiliary CJK stream discarded every boolean
- operator and `OR`-joined the CJK runs it found, and because that stream is
- unioned into the primary one, `東京 NOT 大阪` fused the 大阪-only pages back in
- and ranked them as if they had been asked for. The stream now declines such a
- query, so unspaced-CJK recall narrows to the pre-feature answer for it instead
- of inverting; `OR` queries are unaffected.
- ([#1542](https://github.com/akitaonrails/ai-memory/pull/1542))
-- An `openai-oauth` answer the Codex backend stopped at its output-token
- budget is now a terminal truncation instead of a retryable `502`. The
- streaming parser read `response.incomplete` as a provider fault, so the
- fallback chain advanced to the next candidate and opened a circuit, and the
- SessionEnd consolidation job kept re-sending the same prompt on its backoff
- schedule, each attempt truncating again at the same budget.
- ([#1543](https://github.com/akitaonrails/ai-memory/pull/1543))
-
-- `memory_read_page` now answers a missing read target with `invalid params`
- (-32602) instead of an internal error (-32603). A page absent under the
- resolved scope, and a query that matched nothing, are caller-fixable: the
- store answered, there is simply nothing there, and a client reads -32603 as
- "retry". `memory_status` and `memory_read_session_observations` already
- answer -32602 for an unknown project or session. The messages and the
- auto-resolved-scope hint are unchanged, and a genuine disk or store failure
- on the same path still answers -32603.
- ([#1544](https://github.com/akitaonrails/ai-memory/pull/1544))
-- An OpenCode subagent session's end no longer hands the next session a
- sub-task baton. The generated plugin forwarded the session's `parentID` as
- the `agent_id` subagent marker on `session.created` but not on
- `session.deleted`, so the `session-end` request carried no marker, the
- router did not recognize a child session, and it published a summary page
- and an open handoff that the next root session in that checkout consumed.
- ([#1546](https://github.com/akitaonrails/ai-memory/pull/1546))
-- `install-mcp --client opencode --flavor <dialect>` now writes the flavored
- URL into the OpenCode entry. Both OpenCode entry builders read the server
- URL directly instead of the flavored one, so the flag was silently dropped
- for a client its own documentation names: a Vertex-routed install got a bare
- URL and 400'd every `tools/list`. OpenCode installs that do not pass
- `--flavor` are unchanged.
- ([#1547](https://github.com/akitaonrails/ai-memory/pull/1547))
-
-- A `title:` or `body:` filter on an unspaced-CJK search now narrows the
- auxiliary CJK stream too. The stream read `:` as a plain run separator and
- dropped the qualifier, so its MATCH searched every indexed column including
- the path, and because that stream is unioned into the primary one,
- `title:支付服务` returned pages holding the term only in their body or path.
- ([#1548](https://github.com/akitaonrails/ai-memory/pull/1548))
-- An Anthropic structured answer the model stopped at `max_tokens` is now a
- terminal truncation instead of a successful result. The provider did not read
- `stop_reason`, so a `tool_use` block holding only the JSON produced before the
- budget ran out was returned as a complete answer: a consolidation or bootstrap
- chunk could write a fraction of its pages and report success. On models that
- reject a forced `tool_choice` the same stop reported "no tool_use block"
- instead. Non-structured completions are unchanged — prose cut at the budget is
- still returned.
- ([#1549](https://github.com/akitaonrails/ai-memory/pull/1549))
-- Counted a page needing only an L0 abstract embedding in `ai-memory embed
- --dry-run` and `/admin/embed`. A page whose body vector was already current
- appeared in neither the would-embed nor the up-to-date total, so the dry run
- reported no work for a scope where a live run writes abstract embeddings.
- ([#1550](https://github.com/akitaonrails/ai-memory/pull/1550))
-
-- The PowerShell `session-start` hooks for Claude Code, Command Code and Devin
- now wrap the handoff in the same `hookSpecificOutput` envelope their POSIX
- peers emit. On Windows the baton was written as bare text, so the harness
- logged "Hook output does not start with {, treating as plain text" on every
- start and the handoff arrived unstructured instead of as `additionalContext`.
- ([#1551](https://github.com/akitaonrails/ai-memory/pull/1551))
-- The Japanese iteration mark 々 (and the other letters of CJK Symbols and
- Punctuation) now stay inside a CJK run. They terminated one, so a word like
- 日々 was indexed as two single characters and searching it emitted a bare
- `"日"` that matched every page containing 日 while 日々 itself was unfindable
- as a unit. Indexing changes with this, so existing rows keep their old terms
- until they are rewritten or the index is rebuilt by a compaction.
- ([#1552](https://github.com/akitaonrails/ai-memory/pull/1552))
-- `memory_write_page` now refuses a relation target whose `project:` or
- `workspace/project:` scope holds a character the link reader cannot parse,
- such as a space in `my project:notes/x`. The write boundary used a looser
- character class than the reader, so the colon stayed inside the page path on
- read and the write created an edge to a path no page write can ever produce —
- a `links` row that could never be resolved.
- ([#1553](https://github.com/akitaonrails/ai-memory/pull/1553))
-
-- `memory_handoff_cancel` now answers a well-formed `handoff_id` that resolves
- to nothing in scope with `invalid params` (-32602) instead of an internal
- error (-32603). The lookup succeeded and found no row, so the id is the
- caller's to fix, and a client reads -32603 as "retry". The same function
- already answered a malformed id with -32602, and `memory_handoff_accept`
- reports an unknown id as `{"handoff": null}`. The message is unchanged and
- still identical for an absent id and for another operator's, so cancelling
- reveals no more than before.
- ([#1554](https://github.com/akitaonrails/ai-memory/pull/1554))
-- `ai-memory run` no longer loses a native session selector that sits behind a
- non-UTF-8 argument. The scan over the forwarded arguments ended at the first
- argument that was not valid UTF-8 instead of skipping it, so a run pinned with
- an explicit `--session`/`--resume` kept no expected session id and fell back
- to post-exit transcript discovery.
- ([#1555](https://github.com/akitaonrails/ai-memory/pull/1555))
-- Dropped the merged-away page's `summary:` and `abstract:` from the merge
- stub left behind by cold-cluster dedup and the dream pass. Retrieval
- prefers a frontmatter summary over the body, so the brief and the
- non-keyword hit lists described the stub as if it still held content that
- had moved to the survivor. The pre-merge frontmatter stays reachable
- through the supersession chain; compaction is unchanged.
- ([#1556](https://github.com/akitaonrails/ai-memory/pull/1556))
-
-- The OKF migration now conforms a page nested under a project bundle whose
- file is named `index.md`. Only the bundle root's own `index.md` is reserved,
- but the skip matched on the basename at any depth, so the database row was
- conformed while its file kept pre-OKF frontmatter — and markdown being the
- source of truth, the next reindex de-conformed the page again.
- ([#1557](https://github.com/akitaonrails/ai-memory/pull/1557))
-- A root Grok session no longer loses its handoff because a tool used one of
- the subagent marker key names. The shell `post-tool-use` hook matched
- `agent_id` and its siblings as substrings of the whole raw payload, so a key
- of that name nested in `tool_input` or in a structured tool result, or a
- blank top-level value, suppressed the fetch. The gate now reads top-level
- keys with a non-empty string value, like the native router and the
- PowerShell bundle already did.
- ([#1558](https://github.com/akitaonrails/ai-memory/pull/1558))
-- `ai-memory list-projects` now sizes its columns by terminal display width
- rather than bytes. Accented names no longer add phantom padding, and
- double-width CJK project or workspace names no longer shift later columns.
- ([#1559](https://github.com/akitaonrails/ai-memory/pull/1559))
-
-- A byte size just under a unit boundary now carries to the next unit instead
- of printing a magnitude that unit cannot hold. The scaling loop stopped at
- `value < 1024.0` while the result is rendered with one decimal, so a
- database of 1 MiB minus six bytes made `ai-memory status` report
- `1024.0 KiB on disk` rather than `1.0 MiB`; `reclaim-ledger-versions` could
- likewise print `1024.0 KiB -> 1.0 MiB` for a six-byte difference.
- ([#1562](https://github.com/akitaonrails/ai-memory/pull/1562))
-
-- A popped message can no longer pass its own text off as `ai-memory`'s. The
- human rendering of `message pop` printed the sender's subject above the
- security notice and the body between two literal fence lines, neither
- escaped, so a newline in the subject forged lines in the provenance block
- and an `---- end of body ----` line in the body closed the fence early. The
- subject now renders on one line, body fence markers are neutralized, and
- terminal control sequences are stripped; both JSON paths remain structural.
- ([#1563](https://github.com/akitaonrails/ai-memory/pull/1563))
- Memory health no longer counts a link from a superseded or TTL-expired page
version as a reference. A page whose only inbound link was removed by a later
edit was reported as linked, because the old version's `links` row survives
diff --git a/Cargo.lock b/Cargo.lock
index c78ebfd9..41c3be91 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -346,6 +346,7 @@ dependencies = [
"ai-memory-core",
"anyhow",
"jiff",
+ "libc",
"rusqlite",
"serde",
"serde_json",
diff --git a/bin/ai-memory.ps1 b/bin/ai-memory.ps1
index adb43e16..7250b977 100644
--- a/bin/ai-memory.ps1
+++ b/bin/ai-memory.ps1
@@ -105,8 +105,67 @@ function Get-NativeHostBin {
exit 127
}
+$VolumeTokenFile = if ($env:LOCALAPPDATA) {
+ Join-Path $env:LOCALAPPDATA "ai-memory\server-token"
+} else {
+ Join-Path $HOME ".local\share\ai-memory\server-token"
+}
+
+function Test-VolumeTokenApplies {
+ if (-not [string]::IsNullOrEmpty([Environment]::GetEnvironmentVariable("AI_MEMORY_AUTH_TOKEN")) -or
+ -not [string]::IsNullOrEmpty([Environment]::GetEnvironmentVariable("AI_MEMORY_AUTH__BEARER_TOKEN_FILE"))) {
+ return $false
+ }
+ return -not ($env:AI_MEMORY_DATA_DIR -and
+ (Test-Path -LiteralPath $env:AI_MEMORY_DATA_DIR -PathType Container))
+}
+
+function Use-VolumeToken {
+ if ((Test-VolumeTokenApplies) -and
+ (Test-Path -LiteralPath $VolumeTokenFile -PathType Leaf) -and
+ (Get-Item -LiteralPath $VolumeTokenFile).Length -gt 0) {
+ $env:AI_MEMORY_AUTH__BEARER_TOKEN_FILE = $VolumeTokenFile
+ }
+}
+
+# Refresh once during native hook setup. Managed launches stay independent of
+# the container engine and reuse this host copy, matching the POSIX wrapper.
+function Update-VolumeToken {
+ if (-not (Test-VolumeTokenApplies)) {
+ return
+ }
+ if (-not (Get-Command $Docker -ErrorAction SilentlyContinue)) {
+ Use-VolumeToken
+ return
+ }
+ $PreviousErrorAction = $ErrorActionPreference
+ $ErrorActionPreference = "SilentlyContinue"
+ try {
+ $Token = (& $Docker run --rm -v "${DataVolume}:/data:ro" --entrypoint /bin/sh $Image -c 'if grep -qs ''^[[:space:]]*bearer_token_file[[:space:]]*=[[:space:]]*"auth-tokens/default"'' /data/config.toml; then cat /data/auth-tokens/default 2>/dev/null; fi; exit 0' 2>$null)
+ $Succeeded = $LASTEXITCODE -eq 0
+ } finally {
+ $ErrorActionPreference = $PreviousErrorAction
+ }
+ if (-not $Succeeded) {
+ Use-VolumeToken
+ return
+ }
+ $Token = ([string]$Token).Trim()
+ if ([string]::IsNullOrEmpty($Token)) {
+ Remove-Item -LiteralPath $VolumeTokenFile -Force -ErrorAction SilentlyContinue
+ return
+ }
+ $TokenDir = Split-Path -Parent $VolumeTokenFile
+ New-Item -ItemType Directory -Force -Path $TokenDir | Out-Null
+ $Temporary = "$VolumeTokenFile.tmp.$PID"
+ [IO.File]::WriteAllText($Temporary, "$Token`n", [Text.UTF8Encoding]::new($false))
+ Move-Item -LiteralPath $Temporary -Destination $VolumeTokenFile -Force
+ Use-VolumeToken
+}
+
if ((Get-WrapperSubcommand $CommandArgs) -in $NativeHostCommands) {
$NativeBin = Get-NativeHostBin
+ Use-VolumeToken
# The intercepted commands run on the host, so AI_MEMORY_SERVER_URL is
# inherited untouched: the client's own default (http://127.0.0.1:49374)
# already reaches the port Docker Desktop publishes there; an explicit
@@ -126,6 +185,14 @@ if ((Get-WrapperSubcommand $CommandArgs) -in $NativeHostCommands) {
exit $LASTEXITCODE
}
+if ((Get-WrapperSubcommand $CommandArgs) -eq "install-hooks" -and
+ [string]::IsNullOrEmpty([Environment]::GetEnvironmentVariable("AI_MEMORY_HOOK_PLATFORM"))) {
+ $NativeBin = Get-NativeHostBin
+ Update-VolumeToken
+ & $NativeBin @CommandArgs
+ exit $LASTEXITCODE
+}
+
if (-not (Get-Command $Docker -ErrorAction SilentlyContinue)) {
Write-Error "Could not find Docker command '$Docker'. Install Docker Desktop or set AI_MEMORY_DOCKER."
exit 127
diff --git a/companions/ai-memory-wikisync/README.md b/companions/ai-memory-wikisync/README.md
index 99f9e1f0..a216ea45 100644
--- a/companions/ai-memory-wikisync/README.md
+++ b/companions/ai-memory-wikisync/README.md
@@ -57,8 +57,9 @@ ai-memory-wikisync sync ... --apply --propagate-deletes
the `git add` / `git commit` / `git push` commands you may run yourself.
The tool never runs git, never commits, and never pushes.
- `--include FAMILY` is a strict, explicit allowlist of top-level wiki
- directories (`_rules`, `decisions`, …). At least one is required and a
- bare `*` is refused: only what you name is exported.
+ families: a directory (`_rules`, `decisions`, …) or a top-level Markdown
+ page with that stem (`roadmap` selects `roadmap.md`). At least one is
+ required and a bare `*` is refused: only what you name is exported.
- Auth is a bearer token via `--token` or `AI_MEMORY_AUTH_TOKEN` (plus
`AI_MEMORY_SERVER_URL` for the server origin). Tokens are never logged
and never written to disk.
diff --git a/crates/ai-memory-cli/tests/suite/packaging.rs b/crates/ai-memory-cli/tests/suite/packaging.rs
index c0f605b1..98c6eafa 100644
--- a/crates/ai-memory-cli/tests/suite/packaging.rs
+++ b/crates/ai-memory-cli/tests/suite/packaging.rs
@@ -1450,6 +1450,8 @@ fn run_powershell_wrapper_with_fake_native(
">>\"%AI_MEMORY_TEST_NATIVE_ARGS%\" echo autowire: %AI_MEMORY_RUN_AUTOWIRE%\r\n",
"if not defined AI_MEMORY_RUN_AUTOWIRE ",
">>\"%AI_MEMORY_TEST_NATIVE_ARGS%\" echo autowire: unset\r\n",
+ "if defined AI_MEMORY_AUTH__BEARER_TOKEN_FILE ",
+ ">>\"%AI_MEMORY_TEST_NATIVE_ARGS%\" echo bearer-file: %AI_MEMORY_AUTH__BEARER_TOKEN_FILE%\r\n",
"exit /b %AI_MEMORY_TEST_NATIVE_EXIT%\r\n",
),
)
@@ -1457,7 +1459,12 @@ fn run_powershell_wrapper_with_fake_native(
let docker = tmp.path().join("docker.cmd");
std::fs::write(
&docker,
- "@echo off\r\n>>\"%AI_MEMORY_TEST_DOCKER_ARGS%\" echo %*\r\nexit /b 0\r\n",
+ concat!(
+ "@echo off\r\n",
+ ">>\"%AI_MEMORY_TEST_DOCKER_ARGS%\" echo %*\r\n",
+ "echo %* | findstr /c:\"auth-tokens/default\" >nul && echo test-volume-token\r\n",
+ "exit /b 0\r\n",
+ ),
)
.unwrap();
@@ -1480,6 +1487,7 @@ fn run_powershell_wrapper_with_fake_native(
.env("AI_MEMORY_TEST_NATIVE_EXIT", "7")
.env("AI_MEMORY_TEST_DOCKER_ARGS", &docker_args)
.env("AI_MEMORY_DATA_VOLUME", "test-ai-memory-data")
+ .env("LOCALAPPDATA", tmp.path())
.env_remove("AI_MEMORY_DATA_DIR")
.env_remove("AI_MEMORY_SERVER_URL")
.env_remove("AI_MEMORY_RUN_AUTOWIRE");
@@ -3644,6 +3652,28 @@ mod slow {
);
}
+ #[cfg(windows)]
+ #[test]
+ fn windows_install_hooks_refreshes_the_volume_bearer_for_managed_launches() {
+ let (code, native_log, docker_log) = run_powershell_wrapper_with_fake_native(
+ &["install-hooks", "--agent", "claude-code"],
+ &[],
+ );
+ assert_eq!(code, Some(7));
+ assert!(
+ native_log.contains("argv: install-hooks --agent claude-code"),
+ "native install must receive the original argv; got {native_log}"
+ );
+ assert!(
+ native_log.contains("bearer-file:"),
+ "native install must receive the refreshed bearer path; got {native_log}"
+ );
+ assert!(
+ docker_log.contains("auth-tokens/default"),
+ "setup must read the configured bearer from the named volume; got {docker_log}"
+ );
+ }
+
// Without the native client the wrapper must refuse clearly (pointing at
// the documented installer) instead of silently falling back to the
// helper container, where the command used to die with a misleading
diff --git a/crates/ai-memory-consolidate/tests/suite/recall_eval.rs b/crates/ai-memory-consolidate/tests/suite/recall_eval.rs
index c1c0ff3b..7d6d51e8 100644
--- a/crates/ai-memory-consolidate/tests/suite/recall_eval.rs
+++ b/crates/ai-memory-consolidate/tests/suite/recall_eval.rs
@@ -516,7 +516,10 @@ async fn raw_observation_fallback_recovers_detail_when_wiki_misses() {
.expect("raw search");
assert_eq!(raw_hits.len(), 1);
assert_eq!(raw_hits[0].session_id, session_id);
- assert!(raw_hits[0].snippet.contains("<mark>capybara</mark>"));
+ assert!(
+ ai_memory_store::highlighted_snippet_html(&raw_hits[0].snippet)
+ .contains("<mark>capybara</mark>")
+ );
}
/// Cross-project profile recall (`docs/cross-project-profile.md`): a habit the
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 76d76bb7..e73b56ea 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -1792,7 +1792,10 @@ async fn fetch_and_accept_handoff_at(
busy_since,
)
.await?;
- let handoff_md = handoff.as_ref().map(render_handoff_markdown);
+ let claude_capped = agent == AgentKind::ClaudeCode;
+ let handoff_md = handoff.as_ref().map(|handoff| {
+ render_handoff_markdown_with_budget(handoff, claude_capped.then_some(CLAUDE_HANDOFF_CHARS))
+ });
// The brief is additive and non-destructive: unlike the handoff (a
// single-use slot claimed below), it is recomposed on every opted-in
// session start — exactly what a Claude Code `/clear` needs (#176).
@@ -1816,9 +1819,16 @@ async fn fetch_and_accept_handoff_at(
}
};
let profile_flags = persist_profile_flags(state, &query, ws, proj, may_write_profile).await;
- let profile_md =
- render_requested_profile_digest(state, &query, ws, proj, viewer, profile_flags.consume)
- .await;
+ let profile_md = render_requested_profile_digest(
+ state,
+ &query,
+ ws,
+ proj,
+ viewer,
+ profile_flags.consume,
+ claude_capped.then_some(CLAUDE_PROFILE_CHARS),
+ )
+ .await;
// Handoff right after the profile digest: it is a short curated pointer
// and must not be buried under a ledger that can run tens of KB. The
// existing ledger-then-brief order is preserved. Claim both single-use inputs only after every
@@ -1998,21 +2008,15 @@ async fn fetch_and_accept_handoff_at(
// while everything after it changes every session, so leading with it
// keeps it in the reusable part of the harness's prompt cache (design:
// docs/design-cross-project-profile.md §3).
- Ok(combine_handoff_and_brief(
+ Ok(combine_startup_context(
+ agent,
profile_md,
- combine_handoff_and_brief(
- handoff_md,
- combine_handoff_and_brief(
- handoff_notice,
- combine_handoff_and_brief(
- continuity_notice,
- combine_handoff_and_brief(
- managed_md,
- combine_handoff_and_brief(brief_md, inbox_notice),
- ),
- ),
- ),
- ),
+ handoff_md,
+ handoff_notice,
+ continuity_notice,
+ managed_md,
+ brief_md,
+ inbox_notice,
))
}
@@ -2440,6 +2444,7 @@ async fn render_requested_profile_digest(
project_id: ProjectId,
viewer: Option<ai_memory_core::UserId>,
consume: bool,
+ budget_cap: Option<usize>,
) -> Option<String> {
if !state.profile.inject_on_session_start
|| !consume
@@ -2492,6 +2497,7 @@ async fn render_requested_profile_digest(
} else {
state.profile.digest_budget()
};
+ let budget = budget_cap.map_or(budget, |cap| budget.min(cap));
ai_memory_core::profile::render_digest(
&inputs.entries,
&inputs.project_tags,
@@ -2513,6 +2519,87 @@ fn combine_handoff_and_brief(
}
}
+const CLAUDE_ADDITIONAL_CONTEXT_CHARS: usize = 9_800;
+const CLAUDE_PROFILE_CHARS: usize = 2_400;
+const CLAUDE_HANDOFF_CHARS: usize = 4_800;
+
+#[allow(clippy::too_many_arguments)]
+fn combine_startup_context(
+ agent: AgentKind,
+ profile: Option<String>,
+ handoff: Option<String>,
+ handoff_notice: Option<String>,
+ continuity_notice: Option<String>,
+ managed: Option<String>,
+ brief: Option<String>,
+ inbox: Option<String>,
+) -> Option<String> {
+ if agent != AgentKind::ClaudeCode {
+ return combine_handoff_and_brief(
+ profile,
+ combine_handoff_and_brief(
+ handoff,
+ combine_handoff_and_brief(
+ handoff_notice,
+ combine_handoff_and_brief(
+ continuity_notice,
+ combine_handoff_and_brief(managed, combine_handoff_and_brief(brief, inbox)),
+ ),
+ ),
+ ),
+ );
+ }
+
+ // Mandatory signals are selected first but retain their normal display
+ // order. Optional ledger/brief material is admitted only when the whole
+ // response stays inline under Claude Code's fixed 10k hook ceiling.
+ let sections = [profile, handoff, handoff_notice, continuity_notice, inbox];
+ let mut selected = [false; 5];
+ let mut used = 0usize;
+ let mut selected_count = 0usize;
+ // Continue-work signals outrank the profile when an unusually large
+ // combination approaches Claude Code's fixed hook-response ceiling.
+ for index in [1, 2, 3, 4, 0] {
+ if let Some(section) = sections[index].as_ref() {
+ let separator = usize::from(selected_count > 0);
+ if used + separator + section.chars().count() <= CLAUDE_ADDITIONAL_CONTEXT_CHARS {
+ used += separator + section.chars().count();
+ selected[index] = true;
+ selected_count += 1;
+ }
+ }
+ }
+ let mut kept = sections
+ .into_iter()
+ .enumerate()
+ .filter_map(|(index, section)| selected[index].then_some(section).flatten())
+ .collect::<Vec<_>>();
+ for (section, omission_notice) in [
+ (
+ managed,
+ Some(
+ "ai-memory: additional managed-workstream history did not fit Claude Code's inline startup limit. Search the complete visible ledger with `ai-memory workstream-search \"<query>\"`; this managed process already carries the workstream id.",
+ ),
+ ),
+ (brief, None),
+ ] {
+ if let Some(section) = section {
+ let separator = usize::from(!kept.is_empty());
+ if used + separator + section.chars().count() <= CLAUDE_ADDITIONAL_CONTEXT_CHARS {
+ used += separator + section.chars().count();
+ kept.push(section);
+ } else if let Some(notice) = omission_notice {
+ let notice_chars = notice.chars().count();
+ if used + separator + notice_chars <= CLAUDE_ADDITIONAL_CONTEXT_CHARS {
+ used += separator + notice_chars;
+ kept.push(notice.to_owned());
+ }
+ }
+ }
+ }
+ (!kept.is_empty()).then(|| kept.join("\n"))
+}
+
/// Default char budget for the session-start brief (~1k tokens at the
/// usual ~4 chars/token) — enough for a few rules pages without taxing
/// every session start.
@@ -2942,7 +3029,7 @@ fn render_session_brief(
Some(buf)
}
-fn render_handoff_markdown(h: &Handoff) -> String {
+fn render_handoff_markdown_with_budget(h: &Handoff, budget: Option<usize>) -> String {
// Layout goal: TUI-renderable + agent-friendly. The previous
// shape put a paragraph-long `## Summary` first, which made the
// hook output look like a wall of text in Codex's "completed"
@@ -2991,6 +3078,18 @@ fn render_handoff_markdown(h: &Handoff) -> String {
buf.push_str(h.content.summary.trim());
buf.push('\n');
escape_untrusted_history_tail(&mut buf, history_start);
+ if let Some(budget) = budget {
+ let footer_room = UNTRUSTED_HISTORY_END.chars().count() + 520;
+ let ceiling = budget.saturating_sub(footer_room).max(history_start);
+ if buf.chars().count() > ceiling {
+ let cut = buf
+ .char_indices()
+ .nth(ceiling)
+ .map_or(buf.len(), |(at, _)| at);
+ buf.truncate(cut);
+ buf.push_str("\n[handoff detail omitted to fit this harness's startup limit]\n");
+ }
+ }
buf.push('\n');
buf.push_str(UNTRUSTED_HISTORY_END);
buf.push('\n');
@@ -7432,6 +7531,50 @@ pub(crate) mod tests {
);
}
+ #[test]
+ fn claude_startup_context_stays_inline_and_keeps_must_see_notices() {
+ let output = combine_startup_context(
+ AgentKind::ClaudeCode,
+ Some("profile".repeat(300)),
+ Some("HANDOFF".repeat(500)),
+ Some("handoff notice".into()),
+ Some("continuity notice".into()),
+ Some("managed ledger".repeat(2_000)),
+ Some("project brief".repeat(2_000)),
+ Some("INBOX NOTICE".into()),
+ )
+ .unwrap();
+
+ assert!(output.chars().count() <= CLAUDE_ADDITIONAL_CONTEXT_CHARS);
+ assert!(output.contains("HANDOFF"));
+ assert!(output.contains("continuity notice"));
+ assert!(output.contains("INBOX NOTICE"));
+ assert!(!output.contains("managed ledger"));
+ assert!(!output.contains("project brief"));
+ }
+
+ #[test]
+ fn claude_startup_context_prioritizes_continuation_over_a_large_profile() {
+ let output = combine_startup_context(
+ AgentKind::ClaudeCode,
+ Some("profile".repeat(1_400)),
+ Some("HANDOFF".repeat(600)),
+ Some("HANDOFF NOTICE".repeat(40)),
+ Some("CONTINUITY NOTICE".repeat(40)),
+ None,
+ None,
+ Some("INBOX NOTICE".repeat(40)),
+ )
+ .unwrap();
+
+ assert!(output.chars().count() <= CLAUDE_ADDITIONAL_CONTEXT_CHARS);
+ assert!(output.contains("HANDOFF"));
+ assert!(output.contains("HANDOFF NOTICE"));
+ assert!(output.contains("CONTINUITY NOTICE"));
+ assert!(output.contains("INBOX NOTICE"));
+ assert!(!output.contains("profile"));
+ }
+
#[test]
fn automatic_memory_blocks_mark_dynamic_content_as_untrusted() {
let handoff = Handoff {
@@ -7464,7 +7607,7 @@ pub(crate) mod tests {
accepted_by_user: None,
},
};
- let rendered = render_handoff_markdown(&handoff);
+ let rendered = render_handoff_markdown_with_budget(&handoff, None);
let warning = rendered
.find(ai_memory_core::UNTRUSTED_MEMORY_NOTICE)
.expect("handoff must include the trust boundary");
diff --git a/crates/ai-memory-llm/src/codex.rs b/crates/ai-memory-llm/src/codex.rs
index b9e1617e..a9115307 100644
--- a/crates/ai-memory-llm/src/codex.rs
+++ b/crates/ai-memory-llm/src/codex.rs
@@ -20,8 +20,8 @@ use crate::codex_responses::{CODEX_RESPONSES_URL, CodexResponsesAuth, post_codex
use crate::error::{LlmError, LlmResult};
use crate::openai::{STRUCTURED_OUTPUT_SCHEMA_NAME, enforce_strict_object_schemas};
use crate::openai_oauth::{
- CodexResponsesRequest, CodexText, CodexTextFormat, build_request, extract_output_text,
- into_chat_response,
+ CodexResponsesRequest, CodexText, CodexTextFormat, build_request, into_chat_response,
+ require_output_text,
};
use crate::provider::LlmProvider;
use crate::types::{ChatRequest, ChatResponse, ExtraHeaders, ReasoningEffort};
@@ -214,11 +214,7 @@ impl LlmProvider for CodexProvider {
// error, as the OpenAI path already treats it: `unwrap_or_default()` fed
// an empty string to serde, so the caller saw "EOF while parsing a value
// at line 1 column 0", which names neither the model nor the cause.
- let Some(text) = extract_output_text(&response).filter(|t| !t.trim().is_empty()) else {
- return Err(LlmError::EmptyContent {
- model: self.model.clone(),
- });
- };
+ let text = require_output_text(&response, &self.model)?;
serde_json::from_str(&text).map_err(LlmError::from)
}
}
diff --git a/crates/ai-memory-llm/src/openai.rs b/crates/ai-memory-llm/src/openai.rs
index fb1749bb..2e9ed387 100644
--- a/crates/ai-memory-llm/src/openai.rs
+++ b/crates/ai-memory-llm/src/openai.rs
@@ -1646,4 +1646,36 @@ mod tests {
"the official provider must not gain the openai-compat header"
);
}
+
+ #[tokio::test]
+ async fn official_structured_completion_classifies_whitespace_as_empty_content() {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path("/v1/chat/completions"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
+ "model": "gpt-empty",
+ "choices": [{
+ "message": { "content": " \n\t" },
+ "finish_reason": "stop"
+ }]
+ })))
+ .mount(&server)
+ .await;
+ let provider = OpenAiProvider::new(SecretString::from("sk-test"), "gpt-empty")
+ .unwrap()
+ .with_base_url(server.uri());
+
+ let error = provider
+ .complete_structured_raw(
+ ChatRequest::user_prompt("return JSON"),
+ serde_json::json!({"type": "object", "properties": {}}),
+ )
+ .await
+ .expect_err("whitespace-only output must be empty content");
+
+ assert_eq!(error.class(), "empty-content");
+ assert!(
+ matches!(error, crate::error::LlmError::EmptyContent { model } if model == "gpt-empty")
+ );
+ }
}
diff --git a/crates/ai-memory-llm/src/openai_oauth.rs b/crates/ai-memory-llm/src/openai_oauth.rs
index c890dd12..17c1ff13 100644
--- a/crates/ai-memory-llm/src/openai_oauth.rs
+++ b/crates/ai-memory-llm/src/openai_oauth.rs
@@ -269,11 +269,7 @@ impl LlmProvider for OpenAiOAuthProvider {
// error, as the OpenAI path already treats it: `unwrap_or_default()` fed
// an empty string to serde, so the caller saw "EOF while parsing a value
// at line 1 column 0", which names neither the model nor the cause.
- let Some(text) = extract_output_text(&response).filter(|t| !t.trim().is_empty()) else {
- return Err(LlmError::EmptyContent {
- model: self.model.clone(),
- });
- };
+ let text = require_output_text(&response, &self.model)?;
serde_json::from_str::<serde_json::Value>(&text).map_err(LlmError::from)
}
}
@@ -586,6 +582,17 @@ pub(crate) fn extract_output_text(response: &CodexResponsesResponse) -> Option<S
.map(ToOwned::to_owned)
}
+pub(crate) fn require_output_text(
+ response: &CodexResponsesResponse,
+ model: &str,
+) -> LlmResult<String> {
+ extract_output_text(response)
+ .filter(|text| !text.trim().is_empty())
+ .ok_or_else(|| LlmError::EmptyContent {
+ model: model.to_owned(),
+ })
+}
+
fn extract_account_id_from_jwt(token: &str) -> Option<String> {
let payload = token.split('.').nth(1)?;
let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
@@ -1011,4 +1018,17 @@ mod tests {
.unwrap();
assert_eq!(extract_output_text(&nested).as_deref(), Some("nested"));
}
+
+ #[test]
+ fn responses_structured_output_requires_non_blank_text() {
+ for response in [
+ serde_json::from_value(json!({"output": []})).unwrap(),
+ serde_json::from_value(json!({"output_text": " \n\t", "output": []})).unwrap(),
+ ] {
+ let error = require_output_text(&response, "gpt-empty")
+ .expect_err("missing or blank Responses output must be empty content");
+ assert_eq!(error.class(), "empty-content");
+ assert!(matches!(error, LlmError::EmptyContent { model } if model == "gpt-empty"));
+ }
+ }
}
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 523b6145..b32094ca 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -1743,7 +1743,7 @@ impl From<ai_memory_store::PageHitWithMeta> for GlobalSearchHit {
id: hit.id,
path: hit.path,
title: hit.title,
- snippet: hit.snippet,
+ snippet: ai_memory_store::highlighted_snippet_html(&hit.snippet),
rank: hit.rank,
workspace: hit.workspace_name,
project: hit.project_name,
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 7f4728d6..df78feda 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -926,7 +926,7 @@ async fn rerank_page_hits(
|(hit, _)| ai_memory_llm::RerankCandidate {
id: hit.id.to_string(),
title: hit.title.clone(),
- snippet: hit.snippet.clone(),
+ snippet: ai_memory_store::plain_snippet(&hit.snippet),
},
|(_, explain), relevance| {
if let Some(explain) = explain.as_mut() {
@@ -7689,7 +7689,7 @@ fn build_answer_request(
reasoning: ReasoningTier,
) -> ai_memory_llm::ChatRequest {
fn clean(snippet: &str) -> String {
- snippet.replace("<mark>", "").replace("</mark>", "")
+ ai_memory_store::plain_snippet(snippet)
}
let mut user = String::new();
user.push_str("## Question\n\n");
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 6a078b01..6a59f99c 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -87,10 +87,10 @@ pub use reader::{
AutoImproveParkedClaim, BriefPageBody, BriefingPage, BriefingSnapshot, ClientActivity,
ContaminationFinding, ContaminationReport, ContaminationSummary, ContradictionEdge,
CrossProjectEdge, DecayCandidate, DecayTombstone, DerivedIndexStatus, EmbeddingTripleCount,
- FeedbackFinding, GraphVia, HealthDetail, HealthPage, HybridSearch, HybridSearchOutcome,
- IdleOpenSession, InboxCount, InboxEntry, LinkGraph, LinkGraphEdge, LinkGraphNode,
- ObservationHit, ObservationOrder, ObservationPage, ObservationPageResult,
- ObservationProjectionTotals, ObservationRecord, OpenSession, PAGE_KINDS,
+ FTS_HIGHLIGHT_END, FTS_HIGHLIGHT_START, FeedbackFinding, GraphVia, HealthDetail, HealthPage,
+ HybridSearch, HybridSearchOutcome, IdleOpenSession, InboxCount, InboxEntry, LinkGraph,
+ LinkGraphEdge, LinkGraphNode, ObservationHit, ObservationOrder, ObservationPage,
+ ObservationPageResult, ObservationProjectionTotals, ObservationRecord, OpenSession, PAGE_KINDS,
PAGE_VERSIONS_MAX_LIMIT, PROJECT_LINK_GRAPH_MAX_NODES, PageAuthor, PageFilter, PageHit,
PageHitWithMeta, PageLinks, PageLinksPreview, PageMeta, PageSummary, PageVersion,
PageVersionBody, PageVersions, ProjectCoordinateCollisionReason, ProjectCoordinateDiagnostic,
@@ -101,7 +101,7 @@ pub use reader::{
SessionEndDisposition, SessionKindSummary, SessionLine, SessionObservationSnapshot,
SessionPromptTitles, SessionSummary, SessionToolTitles, SettledPage, StatusCounts,
StorageStatus, StoredEmbedding, StoredPageBody, StreamTimings, VectorQuery, WorkspaceScopeRow,
- WorkspaceSummary, f32_vec_to_bytes,
+ WorkspaceSummary, f32_vec_to_bytes, highlighted_snippet_html, plain_snippet,
};
pub use retrieval_tuning::{RetrievalTuning, is_session_recall_query};
pub use scope::{
@@ -2481,7 +2481,7 @@ mod tests {
.unwrap();
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].path.as_str(), "alpha.md");
- assert!(hits[0].snippet.contains("<mark>quick</mark>"));
+ assert!(highlighted_snippet_html(&hits[0].snippet).contains("<mark>quick</mark>"));
// Supersede: only the latest version should appear in counts'
// pages_latest, and search should still return exactly one hit.
@@ -3628,7 +3628,7 @@ mod tests {
.unwrap();
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].session_id, session_id);
- assert!(hits[0].snippet.contains("<mark>zebra</mark>"));
+ assert!(highlighted_snippet_html(&hits[0].snippet).contains("<mark>zebra</mark>"));
}
/// The public writer API only accepts `Sanitized<NewObservation>`, and
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 649449bc..5bdc50e1 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -426,6 +426,63 @@ const OBSERVATION_STREAM_IDS_PER_PAGE: usize = 3;
/// window; an observation body usually does, and a full window made each
/// excerpt-backed hit cost more context than the page hit it stands in for.
const OBSERVATION_SNIPPET_TOKENS: usize = 16;
+/// Internal FTS highlight delimiters. Durable text crosses the sanitizer,
+/// which strips both control characters, so page content cannot impersonate
+/// a match. Presentation boundaries translate these markers to HTML or remove
+/// them for plain-text/model input.
+pub const FTS_HIGHLIGHT_START: &str = "\u{1e}";
+/// Closing delimiter paired with [`FTS_HIGHLIGHT_START`].
+pub const FTS_HIGHLIGHT_END: &str = "\u{1f}";
+
+/// Remove internal FTS highlight delimiters without altering page text.
+#[must_use]
+pub fn plain_snippet(snippet: &str) -> String {
+ snippet
+ .replace(FTS_HIGHLIGHT_START, "")
+ .replace(FTS_HIGHLIGHT_END, "")
+}
+
+/// Render an internal FTS snippet as safe HTML, preserving only highlights
+/// produced by SQLite. All page text, including literal `<mark>` tags, is
+/// escaped before it reaches an HTML `|safe` boundary or JSON frontend.
+#[must_use]
+pub fn highlighted_snippet_html(snippet: &str) -> String {
+ let mut out = String::with_capacity(snippet.len());
+ let mut rest = snippet;
+ while let Some(at) = rest.find(FTS_HIGHLIGHT_START) {
+ let after = &rest[at + FTS_HIGHLIGHT_START.len()..];
+ let Some(close) = after.find(FTS_HIGHLIGHT_END) else {
+ break;
+ };
+ push_html_escaped(&mut out, &rest[..at]);
+ out.push_str("<mark>");
+ push_html_escaped(&mut out, &after[..close]);
+ out.push_str("</mark>");
+ rest = &after[close + FTS_HIGHLIGHT_END.len()..];
+ }
+ push_html_escaped(&mut out, rest);
+ out
+}
+
+fn push_html_escaped(out: &mut String, input: &str) {
+ for c in input.chars() {
+ match c {
+ '&' => out.push_str("&amp;"),
+ '<' => out.push_str("&lt;"),
+ '>' => out.push_str("&gt;"),
+ '"' => out.push_str("&quot;"),
+ '\'' => out.push_str("&#39;"),
+ _ => out.push(c),
+ }
+ }
+}
+
+fn serialize_highlighted_snippet<S>(snippet: &String, serializer: S) -> Result<S::Ok, S::Error>
+where
+ S: serde::Serializer,
+{
+ serializer.serialize_str(&highlighted_snippet_html(snippet))
+}
/// A project's first and last observation rowid, bound to `?1` = project id.
///
/// `idx_observations_project` is `(project_id)` with the implicit rowid
@@ -1282,7 +1339,9 @@ pub struct PageHit {
pub path: PagePath,
/// Page title.
pub title: String,
- /// FTS5 snippet of the body around the matched terms (HTML-marked).
+ /// FTS5 snippet of the body around matched terms. Internally delimited;
+ /// serialized as safe HTML with `<mark>` around genuine matches.
+ #[serde(serialize_with = "serialize_highlighted_snippet")]
pub snippet: String,
/// Relevance rank after the bounded authority adjustment (lower is better).
pub rank: f64,
@@ -1586,7 +1645,9 @@ pub struct PageHitWithMeta {
pub path: PagePath,
/// Page title.
pub title: String,
- /// FTS5 snippet of the body around the matched terms (HTML-marked).
+ /// FTS5 snippet of the body around matched terms. Internally delimited;
+ /// serialized as safe HTML with `<mark>` around genuine matches.
+ #[serde(serialize_with = "serialize_highlighted_snippet")]
pub snippet: String,
/// Relevance rank after the bounded authority adjustment (lower is better).
pub rank: f64,
@@ -1604,6 +1665,7 @@ pub struct ObservationHit {
/// Observation title.
pub title: String,
/// FTS5 snippet of the raw observation body around the matched terms.
+ #[serde(serialize_with = "serialize_highlighted_snippet")]
pub snippet: String,
/// FTS5 rank score (lower is better).
pub rank: f64,
@@ -2902,7 +2964,7 @@ impl ReaderPool {
readable_repository_filter("pages.project_id", viewer, 4);
let sql = format!(
"SELECT pages.id, pages.path, pages.title, \
- snippet(pages_fts, 1, '<mark>', '</mark>', '…', 24) AS snip, \
+ snippet(pages_fts, 1, char(30), char(31), '…', 24) AS snip, \
pages_fts.rank, pages.tier, pages.pinned, \
pages.frontmatter_json, {kind_expr} AS kind \
FROM pages_fts \
@@ -3059,7 +3121,7 @@ impl ReaderPool {
let kind_expr = page_kind_expr("pages.path", "pages.frontmatter_json");
let sql = format!(
"SELECT workspaces.name, projects.name, pages.path, pages.title, \
- snippet(pages_fts, 1, '<mark>', '</mark>', '…', 24) AS snip, \
+ snippet(pages_fts, 1, char(30), char(31), '…', 24) AS snip, \
pages_fts.rank, pages.tier, pages.pinned, \
pages.frontmatter_json, {kind_expr} AS kind, pages.id \
FROM pages_fts \
@@ -3262,7 +3324,7 @@ impl ReaderPool {
let kind_expr = page_kind_expr("pages.path", "pages.frontmatter_json");
let sql = format!(
"SELECT pages.id, pages.path, pages.title, \
- snippet(pages_fts, 1, '<mark>', '</mark>', '…', 24) AS snip, \
+ snippet(pages_fts, 1, char(30), char(31), '…', 24) AS snip, \
pages_fts.rank, pages.tier, pages.pinned, \
pages.frontmatter_json, {kind_expr} AS kind \
FROM pages_fts \
@@ -3421,7 +3483,7 @@ impl ReaderPool {
let limit_placeholder = 7 + kept_params.len();
let sql = format!(
"SELECT pages.id, pages.path, pages.title, \
- snippet(pages_fts, 1, '<mark>', '</mark>', '…', 24) AS snip, \
+ snippet(pages_fts, 1, char(30), char(31), '…', 24) AS snip, \
pages_fts.rank, pages.tier, pages.pinned, \
pages.frontmatter_json, {kind_expr} AS kind \
FROM pages_fts \
@@ -3795,7 +3857,7 @@ impl ReaderPool {
let mut stmt = conn.prepare(&format!(
"SELECT observations.id, observations.session_id, observations.kind, \
observations.title, \
- snippet(observations_fts, 1, '<mark>', '</mark>', '…', 24) AS snip, \
+ snippet(observations_fts, 1, char(30), char(31), '…', 24) AS snip, \
observations_fts.rank, observations.created_at \
FROM observations_fts \
JOIN observations ON observations.rowid = observations_fts.rowid \
@@ -3980,7 +4042,7 @@ impl ReaderPool {
// and re-enters FTS once per row, which is far slower.
let mut stmt = tx.prepare(&format!(
"SELECT observations.id, observations.session_id, \
- snippet(observations_fts, 1, '<mark>', '</mark>', '…', \
+ snippet(observations_fts, 1, char(30), char(31), '…', \
{OBSERVATION_SNIPPET_TOKENS}) \
FROM observations_fts \
CROSS JOIN observations ON observations.rowid = observations_fts.rowid \
diff --git a/crates/ai-memory-store/tests/suite/retrieval_observation_stream.rs b/crates/ai-memory-store/tests/suite/retrieval_observation_stream.rs
index 7a05fc0b..36d137cf 100644
--- a/crates/ai-memory-store/tests/suite/retrieval_observation_stream.rs
+++ b/crates/ai-memory-store/tests/suite/retrieval_observation_stream.rs
@@ -194,7 +194,11 @@ async fn an_observation_hit_lifts_its_own_session_page() {
assert!((details.fused - details.rrf.observation).abs() < 1e-12);
// The page had no snippet of its own for these words, so the bounded,
// already-sanitized observation excerpt explains the hit.
- assert!(hit.snippet.contains("<mark>"), "{}", hit.snippet);
+ assert!(
+ ai_memory_store::highlighted_snippet_html(&hit.snippet).contains("<mark>"),
+ "{}",
+ hit.snippet
+ );
assert!(hit.snippet.contains("quasar"), "{}", hit.snippet);
assert!(!hit.title.is_empty());
}
@@ -574,7 +578,8 @@ async fn an_untitled_session_page_keeps_the_observation_excerpt() {
let hits = search(&store, ws, proj, "heron").await;
assert_eq!(hits.len(), 1);
assert!(
- hits[0].0.snippet.contains("<mark>heron</mark>"),
+ ai_memory_store::highlighted_snippet_html(&hits[0].0.snippet)
+ .contains("<mark>heron</mark>"),
"{}",
hits[0].0.snippet
);
diff --git a/crates/ai-memory-web/src/markdown.rs b/crates/ai-memory-web/src/markdown.rs
index 843083aa..60ec5a74 100644
--- a/crates/ai-memory-web/src/markdown.rs
+++ b/crates/ai-memory-web/src/markdown.rs
@@ -709,55 +709,14 @@ fn has_external_or_unsafe_scheme(target: &str) -> bool {
|| lower.starts_with("file:")
}
-/// Escape text for insertion into an HTML template while preserving the
-/// fixed `<mark>` tags emitted by SQLite FTS snippets.
+/// Escape an internal FTS snippet for insertion into an HTML template.
///
-/// Only a balanced, non-nested `<mark>…</mark>` pair is kept as markup,
-/// which is all SQLite's highlighter ever emits. A marker from the page's
-/// own body does not form one, and escaping it keeps an unbalanced tag out
-/// of the template's `|safe` slot, where it would highlight the rest of the
-/// excerpt as if it were a query match.
+/// SQLite wraps matches in control delimiters that the durable sanitizer
+/// forbids in page content. Only those unforgeable delimiters become
+/// `<mark>` tags; literal markup from a page is always escaped.
#[must_use]
pub fn escape_snippet(snippet: &str) -> String {
- const OPEN: &str = "<mark>";
- const CLOSE: &str = "</mark>";
- let mut out = String::with_capacity(snippet.len());
- let mut rest = snippet;
- while let Some(at) = rest.find(OPEN) {
- let after = &rest[at + OPEN.len()..];
- let Some(close) = after.find(CLOSE) else {
- break;
- };
- if after[..close].contains(OPEN) {
- // A second opening marker intervenes, so this one closes
- // nothing: emit it as the text it is and look on from there.
- out.push_str(&escape_html(&rest[..at + OPEN.len()]));
- rest = after;
- continue;
- }
- out.push_str(&escape_html(&rest[..at]));
- out.push_str(OPEN);
- out.push_str(&escape_html(&after[..close]));
- out.push_str(CLOSE);
- rest = &after[close + CLOSE.len()..];
- }
- out.push_str(&escape_html(rest));
- out
-}
-
-fn escape_html(input: &str) -> String {
- let mut out = String::with_capacity(input.len());
- for c in input.chars() {
- match c {
- '&' => out.push_str("&amp;"),
- '<' => out.push_str("&lt;"),
- '>' => out.push_str("&gt;"),
- '"' => out.push_str("&quot;"),
- '\'' => out.push_str("&#39;"),
- _ => out.push(c),
- }
- }
- out
+ ai_memory_store::highlighted_snippet_html(snippet)
}
/// Drop the leading H1 from a markdown body when it repeats `title`.
@@ -938,7 +897,11 @@ mod tests {
#[test]
fn escapes_search_snippet_but_keeps_marks() {
- let out = escape_snippet("<script>x</script> <mark>hit</mark>");
+ let out = escape_snippet(&format!(
+ "<script>x</script> {}hit{}",
+ ai_memory_store::FTS_HIGHLIGHT_START,
+ ai_memory_store::FTS_HIGHLIGHT_END
+ ));
assert!(out.contains("&lt;script&gt;x&lt;/script&gt;"));
assert!(out.contains("<mark>hit</mark>"));
}
@@ -947,20 +910,28 @@ mod tests {
fn a_literal_mark_tag_in_page_text_stays_text() {
assert_eq!(
escape_snippet("use <mark> here <mark>hit</mark>"),
- "use &lt;mark&gt; here <mark>hit</mark>"
+ "use &lt;mark&gt; here &lt;mark&gt;hit&lt;/mark&gt;"
);
- // An opening marker the highlighter never closed, and a stray
- // closing one, are both page text.
assert_eq!(escape_snippet("see <mark> here"), "see &lt;mark&gt; here");
assert_eq!(escape_snippet("a </mark> b"), "a &lt;/mark&gt; b");
- // Controls: the highlighter's own pairs survive, and text between
- // and inside them is still escaped.
+ let highlighted = format!(
+ "{}a{} x {}b{}",
+ ai_memory_store::FTS_HIGHLIGHT_START,
+ ai_memory_store::FTS_HIGHLIGHT_END,
+ ai_memory_store::FTS_HIGHLIGHT_START,
+ ai_memory_store::FTS_HIGHLIGHT_END
+ );
assert_eq!(
- escape_snippet("<mark>a</mark> x <mark>b</mark>"),
+ escape_snippet(&highlighted),
"<mark>a</mark> x <mark>b</mark>"
);
+ let escaped_inside = format!(
+ "{}a&b{} <script>",
+ ai_memory_store::FTS_HIGHLIGHT_START,
+ ai_memory_store::FTS_HIGHLIGHT_END
+ );
assert_eq!(
- escape_snippet("<mark>a&b</mark> <script>"),
+ escape_snippet(&escaped_inside),
"<mark>a&amp;b</mark> &lt;script&gt;"
);
}
diff --git a/crates/ai-memory-web/src/recall.rs b/crates/ai-memory-web/src/recall.rs
index 09d161bc..bdd985fd 100644
--- a/crates/ai-memory-web/src/recall.rs
+++ b/crates/ai-memory-web/src/recall.rs
@@ -102,7 +102,7 @@ pub(crate) async fn search_scopes(
|(hit, _)| RerankCandidate {
id: hit.id.to_string(),
title: hit.title.clone(),
- snippet: hit.snippet.clone(),
+ snippet: ai_memory_store::plain_snippet(&hit.snippet),
},
|(_, details), relevance| {
if let Some(details) = details.as_mut() {
diff --git a/crates/ai-memory-web/src/routes/api.rs b/crates/ai-memory-web/src/routes/api.rs
index ea7c510e..ac8eeedd 100644
--- a/crates/ai-memory-web/src/routes/api.rs
+++ b/crates/ai-memory-web/src/routes/api.rs
@@ -1361,7 +1361,7 @@ async fn enrich_hits(state: &WebState, hits: Vec<PageHit>) -> Result<Vec<ApiSear
path: meta.path,
project: meta.project_name,
rank: hit.rank,
- snippet: hit.snippet,
+ snippet: ai_memory_store::highlighted_snippet_html(&hit.snippet),
title: hit.title,
workspace: meta.workspace_name,
});
diff --git a/crates/ai-memory-workstream/Cargo.toml b/crates/ai-memory-workstream/Cargo.toml
index f9badd42..6cef9644 100644
--- a/crates/ai-memory-workstream/Cargo.toml
+++ b/crates/ai-memory-workstream/Cargo.toml
@@ -18,6 +18,7 @@ sha2.workspace = true
# Kimi wire records timestamp in ms epoch; jiff renders them RFC3339 like the
# other harnesses' native ISO strings.
jiff.workspace = true
+libc.workspace = true
rusqlite.workspace = true
tokio.workspace = true
uuid.workspace = true
diff --git a/crates/ai-memory-workstream/src/transcript.rs b/crates/ai-memory-workstream/src/transcript.rs
index 9e09f920..42e1c1a4 100644
--- a/crates/ai-memory-workstream/src/transcript.rs
+++ b/crates/ai-memory-workstream/src/transcript.rs
@@ -4189,15 +4189,18 @@ fn export_antigravity(
Some((path, file, len))
});
let Some((history, mut file, len)) = opened else {
- losses.push(
- "Antigravity history.jsonl is missing or unreadable; no user prompts were imported"
- .into(),
- );
+ let events = antigravity_brain_prompt_events(home, session_dir, session, &mut losses);
+ if events.is_empty() {
+ losses.push(
+ "Antigravity history.jsonl and brain transcript are missing or unreadable; no user prompts were imported"
+ .into(),
+ );
+ }
losses.push(ANTIGRAVITY_PROMPTS_ONLY.into());
return Ok(ExportedTranscript {
native_session_id: session.to_string(),
source_cursor: None,
- events: Vec::new(),
+ events,
losses,
});
};
@@ -4227,6 +4230,7 @@ fn export_antigravity(
let mut offset = start;
let mut line = Vec::new();
let mut prompts: Vec<HistoryPrompt> = Vec::new();
+ let mut saw_session_prompt = false;
// Unlabelled prompts from this checkout that could have opened it.
let mut openers: Vec<HistoryPrompt> = Vec::new();
loop {
@@ -4294,6 +4298,7 @@ fn export_antigravity(
losses.push("Antigravity shell commands were intentionally excluded".into());
}
(Some(_), AntigravityHistoryKind::Prompt) => {
+ saw_session_prompt = true;
if in_checkout(entry.workspace) {
prompts.push(prompt());
} else {
@@ -4343,6 +4348,17 @@ fn export_antigravity(
prompt.metadata,
);
}
+ // A prompt explicitly attributed to this conversation but typed in a
+ // different checkout is authoritative scope evidence. Falling back to
+ // the conversation-wide brain log here would re-admit the rejected text.
+ if events.is_empty() && !saw_session_prompt {
+ events.extend(antigravity_brain_prompt_events(
+ home,
+ session_dir,
+ session,
+ &mut losses,
+ ));
+ }
losses.push(ANTIGRAVITY_PROMPTS_ONLY.into());
Ok(ExportedTranscript {
native_session_id: session.to_string(),
@@ -4357,7 +4373,182 @@ fn export_antigravity(
})
}
-const ANTIGRAVITY_PROMPTS_ONLY: &str = "Antigravity assistant and tool steps are not decodable; only user prompts from history.jsonl were imported";
+const ANTIGRAVITY_PROMPTS_ONLY: &str = "Antigravity assistant and tool steps are not decodable; only explicit user prompts were imported";
+
+const MAX_ANTIGRAVITY_BRAIN_BYTES: u64 = 8 * 1024 * 1024;
+const MAX_ANTIGRAVITY_BRAIN_LINE_BYTES: usize = 1024 * 1024;
+
+fn antigravity_brain_prompt_events(
+ home: &Path,
+ session_dir: Option<&Path>,
+ session: &str,
+ losses: &mut Vec<String>,
+) -> Vec<NewWorkstreamEvent> {
+ let session_root = session_root(ManagedHarness::Antigravity, home, session_dir);
+ let Some(root) = session_root.parent() else {
+ return Vec::new();
+ };
+ let Ok(root) = root.canonicalize() else {
+ return Vec::new();
+ };
+ let logs = root
+ .join("brain")
+ .join(session)
+ .join(".system_generated")
+ .join("logs");
+ let opened = ["transcript.jsonl", "transcript_full.jsonl"]
+ .into_iter()
+ .map(|name| logs.join(name))
+ .find_map(|candidate| open_contained_antigravity_transcript(&root, &candidate));
+ let Some(file) = opened else {
+ return Vec::new();
+ };
+ let mut events = Vec::new();
+ let mut reader = BufReader::new(file);
+ let mut line = Vec::new();
+ let mut offset = 0u64;
+ loop {
+ let start = offset;
+ let read = match read_bounded_line(
+ &mut reader,
+ MAX_ANTIGRAVITY_BRAIN_LINE_BYTES,
+ b"USER_INPUT",
+ &mut line,
+ &mut Sha256::new(),
+ ) {
+ Ok(BoundedLine::Line(read)) => read,
+ Ok(BoundedLine::Oversized { read, mentions }) => {
+ offset += read;
+ if mentions {
+ losses.push("oversized Antigravity brain prompt records were skipped".into());
+ }
+ continue;
+ }
+ Ok(BoundedLine::Eof | BoundedLine::Partial) => break,
+ Err(_) => {
+ losses.push("Antigravity brain transcript became unreadable".into());
+ break;
+ }
+ };
+ offset += read;
+ let raw = line.strip_suffix(b"\n").unwrap_or(&line);
+ let Some((text, step, created_at)) = antigravity_brain_prompt(raw) else {
+ continue;
+ };
+ let hash = format!("{:x}", Sha256::digest(raw));
+ let record = format!("brain-{}-{}", step.unwrap_or(start), &hash[..16]);
+ push_event(
+ &mut events,
+ AgentKind::AntigravityCli,
+ session,
+ &record,
+ 0,
+ WorkstreamEventKind::Message,
+ Some("user"),
+ &text,
+ created_at,
+ json!({"source": "brain-transcript"}),
+ );
+ }
+ events
+}
+
+fn open_contained_antigravity_transcript(root: &Path, path: &Path) -> Option<File> {
+ let canonical = path.canonicalize().ok()?;
+ if !canonical.starts_with(root) || fs::symlink_metadata(path).ok()?.file_type().is_symlink() {
+ return None;
+ }
+ #[cfg(unix)]
+ let file = {
+ use std::os::unix::fs::OpenOptionsExt as _;
+ fs::OpenOptions::new()
+ .read(true)
+ .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
+ .open(&canonical)
+ .ok()?
+ };
+ #[cfg(not(unix))]
+ let file = File::open(&canonical).ok()?;
+ let metadata = file.metadata().ok()?;
+ if !metadata.is_file() || metadata.len() > MAX_ANTIGRAVITY_BRAIN_BYTES {
+ return None;
+ }
+ #[cfg(target_os = "linux")]
+ {
+ use std::os::fd::AsRawFd as _;
+ let descriptor = fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd())).ok()?;
+ if descriptor != canonical {
+ return None;
+ }
+ }
+ Some(file)
+}
+
+fn antigravity_brain_prompt(raw: &[u8]) -> Option<(String, Option<u64>, Option<String>)> {
+ if !raw
+ .windows(b"USER_INPUT".len())
+ .any(|window| window.eq_ignore_ascii_case(b"USER_INPUT"))
+ {
+ return None;
+ }
+ let value: Value = serde_json::from_slice(raw).ok()?;
+ let step = value.as_object()?;
+ let kind = step.get("type")?.as_str()?.trim().to_ascii_uppercase();
+ if kind != "USER_INPUT" && !kind.ends_with("_USER_INPUT") {
+ return None;
+ }
+ if let Some(source) = step.get("source") {
+ let source = source.as_str()?.trim().to_ascii_uppercase();
+ if source != "USER_EXPLICIT" && !source.ends_with("_USER_EXPLICIT") {
+ return None;
+ }
+ }
+ let content = antigravity_content_text(step.get("content")?)?;
+ let text = antigravity_user_request_text(&content).trim().to_owned();
+ if text.is_empty() {
+ return None;
+ }
+ let index = step.get("step_index").and_then(|value| {
+ value
+ .as_u64()
+ .or_else(|| value.as_str().and_then(|text| text.trim().parse().ok()))
+ });
+ let created_at = step
+ .get("created_at")
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|value| value.parse::<jiff::Timestamp>().is_ok())
+ .map(str::to_owned);
+ Some((text, index, created_at))
+}
+
+fn antigravity_content_text(content: &Value) -> Option<String> {
+ match content {
+ Value::String(text) => Some(text.clone()),
+ Value::Object(part) => part.get("text").and_then(Value::as_str).map(str::to_owned),
+ Value::Array(parts) => {
+ let text: Vec<&str> = parts
+ .iter()
+ .filter_map(|part| {
+ part.as_str()
+ .or_else(|| part.get("text").and_then(Value::as_str))
+ })
+ .collect();
+ (!text.is_empty()).then(|| text.join("\n"))
+ }
+ _ => None,
+ }
+}
+
+fn antigravity_user_request_text(content: &str) -> &str {
+ const OPEN: &str = "<USER_REQUEST>";
+ const CLOSE: &str = "</USER_REQUEST>";
+ let Some(start) = content.find(OPEN) else {
+ return content;
+ };
+ let inner = &content[start + OPEN.len()..];
+ inner.find(CLOSE).map_or(inner, |end| &inner[..end])
+}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AntigravityHistoryKind {
@@ -9155,6 +9346,23 @@ mod tests {
fs::write(root.parent().unwrap().join("history.jsonl"), body).unwrap();
}
+ fn write_antigravity_brain(root: &Path, lines: &[Value]) {
+ let logs = root
+ .parent()
+ .unwrap()
+ .join("brain")
+ .join(AG_MINE)
+ .join(".system_generated/logs");
+ fs::create_dir_all(&logs).unwrap();
+ let mut body = lines
+ .iter()
+ .map(Value::to_string)
+ .collect::<Vec<_>>()
+ .join("\n");
+ body.push('\n');
+ fs::write(logs.join("transcript.jsonl"), body).unwrap();
+ }
+
async fn export_antigravity_fixture(
fixture: &AntigravityFixture,
cursor: Option<&str>,
@@ -9218,6 +9426,107 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn antigravity_print_mode_falls_back_to_explicit_brain_prompts() {
+ let fixture = antigravity_fixture();
+ write_antigravity_brain(
+ &fixture.root,
+ &[
+ json!({
+ "step_index": 1,
+ "type": "USER_INPUT",
+ "source": "USER_EXPLICIT",
+ "content": "print-mode prompt",
+ "created_at": "2026-10-22T12:00:00Z"
+ }),
+ json!({
+ "step_index": 2,
+ "type": "USER_INPUT",
+ "source": "HOOK",
+ "content": "injected canary"
+ }),
+ json!({
+ "step_index": 3,
+ "type": "TOOL_OUTPUT",
+ "content": "USER_INPUT canary in tool output"
+ }),
+ ],
+ );
+
+ let exported = export_antigravity_fixture(&fixture, None).await;
+
+ assert_eq!(prompts(&exported), ["print-mode prompt"]);
+ assert_eq!(
+ exported.events[0].metadata,
+ json!({"source": "brain-transcript"})
+ );
+ }
+
+ #[tokio::test]
+ async fn antigravity_brain_fallback_does_not_re_admit_foreign_workspace_prompts() {
+ let fixture = antigravity_fixture();
+ write_antigravity_history(
+ &fixture.root,
+ &[history_line(
+ Some(AG_MINE),
+ &fixture.other,
+ "foreign history prompt",
+ AG_PAST,
+ )],
+ );
+ write_antigravity_brain(
+ &fixture.root,
+ &[json!({
+ "step_index": 1,
+ "type": "USER_INPUT",
+ "source": "USER_EXPLICIT",
+ "content": "foreign brain prompt"
+ })],
+ );
+
+ let exported = export_antigravity_fixture(&fixture, None).await;
+
+ assert!(exported.events.is_empty(), "{:?}", exported.events);
+ assert!(
+ exported
+ .losses
+ .iter()
+ .any(|loss| loss.contains("another workspace")),
+ "{:?}",
+ exported.losses
+ );
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn antigravity_brain_fallback_refuses_a_symlink_escape() {
+ use std::os::unix::fs::symlink;
+
+ let fixture = antigravity_fixture();
+ let outside = fixture.temp.path().join("outside");
+ fs::create_dir_all(outside.join(".system_generated/logs")).unwrap();
+ fs::write(
+ outside.join(".system_generated/logs/transcript.jsonl"),
+ format!(
+ "{}\n",
+ json!({
+ "step_index": 1,
+ "type": "USER_INPUT",
+ "source": "USER_EXPLICIT",
+ "content": "escape canary"
+ })
+ ),
+ )
+ .unwrap();
+ let brain = fixture.root.parent().unwrap().join("brain");
+ fs::create_dir_all(&brain).unwrap();
+ symlink(&outside, brain.join(AG_MINE)).unwrap();
+
+ let exported = export_antigravity_fixture(&fixture, None).await;
+
+ assert!(exported.events.is_empty(), "{:?}", exported.events);
+ }
+
/// `agy --conversation=<id>` run from another directory keeps the id but
/// records that directory, so the id alone must not admit the line.
#[tokio::test]
diff --git a/docs/desktop/verification-2026-10.md b/docs/desktop/verification-2026-10.md
index 35e42310..e01fb339 100644
--- a/docs/desktop/verification-2026-10.md
+++ b/docs/desktop/verification-2026-10.md
@@ -88,9 +88,9 @@ recorder, `agy -p` and the documented stream-json input
`transcript.jsonl` sits next to it. The docs name only `transcript.jsonl`.
Both start with a `USER_INPUT` step whose `content` holds the prompt in
`<USER_REQUEST>` tags, in print mode as well.
-- Print mode writes no `~/.gemini/antigravity-cli/history.jsonl` line (the
- #1160 replay therefore has nothing to replay for `agy -p`); the transcript
- does have the prompt.
+- Print mode writes no `~/.gemini/antigravity-cli/history.jsonl` line; the
+ transcript does have the prompt and managed export now uses it as the
+ print-mode fallback (#1605).
- Conversation state is kept per conversation in
`~/.gemini/antigravity-cli/conversations/<id>.db`, with `brain/<id>/`,
`annotations/<id>.pbtxt` and `presence/<id>.lock` alongside.
diff --git a/docs/install.md b/docs/install.md
index e963a7a9..4b9f711a 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -1430,8 +1430,10 @@ handoff are built with them. Each prompt is keyed as `backfill` keys it, so a
re-close stores it once and a prompt typed after the first finalize arrives
with the next. A checkout the capture allowlist does not admit sends none,
`--all-owners` replays none (other users' prompts are not in this machine's
-history), and a missing or unreadable `history.jsonl` only prints a warning.
-`agy -p` runs write no `history.jsonl` line, so they have no prompt to replay.
+history). When history is missing or yields no prompt, export falls back to
+the selected conversation's bounded, containment-checked brain transcript and
+keeps only explicit user-input steps. `agy -p` writes no `history.jsonl` line,
+so this fallback supplies its prompt.
Rerun `ai-memory install-hooks --agent antigravity-cli --apply` after
upgrading. An install from an earlier release runs its `session-start` handler
diff --git a/docs/managed-workstreams.md b/docs/managed-workstreams.md
index a2ecdc30..0a1bbfa4 100644
--- a/docs/managed-workstreams.md
+++ b/docs/managed-workstreams.md
@@ -739,7 +739,7 @@ change does not add an atomic disk/SQL seal or change lease/retry policy.
| Kiro CLI v3 | native default creation with `--v3` | `--v3 --resume-id <sess_uuid>` | `$KIRO_HOME/sessions/<checkout-bucket>/<sess_uuid>/messages.jsonl` (+ sibling `session.json` metadata) |
| OMP | native default creation | `--resume=<id>` | `<agent dir>/sessions/**/*.jsonl`, or the XDG session directory described below |
| Grok Build CLI | generated `--session-id` | `--resume <id>` | `$GROK_HOME/sessions/*/*/chat_history.jsonl` |
-| Antigravity CLI | native default creation | `--conversation <id>` | `~/.gemini/antigravity-cli/conversations/<id>.db` metadata; user prompts only from `~/.gemini/antigravity-cli/history.jsonl` (assistant and tool steps come from lifecycle-hook capture) |
+| Antigravity CLI | native default creation | `--conversation <id>` | `~/.gemini/antigravity-cli/conversations/<id>.db` metadata; user prompts from `history.jsonl`, falling back to that conversation's bounded `brain/<id>/.system_generated/logs/transcript{,_full}.jsonl` for print mode (assistant and tool steps come from lifecycle-hook capture) |
| GitHub Copilot CLI | generated `--session-id` | `--resume=<id>` | `$COPILOT_HOME/session-state/<uuid>/events.jsonl` (`COPILOT_HOME` defaults to `~/.copilot`) |
OMP's agent directory is `~/.omp/agent` for the default profile and
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 6a698934..a33c765b 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -111,7 +111,7 @@ means the boundary is not built yet.
| 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; for Claude it moves the run's own session to a background session only when `ai-memory-workstream` `claude_continued_session` finds a `sessionKind: "bg"` record that names that exact session as its attached client and this checkout as `cwd` (#1050), and to a `/clear`ed session only when that session's own transcript records the `/clear` command and names the run's session as its launch `session_id` from this checkout or below it; `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` `claude_continued_session_follows_only_this_checkouts_bg_records` (a concurrent launch's background session, another checkout's, and a non-background record refused; own attachment control); `transcript.rs` `claude_continued_session_follows_only_this_launchs_clear` (an uncleared transcript, a quoted `/clear`, another checkout's clear, a concurrent launch's clear, a subagent file, and a pre-run clear refused; own clear and the newest of two as controls); `run.rs` `a_claude_run_that_attached_to_a_background_session_follows_it`, `a_claude_run_that_was_cleared_follows_the_new_session`; `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 |
| 13a | Managed Codex stale-daemon run recovery (#987; concurrent launches, project/worktree isolation, operator isolation) | `managed_runs.owner_user` (V71) uses the topology-aware `IdentityKey` owner stamp; `router.rs` resolves and authorizes the SessionStart repository before handling the untrusted run id; store `link_or_adopt_native_session` selects and links in one writer transaction and admits only the sole live, undelivered, never-linked Codex run in the exact workspace/project/checkout-cwd/owner bucket. An active supplied id must itself match every boundary; another harness, an ambiguity, or a second native session is refused | `multi_session.rs` `stale_codex_run_recovery_cannot_cross_project_owner_or_session_boundaries` (foreign owner, foreign checkout, and cross-project candidates refused; project-local controls and racing rebind), `stale_codex_run_recovery_fails_closed_on_ambiguity_and_active_mismatch` (two candidates and active foreign id refused, exact control); `workstream.rs` `prepare_stamps_the_operator_bucket_used_by_session_start_recovery` (HTTP actor stamp with foreign and legitimate controls); `router.rs` `managed_session_start_delivers_ledger_and_pending_handoff` supplies a finished stale id and proves the new run is linked and delivered | STRONG for SessionStart recovery. No candidate is selected from a run id's stale scope, another checkout, or another operator bucket; ambiguity deliberately falls back to no managed packet |
| 13b | Managed-run lease exclusivity and explicit recovery (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and otherwise refuses an `active` run inside the writer transaction (`StoreError::WorkstreamBusy`). The explicit `force_unlock` path may expire and replace that row in the same transaction only when its durable `owner_user` equals the incoming actor's attribution; different operators remain isolated. `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` normally uses `wait_out_held_lease`; `--force-unlock` instead asks once and fails immediately when refused. Neither path treats the informational `lease_owner` label as authority | `multi_session.rs` `force_unlock_replaces_only_the_same_operators_active_run` (foreign operator refused with live control, same operator succeeds, old run loses heartbeat, unattributed single-user control); hooks `workstream.rs` `force_unlock_cannot_evict_another_operator` exercises the HTTP actor boundary; CLI `run.rs` `force_unlock_asks_once_instead_of_waiting_out_the_lease`; existing controls `managed_workstream_batches_are_idempotent_and_release_the_lease`, `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over`, `interactive_launch_waits_out_a_lapsing_lease_then_proceeds`, and `ctrl_c_aborts_the_held_lease_wait_immediately` | STRONG for exclusivity. The `lease_owner` label (`host:pid`) is informational only and not unique inside ai-jail (every jailed launcher reports `ai-sandbox:<ns-pid>`), so it must never become an ownership key. A shared unattributed/root context is intentionally one operator bucket; deployments needing person-level refusal must authenticate DB users |
-| 13c | A native store shared by every project yields only this checkout's records (Antigravity `history.jsonl`) | `ai-memory-workstream/src/transcript.rs` `export_antigravity` — the conversation must first pass `locate_session_file` (UUID file name + `.db` workspace == `cwd`); every `history.jsonl` line must match both that `conversationId` and, by `same_path`, this `cwd` (a conversation resumed in another directory keeps its id but records that directory, so the id alone is not enough); an id-less opening prompt is attributed only when exactly one same-workspace candidate falls within 5 s of the `.db` creation time and no other conversation of this checkout was created within 5 s of it; slash/shell entries and oversized lines are dropped, and only records naming this conversation are reported as its losses | `transcript.rs` `antigravity_history_exports_only_this_conversations_prompts_in_this_workspace` (other conversation in this and another workspace refused; own control passes), `antigravity_history_drops_prompts_from_a_resumed_conversation_in_another_workspace` (same id, foreign workspace refused), `antigravity_export_rejects_a_conversation_from_another_workspace`, `antigravity_export_rejects_unknown_or_traversal_ids`, `antigravity_opening_prompt_is_refused_when_another_conversation_started_with_it` (an opener another conversation of this checkout could own is refused), `antigravity_opening_prompt_covers_a_single_prompt_conversation` (control), `antigravity_history_reports_no_losses_for_foreign_records`; `backfill_e2e.rs` `backfill_imports_antigravity_prompts_from_history_and_nothing_foreign` (foreign prompts absent from wiki and db) | STRONG |
+| 13c | A native store shared by every project yields only this checkout's records (Antigravity `history.jsonl` or its print-mode brain transcript) | `ai-memory-workstream/src/transcript.rs` `export_antigravity` — the conversation must first pass `locate_session_file` (UUID file name + `.db` workspace == `cwd`); every `history.jsonl` line must match both that `conversationId` and, by `same_path`, this `cwd` (a conversation resumed in another directory keeps its id but records that directory, so the id alone is not enough); an id-less opening prompt is attributed only when exactly one same-workspace candidate falls within 5 s of the `.db` creation time and no other conversation of this checkout was created within 5 s of it; slash/shell entries and oversized lines are dropped, and only records naming this conversation are reported as its losses; when history yields no prompt, `antigravity_brain_prompt_events` opens only a regular transcript canonically contained below this conversation, caps the file at 8 MiB and each line at 1 MiB, and accepts only explicit `USER_INPUT` steps | `transcript.rs` `antigravity_history_exports_only_this_conversations_prompts_in_this_workspace` (other conversation in this and another workspace refused; own control passes), `antigravity_history_drops_prompts_from_a_resumed_conversation_in_another_workspace` (same id, foreign workspace refused), `antigravity_export_rejects_a_conversation_from_another_workspace`, `antigravity_export_rejects_unknown_or_traversal_ids`, `antigravity_opening_prompt_is_refused_when_another_conversation_started_with_it` (an opener another conversation of this checkout could own is refused), `antigravity_opening_prompt_covers_a_single_prompt_conversation` (control), `antigravity_history_reports_no_losses_for_foreign_records`, `antigravity_print_mode_falls_back_to_explicit_brain_prompts`; `backfill_e2e.rs` `backfill_imports_antigravity_prompts_from_history_and_nothing_foreign` (foreign prompts absent from wiki and db) | STRONG |
| 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 otherwise never taken from a caller (only derived from already-authorized hits); the one exception, the web page-history `from`/`to` version ids, is looked up only inside the scope `routes/mod.rs` `resolve_read_scope` (`lookup_existing_scope_guarded`, `ProjectAccess::Read`) has already authorized and the requested path (`page_version_body`), so a foreign id reads as not found; incremental `recent` resolves and authorizes the requested project before decoding its scope-bound cursor; batch outcomes do not bypass the capture grant or session owner check | `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`, `observation_stream_evidence_stays_inside_a_restricted_project` (with `[retrieval] observation_stream` on, a non-grantee naming the restricted project, listing it in `scopes`, or searching their own project never sees the session page or its observation excerpt; the writer and a read-grant holder do; fails with the read check in `ProjectAuthz::authorize` neutralized), `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`, `a_reader_cannot_change_a_projects_profile_flags_at_session_start` (a Read grant's `profile_contribute`/`profile_consume` at session start neither opts the project out nor back in; Write-grant control records both; fails with the Write check forced on), `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository` (foreign raw workstream id refuses populated provenance; granted reader receives the source record and tool correlation); `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project` (also a paginated namespace URL, `/p/secrets/?page=2`), `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (19 tests) or the SQL filter (9 tests) neutralized; `routes.rs` `api_recent_incremental_rechecks_restricted_scope_on_cursor` (a valid cursor cannot bypass a revoked grant; granted control passes), `api_recent_incremental_paginates_over_120_pages_and_binds_cursor`; `mcp_stateless_http.rs` `generic_machine_client_writes_queries_and_claims_a_handoff` (real machine key, foreign scope and partial scope refused); `router.rs` `an_unauthorized_batch_item_is_consumed_rather_than_retried`, `batch_acknowledges_foreign_collision_then_commits_next_item` (refused foreign item followed by a legitimate stored item); `ai-memory-web` `history_replay.rs` `history_and_timeline_honour_grants_in_a_restricted_project` (page history in HTML and JSON and the session timeline: a non-grantee gets 403 without the body, a grantee and root get 200; bite: resolving through the unguarded `lookup_existing_scope` fails it) | 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 |
| 14aa | Companion capture privacy before persistence and delivery | `companions/ai-memory-client/src/lib.rs` `reject_sensitive`, `sanitize_external_value`, `check_body`; `src/scrub.rs` `sanitize_external_text`; relay `identity::validate`, `check_scope`, `relay::init` and `flush_locked`; importer `plan_external_conversation`, `planned_hook_event`, `truncate_utf8`, `ImportClient::post_hook_batch`; importer agentmemory routes `vault::plan`, `export::plan`, `export::replay_session`, `agentmemory::validate_id` | SDK secret-position, nested key, numeric metric (11 names plus numeric `*_tokens` counts; string values still redact), bounded schema and literal-marker tests; relay `sensitive_envelope_is_rejected_before_enqueue_with_clean_control`, `new_native_bodies_are_sanitized_before_hash_enqueue_and_exact_retry`, `unsafe_legacy_pending_is_dropped_locally_and_never_blocks_its_session`, `unsafe_legacy_native_identity_is_dropped_and_its_session_continues`, `legacy_binding_scope_spaces_are_preserved_on_delivery`; importer `sensitive_native_identity_is_refused_before_manifest_and_http_with_unicode_control`, `shared_key_sanitation_precedes_plan_manifest_transport_and_exact_retry`, `preview_and_manifest_use_scrubbed_bodies_and_digest`, `forged_body_authority_is_refused_before_transport`, `sanitized_redaction_markers_survive_utf8_byte_caps_in_bodies_and_titles`, agentmemory `page_bodies_are_redacted_before_planning`, `text_is_redacted_before_the_plan_exists` (page bodies and replayed observations), `ids_that_look_like_credentials_or_carry_controls_are_refused`. Controls preserve opaque native Unicode IDs, metric representation and untrusted provenance. An unsafe item queued before these checks never reaches the wire (body or request line); it leaves the queue as a local `dropped_policy` receipt so the rest of its session ships. Guard-removal runtime probes target the final formatted sources and restore identical hashes. | Client-side privacy only; server scope, auth, admission and capture-policy guards remain authoritative |
| 14ap | Managed-run mutation owner and current project access (finish, cancel, heartbeat, native-session link, context acceptance) | `hooks/src/workstream.rs` `authorize_run_owner` derives `ManagedRunAuthority` only from authenticated middleware extensions and checks the real run before any mutation — for finish before status/payload/segment handling; cancel, heartbeat, link and context acceptance go through the same helper, so none is a side door around finish's rule; `ReaderPool::authorize_managed_run` and `store/src/workstream.rs` `authorize_run_mutation` use a read snapshot and the existing writer transaction, respectively. Strict resolution (`project_authz.rs` `resolve_project_authz_strict`, the canonical decision with a fail-closed resolution mode, so the reserved global-scope write gate applies here too) requires the actual workspace/project pair, current user existence and current Write decision for DB principals. The private trusted-proxy policy requires authenticated User capability, a canonical identity, no DB principal and server proxy configuration; it retains legacy project admission after strict scope validation, with ownership still enforced. Human-login disable does not revoke API keys. The legacy resolver and auth middleware remain unchanged. Both writer entry paths, including finished retries, require the same authority; no cross-owner bypass | MCP `auth.rs` `owner_finish_http_refuses_another_writer_before_payload_or_segment`, `owner_finish_http_trusted_proxy_preserves_restricted_lifecycle`, `owner_finish_http_active_api_key_survives_disabled_human_login`; store `multi_session.rs` `owner_finish_store_refuses_another_writer_including_finished_retry`, `owner_finish_store_rechecks_write_after_preflight`, `owner_finish_store_refuses_a_deleted_user_after_preflight`, `owner_finish_store_proxy_policy_requires_server_and_authenticated_identity`, `owner_finish_store_raw_ids_use_the_actual_project_and_workspace`, `owner_finish_store_topology_reload_and_phase_controls`, `owner_finish_store_strict_resolution_refuses_pairing_missing_and_sql_failure`, `owner_finish_store_keeps_qualified_identity_namespaces`; hooks `workstream.rs` `owner_finish_revocation_between_preflight_and_both_writer_paths`; MCP `auth.rs` `owner_finish_http_real_auth_rungs_shared_and_project_controls`, `owner_finish_http_preserves_late_active_terminal_and_missing_phases`; hooks `workstream.rs` `run_mutation_routes_refuse_another_operator` (another operator and root under another identity refused on heartbeat/link/accept/cancel, run left active; owner admitted); store `project_authz.rs` `strict_resolution_shares_the_global_gate_and_fails_closed_on_a_gap`. Guard-neutralization recipes and results accompany the local frozen patch | SQL refusal is atomic within finish's writer transaction; a revocation after preflight can leave an unindexed raw segment. Cancel, heartbeat, link and acceptance check one read snapshot immediately before a single-row update (a run's owner never changes). A later hook event carrying `AI_MEMORY_RUN_ID` links its native session only through `link_native_session_in_scope`, which applies the SessionStart boundary (`ManagedRunBoundaryRow::admits`: the run's own project and operator) and refuses a foreign run id while the event itself is still captured (`router.rs` `hook_event_links_a_managed_run_only_from_its_operator`, `hook_event_in_another_project_does_not_link_the_run`, control `hook_event_links_a_shared_run_on_a_single_operator_server`; #1082). Shared NULL ownership, trusted-proxy project admission and late still-active finishes remain intentional |
diff --git a/docs/support-matrix.md b/docs/support-matrix.md
index 302c5abe..6561d51c 100644
--- a/docs/support-matrix.md
+++ b/docs/support-matrix.md
@@ -32,7 +32,7 @@
| Claude Desktop (Chat) | MCP-only | Uses `mcp-remote`; the ordinary Chat surface does not run lifecycle hooks. macOS, Windows, and Linux (Anthropic's Debian/Ubuntu beta, `~/.config/Claude/claude_desktop_config.json`). Cowork capture is not claimed; see the explicit boundary in [`mcp-install.md`](mcp-install.md#claude-desktop). |
| Claude Desktop (Code tab) | Supported | Local Code-tab sessions run Claude Code with the user's `~/.claude/settings.json`, so the Claude Code hooks capture them as `claude-code`; a session without a project folder lands in its own scratch-directory project. |
| OpenClaw | Supported | MCP config + native plugin lifecycle hooks; generated plugin enforces capture exclusions. |
-| Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias; per Antigravity's docs the desktop App and the IDE read the same global `~/.gemini/config/hooks.json`). `SessionStart` delivers the handoff as an `injectSteps` system message that stays in the conversation. `PreInvocation` with `invocationNum = 0` starts each user turn: the native hook records the turn's prompt from the conversation's own transcript, since no Antigravity hook payload carries it, and on builds without `SessionStart` the first turn's `PreInvocation` stands in for it, once per conversation. A `Stop` that finished the turn with nothing left running (`terminationReason` `NO_TOOL_CALL` or `model_stop`, `fullyIdle: true`) writes a turn checkpoint: the summary page and the conversation's one handoff are refreshed and the conversation stays open; a new session in the project receives that handoff once the conversation has been quiet for 10 minutes. There is still no conversation-end event: `ai-memory finalize-session --agent antigravity-cli` closes a conversation at once, hands its baton over and queues opt-in SessionEnd consolidation; an interactive session launched with `ai-memory run antigravity` is finalized automatically when it exits if the run can tie the session to itself (see [`docs/managed-workstreams.md`](managed-workstreams.md)). `ai-memory run antigravity` (aliases `antigravity-cli`, `agy`) adds managed workstream resume via `--conversation`; its conversation store is not decoded, so the ledger takes user prompts from `agy`'s `history.jsonl` (only this conversation's lines typed in this checkout) and assistant and tool steps from hook capture. Tool outputs (`run_command`, `view_file`, `list_dir`, etc.) are resolved directly from `.system_generated/steps/<stepIdx>/output.txt` during `post-tool-use` while mutation tools preserve code from arguments (#966). Skills: Antigravity reads workspace skills from `.agents/skills` and global skills from `~/.gemini/config/skills` (App and IDE) and `~/.gemini/antigravity-cli/skills` (CLI), not from `~/.agents/skills` ([Antigravity docs](https://antigravity.google/docs/skills/)); `install-skills --scope global --agent antigravity` and `setup` write the managed skills into both global roots, and `uninstall --only skills` sweeps them. |
+| Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias; per Antigravity's docs the desktop App and the IDE read the same global `~/.gemini/config/hooks.json`). `SessionStart` delivers the handoff as an `injectSteps` system message that stays in the conversation. `PreInvocation` with `invocationNum = 0` starts each user turn: the native hook records the turn's prompt from the conversation's own transcript, since no Antigravity hook payload carries it, and on builds without `SessionStart` the first turn's `PreInvocation` stands in for it, once per conversation. A `Stop` that finished the turn with nothing left running (`terminationReason` `NO_TOOL_CALL` or `model_stop`, `fullyIdle: true`) writes a turn checkpoint: the summary page and the conversation's one handoff are refreshed and the conversation stays open; a new session in the project receives that handoff once the conversation has been quiet for 10 minutes. There is still no conversation-end event: `ai-memory finalize-session --agent antigravity-cli` closes a conversation at once, hands its baton over and queues opt-in SessionEnd consolidation; an interactive session launched with `ai-memory run antigravity` is finalized automatically when it exits if the run can tie the session to itself (see [`docs/managed-workstreams.md`](managed-workstreams.md)). `ai-memory run antigravity` (aliases `antigravity-cli`, `agy`) adds managed workstream resume via `--conversation`; its conversation store is not decoded, so the ledger takes user prompts from `agy`'s `history.jsonl` (only this conversation's lines typed in this checkout), falling back to that conversation's bounded brain transcript for print mode, and takes assistant and tool steps from hook capture. Tool outputs (`run_command`, `view_file`, `list_dir`, etc.) are resolved directly from `.system_generated/steps/<stepIdx>/output.txt` during `post-tool-use` while mutation tools preserve code from arguments (#966). Skills: Antigravity reads workspace skills from `.agents/skills` and global skills from `~/.gemini/config/skills` (App and IDE) and `~/.gemini/antigravity-cli/skills` (CLI), not from `~/.agents/skills` ([Antigravity docs](https://antigravity.google/docs/skills/)); `install-skills --scope global --agent antigravity` and `setup` write the managed skills into both global roots, and `uninstall --only skills` sweeps them. |
| Grok Build CLI | Supported | MCP config (`install-mcp --client grok` → `$GROK_HOME/config.toml`, default `~/.grok/config.toml`) + lifecycle hooks (`install-hooks --agent grok` → `$GROK_HOME/hooks/ai-memory.json`, default `~/.grok/hooks/ai-memory.json`, Grok-specific hook bundle). Capture works. `SessionStart` and `UserPromptSubmit` do not accept the handoff (Grok discards that stdout). `install-hooks --agent grok --apply` and `install-skills --scope global --agent grok` also write `$GROK_HOME/rules/ai-memory-handoff.md` so the first turn calls `memory_handoff_list` through `use_tool` with the qualified catalog key `ai-memory__memory_handoff_list` (Grok reaches MCP tools only through that meta-tool) ahead of any file read, correcting `workspace`/`project` from `./.ai-memory.toml` only when that list is empty or a scope error; the first `PostToolUse` then prints `hookSpecificOutput.additionalContext` with the pending handoff and an opted-in `[briefing]`. If that rule is absent and no tool runs, recover via MCP `memory_handoff_list` then `memory_handoff_accept` with that `handoff_id`. `ai-memory run grok` adds managed workstream resume with the context packet delivered natively through `--rules`. Skills root: `.grok/skills` / `$GROK_HOME/skills` (default `~/.grok/skills`). A prompt starting with `reload context` receives a compaction recap on the next `PostToolUse` `additionalContext`, not with the prompt (see [`usage.md`](usage.md#reload-context-after-a-compaction)). |
| Swival CLI | MCP-only | `install-mcp --client swival --apply` merges a native HTTP entry into the project-root `.swival/mcp.json`, preserving sibling servers. Lifecycle and managed-workstream support are not claimed because Swival's callback contract does not expose a stable session identifier. |
| Zero | Supported | `install-mcp --client zero` (native HTTP + bearer in `~/.config/zero/config.json` when the token is passed explicitly; a token-file install gets a stdio `ai-memory mcp-bridge --no-session-id` entry instead) + lifecycle hooks via `install-hooks --agent zero --apply` (exec-form native commands in `~/.config/zero/hooks.json`, JSON payload on stdin, no shell). Capture works incl. specialist (subagent) events; no handoff injection — Zero discards `sessionStart` stdout, so recover handoffs via MCP `memory_handoff_list` then `memory_handoff_accept` with that `handoff_id`. Zero runs hooks in its sandbox, which by default denies network (loopback too) and writes outside the workspace, so events stay in the hook spool: allow `sandbox.network` and add the ai-memory data dir to `sandbox.additionalWriteRoots` in the global `~/.config/zero/config.json` (network allow covers every Zero shell command; `sessionEnd` then delivers in-process within a fixed 10-second budget, since the sandbox kills detached drainers), or run `ai-memory hook-drain` from a normal shell (see [`mcp-install.md`](mcp-install.md#zero-gitlawbzero)). |
diff --git a/docs/windows.md b/docs/windows.md
index 27b0aef2..c5314509 100644
--- a/docs/windows.md
+++ b/docs/windows.md
@@ -189,23 +189,12 @@ container, which has no host CLIs.
talks to `http://127.0.0.1:49374`, the port the container publishes on the
host; a remote-server URL wins, as with every other wrapper command.
- When the container server has auth enabled (a fresh install mints a root
- bearer into the volume), the native client needs that token or the server
- rejects these commands with `401`. The Linux/macOS wrapper copies the
- token out of the named volume for its native host commands; the
- PowerShell wrapper does not do that yet
- ([#1603](https://github.com/akitaonrails/ai-memory/issues/1603)). Until it
- does, copy the token out once yourself and point the client at the file:
-
- ```powershell
- New-Item -ItemType Directory -Force "$env:LOCALAPPDATA\ai-memory" | Out-Null
- $token = docker run --rm -v ai-memory-data:/data:ro --entrypoint /bin/sh akitaonrails/ai-memory:latest -c "cat /data/auth-tokens/default"
- Set-Content -NoNewline "$env:LOCALAPPDATA\ai-memory\server-token" $token.Trim()
- $env:AI_MEMORY_AUTH__BEARER_TOKEN_FILE = "$env:LOCALAPPDATA\ai-memory\server-token"
- ```
-
- Setting `AI_MEMORY_AUTH__BEARER_TOKEN_FILE` in your user environment covers
- every terminal. A plain `$env:AI_MEMORY_AUTH_TOKEN = "<token>"` also works
- for a single session. Refresh the copy whenever the volume's token rotates.
+ bearer into the volume), run `install-hooks --agent <agent> --apply` once.
+ The wrapper refreshes a host copy at
+ `%LOCALAPPDATA%\ai-memory\server-token`; later managed launches reuse it
+ without starting a helper container. An explicit `AI_MEMORY_AUTH_TOKEN`,
+ `AI_MEMORY_AUTH__BEARER_TOKEN_FILE`, or bind-mounted `AI_MEMORY_DATA_DIR`
+ still wins. Rerun `install-hooks` after rotating the volume token.
- A managed launch does not rewire hooks or MCP: what `install-hooks` and
`install-mcp` rendered through the container stays in place (the wrapper
sets `AI_MEMORY_RUN_AUTOWIRE=false` for the intercepted commands unless you