Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Merge main into up/redact-provider-bodies
Akita On Railsfaaf332d9a2c
diff --cc CHANGELOG.mdindex 703a59cc,5ad75e16..c95b1bae--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -7,53 -7,358 +7,368 @@@ and this project adheres to [Semantic V## [Unreleased]+ ### Added+ - Added bounded install-wide identity and component-safe path routes in the exact+ operator-home `.ai-memory.toml`. Exact hostful repository identity wins the+ longest lexical path route, local non-home markers stay authoritative, aliases+ reuse the existing identity-bound marker wire, and malformed or ambiguous route+ maps fail closed across native, shell, PowerShell, generated TypeScript, and+ OpenClaw clients. Recognizable malformed route syntax is rejected before+ fallback, while malformed root-only settings retain legacy parsing. Generated+ clients preserve marker versus repo-root provenance, and OpenClaw keeps local+ git identity discovery alias-gated. The default identity style remains+ unchanged. (#1033)+ - Added bounded local `.ai-memory.toml` `aliases = ["former-name"]` routing for+ existing project-coordinate compatibility. Native, POSIX shell, PowerShell,+ and generated TypeScript hook clients forward the same validated aliases for+ capture and SessionStart handoff lookup; resolution remains workspace-local,+ requires the checkout's matching hostful git-remote identity, preserves the+ existing UUID, and permits only write-authorized canonical-name promotion.+ Aliases are not persisted, and the default naming style is unchanged. (#1033)+ - Added read-only project-coordinate diagnostics to `ai-memory doctor` and the+ root-gated `GET /admin/project-coordinate` endpoint. The report classifies+ exact, canonical-compatibility, legacy-compatibility, missing, and ambiguous+ names; shows safe local marker/repository evidence and rename eligibility;+ and reports collisions without creating, claiming, renaming, or exposing+ remote credentials or marker paths. Ambiguous results keep local session+ evidence and mark server capture counts unavailable; any returned preferred+ project is contextual only, never a unique resolution. (#1033)+ - Added the cross-project profile (`docs/cross-project-profile.md`, design in+ `docs/design-cross-project-profile.md`): a small set of `profile/` pages+ recording how the user usually works, delivered to every project and every+ harness at session start as a fenced, byte-budgeted digest of defaults that+ rank below the user's instructions, the repository's rules file and the+ project's own memory. It is on by default for a single-operator server,+ shared across every workspace, and off on a multi-user server until+ `[profile] enabled = true`, which gives each operator a private, restricted+ profile; `share = "global"` or `"workspace"` makes a team profile that is+ read-open and write-gated like `_global`, admits a habit only on evidence+ from at least two operators, and is presented as team defaults. The digest filters entries by the+ stack the project's activity shows, stays byte-identical between sessions,+ and gives a project with no memory yet a larger baseline. `memory_write_page`+ and `memory_delete_page` accept `scope: "profile"`, `memory_query` returns+ profile entries in `global_scope_hits`, a marker's `[profile] contribute` /+ `consume` keys opt a project out of contributing or receiving (an opt-out+ stays recorded until a marker says otherwise), and+ `ai-memory profile status | list | show | forget | review | rebuild`+ inspects and curates it, while `ai-memory profile apply` writes the entries+ that fit a repository into a managed block of its rules file (`--remove`+ takes it out), never touching anything outside the block. Entries are+ learned on their own: a server pass, run after each session ends and+ hourly, harvests the user's own+ preference-shaped prompts (never tool output), the project's curated pages+ and its stack signals, and converges them across projects into entries once+ the user states a choice as general or it appears in `min_projects`+ projects, the newest ruling winning. With an LLM provider the pass+ classifies and restates entries through JSON-schema calls and falls back to+ the zero-LLM path on any error. It never rewrites an entry edited by hand,+ and an entry removed with `profile forget` stays removed until the user+ states it again. (#1000)+ - Added `ai-memory resume --search` with immediate type-to-filter name search,+ and `resume --all`, which keeps the previous cross-checkout picker: every+ linked checkout, the current one first, each listed with its own fully+ paginated query. (#1039)+ - Added `install-hooks --agent claude-code --scope project`, which writes the+ hook configuration to the checkout's gitignored `.claude/settings.local.json`+ (where Claude Code reads it: the git root, or the launch directory on+ Windows and when the repository root is the home directory) instead of the+ user-level `settings.json`, so capture is opted in per repository. The+ installer warns when that file is not ignored by git, refuses the+ inline-token fallback for it, notes when the other scope also carries+ ai-memory hooks, and keeps its backups under the data dir instead of the+ checkout; `uninstall` run inside the checkout sweeps it and reminds you to+ do the same in other project-scoped checkouts; `upgrade` and the+ `ai-memory run` auto-wire no longer add user-level Claude Code hooks on top+ of a project-scoped install. (#1034)+ - Added explicit MCP behavior annotations (title, read-only, destructive,+ idempotent, and open-world hints) to all 23 tools. Reordered the MCP server+ instructions so scope selection, untrusted-memory handling, deliberate+ cross-project broadening, capture policy, and handoff safety remain complete+ within the first 2,048 characters used by truncating clients. The longer+ per-tool routing reference remains available to clients that accept it.+ (#920)+ - Added env-only named launch profiles for `ai-memory run --profile NAME` via+ `[run.profiles.<name>.env]` in `config.toml`. Profile values feed the same+ native-session, auto-wire, and child-process environment path as `--env`;+ precedence is profile, then `--env-file`, then repeated `--env`. Unknown or+ invalid profiles fail before a workstream lease or child process; an unknown+ name lists the defined profiles or prints a table to paste. (#922; error+ message, tests and docs from #1031 by @geeksilva97)+ - Added cross-project attribution for native lifecycle file-tool events whose+ harness keeps reporting the parent session's cwd. A bounded, recognized+ absolute target reroutes only when every path proves the same repository or+ marker boundary; destination capture exclusions and server profiles are+ resolved before the event is spooled. Relative, mixed-project, unsupported,+ and arbitrary non-project paths keep the original route. (#932)+ - Added `serve --enable-api` / `AI_MEMORY_ENABLE_API=true` to mount the+ authenticated read-only `/api/v1` surface without the browser UI. Existing+ `--enable-web` behavior is unchanged and still includes the API. Documented+ the acceptance and safety boundary for a repository-backed team-wiki sync+ companion. (#986)+ - Added `[handoff].claim_on_session_start` (default `true` - unchanged+ behavior). When set to `false`, `SessionStart` no longer claims a pending+ handoff automatically; it renders a non-consuming notice naming the exact+ `handoff_id`, `from_agent`, and age instead (mirroring the existing inbox+ notice: metadata only, never the stored summary/open-questions/next-steps+ text), and the agent or operator picks it up explicitly with+ `memory_handoff_accept`. Fixes an unrelated next session, a different+ harness, or a non-interactive launch silently consuming a baton meant for+ a specific session. Server-wide for now; a per-project override is left for+ a follow-up change. (#1030)+ - Added a default-quit prompt after a successful interactive managed run so the+ operator can re-run the current harness or switch to another installed+ harness in the same workstream. Utility, failed, interrupted,+ non-interactive, and custom-`--executable` runs keep their existing exit+ behavior. Resolves #909. (#975)+ - Added `ai-memory backup-agents` and dry-run-by-default+ `ai-memory restore-agents` commands for host agent configurations, skills,+ plugins, and project instructions. Archives are written atomically with+ private Unix permissions, MCP config text is sanitized by default, and+ restore bounds archive input, verifies manifest checksums and completeness,+ refuses duplicate or symlink-escaping targets, and keeps overwritten files+ as timestamped backups. Other asset types are copied verbatim and may contain+ secrets or active instructions/code. (#962)+ - Added a NixOS module (`nix/nixos-module.nix`, exposed as+ `nixosModules.default`) with a dedicated non-login system user and a hardened+ NixOS systemd sandbox. A minimal typed set plus `freeformType` renders+ declarative `config.toml`; values land in a world-readable store path, so+ secrets (including `llm_headers`) use `ageSecret`, `sopsSecret`, or+ `environmentFile`. Non-loopback binds require a secret source. The module+ includes opt-in web, firewall, and resource settings plus eval and privileged+ container checks. Flake packages are exported for x86_64 Linux, aarch64+ Linux, and Apple Silicon macOS; Intel macOS remains available through the+ release tarball and Homebrew rather than the pinned Nixpkgs revision. (#989)+ - Added `ai-memory doctor` reporting for Claude Code's default native+ `memory/` store for the current repository: location, file count, and whether+ the nearest marker's `ignore_paths` would exclude a read. Repository-root+ resolution keeps worktrees and subdirectories on the same report, and the+ output warns that shell/PowerShell compatibility hooks do not enforce the+ exclusion. Resolves #1003. (#1005)+ - Added per-event outcomes to `/hook/batch` acknowledgements and process-lifetime+ ingest counters for stored events, replays, recovery, ignored endings,+ collisions and failures. Legacy acknowledgement fields were preserved. (#1015)+ - Added receipt outcomes and delivery counts to the companion relay. Opening a+ schema 1 queue now upgrades it atomically to schema 2; older relay binaries+ refuse schema 2, so downgrade requires a pre-upgrade backup with all queue+ users stopped. Pending order and existing delivery metadata were preserved.+ Receipts now retain their first known outcome. (#1015)+ - Added `ai-memory list-projects [--workspace] [--json]`: a plain, scriptable+ listing of every workspace/project pair the server knows about, sorted by+ workspace then project. Previously the only way to see this from outside+ an interactive `show` session was to call `GET /api/v1/projects` directly.+ (#1022)+ - Added scope and policy preflight to `ai-memory hook --check-capture`, including+ event eligibility, sanitized routing hints and server-remapping information.+ Partial scope, excluded events, rejected profiles and oversized hints refuse+ capture. Inspection neither ingests events nor claims handoffs. (#1019)+ - Added the latest scoped consolidation job's state and attempt count to HTTP+ session summaries and MCP `memory_read_session_observations`. The field is+ `null` when no job exists; provider errors remain private and existing session+ ownership filters are preserved. (#1018)+ - Added incremental paging to scoped HTTP `recent` reads with `updated_since`+ and an opaque, scope-bound cursor. Queries preserve equal-time ordering,+ exclude expired and superseded pages and recheck authorization on each+ request. Calls without incremental arguments retain their existing array+ response. Added a generic MCP/HTTP integration guide. (#1017)+ - Added machine-authenticated `GET /identity`, available with the web UI+ disabled, and `ai-memory doctor` diagnostics for caller identity, external+ capture ownership and sessions with multiple capture sources (native events+ or distinct extensions, including backfill).+ Mixed-source counts preserve scope, session ownership and time-window filters;+ older servers leave unsupported fields unknown. (#1016)+ - Added shared capture privacy checks to the relay and the conversation importer,+ run before an event is hashed, persisted, previewed or delivered: they refuse+ credential-shaped native identities, scrub nested credentials while keeping+ numeric token counts, and drop locally a relay item queued before them that+ fails them, so it no longer holds its session. (#1072)+ - Added `[handoff].create_on_session_end` (default `true` - unchanged+ behavior). When set to `false`, unmanaged session ends write the session+ summary page and enqueue consolidation as usual, but skip creating an+ automatic open handoff for the next session; OpenCode turn checkpoints+ refresh the page without a baton too. Explicit handoffs created via+ `memory_handoff_begin` and managed workstream runs remain unaffected.+ Server-wide: applies to every operator on this server. (#1043)+ - Added bounded, sanitized native-record and adapter correlation provenance to+ managed-workstream search/tail results and the CLI's text/JSON output, with+ compatible optional fields and sanitization of legacy provenance on reads. (#1057)+ - Added Portuguese history phrases to the existing opt-in session-recall+ router (`[retrieval] query_intent`), including accented and unaccented spellings of+ "última sessão", "onde paramos ontem", and "decisão anterior". Word+ boundaries and explicit history phrases keep technical session queries+ unchanged; routing remains off by default. (#1056)+ - Added shared, typed and bounded `entities`, `abstract`, and `relations`+ metadata to MCP `memory_write_page` and admin `/admin/write-page`, plus bounded+ MCP `kind` while preserving the admin's legacy `kind` adapter. Kept existing+ request shapes, entity normalization, authenticated attribution and the wiki+ write pipeline. Documented whole-page replacement, raw-input metadata bounds+ and trimmed relation scope components. (#1055)+ - Added structured results for the existing auto-improvement eval execution in+ review reports, staged run metadata, and accepted proposal sidecars, with+ server-generated eval IDs, evaluated request/body digests, checker invocation+ identity, observed success/rejection/failure/timeout, and sanitized bounded+ reasons. Report deserialization discarded supplied eval observations. (#1053)+ - Added `grizzybot` as a recognised agent (wire value `grizzybot`, alias+ `grizzy-bot`), so GrizzyBot's lifecycle events are attributed to it instead+ of `other` and its tool calls are captured as closed-schema tool families,+ like other Claude Code-shaped agents. GrizzyBot posts to `/hook` and+ `/mcp` itself, so there is nothing to install. Adds migration V72 to extend+ the `sessions.agent_kind` CHECK constraint. (#1036)+ - Added GitHub Copilot CLI as a hooked agent: `install-hooks --agent+ copilot-cli` writes `$COPILOT_HOME/hooks/ai-memory.json` (default+ `~/.copilot/hooks/ai-memory.json`) with Copilot's flat, matcher-less entries+ and PascalCase event names, so Copilot sends its VS Code/Claude-compatible+ payload. Ten events — Claude Code's nine plus `PostToolUseFailure` — with+ native commands enforcing capture exclusions; tool output is read from+ `tool_result.text_result_for_llm` and the outcome from+ `tool_result.result_type`. The `SessionStart` hook delivers the prior+ session's handoff through Copilot's top-level `additionalContext` (ported+ from #1069). There is deliberately no `--scope project`. The bare+ `install-mcp --client copilot` alias keeps meaning VS Code Copilot;+ `ai-memory run copilot` follows separately. (#1040)+ - Added `install-mcp --client copilot-cli`, which merges ai-memory's remote+ entry (`type: "http"`, `url`, bearer `headers`, `tools: ["*"]`) into the root+ `mcpServers` map of `$COPILOT_HOME/mcp-config.json` (default+ `~/.copilot/mcp-config.json`), preserving other servers. `install-hooks+ --agent copilot-cli` without `--server-url` now reads the server URL and+ bearer back from that entry, and `uninstall` removes it. (#1040)+ - Added an optional `session_id` to `memory_write_page`, so an agent can+ write a session's page with its own model and keep it traceable to the+ session. The session must belong to the project the page is written to, and+ the page records it as session evidence. A page that cites a session does+ not overwrite a pinned page. Writing `sessions/<id>.md` also stamps the+ frontmatter `memory_consolidate` writes there (`session_id`, `agent`,+ `consolidated`, plus `consolidated_by: agent`), defaults the tier to+ `episodic`, applies the same duplicate-title suffix, and marks the session's+ queued SessionEnd consolidation job completed. (#1038)+ - Added `identity_style = "path" | "host_path"` marker control for remote-backed+ project naming. `path` names from the full repository path without the host+ (`github.com/acme/api` → `acme-api`); `host_path` preserves the former naming+ behavior as an explicit opt-out. Captures always route by the full hostful+ identity, and cross-forge path collisions never merge. (#1033)+ - Added `[hook_spool] max_attempts` and+ `AI_MEMORY_HOOK_SPOOL_MAX_ATTEMPTS` to configure failed drain passes before+ dropping an event; zero disables attempt-based drops while age and spool+ size limits remain. (#1092)+### Changed+- Redacted provider response bodies from the error surfaces this change+ touches: the `memory_consolidate` and `memory_auto_improve` MCP errors, the+ `memory_explore` degradation reason and warning, the reranker degradation+ warning, the consolidator's transient-retry warning, the SessionEnd+ consolidation worker's queue `last_error` and failure logs, the+ auto-improve scheduler's claim `last_error` and tick warnings, and the hook+ router's checkpoint-fallback warning now carry a stable `class`/`status`+ summary (for example `class=provider status=400`) instead of the error's+ `Display`, which for a provider failure includes the upstream response+ body. Other error surfaces are unchanged. (#1103)+ - Changed static CLI/MCP project-name resolution to accept an existing+ repository's canonical hostless path name and its v2 basename compatibility+ key. Reads remain find-only; an authorized write through the canonical key+ promotes only `projects.name` in place, preserving the project UUID and all+ dependent rows. Project scope manifests preserve the optional full hostful+ identity/source and derived keys so clean reindex reconstructs the same UUID+ and lookup behavior; older manifests remain valid. MCP, admin, and+ managed-workstream writes refresh the manifest after promotion and disclose a+ post-commit refresh failure for startup repair on both success and any later+ operation error, retaining the first warning across busy retries and lease+ wait-out; managed-run caller validation happens before promotion.+ Ambiguous cross-forge keys and target-name conflicts fail closed. Current+ clients now explicitly send `path` for a valid remote and send explicit+ `host_path` for the opt-out; a new server deliberately interprets an omitted+ field as legacy `host_path` so old clients cannot be silently renamed. Existing compatible projects are+ promoted only by authorized capture/write and keep their UUID; read-only+ handoff/static lookups never rename. (#1033)+ - Changed the documented precedence between rules and memory: the user's+ instructions, then the repository's rules file, then the project's memory,+ then the cross-project profile. Where no hard rule exists, agents now use+ what memory already knows instead of asking again; the routing snippet,+ MCP instructions and durable-pages skill send standing cross-project+ preferences to the profile (`scope: "profile"`). (#1000)+ - Scoped `ai-memory resume` to the current checkout by default instead of every+ linked project (`--all` restores the old view) and removed its default result+ cutoff with bounded server pagination, preserving Left/Right harness+ selection. Explicit limits now apply after the initial search; against an+ older server that ignores paging, the picker warns and shows the first page.+ `continue` retained its cross-directory behavior. (#1039)- Documented FutureInfra as an endpoint for the existing `openai-compat`provider. (#1026)+ - `.github/workflows/nix.yml` builds the flake on `x86_64-linux` for path-+ filtered PRs and pushes (package smoke + NixOS module eval /+ sandbox-parity). The `aarch64-darwin` package smoke and the privileged+ NixOS container smoke run only on schedule, `workflow_dispatch`, or a PR+ labelled `nix` / `full-ci`. (#989)+ - Restricted managed-workstream provenance to scrubbed source labels and an+ explicit scalar metadata allowlist, with 512-byte string bounds. Client event+ ids beginning with `managed-run:` are reserved for server checkpoints and+ extraction-loss annotations. Active-run retries reject changes to an existing+ event's agent, native session or kind, and retain its first indexed content+ and provenance across sanitizer changes. (#1057)+ - The SessionEnd consolidation worker leaves a session page alone when the+ agent wrote it through `memory_write_page` and no observation arrived after+ it: the page records the session's observation count as+ `observation_generation`, and the worker completes a job whose generation+ that count reaches instead of replacing the page with the server's+ provider. A page written before the session's last observation is+ consolidated as before. (#1038)+ - Required managed-run finish imports and finished retries, and the cancel,+ heartbeat, native-session link and context-acceptance routes, to pass an+ authenticated owner check and current project access checks (repeated in+ finish's writer transaction), so another operator cannot release or rebind a+ run. Database users required current Write access; trusted+ proxy operators retained their existing project policy. Active API keys+ remained valid after human login was disabled. Shared, unattributed runs and+ late finishes of still-active runs retained their existing behavior. (#1075)+ - Required new managed native-session bindings and imports to preserve the+ exact original identity within 512 UTF-8 bytes and pass privacy validation+ before use or persistence. Invalid historical identities were projected as+ unknown (`native_session_id: ""`) in workstream search without rewriting+ stored history; the CLI also protected reads from older servers. (#1079)### Fixed- - Fixed `memory_handoff_list` MCP tool calls being counted under writes in- `client_activity`: the read-only inspection tool is now classified as a read- in `tool_call_is_write`. (#1088)- - Fixed a store write sent while the writer was shutting down occasionally- waiting forever instead of failing with `WriterClosed`: the writer now- closes its queue and drains in-flight commands before it stops.- - Fixed `resume` and `workstreams` running `git status` on every linked checkout- before listing anything: listing now reads only the checkout's stable- fingerprints, so a large working tree or a slow filesystem-monitor hook no- longer blocks the picker before its first frame. (#1039)- - Fixed the generated OpenCode 2 plugin ending every tracked session when- OpenCode unloads it on idle-location eviction. Unload is not shutdown: the- host and its sessions stay alive, so each eviction froze a live session- (`SessionStart` cannot reopen an ended OpenCode session), fabricated a- spurious summary page and open handoff, and made the next baton fetch fail- with `invalid state: an ended session cannot accept a handoff`. Plugin- unload no longer posts `session-end`; deletion (`session.deleted`) remains- the end signal and a completed root turn already publishes its continuation- checkpoint and baton. Regenerate the plugin with- `ai-memory install-hooks --agent opencode2 --apply`. (#1074)- - Fixed watcher reindexing racing with writes and batches to the same page by- sharing their per-page mutex from disk read through SQLite upsert. Both- mutation guards are released before embedding; external editors remain- outside this coordination. (#1059)- - Fixed a managed Claude Code run losing its conversation after `/resume` on a- Claude Code background session. The run used to finish on the foreground- session it started with, which held none of the conversation, so the next- `ai-memory run claude` or `continue` resumed it and Claude opened an empty- session. A Claude run now finishes on the background session its own- session attached to in this checkout, found from that transcript's- `sessionKind: "bg"` records; another launch's background session is never- taken. (#1050)+ - Fixed hook `title_hint` extraction leaving a trailing CR on Windows CRLF+ payloads and keeping embedded newlines on SessionStart, Notification, and+ PostCompaction titles. First-line splitting now uses `str::lines`. (#1111)+ - Fixed wiki confinement walks failing on Windows with `PermissionDenied`+ (sharing violation) or `ERROR_DELETE_PENDING` when a concurrent commit or+ the atomic writer held or rename-replaced a file mid-walk; per-entry walk+ probes now skip those as transient churn exactly like the NotFound vanish+ race, while every entry that does stat is still refused when link-like and+ root-level probes keep their strict semantics. (#1107)+ - Fixed generic OpenCode commands selecting integration contracts from command+ spelling instead of the executable's major version. `run opencode` now probes+ the exact executable once and carries the resolved V1/V2 dialect through+ session discovery, launch, auto-wire, and transcript import; hook and MCP+ installers use the same strict resolver, while container-oriented+ `setup-agent` requires an explicit V1/V2 artifact dialect. Probe and launch+ share one captured child environment with `--env` overlays, including Windows+ key casing. Automatic launch skips an unresolvable OpenCode candidate without+ hiding other harnesses. Hook/MCP transitions reuse ownership-verified endpoint+ and token settings across both schemas and reject conflicting generated+ entries. Migrations remove only entries proven generated by ai-memory, and plugin+ cleanup never overwrites a concurrent user replacement while restoring an+ unowned quarantined file. (#1097)+ - Fixed Codex on the Kimi coding endpoint failing every model call with+ "tools.function.parameters is not a valid moonshot flavored json schema+ (... detected infinite recursion without termination condition ...)".+ Moonshot's validator never resolves `$ref`, so the `$defs`/`$ref` pairs+ Codex forwards from MCP input schemas failed the request at any depth —+ including the `ReasoningTier` reference on `memory_query` and+ `memory_explore` and the `FeedbackKind` reference on `memory_feedback` —+ not just at the root. The `?flavor=moonshot` dialect now inlines every+ `#/$defs/*` reference and drops the emptied `$defs` table; nested+ combinators (which Moonshot accepts) and runtime validation are unchanged.+ `?flavor=bedrock` and `?flavor=gemini` keep serving `$defs`/`$ref` as+ before. (#1093)+ - Confined wiki reads, writes, indexing, recovery, and lifecycle cleanup to real+ project-tree directories by refusing symbolic links and filesystem reparse+ points at namespace roots or descendants. (#1107)+ - Fixed a later hook event carrying a managed-run id linking its native session+ to that run without the checks SessionStart applies. It now links only from+ the run's own project and operator; an event from elsewhere is still captured+ but no longer repoints the run. (#1082)+ - Fixed completed retries and no-op session endings advancing+ `last_persisted_ms` without a durable write. Recovery still advances the+ timestamp when it commits a new page or terminal effect. (#1015)- Fixed interrupted launchers blocking an immediate managed-workstream restartby adding explicit `ai-memory run --force-unlock` recovery. The serveratomically expires and replaces only a lease attributed to the samediff --cc crates/ai-memory-cli/src/commands/serve.rsindex 8bea5c15,76bd4f72..1f65ed4b--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@@ -4110,140 -4241,189 +4292,323 @@@ mod tests);}+ // Mutation captured: persisting the error's `Display` writes the private+ // provider body into the queue row; the worker must persist only the+ // redacted class/status summary, and a failed first attempt keeps the+ // queue's scheduled retry instead of flipping terminal.+ #[tokio::test]+ async fn session_end_worker_persists_redacted_summary_not_provider_body() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let workspace_id = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let project_id = store+ .writer+ .get_or_create_project(workspace_id, "project", None)+ .await+ .unwrap();+ let session_id = SessionId::new();+ store+ .writer+ .begin_session(NewSession {+ occurred_at: None,+ id: session_id,+ workspace_id,+ project_id,+ agent_kind: AgentKind::Codex,+ cwd: None,+ actor_user: None,+ })+ .await+ .unwrap();+ store+ .writer+ .insert_observation(Sanitized::new(+ NewObservation {+ occurred_at: None,+ session_id,+ workspace_id,+ project_id,+ kind: ObservationKind::UserPrompt,+ extension: None,+ source_event: None,+ title: "finish".into(),+ body: "end the session".into(),+ importance: 8,+ },+ &Sanitizer::default(),+ ))+ .await+ .unwrap();+ store.writer.end_session(session_id, None).await.unwrap();+ store+ .writer+ .enqueue_session_consolidation(workspace_id, project_id, session_id)+ .await+ .unwrap();++ let consolidator = Arc::new(Consolidator::new(+ store.reader.clone(),+ store.writer.clone(),+ Wiki::new(tmp.path(), store.writer.clone()).unwrap(),+ Arc::new(Provider400ConsolidationLlm),+ workspace_id,+ project_id,+ ));+ let notify = Arc::new(tokio::sync::Notify::new());+ let completed = Arc::new(tokio::sync::Notify::new());+ let cancel = CancellationToken::new();+ let task = tokio::spawn(run_session_consolidation_worker(+ store.writer.clone(),+ consolidator,+ notify.clone(),+ cancel.child_token(),+ completed.clone(),+ ));+ notify.notify_one();++ // Read the queue row through a read-only connection (WAL readers do+ // not block the writer): the row exists from enqueue, is `running`+ // while claimed, and settles with a `last_error` once the failure+ // lands.+ let db = rusqlite::Connection::open(store.db_path()).unwrap();+ let deadline = std::time::Instant::now() + Duration::from_secs(5);+ let (state, last_error, next_attempt_at) = loop {+ let row = db+ .query_row(+ "SELECT state, last_error, next_attempt_at \+ FROM session_consolidation_jobs WHERE session_id = ?1",+ rusqlite::params![session_id.as_bytes()],+ |r| {+ Ok::<(String, Option<String>, Option<i64>), _>((+ r.get(0)?,+ r.get(1)?,+ r.get(2)?,+ ))+ },+ )+ .ok();+ if let Some(row) = &row+ && &row.0 != "running"+ && row.1.is_some()+ {+ break row.clone();+ }+ assert!(+ std::time::Instant::now() < deadline,+ "failure row never settled"+ );+ tokio::time::sleep(Duration::from_millis(50)).await;+ };+ cancel.cancel();+ task.await.unwrap();++ assert_eq!(+ last_error.as_deref(),+ Some("consolidation failed: class=provider status=400"),+ "only the redacted class/status summary may be persisted"+ );+ let last_error = last_error.expect("checked above");+ assert!(+ !last_error.contains("SENTINEL_PRIVATE_BODY"),+ "provider body leaked into the queue row: {last_error}"+ );+ assert_eq!(+ state, "pending",+ "a failed first attempt must keep the queue's retry"+ );+ assert!(+ next_attempt_at.is_some(),+ "the retryable failure must keep a scheduled retry"+ );+ }++ /// An ended session with one observation and a queued SessionEnd job,+ /// plus a session page carrying `frontmatter`, as `memory_write_page`+ /// leaves it when the agent writes the page itself.+ async fn session_with_written_page(+ frontmatter: serde_json::Value,+ ) -> (TempDir, Store, Wiki, WorkspaceId, ProjectId, SessionId) {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let workspace_id = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let project_id = store+ .writer+ .get_or_create_project(workspace_id, "project", None)+ .await+ .unwrap();+ let session_id = SessionId::new();+ store+ .writer+ .begin_session(NewSession {+ occurred_at: None,+ id: session_id,+ workspace_id,+ project_id,+ agent_kind: AgentKind::Codex,+ cwd: None,+ actor_user: None,+ })+ .await+ .unwrap();+ store+ .writer+ .insert_observation(Sanitized::new(+ NewObservation {+ occurred_at: None,+ session_id,+ workspace_id,+ project_id,+ kind: ObservationKind::UserPrompt,+ extension: None,+ source_event: None,+ title: "finish".into(),+ body: "complete the durable job".into(),+ importance: 8,+ },+ &Sanitizer::default(),+ ))+ .await+ .unwrap();+ store.writer.end_session(session_id, None).await.unwrap();+ store+ .writer+ .enqueue_session_consolidation(workspace_id, project_id, session_id)+ .await+ .unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ wiki.write_page(WritePageRequest {+ workspace_id,+ project_id,+ path: PagePath::new(format!("sessions/{session_id}.md")).unwrap(),+ frontmatter,+ body: "# Agent page\n\nWritten by the agent before the session ended.".into(),+ tier: Tier::Episodic,+ pinned: false,+ title: None,+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),+ evidence: Vec::new(),+ })+ .await+ .unwrap();+ (tmp, store, wiki, workspace_id, project_id, session_id)+ }++ /// Run the worker once over the queued job and return the session page body.+ async fn run_worker_once(+ store: &Store,+ wiki: Wiki,+ llm: Arc<dyn LlmProvider>,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ session_id: SessionId,+ ) -> String {+ let consolidator = Arc::new(Consolidator::new(+ store.reader.clone(),+ store.writer.clone(),+ wiki,+ llm,+ workspace_id,+ project_id,+ ));+ let notify = Arc::new(tokio::sync::Notify::new());+ let completed = Arc::new(tokio::sync::Notify::new());+ let cancel = CancellationToken::new();+ let task = tokio::spawn(run_session_consolidation_worker(+ store.writer.clone(),+ consolidator,+ notify.clone(),+ cancel.child_token(),+ completed.clone(),+ ));+ notify.notify_one();+ tokio::time::timeout(Duration::from_secs(5), completed.notified())+ .await+ .expect("worker should settle the queued job");+ cancel.cancel();+ task.await.unwrap();+ let now = jiff::Timestamp::now().as_microsecond();+ assert!(+ store+ .writer+ .claim_session_consolidation(now, now - 1)+ .await+ .unwrap()+ .is_none(),+ "a settled job must not be claimed again"+ );+ store+ .reader+ .page_body_by_ids(+ workspace_id,+ project_id,+ &format!("sessions/{session_id}.md"),+ )+ .await+ .unwrap()+ .map(|page| page.body)+ .unwrap_or_default()+ }++ /// The agent wrote the session page while the session was open, and no+ /// observation arrived after it: the worker completes the job without a+ /// completion (the provider panics if called) and keeps the page.+ #[tokio::test]+ async fn session_consolidation_worker_keeps_a_current_agent_page() {+ let (_tmp, store, wiki, workspace_id, project_id, session_id) =+ session_with_written_page(serde_json::json!({+ "consolidated_by": "agent",+ "observation_generation": 1,+ }))+ .await;+ let body = run_worker_once(+ &store,+ wiki,+ Arc::new(PanicLlm),+ workspace_id,+ project_id,+ session_id,+ )+ .await;+ assert!(body.contains("Written by the agent"), "{body}");+ }++ /// Controls: a page the agent wrote before the job's last observation,+ /// and a page with a current generation that no agent wrote, are both+ /// consolidated as before.+ #[tokio::test]+ async fn session_consolidation_worker_replaces_a_stale_or_non_agent_page() {+ for frontmatter in [+ serde_json::json!({"consolidated_by": "agent", "observation_generation": 0}),+ serde_json::json!({"observation_generation": 1}),+ ] {+ let (_tmp, store, wiki, workspace_id, project_id, session_id) =+ session_with_written_page(frontmatter.clone()).await;+ let body = run_worker_once(+ &store,+ wiki,+ Arc::new(SuccessfulConsolidationLlm),+ workspace_id,+ project_id,+ session_id,+ )+ .await;+ assert!(+ body.contains("Durable worker completed"),+ "{frontmatter}: {body}"+ );+ }+ }+async fn two_project_wiki() -> (TempDir, Store, Wiki, WorkspaceId, ProjectId, ProjectId) {let tmp = TempDir::new().unwrap();let store = Store::open(tmp.path()).unwrap();diff --cc crates/ai-memory-consolidate/src/lib.rsindex f5ebf4a7,4ea1c72e..2320af04--- a/crates/ai-memory-consolidate/src/lib.rs+++ b/crates/ai-memory-consolidate/src/lib.rs@@@ -64,7 -65,8 +65,8 @@@ pub use consolidator::BATCH_SYSTEM_PROMPT, Consolidator, ConsolidatorError, ConsolidatorResult,DEFAULT_CONSOLIDATION_INPUT_TOKEN_SAFETY_MARGIN, DEFAULT_CONSOLIDATION_MAX_INPUT_TOKENS,DEFAULT_CONSOLIDATION_MAX_OUTPUT_TOKENS, MIN_CONSOLIDATION_MAX_INPUT_TOKENS,- MIN_CONSOLIDATION_MAX_OUTPUT_TOKENS, build_batch_request, redacted_error_summary,+ MIN_CONSOLIDATION_MAX_OUTPUT_TOKENS, build_batch_request, disambiguate_colliding_session_title,- existing_session_page_titles,++ existing_session_page_titles, redacted_error_summary,};pub use curator::{CuratorFinding, CuratorParams, CuratorReport, render_curator_report_markdown,diff --cc crates/ai-memory-hooks/Cargo.tomlindex ca66b097,4437f17e..f4475f3a--- a/crates/ai-memory-hooks/Cargo.toml+++ b/crates/ai-memory-hooks/Cargo.toml@@@ -35,9 -35,7 +35,10 @@@ tempfile.workspace = trugit2.workspace = trueai-memory-llm.workspace = trueasync-trait.workspace = true+# Per-test log capture in the checkpoint redaction tests (thread-local+# `set_default`); the same workspace dep the MCP crate's dev-deps use.+tracing-subscriber.workspace = true+ rusqlite.workspace = true[lints]workspace = truediff --cc crates/ai-memory-hooks/src/router.rsindex f5c7b691,1abb6e67..d84ef5a6--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@@ -4852,143 -5939,6 +5939,146 @@@ mod tests);}+ /// A provider that fails with a private body: the checkpoint fallback+ /// warning must carry class/status only, never the body.+ struct CheckpointSentinelLlm;++ #[async_trait::async_trait]+ impl LlmProvider for CheckpointSentinelLlm {+ fn name(&self) -> &'static str {+ "checkpoint-sentinel"+ }++ fn model(&self) -> &str {+ "sentinel-model"+ }++ async fn complete(&self, _request: ChatRequest) -> LlmResult<ChatResponse> {+ Err(self.fail())+ }++ async fn complete_structured_raw(+ &self,+ _request: ChatRequest,+ _schema: serde_json::Value,+ ) -> LlmResult<serde_json::Value> {+ Err(self.fail())+ }+ }++ impl CheckpointSentinelLlm {+ fn fail(&self) -> ai_memory_llm::LlmError {+ ai_memory_llm::LlmError::Provider {+ status: 400,+ body: "SENTINEL_PRIVATE_BODY".into(),+ }+ }+ }++ /// Captures everything a subscriber writes so a test can assert on it.+ /// `set_default` is thread-local and each `#[tokio::test]` runs on its+ /// own thread, so parallel tests do not share (or fight over) a capture.+ #[derive(Clone, Default)]+ struct CapturedLog(Arc<Mutex<Vec<u8>>>);++ impl CapturedLog {+ fn text(&self) -> String {+ String::from_utf8_lossy(&self.0.lock().unwrap()).into_owned()+ }+ }++ impl std::io::Write for CapturedLog {+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {+ self.0.lock().unwrap().extend_from_slice(buf);+ Ok(buf.len())+ }++ fn flush(&mut self) -> std::io::Result<()> {+ Ok(())+ }+ }++ impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for CapturedLog {+ type Writer = Self;++ fn make_writer(&'a self) -> Self::Writer {+ self.clone()+ }+ }++ /// Mutation captured: logging the `ConsolidatorError`'s `Display` on the+ /// fallback path copies the provider body into the hook log. Both+ /// checkpoint flavors (PreCompact and PostCompaction) run the same+ /// function, so both labels are driven against the sentinel provider.+ #[tokio::test]+ async fn checkpoint_fallback_log_carries_class_status_not_provider_body() {+ let captured = CapturedLog::default();+ let subscriber = tracing_subscriber::fmt()+ .with_writer(captured.clone())+ .with_max_level(tracing::Level::WARN)+ .with_ansi(false)+ .finish();+ let _guard = tracing::subscriber::set_default(subscriber);++ let tmp = TempDir::new().unwrap();+ let mut state = make_state(&tmp).await;+ state.consolidator = Some(Arc::new(Consolidator::new(+ state.reader.clone(),+ state.writer.clone(),+ state.wiki.clone(),+ Arc::new(CheckpointSentinelLlm),+ state.workspace_id,+ state.project_id,+ )));++ for checkpoint_label in ["pre-compact", "post-compaction"] {+ let session_id = seed_checkpoint_observation(&state, "keep-this-working-state").await;+ consolidate_or_synth(+ &state,+ session_id,+ state.workspace_id,+ state.project_id,+ AgentKind::ClaudeCode,- checkpoint_label,++ HookCheckpoint {++ label: checkpoint_label,++ track_page_write: true,++ },+ ai_memory_core::ActorContext::anonymous(),+ )+ .await+ .expect("a provider 400 must not lose the checkpoint");++ let path = ai_memory_core::PagePath::new(format!("sessions/{session_id}.md")).unwrap();+ let page = state+ .wiki+ .read_page(state.workspace_id, state.project_id, &path)+ .unwrap_or_else(|e| panic!("rule-based checkpoint page missing: {e}"));+ assert!(+ page.body.contains("keep-this-working-state"),+ "fallback page must carry the session's observations, got: {}",+ page.body+ );+ }++ let logged = captured.text();+ for checkpoint_label in ["pre-compact", "post-compaction"] {+ assert!(+ logged.contains(&format!(+ "{checkpoint_label}: LLM consolidation unavailable; falling back to rule-based checkpoint"+ )),+ "the fallback warning must fire for {checkpoint_label}; captured log was: {logged:?}"+ );+ }+ assert!(+ logged.contains("class=provider status=400"),+ "the redacted class/status must stay diagnosable: {logged}"+ );+ assert!(+ !logged.contains("SENTINEL_PRIVATE_BODY"),+ "provider body leaked into the checkpoint log: {logged}"+ );+ }+/// A provider failure happens after the consolidate preflight. The/// fallback write must still use the same operation so consolidate-only/// admission policy and mutations run on the actual page body too.