Skip to content

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

Rust

Merge pull request #1903 from matheus-rodrigues00/fix/generated-hook-redirects

AkitaOnRailsc59e7ab05d45
diff --cc CHANGELOG.md
index ea7d4c7c,11db5ed8..64cc226e
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -13,48 -13,15 +13,57 @@@ version in [`docs/changelog/`](docs/cha
### Fixed
+ - The generated OpenCode, OpenCode 2, OMP, Pi and OpenClaw integrations no
+ longer follow HTTP redirects, matching the native hook client (#1818).
+ Behind an SSO gateway, proxy or captive portal that redirects to a login
+ page, the page's `200` counted as a delivery: the spool drain deleted
+ spooled events and new ones were never spooled, the login page's HTML was
+ injected as the session's handoff, and a `307` or `308` replayed event
+ bodies to the redirect target. A redirect now fails the request like an
+ unreachable server, so the event stays spooled and no handoff is injected.
+ `ai-memory upgrade` refreshes installed integrations (#1902).
+- `ai-memory-wikisync` no longer refuses a destination as "already being
+ modified" right after its own run released it. On Unix a child forked by
+ another thread inherits the lock until it calls `exec`, so the next run
+ could see it still held; the acquire now retries for about half a second.
+ A real concurrent run is still refused. This failed the companion's CI
+ suite about one run in five (#1897).
+- `ai-memory upgrade` on Windows now waits for a scanner to release the
+ running or the freshly written binary before swapping them, instead of
+ failing with "being used by another process". The swap retries that
+ sharing violation for about eight seconds, as the wiki's atomic writes
+ already did (#1895).
+- Captured Claude Code tool failures. Claude Code fires `PostToolUseFailure`,
+ not `PostToolUse`, when a tool fails, and ai-memory never wired that event
+ for Claude Code, so failed commands, builds and test runs never reached
+ capture, search, consolidation or the handoff. `install-hooks --agent
+ claude-code`, `setup` and the marketplace plugin now wire it to the
+ post-tool-use handler; the observation records `outcome: error` with the
+ bounded error text (never the tool's arguments); the session page counts
+ failed calls and quotes the newest one; the automatic handoff adds a `Last
+ failed tool call` line; and the plugin no longer drops a failure when
+ settings hooks wire only the success event. Re-run `ai-memory install-hooks
+ --agent claude-code --apply` (or `ai-memory setup`) on an existing install.
+ Grok Build CLI keeps its nine events (#1893).
+- `bootstrap` now waits for a provider's `Retry-After` before retrying a
+ chunk, capped at 32 s like the remote embedders (#1397). It retried after a
+ fixed 2 s and gave up after three attempts, so a rate-limited hosted API
+ (DeepSeek, OpenAI) failed the run while it was still asking the client to
+ wait. Without a hint the fixed 2 s delay is unchanged (#1889).
+- `GET /handoff` (the `session-start` hook) returns again on large projects.
+ On a store without planner statistics, the unfinished-session recovery
+ lookup walked every observation in the project and rescanned the project for
+ each one, so the request never returned and left a server thread spinning.
+ It now checks each of the project's sessions once through
+ `idx_observations_session` and reads the project's handoffs once (#1879).
+- A 2.x project is now adopted whichever checkout of its repository captures
+ first. When a linked worktree (`git worktree add`) captured before the main
+ checkout, the repository identity created a new project, every checkout then
+ followed the identity there, and the 2.x project with its pages and sessions
+ was orphaned. A worktree now claims the identity-less project named after its
+ main checkout, as the main checkout would. The server reads the worktree's
+ git metadata to find it; `docs/upgrading-to-3.0.md` covers a server that
+ cannot read the checkout (#1880).
- Project search links now use the project's current stored name after
resolving a canonical or legacy key. Results, breadcrumbs, and the scope
selector stay on that project without renaming it (#1875).
diff --cc docs/security-boundaries.md
index 8c4e844a,c246d474..c357f331
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@@ -166,8 -166,9 +166,9 @@@ the legitimate restricted-project contr
| 27a | Provider credentials stay on the configured origin | `ai-memory-llm/src/redirect.rs` `same_origin_redirects`, set on every provider and embedder client (`anthropic.rs`, `codex.rs`, `copilot.rs`, `embedding.rs`, `gemini.rs`, `google.rs`, `openai.rs`, `openai_oauth.rs`, `opencode.rs`): a redirect is followed only when scheme, host and port match the previous request, with reqwest's ten-hop limit; any other redirect fails the request. reqwest's own guard strips only `Authorization`, cookies and the proxy headers, so `x-api-key`, `x-goog-api-key` and `llm_headers` values depend on this one. The local model download (`local.rs`) carries no credential and keeps the default policy for its CDN redirects; OIDC and CLI login requests refuse every redirect on clients of their own (`oidc.rs`, `auth.rs` `auth_http_client`) | `ai-memory-llm` `tests/suite/redirect_credentials.rs` `gemini_api_key_does_not_follow_a_cross_origin_redirect`, `anthropic_api_key_does_not_follow_a_cross_origin_redirect`, `operator_headers_do_not_follow_a_cross_origin_redirect` (with `Authorization` stripped as the control), `google_embedder_key_does_not_follow_a_cross_origin_redirect`, `a_refused_redirect_says_where_it_pointed`; legitimate control `a_same_origin_redirect_still_reaches_the_provider` (the key follows a path redirect on one origin); each cross-origin test fails with the policy removed | STRONG for the provider and embedder clients in `ai-memory-llm` |
| 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 |
-| 27d | Hook clients never follow a redirect with an event, a bearer or a handoff read | `ai-memory-cli/src/commands/hook_capture.rs` `build_client` (`Policy::none()`, #1818) for the native hook's posts, batches and handoff GET; every `fetch` in the generated TypeScript integrations passes `redirect: "error"`: the shared spool drain (`render_shared.rs` `ts_spool_runtime`), the hook POST `add_hook_spooling` installs (OpenCode, OpenCode 2, OMP, Pi), the OpenCode handoff and recap reads, the OMP/Pi handoff read and the Pi MCP bridge (`install_hooks.rs`), and the OpenClaw plugin's post and handoff read (`openclaw_plugin.rs`). A refused redirect takes the unreachable-server path: the event stays spooled and no handoff is injected | `hook_capture.rs` `build_client_refuses_redirects`, `post_hook_does_not_follow_redirect`, `post_batch_does_not_follow_redirect`, `get_handoff_does_not_follow_redirect` (the redirect target receives nothing); `render_shared.rs` `assert_every_ts_request_carries_client_marker` (every generated `fetch` carries `redirect: "error"`, run for all five integrations); `install_hooks.rs` `slow_generated_handoff_runtime::omp_extension_refuses_a_gateway_redirect` (a Node run behind a 302/307 gateway: its login origin gets no request, no handoff is injected, a spooled event survives the drain and the session's posts are spooled; it fails with the option removed) | STRONG for the native client and the generated TypeScript integrations; the legacy script bundles are not covered (`hooks/_lib.sh` curl does not follow but prints any handoff response body; `hooks/lib/ai-memory-hook.ps1` `Invoke-WebRequest` follows by default) |
++| 27d | The native hook and generated TypeScript clients never follow a redirect with an event, a bearer or a handoff read | `ai-memory-cli/src/commands/hook_capture.rs` `build_client` (`Policy::none()`, #1818) for the native hook's posts, batches and handoff GET; every `fetch` in the generated TypeScript integrations passes `redirect: "error"`: the shared spool drain (`render_shared.rs` `ts_spool_runtime`), the hook POST `add_hook_spooling` installs (OpenCode, OpenCode 2, OMP, Pi), the OpenCode handoff and recap reads, the OMP/Pi handoff read and the Pi MCP bridge (`install_hooks.rs`), and the OpenClaw plugin's post and handoff read (`openclaw_plugin.rs`). A refused redirect takes the unreachable-server path: the event stays spooled and no handoff is injected | `hook_capture.rs` `build_client_refuses_redirects`, `post_hook_does_not_follow_redirect`, `post_batch_does_not_follow_redirect`, `get_handoff_does_not_follow_redirect` (the redirect target receives nothing); `render_shared.rs` `assert_every_ts_request_carries_client_marker` (every generated `fetch` carries `redirect: "error"`, run for all five integrations); `install_hooks.rs` `slow_generated_handoff_runtime::omp_extension_refuses_a_gateway_redirect` (a Node run behind a 302/307 gateway: its login origin gets no request, no handoff is injected, a spooled event survives the drain and the session's posts are spooled; it fails with the option removed) | STRONG for the native client and the generated TypeScript integrations; the legacy script bundles are not covered (`hooks/_lib.sh` curl does not follow but prints any handoff response body; `hooks/lib/ai-memory-hook.ps1` `Invoke-WebRequest` follows by default) |
| 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 |
+| 29 | Interrupted-session recovery stays scope-, owner-, and receiver-bound | `ReaderPool::latest_interrupted_session_candidate` (`latest_interrupted_session_candidate_sql`) filters scope, owner and receiver before selection, and judges a session's work, end and handoff coverage only from rows in the same scope; hooks render only the admitted candidate and exclude the receiving session | `multi_session.rs` `interrupted_recovery_refuses_foreign_scope_owner_and_receiver_with_controls`, `interrupted_recovery_ignores_foreign_scope_work_and_batons_with_controls` (foreign work does not reopen an ended session and a foreign baton does not hide unfinished work; home-scope work and batons are the 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 |
| 30a | Session drilldowns are owner-scoped for a user and complete for root | `ai-memory-web/src/routes/api.rs` `session_owner_filter_for`: `AuthLevel::Root` → `OwnerFilter::Any`, every other caller → `owner_filter_for` (own plus shared). Used by `routes/agents.rs`, `routes/project.rs` (sessions, agent and token-usage tabs), `routes/session.rs`, and the `/api/v1` `sessions_handler` and `session_observations_handler`. Handoff reads keep `owner_filter_for` and root's explicit `all_owners` | `ai-memory-web` `operations.rs` `operations_root_drilldowns_reach_every_users_sessions_and_users_stay_owned`: a user's agent page, Sessions tab and session list omit another user's session and its session page and observations answer 404; root's list it and answer 200 (control: the user's own and the shared session stay visible) | STRONG. Bite checks: with root mapped to `owner_filter_for`, root's agent page misses the other user's session; with every caller mapped to `Any`, the user's agent page lists it |
| 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 |