Skip to content

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

Rust

Merge pull request #1832 from M4ster3001/up/inbox-edit-queued-messages

AkitaOnRails81fef3a14a02
diff --cc CHANGELOG.md
index a5d7e615,72672452..74e9d1c6
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -13,365 -13,176 +13,535 @@@ version in [`docs/changelog/`](docs/cha
### Added
+- Added `ai-memory run --no-exit-prompt`, `[run] exit_prompt = false`, and
+ `AI_MEMORY_RUN_EXIT_PROMPT=false` to skip the switch/rerun menu after a
+ successful interactive session. The menu remains enabled by default (#1776).
+
+- `ai-memory merge-project --workspace <w> --from <source> --into <target>`
+ losslessly joins two project identities inside one workspace. Its default is
+ an exact dry run; `--confirm` re-stamps page history, sessions, observations,
+ handoffs, embeddings and managed workstreams in one writer transaction, then
+ removes the source project. Same-path pages get a new target version that
+ appends the source body behind an `ai-memory:merged-from` marker while both
+ prior histories remain restorable. The target frontmatter wins, a one-sided
+ expiry is removed, and the combined page is flagged stale for consolidation.
+ `restore-page --page-id <uuid>` restores either retained history even after
+ the source identity is removed. Open sessions and live managed runs refuse
+ the merge (#1645).
+- `audit-contamination` now reports projects in one workspace whose names
+ collide after Unicode compatibility decomposition, case folding, and
+ removal of non-spacing marks. Findings distinguish case from accent
+ differences and include page/session counts plus last activity (#1645).
+
+- Cross-project messages can carry an optional epistemic `nature` (`unknown`,
+ `measured`, `reported`, or `inferred`) and bounded supporting `evidence`.
+ The server refuses a `measured` send without non-empty evidence; existing
+ messages and callers remain `unknown` by default (#1428).
+
+- Added `memory_patch_page` for atomic, heading-anchored edits to an existing
+ Markdown page without re-emitting its body or metadata. It requires the
+ page's current `page_id`; section replacement additionally requires the
+ bounded SHA-256 token returned by `memory_read_page`. Missing, duplicate or
+ fenced-code headings, stale tokens, conflicting edits, failed admission and
+ concurrent writes leave the page unchanged. The typed TypeScript client
+ exposes the same contract as `pages.patch` (#1697).
+
+- Added an offline `ai-memory-eval abstention` benchmark with versioned
+ clean-room answerable, hard-negative, conflicting, partial and
+ missing-channel fixtures; raw lexical/score/density/belief signals;
+ FSR/FAR/coverage threshold sweeps with undefined denominators preserved;
+ optional reuse of pinned LongMemEval `*_abs` cases; and optional structured
+ LLM answerability through the existing QA provider path. Conflicting and
+ partial cases remain separate from binary ground truth, no threshold is
+ presented as calibrated, and production runtime behavior is unchanged.
+ The retrieval evaluator now also parses production's structured
+ `{text,citations}` answer shape instead of a stale string (#1717).
+
+- Added `[briefing] inject_on_subagent_start` to `.ai-memory.toml`. A project
+ that sets it hands each `claude-code` subagent the project brief when the
+ subagent starts: the same pinned, `_rules/` and `_slots/` brief that
+ `inject_on_session_start` adds at session start, kept within `max_chars` and
+ within the 10,000-character limit of that agent's hook context. The hook
+ reads it from a new read-only `GET /brief`, which resolves and authorizes the
+ project as `/handoff` does but never reads or claims a handoff, so a subagent
+ cannot take its parent session's baton. A server without the route answers
+ 404 and the subagent starts as before. The native hook and the
+ `hooks/claude-code` shell and PowerShell scripts deliver it, and every marker
+ parser treats the key as a settings boundary. It is off by default (#1715).
+
+- Added an optional `[query_answer] max_context_tokens` admission budget for
+ answer synthesis. It preserves retrieval hits, reports omitted or clipped
+ evidence, prioritizes known newer corrections, prefers whole snippets and
+ clips only complete trailing sentences or statements into leftover space. It
+ skips the model when no meaningful evidence fits. The default
+ remains disabled (#1684).
+
+- `GET /admin/status` and `ai-memory status --json` now carry a
+ `consolidation` block: the queue counts plus up to 20 `failed_sessions`
+ (`session_id`, `attempts`, `failed_at_us`, scrubbed `last_error`), newest
+ first. A consolidation run that gives up after its retries now has a
+ machine-readable record with the session ids needed to re-run it, instead of
+ only a journal line and the `/health` panel's count — which also resets with
+ the process. The web health panel's own view stays counts-only, and an older
+ server's status shape is unchanged (#1692).
+
+- Added the bundled `coding-v1` retrieval-evaluation corpus for offline checks
+ of decision rationale, resolved-error causes, correction evidence, and late
+ session details. It reuses the existing scorer and A/B reports; it measures
+ evidence retrieval, not semantic answer correctness or handoff behavior (#1686).
+
+- `[auto_improve.eval] builtin = "structure"` runs the eval gate's structural
+ checks in process, so the gate needs no interpreter, no scorer script inside
+ the container and no timeout to hit. It checks an H1, an upper-case
+ `TODO`/`TBD` placeholder (a hard failure), a `##` section and a list of steps
+ for `procedures/`, and text beyond the heading within 2,400 characters for
+ `_rules/` — never a section name or a wording, so the wiki's language does
+ not matter. `eval_results` records `checker_name = "builtin:structure"`.
+ `builtin` and `command` are mutually exclusive; `command` is unchanged for
+ project-specific scorers (#1638).
+
+- `ai-memory llm-test --server` probes the server's own configured provider
+ instead of building one from the caller's environment, through a new
+ root-only `POST /admin/llm-test`. The retry hint that `status` and the health
+ panel print now names it: with the server in a container or on another host
+ its keys exist only there, so the old client-side hint failed with "no API
+ key" or a provider `400` while the server was healthy. The probe runs one
+ fixed short prompt, reports provider, model, latency and the error class, and
+ scrubs the provider's message before printing it (#1639).
+
+- Added `[handoff] deliver_on_session_start = false` to `.ai-memory.toml`. A
+ project that sets it no longer gets its handoff, or the continuity notice, at
+ session start; the handoff is still created when the session ends and stays
+ open for `memory_handoff_accept`. The native hook, the shell and PowerShell
+ scripts and the generated TypeScript integrations send `handoff=0` only when
+ the value is explicitly falsy (#1621).
+
+- Added first-party Qoder CLI/IDE lifecycle and MCP support. Both installers
+ merge into `~/.qoder/settings.json`: `install-mcp --client qoder` writes a
+ sessionless stdio bridge, while `install-hooks --agent qoder` registers the
+ eight documented memory-bearing events as native commands. Session start
+ delivers a pending handoff through `hookSpecificOutput.additionalContext`,
+ prompt/tool capture uses Qoder's Claude-shaped payloads, and a missing hook
+ `cwd` falls back only to `QODER_PROJECT_DIR`. Setup detects `~/.qoder`,
+ uninstall removes both entries, and agent backups include its settings and
+ shared AGENTS-compatible skills/instructions (#1611).
+
+- Profile writes now return `digest_warning` when the selected summary,
+ abstract, or prose statement exceeds the 240-byte session-start digest
+ limit. The write still succeeds, but its author can shorten the summary
+ instead of discovering the truncation only in a later session (#1609).
+
+- Added project routing for the named profiles of a multiplexing Hermes
+ gateway. The gateway exports only the default profile's `terminal.cwd`, so
+ every other profile's events used to fall back to the gateway's own working
+ directory and all its bots landed in one project. A gateway event of a named
+ profile now routes by an `.ai-memory.toml` placed in that profile's Hermes
+ home (`~/.hermes/profiles/<name>`, or under the gateway's `HERMES_HOME`), and
+ that marker's capture exclusions and server profile apply. A profile without
+ such a marker keeps the old behavior. The profile name is checked against
+ Hermes' profile-id pattern before it is used as a path (#1597).
+
+- Added Hermes Agent hook consent to `ai-memory doctor`. Hermes runs a shell
+ hook only when that exact command is approved in the home's
+ `shell-hooks-allowlist.json`, and each profile under
+ `~/.hermes/profiles/<name>` keeps its own allowlist. A profile with the
+ ai-memory hooks in `config.yaml` but no approvals captured nothing, and its
+ gateway only logged `not allowlisted — skipped` for each event. `doctor` now
+ reads the root home and every profile, reports which ai-memory hook events
+ each one wires, and warns about every profile whose events are not
+ allowlisted (unless `hooks_auto_accept` is on), with the `hermes -p <name>
+ --accept-hooks` command that approves them. The JSON output gains a `hermes`
+ array. It never writes either file and never prints the hook commands,
+ which can embed a bearer token (#1598).
+
+- Added `AI_MEMORY_RERANK_TIMEOUT_SECS` (`rerank_timeout_secs` in
+ `config.toml`) to set the `memory_query` reranker budget, which was fixed at
+ 20 seconds. The default stays 20 and zero is rejected at startup. A hosted
+ provider behind an LLM fallback chain can spend the whole fixed budget on one
+ slow 503 before the next candidate answers, and every such query then keeps
+ its pre-rerank order. ([#1614](https://github.com/akitaonrails/ai-memory/issues/1614))
+
+- `ai-memory status` now shows the client's version next to the server's: a
+ `ai-memory X (client)` line under `ai-memory X (server)`, and `version` in
+ the JSON `client` object. In a split install (native client and hooks, the
+ server in a container or on another host) the two drift apart when only one
+ side is upgraded, and nothing showed it. When they differ in major version,
+ the text report adds a warning to upgrade the older side (#1644).
+
+### Changed
+
+- `memory_lint` now reports embedding-band pairs as
+ `similarity_candidate` instead of `contradiction`, and no longer infers that
+ a newer page supersedes an older one from timestamps alone. Explicit
+ `contradicts` edges remain `contradiction` findings (#1685).
+
+- `move-project` now refuses the **copy+purge merge** — the path taken when the
+ destination workspace already holds a project of the same name — unless
+ `--allow-lossy-merge` is passed as well as `--confirm`. That path keeps only
+ the source's latest pages and deletes the project with its sessions,
+ observations, handoffs and older page versions, which `--confirm` written for
+ "move this project" did not say; the refusal answers `409` with the counts it
+ would discard. A true-move (fresh destination, everything preserved) is
+ unchanged, and `merge-workspace`, whose command already says merge, keeps
+ working without the extra flag (#1713).
+
+- `memory_install_self_routing(compact: true)` and `ai-memory
+ install-instructions --compact` now return a block that is actually compact:
+ 2.1 KB instead of 5.9 KB, close to the 7.9 KB full block it was supposed to
+ replace. It keeps the rules a session needs without reading anything else
+ (scope selection for session-aware and static clients, managed-run resume,
+ capture, the untrusted-memory trust rule, and where rules belong) and points
+ at the installed `ai-memory-*` Agent Skills for the rest, which it already
+ required to be installed (#1672).
+
+- When the native session linked to a workstream is missing from its store,
+ an interactive `ai-memory run <harness>` now also names the newest session
+ this checkout still holds for that harness and the native selector that
+ resumes it, such as `resume <id>` for Codex. The launch still starts fresh
+ as before; running the same command again with that selector right after
+ the harness name links that session instead (#1654).
+
+- Managed-workstream startup packets now render completed tool calls and
+ results as compact provenance stubs instead of spending the 30,000-character
+ resume budget on raw command output or generated file content. Conversation,
+ checkpoints, compactions, and annotations remain inline; the complete
+ sanitized tool evidence stays searchable in the ledger (#1607).
+
+- The LLM fallback chain now logs its own events. A transient candidate
+ failure logs a warning with that candidate's provider, model, chain
+ position, error class, HTTP status and cooldown, and an info line records
+ each change of the answering candidate. Before, the chain logged nothing,
+ and callers such as the reranker named only the first candidate, so a log
+ could blame the primary for a timeout another candidate caused. Response
+ bodies are never logged (#1628).
+
+### Changed
+
+- Documented the settings that `config.default.toml` had left out, and added
+ `docs/config-properties.md`, a reference table of every key `config.toml`
+ accepts with its default, environment variable and purpose. The template now
+ describes the `llm_*` keys (including `llm_compat_strict` and
+ `[[llm_fallbacks]]`), the embedding endpoint and prefix keys,
+ `tcp_keepalive_secs`, `base_path`, `release_base_url`, `cors_allow_origins`,
+ `consolidate_on_session_end`, `backfill_on_start`, `run_autowire`,
+ `claude_true_yolo`, the `contradiction_band_*` keys, and the `[run]`,
+ `[hook_spool]`, `[handoff]`, `[maintenance]`, `[dream]`, `[retrieval]`,
+ `[search.fts]`, `[profile]` and `[[admission_webhooks]]` sections. It also
+ lists the remaining keys of `[decay]` (including `[decay.half_life_days]`),
+ `[consolidation]`, `[auto_improve]`, `[auto_scope]` and `[auth]`, and the
+ `[auto_improve.scheduler.experience_entropy_filter]` table. The new entries
+ are all commented examples, and keys with a built-in default show that
+ default. `AGENTS.md` now requires a new config key to land in both files.
+
++### Added
++
+ - Added editing for queued messages in the web inbox. Edit takes a message that
+ is still waiting out of the queue, so no agent can collect it, and opens an
+ inline editor. Saving puts the new text back at the message's original place
+ in the queue, after the usual sanitizer, size caps and `message_send`
+ admission. Discarding returns it unchanged. A held message shows as Editing,
+ with a count above the list and a way back into the editor. Editing needs
+ write access to the mailbox project and to the project the message came from,
+ and a message an agent already collected cannot be edited. Held messages use a
- new `editing` state (migration V93) that no claim path selects (#1832).
++ new `editing` state (migration V95) that no claim path selects (#1832).
+
+ - Added server-side response investigation to the project dashboard. Responses
+ can be filtered by UTC period, exact model, harness, session, turn and tool,
+ with complete pagination, filtered token totals and bounded native turn and
+ tool provenance. The context lives in extra `token_calls` columns and a
- `token_call_tools` table (migration V92). A response from an older hook keeps
++ `token_call_tools` table (migration V94). A response from an older hook keeps
+ its provenance unknown instead of guessed. Filters apply after project
+ authorization and the session-owner check and before counting, ranking and
+ pagination (#1830).
+
+ - Added version-specific knowledge evidence to the page and project views:
+ readable source links, declared contradictions, expiration context and an
+ on-page recall recomputation that reuses the original search filters (#1830).
+
+ - Added caller-aware installation states and next steps to feature guides and
+ the authenticated `/api/v1/docs/features/status` reference. They
+ separate effective settings from client facts the server cannot know, and
+ administrative settings are masked for callers without admin rights (#1830).
+
+ - Replaced the static Inbox label with live, access-filtered pending counts and
+ project links throughout the web navigation. Counts are grouped by workspace
+ and project, hide restricted projects, never consume mail, and link to the
+ pending-only mailbox of the project that has mail. Received inboxes open on
+ pending messages, with older queued requests behind collected history, and the
+ composer shows the current project explicitly (#1830).
+
+ - Added bundled product documentation to the web UI and the API. The guides and
+ release notes are compiled into the binary and served at `/web/docs`,
+ `/web/docs/changelog` and `/web/docs/{id}` (a `.md` suffix returns the
+ Markdown). They include searchable feature activation guides, per-release
+ changelogs, and authenticated `/api/v1/docs` JSON and Markdown references for
+ agents. No network access or LLM is needed, and the pages describe shipped
+ capabilities without exposing the running server's configuration or
+ credentials. The source-built Docker image now copies `CHANGELOG.md` for this
+ (#1829).
+
+ - Organized project pages into accessible tabs showing one section at a time: Overview,
+ Agents, Token usage, Sessions and Knowledge. The selected tab is kept in the
+ URL (`?tab=agents`), which keeps reload, shared links and browser history in
+ sync, and the tabs support Left, Right, Home and End. Existing
+ `#agents`-style section bookmarks still open the matching tab (#1829).
+
+ - Updated the browser inbox composer to default To project to the source
+ project and list only harnesses with captured sessions in the destination
+ workspace and project. It resets a stale recipient when a project changes,
+ and it disables sending, with an explanation, for a project that has no
+ registered agent (#1829).
+
+ - Redesigned the responsive web dashboard. It has persistent workspace
+ navigation, searchable project cards, per-agent consumption and coverage, and
+ session drilldowns that show the token totals recorded for each agent (#1828).
+
+ - Added a browser inbox at `/web/inbox`. It lists received and sent mail
+ without consuming it. A caller with write access to both the source and the
+ destination project can also queue a message for a registered harness of that
+ project. The text goes through the configured sanitizer and admission before
+ the single writer, and the browser never claims mail or starts an agent.
- Messages can now be addressed to one harness (`to_agent`, migration V91).
++ Messages can now be addressed to one harness (`to_agent`, migration V93).
+ `memory_message_pop` and `ai-memory message pop` take an optional `agent`,
+ and only that harness can claim the message, even by id. Existing shared mail
+ (`to_agent = NULL`) behaves as before. A claim from a session-aware client
+ whose routing metadata arrives before its session start was persisted is no
+ longer refused. A browser session opened with the legacy read-only login can
+ send with an explicit write token supplied for that one request and cleared
+ right after, with no browser persistence (#1828).
+
+ - Added live, deduplicated response token accounting for Claude Code and Codex.
+ Updated native hooks to send measured response usage on `post-tool-use`,
+ `stop`, `pre-compact` and `session-end`, keeping open-session totals current
+ rather than waiting for session end. Each response is stored once by its
- native identity in a new `token_calls` ledger (V90). A partial or replayed
++ native identity in a new `token_calls` ledger (V92). A partial or replayed
+ delivery raises the stored counters column by column and never adds the same
+ response twice. Live extraction reads a bounded 4 MiB transcript tail and
+ reports at most 256 responses per event. Fresh input excludes cache reads, so
+ Codex, whose reports included cached input, is normalized once during the
+ upgrade. The project page has a Token usage panel listing the fifty largest
+ captured responses. It flags contexts of at least 100,000 tokens, outputs of
+ at least 20,000 tokens and responses above three times the project average.
+ Only counters, response identities and model names are kept, and project
+ authorization and session-owner filters apply before ranking or aggregation
+ (#1811).
+
+ - Added Light, Dark and System theme controls to the web UI. The choice is
+ stored in the browser and System follows the operating system. Tailwind's
+ dark variant now uses the `dark` class instead of the media query, so a
+ manual choice overrides the system setting (#1811).
+
+ - Added a memory dashboard to the read-only web home, using sanitized data:
+ projects, sessions, sanitized capture events, compiled pages, open-session
+ continuity signals and last activity. Project cards separate captured work
+ from compiled pages, so an active hook no longer looks empty just because
+ its sessions have not ended (#1803).
+
+ - Added dashboard hook-health counters for accepted, policy-dropped,
+ capacity-shed and rate-limited events. They count events since the process
+ started, and prompt, command, path and payload data is neither persisted nor
+ rendered (#1803).
+
+ - Added agent CLI attribution to the project overview to show which harnesses
+ produced a project's memory. The stats card has an "Agents" badge row with session counts per
+ harness, and each Recent Activity entry shows the harness whose session last
+ contributed evidence to that page version. Both are best effort: a page or
+ project with no session evidence shows no badge (#1803).
+
+ - Added per-session token accounting. At `session-end` the native hook (Claude Code
+ and Codex) reads the harness's own transcript and reports cumulative input,
+ output, cache-write and cache-read totals. It scans Claude Code's JSONL in
+ full and reads only the tail of Codex's rollout file, since both can reach
+ hundreds of MB. The server stores the totals with a `MAX(existing, reported)`
+ upsert, so a replayed or out-of-order delivery never lowers a total. The
+ project overview page shows a "Tokens" total in the stats card and a Sessions
+ table (agent, start, duration, events, tokens) with the 20 most recent
+ sessions. A session whose harness never reported usage, an unsupported
+ harness or an older client shows no number, never a zero (#1803).
+
+ - Added recovery of usage and closure for sessions missing a graceful
+ `session-end`, which previously stayed open without tokens. This usually
+ happens when a paid quota runs out mid-task and the operator switches agents. When a new session
+ starts in the same scope and finds one quiet for at least 15 minutes, the
+ client looks for the old session's own transcript (Claude Code and Codex),
+ reports its usage and closes it with a normal synthetic `session-end`. That
+ is safe if the old session turns out to be live, because a later real
+ `session-end` with more work runs the full end path again. A second, more
+ conservative scheduled sweep closes sessions nobody continues anywhere,
+ after 48 hours without activity in any scope, so `open_session_count` stops
+ growing. It attaches no usage and starts no consolidation, because the
+ server cannot read a client's transcript outside a live hook request (#1803).
+
### Fixed
+- Updated `libz-sys` to 1.1.31 so its build probe no longer records the build
+ environment, including possible secrets, in Cargo target artifacts
+ (RUSTSEC-2026-0418).
+- Imported every Claude transcript left behind by `/clear`, oldest first,
+ before finalizing the managed run on the newest session. Pre-clear turns now
+ retain their native-session provenance instead of disappearing from the
+ workstream ledger (#1797).
+- Kept purge-session tombstones out of automatic hollow-project cleanup, so
+ an old otherwise-empty project cannot lose replay protection immediately
+ after its session is purged (GHSA-pphw-hm98-3wh4).
+- Made Crush transcript cursors revision-aware within their one-second native
+ timestamp bucket. Same-second inserts and edits are now imported exactly
+ once, while captured recovery endpoints still exclude later revisions
+ (#1813).
+- Made TypeScript SDK capability initialization client-owned with independently
+ cancellable waits, so one caller cannot abort another caller's shared probe
+ and a later caller observes its own cancellation promptly (#1815).
+- Initialized MCP sessions in the document and agentmemory importer routes,
+ retaining validated session IDs and sending `notifications/initialized`, so
+ conditional imports work with both stateless and `--http-stateful` servers
+ (#1836).
+- Explicit `ai-memory run --fresh claude` launches now expose the previously
+ linked Claude session through `AI_MEMORY_PREVIOUS_SESSION_HISTORY`, including
+ when the two sessions live under different Claude config homes (#1789).
+- Replaced the misleading hook-refresh-only warning after a linked Codex run
+ fails to acknowledge context with a `/new`-specific ownership warning. The
+ wrapper does not adopt the unlinked thread because Codex supplies no trusted
+ parent relationship (#1788).
+
+- Sorted recent page lists by timestamp rather than RFC3339 text, so updates
+ with different fractional-second precision appear in chronological order
+ in the legacy recent API, project activity, folder previews and namespace
+ listings. Kept title-sort and equal-timestamp path tie-breaks (#1247).
+
+- Fixed `restore` replacing live data when a backup without `config.toml`
+ contains API keys that the configured pepper cannot verify. It now refuses
+ before the swap, preserving the live wiki, database and config, and names
+ the original configuration as the remedy (#1495).
+
+- Preserved explicit DOCX/PPTX line breaks and DOCX tabs in document imports
+ when XML uses paired tags, including formatted PowerPoint breaks in slides
+ and speaker notes. DOCX carriage returns now also keep adjacent text runs
+ on separate lines instead of joining their words. Paragraph tab-stop
+ definitions no longer insert spurious tabs into the extracted text (#1786).
+
+- Kept a wiki-sync server page when its repository file was recreated after
+ the sync planned a deletion. `sync --propagate-deletes --apply` now rechecks
+ local absence before sending the delete, preserves the page's baseline and
+ reports the changed file for the next sync, including with `--prefer repo`
+ (#1787).
+- Transcript imports (`backfill`, the `run` ledger, `recover`) now drop Codex
+ memory-writing agent runs by the same signals the live hook uses: the
+ checkout cwd, an event's recorded cwd, or a Codex user prompt that opens
+ with `## Memory Writing Agent`. A custom `CODEX_HOME` whose last path
+ component is not `.codex` previously reimported those sessions (#1790).
+- Admission webhook HTTP requests now follow redirects only within the
+ configured `scheme://host:port` origin (up to 10 hops) and fail on
+ cross-origin redirects without forwarding page payloads or applying foreign
+ response mutations, surfacing the redirect refusal cause in logs and
+ `reject`-policy errors (#1794).
+- `ai-memory project access` and `ai-memory project grants` now refuse empty
+ or whitespace-only `--workspace`, `--project`, and (for access) `--mode`
+ values before sending any request to the server. These commands take
+ required names and never call `resolve_scope`, so the #1774 choke point
+ did not cover them (#1791).
+- `ai-memory user grant` and `ai-memory user revoke` now refuse empty or
+ whitespace-only `--user`, `--workspace`, `--project`, and (for grant)
+ `--level` values before sending any request to the server. These commands
+ take required names and never call `resolve_scope`, so the #1774 choke
+ point did not cover them (#1792).
+- Stopped the lifecycle relay from treating an oversized HTTP response as a
+ transport failure and immediately resending its batch. A response beyond the
+ 64 KiB acknowledgement cap now retains its HTTP status, stops the flush, and
+ keeps unacknowledged events pending, including on HTTP 429 backpressure (#1799).
+- Decoded WebVTT cue character references before document-import sanitization,
+ preserving literal escaped tags and applying the existing text-size limit
+ to the decoded text. SRT extraction is unchanged (#1800).
+- Preserved native OIDC hook-spool entries when the POSIX or PowerShell script
+ bundle drained the shared queue. Scripts now leave those entries for native
+ credential resolution instead of posting them anonymously and retiring them
+ on a 2xx or 401 response; static, anonymous and legacy entries still drain
+ normally (#1801).
+- Refused backup restores with a missing or invalid gzip trailer before
+ replacing live data, even when all tar entries were readable (#1805).
+- Kept separate pre-migration archives when installations share a backup
+ destination and start in the same second, instead of overwriting an
+ existing installation's snapshot (#1806).
+- Restored the previous wiki file when `restore-page` could not commit its
+ SQLite update, including a rejected case-colliding historical path. Restores
+ now share the page writer's lock through conformance, file replacement and
+ indexing so a concurrent write to that same path cannot leave disk and
+ SQLite disagreeing (#1807).
+- Kept concurrent page edits current during opt-in cold-cluster dedup and dream
+ merges. Each write batch now skips if a selected source version changed,
+ preserving the newer body, tier and pin along with unchanged peers (#1808).
+- Dropping the final store writer handle now finishes when its command queue
+ is full. Accepted writes still drain before the writer thread exits, including
+ when callers have cancelled their waits (#1809).
+
+- Scheduled empty-project cleanup now preserves projects that have sent or
+ received agent messages, including claimed/cancelled history, so it cannot
+ silently delete their inbox/outbox through a project cascade (#1810).
+
+- Fixed `server add` rejecting valid inline tables in `servers.toml`, including
+ token rotations and URL changes. Updates now accept the same table forms as
+ reads and removal, preserving registered roots and other profiles (#1812).
+- Kept OpenCode V1 failed tool results in the managed workstream ledger,
+ including their visible error text and error status, instead of importing
+ only the call and silently dropping the failure reason (#1814).
+- Initialized the TypeScript SDK's MCP session before the first `callTool`,
+ fixing HTTP 422 responses with `--http-stateful`. Raw calls still skip
+ schema checks, and later wrapped calls reuse the session (#1816).
+- Preserved literal reasoning tags and their contents inside structured JSON
+ strings when parsing OpenAI-compatible tolerant replies and Anthropic text
+ replies. Reasoning blocks outside the JSON are still removed, including
+ when a strict OpenAI-compatible request falls back to tolerant parsing (#1817).
+- Disabled HTTP redirect following on the native hook client (`build_client`)
+ so 3xx responses from SSO gateways, captive portals, or proxies fail closed
+ instead of following to a 200 OK login page, which dropped spooled hook events
+ and injected login HTML into agent handoff context (#1818).
+- Supported singular units (`day`, `week`, `month`) and weeks in
+ `parse_since_to_epoch` for git commit filtering during consolidation
+ bootstrapping, trimmed surrounding whitespace, rejected negative intervals,
+ and used checked arithmetic to prevent integer overflow panics (#1820).
+- Kept OpenCode 2 failed tool results in the managed workstream ledger,
+ including their visible error text and error status, instead of importing
+ only the call and recording a status-error loss (#1823).
+- Imported OpenCode 2 compaction session messages into the managed workstream
+ ledger (`summary`, or `error.message` on a failed compaction) instead of
+ dropping them with no event and no loss (#1824).
+- `memory_query(global=false)` now overrides a project's
+ `[recall] default_global` marker and uses the resolved project's normal
+ search. Previously the explicit opt-out still returned cross-project
+ `global_hits` and disabled project-only query options (#1835).
+- Honored `base_path` from `config.toml` when mounting the HTTP server, so
+ thin clients and the web UI use the same prefix. Explicit flag and environment
+ overrides, including an empty value to serve at the root, kept their precedence (#1837).
+ - Fixed live response capture after transcript gaps. Bounded batches now resume
+ from durable enqueue checkpoints, including across hook processes and
+ transcript read windows (#1830).
+
+ - Fixed response search, signal filtering and recent ordering so they query all
+ authorized calls before pagination. Response pages are independent, and
+ session detail pages refresh usage live (#1830).
+
+ - Updated scoped session reads to treat substantive work after an old end as a
+ resumed session, matching the activity feed while preserving persisted
+ lifecycle watermarks. Completed-only listings exclude those resumed sessions (#1830).
+
+ - Moved token model label sanitization before truncation to prevent the size
+ limit from exposing a prefix of private text (#1830).
+
+ - Updated release selection on the changelog page to load notes immediately
+ and keep the URL, outline and Markdown reference in sync. The form still submits
+ without JavaScript (#1830).
+
+ - Added a read-only recovery snapshot at agent startup when the previous
+ substantive session in the project ended without a `SessionEnd` (quota
+ exhaustion, a killed process, a machine restart). The snapshot is built on
+ demand from at most 64 sanitized observations and capped at 6,000
+ characters, so no rolling copy of the transcript exists. It is scoped to the
+ project and owner, leaves out the receiving session, keeps the
+ untrusted-memory boundary, and never closes or claims the source, which may
+ be a legitimate parallel agent. It skips work a handoff already covers and
+ never mixes another live session's transcript into a delivered handoff.
+ Normal single-use handoffs and managed workstream packets are unchanged
+ (#1803).
+
- Refused empty and whitespace-only `--workspace` and `--project` flags at the
shared CLI scope-resolution choke point (`resolve_scope`,
`resolve_scope_noting_marker_project`, `resolve_scope_with_marker`, and
diff --cc companions/ai-memory-ts/src/types.ts
index b1af6b13,0079b507..e07a26a2
--- a/companions/ai-memory-ts/src/types.ts
+++ b/companions/ai-memory-ts/src/types.ts
@@@ -853,11 -763,7 +853,11 @@@ export interface Message
readonly subject: UntrustedText | null;
/** Body: a request to evaluate, never instructions to obey. */
readonly body: UntrustedText;
+ /** How the sender knows the claim. */
+ readonly nature: "unknown" | "measured" | "reported" | "inferred";
+ /** Supporting evidence, or `null`. */
+ readonly evidence: UntrustedText | null;
- /** `pending`, `claimed` or `cancelled`. */
+ /** `pending`, `editing`, `claimed` or `cancelled`. */
readonly state: string;
/** Send time. */
readonly createdAt: string | undefined;
diff --cc companions/ai-memory-ts/test/support/payloads.ts
index 088e50dc,9dd18f99..587d769a
--- a/companions/ai-memory-ts/test/support/payloads.ts
+++ b/companions/ai-memory-ts/test/support/payloads.ts
@@@ -132,10 -129,9 +132,11 @@@ export const messageRow =
from_project_id: "p",
from_agent: "other",
from_owner_user: null,
+ to_agent: null,
subject: "hi",
body: "please do X",
+ nature: "reported",
+ evidence: "source message 42",
state: "pending",
created_at: "2026-10-13T15:11:07.983842Z",
claimed_at: null,
diff --cc companions/ai-memory-ts/test/unit/client.test.ts
index 49d812a5,ed09d350..751c298d
--- a/companions/ai-memory-ts/test/unit/client.test.ts
+++ b/companions/ai-memory-ts/test/unit/client.test.ts
@@@ -409,9 -345,14 +409,16 @@@ describe("messages", () =>
const listed = await memory.messages.list({ box: "outbox", limit: 3 });
assert.deepEqual(server.lastArgs(), { workspace: "demo", project: "app", box: "outbox", limit: 3 });
assert.equal(listed.messages[0]?.body, "please do X");
+ assert.equal(listed.messages[0]?.nature, "reported");
+ assert.equal(listed.messages[0]?.evidence, "source message 42");
- const popped = await memory.messages.pop({ messageId: payloads.MESSAGE_ID });
+ assert.equal(listed.messages[0]?.toAgent, null);
+ const popped = await memory.messages.pop({ messageId: payloads.MESSAGE_ID, agent: "codex" });
+ assert.deepEqual(server.lastArgs(), {
+ workspace: "demo",
+ project: "app",
+ message_id: payloads.MESSAGE_ID,
+ agent: "codex",
+ });
assert.equal(popped.message?.state, "claimed");
assert.equal(popped.securityNotice, "UNTRUSTED");
const cancelled = await memory.messages.cancel();
@@@ -708,16 -578,9 +715,16 @@@ describe("wire names", () =>
memory.handoffs.list({ anyOwner: true, limit: 1 }),
memory.handoffs.accept({ handoffId: "h", anyOwner: true }),
memory.handoffs.cancel({ handoffId: "h", anyOwner: true }),
- memory.messages.send({ to: OTHER, from: SCOPE, body: "b", subject: "s" }),
+ memory.messages.send({
+ to: OTHER,
+ from: SCOPE,
+ body: "b",
+ subject: "s",
+ nature: "measured",
+ evidence: "test:1",
+ }),
memory.messages.list({ box: "inbox", limit: 1 }),
- memory.messages.pop({ messageId: "m" }),
+ memory.messages.pop({ messageId: "m", agent: "codex" }),
memory.messages.cancel({ messageId: "m" }),
];
await Promise.allSettled(calls);
diff --cc crates/ai-memory-cli/src/commands/run.rs
index ac96d3aa,95fdaa83..321018f9
--- a/crates/ai-memory-cli/src/commands/run.rs
+++ b/crates/ai-memory-cli/src/commands/run.rs
@@@ -16,17 -16,17 +16,17 @@@ use ai_memory_workstream::
AmbiguousNativeSession, ClaudeContinuation, ExportedTranscript, FORWARDED_ENV_NAMES,
JailChecklistItem, JailHostFacts, JailSupport, JailToggleChoice, JailToggleKind, LaunchMode,
LaunchPlan, LaunchRoots, ManagedHarness, NativeSessionCandidate, ai_jail_support,
- allows_native_session_adoption, apply_claude_true_yolo, apply_yolo, build_ai_jail_invocation,
- build_launch_plan, build_launch_plan_with_env_lookup, claude_continued_session,
- claude_live_background_attach_id, claude_session_ran_in_background, clean_path,
- crush_global_config_path, discover_native_session, export_transcript,
- has_native_session_selector, inside_ai_jail_here, inspect_repository,
- is_interactive_session_invocation, jail_checklist, jail_toggle, kiro_explicit_session_id,
- kiro_harness_from_source_cursor, kiro_selects_non_default_engine, kiro_selects_v2_engine,
- kiro_selects_v3_engine, kiro_v3_resume_uses_default_store, list_native_sessions,
- marked_choices, native_session_exists, native_session_in_checkout, native_store_root,
- omp_profile_flag, omp_profile_flag_env, parse_jail_toggles, store_override_vars,
- transcript_baseline, transcript_interval_digests, usable_ai_jail_here,
+ allows_native_session_adoption, apply_claude_true_yolo, apply_jail_process_isolation,
+ apply_yolo, build_ai_jail_invocation, build_launch_plan, build_launch_plan_with_env_lookup,
- claude_continued_sessions, claude_live_background_attach_id, claude_session_ran_in_background,
- clean_path, crush_global_config_path, discover_native_session, export_transcript,
- has_native_session_selector, inside_ai_jail_here, inspect_repository,
- is_interactive_session_invocation, jail_checklist, jail_toggle, kiro_explicit_session_id,
- kiro_harness_from_source_cursor, kiro_selects_non_default_engine, kiro_selects_v2_engine,
- kiro_selects_v3_engine, kiro_v3_resume_uses_default_store, list_native_sessions,
- marked_choices, native_session_exists, native_session_in_checkout, native_store_root,
- omp_profile_flag, omp_profile_flag_env, parse_jail_toggles, store_override_vars,
- transcript_baseline, transcript_interval_digests, usable_ai_jail_here,
++ claude_continued_session, claude_continued_sessions, claude_live_background_attach_id,
++ claude_session_ran_in_background, clean_path, crush_global_config_path,
++ discover_native_session, export_transcript, has_native_session_selector, inside_ai_jail_here,
++ inspect_repository, is_interactive_session_invocation, jail_checklist, jail_toggle,
++ kiro_explicit_session_id, kiro_harness_from_source_cursor, kiro_selects_non_default_engine,
++ kiro_selects_v2_engine, kiro_selects_v3_engine, kiro_v3_resume_uses_default_store,
++ list_native_sessions, marked_choices, native_session_exists, native_session_in_checkout,
++ native_store_root, omp_profile_flag, omp_profile_flag_env, parse_jail_toggles,
++ store_override_vars, transcript_baseline, transcript_interval_digests, usable_ai_jail_here,
wait_for_transcript_flush,
};
use anyhow::{Context as _, Result, anyhow};
diff --cc crates/ai-memory-cli/src/commands/serve.rs
index f24a063f,f0039688..e58ecfd6
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@@ -1875,8 -1874,8 +1876,8 @@@ pub async fn run(config: &Config, args
"AI_MEMORY_WEB_SLUG is not a safe path prefix; serving the web UI at the base-path root instead",
);
}
- let base_href = web_base_href(&args.base_path, &args.web_slug);
+ let base_href = web_base_href(configured_base_path, &args.web_slug);
- let web = split_web_routers(
+ let web = split_web_routers_with_metrics(
args.enable_web,
store.reader.clone(),
wiki.clone(),
diff --cc crates/ai-memory-core/src/lib.rs
index 89daf192,6db8c90a..3ef671a0
--- a/crates/ai-memory-core/src/lib.rs
+++ b/crates/ai-memory-core/src/lib.rs
@@@ -79,10 -79,13 +79,13 @@@ pub use ids::
portable_page_key,
};
pub use message::{
- AgentMessage, MessageBox, MessageClaim, MessageOrigin, MessageState, NewAgentMessage,
- UNTRUSTED_MESSAGE_NOTICE,
+ AgentMessage, MessageBox, MessageClaim, MessageNature, MessageOrigin, MessageState,
+ NewAgentMessage, UNTRUSTED_MESSAGE_NOTICE,
};
- pub use observation::{NewObservation, NewSession, Observation, ObservationKind};
+ pub use observation::{
+ NewObservation, NewSession, NewSessionUsage, Observation, ObservationKind, TokenCall,
+ TokenCallContext, TokenToolRef, TokenToolRelation,
+ };
pub use page::{
FeedbackKind, LinkTarget, MAX_ENTITIES_PER_PAGE, MAX_ENTITY_LEN, NewPage, Page, PageEvidence,
PageEvidenceKind, Relation, Tier, frontmatter_entity_names, normalize_entities,
diff --cc crates/ai-memory-core/src/message.rs
index 5eb86436,0e81eeff..812f79b4
--- a/crates/ai-memory-core/src/message.rs
+++ b/crates/ai-memory-core/src/message.rs
@@@ -42,56 -42,11 +42,59 @@@ pub enum MessageState
Claimed,
/// The sender retracted it before it was popped.
Cancelled,
+ /// The sender took it out of the queue to edit it. It cannot be popped
+ /// until the edit is saved or released, which returns it to `Pending`.
+ Editing,
}
+/// How the sender knows the claim carried by a cross-project message.
+#[derive(
+ Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
+)]
+#[serde(rename_all = "snake_case")]
+pub enum MessageNature {
+ /// The sender did not classify the claim. This is the compatibility
+ /// default for messages created before epistemic tags existed.
+ #[default]
+ Unknown,
+ /// The sender directly measured or verified the claim. Evidence is
+ /// required when sending this value.
+ Measured,
+ /// The sender is relaying a claim learned from another source.
+ Reported,
+ /// The sender derived the claim from available evidence.
+ Inferred,
+}
+
+impl MessageNature {
+ /// Canonical wire and storage string.
+ #[must_use]
+ pub const fn as_str(self) -> &'static str {
+ match self {
+ Self::Unknown => "unknown",
+ Self::Measured => "measured",
+ Self::Reported => "reported",
+ Self::Inferred => "inferred",
+ }
+ }
+}
+
+impl std::str::FromStr for MessageNature {
+ type Err = crate::MemoryError;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ match s {
+ "unknown" => Ok(Self::Unknown),
+ "measured" => Ok(Self::Measured),
+ "reported" => Ok(Self::Reported),
+ "inferred" => Ok(Self::Inferred),
+ other => Err(crate::MemoryError::MalformedRecord(format!(
+ "unknown message nature: {other}"
+ ))),
+ }
+ }
+}
+
impl MessageState {
/// Canonical wire string.
#[must_use]
diff --cc crates/ai-memory-hooks/src/router.rs
index 6a06b978,72e2291f..7ad34bf1
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@@ -16,14 -16,16 +16,14 @@@ use ai_memory_consolidate::Consolidator
use ai_memory_core::{
ActiveProject, ActorKey, AgentKind, DEFAULT_WORKSPACE_NAME, Handoff, IdentityKey,
MANAGED_WORKSTREAM_PACKET_MARKER, ManagedRunId, MidSessionRouting, NewHandoff, NewObservation,
- NewSession, PageId, PagePath, ProjectId, Sanitized, Sanitizer, SessionId, WorkspaceId,
- WorkstreamEvent, WorkstreamEventKind, truncate_utf8_bytes,
+ NewSession, NewSessionUsage, ObservationKind, PageId, PagePath, ProjectId, Sanitized,
- Sanitizer, SessionId, WorkspaceId, WorkstreamEvent, truncate_utf8_bytes,
++ Sanitizer, SessionId, WorkspaceId, WorkstreamEvent, WorkstreamEventKind, truncate_utf8_bytes,
};
use ai_memory_store::{
- HookSessionAdmission, IngestObservationOutcome, StoreError, WriterHandle,
- lookup_existing_workspace,
+ HookSessionAdmission, IngestObservationOutcome, InterruptedSessionCandidate, ObservationOrder,
+ ObservationPage, ObservationRecord, StoreError, WriterHandle, lookup_existing_workspace,
};
-#[cfg(test)]
-use ai_memory_core::WorkstreamEventKind;
use ai_memory_wiki::{AdmissionContext, AdmissionOp, Wiki};
use axum::body::{Body, to_bytes};
use axum::extract::{Query, State};
@@@ -5734,10 -6021,9 +6116,11 @@@ pub(crate) mod tests
from_owner_user: None,
to_workspace_id: state.workspace_id,
to_project_id: state.project_id,
+ to_agent: None,
subject: Some(format!("subject {i}")),
body: format!("please do task {i}"),
+ nature: ai_memory_core::MessageNature::Unknown,
+ evidence: None,
})
.await
.unwrap();
diff --cc crates/ai-memory-mcp/src/admin.rs
index 2dd9abd5,568ae582..30e12131
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@@ -3583,10 -3411,9 +3583,11 @@@ async fn handle_send_message
from_owner_user,
to_workspace_id: to_ws,
to_project_id: to_proj,
+ to_agent: None,
subject,
body,
+ nature: req.nature,
+ evidence,
};
// Match MCP's crossing-point admission and post-commit observer ordering.
@@@ -10058,10 -9563,9 +10069,11 @@@ mod tests
from_owner_user: None,
to_workspace_id: ws,
to_project_id: recipient,
+ to_agent: None,
subject: None,
body: "fixture".into(),
+ nature: ai_memory_core::MessageNature::Unknown,
+ evidence: None,
})
.await
.unwrap();
diff --cc crates/ai-memory-mcp/src/server.rs
index 939b7333,61a3e42e..e4805ea5
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@@ -6505,10 -6227,9 +6511,11 @@@ impl AiMemoryServer
from_owner_user,
to_workspace_id: to_ws,
to_project_id: to_proj,
+ to_agent: None,
subject,
body,
+ nature: args.nature,
+ evidence,
};
// Admission is asked at the crossing point (the recipient scope): a
// per-operator webhook can refuse prompt-derived text entering another
diff --cc crates/ai-memory-store/migrations/V91__session_usage.sql
index 00000000,3465673e..3465673e
mode 000000,100644..100644
--- a/crates/ai-memory-store/migrations/V91__session_usage.sql
+++ b/crates/ai-memory-store/migrations/V91__session_usage.sql
diff --cc crates/ai-memory-store/migrations/V92__token_calls.sql
index 00000000,37ede306..37ede306
mode 000000,100644..100644
--- a/crates/ai-memory-store/migrations/V92__token_calls.sql
+++ b/crates/ai-memory-store/migrations/V92__token_calls.sql
diff --cc crates/ai-memory-store/migrations/V93__addressed_messages.sql
index 00000000,af698ff8..af698ff8
mode 000000,100644..100644
--- a/crates/ai-memory-store/migrations/V93__addressed_messages.sql
+++ b/crates/ai-memory-store/migrations/V93__addressed_messages.sql
diff --cc crates/ai-memory-store/migrations/V94__token_call_context.sql
index 00000000,9a58f9f8..9a58f9f8
mode 000000,100644..100644
--- a/crates/ai-memory-store/migrations/V94__token_call_context.sql
+++ b/crates/ai-memory-store/migrations/V94__token_call_context.sql
diff --cc crates/ai-memory-store/migrations/V95__message_editing_state.sql
index 00000000,95ebad41..22d9d3b5
mode 000000,100644..100644
--- a/crates/ai-memory-store/migrations/V95__message_editing_state.sql
+++ b/crates/ai-memory-store/migrations/V95__message_editing_state.sql
@@@ -1,0 -1,64 +1,67 @@@
+ -- Let a queued message be held out of the queue while its sender edits it.
+ --
+ -- `agent_messages.state` gains 'editing'. The claim path only ever selects
+ -- `state = 'pending'`, so a held message cannot be popped by any harness until
+ -- the edit is saved or released, which sets it back to 'pending'. The row keeps
+ -- its id and its place in the queue (`created_at`), and `edited_at` records
+ -- when the text last changed.
+ --
+ -- SQLite cannot alter a CHECK constraint, so the table is rebuilt. `Store::open`
+ -- turns foreign keys off around the migration runner (a PRAGMA inside
+ -- refinery's transaction is ignored), which keeps the DROP from cascading.
--- Nothing references `agent_messages`. V64 and V91 created its indexes.
++-- Nothing references `agent_messages`. V64 and V93 created its indexes.
+
+ CREATE TABLE agent_messages_new (
+ id BLOB PRIMARY KEY NOT NULL,
+ from_workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
+ from_project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
+ from_agent TEXT NOT NULL,
+ from_session_id BLOB REFERENCES sessions(id) ON DELETE SET NULL,
+ from_owner_user TEXT,
+ to_workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
+ to_project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
+ subject TEXT,
+ body TEXT NOT NULL,
+ state TEXT NOT NULL DEFAULT 'pending'
+ CHECK (state IN ('pending','claimed','cancelled','editing')),
+ created_at INTEGER NOT NULL,
+ claimed_at INTEGER,
+ claimed_by_session BLOB REFERENCES sessions(id) ON DELETE SET NULL,
+ claimed_by_agent TEXT,
+ claimed_by_user TEXT,
++ nature TEXT
++ CHECK (nature IS NULL OR nature IN ('unknown','measured','reported','inferred')),
++ evidence TEXT,
+ to_agent TEXT,
+ edited_at INTEGER,
+ FOREIGN KEY (from_session_id) REFERENCES sessions(id) ON DELETE SET NULL,
+ FOREIGN KEY (claimed_by_session) REFERENCES sessions(id) ON DELETE SET NULL
+ );
+
+ INSERT INTO agent_messages_new (
+ id, from_workspace_id, from_project_id, from_agent, from_session_id,
+ from_owner_user, to_workspace_id, to_project_id, subject, body, state,
+ created_at, claimed_at, claimed_by_session, claimed_by_agent,
- claimed_by_user, to_agent
++ claimed_by_user, nature, evidence, to_agent
+ )
+ SELECT
+ id, from_workspace_id, from_project_id, from_agent, from_session_id,
+ from_owner_user, to_workspace_id, to_project_id, subject, body, state,
+ created_at, claimed_at, claimed_by_session, claimed_by_agent,
- claimed_by_user, to_agent
++ claimed_by_user, nature, evidence, to_agent
+ FROM agent_messages;
+
+ DROP TABLE agent_messages;
+
+ ALTER TABLE agent_messages_new RENAME TO agent_messages;
+
+ CREATE INDEX idx_agent_messages_inbox
+ ON agent_messages(to_workspace_id, to_project_id, created_at)
+ WHERE state = 'pending';
+
+ CREATE INDEX idx_agent_messages_outbox
+ ON agent_messages(from_workspace_id, from_project_id, created_at)
+ WHERE state = 'pending';
+
+ CREATE INDEX idx_messages_agent_inbox
+ ON agent_messages(to_workspace_id, to_project_id, state, to_agent, created_at);
diff --cc crates/ai-memory-store/src/api_credentials.rs
index e23c7ca4,44704269..8a1944ff
--- a/crates/ai-memory-store/src/api_credentials.rs
+++ b/crates/ai-memory-store/src/api_credentials.rs
@@@ -470,7 -470,7 +470,7 @@@ mod tests
|row| row.get(0),
)
.unwrap();
- assert_eq!(version, 90, "update the pin when adding a migration");
- assert_eq!(version, 93, "update the pin when adding a migration");
++ assert_eq!(version, 95, "update the pin when adding a migration");
let cols: i64 = conn
.query_row(
"SELECT COUNT(*) FROM pragma_table_info('users') \
@@@ -748,11 -748,10 +748,11 @@@
)
.unwrap();
assert_eq!(
-- cols, 18,
++ cols, 20,
"id, from_workspace_id, from_project_id, from_agent, from_session_id, \
from_owner_user, to_workspace_id, to_project_id, subject, body, state, \
- created_at, claimed_at, claimed_by_session, claimed_by_agent, claimed_by_user, to_agent, edited_at"
+ created_at, claimed_at, claimed_by_session, claimed_by_agent, claimed_by_user, \
- nature, evidence"
++ nature, evidence, to_agent, edited_at"
);
}
diff --cc crates/ai-memory-store/src/lib.rs
index d75b509c,bb77e30b..2775c370
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@@ -84,27 -87,27 +88,28 @@@ pub use project_authz::
RESTRICTED_PROJECT_FORBIDDEN, authorize_project, resolve_project_authz,
};
pub use reader::{
- ActivityWindow, AgentSessionCount, AuditEvent, AuditLogFilter, AutoImproveCandidateSession,
- AutoImproveParkedClaim, BriefPageBody, BriefingPage, BriefingSnapshot, ClientActivity,
- ContaminationFinding, ContaminationReport, ContaminationSummary, ContradictionEdge,
- CrossProjectEdge, DecayCandidate, DecayTombstone, DerivedIndexStatus, EmbeddingTripleCount,
- FTS_HIGHLIGHT_END, FTS_HIGHLIGHT_START, FeedbackFinding, GraphVia, HealthDetail, HealthPage,
- HybridSearch, HybridSearchOutcome, IdleOpenSession, InboxCount, InboxEntry,
- InterruptedSessionCandidate, 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, ProjectCoordinateStatus,
- ProjectSummary, RELATED_WALK_MAX_DEPTH, RELATED_WALK_MAX_NODES, ReaderPool,
- ReindexTargetStatus, RelatedNode, RelatedPage, RrfContributions, SESSION_LINE_TITLE_CHARS,
- SUBSTANTIVE_OBSERVATION_KIND_SQL, ScopeRow, SearchExplain, SessionActivity,
- SessionConsolidationQueue, SessionConsolidationSummary, SessionDependentRows,
+ ActivityWindow, AgentSessionCount, AnswerEvidenceMeta, AuditEvent, AuditLogFilter,
+ AutoImproveCandidateSession, AutoImproveParkedClaim, BriefPageBody, BriefingPage,
+ BriefingSnapshot, ClientActivity, ContaminationFinding, ContaminationReport,
+ ContaminationSummary, ContradictionEdge, CrossProjectEdge, DecayCandidate, DecayTombstone,
+ DerivedIndexStatus, EmbeddingTripleCount, FTS_HIGHLIGHT_END, FTS_HIGHLIGHT_START,
+ FeedbackFinding, GraphVia, HealthDetail, HealthPage, HybridSearch, HybridSearchOutcome,
- IdleOpenSession, InboxCount, InboxEntry, LinkGraph, LinkGraphEdge, LinkGraphNode,
- ObservationHit, ObservationOrder, ObservationPage, ObservationPageResult,
++ IdleOpenSession, InboxCount, InboxEntry, InterruptedSessionCandidate, 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,
+ ProjectCoordinateStatus, ProjectSummary, RELATED_WALK_MAX_DEPTH, RELATED_WALK_MAX_NODES,
+ ReaderPool, ReindexTargetStatus, RelatedNode, RelatedPage, RrfContributions,
+ SESSION_LINE_TITLE_CHARS, SUBSTANTIVE_OBSERVATION_KIND_SQL, ScopeRow, SearchExplain,
+ SessionActivity, SessionConsolidationQueue, SessionConsolidationSummary, SessionDependentRows,
SessionEndDisposition, SessionKindSummary, SessionLine, SessionObservationSnapshot,
- SessionPromptTitles, SessionSummary, SessionToolTitles, SettledPage, StatusCounts,
- StorageStatus, StoredEmbedding, StoredPageBody, StreamTimings, VectorQuery, WorkspaceScopeRow,
+ SessionPromptTitles, SessionSummary, SessionToolTitles, SessionUsageView, SettledPage,
+ StatusCounts, StorageStatus, StoredEmbedding, StoredPageBody, StreamTimings, TokenCallOrder,
+ TokenCallQuery, TokenCallView, TokenUsageReport, VectorQuery, WorkspaceScopeRow,
WorkspaceSummary, f32_vec_to_bytes, highlighted_snippet_html, plain_snippet,
+ project_name_fold_key,
};
pub use retrieval_tuning::{RetrievalTuning, is_session_recall_query};
pub use scope::{
diff --cc crates/ai-memory-store/src/migrations.rs
index 37d9933e,08eb594a..baa153d0
--- a/crates/ai-memory-store/src/migrations.rs
+++ b/crates/ai-memory-store/src/migrations.rs
@@@ -164,6 -164,158 +164,158 @@@ mod tests
};
use rusqlite::{Connection, params};
+ #[test]
+ fn v92_preserves_old_response_rows_and_cascades_context() {
+ let mut conn = Connection::open_in_memory().unwrap();
+ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();
+ run_to(&mut conn, 91).unwrap();
+ conn.execute_batch("INSERT INTO workspaces(id,name,created_at) VALUES(zeroblob(16),'usage',1);
+ INSERT INTO projects(id,workspace_id,name,created_at) VALUES(zeroblob(16),zeroblob(16),'usage',1);
+ INSERT INTO sessions(id,workspace_id,project_id,agent_kind,started_at) VALUES(zeroblob(16),zeroblob(16),zeroblob(16),'codex',1);
+ INSERT INTO token_calls(session_id,call_id,input_tokens,output_tokens,cache_write_tokens,cache_read_tokens,observed_at) VALUES(zeroblob(16),'old-response',70,7,0,0,123);").unwrap();
+ run(&mut conn).unwrap();
+ run(&mut conn).unwrap();
+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
+ let preserved:(u64,u64,i64,Option<String>,Option<String>,Option<i64>)=conn.query_row("SELECT input_tokens,output_tokens,observed_at,turn_id,native_response_id,response_at FROM token_calls",[],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?,r.get(5)?))).unwrap();
+ assert_eq!(preserved, (70, 7, 123, None, None, None));
+ conn.execute_batch("INSERT INTO token_call_tools(session_id,call_id,tool_id,tool_name,relation) VALUES(zeroblob(16),'old-response','tool-1','Read','requested');
+ DELETE FROM token_calls WHERE call_id='old-response';").unwrap();
+ assert_eq!(
+ conn.query_row("SELECT COUNT(*) FROM token_call_tools", [], |r| r
+ .get::<_, u64>(0))
+ .unwrap(),
+ 0
+ );
+ }
+
+ #[test]
+ fn v90_normalizes_codex_cache_once_and_preserves_claude() {
+ let mut conn = Connection::open_in_memory().unwrap();
+ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();
+ run_to(&mut conn, 89).unwrap();
+ conn.execute_batch("INSERT INTO workspaces(id,name,created_at) VALUES(zeroblob(16),'usage',1);
+ INSERT INTO projects(id,workspace_id,name,created_at) VALUES(zeroblob(16),zeroblob(16),'usage',1);
+ INSERT INTO sessions(id,workspace_id,project_id,agent_kind,started_at) VALUES(zeroblob(16),zeroblob(16),zeroblob(16),'codex',1);
+ INSERT INTO sessions(id,workspace_id,project_id,agent_kind,started_at) VALUES(x'00000000000000000000000000000001',zeroblob(16),zeroblob(16),'claude-code',1);
+ INSERT INTO session_usage(session_id,input_tokens,cache_read_tokens,updated_at) SELECT id,1000,800,1 FROM sessions;").unwrap();
+ run(&mut conn).unwrap();
+ run(&mut conn).unwrap();
+ let codex: u64 = conn
+ .query_row(
+ "SELECT input_tokens FROM session_usage WHERE session_id=zeroblob(16)",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ let claude:u64=conn.query_row("SELECT input_tokens FROM session_usage WHERE session_id=x'00000000000000000000000000000001'",[],|r|r.get(0)).unwrap();
+ assert_eq!(codex, 200);
+ assert_eq!(claude, 1000);
+ }
+
- /// V93 rebuilds `agent_messages` so a message can be held in `editing`.
++ /// V95 rebuilds `agent_messages` so a message can be held in `editing`.
+ /// Existing mail keeps its text, state, order and addressee, the three
+ /// indexes come back, and `editing` is the only value the constraint gained.
+ #[test]
+ fn v93_accepts_the_editing_state_and_keeps_existing_messages() {
+ let mut conn = Connection::open_in_memory().unwrap();
+ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();
+ run_to(&mut conn, 92).unwrap();
+ conn.execute_batch(
+ "INSERT INTO workspaces(id,name,created_at) VALUES(zeroblob(16),'mail',1);
+ INSERT INTO projects(id,workspace_id,name,created_at) VALUES(zeroblob(16),zeroblob(16),'mail',1);
+ INSERT INTO agent_messages(id,from_workspace_id,from_project_id,from_agent,to_workspace_id,to_project_id,subject,body,state,created_at,to_agent,from_owner_user)
+ VALUES(x'01000000000000000000000000000000',zeroblob(16),zeroblob(16),'other',zeroblob(16),zeroblob(16),'s','queued','pending',5,'codex','user:sender');
+ INSERT INTO agent_messages(id,from_workspace_id,from_project_id,from_agent,to_workspace_id,to_project_id,body,state,created_at,claimed_at,claimed_by_agent)
+ VALUES(x'02000000000000000000000000000000',zeroblob(16),zeroblob(16),'other',zeroblob(16),zeroblob(16),'done','claimed',6,7,'codex');",
+ )
+ .unwrap();
+ run(&mut conn).unwrap();
+ run(&mut conn).unwrap();
+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();
+
+ let rows: Vec<(String, String, i64, Option<String>)> = conn
+ .prepare(
+ "SELECT state, body, created_at, to_agent FROM agent_messages ORDER BY created_at",
+ )
+ .unwrap()
+ .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)))
+ .unwrap()
+ .collect::<Result<_, _>>()
+ .unwrap();
+ assert_eq!(
+ rows,
+ vec![
+ (
+ "pending".to_owned(),
+ "queued".to_owned(),
+ 5,
+ Some("codex".to_owned())
+ ),
+ ("claimed".to_owned(), "done".to_owned(), 6, None),
+ ]
+ );
+ conn.execute(
+ "UPDATE agent_messages SET state='editing' WHERE body='queued'",
+ [],
+ )
+ .unwrap();
+ assert!(
+ conn.execute(
+ "UPDATE agent_messages SET state='held' WHERE body='queued'",
+ [],
+ )
+ .is_err(),
+ "the state constraint must still reject unknown values"
+ );
+ let indexes: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM sqlite_master WHERE type='index' AND tbl_name='agent_messages' \
+ AND name IN ('idx_agent_messages_inbox','idx_agent_messages_outbox','idx_messages_agent_inbox')",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(indexes, 3);
+ let edited_at: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM pragma_table_info('agent_messages') WHERE name='edited_at'",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(edited_at, 1);
+ let provenance: (Option<String>, Option<String>) = conn
+ .query_row(
+ "SELECT from_owner_user, subject FROM agent_messages WHERE body='queued'",
+ [],
+ |r| Ok((r.get(0)?, r.get(1)?)),
+ )
+ .unwrap();
+ assert_eq!(
+ provenance,
+ (Some("user:sender".to_owned()), Some("s".to_owned())),
+ "the sender identity and subject survive the rebuild"
+ );
+ assert!(
+ conn.execute(
+ "UPDATE agent_messages SET from_session_id=zeroblob(16) WHERE body='queued'",
+ [],
+ )
+ .is_err(),
+ "the sender-session foreign key survives the rebuild"
+ );
+ conn.execute_batch("INSERT INTO sessions(id,workspace_id,project_id,agent_kind,started_at) VALUES(zeroblob(16),zeroblob(16),zeroblob(16),'codex',1);
+ UPDATE agent_messages SET from_session_id=zeroblob(16) WHERE body='queued';").unwrap();
+ let dangling: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM pragma_foreign_key_check('agent_messages')",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(dangling, 0);
+ }
+
/// A store migrated by a newer build (an applied version above anything
/// this binary embeds) must fail to open with the actionable
/// `DataSchemaAhead` error, not refinery's raw "missing from the
diff --cc crates/ai-memory-store/src/ops.rs
index 86ac8cd7,9731bf5c..918cf850
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@@ -5641,6 -5762,9 +5784,9 @@@ pub(crate) fn row_to_agent_message
id: MessageId::from_slice(&id_bytes)?,
to_workspace_id: WorkspaceId::from_slice(&to_ws)?,
to_project_id: ProjectId::from_slice(&to_pj)?,
+ to_agent: row
- .get::<_, Option<String>>(12)?
++ .get::<_, Option<String>>(14)?
+ .map(|s| AgentKind::from_wire(&s)),
origin: MessageOrigin {
from_workspace_id: WorkspaceId::from_slice(&from_ws)?,
from_project_id: ProjectId::from_slice(&from_pj)?,
@@@ -5676,7 -5794,7 +5822,7 @@@
/// The stable column list backing [`row_to_agent_message`].
pub(crate) const MESSAGE_COLUMNS: &str = "id, from_workspace_id, from_project_id, from_agent, \
from_owner_user, to_workspace_id, to_project_id, subject, body, state, created_at, claimed_at, \
- nature, evidence";
- to_agent";
++ nature, evidence, to_agent";
/// Send a message into a recipient project's inbox.
///
@@@ -5721,8 -5829,8 +5867,8 @@@ pub fn insert_message(conn: &mut Connec
"INSERT INTO agent_messages ( \
id, from_workspace_id, from_project_id, from_agent, from_session_id, \
from_owner_user, to_workspace_id, to_project_id, subject, body, state, created_at, \
- nature, evidence \
- ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, 'pending', ?11, ?12, ?13)",
- to_agent \
- ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, 'pending', ?11, ?12)",
++ nature, evidence, to_agent \
++ ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, 'pending', ?11, ?12, ?13, ?14)",
params![
id.as_bytes(),
m.from_workspace_id.as_bytes(),
@@@ -5735,8 -5843,7 +5881,9 @@@
subject,
body,
now,
+ m.nature.as_str(),
+ evidence,
+ m.to_agent.map(|a| a.as_str()),
],
)?;
// Audit records the lifecycle event under the recipient scope (the crossing
@@@ -16981,158 -16549,6 +17286,161 @@@ pub(crate) mod tests
assert!(sweep_hollow_projects(&mut conn, 7).unwrap().is_empty());
}
+ #[test]
+ fn sweep_hollow_projects_preserves_purged_session_tombstones() {
+ use ai_memory_core::{AgentKind, NewSession, SessionId};
+
+ let (_tmp, mut conn, workspace_id, _scratch) = fresh_db();
+ let project_id = get_or_create_project(&mut conn, &workspace_id, "purged", None).unwrap();
+ conn.execute(
+ "UPDATE projects SET created_at = created_at - ?1 WHERE id = ?2",
+ params![8 * 24 * 60 * 60 * 1_000_000_i64, project_id.as_bytes()],
+ )
+ .unwrap();
+ let session_id = SessionId::new();
+ begin_session(
+ &mut conn,
+ &NewSession {
+ occurred_at: None,
+ id: session_id,
+ workspace_id,
+ project_id,
+ agent_kind: AgentKind::Codex,
+ cwd: None,
+ actor_user: None,
+ },
+ )
+ .unwrap();
+ purge_session(
+ &mut conn,
+ workspace_id,
+ project_id,
+ session_id,
+ None,
+ Compaction::Skip,
+ PurgeMode::Commit,
+ )
+ .unwrap();
+
+ assert!(sweep_hollow_projects(&mut conn, 7).unwrap().is_empty());
+ let retained: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM purged_sessions WHERE session_id = ?1 AND project_id = ?2",
+ params![session_id.as_bytes(), project_id.as_bytes()],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(retained, 1, "purge replay protection must outlive cleanup");
+ }
+
+ #[test]
+ fn sweep_hollow_projects_preserves_message_senders_recipients_and_history() {
+ let mut failures = Vec::new();
+ for state in ["pending", "claimed", "cancelled"] {
+ for old_sender in [true, false] {
+ let (_tmp, mut conn, from_ws, _) = fresh_db();
+ let to_ws = get_or_create_workspace(&mut conn, "recipient-workspace").unwrap();
+ let from = get_or_create_project(&mut conn, &from_ws, "sender", None).unwrap();
+ let to = get_or_create_project(&mut conn, &to_ws, "recipient", None).unwrap();
+ let empty = get_or_create_project(&mut conn, &from_ws, "empty", None).unwrap();
+ let old = if old_sender { from } else { to };
+ conn.execute(
+ "UPDATE projects SET created_at = created_at - ?1 WHERE id IN (?2, ?3)",
+ params![
+ 8 * 24 * 60 * 60 * 1_000_000_i64,
+ old.as_bytes(),
+ empty.as_bytes()
+ ],
+ )
+ .unwrap();
+
+ // The message is fresh even though one project is old. No
+ // lifecycle session or page otherwise protects either end.
+ let id = insert_message(
+ &mut conn,
+ &NewAgentMessage {
+ from_workspace_id: from_ws,
+ from_project_id: from,
+ from_agent: AgentKind::Codex,
+ from_session_id: None,
+ from_owner_user: None,
+ to_workspace_id: to_ws,
+ to_project_id: to,
+ subject: Some("Retained message".into()),
+ body: "Keep the request and its history".into(),
++ nature: ai_memory_core::MessageNature::Unknown,
++ evidence: None,
++ to_agent: None,
+ },
+ )
+ .unwrap();
+ match state {
+ "claimed" => {
+ let claimed = pop_message(
+ &mut conn,
+ &MessageClaim {
+ workspace_id: to_ws,
+ project_id: to,
+ claiming_agent: AgentKind::Codex,
+ claiming_session: None,
+ claiming_user: None,
+ },
+ Some(id),
+ )
+ .unwrap();
+ assert!(claimed.is_some());
+ }
+ "cancelled" => {
+ assert_eq!(
+ cancel_messages(&mut conn, &from_ws, &from, Some(id)).unwrap(),
+ 1
+ );
+ }
+ _ => {}
+ }
+
+ let deleted = sweep_hollow_projects(&mut conn, 7).unwrap();
+ let empty_count: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM projects WHERE id = ?1",
+ [empty.as_bytes()],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(
+ empty_count, 0,
+ "genuinely hollow projects must still be removed"
+ );
+ let endpoints: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM projects WHERE id IN (?1, ?2)",
+ params![from.as_bytes(), to.as_bytes()],
+ |r| r.get(0),
+ )
+ .unwrap();
+ let retained: Option<(String, String)> = conn
+ .query_row(
+ "SELECT state, body FROM agent_messages WHERE id = ?1",
+ [id.as_bytes()],
+ |r| Ok((r.get(0)?, r.get(1)?)),
+ )
+ .optional()
+ .unwrap();
+ if deleted != ["empty"]
+ || endpoints != 2
+ || retained != Some((state.into(), "Keep the request and its history".into()))
+ {
+ failures.push(format!("{state}, old_sender={old_sender}: deleted={deleted:?}, endpoints={endpoints}, message={retained:?}"));
+ }
+ assert!(sweep_hollow_projects(&mut conn, 7).unwrap().is_empty());
+ }
+ }
+ assert!(
+ failures.is_empty(),
+ "message-bearing projects were swept: {failures:#?}"
+ );
+ }
+
/// Insert a `sessions` row using only the columns that have existed since
/// V01, for fixtures that deliberately stop at an older schema version.
/// The production `begin_session` writes whatever columns the CURRENT
@@@ -19440,4 -18856,212 +19748,212 @@@
);
assert_eq!(audit_row_for(&conn, "release_lifecycle_only_handoff").0, 1);
}
+
+ /// Token-cost visibility: the harness reports cumulative totals,
+ /// not deltas, so a later report must only ever raise a stored column,
+ /// never lower it — a replayed or out-of-order hook delivery is
+ /// therefore harmless. `model` only updates when the new report
+ /// actually names one.
+ #[test]
+ fn upsert_session_usage_keeps_the_max_per_column() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let session = hook_session(SessionId::new(), ws, proj, None);
+ begin_session(&mut conn, &session).unwrap();
+
+ upsert_session_usage(
+ &conn,
+ &NewSessionUsage {
+ session_id: session.id,
+ input_tokens: 100,
+ output_tokens: 50,
+ cache_write_tokens: 10,
+ cache_read_tokens: 5,
+ model: Some("claude-sonnet-5".into()),
+ },
+ )
+ .unwrap();
+
+ // A stale, smaller report (e.g. a retried older delivery) must not
+ // lower any column, and an absent model must not blank the stored one.
+ upsert_session_usage(
+ &conn,
+ &NewSessionUsage {
+ session_id: session.id,
+ input_tokens: 10,
+ output_tokens: 5,
+ cache_write_tokens: 1,
+ cache_read_tokens: 0,
+ model: None,
+ },
+ )
+ .unwrap();
+
+ let (input, output, cache_write, cache_read, model): (i64, i64, i64, i64, String) = conn
+ .query_row(
+ "SELECT input_tokens, output_tokens, cache_write_tokens, cache_read_tokens, model \
+ FROM session_usage WHERE session_id = ?1",
+ params![session.id.as_bytes()],
+ |row| {
+ Ok((
+ row.get(0)?,
+ row.get(1)?,
+ row.get(2)?,
+ row.get(3)?,
+ row.get(4)?,
+ ))
+ },
+ )
+ .unwrap();
+ assert_eq!((input, output, cache_write, cache_read), (100, 50, 10, 5));
+ assert_eq!(model, "claude-sonnet-5");
+
+ // A genuinely larger later report raises every column and updates
+ // the model.
+ upsert_session_usage(
+ &conn,
+ &NewSessionUsage {
+ session_id: session.id,
+ input_tokens: 200,
+ output_tokens: 80,
+ cache_write_tokens: 20,
+ cache_read_tokens: 15,
+ model: Some("claude-opus-5-5".into()),
+ },
+ )
+ .unwrap();
+ let (input, model): (i64, String) = conn
+ .query_row(
+ "SELECT input_tokens, model FROM session_usage WHERE session_id = ?1",
+ params![session.id.as_bytes()],
+ |row| Ok((row.get(0)?, row.get(1)?)),
+ )
+ .unwrap();
+ assert_eq!(input, 200);
+ assert_eq!(model, "claude-opus-5-5");
+ }
+
- /// `session_usage` cascades with its session (V89), same as
++ /// `session_usage` cascades with its session (V91), same as
+ /// `page_evidence` does with its page (V63) — usage never outlives the
+ /// session it measures.
+ #[test]
+ fn upsert_session_usage_cascades_on_session_purge() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let session = hook_session(SessionId::new(), ws, proj, None);
+ begin_session(&mut conn, &session).unwrap();
+ upsert_session_usage(
+ &conn,
+ &NewSessionUsage {
+ session_id: session.id,
+ input_tokens: 1,
+ output_tokens: 1,
+ cache_write_tokens: 0,
+ cache_read_tokens: 0,
+ model: None,
+ },
+ )
+ .unwrap();
+
+ purge_session(
+ &mut conn,
+ ws,
+ proj,
+ session.id,
+ None,
+ Compaction::Skip,
+ PurgeMode::Commit,
+ )
+ .unwrap();
+
+ let rows: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM session_usage WHERE session_id = ?1",
+ params![session.id.as_bytes()],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(rows, 0);
+ }
+
+ /// Safety-net sweep: only a session quiet since before
+ /// the cutoff gets closed, an already-ended session is left untouched,
+ /// and no consolidation is ever implied (`summary_page_id` stays NULL).
+ #[test]
+ fn close_abandoned_sessions_only_closes_stale_open_sessions() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let now = Timestamp::now().as_microsecond();
+ let one_day_us = 24 * 60 * 60 * 1_000_000;
+
+ let stale = hook_session(SessionId::new(), ws, proj, None);
+ begin_session(&mut conn, &stale).unwrap();
+ conn.execute(
+ "UPDATE sessions SET started_at = ?1 WHERE id = ?2",
+ params![now - 3 * one_day_us, stale.id.as_bytes()],
+ )
+ .unwrap();
+
+ let fresh = hook_session(SessionId::new(), ws, proj, None);
+ begin_session(&mut conn, &fresh).unwrap();
+ conn.execute(
+ "UPDATE sessions SET started_at = ?1 WHERE id = ?2",
+ params![now - one_day_us / 2, fresh.id.as_bytes()],
+ )
+ .unwrap();
+
+ let already_ended = hook_session(SessionId::new(), ws, proj, None);
+ begin_session(&mut conn, &already_ended).unwrap();
+ conn.execute(
+ "UPDATE sessions SET started_at = ?1 WHERE id = ?2",
+ params![now - 3 * one_day_us, already_ended.id.as_bytes()],
+ )
+ .unwrap();
+ end_session(&mut conn, &already_ended.id, None).unwrap();
+ let already_ended_at_before: i64 = conn
+ .query_row(
+ "SELECT ended_at FROM sessions WHERE id = ?1",
+ params![already_ended.id.as_bytes()],
+ |row| row.get(0),
+ )
+ .unwrap();
+
+ let cutoff_us = now - one_day_us;
+ let closed = close_abandoned_sessions(&conn, cutoff_us).unwrap();
+ assert_eq!(closed, 1, "only the stale open session must close");
+
+ let (ended_at, summary_page_id): (Option<i64>, Option<Vec<u8>>) = conn
+ .query_row(
+ "SELECT ended_at, summary_page_id FROM sessions WHERE id = ?1",
+ params![stale.id.as_bytes()],
+ |row| Ok((row.get(0)?, row.get(1)?)),
+ )
+ .unwrap();
+ assert!(ended_at.is_some(), "stale session must be closed");
+ assert!(
+ summary_page_id.is_none(),
+ "the safety net must never imply consolidation happened"
+ );
+
+ let fresh_ended_at: Option<i64> = conn
+ .query_row(
+ "SELECT ended_at FROM sessions WHERE id = ?1",
+ params![fresh.id.as_bytes()],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert!(
+ fresh_ended_at.is_none(),
+ "a recently-started session must stay open"
+ );
+
+ let already_ended_at_after: i64 = conn
+ .query_row(
+ "SELECT ended_at FROM sessions WHERE id = ?1",
+ params![already_ended.id.as_bytes()],
+ |row| row.get(0),
+ )
+ .unwrap();
+ assert_eq!(
+ already_ended_at_after, already_ended_at_before,
+ "an already-ended session's ended_at must be left exactly as it was"
+ );
+ }
}
diff --cc crates/ai-memory-store/src/reader.rs
index 9b417193,10bed7c9..c211ef9d
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@@ -6,9 -6,9 +6,10 @@@
//! soft cap: a connection that comes back when the pool is already full
//! is simply dropped.
+use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
+ use std::str::FromStr;
use std::sync::Arc;
use ai_memory_core::{
@@@ -2252,26 -2313,10 +2389,28 @@@ pub struct ProjectSummary
/// ISO-8601 timestamp of the newest `updated_at`, or `None` when
/// the project has no pages yet.
pub last_updated: Option<String>,
+ /// Most recent capture, session start, or page update in this project.
+ pub last_activity: Option<String>,
}
+/// Counts of the records a destructive project operation would discard
+/// (#1713).
+///
+/// Used as the preflight a `move-project` refusal shows: the copy+purge merge
+/// keeps the source's latest pages only, so the rest of this is what the
+/// operator is about to delete.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
+pub struct ProjectRecordCounts {
+ /// Unexpired latest pages.
+ pub pages: u64,
+ /// Sessions recorded in the project.
+ pub sessions: u64,
+ /// Observations captured for those sessions.
+ pub observations: u64,
+ /// Handoffs created or accepted in the project.
+ pub handoffs: u64,
+}
+
/// Pending inbox depth for one recipient project. Returned by
/// [`ReaderPool::pending_inbox_counts`]; projects with nothing pending have no
/// row.
diff --cc crates/ai-memory-store/tests/suite/agent_messages.rs
index e0967001,e84fb9ec..123519fb
--- a/crates/ai-memory-store/tests/suite/agent_messages.rs
+++ b/crates/ai-memory-store/tests/suite/agent_messages.rs
@@@ -9,7 -9,7 +9,8 @@@
//! recipient inbox is bounded so a flood cannot exhaust its context/storage.
use ai_memory_core::{
- AgentKind, MessageBox, MessageClaim, MessageNature, NewAgentMessage, ProjectId, WorkspaceId,
- AgentKind, MessageBox, MessageClaim, MessageState, NewAgentMessage, ProjectId, WorkspaceId,
++ AgentKind, MessageBox, MessageClaim, MessageNature, MessageState, NewAgentMessage, ProjectId,
++ WorkspaceId,
};
use ai_memory_store::{MAX_PENDING_INBOX_MESSAGES, Store};
@@@ -124,10 -40,9 +125,11 @@@ fn message
from_owner_user: None,
to_workspace_id: to.0,
to_project_id: to.1,
+ to_agent: None,
subject: Some("need a thing".into()),
body: body.into(),
+ nature: ai_memory_core::MessageNature::Unknown,
+ evidence: None,
}
}
diff --cc crates/ai-memory-web/src/routes/inbox.rs
index 00000000,cefe01da..94278658
mode 000000,100644..100644
--- a/crates/ai-memory-web/src/routes/inbox.rs
+++ b/crates/ai-memory-web/src/routes/inbox.rs
@@@ -1,0 -1,654 +1,656 @@@
+ //! Non-consuming mailbox history and an authorized browser message composer.
+
+ use crate::{
+ state::WebState,
+ templates::{agent_label, encode_segment, humanize, project_href},
+ views::{InboxView, MessageRow, RecipientOption, ScopeOption},
+ };
+ use ai_memory_core::{
+ ActorContext, AgentKind, AuthLevel, Capability, MessageBox, MessageState, NewAgentMessage,
+ };
+ use ai_memory_store::{ProjectAccess, lookup_existing_scope_guarded};
+ use askama::Template;
+ use axum::{
+ Json,
+ extract::{Query, State},
+ http::{HeaderMap, StatusCode},
+ response::{Html, IntoResponse, Response},
+ };
+ use serde::Deserialize;
+ use std::{collections::HashMap, sync::Arc};
+
+ #[derive(Default, Deserialize)]
+ pub(crate) struct InboxQuery {
+ workspace: Option<String>,
+ project: Option<String>,
+ agent: Option<String>,
+ #[serde(default)]
+ offset: usize,
+ #[serde(default, rename = "box")]
+ mailbox: Option<String>,
+ state: Option<String>,
+ }
+
+ fn mailbox_href(workspace: &str, project: &str, outbox: bool, offset: usize) -> String {
+ format!(
+ "inbox?workspace={}&project={}&box={}&offset={offset}",
+ encode_segment(workspace),
+ encode_segment(project),
+ if outbox { "outbox" } else { "inbox" }
+ )
+ }
+
+ pub(crate) async fn handler(
+ State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+ legacy: Option<axum::Extension<ai_memory_core::LegacyBrowserAuth>>,
+ Query(query): Query<InboxQuery>,
+ ) -> Response {
+ let viewer = viewer.map(|v| v.0.user());
+ let (projects, counts, directory) = match tokio::try_join!(
+ state.reader.list_projects_with_stats(viewer),
+ state.reader.pending_inbox_counts(viewer),
+ state.reader.registered_agents(viewer),
+ ) {
+ Ok(data) => data,
+ Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
+ };
+ let pending: HashMap<_, _> = counts
+ .into_iter()
+ .map(|c| ((c.workspace_name, c.project_name), c.pending))
+ .collect();
+ let requested = match (query.workspace, query.project) {
+ (Some(w), Some(p)) => (w, p),
+ (None, None) => projects
+ .iter()
+ .find(|p| pending.contains_key(&(p.workspace_name.clone(), p.project_name.clone())))
+ .or_else(|| projects.first())
+ .map(|p| (p.workspace_name.clone(), p.project_name.clone()))
+ .unwrap_or_default(),
+ _ => {
+ return (
+ StatusCode::BAD_REQUEST,
+ "Select both workspace and project.",
+ )
+ .into_response();
+ }
+ };
+ let (workspace, project) = requested;
+ let mailbox = match query.mailbox.as_deref() {
+ None | Some("inbox") => MessageBox::Inbox,
+ Some("outbox") => MessageBox::Outbox,
+ _ => return StatusCode::BAD_REQUEST.into_response(),
+ };
+ let inbox = mailbox == MessageBox::Inbox;
+ let message_state = match query.state.as_deref() {
+ None if inbox => Some(MessageState::Pending),
+ None | Some("") => None,
+ Some(raw) => match raw.parse::<MessageState>() {
+ Ok(state) => Some(state),
+ Err(_) => return StatusCode::BAD_REQUEST.into_response(),
+ },
+ };
+ let filtered_href = |outbox, offset| {
+ let mut href = mailbox_href(&workspace, &project, outbox, offset);
+ if let Some(state) = message_state {
+ href.push_str("&state=");
+ href.push_str(state.as_str());
+ } else {
+ href.push_str("&state=");
+ }
+ href
+ };
+ let scope = if workspace.is_empty() && project.is_empty() {
+ None
+ } else {
+ match super::resolve_read_scope(&state, viewer, &workspace, &project).await {
+ Ok(s) => Some(s),
+ Err(e) => return super::page::refusal_response(&e),
+ }
+ };
+ let recipients = directory
+ .into_iter()
+ .map(|r| {
+ let selected = r.workspace == workspace
+ && r.project == project
+ && query.agent.as_deref() == Some(r.agent.as_str());
+ RecipientOption {
+ label: agent_label(r.agent).into(),
+ workspace: r.workspace,
+ project: r.project,
+ agent: r.agent.as_str().into(),
+ selected,
+ }
+ })
+ .collect::<Vec<_>>();
+ let visible: HashMap<_, _> = projects
+ .iter()
+ .map(|p| {
+ (
+ (p.workspace_id.clone(), p.project_id.clone()),
+ format!("{} / {}", p.workspace_name, p.project_name),
+ )
+ })
+ .collect();
+ let mut messages = match scope {
+ Some(scope) => match state
+ .reader
+ .message_history_filtered(
+ scope.workspace_id,
+ scope.project_id,
+ mailbox,
+ message_state,
+ 51,
+ query.offset,
+ )
+ .await
+ {
+ Ok(m) => m,
+ Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
+ },
+ None => Vec::new(),
+ };
+ let more = messages.len() > 50;
+ messages.truncate(50);
+ let editing_count = match (&scope, inbox) {
+ (Some(scope), true) => match state
+ .reader
+ .message_history_filtered(
+ scope.workspace_id,
+ scope.project_id,
+ MessageBox::Inbox,
+ Some(MessageState::Editing),
+ 100,
+ 0,
+ )
+ .await
+ {
+ Ok(held) => held.len(),
+ Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
+ },
+ _ => 0,
+ };
+ let rows = messages
+ .into_iter()
+ .map(|m| {
+ let from = visible
+ .get(&(
+ m.origin.from_workspace_id.to_string(),
+ m.origin.from_project_id.to_string(),
+ ))
+ .cloned()
+ .unwrap_or_else(|| "A project you cannot read".into());
+ let to = visible
+ .get(&(m.to_workspace_id.to_string(), m.to_project_id.to_string()))
+ .cloned()
+ .unwrap_or_else(|| "A project you cannot read".into());
+ let raw_subject = m.subject.clone().unwrap_or_default();
+ MessageRow {
+ id: m.id.to_string(),
+ raw_subject,
+ subject: m
+ .subject
+ .filter(|s| !s.is_empty())
+ .unwrap_or_else(|| "Untitled message".into()),
+ body: m.body,
+ from,
+ to,
+ agent: m
+ .to_agent
+ .map(|a| agent_label(a).to_owned())
+ .unwrap_or_else(|| "Any project agent".into()),
+ state: m.state.as_str().into(),
+ state_label: match m.state {
+ MessageState::Pending => "Queued",
+ MessageState::Claimed => "Collected",
+ MessageState::Cancelled => "Cancelled",
+ MessageState::Editing => "Editing",
+ },
+ when: humanize(&m.created_at.to_string()),
+ }
+ })
+ .collect();
+ let scopes: Vec<_> = projects
+ .into_iter()
+ .map(|p| ScopeOption {
+ pending: pending
+ .get(&(p.workspace_name.clone(), p.project_name.clone()))
+ .copied()
+ .unwrap_or(0),
+ inbox_href: format!(
+ "{}&state=pending",
+ mailbox_href(&p.workspace_name, &p.project_name, false, 0)
+ ),
+ selected: p.workspace_name == workspace && p.project_name == project,
+ workspace: p.workspace_name,
+ project: p.project_name,
+ })
+ .collect();
+ let view = InboxView {
+ pending_total: scopes
+ .iter()
+ .fold(0_u64, |total, s| total.saturating_add(s.pending)),
+ pending_projects: scopes.iter().filter(|s| s.pending > 0).count(),
+ scopes,
+ editing_count,
+ editing_href: format!(
+ "{}&state=editing",
+ mailbox_href(&workspace, &project, false, 0)
+ ),
+ inbox_href: filtered_href(false, 0),
+ outbox_href: filtered_href(true, 0),
+ state: message_state.map_or("", |s| s.as_str()).into(),
+ previous: if query.offset > 0 {
+ filtered_href(!inbox, query.offset.saturating_sub(50))
+ } else {
+ String::new()
+ },
+ next: if more {
+ filtered_href(!inbox, query.offset.saturating_add(50))
+ } else {
+ String::new()
+ },
+ can_send: recipients
+ .iter()
+ .any(|r| r.workspace == workspace && r.project == project),
+ needs_write_token: legacy.is_some(),
+ project_href: project_href(&workspace, &project),
+ workspace,
+ project,
+ recipients,
+ rows,
+ inbox,
+ };
+ match view.render() {
+ Ok(html) => Html(html).into_response(),
+ Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
+ }
+ }
+
+ #[derive(Deserialize)]
+ pub(crate) struct ComposeMessage {
+ from_workspace: String,
+ from_project: String,
+ to_workspace: String,
+ to_project: String,
+ to_agent: String,
+ subject: String,
+ body: String,
+ }
+
+ fn error(status: StatusCode, message: &str) -> Response {
+ (status, Json(serde_json::json!({"error":message}))).into_response()
+ }
+
+ /// What a browser write needs after the checks every write shares.
+ struct BrowserWriter {
+ viewer: Option<ai_memory_core::UserId>,
+ distinguishes: bool,
+ }
+
+ /// The checks every browser write to the mailbox shares: the UI header, the
+ /// same-origin check, a signed-in operator when operators are distinguished,
+ /// and the normal-write capability.
+ async fn authorize_browser_write(
+ state: &WebState,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+ level: Option<axum::Extension<AuthLevel>>,
+ headers: &HeaderMap,
+ ) -> Result<BrowserWriter, Response> {
+ // A custom header plus JSON prevents a cross-site form from using cached
+ // Basic credentials. Cookie sessions additionally pass dual-auth CSRF.
+ if headers.get("x-ai-memory-ui").and_then(|h| h.to_str().ok()) != Some("1") {
+ return Err(error(
+ StatusCode::FORBIDDEN,
+ "Refresh the inbox and try again.",
+ ));
+ }
+ if let Some(origin) = headers.get("origin").and_then(|h| h.to_str().ok()) {
+ let authority = origin
+ .parse::<axum::http::Uri>()
+ .ok()
+ .and_then(|u| u.authority().map(|a| a.as_str().to_owned()));
+ if authority.as_deref() != headers.get("host").and_then(|h| h.to_str().ok()) {
+ return Err(error(
+ StatusCode::FORBIDDEN,
+ "Messages must be sent from this dashboard.",
+ ));
+ }
+ }
+ let distinguishes = state
+ .reader
+ .distinguishes_operators(state.trusted_proxy_identity)
+ .await
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())?;
+ let level = level.map_or(AuthLevel::Anonymous, |l| l.0);
+ if distinguishes && level == AuthLevel::Anonymous {
+ return Err(error(
+ StatusCode::UNAUTHORIZED,
+ "Sign in to send a message.",
+ ));
+ }
+ if level
+ .authorize(Capability::NormalWrite, distinguishes)
+ .is_err()
+ {
+ return Err(StatusCode::FORBIDDEN.into_response());
+ }
+ let viewer = viewer.map(|v| v.0.user());
+ if level == AuthLevel::User && viewer.is_none() {
+ return Err(StatusCode::FORBIDDEN.into_response());
+ }
+ Ok(BrowserWriter {
+ viewer,
+ distinguishes,
+ })
+ }
+
+ pub(crate) async fn send(
+ State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+ actor: Option<axum::Extension<ActorContext>>,
+ level: Option<axum::Extension<AuthLevel>>,
+ headers: HeaderMap,
+ Json(input): Json<ComposeMessage>,
+ ) -> Response {
+ let BrowserWriter {
+ viewer,
+ distinguishes,
+ } = match authorize_browser_write(&state, viewer, level, &headers).await {
+ Ok(writer) => writer,
+ Err(refusal) => return refusal,
+ };
+ let source = match lookup_existing_scope_guarded(
+ &state.reader,
+ &input.from_workspace,
+ &input.from_project,
+ viewer,
+ ProjectAccess::Write,
+ )
+ .await
+ {
+ Ok(s) => s,
+ Err(e) => return super::page::refusal_response(&e),
+ };
+ let target = match lookup_existing_scope_guarded(
+ &state.reader,
+ &input.to_workspace,
+ &input.to_project,
+ viewer,
+ ProjectAccess::Write,
+ )
+ .await
+ {
+ Ok(s) => s,
+ Err(e) => return super::page::refusal_response(&e),
+ };
+ let agent = AgentKind::from_wire(&input.to_agent);
+ if agent.as_str() != input.to_agent {
+ return error(StatusCode::BAD_REQUEST, "Select a registered agent.");
+ }
+ let known = match state
+ .reader
+ .agent_usage(
+ target.workspace_id,
+ target.project_id,
+ ai_memory_core::OwnerFilter::Any,
+ )
+ .await
+ {
+ Ok(rows) => rows.iter().any(|r| r.agent == input.to_agent),
+ Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
+ };
+ if !known {
+ return error(
+ StatusCode::BAD_REQUEST,
+ "That agent has no registered session in the recipient project.",
+ );
+ }
+ if input.body.trim().is_empty()
+ || input.body.chars().count() > 8_000
+ || input.subject.chars().count() > 200
+ {
+ return error(
+ StatusCode::BAD_REQUEST,
+ "Enter a message up to 8,000 characters and a subject up to 200 characters.",
+ );
+ }
+ let actor = actor.map_or_else(ActorContext::anonymous, |a| a.0);
+ let message = NewAgentMessage {
+ from_workspace_id: source.workspace_id,
+ from_project_id: source.project_id,
+ from_agent: AgentKind::Other,
+ from_session_id: None,
+ from_owner_user: ai_memory_core::owner_stamp(actor.identity_key().as_ref(), distinguishes),
+ to_workspace_id: target.workspace_id,
+ to_project_id: target.project_id,
+ to_agent: Some(agent),
+ subject: Some(input.subject.trim().to_owned()),
+ body: input.body.trim().to_owned(),
++ nature: ai_memory_core::MessageNature::Unknown,
++ evidence: None,
+ };
+ match state.wiki.send_agent_message(message, actor).await {
+ Ok(id) => (
+ StatusCode::CREATED,
+ Json(serde_json::json!({"message_id":id.to_string(),"state":"pending"})),
+ )
+ .into_response(),
+ Err(ai_memory_wiki::WikiError::Store(ai_memory_store::StoreError::InvalidState(_))) => {
+ error(
+ StatusCode::CONFLICT,
+ "This inbox is full. An agent must collect pending mail first.",
+ )
+ }
+ Err(e) => {
+ tracing::warn!(error=%e,"browser message refused");
+ error(
+ StatusCode::FORBIDDEN,
+ "The message could not be queued. Check project access and message admission policy.",
+ )
+ }
+ }
+ }
+
+ #[derive(Deserialize)]
+ pub(crate) struct EditMessage {
+ workspace: String,
+ project: String,
+ #[serde(default)]
+ subject: Option<String>,
+ #[serde(default)]
+ body: Option<String>,
+ }
+
+ /// Resolve the message a browser edit targets, and refuse unless the caller
+ /// could have sent it: write access to the recipient mailbox it sits in and to
+ /// the project it came from. Without the second check, anyone who can write to
+ /// a project could rewrite what another project's agent asked it to do.
+ async fn editable_message(
+ state: &WebState,
+ writer: &BrowserWriter,
+ raw_id: &str,
+ input: &EditMessage,
+ ) -> Result<
+ (
+ ai_memory_core::WorkspaceId,
+ ai_memory_core::ProjectId,
+ ai_memory_core::MessageId,
+ ),
+ Response,
+ > {
+ let id = raw_id
+ .parse::<ai_memory_core::MessageId>()
+ .map_err(|_| error(StatusCode::BAD_REQUEST, "That is not a message id."))?;
+ let target = lookup_existing_scope_guarded(
+ &state.reader,
+ &input.workspace,
+ &input.project,
+ writer.viewer,
+ ProjectAccess::Write,
+ )
+ .await
+ .map_err(|e| super::page::refusal_response(&e))?;
+ let message = state
+ .reader
+ .message_in_mailbox(target.workspace_id, target.project_id, id)
+ .await
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())?
+ .ok_or_else(|| {
+ error(
+ StatusCode::NOT_FOUND,
+ "That message is not in this mailbox.",
+ )
+ })?;
+ let visible = state
+ .reader
+ .list_projects_with_stats(writer.viewer)
+ .await
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())?;
+ let Some(origin) = visible.into_iter().find(|p| {
+ p.workspace_id == message.origin.from_workspace_id.to_string()
+ && p.project_id == message.origin.from_project_id.to_string()
+ }) else {
+ return Err(error(
+ StatusCode::FORBIDDEN,
+ "You cannot edit mail sent from a project you cannot write to.",
+ ));
+ };
+ lookup_existing_scope_guarded(
+ &state.reader,
+ &origin.workspace_name,
+ &origin.project_name,
+ writer.viewer,
+ ProjectAccess::Write,
+ )
+ .await
+ .map_err(|e| super::page::refusal_response(&e))?;
+ Ok((target.workspace_id, target.project_id, id))
+ }
+
+ /// Take a queued message out of the queue so it can be edited.
+ pub(crate) async fn begin_edit(
+ State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+ level: Option<axum::Extension<AuthLevel>>,
+ headers: HeaderMap,
+ axum::extract::Path(raw_id): axum::extract::Path<String>,
+ Json(input): Json<EditMessage>,
+ ) -> Response {
+ let writer = match authorize_browser_write(&state, viewer, level, &headers).await {
+ Ok(writer) => writer,
+ Err(refusal) => return refusal,
+ };
+ let (workspace_id, project_id, id) =
+ match editable_message(&state, &writer, &raw_id, &input).await {
+ Ok(target) => target,
+ Err(refusal) => return refusal,
+ };
+ match state
+ .wiki
+ .begin_agent_message_edit(workspace_id, project_id, id)
+ .await
+ {
+ Ok(Some(message)) => Json(serde_json::json!({
+ "message_id": message.id.to_string(),
+ "state": message.state.as_str(),
+ "subject": message.subject.unwrap_or_default(),
+ "body": message.body,
+ }))
+ .into_response(),
+ Ok(None) => error(
+ StatusCode::CONFLICT,
+ "An agent already collected this message, or it is no longer queued.",
+ ),
+ Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
+ }
+ }
+
+ /// Save new text for a held message and return it to the queue.
+ pub(crate) async fn save_edit(
+ State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+ actor: Option<axum::Extension<ActorContext>>,
+ level: Option<axum::Extension<AuthLevel>>,
+ headers: HeaderMap,
+ axum::extract::Path(raw_id): axum::extract::Path<String>,
+ Json(input): Json<EditMessage>,
+ ) -> Response {
+ let writer = match authorize_browser_write(&state, viewer, level, &headers).await {
+ Ok(writer) => writer,
+ Err(refusal) => return refusal,
+ };
+ let (workspace_id, project_id, id) =
+ match editable_message(&state, &writer, &raw_id, &input).await {
+ Ok(target) => target,
+ Err(refusal) => return refusal,
+ };
+ let body = input.body.clone().unwrap_or_default();
+ let subject = input.subject.clone().unwrap_or_default();
+ if body.trim().is_empty() || body.chars().count() > 8_000 || subject.chars().count() > 200 {
+ return error(
+ StatusCode::BAD_REQUEST,
+ "Enter a message up to 8,000 characters and a subject up to 200 characters.",
+ );
+ }
+ let actor = actor.map_or_else(ActorContext::anonymous, |a| a.0);
+ match state
+ .wiki
+ .save_agent_message_edit(
+ workspace_id,
+ project_id,
+ id,
+ Some(subject.trim().to_owned()),
+ body.trim().to_owned(),
+ actor,
+ )
+ .await
+ {
+ Ok(true) => Json(serde_json::json!({"message_id": id.to_string(), "state": "pending"}))
+ .into_response(),
+ Ok(false) => error(
+ StatusCode::CONFLICT,
+ "This message is no longer being edited.",
+ ),
+ Err(e) => {
+ tracing::warn!(error=%e,"browser message edit refused");
+ error(
+ StatusCode::FORBIDDEN,
+ "The message could not be saved. Check project access and message admission policy.",
+ )
+ }
+ }
+ }
+
+ /// Return a held message to the queue without changing it.
+ pub(crate) async fn release_edit(
+ State(state): State<Arc<WebState>>,
+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,
+ level: Option<axum::Extension<AuthLevel>>,
+ headers: HeaderMap,
+ axum::extract::Path(raw_id): axum::extract::Path<String>,
+ Json(input): Json<EditMessage>,
+ ) -> Response {
+ let writer = match authorize_browser_write(&state, viewer, level, &headers).await {
+ Ok(writer) => writer,
+ Err(refusal) => return refusal,
+ };
+ let (workspace_id, project_id, id) =
+ match editable_message(&state, &writer, &raw_id, &input).await {
+ Ok(target) => target,
+ Err(refusal) => return refusal,
+ };
+ match state
+ .wiki
+ .release_agent_message_edit(workspace_id, project_id, id)
+ .await
+ {
+ Ok(true) => Json(serde_json::json!({"message_id": id.to_string(), "state": "pending"}))
+ .into_response(),
+ Ok(false) => error(
+ StatusCode::CONFLICT,
+ "This message is no longer being edited.",
+ ),
+ Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
+ }
+ }
diff --cc crates/ai-memory-web/src/routes/project.rs
index 0441acf5,bf8b647b..d255cba9
--- a/crates/ai-memory-web/src/routes/project.rs
+++ b/crates/ai-memory-web/src/routes/project.rs
@@@ -5,10 -4,9 +5,10 @@@ use std::collections::BTreeMap
use std::sync::Arc;
use askama::Template;
- use axum::extract::{Path, State};
+ use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::response::{Html, IntoResponse, Response};
+use jiff::Timestamp;
use ai_memory_store::ResolvedScope;
@@@ -99,8 -205,9 +207,9 @@@ async fn render
&mut knowledge_map
};
map.entry(folder).or_default().push((
- p.updated_at.clone(),
+ p.updated_at.parse::<Timestamp>().ok(),
PageRow {
+ agent_label: None,
path: p.path.clone(),
href: page_href(&workspace, &project, &p.path),
title: p.title.clone(),
diff --cc crates/ai-memory-web/src/templates.rs
index e9e9b5dc,b5666a57..b3b96656
--- a/crates/ai-memory-web/src/templates.rs
+++ b/crates/ai-memory-web/src/templates.rs
@@@ -77,6 -77,60 +77,61 @@@ fn encode_path(path: &str) -> String
.join("/")
}
+ /// Compact human-readable token count (`12345` → `"12.3k"`, `2_100_000` →
+ /// `"2.1M"`). Values under 1000 render as a plain integer.
+ #[must_use]
+ pub(crate) fn fmt_tokens(n: u64) -> String {
+ if n >= 1_000_000 {
+ format!("{:.1}M", n as f64 / 1_000_000.0)
+ } else if n >= 1_000 {
+ format!("{:.1}k", n as f64 / 1_000.0)
+ } else {
+ n.to_string()
+ }
+ }
+
+ /// Human-readable label for an agent-kind badge (`claude-code` → `Claude
+ /// Code`). Purely a display concern — the wire form
+ /// ([`ai_memory_core::AgentKind::as_str`]) stays the identity used
+ /// everywhere else.
+ #[must_use]
+ pub(crate) fn agent_label(kind: ai_memory_core::AgentKind) -> &'static str {
+ use ai_memory_core::AgentKind;
+ match kind {
+ AgentKind::ClaudeCode => "Claude Code",
+ AgentKind::Codex => "Codex",
+ AgentKind::OpenCode => "OpenCode",
+ AgentKind::Cursor => "Cursor",
+ AgentKind::GeminiCli => "Gemini CLI",
+ AgentKind::ClaudeDesktop => "Claude Desktop",
+ AgentKind::OpenClaw => "OpenClaw",
+ AgentKind::AntigravityCli => "Antigravity CLI",
+ AgentKind::Omp => "Oh My Pi",
+ AgentKind::Pi => "Pi",
+ AgentKind::Crush => "Crush",
+ AgentKind::Grok => "Grok Build CLI",
+ AgentKind::Zero => "Zero",
+ AgentKind::Devin => "Devin",
+ AgentKind::KimiCode => "Kimi Code",
+ AgentKind::KiroCli => "Kiro CLI",
+ AgentKind::CommandCode => "Command Code",
+ AgentKind::Hermes => "Hermes",
+ AgentKind::Pool => "Pool",
+ AgentKind::Zcode => "ZCode",
+ AgentKind::CopilotCli => "Copilot CLI",
+ AgentKind::Grizzybot => "GrizzyBot",
+ AgentKind::Droid => "Droid",
+ AgentKind::Muse => "Muse",
+ AgentKind::CodeBuddy => "CodeBuddy",
+ AgentKind::IbmBob => "IBM Bob",
+ AgentKind::Dsh => "DSH",
+ AgentKind::Cline => "Cline",
+ AgentKind::QwenCode => "Qwen Code",
++ AgentKind::Qoder => "Qoder",
+ AgentKind::Other => "Other",
+ }
+ }
+
pub(crate) fn encode_segment(segment: &str) -> String {
let mut out = String::with_capacity(segment.len());
for byte in segment.bytes() {
@@@ -218,8 -354,6 +355,7 @@@ pub(crate) struct AgentBadge
pub(crate) struct MailboxRow {
/// Subject line, or a placeholder when the sender gave none.
pub subject: String,
+ /// Epistemic classification supplied by the sender.
- pub nature: String,
/// `workspace/project` of the sender, or a neutral label when the viewer
/// may not read it.
pub sender: String,
diff --cc crates/ai-memory-web/tests/suite/routes.rs
index 3ca55a15,f64547e0..e52412d6
--- a/crates/ai-memory-web/tests/suite/routes.rs
+++ b/crates/ai-memory-web/tests/suite/routes.rs
@@@ -4797,10 -5012,9 +5141,11 @@@ async fn send_mail
from_owner_user: None,
to_workspace_id: to.0,
to_project_id: to.1,
+ to_agent: None,
subject: Some(subject.to_owned()),
body: body.to_owned(),
+ nature: ai_memory_core::MessageNature::Unknown,
+ evidence: None,
})
.await
.unwrap();
diff --cc docs/ARCHITECTURE.md
index a60cf0ae,cba51c08..f3e7840e
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@@ -265,10 -276,25 +276,26 @@@ from hook paths
enumerate every existing workspace/project scope before doing per-project
work, matching the auto-improvement scheduler's store-wide scope model. A
separate daily cleanup removes week-old project rows only when they contain
- no pages, sessions, observations, handoffs, managed workstreams, or
+ no pages, sessions, observations, handoffs, managed workstreams, sent or
+ received agent messages (including claimed/cancelled history), or
auto-improvement data; managed continuity history therefore keeps its
project scope alive even when no lifecycle-hook session has been captured.
+ The same scheduled sweep tick also runs one store-wide
+ `close_abandoned_sessions` batched `UPDATE`. A session with no activity
+ for 48 hours and no `SessionEnd` gets `ended_at` set from its own last
+ activity, with no summary page and no usage. This keeps
+ `open_session_count` from growing on sessions nobody continues, and it is
+ narrower than a real end (see the session-usage row below).
+ A session that is continued, meaning a new session starts in the same
+ scope while the old one has been quiet for 15 minutes or more, is closed
+ sooner on the client, including usage recovery. After that threshold the
+ read-only recovery packet that `render_interrupted_session_context`
+ (`ai-memory-hooks/src/router.rs`) builds also carries a machine-parsed
+ marker. The client uses it to find the old session's transcript, report
+ its usage and send a normal synthetic `SessionEnd`. This is safe even if
+ the old session is still live: a later real `SessionEnd` with more
+ observations than the early close saw re-runs the full end path
+ (`SessionEndDisposition::ReEndWithNewWork`, issue #152).
8. Backups: `ai-memory backup --to <tarball>` uses SQLite's online
backup API so the source stays writable; `ai-memory restore`
reverses. Or: `git push` the wiki dir + `rsync` the data dir.
@@@ -596,8 -608,13 +623,13 @@@ prunable rather than only after it age
| `page_feedback` | Append-only `memory_feedback` signals (`helpful` / `not_helpful` / `stale` / `wrong`) keyed by page *version*, with an optional sanitized reason and `salience_after`. Source of truth for the derived `pages.salience`; the lint pass reads unresolved stale/wrong rows joined against `is_latest = 1`, so a rewrite retires the finding. |
| `page_access` | One row per latest page and qualified operator identity. Supplies the optional access-breadth retention term without changing the existing shared access counter. |
| `page_evidence` | V63 append-only record of what produced or reaffirmed each page version: consolidation cites the `session` it ran on, written in the page-upsert transaction and cascaded on purge. Feeds a read-time, zero-LLM **belief-strength `confidence`** (`ai_memory_store::belief`, B1 / `docs/design-hindsight-borrowings.md` P2): a bounded `[0.0, 0.95]` function of distinct supporting sessions (breadth, not raw count), recency of the newest sighting, and live `contradicts` count. Exposed as `confidence` + `evidence_count` in `memory_query(explain=true)`, as `evidence_rows` in `memory_status`, and used to order the opt-in `settled_first` briefing, all **ranking-inert**. It folds into `PageAuthority` only behind `[retrieval] belief_authority_weight` (**default `0.0`/OFF, R2-gated**), as one bounded factor inside the `[0.55, 1.50]` clamp; a supersession always wins regardless of evidence (a superseded version is never boosted). |
-| `agent_messages` | V64 cross-project message inbox/queue (`docs/agent-messaging.md`). Directed, claim-once mail from a sender coordinate to a recipient coordinate; `pending`→`claimed` (popped exactly once, the handoff compare-and-set) or `pending`→`cancelled` (sender retracts). The one table that crosses per-project isolation, so reads are keyed by the recipient coordinate (inbox) or sender coordinate (outbox); `from_owner_user`/`claimed_by_user` are attribution only, never a read filter. Recipient inbox depth is capped. `ON DELETE CASCADE` on both coordinate pairs. |
+| `agent_messages` | V64 cross-project message inbox/queue (`docs/agent-messaging.md`), extended by V90 with optional epistemic nature/evidence. Directed, claim-once mail from a sender coordinate to a recipient coordinate; `pending`→`claimed` (popped exactly once, the handoff compare-and-set) or `pending`→`cancelled` (sender retracts). The one table that crosses per-project isolation, so reads are keyed by the recipient coordinate (inbox) or sender coordinate (outbox); `from_owner_user`/`claimed_by_user` are attribution only, never a read filter. Recipient inbox depth is capped. `ON DELETE CASCADE` on both coordinate pairs. |
| `pages.compacted_at` | V65 nullable A2 tier-down marker (`docs/design-memory-aging.md` §A2). Set when the forget-sweep extractively compacts a cold episodic page (opt-in `[decay] compact_cold_episodic`) instead of evicting it; derived at the single page-upsert choke point from a `compacted: true` frontmatter mirror, so the marker and compacted body land in one transaction. Additive `ADD COLUMN`, no backfill; the sweep populates it lazily. The sweep and curator skip a marked page so it is never re-compacted, re-evicted, or re-reported as cold. Reversible: the full pre-compaction body stays in git + the supersession chain. |
-| `session_usage` | V89 one row per session: cumulative input/output/cache-write/cache-read tokens the harness's own transcript reported at `session-end`, plus the last-seen model name. Written client-side (`ai-memory-cli`'s `session_usage` module reads the transcript; `hook.rs` splices it into the session-end body as `_ai_memory_usage`; the writer upserts with `MAX(existing, reported)` per column). Cascades with its session on purge/delete. Surfaced on the /web project page's Tokens stat and Sessions table; `None` (not zero) for a session whose harness never reported usage. |
-| `token_calls` | V90 per-session native response identities with content-free input, output and cache counters. Live hooks merge partial/replayed responses with column-wise maxima in one writer transaction, then refresh cumulative session usage. Project reads authorize the project and apply session ownership before counting or ranking. V90 also converts historical Codex input totals to fresh input, excluding cache reads. |
-| `agent_messages.to_agent` | V91 optional registered harness recipient; NULL keeps the shared project inbox. Both claim guards enforce addressed delivery. |
-| `token_calls` context and `token_call_tools` | V92 nullable native turn/response coordinates and response time, plus bounded tool references keyed by session/response. One writer transaction persists counters, provenance and session totals; tools cascade with their response. Missing context stays unknown. Server-side UTC/model/harness/session/turn/tool filters run after scope/owner checks and before pagination. |
-| `agent_messages.state` `editing` | V93 lets a sender hold a pending message out of the queue while editing it. The claim path selects only `pending`, so a held message cannot be popped by order or by id. The row keeps its id and `created_at`, and `edited_at` records the last text change. `ops::begin_message_edit` and `finish_message_edit` are single `UPDATE`s scoped to the recipient coordinate and the expected state, so a collected, cancelled or foreign message is left alone. Saving goes through the sanitizer and `message_send` admission. |
++| `session_usage` | V91 one row per session: cumulative input/output/cache-write/cache-read tokens the harness's own transcript reported at `session-end`, plus the last-seen model name. Written client-side (`ai-memory-cli`'s `session_usage` module reads the transcript; `hook.rs` splices it into the session-end body as `_ai_memory_usage`; the writer upserts with `MAX(existing, reported)` per column). Cascades with its session on purge/delete. Surfaced on the /web project page's Tokens stat and Sessions table; `None` (not zero) for a session whose harness never reported usage. |
++| `token_calls` | V92 per-session native response identities with content-free input, output and cache counters. Live hooks merge partial/replayed responses with column-wise maxima in one writer transaction, then refresh cumulative session usage. Project reads authorize the project and apply session ownership before counting or ranking. V92 also converts historical Codex input totals to fresh input, excluding cache reads. |
++| `agent_messages.to_agent` | V93 optional registered harness recipient; NULL keeps the shared project inbox. Both claim guards enforce addressed delivery. |
++| `token_calls` context and `token_call_tools` | V94 nullable native turn/response coordinates and response time, plus bounded tool references keyed by session/response. One writer transaction persists counters, provenance and session totals; tools cascade with their response. Missing context stays unknown. Server-side UTC/model/harness/session/turn/tool filters run after scope/owner checks and before pagination. |
++| `agent_messages.state` `editing` | V95 lets a sender hold a pending message out of the queue while editing it. The claim path selects only `pending`, so a held message cannot be popped by order or by id. The row keeps its id and `created_at`, and `edited_at` records the last text change. `ops::begin_message_edit` and `finish_message_edit` are single `UPDATE`s scoped to the recipient coordinate and the expected state, so a collected, cancelled or foreign message is left alone. Saving goes through the sanitizer and `message_send` admission. |
| `client_activity` | Server-wide MCP tool-call counters split into reads/writes and bucketed by UTC day. The MCP request choke point flushes buffered calls on a one-minute background interval; failed batches retry from bounded memory. Each day stores at most 128 sanitized client labels plus `other`, so an untrusted `clientInfo.name` cannot create traffic-proportional rows. |
| `auto_improve_proposals` | Staged learning and maintenance edits with immutable target snapshots and append-only decision events. Pending-target uniqueness is scoped by the qualified staging identity; unattributed proposals retain the historical shared bucket. |
| `entities`, `entity_page_links` | V38 noun index derived from canonical frontmatter. Names are normalized and unique per project; links target immutable page versions while retrieval filters to the latest version. Scope-pairing triggers prevent cross-project links. Powers the fourth RRF retrieval stream. |
diff --cc docs/agent-messaging.md
index 7b7b1554,8e95bd3d..48b31285
--- a/docs/agent-messaging.md
+++ b/docs/agent-messaging.md
@@@ -30,13 -28,10 +31,14 @@@ ever sees mail addressed **to** it (it
turned into a dead inbox nobody reads.
- **Bounded.** Each recipient inbox holds at most 256 pending messages; a full
inbox rejects new sends.
+- **Epistemic provenance.** A sender may classify a claim as `measured`,
+ `reported`, `inferred`, or `unknown` (the compatibility default). A measured
+ claim is refused unless it includes non-empty supporting `evidence`; both
+ fields are scrubbed, bounded, and shown by inbox list and pop responses.
- A wiki page is not a message. `memory_message_send` is the only thing that
- lands in a project's inbox; writing a page into the target project with
+ A wiki page is not a message. Agents send through `memory_message_send`, and
+ people can use the web composer described below. Writing a page into the target
+ project with
`memory_write_page` stores knowledge there but is never surfaced as mail, so
a "report" delivered as a page sits unread. When the ask is to send, notify,
or leave a message for the agent in another project, use
diff --cc docs/security-boundaries.md
index 7322b282,3f6018df..8622e0a2
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@@ -162,6 -161,6 +162,10 @@@ the legitimate restricted-project contr
| 27b | LLM workload telemetry cannot turn prompts, outputs, scopes, projects, or caller text into status data or unbounded metric labels | `ai-memory-llm/src/types.rs` `LlmWorkload` is a closed enum carried beside, but absent from the display/wire form of, `LlmOperationId`; `health.rs` `LlmWorkloadHealth` uses one fixed array and fixed latency buckets and records only counts/times/coarse estimates/reported usage/redacted error class and status; `ProviderHealth::snapshot` omits the rows when LLM support is disabled; `/admin/status` remains behind the common admin gate | `ai-memory-llm` `workload_snapshot_is_bounded_redacted_and_percentiled` (private prompt, output and upstream body absent; fixed row count, recovery-preserved last error, and percentile controls), `llm_wrapper_forwards_the_callers_operation_id` (label recorded while the same UUID-only id reaches the provider), `types::tests::workload_labels_are_stable_and_do_not_change_the_wire_operation_id`; `ai-memory-mcp` `status_reports_bounded_content_free_llm_workload_telemetry` (private prompt absent from serialized status, one fixed row per label), `status_reports_provider_health_block` (disabled LLM emits no rows) | STRONG for content/cardinality and the existing root-only admin surface |
| 27c | A maintenance compaction cannot replace a newer user page or partly apply a stale batch | `ai-memory-consolidate/src/sweep.rs` carries each selected source `PageId` into `Wiki::apply_batch_if`; `ai-memory-wiki/src/wiki.rs` checks the preconditions after locking every page, installs files with rollback snapshots, and delegates the decisive check to `WriterHandle::upsert_pages_batch_if`; `ai-memory-store/src/ops.rs` validates every latest id and writes every replacement in one SQLite transaction, returning a mismatch before any write | store `conditional_page_batch_is_all_or_nothing`; wiki `conditional_batch_rejects_every_page_when_one_version_changed` (file and DB controls); consolidate `compaction_does_not_supersede_a_concurrent_fresh_write` (an admission barrier lands a semantic pinned correction after A2 reads the old body, then proves the correction remains latest and the selected batch stays uncommitted) | STRONG; all-or-nothing intentionally retries unchanged peers with the next sweep instead of weakening invariant #2 into per-page writes |
| 28 | An Antigravity hook reads, and uploads as prompts, only the named conversation's own transcript, within bounds | `ai-memory-hooks/src/antigravity.rs` `antigravity_transcript_path` accepts the payload's `transcriptPath` only when it is absolute, has no `..`, names `transcript.jsonl` or `transcript_full.jsonl`, and its canonical directory equals `canonical(<home>/.gemini/<app>/brain)/<conversationId>/.system_generated/logs` for `<app>` `antigravity`, `antigravity-cli` or `antigravity-ide`, with `conversationId` a plain id (`antigravity_conversation_id`); `read_transcript_prompts` opens only a regular, non-symlink file that is still the same file once open (`open_regular_file`, opened with `O_NOFOLLOW | O_NONBLOCK` so a symlink or FIFO swapped in after the check is refused without blocking, and on Linux only when the opened descriptor's `/proc/self/fd` path is the checked one, so a directory swapped for a symlink after the containment check is refused too), reads at most `MAX_TRANSCRIPT_SCAN_BYTES` per hook and parses lines up to `MAX_TRANSCRIPT_LINE_BYTES`, and returns only `USER_INPUT` steps whose `source` is absent or `USER_EXPLICIT`; `ai-memory-cli/src/commands/hook.rs` `antigravity_transcript_prompt_events` runs inside the spool block, so after the capture allowlist, routing, server-profile and external-capture gates, with the home `run_with_payload` resolved once; its path checks, bounded cursor load and transcript read run behind `ANTIGRAVITY_TRANSCRIPT_READ_BUDGET`, and a timeout advances no cursor so a later hook retries; cursor replacement uses the canonical atomic writer; each prompt is capped and scrubbed client-side, keyed by conversation and step, and sanitized again by the server (row 7) | `antigravity.rs` `transcript_path_refuses_anything_outside_the_conversations_own_logs` (another conversation's transcript, the same layout outside the home, another file in the logs directory, an unknown app directory, `..`, a traversal or empty id, a relative path, a missing or non-string path; the conversation's own transcript is the control), `transcript_path_refuses_symlinked_directories_that_leave_the_conversation` (a symlinked `.system_generated` and `brain/<id>` refused; a symlinked `~/.gemini` accepted as the control), `transcript_reader_refuses_symlinks_and_special_files` (a symlinked transcript and a directory refused; the same bytes as a regular file are read), `skips_injected_malformed_empty_and_non_prompt_steps`, `a_line_longer_than_the_scan_budget_is_skipped_across_reads`, `one_read_returns_a_bounded_number_of_prompts`; `hook.rs` `antigravity_transcript_reads_are_confined_to_the_conversations_own_logs` (end to end through the native hook: a forged path outside the home, another conversation's transcript and an arbitrary JSONL file under the home spool no prompt; the conversation's own transcript spools one), `antigravity_transcript_prompts_follow_the_capture_allowlist` (a repository the allowlist leaves out is not read), `antigravity_transcript_read_deadline_does_not_wait_for_blocked_work`, and `antigravity_transcript_cursor_store_is_atomic_and_bounded` (oversized cursor refused) | STRONG on Linux, including the opened descriptor path. Stable symlink escapes and special files are refused on every platform; without Linux `/proc/self/fd`, a same-user process able to replace an ancestor in the narrow interval between canonicalization and open could redirect the read, which still remains size- and time-bounded. The directory-swap bite test is Linux-only; the other symlink cases are `cfg(unix)` |
++| 29 | Interrupted-session recovery stays scope-, owner-, and receiver-bound | `ReaderPool::latest_interrupted_session_candidate` filters before selection; hooks render only the admitted candidate and exclude the receiving session | `multi_session.rs` `interrupted_recovery_refuses_foreign_scope_owner_and_receiver_with_controls`; hooks `unfinished_session_recovery_is_owner_scoped_and_excludes_receiver` | STRONG |
++| 30 | Per-response usage remains project/session/owner scoped and replay-monotonic | `ReaderPool::token_usage_report_page` applies scope, owner, search, and signal filters before pagination; `ops::upsert_token_calls` keys native response ids by session and merges counters with maxima in one writer transaction | `live_token_usage.rs` scope, owner, pagination, replay, and mutation controls | STRONG |
++| 31 | Browser inbox operations hide restricted projects and preserve both-coordinate write authorization | Inbox and notification routes derive choices and counts from viewer-filtered projects; sends and edits require write access to the recipient and sender coordinates, sanitization, admission, CSRF, and fixed capabilities | `operations.rs` restricted-project, foreign-workspace, authorization, and notification tests; dashboard browser mutation cases | STRONG |
++| 32 | Directed and held messages cannot be claimed by the wrong harness or while editing | Both message claim guards require `state = 'pending'` and match `to_agent`; begin/finish edit are coordinate- and state-guarded single-writer updates | `agent_messages.rs` addressed claim-once and editing-state tests; web authorization tests; mutation probes for wrong-harness and held-message claims | STRONG |
### IBM Bob evidence