Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Merge branch 'main' into release/3.2
AkitaOnRailse83746ab5028
diff --cc CHANGELOG.mdindex 604f3790,a8c973ca..ac828da4--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -11,70 -11,174 +11,238 @@@ version in [`docs/changelog/`](docs/cha## [Unreleased]+### Added+- Added first-party Cline CLI lifecycle and MCP support. `install-hooks+ --agent cline --apply` writes Cline's nine supported event files globally or+ per project, refuses user-owned and symlinked targets, and keeps embedded+ bearer credentials owner-only. `install-mcp --client cline --apply` writes+ Cline's top-level transport fields and explicitly selects Streamable HTTP.+ Detached start hooks recover handoffs through MCP; yolo mode disables hooks.+ Also added `install-mcp --client freebuff --apply`, which registers the+ sessionless stdio bridge in `~/.agents/mcp.json` without starting another+ ai-memory server. (#1335)+- Added `[ingest] drop_events` (env `AI_MEMORY_INGEST__DROP_EVENTS`), an+ opt-in list of hook event kinds the server drops before storing them, next+ to the existing `drop_tool_use_id_prefixes` and `drop_tool_names`. A dropped+ event gets the same 202, `dropped_by_policy` metric and log as the other+ policy drops, before the rate limiter, the ingest semaphore and the+ sanitizer. Subagent classification precedes every id, name, and kind matcher,+ so a matching marked event still seeds tracking for its unmarked tail. The+ default drops nothing. `Config::load` checks each value+ against the typed event kind and rejects unknown kinds and `session-start`+ and `session-end`, which open and close sessions. The motivating case is+ `pre-tool-use`: in one production store about 87% of those observations had+ an empty body, and each pairs with a `post-tool-use` that carries the+ content. With `pre-tool-use` dropped, a session whose only work was a tool+ call that never finished now ends as lifecycle-only. (#1339)+- Added opt-in `[sessions] idle_end_after_hours` (env+ `AI_MEMORY_SESSIONS__IDLE_END_AFTER_HOURS`; default `0`, off; range+ `1..=8760`). When it is set, the `serve` maintenance tick ends open sessions+ with no activity for that many hours, such as a harness that crashed or a+ terminal closed before `SessionEnd` fired. A substantive session gets its+ `sessions/<id>.md` summary page, attributed to the session's owner, and its+ consolidation job. A boundary-only session ends lifecycle-only and releases+ the handoff it had accepted. The tick creates no handoff of its own and skips+ sessions bound to an active managed run. A real `SessionEnd` or checkpoint+ that lands while the tick runs wins, and the tick leaves that session alone.+ `ended_at` is the time of the tick; the session's last activity goes in the+ audit row. (#1338)+- Added first-party DeepSeek Harness (DSH) lifecycle capture. `install-hooks+ --agent dsh` (aliases `deepseek-harness`, `deepseek_harness`) stages the+ new `hooks/dsh` bundle, writes a generated Claude Code `hooks.json`, and+ prints a Cordis patch fragment that mounts DSH's official+ `@deepseek-ai/dsh-hooks-claude-code` bridge on+ `$DSH_HOME/profiles/<profile>/cordis.patch.yml` (the patch file itself is+ never auto-written). DSH sessions are stored as `agent=dsh`, and its bridge+ forwards Claude Code-shaped tool payloads, so `[capture] ignore_paths`+ exclusions apply to its file, search and shell calls (Windows `pwsh`, POSIX+ `bash`) like any other Claude-shaped adapter; the reserved Code Mode+ `run_code` transport that its `headless` profile calls is treated as inline+ program source. The bridge+ delivers exactly seven events (no `PreCompact` or `SessionEnd`) and runs+ `SessionStart` detached, so finished sessions close with+ `finalize-session --agent dsh` and pending handoffs are recovered via+ `memory_handoff_list` / `memory_handoff_accept`. (#1337)+- Added an Antigravity skill root family. `install-skills --agent antigravity`+ (aliases `antigravity-cli`, `agy`; also `install-instructions+ --skills-agent antigravity`) writes the managed Agent Skills to both global+ roots Antigravity reads, `~/.gemini/config/skills` (App and IDE) and+ `~/.gemini/antigravity-cli/skills` (CLI), or to the workspace+ `.agents/skills` with `--scope project`. `ai-memory setup` now uses it for+ Antigravity, which until now got its skills only in `~/.agents/skills`, a+ directory Antigravity does not read globally, and `uninstall --only skills`+ sweeps both roots. MCP-driven routing refresh and `backup-agents` expose and+ preserve the same roots, including the shared project `.agents/skills`.+ (#1357)++ ### Fixed+ - Fixed native hook events getting stranded forever when a harness killed the+ process after the spool file was synced but before its atomic rename. A later+ drain adopts complete, valid `*.json.tmp` entries after a five-minute grace+ period and removes malformed old remnants. Claude Code settings installs now+ give `SessionEnd` a 15-second timeout instead of its 1.5-second default budget;+ plugin hooks rely on recovery because Claude does not let plugin timeouts+ raise that budget. (#1377)+ - Hardened OIDC credential transport after CodeQL alert #176: the shared+ refresh-grant sink now requires a typed TLS-or-loopback endpoint, and device+ authorization and token polling revalidate their endpoints immediately+ before each request. A caller-mutated discovery object can no longer bypass+ the login-time HTTPS check.+ - On Windows, `setup` now starts the logon host with a plain executable path,+ and the host passes plain drive/UNC data-directory and config arguments to the+ supervisor and server it launches, instead of the `\\?\` verbatim prefix a+ canonical path carries. The `Run` value was already plain (3.1.0); this covers+ the command lines built from `current_exe()` and the canonical data dir. This+ path cleanup does not by itself resolve Bitdefender's behavioral detection.+ (#1280)+ - Fixed an explicit `llm_base_url` (or `AI_MEMORY_LLM_BASE_URL`) being dropped+ for the `anthropic` and `openai` providers. Config resolved the override for+ every provider, as documented, but the provider factory never applied it to+ those two, so requests and the API key went straight to api.anthropic.com or+ api.openai.com with nothing in the log. A gateway or reverse proxy set in front+ of either vendor now receives the traffic. The docs now name the backends that+ take no override: the ChatGPT backend behind `openai-oauth` and `codex`, and+ `cursor`'s CLI. (#1347)+ - Corrected the `ExtractionState::NotApplicable` documentation and aligned the+ generated OpenCode capture policy with the native evaluator: only an active+ policy dropping a search/list tool reports `not-applicable`; an invalid+ policy reports `extracted`. `ai-memory hook --check-capture` also uses+ `not-applicable` when no policy was evaluated. (#1352)+ - `ai-memory auth login openai-oauth` and `auth login copilot` no longer print+ a failed endpoint's whole response body. Error bodies are bounded, scrubbed+ of secrets and terminal control sequences, then capped for display; provider+ errors, including OIDC login and refresh, use the same ordering so a secret+ at the display boundary is still redacted. (#1359)+ - Fixed OIDC device login and refresh sending credential-bearing requests to+ non-TLS endpoints. Issuers and advertised or persisted device/token endpoints+ must now use `https` outside loopback, and authentication requests do not+ follow redirects. Plain `http` remains available for local test issuers on+ `localhost`, `127.0.0.1` and `::1`. (#1354)+ - Fixed `install-instructions` printing a false "Claude Code reads <file> instead+ of AGENTS.md" note when `$HOME` is reached through a symlink. The home+ `.claude/CLAUDE.md` skip now compares with the same canonicalising+ `paths_match` helper the import check uses, so a symlinked home matches its+ resolved path. (#1345)+ - Corrected stale claims in `docs/comparison.md` and `docs/competitive-parity.md`+ that said Windows has no service step and the Windows install is experimental.+ The 3.1 `install.ps1` + `setup` Windows service step is shipped production,+ not experimental; the "3.0 (unreleased)" observation-stream note is corrected+ to reflect the released 3.0 line. (#1271)+ - Made the executable auto-improvement eval policy server-owned. Manual CLI and+ HTTP reviews now use `[auto_improve.eval]` from the server process, and legacy+ requests that try to supply an `eval` object fail closed with an upgrade+ message.+ - Made managed cross-harness continuation survive quota exhaustion without a+ voluntary handoff. The startup packet now places its server-authored resume+ directive outside the untrusted transcript fence, and refreshed+ `CLAUDE.md` / `AGENTS.md` routing tells an incoming agent that "continue",+ "resume", and "pick up where we left off" must consult the private+ `AI_MEMORY_PREVIOUS_SESSION_HISTORY` dossier when the managed-run variables+ are present. The dossier remains untrusted evidence and stays local to the+ launcher machine.+ - Fixed unbounded memory use in consolidation and auto-improve for long+ sessions: both paths now read a bounded projection of the session's+ observations instead of loading every row, keeping the LLM input+ byte-identical. Sessions with no observations in the consolidator's target+ scope (purged or foreign) are refused before any work, exactly as empty+ sessions were before. (#1363)+ - Fixed the session page's uncapped `## Prompts` list. Above 500 prompts the+ page now lists the first 250 titles and the last 250, numbered by their real+ position, with one line between them saying how many were left out. The+ store reads at most 500 titles for it, and the page's prompt count and the+ digest stats still report the true total. (#1349)+ - Fixed auto-improve approvals that failed because a `reject`-policy admission+ webhook was unreachable, timed out, rate-limited or answered 5xx being+ stored as rejections. The proposal is still marked `failed`, but the outage+ no longer enters the rejection buffer, so later reviews are not told to+ avoid a proposal nobody refused and rejection telemetry counts only real+ refusals. (#1358)+ - Fixed consolidation persisting non-page `relations:` targets in YAML+ frontmatter on disk. Raw titles containing dots, directory paths, or stemless+ `.md` strings in `relations:` were previously written into frontmatter and+ retained by `prune_relations` when `extract_relation_links` returned an empty+ list, causing the wiki watcher to emit repeated warnings on every+ reconciliation pass. Targets are now validated through `extract_relation_links`+ before frontmatter assembly and during relation pruning. (#1353, #1366)+ - Consolidation now also drops well-shaped same-project `relations:` targets+ that name no existing page. Relations among pages in the same atomic batch+ remain valid, and ordinary same-project body wikilinks may still point to a+ page that will be written later. (#1353)+ - Verified target latest status and expiration in+ `ReaderPool::contradiction_edges`, so a contradiction pointing at a+ tombstoned or expired page is reported as unresolved instead of active, and+ expired source pages do not emit contradiction findings. (#1367)+ - Verified target latest status and expiration in+ `ReaderPool::dangling_cross_project_links`, so cross-project links to+ tombstoned or expired pages are reported as dangling instead of resolved,+ and expired source pages do not emit dangling link findings. (#1368)+ - Fixed the `/web` project tree and its recent-activity list, the namespace+ listing, and the `/api/v1` `pages` list and legacy `recent` array showing+ pages whose `expires_at` TTL had passed, which search, `memory_recent`, the+ incremental `recent` form and page history already hid. A project move and+ the curator still see every current page, and an exact-path read of an+ expired page still answers. (#1369)+ - Fixed `memory_read_page` returning a page whose `expires_at` TTL had passed+ with nothing to say so. The TTL design keeps an exact-path read answering for+ such a page while `memory_query`, `memory_recent` and the briefing hide it,+ and promised the response would carry `expired: true`; the flag was never+ written. The response now carries `expired: true` for an expired page, on+ both the markdown and the DB-fallback branch, and is unchanged for a live+ one. (#1371)+ - Fixed the `/web` page view showing a page whose `expires_at` TTL had passed+ exactly like a live one, although search and the project listings leave such+ a page out. The metadata row now carries an `expired` badge beside the tier+ and kind; a live page renders as before. (#1372)+ - Fixed `GET /admin/read-page` and `ai-memory read-page` returning a page whose+ `expires_at` TTL had passed with nothing to say so, although `search` no+ longer lists such a page. The response now carries `expired: true` for an+ expired page, on both the markdown and the DB-fallback branch, and+ `read-page` prints an `expired: true` line (the field also appears in+ `--json`); a live page's output is unchanged. (#1373)+ - Fixed web wikilink rendering generating dead links for directory and stemless+ targets. In markdown pages, wikilinks pointing to a directory (`[[notes/]]`) or+ a stemless target (`[[notes/.md]]`, `[[.md]]`) were rewritten into invalid+ page links that yielded 404 responses in the web browser. They now remain as+ literal text, aligning web wikilink preprocessing with the wiki engine's link+ extractor. (#1364)+ - `install-mcp` now writes the absolute path of the `ai-memory` binary as the+ `command` of every stdio bridge entry (Claude Code's session-aware entry,+ Muse Code and the session-less bridge of the other clients), as hook+ commands already did. A client started without `~/.local/bin` on its `PATH`+ no longer fails to spawn the bridge. The Docker wrapper keeps the bare+ `ai-memory`, and existing entries with either form are still recognized.+ (#1362)++ - Fixed the session-start brief hiding a page's body behind a longer+ frontmatter excerpt. When a pinned, `_rules/` or `_slots/` page had a+ `summary:` or `abstract:` longer than its body, the brief printed that+ excerpt instead of the body, however much of `[briefing] max_chars` was+ left, so a small wiki whose pages fit did not get every body whole. Such a+ body now shows whole: it is priced at its own size when the brief decides+ which pages fit, and the bytes it saves over the excerpt go to other pages.+ A page with an empty body keeps its excerpt. (#1360)+ - Fixed `ai-memory setup` wiring OpenCode 2 with OpenCode 1 artifacts. A+ named `--agent opencode` (or `open-code`), or an OpenCode found by the+ session store both majors share, always got the V1 function plugin+ `plugins/ai-memory.ts` and a direct `mcp.ai-memory` entry, which OpenCode+ 2 does not load. `setup` now runs `opencode --version` once, as+ `install-mcp` and `install-hooks` already did for the generic spelling, and+ wires the V2 `{ id, setup }` plugin and nested `mcp.servers` entry when it+ reports major 2. A failed probe writes no OpenCode wiring and is reported+ as a setup problem; `--agent opencode2` still forces V2 without probing.+ (#1356)+ - Fixed `ai-memory mcp-bridge` exiting when a client sent `server/discover`+ before `initialize`. A client that supports both the 2026-07-28 MCP revision+ and the older `initialize` handshake, such as Antigravity CLI 1.4 and the+ Antigravity 2.24 app, sends that probe first and falls back to `initialize`+ when the server answers with an error. The bridge ended the session instead,+ so the fallback found a closed pipe (`calling initialize: client is closing:+ EOF`) and the client never connected. Until `initialize` arrives, the bridge+ now answers every other request with a JSON-RPC Method not found error,+ ignores notifications such as the client cancelling its probe, and still+ answers `ping`. A client that starts with `initialize` sees no change.+ (#1355)+## [3.1.0] - 2026-10-16### Addeddiff --cc crates/ai-memory-cli/src/commands/install_mcp.rsindex 8508d967,9ca3a3b2..123598c4--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@@ -225,26 -254,15 +258,26 @@@ fn session_less_bridge_args(args: &Inst"--no-session-id".to_owned(),"--server-url".to_owned(),flavored_url_for(args, base_url),- ]+ ];+ if let Some(data_dir) = &args.bridge_data_dir {+ argv.extend([+ "--data-dir".to_owned(),+ data_dir.to_string_lossy().into_owned(),+ ]);+ }+ argv}- /// The upstream URL of an ai-memory bridge entry: `command: "ai-memory"` with+ /// The upstream URL of an ai-memory bridge entry: an ai-memory `command` with/// `args`, or OpenCode's single `command` array, running `mcp-bridge` with a/// `--server-url`. `None` for any other entry.pub(crate) fn bridge_entry_url(entry: &serde_json::Value) -> Option<&str> {+ let entry = entry+ .get("transport")+ .filter(|transport| transport.is_object())+ .unwrap_or(entry);let argv: Vec<&str> = match entry.get("command")? {- serde_json::Value::String(command) if command == BRIDGE_COMMAND => entry+ serde_json::Value::String(command) if is_bridge_command(command) => entry.get("args")?.as_array()?.iter()@@@ -372,30 -385,18 +405,30 @@@ fn stdio_bridge_entry(args: &InstallMcp| McpClient::KimiCode| McpClient::KiroCli| McpClient::Openclaw- | McpClient::IbmBob => plain(),+ | McpClient::IbmBob+ | McpClient::Cline => plain(),McpClient::GeminiCli | McpClient::AntigravityCli => json!({- "command": BRIDGE_COMMAND,+ "command": command,"args": bridge,"timeout": GEMINI_MCP_TIMEOUT_MS,}),McpClient::Cursor | McpClient::VsCodeCopilot | McpClient::Swival | McpClient::Zero => {typed("stdio")}+ McpClient::Freebuff => {+ let env = args+ .auth_token+ .as_ref()+ .map_or_else(|| json!({}), |token| json!({"AI_MEMORY_AUTH_TOKEN": token}));+ json!({+ "command": BRIDGE_COMMAND,+ "args": bridge,+ "env": env,+ })+ }McpClient::Omp => json!({"type": "stdio",- "command": BRIDGE_COMMAND,+ "command": command,"args": bridge,"enabled": true,}),diff --cc crates/ai-memory-store/src/lib.rsindex 3de56da0,54b54287..2ddbf8e1--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@@ -87,19 -86,19 +87,19 @@@ pub use reader::AutoImproveParkedClaim, BriefPageBody, BriefingPage, BriefingSnapshot, ClientActivity,ContaminationFinding, ContaminationReport, ContaminationSummary, ContradictionEdge,DecayCandidate, DecayTombstone, DerivedIndexStatus, EmbeddingTripleCount, FeedbackFinding,- GraphVia, HealthDetail, HealthPage, HybridSearch, InboxCount, InboxEntry, ObservationHit,- ObservationOrder, ObservationPage, ObservationPageResult, ObservationProjectionTotals,- ObservationRecord, OpenSession, PAGE_KINDS, PAGE_VERSIONS_MAX_LIMIT, 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,- SessionConsolidationQueue, SessionConsolidationSummary, SessionDependentRows,- SessionEndDisposition, SessionKindSummary, SessionLine, SessionObservationSnapshot,- SessionPromptTitles, SessionSummary, SessionToolTitles, SettledPage, StatusCounts,- StorageStatus, StoredEmbedding, StoredPageBody, StreamTimings, VectorQuery, WorkspaceScopeRow,- WorkspaceSummary, f32_vec_to_bytes,+ GraphVia, HealthDetail, HealthPage, HybridSearch, IdleOpenSession, InboxCount, InboxEntry,- ObservationHit, ObservationOrder, ObservationPage, ObservationPageResult, ObservationRecord,- OpenSession, PAGE_KINDS, PAGE_VERSIONS_MAX_LIMIT, 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,- SessionConsolidationQueue, SessionConsolidationSummary, SessionDependentRows,- SessionEndDisposition, SessionKindSummary, SessionLine, SessionObservationSnapshot,- SessionSummary, SessionToolTitles, SettledPage, StatusCounts, StorageStatus, StoredEmbedding,- StoredPageBody, StreamTimings, VectorQuery, WorkspaceScopeRow, WorkspaceSummary,- f32_vec_to_bytes,++ ObservationHit, ObservationOrder, ObservationPage, ObservationPageResult,++ ObservationProjectionTotals, ObservationRecord, OpenSession, PAGE_KINDS,++ PAGE_VERSIONS_MAX_LIMIT, 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, SessionConsolidationQueue,++ SessionConsolidationSummary, SessionDependentRows, SessionEndDisposition, SessionKindSummary,++ SessionLine, SessionObservationSnapshot, SessionPromptTitles, SessionSummary,++ SessionToolTitles, SettledPage, StatusCounts, StorageStatus, StoredEmbedding, StoredPageBody,++ StreamTimings, VectorQuery, WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,};pub use retrieval_tuning::{RetrievalTuning, is_session_recall_query};pub use scope::{diff --cc docs/security-boundaries.mdindex 43070b6e,407ed55a..f75ace00--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@@ -113,9 -114,9 +117,9 @@@ means the boundary is not built yet| 14c | Client-supplied event time is bounded and self-scoped (#919) | `ai-memory-hooks/src/payload.rs` `HookEnvelope::occurred_at_micros` — a `/hook` caller's optional `occurred_at` must be `> 0` and `<= now + 5min`; it only sets the caller's *own* admitted session's `started_at`/`ended_at`/`created_at`, never another session/project/user, and the ingest dedup `seen_at`/TTL stays on `now` | `payload.rs` `occurred_at_micros_rejects_a_far_future_timestamp`, `…_rejects_non_positive_values`, `…_rejects_garbage_strings` | MEDIUM — self-scoped numeric bound; no cross-tenant surface (a client already controls its own content) || 14d | `include_related` and the web page's backlinks show and walk only readable projects (#708) | `ai-memory-store/src/reader.rs` `related_walk(.., viewer)` — both the outgoing and incoming hop queries carry `readable_repository_predicate("pg.project_id", viewer)`, the same far-end filter `page_links` and `page_links_preview` apply (the preview's visible totals are counted under it too), so a page in a project the viewer cannot read is neither returned nor expanded; `ai-memory-mcp/src/server.rs` `memory_read_page` passes `viewer_from_parts`, `ai-memory-web/src/routes/page.rs` passes the request's viewer to `page_links_preview`, and the access bump only touches the filtered nodes | `related_walk.rs` `the_walk_hides_and_does_not_cross_projects_the_viewer_cannot_read` (an outgoing and an incoming neighbour in an ungranted restricted project are absent, and so is a granted page reachable only through one; control: a granted restricted project is shown, and no viewer walks the whole graph) — fails with the predicate removed; `ai-memory-web` `tests/suite/routes.rs` `page_backlink_from_an_unreadable_project_is_hidden` (the `/web` page's "Cited by" omits a page in an ungranted restricted project, with no title, path or project name; controls: a reader of both projects and an unrestricted viewer see it) — fails with the page handler passing no viewer to `page_links_preview`; `related_walk.rs` `page_links_preview_caps_in_sql_and_counts_only_readable_neighbours` (back-links from an ungranted restricted project are neither listed nor counted in the total behind "and N more"; control: no viewer counts them all) — fails with the predicate removed; `ai-memory-mcp` `server.rs` `bob_does_not_see_restricted_pages_through_the_related_walk` (an ungranted user's `memory_read_page{include_related}` omits the restricted page; control: no viewer still reaches it) — fails with `memory_read_page` passing `None` instead of `viewer_from_parts` | STRONG || 14e | `memory_write_page` session evidence cites only a session of the target project (#708) | `ai-memory-mcp/src/server.rs` `memory_write_page` — a `session_id` is accepted only when `require_session_in_scope` resolves the session (where its observations landed, else its session row, as `Consolidator::session_target` does) to the same `(workspace_id, project_id)` the write grant was checked against; unknown and foreign ids get one refusal, so the error is no existence oracle; `scope: "global"` with a `session_id` is refused; `refuse_pinned_page_overwrite` keeps a write that cites a session off a pinned page; only a write to `sessions/<id>.md` reconciles the session's queued SessionEnd job | `server.rs` `write_page_refuses_a_session_from_another_project` (a foreign and an unknown session refused, no evidence row written, the foreign job still queued; control: the project's own session accepted), `session_evidence_write_leaves_a_pinned_page_alone` (control: the same write without `session_id` edits the page), `session_evidence_on_another_path_leaves_the_job_queued`, `write_page_rejects_a_malformed_or_global_session_id` — each of the scope check, the pinned check and the session-page-only reconcile proven to fail its test when removed | STRONG |- | 14f | Consolidation apply path validates cross-scope wikilinks against the store (#1218) | `ai-memory-consolidate/src/link_guard.rs` `unresolved_cross_scope_links` — every `[[project:path]]` / `[[workspace/project:path]]` / `[[_global:path]]` target in a proposed body is resolved with the no-create `lookup_existing_scope` (never creates a scope) and batch-checked via `reader.rs` `existing_latest_paths`; a missing workspace/project, an ambiguous project name, or a missing target page de-links the wikilink, while a genuine store failure aborts the consolidation before any write. Typed `relations:` frontmatter targets go through the same check, and `prune_relations` drops an unresolved entry (an emptied relation and an emptied map with it). `delink_body` → `ai-memory-wiki/src/markdown.rs` `delink_wikilinks` drops the brackets and keeps the label, skipping code fences and inline code exactly as `extract_links` does. Wired into all three apply paths (`consolidator.rs` single-page and batch, `bootstrap.rs`) after the pinned/foreign-slot/portable guards and before the atomic `Wiki::apply_batch` / `write_page`, so an invented cross-project dependency can no longer be written and flagged by the lint pass later. Same-project `[[target]]` links stay untouched by design (the target may be written later). The probe runs with no viewer, so it reports nothing for a `restricted` project (the global preferences project excepted): a link into one is always de-linked, and whether a link survived says nothing about which paths exist there | `consolidator.rs` `batch_delinks_invented_cross_scope_wikilinks` (invented `[[_global:nope]]`, `[[otherproj:notes/missing.md]]`, `[[ghostproj:x.md]]` de-linked to plain text; controls: a cross-scope link to an existing page and a same-project pending link survive byte-identical; `dangling_cross_project_links` left empty), `single_page_delinks_invented_cross_scope_wikilinks`, `single_page_drops_unresolved_cross_scope_relations` (unresolved `relations:` entries dropped; controls: a live cross-scope and a same-project target stay), `link_guard.rs` `prune_relations_drops_only_unresolved_cross_scope_entries`, `bootstrap.rs` `bootstrap_delinks_invented_cross_scope_wikilinks` — each proven to fail with the guard neutralized; `markdown.rs` `delink_wikilinks_strips_only_listed_cross_scope_links`, `delink_wikilinks_without_label_keeps_the_target_text`, `delink_wikilinks_skips_code_and_leaves_empty_set_untouched`; store `multi_session.rs` `existing_latest_paths_reports_exactly_the_live_paths` (exact live-path set, superseded path still resolves, foreign scope sees nothing), `existing_latest_paths_reports_nothing_for_a_restricted_project` (real and absent paths answer alike while restricted; control: reopened, the page is seen) | STRONG |+ | 14f | Consolidation apply path validates generated cross-scope body links and every typed relation against the store (#1218, #1353) | `ai-memory-consolidate/src/link_guard.rs` `unresolved_generated_links` keeps body and relation refusals separate. Every `[[project:path]]` / `[[workspace/project:path]]` / `[[_global:path]]` target in a proposed body is resolved with the no-create `lookup_existing_scope` and batch-checked via `reader.rs` `existing_latest_paths`; a missing workspace/project, ambiguous project name, or missing target de-links the body link. Every typed `relations:` target is checked too, including same-project targets; a local target is admitted only when it already exists or is another page in the same atomic batch. `prune_relations` drops malformed and unresolved entries. Same-project body links stay untouched by design. Wired into consolidation single/batch and bootstrap before writes; restricted cross-project probes reveal no paths | `consolidator.rs` `batch_delinks_invented_cross_scope_wikilinks`, `single_page_delinks_invented_cross_scope_wikilinks`, `single_page_drops_unresolved_cross_scope_relations`; `link_guard.rs` `same_project_relations_require_existing_or_same_batch_targets` (missing local relation refused, same-batch relation and dangling local body link controls), malformed and cross-scope prune tests; bootstrap cross-scope test; store `multi_session.rs` `existing_latest_paths_reports_exactly_the_live_paths`, `existing_latest_paths_reports_nothing_for_a_restricted_project` | STRONG || 14g | Web project search and its recall trace honour `memory_query`'s scope rules (#708) and never describe another project | `ai-memory-web/src/routes/search.rs` resolves `workspace`+`project` through `resolve_read_scope` (`lookup_existing_scope_guarded`, no-create, `ProjectAccess::Read`) before any ranking, and refuses partial scope; scoped `/api/v1/search` keeps `lookup_project` / `resolve_many_existing_scopes_guarded`; `ai-memory-web/src/recall.rs` ranks only the resolved scopes through `ReaderPool::hybrid_search_scopes`, whose streams and graph expansion are bound to each `(workspace_id, project_id)`; a search with no scope stays `search_pages_with_meta(.., viewer)` (readable repositories only) | `ai-memory-web` `tests/suite/recall_trace.rs` — `project_search_refuses_a_restricted_project_without_a_grant` (bob, with no grant, gets 403 from `/web/search` with and without `explain=1` and from scoped `/api/v1/search`, with no path, body text or trace in the response, and a `scopes` POST naming the restricted project next to an open one is refused; alice's grant and an unrestricted viewer are the controls), `project_search_fails_closed_on_unknown_and_partial_scope` (unknown project or workspace 404 with nothing created, partial scope 400), `explain_renders_stream_ranks_rrf_authority_and_timings` (a better-matching page in a sibling project never reaches the hits or the trace), `search_scope_selector_lists_only_readable_projects` (the search page's "Search in" selector lists only projects the viewer may read, and a hand-typed `scope=` for an ungranted project is a 403 that leaks nothing; controls: the granted reader and an unrestricted viewer; passing no viewer to `list_projects_with_stats` in the handler fails it), `routes.rs` `search_page_scope_selector_round_trips_and_rejects_malformed_values` (a malformed `scope` is a 400); `recall_trace.rs` `kind_filter_does_not_widen_what_a_viewer_can_read` (a `kind`/`tier` filter only narrows: bob gets no hits and a 403 on a scoped search; alice and an unrestricted viewer are the controls), `search_filters_a_project_by_kind_and_tier_keeping_rank_order` (survivors of a filter keep the unfiltered order), `reranker_is_shown_only_the_pages_the_filter_keeps` (a dropped page never reaches the reranker), `kind_and_tier_filters_hold_in_every_stream` (FTS, entity, vector, observation and both graph directions each filter in SQL; dropping any one stream's predicate fails it), `kind_filter_finds_a_rare_kind_the_unfiltered_page_ranks_out` and `cross_project_kind_filter_sees_past_the_candidate_window` (the filter sees past the candidate window in both modes); `ai-memory-mcp` `tests/suite/web_search_parity.rs` (same top-k order as `memory_query` from `/web` and `/api/v1`, with a deterministic embedder and with none, explain on and off, and merged `scopes`; controls show a web search without the embedder, or the old FTS-only scoped search, would fail it) | STRONG. Bite checks: passing no viewer to `resolve_read_scope` in the search handler, to `lookup_project` or to `resolve_scopes` in the API each fails the restricted-project test; dropping the query vector in `recall.rs` fails the embedder parity tests |-| 15 | Agent-archive restore path confinement, resource bounds, and consistency | `ai-memory-cli/src/commands/restore_agents.rs` stages only bounded regular UTF-8 entries; requires a one-to-one manifest/body/checksum/target mapping; allowlists destinations by scope; rejects symlinked descendants; writes each file atomically and rolls back earlier writes after a later failure. `backup_agents.rs` skips direct and directory-root source symlinks, bounds individual assets, and atomically replaces a private archive only after gzip completion | `backup_agents.rs` `restore_agents_rejects_path_traversal`, `restore_agents_rejects_unauthorized_destination_path`, `restore_agents_verifies_sha256_integrity`, `restore_agents_requires_a_complete_one_to_one_manifest`, `restore_agents_rejects_oversized_entries_from_the_header`, `restore_agents_rejects_a_symlinked_destination_parent`, `backup_agents_does_not_follow_config_or_asset_root_symlinks`, and `failed_backup_leaves_the_previous_archive_intact`; `backup_and_restore_agents_round_trip` is the valid-path control; `restore_agents::tests::rollback_removes_new_files_and_restores_overwrites` covers recovery | STRONG |+| 15 | Agent-archive restore path confinement, resource bounds, and consistency | `ai-memory-cli/src/commands/restore_agents.rs` stages only bounded regular UTF-8 entries; requires a one-to-one manifest/body/checksum/target mapping; allowlists destinations by scope; rejects symlinked descendants; writes each file atomically and rolls back earlier writes after a later failure. `backup_agents.rs` skips direct and directory-root source symlinks, bounds individual assets, attributes a shared skill root only once, and atomically replaces a private archive only after gzip completion | `backup_agents.rs` `restore_agents_rejects_path_traversal`, `restore_agents_rejects_unauthorized_destination_path`, `restore_agents_verifies_sha256_integrity`, `restore_agents_requires_a_complete_one_to_one_manifest`, `restore_agents_rejects_oversized_entries_from_the_header`, `restore_agents_rejects_a_symlinked_destination_parent`, `backup_agents_does_not_follow_config_or_asset_root_symlinks` (Claude and Antigravity roots), and `failed_backup_leaves_the_previous_archive_intact`; `backup_and_restore_agents_round_trip` and `antigravity_backup_round_trips_every_documented_skill_root` are the valid-path controls; `restore_agents::tests::rollback_removes_new_files_and_restores_overwrites` covers recovery | STRONG || 16 | Relay queue identity, migration, and private filesystem state | `companions/ai-memory-relay/src/queue.rs` `Queue::open_inner` performs read-only identity preflight, rechecks under `IMMEDIATE`, commits schema and metadata together; `configure` checks the presence of user objects and rechecks `identity`/`schema_version` metadata on the same connection before every bounded BUSY/LOCKED retry; `fsguard.rs` checks existing paths and creates owner-only files before SQLite opens them | `tests/relay.rs` `a_foreign_database_is_refused_byte_for_byte`, `unknown_schemas_refuse_without_mutation`, `a_foreign_database_with_a_writer_is_refused_before_write_coordination`, `a_foreign_identity_after_preflight_is_refused_without_mutation`, `a_foreign_identity_during_journal_retry_is_refused_without_mutation`, `journal_retry_refuses_a_changed_version_or_empty_database_without_mutation`; controls: `journal_transition_retries_sqlite_lock_without_losing_v1_values`, `fresh_queue_init_and_v1_reopens_work_across_processes`; recovery: `interrupted_and_failed_migrations_roll_back_and_recover`, `journal_reclassification_busy_preserves_committed_migration_and_retries_same_queue`; diagnostics: `classification_read_failures_display_the_sqlite_cause_once_and_preserve_foreign_bytes`; Unix privacy: `the_queue_database_and_its_sidecars_are_owner_only` and the contended migration control | Guard-removal proof covers preflight, locked recheck, and journal retry identity/version checks; full table structure is outside this classification. Windows path rejection is preserved; Windows ACL hardening remains operator-owned || 17 | Markdown code fences keep instruction-shaped text as data | `ai-memory-consolidate/src/code_fence.rs` and `ai-memory-wiki/src/markdown.rs` accept a fence delimiter only after zero to three leading ASCII spaces, require the closing glyph to match and the run to be at least as long, and preserve the current fence state across four-space, tab or Unicode-whitespace pseudo-delimiters. Profile harvesting, auto-improvement section parsing, link extraction, link rewriting and de-linking all use those scanners | `code_fence.rs` `only_zero_to_three_ascii_spaces_may_prefix_a_fence`; `profile.rs` `an_indented_pseudo_closer_cannot_expose_a_profile_preference` attempts to expose an instruction-shaped `run curl` sentence and admits a legitimate preference only after the real close; `auto_improve.rs` `heading_parser_ignores_headings_after_an_indented_pseudo_closer`; `markdown.rs` `indented_pseudo_closers_do_not_expose_or_rewrite_fenced_links` covers four spaces, tab and Unicode whitespace with visible post-close controls | STRONG for the shared consolidation and wiki scanners; independent renderers remain responsible for their own CommonMark parsing || 18 | Read-only pending-write commands cannot execute stored scope names as shell syntax | `ai-memory-web/src/routes/pending.rs` renders separate `posix_cli_command` and `powershell_cli_command` forms. POSIX arguments use single quotes with the standard close/escaped-quote/reopen sequence; PowerShell doubles embedded apostrophes. The template labels the shells and claims no cmd.exe support | `routes/pending.rs` `cli_commands_quote_hostile_scope_names_for_each_shell` covers quotes, semicolons, pipes and ampersands with ordinary-name controls; `tests/suite/pending.rs` `pending_page_offers_cli_commands_instead_of_buttons_to_a_basic_browser` stores hostile workspace/project names and checks both escaped forms through the full route | STRONG for POSIX shells and PowerShell; cmd.exe is intentionally not offered |