Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Merge release/2.6 into main for 2.6.0
AkitaOnRails769d1b6e7c94
diff --cc CHANGELOG.mdindex c19436c1,092e4da4..7d8355ba--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -7,77 -7,321 +7,355 @@@ and this project adheres to [Semantic V## [Unreleased]+ ### Added+ - Added bounded install-wide identity and component-safe path routes in the exact+ operator-home `.ai-memory.toml`. Exact hostful repository identity wins the+ longest lexical path route, local non-home markers stay authoritative, aliases+ reuse the existing identity-bound marker wire, and malformed or ambiguous route+ maps fail closed across native, shell, PowerShell, generated TypeScript, and+ OpenClaw clients. Recognizable malformed route syntax is rejected before+ fallback, while malformed root-only settings retain legacy parsing. Generated+ clients preserve marker versus repo-root provenance, and OpenClaw keeps local+ git identity discovery alias-gated. The default identity style remains+ unchanged. (#1033)+ - Added bounded local `.ai-memory.toml` `aliases = ["former-name"]` routing for+ existing project-coordinate compatibility. Native, POSIX shell, PowerShell,+ and generated TypeScript hook clients forward the same validated aliases for+ capture and SessionStart handoff lookup; resolution remains workspace-local,+ requires the checkout's matching hostful git-remote identity, preserves the+ existing UUID, and permits only write-authorized canonical-name promotion.+ Aliases are not persisted, and the default naming style is unchanged. (#1033)+ - Added read-only project-coordinate diagnostics to `ai-memory doctor` and the+ root-gated `GET /admin/project-coordinate` endpoint. The report classifies+ exact, canonical-compatibility, legacy-compatibility, missing, and ambiguous+ names; shows safe local marker/repository evidence and rename eligibility;+ and reports collisions without creating, claiming, renaming, or exposing+ remote credentials or marker paths. Ambiguous results keep local session+ evidence and mark server capture counts unavailable; any returned preferred+ project is contextual only, never a unique resolution. (#1033)+ - Added the cross-project profile (`docs/cross-project-profile.md`, design in+ `docs/design-cross-project-profile.md`): a small set of `profile/` pages+ recording how the user usually works, delivered to every project and every+ harness at session start as a fenced, byte-budgeted digest of defaults that+ rank below the user's instructions, the repository's rules file and the+ project's own memory. It is on by default for a single-operator server,+ shared across every workspace, and off on a multi-user server until+ `[profile] enabled = true`, which gives each operator a private, restricted+ profile; `share = "global"` or `"workspace"` makes a team profile that is+ read-open and write-gated like `_global`, admits a habit only on evidence+ from at least two operators, and is presented as team defaults. The digest filters entries by the+ stack the project's activity shows, stays byte-identical between sessions,+ and gives a project with no memory yet a larger baseline. `memory_write_page`+ and `memory_delete_page` accept `scope: "profile"`, `memory_query` returns+ profile entries in `global_scope_hits`, a marker's `[profile] contribute` /+ `consume` keys opt a project out of contributing or receiving (an opt-out+ stays recorded until a marker says otherwise), and+ `ai-memory profile status | list | show | forget | review | rebuild`+ inspects and curates it, while `ai-memory profile apply` writes the entries+ that fit a repository into a managed block of its rules file (`--remove`+ takes it out), never touching anything outside the block. Entries are+ learned on their own: a server pass, run after each session ends and+ hourly, harvests the user's own+ preference-shaped prompts (never tool output), the project's curated pages+ and its stack signals, and converges them across projects into entries once+ the user states a choice as general or it appears in `min_projects`+ projects, the newest ruling winning. With an LLM provider the pass+ classifies and restates entries through JSON-schema calls and falls back to+ the zero-LLM path on any error. It never rewrites an entry edited by hand,+ and an entry removed with `profile forget` stays removed until the user+ states it again. (#1000)+ - Added `ai-memory resume --search` with immediate type-to-filter name search,+ and `resume --all`, which keeps the previous cross-checkout picker: every+ linked checkout, the current one first, each listed with its own fully+ paginated query. (#1039)+ - Added `install-hooks --agent claude-code --scope project`, which writes the+ hook configuration to the checkout's gitignored `.claude/settings.local.json`+ (where Claude Code reads it: the git root, or the launch directory on+ Windows and when the repository root is the home directory) instead of the+ user-level `settings.json`, so capture is opted in per repository. The+ installer warns when that file is not ignored by git, refuses the+ inline-token fallback for it, notes when the other scope also carries+ ai-memory hooks, and keeps its backups under the data dir instead of the+ checkout; `uninstall` run inside the checkout sweeps it and reminds you to+ do the same in other project-scoped checkouts; `upgrade` and the+ `ai-memory run` auto-wire no longer add user-level Claude Code hooks on top+ of a project-scoped install. (#1034)+ - Added explicit MCP behavior annotations (title, read-only, destructive,+ idempotent, and open-world hints) to all 23 tools. Reordered the MCP server+ instructions so scope selection, untrusted-memory handling, deliberate+ cross-project broadening, capture policy, and handoff safety remain complete+ within the first 2,048 characters used by truncating clients. The longer+ per-tool routing reference remains available to clients that accept it.+ (#920)+ - Added env-only named launch profiles for `ai-memory run --profile NAME` via+ `[run.profiles.<name>.env]` in `config.toml`. Profile values feed the same+ native-session, auto-wire, and child-process environment path as `--env`;+ precedence is profile, then `--env-file`, then repeated `--env`. Unknown or+ invalid profiles fail before a workstream lease or child process; an unknown+ name lists the defined profiles or prints a table to paste. (#922; error+ message, tests and docs from #1031 by @geeksilva97)+ - Added cross-project attribution for native lifecycle file-tool events whose+ harness keeps reporting the parent session's cwd. A bounded, recognized+ absolute target reroutes only when every path proves the same repository or+ marker boundary; destination capture exclusions and server profiles are+ resolved before the event is spooled. Relative, mixed-project, unsupported,+ and arbitrary non-project paths keep the original route. (#932)+ - Added `serve --enable-api` / `AI_MEMORY_ENABLE_API=true` to mount the+ authenticated read-only `/api/v1` surface without the browser UI. Existing+ `--enable-web` behavior is unchanged and still includes the API. Documented+ the acceptance and safety boundary for a repository-backed team-wiki sync+ companion. (#986)+ - Added `[handoff].claim_on_session_start` (default `true` - unchanged+ behavior). When set to `false`, `SessionStart` no longer claims a pending+ handoff automatically; it renders a non-consuming notice naming the exact+ `handoff_id`, `from_agent`, and age instead (mirroring the existing inbox+ notice: metadata only, never the stored summary/open-questions/next-steps+ text), and the agent or operator picks it up explicitly with+ `memory_handoff_accept`. Fixes an unrelated next session, a different+ harness, or a non-interactive launch silently consuming a baton meant for+ a specific session. Server-wide for now; a per-project override is left for+ a follow-up change. (#1030)+ - Added a default-quit prompt after a successful interactive managed run so the+ operator can re-run the current harness or switch to another installed+ harness in the same workstream. Utility, failed, interrupted,+ non-interactive, and custom-`--executable` runs keep their existing exit+ behavior. Resolves #909. (#975)+ - Added `ai-memory backup-agents` and dry-run-by-default+ `ai-memory restore-agents` commands for host agent configurations, skills,+ plugins, and project instructions. Archives are written atomically with+ private Unix permissions, MCP config text is sanitized by default, and+ restore bounds archive input, verifies manifest checksums and completeness,+ refuses duplicate or symlink-escaping targets, and keeps overwritten files+ as timestamped backups. Other asset types are copied verbatim and may contain+ secrets or active instructions/code. (#962)+ - Added a NixOS module (`nix/nixos-module.nix`, exposed as+ `nixosModules.default`) with a dedicated non-login system user and a hardened+ NixOS systemd sandbox. A minimal typed set plus `freeformType` renders+ declarative `config.toml`; values land in a world-readable store path, so+ secrets (including `llm_headers`) use `ageSecret`, `sopsSecret`, or+ `environmentFile`. Non-loopback binds require a secret source. The module+ includes opt-in web, firewall, and resource settings plus eval and privileged+ container checks. Flake packages are exported for x86_64 Linux, aarch64+ Linux, and Apple Silicon macOS; Intel macOS remains available through the+ release tarball and Homebrew rather than the pinned Nixpkgs revision. (#989)+ - Added `ai-memory doctor` reporting for Claude Code's default native+ `memory/` store for the current repository: location, file count, and whether+ the nearest marker's `ignore_paths` would exclude a read. Repository-root+ resolution keeps worktrees and subdirectories on the same report, and the+ output warns that shell/PowerShell compatibility hooks do not enforce the+ exclusion. Resolves #1003. (#1005)+ - Added per-event outcomes to `/hook/batch` acknowledgements and process-lifetime+ ingest counters for stored events, replays, recovery, ignored endings,+ collisions and failures. Legacy acknowledgement fields were preserved. (#1015)+ - Added receipt outcomes and delivery counts to the companion relay. Opening a+ schema 1 queue now upgrades it atomically to schema 2; older relay binaries+ refuse schema 2, so downgrade requires a pre-upgrade backup with all queue+ users stopped. Pending order and existing delivery metadata were preserved.+ Receipts now retain their first known outcome. (#1015)+ - Added `ai-memory list-projects [--workspace] [--json]`: a plain, scriptable+ listing of every workspace/project pair the server knows about, sorted by+ workspace then project. Previously the only way to see this from outside+ an interactive `show` session was to call `GET /api/v1/projects` directly.+ (#1022)+ - Added scope and policy preflight to `ai-memory hook --check-capture`, including+ event eligibility, sanitized routing hints and server-remapping information.+ Partial scope, excluded events, rejected profiles and oversized hints refuse+ capture. Inspection neither ingests events nor claims handoffs. (#1019)+ - Added the latest scoped consolidation job's state and attempt count to HTTP+ session summaries and MCP `memory_read_session_observations`. The field is+ `null` when no job exists; provider errors remain private and existing session+ ownership filters are preserved. (#1018)+ - Added incremental paging to scoped HTTP `recent` reads with `updated_since`+ and an opaque, scope-bound cursor. Queries preserve equal-time ordering,+ exclude expired and superseded pages and recheck authorization on each+ request. Calls without incremental arguments retain their existing array+ response. Added a generic MCP/HTTP integration guide. (#1017)+ - Added machine-authenticated `GET /identity`, available with the web UI+ disabled, and `ai-memory doctor` diagnostics for caller identity, external+ capture ownership and sessions with multiple capture sources (native events+ or distinct extensions, including backfill).+ Mixed-source counts preserve scope, session ownership and time-window filters;+ older servers leave unsupported fields unknown. (#1016)+ - Added shared capture privacy checks to the relay and the conversation importer,+ run before an event is hashed, persisted, previewed or delivered: they refuse+ credential-shaped native identities, scrub nested credentials while keeping+ numeric token counts, and drop locally a relay item queued before them that+ fails them, so it no longer holds its session. (#1072)+ - Added `[handoff].create_on_session_end` (default `true` - unchanged+ behavior). When set to `false`, unmanaged session ends write the session+ summary page and enqueue consolidation as usual, but skip creating an+ automatic open handoff for the next session; OpenCode turn checkpoints+ refresh the page without a baton too. Explicit handoffs created via+ `memory_handoff_begin` and managed workstream runs remain unaffected.+ Server-wide: applies to every operator on this server. (#1043)+ - Added bounded, sanitized native-record and adapter correlation provenance to+ managed-workstream search/tail results and the CLI's text/JSON output, with+ compatible optional fields and sanitization of legacy provenance on reads. (#1057)+ - Added Portuguese history phrases to the existing opt-in session-recall+ router (`[retrieval] query_intent`), including accented and unaccented spellings of+ "última sessão", "onde paramos ontem", and "decisão anterior". Word+ boundaries and explicit history phrases keep technical session queries+ unchanged; routing remains off by default. (#1056)+ - Added shared, typed and bounded `entities`, `abstract`, and `relations`+ metadata to MCP `memory_write_page` and admin `/admin/write-page`, plus bounded+ MCP `kind` while preserving the admin's legacy `kind` adapter. Kept existing+ request shapes, entity normalization, authenticated attribution and the wiki+ write pipeline. Documented whole-page replacement, raw-input metadata bounds+ and trimmed relation scope components. (#1055)+ - Added structured results for the existing auto-improvement eval execution in+ review reports, staged run metadata, and accepted proposal sidecars, with+ server-generated eval IDs, evaluated request/body digests, checker invocation+ identity, observed success/rejection/failure/timeout, and sanitized bounded+ reasons. Report deserialization discarded supplied eval observations. (#1053)+ - Added `grizzybot` as a recognised agent (wire value `grizzybot`, alias+ `grizzy-bot`), so GrizzyBot's lifecycle events are attributed to it instead+ of `other` and its tool calls are captured as closed-schema tool families,+ like other Claude Code-shaped agents. GrizzyBot posts to `/hook` and+ `/mcp` itself, so there is nothing to install. Adds migration V72 to extend+ the `sessions.agent_kind` CHECK constraint. (#1036)+ - Added GitHub Copilot CLI as a hooked agent: `install-hooks --agent+ copilot-cli` writes `$COPILOT_HOME/hooks/ai-memory.json` (default+ `~/.copilot/hooks/ai-memory.json`) with Copilot's flat, matcher-less entries+ and PascalCase event names, so Copilot sends its VS Code/Claude-compatible+ payload. Ten events — Claude Code's nine plus `PostToolUseFailure` — with+ native commands enforcing capture exclusions; tool output is read from+ `tool_result.text_result_for_llm` and the outcome from+ `tool_result.result_type`. The `SessionStart` hook delivers the prior+ session's handoff through Copilot's top-level `additionalContext` (ported+ from #1069). There is deliberately no `--scope project`. The bare+ `install-mcp --client copilot` alias keeps meaning VS Code Copilot;+ `ai-memory run copilot` follows separately. (#1040)+ - Added `install-mcp --client copilot-cli`, which merges ai-memory's remote+ entry (`type: "http"`, `url`, bearer `headers`, `tools: ["*"]`) into the root+ `mcpServers` map of `$COPILOT_HOME/mcp-config.json` (default+ `~/.copilot/mcp-config.json`), preserving other servers. `install-hooks+ --agent copilot-cli` without `--server-url` now reads the server URL and+ bearer back from that entry, and `uninstall` removes it. (#1040)+ - Added an optional `session_id` to `memory_write_page`, so an agent can+ write a session's page with its own model and keep it traceable to the+ session. The session must belong to the project the page is written to, and+ the page records it as session evidence. A page that cites a session does+ not overwrite a pinned page. Writing `sessions/<id>.md` also stamps the+ frontmatter `memory_consolidate` writes there (`session_id`, `agent`,+ `consolidated`, plus `consolidated_by: agent`), defaults the tier to+ `episodic`, applies the same duplicate-title suffix, and marks the session's+ queued SessionEnd consolidation job completed. (#1038)+ - Added `identity_style = "path" | "host_path"` marker control for remote-backed+ project naming. `path` names from the full repository path without the host+ (`github.com/acme/api` → `acme-api`); `host_path` preserves the former naming+ behavior as an explicit opt-out. Captures always route by the full hostful+ identity, and cross-forge path collisions never merge. (#1033)+ - Added `[hook_spool] max_attempts` and+ `AI_MEMORY_HOOK_SPOOL_MAX_ATTEMPTS` to configure failed drain passes before+ dropping an event; zero disables attempt-based drops while age and spool+ size limits remain. (#1092)+### Changed+ - Changed static CLI/MCP project-name resolution to accept an existing+ repository's canonical hostless path name and its v2 basename compatibility+ key. Reads remain find-only; an authorized write through the canonical key+ promotes only `projects.name` in place, preserving the project UUID and all+ dependent rows. Project scope manifests preserve the optional full hostful+ identity/source and derived keys so clean reindex reconstructs the same UUID+ and lookup behavior; older manifests remain valid. MCP, admin, and+ managed-workstream writes refresh the manifest after promotion and disclose a+ post-commit refresh failure for startup repair on both success and any later+ operation error, retaining the first warning across busy retries and lease+ wait-out; managed-run caller validation happens before promotion.+ Ambiguous cross-forge keys and target-name conflicts fail closed. Current+ clients now explicitly send `path` for a valid remote and send explicit+ `host_path` for the opt-out; a new server deliberately interprets an omitted+ field as legacy `host_path` so old clients cannot be silently renamed. Existing compatible projects are+ promoted only by authorized capture/write and keep their UUID; read-only+ handoff/static lookups never rename. (#1033)+ - Changed the documented precedence between rules and memory: the user's+ instructions, then the repository's rules file, then the project's memory,+ then the cross-project profile. Where no hard rule exists, agents now use+ what memory already knows instead of asking again; the routing snippet,+ MCP instructions and durable-pages skill send standing cross-project+ preferences to the profile (`scope: "profile"`). (#1000)+ - Scoped `ai-memory resume` to the current checkout by default instead of every+ linked project (`--all` restores the old view) and removed its default result+ cutoff with bounded server pagination, preserving Left/Right harness+ selection. Explicit limits now apply after the initial search; against an+ older server that ignores paging, the picker warns and shows the first page.+ `continue` retained its cross-directory behavior. (#1039)- Documented FutureInfra as an endpoint for the existing `openai-compat`provider. (#1026)+ - `.github/workflows/nix.yml` builds the flake on `x86_64-linux` for path-+ filtered PRs and pushes (package smoke + NixOS module eval /+ sandbox-parity). The `aarch64-darwin` package smoke and the privileged+ NixOS container smoke run only on schedule, `workflow_dispatch`, or a PR+ labelled `nix` / `full-ci`. (#989)+ - Restricted managed-workstream provenance to scrubbed source labels and an+ explicit scalar metadata allowlist, with 512-byte string bounds. Client event+ ids beginning with `managed-run:` are reserved for server checkpoints and+ extraction-loss annotations. Active-run retries reject changes to an existing+ event's agent, native session or kind, and retain its first indexed content+ and provenance across sanitizer changes. (#1057)+ - The SessionEnd consolidation worker leaves a session page alone when the+ agent wrote it through `memory_write_page` and no observation arrived after+ it: the page records the session's observation count as+ `observation_generation`, and the worker completes a job whose generation+ that count reaches instead of replacing the page with the server's+ provider. A page written before the session's last observation is+ consolidated as before. (#1038)+ - Required managed-run finish imports and finished retries, and the cancel,+ heartbeat, native-session link and context-acceptance routes, to pass an+ authenticated owner check and current project access checks (repeated in+ finish's writer transaction), so another operator cannot release or rebind a+ run. Database users required current Write access; trusted+ proxy operators retained their existing project policy. Active API keys+ remained valid after human login was disabled. Shared, unattributed runs and+ late finishes of still-active runs retained their existing behavior. (#1075)+ - Required new managed native-session bindings and imports to preserve the+ exact original identity within 512 UTF-8 bytes and pass privacy validation+ before use or persistence. Invalid historical identities were projected as+ unknown (`native_session_id: ""`) in workstream search without rewriting+ stored history; the CLI also protected reads from older servers. (#1079)### Fixed+- Fixed wiki confinement walks failing on Windows with `PermissionDenied`+ (sharing violation) or `ERROR_DELETE_PENDING` when a concurrent commit or+ the atomic writer held or rename-replaced a file mid-walk; per-entry walk+ probes now skip those as transient churn exactly like the NotFound vanish+ race, while every entry that does stat is still refused when link-like and+ root-level probes keep their strict semantics. (#1107)+- Fixed generic OpenCode commands selecting integration contracts from command+ spelling instead of the executable's major version. `run opencode` now probes+ the exact executable once and carries the resolved V1/V2 dialect through+ session discovery, launch, auto-wire, and transcript import; hook and MCP+ installers use the same strict resolver, while container-oriented+ `setup-agent` requires an explicit V1/V2 artifact dialect. Probe and launch+ share one captured child environment with `--env` overlays, including Windows+ key casing. Automatic launch skips an unresolvable OpenCode candidate without+ hiding other harnesses. Hook/MCP transitions reuse ownership-verified endpoint+ and token settings across both schemas and reject conflicting generated+ entries. Migrations remove only entries proven generated by ai-memory, and plugin+ cleanup never overwrites a concurrent user replacement while restoring an+ unowned quarantined file. (#1097)+- Fixed Codex on the Kimi coding endpoint failing every model call with+ "tools.function.parameters is not a valid moonshot flavored json schema+ (... detected infinite recursion without termination condition ...)".+ Moonshot's validator never resolves `$ref`, so the `$defs`/`$ref` pairs+ Codex forwards from MCP input schemas failed the request at any depth —+ including the `ReasoningTier` reference on `memory_query` and+ `memory_explore` and the `FeedbackKind` reference on `memory_feedback` —+ not just at the root. The `?flavor=moonshot` dialect now inlines every+ `#/$defs/*` reference and drops the emptied `$defs` table; nested+ combinators (which Moonshot accepts) and runtime validation are unchanged.+ `?flavor=bedrock` and `?flavor=gemini` keep serving `$defs`/`$ref` as+ before. (#1093)+- Confined wiki reads, writes, indexing, recovery, and lifecycle cleanup to real+ project-tree directories by refusing symbolic links and filesystem reparse+ points at namespace roots or descendants. (#1107)- - Fixed `memory_handoff_list` MCP tool calls being counted under writes in- `client_activity`: the read-only inspection tool is now classified as a read- in `tool_call_is_write`. (#1088)- - Fixed a store write sent while the writer was shutting down occasionally- waiting forever instead of failing with `WriterClosed`: the writer now- closes its queue and drains in-flight commands before it stops.- - Fixed `resume` and `workstreams` running `git status` on every linked checkout- before listing anything: listing now reads only the checkout's stable- fingerprints, so a large working tree or a slow filesystem-monitor hook no- longer blocks the picker before its first frame. (#1039)- - Fixed the generated OpenCode 2 plugin ending every tracked session when- OpenCode unloads it on idle-location eviction. Unload is not shutdown: the- host and its sessions stay alive, so each eviction froze a live session- (`SessionStart` cannot reopen an ended OpenCode session), fabricated a- spurious summary page and open handoff, and made the next baton fetch fail- with `invalid state: an ended session cannot accept a handoff`. Plugin- unload no longer posts `session-end`; deletion (`session.deleted`) remains- the end signal and a completed root turn already publishes its continuation- checkpoint and baton. Regenerate the plugin with- `ai-memory install-hooks --agent opencode2 --apply`. (#1074)- - Fixed watcher reindexing racing with writes and batches to the same page by- sharing their per-page mutex from disk read through SQLite upsert. Both- mutation guards are released before embedding; external editors remain- outside this coordination. (#1059)- - Fixed a managed Claude Code run losing its conversation after `/resume` on a- Claude Code background session. The run used to finish on the foreground- session it started with, which held none of the conversation, so the next- `ai-memory run claude` or `continue` resumed it and Claude opened an empty- session. A Claude run now finishes on the background session its own- session attached to in this checkout, found from that transcript's- `sessionKind: "bg"` records; another launch's background session is never- taken. (#1050)+ - Fixed a later hook event carrying a managed-run id linking its native session+ to that run without the checks SessionStart applies. It now links only from+ the run's own project and operator; an event from elsewhere is still captured+ but no longer repoints the run. (#1082)+ - Fixed completed retries and no-op session endings advancing+ `last_persisted_ms` without a durable write. Recovery still advances the+ timestamp when it commits a new page or terminal effect. (#1015)- Fixed interrupted launchers blocking an immediate managed-workstream restartby adding explicit `ai-memory run --force-unlock` recovery. The serveratomically expires and replaces only a lease attributed to the samediff --cc crates/ai-memory-cli/src/commands/install_hooks.rsindex 1501c6aa,2b87ab39..679bdf59--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@@ -372,39 -524,16 +524,46 @@@ fn kiro_cli_home_join////// # Errors/// Returns an error if the hook script directory cannot be located.-pub fn run(config: &Config, mut args: InstallHooksArgs) -> Result<()> {+pub fn run(config: &Config, args: InstallHooksArgs) -> Result<()> {- run_with_opencode_dialect(config, args, None)+ if args.scope == HookInstallScope::Project && args.agent != AgentChoice::ClaudeCode {+ anyhow::bail!(+ "`--scope project` is only supported for `--agent claude-code`; ai-memory writes no \+ project-local hook file for {}",+ args.agent.kind().as_str()+ );+ }- let inferred = if args.server_url.is_none() {- infer_installed_mcp_config(args.agent)?++ run_with_opencode_dialect_and_mcp_path(config, args, None, None)+}++pub(crate) fn run_with_opencode_dialect(+ config: &Config,+ args: InstallHooksArgs,+ dialect: Option<ai_memory_workstream::OpenCodeDialect>,+) -> Result<()> {+ run_with_opencode_dialect_and_mcp_path(config, args, dialect, None)+}++pub(crate) fn run_with_opencode_dialect_and_mcp_path(+ config: &Config,+ mut args: InstallHooksArgs,+ dialect: Option<ai_memory_workstream::OpenCodeDialect>,+ mcp_config_path: Option<&Path>,+) -> Result<()> {+ let child_env = super::run::EffectiveChildEnv::from_runtime(&config.runtime_env);+ args.agent = match (args.agent, dialect) {+ (AgentChoice::OpenCode, Some(ai_memory_workstream::OpenCodeDialect::V1)) => {+ AgentChoice::OpenCode+ }+ (AgentChoice::OpenCode, Some(ai_memory_workstream::OpenCodeDialect::V2)) => {+ AgentChoice::OpenCode2+ }+ (agent, None) => super::opencode_dialect::resolve_agent(agent, &child_env)?,+ (agent, Some(_)) => agent,+ };+ let needs_inferred_url = args.server_url.is_none() && !config.server_url_configured();+ let needs_inferred_token = args.auth_token.is_none() && config.auth.bearer_token.is_none();+ let inferred = if needs_inferred_url || needs_inferred_token {+ infer_installed_mcp_config(args.agent, mcp_config_path)?} else {None};diff --cc crates/ai-memory-cli/src/commands/mod.rsindex 792fbc5d,a39eb973..02f18239--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@@ -58,9 -69,9 +69,10 @@@ pub mod messagepub mod move_project;pub mod move_session;pub mod openclaw_plugin;+pub mod opencode_dialect;pub mod path_util;pub mod pending_writes;+ pub mod profile;pub mod project;pub mod project_registry;pub mod purge_preview;diff --cc crates/ai-memory-cli/src/commands/resume.rsindex 67b80166,8b79dba7..f6e62f60--- a/crates/ai-memory-cli/src/commands/resume.rs+++ b/crates/ai-memory-cli/src/commands/resume.rs@@@ -36,8 -40,122 +40,122 @@@ pub async fn run(config: &Config, args}let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;- let mut links = project_registry::links_for_server(config, &endpoint)?;- match current_checkout_link(config, &endpoint) {+ let cwd = std::env::current_dir().context("reading the current checkout")?;+ let candidates = if args.all {+ candidates_across_checkouts(config, &endpoint, &args, &cwd).await?+ } else {+ candidates_for_checkout(config, &endpoint, &args, &cwd).await?+ };+- let harnesses = available_harnesses();++ let harnesses = available_harnesses(config);+ let mut harness_indices = vec![0usize; candidates.len()];+ let mut choices = candidates+ .iter()+ .map(|candidate| choice_for(candidate, None))+ .collect::<Vec<_>>();+ let Some(index) = select_with_horizontal(+ "Resume workstream",+ &mut choices,+ "left/right harness",+ args.search.as_deref(),+ &mut |index, direction, choice| {+ let harness =+ cycle_selected_harness(&mut harness_indices, index, &harnesses, direction);+ *choice = choice_for(&candidates[index], harness);+ },+ )?+ else {+ return Ok(0);+ };+ let selected = &candidates[index];+ let target = continue_session::resolve_target(config, &selected.link)?;+ let harness = selected_harness(harness_indices[index], &harnesses);+ eprintln!(+ "resuming workstream '{}' with harness '{}' in {} at {}",+ terminal_text(&selected.summary.name),+ harness+ .map(harness_name)+ .unwrap_or_else(|| "auto".to_owned()),+ scope_label(&selected.link),+ terminal_text(&selected.target.to_string_lossy())+ );+ crate::commands::run::run_from(+ config,+ RunArgs {+ workspace: Some(selected.link.workspace.clone()),+ project: Some(selected.link.project.clone()),+ workstream: Some(selected.summary.name.clone()),+ new_workstream: None,+ executable: None,+ yolo: args.yolo,+ true_yolo: args.true_yolo,+ jail: None,+ no_jail: false,+ fresh: args.fresh,+ force_unlock: false,+ no_autowire: false,+ profile: None,+ env: Vec::new(),+ env_file: None,+ harness,+ native_args: Vec::new(),+ },+ &target,+ )+ .await+ }++ async fn candidates_for_checkout(+ config: &Config,+ endpoint: &ServerEndpoint,+ args: &ResumeArgs,+ cwd: &Path,+ ) -> Result<Vec<Candidate>> {+ let link = current_checkout_link(config, endpoint, cwd)?;+ if args+ .workspace+ .as_deref()+ .is_some_and(|workspace| workspace != link.workspace)+ {+ bail!(+ "current checkout belongs to {}, not workspace '{}'",+ scope_label(&link),+ terminal_text(args.workspace.as_deref().unwrap_or_default())+ );+ }+ let summaries =+ workstreams::list_all_for_checkout(endpoint, &link.workspace, &link.project, &link.path)+ .await?;+ if summaries.is_empty() {+ bail!(+ "no managed workstreams for the current checkout ({}); launch one here with `ai-memory run <harness>` first",+ scope_label(&link)+ );+ }+ let mut candidates = summaries+ .into_iter()+ .map(|summary| Candidate {+ target: link.path.clone(),+ link: link.clone(),+ summary,+ })+ .collect::<Vec<_>>();+ order_candidates(&mut candidates);+ apply_limit(&mut candidates, args, "the current checkout")?;+ Ok(candidates)+ }++ /// `--all`: every checkout linked for this server, the current one first.+ /// Each checkout is listed through its own fingerprint-scoped query, and one+ /// that cannot be resolved or queried is skipped with a note.+ async fn candidates_across_checkouts(+ config: &Config,+ endpoint: &ServerEndpoint,+ args: &ResumeArgs,+ cwd: &Path,+ ) -> Result<Vec<Candidate>> {+ let mut links = project_registry::links_for_server(config, endpoint)?;+ match current_checkout_link(config, endpoint, cwd) {Ok(current) => {if !links.iter().any(|link| {link.workspace == current.workspacediff --cc crates/ai-memory-cli/src/commands/run.rsindex cf7a1f04,12b14d7f..4ee47d6a--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@@ -16,17 -16,19 +16,19 @@@ use ai_memory_workstream::JailHostFacts, JailSupport, JailToggleChoice, JailToggleKind, LaunchMode, LaunchPlan,LaunchRoots, ManagedHarness, NativeSessionCandidate, ai_jail_support,allows_native_session_adoption, apply_claude_true_yolo, apply_yolo, build_ai_jail_invocation,- build_launch_plan, build_launch_plan_with_env, claude_attached_background_session,+ build_launch_plan, build_launch_plan_with_env_lookup, claude_attached_background_session,claude_live_background_attach_id, claude_session_ran_in_background, clean_path,crush_global_config_path, discover_native_session, export_transcript,- has_native_session_selector, inside_ai_jail_here, inspect_repository, jail_checklist,- jail_toggle, kiro_explicit_session_id, kiro_harness_from_source_cursor,- kiro_selects_non_default_engine, kiro_selects_v2_engine, kiro_selects_v3_engine,- kiro_v3_resume_uses_default_store, list_native_sessions, marked_choices, native_session_exists,- native_session_in_checkout, native_store_root, omp_profile_flag, omp_profile_flag_env,- parse_jail_toggles, store_override_vars, usable_ai_jail_here, wait_for_transcript_flush,+ has_native_session_selector, inside_ai_jail_here, inspect_repository,+ is_interactive_session_invocation, jail_checklist, jail_toggle, kiro_explicit_session_id,+ kiro_harness_from_source_cursor, kiro_selects_non_default_engine, kiro_selects_v2_engine,+ kiro_selects_v3_engine, kiro_v3_resume_uses_default_store, list_native_sessions,+ marked_choices, native_session_exists, native_session_in_checkout, native_store_root,+ omp_profile_flag, omp_profile_flag_env, parse_jail_toggles, store_override_vars,+ usable_ai_jail_here, wait_for_transcript_flush,};use anyhow::{Context as _, Result, anyhow};+ use clap::ValueEnum as _;use tokio::process::Command;use tokio_util::sync::CancellationToken;@@@ -252,6 -124,198 +254,203 @@@ pub(super) async fn run_from_with_wirincwd: &Path,wire_overrides: &super::run_autowire::WireOverrides,) -> Result<i32> {+ run_once_with_wiring(config, args, cwd, wire_overrides)+ .await+ .map(|outcome| outcome.exit_code)+ }++ #[derive(Debug)]+ struct RunOutcome {+ exit_code: i32,+ harness: ManagedHarness,+ interactive_session: bool,+ mode: LaunchMode,+ workstream_name: String,+ }++ #[derive(Debug, Clone, Copy, PartialEq, Eq)]+ enum AfterRunAction {+ Switch(RunHarnessChoice),+ Rerun,+ Quit,+ }++ async fn run_with_exit_prompt(config: &Config, args: RunArgs, cwd: &Path) -> Result<i32> {+ let interactive_terminal =+ io::stdin().is_terminal() && io::stdout().is_terminal() && io::stderr().is_terminal();+ let custom_executable = args.executable.is_some();+ let mut next_args = args;+ preserve_trailing_run_options(&mut next_args);++ loop {+ let outcome = run_once_with_wiring(+ config,+ next_args.clone(),+ cwd,+ &super::run_autowire::WireOverrides::default(),+ )+ .await?;+ if !should_offer_after_run(&outcome, interactive_terminal, custom_executable) {+ return Ok(outcome.exit_code);+ }+- let available = available_switch_harnesses(outcome.harness);++ let switch_env = EffectiveChildEnv::from_runtime(&config.runtime_env);++ let available = available_switch_harnesses(outcome.harness, &switch_env);+ let action = {+ let stdin = io::stdin();+ let stderr = io::stderr();+ choose_after_run(+ outcome.harness,+ &outcome.workstream_name,+ &available,+ &mut stdin.lock(),+ &mut stderr.lock(),+ )+ };+ let action = match action {+ Ok(action) => action,+ Err(error) => {+ eprintln!("ai-memory: could not read the post-run choice ({error}); exiting");+ return Ok(outcome.exit_code);+ }+ };+ if !apply_after_run_action(&mut next_args, &outcome, action) {+ return Ok(outcome.exit_code);+ }+ }+ }++ fn should_offer_after_run(+ outcome: &RunOutcome,+ interactive_terminal: bool,+ custom_executable: bool,+ ) -> bool {+ outcome.exit_code == 0+ && outcome.mode == LaunchMode::Session+ && outcome.interactive_session+ && interactive_terminal+ && !custom_executable+ }++ fn preserve_trailing_run_options(args: &mut RunArgs) {+ args.yolo |= remove_wrapper_yolo(&mut args.native_args);+ args.true_yolo |= remove_wrapper_true_yolo(&mut args.native_args);+ args.no_autowire |= remove_wrapper_no_autowire(&mut args.native_args);+ let trailing_jail = remove_wrapper_jail(&mut args.native_args);+ if trailing_jail.jail.is_some() {+ args.jail = trailing_jail.jail;+ }+ args.no_jail |= trailing_jail.no_jail;+ }+-fn available_switch_harnesses(current: ManagedHarness) -> Vec<RunHarnessChoice> {++fn available_switch_harnesses(++ current: ManagedHarness,++ env: &EffectiveChildEnv,++) -> Vec<RunHarnessChoice> {++ let search = env.executable_search();+ RunHarnessChoice::value_variants()+ .iter()+ .copied()+ .filter(|choice| {+ managed_harness(*choice).agent_kind() != current.agent_kind()- && harness_available(*choice)++ && harness_available(*choice, search)+ })+ .collect()+ }++ fn choose_after_run(+ current: ManagedHarness,+ workstream_name: &str,+ available: &[RunHarnessChoice],+ input: &mut impl io::BufRead,+ output: &mut impl io::Write,+ ) -> io::Result<AfterRunAction> {+ writeln!(+ output,+ "ai-memory: {} exited successfully in workstream '{}'.",+ current.as_str(),+ workstream_name+ )?;+ for (index, choice) in available.iter().enumerate() {+ writeln!(+ output,+ " {}) switch to {}",+ index + 1,+ managed_harness(*choice).as_str()+ )?;+ }+ writeln!(output, " r) run {} again", current.as_str())?;+ writeln!(output, " q) quit (default)")?;++ loop {+ write!(output, "Select [q]: ")?;+ output.flush()?;+ let mut line = String::new();+ if input.read_line(&mut line)? == 0 {+ return Ok(AfterRunAction::Quit);+ }+ let choice = line.trim();+ if choice.is_empty() || choice.eq_ignore_ascii_case("q") || choice == "0" {+ return Ok(AfterRunAction::Quit);+ }+ if choice.eq_ignore_ascii_case("r") {+ return Ok(AfterRunAction::Rerun);+ }+ if let Ok(index) = choice.parse::<usize>()+ && let Some(harness) = index.checked_sub(1).and_then(|i| available.get(i))+ {+ return Ok(AfterRunAction::Switch(*harness));+ }+ writeln!(output, "Choose a listed number, r, or q.")?;+ }+ }++ fn apply_after_run_action(+ args: &mut RunArgs,+ outcome: &RunOutcome,+ action: AfterRunAction,+ ) -> bool {+ let choice = match action {+ AfterRunAction::Quit => return false,+ AfterRunAction::Switch(choice) => choice,+ AfterRunAction::Rerun => run_harness_choice(outcome.harness),+ };+ args.harness = Some(choice);+ args.native_args =+ if action == AfterRunAction::Rerun && outcome.harness == ManagedHarness::KiroV3 {+ vec![OsString::from("--v3")]+ } else {+ Vec::new()+ };+ args.workstream = Some(outcome.workstream_name.clone());+ args.new_workstream = None;+ args.fresh = false;+ true+ }++ const fn run_harness_choice(harness: ManagedHarness) -> RunHarnessChoice {+ match harness {+ ManagedHarness::Claude => RunHarnessChoice::Claude,+ ManagedHarness::Codex => RunHarnessChoice::Codex,+ ManagedHarness::OpenCode => RunHarnessChoice::OpenCode,+ ManagedHarness::OpenCode2 => RunHarnessChoice::OpenCode2,+ ManagedHarness::Pi => RunHarnessChoice::Pi,+ ManagedHarness::Crush => RunHarnessChoice::Crush,+ ManagedHarness::Omp => RunHarnessChoice::Omp,+ ManagedHarness::Kimi => RunHarnessChoice::Kimi,+ ManagedHarness::CommandCode => RunHarnessChoice::CommandCode,+ ManagedHarness::Kiro | ManagedHarness::KiroV3 => RunHarnessChoice::Kiro,+ ManagedHarness::Grok => RunHarnessChoice::Grok,+ ManagedHarness::Antigravity => RunHarnessChoice::Antigravity,+ }+ }++ async fn run_once_with_wiring(+ config: &Config,+ args: RunArgs,+ cwd: &Path,+ wire_overrides: &super::run_autowire::WireOverrides,+ ) -> Result<RunOutcome> {let repository = inspect_repository(cwd)?;let home = native_home(config).context("locating native harness session storage")?;let automatic_harness = args.harness.is_none();@@@ -274,10 -336,19 +473,21 @@@let force_fresh = args.fresh || trailing_fresh;let force_unlock = args.force_unlock || trailing_force_unlock;let no_autowire = args.no_autowire || trailing_no_autowire;- let run_env = resolve_run_env(args.env_file.as_deref(), &args.env)- .context("resolving --env/--env-file for the managed run")?;+ let profile = args+ .profile+ .as_deref()+ .map(|name| {+ config+ .run+ .profiles+ .get(name)+ .ok_or_else(|| unknown_run_profile(&config.run, name))+ })+ .transpose()?;+ let run_env = resolve_run_env(profile, args.env_file.as_deref(), &args.env)+ .context("resolving --profile/--env-file/--env for the managed run")?;+ let child_env = EffectiveChildEnv::with_overrides(&config.runtime_env, &run_env);+ let executable_search = child_env.executable_search();if automatic_harness && !native_args.is_empty() {return Err(anyhow!("native harness arguments require an explicit harness; try `ai-memory run codex ...`"@@@ -521,8 -546,9 +738,9 @@@force_fresh,&home,&repository.cwd,- &run_env,+ &child_env,));+ let interactive_session = is_interactive_session_invocation(harness, &native_args);let resumes_linked_session = !force_fresh&& orphaned_session.is_none()&& prepared.native_session_id.is_some()@@@ -707,7 -745,7 +932,8 @@@harness,wire_overrides,&wire_env,+ &wire_child_env,+ &repository.cwd,);}// A Kiro v3 resume that dropped `KIRO_HOME` runs against the default store.@@@ -2088,8 -2160,11 +2371,11 @@@ fn build_preflighted_launch_planforce_fresh: bool,home: &Path,cwd: &Path,- env_overrides: &[(String, String)],+ env: &EffectiveChildEnv,) -> Result<(LaunchPlan, Option<String>)> {+ if let Some(id) = linked_session_id {+ NativeSessionIdentity::parse(id, &Sanitizer::builtin())?;+ }let explicit_selector = has_native_session_selector(harness, &native_args);if force_fresh && explicit_selector {return Err(anyhow!(@@@ -5643,122 -6122,6 +6498,124 @@@ mod testsassert_eq!(std::fs::read_to_string(packet).unwrap(), "managed packet");}+ #[cfg(unix)]+ #[tokio::test]+ async fn opencode_executable_probe_selects_v2_for_launch_and_autowire() {+ use std::os::unix::fs::PermissionsExt as _;++ use crate::commands::run_autowire::WireOverrides;+ use crate::config::Config;++ let app = Router::new()+ .route(+ "/workstream/runs",+ post(|| async {+ axum::Json(PrepareManagedRunResponse {+ workstream_id: WorkstreamId::new(),+ workstream_name: "default".into(),+ run_id: ManagedRunId::new(),+ resolved_agent: None,+ native_session_id: None,+ source_cursor: None,+ sync_after: 0,+ sync_through: 0,+ may_adopt_existing_session: false,++ manifest_warning: None,+ })+ }),+ )+ .route(+ "/workstream/runs/{run_id}/finish",+ post(|| async {+ axum::Json(FinishManagedRunResponse {+ imported_events: 0,+ latest_sequence: 0,+ })+ }),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });++ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let repo = tempfile::tempdir().unwrap();+ let launched = repo.path().join("launched");+ let executable_dir = repo.path().join("child-bin");+ std::fs::create_dir_all(&executable_dir).unwrap();+ let executable = executable_dir.join("opencode");+ std::fs::write(+ &executable,+ format!(+ "#!/bin/sh\nif [ \"$1\" = --version ]; then printf 'opencode v%s.0.23\\n' \"$OPENCODE_MAJOR\"; exit 0; fi\nprintf '%s|%s\\n' \"$*\" \"$OPENCODE_MAJOR\" > {}\n",+ launched.display()+ ),+ )+ .unwrap();+ std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();++ let plugins = data.path().join("plugins");+ std::fs::create_dir_all(&plugins).unwrap();+ let plugin = plugins.join("ai-memory-opencode2.ts");+ let mcp = data.path().join("opencode.json");+ let mut config = Config::load(None, Some(home.path().to_path_buf())).unwrap();+ config.data_dir = data.path().to_path_buf();+ config.home_dir = Some(home.path().to_string_lossy().into_owned());+ config.server_url = format!("http://{address}");+ config.run_autowire = true;+ let overrides = WireOverrides {+ hooks_config_file: Some(plugin.clone()),+ mcp_config_file: Some(mcp.clone()),+ ..WireOverrides::default()+ };+ let args = RunArgs {+ workspace: Some("ws".into()),+ project: Some("proj".into()),+ workstream: None,+ new_workstream: None,+ executable: None,++ profile: None,+ yolo: false,+ true_yolo: false,+ jail: None,+ no_jail: false,+ fresh: false,+ force_unlock: false,+ no_autowire: false,+ env: vec![+ ("PATH".into(), executable_dir.display().to_string()),+ ("OPENCODE_MAJOR".into(), "2".into()),+ ],+ env_file: None,+ harness: Some(RunHarnessChoice::OpenCode),+ native_args: vec![OsString::from("--help")],+ };++ let exit = run_from_with_wiring(&config, args, repo.path(), &overrides)+ .await+ .unwrap();+ assert_eq!(exit, 0);+ assert_eq!(+ std::fs::read_to_string(launched).unwrap().trim(),+ "--help|2"+ );+ assert!(+ std::fs::read_to_string(plugin)+ .unwrap()+ .contains("const AiMemoryOpencode2: Plugin.Plugin")+ );+ let mcp: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(mcp).unwrap()).unwrap();+ assert!(mcp["mcp"]["servers"]["ai-memory"].is_object());+ let sentinels = std::fs::read_dir(crate::commands::run_autowire::autowire_state_dir(+ data.path(),+ ))+ .unwrap()+ .count();+ assert_eq!(sentinels, 1);+ server.abort();+ }+/// The `ai-memory run` -> autowire -> child-spawn seam: driving the launcher/// entry point (`run_from_with_wiring`) must run auto-wire *before* the child/// starts, so the harness's ai-memory hooks + MCP are installed and the@@@ -6741,4 -7187,434 +7681,434 @@@drop(seen);server.abort();}++ #[test]+ fn native_identity_run_preflight_refuses_before_resume_or_private_path() {+ let home = tempfile::tempdir().unwrap();+ for id in [+ "sk-abcdefghijklmnopqrstuvwx",+ "native\u{202e}tail",+ "native\u{200b}tail",+ ] {+ let result = build_preflighted_launch_plan(+ ManagedHarness::Codex,+ None,+ Vec::new(),+ Some(id),+ false,+ home.path(),+ home.path(),- &[],++ &EffectiveChildEnv::default(),+ );+ assert!(+ result.is_err(),+ "dirty server identity must be refused before resume"+ );+ assert!(!format!("{:#}", result.unwrap_err()).contains(id));+ }+ assert!(+ build_preflighted_launch_plan(+ ManagedHarness::Claude,+ None,+ Vec::new(),+ Some("sk-abcdefghijklmnopqrstuvwx"),+ true,+ home.path(),+ home.path(),- &[]++ &EffectiveChildEnv::default(),+ )+ .is_err(),+ "fresh mode must validate the original prepared identity before discarding it"+ );+ let (plan, _) = build_preflighted_launch_plan(+ ManagedHarness::Claude,+ None,+ Vec::new(),+ None,+ false,+ home.path(),+ home.path(),- &[],++ &EffectiveChildEnv::default(),+ )+ .unwrap();+ assert!(uuid::Uuid::parse_str(plan.expected_session_id.as_deref().unwrap()).is_ok());+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn native_identity_run_old_server_refusal_prevents_child_and_transport() {+ let (address, server) = mock_workstream_server(Some("private-vendor")).await;+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let repo = tempfile::tempdir().unwrap();+ let (script, captured) = capture_env_script(repo.path(), "AI_MEMORY_MANAGED_RUN");+ let mut config = launch_config(home.path(), data.path(), address);+ config.run_autowire = false;+ config.sanitize.extra_patterns.push("private-vendor".into());+ let result = run_from(+ &config,+ run_args(RunHarnessChoice::Claude, script, Vec::new(), &[]),+ repo.path(),+ )+ .await;+ assert!(+ result.is_err(),+ "old server dirty identity must refuse the actual launch"+ );+ assert!(!captured.exists(), "child must not start");+ assert!(!format!("{:#}", result.unwrap_err()).contains("private-vendor"));+ server.abort();+ }+ #[tokio::test]+ async fn native_identity_finish_transport_refuses_before_request_and_preserves_exact_control() {+ let requests = Arc::new(std::sync::Mutex::new(Vec::<FinishManagedRunRequest>::new()));+ let captured = requests.clone();+ let app = Router::new().route(+ "/workstream/runs/{id}/finish",+ post(+ move |axum::Json(request): axum::Json<FinishManagedRunRequest>| {+ let captured = captured.clone();+ async move {+ captured.lock().unwrap().push(request);+ axum::Json(FinishManagedRunResponse {+ imported_events: 1,+ latest_sequence: 1,+ })+ }+ },+ ),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ let home = tempfile::tempdir().unwrap();+ let config = launch_config(home.path(), home.path(), address);+ let endpoint = ServerEndpoint::from_config_resolving_auth(&config).await;+ let sanitizer = Sanitizer::new(&ai_memory_core::SanitizeConfig {+ extra_patterns: vec!["private-vendor".into()],+ ..Default::default()+ })+ .unwrap();+ let transcript = |id: &str| ExportedTranscript {+ native_session_id: id.into(),+ source_cursor: Some("cursor".into()),+ events: Vec::new(),+ losses: Vec::new(),+ };+ for bad in ["sk-abcdefghijklmnopqrstuvwx", "private-vendor"] {+ assert!(+ import_batches(+ &endpoint,+ "/workstream/runs/test",+ transcript(bad),+ Default::default(),+ Some(0),+ &sanitizer,+ )+ .await+ .is_err(),+ "dirty finish identity must not reach transport"+ );+ assert!(requests.lock().unwrap().is_empty());+ let mut with_event = transcript("vendor-界-01");+ with_event.events.push(ai_memory_core::NewWorkstreamEvent {+ event_id: "e".into(),+ agent: AgentKind::Codex,+ native_session_id: bad.into(),+ source_record_id: None,+ kind: ai_memory_core::WorkstreamEventKind::Message,+ role: None,+ content: "shared history".into(),+ occurred_at: None,+ metadata: serde_json::json!({}),+ });+ assert!(+ import_batches(+ &endpoint,+ "/workstream/runs/test",+ with_event,+ Default::default(),+ Some(0),+ &sanitizer,+ )+ .await+ .is_err(),+ "dirty event identity must not reach transport"+ );+ assert!(requests.lock().unwrap().is_empty());+ }+ assert_eq!(+ import_batches(+ &endpoint,+ "/workstream/runs/test",+ transcript("vendor-界-01"),+ Default::default(),+ Some(0),+ &sanitizer,+ )+ .await+ .unwrap(),+ 1+ );+ assert_eq!(+ requests.lock().unwrap()[0].native_session_id.as_deref(),+ Some("vendor-界-01")+ );+ assert_eq!(+ requests.lock().unwrap()[0].source_cursor.as_deref(),+ Some("cursor")+ );+ server.abort();+ }++ #[tokio::test]+ async fn native_identity_run_status_and_expected_refuse_before_discovery() {+ let home = tempfile::tempdir().unwrap();+ let mut plan = build_launch_plan(ManagedHarness::Codex, None, Vec::new(), None).unwrap();+ plan.session_dir = None;+ let sanitizer = Sanitizer::new(&ai_memory_core::SanitizeConfig {+ extra_patterns: vec!["private-vendor".into()],+ ..Default::default()+ })+ .unwrap();+ for bad in ["sk-abcdefghijklmnopqrstuvwx", "private-vendor"] {+ plan.expected_session_id = Some(bad.into());+ assert!(+ own_native_session(+ &plan,+ ManagedHarness::Codex,+ home.path(),+ home.path(),+ None,+ &sanitizer+ )+ .is_err(),+ "expected identity must refuse before use"+ );+ plan.expected_session_id = None;+ let status = ManagedRunStatus {+ run_id: ManagedRunId::new(),+ workstream_id: WorkstreamId::new(),+ agent: AgentKind::Codex,+ native_session_id: Some(bad.into()),+ native_session_linked: true,+ context_delivered: false,+ state: "active".into(),+ };+ assert!(+ own_native_session(+ &plan,+ ManagedHarness::Codex,+ home.path(),+ home.path(),+ Some(&status),+ &sanitizer,+ )+ .is_err(),+ "linked status must refuse before native IO"+ );+ assert!(+ resolve_native_session_after_run(+ &plan,+ ManagedHarness::Codex,+ home.path(),+ home.path(),+ SystemTime::now(),+ Some(&status),+ &sanitizer,+ )+ .await+ .is_err(),+ "dirty old-server status must not fall back to discovery"+ );+ plan.expected_session_id = Some("vendor-界-01".into());+ assert_eq!(+ own_native_session(+ &plan,+ ManagedHarness::Codex,+ home.path(),+ home.path(),+ None,+ &sanitizer+ )+ .unwrap()+ .as_deref(),+ Some("vendor-界-01")+ );+ }+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn native_identity_run_configured_selector_refuses_before_link_or_child() {+ let (address, server) = mock_workstream_server(None).await;+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let repo = tempfile::tempdir().unwrap();+ let (script, captured) = capture_env_script(repo.path(), "AI_MEMORY_MANAGED_RUN");+ let mut config = launch_config(home.path(), data.path(), address);+ config.run_autowire = false;+ config.sanitize.extra_patterns.push("private-vendor".into());+ let result = run_from(+ &config,+ run_args(+ RunHarnessChoice::Claude,+ script,+ Vec::new(),+ &["--session-id", "private-vendor"],+ ),+ repo.path(),+ )+ .await;+ assert!(+ result.is_err(),+ "configured selector must refuse before link and spawn"+ );+ assert!(!captured.exists());+ assert!(!format!("{:#}", result.unwrap_err()).contains("private-vendor"));+ server.abort();+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn native_identity_run_configured_old_status_refuses_before_native_io_and_finish() {+ for id in ["private-vendor", "vendor-界-01"] {+ let finishes = Arc::new(std::sync::Mutex::new(Vec::<FinishManagedRunRequest>::new()));+ let captured_finishes = finishes.clone();+ let app = Router::new()+ .route(+ "/workstream/runs",+ post(|| async {+ axum::Json(PrepareManagedRunResponse {+ workstream_id: WorkstreamId::new(),+ workstream_name: "default".into(),+ run_id: ManagedRunId::new(),+ resolved_agent: None,+ native_session_id: None,+ source_cursor: None,+ sync_after: 0,+ sync_through: 0,+ may_adopt_existing_session: false,+ manifest_warning: None,+ })+ }),+ )+ .route(+ "/workstream/runs/{id}",+ axum::routing::get(move || async move {+ axum::Json(ManagedRunStatus {+ run_id: ManagedRunId::new(),+ workstream_id: WorkstreamId::new(),+ agent: AgentKind::Codex,+ native_session_id: Some(id.into()),+ native_session_linked: false,+ context_delivered: false,+ state: "active".into(),+ })+ }),+ )+ .route(+ "/workstream/runs/{id}/finish",+ post(+ move |axum::Json(request): axum::Json<FinishManagedRunRequest>| {+ let captured_finishes = captured_finishes.clone();+ async move {+ captured_finishes.lock().unwrap().push(request);+ axum::Json(FinishManagedRunResponse {+ imported_events: 0,+ latest_sequence: 0,+ })+ }+ },+ ),+ )+ .route(+ "/workstream/runs/{id}/cancel",+ post(|| async { StatusCode::NO_CONTENT }),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ let home = tempfile::tempdir().unwrap();+ let repo = tempfile::tempdir().unwrap();+ let (script, child_capture) = capture_env_script(repo.path(), "AI_MEMORY_MANAGED_RUN");+ let mut config = launch_config(home.path(), home.path(), address);+ config.run_autowire = false;+ config.sanitize.extra_patterns.push("private-vendor".into());+ let result = run_from(+ &config,+ run_args(RunHarnessChoice::Codex, script, Vec::new(), &[]),+ repo.path(),+ )+ .await;+ assert!(+ child_capture.exists(),+ "the status is returned after the child exits"+ );+ if id == "private-vendor" {+ assert!(+ result.is_err(),+ "configured old status must refuse before native IO and finish"+ );+ assert!(!format!("{:#}", result.unwrap_err()).contains(id));+ assert!(finishes.lock().unwrap().is_empty());+ } else {+ assert_eq!(result.unwrap(), 0);+ assert_eq!(+ finishes.lock().unwrap()[0].native_session_id.as_deref(),+ Some(id)+ );+ }+ server.abort();+ }+ }++ #[tokio::test]+ async fn native_identity_run_configured_discovery_refuses_before_export() {+ let sanitizer = Sanitizer::new(&ai_memory_core::SanitizeConfig {+ extra_patterns: vec!["private-vendor".into()],+ ..Default::default()+ })+ .unwrap();+ for id in ["private-vendor", "vendor-界-01"] {+ let home = tempfile::tempdir().unwrap();+ let cwd = home.path().join("repo");+ let root = home.path().join(".codex/sessions/2026/01/01");+ std::fs::create_dir_all(&cwd).unwrap();+ std::fs::create_dir_all(&root).unwrap();+ let started_at = SystemTime::now();+ std::fs::write(+ root.join("rollout-current.jsonl"),+ format!(+ "{}\n",+ serde_json::json!({+ "type": "session_meta", "payload": {"id": id, "cwd": cwd}+ })+ ),+ )+ .unwrap();+ let mut plan =+ build_launch_plan(ManagedHarness::Codex, None, Vec::new(), None).unwrap();+ plan.session_dir = None;+ let result = resolve_native_session_after_run(+ &plan,+ ManagedHarness::Codex,+ home.path(),+ &cwd,+ started_at,+ None,+ &sanitizer,+ )+ .await;+ if id == "private-vendor" {+ assert!(+ result.is_err(),+ "configured discovered identity must refuse before export"+ );+ assert!(!format!("{:#}", result.unwrap_err()).contains(id));+ } else {+ assert_eq!(result.unwrap().as_deref(), Some(id));+ }+ }+ }}diff --cc crates/ai-memory-cli/src/commands/run_autowire.rsindex d2bf0cc3,9ae08f1e..10981bdb--- a/crates/ai-memory-cli/src/commands/run_autowire.rs+++ b/crates/ai-memory-cli/src/commands/run_autowire.rs@@@ -173,48 -169,35 +173,64 @@@ struct WireTargets/// the installer's own check (which reads ai-memory's environment) would/// miss it.shared_extensions_dir: Option<PathBuf>,+ /// A `--scope project` Claude Code install covering the launch directory;+ /// hooks are not wired user-level on top of it.+ project_hooks: Option<PathBuf>,}+#[cfg(test)]fn wire_targets(config: &Config,harness: ManagedHarness,overrides: &WireOverrides,run_env: &[(String, String)],+ launch_cwd: &Path,+) -> Option<WireTargets> {+ let effective_env = super::run::EffectiveChildEnv::with_overrides(&config.runtime_env, run_env);- wire_targets_with_env(config, harness, overrides, run_env, &effective_env)++ wire_targets_with_env(++ config,++ harness,++ overrides,++ run_env,++ &effective_env,++ launch_cwd,++ )+}++fn wire_targets_with_env(+ config: &Config,+ harness: ManagedHarness,+ overrides: &WireOverrides,+ run_env: &[(String, String)],+ effective_env: &super::run::EffectiveChildEnv,++ launch_cwd: &Path,) -> Option<WireTargets> {let agent = agent_choice_for_harness(harness)?;+ let opencode_dialect = match harness {+ ManagedHarness::OpenCode => Some(OpenCodeDialect::V1),+ ManagedHarness::OpenCode2 => Some(OpenCodeDialect::V2),+ _ => None,+ };+ let project_hooks = project_scoped_claude_hooks(agent, launch_cwd);- let hook_env = LaunchEnv::new(run_env);+ let hook_env = LaunchEnv::new(effective_env, run_env);let hook_target = install_hooks::hook_config_target_with(agent, &|name| hook_env.var_os(name));let mcp_client = install_hooks::mcp_client_for_agent(agent);- let mcp_env = LaunchEnv::new(run_env);+ let mcp_env = LaunchEnv::new(effective_env, run_env);let mcp_target = mcp_client.map(|client| install_mcp::mcp_config_path_with(client, &|name| mcp_env.var_os(name)));let sentinel = sentinel_path(&config.data_dir,agent,&[+ opencode_dialect.map_or_else(+ || "dialect:default".to_string(),+ |dialect| format!("opencode-major:{}", dialect.major()),+ ),target_key(overrides.hooks_config_file.as_deref(), Some(&hook_target)),target_key(overrides.mcp_config_file.as_deref(), mcp_target.as_ref()),+ project_hooks+ .as_deref()+ .map_or_else(|| "none".to_string(), |path| path.display().to_string()),],);let shared_extensions_dir = match (&overrides.hooks_config_file, &hook_target) {@@@ -406,26 -385,18 +424,45 @@@ fn wire_installs(config: &Config, targe/// Production launches pass [`WireOverrides::default()`] (via/// [`run_from`](super::run::run_from)); the overrides exist only so the seam can/// be exercised without writing to the developer's real `$HOME`.+ ///+ /// `launch_cwd` is the directory the harness is launched in — a `resume` may+ /// launch into a checkout other than the shell's — and is where a+ /// `--scope project` Claude Code install is looked for.+#[cfg(test)]pub(crate) fn ensure_wired_with(config: &Config,harness: ManagedHarness,overrides: &WireOverrides,run_env: &[(String, String)],+ launch_cwd: &Path,) {- let Some(targets) = wire_targets(config, harness, overrides, run_env, launch_cwd) else {+ let effective_env = super::run::EffectiveChildEnv::with_overrides(&config.runtime_env, run_env);- ensure_wired_with_env(config, harness, overrides, run_env, &effective_env);++ ensure_wired_with_env(++ config,++ harness,++ overrides,++ run_env,++ &effective_env,++ launch_cwd,++ );+}++pub(crate) fn ensure_wired_with_env(+ config: &Config,+ harness: ManagedHarness,+ overrides: &WireOverrides,+ run_env: &[(String, String)],+ effective_env: &super::run::EffectiveChildEnv,++ launch_cwd: &Path,+) {- let Some(targets) = wire_targets_with_env(config, harness, overrides, run_env, effective_env)- else {++ let Some(targets) = wire_targets_with_env(++ config,++ harness,++ overrides,++ run_env,++ effective_env,++ launch_cwd,++ ) else {return;};if targets.sentinel.exists() {@@@ -573,83 -668,6 +751,109 @@@ mod tests);}+ #[test]+ fn opencode_major_transition_changes_the_autowire_sentinel() {+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let config = test_config(home.path(), data.path());+ let overrides = WireOverrides::default();- let v1 = wire_targets(&config, ManagedHarness::OpenCode, &overrides, &[]).unwrap();- let v2 = wire_targets(&config, ManagedHarness::OpenCode2, &overrides, &[]).unwrap();++ let v1 = wire_targets(++ &config,++ ManagedHarness::OpenCode,++ &overrides,++ &[],++ &config.data_dir,++ )++ .unwrap();++ let v2 = wire_targets(++ &config,++ ManagedHarness::OpenCode2,++ &overrides,++ &[],++ &config.data_dir,++ )++ .unwrap();+ assert_ne!(v1.sentinel, v2.sentinel);+ }++ #[test]+ fn opencode_autowire_migrates_mcp_before_hooks_infer_transition_settings() {+ let data = tempfile::tempdir().unwrap();+ let plugin = data.path().join("plugins/ai-memory-opencode2.ts");+ let mcp = data.path().join("opencode.json");+ std::fs::write(+ &mcp,+ r#"{"mcp":{"ai-memory":{"type":"remote","url":"http://transition-host:49374/mcp","enabled":true,"headers":{"Authorization":"Bearer transition-token"}}}}"#,+ )+ .unwrap();+ let config = Config {+ data_dir: data.path().join("data"),+ run_autowire: true,+ ..Config::default()+ };+ let overrides = WireOverrides {+ hooks_config_file: Some(plugin.clone()),+ mcp_config_file: Some(mcp.clone()),+ ..WireOverrides::default()+ };+- ensure_wired_with(&config, ManagedHarness::OpenCode2, &overrides, &[]);++ ensure_wired_with(++ &config,++ ManagedHarness::OpenCode2,++ &overrides,++ &[],++ &config.data_dir,++ );++ let mcp: serde_json::Value =+ serde_json::from_str(&std::fs::read_to_string(mcp).unwrap()).unwrap();+ assert!(mcp.pointer("/mcp/ai-memory").is_none());+ assert_eq!(+ mcp.pointer("/mcp/servers/ai-memory/url"),+ Some(&serde_json::json!("http://transition-host:49374/mcp"))+ );+ assert!(+ std::fs::read_to_string(plugin)+ .unwrap()+ .contains("http://transition-host:49374")+ );+ assert_eq!(+ crate::config::read_hook_auth_token(&config.data_dir).as_deref(),+ Some("transition-token")+ );+ }++ #[test]+ fn opencode_autowire_does_not_write_hooks_when_mcp_transition_conflicts() {+ let data = tempfile::tempdir().unwrap();+ let plugin = data.path().join("plugins/ai-memory-opencode2.ts");+ let mcp = data.path().join("opencode.json");+ let initial = r#"{"mcp":{"ai-memory":{"type":"remote","url":"http://v1-host:49374/mcp","enabled":true},"servers":{"ai-memory":{"type":"remote","url":"http://v2-host:49374/mcp","oauth":false}}}}"#;+ std::fs::write(&mcp, initial).unwrap();+ let config = Config {+ data_dir: data.path().join("data"),+ run_autowire: true,+ ..Config::default()+ };+ let overrides = WireOverrides {+ hooks_config_file: Some(plugin.clone()),+ mcp_config_file: Some(mcp.clone()),+ ..WireOverrides::default()+ };+- ensure_wired_with(&config, ManagedHarness::OpenCode2, &overrides, &[]);++ ensure_wired_with(++ &config,++ ManagedHarness::OpenCode2,++ &overrides,++ &[],++ &config.data_dir,++ );++ assert!(!plugin.exists());+ assert_eq!(std::fs::read_to_string(mcp).unwrap(), initial);+ assert!(crate::config::read_hook_auth_token(&config.data_dir).is_none());+ }+#[test]fn sentinel_keys_on_agent_version_and_install_targets() {let dir = Path::new("/data");diff --cc crates/ai-memory-cli/src/commands/setup_agent.rsindex b1ad0fc6,61e5ca30..757d6f0e--- a/crates/ai-memory-cli/src/commands/setup_agent.rs+++ b/crates/ai-memory-cli/src/commands/setup_agent.rs@@@ -36,14 -36,14 +36,16 @@@ use std::path::{Path, PathBuf}use anyhow::{Context, Result, bail};- use crate::cli::{AgentChoice, InstallHooksArgs, InstallMcpArgs, McpClient, SetupAgentArgs};-use crate::cli::{AgentChoice, SetupAgentArgs};-use crate::commands::install_mcp;++use crate::cli::{++ AgentChoice, HookInstallScope, InstallHooksArgs, InstallMcpArgs, McpClient, SetupAgentArgs,++};use crate::commands::render_shared::{ANTIGRAVITY_LIFECYCLE_EVENTS, ANTIGRAVITY_TOOL_EVENTS, CODEX_PROFILE, COMMAND_CODE_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, build_pool_settings_yaml,- hook_script_for_current_platform,+ COPILOT_CLI_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,+ build_pool_settings_yaml, hook_script_for_current_platform,};+use crate::commands::{install_hooks, install_mcp};use crate::config::{Config, DEFAULT_SERVER_URL};/// Run the `setup-agent` subcommand.@@@ -345,49 -330,6 +350,50 @@@ fn emit_extension_setup_hint(config: &C"# Legacy shell/PowerShell and remote-only paths are unsupported compatibility modes.");println!("# Install it directly instead:");+ if matches!(args.agent, AgentChoice::OpenCode | AgentChoice::OpenCode2) {+ let dialect = if args.agent == AgentChoice::OpenCode {+ ai_memory_workstream::OpenCodeDialect::V1+ } else {+ ai_memory_workstream::OpenCodeDialect::V2+ };+ install_hooks::run_with_opencode_dialect(+ config,+ InstallHooksArgs {+ agent: AgentChoice::OpenCode,+ hooks_dir: None,+ server_url: Some(args.server_url.clone()),+ auth_token: args.auth_token.clone(),+ as_user: None,+ apply: false,+ config_file: None,++ scope: HookInstallScope::Global,+ project_strategy: None,+ capture_assistant: false,+ capture_mode: None,+ no_capture_prompts: false,+ capture_prompts: false,+ profile: None,+ },+ Some(dialect),+ )?;+ install_mcp::run_with_opencode_dialect(+ config,+ InstallMcpArgs {+ client: McpClient::OpenCode,+ server_url: Some(args.server_url.clone()),+ name: "ai-memory".to_string(),+ auth_token: args.auth_token.clone(),+ apply: false,+ config_file: None,+ session_aware: false,+ flavor: None,+ },+ Some(dialect),+ )?;+ println!();+ println!("{restart_note}");+ return Ok(());+ }println!("ai-memory install-hooks --agent {agent} --apply \\");if args.auth_token.is_some() {println!(" --server-url {} \\", args.server_url);diff --cc crates/ai-memory-cli/src/config.rsindex e734ada0,899264b8..077b0804--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@@ -6,7 -6,7 +6,8 @@@//! guard read `process.env` while the rest of the codebase used//! `getMergedEnv()`, masking the bug for weeks).+ use std::collections::{BTreeMap, HashSet};+use std::ffi::OsString;use std::path::{Path, PathBuf};use std::sync::Arc;@@@ -645,7 -654,7 +667,8 @@@ pub struct RuntimeEnvscope_cwd: Option<String>,ignore_marker: bool,project_strategy: Option<String>,+ process_env: CapturedProcessEnv,+ capture_owner_active: bool,claude_code_session_id: Option<String>,anthropic_api_key: Option<SecretString>,anthropic_oauth_token: Option<SecretString>,@@@ -663,9 -673,8 +687,9 @@@}impl RuntimeEnv {- fn from_process() -> Self {+ pub(crate) fn from_process() -> Self {let platform_home = dirs::home_dir();+ let process_env = CapturedProcessEnv(std::env::vars_os().collect());Self {data_dir: env_path("AI_MEMORY_DATA_DIR"),home_dir: resolve_operator_home(@@@ -689,7 -698,8 +713,9 @@@// --project-strategy` bakes into the generated hook commands.// Consulted only when a marker does not pin one.project_strategy: env_string("AI_MEMORY_PROJECT_STRATEGY"),+ process_env,+ capture_owner_active: env_string("AI_MEMORY_CAPTURE_OWNER")+ .is_some_and(|value| !value.trim().is_empty()),claude_code_session_id: env_string("CLAUDE_CODE_SESSION_ID"),anthropic_api_key: env_secret("ANTHROPIC_API_KEY"),// CLAUDE_CODE_OAUTH_TOKEN is what `claude setup-token` writes;@@@ -748,12 -765,12 +781,18 @@@self.project_strategy.as_deref()}+ /// Complete process environment captured by the single config-read path.+ #[must_use]+ pub fn process_env(&self) -> &[(OsString, OsString)] {+ &self.process_env.0+ }++ /// Whether this invocation delegates native capture to an external producer.+ #[must_use]+ pub fn capture_owner_active(&self) -> bool {+ self.capture_owner_active+ }+/// Claude Code lifecycle session id inherited by an stdio MCP subprocess.#[must_use]pub fn claude_code_session_id(&self) -> Option<&str> {diff --cc crates/ai-memory-cli/tests/suite/main.rsindex e79f56a0,5797a898..a7283522--- a/crates/ai-memory-cli/tests/suite/main.rs+++ b/crates/ai-memory-cli/tests/suite/main.rs@@@ -21,8 -22,8 +22,9 @@@ mod hook_payloadmod jail_toggles_e2e;mod marker_scope;mod message_e2e;+mod opencode_dialect;mod packaging;+ mod profile_e2e;mod removal;mod repo_layout;mod routing_instructions;diff --cc crates/ai-memory-wiki/src/wiki.rsindex 4c77d760,0d413d32..c9f02297--- a/crates/ai-memory-wiki/src/wiki.rs+++ b/crates/ai-memory-wiki/src/wiki.rs@@@ -693,26 -670,19 +693,27 @@@ impl Wikireturn;}};- let ws_dir = self.root.join(workspace_id.to_string());+ let ws_dir = match workspace_path(&self.root, workspace_id, Prepare::Directory) {+ Ok(path) => path,+ Err(error) => {+ tracing::warn!(%error, "scope-manifest path confinement failed (non-fatal)");+ return;+ }+ };- let mut project_fm = serde_json::json!({ "project": scope.project_name });- if let Some(repo_path) = scope.repo_path {- project_fm["repo_path"] = serde_json::Value::String(repo_path);- }+ let workspace_name = scope.workspace_name.clone();+ let project_fm = match Self::project_scope_frontmatter(scope) {+ Ok(frontmatter) => frontmatter,+ Err(e) => {+ tracing::warn!(error = %e, "scope-manifest identity is invalid (non-fatal)");+ return;+ }+ };let written = self- .write_scope_manifest(- &ws_dir,- serde_json::json!({ "workspace": scope.workspace_name }),- )+ .write_scope_manifest(&ws_dir, serde_json::json!({ "workspace": workspace_name })).and_then(|_| {- self.write_scope_manifest(&ws_dir.join(project_id.to_string()), project_fm)+ let project_dir =+ self.confined_project_root(workspace_id, project_id, Prepare::Directory)?;+ self.write_scope_manifest(&project_dir, project_fm)});match written {Ok(_) => {@@@ -2182,12 -2162,9 +2304,9 @@@}}for s in scopes {- let ws_dir = self.root().join(s.workspace_id.to_string());- let project_dir = ws_dir.join(s.project_id.to_string());+ let project_dir =+ self.confined_project_root(s.workspace_id, s.project_id, Prepare::Directory)?;- let mut fm = serde_json::json!({ "project": s.project_name });- if let Some(rp) = s.repo_path {- fm["repo_path"] = serde_json::Value::String(rp);- }+ let fm = Self::project_scope_frontmatter(s)?;if self.write_scope_manifest(&project_dir, fm)? {written += 1;}diff --cc crates/ai-memory-workstream/src/harness.rsindex 55b69c3a,f9eecebf..5244075b--- a/crates/ai-memory-workstream/src/harness.rs+++ b/crates/ai-memory-workstream/src/harness.rs@@@ -1842,35 -1737,30 +1862,59 @@@ mod tests));}+ #[test]+ fn opencode_version_parser_accepts_strict_and_decorated_versions() {+ for (output, expected) in [+ ("1.18.34", OpenCodeDialect::V1),+ ("v2.0.23", OpenCodeDialect::V2),+ ("OpenCode v2.0.23 (build abc)", OpenCodeDialect::V2),+ ("opencode 1.18.34-beta.1", OpenCodeDialect::V1),+ ] {+ assert_eq!(+ OpenCodeDialect::parse_version_output(output).unwrap(),+ expected+ );+ }+ }++ #[test]+ fn opencode_version_parser_rejects_malformed_and_unsupported_versions() {+ for output in ["2", "2.0", "latest", "version 2.x", "1.2.3 2.0.0"] {+ assert!(+ OpenCodeDialect::parse_version_output(output).is_err(),+ "{output}"+ );+ }+ let error = OpenCodeDialect::parse_version_output("3.0.0")+ .unwrap_err()+ .to_string();+ assert!(error.contains("major 3 is not supported"), "{error}");+ }++ #[test]+ fn post_run_prompt_is_limited_to_interactive_session_invocations() {+ assert!(is_interactive_session_invocation(+ ManagedHarness::Codex,+ &[OsString::from("resume"), OsString::from("chosen")]+ ));+ assert!(!is_interactive_session_invocation(+ ManagedHarness::Codex,+ &[OsString::from("exec"), OsString::from("continue here")]+ ));+ assert!(!is_interactive_session_invocation(+ ManagedHarness::Claude,+ &[OsString::from("--print"), OsString::from("continue here")]+ ));+ assert!(!is_interactive_session_invocation(+ ManagedHarness::Pi,+ &[OsString::from("--no-session")]+ ));+ assert!(is_interactive_session_invocation(+ ManagedHarness::Claude,+ &[OsString::from("--model"), OsString::from("opus")]+ ));+ }+#[test]fn opencode2_shares_v1_session_contract_with_its_own_binary() {for name in ["opencode2", "opencode-v2", "open-code2"] {diff --cc crates/ai-memory-workstream/src/lib.rsindex fa2f2318,bb1c6691..e00ad78f--- a/crates/ai-memory-workstream/src/lib.rs+++ b/crates/ai-memory-workstream/src/lib.rs@@@ -6,13 -6,12 +6,13 @@@ mod repositorymod transcript;pub use harness::{- LaunchMode, LaunchPlan, LaunchRoots, ManagedHarness, allows_native_session_adoption,- apply_claude_true_yolo, apply_yolo, build_launch_plan, build_launch_plan_with_env, clean_path,- crush_data_dir, crush_global_config_path, env_dir_override, has_native_session_selector,+ LaunchMode, LaunchPlan, LaunchRoots, ManagedHarness, OpenCodeDialect,+ allows_native_session_adoption, apply_claude_true_yolo, apply_yolo, build_launch_plan,+ build_launch_plan_with_env, build_launch_plan_with_env_lookup, clean_path, crush_data_dir,+ crush_global_config_path, env_dir_override, has_native_session_selector,- kiro_explicit_session_id, kiro_selects_non_default_engine, kiro_selects_v2_engine,- kiro_selects_v3_engine, omp_agent_dir, omp_profile_flag, omp_profile_flag_env,- store_override_vars,+ is_interactive_session_invocation, kiro_explicit_session_id, kiro_selects_non_default_engine,+ kiro_selects_v2_engine, kiro_selects_v3_engine, omp_agent_dir, omp_profile_flag,+ omp_profile_flag_env, store_override_vars,};pub use jail::{FORWARDED_ENV_NAMES, JAIL_TOGGLES, JailChecklistItem, JailEnv, JailHostFacts, JailOs,diff --cc docs/security-boundaries.mdindex 9af5c3d6,b42cb1b3..9ed7beff--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@@ -55,15 -63,16 +64,17 @@@ boundary not yet built| 10d | Workspace delete's own row counts are scope-bound to `workspace_id` (a workspace's *own* rows are never over- or under-counted by a sibling workspace's), its cross-workspace observation/handoff cascade is reported by both preview and confirm rather than prevented (same as `purge-project` one level down), the non-empty guard fails closed without `force`, and `delete-workspace`'s `dry_run` always wins | `ai-memory-store/src/ops.rs` `delete_workspace` — every direct count and the `DELETE FROM workspaces` itself are scoped by `workspace_id = ?1`; the two `collateral_*` counts are scoped by `workspace_id != ?1` so a row is counted as one or the other but never both; `projects_deleted > 0 && !force → WorkspaceNotEmpty` fail-closed, and a missing workspace is `NotFound`, both checked identically under `PurgeMode::Preview` and `PurgeMode::Commit`; whole op in one transaction; `admin.rs` `handle_delete_workspace` checks `req.dry_run` unconditionally, before building the confirmed path, mirroring `reclaim-ledger-versions`/`purge-project`; root-only gate is the shared `/admin/*` multi-user auth ladder, not a separate check | `admin_move.rs` `delete_workspace_dry_run_never_counts_a_different_workspaces_rows` — previewing workspace A counts only its own project/page/session/observation/handoff rows, not workspace B's (which holds two like-named projects and its own full row set), and a session living in B that stamps an observation directly into A is counted in A's own `observations_deleted`, never in `collateral_observations_deleted` (the two counts are mutually exclusive by construction); `admin_move.rs` `delete_workspace_force_true_and_dry_run_true_still_only_previews` — `{"force": true, "dry_run": true}` deletes nothing; `ops.rs` `delete_workspace_dry_run_changes_nothing` — every table's row count, including `workspaces` itself and the `purged_scopes` tombstone (the two tables a confirmed delete's own transaction writes to), is identical before/after a `PurgeMode::Preview` run; `ops.rs` `delete_workspace_dry_run_and_confirmed_delete_both_report_collateral_damage_in_another_workspace` and `admin_move.rs` of the same name — deleting workspace W collaterally deletes an observation, and orphans a handoff's session reference, in a *different* workspace (via `sessions` cascading out of W), and both the preview and the confirmed response count it identically — the cascade itself is reported, not blocked, by either; `admin_move.rs` `delete_workspace_dry_run_refuses_non_empty_without_force` / `delete_workspace_dry_run_nonexistent_workspace_returns_404` — same `409`/`404` a confirmed delete would give; `admin.rs` `multiuser_delete_workspace_dry_run_rejects_db_user_and_anonymous` — root reaches the preview handler (404 control), DB user gets 403, anonymous gets 401 | STRONG || 10e | Reconcile-tombstone of a disk-deleted page is opt-in, soft, scope-bound, and false-positive-guarded (invariant #16, #929 delete-half) | `ai-memory-wiki/src/watcher.rs` — off by default (`[maintenance] reconcile_tombstones_deleted_pages`); a page is tombstoned only after its file is observed missing on two consecutive passes (streak resets if the path's `PageId` changed), re-verified against the live filesystem immediately before acting, with reserved/indexed-but-unwalked paths (`bootstrap.md`, `_meta.md`, `_pending/`, `sessions/*.md`) excluded and a circuit breaker that skips a whole scope when `> max(3, 50%)` of its pages look missing or a non-partial walk finds nothing; `ai-memory-store/src/ops.rs` `soft_delete_for_reconcile_if_latest` is a soft tombstone (`is_latest=0` + `superseded_at`, decay's shape) through the single writer actor in one transaction — never a filesystem write — scoped to the page's own `(workspace_id, project_id)` | `watcher.rs` `reconcile_delete_disabled_by_default_never_tombstones_a_missing_page`, `reconcile_delete_cross_project_isolation` (project A's deletion never tombstones project B's same-path page), `reconcile_tombstone_refuses_a_stale_latest_id`, `reconcile_tombstone_refuses_when_the_file_still_exists`, `reconcile_tombstone_never_touches_the_filesystem`; `ops.rs` `reconcile_tombstone_resurrects_instead_of_orphaning_on_recreate` | STRONG || 10f | Session-time repair is scope-bound (no cross-project timestamp rewrite) | `ai-memory-store/src/ops.rs` `repair_session_times` — every candidate is read back and updated with `WHERE id=? AND workspace_id=? AND project_id=?`; a row outside that 3-tuple is reported `NotFound` and untouched, same code path as an id that does not exist at all; `ai-memory-mcp/src/admin.rs` `handle_repair_session_times` passes the caller's `(workspace, project)` straight through, never the candidate's own | `ops.rs` `repair_session_times_does_not_touch_a_session_of_another_project` (control: sibling session in-scope repaired in the same batch); `admin_repair_session_times.rs` `cross_project_session_is_not_found_and_untouched`; both bite-checked by dropping the `project_id` filter | STRONG |- | 11a | Hook backpressure (202/429) + bounded fan-out (invariant #5) | `ai-memory-hooks/src/router.rs` semaphore→429, 202 immediately, `MAX_HOOK_BATCH_ITEMS`, bounded LRU limiter | `router.rs` `handle_hook_returns_429_when_ingest_saturated`, `ingest_rate_limiter_is_bounded` | STRONG |- | 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn), including shell commands whose arguments name an ignored path (`match_command`; argv elements matched whole and tokenized); an invalid marker makes file and shell calls metadata-only, and the server admits a metadata-only shell body only under an invalid marker (`router.rs` `metadata_protocol_is_legal`); generated OpenCode/OMP/Pi/OpenClaw integrations mirror it in `render_shared.rs` `ts_capture_policy_v1` (`captureMatchCommand`). Candidate/argument flavor (`Flavor::Posix` vs `Flavor::Windows`, used to pick which `ignore_paths` patterns even apply) is derived from the **host** (the cwd), never from the candidate string alone — a POSIX-host candidate spelled with a leading `//` is collapsed to a single `/` before flavor detection (`normalize_candidate`; TS `captureNormalize`'s `windowsHost` parameter, sourced from `captureHostWindows(cwd)`), fixing GHSA-vh98 (a `//`-prefixed candidate used to self-classify as `Flavor::Windows` regardless of host, matching zero POSIX patterns and being captured instead of dropped); a genuine Windows/UNC host (cwd itself windows-flavored) is unaffected | `capture_policy.rs` per-agent `…honors_exclusions` tests, `shell_fixture_vectors` (shared `capture-policy.json` `shell` drop/keep vectors: tool aliases incl. OpenClaw/Devin `exec`, `workdir`, glob directories, Windows paths, and a POSIX-host leading-`//` command via `/{root}/docs/adr/x.md`), `shell_tool_shapes_of_every_adapter_honor_exclusions`, `fixture_vectors` (incl. TS-adapter `bash`/`exec` vectors, and `normalization`'s leading-`//` POSIX vectors alongside the kept Windows-cwd UNC vectors as the no-regression control); `shell_matching_is_off_when_inactive_and_fails_closed_when_invalid_or_over_budget`; `router.rs` `capture_protocol_shell_decisions_survive_server_reinspection`, `capture_protocol_invalid_marker_shell_is_metadata_only` (active metadata-only shell refused, older client's invalid-marker keep stripped, commandless control kept), `capture_protocol_unparseable_marker_strips_shell_events` (server fallback for an unparseable marker), `capture_protocol_invalid_shell_metadata_claim_must_be_canonical` (a stripped shell claim with a path count or non-`extracted` state is refused); `capture_policy.rs` `invalid_marker_strips_shell_calls_with_unparseable_commands`, `long_bash_lc_script_in_argv_is_not_dropped_by_the_match_budget`, **`a_leading_double_slash_candidate_does_not_escape_posix_ignore_paths_via_flavor_mismatch`** (GHSA-vh98 adversarial: attempts the `//repo/secret/...` violation on a POSIX host, proves it now drops, with a plain-single-slash control and a Windows-hosted genuine-UNC control both still correct — fails on the pre-fix code); `hook.rs` `shell_command_reading_an_ignored_path_is_dropped_before_spool`; `render_shared.rs` `generated_capture_policy_v1_node_runtime_evidence` (runs the same fixture sections, including the GHSA-vh98 vectors, against the emitted TypeScript; `#[ignore]` locally, run with `--ignored` under Node 24 by the Linux CI test job) | STRONG |- | 11h | Docker-wrapper capture-policy capability (#1002) | `bin/ai-memory` routes ordinary Linux/macOS `install-hooks` and upgrade refreshes through the stable checksum-verified native host client, so the hook process executes the capture-policy boundary in 11b before spool/network. Only an explicit `AI_MEMORY_HOOK_PLATFORM=posix|windows` retains the documented script compatibility path and its warning; `AI_MEMORY_NATIVE_BIN` may not point back to the wrapper | `scripts/check-native-packaging.sh` `Checking host-launch wrapper routing`: a default allowlist install reaches the fake native client while a Docker executable that always fails proves no container fallback occurred; the explicit `posix` control reaches fake Docker and adds no native invocation; the self-referential native override is refused | STRONG on the shipped Linux/macOS wrapper. Windows and remote/manual script installers remain explicitly outside capture-policy v1 |+ | 11a | Hook backpressure (202/429) + bounded fan-out (invariant #5) | `ai-memory-hooks/src/router.rs` semaphore→429, 202 immediately, `MAX_HOOK_BATCH_ITEMS`, bounded LRU limiter; batch acknowledgements retain only processed indices and classify terminal drops without consuming capacity | `router.rs` `handle_hook_returns_429_when_ingest_saturated`, `ingest_rate_limiter_is_bounded`; `router.rs` `handle_hook_batch_skips_rate_limited_first_item_and_accepts_later_source`, `handle_hook_batch_reports_failed_index_after_rate_limited_skip`, `handle_hook_batch_drops_subagent_events_before_capacity_check` (each asserts result indices and includes an accepted control) | STRONG |+ | 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn), including shell commands whose arguments name an ignored path (`match_command`; argv elements matched whole and tokenized); an invalid marker makes file and shell calls metadata-only, and the server admits a metadata-only shell body only under an invalid marker (`router.rs` `metadata_protocol_is_legal`); generated OpenCode/OMP/Pi/OpenClaw integrations mirror it in `render_shared.rs` `ts_capture_policy_v1` (`captureMatchCommand`). Candidate/argument flavor (`Flavor::Posix` vs `Flavor::Windows`, used to pick which `ignore_paths` patterns even apply) is derived from the **host** (the cwd), never from the candidate string alone — a POSIX-host candidate spelled with a leading `//` is collapsed to a single `/` before flavor detection (`normalize_candidate`; TS `captureNormalize`'s `windowsHost` parameter, sourced from `captureHostWindows(cwd)`), fixing GHSA-vh98 (a `//`-prefixed candidate used to self-classify as `Flavor::Windows` regardless of host, matching zero POSIX patterns and being captured instead of dropped); a genuine Windows/UNC host (cwd itself windows-flavored) is unaffected; `hook.rs` `--check-capture` preflight uses the same capture policy before any spool or spawn | `capture_policy.rs` per-agent `…honors_exclusions` tests, `shell_fixture_vectors` (shared `capture-policy.json` `shell` drop/keep vectors: tool aliases incl. OpenClaw/Devin `exec`, `workdir`, glob directories, Windows paths, and a POSIX-host leading-`//` command via `/{root}/docs/adr/x.md`), `shell_tool_shapes_of_every_adapter_honor_exclusions`, `fixture_vectors` (incl. TS-adapter `bash`/`exec` vectors, and `normalization`'s leading-`//` POSIX vectors alongside the kept Windows-cwd UNC vectors as the no-regression control); `shell_matching_is_off_when_inactive_and_fails_closed_when_invalid_or_over_budget`; `router.rs` `capture_protocol_shell_decisions_survive_server_reinspection`, `capture_protocol_invalid_marker_shell_is_metadata_only` (active metadata-only shell refused, older client's invalid-marker keep stripped, commandless control kept), `capture_protocol_unparseable_marker_strips_shell_events` (server fallback for an unparseable marker), `capture_protocol_invalid_shell_metadata_claim_must_be_canonical` (a stripped shell claim with a path count or non-`extracted` state is refused); `capture_policy.rs` `invalid_marker_strips_shell_calls_with_unparseable_commands`, `long_bash_lc_script_in_argv_is_not_dropped_by_the_match_budget`, **`a_leading_double_slash_candidate_does_not_escape_posix_ignore_paths_via_flavor_mismatch`** (GHSA-vh98 adversarial: attempts the `//repo/secret/...` violation on a POSIX host, proves it now drops, with a plain-single-slash control and a Windows-hosted genuine-UNC control both still correct — fails on the pre-fix code); `hook.rs` `shell_command_reading_an_ignored_path_is_dropped_before_spool`; `render_shared.rs` `generated_capture_policy_v1_node_runtime_evidence` (runs the same fixture sections, including the GHSA-vh98 vectors, against the emitted TypeScript; `#[ignore]` locally, run with `--ignored` under Node 24 by the Linux CI test job); `hook.rs` `check_capture_refuses_partial_scope_and_excluded_content` (ignored-path and partial-scope violations refused, complete public-path control passes), `check_capture_bounds_marker_hints_and_refuses_oversized_scope` (513-byte hints refused, 512-byte control passes; native routing preserved) | STRONG || 11c | Capture hook ≤200ms budget (invariant #5) | `hooks/_lib.sh` capture path `curl --max-time 0.2` (context-fetch 1.0s and background drain 2.0s are separate, larger-budget paths) | none (shell-script timeout; hard to unit-test) — watch on any capture-path change | WATCH |- | 11d | Hook server-profile routing: a marker-selected server gets only its own capture and its own token (#992) | `ai-memory-cli/src/server_profiles.rs` `resolve` (validated `ProfileName`, strict `servers.toml` parse, `roots` required once two profiles exist, component-wise root match) and `marker.rs` `find_server_selection` (inherited down the tree, any value shape counts); `commands/hook.rs` `resolve_hook_route` drops a `Rejected` route before spool, handoff and backfill, and hands the drainer no live token for a profile route; `commands/hook_spool.rs` `static_retry_token` (a profile entry retries only with its own stored token), the loopback reroot skip, and chunk splitting on `profile`; generated TS `captureServerRouted` drops a routed repository and gates `fetchHandoff`; `hooks/_lib.sh` `ai_memory_server_routed` (flag refused by `ai_memory_post_hook`/`ai_memory_get_handoff`) and `hooks/lib/ai-memory-hook.ps1` `Test-AiMemoryServerRouted` drop it in the script hooks | `hook.rs` `each_repository_spools_to_its_own_profile_with_its_own_token`, `a_selection_that_does_not_resolve_emits_nothing` (unknown / tokenless / outside roots / roots required / invalid name, plus a resolving control), `session_start_handoff_comes_from_the_profile_server_only`, `a_repository_without_a_server_key_keeps_the_install_default`; `hook_spool.rs` `a_profile_entry_is_never_retried_with_the_install_live_token` (server B accepts exactly the install's live token and must still not get it), `a_profile_entry_recovers_with_its_own_rotated_token` (control), `a_profile_entry_on_a_dead_loopback_port_is_not_rerouted_to_the_default`, `profile_and_default_entries_at_one_address_ride_separate_batches`; `server_profiles.rs` roots/registry/name tests; `marker.rs` `nested_markers_without_server_inherit_the_ancestor_selection`; `install_hooks.rs` `generated_integrations_fail_closed_on_a_server_profile_marker`, `openclaw_plugin.rs` `openclaw_plugin_fails_closed_on_a_server_profile_marker`, and the `server-routed-*` checks in `generated_capture_policy_v1_node_runtime_evidence`; `hook.rs` `an_event_without_a_payload_cwd_routes_by_the_process_cwd`, `a_refused_route_prints_nothing_for_kimi_user_prompts`; `hook_spool.rs` `a_profile_entry_is_not_retried_with_a_token_issued_for_a_new_url`; `server_profiles.rs` `changing_the_url_without_a_token_discards_the_old_token`, `omitted_roots_keep_the_registered_ones`; `marker.rs` `outside_home_the_walk_reaches_a_marker_above_the_checkout_root`, `encoding_noise_cannot_hide_a_server_key`, `an_unreadable_marker_is_a_refused_selection`; `backfill.rs` `a_spawned_backfill_authenticates_like_the_hook_that_spawned_it`; `tests/hooks/test_lib.sh` "server profiles (#992)" section; `hook.rs` `a_mixed_spool_drains_each_event_only_to_its_own_server` (two token-gated servers, one spool, one drain: each server receives exactly its own event with exactly its own bearer); `tests/suite/server_profiles.rs` (the built binary: `server add` → `hook` spools to the profile with its token, unknown profile spools nothing, `uninstall` removes the tokens; `two_real_servers_each_receive_only_their_own_repository` runs two real `ai-memory serve` children with different root tokens and checks on each server which repository landed there); `ai-memory-hooks` `powershell_server_routed.rs` `server_routed_guard_mirrors_the_native_walk` (runs `Test-AiMemoryServerRouted` under real PowerShell: inherited, BOM, look-alike keys, the `$HOME` boundary with its control, past a checkout root outside home, current directory); `tests/hooks/test_lib.sh` and `powershell_home.rs` `a_trailing_separator_on_home_keeps_the_walk_boundary` (a `$HOME` ending in `/` or `\` keeps both script walks at home: a `server` marker above it routes nothing, with a root-home control that does) | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` |+ | 11d | Hook server-profile routing: a marker-selected server gets only its own capture and its own token (#992) | `ai-memory-cli/src/server_profiles.rs` `resolve` (validated `ProfileName`, strict `servers.toml` parse, `roots` required once two profiles exist, component-wise root match) and `marker.rs` `find_server_selection` (inherited down the tree, any value shape counts); `commands/hook.rs` `resolve_hook_route` drops a `Rejected` route before spool, handoff and backfill, and hands the drainer no live token for a profile route; `commands/hook_spool.rs` `static_retry_token` (a profile entry retries only with its own stored token), the loopback reroot skip, and chunk splitting on `profile`; generated TS `captureServerRouted` drops a routed repository and gates `fetchHandoff`; `hooks/_lib.sh` `ai_memory_server_routed` (flag refused by `ai_memory_post_hook`/`ai_memory_get_handoff`) and `hooks/lib/ai-memory-hook.ps1` `Test-AiMemoryServerRouted` drop it in the script hooks; `--check-capture` refuses a rejected server-profile selection without printing its token or URL | `hook.rs` `each_repository_spools_to_its_own_profile_with_its_own_token`, `a_selection_that_does_not_resolve_emits_nothing` (unknown / tokenless / outside roots / roots required / invalid name, plus a resolving control), `session_start_handoff_comes_from_the_profile_server_only`, `a_repository_without_a_server_key_keeps_the_install_default`; `hook_spool.rs` `a_profile_entry_is_never_retried_with_the_install_live_token` (server B accepts exactly the install's live token and must still not get it), `a_profile_entry_recovers_with_its_own_rotated_token` (control), `a_profile_entry_on_a_dead_loopback_port_is_not_rerouted_to_the_default`, `profile_and_default_entries_at_one_address_ride_separate_batches`; `server_profiles.rs` roots/registry/name tests; `marker.rs` `nested_markers_without_server_inherit_the_ancestor_selection`; `install_hooks.rs` `generated_integrations_fail_closed_on_a_server_profile_marker`, `openclaw_plugin.rs` `openclaw_plugin_fails_closed_on_a_server_profile_marker`, and the `server-routed-*` checks in `generated_capture_policy_v1_node_runtime_evidence`; `hook.rs` `an_event_without_a_payload_cwd_routes_by_the_process_cwd`, `a_refused_route_prints_nothing_for_kimi_user_prompts`; `hook_spool.rs` `a_profile_entry_is_not_retried_with_a_token_issued_for_a_new_url`; `server_profiles.rs` `changing_the_url_without_a_token_discards_the_old_token`, `omitted_roots_keep_the_registered_ones`; `marker.rs` `outside_home_the_walk_reaches_a_marker_above_the_checkout_root`, `encoding_noise_cannot_hide_a_server_key`, `an_unreadable_marker_is_a_refused_selection`; `backfill.rs` `a_spawned_backfill_authenticates_like_the_hook_that_spawned_it`; `tests/hooks/test_lib.sh` "server profiles (#992)" section; `hook.rs` `a_mixed_spool_drains_each_event_only_to_its_own_server` (two token-gated servers, one spool, one drain: each server receives exactly its own event with exactly its own bearer); `tests/suite/server_profiles.rs` (the built binary: `server add` → `hook` spools to the profile with its token, unknown profile spools nothing, `uninstall` removes the tokens; `two_real_servers_each_receive_only_their_own_repository` runs two real `ai-memory serve` children with different root tokens and checks on each server which repository landed there); `ai-memory-hooks` `powershell_server_routed.rs` `server_routed_guard_mirrors_the_native_walk` (runs `Test-AiMemoryServerRouted` under real PowerShell: inherited, BOM, look-alike keys, the `$HOME` boundary with its control, past a checkout root outside home, current directory); `hook.rs` `a_selection_that_does_not_resolve_emits_nothing` (rejected routes refuse preflight; resolved profile control passes); `tests/hooks/test_lib.sh` and `powershell_home.rs` `a_trailing_separator_on_home_keeps_the_walk_boundary` (a `$HOME` ending in `/` or `\` keeps both script walks at home: a `server` marker above it routes nothing, with a root-home control that does) | STRONG for native hooks, generated TS, `.sh` and `.ps1` hooks. Known gap: an older binary draining a shared spool ignores `profile` || 11e | Native self-upgrade archive confinement (#1025) | `ai-memory-cli/src/commands/upgrade.rs` normalizes every tar/zip path, rejects links and special entries, extracts only the binary and `hooks/`, accepts only the exact non-runtime support layout emitted by `release.yml`, and caps both entry count and declared expanded bytes before writing | `upgrade.rs` `release_workflow_support_assets_are_exact_and_ignored` (shipped support paths admitted, near-miss docs/packaging/template paths refused), `extracts_archive_built_like_release_yml` and `extracts_zip_happy_path_with_hooks` (real workflow-shaped archives succeed but support assets are not written), `validate_rejects_path_traversal`, `zip_extract_rejects_path_traversal`, `tar_extract_rejects_declared_expansion_past_limit`, with binary/hooks extraction as the legitimate control | STRONG || 11f | Native hook executable-path integrity after self-replacement (#1027) | `ai-memory-cli/src/commands/render_shared.rs` `hook_embedded_exe_path` is the single executable resolver for every persisted native hook form (POSIX/Windows command, Windows exec, Zero, ZCode, OpenCode 2 assistant capture): it prefers an existing literal path, strips Linux's trailing ` (deleted)` procfs marker only when the stripped installed binary exists, and otherwise falls back to the platform command name. Upgrade keeps the already-loaded config and refreshes in-process | `render_shared.rs` `embedded_exe_strips_the_marker_when_the_stripped_path_exists`, `embedded_exe_preserves_a_real_file_whose_name_has_the_marker_suffix`, `embedded_exe_falls_back_when_the_resolved_path_is_missing`, `hook_embedded_exe_path_names_an_existing_file_without_marker`; `upgrade_e2e.rs` `native_upgrade_refreshes_hooks_without_a_deleted_path_or_losing_cli_data_dir` reproduces the replacement window through the shipped binary, plants the corrupt suffix, and proves refresh removes it while preserving a CLI-only data dir | STRONG on Linux reproduction plus platform-neutral resolver/render coverage; Windows path rendering remains covered by its existing command/exec tests and full Windows CI |- | 11g | OpenCode executable probing and generated-config cleanup (#1097) | `ai-memory-cli/src/config.rs` captures the full process environment once in typed `RuntimeEnv`; `run.rs` overlays explicit `run --env` values with platform key semantics and uses that same effective environment for executable resolution, probing, and launch without rereading process environment; `opencode_dialect.rs` invokes only direct argv `--version`, caps output and time, and rejects malformed/future majors. Automatic launch skips only OpenCode on probe failure; explicit OpenCode fails. `install_hooks.rs` quarantines the incompatible sibling before reading its exact ownership markers, restores unowned content with an atomic no-replace link, and never deletes or overwrites a concurrent replacement; `install_mcp.rs` owns the shared dual-schema endpoint/token inference used by both installers, rejects conflicting generated V1/V2 entries before mutation, and migrates an alternate-major entry only when endpoint, generated shape, and absent-or-Authorization-only headers match, preserving custom headers and ambiguous entries; auto-wire migrates MCP before hooks infer from that exact config path and skips hook mutation when transition preflight fails | `run.rs` `automatic_opencode_probe_failure_keeps_another_harness_available`, `opencode_executable_probe_selects_v2_for_launch_and_autowire`, effective-child-environment PATH casing controls, fake V1/V2/env-derived-major/malformed/future/timeout executable tests, `setup-agent` V1/V2 no-probe integration controls; `install_hooks.rs` `opencode_plugin_cleanup_removes_only_exact_owned_incompatible_sibling`, `opencode_plugin_cleanup_preserves_a_concurrent_user_replacement`, `opencode_plugin_restore_moves_quarantine_when_destination_is_free`, `opencode_plugin_restore_preserves_an_existing_replacement`, `opencode_plugin_restore_does_not_replace_a_file_created_at_restore_window`, `opencode_plugin_cleanup_does_not_escape_custom_target_directory`; `install_mcp.rs` `opencode_install_reuses_owned_endpoint_and_token_across_major_transitions`, `opencode_install_refuses_conflicting_owned_transition_entries`, `opencode_install_does_not_infer_from_a_user_owned_transition_entry`, `opencode_mcp_migration_moves_only_owned_alternate_shape`, `opencode_mcp_migration_preserves_ambiguous_user_entry`, `opencode_mcp_migration_preserves_custom_headers`, `opencode_mcp_migration_accepts_only_historical_generated_headers` | STRONG for Unix process probes and platform-neutral ownership gates; exact Windows executable resolution remains covered by `run.rs` resolver tests and requires the PR `windows` label |- | 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401 | STRONG |+ | 11g | Cross-project file attribution cannot bypass destination capture or server routing (#932) | `ai-memory-hooks/src/capture_policy.rs` `absolute_file_tool_paths` accepts only bounded, recognized, absolute file-tool candidates; `ai-memory-cli/src/commands/hook.rs` `file_tool_routing_cwd` requires every path to prove the same repository/marker boundary and resolves that destination before capture policy, server profile, scope hints, or spool credentials. Relative, mixed-project, unsupported, and arbitrary non-project paths keep the payload cwd | `hook.rs` `absolute_file_target_uses_destination_scope_and_capture_policy` (hostile content under the destination exclusion is never spooled; a public control is routed there), `absolute_file_target_cannot_escape_a_destination_server_profile` (unregistered destination profile drops instead of falling back to source/install default), `file_target_routing_refuses_relative_external_and_mixed_project_paths` | STRONG for native `ai-memory hook`; generated and compatibility hooks retain cwd-only routing |+ | 11h | Docker-wrapper capture-policy capability (#1002) | `bin/ai-memory` routes ordinary Linux/macOS `install-hooks` and upgrade refreshes through the stable checksum-verified native host client, so the hook process executes the capture-policy boundary in 11b before spool/network. Only an explicit `AI_MEMORY_HOOK_PLATFORM=posix|windows` retains the documented script compatibility path and its warning; `AI_MEMORY_NATIVE_BIN` may not point back to the wrapper | `scripts/check-native-packaging.sh` `Checking host-launch wrapper routing`: a default allowlist install reaches the fake native client while a Docker executable that always fails proves no container fallback occurred; the explicit `posix` control reaches fake Docker and adds no native invocation; the self-referential native override is refused | STRONG on the shipped Linux/macOS wrapper. Windows and remote/manual script installers remain explicitly outside capture-policy v1 |++| 11i | OpenCode executable probing and generated-config cleanup (#1097) | `ai-memory-cli/src/config.rs` captures the full process environment once in typed `RuntimeEnv`; `run.rs` overlays explicit `run --env` values with platform key semantics and uses that same effective environment for executable resolution, probing, and launch without rereading process environment; `opencode_dialect.rs` invokes only direct argv `--version`, caps output and time, and rejects malformed/future majors. Automatic launch skips only OpenCode on probe failure; explicit OpenCode fails. `install_hooks.rs` quarantines the incompatible sibling before reading its exact ownership markers, restores unowned content with an atomic no-replace link, and never deletes or overwrites a concurrent replacement; `install_mcp.rs` owns the shared dual-schema endpoint/token inference used by both installers, rejects conflicting generated V1/V2 entries before mutation, and migrates an alternate-major entry only when endpoint, generated shape, and absent-or-Authorization-only headers match, preserving custom headers and ambiguous entries; auto-wire migrates MCP before hooks infer from that exact config path and skips hook mutation when transition preflight fails | `run.rs` `automatic_opencode_probe_failure_keeps_another_harness_available`, `opencode_executable_probe_selects_v2_for_launch_and_autowire`, effective-child-environment PATH casing controls, fake V1/V2/env-derived-major/malformed/future/timeout executable tests, `setup-agent` V1/V2 no-probe integration controls; `install_hooks.rs` `opencode_plugin_cleanup_removes_only_exact_owned_incompatible_sibling`, `opencode_plugin_cleanup_preserves_a_concurrent_user_replacement`, `opencode_plugin_restore_moves_quarantine_when_destination_is_free`, `opencode_plugin_restore_preserves_an_existing_replacement`, `opencode_plugin_restore_does_not_replace_a_file_created_at_restore_window`, `opencode_plugin_cleanup_does_not_escape_custom_target_directory`; `install_mcp.rs` `opencode_install_reuses_owned_endpoint_and_token_across_major_transitions`, `opencode_install_refuses_conflicting_owned_transition_entries`, `opencode_install_does_not_infer_from_a_user_owned_transition_entry`, `opencode_mcp_migration_moves_only_owned_alternate_shape`, `opencode_mcp_migration_preserves_ambiguous_user_entry`, `opencode_mcp_migration_preserves_custom_headers`, `opencode_mcp_migration_accepts_only_historical_generated_headers` | STRONG for Unix process probes and platform-neutral ownership gates; exact Windows executable resolution remains covered by `run.rs` resolver tests and requires the PR `windows` label |+ | 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer`; `serve.rs` mounts `/identity` inside the host and machine-auth gates even with web disabled; `nix/nixos-module.nix` treats only literal `127.0.0.1`/`::1` as loopback, requires exactly one secret environment source for other binds, keeps secret auth and `llm_headers` values out of the Nix store, and brackets IPv6 in `ExecStart` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401; `serve.rs` `machine_identity_remains_authenticated_with_web_disabled_and_expired_keys` (wrong and expired keys refused, valid machine key accepted, web remains disabled); `flake.nix` `nixos-module-eval` refuses `localhost` and `0.0.0.0` without a secret source, refuses two secret sources, `settings.auth` secrets, and `settings.llm_headers`, with literal IPv4/IPv6 loopback and one-source controls | STRONG |+ | 12b | Managed-workstream provenance privacy, stable replay identity and server event namespace | `ai-memory-core/src/workstream.rs` `scrub_workstream_provenance`; `ai-memory-hooks/src/workstream.rs` `finish_run` reserved client-id check and `sanitize_events` before immutable segments; `ai-memory-store/src/workstream.rs` `finish_run` stable identity check and `stored_event`, using an explicitly supplied configured sanitizer; no changes to the typed observation boundary | `store/tests/suite/workstream_provenance.rs` `workstream_provenance_is_bounded_scrubbed_and_idempotent_before_storage` (hostile and oversized source ids, unknown metadata, legitimate correlation, retry and distinct event ids), `workstream_provenance_legacy_reads_strip_secrets_and_unknown_metadata` (search and tail, malformed/oversized legacy JSON), `workstream_provenance_reused_event_id_retains_data_and_refuses_identity_change` (first indexed version retained, identity refusal and batch rollback), `workstream_provenance_replay_survives_sanitizer_changes` (new extra patterns and removal of a built-in-pattern allowlist exemption, with identity-refusal control), `workstream_provenance_replay_preserves_legacy_rows_above_bounds`, `workstream_provenance_finished_run_ignores_late_events`, `workstream_provenance_retry_with_marker_matching_pattern_is_idempotent`; `hooks` `workstream_provenance_finish_scrubs_before_raw_segment_and_search` (custom sanitizer, immutable segment, SQL recovery and finished-run no-op), `workstream_provenance_client_cannot_use_server_event_ids` (reserved ids refused before raw writes, normal client event and server-generated checkpoint/loss controls); `cli/tests/suite/workstream_provenance.rs` (text/JSON and old server DTOs) | STRONG: privacy, stable-identity and reserved-namespace regressions fail with their guards bypassed; an isolated allowlist bypass fails on the unknown key, and bypassing the raw-id search authorization returns 200 where its test requires 403. No provenance is emitted in startup packets, and old raw segments are not rewritten || 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-store/src/workstream.rs` `link_native_session` stamps `native_session_linked_at` on its own run only, both `finish` updates drop the stamp when the session changes, `run_status` reports it; `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a linked session only when `ai-memory-workstream` `native_session_in_checkout` holds it for this checkout (OpenCode by recorded directory), never falls back to a link it set aside, and turns an `AmbiguousNativeSession` into a warning with nothing imported; for Claude it moves the run's own session to a background session only when `ai-memory-workstream` `claude_attached_background_session` finds a `sessionKind: "bg"` record that names that exact session as its attached client and this checkout as `cwd` (#1050); `ai-memory-workstream/src/transcript.rs` `discover_crush` claims only the one top-level session created (or, with `--continue`, touched) during the run, and in a data directory outside the project only one that edited a file in it | `multi_session.rs` `a_session_linked_by_one_managed_run_is_not_another_runs`; `run.rs` `a_session_linked_during_the_run_wins_over_discovery` (concurrent newer session, another checkout's link refused, no fallback to it, unlinked control); `transcript.rs` `claude_attached_background_session_follows_only_this_checkouts_bg_records` (a concurrent launch's background session, another checkout's, and a non-background record refused; own attachment control); `run.rs` `a_claude_run_that_attached_to_a_background_session_follows_it`; `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run`; `run.rs` `ambiguous_crush_discovery_keeps_the_run`; `transcript.rs` `crush_discovery_claims_only_the_session_the_run_created`, `crush_discovery_in_a_shared_store_claims_only_an_edit_here` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout; Crush, which has no hooks, relies on that discovery alone and claims nothing when it is ambiguous || 13a | Managed Codex stale-daemon run recovery (#987; concurrent launches, project/worktree isolation, operator isolation) | `managed_runs.owner_user` (V71) uses the topology-aware `IdentityKey` owner stamp; `router.rs` resolves and authorizes the SessionStart repository before handling the untrusted run id; store `link_or_adopt_native_session` selects and links in one writer transaction and admits only the sole live, undelivered, never-linked Codex run in the exact workspace/project/checkout-cwd/owner bucket. An active supplied id must itself match every boundary; another harness, an ambiguity, or a second native session is refused | `multi_session.rs` `stale_codex_run_recovery_cannot_cross_project_owner_or_session_boundaries` (foreign owner, foreign checkout, and cross-project candidates refused; project-local controls and racing rebind), `stale_codex_run_recovery_fails_closed_on_ambiguity_and_active_mismatch` (two candidates and active foreign id refused, exact control); `workstream.rs` `prepare_stamps_the_operator_bucket_used_by_session_start_recovery` (HTTP actor stamp with foreign and legitimate controls); `router.rs` `managed_session_start_delivers_ledger_and_pending_handoff` supplies a finished stale id and proves the new run is linked and delivered | STRONG for SessionStart recovery. No candidate is selected from a run id's stale scope, another checkout, or another operator bucket; ambiguity deliberately falls back to no managed packet || 13b | Managed-run lease exclusivity and explicit recovery (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and otherwise refuses an `active` run inside the writer transaction (`StoreError::WorkstreamBusy`). The explicit `force_unlock` path may expire and replace that row in the same transaction only when its durable `owner_user` equals the incoming actor's attribution; different operators remain isolated. `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` normally uses `wait_out_held_lease`; `--force-unlock` instead asks once and fails immediately when refused. Neither path treats the informational `lease_owner` label as authority | `multi_session.rs` `force_unlock_replaces_only_the_same_operators_active_run` (foreign operator refused with live control, same operator succeeds, old run loses heartbeat, unattributed single-user control); hooks `workstream.rs` `force_unlock_cannot_evict_another_operator` exercises the HTTP actor boundary; CLI `run.rs` `force_unlock_asks_once_instead_of_waiting_out_the_lease`; existing controls `managed_workstream_batches_are_idempotent_and_release_the_lease`, `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over`, `interactive_launch_waits_out_a_lapsing_lease_then_proceeds`, and `ctrl_c_aborts_the_held_lease_wait_immediately` | STRONG for exclusivity. The `lease_owner` label (`host:pid`) is informational only and not unique inside ai-jail (every jailed launcher reports `ai-sandbox:<ns-pid>`), so it must never become an ownership key. A shared unattributed/root context is intentionally one operator bucket; deployments needing person-level refusal must authenticate DB users |