Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Merge remote-tracking branch 'origin/main' into maint/pr-361
AkitaOnRails89fbf6a6764f
diff --cc CHANGELOG.mdindex 32eb9d0e,1aa11f77..76fdcfe5--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -7,37 -7,688 +7,698 @@@ and this project adheres to [Semantic V## [Unreleased]+### Added- - Version-aware lifecycle hooks for the AWS Kiro CLI (#355). The two agent- engines of the same binary use incompatible hook surfaces, so each is- selected explicitly and never guessed: `install-hooks --agent kiro-cli`- merges five flat camelCase entries (`agentSpawn`, `userPromptSubmit`,- `preToolUse`, `postToolUse`, `stop`) into every existing v2 agent config- under `~/.kiro/agents/` (the v2 engine has no global hook surface and the- built-in default agent has no file on disk), while- `install-hooks --agent kiro-cli-v3` writes the standalone versioned hooks- file `~/.kiro/hooks/ai-memory.json` with PascalCase triggers for the- early-access v3 engine. Both honor `$KIRO_HOME`, share one- `hooks/kiro-cli/` script bundle, preserve third-party hook entries on- re-apply and uninstall, and keep capture fail-open (always exit 0; no- stdout on capture paths, because exit code 2 blocks the tool call and- session-start/user-prompt stdout is injected into the agent context).- Handoffs inject through session-start stdout on both engines (v2- `agentSpawn`, v3 `SessionStart`), raw and unenveloped per the official- contracts; the native `ai-memory hook` command suppresses its `{}`- protocol line for `kiro-cli` for the same reason. Tool payloads- (`tool_name`/`tool_input`, `tool_response.success`) join the capture- policy with fixture vectors, including Kiro's `fs_read` batched- `operations` path extraction; the v3 stdin payload shape is not publicly- documented and stays conservative. Contracts verified against kiro-cli- 2.16.0 and kiro.dev's v2/v3 hook references; docs cover both engines,- MCP setup, and the v2/v3 session id-space split.- - `?flavor=bedrock` marker on the MCP URL, an alias of the existing- Moonshot root-schema flattening: Amazon Bedrock's Converse API (used by- the Kiro CLI) rejects root-level `anyOf`/`oneOf`/`allOf` in tool- schemas, so a Kiro `~/.kiro/settings/mcp.json` pointing at- `…/mcp?flavor=bedrock` gets the same tools with flattened root schemas++- Added verified Kiro CLI v2 lifecycle hooks. CamelCase hooks merge into++ existing agent configs, honor `$KIRO_HOME`, preserve unrelated hooks and++ per-agent project strategies, fail before changing any target when one is++ invalid, infer remote connectivity from the managed Kiro MCP entry, inject++ handoffs through `agentSpawn` stdout, enforce capture exclusions for known++ v2 tool payloads, and uninstall only exact ai-memory entries. Kiro v3 hook++ capture remains unsupported until its command-input payload is documented++ and can be fixture-tested (#355).+++ ## [1.23.0] - 2026-08-03++ ### Changed+ - Documented provider-neutral coexistence with structural code-intelligence+ tools: use ai-memory for historical intent and continuity, use the current+ checkout or structural provider for live symbols and impact analysis, verify+ historical structural claims before acting, and keep source, builds, tests,+ and observed runtime behavior authoritative. No provider coupling, automatic+ querying, or persisted structural-evidence schema was added (#353).++ ### Fixed+ - Antigravity CLI's generated native `PreToolUse` hook now returns the required+ `{"decision":"allow"}` response on normal capture, malformed input, and+ capture-policy drops. Local installs default to the native spool-based hook+ command, whose generic `{}` response caused Antigravity to deny every tool+ call even though the staged shell and PowerShell hooks already returned the+ correct decision (#352).++ ### Added+ - Kiro CLI is now supported as an MCP-only client through `install-mcp+ --client kiro-cli` (alias `kiro`). The installer preserves existing+ `$KIRO_HOME/settings/mcp.json` content, adds bearer headers when configured,+ honors `$KIRO_HOME`, and appends a Bedrock schema flavor that removes only+ unsupported root-level JSON Schema combinators. Non-loopback Kiro endpoints+ must use HTTPS and are rejected before `--apply` writes an unusable config.+ Kiro lifecycle hooks and managed workstreams remain deferred because its v2+ and early-access v3 engines use incompatible hook and session formats(#351).+ - Added `ai-memory continue`, which resumes the most recently launched managed+ checkout from any directory. `run`'s bare mode already continues the current+ checkout, but its workstream lookup is keyed by repository and worktree+ fingerprints, so it requires a `cd` first. `continue` orders the client-local+ checkout links by their `linked_at` stamp, revalidates the newest one's path+ and resolved scope, and then delegates to the same bare-mode launch. Stale,+ retargeted, scope-mismatched, or corrupt-ordering links are announced on+ stderr and skipped rather than silently resuming a different project. It+ accepts `--workspace`,+ `--yolo`, and `--fresh`; native harness arguments and `--executable` remain+ unavailable because bare mode does not know which harness it will pick.+ Docker-wrapper installs route the command through the checksum-verified host+ client so it can inspect local checkouts, session stores, and harnesses+ (#350).+ - New `GET /admin/sessions/by-agent` endpoint reporting how many sessions+ each agent CLI opened in one scope (`claude-code`, `cursor`, `codex`, …),+ so a dashboard can answer "where is this project's memory coming from".+ `sessions.agent_kind` already carried the answer but no read surface+ exposed it — the existing `/admin/open-sessions` takes the agent as a+ *filter* and returns neither the kind nor a total. Counts cover open and+ ended sessions alike, take an optional `since_days` window (`0` or absent+ = whole history), and order count-descending with an agent-name tiebreak+ so equal counts do not reorder between calls. Like the other scoped admin+ reads it reports the caller's own sessions plus unowned ones, with+ `all_owners=true` as the recovery switch. Unknown scopes 404 rather than+ being auto-created. No migration. (#349)++ ## [1.22.0] - 2026-08-01++ ### Added+ - Added `ai-memory show`, a project-first managed launcher that joins private+ client-local checkout links with public server project metadata and a bounded+ local scan, then launches an installed harness without changing the parent+ process directory. It supports discovery-only `--json`, stages new projects+ atomically with routing and Agent Skills, keeps remote-server filesystem paths+ private, refreshes links after successful managed prepares and CLI+ rename/move operations, and runs host-side through the Docker wrapper (#342).+ - Hook ingestion now recognizes Hermes Agent as a concrete session kind and+ understands its documented shell-hook `tool_name` / `tool_input` envelope+ for bounded tool-family titles and capture exclusions. Migration V44 expands+ the session allowlist without losing session ownership, observation+ watermarks, indexes, or scope-pairing triggers. This remains protocol support,+ not a first-party Hermes installer, and session-start handoff acceptance stays+ disabled because Hermes ignores that hook's stdout (#337).+ - Trusted-proxy identity now has a dedicated+ `[auth].actor_proxy_bearer_token`, distinct from the root bearer. Proxy+ requests must assert either a username or the complete OIDC issuer/subject+ pair; missing, partial, duplicated, or comma-folded identity headers fail+ closed. Proxied root access requires the configured OIDC issuer/subject pair;+ a display username never grants root. Ordinary root and DB-user requests+ continue to ignore raw actor headers, and leaving the proxy token unset+ preserves existing behavior (#333).+ - Qualified identity keys now keep usernames separate from OIDC+ `(issuer, subject)` pairs and drive active-project routing consistently for+ hook and MCP requests. The stable OIDC pair outranks display usernames, so+ same-subject users from different issuers cannot alias each other (#333).+ - The `/admin/*` route layer and the MCP `memory_forget_sweep` tool now ask+ "does this deployment distinguish operators" instead of "do `users` rows+ exist", so a trusted-proxy deployment — which never writes a `users` row —+ gets root-only admin gating instead of waving every proxied caller through+ the single-operator escape hatch (#333).+ - Optional `[slots] per_user` namespaced engine-written memory slots by the+ authenticated operator. Session briefs and consolidation prompts now receive+ shared slots plus that operator's own bounded namespace, while foreign slot+ writes are refused. The feature defaults off, preserves existing shared+ slots, and intentionally leaves exact wiki reads and searches project-wide+ because it is an agent-context injection boundary rather than RBAC (#335).+ - Handoffs now belong to the operator that created them (migration V39). On a+ server shared by several people the open-handoff lookup was scoped by+ `(workspace, project, state)` alone, so the next session to start — whoever it+ belonged to — consumed the pending baton, and delivery is destructive, so the+ author simply lost it. `cwd` did not help: a handoff created through+ `memory_handoff_begin` is always manual (`from_session_id = NULL`), and manual+ handoffs bypass the cwd check and outrank automatic ones, so the deliberate+ artefact was exactly the one that crossed operators. Ownership is now checked+ before those rules, and the owner column holds the qualified+ `IdentityKey::storage_key()` TEXT. `memory_handoff_begin` gains `shared: true`+ to publish a baton to the whole project on purpose; `memory_handoff_accept`+ gains `any_owner: true` for recovery. A NULL owner still means "shared", so+ every stored row and every caller without an authenticated actor behaves+ exactly as before (#334).+ - Sessions record their operator (migration V40), and the open-session lookup+ behind `GET /admin/open-sessions` is scoped to the caller unless+ `all_owners=true`. `finalize-session` drives off that lookup and acts+ destructively on the result — ending the session, synthesising a page from its+ observations and minting a handoff carrying its raw prompts — so picking "the+ newest open session in the scope" could do all of that to a colleague's live+ session. The new `--all-owners` flag exposes the server switch (#334).+ - New `GET /api/v1/workspaces/{workspace}/projects/{project}/handoffs` lists a+ project's handoffs, filtered by `state` and scoped by owner, backed by new+ non-partial indexes (migration V41) since every pre-existing handoffs index is+ partial on `state = 'open'`. There was no handoff listing anywhere in the+ system: readers only ever fetched the single pending one and consumed it, so a+ mis-delivered baton could not be inspected or recovered. On a server that+ authenticates, the prompt-derived fields (`summary`, `open_questions`,+ `next_steps`) are served to a caller the server can name and to the root+ operator, and are omitted with `redacted: true` for a caller it can place as+ neither — unowned rows are shared, so such a caller matches every one of them,+ and unlike the overview's single newest card this returns the project's whole+ history. Cross-owner reads require the explicit root-only+ `all_owners=true` recovery switch. The metadata is served either way,+ which is what makes the listing useful; a server with no auth configured+ serves the bodies too, since it already serves every page body+ unauthenticated (#334).+ - New admission-chain operations `handoff_begin`, `handoff_accept` and+ `handoff_cancel`. Handoffs live in their own table, so their lifecycle never+ passed through `Wiki::write_page` and was invisible to admission webhooks —+ leaving the operations that move prompt-derived text between operators+ unauthorizable. Every path raising one of them asks and announces in the same+ order: only the webhooks that can refuse (blocking + reject policy) are+ awaited before the operation, and observers are dispatched fire-and-forget+ after it, only if it happened — so `memory_handoff_accept`, whose routine+ answer is `{"handoff": null}`, never announces an accept that found nothing,+ and a mirror is never told about a baton the engine then abandoned. The+ automatic SessionEnd handoff and the session-start claim run through the same+ chain as their operator-triggered counterparts, forwarding the caller's+ webhook skip-list under the same root-only rule as every other transport.+ Neither can cost an operator anything beyond the operation the webhook+ declined: SessionEnd still writes the summary page, runs the opt-in+ consolidation and commits (a refusal skips the baton and is logged), and a+ refused, timed-out or unreachable claim leaves the handoff open for the next+ session (#334).+ - Pending auto-improve proposals record who staged them (V42+ `staged_by_actor_user`, the qualified identity key, surfaced on the proposal+ detail), and the one-pending-per-target rule is scoped per operator through+ a NULL-collapsing unique index, so one operator's pending suggestion stops+ blocking everybody else's for the same page while every unattributed caller+ keeps the original one-per-page rule unchanged (#336).+ - Page reinforcement records each distinct authenticated operator (V43+ `page_access`) beside the existing shared access counter. The opt-in+ `[decay] breadth_weight` term (default `0.0`) lets the forget sweep retain+ pages reinforced by several operators without changing existing scores at+ the default or for pages with zero or one identified reader (#336).++ - `run` accepts `antigravity` (aliases `antigravity-cli`, `agy`) as a+ managed harness, so an Antigravity session joins the same workstream as the+ Claude Code or Codex sessions on the same checkout. `agy` accepts no+ caller-chosen id for a new conversation, so a fresh launch injects no+ selector and the id is linked by the hooks or discovered afterwards; a+ linked resume passes `--conversation <id>`, and `--continue` / `-c` is+ respected as an explicit user choice. `--yolo` maps to+ `--dangerously-skip-permissions`, and the utility+ subcommands (`models`, `plugin`, `update`, …) pass through without a selector.+ Conversation discovery reads the per-conversation SQLite databases under+ `~/.gemini/antigravity-cli/conversations/`: the id is the file name and the+ workspace comes from two observed protobuf fields, so only conversations+ opened on the current directory are offered and a database from another `agy`+ version is skipped instead of failing the listing. Step payloads are+ undocumented, unversioned protobuf, so conversation text is deliberately not+ decoded — the visible-event ledger for this harness comes from lifecycle-hook+ capture, and transcript export fails with a message saying so. Antigravity is+ not part of the no-argument auto-detection pool. The native contract was+ verified against Antigravity CLI v1.1.7 (#345).++ ### Fixed+ - `run` on Windows now resolves npm-style harness installs through `PATHEXT`+ and starts the resolved wrapper. This avoids accepting an extensionless Unix+ shell shim such as `opencode` during availability checks and then failing to+ launch it when the adjacent `opencode.cmd` is the Windows entry point. Unix+ resolution remains unchanged (#343).+ - `memory_auto_improve` without a `session_id` now selects the newest+ completed session that has no persisted auto-improvement run. Preflight-+ skipped sessions therefore advance the implicit manual-review queue instead+ of permanently starving older sessions; passing an explicit session ID still+ permits a targeted rerun (#338).+ - Handoff and session ownership is stamped only where the deployment actually+ distinguishes operators. A server with `[auth].bearer_token` ++ `[auth].root_username`, no `users` rows and no proxy has one operator and two+ transports: stamping that one name on every HTTP write while the stdio /+ in-process transport carries no actor would make one person's handoffs and+ sessions invisible to their own other transport on the same data directory.+ With nobody to separate, the stamp is the pre-ownership `NULL` and both+ transports agree. Reads are deliberately not gated the same way, so rows+ stamped while a deployment did distinguish operators stay readable by that+ operator afterwards (#334).+ - The automatic SessionEnd handoff, the session page and both consolidation+ paths attribute to the operator recorded on the **session**, not to whoever+ delivered the event — a spool drain, a shared hook token or an operator+ finalizing a stuck session all carry a different identity. The atomic store+ operation also rejects a handoff whose owner differs from its source session+ (#334).+ - Briefings and both read-only overviews — workspace and project — scope+ handoffs to the requesting actor instead of showing only unowned ones, and+ `pending_handoff_count` applies the same filter as the fetch — otherwise a+ briefing advertises a pending baton the same caller can never retrieve, and on+ any server that stamps owners the overview's handoff card would go permanently+ empty while the count beside it kept reporting the row. The read-only+ `/api/v1` overview no longer surfaces handoffs that belong to a specific+ operator, including the raw prompt text an automatic handoff is synthesised+ from, to a browser the server cannot attribute (#334).+ - Retiring superseded automatic handoffs no longer crosses an operator+ boundary. Both sweeps — the same-cwd expiry on a new SessionEnd handoff and+ the post-claim cleanup after an accept — match on the acting handoff's+ `owner_user`, so one person starting or ending a session in a directory+ cannot expire another person's pending baton. A shared handoff (no owner) is+ visible to everyone, so it is only ever superseded by another shared one; on+ a single-operator or unauthenticated server every row is unowned and the+ sweeps behave exactly as they did (#334).+ - `ops::accept_handoff` propagates whether the claim actually succeeded, so+ `memory_handoff_accept` no longer returns the handoff body when the atomic+ claim was lost — previously two agents could be handed the same baton. The+ cross-operator escape hatches require admin authority: `any_owner` on+ `memory_handoff_accept` and on `memory_handoff_cancel` (which previously had+ no recovery path at all, so a handoff whose owner no longer matched any+ reachable identity could not be discarded), and `--all-owners` on+ `ai-memory finalize-session` (#334).+ - The `[auto_scope] per_actor` active-project map is keyed by the qualified+ identity on both sides — the hook ingress that publishes and the MCP tools+ that read — so an OIDC-proxied operator's writes and reads land on the same+ slot instead of silently missing on every read (#334).+ - Owner predicates for pending and exact-id handoff reads now execute in SQL+ before prompt-derived fields are loaded. Exact-id cancellation returns the+ same result for absent, wrong-scope and foreign-owner ids, so it no longer+ discloses another operator's handoff state before authorization. Accept and+ cancel also recheck the expected workspace and project in the atomic state+ update, closing a lifecycle race between the scoped read and destructive+ write (#334).+ - Ownership writes reject malformed identity keys, and malformed non-null+ session-owner keys already present in the database fail closed during hook+ processing instead of being converted to the shared `NULL` bucket.+ Named-user handoff history uses two indexed shared/owned ranges, so a large+ volume of another operator's rows cannot turn a bounded listing into a+ project-wide scan (#334).+ - Actor-scoped briefing, overview and handoff-history responses now use+ `Cache-Control: private, no-store`, preventing a browser from reusing one+ operator's prompt-derived response after credentials at the same URL change+ to another operator (#334).+ - Automatic session-start handoff admission is capped at 750 ms, below the+ shortest shipped client's one-second fetch timeout. A slow deciding webhook+ leaves the baton open instead of approving and consuming it after the caller+ has disconnected (#334).+ - A staged auto-improve proposal colliding with one already pending no longer+ aborts its whole staging run (losing the run row, its sibling proposals and+ the paid LLM review): the colliding proposal alone is skipped, and every+ staging surface — `memory_auto_improve`, `/admin/auto-improve`, the+ telemetry report, the curator, the CLI and the scheduler's log — names the+ skipped target and the reason instead of silently returning N-1 proposals+ (#336).++ ## [1.21.0] - 2026-07-31++ ### Added+ - Per-page TTL via a frontmatter `expires_at:` key (RFC3339, or a bare+ `YYYY-MM-DD` meaning end of that day UTC), mirrored into a new+ `pages.expires_at` column (V36) and settable through a new optional+ `expires_at` parameter on `memory_write_page`. Expired pages are hidden+ from `memory_query`/`memory_recent`/briefing/session-brief surfaces —+ `memory_query` gains `include_expired: true` to still see them — while+ exact-path reads still return the page, annotated `expired: true`,+ because an explicit read is not a search. The forget sweep hard-deletes+ them through the wiki layer, so the markdown file goes too, not just+ the rows. An explicit TTL outranks `pinned` (a pin means "don't decay+ this", not "keep it past the date its author set"); `memory_lint`+ flags pinned+expiring pages so the combination is visible rather than+ silent. (#309)+ - Zed editor as an MCP-only client. `install-mcp --client zed` renders,+ and `--apply` idempotently merges, a native remote HTTP entry under the+ top-level `context_servers` map in Zed's platform user `settings.json`,+ with optional bearer headers. The JSONC-aware apply and uninstall paths+ preserve user comments, trailing commas, unrelated settings, and sibling+ servers while changing only the matching ai-memory entry. Zed does not+ provide lifecycle hooks or managed-workstream continuity. (#321)+ - Entity-match retrieval as a fourth RRF stream (V38 `entities` ++ `entity_page_links`). Consolidation emits up to 10 normalized technologies,+ components, services, files, or domain nouns per page into frontmatter;+ manually edited `entities` use the same index path, and reindex rebuilds the+ derived tables from markdown. Project-scoped query tokens match exact names,+ name prefixes, or word prefixes inside compound names and are weighted by+ inverse entity frequency before RRF fusion and the existing authority and+ optional LLM reranking stages. Empty entity indexes contribute no candidates+ or score, and entity matching makes no LLM call. `explain: true` reports the+ entity stream's rank, raw inverse-frequency weight, contribution, and matched+ names. (#320)+ - Optional post-RRF reranking for project and explicit-scope+ `memory_query`, off by default. Set `AI_MEMORY_RERANKER=llm` (requires+ `AI_MEMORY_LLM_PROVIDER`) to over-fetch candidates, fuse scopes, and+ make at most one structured-output call through any existing LLM+ provider. The prompt JSON-encodes untrusted input and sends the query+ (up to 1,000 bytes) plus at most 30 page titles (200 bytes each) and+ snippets (600 bytes each) to that provider. The requested result limit+ is preserved even above 30; only the first 30 candidates are judged.+ A partial/duplicate/unknown id set, invalid score, timeout, provider error,+ or four-call concurrency saturation preserves the pre-rerank order.+ `global=true` and supplemental+ global-preference hits keep their existing non-RRF ranking. With+ `explain: true`, judged hits include `rerank_score`. Unknown reranker+ values and `llm` without a provider fail at startup. (#319)+ - New MCP tool `memory_feedback` (17th tool) — the "finer-grained+ reinforcement beyond access counts" P2 item. Record how useful a+ recalled page actually was by exact path: `helpful` / `not_helpful`+ step the page's new `pages.salience` column (V37, bounded to+ `[0.25, 2.0]` in 0.25 steps), which now scales the retention formula's+ time term for sweep-eligible episodic pages instead of a single global+ `salience_default`; `stale` /+ `wrong` floor the salience AND surface the page as a+ `feedback_flagged` finding in the next `memory_lint` report. Signals+ land in a new append-only `page_feedback` table with an optional+ sanitized, bounded single-line reason, the resulting salience needed to+ rebuild derived state, and a full audit-log entry. Nothing is ever+ deleted by feedback. The exact path resolves to the current page version+ in the feedback transaction, so rewriting a flagged page later retires+ both its salience and its lint findings — there is no separate dismissal+ state. Pages without feedback keep `salience = NULL`, which reads as+ exactly the previous behaviour. Retrieved content cannot authorize a+ feedback call; agents treat it as untrusted data. (#318)+ - `memory_query` gained an optional `explain: true` mode for project and+ explicit-scope searches. Each compiled-page hit then includes its 1-based+ FTS5, entity, vector, and graph ranks; raw BM25/cosine/entity values; matched+ entity names; graph seed and link direction; per-stream RRF contributions;+ fused score; and bounded authority multiplier. `streams_active` makes vector+ degradation visible. Global+ cross-project search reports its distinct FTS-only stream but does not attach+ RRF details to `global_hits`. Explain provenance is computed only when+ requested. (#317)+ - Per-project consolidation instructions: write a reserved+ `_prompts/consolidation.md` wiki page (via `memory_write_page` or on+ disk - no config key) and its body is appended to both single-page and+ multi-page consolidation prompts as advisory preferences ("prefer+ Portuguese titles", "skip CI noise", ...). The block is scrubbed+ through the configured sanitizer, capped at 2,000 characters, JSON-encoded,+ and injected into the LLM user message under an explicitly untrusted,+ schema-subordinate system-prompt contract. `memory_consolidate` also gained+ an optional `instructions` argument that overrides the page for one call;+ TTL-expired standing pages are ignored. (#316)++ ### Fixed+ - Zero-embedding startup and current retrieval descriptions now include the+ entity-match stream, and release notes attribute per-page TTL to the release+ where it shipped. (#329)+ - Retrieved `_rules/`, `gotchas/`, `procedures/`, and `decisions/` pages are now+ described consistently across MCP and installed skill prompts as untrusted+ historical evidence, removing contradictory language that elevated stored+ prose into operating policy or constraints. (#325)+ - A project-scoped forget sweep now purges aged decay tombstones only from its+ resolved workspace/project instead of deleting eligible derived rows across+ every project. Entity-index rows orphaned by the scoped purge are removed in+ the same transaction, and `hard_deleted` reports only the target scope. (#323)+ - Zero-LLM `memory_query` now keeps graph-neighbour expansion active instead+ of falling back to FTS5 alone when no query embedding exists. Equal adjusted+ hybrid and explicit multi-scope scores now use a deterministic path+ tiebreak. (#317)++ ## [1.20.2] - 2026-07-30++ ### Fixed+ - Docker build contexts now exclude the gitignored operator deployment files,+ preventing local server configuration and production environment secrets+ from being sent to the Docker builder. A packaging regression test keeps the+ exclusions as the final ignore rules so later negations cannot re-include+ them. (#314)+ - Managed workstream heartbeats now bound each server request and condense an+ outage into one short notice plus one recovery notice. Active launchers keep+ the lease-safe 30-second retry cadence without printing the same timeout on+ every attempt, and may renew their original run after a longer outage unless+ another launcher has already claimed the workstream. (#311)++ ## [1.20.1] - 2026-07-30++ ### Fixed+ - Managed workstream packets, handoffs, project briefs, MCP routing prompts,+ and all LLM maintenance prompts now identify stored project material as+ untrusted historical data rather than executable instructions. This limits+ persistent prompt injection through captured prompts, tool output, wiki+ pages, commit messages, or another authenticated user's shared content.+ (#302)+ - Docker wrapper installation and self-upgrade now use checksum-verified assets+ from the latest GitHub Release instead of executing the mutable `main` branch.+ The standalone hook installer and hook bundle use the same verified release+ path and install only the expected hook members without extracting arbitrary+ archive paths. Release jobs publish POSIX/Windows wrapper and hook assets with+ SHA-256 companions, all GitHub Actions are commit-pinned, and default+ workflow permissions are read-only outside the release publisher.+ (#302)++ ## [1.20.0] - 2026-07-30++ ### Added+ - New `openai-compat` embedding provider for self-hosted engines+ (Ollama, LM Studio, vLLM). Set+ `AI_MEMORY_EMBEDDING_PROVIDER=openai-compat` together with explicit+ `AI_MEMORY_EMBEDDING_BASE_URL`, `AI_MEMORY_EMBEDDING_MODEL`, and+ `AI_MEMORY_EMBEDDING_DIM` — there is no safe default model or+ dimensionality for a self-hosted engine, so each is required rather+ than guessed. Unlike the other providers it is keyless: a bearer+ token is sent only when `LLM_API_KEY` is present, for gateways that+ want one. Embeddings are stored under their own+ `provider="openai-compat"` identity, so switching an existing+ `openai`+base-URL setup over changes the stored+ `{provider, model, dim}` triple — run `ai-memory embed --force` to+ re-embed. (#300)++ ### Fixed+ - Antigravity CLI's `PreInvocation` hook now maps only its documented+ `invocationNum = 0` call to ai-memory's synthetic `SessionStart`. Later model+ invocations perform no capture or destructive handoff fetch, so a manual+ handoff created while the conversation winds down remains open for the next+ session. Native Windows hooks also emit Antigravity's required `injectSteps`+ envelope instead of Claude Code's `hookSpecificOutput` shape. (#298)+ - Automatic handoff selection now prefers the newest cwd-eligible session over+ a stale, more-specific ancestor. A new automatic handoff expires prior open+ automatic handoffs from the exact cwd, and accepting the winner atomically+ expires older eligible automatic handoffs. Manual and sibling-directory+ handoffs remain open, preventing stale delivery and inflated pending counts.+ (#293)+ - OpenAI-compatible providers now send each structured operation's JSON Schema+ through `response_format=json_schema` by default, so local models cannot+ replace consolidation JSON with prose or omit required fields. Explicit+ structured-output capability rejections fall back to the tolerant parser;+ other HTTP failures still propagate, and+ `AI_MEMORY_LLM_COMPAT_STRICT=false` remains the compatibility opt-out. (#292)+ - Recognized Antigravity CLI's native file/edit and search tools, applied path+ exclusions to its `TargetFile` operations, and captured bounded successful+ edit content from `toolCall.args` when the hook omits an output field. Generic+ MCP/resource tools remain fail-closed until their path schemas are proven,+ while failed edits retain their error instead of attempted content. (#294)++ ## [1.19.2] - 2026-07-28++ ### Fixed+ - Source installation no longer fails when `cargo install --path` resolves+ rmcp 1.8, whose `peer_info()` return type differs from rmcp 1.7. CI now checks+ the unlocked source-install resolution separately from the workspace's+ lock-aware gates, while the documented persistent Windows install uses+ `--locked` for reproducibility. (#285)+ - Antigravity CLI hook installation and documentation now expose the existing+ agent-aware manual finalizer:+ `ai-memory finalize-session --agent antigravity-cli`. Antigravity's `Stop`+ event ends one execution loop rather than the conversation, so it remains a+ normal observation; the explicit command closes the latest scoped session+ through the canonical SessionEnd path, producing its summary and automatic+ handoff and queueing opt-in consolidation. The docs also clarify that+ `memory_handoff_begin` deliberately creates a session-neutral, project-wide+ manual handoff for every MCP client; attributed handoffs come from canonical+ SessionEnd processing. (#284)++ ## [1.19.1] - 2026-07-27++ ### Changed+ - Wiki search now applies a bounded source-authority adjustment after FTS5,+ graph, and optional vector candidate generation. Canonical rules, decisions,+ procedures, gotchas, semantic/procedural tiers, `pinned` pages, and+ `canonical` / `active` / `source-of-truth` tags win close relevance contests;+ episodic sessions, `_lint/` output, investigations, and pages tagged+ `superseded`, `historical`, `test-fixture`, or `do-not-answer-from` are+ downgraded but remain searchable. Exact session-only queries still retrieve+ their evidence, and the returned `rank` includes the bounded adjustment so+ multi-scope merging preserves the same order. (#269)+ - Client CLI commands now resolve their `(workspace, project)` from the+ nearest `.ai-memory.toml` marker, not just the lifecycle hooks. Previously+ only the hook path read the marker, so a checkout declaring+ `workspace = "acme"` had its captures land in `acme` while `run`,+ `bootstrap`, `search`, `write-page` and every other scope-taking command+ resolved into `default` — the same repository split across two scopes, with+ `ai-memory run`'s managed workstream stranded on the wrong side. Each field+ still prefers an explicit flag; when the marker decides one, the command+ announces the resolved scope on stderr, naming which half the marker+ decided. `AI_MEMORY_IGNORE_MARKER=1` restores the previous resolution for+ one invocation (client commands only — the hooks keep reading the marker).+ `embed --force` without `--project` still fans out across the workspace and+ no longer needs a derivable project name. `ai-memory serve` is unchanged:+ it has no caller cwd, and its `--workspace` / `--project` remain the baked+ fallback for hook events without a usable one. (#259)+ - Marker discovery now stays inside its trust boundary when the caller's cwd+ is outside `$HOME`: it walks no higher than the nearest checkout root, or+ checks only cwd for a non-git directory. Workspace-only markers also keep+ the hooks' documented `project = basename(cwd)` behavior for CLI commands,+ including subdirectories and linked worktrees. (#259)++ ### Fixed+ - Scheduled hollow-project cleanup now treats managed workstreams as project+ data. Older projects whose only history is a managed workstream, including+ those with a live run, are no longer cascade-deleted out from under the+ workstream heartbeat or left with orphaned transcript segments. (#279)+ - Hybrid search now gives its FTS, vector, and graph streams the same bounded+ candidate window used by authority-aware FTS search. Small result limits no+ longer exclude a canonical page before post-fusion authority ranking can+ promote it, and candidate-limit arithmetic is saturating throughout. (#277)+ - Forced workspace deletion now removes the immutable managed-workstream+ segment directories whose database rows are removed by the workspace+ cascade. Its admin report includes workstream/run counts and IDs, and raw+ segment cleanup participates in the existing filesystem partial-failure+ reporting instead of leaving transcript data orphaned. (#275)+ - Lossless `move-project` true moves now re-stamp managed workstreams into the+ destination workspace in the same transaction as the project and its other+ denormalized child rows. Previously the project moved while its managed+ workstreams retained the source `workspace_id`, hiding portable history from+ destination-scope lookup and violating the project/workspace pairing+ invariant. The admin response now reports `workstreams_moved`. (#273)+ - SessionEnd recovery now commits the ended generation and automatic handoff in+ one SQLite transaction, then lets an already-ended native replay converge the+ remaining wiki commit, durable consolidation enqueue, and ingest-key+ completion. An interruption after `ended_at` can no longer strand a missing+ handoff or permanently pending spool key, and missing or scope/agent-+ mismatched SessionEnd events no longer attempt consolidation recovery against+ an unrelated session. (#271)+ - Bare `install-hooks --apply` re-runs, including the Docker wrapper's+ post-upgrade refresh, now preserve an install's baked `repo-root` project+ strategy for every supported hook integration. An explicit+ `--project-strategy basename` still removes the install-wide default. (#267)+ - Installer `--apply` modes now write through symlinked agent configuration+ files instead of atomically replacing the symlink itself. Symlink chains and+ dangling final targets are preserved, while backups remain next to the+ user-facing configuration path. (#264)+ - SessionEnd re-consolidation now converges by comparing the current+ observation count with a persisted count stamped by the latest completed+ end, instead of comparing independently generated wall-clock timestamps.+ Clock skew could otherwise leave an old observation permanently "new" and+ repeatedly rewrite the same session page, handoff, and opt-in LLM job with no+ agent activity. Existing ended sessions are baselined during migration so an+ upgrade does not enqueue historical catch-up work. (#268)+ - Capture exclusions now canonicalize an existing hook working directory+ before matching paths, so filesystem aliases such as macOS `/var` versus+ `/private/var` cannot turn an excluded file event into a spooled event.+ Marker discovery tests likewise accept the canonical path they request.+ (#265)+ - Opt-in SessionEnd LLM consolidation now runs from a durable, generation-+ idempotent queue instead of inside the hook batch request. The hook commits+ its deterministic session page and handoff, persists the provider job, and+ returns without waiting for LLM latency; a single bounded worker recovers+ queued or expired-lease work after restart and makes at most five provider+ attempts with backoff. A stale SessionEnd redelivery also repairs the+ enqueue when the original request was cancelled just after `ended_at`, so+ the default hook drain timeout can no longer silently strand the heuristic+ page as the final result. (#265)+ - `purge-project` no longer deletes a project out from under a running agent.+ `workstreams` cascades from `projects` and `managed_runs` cascades from+ `workstreams`, so purging a scope that still held a live managed run tore+ out its lease row: the wrapper then failed every heartbeat with+ `409 managed run lease is not active` and the session's transcript never+ reached the ledger. The purge now refuses with a `409` naming the offending+ workstreams unless `--force` is passed, and its report counts the+ `workstreams` and `managed_runs` the cascade removes; their+ `raw/workstreams/<id>/` directories are now removed server-side and included+ in the same filesystem success/failure report instead of being orphaned.+ Those counters previously showed `0 pages, 0 sessions, …` and made such a+ scope look safe to delete. Liveness is the lease, not the row state: a+ crashed wrapper leaves `state = 'active'` behind until the next+ `ai-memory run` sweeps it, so only a lease that has not yet expired blocks+ the purge. `move-project`'s+ copy-purge merge surfaces the same conflict as a `409` naming how many+ pages were already copied, instead of a `500`; its `--force` flag only+ overrides the active-project guard and never destroys a live managed-run+ lease. (#259)++ ## [1.19.0] - 2026-07-25++ ### Fixed+ - Claude Desktop's rendered Windows MCP instructions now distinguish the+ unpackaged `%APPDATA%` config from the detected MSIX `LocalCache` config, and+ contributor, managed-workstream, and CLI reference docs no longer omit+ recently shipped harnesses or commands. (#256)+ - The opt-in managed-workstream real-harness acceptance runner now verifies+ context delivery from the managed-run cursor/acknowledgement state and a new+ persisted assistant event instead of requiring the model to quote a prior+ sentinel. Large Claude Code hook packets can be file-backed, so acceptance no+ longer passes or fails based on whether the model chooses to use `Read`.+ The deterministic fake Grok leg covers the same assertion path. (#242)++ ### Added+ - `install-mcp --client claude-code --session-aware` now registers an+ ai-memory-owned stdio bridge that forwards Claude Code's+ `CLAUDE_CODE_SESSION_ID` as `X-Memory-Actor-Session-Id` on every upstream+ HTTP MCP request. This makes `[auto_scope] mode = "per_session"` effective+ for concurrent Claude Code sessions against local or remote servers while+ leaving the existing static HTTP registration as the default. The bridge+ preserves bearer auth, stateless/stateful HTTP compatibility, and uninstall+ ownership; both Docker wrappers forward the Claude session variable into+ the helper container. (#244)+ - `GET /admin/open-sessions` lists open (not yet ended) sessions for one+ workspace/project/agent, newest first (`all=true` returns every match).+ `ai-memory finalize-session` now uses this endpoint instead of opening+ the local SQLite index directly, so every CLI command is a thin HTTP+ client of the running server; the command now requires a reachable+ server and no longer works against an offline data directory. (#236)+ - Managed workstream support for Grok Build CLI: `ai-memory run grok` (alias+ `grok-build`) creates fresh sessions with a wrapper-generated `--session-id`,+ resumes linked sessions with `--resume`, maps wrapper `--yolo` onto Grok's+ native `--yolo`/`--always-approve`, and delivers the bounded workstream+ context packet through Grok's native `--rules` flag (system-prompt append,+ acknowledged only after the child spawns). Transcript import reads+ `$GROK_HOME/sessions/*/*/chat_history.jsonl` read-only with a+ prefix-validated cursor and content-hash event ids so rewind-driven journal+ rewrites cannot duplicate history; system prompts and encrypted reasoning+ are excluded as loss annotations, as are the harness-injected `<user_info>`+ and `<system-reminder>` blocks Grok stores inside `user` records (project+ instructions, the skills catalogue, and connected MCP servers), which would+ otherwise leak harness internals into the portable ledger and evict real+ conversation from the startup packet budget. Discovery+ matches checkouts through `summary.json`'s recorded `info.cwd` and honors+ `GROK_HOME`. Grok stays out of the bare-mode automatic pool. Verified+ against Grok Build CLI v0.2.111 ([#237]).++ ### Changed+ - Single-page, batch, and bootstrap consolidation prompts now ask the model+ to connect related wiki pages with path-based wikilinks and to mirror the+ dominant natural language of the source material while preserving code,+ identifiers, paths, commands, error strings, and JSON field names. (#238)+ - The M8 access-counter reinforcement now bumps a page's `access_count` and+ `last_accessed_at` at most once per minute instead of on every search that+ returns it. A first sighting still bumps immediately, and a continuously hot+ page remains eligible once per window, while the cooldown map self-prunes to+ the pages searched within the window. This reduces redundant single-writer+ work under bursty or overlapping searches while intentionally making+ `access_count` a coarser retention signal. (#239)++ ### Fixed+ - Managed workstream packets now carry a versioned origin marker, and Claude+ Code transcript import excludes a tool result only when its content begins+ with that marker (or the legacy rendered packet header). This prevents a+ large SessionStart packet that Claude persists and later reads from+ `tool-results/` from re-entering the ledger and recursively consuming future+ packet budgets, while ordinary tool results that merely mention the marker+ remain visible. (#241)+ - Lifecycle `user-prompt` and `post-compaction` bodies are now truncated+ UTF-8-safely at 16 KiB, while notification and tool excerpts remain capped at+ 2 KB. Native hook commands apply the event cap before local spooling or+ transport, the server repeats it for direct and older clients, and the+ sanitized observation boundary independently caps every durable body at+ 16 KiB so neither SQLite nor observation FTS can grow to the 10 MiB HTTP+ transport limit. (#249)+ - `ai-memory run <harness>` now verifies an ai-memory-injected native resume+ target still exists in that harness's read-only session store. A confirmed+ orphan starts a fresh native session and repoints the same workstream instead+ of retrying the dead id forever. The new wrapper-owned `--fresh` flag forces+ the same per-workstream recovery without a resume attempt or adoption prompt;+ explicit native resume/session/fork selectors remain authoritative and+ cannot be combined with `--fresh`. (#240)+ - `install-mcp --client claude-desktop` now detects an MSIX-packaged+ Claude Desktop on Windows and writes to its virtualized+ `AppData\Local\Packages\Claude_<id>\LocalCache\Roaming\Claude\claude_desktop_config.json`+ instead of the plain `%APPDATA%\Claude\` path. Previously this+ silently wrote a config file the running app ignored, so the MCP+ server never appeared after restart. The detector uses Windows'+ resolved local and roaming app-data roots, prefers an existing config+ when multiple package directories exist, and fails with an explicit+ `--config-file` recovery instruction when the active package is+ ambiguous. Unpackaged installs keep resolving to the plain path.+ (#250)++ - The Docker wrappers (`bin/ai-memory`, `bin/ai-memory.ps1`) kept stdin+ attached only on a real terminal, so every piped or redirected+ invocation reached the container with a closed stdin. `ai-memory+ write-page --body -` therefore stored a page with frontmatter and an+ empty body while still reporting a successful write, and the same+ applied to any other stdin reader (hooks fed by a pipe). The wrappers+ now always pass `-i`, while `-t` is added only when stdin and stdout are+ both terminals. `AI_MEMORY_NO_TTY=1` disables only TTY allocation and+ no longer disconnects stdin. (#243)+ - Managed `SessionStart` delivery now includes a pending single-use+ handoff before the portable workstream ledger and optional project+ brief. Handoff and ledger acknowledgements are claimed together only+ after the complete response has been assembled; a failed or racing+ ledger claim cannot consume the handoff or suppress retry delivery.+ (#235)## [1.18.0] - 2026-07-23diff --cc README.mdindex 3401352d,5adccbb1..10ffcf85--- a/README.md+++ b/README.md@@@ -31,18 -31,19 +31,19 @@@| Oh My Pi / OMP | Supported | Use `--client omp` / `--agent omp` (or `oh-my-pi`) for native `.omp` MCP config + TypeScript extension; generated extension enforces capture exclusions. || Pi | Supported | Generated `~/.pi/agent/extensions/ai-memory.ts` extension provides lifecycle capture and an HTTP MCP bridge; generated extension enforces capture exclusions. || Crush | Managed-only | `ai-memory run crush` resumes its project-local session database and supplies portable context through a temporary supported global-context file; no lifecycle-hook installer is provided. |- | Managed workstreams | Opt-in | `ai-memory run` provides transparent cross-harness continuity for Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, and OMP. Direct launches remain unchanged. See [`docs/managed-workstreams.md`](docs/managed-workstreams.md). |+ | Managed workstreams | Opt-in | `ai-memory run` provides transparent cross-harness continuity for Claude Code, Codex, OpenCode, Pi, Crush, Kimi Code, OMP, Grok Build CLI, and Antigravity CLI. Direct launches remain unchanged. See [`docs/managed-workstreams.md`](docs/managed-workstreams.md). || Claude Desktop | MCP-only | Uses `mcp-remote`; no lifecycle hooks. || OpenClaw | Supported | MCP config + native plugin lifecycle hooks; generated plugin enforces capture exclusions. |- | Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). |- | Grok Build CLI | Supported | MCP config (`install-mcp --client grok` → `$GROK_HOME/config.toml`, default `~/.grok/config.toml`) + lifecycle hooks (`install-hooks --agent grok` → `$GROK_HOME/hooks/ai-memory.json`, default `~/.grok/hooks/ai-memory.json`, Grok-specific hook bundle). Capture works; no handoff injection — Grok ignores `SessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. Skills root: `.grok/skills` / `$GROK_HOME/skills` (default `~/.grok/skills`). |+ | Antigravity CLI | Supported | MCP config (`serverUrl`) + lifecycle hooks (`agy` alias). Only `PreInvocation` with `invocationNum = 0` maps to SessionStart; later model calls cannot consume a next-session handoff. No automatic true session-end hook, so run `ai-memory finalize-session --agent antigravity-cli` after the final turn when you need a summary, handoff, and opt-in SessionEnd consolidation. `ai-memory run antigravity` (aliases `antigravity-cli`, `agy`) adds managed workstream resume via `--conversation`; conversation text is not decoded, so the ledger for this harness comes from hook capture. |+ | Grok Build CLI | Supported | MCP config (`install-mcp --client grok` → `$GROK_HOME/config.toml`, default `~/.grok/config.toml`) + lifecycle hooks (`install-hooks --agent grok` → `$GROK_HOME/hooks/ai-memory.json`, default `~/.grok/hooks/ai-memory.json`, Grok-specific hook bundle). Capture works; no hook handoff injection — Grok ignores `SessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. `ai-memory run grok` adds managed workstream resume with the context packet delivered natively through `--rules`. Skills root: `.grok/skills` / `$GROK_HOME/skills` (default `~/.grok/skills`). || Zero | Supported | `install-mcp --client zero` (native HTTP + bearer in `~/.config/zero/config.json`) + lifecycle hooks via `install-hooks --agent zero --apply` (exec-form native commands in `~/.config/zero/hooks.json`, JSON payload on stdin, no shell). Capture works incl. specialist (subagent) events; no handoff injection — Zero discards `sessionStart` stdout, so recover handoffs via MCP `memory_handoff_accept`. || Kimi Code | Supported | MCP config (`url` entry in `~/.kimi-code/mcp.json`) + lifecycle hooks (`[[hooks]]` in `~/.kimi-code/config.toml`, 10 events including subagent start/stop and `PostToolUseFailure` for tool-failure capture); both paths honor `$KIMI_CODE_HOME`. Handoffs inject via `UserPromptSubmit` stdout (Kimi Code discards `SessionStart` hook stdout); `ai-memory run kimi` adds managed workstream resume. |- | Kiro CLI | Hooks (engine-aware) | Lifecycle hooks for both agent engines of the AWS Kiro CLI, selected explicitly because their hook surfaces are incompatible: `install-hooks --agent kiro-cli` merges camelCase hook entries into every existing v2 agent config (`~/.kiro/agents/*.json`; the v2 engine has no global hook surface), and `install-hooks --agent kiro-cli-v3` writes the standalone versioned hooks file `~/.kiro/hooks/ai-memory.json` for the early-access v3 engine. Both honor `$KIRO_HOME` and share one script bundle. Handoffs inject via session-start stdout on both engines (v2 `agentSpawn`, v3 `SessionStart`). MCP: configure `~/.kiro/settings/mcp.json` manually (see docs/install.md). |-| Kiro CLI | MCP-only | `install-mcp --client kiro-cli` (alias `kiro`) merges a native remote entry into `$KIRO_HOME/settings/mcp.json` (default `~/.kiro/settings/mcp.json`). Kiro's Bedrock-compatible schema flavor is applied automatically. Remote endpoints must use HTTPS; plain HTTP is accepted only on loopback. Hooks and managed workstreams are not yet supported because Kiro v2 and v3 use incompatible hook and session formats. |++| Kiro CLI | Supported (v2) | MCP config uses `install-mcp --client kiro-cli` (alias `kiro`) and Kiro's Bedrock-compatible schema flavor. `install-hooks --agent kiro-cli` merges verified v2 hooks into existing agent configs, honors `$KIRO_HOME`, preserves unrelated entries, and injects pending handoffs through `agentSpawn` stdout. Kiro v3 hook capture is not yet supported because its command-input payload is undocumented. Managed workstreams are tracked separately. || VS Code Copilot | MCP-only | `.vscode/mcp.json` for Copilot agent mode; no lifecycle hooks (Copilot does not expose them yet). |- | Hermes Agent | Community | A community-maintained [`ai-memory-hermes-plugin`](https://github.com/MrLuciano/ai-memory-hermes-plugin) is available. It is not part of ai-memory's first-party install surface; review its compatibility matrix, install/uninstall scripts, and secret handling before using it. |+ | Zed | MCP-only | Native remote MCP under `context_servers` in Zed's user `settings.json`; no lifecycle hooks or managed-workstream support. |+ | Hermes Agent | Community | Core hook ingestion recognizes `agent=hermes` and Hermes' documented shell-hook `tool_name` / `tool_input` payload for concrete session attribution, tool-family titles, and capture exclusions. A community-maintained [`ai-memory-hermes-plugin`](https://github.com/MrLuciano/ai-memory-hermes-plugin) is available, but no first-party installer is shipped; review its compatibility matrix, install/uninstall scripts, and secret handling before using it. Hermes ignores session-start hook stdout, so recover handoffs through MCP. || LLM/auth providers | Supported | Anthropic, OpenAI, OpenAI OAuth/Codex, GitHub Copilot, Gemini, OpenCode Zen/Go, OpenAI-compatible endpoints, and generic OIDC device auth for native hooks. |- | Embedding providers | Supported | OpenAI, Voyage, and Google Gemini. |+ | Embedding providers | Supported | OpenAI, Voyage, Google Gemini, and keyless OpenAI-compatible endpoints such as Ollama, LM Studio, and vLLM. |## What it is@@@ -111,11 -147,11 +147,10 @@@ priors are at the [bottom](#influences-mode. Mounted on the same axum server as MCP.- **Multi-agent + multi-machine ready.** Supported clients: ClaudeCode, Codex, Devin CLI, OpenCode, Cursor, Claude Desktop (via `mcp-remote`),- Gemini CLI, Antigravity CLI, Grok Build CLI, Kimi Code, Kiro CLI- (hooks for both agent engines), OpenClaw, Oh My Pi- / OMP (`omp` / `oh-my-pi`), Pi via generated bridge extension, and VS Code- GitHub Copilot agent mode- (MCP-only, workspace `.vscode/mcp.json`).+ Gemini CLI, Antigravity CLI, Grok Build CLI, Kimi Code, OpenClaw, Oh My Pi+ / OMP (`omp` / `oh-my-pi`), Pi via generated bridge extension, VS Code+ GitHub Copilot agent mode (MCP-only, workspace `.vscode/mcp.json`), Kiro CLI- (MCP-only, `$KIRO_HOME/settings/mcp.json`), and Zed (MCP-only, user- `settings.json`).++ (MCP + v2 lifecycle hooks), and Zed (MCP-only, user `settings.json`).Server runs local (loopback) OR on a homelab box (LAN/VPN/cloud)with bearer-token auth. Shared servers can opt into[`[auto_scope]` modes](docs/auto-scope.md) for per-user or@@@ -314,15 -452,14 +451,19 @@@ docker run -d --name ai-memory# 3. Wire your agent CLI in two commands. The wrapper takes care of# mounts and each client's config-path detection. Re-run with# `--agent codex`, `--agent devin`, `--agent opencode`, `--agent gemini-cli`,- # `--agent grok`, `--agent kimi-code`, `--agent kiro-cli` (or `kiro-cli-v3`),- # `--agent omp`, `--agent oh-my-pi`, `--client cursor`,- # `--client gemini-cli`, `--client grok`, etc.-# `--agent grok`, `--agent kimi-code`, `--agent omp`, `--agent oh-my-pi`, `--client cursor`,++# `--agent grok`, `--agent kimi-code`, `--agent kiro-cli`, `--agent omp`,++# `--agent oh-my-pi`, `--client cursor`,+ # `--client gemini-cli`, `--client grok`, `--client kiro-cli`, etc.# for additional agents; full list in docs/install.md.ai-memory install-mcp --client claude-code --applyai-memory install-hooks --agent claude-code --apply# Grok Build CLI example:# ai-memory install-mcp --client grok --apply# ai-memory install-hooks --agent grok --apply++# Kiro CLI v2 example (requires an existing Kiro agent config):++# ai-memory install-mcp --client kiro-cli --apply++# ai-memory install-hooks --agent kiro-cli --apply++# Kiro CLI v3 hook capture is not yet supported; see docs/install.md.```On Linux/macOS, that's it. Start a Claude Code session as usual - everydiff --cc crates/ai-memory-cli/src/cli.rsindex 8412be02,e1a2926d..542ac38d--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@@ -931,18 -1011,6 +1011,11 @@@ pub enum AgentChoice/// Kimi Code CLI (Moonshot AI).#[value(alias = "kimi")]KimiCode,- /// Kiro CLI (AWS), default v2 agent engine — camelCase lifecycle hooks- /// embedded in agent configs under `~/.kiro/agents/*.json`. The v2 and- /// v3 engines of the same binary use incompatible hook surfaces, so- /// each is selected explicitly; use `kiro-cli-v3` for the v3 engine.++ /// Kiro CLI (AWS), v2 agent engine — camelCase lifecycle hooks embedded++ /// in agent configs under `~/.kiro/agents/*.json`. Kiro v3's standalone++ /// hooks do not yet document a command-input payload contract.+ #[value(alias = "kiro")]+ KiroCli,- /// Kiro CLI (AWS), early-access v3 agent engine (`kiro-cli --v3`) —- /// PascalCase triggers in a standalone versioned hooks file at- /// `~/.kiro/hooks/ai-memory.json`. Select explicitly; the v2 engine- /// ignores this surface and vice versa.- #[value(name = "kiro-cli-v3", alias = "kiro-v3")]- KiroCliV3,}impl AgentChoice {@@@ -968,9 -1036,6 +1041,7 @@@Self::Zero => AgentKind::Zero,Self::Devin => AgentKind::Devin,Self::KimiCode => AgentKind::KimiCode,- // Both Kiro engine surfaces are the same product and session- // identity; only the installed hook surface differs.- Self::KiroCli | Self::KiroCliV3 => AgentKind::KiroCli,++ Self::KiroCli => AgentKind::KiroCli,}}@@@ -1057,6 -1130,11 +1136,11 @@@ pub enum McpClient/// Kimi Code CLI (Moonshot AI).#[value(alias = "kimi")]KimiCode,+ /// Kiro CLI - `$KIRO_HOME/settings/mcp.json` (default- /// `~/.kiro/settings/mcp.json`). MCP-only: Kiro v2 and v3 use- /// incompatible hook and session formats.++ /// `~/.kiro/settings/mcp.json`). Pair with++ /// `install-hooks --agent kiro-cli` for verified v2 lifecycle capture.+ #[value(alias = "kiro")]+ KiroCli,/// VS Code GitHub Copilot (agent mode) — per-workspace/// `.vscode/mcp.json`. Copilot's agent mode reads MCP servers/// from VS Code's own MCP framework (top-level `servers` key),@@@ -1920,6 -2152,6 +2158,40 @@@ mod testsassert!(matches!(hook_args.agent, AgentChoice::Devin));}++ #[test]++ fn kiro_v2_hook_aliases_parse_and_v3_is_not_advertised() {++ for alias in ["kiro-cli", "kiro"] {++ let cli = Cli::try_parse_from([++ "ai-memory",++ "install-hooks",++ "--agent",++ alias,++ "--server-url",++ "http://127.0.0.1:49374",++ ])++ .unwrap_or_else(|error| panic!("failed to parse Kiro v2 alias {alias}: {error}"));++ let Command::InstallHooks(args) = cli.command else {++ panic!("expected install-hooks for Kiro v2 alias {alias}");++ };++ assert_eq!(args.agent, AgentChoice::KiroCli);++ }++ for unsupported in ["kiro-cli-v3", "kiro-v3"] {++ let error = Cli::try_parse_from([++ "ai-memory",++ "install-hooks",++ "--agent",++ unsupported,++ "--server-url",++ "http://127.0.0.1:49374",++ ])++ .unwrap_err();++ assert!(++ error.to_string().contains("invalid value"),++ "v3 must remain unsupported until its payload contract is verified: {error}"++ );++ }++ }++#[test]fn install_hooks_project_strategy_repo_root_parses() {let cli = Cli::try_parse_from([diff --cc crates/ai-memory-cli/src/commands/hook.rsindex 5b335c9b,d5d214cb..dbeee6e1--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@@ -363,6 -360,42 +360,47 @@@ fn parse_minutes(raw: Option<String>, d}}+ fn should_process_hook_event(agent: AgentKind, event: HookEvent, raw: &serde_json::Value) -> bool {+ if agent == AgentKind::AntigravityCli && event == HookEvent::SessionStart {+ return raw.get("invocationNum").and_then(serde_json::Value::as_u64) == Some(0);+ }+ true+ }++ fn write_success_response<W: std::io::Write>(+ stdout: &mut W,+ agent: AgentKind,+ event: HookEvent,+ ) -> std::io::Result<()> {- if agent == AgentKind::AntigravityCli && event == HookEvent::PreToolUse {++ if agent == AgentKind::KiroCli {++ // Kiro adds successful SessionStart/UserPromptSubmit stdout to model++ // context, and v2 Stop parses stdout for a block decision. Capture-only++ // hooks therefore stay silent unless SessionStart has real context.++ Ok(())++ } else if agent == AgentKind::AntigravityCli && event == HookEvent::PreToolUse {+ writeln!(stdout, r#"{{"decision": "allow"}}"#)+ } else {+ writeln!(stdout, "{{}}")+ }+ }++ fn session_start_handoff_envelope(agent: AgentKind, handoff: String) -> serde_json::Value {+ if agent == AgentKind::AntigravityCli {+ serde_json::json!({+ "injectSteps": [{+ "ephemeralMessage": handoff,+ }]+ })+ } else {+ serde_json::json!({+ "hookSpecificOutput": {+ "hookEventName": "SessionStart",+ "additionalContext": handoff,+ }+ })+ }+ }+/// Run a single hook end-to-end. Always returns Ok and always writes a JSON/// object to stdout — a hook must never fail the agent.///@@@ -595,19 -625,8 +630,14 @@@ wherif let Some(handoff) =get_handoff(&client, &handoff_url, bearer.as_deref(), handoff_timeout()).await{- if inert_stdout {- let envelope = serde_json::json!({- "hookSpecificOutput": {- "hookEventName": "SessionStart",- "additionalContext": handoff,- }- });- writeln!(stdout, "{envelope}")?;- } else {- // Kiro adds this stdout to the agent context verbatim- // and documents no envelope, so print the raw handoff.- let envelope = session_start_handoff_envelope(agent_kind, handoff);- writeln!(stdout, "{envelope}")?;++ if agent_kind == AgentKind::KiroCli {++ // Kiro v2 consumes agentSpawn stdout verbatim and defines++ // no wrapper envelope.+ writeln!(stdout, "{handoff}")?;++ } else {++ let envelope = session_start_handoff_envelope(agent_kind, handoff);++ writeln!(stdout, "{envelope}")?;+ }return Ok(());}}@@@ -839,6 -864,101 +875,103 @@@ mod testsassert!(!should_spawn_background_drainer("user-prompt"));}+ #[test]+ fn antigravity_preinvocation_only_maps_invocation_zero_to_session_start() {+ for (raw, expected) in [+ (serde_json::json!({"invocationNum": 0}), true),+ (serde_json::json!({"invocationNum": 1}), false),+ (serde_json::json!({"invocationNum": 0.5}), false),+ (serde_json::json!({"invocationNum": "0"}), false),+ (serde_json::json!({}), false),+ ] {+ assert_eq!(+ should_process_hook_event(AgentKind::AntigravityCli, HookEvent::SessionStart, &raw,),+ expected,+ "{raw}"+ );+ }+ assert!(should_process_hook_event(+ AgentKind::ClaudeCode,+ HookEvent::SessionStart,+ &serde_json::json!({})+ ));+ assert!(should_process_hook_event(+ AgentKind::AntigravityCli,+ HookEvent::PostToolUse,+ &serde_json::json!({})+ ));+ }++ #[test]+ fn hook_success_response_is_specific_to_antigravity_pre_tool_use() {+ for (agent, event, expected) in [+ (+ AgentKind::AntigravityCli,+ HookEvent::PreToolUse,+ b"{\"decision\": \"allow\"}\n".as_slice(),+ ),+ (+ AgentKind::AntigravityCli,+ HookEvent::PostToolUse,+ b"{}\n".as_slice(),+ ),+ (+ AgentKind::ClaudeCode,+ HookEvent::PreToolUse,+ b"{}\n".as_slice(),+ ),++ (AgentKind::KiroCli, HookEvent::PreToolUse, b"".as_slice()),++ (AgentKind::KiroCli, HookEvent::SessionStart, b"".as_slice()),+ ] {+ let mut output = Vec::new();+ write_success_response(&mut output, agent, event).unwrap();+ assert_eq!(output, expected, "{agent:?} {event:?}");+ }+ }++ #[tokio::test]+ async fn antigravity_native_pre_tool_use_allows_and_spools_valid_input() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir.clone()),+ antigravity_hook_args("pre-tool-use", "http://127.0.0.1:1"),+ serde_json::json!({+ "conversationId": "agy-session",+ "workspacePaths": [tmp.path()],+ "toolCall": {"name": "view_file", "args": {"AbsolutePath": "README.md"}}+ })+ .to_string(),+ &mut stdout,+ |_| Ok(()),+ )+ .await+ .unwrap();++ assert_eq!(stdout, b"{\"decision\": \"allow\"}\n");+ assert_eq!(hook_spool::spool_len(&hook_spool::spool_dir(&data_dir)), 1);+ }++ #[tokio::test]+ async fn antigravity_native_pre_tool_use_fails_open_on_malformed_input() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir.clone()),+ antigravity_hook_args("pre-tool-use", "http://127.0.0.1:1"),+ "not-json".into(),+ &mut stdout,+ |_| Ok(()),+ )+ .await+ .unwrap();++ assert_eq!(stdout, b"{\"decision\": \"allow\"}\n");+ assert_eq!(hook_spool::spool_len(&hook_spool::spool_dir(&data_dir)), 0);+ }+#[test]fn incremental_threshold_parses_and_falls_back() {assert_eq!(incremental_drain_threshold_from(|_| Some("64".into())), 64);@@@ -1616,6 -1812,18 +1825,30 @@@}}++ fn kiro_hook_args(event: &str, server_url: &str) -> HookArgs {++ HookArgs {++ event: event.into(),++ agent: "kiro-cli".into(),++ server_url: server_url.into(),++ auth_token: None,++ project_strategy: None,++ check_capture: false,++ capture_assistant: false,++ }++ }+++ fn antigravity_hook_args(event: &str, server_url: &str) -> HookArgs {+ HookArgs {+ event: event.into(),+ agent: "antigravity-cli".into(),+ server_url: server_url.into(),+ auth_token: None,+ project_strategy: None,+ check_capture: false,+ capture_assistant: false,+ }+ }+/// Recording HTTP stub: replies to every request with `status`/`body` and/// streams each request head back so tests can assert which endpoints the/// hook touched (session-start also drains the spool, so POSTs to `/hook`@@@ -1656,6 -1864,80 +1889,114 @@@.flatten()}+ #[tokio::test]+ async fn antigravity_initial_invocation_fetches_with_native_output_contract() {+ let tmp = tempfile::tempdir().unwrap();+ let (base, mut requests) = serve_requests("200 OK", "AGY-HANDOFF").await;+ let mut stdout = Vec::new();+ run_with_payload(+ Some(tmp.path().join("data")),+ antigravity_hook_args("session-start", &base),+ serde_json::json!({+ "invocationNum": 0,+ "initialNumSteps": 0,+ "conversationId": "agy-conversation",+ "workspacePaths": [tmp.path()]+ })+ .to_string(),+ &mut stdout,+ |_| Ok(()),+ )+ .await+ .unwrap();++ let output: serde_json::Value = serde_json::from_slice(&stdout).unwrap();+ assert_eq!(+ output,+ serde_json::json!({+ "injectSteps": [{"ephemeralMessage": "AGY-HANDOFF"}]+ })+ );+ let mut recorded = Vec::new();+ while let Some(request) = first_request(&mut requests).await {+ recorded.push(request);+ }+ assert!(+ recorded+ .iter()+ .any(|request| request.starts_with("POST /hook")),+ "{recorded:?}"+ );+ assert!(+ recorded.iter().any(|request| {+ request.starts_with("GET /handoff?")+ && request.contains("session_id=agy-conversation")+ }),+ "{recorded:?}"+ );+ }++ #[tokio::test]+ async fn antigravity_later_invocation_has_no_capture_or_handoff_side_effects() {+ let tmp = tempfile::tempdir().unwrap();+ let data_dir = tmp.path().join("data");+ let (base, mut requests) = serve_requests("200 OK", "MUST-NOT-BE-CONSUMED").await;+ let mut stdout = Vec::new();+ run_with_payload(+ Some(data_dir.clone()),+ antigravity_hook_args("session-start", &base),+ serde_json::json!({+ "invocationNum": 4,+ "initialNumSteps": 12,+ "conversationId": "agy-conversation",+ "workspacePaths": [tmp.path()]+ })+ .to_string(),+ &mut stdout,+ |_| Err(std::io::Error::other("must not spawn")),+ )+ .await+ .unwrap();++ assert_eq!(stdout, b"{}\n");+ assert!(first_request(&mut requests).await.is_none());+ assert_eq!(hook_spool::spool_len(&hook_spool::spool_dir(&data_dir)), 0);+ }+++ #[tokio::test]++ async fn kiro_session_start_prints_handoff_verbatim() {++ let tmp = tempfile::tempdir().unwrap();++ let (base, mut requests) = serve_requests("200 OK", "KIRO-HANDOFF").await;++ let mut stdout = Vec::new();++ run_with_payload(++ Some(tmp.path().join("data")),++ kiro_hook_args("session-start", &base),++ serde_json::json!({++ "session_id": "kiro-session",++ "cwd": tmp.path()++ })++ .to_string(),++ &mut stdout,++ |_| Ok(()),++ )++ .await++ .unwrap();++++ assert_eq!(stdout, b"KIRO-HANDOFF\n");++ let mut recorded = Vec::new();++ while let Some(request) = first_request(&mut requests).await {++ recorded.push(request);++ }++ assert!(++ recorded.iter().any(|request| {++ request.starts_with("GET /handoff?")++ && request.contains("agent=kiro-cli")++ && request.contains("session_id=kiro-session")++ }),++ "{recorded:?}"++ );++ }++#[tokio::test]async fn kimi_user_prompt_prints_the_handoff_body_verbatim() {let tmp = tempfile::tempdir().unwrap();diff --cc crates/ai-memory-cli/src/commands/install_hooks.rsindex 46e6a781,e41a8849..d9a112ea--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@@ -26,12 -26,11 +26,12 @@@ use crate::commands::openclaw_pluginuse crate::commands::path_util::home_dir;use crate::commands::render_shared::{ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CODEX_PROFILE, CURSOR_PROFILE,- GEMINI_PROFILE, KIMI_CODE_EVENTS, KIRO_CLI_V2_EVENTS, KIRO_CLI_V3_EVENTS,- build_antigravity_payload_with_data_dir, build_claude_code_payload_with_data_dir,- build_devin_payload_with_data_dir, build_grok_payload_with_data_dir,- build_kiro_cli_v2_hooks_value, build_kiro_cli_v3_hooks_file, build_profile_payload_for_agent,- hook_script_for_claude_code, hook_script_for_current_platform, kimi_code_hook_commands,- local_hook_policy_v1_supported, ts_capture_policy_v1, ts_string_literal,- GEMINI_PROFILE, KIMI_CODE_EVENTS, build_antigravity_payload_with_data_dir,++ GEMINI_PROFILE, KIMI_CODE_EVENTS, KIRO_CLI_V2_EVENTS, build_antigravity_payload_with_data_dir,+ build_claude_code_payload_with_data_dir, build_devin_payload_with_data_dir,- build_grok_payload_with_data_dir, build_profile_payload_for_agent, hook_script_for_claude_code,- hook_script_for_current_platform, kimi_code_hook_commands, local_hook_policy_v1_supported,- ts_capture_policy_v1, ts_string_literal,++ build_grok_payload_with_data_dir, build_kiro_cli_v2_hooks_value,++ build_profile_payload_for_agent, hook_script_for_claude_code, hook_script_for_current_platform,++ kimi_code_hook_commands, local_hook_policy_v1_supported, ts_capture_policy_v1,++ ts_string_literal,};use crate::config::{Config, DEFAULT_SERVER_URL};@@@ -178,41 -177,6 +178,32 @@@ fn kimi_code_config_path_in.join("config.toml"))}+/// `$KIRO_HOME/agents` when set, else `~/.kiro/agents`. The Kiro CLI v2+/// engine embeds hooks inside per-agent config JSONs in this directory;+/// there is no global v2 hook surface, and the built-in default agent+/// has no file on disk. `KIRO_HOME` relocation is honored by the real+/// binary (verified against kiro-cli 2.16.0: settings are written under+/// `$KIRO_HOME` when set).+pub(crate) fn kiro_cli_agents_dir() -> anyhow::Result<std::path::PathBuf> {+ kiro_cli_home_join(std::env::var_os("KIRO_HOME"), "agents")+}+- /// `$KIRO_HOME/hooks/ai-memory.json` when set, else- /// `~/.kiro/hooks/ai-memory.json`. The Kiro CLI v3 engine discovers- /// every standalone hooks file under `~/.kiro/hooks/` in every- /// workspace (global hooks are a v3-only feature), so ai-memory owns a- /// dedicated file and never touches other tools' hook files.- pub(crate) fn kiro_cli_v3_hooks_path() -> anyhow::Result<std::path::PathBuf> {- Ok(kiro_cli_home_join(std::env::var_os("KIRO_HOME"), "hooks")?.join("ai-memory.json"))- }-+/// The env value comes in as a parameter so tests can exercise both+/// branches without mutating process env (mirrors+/// `kimi_code_config_path_in`).+fn kiro_cli_home_join(+ env_override: Option<std::ffi::OsString>,+ child: &str,+) -> anyhow::Result<std::path::PathBuf> {+ if let Some(dir) = env_override.filter(|value| !value.is_empty()) {+ return Ok(PathBuf::from(dir).join(child));+ }+ Ok(home_dir()+ .context("could not locate $HOME for ~/.kiro")?+ .join(".kiro")+ .join(child))+}+/// Run the `install-hooks` subcommand.////// # Errors@@@ -318,23 -291,9 +318,19 @@@ pub fn run(config: &Config, mut args: Ilet hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;apply_to_kimi_code_config(&hooks_dir, &server_url, auth, &config.data_dir, &args)}+ AgentChoice::KiroCli => {+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;+ apply_to_kiro_cli_agent_configs(+ &hooks_dir,+ &server_url,+ auth,+ &config.data_dir,+ &args,+ )+ }- AgentChoice::KiroCliV3 => {- let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;- apply_to_kiro_cli_v3_hooks(&hooks_dir, &server_url, auth, &config.data_dir, &args)- }};}- let strategy = args.project_strategy.baked();+ let strategy = args.project_strategy.and_then(ProjectStrategyArg::baked);match args.agent {AgentChoice::OpenCode => render_opencode_plugin(&server_url, auth, strategy),AgentChoice::Pi => render_pi_extension(&server_url, auth, strategy),@@@ -416,14 -375,6 +412,10 @@@let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;render_kimi_code(&hooks_dir, &server_url, auth, &config.data_dir, strategy)}+ AgentChoice::KiroCli => {+ let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;+ render_kiro_cli(&hooks_dir, &server_url, auth, &config.data_dir, strategy)+ }- AgentChoice::KiroCliV3 => {- let hooks_dir = resolve_hooks_dir(args.hooks_dir.as_deref(), args.agent)?;- render_kiro_cli_v3(&hooks_dir, &server_url, auth, &config.data_dir, strategy)- }}}@@@ -433,6 -384,161 +425,168 @@@ struct InferredMcpConfigauth_token: Option<String>,}+ /// The project-strategy to install for `args`: the explicit `--project-strategy`+ /// when one was given, otherwise the strategy an earlier `--apply` baked into+ /// the agent's existing config (so a bare re-apply preserves it instead of+ /// reverting to basename). `None` means "bake nothing", unchanged from before.+ fn install_project_strategy(args: &InstallHooksArgs) -> Option<ProjectStrategyArg> {+ if args.project_strategy.is_some() {+ return args.project_strategy;+ }++ // Kiro v2 can update several agent configs in one run. Each config may++ // carry a different previously-baked strategy, so recover it per target in++ // `apply_to_kiro_cli_agent_configs` instead of choosing one globally.++ if args.agent == AgentChoice::KiroCli {++ return None;++ }+ existing_agent_config(args)+ .as_deref()+ .and_then(|existing| baked_project_strategy(args.agent, existing))+ }++ /// Read the config file `--apply` will update for the selected agent.+ fn existing_agent_config(args: &InstallHooksArgs) -> Option<String> {+ let path = if let Some(path) = &args.config_file {+ if args.agent == AgentChoice::Openclaw {+ path.join(openclaw_plugin::ENTRYPOINT_TS)+ } else {+ path.clone()+ }+ } else {+ match args.agent {+ AgentChoice::ClaudeCode => claude_settings_path().ok()?,+ AgentChoice::Codex => codex_hooks_path().ok()?,+ AgentChoice::Cursor => cursor_hooks_path().ok()?,+ AgentChoice::GeminiCli => gemini_settings_path().ok()?,+ AgentChoice::OpenCode => opencode_plugin_path().ok()?,+ AgentChoice::Pi => pi_extension_path().ok()?,+ AgentChoice::Omp => omp_extension_path().ok()?,+ AgentChoice::Openclaw => openclaw_plugin::default_plugin_dir()+ .ok()?+ .join(openclaw_plugin::ENTRYPOINT_TS),+ AgentChoice::AntigravityCli => antigravity_hooks_path().ok()?,+ AgentChoice::Grok => grok_hooks_path().ok()?,+ AgentChoice::Zero => zero_hooks_path().ok()?,+ AgentChoice::Devin => devin_hooks_path().ok()?,+ AgentChoice::KimiCode => kimi_code_config_path().ok()?,++ AgentChoice::KiroCli => return None,+ }+ };+ std::fs::read_to_string(path).ok()+ }++ /// Recover a strategy only from configuration entries ai-memory owns. Shared+ /// JSON/TOML config files may contain unrelated hooks, while generated+ /// TypeScript files carry an explicit ownership header.+ fn baked_project_strategy(agent: AgentChoice, existing: &str) -> Option<ProjectStrategyArg> {+ match agent {+ AgentChoice::OpenCode | AgentChoice::Pi | AgentChoice::Omp | AgentChoice::Openclaw => {+ let marker = match agent {+ AgentChoice::OpenCode => "--agent opencode --apply`.",+ AgentChoice::Pi => "--agent pi --apply`.",+ AgentChoice::Omp => "--agent omp --apply`.",+ AgentChoice::Openclaw => "--agent openclaw --apply`.",+ _ => return None,+ };+ existing+ .lines()+ .next()+ .filter(|line| {+ line.starts_with("// Auto-generated by `ai-memory install-hooks ")+ && line.ends_with(marker)+ })+ .and_then(|_| project_strategy_from_text(existing))+ }+ AgentChoice::KimiCode => {+ let document: toml_edit::DocumentMut = existing.parse().ok()?;+ document+ .get("hooks")+ .and_then(toml_edit::Item::as_array_of_tables)+ .and_then(|hooks| {+ hooks.iter().find_map(|entry| {+ if !is_ai_memory_toml_hook_entry(entry) {+ return None;+ }+ entry+ .get("command")+ .and_then(|item| item.as_str())+ .and_then(project_strategy_from_text)+ })+ })+ }+ _ => serde_json::from_str(existing)+ .ok()+ .as_ref()+ .and_then(project_strategy_from_json),+ }+ }++ fn project_strategy_from_json(value: &serde_json::Value) -> Option<ProjectStrategyArg> {+ if is_ai_memory_hook_entry(value) {+ if let Some(strategy) = value+ .get("command")+ .and_then(|command| command.as_str())+ .and_then(project_strategy_from_text)+ {+ return Some(strategy);+ }+ if let Some(args) = value.get("args").and_then(|args| args.as_array()) {+ let args: Vec<&str> = args.iter().filter_map(|arg| arg.as_str()).collect();+ for (index, arg) in args.iter().enumerate() {+ if let Some(value) = arg.strip_prefix("--project-strategy=")+ && is_repo_root_strategy(value)+ {+ return Some(ProjectStrategyArg::RepoRoot);+ }+ if *arg == "--project-strategy"+ && args+ .get(index + 1)+ .is_some_and(|value| is_repo_root_strategy(value))+ {+ return Some(ProjectStrategyArg::RepoRoot);+ }+ }+ }+ }++ match value {+ serde_json::Value::Array(values) => values.iter().find_map(project_strategy_from_json),+ serde_json::Value::Object(values) => values.values().find_map(project_strategy_from_json),+ _ => None,+ }+ }++ /// Only `repo-root` is baked (`basename` removes the marker), so it is the sole+ /// value recovered from legacy shell commands and generated source.+ fn project_strategy_from_text(existing: &str) -> Option<ProjectStrategyArg> {+ for marker in [+ "AI_MEMORY_PROJECT_STRATEGY=",+ "--project-strategy=",+ "--project-strategy ",+ "const DEFAULT_PROJECT_STRATEGY =",+ ] {+ for rest in existing.split(marker).skip(1) {+ let token: String = rest+ .trim_start_matches(|character: char| {+ character.is_ascii_whitespace() || matches!(character, '\'' | '"')+ })+ .chars()+ .take_while(|character| {+ character.is_ascii_alphanumeric() || matches!(character, '-' | '_')+ })+ .collect();+ if is_repo_root_strategy(&token) {+ return Some(ProjectStrategyArg::RepoRoot);+ }+ }+ }+ None+ }++ fn is_repo_root_strategy(value: &str) -> bool {+ matches!(value, "repo-root" | "repo_root")+ }+/// Reject `--as-user X` without a usable `--auth-token`. P1.8/// metadata flag — without a token, the hook scripts would still/// authenticate anonymously (or as root if the operator reused the@@@ -634,10 -746,6 +794,7 @@@ fn mcp_client_for_agent(agent: AgentCho// Pi bridges MCP through its generated extension, not a native// mcp.json the installer can scrape.AgentChoice::Pi => None,- // Kiro CLI's MCP config (~/.kiro/settings/mcp.json) is documented- // for manual setup only; the installer does not manage it yet, so- // there is nothing to infer a server URL from.- AgentChoice::KiroCli | AgentChoice::KiroCliV3 => None,++ AgentChoice::KiroCli => Some(McpClient::KiroCli),}}@@@ -862,6 -970,6 +1019,33 @@@ fn overlay_event_hooksmap.insert(event.to_string(), serde_json::Value::Array(entries));}++fn overlay_kiro_cli_event_hooks(++ map: &mut serde_json::Map<String, serde_json::Value>,++ event: &str,++ our_value: &serde_json::Value,++) {++ let mut entries: Vec<serde_json::Value> = map++ .get(event)++ .and_then(|value| value.as_array())++ .map(|existing| {++ existing++ .iter()++ .filter(|entry| {++ !entry++ .get("command")++ .and_then(serde_json::Value::as_str)++ .is_some_and(is_ai_memory_kiro_hook_command)++ })++ .cloned()++ .collect()++ })++ .unwrap_or_default();++ if let Some(ours) = our_value.as_array() {++ entries.extend(ours.iter().cloned());++ }++ map.insert(event.to_string(), serde_json::Value::Array(entries));++}++/// Mutate `~/.claude/settings.json` in place: replace the hook entries/// ai-memory cares about (`CLAUDE_CODE_EVENTS`); preserve every other hook the/// user has wired up to other tools.@@@ -1577,239 -1776,6 +1852,213 @@@ fn is_ai_memory_toml_hook_entry(entry:lower.contains("ai-memory") || lower.contains("ai_memory")}+/// Merge ai-memory's camelCase hook entries into every existing Kiro CLI+/// v2 agent config (`~/.kiro/agents/*.json`, or the single file passed+/// via `--config-file`).+///+/// The v2 engine has no global hook surface: hooks fire only for the+/// agent config that is active, so the installer updates each config the+/// user already has. It never invents one — a fabricated agent config+/// would not be the active agent (the built-in default has no file on+/// disk), so hooks in it would never fire and the install would look+/// successful while capturing nothing.+fn apply_to_kiro_cli_agent_configs(+ hooks_dir: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ args: &InstallHooksArgs,+) -> Result<()> {+ // Resolve targets before staging anything so a missing-agent-config+ // bail leaves no half-done install behind.+ let targets: Vec<PathBuf> = match &args.config_file {+ Some(p) => {+ anyhow::ensure!(+ p.is_file(),+ "{} does not exist. Kiro CLI v2 hooks live inside an existing agent config; \- create one first (`kiro-cli agent create`) and re-run, or use \- `--agent kiro-cli-v3` for the v3 engine's standalone hooks file.",++ create one first (`kiro-cli agent create`) and re-run. Kiro v3 hooks remain \++ unsupported until its command-input payload contract is documented.",+ p.display()+ );+ vec![p.clone()]+ }+ None => list_kiro_cli_agent_configs(&kiro_cli_agents_dir()?)?,+ };+ anyhow::ensure!(+ !targets.is_empty(),+ "no Kiro CLI agent configs found in {}. The v2 engine only fires hooks defined in an \+ agent config and the built-in default agent has no file on disk, so create an agent \+ first (`kiro-cli agent create`, then `kiro-cli agent set-default <name>`) and re-run. \- For the v3 engine use `--agent kiro-cli-v3`, which installs a standalone hooks file \- and needs no agent config.",++ Kiro v3 hooks remain unsupported until its command-input payload contract is \++ documented.",+ kiro_cli_agents_dir()?.display()+ );++ let prepared = preflight_kiro_cli_agent_configs(++ targets,++ hooks_dir,++ server_url,++ auth_token,++ data_dir,++ args.project_strategy,++ )?;+++ let staged = stage_hook_scripts(hooks_dir, "kiro-cli")?;+ let command_dir = staged_command_dir(&staged, "kiro-cli");- let strategy = args.project_strategy.baked();- for path in targets {++ for (path, strategy) in prepared {+ let outcome = merge_kiro_cli_agent_hooks(+ &command_dir,+ server_url,+ auth_token,+ data_dir,- strategy,++ strategy.and_then(ProjectStrategyArg::baked),+ &path,+ )?;+ println!(+ "✓ {} {} ({})",+ outcome.verb(),+ path.display(),+ match outcome {+ ApplyOutcome::Created => "new file",+ ApplyOutcome::Updated => "backup written next to it",+ ApplyOutcome::NoOp => "already up to date",+ }+ );+ }+ Ok(())+}+++/// Parse and validate every Kiro v2 target before staging scripts or writing++/// any config. The strategy is recovered per file because Kiro can update++/// several independently-configured agents in one invocation.++fn preflight_kiro_cli_agent_configs(++ targets: Vec<PathBuf>,++ command_dir: &Path,++ server_url: &str,++ auth_token: Option<&str>,++ data_dir: &Path,++ explicit_strategy: Option<ProjectStrategyArg>,++) -> Result<Vec<(PathBuf, Option<ProjectStrategyArg>)>> {++ let mut prepared = Vec::with_capacity(targets.len());++ for path in targets {++ let existing =++ fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;++ let strategy =++ explicit_strategy.or_else(|| baked_project_strategy(AgentChoice::KiroCli, &existing));++ render_kiro_cli_agent_hooks(++ &existing,++ command_dir,++ server_url,++ auth_token,++ data_dir,++ strategy.and_then(ProjectStrategyArg::baked),++ &path,++ )?;++ prepared.push((path, strategy));++ }++ Ok(prepared)++}+++/// Merge ai-memory's v2 hook entries into one Kiro agent config,+/// preserving every third-party entry under the same triggers and every+/// non-hook field of the agent definition.+fn merge_kiro_cli_agent_hooks(+ staged: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ project_strategy: Option<&str>,+ config_path: &Path,+) -> Result<ApplyOutcome> {- let our_hooks = build_kiro_cli_v2_hooks_value(- staged,- server_url,- auth_token,- Some(data_dir),- project_strategy,- );+ apply_atomic(config_path, |existing| {- mutate_json(existing, |root| {- let hooks = root- .entry("hooks")- .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))- .as_object_mut()- .with_context(|| {- format!(- "`hooks` in {} is present but not an object",- config_path.display()- )- })?;- for (event, value) in &our_hooks {- overlay_event_hooks(hooks, event, value);- }- Ok(())- })++ render_kiro_cli_agent_hooks(++ existing,++ staged,++ server_url,++ auth_token,++ data_dir,++ project_strategy,++ config_path,++ )+ })+}+- /// Every `*.json` agent config in the Kiro CLI global agents directory,- /// sorted for deterministic apply order. A missing directory is an empty- /// list, not an error — the caller decides how to report it.- pub(crate) fn list_kiro_cli_agent_configs(dir: &Path) -> Result<Vec<PathBuf>> {- let Ok(entries) = fs::read_dir(dir) else {- return Ok(Vec::new());- };- let mut configs: Vec<PathBuf> = entries- .filter_map(std::result::Result::ok)- .map(|e| e.path())- .filter(|p| p.is_file() && p.extension().and_then(|e| e.to_str()) == Some("json"))- .collect();- configs.sort();- Ok(configs)- }-- /// Write/refresh ai-memory's standalone Kiro CLI v3 hooks file- /// (`~/.kiro/hooks/ai-memory.json`). The file is ours by name, but a- /// user may still have added entries to it, so reapply preserves any- /// hook entry that is not ai-memory-owned (see- /// [`is_ai_memory_kiro_v3_hook_entry`]). Other `*.json` files in the- /// hooks directory are never touched.- fn apply_to_kiro_cli_v3_hooks(- hooks_dir: &Path,- server_url: &str,- auth_token: Option<&str>,- data_dir: &Path,- args: &InstallHooksArgs,- ) -> Result<()> {- let path = match &args.config_file {- Some(p) => p.clone(),- None => kiro_cli_v3_hooks_path()?,- };- let staged = stage_hook_scripts(hooks_dir, "kiro-cli")?;- let command_dir = staged_command_dir(&staged, "kiro-cli");- let strategy = args.project_strategy.baked();- let outcome = merge_kiro_cli_v3_hooks(- &command_dir,- server_url,- auth_token,- data_dir,- strategy,- &path,- )?;- println!(- "✓ {} {} ({})",- outcome.verb(),- path.display(),- match outcome {- ApplyOutcome::Created => "new file",- ApplyOutcome::Updated => "backup written next to it",- ApplyOutcome::NoOp => "already up to date",- }- );- Ok(())- }-- /// Merge ai-memory's entries into the standalone Kiro v3 hooks file,- /// preserving any non-ai-memory entries a user added to the same file.- fn merge_kiro_cli_v3_hooks(++fn render_kiro_cli_agent_hooks(++ existing: &str,+ staged: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ project_strategy: Option<&str>,- path: &Path,- ) -> Result<ApplyOutcome> {- let payload = build_kiro_cli_v3_hooks_file(++ config_path: &Path,++) -> Result<String> {++ let our_hooks = build_kiro_cli_v2_hooks_value(+ staged,+ server_url,+ auth_token,+ Some(data_dir),+ project_strategy,+ );- let our_entries = payload- .get("hooks")- .and_then(|v| v.as_array())- .context("internal: build_kiro_cli_v3_hooks_file didn't return a hooks array")?- .clone();- apply_atomic(path, |existing| {- mutate_json(existing, |root| {- upsert_kiro_cli_v3_hooks(root, &our_entries)- })++ mutate_json(existing, |root| {++ let hooks = root++ .entry("hooks")++ .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()))++ .as_object_mut()++ .with_context(|| {++ format!(++ "`hooks` in {} is present but not an object",++ config_path.display()++ )++ })?;++ for (event, value) in &our_hooks {++ overlay_kiro_cli_event_hooks(hooks, event, value);++ }++ Ok(())+ })+}+- /// Insert or refresh ai-memory's entries in a Kiro v3 hooks file value:- /// pin `version: "v1"` (the schema this installer writes), drop prior- /// ai-memory entries, append the fresh set, keep everything else.- fn upsert_kiro_cli_v3_hooks(- root: &mut serde_json::Map<String, serde_json::Value>,- our_entries: &[serde_json::Value],- ) -> Result<()> {- root.insert(- "version".to_string(),- serde_json::Value::String("v1".to_string()),- );- let hooks = root- .entry("hooks")- .or_insert_with(|| serde_json::Value::Array(Vec::new()))- .as_array_mut()- .context("`hooks` is present in the Kiro v3 hooks file but not an array")?;- hooks.retain(|entry| !is_ai_memory_kiro_v3_hook_entry(entry));- hooks.extend(our_entries.iter().cloned());- Ok(())++/// Every `*.json` agent config in the Kiro CLI global agents directory,++/// sorted for deterministic apply order. A missing directory is an empty++/// list, not an error — the caller decides how to report it.++pub(crate) fn list_kiro_cli_agent_configs(dir: &Path) -> Result<Vec<PathBuf>> {++ let entries = match fs::read_dir(dir) {++ Ok(entries) => entries,++ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),++ Err(error) => {++ return Err(error).with_context(|| format!("reading {}", dir.display()));++ }++ };++ let mut configs = Vec::new();++ for entry in entries {++ let entry = entry.with_context(|| format!("reading entry in {}", dir.display()))?;++ let path = entry.path();++ let metadata = fs::metadata(&path)++ .with_context(|| format!("reading metadata for {}", path.display()))?;++ if metadata.is_file() && path.extension().and_then(|e| e.to_str()) == Some("json") {++ configs.push(path);++ }++ }++ configs.sort();++ Ok(configs)+}+- /// True if a Kiro v3 hook entry belongs to ai-memory: its `name` carries- /// the `ai-memory-` prefix (what this installer writes) or its command- /// action references ai-memory (legacy/hand-edited installs).- fn is_ai_memory_kiro_v3_hook_entry(entry: &serde_json::Value) -> bool {- if entry- .get("name")- .and_then(|n| n.as_str())- .is_some_and(|n| n.starts_with("ai-memory-"))- {- return true;- }- entry- .get("action")- .and_then(|a| a.get("command"))- .and_then(|c| c.as_str())- .is_some_and(|command| {- let lower = command.to_ascii_lowercase();- lower.contains("ai-memory") || lower.contains("ai_memory")++pub(crate) fn is_ai_memory_kiro_hook_command(command: &str) -> bool {++ let lower = command.to_ascii_lowercase();++ let generated_script =++ lower.contains("/hooks/kiro-cli/") || lower.contains("\\hooks\\kiro-cli\\");++ let ai_memory_executable = lower.contains("ai-memory") || lower.contains("ai_memory");++ let native_hook = ai_memory_executable++ && lower.contains(" hook ")++ && lower.contains("--agent kiro-cli")++ && lower.contains("--server-url");++ (generated_script || native_hook)++ && KIRO_CLI_V2_EVENTS.iter().any(|(_, script)| {++ let stem = script.trim_end_matches(".sh");++ lower.contains(script)++ || lower.contains(&format!("{stem}.ps1"))++ || lower.contains(&format!("--event {stem}"))+ })+}+/// Generate an OpenCode plugin at `~/.config/opencode/plugins/ai-memory.ts`.////// OpenCode's integration surface is a TypeScript plugin, not a JSON@@@ -3536,112 -3534,10 +3817,63 @@@ fn render_kimi_codeOk(())}+fn render_kiro_cli(+ hooks_dir: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: &Path,+ project_strategy: Option<&str>,+) -> Result<()> {+ // Soft check (same rationale as render_claude_code): warn, don't bail,+ // so the docker host-path flow still works.+ for (_, script) in KIRO_CLI_V2_EVENTS {+ let script = hook_script_for_current_platform(script);+ let abs = hooks_dir.join(script.as_ref());+ if !abs.exists() {+ eprintln!(+ "# warning: {} not present on this filesystem. \+ If this command is running inside docker against a \+ host path, you can ignore this; otherwise extract \+ the scripts first with `ai-memory setup-agent`.",+ abs.display()+ );+ }+ }+ let hooks = build_kiro_cli_v2_hooks_value(+ hooks_dir,+ server_url,+ auth_token,+ Some(data_dir),+ project_strategy,+ );+ println!("// Kiro CLI v2-engine hooks — merge the \"hooks\" object into each");+ println!("// agent config under $KIRO_HOME/agents (~/.kiro/agents when unset),");+ println!("// or re-run with --apply to merge into every existing agent config,");+ println!("// preserving third-party hook entries. The v2 engine fires hooks");+ println!("// only for the active agent config; the built-in default agent has");- println!("// no file, so create one first (`kiro-cli agent create`). For the");- println!("// v3 engine use `--agent kiro-cli-v3` instead — the surfaces are");- println!("// not compatible.");++ println!("// no file, so create one first (`kiro-cli agent create`). Kiro v3");++ println!("// hooks remain unsupported because their command-input payload is");++ println!("// not documented; do not reuse this v2 registration there.");+ println!("// Hook scripts: {}", hooks_dir.display());+ println!("// AI-memory server URL: {server_url}");+ if auth_token.is_some() {+ println!("// Auth: AI_MEMORY_AUTH_TOKEN embedded in each hook command below.");+ println!("// Treat agent configs as sensitive (chmod 600).");+ }+ println!();+ println!(+ "{}",+ serde_json::to_string_pretty(&serde_json::json!({ "hooks": hooks }))+ .expect("static hook payload serializes")+ );+ Ok(())+}+- fn render_kiro_cli_v3(- hooks_dir: &Path,- server_url: &str,- auth_token: Option<&str>,- data_dir: &Path,- project_strategy: Option<&str>,- ) -> Result<()> {- for (_, script) in KIRO_CLI_V3_EVENTS {- let script = hook_script_for_current_platform(script);- let abs = hooks_dir.join(script.as_ref());- if !abs.exists() {- eprintln!(- "# warning: {} not present on this filesystem. \- If this command is running inside docker against a \- host path, you can ignore this; otherwise extract \- the scripts first with `ai-memory setup-agent`.",- abs.display()- );- }- }- let payload = build_kiro_cli_v3_hooks_file(- hooks_dir,- server_url,- auth_token,- Some(data_dir),- project_strategy,- );- println!("// Kiro CLI v3-engine hooks file — write as");- println!("// $KIRO_HOME/hooks/ai-memory.json (~/.kiro/hooks/ai-memory.json when");- println!("// unset), or re-run with --apply to write it in place, preserving");- println!("// non-ai-memory entries a user may have added to the same file.");- println!("// Global hooks fire in every workspace on the v3 engine only; the");- println!("// v2 engine ignores this surface — use `--agent kiro-cli` for it.");- println!("// Hook scripts: {}", hooks_dir.display());- println!("// AI-memory server URL: {server_url}");- if auth_token.is_some() {- println!("// Auth: AI_MEMORY_AUTH_TOKEN embedded in each hook command below.");- println!("// Treat the hooks file as sensitive (chmod 600).");- }- println!();- println!(- "{}",- serde_json::to_string_pretty(&payload).expect("static hook payload serializes")- );- Ok(())- }-#[cfg(test)]mod tests {use super::*;use crate::cli::ProjectStrategyArg;- use crate::commands::render_shared::{- KIRO_CLI_V2_SESSION_START_MAX_OUTPUT, KIRO_CLI_V3_HOOK_TIMEOUT_SECONDS,- };++ use crate::commands::render_shared::KIRO_CLI_V2_SESSION_START_MAX_OUTPUT;use std::collections::BTreeMap;use std::fs;#[cfg(any(unix, windows))]@@@ -5728,284 -5998,6 +6334,239 @@@ command = "AI_MEMORY_HOOK_URL=http://ol}}+ // ----------------------------------------------------------------- // Kiro CLI tests (v2 agent-config hooks + v3 standalone hooks file)++ // Kiro CLI v2 agent-config hook tests.+ // ----------------------------------------------------------------++ const KIRO_CLI_STUB_SCRIPTS: [&str; 5] = [+ "session-start.sh",+ "user-prompt-submit.sh",+ "pre-tool-use.sh",+ "post-tool-use.sh",+ "stop.sh",+ ];++ #[test]+ fn kiro_cli_apply_writes_all_v2_events_into_agent_config() {+ let hooks_tmp = TempDir::new().unwrap();+ stub_scripts(hooks_tmp.path(), &KIRO_CLI_STUB_SCRIPTS);++ let config_tmp = TempDir::new().unwrap();+ let config_path = config_tmp.path().join("dev.json");+ fs::write(+ &config_path,+ r#"{"name": "dev", "description": "my agent", "tools": ["*"]}"#,+ )+ .unwrap();++ let outcome = merge_kiro_cli_agent_hooks(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ config_tmp.path(),+ None,+ &config_path,+ )+ .unwrap();+ assert_eq!(outcome, ApplyOutcome::Updated);++ let root: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();+ // Non-hook agent fields survive the merge.+ assert_eq!(root["name"], "dev");+ assert_eq!(root["tools"][0], "*");+ let hooks = root["hooks"].as_object().expect("hooks object");+ assert_eq!(hooks.len(), KIRO_CLI_V2_EVENTS.len());+ for (event, script) in KIRO_CLI_V2_EVENTS {+ let entries = hooks[event].as_array().expect("event array");+ assert_eq!(entries.len(), 1, "{event}");+ let entry = entries[0].as_object().expect("entry object");+ let command = entry["command"].as_str().unwrap();+ let stem = script.strip_suffix(".sh").unwrap();+ assert!(+ command.contains(stem),+ "{event}: command must reference the staged script: {command}"+ );+ // The v2 Hook schema has no `type` field, and an empty-string+ // matcher would match no tool at all (absent = every tool), so+ // neither key may be written.+ assert!(!entry.contains_key("type"), "{event}: no type key");+ assert!(!entry.contains_key("matcher"), "{event}: no matcher key");+ if event == "agentSpawn" {+ // The handoff + brief must not be truncated mid-injection.+ assert_eq!(+ entry["max_output_size"],+ serde_json::json!(KIRO_CLI_V2_SESSION_START_MAX_OUTPUT)+ );+ } else {+ assert!(!entry.contains_key("max_output_size"), "{event}");+ }+ }+ }++ #[test]+ fn kiro_cli_apply_preserves_third_party_hooks_and_is_idempotent() {+ let hooks_tmp = TempDir::new().unwrap();+ stub_scripts(hooks_tmp.path(), &KIRO_CLI_STUB_SCRIPTS);++ let config_tmp = TempDir::new().unwrap();+ let config_path = config_tmp.path().join("dev.json");+ fs::write(+ &config_path,+ r#"{+ "name": "dev",+ "hooks": {+ "agentSpawn": [+ {"command": "git status"},++ {"command": "echo ai-memory status"},+ {"command": "AI_MEMORY_HOOK_URL=http://old:1 /old/ai-memory/hooks/kiro-cli/session-start.sh"}+ ],+ "preToolUse": [+ {"matcher": "execute_bash", "command": "echo audit >> /tmp/audit.log"}+ ]+ }+}"#,+ )+ .unwrap();++ let apply = || {+ merge_kiro_cli_agent_hooks(+ hooks_tmp.path(),+ "http://127.0.0.1:49374",+ None,+ config_tmp.path(),+ None,+ &config_path,+ )+ };+ assert_eq!(apply().unwrap(), ApplyOutcome::Updated);++ let root: serde_json::Value =+ serde_json::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();+ let spawn = root["hooks"]["agentSpawn"].as_array().unwrap();+ // Third-party entry first (preserved), our refreshed entry after;+ // the stale ai-memory entry is gone.- assert_eq!(spawn.len(), 2);++ assert_eq!(spawn.len(), 3);+ assert_eq!(spawn[0]["command"], "git status");- let ours = spawn[1]["command"].as_str().unwrap();++ assert_eq!(spawn[1]["command"], "echo ai-memory status");++ let ours = spawn[2]["command"].as_str().unwrap();+ assert!(ours.contains("session-start"), "{ours}");+ assert!(+ !ours.contains("http://old:1"),+ "stale entry replaced: {ours}"+ );+ // A third-party hook under a trigger we also write survives with+ // its matcher intact.+ let pre = root["hooks"]["preToolUse"].as_array().unwrap();+ assert_eq!(pre.len(), 2);+ assert_eq!(pre[0]["matcher"], "execute_bash");++ // Second apply with identical inputs must be a no-op.+ assert_eq!(apply().unwrap(), ApplyOutcome::NoOp);+ }++ #[test]+ fn kiro_cli_paths_honour_kiro_home() {+ let custom = if cfg!(windows) {+ r"C:\custom\kiro"+ } else {+ "/custom/kiro"+ };+ let agents = kiro_cli_home_join(Some(std::ffi::OsString::from(custom)), "agents").unwrap();+ assert_eq!(agents, Path::new(custom).join("agents"));++ // Empty override and unset var both fall back to ~/.kiro.+ for env in [None, Some(std::ffi::OsString::new())] {+ let agents = kiro_cli_home_join(env.clone(), "agents").unwrap();+ assert!(+ agents.ends_with(Path::new(".kiro").join("agents")),+ "default must be ~/.kiro/agents, got {}",+ agents.display()+ );- let hooks = kiro_cli_home_join(env, "hooks").unwrap();- assert!(- hooks.ends_with(Path::new(".kiro").join("hooks")),- "default must be ~/.kiro/hooks, got {}",- hooks.display()- );+ }+ }+++ #[test]++ fn kiro_hooks_infer_the_managed_mcp_client() {++ assert_eq!(++ mcp_client_for_agent(AgentChoice::KiroCli),++ Some(McpClient::KiroCli)++ );++ }+++ #[test]+ fn kiro_cli_agent_config_listing_is_sorted_json_only() {+ let tmp = TempDir::new().unwrap();+ fs::write(tmp.path().join("b.json"), "{}").unwrap();+ fs::write(tmp.path().join("a.json"), "{}").unwrap();+ fs::write(tmp.path().join("notes.md"), "not an agent").unwrap();+ fs::create_dir(tmp.path().join("sub.json")).unwrap();++ let listed = list_kiro_cli_agent_configs(tmp.path()).unwrap();+ assert_eq!(+ listed,+ vec![tmp.path().join("a.json"), tmp.path().join("b.json")]+ );++ // A missing directory is an empty list, not an error.+ assert!(+ list_kiro_cli_agent_configs(&tmp.path().join("missing"))+ .unwrap()+ .is_empty()+ );++++ let not_a_directory = tmp.path().join("agents.json");++ fs::write(¬_a_directory, "{}").unwrap();++ let error = list_kiro_cli_agent_configs(¬_a_directory).unwrap_err();++ assert!(++ format!("{error:#}").contains("reading"),++ "filesystem failures must not look like an empty agent directory: {error:#}"++ );+ }++ #[test]- fn kiro_cli_v3_apply_writes_versioned_hooks_file() {- let hooks_tmp = TempDir::new().unwrap();- stub_scripts(hooks_tmp.path(), &KIRO_CLI_STUB_SCRIPTS);-- let config_tmp = TempDir::new().unwrap();- let path = config_tmp.path().join("ai-memory.json");++ fn kiro_cli_v2_preflight_is_all_or_nothing_and_preserves_per_agent_strategy() {++ let tmp = TempDir::new().unwrap();++ let repo_root = tmp.path().join("a.json");++ let basename = tmp.path().join("b.json");++ fs::write(++ &repo_root,++ r#"{"name":"a","hooks":{"agentSpawn":[{"command":"AI_MEMORY_PROJECT_STRATEGY=repo-root /old/hooks/kiro-cli/session-start.sh"}]}}"#,++ )++ .unwrap();++ fs::write(&basename, r#"{"name":"b"}"#).unwrap();+- let outcome = merge_kiro_cli_v3_hooks(- hooks_tmp.path(),++ let prepared = preflight_kiro_cli_agent_configs(++ vec![repo_root.clone(), basename.clone()],++ tmp.path(),+ "http://127.0.0.1:49374",+ None,- config_tmp.path(),++ tmp.path(),+ None,- &path,+ )+ .unwrap();- assert_eq!(outcome, ApplyOutcome::Created);-- let root: serde_json::Value =- serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();- assert_eq!(root["version"], "v1");- let hooks = root["hooks"].as_array().expect("hooks array");- assert_eq!(hooks.len(), KIRO_CLI_V3_EVENTS.len());- for (entry, (trigger, script)) in hooks.iter().zip(KIRO_CLI_V3_EVENTS.iter()) {- assert_eq!(entry["trigger"], *trigger);- let stem = script.strip_suffix(".sh").unwrap();- assert_eq!(- entry["name"],- serde_json::json!(format!("ai-memory-{stem}"))- );- assert_eq!(entry["action"]["type"], "command");- let command = entry["action"]["command"].as_str().unwrap();- assert!(command.contains(stem), "{trigger}: {command}");- // v3 timeout is seconds (v2 uses timeout_ms) — a mixed-up- // unit would give hooks a 10 ms budget.- assert_eq!(- entry["timeout"],- serde_json::json!(KIRO_CLI_V3_HOOK_TIMEOUT_SECONDS)- );- assert!(- entry.get("matcher").is_none(),- "{trigger}: no matcher — omitted always fires"- );- }- }-- #[test]- fn kiro_cli_v3_apply_preserves_user_entries_and_is_idempotent() {- let hooks_tmp = TempDir::new().unwrap();- stub_scripts(hooks_tmp.path(), &KIRO_CLI_STUB_SCRIPTS);-- let config_tmp = TempDir::new().unwrap();- let path = config_tmp.path().join("ai-memory.json");- fs::write(- &path,- r#"{- "version": "v1",- "hooks": [- {"name": "lint-on-save", "trigger": "PostFileSave", "matcher": "\\.rs$",- "action": {"type": "command", "command": "cargo fmt"}},- {"name": "ai-memory-session-start", "trigger": "SessionStart",- "action": {"type": "command", "command": "/old/ai-memory/hooks/kiro-cli/session-start.sh"}}- ]- }"#,++ assert_eq!(prepared[0].1, Some(ProjectStrategyArg::RepoRoot));++ assert_eq!(prepared[1].1, None);++++ let before = fs::read_to_string(&repo_root).unwrap();++ fs::write(&basename, "{not-json").unwrap();++ let error = preflight_kiro_cli_agent_configs(++ vec![repo_root.clone(), basename],++ tmp.path(),++ "http://127.0.0.1:49374",++ None,++ tmp.path(),++ None,+ )- .unwrap();-- let apply = || {- merge_kiro_cli_v3_hooks(- hooks_tmp.path(),- "http://127.0.0.1:49374",- None,- config_tmp.path(),- None,- &path,- )- };- assert_eq!(apply().unwrap(), ApplyOutcome::Updated);-- let root: serde_json::Value =- serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();- let hooks = root["hooks"].as_array().unwrap();- // The user's hook survives in front; our five refreshed entries- // replace the single stale ai-memory entry.- assert_eq!(hooks.len(), 1 + KIRO_CLI_V3_EVENTS.len());- assert_eq!(hooks[0]["name"], "lint-on-save");- assert_eq!(hooks[1]["name"], "ai-memory-session-start");- let refreshed = hooks[1]["action"]["command"].as_str().unwrap();- // The refreshed command replaces the stale path regardless of the- // platform's command form (native binary or staged script).- assert!(refreshed.contains("session-start"), "{refreshed}");- assert!(- !refreshed.contains("/old/ai-memory"),- "stale ai-memory entry must be replaced: {refreshed}"++ .unwrap_err();++ assert!(format!("{error:#}").contains("valid JSON"));++ assert_eq!(++ fs::read_to_string(repo_root).unwrap(),++ before,++ "a malformed later config must not mutate an earlier agent"+ );-- assert_eq!(apply().unwrap(), ApplyOutcome::NoOp);+ }+// ----------------------------------------------------------------// Devin tests// ----------------------------------------------------------------diff --cc crates/ai-memory-cli/src/commands/install_mcp.rsindex 04785a9c,702c92da..8add847c--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@@ -893,6 -1137,22 +1137,24 @@@ fn render_kimi_code(args: &InstallMcpAr))}+ fn render_kiro_cli(args: &InstallMcpArgs) -> Result<String> {+ Ok(format!(+ "# Kiro CLI - merge into $KIRO_HOME/settings/mcp.json\n\+ # (defaults to ~/.kiro/settings/mcp.json):\n\+ #\n\+ # Kiro accepts HTTPS remote endpoints and plain HTTP only on\n\+ # localhost. `?flavor=bedrock` removes unsupported root-level\n\+ # schema combinators while handler validation remains unchanged.\n\- # This integration is MCP-only; Kiro v2 and v3 use incompatible\n\- # hook and session formats, so lifecycle capture and managed\n\- # workstreams are not installed.\n\++ # Lifecycle capture for the documented v2 engine is installed\n\++ # separately with `install-hooks --agent kiro-cli`. Kiro v3 hook\n\++ # capture remains unsupported until its command-input contract is\n\++ # documented.\n\++ # Managed workstreams are not installed by this command.\n\+ {snippet}\n",+ snippet = render_json_mcp_fragment(args)?,+ ))+ }+fn render_vscode_copilot(args: &InstallMcpArgs) -> Result<String> {Ok(format!("# VS Code GitHub Copilot (agent mode) — write to one of:\n\@@@ -1241,6 -1806,13 +1808,14 @@@ mod testslet kimi_with_token = render_with_token(McpClient::KimiCode);assert!(kimi_with_token.contains("\"headers\""));assert!(kimi_with_token.contains("\"Authorization\": \"Bearer test-token-deadbeef\""));+ let kiro = render_for_test(McpClient::KiroCli);+ assert!(kiro.contains("\"mcpServers\""));+ assert!(kiro.contains("http://127.0.0.1:49374/mcp?flavor=bedrock"));+ assert!(!kiro.contains("\"transport\""));- assert!(kiro.contains("MCP-only"));++ assert!(kiro.contains("install-hooks --agent kiro-cli"));++ assert!(kiro.contains("Kiro v3 hook"));+ let kiro_with_token = render_with_token(McpClient::KiroCli);+ assert!(kiro_with_token.contains("\"Authorization\": \"Bearer test-token-deadbeef\""));// VS Code Copilot must use the `servers` top-level key — the// `mcpServers` form is silently ignored by VS Code's MCP// framework. Regression guard against a future copy-pastediff --cc crates/ai-memory-cli/src/commands/render_shared.rsindex 22635f26,581aeea6..7ac46f3b--- a/crates/ai-memory-cli/src/commands/render_shared.rs+++ b/crates/ai-memory-cli/src/commands/render_shared.rs@@@ -77,47 -77,6 +77,29 @@@ pub(crate) const KIMI_CODE_EVENTS: [(&s("SubagentStop", "subagent-stop.sh"),];+/// Kiro CLI v2-engine lifecycle events. Each pair is+/// `(trigger-name-in-agent-config, POSIX hook-script-filename)`.+///+/// The v2 engine embeds hooks in agent configs (`~/.kiro/agents/*.json`)+/// keyed by camelCase triggers, per kiro.dev/docs/cli/hooks and the+/// shipping `HookTrigger` serde in aws/amazon-q-developer-cli+/// (`crates/chat-cli/src/cli/agent/hook.rs`). The vocabulary is exactly+/// these five events — there is no PreCompact/SessionEnd/subagent+/// equivalent. Adding a hook event means updating this list AND adding+/// the matching `.sh` and `.ps1` files under `hooks/kiro-cli/`; the+/// install-hooks parity test fails if the bundle drifts.+///- /// The v3 engine of the same binary uses an incompatible standalone- /// hooks file with PascalCase triggers — see [`KIRO_CLI_V3_EVENTS`].- /// Do not mix the two vocabularies.++/// Kiro's v3 engine uses a different standalone registration format, but++/// its command-input payload is not documented. Do not advertise or install++/// v3 hooks until that input contract can be captured in fixtures and tested.+pub(crate) const KIRO_CLI_V2_EVENTS: [(&str, &str); 5] = [+ ("agentSpawn", "session-start.sh"),+ ("userPromptSubmit", "user-prompt-submit.sh"),+ ("preToolUse", "pre-tool-use.sh"),+ ("postToolUse", "post-tool-use.sh"),+ ("stop", "stop.sh"),+];+- /// Kiro CLI v3-engine lifecycle triggers (early access, `kiro-cli --v3`).- /// Each pair is `(PascalCase trigger, POSIX hook-script-filename)`.- ///- /// The v3 engine reads standalone versioned hooks files- /// (`.kiro/hooks/*.json` per workspace, `~/.kiro/hooks/*.json` global)- /// per kiro.dev/docs/cli/v3/hooks. v3 also defines task/file/manual- /// triggers (PreTaskExec, PostFileSave, …) that ai-memory does not- /// subscribe to; capture sticks to the shared five-event vocabulary.- /// The same `hooks/kiro-cli/` script bundle serves both engines — only- /// the registration surface differs.- pub(crate) const KIRO_CLI_V3_EVENTS: [(&str, &str); 5] = [- ("SessionStart", "session-start.sh"),- ("UserPromptSubmit", "user-prompt-submit.sh"),- ("PreToolUse", "pre-tool-use.sh"),- ("PostToolUse", "post-tool-use.sh"),- ("Stop", "stop.sh"),- ];-/// Devin lifecycle events ai-memory hooks. Each pair is/// `(event-name-in-Devin-settings, POSIX hook-script-filename)`.///@@@ -779,139 -798,6 +821,73 @@@ fn kimi_code_hook_commands_for_platform.collect()}+/// Build the `hooks` map for a Kiro CLI v2-engine agent config. Entry+/// shape per the shipping `Hook` struct (aws/amazon-q-developer-cli+/// `crates/chat-cli/src/cli/agent/hook.rs`): a flat+/// `{ "command": … }` object per trigger. Two deliberate omissions:+///+/// - no `matcher` key: in Kiro v2 an *absent* matcher applies the hook+/// to every tool, while an empty-string matcher is a tool-name+/// pattern that matches nothing — the opposite of Claude Code's+/// empty-matcher convention, so `HookShape::Flat` must not be reused;+/// - no `type` key: the v2 `Hook` struct has no such field.+///+/// `agentSpawn` sets `max_output_size` above the 10 KiB default so a+/// fetched handoff + compiled project brief is not truncated mid-JSON+/// before Kiro adds it to the agent context.+pub(crate) fn build_kiro_cli_v2_hooks_value(+ emit_root: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ data_dir: Option<&Path>,+ project_strategy: Option<&str>,+) -> serde_json::Map<String, Value> {+ build_kiro_cli_v2_hooks_value_for_platform(+ emit_root,+ server_url,+ auth_token,+ HookCommandPlatform::current(),+ data_dir,+ project_strategy,+ )+}++/// Session-start context injection ceiling for Kiro v2 (`max_output_size`).+/// Kiro truncates hook stdout beyond this; 64 KiB comfortably covers a+/// handoff plus a `[briefing]`-budgeted brief.+pub(crate) const KIRO_CLI_V2_SESSION_START_MAX_OUTPUT: usize = 64 * 1024;++fn build_kiro_cli_v2_hooks_value_for_platform(+ emit_root: &Path,+ server_url: &str,+ auth_token: Option<&str>,+ platform: HookCommandPlatform,+ data_dir: Option<&Path>,+ project_strategy: Option<&str>,+) -> serde_json::Map<String, Value> {+ let mut hooks = serde_json::Map::new();+ for (event, script) in KIRO_CLI_V2_EVENTS {+ let script = script_for_platform(script, platform);+ let abs = emit_root.join(script.as_ref());+ let command = hook_command(+ &abs,+ server_url,+ auth_token,+ HookCommandContext::new(platform, "kiro-cli", data_dir, project_strategy),+ );+ let mut entry = serde_json::Map::new();+ entry.insert("command".to_string(), Value::String(command));+ if event == "agentSpawn" {+ entry.insert(+ "max_output_size".to_string(),+ Value::from(KIRO_CLI_V2_SESSION_START_MAX_OUTPUT),+ );+ }+ hooks.insert(event.to_string(), json!([Value::Object(entry)]));+ }+ hooks+}+- /// Build the standalone versioned hooks file for the Kiro CLI v3 engine- /// (`~/.kiro/hooks/ai-memory.json`), per kiro.dev/docs/cli/v3/hooks:- /// `{"version":"v1","hooks":[{name, description, trigger, action, timeout}]}`- /// with PascalCase triggers and `{"type":"command","command":…}` actions.- /// No `matcher` key — an omitted matcher always fires, and v3 matchers- /// are regexes over tool names / prompt text, none of which a capture- /// hook wants to filter. Every entry name carries the `ai-memory-`- /// prefix; reapply and uninstall identify our entries by that prefix or- /// by the command string, so third-party hooks that a user placed in- /// the same file survive.- ///- /// `timeout` is in SECONDS on v3 (not v2's `timeout_ms`). The scripts- /// self-bound their network waits well under a second, so 10 s is a- /// generous ceiling that still protects the session UX.- pub(crate) fn build_kiro_cli_v3_hooks_file(- emit_root: &Path,- server_url: &str,- auth_token: Option<&str>,- data_dir: Option<&Path>,- project_strategy: Option<&str>,- ) -> Value {- build_kiro_cli_v3_hooks_file_for_platform(- emit_root,- server_url,- auth_token,- HookCommandPlatform::current(),- data_dir,- project_strategy,- )- }-- /// Timeout (seconds) for ai-memory's Kiro v3 hook entries.- pub(crate) const KIRO_CLI_V3_HOOK_TIMEOUT_SECONDS: u64 = 10;-- fn build_kiro_cli_v3_hooks_file_for_platform(- emit_root: &Path,- server_url: &str,- auth_token: Option<&str>,- platform: HookCommandPlatform,- data_dir: Option<&Path>,- project_strategy: Option<&str>,- ) -> Value {- let hooks: Vec<Value> = KIRO_CLI_V3_EVENTS- .iter()- .map(|(trigger, script)| {- let stem = script.trim_end_matches(".sh");- let script = script_for_platform(script, platform);- let abs = emit_root.join(script.as_ref());- let command = hook_command(- &abs,- server_url,- auth_token,- HookCommandContext::new(platform, "kiro-cli", data_dir, project_strategy),- );- json!({- "name": format!("ai-memory-{stem}"),- "description": "ai-memory lifecycle capture (fire-and-forget)",- "trigger": trigger,- "action": { "type": "command", "command": command },- "timeout": KIRO_CLI_V3_HOOK_TIMEOUT_SECONDS,- })- })- .collect();- json!({ "version": "v1", "hooks": hooks })- }-#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub(crate) enum HookCommandPlatform {Posix,diff --cc crates/ai-memory-cli/src/commands/setup_agent.rsindex 6f887f9c,c05d238b..11533505--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@@ -38,9 -38,8 +38,8 @@@ use crate::cli::{AgentChoice, SetupAgenuse crate::commands::install_mcp;use crate::commands::render_shared::{ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CODEX_PROFILE, CURSOR_PROFILE,- GEMINI_PROFILE, KIMI_CODE_EVENTS, KIRO_CLI_V2_EVENTS, KIRO_CLI_V3_EVENTS,- build_claude_code_payload, build_devin_payload, build_grok_payload,- hook_script_for_current_platform,- GEMINI_PROFILE, KIMI_CODE_EVENTS, build_claude_code_payload, build_devin_payload,- build_grok_payload, hook_script_for_current_platform,++ GEMINI_PROFILE, KIMI_CODE_EVENTS, KIRO_CLI_V2_EVENTS, build_claude_code_payload,++ build_devin_payload, build_grok_payload, hook_script_for_current_platform,};use crate::config::{Config, DEFAULT_SERVER_URL};@@@ -150,16 -149,6 +149,11 @@@ pub fn run(config: &Config, args: Setup// script listing is deduplicated below; apply-mode owns the exact// `[[hooks]]` TOML merge into the user's config.toml.AgentChoice::KimiCode => emit_other(&emit_root, agent_sub, &args, &[&KIMI_CODE_EVENTS]),- // Both Kiro engine surfaces stage the same `hooks/kiro-cli/`- // bundle; only the registration config differs (v2 agent-config- // entries vs the v3 standalone hooks file), and apply-mode owns- // those exact merges.++ // Kiro v2 embeds its lifecycle hooks in agent configs. Kiro v3 is++ // withheld until its command-input payload contract is documented.+ AgentChoice::KiroCli => {+ emit_other(&emit_root, agent_sub, &args, &[&KIRO_CLI_V2_EVENTS]);+ }- AgentChoice::KiroCliV3 => {- emit_other(&emit_root, agent_sub, &args, &[&KIRO_CLI_V3_EVENTS]);- }AgentChoice::OpenCode| AgentChoice::Pi| AgentChoice::Omp@@@ -687,55 -676,4 +681,32 @@@ mod testsassert_eq!(KIMI_CODE_EVENTS.len(), 10);assert_eq!(paths.len(), 9);}++ #[test]- fn kiro_cli_manual_script_paths_cover_both_engine_event_sets() {- // Both Kiro engines share one five-script bundle; only the- // trigger spellings differ (v2 camelCase in agent configs, v3- // PascalCase in the standalone hooks file). The parity gate- // keeps the bundle and both event tables from drifting apart.++ fn kiro_cli_manual_script_paths_cover_v2_event_set() {+ let root = Path::new("/hooks/kiro-cli");+ let v2_paths = event_script_paths(root, &[&KIRO_CLI_V2_EVENTS]);- let v3_paths = event_script_paths(root, &[&KIRO_CLI_V3_EVENTS]);- assert_eq!(- v2_paths, v3_paths,- "both engines must stage the same bundle"- );+ let rendered = v2_paths+ .iter()+ .map(|path| path.to_string_lossy())+ .collect::<Vec<_>>()+ .join("\n");++ for script in [+ "session-start",+ "user-prompt-submit",+ "pre-tool-use",+ "post-tool-use",+ "stop",+ ] {+ assert!(+ rendered.contains(script),+ "Kiro CLI setup-agent must list {script}; got:\n{rendered}"+ );+ }- // The v2 vocabulary is exactly five camelCase triggers; the v3- // vocabulary is the same five in PascalCase. No PreCompact /- // SessionEnd / subagent equivalents exist on either engine.++ // The documented v2 vocabulary has no PreCompact, SessionEnd, or++ // subagent equivalents.+ assert_eq!(KIRO_CLI_V2_EVENTS.len(), 5);- assert_eq!(KIRO_CLI_V3_EVENTS.len(), 5);+ assert_eq!(v2_paths.len(), 5);- // Positional pairing: entry N of both tables is the same logical- // event registered under each engine's spelling (v2 `agentSpawn`- // pairs with v3 `SessionStart`), so the script must match- // position by position.- for ((v2_event, v2_script), (v3_event, v3_script)) in- KIRO_CLI_V2_EVENTS.iter().zip(KIRO_CLI_V3_EVENTS.iter())- {- assert_eq!(- v2_script, v3_script,- "v2 {v2_event} and v3 {v3_event} must run the same script"- );- }+ }}diff --cc crates/ai-memory-cli/src/commands/uninstall.rsindex 3173e905,35e723e1..b3a8736b--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@@ -42,10 -42,6 +42,8 @@@ enum RewriteOpZeroHooksJson,/// Kimi Code `[[hooks]]` rules inside config.toml.KimiCodeHooksToml,- /// Kiro CLI v3 standalone hooks file — `hooks` array entries whose- /// `name` carries the `ai-memory-` prefix (or whose command action- /// references ai-memory).- KiroCliV3HooksJson,++ /// Kiro CLI v2 agent-config hooks with exact generated command signatures.++ KiroCliV2HooksJson,/// MCP JSON config for one client shape.McpJson(McpClient),/// Codex TOML MCP config.@@@ -212,6 -199,6 +201,26 @@@ fn build_plan(args: &UninstallArgs) ->);}++ let mut kiro_configs =++ install_hooks::list_kiro_cli_agent_configs(&install_hooks::kiro_cli_agents_dir()?)?;++ let cwd = std::env::current_dir().context("getting CWD for Kiro hook removal")?;++ kiro_configs.extend(install_hooks::list_kiro_cli_agent_configs(++ &cwd.join(".kiro/agents"),++ )?);++ kiro_configs.sort();++ kiro_configs.dedup();++ for path in kiro_configs {++ let content = std::fs::read_to_string(&path)++ .with_context(|| format!("reading {}", path.display()))?;++ let removal = strip_kiro_cli_v2_hooks(&content)?;++ push_rewrite(++ &mut plan,++ path,++ removal.removed_events,++ RewriteOp::KiroCliV2HooksJson,++ );++ }++let antigravity = install_hooks::antigravity_hooks_path()?;if antigravity.exists() {let content = std::fs::read_to_string(&antigravity)@@@ -494,7 -470,6 +492,7 @@@ fn apply_change(change: &PlannedChange}RewriteOp::ZeroHooksJson => strip_zero_hooks(&out)?.new_content,RewriteOp::KimiCodeHooksToml => strip_kimi_code_hooks(&out)?.new_content,- RewriteOp::KiroCliV3HooksJson => strip_kiro_cli_v3_hooks(&out)?.new_content,++ RewriteOp::KiroCliV2HooksJson => strip_kiro_cli_v2_hooks(&out)?.new_content,RewriteOp::McpJson(client) => {strip_mcp_json_client(&out, client, name, url)?.0}@@@ -801,43 -776,6 +799,45 @@@ fn strip_zero_hooks(content: &str) -> R})}- /// Remove ai-memory's entries from the Kiro CLI v3 standalone hooks file- /// (`~/.kiro/hooks/ai-memory.json`). Install writes every entry with the- /// `ai-memory-` name prefix, so the prefix is the primary ownership- /// signature; a command action referencing ai-memory covers hand-edited- /// entries. Non-ai-memory entries a user added to the same file survive,- /// and the pinned `version` key is left alone (an empty `hooks` array is- /// a valid v3 file).- fn strip_kiro_cli_v3_hooks(content: &str) -> Result<HookRemoval> {++fn strip_kiro_cli_v2_hooks(content: &str) -> Result<HookRemoval> {+ let mut removed_events = Vec::new();+ let new_content = mutate_json(content, |root| {- let Some(hooks) = root.get_mut("hooks").and_then(|v| v.as_array_mut()) else {++ let Some(hooks) = root++ .get_mut("hooks")++ .and_then(|value| value.as_object_mut())++ else {+ return Ok(());+ };- hooks.retain(|hook| {- let name = hook.get("name").and_then(|v| v.as_str());- let ours = name.is_some_and(|name| name.starts_with("ai-memory-"))- || hook- .get("action")- .and_then(|action| action.get("command"))- .and_then(|command| command.as_str())- .is_some_and(|command| {- let lower = command.to_ascii_lowercase();- lower.contains("ai-memory") || lower.contains("ai_memory")- });- if ours {- removed_events.push(format!("kiro-cli-v3.{}", name.unwrap_or("<unnamed>")));++ let events: Vec<String> = hooks.keys().cloned().collect();++ for event in events {++ let Some(entries) = hooks.get_mut(&event).and_then(|value| value.as_array_mut()) else {++ continue;++ };++ let original_len = entries.len();++ entries.retain(|entry| {++ !entry++ .get("command")++ .and_then(serde_json::Value::as_str)++ .is_some_and(install_hooks::is_ai_memory_kiro_hook_command)++ });++ if entries.len() != original_len {++ removed_events.push(event.clone());+ }- !ours- });++ if entries.is_empty() {++ hooks.remove(&event);++ }++ }++ if hooks.is_empty() {++ root.remove("hooks");++ }+ Ok(())+ })?;+ Ok(HookRemoval {+ new_content,+ removed_events,+ })+}+/// Remove ai-memory hook entries from Devin's `hooks.v1.json`, whose root/// object is the hook-event map. This is intentionally separate from/// `strip_ai_memory_hooks` so we never infer a flat shape for other agents.diff --cc crates/ai-memory-cli/tests/removal.rsindex 6660d579,6af0fe9a..675ff924--- a/crates/ai-memory-cli/tests/removal.rs+++ b/crates/ai-memory-cli/tests/removal.rs@@@ -40,6 -40,6 +40,8 @@@ fn command_with_home(home: &Path) -> Co// A host-level KIMI_CODE_HOME would pull uninstall's kimi-code// config sweep out of the sandbox; tests opt back in explicitly..env_remove("KIMI_CODE_HOME")++ // The same isolation is required for Kiro's relocatable config root.++ .env_remove("KIRO_HOME")// Keep Claude installer/removal tests inside their temp HOME unless a// test explicitly opts into a relocated config root..env_remove("CLAUDE_CONFIG_DIR");@@@ -1085,86 -1085,6 +1087,104 @@@ command = "'/usr/local/bin/ai-memory' h);}+#[test]- fn uninstall_kiro_cli_hooks_preserves_user_entries_on_both_engines() {++fn uninstall_kiro_cli_hooks_preserves_user_and_v3_entries() {+ let _guard = cli_test_lock();++ let project = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();+ let kiro = home.path().join(".kiro");++ // v2 engine surface: an agent config with a third-party hook next to ours.+ let agents = kiro.join("agents");+ std::fs::create_dir_all(&agents).unwrap();+ let agent_config = agents.join("dev.json");+ std::fs::write(+ &agent_config,+ r#"{+ "name": "dev",+ "tools": ["*"],+ "hooks": {+ "agentSpawn": [+ {"command": "git status"},- {"command": "AI_MEMORY_HOOK_URL=http://h /x/kiro-cli/session-start.sh", "max_output_size": 65536}++ {"command": "echo ai-memory status"},++ {"command": "AI_MEMORY_HOOK_URL=http://h /x/hooks/kiro-cli/session-start.sh", "max_output_size": 65536}+ ],+ "stop": [+ {"command": "'/usr/local/bin/ai-memory' hook --event stop --agent kiro-cli --server-url http://h:49374"}+ ]+ }+}"#,+ )+ .unwrap();+- // v3 engine surface: our standalone hooks file with one user entry inside.++ let local_agent = project.path().join(".kiro/agents/local.json");++ write_file(++ &local_agent,++ r#"{"name":"local","hooks":{"stop":[{"command":"/x/hooks/kiro-cli/stop.sh"}]}}"#,++ );++++ // v3 is unsupported because its command-input contract is undocumented.++ // Uninstall must leave even an ai-memory-looking standalone file untouched.+ let hooks_dir = kiro.join("hooks");+ std::fs::create_dir_all(&hooks_dir).unwrap();+ let v3_file = hooks_dir.join("ai-memory.json");+ std::fs::write(+ &v3_file,+ r#"{+ "version": "v1",+ "hooks": [+ {"name": "ai-memory-session-start", "trigger": "SessionStart",+ "action": {"type": "command", "command": "/x/kiro-cli/session-start.sh"}, "timeout": 10},+ {"name": "lint-on-save", "trigger": "PostFileSave", "matcher": "\\.rs$",+ "action": {"type": "command", "command": "cargo fmt"}}+ ]+}"#,+ )+ .unwrap();+ // A neighbouring third-party hooks file must never be touched.+ let third_party_file = hooks_dir.join("team-hooks.json");+ let third_party_body = r#"{"version":"v1","hooks":[{"name":"security-check","trigger":"PreToolUse","action":{"type":"command","command":"/usr/bin/audit"}}]}"#;+ std::fs::write(&third_party_file, third_party_body).unwrap();++ let status = command_with_home(home.path())+ .args(["uninstall", "--apply", "--only", "hooks", "--yes"])++ .current_dir(project.path())+ .status()+ .unwrap();+ assert!(status.success(), "uninstall failed");++ let agent_after: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(&agent_config).unwrap()).unwrap();+ assert_eq!(agent_after["name"], "dev", "agent definition must survive");+ let spawn = agent_after["hooks"]["agentSpawn"].as_array().unwrap();- assert_eq!(spawn.len(), 1, "only ai-memory entries removed");++ assert_eq!(spawn.len(), 2, "only exact ai-memory entries removed");+ assert_eq!(spawn[0]["command"], "git status");++ assert_eq!(spawn[1]["command"], "echo ai-memory status");+ assert!(+ agent_after["hooks"].get("stop").is_none(),+ "an event array left empty is dropped"+ );++ let local_after: serde_json::Value =++ serde_json::from_str(&std::fs::read_to_string(&local_agent).unwrap()).unwrap();++ assert!(++ local_after.get("hooks").is_none(),++ "project-local ai-memory hooks must also be removed"++ );+- let v3_after: serde_json::Value =- serde_json::from_str(&std::fs::read_to_string(&v3_file).unwrap()).unwrap();- let v3_hooks = v3_after["hooks"].as_array().unwrap();- assert_eq!(v3_hooks.len(), 1, "user entry in our file must survive");- assert_eq!(v3_hooks[0]["name"], "lint-on-save");++ assert!(++ std::fs::read_to_string(&v3_file)++ .unwrap()++ .contains("ai-memory-session-start"),++ "unsupported v3 hook files must remain untouched"++ );++ assert_eq!(+ std::fs::read_to_string(&third_party_file).unwrap(),+ third_party_body,+ "third-party hooks files must stay byte-identical"+ );+}+#[test]fn uninstall_mcp_custom_url_removes_kimi_code_only_by_endpoint() {let _guard = cli_test_lock();diff --cc crates/ai-memory-core/src/ids.rsindex 5fd28b9e,6bc7b7f2..351bd784--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@@ -208,9 -210,8 +210,10 @@@ pub enum AgentKindDevin,/// Kimi Code CLI (Moonshot AI).KimiCode,- /// Kiro CLI (AWS), covering both the default v2 agent engine and the- /// early-access v3 engine of the same binary.++ /// AWS Kiro CLI (verified v2 lifecycle protocol).+ KiroCli,+ /// Hermes Agent (Nous Research).+ Hermes,/// Anything else (manual capture, future agents).Other,}@@@ -221,7 -222,7 +224,7 @@@ impl AgentKind/// CHECK constraint accepts every kind (the Zero integration shipped/// with the enum variant but without the V26 migration and only a/// live test caught it). Extend together with the enum.-- pub const ALL: [Self; 17] = [++ pub const ALL: [Self; 18] = [Self::ClaudeCode,Self::Codex,Self::OpenCode,@@@ -237,7 -238,7 +240,8 @@@Self::Zero,Self::Devin,Self::KimiCode,+ Self::KiroCli,+ Self::Hermes,Self::Other,];@@@ -260,7 -261,7 +264,8 @@@Self::Zero => "zero",Self::Devin => "devin",Self::KimiCode => "kimi-code",+ Self::KiroCli => "kiro-cli",+ Self::Hermes => "hermes",Self::Other => "other",}}@@@ -286,7 -287,7 +291,8 @@@"zero" => Self::Zero,"devin" => Self::Devin,"kimi-code" | "kimi" => Self::KimiCode,- "kiro-cli" | "kiro" | "kiro_cli" => Self::KiroCli,++ "kiro-cli" | "kiro" => Self::KiroCli,+ "hermes" | "hermes-agent" => Self::Hermes,_ => Self::Other,}}@@@ -430,29 -424,22 +429,39 @@@ mod tests}#[test]- fn agent_kind_kiro_cli_round_trips() {+ fn agent_kind_hermes_round_trips_without_claiming_handoff_delivery() {+ assert_eq!(AgentKind::Hermes.as_str(), "hermes");+ assert_eq!(AgentKind::from_wire("hermes"), AgentKind::Hermes);+ assert_eq!(AgentKind::from_wire("hermes-agent"), AgentKind::Hermes);+ assert_eq!(+ serde_json::from_str::<AgentKind>("\"hermes\"").unwrap(),+ AgentKind::Hermes+ );+ assert_eq!(+ serde_json::to_string(&AgentKind::Hermes).unwrap(),+ "\"hermes\""+ );+ assert!(!AgentKind::Hermes.session_start_injects_handoff());+ assert!(!AgentKind::Hermes.user_prompt_injects_handoff());+ }+++ #[test]++ fn agent_kind_kiro_cli_round_trips_and_injects_at_session_start() {+ assert_eq!(AgentKind::KiroCli.as_str(), "kiro-cli");+ assert_eq!(AgentKind::from_wire("kiro-cli"), AgentKind::KiroCli);+ assert_eq!(AgentKind::from_wire("kiro"), AgentKind::KiroCli);- assert_eq!(AgentKind::from_wire("kiro_cli"), AgentKind::KiroCli);- // serde uses rename_all = "kebab-case" → "kiro-cli".+ assert_eq!(+ serde_json::to_string(&AgentKind::KiroCli).unwrap(),+ "\"kiro-cli\""+ );+ assert_eq!(+ serde_json::from_str::<AgentKind>("\"kiro-cli\"").unwrap(),+ AgentKind::KiroCli+ );- // Unknown tags still degrade to Other.- assert_eq!(AgentKind::from_wire("kiro-ide"), AgentKind::Other);- // Both Kiro engines add session-start hook stdout to the agent- // context (v2 agentSpawn, v3 SessionStart), so the handoff is- // fetched and injected there — not on UserPromptSubmit.+ assert!(AgentKind::KiroCli.session_start_injects_handoff());+ assert!(!AgentKind::KiroCli.user_prompt_injects_handoff());+ }+#[test]fn user_prompt_handoff_injection_is_kimi_only() {for agent in AgentKind::ALL {diff --cc crates/ai-memory-hooks/src/capture_policy.rsindex 2d92e64a,c8af4d50..5aace4fa--- a/crates/ai-memory-hooks/src/capture_policy.rs+++ b/crates/ai-memory-hooks/src/capture_policy.rs@@@ -141,7 -138,15 +138,18 @@@ pub(crate) fn tool_observation_metadataobject.get("tool")?.as_str()?,object.get("callID").and_then(Value::as_str),),++ // Kiro v2 tool hooks use `tool_name` + `tool_input`. Unknown payload++ // shapes fail safe to metadata-only under an active policy.++ AgentKind::KiroCli => (object.get("tool_name")?.as_str()?, None),AgentKind::AntigravityCli => (object.get("toolCall")?.get("name")?.as_str()?, None),+ AgentKind::Hermes => (+ object.get("tool_name")?.as_str()?,+ object+ .get("extra")+ .and_then(Value::as_object)+ .and_then(|extra| extra.get("tool_call_id"))+ .and_then(Value::as_str),+ ),_ => return None,};// PreToolUse needs a proven input shape. PostToolUse deliberately does@@@ -151,7 -156,7 +159,10 @@@AgentKind::AntigravityCli => object.get("toolCall")?.get("args").is_some(),_ => object.get(- if matches!(agent, AgentKind::ClaudeCode | AgentKind::KiroCli) {- if matches!(agent, AgentKind::ClaudeCode | AgentKind::Hermes) {++ if matches!(++ agent,++ AgentKind::ClaudeCode | AgentKind::Hermes | AgentKind::KiroCli++ ) {"tool_input"} else {"args"@@@ -173,17 -178,6 +184,15 @@@ pub(crate) fn tool_observation_outcome(Some(false) => ToolOutcome::Success,None => ToolOutcome::Unknown,},- // Kiro CLI postToolUse documents `tool_response.success`- // (kiro.dev/docs/cli/hooks).+ AgentKind::KiroCli => match raw+ .get("tool_response")+ .and_then(|response| response.get("success"))+ .and_then(Value::as_bool)+ {+ Some(true) => ToolOutcome::Success,+ Some(false) => ToolOutcome::Error,+ None => ToolOutcome::Unknown,+ },AgentKind::AntigravityCliif raw.get("error")@@@ -524,7 -518,7 +533,8 @@@ fn extract(agent: AgentKind, raw: &Valu| AgentKind::Cursor| AgentKind::GeminiCli| AgentKind::Devin- | AgentKind::Hermes => object++ | AgentKind::Hermes+ | AgentKind::KiroCli => object.get("tool_name").and_then(Value::as_str).map(|name| (name, object.get("tool_input"))),@@@ -573,17 -567,30 +583,31 @@@fn family(name: &str) -> ToolFamily {match name.to_ascii_lowercase().as_str() {- // `fs_read`/`fs_write` are Kiro CLI's built-in file tools- // (kiro.dev/docs/cli/reference/built-in-tools).- "read" | "write" | "edit" | "apply_patch" | "notebookedit" | "notebook_edit"- | "create_file" | "delete_file" | "rename_file" | "move_file" | "multi_edit"- | "multiedit" | "replace" | "replace_all" | "fs_read" | "fs_write" => ToolFamily::File,- "search" | "grep" | "glob" | "find" | "list" | "ls" | "list_files" | "read_dir" => {- ToolFamily::SearchList- }- // `execute_bash`/`execute_cmd` are Kiro CLI's shell tools.- "bash" | "shell" | "execute" | "run_command" | "web_search" | "execute_bash"- | "execute_cmd" => ToolFamily::NonFile,+ "read"+ | "write"+ | "edit"+ | "apply_patch"+ | "notebookedit"+ | "notebook_edit"+ | "create_file"+ | "delete_file"+ | "rename_file"+ | "move_file"+ | "multi_edit"+ | "multiedit"+ | "replace"+ | "replace_all"+ | "view_file"+ | "replace_file_content"+ | "multi_replace_file_content"- | "write_to_file" => ToolFamily::File,++ | "write_to_file"++ | "fs_read"++ | "fs_write" => ToolFamily::File,+ "read_file" | "write_file" | "patch" => ToolFamily::File,+ "search" | "grep" | "glob" | "find" | "list" | "ls" | "list_files" | "read_dir"+ | "list_dir" | "grep_search" | "search_files" => ToolFamily::SearchList,- "bash" | "shell" | "execute" | "run_command" | "web_search" | "terminal" => {- ToolFamily::NonFile- }++ "bash" | "shell" | "execute" | "run_command" | "web_search" | "terminal"++ | "execute_bash" | "execute_cmd" => ToolFamily::NonFile,_ => ToolFamily::Unknown,}}@@@ -627,28 -634,6 +651,21 @@@ fn extract_paths(name: &str, args: &Val}paths.extend(paths_in_entry);}+ }- // Kiro CLI's `fs_read` batches its targets as- // `{"operations":[{"mode":…,"path":…},…]}`; every operation must- // yield a path or the extraction is treated as malformed (which- // fails safe under an active policy).+ if name.eq_ignore_ascii_case("fs_read")+ && let Some(operations) = object.get("operations")+ {+ let entries = operations.as_array()?;- if entries.is_empty() {- return None;- }- if entries.len() > MAX_CAPTURE_CANDIDATES {++ if entries.is_empty() || entries.len() > MAX_CAPTURE_CANDIDATES {+ return None;+ }+ for entry in entries {+ let paths_in_entry = direct_paths(entry.as_object()?)?;+ if paths.len().checked_add(paths_in_entry.len())? > MAX_CAPTURE_CANDIDATES {+ return None;+ }+ paths.extend(paths_in_entry);+ }}(!paths.is_empty()&& paths.iter().all(|path| {diff --cc crates/ai-memory-store/migrations/V45__sessions_kiro_cli_agent_kind.sqlindex 00000000,00000000..8dca0e32new file mode 100644--- /dev/null+++ b/crates/ai-memory-store/migrations/V45__sessions_kiro_cli_agent_kind.sql@@@ -1,0 -1,0 +1,73 @@@++-- Expand sessions.agent_kind CHECK for AWS Kiro CLI.++--++-- Keep the complete V44 schema, indexes, and scope-pairing triggers while++-- adding the `kiro-cli` wire value.++++PRAGMA foreign_keys = OFF;++++DROP TRIGGER IF EXISTS auto_improve_scheduler_claims_session_pairing_ai;++DROP TRIGGER IF EXISTS session_consolidation_jobs_session_pairing_ai;++++CREATE TABLE sessions_new (++ id BLOB PRIMARY KEY NOT NULL,++ workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,++ project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,++ agent_kind TEXT NOT NULL CHECK (agent_kind IN ('claude-code','codex','open-code','cursor','gemini-cli','claude-desktop','openclaw','antigravity-cli','omp','pi','crush','grok','zero','devin','kimi-code','kiro-cli','hermes','other')),++ cwd TEXT,++ started_at INTEGER NOT NULL,++ ended_at INTEGER,++ summary_page_id BLOB REFERENCES pages(id) ON DELETE SET NULL,++ ended_observation_count INTEGER NOT NULL DEFAULT 0 CHECK (ended_observation_count >= 0),++ actor_user TEXT++);++++INSERT INTO sessions_new (++ id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at,++ summary_page_id, ended_observation_count, actor_user++)++SELECT++ id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at,++ summary_page_id, ended_observation_count, actor_user++FROM sessions;++++DROP TABLE sessions;++++ALTER TABLE sessions_new RENAME TO sessions;++++CREATE INDEX idx_sessions_recent ON sessions(workspace_id, project_id, started_at DESC);++CREATE INDEX idx_sessions_project ON sessions(project_id);++CREATE INDEX idx_sessions_started_at ON sessions(started_at DESC);++CREATE INDEX idx_sessions_scope_ended++ ON sessions(workspace_id, project_id, ended_at ASC)++ WHERE ended_at IS NOT NULL;++CREATE INDEX idx_sessions_open_owner++ ON sessions(workspace_id, project_id, agent_kind, actor_user)++ WHERE ended_at IS NULL;++++CREATE TRIGGER sessions_ws_proj_pairing_ai++BEFORE INSERT ON sessions++FOR EACH ROW++WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM projects WHERE id = NEW.project_id)++BEGIN++ SELECT RAISE(ABORT, 'sessions.workspace_id does not match the project''s workspace');++END;++++CREATE TRIGGER auto_improve_scheduler_claims_session_pairing_ai++BEFORE INSERT ON auto_improve_scheduler_claims++FOR EACH ROW++WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM sessions WHERE id = NEW.session_id)++ OR NEW.project_id IS NOT (SELECT project_id FROM sessions WHERE id = NEW.session_id)++BEGIN++ SELECT RAISE(ABORT, 'auto_improve_scheduler_claims scope does not match the session scope');++END;++++CREATE TRIGGER session_consolidation_jobs_session_pairing_ai++BEFORE INSERT ON session_consolidation_jobs++FOR EACH ROW++WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM sessions WHERE id = NEW.session_id)++ OR NEW.project_id IS NOT (SELECT project_id FROM sessions WHERE id = NEW.session_id)++BEGIN++ SELECT RAISE(ABORT, 'session_consolidation_jobs scope does not match the session scope');++END;++++PRAGMA foreign_keys = ON;diff --cc crates/ai-memory-store/src/migrations.rsindex be471589,58f0df8c..8e919ab2--- a/crates/ai-memory-store/src/migrations.rs+++ b/crates/ai-memory-store/src/migrations.rs@@@ -141,4 -238,354 +238,426 @@@ mod tests.unwrap();assert_eq!(state_table, 1);}++ #[test]+ fn v38_adds_scoped_entity_index_without_disturbing_existing_pages() {+ let mut conn = Connection::open_in_memory().unwrap();+ run_to(&mut conn, 37).unwrap();++ let ws1 = [1_u8; 16];+ let ws2 = [2_u8; 16];+ let proj1 = [3_u8; 16];+ let proj2 = [4_u8; 16];+ let page1 = [5_u8; 16];+ let page2 = [6_u8; 16];+ let hash = [0_u8; 32];+ for (workspace, name) in [(ws1, "one"), (ws2, "two")] {+ conn.execute(+ "INSERT INTO workspaces (id, name, created_at) VALUES (?1, ?2, 1)",+ params![workspace.as_slice(), name],+ )+ .unwrap();+ }+ for (project, workspace, name) in [(proj1, ws1, "project-one"), (proj2, ws2, "project-two")]+ {+ conn.execute(+ "INSERT INTO projects (id, workspace_id, name, created_at) \+ VALUES (?1, ?2, ?3, 1)",+ params![project.as_slice(), workspace.as_slice(), name],+ )+ .unwrap();+ }+ for (page, workspace, project, path) in+ [(page1, ws1, proj1, "one.md"), (page2, ws2, proj2, "two.md")]+ {+ conn.execute(+ "INSERT INTO pages \+ (id, workspace_id, project_id, path, title, tier, body, body_sha256, \+ frontmatter_json, is_latest, pinned, created_at, updated_at) \+ VALUES (?1, ?2, ?3, ?4, 'title', 'semantic', 'body', ?5, '{}', 1, 0, 1, 1)",+ params![+ page.as_slice(),+ workspace.as_slice(),+ project.as_slice(),+ path,+ hash.as_slice()+ ],+ )+ .unwrap();+ }++ run(&mut conn).unwrap();+ assert_eq!(schema_object_count(&conn, "table", "entities"), 1);+ assert_eq!(schema_object_count(&conn, "table", "entity_page_links"), 1);+ assert_eq!(+ schema_object_count(&conn, "trigger", "entities_ws_proj_pairing_ai"),+ 1+ );+ assert_eq!(+ schema_object_count(&conn, "trigger", "entity_page_links_scope_pairing_ai"),+ 1+ );+ assert_eq!(+ conn.query_row("SELECT COUNT(*) FROM pages", [], |row| row.get::<_, i64>(0))+ .unwrap(),+ 2,+ "V38 must preserve existing pages"+ );++ let entity1 = [7_u8; 16];+ conn.execute(+ "INSERT INTO entities (id, workspace_id, project_id, name, created_at) \+ VALUES (?1, ?2, ?3, 'sqlite', 1)",+ params![entity1.as_slice(), ws1.as_slice(), proj1.as_slice()],+ )+ .unwrap();+ conn.execute(+ "INSERT INTO entity_page_links (entity_id, page_id) VALUES (?1, ?2)",+ params![entity1.as_slice(), page1.as_slice()],+ )+ .unwrap();++ let wrong_scope = conn+ .execute(+ "INSERT INTO entities (id, workspace_id, project_id, name, created_at) \+ VALUES (?1, ?2, ?3, 'mismatch', 1)",+ params![[8_u8; 16].as_slice(), ws2.as_slice(), proj1.as_slice()],+ )+ .unwrap_err();+ assert!(+ wrong_scope+ .to_string()+ .contains("workspace/project mismatch")+ );+ let wrong_page = conn+ .execute(+ "INSERT INTO entity_page_links (entity_id, page_id) VALUES (?1, ?2)",+ params![entity1.as_slice(), page2.as_slice()],+ )+ .unwrap_err();+ assert!(+ wrong_page+ .to_string()+ .contains("entity/page scope mismatch")+ );+ assert!(+ conn.execute(+ "INSERT INTO entities (id, workspace_id, project_id, name, created_at) \+ VALUES (?1, ?2, ?3, ?4, 1)",+ params![+ [9_u8; 16].as_slice(),+ ws1.as_slice(),+ proj1.as_slice(),+ "x".repeat(65)+ ],+ )+ .is_err(),+ "the schema must enforce the public entity length bound"+ );+ }++ #[test]+ fn v33_to_v35_preserves_queue_and_backfills_end_generation() {+ let mut conn = Connection::open_in_memory().unwrap();+ run_to(&mut conn, 33).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();+ let workspace_id = crate::ops::get_or_create_workspace(&mut conn, "default").unwrap();+ let project_id =+ crate::ops::get_or_create_project(&mut conn, &workspace_id, "project", None).unwrap();+ let session_id = SessionId::new();+ // Era-appropriate raw insert. This fixture deliberately stops at V33+ // and then migrates forward, so it must not go through `begin_session`:+ // that writes whatever columns the CURRENT schema has, and every later+ // migration that adds one would break a test about an older era.+ conn.execute(+ "INSERT INTO sessions \+ (id, workspace_id, project_id, agent_kind, cwd, started_at) \+ VALUES (?1, ?2, ?3, ?4, NULL, ?5)",+ params![+ session_id.as_bytes(),+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ AgentKind::Codex.as_str(),+ jiff::Timestamp::now().as_microsecond(),+ ],+ )+ .unwrap();+ crate::ops::insert_observation(+ &mut conn,+ &NewObservation {+ session_id,+ workspace_id,+ project_id,+ kind: ObservationKind::UserPrompt,+ extension: None,+ source_event: None,+ title: "prompt".into(),+ body: "continue".into(),+ importance: 8,+ },+ )+ .unwrap();+ conn.execute(+ "UPDATE sessions SET ended_at = 1 WHERE id = ?1",+ params![session_id.as_bytes()],+ )+ .unwrap();++ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();+ run(&mut conn).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();+ assert_eq!(schema_object_count(&conn, "table", "sessions"), 1);+ assert_eq!(+ schema_object_count(&conn, "table", "session_consolidation_jobs"),+ 1+ );+ assert_eq!(+ schema_object_count(+ &conn,+ "trigger",+ "session_consolidation_jobs_session_pairing_ai"+ ),+ 1+ );+ let ended_observation_count: u64 = conn+ .query_row(+ "SELECT ended_observation_count FROM sessions WHERE id = ?1",+ params![session_id.as_bytes()],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(+ ended_observation_count, 1,+ "V35 must baseline existing ended sessions without catch-up work"+ );+ assert!(+ crate::session_consolidation::enqueue(&mut conn, workspace_id, project_id, session_id,)+ .unwrap()+ );+ }++ #[test]+ fn v39_to_v41_preserve_existing_rows_as_shared_and_add_listing_indexes() {+ let mut conn = Connection::open_in_memory().unwrap();+ run_to(&mut conn, 38).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();+ let workspace_id = crate::ops::get_or_create_workspace(&mut conn, "default").unwrap();+ let project_id =+ crate::ops::get_or_create_project(&mut conn, &workspace_id, "project", None).unwrap();+ let session_id = SessionId::new();+ let handoff_id = HandoffId::new();+ conn.execute(+ "INSERT INTO sessions \+ (id, workspace_id, project_id, agent_kind, cwd, started_at) \+ VALUES (?1, ?2, ?3, ?4, NULL, 1)",+ params![+ session_id.as_bytes(),+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ AgentKind::Codex.as_str(),+ ],+ )+ .unwrap();+ conn.execute(+ "INSERT INTO handoffs \+ (id, workspace_id, project_id, from_agent, summary, created_at) \+ VALUES (?1, ?2, ?3, ?4, ?5, 1)",+ params![+ handoff_id.as_bytes(),+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ AgentKind::Codex.as_str(),+ "legacy baton",+ ],+ )+ .unwrap();++ run(&mut conn).unwrap();++ let actor_user: Option<String> = conn+ .query_row(+ "SELECT actor_user FROM sessions WHERE id = ?1",+ params![session_id.as_bytes()],+ |row| row.get(0),+ )+ .unwrap();+ let (owner_user, accepted_by_user): (Option<String>, Option<String>) = conn+ .query_row(+ "SELECT owner_user, accepted_by_user FROM handoffs WHERE id = ?1",+ params![handoff_id.as_bytes()],+ |row| Ok((row.get(0)?, row.get(1)?)),+ )+ .unwrap();+ assert_eq!(actor_user, None, "legacy sessions remain shared");+ assert_eq!(owner_user, None, "legacy handoffs remain shared");+ assert_eq!(accepted_by_user, None);+ for index in [+ "idx_handoffs_open_owner",+ "idx_sessions_open_owner",+ "idx_handoffs_project_recent",+ "idx_handoffs_project_owner_recent",+ ] {+ assert_eq!(+ schema_object_count(&conn, "index", index),+ 1,+ "missing ownership/listing index {index}",+ );+ }+ }++ #[test]+ fn v43_to_v44_preserves_session_state_and_all_scope_guards() {+ let mut conn = Connection::open_in_memory().unwrap();+ run_to(&mut conn, 43).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();+ let workspace_id = crate::ops::get_or_create_workspace(&mut conn, "default").unwrap();+ let project_id =+ crate::ops::get_or_create_project(&mut conn, &workspace_id, "project", None).unwrap();+ let existing = SessionId::new();+ conn.execute(+ "INSERT INTO sessions \+ (id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at, \+ ended_observation_count, actor_user) \+ VALUES (?1, ?2, ?3, 'codex', '/repo', 1, 2, 7, 'user:alice')",+ params![+ existing.as_bytes(),+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ ],+ )+ .unwrap();++ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();+ run(&mut conn).unwrap();+ conn.pragma_update(None, "foreign_keys", "ON").unwrap();++ let preserved: (String, String, i64, Option<String>) = conn+ .query_row(+ "SELECT agent_kind, cwd, ended_observation_count, actor_user \+ FROM sessions WHERE id = ?1",+ params![existing.as_bytes()],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),+ )+ .unwrap();+ assert_eq!(+ preserved,+ ("codex".into(), "/repo".into(), 7, Some("user:alice".into()))+ );++ for index in [+ "idx_sessions_recent",+ "idx_sessions_project",+ "idx_sessions_started_at",+ "idx_sessions_scope_ended",+ "idx_sessions_open_owner",+ ] {+ assert_eq!(+ schema_object_count(&conn, "index", index),+ 1,+ "V44 dropped session index {index}"+ );+ }+ for trigger in [+ "sessions_ws_proj_pairing_ai",+ "auto_improve_scheduler_claims_session_pairing_ai",+ "session_consolidation_jobs_session_pairing_ai",+ ] {+ assert_eq!(+ schema_object_count(&conn, "trigger", trigger),+ 1,+ "V44 dropped scope guard {trigger}"+ );+ }+ let foreign_key_errors: i64 = conn+ .query_row("SELECT COUNT(*) FROM pragma_foreign_key_check", [], |row| {+ row.get(0)+ })+ .unwrap();+ assert_eq!(foreign_key_errors, 0);++ crate::ops::begin_session(+ &mut conn,+ &NewSession {+ id: SessionId::new(),+ workspace_id,+ project_id,+ agent_kind: AgentKind::Hermes,+ cwd: Some("/repo".into()),+ actor_user: Some("user:alice".into()),+ },+ )+ .unwrap();+ }++++ #[test]++ fn v44_to_v45_preserves_session_state_and_accepts_kiro_cli() {++ let mut conn = Connection::open_in_memory().unwrap();++ run_to(&mut conn, 44).unwrap();++ conn.pragma_update(None, "foreign_keys", "ON").unwrap();++ let workspace_id = crate::ops::get_or_create_workspace(&mut conn, "default").unwrap();++ let project_id =++ crate::ops::get_or_create_project(&mut conn, &workspace_id, "project", None).unwrap();++ let existing = SessionId::new();++ conn.execute(++ "INSERT INTO sessions \++ (id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at, \++ ended_observation_count, actor_user) \++ VALUES (?1, ?2, ?3, 'hermes', '/repo', 1, 2, 7, 'user:alice')",++ params![++ existing.as_bytes(),++ workspace_id.as_bytes(),++ project_id.as_bytes(),++ ],++ )++ .unwrap();++++ conn.pragma_update(None, "foreign_keys", "OFF").unwrap();++ run(&mut conn).unwrap();++ conn.pragma_update(None, "foreign_keys", "ON").unwrap();++++ let preserved: (String, String, i64, Option<String>) = conn++ .query_row(++ "SELECT agent_kind, cwd, ended_observation_count, actor_user \++ FROM sessions WHERE id = ?1",++ params![existing.as_bytes()],++ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),++ )++ .unwrap();++ assert_eq!(++ preserved,++ (++ "hermes".into(),++ "/repo".into(),++ 7,++ Some("user:alice".into())++ )++ );++++ crate::ops::begin_session(++ &mut conn,++ &NewSession {++ id: SessionId::new(),++ workspace_id,++ project_id,++ agent_kind: AgentKind::KiroCli,++ cwd: Some("/repo".into()),++ actor_user: Some("user:alice".into()),++ },++ )++ .unwrap();++++ for name in [++ "idx_sessions_open_owner",++ "sessions_ws_proj_pairing_ai",++ "auto_improve_scheduler_claims_session_pairing_ai",++ "session_consolidation_jobs_session_pairing_ai",++ ] {++ let kind = if name.starts_with("idx_") {++ "index"++ } else {++ "trigger"++ };++ assert_eq!(schema_object_count(&conn, kind, name), 1, "missing {name}");++ }++ }}diff --cc docs/install.mdindex 8762aa06,cfc979c7..ac4e5483--- a/docs/install.md+++ b/docs/install.md@@@ -560,9 -599,9 +599,9 @@@ Each agent CLI needs two thingsWithout this, the agent can still query memory but capturebecomes manual.- Claude Desktop and VS Code Copilot are MCP-only today. The hook-capable clients- in the [README Support Matrix](../README.md#support-matrix), including Pi and- Zero, have lifecycle capture paths through `install-hooks`.-Claude Desktop, Kiro CLI, VS Code Copilot, and Zed are MCP-only today. The++Claude Desktop, VS Code Copilot, and Zed are MCP-only today. The+ hook-capable clients in the [README Support Matrix](../README.md#support-matrix),+ including Pi and Zero, have lifecycle capture paths through `install-hooks`.> **Hook install pattern.** Local supported profiles default to host-native> commands. Claude Code may use its supported Windows exec form (`command` =@@@ -683,88 -737,30 +737,65 @@@ Kimi Code hook entries accept only `eve### Kiro CLI- The AWS Kiro CLI ships two agent engines in one binary — the default v2- engine and the early-access v3 engine (`kiro-cli chat --agent-engine v3`,- alias `--v3`) — and their hook surfaces are **not compatible**: v2 embeds- camelCase hook entries inside agent configs, while v3 reads standalone- versioned hooks files with PascalCase triggers. ai-memory never guesses- which engine you use; each surface is installed by its own explicit agent- selection, and installing both is safe (each engine ignores the other's- surface). Both honor `$KIRO_HOME` (default `~/.kiro`) and stage the same- `hooks/kiro-cli/` script bundle. Contracts verified against kiro-cli- 2.16.0 and the official hook references- ([v2](https://kiro.dev/docs/cli/hooks/), [v3](https://kiro.dev/docs/cli/v3/hooks/)).-- **v2 engine (default)** — hooks live inside each agent config- (`~/.kiro/agents/*.json`); there is no global v2 hook surface, and the- built-in default agent has no file on disk. Create an agent config first- if you have none (`kiro-cli agent create`, then- `kiro-cli agent set-default <name>`):-Kiro CLI is MCP-only in this release. Its global MCP file is-`$KIRO_HOME/settings/mcp.json`, defaulting to `~/.kiro/settings/mcp.json`;-pass `--config-file .kiro/settings/mcp.json` for a project-scoped entry.++Kiro CLI has one MCP surface. ai-memory supports the documented v2 lifecycle++hook surface; Kiro v3 uses an incompatible standalone registration format and++does not document the command-input payload yet. The global MCP file is++`$KIRO_HOME/settings/mcp.json`, defaulting to++`~/.kiro/settings/mcp.json`; pass `--config-file .kiro/settings/mcp.json` for a++project-scoped entry.```bash- ai-memory install-hooks --agent kiro-cli --apply \- --server-url "http://homelab:49374" \+ ai-memory install-mcp --client kiro-cli --apply \+ --server-url "https://memory.example/mcp" \--auth-token "$TOKEN"```- This merges five flat entries — `agentSpawn`, `userPromptSubmit`,- `preToolUse`, `postToolUse`, `stop` — into **every** existing agent config- (or only the one passed via `--config-file`), preserving third-party- entries under the same triggers. Entries deliberately carry no `matcher`- key: in Kiro v2 an absent matcher applies the hook to every tool, while an- empty-string matcher matches nothing. The `agentSpawn` entry raises- `max_output_size` to 64 KiB so an injected handoff + project brief is not- truncated. A pending handoff is injected at `agentSpawn` through the- hook's exit-0 stdout, which the v2 engine adds to the agent context.+ The `kiro` alias is equivalent. The installed URL includes+ `?flavor=bedrock` so Kiro's Bedrock backend receives schemas without+ root-level `anyOf`, `oneOf`, or `allOf`; nested schemas and runtime validation+ remain intact. Kiro requires HTTPS for non-loopback remote servers, so the CLI+ rejects a plain-HTTP homelab URL before changing the file. Configure a reverse+ proxy as described in [HTTPS via reverse proxy](https-via-proxy.md).- **v3 engine (early access)** — hooks are standalone files; global ones- under `~/.kiro/hooks/` fire in every workspace:-Kiro v2 and the early-access v3 engine use incompatible hook and persisted-session formats. `install-hooks --agent kiro-cli` and `ai-memory run kiro` are-therefore deferred until both formats have fixtures and explicit compatibility-tests; this MCP registration does not claim automatic capture or managed-resume. Follow [#355](https://github.com/akitaonrails/ai-memory/issues/355) for-hooks and [#356](https://github.com/akitaonrails/ai-memory/issues/356) for the-managed-workstream adapter.++Install v2 hooks with the `kiro-cli` agent value. When `--server-url` is omitted,++`install-hooks` can infer the hook origin and bearer token from the managed MCP++entry above.++```bash- ai-memory install-hooks --agent kiro-cli-v3 --apply \- --server-url "http://homelab:49374" \- --auth-token "$TOKEN"- ```++# Default v2 engine: merge hooks into every existing global agent config.++ai-memory install-hooks --agent kiro-cli --apply+- This writes `~/.kiro/hooks/ai-memory.json` (`{"version":"v1","hooks":[…]}`)- with five command actions — `SessionStart`, `UserPromptSubmit`,- `PreToolUse`, `PostToolUse`, `Stop` — and a 10-second timeout each (v3- timeouts are seconds; v2 uses `timeout_ms`). Other `*.json` files in the- hooks directory are never touched, and non-ai-memory entries inside- `ai-memory.json` survive re-applies and uninstall. A pending handoff is- injected at `SessionStart` through the hook's exit-0 stdout, which the v3- engine adds to the agent context. The v3 stdin payload field names are not- publicly documented yet; capture forwards the raw event JSON, and- tool-payload extraction (for `[capture] ignore_paths` enforcement) is- verified on the v2 payload shape (`tool_name`/`tool_input`).-- On both engines the hooks are fail-open by contract: they always exit 0- and print nothing on capture paths (exit code 2 would block the tool call- on `preToolUse`/`PreToolUse`, and stray stdout would leak into the agent- context on session-start/user-prompt events), so a stopped ai-memory- server never breaks a Kiro session.-- **MCP** — the installer does not manage Kiro's MCP config yet. Add the- server manually to `~/.kiro/settings/mcp.json`, using the `bedrock`- schema flavor: Kiro talks to Amazon Bedrock's Converse API, which rejects- root-level `anyOf`/`oneOf`/`allOf` in tool schemas, and the flavored URL- serves the same tools with flattened root schemas:-- ```json- {- "mcpServers": {- "ai-memory": {- "url": "http://homelab:49374/mcp?flavor=bedrock",- "headers": { "Authorization": "Bearer YOUR_TOKEN" }- }- }- }++# A project-local v2 agent overrides a same-named global agent. Update the++# selected local config explicitly instead of assuming the global copy runs.++ai-memory install-hooks --agent kiro-cli --apply \++ --config-file .kiro/agents/<agent-name>.json+```+- Sessions launched with `--v3` cannot be resumed by the v2 engine (and- vice versa) — the resume hint Kiro prints at session end needs `--v3`- added manually. Managed `ai-memory run kiro` support is tracked- separately (upstream issue #356).++The v2 engine stores camelCase hooks inside agent JSON files. ai-memory updates++existing `$KIRO_HOME/agents/*.json` files only; it will not fabricate an agent++that Kiro never selects. Create and select an agent first when that directory++is empty. Kiro gives [project-local agents precedence over global agents](https://kiro.dev/docs/cli/custom-agents/configuration-reference/),++so use `--config-file` when the active definition lives under++`.kiro/agents/`. All target files are parsed before any one is changed, and++unrelated agent fields, third-party hooks, and each agent's existing++`--project-strategy` remain intact.++++The install registers spawn, user-prompt, pre-tool, post-tool, and stop capture,++remains fail-open when ai-memory is unavailable, and delivers a pending handoff++through successful `agentSpawn` stdout. Verified v2 tool payloads enforce++`[capture] ignore_paths`; an unrecognized payload shape is stored as bounded++metadata rather than exposing file content.++++Kiro v3 hook capture is intentionally not advertised or installed. Its++[migration guide](https://kiro.dev/docs/cli/v3/hooks-migration/) documents the++standalone registration schema but not the JSON sent to command hooks. Supporting++it without that contract would risk silently losing capture and exclusion++semantics. Add v3 only after real payload fixtures can exercise that boundary.++++`ai-memory uninstall --only hooks --apply --yes` removes only exact ai-memory v2++entries from global agents and the current project's `.kiro/agents` directory;++it leaves standalone v3 files untouched. Managed `ai-memory run kiro` support++is tracked separately in [#356](https://github.com/akitaonrails/ai-memory/issues/356).### OpenCode@@@ -904,20 -900,28 +935,32 @@@ docker run --rm akitaonrails/ai-memory:install-hooks --agent openclaw --auth-token "$TOKEN" \--server-url "http://homelab:49374"+ docker run --rm akitaonrails/ai-memory:latest \+ install-mcp --client kiro-cli --auth-token "$TOKEN" \+ --server-url "https://memory.example/mcp"+++docker run --rm akitaonrails/ai-memory:latest \++ install-hooks --agent kiro-cli --auth-token "$TOKEN" \++ --server-url "https://memory.example"++docker run --rm akitaonrails/ai-memory:latest \install-mcp --client vscode-copilot --auth-token "$TOKEN" \--server-url "http://homelab:49374/mcp"++ docker run --rm akitaonrails/ai-memory:latest \+ install-mcp --client zed --auth-token "$TOKEN" \+ --server-url "http://homelab:49374/mcp"```--Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, and OpenClaw support both++Cursor, Gemini CLI, Antigravity CLI, Grok Build CLI, Kiro CLI, and OpenClaw support both`install-mcp` and `install-hooks`. Grok's `install-mcp --client grok` writes`$GROK_HOME/config.toml` (default `~/.grok/config.toml`); its hooks live under`$GROK_HOME/hooks` (default `~/.grok/hooks`). `install-hooks --agent grok`captures lifecycle events.Grok ignores `SessionStart` stdout, so handoffs must be accepted through MCP with- `memory_handoff_accept` when resuming. Claude Desktop and VS Code Copilot are MCP-only here,- so you'll need to nudge the model to call `memory_query` /- `memory_handoff_accept` itself.-`memory_handoff_accept` when resuming. Claude Desktop, Kiro CLI, VS Code-Copilot, and Zed are MCP-only here, so you'll need to nudge the model to call++`memory_handoff_accept` when resuming. Claude Desktop, VS Code Copilot, and Zed++are MCP-only here, so you'll need to nudge the model to call+ `memory_query` / `memory_handoff_accept` itself.For clients with `install-hooks` support, the capture path handleshandoff injection at session start or the client's closest equivalent, exceptfor Grok's (and Zero's) no-stdout SessionStart behavior (Antigravity CLI uses `PreInvocation`).diff --cc docs/mcp-install.mdindex 15e8fa50,f4c4a95b..756f3431--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@@ -38,8 -38,8 +38,8 @@@ ignore_paths`; legacy shell/PowerShellnot. Reinstall/refresh an existing hook or plugin to gain it; see[Capture exclusions](marker-file.md#capture-exclusions).- Claude Desktop and VS Code Copilot are **MCP-only** here: they expose- long-term memory to their LLMs via ai-memory's MCP tools-Claude Desktop, Kiro CLI, VS Code Copilot, and Zed are **MCP-only** here: they++Claude Desktop, VS Code Copilot, and Zed are **MCP-only** here: they+ expose long-term memory to their LLMs via ai-memory's MCP tools(`memory_query`, `memory_recent`, `memory_handoff_accept`, etc.), butthey do not auto-capture session events into ai-memory's `/hook`endpoint. The trade-off:@@@ -662,6 -793,57 +793,71 @@@ same pattern as Gemini CLIbut are mutually exclusive event triggers, so successful and failed callsare both captured once.+ ## Kiro CLI+-**Status:** MCP supported. Lifecycle hooks and managed workstreams are not yet-supported.++**Status:** MCP and v2 lifecycle hooks supported. Managed workstreams are++tracked separately.++ **Config file:** `$KIRO_HOME/settings/mcp.json`, defaulting to+ `~/.kiro/settings/mcp.json`. Use `--config-file .kiro/settings/mcp.json` when+ you intentionally want Kiro's lower-scope project configuration instead.++ ```bash+ ai-memory install-mcp --client kiro-cli --apply \+ --server-url "https://memory.example/mcp" --auth-token "$TOKEN"+ ```++ The `kiro` alias is equivalent. The command preserves unrelated settings and+ servers, and merges this entry idempotently:++ ```json+ {+ "mcpServers": {+ "ai-memory": {+ "url": "https://memory.example/mcp?flavor=bedrock",+ "headers": { "Authorization": "Bearer <token>" }+ }+ }+ }+ ```++ Kiro sends MCP tool schemas through Amazon Bedrock, which rejects root-level+ `anyOf`, `oneOf`, and `allOf`. The installer appends `?flavor=bedrock`; the+ server strips only those root combinators for that request while preserving+ nested schemas and the handlers' runtime validation. Kimi Code's existing+ `?flavor=moonshot` behavior remains supported independently.++ Kiro permits remote MCP URLs over HTTPS. Plain HTTP is accepted only for+ `localhost`, `127.0.0.1`, or another loopback address; `install-mcp` rejects a+ non-loopback HTTP URL before writing the config. See+ [HTTPS via reverse proxy](https-via-proxy.md) for a homelab deployment.+-Kiro CLI v3 changes both its hook schema and its persisted session format from-v2. Until each version has fixtures and an explicit compatibility contract,-`install-hooks --agent kiro-cli` and `ai-memory run kiro` are intentionally not-advertised or accepted. Follow-[#355](https://github.com/akitaonrails/ai-memory/issues/355) for hooks and++ai-memory supports Kiro's documented v2 hook registration format:++++```bash++# v2: update every existing global agent definition.++ai-memory install-hooks --agent kiro-cli --apply++++# v2 project-local agent: target the active definition explicitly.++ai-memory install-hooks --agent kiro-cli --apply \++ --config-file .kiro/agents/<agent-name>.json++```++++The v2 installer refuses to create a synthetic agent file and parses every++target before changing any of them. Project-local Kiro agents override global++agents, so `--config-file` is required when the active definition lives under++`.kiro/agents/`. The integration remains fail-open, injects pending handoffs++through `agentSpawn` stdout, and honors `$KIRO_HOME`. Kiro v3 hook capture is++not installed because its registration migration guide does not document the++command-input payload needed to validate capture and exclusion behavior. Follow+ [#356](https://github.com/akitaonrails/ai-memory/issues/356) for managed+ workstreams.++ Sources: <https://kiro.dev/docs/cli/mcp/configuration/>,+ <https://kiro.dev/docs/cli/reference/settings/>,-<https://kiro.dev/docs/cli/v3/>.++<https://kiro.dev/docs/cli/hooks/>, and++<https://kiro.dev/docs/cli/v3/hooks-migration/>.+## OpenClaw**Status:** ✅ MCP supported. ✅ Lifecycle hooks supported via a nativediff --cc docs/usage.mdindex e78823d8,eacae8b7..f3d45fa3--- a/docs/usage.md+++ b/docs/usage.md@@@ -211,14 -304,11 +304,14 @@@ Client cleanup hints- Kimi Code: check `~/.kimi-code/mcp.json` and the `[[hooks]]` entries in`~/.kimi-code/config.toml` (both under `$KIMI_CODE_HOME` when set) for staleMCP or hook entries.+- Kiro CLI: check the `hooks` objects inside `~/.kiro/agents/*.json` (v2- engine), the `~/.kiro/hooks/ai-memory.json` file (v3 engine), and- `~/.kiro/settings/mcp.json` (all under `$KIRO_HOME` when set) for stale- entries.++ engine) and `~/.kiro/settings/mcp.json` (both under `$KIRO_HOME` when set)++ for stale ai-memory entries. ai-memory does not install Kiro v3 hook files.- OpenCode, OpenClaw, and OMP: check MCP config and plugin/extension directories;move old memory plugins to a disabled/quarantine directory before deleting.- - VS Code Copilot and Claude Desktop: these are usually MCP-only, so confirm- whether the old tool was providing capture hooks elsewhere.+ - VS Code Copilot, Claude Desktop, and Zed: these are MCP-only, so confirm+ whether the old tool was providing capture hooks elsewhere. Zed's MCP+ entries live under `context_servers` in its user `settings.json`.If you want a visible startup reminder during the transition, keep it small. Arules-file note such as “Active memory: ai-memory; legacy export is historicaldiff --cc docs/windows.mdindex 7061809a,cd05d84f..aca5c7f3--- a/docs/windows.md+++ b/docs/windows.md@@@ -6,8 -6,8 +6,8 @@@ agent CLI actually runs## Rule Of ThumbRun `install-mcp` and `install-hooks` from the same environment that--launches Claude Code, Codex, Devin CLI, Cursor, Gemini CLI, Kimi Code,- Kiro CLI, or another agent.++launches Claude Code, Codex, Devin CLI, Cursor, Gemini CLI, Kimi Code, Kiro CLI,+ Antigravity CLI, or another agent.- If the agent runs inside WSL2, install ai-memory inside WSL2.- If the agent runs as a native Windows process, install ai-memory from@@@ -121,8 -143,7 +143,7 @@@ for each native Windows agent so existicommand form.Use the matching `--client` / `--agent` values for other clients, for- example `codex`, `devin`, `kimi-code`, `kiro-cli` (or `kiro-cli-v3` for- the v3 engine's hooks file), `cursor`, or `gemini-cli`.-example `codex`, `devin`, `kimi-code`, `cursor`, or `gemini-cli`.++example `codex`, `devin`, `kimi-code`, `kiro-cli`, `cursor`, or `gemini-cli`.For Devin, `install-mcp --client devin --apply` writes MCP config to`%USERPROFILE%\.devin\config.json`. `install-hooks --agent devin --apply`@@@ -130,6 -151,6 +151,14 @@@ writes lifecycle hooks to `%USERPROFILEpass `--config-file "%USERPROFILE%\.devin\config.json"` if you want hooks underthe `hooks` key in Devin's main config file.++For Kiro CLI, `install-mcp --client kiro-cli --apply` writes++`%USERPROFILE%\.kiro\settings\mcp.json` unless `$env:KIRO_HOME` overrides the++root. `install-hooks --agent kiro-cli --apply` updates existing v2 agent files++under `.kiro\agents`; use `--config-file` for a project-local agent. Kiro v3++hook capture remains unsupported until its command-input payload is documented.++Run these commands from the same native Windows environment that launches Kiro++so generated executable paths remain valid.++## Scenario C: Prebuilt Release Binary (No Toolchain)Use this when the agent CLI runs as a native Windows process and you wantdiff --cc hooks/kiro-cli/post-tool-use.ps1index c317ee09,00000000..fe2a9b0emode 100644,000000..100644--- a/hooks/kiro-cli/post-tool-use.ps1+++ b/hooks/kiro-cli/post-tool-use.ps1@@@ -1,4 -1,0 +1,4 @@@- # Kiro CLI post-tool-use hook (v2: postToolUse; v3: PostToolUse).++# Kiro CLI v2 post-tool-use hook (postToolUse).+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "post-tool-use" -Agent "kiro-cli"+exit 0diff --cc hooks/kiro-cli/post-tool-use.shindex 71037cde,00000000..b3fd56d4mode 100755,000000..100755--- a/hooks/kiro-cli/post-tool-use.sh+++ b/hooks/kiro-cli/post-tool-use.sh@@@ -1,15 -1,0 +1,15 @@@+#!/bin/sh- # Kiro CLI post-tool-use hook (v2: postToolUse; v3: PostToolUse).++# Kiro CLI v2 post-tool-use hook (postToolUse).+# Forwards the event JSON to the ai-memory server, fire-and-forget.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_extract_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=post-tool-use&agent=kiro-cli${QS}" >/dev/null 2>&1 || true+exit 0diff --cc hooks/kiro-cli/pre-tool-use.ps1index 54e70068,00000000..8784202fmode 100644,000000..100644--- a/hooks/kiro-cli/pre-tool-use.ps1+++ b/hooks/kiro-cli/pre-tool-use.ps1@@@ -1,6 -1,0 +1,6 @@@- # Kiro CLI pre-tool-use hook (v2: preToolUse; v3: PreToolUse).++# Kiro CLI v2 pre-tool-use hook (preToolUse).+# Fail-open by contract: exit 0 unconditionally and print nothing —- # exit code 2 would block the tool call on both engines.++# exit code 2 would block the tool call.+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "pre-tool-use" -Agent "kiro-cli"+exit 0diff --cc hooks/kiro-cli/pre-tool-use.shindex 10f378db,00000000..33ca240emode 100755,000000..100755--- a/hooks/kiro-cli/pre-tool-use.sh+++ b/hooks/kiro-cli/pre-tool-use.sh@@@ -1,18 -1,0 +1,18 @@@+#!/bin/sh- # Kiro CLI pre-tool-use hook (v2: preToolUse; v3: PreToolUse).++# Kiro CLI v2 pre-tool-use hook (preToolUse).+# Forwards the event JSON to the ai-memory server, fire-and-forget.+# Fail-open by contract: exit 0 unconditionally and print nothing.- # Exit code 2 would BLOCK the tool call on both engines, so a capture++# Exit code 2 would BLOCK the tool call, so a capture+# hook must never let a server error surface as a non-zero exit.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_extract_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=pre-tool-use&agent=kiro-cli${QS}" >/dev/null 2>&1 || true+exit 0diff --cc hooks/kiro-cli/session-start.ps1index 15f70f76,00000000..9ae5eae5mode 100644,000000..100644--- a/hooks/kiro-cli/session-start.ps1+++ b/hooks/kiro-cli/session-start.ps1@@@ -1,8 -1,0 +1,8 @@@- # Kiro CLI session-start hook (v2 engine: agentSpawn; v3: SessionStart).- # Both Kiro engines add this hook's exit-0 stdout to the agent context,++# Kiro CLI v2 session-start hook (agentSpawn).++# Kiro adds this hook's exit-0 stdout to the agent context,+# so the pending handoff is fetched and printed raw here (no envelope —+# Kiro documents none). The compiled project brief rides the same fetch+# once per session.+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "session-start" -Agent "kiro-cli" -FetchHandoff -BriefingOncePerSession+exit 0diff --cc hooks/kiro-cli/session-start.shindex e0a31a16,00000000..a31b6b3bmode 100755,000000..100755--- a/hooks/kiro-cli/session-start.sh+++ b/hooks/kiro-cli/session-start.sh@@@ -1,48 -1,0 +1,47 @@@+#!/bin/sh- # Kiro CLI session-start hook (v2 engine: agentSpawn; v3 engine: SessionStart).++# Kiro CLI v2 session-start hook (agentSpawn).+# 1. Forwards the event JSON to the ai-memory server (fire-and-forget).+# 2. Synchronously fetches any pending cross-agent handoff and prints the- # raw body to stdout — both Kiro engines add this hook's exit-0 stdout- # to the agent context (v2 per kiro.dev/docs/cli/hooks, v3 per- # kiro.dev/docs/cli/v3/hooks), so the resuming agent sees prior context- # with no human in the loop. Kiro documents no JSON envelope for hook++# raw body to stdout. Kiro v2 adds this hook's exit-0 stdout to the agent++# context, so the resuming agent sees prior context with no human in the++# loop. Kiro documents no JSON envelope for hook+# stdout, so print the raw handoff body or nothing at all.+# 3. Delivers the compiled project brief ([briefing]+# inject_on_session_start) once per session, gated by a marker file+# keyed on Kiro's native session id when the payload carries one.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_extract_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")+SESSION_ID=$(ai_memory_extract_session_id "$PAYLOAD")+SESSION_QS=""+[ -n "$SESSION_ID" ] && SESSION_QS="&session_id=$(ai_memory_url_encode "$SESSION_ID")"++# Once-per-session briefing gate. Marker files are created only when the+# repository opted in. Prefer Kiro's native session id when supplied;+# otherwise use a stable hash of agent+cwd.+BRIEF_QS=$(ai_memory_briefing_qs "$CWD")+BRIEF_FILE=""+if [ -n "$BRIEF_QS" ]; then+ BRIEF_KEY="$SESSION_ID"+ if [ -z "$BRIEF_KEY" ]; then+ BRIEF_KEY="kiro-cli-$(printf '%s' "kiro-cli:$CWD" | cksum | awk '{print $1}')"+ fi+ BRIEF_FILE=$(ai_memory_briefed_file "$BRIEF_KEY")+ [ -f "$BRIEF_FILE" ] && BRIEF_QS=""+fi++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=session-start&agent=kiro-cli${QS}" >/dev/null 2>&1 || true++HANDOFF=$(ai_memory_get_handoff "$SERVER/handoff?agent=kiro-cli${QS}${SESSION_QS}${BRIEF_QS}" 2>/dev/null || true)+# Mark an opted-in session as briefed only AFTER the GET completed — success+# or error. Fail-open on purpose: with the server down the flagged request+# delivers nothing anyway, and the one lost brief returns next session.+[ -n "$BRIEF_FILE" ] && ai_memory_mark_briefed "$BRIEF_FILE"+[ -n "$HANDOFF" ] && printf '%s\n' "$HANDOFF"+exit 0diff --cc hooks/kiro-cli/stop.ps1index c98626fa,00000000..407135a8mode 100644,000000..100644--- a/hooks/kiro-cli/stop.ps1+++ b/hooks/kiro-cli/stop.ps1@@@ -1,7 -1,0 +1,7 @@@- # Kiro CLI stop hook (v2: stop; v3: Stop).++# Kiro CLI v2 stop hook (stop).+# Print nothing: on the v2 engine a stop hook's stdout can carry a+# {"decision":"block"} verdict that would re-prompt the model, so a+# capture-only hook keeps stdout empty and exits 0.+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "stop" -Agent "kiro-cli"+exit 0diff --cc hooks/kiro-cli/stop.shindex 382e9974,00000000..65b1b6fbmode 100755,000000..100755--- a/hooks/kiro-cli/stop.sh+++ b/hooks/kiro-cli/stop.sh@@@ -1,18 -1,0 +1,18 @@@+#!/bin/sh- # Kiro CLI stop hook (v2: stop; v3: Stop).++# Kiro CLI v2 stop hook (stop).+# Forwards the event JSON to the ai-memory server, fire-and-forget.+# Print nothing: on the v2 engine a stop hook's stdout can carry a+# {"decision":"block"} verdict that would re-prompt the model, so a+# capture-only hook must keep stdout empty and exit 0.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_extract_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=stop&agent=kiro-cli${QS}" >/dev/null 2>&1 || true+exit 0diff --cc hooks/kiro-cli/user-prompt-submit.ps1index b8e1553e,00000000..e4ea97cdmode 100644,000000..100644--- a/hooks/kiro-cli/user-prompt-submit.ps1+++ b/hooks/kiro-cli/user-prompt-submit.ps1@@@ -1,6 -1,0 +1,6 @@@- # Kiro CLI user-prompt hook (v2: userPromptSubmit; v3: UserPromptSubmit).++# Kiro CLI v2 user-prompt hook (userPromptSubmit).+# Capture only — the handoff is injected by session-start.ps1. Print+# nothing: exit-0 stdout would be added to the conversation context.+. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"+Invoke-AiMemoryHook -Event "user-prompt" -Agent "kiro-cli"+exit 0diff --cc hooks/kiro-cli/user-prompt-submit.shindex 2877d3d9,00000000..a363bdbamode 100755,000000..100755--- a/hooks/kiro-cli/user-prompt-submit.sh+++ b/hooks/kiro-cli/user-prompt-submit.sh@@@ -1,18 -1,0 +1,18 @@@+#!/bin/sh- # Kiro CLI user-prompt hook (v2: userPromptSubmit; v3: UserPromptSubmit).++# Kiro CLI v2 user-prompt hook (userPromptSubmit).+# Forwards the event JSON to the ai-memory server, fire-and-forget. The- # handoff is injected by session-start.sh — both Kiro engines add that++# handoff is injected by session-start.sh — Kiro v2 adds that+# hook's stdout to the agent context, so this hook only captures. Print+# nothing: exit-0 stdout would be added to the conversation context.+_lib_dir="$(dirname "$0")"+[ -f "$_lib_dir/_lib.sh" ] || _lib_dir="$_lib_dir/.."+. "$_lib_dir/_lib.sh"++SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"+PAYLOAD=$(cat)+CWD=$(ai_memory_extract_cwd "$PAYLOAD")+QS=$(ai_memory_marker_qs "$CWD")++printf '%s' "$PAYLOAD" \+ | ai_memory_post_hook "$SERVER/hook?event=user-prompt&agent=kiro-cli${QS}" >/dev/null 2>&1 || true+exit 0diff --cc scripts/install-hooks.shindex e86f9c62,890027f5..69e2ddee--- a/scripts/install-hooks.sh+++ b/scripts/install-hooks.sh@@@ -2,15 -2,14 +2,14 @@@# Curl-based installer for ai-memory's lifecycle-hook scripts.## Use when you don't want to clone the repo and don't want to use the- # docker image to extract the bundle. Pulls each hook script for the- # requested agent straight from the published GitHub raw URL.+ # docker image to extract the bundle. Downloads a checksum-verified hook+ # archive from a GitHub Release, then installs only the requested agent files.## Usage:- # curl -sSL https://raw.githubusercontent.com/akitaonrails/ai-memory/main/scripts/install-hooks.sh \- # | bash -s -- --agent claude-code+ # ai-memory-install-hooks --agent claude-code## Options:-# --agent <claude-code|codex|cursor|gemini-cli|kimi-code|antigravity-cli|grok|opencode|openclaw|omp|oh-my-pi|pi>+# --agent <claude-code|codex|cursor|gemini-cli|kimi-code|kiro-cli|antigravity-cli|grok|opencode|openclaw|omp|oh-my-pi|pi># which agent (default: claude-code;# generated-plugin agents print hints)# --to <dir> install root (default: $HOME/.ai-memory/hooks)@@@ -46,11 -46,9 +46,10 @@@ while [[ $# -gt 0 ]]; ddonecase "$AGENT" in- claude-code|codex|cursor|gemini-cli|kimi-code|antigravity-cli|grok|opencode|openclaw|omp|pi|oh-my-pi) ;;+ claude-code|codex|cursor|gemini-cli|kimi-code|kiro-cli|antigravity-cli|grok|opencode|openclaw|omp|pi|oh-my-pi) ;;- # Both Kiro engine selections stage the same hooks/kiro-cli bundle.- kiro|kiro-cli-v3|kiro-v3) AGENT="kiro-cli" ;;++ kiro) AGENT="kiro-cli" ;;*)- echo "unsupported agent: $AGENT (expected claude-code | codex | cursor | gemini-cli | kimi-code | antigravity-cli | grok | opencode | openclaw | omp | pi | oh-my-pi)" >&2+ echo "unsupported agent: $AGENT (expected claude-code | codex | cursor | gemini-cli | kimi-code | kiro-cli | antigravity-cli | grok | opencode | openclaw | omp | pi | oh-my-pi)" >&2exit 64 ;;esac@@@ -99,19 -106,6 +107,19 @@@ if [[ "$AGENT" == "kimi-code" ]]; theSCRIPTS+=("subagent-start" "subagent-stop")fi- # kiro-cli's hook vocabulary is exactly five events on both engines —++# kiro-cli v2's hook vocabulary is exactly five events —+# no pre-compact/session-end equivalents exist, so fetching them would+# 404 and abort the install.+if [[ "$AGENT" == "kiro-cli" ]]; then+ SCRIPTS=(+ "session-start"+ "user-prompt-submit"+ "pre-tool-use"+ "post-tool-use"+ "stop"+ )+fi+DEST="$TO/$AGENT"mkdir -p "$DEST"