Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Merge pull request #962 from Barba2k2/backup-agent-assets
AkitaOnRails48554cadf026
diff --cc CHANGELOG.mdindex 209c1e66,2479a23e..7fdaaa43--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -8,280 -8,12 +8,288 @@@ and this project adheres to [Semantic V## [Unreleased]### Added-- Added `ai-memory backup-agents` and `ai-memory restore-agents` commands for- host AI agent configurations, skills, plugins, and project instructions.- Backups sanitized MCP config text by default; other assets were copied- verbatim and could contain secrets. Archives included deterministic manifests- with SHA-256 checksums, dry-run previews, agent/scope filters, and path-guarded- atomic restores. (#962)++- 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 exposed as `nixosModules.default`, with a dedicated+ non-login service user, a hardened systemd unit, declarative non-secret+ settings, agenix/sops/environment-file secret sources, and opt-in web,+ firewall, and resource settings. Non-loopback binds require exactly one+ secret source; expensive Darwin and privileged container checks run only in+ the full CI tier. (#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. (#1003)+- 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)++### Changed+- Documented FutureInfra as an endpoint for the existing `openai-compat`+ provider. (#1026)++### Fixed+- 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)+- `ai-memory doctor` now warns when the nearest `.ai-memory.toml`'s+ `[capture]` section is invalid. This fails closed today — every file and+ shell tool event is reduced to metadata until the marker is fixed, nothing+ leaks — but nothing surfaced that it had happened, so an operator could+ believe `ignore_paths` was excluding paths it no longer was. The check is+ based on the same resolution state the live hook path uses (not just+ whether the TOML parses), so it also catches a `[capture]` table that+ parses fine but is still rejected at compile time, e.g. an unsupported glob+ character in `ignore_paths`. (#1021)+- Fixed the shell and PowerShell hook scripts mishandling a `$HOME` that ends+ in a separator: the shell walks missed a marker between the checkout and+ home, and the PowerShell walks went past home and read a marker above it.+ Both now match the native `ai-memory hook` walk. (#1023)+- Fixed `ai-memory run --jail` leaving the `ssh` toggle unchecked when+ `git push` goes over SSH but `origin`'s fetch URL does not show it: an HTTPS+ `origin` with an SSH `pushurl` or `pushInsteadOf`, or a `host:path` remote+ using an `~/.ssh/config` alias. The interactive offer now also uses+ ai-jail's own dry-run preflight, so a backend that exists but fails ai-jail's+ trust checks is treated as unavailable instead of producing a broken offer.+ (#1024)++## [2.5.2] - 2026-10-01++### Added+- Added `ai-memory run --jail[=TOGGLES]` and `--no-jail`, and an interactive+ checklist after the `--yolo` ai-jail offer, to choose which ai-jail+ credentials and capabilities the jailed session gets. Bare `--jail` re-runs+ inside ai-jail without asking, using smart defaults: every credential present+ on the host (`~/.config/gh`, `~/.aws`, `~/.kube`, `~/.config/gcloud`,+ `~/.docker/config.json`), SSH when `origin` is an SSH remote, and worktree+ metadata in a linked worktree; host capabilities (`docker`, `gpu`,+ `display`, `pictures`, `tailscale`) stay off, and anything else is left to+ the user's own ai-jail config. `--jail=github,aws,no-mise` is exact: it+ passes every checklist row it does not name as `--no-X`, so a global+ `~/.ai-jail` cannot add to it (`all` and `none` also work); the checklist+ likewise passes unchecked rows as `--no-X`. `--jail` works without `--yolo`+ and in scripts, and fails instead of running unjailed when ai-jail is not+ usable. Only toggles the installed ai-jail advertises in its+ `--help` are offered or passed; the credential mounts need ai-jail 2.5.0.+ ai-jail's security switches (`seccomp`, `landlock`, `private-home`, …) are+ never accepted. `--no-jail` skips the offer while keeping the `--yolo`+ warning. A project `.ai-jail` in the launch directory replaces the checklist+ and the bare-`--jail` defaults (ai-jail loads it under its own trust rules;+ `--jail=…` still applies on top), and every jailed re-run now passes+ `--no-save-config`, so ai-jail no longer writes ai-memory's `--network` /+ `--agent-state` / credential flags into the repository's `.ai-jail`.++### Fixed+- Fixed the shell and PowerShell session-start hooks for Claude Code, Codex,+ Cursor, Gemini CLI, OpenCode, Command Code, Devin, and Antigravity CLI not+ sending the marker's `[briefing]` keys (`briefing`, `briefing_budget`) on the+ handoff request, so a repository with `inject_on_session_start = true` got+ the handoff without its compiled brief on script installs (Docker wrapper,+ `setup-agent`). Only the native `ai-memory hook` command and the Kiro CLI and+ Kimi Code scripts sent them; all now match `docs/marker-file.md`. (#998)+- Fixed a wiki checkpoint leaving `.git/index` behind the commit it made. A+ path-scoped checkpoint wrote the index file only once every 50 commits, so+ between writes `HEAD` and the working tree held the new page while the index+ still named the old blob, and `git status` from outside the server showed+ every checkpointed page as `MM`; a checkpoint with nothing to commit left a+ stale index the same way. The history itself was always correct. Not specific+ to Windows. (#983, #1006)+- Fixed a wiki checkpoint failing instead of retrying when a full walk listed a+ file that was gone by the time it was read (libgit2's `Os`-class "failed to+ read file into stream", e.g. an atomic writer's temp file renamed away+ mid-walk). It now takes the same bounded racy-read retry as a file changed+ mid-write; unrelated I/O errors still fail fast. This was also the source of+ an intermittent `concurrent_commits_queue_instead_of_failing` CI failure.++### Security+- Fixed GHSA-gf78-hf8g-vffm: `memory_read_page` with `include_related` returning pages from+ projects the caller cannot read under per-project authorization, and walking+ through them to reach others: in multi-user mode an authenticated user without+ a grant saw the paths, titles, kinds, and project names of pages in a+ `restricted` project up to three hops away (never their bodies). `page_links`+ and the graph already hid them; the multi-hop related walk now filters every+ hop the same way. Installs without authorization, and root, are unchanged.+ (#999)+- Fixed CLI `ai-memory message send` (`POST /admin/messages/send`) bypassing+ `message_send` admission: it inserted the message without consulting a+ configured webhook's reject policy or notifying observers, while the MCP+ send path enforced both. It now runs admission at the recipient scope before+ the insert — a rejection returns 403 and stores nothing — and notifies+ observers only after a successful commit, without waiting on nonblocking+ ones. (#756)++## [2.5.1] - 2026-10-01++### Fixed+- Fixed `ai-memory run --yolo`'s ai-jail re-exec aborting when the wrapped+ command carried a flag that ai-jail also defines: `run claude --yolo --env+ GH_TOKEN=…` failed with "flag --env after command would be passed to the+ child". The invocation now separates ai-jail's sandbox flags from the+ wrapped command with `--`; forwarding such a flag also needs ai-jail 2.4.2 or+ later, whose guard honors the separator.+- Fixed the `--yolo` ai-jail offer appearing when accepting it could not+ work. It is now shown only on Linux/macOS when both ai-jail and its sandbox+ backend (`bwrap` / `sandbox-exec`) are present — never on Windows, even with a+ file named `ai-jail` on `PATH` — and otherwise the run proceeds without the+ question. The re-exec runs the exact binary that was found, so a+ `~/.local/bin`-only ai-jail no longer fails to exec after the user accepted.+- Fixed `--true-yolo`. It now implies `--yolo` (the warning, the ai-jail+ offer, and each harness's dangerous mode), so passing it alone no longer+ bypassed Claude's permissions with no warning; it is interchangeable with+ `--yolo` for non-Claude harnesses instead of printing "ignoring it"; and it is+ recognized after native arguments (`run claude --model opus --true-yolo`)+ instead of being passed to Claude as an unknown option. The `claude_true_yolo`+ config key now+ only upgrades an explicit `--yolo`/`--true-yolo` launch, as documented,+ rather than applying `bypassPermissions` to every managed Claude run.+- Fixed relaunching right after an interrupted `ai-memory run` failing with+ "workstream is already active: owned by … until …" when the previous+ launcher could not release its lease (killed, terminal closed, or an+ ai-jail sandbox torn down). An interactive launch now names the holder and+ waits for that lease to lapse (at most one ~90-second lease; Ctrl-C aborts),+ then starts by itself. A holder that renews the lease meanwhile is reported+ as a launcher still running — never displaced — and non-interactive launches+ keep the short retry window.+- Fixed `--true-yolo` claiming protections it never provided. It set three+ `CLAUDE_CODE_DISABLE_*RM*` environment variables that Claude Code does not+ read, and passed an empty `permissions.ask` array that cannot clear `ask`+ rules from other settings scopes (Claude Code unions them). Both were+ removed; true-yolo now forces only `bypassPermissions`, and the docs state+ that Claude still honors your own `ask` rules and command-safety checks in+ every mode.++### Security+- Fixed GHSA-vh98: a capture-exclusion candidate or shell argument spelled+ with a leading `//` (e.g. `//repo/secret/token.txt`) self-classified as a+ Windows UNC path regardless of the actual host, so it matched zero POSIX+ `ignore_paths` patterns (a flavor mismatch) and was captured instead of+ dropped. Path flavor for an untrusted candidate is now derived from the+ host (the cwd) rather than the candidate string alone, both in the native+ hook (`ai-memory-hooks` `capture_policy.rs`) and the generated+ OpenCode/OMP/Pi/OpenClaw TypeScript integrations+ (`ai-memory-cli` `render_shared.rs`); a genuine Windows/UNC host's UNC+ candidates are unaffected.+## [2.5.0] - 2026-09-30++### Added+- `ai-memory run --yolo` now warns before disarming an agent's safety prompts+ and, on Linux/macOS, offers to re-run the session inside+ [ai-jail](https://github.com/akitaonrails/ai-jail) when it is installed.+ The warning and offer are TTY-gated (stdin and stderr must both be real+ terminals) and skipped entirely when already running inside ai-jail+ (detected via the Linux `ai-sandbox` hostname or the macOS `(jail) ` `PS1`+ prefix), so hook, CI, detached, and piped runs are unaffected. Accepting+ the ai-jail offer re-execs the original invocation under `ai-jail+ --network --agent-state <harness> --env <NAME>...` (only already-set+ credential/config env vars are forwarded); declining `--yolo` itself+ aborts before the agent spawns. A new opt-in `--true-yolo` flag /+ `claude_true_yolo` config key additionally silences Claude Code's+ residual `--dangerously-skip-permissions` prompts (the `rm` timeout and+ confirmation, and the PowerShell `rm` deny) and forces+ `--settings '{"permissions":{"defaultMode":"bypassPermissions","ask":[]}}'`;+ it is a no-op for every other harness. See+ `docs/design-yolo-safety-ai-jail.md`. (#994)+- `ai-memory repair-backfill-timestamps [--project] [--workspace] [--confirm]+ [--json]` and `POST /admin/repair-session-times` correct+ `sessions.started_at`/`ended_at` for sessions an older `backfill` imported+ before it carried the transcript's own event time, which flattened every+ imported session onto the import day. Only rewrites a row whose+ `started_at` actually postdates the candidate's own transcript end (a+ correctly hook-captured session, or a re-run, is a no-op); refuses+ out-of-scope, unchanged, negative, inverted, or future-dated candidates;+ never closes a still-open session; and records an `audit_log` row on+ apply. Dry-run by default. (#921)+- Native tool output resolution for Antigravity CLI lifecycle hooks+ (`post-tool-use`). Command stdout (`run_command`), file views (`view_file`),+ search results (`find_by_name`, `grep_search`, `search_web`), and task+ management outputs are now read directly from+ `.system_generated/steps/<stepIdx>/output.txt` and populated into observation+ excerpts. Code modification capture via `write_to_file` and+ `replace_file_content` remains preserved from invocation arguments. (#966)+- The watcher's reconcile pass can now optionally tombstone a wiki page whose+ file has disappeared from disk, closing part of the gap left by #929 (the+ watcher only reconciled create/modify events, so a deleted file stayed+ indexed until `ai-memory delete-page` ran explicitly). Opt-in and default+ `false` (`[maintenance] reconcile_tombstones_deleted_pages`), so existing+ installs see no behavior change unless they turn it on. When enabled, a+ page's file must be observed missing on two consecutive 30s reconcile+ passes, re-verified against the live filesystem immediately before acting;+ a circuit breaker refuses to act on a whole scope when more than `max(3,+ 50%)` of its candidate pages look missing in one pass, or when a+ non-partial walk finds nothing at all (either shape is far more likely a+ walk/mount problem than genuine mass deletion); and reserved/indexed-but-+ unwalked paths (`bootstrap.md`, `_meta.md`, `_pending/` sidecars, and+ `sessions/*.md` — excluded because a same-workspace `move-session` re-home+ can leave one with a correct row and no file, a separate pre-existing bug)+ are never candidates. The action is a soft tombstone (`is_latest = 0` ++ `superseded_at`, the same shape decay eviction already uses), picked up by+ the SAME aged-tombstone hard-delete sweep decay eviction uses — it is not+ exempt from it. What actually protects it: it is never destroyed while its+ chain has no successor; if the file returns, the new version re-links onto+ the tombstoned chain instead of starting a fresh, disconnected one, so+ nothing is left orphaned for that sweep to destroy. It never runs the+ blocking admission gate (nothing can refuse it), but does fire-and-forget+ any non-blocking observer/mirror webhook on success. `restore-page` and+ version history remain intact. See `docs/okf.md` for the full design.+ (#964)+- `ai-memory run` now finalizes the session when a harness without a native+ session-end hook exits (Command Code, Kiro CLI v2 and v3, Antigravity CLI),+ so the summary, handoff and opt-in SessionEnd consolidation no longer wait+ for a manual `ai-memory finalize-session`. Only a session the run can tie to+ itself (named, chosen before the spawn, or linked during the run) is closed,+ including again after it was resumed; if finalizing fails, the run prints+ the exact command to run and keeps the harness's exit code. (#941)+- After an interactive managed `ai-memory run` session exits successfully, a+ default-quit prompt can switch to another installed harness or re-run the+ current one in the same workstream. The prompt is limited to terminal+ session launches without `--executable`; utility, failed, interrupted, and+ non-interactive runs keep their existing exit behavior. (#909)+- `[consolidation] input_token_safety_margin` (float, default `0.8`, validated+ to `(0.0, 1.0]`) scales the approximate char-count input budget. The+ `max_input_tokens` budget uses a flat chars-per-token heuristic that+ under-budgets denser corpora — pt-BR text and source code tokenize at fewer+ chars per token than English and could overshoot a provider's real input+ limit by ~40%. The default tightens the common case modestly while leaving+ such corpora headroom; lower it further for a mostly non-English or code+ corpus. `max_input_tokens` is now documented as an approximate heuristic in+ the config reference. (#884)- `install-skills --agent hermes` (and the `hermes` entry in`memory_install_self_routing`'s `target_hints`) installs the managed routingskills into Hermes Agent's `.hermes/skills` (project) or `~/.hermes/skills`diff --cc README.mdindex 3b4d9021,7bab0785..86d9dcb0--- a/README.md+++ b/README.md@@@ -439,6 -382,6 +439,10 @@@ readable wiki pages; the next session smonths of history.- Start the server with `--enable-web` for a read-only browser view ofthe wiki and a JSON API under `/api/v1`.++- Back up host-side harness configuration with++ `ai-memory backup-agents -o agent-assets.tar.gz`; inspect a restore with++ `ai-memory restore-agents -i agent-assets.tar.gz`, then add `--apply` only++ after reviewing the active skills, plugins, instructions, and destinations.The full tour — search modes, entities, feedback, briefings, the webAPI — is in [`docs/usage.md`](docs/usage.md) and@@@ -527,7 -468,6 +531,8 @@@ diagram, crate breakdown, schema notes| [`docs/users.md`](docs/users.md) | **Multi-user attribution and human login.** Four-rung bearer ladder, password sessions, `ai-memory user` / `api-key` walkthrough, brownfield migration. || [`docs/https-via-proxy.md`](docs/https-via-proxy.md) | **HTTPS via a reverse proxy.** When you need TLS and when you don't, with copy-paste Caddy / nginx / Cloudflare Tunnel templates and the "secure when you're not" failure modes. || [`docs/lifecycle-ops.md`](docs/lifecycle-ops.md) | **Read before purge / rename / backup / restore / reset / reindex / restore-page.** Safety matrix, per-project disk layout, checkpoint page recovery, and operator workflows. |+| [`docs/backup.md`](docs/backup.md) | Backing up the wiki + data dir to a remote git repository: what to include, what to exclude, scheduled push pattern, restore, and security posture. Companion to `docs/lifecycle-ops.md` (which covers the on-box `ai-memory backup` snapshot). |++| [`docs/design-backup-agent-assets.md`](docs/design-backup-agent-assets.md) | Host agent-asset backup/restore: supported paths, filtering, redaction limits, archive bounds, active-content warning, and rollback behavior. || [`docs/llm-providers.md`](docs/llm-providers.md) | Provider configuration for consolidation and embeddings. || [`docs/security.md`](docs/security.md) | The full security model. || [`docs/support-matrix.md`](docs/support-matrix.md) | The full agent/platform matrix with notes. |diff --cc crates/ai-memory-cli/src/cli.rsindex 492f9482,57283847..a60e42d8--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@@ -1909,6 -1752,38 +1915,39 @@@ pub struct BackupArgspub to: PathBuf,}+ /// Scope of assets to collect for `backup-agents`.+ #[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]+ pub enum AgentBackupScope {+ /// Global user assets only.+ Global,+ /// Project assets only.+ Project,+ /// Both global and project assets.+ Both,+ }++ /// Arguments for `backup-agents`.+ #[derive(Debug, Args)]+ pub struct BackupAgentsArgs {+ /// Destination tarball (`.tar.gz`).+ #[arg(long, short = 'o')]+ pub to: PathBuf,+ /// Comma-separated list of agent names to include (e.g. `claude,codex,antigravity`). Defaults to all detected.+ #[arg(long, value_delimiter = ',')]+ pub agents: Option<Vec<String>>,+ /// Scope of assets to collect: `global`, `project`, or `both`.+ #[arg(long, default_value = "both")]+ pub scope: AgentBackupScope,+ /// Skip MCP-config redaction; other assets are always copied verbatim.- /// Sets archive mode to 0600 on Unix.++ /// Every archive is written with mode 0600 on Unix because instructions++ /// and plugins may also contain secrets.+ #[arg(long)]+ pub include_secrets: bool,+ /// Preview assets that would be backed up without creating an archive.+ #[arg(long)]+ pub dry_run: bool,+ }+/// Arguments for `export-okf`.#[derive(Debug, Args)]pub struct ExportOkfArgs {diff --cc crates/ai-memory-cli/src/commands/backup_agents.rsindex 00000000,64d900f7..72a0c42emode 000000,100644..100644--- a/crates/ai-memory-cli/src/commands/backup_agents.rs+++ b/crates/ai-memory-cli/src/commands/backup_agents.rs@@@ -1,0 -1,892 +1,942 @@@+ //! `ai-memory backup-agents` — snapshot AI agent configurations,+ //! skills, plugins, and instructions into a portable archive.+-use std::fs::{self, File, OpenOptions};++use std::fs::{self, File};+ use std::io::Cursor;+ use std::path::{Path, PathBuf};++ use ai_memory_core::agent_backup::{+ AgentAssetKind, AgentAssetScope, AgentBackupEntry, AgentBackupManifest, HostInfo,+ };+ use ai_memory_core::ids::AgentKind;+ use ai_memory_core::sanitize::{SanitizeConfig, Sanitizer};+ use anyhow::{Context, Result};+ use flate2::Compression;+ use flate2::write::GzEncoder;+ use sha2::{Digest, Sha256};+ use tar::{Builder, Header};+ use tracing::info;++ use crate::cli::{AgentBackupScope, BackupAgentsArgs, McpClient};+ use crate::commands::path_util::{claude_config_dir, home_dir};+ use crate::config::Config;+++const MAX_BACKUP_ASSET_BYTES: u64 = 128 * 1024 * 1024;+++ /// An asset candidate discovered on the host filesystem.+ #[derive(Debug, Clone)]+ pub struct DiscoveredAsset {+ /// Agent owning the asset.+ pub agent: AgentKind,+ /// Kind of asset.+ pub kind: AgentAssetKind,+ /// Global or project-scoped.+ pub scope: AgentAssetScope,+ /// Absolute path on host disk.+ pub source_path: PathBuf,+ /// Target path relative to destination root (home or cwd).+ pub target_relative: String,+ /// Archive destination path inside the tarball.+ pub archive_path: String,+ }++ /// Run the `backup-agents` subcommand.+ ///+ /// # Errors+ /// Returns an error if directory traversal fails, source files cannot be read,+ /// or writing the output archive fails.+ pub fn run(_config: &Config, args: BackupAgentsArgs) -> Result<()> {+ let home = home_dir().context("locating user home directory")?;+ let cwd = std::env::current_dir().context("locating current working directory")?;+- let discovered = discover_assets(&home, &cwd, &args)?;++ let mut discovered = discover_assets(&home, &cwd, &args)?;++++ // Never consume the archive while replacing it. This matters when an++ // existing destination sits under one of the collected plugin trees.++ let destination_identity = fs::canonicalize(&args.to).ok();++ discovered.retain(|asset| {++ destination_identity++ .as_ref()++ .is_none_or(|dest| fs::canonicalize(&asset.source_path).ok().as_ref() != Some(dest))++ });++ discovered.sort_by(|a, b| a.archive_path.cmp(&b.archive_path));++ if discovered.is_empty() {+ println!("No AI agent assets detected for backup.");+ return Ok(());+ }++ if args.dry_run {+ print_dry_run(&discovered);+ return Ok(());+ }++ let dest = &args.to;- if let Some(parent) = dest.parent()- && !parent.as_os_str().is_empty()- {- fs::create_dir_all(parent)- .with_context(|| format!("creating parent dir for {}", dest.display()))?;- }-- let file = {- let mut opts = OpenOptions::new();- opts.write(true).create(true);- #[cfg(unix)]- if args.include_secrets {- use std::os::unix::fs::OpenOptionsExt;- opts.mode(0o600);- }- opts.open(dest)- .with_context(|| format!("creating output archive at {}", dest.display()))?- };-++ let parent = dest++ .parent()++ .filter(|parent| !parent.as_os_str().is_empty())++ .unwrap_or_else(|| Path::new("."));++ fs::create_dir_all(parent)++ .with_context(|| format!("creating parent dir for {}", dest.display()))?;++++ // Agent instructions and plugins are copied verbatim and may contain++ // credentials even in the default sanitized mode. Keep every archive++ // private, and replace the destination only after the gzip stream closes.++ let temporary = tempfile::Builder::new()++ .prefix(".ai-memory-agent-backup.")++ .tempfile_in(parent)++ .with_context(|| format!("creating temporary archive beside {}", dest.display()))?;+ #[cfg(unix)]- if args.include_secrets {++ {+ use std::os::unix::fs::PermissionsExt;- file.set_permissions(fs::Permissions::from_mode(0o600))- .with_context(|| format!("securing output archive {}", dest.display()))?;++ temporary++ .as_file()++ .set_permissions(fs::Permissions::from_mode(0o600))++ .with_context(|| format!("securing temporary archive beside {}", dest.display()))?;+ }- file.set_len(0)- .with_context(|| format!("truncating output archive {}", dest.display()))?;+- let count = build_archive(file, &discovered, args.include_secrets, &home)?;++ let count = build_archive(++ temporary++ .reopen()++ .context("reopening temporary agent archive")?,++ &discovered,++ args.include_secrets,++ )?;++ temporary++ .as_file()++ .sync_all()++ .context("syncing temporary agent archive")?;++ let persisted = temporary++ .persist(dest)++ .map_err(|error| error.error)++ .with_context(|| format!("replacing output archive at {}", dest.display()))?;++ persisted++ .sync_all()++ .with_context(|| format!("syncing output archive at {}", dest.display()))?;++ if let Ok(dir) = File::open(parent) {++ let _ = dir.sync_all();++ }++ let size = fs::metadata(dest).map(|m| m.len()).unwrap_or(0);+ info!(path = %dest.display(), bytes = size, count, "agent assets backup written");++ println!(+ "✓ Backed up {} agent assets to {} ({})",+ count,+ dest.display(),+ human_bytes(size)+ );++ if args.include_secrets {+ eprintln!(+ "⚠️ Warning: Secrets were included without sanitization. Archive mode is 0600 on Unix; protect the file on other platforms."+ );+ }++ Ok(())+ }++ fn print_dry_run(discovered: &[DiscoveredAsset]) {+ println!(+ "Found {} assets across AI agents (dry-run):",+ discovered.len()+ );+ for asset in discovered {+ println!(+ " [{:?}] {:<12} {:<8} -> {}",+ asset.agent,+ asset.kind.label(),+ match asset.scope {+ AgentAssetScope::Global => "global",+ AgentAssetScope::Project => "project",+ },+ asset.source_path.display()+ );+ }+ }++ /// Discover agent assets based on configuration and scopes.+ pub fn discover_assets(+ home: &Path,+ cwd: &Path,+ args: &BackupAgentsArgs,+ ) -> Result<Vec<DiscoveredAsset>> {+ let mut assets = Vec::new();+ let want_global = matches!(+ args.scope,+ AgentBackupScope::Global | AgentBackupScope::Both+ );+ let want_project = matches!(+ args.scope,+ AgentBackupScope::Project | AgentBackupScope::Both+ );++ let filter_agent = |agent: AgentKind| -> bool {+ let Some(filter) = &args.agents else {+ return true;+ };+ matches_agent_filter(agent, filter)+ };++ // 1. Claude Code / Desktop+ if filter_agent(AgentKind::ClaudeCode) {+ if want_global {+ let claude_dir = claude_config_dir(std::env::var_os("CLAUDE_CONFIG_DIR"))+ .unwrap_or_else(|| home.join(".claude"));+ // Global MCP / Settings+ push_if_file(+ &mut assets,+ AgentKind::ClaudeCode,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ claude_dir.join("settings.json"),+ ".claude/settings.json",+ "claude/mcp/settings.json",+ );+ push_if_file(+ &mut assets,+ AgentKind::ClaudeCode,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ home.join(".claude.json"),+ ".claude.json",+ "claude/mcp/claude.json",+ );+ // Global Skills+ collect_dir_assets(+ &mut assets,+ AgentKind::ClaudeCode,+ AgentAssetKind::Skill,+ AgentAssetScope::Global,+ &claude_dir.join("skills"),+ ".claude/skills",+ "claude/skills",+ )?;+ // Plugins+ collect_dir_assets(+ &mut assets,+ AgentKind::ClaudeCode,+ AgentAssetKind::Plugin,+ AgentAssetScope::Global,+ &claude_dir.join("plugins"),+ ".claude/plugins",+ "claude/plugins",+ )?;+ }+ if want_project {+ // Project Skills+ collect_dir_assets(+ &mut assets,+ AgentKind::ClaudeCode,+ AgentAssetKind::Skill,+ AgentAssetScope::Project,+ &cwd.join(".claude").join("skills"),+ ".claude/skills",+ "project/claude/skills",+ )?;+ // Project Instructions+ push_if_file(+ &mut assets,+ AgentKind::ClaudeCode,+ AgentAssetKind::Instruction,+ AgentAssetScope::Project,+ cwd.join("CLAUDE.md"),+ "CLAUDE.md",+ "project/CLAUDE.md",+ );+ }+ }++ // Reuse the installer path so platform-specific Claude Desktop configs+ // are backed up and restored at the same location.+ if filter_agent(AgentKind::ClaudeDesktop) && want_global {+ #[cfg(any(target_os = "macos", target_os = "windows"))]+ {+ let desktop_cfg =+ crate::commands::install_mcp::mcp_config_path(McpClient::ClaudeDesktop)?;+ push_if_file(+ &mut assets,+ AgentKind::ClaudeDesktop,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ desktop_cfg,+ ".claude/claude_desktop_config.json",+ "claude-desktop/claude_desktop_config.json",+ );+ }+ }++ // 2. OpenAI Codex CLI+ if filter_agent(AgentKind::Codex) {+ if want_global {+ let codex_dir = home.join(".codex");+ push_if_file(+ &mut assets,+ AgentKind::Codex,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ codex_dir.join("config.toml"),+ ".codex/config.toml",+ "codex/config.toml",+ );+ push_if_file(+ &mut assets,+ AgentKind::Codex,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ codex_dir.join("mcp.json"),+ ".codex/mcp.json",+ "codex/mcp.json",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::Codex,+ AgentAssetKind::Skill,+ AgentAssetScope::Global,+ &home.join(".agents").join("skills"),+ ".agents/skills",+ "codex/skills/agents",+ )?;+ collect_dir_assets(+ &mut assets,+ AgentKind::Codex,+ AgentAssetKind::Skill,+ AgentAssetScope::Global,+ &codex_dir.join("skills"),+ ".codex/skills",+ "codex/skills/codex",+ )?;+ collect_dir_assets(+ &mut assets,+ AgentKind::Codex,+ AgentAssetKind::Plugin,+ AgentAssetScope::Global,+ &codex_dir.join("plugins"),+ ".codex/plugins",+ "codex/plugins",+ )?;+ }+ if want_project {+ collect_dir_assets(+ &mut assets,+ AgentKind::Codex,+ AgentAssetKind::Skill,+ AgentAssetScope::Project,+ &cwd.join(".agents").join("skills"),+ ".agents/skills",+ "project/agents/skills",+ )?;+ push_if_file(+ &mut assets,+ AgentKind::Codex,+ AgentAssetKind::Instruction,+ AgentAssetScope::Project,+ cwd.join("AGENTS.md"),+ "AGENTS.md",+ "project/AGENTS.md",+ );+ }+ }++ // 3. Antigravity CLI+ if filter_agent(AgentKind::AntigravityCli) {+ let gemini_dir = home.join(".gemini");+ if want_global {+ push_if_file(+ &mut assets,+ AgentKind::AntigravityCli,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ gemini_dir.join("config").join("mcp_config.json"),+ ".gemini/config/mcp_config.json",+ "antigravity/mcp_config.json",+ );+ push_if_file(+ &mut assets,+ AgentKind::AntigravityCli,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ gemini_dir.join("antigravity-cli").join("mcp_config.json"),+ ".gemini/antigravity-cli/mcp_config.json",+ "antigravity/antigravity_mcp.json",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::AntigravityCli,+ AgentAssetKind::Skill,+ AgentAssetScope::Global,+ &gemini_dir.join("antigravity-cli").join("skills"),+ ".gemini/antigravity-cli/skills",+ "antigravity/skills",+ )?;+ collect_dir_assets(+ &mut assets,+ AgentKind::AntigravityCli,+ AgentAssetKind::Plugin,+ AgentAssetScope::Global,+ &gemini_dir.join("antigravity-cli").join("plugins"),+ ".gemini/antigravity-cli/plugins",+ "antigravity/plugins",+ )?;+ }+ if want_project {+ collect_dir_assets(+ &mut assets,+ AgentKind::AntigravityCli,+ AgentAssetKind::Skill,+ AgentAssetScope::Project,+ &cwd.join(".gemini").join("skills"),+ ".gemini/skills",+ "project/gemini/skills",+ )?;+ }+ }++ // 4. Gemini CLI+ if filter_agent(AgentKind::GeminiCli) {+ let gemini_dir = home.join(".gemini");+ if want_global {+ push_if_file(+ &mut assets,+ AgentKind::GeminiCli,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ gemini_dir.join("settings.json"),+ ".gemini/settings.json",+ "gemini/settings.json",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::GeminiCli,+ AgentAssetKind::Skill,+ AgentAssetScope::Global,+ &gemini_dir.join("skills"),+ ".gemini/skills",+ "gemini/skills",+ )?;+ }+ if want_project {+ push_if_file(+ &mut assets,+ AgentKind::GeminiCli,+ AgentAssetKind::Instruction,+ AgentAssetScope::Project,+ cwd.join("GEMINI.md"),+ "GEMINI.md",+ "project/GEMINI.md",+ );+ }+ }++ // 4. Cursor+ if filter_agent(AgentKind::Cursor) {+ if want_global {+ push_if_file(+ &mut assets,+ AgentKind::Cursor,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ home.join(".cursor").join("mcp.json"),+ ".cursor/mcp.json",+ "cursor/mcp.json",+ );+ }+ if want_project {+ push_if_file(+ &mut assets,+ AgentKind::Cursor,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Project,+ cwd.join(".cursor").join("mcp.json"),+ ".cursor/mcp.json",+ "project/cursor/mcp.json",+ );+ push_if_file(+ &mut assets,+ AgentKind::Cursor,+ AgentAssetKind::Instruction,+ AgentAssetScope::Project,+ cwd.join(".cursorrules"),+ ".cursorrules",+ "project/cursor/.cursorrules",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::Cursor,+ AgentAssetKind::Instruction,+ AgentAssetScope::Project,+ &cwd.join(".cursor").join("rules"),+ ".cursor/rules",+ "project/cursor/rules",+ )?;+ }+ }++ // 5. OpenCode (v1 / v2)+ if filter_agent(AgentKind::OpenCode) {+ if want_global {+ let opencode_config =+ crate::commands::install_mcp::mcp_config_path(McpClient::OpenCode)?;+ let opencode_dir = opencode_config+ .parent()+ .map(Path::to_path_buf)+ .context("OpenCode config path has no parent directory")?;+ push_if_file(+ &mut assets,+ AgentKind::OpenCode,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ opencode_config,+ ".config/opencode/opencode.json",+ "opencode/opencode.json",+ );+ push_if_file(+ &mut assets,+ AgentKind::OpenCode,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ opencode_dir.join("opencode.jsonc"),+ ".config/opencode/opencode.jsonc",+ "opencode/opencode.jsonc",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::OpenCode,+ AgentAssetKind::Plugin,+ AgentAssetScope::Global,+ &opencode_dir.join("plugins"),+ ".config/opencode/plugins",+ "opencode/plugins",+ )?;+ }+ if want_project {+ push_if_file(+ &mut assets,+ AgentKind::OpenCode,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Project,+ cwd.join("opencode.json"),+ "opencode.json",+ "project/opencode/opencode.json",+ );+ push_if_file(+ &mut assets,+ AgentKind::OpenCode,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Project,+ cwd.join("opencode.jsonc"),+ "opencode.jsonc",+ "project/opencode/opencode.jsonc",+ );+ }+ }++ // 6. Devin+ if filter_agent(AgentKind::Devin) {+ if want_global {+ let devin_dir = home.join(".devin");+ push_if_file(+ &mut assets,+ AgentKind::Devin,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ devin_dir.join("config.json"),+ ".devin/config.json",+ "devin/config.json",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::Devin,+ AgentAssetKind::Skill,+ AgentAssetScope::Global,+ &devin_dir.join("skills"),+ ".devin/skills",+ "devin/skills",+ )?;+ }+ if want_project {+ collect_dir_assets(+ &mut assets,+ AgentKind::Devin,+ AgentAssetKind::Skill,+ AgentAssetScope::Project,+ &cwd.join(".devin").join("skills"),+ ".devin/skills",+ "project/devin/skills",+ )?;+ }+ }++ // 7. Grok+ if filter_agent(AgentKind::Grok) {+ if want_global {+ let grok_dir = home.join(".grok");+ push_if_file(+ &mut assets,+ AgentKind::Grok,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ grok_dir.join("config.toml"),+ ".grok/config.toml",+ "grok/config.toml",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::Grok,+ AgentAssetKind::Skill,+ AgentAssetScope::Global,+ &grok_dir.join("skills"),+ ".grok/skills",+ "grok/skills",+ )?;+ }+ if want_project {+ push_if_file(+ &mut assets,+ AgentKind::Grok,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Project,+ cwd.join(".grok").join("config.toml"),+ ".grok/config.toml",+ "project/grok/config.toml",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::Grok,+ AgentAssetKind::Skill,+ AgentAssetScope::Project,+ &cwd.join(".grok").join("skills"),+ ".grok/skills",+ "project/grok/skills",+ )?;+ }+ }++ // 8. Kiro CLI+ if filter_agent(AgentKind::KiroCli) && want_global {+ let kiro_dir = home.join(".kiro");+ push_if_file(+ &mut assets,+ AgentKind::KiroCli,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ kiro_dir.join("settings").join("mcp.json"),+ ".kiro/settings/mcp.json",+ "kiro/mcp.json",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::KiroCli,+ AgentAssetKind::Skill,+ AgentAssetScope::Global,+ &kiro_dir.join("agents"),+ ".kiro/agents",+ "kiro/agents",+ )?;+ }++ // 9. OpenClaw+ if filter_agent(AgentKind::OpenClaw) && want_global {+ let openclaw_dir = home.join(".openclaw");+ push_if_file(+ &mut assets,+ AgentKind::OpenClaw,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ openclaw_dir.join("config.json"),+ ".openclaw/config.json",+ "openclaw/config.json",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::OpenClaw,+ AgentAssetKind::Plugin,+ AgentAssetScope::Global,+ &openclaw_dir.join("extensions"),+ ".openclaw/extensions",+ "openclaw/extensions",+ )?;+ }++ // 10. Command Code+ if filter_agent(AgentKind::CommandCode) && want_global {+ let cmdc_dir = home.join(".commandcode");+ push_if_file(+ &mut assets,+ AgentKind::CommandCode,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ cmdc_dir.join("mcp.json"),+ ".commandcode/mcp.json",+ "commandcode/mcp.json",+ );+ }++ // 11. Kimi Code+ if filter_agent(AgentKind::KimiCode) && want_global {+ let kimi_dir = home.join(".kimi");+ push_if_file(+ &mut assets,+ AgentKind::KimiCode,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Global,+ kimi_dir.join("mcp.json"),+ ".kimi/mcp.json",+ "kimi/mcp.json",+ );+ collect_dir_assets(+ &mut assets,+ AgentKind::KimiCode,+ AgentAssetKind::Skill,+ AgentAssetScope::Global,+ &kimi_dir.join("skills"),+ ".kimi/skills",+ "kimi/skills",+ )?;+ }++ // 12. VS Code / Copilot+ if want_project {+ push_if_file(+ &mut assets,+ AgentKind::Other,+ AgentAssetKind::McpConfig,+ AgentAssetScope::Project,+ cwd.join(".vscode").join("mcp.json"),+ ".vscode/mcp.json",+ "project/vscode/mcp.json",+ );+ }++ Ok(assets)+ }++ fn push_if_file(+ assets: &mut Vec<DiscoveredAsset>,+ agent: AgentKind,+ kind: AgentAssetKind,+ scope: AgentAssetScope,+ source: PathBuf,+ target_relative: &str,+ archive_path: &str,+ ) {- if source.is_file() {++ if fs::symlink_metadata(&source).is_ok_and(|metadata| metadata.file_type().is_file()) {+ assets.push(DiscoveredAsset {+ agent,+ kind,+ scope,+ source_path: source,+ target_relative: target_relative.to_string(),+ archive_path: archive_path.to_string(),+ });+ }+ }++ fn collect_dir_assets(+ assets: &mut Vec<DiscoveredAsset>,+ agent: AgentKind,+ kind: AgentAssetKind,+ scope: AgentAssetScope,+ dir: &Path,+ target_prefix: &str,+ archive_prefix: &str,+ ) -> Result<()> {- if !dir.is_dir() {++ if !fs::symlink_metadata(dir).is_ok_and(|metadata| metadata.file_type().is_dir()) {+ return Ok(());+ }+ for entry in fs::read_dir(dir)? {+ let entry = entry?;+ let path = entry.path();+ let file_type = entry.file_type()?;+ if file_type.is_dir() {+ let dir_name = entry.file_name();+ let dir_name_str = dir_name.to_string_lossy();+ if dir_name_str.starts_with('.')+ || dir_name_str == "cache"+ || dir_name_str == "node_modules"+ || dir_name_str == "target"+ || dir_name_str == "venv"+ || dir_name_str == "__pycache__"+ || dir_name_str == "site-packages"+ {+ continue;+ }+ let sub_target = format!("{target_prefix}/{dir_name_str}");+ let sub_archive = format!("{archive_prefix}/{dir_name_str}");+ collect_dir_assets(assets, agent, kind, scope, &path, &sub_target, &sub_archive)?;+ } else if file_type.is_file() {+ let file_name = entry.file_name();+ let file_name_str = file_name.to_string_lossy();+ if file_name_str == ".DS_Store"+ || file_name_str.ends_with(".pyc")+ || file_name_str.ends_with(".pyo")+ {+ continue;+ }+ let target_rel = format!("{target_prefix}/{file_name_str}");+ let archive_path = format!("{archive_prefix}/{file_name_str}");+ assets.push(DiscoveredAsset {+ agent,+ kind,+ scope,+ source_path: path,+ target_relative: target_rel,+ archive_path,+ });+ }+ }+ Ok(())+ }++ fn build_archive(+ output_file: File,+ discovered: &[DiscoveredAsset],+ include_secrets: bool,- home: &Path,+ ) -> Result<usize> {+ let encoder = GzEncoder::new(output_file, Compression::default());+ let mut tar = Builder::new(encoder);+ tar.mode(tar::HeaderMode::Deterministic);+ tar.follow_symlinks(false);++ let sanitizer = if include_secrets {+ None+ } else {+ Some(Sanitizer::new(&SanitizeConfig::default())?)+ };++ let mut entries = Vec::with_capacity(discovered.len());++ for asset in discovered {++ let source_size = fs::symlink_metadata(&asset.source_path)++ .with_context(|| format!("inspecting {}", asset.source_path.display()))?++ .len();++ if source_size > MAX_BACKUP_ASSET_BYTES {++ anyhow::bail!(++ "refusing to archive {}: {} bytes exceeds the per-asset limit of {}",++ asset.source_path.display(),++ source_size,++ MAX_BACKUP_ASSET_BYTES++ );++ }+ let raw_bytes = fs::read(&asset.source_path)+ .with_context(|| format!("reading {}", asset.source_path.display()))?;++ let (final_bytes, is_sanitized) = if let Some(ref sc) = sanitizer+ && matches!(asset.kind, AgentAssetKind::McpConfig)+ {+ if let Ok(text) = std::str::from_utf8(&raw_bytes) {+ let sanitized_text = sc.scrub(text);+ let changed = sanitized_text != text;+ (sanitized_text.into_bytes(), changed)+ } else {+ (raw_bytes, false)+ }+ } else {+ (raw_bytes, false)+ };++ let mut hasher = Sha256::new();+ hasher.update(&final_bytes);+ let sha256 = format!("{:x}", hasher.finalize());++ let mut header = Header::new_gnu();+ header.set_size(final_bytes.len() as u64);- header.set_mode(0o644);++ let mode = portable_mode(&asset.source_path)?;++ header.set_mode(mode.unwrap_or(0o600));+ header.set_mtime(0);+ header.set_cksum();++ tar.append_data(&mut header, &asset.archive_path, Cursor::new(&final_bytes))+ .with_context(|| format!("archiving {}", asset.archive_path))?;++ entries.push(AgentBackupEntry {+ agent: asset.agent,+ asset_kind: asset.kind,+ scope: asset.scope,+ archive_path: asset.archive_path.clone(),+ target_relative: asset.target_relative.clone(),+ sanitized: is_sanitized,+ sha256: Some(sha256),++ mode,+ });+ }++ let any_sanitized = entries.iter().any(|e| e.sanitized);+ let manifest = AgentBackupManifest::new(+ HostInfo {+ os: std::env::consts::OS.to_string(),+ arch: std::env::consts::ARCH.to_string(),- home_dir: Some(home.display().to_string()),++ home_dir: None,+ },+ any_sanitized,+ entries,+ );++ let manifest_bytes =+ serde_json::to_vec_pretty(&manifest).context("serializing agent backup manifest")?;++ let mut manifest_header = Header::new_gnu();+ manifest_header.set_size(manifest_bytes.len() as u64);+ manifest_header.set_mode(0o644);+ manifest_header.set_mtime(0);+ manifest_header.set_cksum();++ tar.append_data(+ &mut manifest_header,+ "manifest.json",+ Cursor::new(&manifest_bytes),+ )+ .context("archiving manifest.json")?;+- tar.finish().context("finalising tar archive")?;++ let encoder = tar.into_inner().context("finalising tar archive")?;++ let output = encoder.finish().context("finalising gzip stream")?;++ output.sync_all().context("syncing gzip stream")?;+ Ok(discovered.len())+ }+++fn portable_mode(path: &Path) -> Result<Option<u32>> {++ #[cfg(unix)]++ {++ use std::os::unix::fs::PermissionsExt as _;++ let mode = fs::metadata(path)++ .with_context(|| format!("reading permissions for {}", path.display()))?++ .permissions()++ .mode()++ & 0o777;++ Ok(Some(mode))++ }++ #[cfg(not(unix))]++ {++ let _ = path;++ Ok(None)++ }++}+++ fn human_bytes(n: u64) -> String {+ const UNITS: &[&str] = &["B", "KiB", "MiB", "GiB"];+ let mut value = n as f64;+ let mut unit = 0;+ while value >= 1024.0 && unit + 1 < UNITS.len() {+ value /= 1024.0;+ unit += 1;+ }+ if unit == 0 {+ format!("{n} {}", UNITS[0])+ } else {+ format!("{value:.2} {}", UNITS[unit])+ }+ }++ /// Match an agent against a list of filter strings, handling kebab-case, snake_case, and aliases.+ pub(crate) fn matches_agent_filter(agent: AgentKind, filter_list: &[String]) -> bool {- let wire = agent.as_str();- let wire_compact = wire.replace(['-', '_'], "");+ filter_list.iter().any(|f| {- let fl = f.trim().to_lowercase();- if fl.is_empty() {- return false;- }- let parsed = AgentKind::from_wire(&fl);- if parsed == agent && parsed != AgentKind::Other {- return true;++ let normalized = f.trim().to_ascii_lowercase().replace('_', "-");++ if agent == AgentKind::Other {++ return matches!(++ normalized.as_str(),++ "other" | "vscode" | "vs-code" | "copilot" | "vscode-copilot"++ );+ }- let fl_compact = fl.replace(['-', '_'], "");- wire == fl- || wire.contains(&fl)- || fl.contains(wire)- || wire_compact == fl_compact- || wire_compact.contains(&fl_compact)- || fl_compact.contains(&wire_compact)++ AgentKind::from_wire(&normalized) == agent+ })+ }diff --cc crates/ai-memory-cli/src/commands/mod.rsindex 40de2e28,3054846c..4c32b16c--- a/crates/ai-memory-cli/src/commands/mod.rs+++ b/crates/ai-memory-cli/src/commands/mod.rs@@@ -73,9 -73,9 +74,10 @@@ pub mod rename_projectpub mod rename_workstream;pub mod render_shared;pub mod reorg;+pub mod repair_backfill_timestamps;pub mod reset;pub mod restore;+ pub mod restore_agents;pub mod restore_page;pub mod resume;pub mod run;diff --cc crates/ai-memory-cli/src/commands/restore_agents.rsindex 00000000,0f0b8206..852aaacdmode 000000,100644..100644--- a/crates/ai-memory-cli/src/commands/restore_agents.rs+++ b/crates/ai-memory-cli/src/commands/restore_agents.rs@@@ -1,0 -1,364 +1,693 @@@-//! `ai-memory restore-agents` — restore AI agent configurations,-//! skills, plugins, and instructions from an archive.++//! `ai-memory restore-agents` - restore host agent assets from a bounded archive.+-use std::collections::HashMap;++use std::collections::{HashMap, HashSet};+ use std::fs::{self, File};-use std::io::Read;++use std::io::{Read, Write};+ use std::path::{Component, Path, PathBuf};++ use ai_memory_core::agent_backup::{- AGENT_BACKUP_SCHEMA_VERSION, AgentAssetScope, AgentBackupManifest,++ AGENT_BACKUP_SCHEMA_VERSION, AgentAssetScope, AgentBackupEntry, AgentBackupManifest,+ };+ use ai_memory_core::ids::AgentKind;-use anyhow::{Context, Result, bail};++use anyhow::{Context as _, Result, anyhow, bail};+ use flate2::read::GzDecoder;-use sha2::{Digest, Sha256};++use sha2::{Digest as _, Sha256};+ use tar::Archive;+ use tracing::info;++ use crate::cli::{AgentBackupScope, McpClient, RestoreAgentsArgs};+ use crate::commands::backup_agents::matches_agent_filter;+ use crate::commands::path_util::{claude_config_dir, home_dir};+ use crate::config::Config;+++const MAX_ARCHIVE_ENTRIES: usize = 20_000;++const MAX_MANIFEST_BYTES: u64 = 4 * 1024 * 1024;++const MAX_ASSET_BYTES: u64 = 128 * 1024 * 1024;++const MAX_ARCHIVE_BYTES: u64 = 512 * 1024 * 1024;++++#[derive(Debug)]++struct StagedAsset {++ path: PathBuf,++ size: u64,++ sha256: String,++}++++#[derive(Debug)]++struct PlannedRestore<'a> {++ entry: &'a AgentBackupEntry,++ target_path: PathBuf,++ staged: &'a StagedAsset,++ exists: bool,++}++++#[derive(Debug)]++struct AppliedRestore {++ target_path: PathBuf,++ backup_path: Option<PathBuf>,++ original_mode: Option<u32>,++}+++ /// Run the `restore-agents` subcommand.+ ///+ /// # Errors-/// Returns an error if the archive cannot be read, contains path traversal,-/// targets unauthorized destination paths, has an unsupported schema version,-/// or fails integrity checks.++/// Returns an error when the archive is malformed, over budget, incomplete,++/// inconsistent with its manifest, or cannot be restored safely.+ pub fn run(_config: &Config, args: RestoreAgentsArgs) -> Result<()> {+ let home = home_dir().context("locating user home directory")?;+ let cwd = std::env::current_dir().context("locating current working directory")?;+- let src = &args.from;- if !src.is_file() {- bail!("backup archive not found at {}", src.display());++ if !args.from.is_file() {++ bail!("backup archive not found at {}", args.from.display());+ }+- let file = File::open(src).with_context(|| format!("opening archive at {}", src.display()))?;- let tar = GzDecoder::new(file);- let mut archive = Archive::new(tar);-- // Read all archive entries into memory keyed by archive_path- let mut files_by_path: HashMap<String, Vec<u8>> = HashMap::new();- let mut manifest_bytes: Option<Vec<u8>> = None;-- for entry in archive.entries()? {- let mut entry = entry?;- let path = entry.path()?.to_string_lossy().to_string();-- validate_archive_path(&path)?;-- let mut buf = Vec::new();- entry.read_to_end(&mut buf)?;-- if path == "manifest.json" {- manifest_bytes = Some(buf);- } else {- files_by_path.insert(path, buf);- }- }-- let Some(manifest_raw) = manifest_bytes else {- bail!("archive at {} is missing manifest.json", src.display());- };-++ let staging = tempfile::tempdir().context("creating restore staging directory")?;++ let (manifest_raw, files_by_path) = stage_archive(&args.from, staging.path())?;+ let manifest: AgentBackupManifest =+ serde_json::from_slice(&manifest_raw).context("parsing agent backup manifest")?;-+ if manifest.version == 0 || manifest.version > AGENT_BACKUP_SCHEMA_VERSION {+ bail!(+ "archive manifest schema version {} is not supported (supported: 1..={})",+ manifest.version,+ AGENT_BACKUP_SCHEMA_VERSION+ );+ }++ let claude_override = claude_config_dir(std::env::var_os("CLAUDE_CONFIG_DIR"));-++ let mut archive_paths = HashSet::with_capacity(manifest.entries.len());++ let mut target_paths = HashSet::with_capacity(manifest.entries.len());+ let mut planned = Vec::new();+ let mut identical_count = 0;++ for entry in &manifest.entries {- if args- .agents- .as_ref()- .is_some_and(|filter| !matches_agent_filter(entry.agent, filter))- {- continue;++ validate_archive_path(&entry.archive_path)?;++ validate_target_relative(entry.scope, &entry.target_relative)?;++ if !archive_paths.insert(entry.archive_path.clone()) {++ bail!(++ "archive manifest contains duplicate asset path {:?}",++ entry.archive_path++ );+ }+++ let staged = files_by_path.get(&entry.archive_path).ok_or_else(|| {++ anyhow!(++ "archive manifest references missing asset {:?}",++ entry.archive_path++ )++ })?;++ let expected_sha = entry.sha256.as_deref().ok_or_else(|| {++ anyhow!(++ "archive asset {:?} is missing its required SHA-256 checksum",++ entry.archive_path++ )++ })?;++ validate_sha256(expected_sha, &entry.archive_path)?;++ if !staged.sha256.eq_ignore_ascii_case(expected_sha) {++ bail!(++ "SHA-256 integrity mismatch for asset {}: expected {}, got {}",++ entry.archive_path,++ expected_sha,++ staged.sha256++ );++ }++ if entry.mode.is_some_and(|mode| mode > 0o777) {++ bail!(++ "archive asset {:?} has unsafe permission bits {:o}",++ entry.archive_path,++ entry.mode.unwrap_or_default()++ );++ }++++ let (base, target_path) = resolve_target(entry, &home, &cwd, claude_override.as_deref())?;++ if !target_paths.insert(target_path.clone()) {++ bail!(++ "archive manifest maps more than one asset to {}",++ target_path.display()++ );++ }++ reject_symlinked_target(&base, &target_path)?;++++ let matches_agent = args++ .agents++ .as_ref()++ .is_none_or(|filter| matches_agent_filter(entry.agent, filter));+ let matches_scope = match args.scope {+ AgentBackupScope::Both => true,+ AgentBackupScope::Global => entry.scope == AgentAssetScope::Global,+ AgentBackupScope::Project => entry.scope == AgentAssetScope::Project,+ };- if !matches_scope {++ if !matches_agent || !matches_scope {+ continue;+ }+- validate_target_relative(entry.scope, &entry.target_relative)?;-- let target_path = match entry.scope {- AgentAssetScope::Global => {- if entry.agent == AgentKind::ClaudeDesktop {- crate::commands::install_mcp::mcp_config_path(McpClient::ClaudeDesktop)?- } else if entry.agent == AgentKind::OpenCode- && let Some(rel) = entry.target_relative.strip_prefix(".config/opencode/")- {- let config =- crate::commands::install_mcp::mcp_config_path(McpClient::OpenCode)?;- config- .parent()- .context("OpenCode config path has no parent directory")?- .join(rel)- } else if entry.agent == AgentKind::ClaudeCode- && let Some(ref custom_dir) = claude_override- && let Some(rel) = entry.target_relative.strip_prefix(".claude/")- {- custom_dir.join(rel)- } else {- home.join(&entry.target_relative)- }++ let exists = match fs::symlink_metadata(&target_path) {++ Ok(metadata) if metadata.file_type().is_file() => true,++ Ok(_) => bail!(++ "refusing to replace non-file destination {}",++ target_path.display()++ ),++ Err(error) if error.kind() == std::io::ErrorKind::NotFound => false,++ Err(error) => {++ return Err(error).with_context(|| format!("inspecting {}", target_path.display()));+ }- AgentAssetScope::Project => cwd.join(&entry.target_relative),+ };++ let identical = exists && files_have_same_digest(&target_path, staged)?;++ if identical {++ identical_count += 1;++ } else {++ planned.push(PlannedRestore {++ entry,++ target_path,++ staged,++ exists,++ });++ }++ }+- let Some(content) = files_by_path.get(&entry.archive_path) else {- warn_missing_asset(&entry.archive_path);- continue;- };++ for archive_path in files_by_path.keys() {++ if !archive_paths.contains(archive_path) {++ bail!("archive contains unmanifested asset {:?}", archive_path);++ }++ }+- // Verify SHA-256 integrity when hash is provided in manifest- if let Some(ref expected_sha) = entry.sha256 {- let mut hasher = Sha256::new();- hasher.update(content);- let actual_sha = format!("{:x}", hasher.finalize());- if !actual_sha.eq_ignore_ascii_case(expected_sha) {- bail!(- "SHA-256 integrity mismatch for asset {}: expected {}, got {}",- entry.archive_path,- expected_sha,- actual_sha- );- }++ if planned.is_empty() {++ if identical_count > 0 {++ println!(++ "All {identical_count} selected assets are already identical on host. Nothing to restore."++ );++ } else {++ println!("No archive assets matched the selected agent and scope filters.");+ }++ return Ok(());++ }++++ let any_sanitized = manifest.sanitized || manifest.entries.iter().any(|entry| entry.sanitized);++ if !args.apply {++ print_dry_run(&planned, identical_count, any_sanitized);++ return Ok(());++ }+- let exists = target_path.is_file();- let is_identical = if exists {- let existing_bytes = fs::read(&target_path)- .with_context(|| format!("reading existing {}", target_path.display()))?;- existing_bytes == *content++ let summary = apply_planned(&planned, args.force)?;++ info!(++ created = summary.created,++ updated = summary.updated,++ identical_count,++ skipped_existing = summary.skipped_existing,++ "restored agent assets"++ );++ println!(++ "\nRestoration complete: {} created, {} updated, {} identical, {} skipped (existing).",++ summary.created, summary.updated, identical_count, summary.skipped_existing++ );++ if any_sanitized {++ eprintln!(++ "Note: this archive contains sanitized configurations. Restored MCP configs may require replacing '[REDACTED:...]' values with valid credentials."++ );++ }++ Ok(())++}++++fn stage_archive(src: &Path, staging: &Path) -> Result<(Vec<u8>, HashMap<String, StagedAsset>)> {++ let file = File::open(src).with_context(|| format!("opening archive at {}", src.display()))?;++ let mut archive = Archive::new(GzDecoder::new(file));++ let mut files_by_path = HashMap::new();++ let mut manifest_bytes = None;++ let mut total_bytes = 0_u64;++++ for (index, entry) in archive.entries()?.enumerate() {++ if index >= MAX_ARCHIVE_ENTRIES {++ bail!("archive contains more than {MAX_ARCHIVE_ENTRIES} entries");++ }++ let mut entry = entry?;++ if !entry.header().entry_type().is_file() {++ bail!("archive entry {} is not a regular file", index + 1);++ }++ let path = entry++ .path()?++ .to_str()++ .context("archive contains a non-UTF-8 path")?++ .to_owned();++ validate_archive_path(&path)?;++ let size = entry.size();++ let limit = if path == "manifest.json" {++ MAX_MANIFEST_BYTES+ } else {- false++ MAX_ASSET_BYTES+ };++ if size > limit {++ bail!("archive entry {:?} exceeds the {} byte limit", path, limit);++ }++ total_bytes = total_bytes++ .checked_add(size)++ .filter(|total| *total <= MAX_ARCHIVE_BYTES)++ .ok_or_else(|| anyhow!("archive expands beyond the {MAX_ARCHIVE_BYTES} byte limit"))?;+- if is_identical {- identical_count += 1;- } else {- planned.push((entry, target_path, content.clone(), exists));++ if path == "manifest.json" {++ if manifest_bytes.is_some() {++ bail!("archive contains more than one manifest.json");++ }++ let mut bytes = Vec::with_capacity(size as usize);++ entry.read_to_end(&mut bytes)?;++ manifest_bytes = Some(bytes);++ continue;++ }++ if files_by_path.contains_key(&path) {++ bail!("archive contains duplicate asset path {:?}", path);++ }++ let staged_path = staging.join(format!("asset-{index:05}"));++ let mut output = File::create(&staged_path)++ .with_context(|| format!("staging archive entry {:?}", path))?;++ let mut hasher = Sha256::new();++ let mut copied = 0_u64;++ let mut buffer = [0_u8; 64 * 1024];++ loop {++ let read = entry.read(&mut buffer)?;++ if read == 0 {++ break;++ }++ copied += read as u64;++ if copied > limit {++ bail!("archive entry {:?} exceeds the {} byte limit", path, limit);++ }++ hasher.update(&buffer[..read]);++ output.write_all(&buffer[..read])?;+ }++ if copied != size {++ bail!(++ "archive entry {:?} declared {size} bytes but yielded {copied}",++ path++ );++ }++ files_by_path.insert(++ path,++ StagedAsset {++ path: staged_path,++ size,++ sha256: format!("{:x}", hasher.finalize()),++ },++ );+ }+- if planned.is_empty() && identical_count > 0 {- println!(- "✓ All {} assets are already identical on host. Nothing to restore.",- identical_count- );- return Ok(());++ Ok((++ manifest_bytes++ .ok_or_else(|| anyhow!("archive at {} is missing manifest.json", src.display()))?,++ files_by_path,++ ))++}++++fn resolve_target(++ entry: &AgentBackupEntry,++ home: &Path,++ cwd: &Path,++ claude_override: Option<&Path>,++) -> Result<(PathBuf, PathBuf)> {++ if entry.scope == AgentAssetScope::Project {++ return Ok((cwd.to_path_buf(), cwd.join(&entry.target_relative)));++ }++ if entry.agent == AgentKind::ClaudeDesktop {++ if entry.target_relative != ".claude/claude_desktop_config.json" {++ bail!(++ "Claude Desktop asset has unexpected destination {:?}",++ entry.target_relative++ );++ }++ let target = crate::commands::install_mcp::mcp_config_path(McpClient::ClaudeDesktop)?;++ let base = target++ .parent()++ .context("Claude Desktop config path has no parent directory")?++ .to_path_buf();++ return Ok((base, target));++ }++ if entry.agent == AgentKind::OpenCode++ && let Some(relative) = entry.target_relative.strip_prefix(".config/opencode/")++ {++ let config = crate::commands::install_mcp::mcp_config_path(McpClient::OpenCode)?;++ let base = config++ .parent()++ .context("OpenCode config path has no parent directory")?++ .to_path_buf();++ return Ok((base.clone(), base.join(relative)));++ }++ if entry.agent == AgentKind::ClaudeCode++ && let Some(custom_dir) = claude_override++ && let Some(relative) = entry.target_relative.strip_prefix(".claude/")++ {++ return Ok((custom_dir.to_path_buf(), custom_dir.join(relative)));+ }++ Ok((home.to_path_buf(), home.join(&entry.target_relative)))++}+- let any_sanitized = manifest.sanitized || manifest.entries.iter().any(|e| e.sanitized);++fn reject_symlinked_target(base: &Path, target: &Path) -> Result<()> {++ let relative = target.strip_prefix(base).with_context(|| {++ format!(++ "restore destination {} escaped its approved base {}",++ target.display(),++ base.display()++ )++ })?;++ let mut current = base.to_path_buf();++ for component in relative.components() {++ let Component::Normal(component) = component else {++ bail!("restore destination contains a non-normal path component");++ };++ current.push(component);++ match fs::symlink_metadata(¤t) {++ Ok(metadata) if metadata.file_type().is_symlink() => {++ bail!(++ "refusing to restore through symlinked path {}",++ current.display()++ );++ }++ Ok(_) => {}++ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}++ Err(error) => {++ return Err(error).with_context(|| format!("inspecting {}", current.display()));++ }++ }++ }++ Ok(())++}+- if !args.apply {- print_dry_run(&planned, identical_count, any_sanitized);- return Ok(());++fn files_have_same_digest(path: &Path, staged: &StagedAsset) -> Result<bool> {++ if fs::metadata(path)?.len() != staged.size {++ return Ok(false);++ }++ Ok(hash_file(path)? == staged.sha256)++}++++fn hash_file(path: &Path) -> Result<String> {++ let mut input = File::open(path).with_context(|| format!("reading {}", path.display()))?;++ let mut hasher = Sha256::new();++ let mut buffer = [0_u8; 64 * 1024];++ loop {++ let read = input.read(&mut buffer)?;++ if read == 0 {++ break;++ }++ hasher.update(&buffer[..read]);+ }++ Ok(format!("{:x}", hasher.finalize()))++}+- let mut created = 0;- let mut updated = 0;- let mut skipped_existing = 0;++#[derive(Debug, Default)]++struct RestoreSummary {++ created: usize,++ updated: usize,++ skipped_existing: usize,++}+- for (_entry, target_path, content, exists) in planned {- if exists && !args.force {++fn apply_planned(planned: &[PlannedRestore<'_>], force: bool) -> Result<RestoreSummary> {++ let mut summary = RestoreSummary::default();++ let mut applied = Vec::new();++++ for item in planned {++ if item.exists && !force {+ println!(+ " [SKIP] {} (already exists, pass --force to overwrite)",- target_path.display()++ item.target_path.display()+ );- skipped_existing += 1;++ summary.skipped_existing += 1;+ continue;+ }-- if let Some(parent) = target_path.parent() {- fs::create_dir_all(parent)- .with_context(|| format!("creating parent dir {}", parent.display()))?;++ let result = apply_one(item, &mut applied);++ if let Err(error) = result {++ let rollback_errors = rollback_applied(&applied);++ if rollback_errors.is_empty() {++ return Err(error).context(format!(++ "restoration failed after {} write(s); earlier writes were rolled back",++ applied.len()++ ));++ }++ return Err(error).context(format!(++ "restoration failed and rollback was incomplete: {}",++ rollback_errors.join("; ")++ ));+ }-- // Keep backup copy of pre-existing file on overwrite- if exists {- let stamp = jiff::Timestamp::now().as_microsecond();- let mut bak = target_path.as_os_str().to_owned();- bak.push(format!(".bak-{stamp}"));- let backup_path = PathBuf::from(bak);- fs::copy(&target_path, &backup_path).with_context(|| {- format!(- "backing up {} to {}",- target_path.display(),- backup_path.display()- )- })?;++ if item.exists {++ println!(" updated {}", item.target_path.display());++ summary.updated += 1;++ } else {++ println!(" created {}", item.target_path.display());++ summary.created += 1;+ }++ }++ Ok(summary)++}+- // Binary-safe atomic write- ai_memory_wiki::write_atomic(&target_path, &content)- .with_context(|| format!("writing {}", target_path.display()))?;++fn apply_one(item: &PlannedRestore<'_>, applied: &mut Vec<AppliedRestore>) -> Result<()> {++ if let Some(parent) = item.target_path.parent() {++ fs::create_dir_all(parent)++ .with_context(|| format!("creating parent dir {}", parent.display()))?;++ }++ let original_mode = portable_mode(&item.target_path)?;++ let backup_path = if item.exists {++ let backup = unique_backup_path(&item.target_path)?;++ fs::copy(&item.target_path, &backup).with_context(|| {++ format!(++ "backing up {} to {}",++ item.target_path.display(),++ backup.display()++ )++ })?;++ Some(backup)++ } else {++ None++ };++ applied.push(AppliedRestore {++ target_path: item.target_path.clone(),++ backup_path,++ original_mode,++ });++++ let content = fs::read(&item.staged.path)++ .with_context(|| format!("reading staged asset {}", item.entry.archive_path))?;++ ai_memory_wiki::write_atomic(&item.target_path, &content)++ .with_context(|| format!("writing {}", item.target_path.display()))?;++ set_portable_mode(&item.target_path, item.entry.mode)?;++ Ok(())++}+- if exists {- println!(" ✓ updated {}", target_path.display());- updated += 1;++fn rollback_applied(applied: &[AppliedRestore]) -> Vec<String> {++ let mut errors = Vec::new();++ for item in applied.iter().rev() {++ let result = if let Some(backup) = &item.backup_path {++ fs::read(backup)++ .with_context(|| format!("reading rollback copy {}", backup.display()))++ .and_then(|content| {++ ai_memory_wiki::write_atomic(&item.target_path, &content)++ .with_context(|| format!("restoring {}", item.target_path.display()))++ })++ .and_then(|_| set_portable_mode(&item.target_path, item.original_mode))+ } else {- println!(" ✓ created {}", target_path.display());- created += 1;++ fs::remove_file(&item.target_path)++ .with_context(|| format!("removing {}", item.target_path.display()))++ };++ if let Err(error) = result {++ errors.push(format!("{}: {error:#}", item.target_path.display()));+ }+ }++ errors++}+- info!(- created,- updated, identical_count, skipped_existing, "restored agent assets"- );- println!(- "\n✓ Restoration complete: {} created, {} updated, {} identical, {} skipped (existing).",- created, updated, identical_count, skipped_existing- );++fn unique_backup_path(target: &Path) -> Result<PathBuf> {++ let stamp = jiff::Timestamp::now().as_microsecond();++ for suffix in 0_u32..=u32::MAX {++ let mut name = target.as_os_str().to_owned();++ name.push(if suffix == 0 {++ format!(".bak-{stamp}")++ } else {++ format!(".bak-{stamp}-{suffix}")++ });++ let candidate = PathBuf::from(name);++ if !candidate.exists() {++ return Ok(candidate);++ }++ }++ bail!(++ "could not allocate a unique backup path beside {}",++ target.display()++ )++}+- if any_sanitized {- eprintln!(- "⚠️ Note: This archive contains sanitized configurations. Restored MCP configs may require updating '[REDACTED:...]' tokens with valid credentials."- );++fn portable_mode(path: &Path) -> Result<Option<u32>> {++ if !path.exists() {++ return Ok(None);++ }++ #[cfg(unix)]++ {++ use std::os::unix::fs::PermissionsExt as _;++ Ok(Some(fs::metadata(path)?.permissions().mode() & 0o777))++ }++ #[cfg(not(unix))]++ {++ let _ = path;++ Ok(None)+ }++}+++fn set_portable_mode(path: &Path, mode: Option<u32>) -> Result<()> {++ #[cfg(unix)]++ if let Some(mode) = mode {++ use std::os::unix::fs::PermissionsExt as _;++ fs::set_permissions(path, fs::Permissions::from_mode(mode & 0o777))++ .with_context(|| format!("restoring permissions on {}", path.display()))?;++ }++ #[cfg(not(unix))]++ let _ = (path, mode);+ Ok(())+ }+-fn print_dry_run(- planned: &[(- &ai_memory_core::agent_backup::AgentBackupEntry,- PathBuf,- Vec<u8>,- bool,- )],- identical_count: usize,- any_sanitized: bool,-) {++fn print_dry_run(planned: &[PlannedRestore<'_>], identical_count: usize, any_sanitized: bool) {+ println!("Restore preview (dry-run, pass --apply to execute):\n");- for (entry, target_path, content, exists) in planned {- let status = if *exists { "[OVERWRITE]" } else { "[CREATE]" };++ for item in planned {++ let status = if item.exists {++ "[OVERWRITE]"++ } else {++ "[CREATE]"++ };+ println!(+ " {status:<12} [{}] {} ({} bytes) -> {}",- entry.agent.as_str(),- entry.asset_kind.label(),- content.len(),- target_path.display()++ item.entry.agent.as_str(),++ item.entry.asset_kind.label(),++ item.staged.size,++ item.target_path.display()+ );+ }+ if identical_count > 0 {+ println!("\n (skipped {identical_count} identical files)");+ }+ if any_sanitized {- println!(- "\n ⚠️ Note: Archive contains sanitized configurations with redacted credentials."++ println!("\n Note: archive contains sanitized configurations with redacted credentials.");++ }++ println!(++ "\nReview the archive source and listed destinations: skills, plugins, and instructions are active content. Rerun with `--apply` to restore."++ );++}++++fn validate_sha256(value: &str, archive_path: &str) -> Result<()> {++ if value.len() != 64 || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {++ bail!(++ "archive asset {:?} has a malformed SHA-256 checksum",++ archive_path+ );+ }- println!("\nRerun with `--apply` to perform restoration.");++ Ok(())+ }++ fn validate_archive_path(path: &str) -> Result<()> {- if path.contains("..")++ if path.is_empty()+ || path.starts_with('/')+ || path.starts_with('\\')++ || path.contains('\\')+ || path.contains('\0')+ || (path.len() >= 2 && path.as_bytes()[1] == b':')++ || path++ .split('/')++ .any(|component| component.is_empty() || component == "." || component == "..")+ {+ bail!("malformed or dangerous archive path: {:?}", path);+ }+ Ok(())+ }+-/// Enforce strict destination allowlisting so restored files cannot escape agent directories.+ fn validate_target_relative(scope: AgentAssetScope, rel_path: &str) -> Result<()> {+ validate_archive_path(rel_path)?;-- let path = Path::new(rel_path);- if !path.components().all(|c| matches!(c, Component::Normal(_))) {++ if !Path::new(rel_path)++ .components()++ .all(|component| matches!(component, Component::Normal(_)))++ {+ bail!(+ "target relative path contains non-normal components: {:?}",+ rel_path+ );+ }++ match scope {+ AgentAssetScope::Global => {- const ALLOWED_GLOBAL_PREFIXES: &[&str] = &[++ const PREFIXES: &[&str] = &[+ ".claude/",- ".claude.json",+ ".codex/",+ ".agents/",+ ".gemini/",+ ".cursor/",+ ".config/opencode/",+ ".devin/",+ ".grok/",+ ".kiro/",+ ".openclaw/",+ ".commandcode/",+ ".kimi/",+ ];- let is_allowed = ALLOWED_GLOBAL_PREFIXES- .iter()- .any(|prefix| rel_path == *prefix || rel_path.starts_with(prefix));- if !is_allowed {++ let allowed = rel_path == ".claude.json"++ || PREFIXES.iter().any(|prefix| rel_path.starts_with(prefix));++ if !allowed {+ bail!(+ "refusing to restore global asset to unauthorized path: {:?}",+ rel_path+ );+ }+ }+ AgentAssetScope::Project => {- const ALLOWED_PROJECT_EXACT: &[&str] = &[++ const EXACT: &[&str] = &[+ "CLAUDE.md",+ "AGENTS.md",+ "GEMINI.md",+ ".cursorrules",+ "opencode.json",+ "opencode.jsonc",+ ".vscode/mcp.json",+ ".cursor/mcp.json",+ ".grok/config.toml",+ ];- const ALLOWED_PROJECT_PREFIXES: &[&str] = &[++ const PREFIXES: &[&str] = &[+ ".claude/skills/",+ ".agents/skills/",+ ".cursor/rules/",+ ".gemini/skills/",+ ".devin/skills/",+ ".grok/skills/",+ ];- let is_allowed = ALLOWED_PROJECT_EXACT.contains(&rel_path)- || ALLOWED_PROJECT_PREFIXES- .iter()- .any(|prefix| rel_path.starts_with(prefix));- if !is_allowed {++ let allowed = EXACT.contains(&rel_path)++ || PREFIXES.iter().any(|prefix| rel_path.starts_with(prefix));++ if !allowed {+ bail!(+ "refusing to restore project asset to unauthorized path: {:?}",+ rel_path+ );+ }+ }+ }+ Ok(())+ }+-fn warn_missing_asset(path: &str) {- tracing::warn!(path, "manifest referenced asset missing from archive body");++#[cfg(test)]++mod tests {++ use super::*;++++ #[test]++ fn rollback_removes_new_files_and_restores_overwrites() {++ let root = tempfile::tempdir().unwrap();++ let existing = root.path().join("existing");++ let created = root.path().join("created");++ let backup = root.path().join("existing.bak");++ fs::write(&existing, b"new").unwrap();++ fs::write(&backup, b"old").unwrap();++ fs::write(&created, b"created").unwrap();++++ let errors = rollback_applied(&[++ AppliedRestore {++ target_path: existing.clone(),++ backup_path: Some(backup),++ original_mode: None,++ },++ AppliedRestore {++ target_path: created.clone(),++ backup_path: None,++ original_mode: None,++ },++ ]);++++ assert!(errors.is_empty(), "{errors:?}");++ assert_eq!(fs::read(existing).unwrap(), b"old");++ assert!(!created.exists());++ }+ }diff --cc crates/ai-memory-cli/tests/suite/backup_agents.rsindex 00000000,26a8d9c1..c5e8f72amode 000000,100644..100644--- a/crates/ai-memory-cli/tests/suite/backup_agents.rs+++ b/crates/ai-memory-cli/tests/suite/backup_agents.rs@@@ -1,0 -1,655 +1,921 @@@+ //! Integration tests for `ai-memory backup-agents` and `ai-memory restore-agents`.++ use std::fs;++use std::io::Write as _;+ use std::path::{Path, PathBuf};+ use std::process::Command;+ use std::sync::{Mutex, MutexGuard};++ static CLI_TEST_LOCK: Mutex<()> = Mutex::new(());++ fn cli_test_lock() -> MutexGuard<'static, ()> {+ CLI_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner())+ }++ fn bin() -> &'static str {+ env!("CARGO_BIN_EXE_ai-memory")+ }++ fn command_with_env(home: &Path, cwd: &Path) -> Command {+ let mut command = Command::new(bin());+ let config_home = home.join(".config");+ let data_home = home.join(".local/share");+ for dir in [&config_home, &data_home] {+ fs::create_dir_all(dir).unwrap();+ }+ command+ .current_dir(cwd)+ .env("HOME", home)+ .env("USERPROFILE", home)+ .env("XDG_CONFIG_HOME", config_home)+ .env("XDG_DATA_HOME", data_home)+ .env("AI_MEMORY_HOME", home)+ .env("AI_MEMORY_DATA_DIR", home.join(".ai-memory-data"))+ .env("AI_MEMORY_EMBEDDING_PROVIDER", "none")+ .env_remove("AI_MEMORY_SERVER_URL")+ .env_remove("AI_MEMORY_AUTH_TOKEN")+ .env_remove("CLAUDE_CONFIG_DIR")+ .env_remove("KIMI_CODE_HOME")+ .env_remove("KIRO_HOME");+ #[cfg(windows)]+ command+ .env("APPDATA", home.join("AppData/Roaming"))+ .env("LOCALAPPDATA", home.join("AppData/Local"));+ command+ }++ fn claude_desktop_config_in(home: &Path) -> Option<PathBuf> {+ #[cfg(target_os = "macos")]+ {+ Some(home.join("Library/Application Support/Claude/claude_desktop_config.json"))+ }+ #[cfg(target_os = "windows")]+ {+ Some(home.join("AppData/Roaming/Claude/claude_desktop_config.json"))+ }+ #[cfg(not(any(target_os = "macos", target_os = "windows")))]+ {+ let _ = home;+ None+ }+ }+++fn sha256(bytes: &[u8]) -> String {++ use sha2::{Digest as _, Sha256};++ format!("{:x}", Sha256::digest(bytes))++}++++fn write_agent_archive(path: &Path, entries: serde_json::Value, bodies: &[(&str, &[u8])]) {++ let file = fs::File::create(path).unwrap();++ let encoder = flate2::write::GzEncoder::new(file, flate2::Compression::default());++ let mut archive = tar::Builder::new(encoder);++ let manifest = serde_json::to_vec(&serde_json::json!({++ "version": 1,++ "created_at": "2026-09-28T00:00:00Z",++ "host": { "os": "linux", "arch": "x86_64" },++ "sanitized": false,++ "entries": entries,++ }))++ .unwrap();++ let mut header = tar::Header::new_gnu();++ header.set_size(manifest.len() as u64);++ header.set_mode(0o600);++ header.set_cksum();++ archive++ .append_data(&mut header, "manifest.json", manifest.as_slice())++ .unwrap();++ for (name, body) in bodies {++ let mut header = tar::Header::new_gnu();++ header.set_size(body.len() as u64);++ header.set_mode(0o600);++ header.set_cksum();++ archive.append_data(&mut header, name, *body).unwrap();++ }++ archive.into_inner().unwrap().finish().unwrap();++}+++ #[test]+ fn backup_and_restore_agents_round_trip() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();++ // 1. Setup mock agent assets+ // Claude+ let claude_settings = home.path().join(".claude/settings.json");+ fs::create_dir_all(claude_settings.parent().unwrap()).unwrap();+ fs::write(+ &claude_settings,+ r#"{"mcpServers":{"local":{"command":"test"}}}"#,+ )+ .unwrap();++ let claude_skill = home.path().join(".claude/skills/test-skill/SKILL.md");+ fs::create_dir_all(claude_skill.parent().unwrap()).unwrap();+ fs::write(&claude_skill, "# Claude Skill\nDetails here").unwrap();++ let claude_md = project.path().join("CLAUDE.md");+ fs::write(&claude_md, "# Project Instructions\nClaude rules").unwrap();++ // Codex+ let codex_config = home.path().join(".codex/config.toml");+ fs::create_dir_all(codex_config.parent().unwrap()).unwrap();+ fs::write(+ &codex_config,+ "[mcp_servers.demo]\nurl = \"http://localhost\"\n",+ )+ .unwrap();++ let agents_md = project.path().join("AGENTS.md");+ fs::write(&agents_md, "# Project Rules\nCodex rules").unwrap();++ let opencode_config = home.path().join(".config/opencode/opencode.json");+ fs::create_dir_all(opencode_config.parent().unwrap()).unwrap();+ fs::write(&opencode_config, r#"{"mcp":{}}"#).unwrap();++ let desktop_config = claude_desktop_config_in(home.path());+ if let Some(path) = &desktop_config {+ fs::create_dir_all(path.parent().unwrap()).unwrap();+ fs::write(path, r#"{"mcpServers":{"desktop":{}}}"#).unwrap();+ }++ // Antigravity / Gemini+ let agy_mcp = home.path().join(".gemini/config/mcp_config.json");+ fs::create_dir_all(agy_mcp.parent().unwrap()).unwrap();+ fs::write(+ &agy_mcp,+ r#"{"mcpServers":{"agy":{"url":"http://127.0.0.1"}}}"#,+ )+ .unwrap();++ let backup_tar = project.path().join("backup.tar.gz");+ fs::write(&backup_tar, "previous archive").unwrap();++ // 2. Run backup-agents+ let output = command_with_env(home.path(), project.path())+ .args([+ "backup-agents",+ "-o",+ backup_tar.to_str().unwrap(),+ "--include-secrets",+ ])+ .output()+ .unwrap();++ assert!(+ output.status.success(),+ "backup-agents failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ assert_eq!(+ fs::metadata(&backup_tar).unwrap().permissions().mode() & 0o777,+ 0o600,+ "archives containing secrets must be private before writing"+ );+ }+ assert!(backup_tar.exists(), "backup tarball was not created");++ // 3. Restore into clean sandbox+ let restore_home = tempfile::tempdir().unwrap();+ let restore_project = tempfile::tempdir().unwrap();++ // Dry-run first+ let dry_run = command_with_env(restore_home.path(), restore_project.path())+ .args(["restore-agents", "-i", backup_tar.to_str().unwrap()])+ .output()+ .unwrap();+ assert!(dry_run.status.success());+ let dry_stdout = String::from_utf8_lossy(&dry_run.stdout);+ assert!(dry_stdout.contains("[CREATE]"));+ assert!(!restore_home.path().join(".claude/settings.json").exists());++ // Apply restore+ let restore = command_with_env(restore_home.path(), restore_project.path())+ .args([+ "restore-agents",+ "-i",+ backup_tar.to_str().unwrap(),+ "--apply",+ ])+ .output()+ .unwrap();+ assert!(+ restore.status.success(),+ "restore-agents failed: {}",+ String::from_utf8_lossy(&restore.stderr)+ );++ // Verify restored assets+ let restored_claude =+ fs::read_to_string(restore_home.path().join(".claude/settings.json")).unwrap();+ assert_eq!(+ restored_claude,+ r#"{"mcpServers":{"local":{"command":"test"}}}"#+ );++ let restored_skill = fs::read_to_string(+ restore_home+ .path()+ .join(".claude/skills/test-skill/SKILL.md"),+ )+ .unwrap();+ assert_eq!(restored_skill, "# Claude Skill\nDetails here");++ let restored_claude_md = fs::read_to_string(restore_project.path().join("CLAUDE.md")).unwrap();+ assert_eq!(restored_claude_md, "# Project Instructions\nClaude rules");++ let restored_codex =+ fs::read_to_string(restore_home.path().join(".codex/config.toml")).unwrap();+ assert_eq!(+ restored_codex,+ "[mcp_servers.demo]\nurl = \"http://localhost\"\n"+ );++ let restored_agents_md = fs::read_to_string(restore_project.path().join("AGENTS.md")).unwrap();+ assert_eq!(restored_agents_md, "# Project Rules\nCodex rules");++ let restored_agy =+ fs::read_to_string(restore_home.path().join(".gemini/config/mcp_config.json")).unwrap();+ assert_eq!(+ restored_agy,+ r#"{"mcpServers":{"agy":{"url":"http://127.0.0.1"}}}"#+ );+ assert!(+ restore_home+ .path()+ .join(".config/opencode/opencode.json")+ .exists()+ );+ if desktop_config.is_some() {+ assert!(+ claude_desktop_config_in(restore_home.path())+ .unwrap()+ .exists()+ );+ }+ }++ #[test]+ fn backup_agents_sanitizes_secrets_by_default() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();++ let claude_settings = home.path().join(".claude/settings.json");+ fs::create_dir_all(claude_settings.parent().unwrap()).unwrap();+ fs::write(+ &claude_settings,+ r#"{"mcpServers":{"remote":{"env":{"GITHUB_TOKEN":"ghp_1234567890abcdef1234567890abcdef1234"}}}}"#,+ )+ .unwrap();++ let backup_tar = project.path().join("sanitized.tar.gz");++ let output = command_with_env(home.path(), project.path())+ .args(["backup-agents", "-o", backup_tar.to_str().unwrap()])+ .output()+ .unwrap();++ assert!(output.status.success());++ #[cfg(unix)]++ {++ use std::os::unix::fs::PermissionsExt as _;++ assert_eq!(++ fs::metadata(&backup_tar).unwrap().permissions().mode() & 0o777,++ 0o600,++ "even sanitized archives contain verbatim active content and must be private"++ );++ }++ // Restore to clean sandbox+ let restore_home = tempfile::tempdir().unwrap();+ let restore_project = tempfile::tempdir().unwrap();++ let restore = command_with_env(restore_home.path(), restore_project.path())+ .args([+ "restore-agents",+ "-i",+ backup_tar.to_str().unwrap(),+ "--apply",+ ])+ .output()+ .unwrap();+ assert!(restore.status.success());++ let restored = fs::read_to_string(restore_home.path().join(".claude/settings.json")).unwrap();+ assert!(+ !restored.contains("ghp_1234567890abcdef1234567890abcdef1234"),+ "raw secret token must be redacted"+ );+ assert!(+ restored.contains("[REDACTED:"),+ "must contain redaction label, got: {restored}"+ );+ }++ #[test]+ fn restore_agents_filters_by_agent_name() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();++ let claude_settings = home.path().join(".claude/settings.json");+ fs::create_dir_all(claude_settings.parent().unwrap()).unwrap();+ fs::write(&claude_settings, r#"{"mcpServers":{"claude":{}}}"#).unwrap();++ let codex_config = home.path().join(".codex/config.toml");+ fs::create_dir_all(codex_config.parent().unwrap()).unwrap();+ fs::write(&codex_config, "[mcp_servers.codex]\n").unwrap();++ let backup_tar = project.path().join("multi_agent.tar.gz");++ let backup_res = command_with_env(home.path(), project.path())+ .args(["backup-agents", "-o", backup_tar.to_str().unwrap()])+ .output()+ .unwrap();+ assert!(backup_res.status.success());++ // Restore ONLY claude+ let restore_home = tempfile::tempdir().unwrap();+ let restore_project = tempfile::tempdir().unwrap();++ let restore_res = command_with_env(restore_home.path(), restore_project.path())+ .args([+ "restore-agents",+ "-i",+ backup_tar.to_str().unwrap(),+ "--agents",+ "claude",+ "--apply",+ ])+ .output()+ .unwrap();+ assert!(restore_res.status.success());++ // Claude restored, Codex NOT restored+ assert!(restore_home.path().join(".claude/settings.json").exists());+ assert!(!restore_home.path().join(".codex/config.toml").exists());+ }++ #[test]+ fn restore_agents_rejects_path_traversal() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();++ let evil_tar = project.path().join("evil.tar.gz");+ {+ let file = std::fs::File::create(&evil_tar).unwrap();+ let enc = flate2::write::GzEncoder::new(file, flate2::Compression::default());+ let mut tar = tar::Builder::new(enc);++ let manifest = r#"{+ "version": 1,+ "created_at": "2026-09-28T00:00:00Z",+ "host": { "os": "macos", "arch": "aarch64" },+ "sanitized": true,+ "entries": [{+ "agent": "claude-code",+ "asset_kind": "mcp-config",+ "scope": "global",+ "archive_path": "evil.txt",+ "target_relative": "../../../etc/passwd"+ }]+ }"#;++ let mut h_m = tar::Header::new_gnu();+ h_m.set_size(manifest.len() as u64);+ h_m.set_cksum();+ tar.append_data(&mut h_m, "manifest.json", std::io::Cursor::new(manifest))+ .unwrap();++ let evil_body = "malicious payload";+ let mut h_b = tar::Header::new_gnu();+ h_b.set_size(evil_body.len() as u64);+ h_b.set_cksum();+ tar.append_data(&mut h_b, "evil.txt", std::io::Cursor::new(evil_body))+ .unwrap();++ tar.finish().unwrap();+ }++ let restore = command_with_env(home.path(), project.path())+ .args([+ "restore-agents",+ "-i",+ evil_tar.to_str().unwrap(),+ "--apply",+ ])+ .output()+ .unwrap();++ assert!(+ !restore.status.success(),+ "must fail on path traversal payload"+ );+ let err = String::from_utf8_lossy(&restore.stderr);+ assert!(err.contains("dangerous") || err.contains("traversal") || err.contains("malformed"));+ }++ #[test]+ fn restore_agents_rejects_unauthorized_destination_path() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();++ let evil_tar = project.path().join("evil_target.tar.gz");+ {+ let file = std::fs::File::create(&evil_tar).unwrap();+ let enc = flate2::write::GzEncoder::new(file, flate2::Compression::default());+ let mut tar = tar::Builder::new(enc);++ let manifest = r#"{+ "version": 1,+ "created_at": "2026-09-28T00:00:00Z",+ "host": { "os": "macos", "arch": "aarch64" },+ "sanitized": true,+ "entries": [{+ "agent": "claude-code",+ "asset_kind": "mcp-config",+ "scope": "project",+ "archive_path": "payload.txt",+ "target_relative": ".git/hooks/pre-commit"+ }]+ }"#;++ let mut h_m = tar::Header::new_gnu();+ h_m.set_size(manifest.len() as u64);+ h_m.set_cksum();+ tar.append_data(&mut h_m, "manifest.json", std::io::Cursor::new(manifest))+ .unwrap();++ let evil_body = "#!/bin/sh\necho malicious";+ let mut h_b = tar::Header::new_gnu();+ h_b.set_size(evil_body.len() as u64);+ h_b.set_cksum();+ tar.append_data(&mut h_b, "payload.txt", std::io::Cursor::new(evil_body))+ .unwrap();++ tar.finish().unwrap();+ }++ let restore = command_with_env(home.path(), project.path())+ .args([+ "restore-agents",+ "-i",+ evil_tar.to_str().unwrap(),+ "--apply",+ ])+ .output()+ .unwrap();++ assert!(+ !restore.status.success(),+ "must reject unauthorized destination path"+ );+ let err = String::from_utf8_lossy(&restore.stderr);+ assert!(err.contains("unauthorized path"));+ }++ #[test]+ fn restore_agents_binary_safe_preserves_raw_bytes() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();++ let plugin_dir = home.path().join(".claude/plugins/test-plugin");+ fs::create_dir_all(&plugin_dir).unwrap();+ let binary_bytes: Vec<u8> = vec![0xFF, 0xFE, 0x00, 0x01, 0x80, 0xC0, 0xDF, 0x80];+ let binary_file = plugin_dir.join("asset.bin");+ fs::write(&binary_file, &binary_bytes).unwrap();++ #[cfg(unix)]++ {++ use std::os::unix::fs::PermissionsExt as _;++ fs::set_permissions(&binary_file, fs::Permissions::from_mode(0o750)).unwrap();++ }++ let backup_tar = project.path().join("binary_test.tar.gz");++ let backup = command_with_env(home.path(), project.path())+ .args(["backup-agents", "-o", backup_tar.to_str().unwrap()])+ .output()+ .unwrap();+ assert!(backup.status.success());++ let restore_home = tempfile::tempdir().unwrap();+ let restore_project = tempfile::tempdir().unwrap();++ let restore = command_with_env(restore_home.path(), restore_project.path())+ .args([+ "restore-agents",+ "-i",+ backup_tar.to_str().unwrap(),+ "--apply",+ ])+ .output()+ .unwrap();+ assert!(+ restore.status.success(),+ "restore failed: {}",+ String::from_utf8_lossy(&restore.stderr)+ );++ let restored_bin = fs::read(+ restore_home+ .path()+ .join(".claude/plugins/test-plugin/asset.bin"),+ )+ .unwrap();+ assert_eq!(+ restored_bin, binary_bytes,+ "binary bytes must be preserved exactly"+ );++ #[cfg(unix)]++ {++ use std::os::unix::fs::PermissionsExt as _;++ let mode = fs::metadata(++ restore_home++ .path()++ .join(".claude/plugins/test-plugin/asset.bin"),++ )++ .unwrap()++ .permissions()++ .mode()++ & 0o777;++ assert_eq!(mode, 0o750, "portable executable bits must be restored");++ }+ }++ #[test]+ fn restore_agents_verifies_sha256_integrity() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();++ let tampered_tar = project.path().join("tampered.tar.gz");+ {+ let file = std::fs::File::create(&tampered_tar).unwrap();+ let enc = flate2::write::GzEncoder::new(file, flate2::Compression::default());+ let mut tar = tar::Builder::new(enc);++ let manifest = r#"{+ "version": 1,+ "created_at": "2026-09-28T00:00:00Z",+ "host": { "os": "macos", "arch": "aarch64" },+ "sanitized": true,+ "entries": [{+ "agent": "claude-code",+ "asset_kind": "instruction",+ "scope": "project",+ "archive_path": "project/CLAUDE.md",+ "target_relative": "CLAUDE.md",+ "sha256": "0000000000000000000000000000000000000000000000000000000000000000"+ }]+ }"#;++ let mut h_m = tar::Header::new_gnu();+ h_m.set_size(manifest.len() as u64);+ h_m.set_cksum();+ tar.append_data(&mut h_m, "manifest.json", std::io::Cursor::new(manifest))+ .unwrap();++ let body = "tampered instruction content";+ let mut h_b = tar::Header::new_gnu();+ h_b.set_size(body.len() as u64);+ h_b.set_cksum();+ tar.append_data(&mut h_b, "project/CLAUDE.md", std::io::Cursor::new(body))+ .unwrap();++ tar.finish().unwrap();+ }++ let restore = command_with_env(home.path(), project.path())+ .args([+ "restore-agents",+ "-i",+ tampered_tar.to_str().unwrap(),+ "--apply",+ ])+ .output()+ .unwrap();++ assert!(+ !restore.status.success(),+ "must fail on SHA-256 integrity mismatch"+ );+ let err = String::from_utf8_lossy(&restore.stderr);+ assert!(err.contains("integrity mismatch") || err.contains("SHA-256"));+ }++ #[test]+ fn backup_and_restore_kebab_case_agent_filter() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();++ let claude_settings = home.path().join(".claude/settings.json");+ fs::create_dir_all(claude_settings.parent().unwrap()).unwrap();+ fs::write(&claude_settings, r#"{"mcpServers":{"claude":{}}}"#).unwrap();++ let codex_config = home.path().join(".codex/config.toml");+ fs::create_dir_all(codex_config.parent().unwrap()).unwrap();+ fs::write(&codex_config, "[mcp_servers.codex]\n").unwrap();++ let backup_tar = project.path().join("kebab_filter.tar.gz");++ // Filter by kebab-case wire string "claude-code"+ let backup_res = command_with_env(home.path(), project.path())+ .args([+ "backup-agents",+ "-o",+ backup_tar.to_str().unwrap(),+ "--agents",+ "claude-code",+ ])+ .output()+ .unwrap();+ assert!(backup_res.status.success());++ let restore_home = tempfile::tempdir().unwrap();+ let restore_project = tempfile::tempdir().unwrap();++ let restore_res = command_with_env(restore_home.path(), restore_project.path())+ .args([+ "restore-agents",+ "-i",+ backup_tar.to_str().unwrap(),+ "--agents",+ "claude-code",+ "--apply",+ ])+ .output()+ .unwrap();+ assert!(restore_res.status.success());++ assert!(restore_home.path().join(".claude/settings.json").exists());+ assert!(!restore_home.path().join(".codex/config.toml").exists());+ }++ #[test]+ fn restore_agents_force_keeps_previous_file_backup() {+ let _guard = cli_test_lock();+ let home = tempfile::tempdir().unwrap();+ let project = tempfile::tempdir().unwrap();+ let source = home.path().join(".claude/settings.json");+ fs::create_dir_all(source.parent().unwrap()).unwrap();+ fs::write(&source, "restored config").unwrap();++ let archive = project.path().join("backup.tar.gz");+ let backup = command_with_env(home.path(), project.path())+ .args([+ "backup-agents",+ "-o",+ archive.to_str().unwrap(),+ "--agents",+ "claude-code",+ "--include-secrets",+ ])+ .output()+ .unwrap();+ assert!(backup.status.success());++ let restore_home = tempfile::tempdir().unwrap();+ let restore_project = tempfile::tempdir().unwrap();+ let existing = restore_home.path().join(".claude/settings.json");+ fs::create_dir_all(existing.parent().unwrap()).unwrap();+ fs::write(&existing, "previous config").unwrap();++ let restore = command_with_env(restore_home.path(), restore_project.path())+ .args([+ "restore-agents",+ "-i",+ archive.to_str().unwrap(),+ "--apply",+ "--force",+ ])+ .output()+ .unwrap();+ assert!(+ restore.status.success(),+ "restore failed: {}",+ String::from_utf8_lossy(&restore.stderr)+ );+ assert_eq!(fs::read(&existing).unwrap(), b"restored config");++ let backup_path = fs::read_dir(existing.parent().unwrap())+ .unwrap()+ .map(|entry| entry.unwrap().path())+ .find(|path| {+ path.file_name()+ .and_then(|name| name.to_str())+ .is_some_and(|name| name.starts_with("settings.json.bak-"))+ })+ .expect("overwrite must keep a backup copy");+ assert_eq!(fs::read(backup_path).unwrap(), b"previous config");+ }++++#[test]++fn restore_agents_requires_a_complete_one_to_one_manifest() {++ let _guard = cli_test_lock();++ let home = tempfile::tempdir().unwrap();++ let project = tempfile::tempdir().unwrap();++ let body = b"# instructions";++ let entry = serde_json::json!({++ "agent": "claude-code",++ "asset_kind": "instruction",++ "scope": "project",++ "archive_path": "project/CLAUDE.md",++ "target_relative": "CLAUDE.md",++ "sha256": sha256(body),++ });++++ let missing = project.path().join("missing.tar.gz");++ write_agent_archive(&missing, serde_json::json!([entry.clone()]), &[]);++ let output = command_with_env(home.path(), project.path())++ .args(["restore-agents", "-i", missing.to_str().unwrap()])++ .output()++ .unwrap();++ assert!(!output.status.success());++ assert!(String::from_utf8_lossy(&output.stderr).contains("missing asset"));++++ let hidden = project.path().join("hidden.tar.gz");++ write_agent_archive(++ &hidden,++ serde_json::json!([]),++ &[("project/CLAUDE.md", body)],++ );++ let output = command_with_env(home.path(), project.path())++ .args(["restore-agents", "-i", hidden.to_str().unwrap()])++ .output()++ .unwrap();++ assert!(!output.status.success());++ assert!(String::from_utf8_lossy(&output.stderr).contains("unmanifested asset"));++++ let duplicate = project.path().join("duplicate.tar.gz");++ let second = serde_json::json!({++ "agent": "codex",++ "asset_kind": "instruction",++ "scope": "project",++ "archive_path": "project/AGENTS-as-CLAUDE.md",++ "target_relative": "CLAUDE.md",++ "sha256": sha256(body),++ });++ write_agent_archive(++ &duplicate,++ serde_json::json!([entry, second]),++ &[++ ("project/CLAUDE.md", body),++ ("project/AGENTS-as-CLAUDE.md", body),++ ],++ );++ let output = command_with_env(home.path(), project.path())++ .args(["restore-agents", "-i", duplicate.to_str().unwrap()])++ .output()++ .unwrap();++ assert!(!output.status.success());++ assert!(String::from_utf8_lossy(&output.stderr).contains("more than one asset"));++}++++#[cfg(unix)]++#[test]++fn restore_agents_rejects_a_symlinked_destination_parent() {++ use std::os::unix::fs::symlink;++++ let _guard = cli_test_lock();++ let source_home = tempfile::tempdir().unwrap();++ let source_project = tempfile::tempdir().unwrap();++ let settings = source_home.path().join(".claude/settings.json");++ fs::create_dir_all(settings.parent().unwrap()).unwrap();++ fs::write(&settings, br#"{"mcpServers":{}}"#).unwrap();++ let archive = source_project.path().join("backup.tar.gz");++ let backup = command_with_env(source_home.path(), source_project.path())++ .args(["backup-agents", "-o", archive.to_str().unwrap()])++ .output()++ .unwrap();++ assert!(backup.status.success());++++ let restore_home = tempfile::tempdir().unwrap();++ let restore_project = tempfile::tempdir().unwrap();++ let outside = tempfile::tempdir().unwrap();++ symlink(outside.path(), restore_home.path().join(".claude")).unwrap();++ let restore = command_with_env(restore_home.path(), restore_project.path())++ .args(["restore-agents", "-i", archive.to_str().unwrap(), "--apply"])++ .output()++ .unwrap();++++ assert!(!restore.status.success());++ assert!(String::from_utf8_lossy(&restore.stderr).contains("symlinked path"));++ assert!(!outside.path().join("settings.json").exists());++}++++#[test]++fn restore_agents_rejects_oversized_entries_from_the_header() {++ let _guard = cli_test_lock();++ let home = tempfile::tempdir().unwrap();++ let project = tempfile::tempdir().unwrap();++ let archive_path = project.path().join("oversized.tar.gz");++ let file = fs::File::create(&archive_path).unwrap();++ let mut encoder = flate2::write::GzEncoder::new(file, flate2::Compression::default());++ let mut header = tar::Header::new_gnu();++ header.set_path("oversized.bin").unwrap();++ header.set_size(128 * 1024 * 1024 + 1);++ header.set_mode(0o600);++ header.set_cksum();++ encoder.write_all(header.as_bytes()).unwrap();++ encoder.finish().unwrap();++++ let output = command_with_env(home.path(), project.path())++ .args(["restore-agents", "-i", archive_path.to_str().unwrap()])++ .output()++ .unwrap();++ assert!(!output.status.success());++ assert!(String::from_utf8_lossy(&output.stderr).contains("exceeds"));++}++++#[test]++fn agent_filters_are_exact_instead_of_substring_matches() {++ let _guard = cli_test_lock();++ let home = tempfile::tempdir().unwrap();++ let project = tempfile::tempdir().unwrap();++ let settings = home.path().join(".claude/settings.json");++ fs::create_dir_all(settings.parent().unwrap()).unwrap();++ fs::write(&settings, br#"{"mcpServers":{}}"#).unwrap();++ let archive = project.path().join("backup.tar.gz");++++ let output = command_with_env(home.path(), project.path())++ .args([++ "backup-agents",++ "-o",++ archive.to_str().unwrap(),++ "--agents",++ "code",++ ])++ .output()++ .unwrap();++ assert!(output.status.success());++ assert!(++ !archive.exists(),++ "ambiguous substring must not select Claude Code"++ );++}++++#[cfg(unix)]++#[test]++fn backup_agents_does_not_follow_config_or_asset_root_symlinks() {++ use std::os::unix::fs::symlink;++++ let _guard = cli_test_lock();++ let home = tempfile::tempdir().unwrap();++ let project = tempfile::tempdir().unwrap();++ let outside = tempfile::tempdir().unwrap();++ let secret = outside.path().join("settings.json");++ fs::write(&secret, br#"{"token":"must-not-leak"}"#).unwrap();++ fs::create_dir_all(home.path().join(".claude")).unwrap();++ symlink(&secret, home.path().join(".claude/settings.json")).unwrap();++ let external_plugins = outside.path().join("plugins");++ fs::create_dir_all(&external_plugins).unwrap();++ fs::write(external_plugins.join("payload"), b"outside plugin").unwrap();++ symlink(&external_plugins, home.path().join(".claude/plugins")).unwrap();++ let archive = project.path().join("backup.tar.gz");++++ let output = command_with_env(home.path(), project.path())++ .args(["backup-agents", "-o", archive.to_str().unwrap()])++ .output()++ .unwrap();++++ assert!(output.status.success());++ assert!(++ !archive.exists(),++ "symlink-only assets must not be archived"++ );++}++++#[test]++fn failed_backup_leaves_the_previous_archive_intact() {++ let _guard = cli_test_lock();++ let home = tempfile::tempdir().unwrap();++ let project = tempfile::tempdir().unwrap();++ let plugin = home.path().join(".claude/plugins/huge.bin");++ fs::create_dir_all(plugin.parent().unwrap()).unwrap();++ fs::File::create(&plugin)++ .unwrap()++ .set_len(128 * 1024 * 1024 + 1)++ .unwrap();++ let archive = project.path().join("backup.tar.gz");++ fs::write(&archive, b"previous valid archive placeholder").unwrap();++++ let output = command_with_env(home.path(), project.path())++ .args(["backup-agents", "-o", archive.to_str().unwrap()])++ .output()++ .unwrap();++++ assert!(!output.status.success());++ assert!(String::from_utf8_lossy(&output.stderr).contains("per-asset limit"));++ assert_eq!(++ fs::read(archive).unwrap(),++ b"previous valid archive placeholder"++ );++}diff --cc crates/ai-memory-core/src/agent_backup.rsindex 00000000,6482f34d..175b1ed1mode 000000,100644..100644--- a/crates/ai-memory-core/src/agent_backup.rs+++ b/crates/ai-memory-core/src/agent_backup.rs@@@ -1,0 -1,107 +1,110 @@@+ //! Domain types for backing up and restoring AI agent assets (skills, MCP configs, plugins, instructions).++ use serde::{Deserialize, Serialize};++ use crate::ids::AgentKind;++ /// Current version of the agent backup archive manifest schema.+ pub const AGENT_BACKUP_SCHEMA_VERSION: u32 = 1;++ /// Classification of an asset used by an AI agent.+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]+ #[serde(rename_all = "kebab-case")]+ pub enum AgentAssetKind {+ /// MCP server configuration file (e.g. `settings.json`, `config.toml`, `mcp.json`).+ McpConfig,+ /// Agent skill file (e.g. `SKILL.md`).+ Skill,+ /// Agent plugin or extension asset.+ Plugin,+ /// Canonical project or agent instruction file (e.g. `CLAUDE.md`, `AGENTS.md`, `.cursorrules`).+ Instruction,+ }++ impl AgentAssetKind {+ /// Human-readable label for CLI reports.+ #[must_use]+ pub const fn label(self) -> &'static str {+ match self {+ Self::McpConfig => "MCP config",+ Self::Skill => "Skill",+ Self::Plugin => "Plugin",+ Self::Instruction => "Instruction",+ }+ }+ }++ /// Scope of the asset: global (user home / system) or project-specific.+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]+ #[serde(rename_all = "kebab-case")]+ pub enum AgentAssetScope {+ /// Global asset stored in the user profile (e.g. `~/.claude/settings.json`, `~/.agents/skills/`).+ Global,+ /// Project-scoped asset stored in the working repository (e.g. `.claude/skills/`, `CLAUDE.md`).+ Project,+ }++ /// Metadata describing host environment where the backup was captured.+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+ pub struct HostInfo {+ /// Operating system name (e.g. "macos", "linux", "windows").+ pub os: String,+ /// Architecture (e.g. "aarch64", "x86_64").+ pub arch: String,+ /// Sanitized user home directory representation if recorded.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub home_dir: Option<String>,+ }++ /// A single backed-up asset entry inside the archive.+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+ pub struct AgentBackupEntry {+ /// AI agent harness associated with this asset.+ pub agent: AgentKind,+ /// Type of the asset (MCP config, skill, plugin, instruction).+ pub asset_kind: AgentAssetKind,+ /// Asset scope (global vs project).+ pub scope: AgentAssetScope,+ /// Relative path inside the tarball archive (e.g. `agents/claude-code/mcp/settings.json`).+ pub archive_path: String,+ /// Path relative to the destination base (e.g. home_dir for Global, project root for Project).+ pub target_relative: String,+ /// Whether this entry was sanitized to remove secrets/tokens.+ #[serde(default)]+ pub sanitized: bool,+ /// SHA-256 hash of the content for integrity verification.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub sha256: Option<String>,++ /// Portable Unix permission bits, with set-id and sticky bits stripped.++ #[serde(default, skip_serializing_if = "Option::is_none")]++ pub mode: Option<u32>,+ }++ /// Root manifest stored at `manifest.json` in the backup archive.+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+ pub struct AgentBackupManifest {+ /// Schema version number.+ pub version: u32,+ /// ISO 8601 creation timestamp.+ pub created_at: String,+ /// Information about host where backup was produced.+ pub host: HostInfo,+ /// Whether any entries were sanitized.+ pub sanitized: bool,+ /// List of backed-up asset entries.+ pub entries: Vec<AgentBackupEntry>,+ }++ impl AgentBackupManifest {+ /// Create a new manifest with default version and given entries.+ #[must_use]+ pub fn new(host: HostInfo, sanitized: bool, entries: Vec<AgentBackupEntry>) -> Self {+ Self {+ version: AGENT_BACKUP_SCHEMA_VERSION,+ created_at: jiff::Timestamp::now().to_string(),+ host,+ sanitized,+ entries,+ }+ }+ }diff --cc docs/ARCHITECTURE.mdindex 9678b46e,a118560d..f272094a--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@@ -564,27 -524,27 +564,28 @@@ wiki browser and JSON APIs stay behind## CLI subcommand surface```-init status run-show continue resume-workstreams rename-workstream workstream-search-audit-contamination search read-page-write-page delete-page serve-reset backup restore-reindex install-hooks hook-install-mcp commit checkpoints-restore-page llm-test forget-sweep-lint curator auto-improve-report-auto-improve finalize-session pending-writes-embed generate-auth-token setup-agent-bootstrap install-instructions install-skills-reorg purge-project rename-project-move-project move-session uninstall-upgrade auth user-completions handoffs purge-session-compact api-key export-okf-message doctor backfill-project reclaim-ledger-versions backup-agents+init status list-projects+run show continue+resume workstreams rename-workstream+workstream-search audit-contamination search+read-page write-page delete-page+serve reset backup+restore reindex install-hooks+hook install-mcp commit+checkpoints restore-page llm-test+forget-sweep lint curator+auto-improve-report auto-improve finalize-session+pending-writes embed generate-auth-token+setup-agent bootstrap install-instructions+install-skills reorg purge-project+rename-project move-project move-session+uninstall upgrade auth+user completions handoffs+purge-session compact api-key+export-okf message doctor+backfill project reclaim-ledger-versions- repair-backfill-timestamps server++repair-backfill-timestamps server backup-agents+ restore-agents```Run `ai-memory --help` for the full tree.diff --cc docs/design-backup-agent-assets.mdindex 00000000,39d1ec98..8e47dc3bmode 000000,100644..100644--- a/docs/design-backup-agent-assets.md+++ b/docs/design-backup-agent-assets.md@@@ -1,0 -1,134 +1,157 @@@-# Design Proposal: Backup and Restore of AI Agent Assets (Skills, MCP, Plugins)++# Backup and Restore of AI Agent Assets (Skills, MCP, Plugins)++ ## 1. Context and Motivation++ `ai-memory` coordinates memory and context across AI coding agents (Claude Code, OpenAI Codex, Antigravity CLI, Gemini CLI, Cursor, OpenCode, Devin, Grok, Kiro, etc.).+-Currently:++Before these commands were added:+ - **Server Backup:** `ai-memory backup` takes a snapshot of the server's SQLite database (`memory.sqlite`), git wiki (`wiki/`), and `config.toml` via `POST /admin/backup`.+ - **Client Configuration Knowledge:** `ai-memory` installers (`install_mcp.rs`, `install_skills.rs`, `install_hooks.rs`, `uninstall.rs`) already have detailed definitions of where each supported AI harness stores MCP servers, skills, plugins, and project instructions.-- **Gap:** There is no command to snapshot, export, backup, or restore the host agent configurations (MCP servers, agent skills, plugins, instructions). When moving to a new machine or backing up a development environment, developers must reconfigure every agent manually.++- **Gap:** There was no command to snapshot, export, backup, or restore host++ agent configurations (MCP servers, agent skills, plugins, instructions).++ Moving to a new machine required reconfiguring every agent manually.++ ---++ ## 2. Target Matrix by Agent Harness++ | Harness | MCP Configuration | Skills (Global / Project) | Plugins / Extensions | Instructions / Rules |+ | :--- | :--- | :--- | :--- | :--- |+ | **Claude Code / Desktop** | `~/.claude.json`<br>`~/.claude/settings.json`<br>`claude_desktop_config.json` | `~/.claude/skills/`<br>`.claude/skills/` | `~/.claude/plugins/`<br>`Claude Extensions/` | `CLAUDE.md` |+ | **OpenAI Codex CLI** | `~/.codex/config.toml`<br>`~/.codex/mcp.json` | `~/.agents/skills/`<br>`.agents/skills/`<br>`~/.codex/skills/` | `~/.codex/plugins/` | `AGENTS.md` |+ | **Antigravity CLI (`agy`) / Gemini** | `~/.gemini/settings.json`<br>`~/.gemini/config/mcp_config.json`<br>`antigravity-cli/mcp_config.json` | `~/.gemini/antigravity-cli/skills/`<br>`~/.gemini/skills/`<br>`.gemini/skills/` | `antigravity-cli/plugins/`<br>`~/.gemini/plugins/` | `GEMINI.md`<br>`AGENTS.md`<br>`rules/` |+ | **Cursor IDE** | `~/.cursor/mcp.json`<br>`.cursor/mcp.json` | — | VS Code / Cursor extensions | `.cursorrules`<br>`.cursor/rules/` |+ | **OpenCode (v1 / v2)** | `opencode.json`<br>`opencode.jsonc`<br>`~/.config/opencode/opencode.json` | `~/.config/opencode/skills/` | `~/.config/opencode/plugins/` | `AGENTS.md` |+ | **Devin CLI** | `~/.devin/config.json` | `~/.devin/skills/` | — | Devin instructions |+ | **Grok Build CLI** | `~/.grok/config.toml` | `~/.grok/skills/` | — | Grok instructions |+ | **Kiro CLI (AWS)** | `~/.kiro/settings/mcp.json` | `~/.kiro/agents/*.json` | — | — |+ | **OpenClaw** | `~/.openclaw/config.json` | — | `~/.openclaw/extensions/` | — |+ | **VS Code Copilot** | `.vscode/mcp.json` | — | Extensions | Copilot instructions |++ Claude Desktop config paths use the same platform-aware resolver as+ `install-mcp`, including packaged Windows installs. OpenCode uses+ `%USERPROFILE%\.config\opencode` on Windows too, as its+ [official troubleshooting guide](https://dev.opencode.ai/docs/troubleshooting/)+ documents.++ ---++ ## 3. Architecture & CLI Design++ ### Dedicated Host CLI Subcommands: `backup-agents` and `restore-agents`++ Host configurations live on the client filesystem, independent of whether the `ai-memory serve` daemon is running. Therefore, backup and restore of agent assets execute as client-side commands.++ #### CLI Command Specification++ ```bash+ # Backup all detected agents into an archive+ ai-memory backup-agents -o agent-assets.tar.gz++ # Filter specific agents or scopes+ ai-memory backup-agents --agents claude,codex,antigravity --scope both -o backup.tar.gz+-# Include raw secrets (warns loudly, sets 0600 file mode)++# Include raw MCP-config secrets (warns loudly; every archive is 0600 on Unix)+ ai-memory backup-agents -o backup.tar.gz --include-secrets++ # Dry-run inspection of an archive before restoring+ ai-memory restore-agents -i backup.tar.gz+-# Apply restoration atomically++# Apply the reviewed restoration plan+ ai-memory restore-agents -i backup.tar.gz --apply+ ```++ ---++ ## 4. Archive Manifest Schema (`manifest.json`)++ Stored in the root of the generated tarball:++ ```json+ {+ "$schema": "https://ai-memory.dev/schemas/agent-backup-v1.json",+ "version": 1,+ "created_at": "2026-09-28T14:30:00Z",+ "host": {+ "os": "macos",+ "arch": "aarch64",- "home_dir": "/Users/developer"++ "home_dir": null+ },+ "sanitized": true,+ "entries": [+ {+ "agent": "claude-code",+ "asset_kind": "mcp-config",+ "scope": "global",+ "archive_path": "agents/claude-code/settings.json",+ "target_relative": ".claude/settings.json"+ },+ {+ "agent": "claude-code",+ "asset_kind": "skill",+ "scope": "global",+ "archive_path": "agents/claude-code/skills/custom-skill/SKILL.md",+ "target_relative": ".claude/skills/custom-skill/SKILL.md"+ },+ {+ "agent": "codex",+ "asset_kind": "mcp-config",+ "scope": "global",+ "archive_path": "agents/codex/config.toml",+ "target_relative": ".codex/config.toml"+ }+ ]+ }+ ```++ ---++ ## 5. Security & Invariants++ 1. **Secret Redaction:**+ - By default, known tokens, bearer headers, and environment keys (`*_TOKEN`, `*_KEY`, `*_SECRET`) in UTF-8 MCP config files are sanitized using `ai-memory-hooks::sanitizer`.+ - Skills, plugins, and instruction files are copied verbatim and may contain secrets.- - Passing `--include-secrets` bypasses MCP redaction; on Unix the archive is set to mode `0600` before writing, and a warning is logged.++ - Passing `--include-secrets` bypasses MCP redaction. Every archive is set++ to mode `0600` on Unix because verbatim instructions and plugins may also++ contain credentials. Other platforms rely on their native ACLs.+ 2. **Symlink Safety:**+ - Archives do not traverse or include external symlinks (`follow_symlinks(false)`).++ - Restore rejects a symlink at the target or in any archive-controlled++ descendant below the approved home/project/config root.+ 3. **Path Traversal Protection:**+ - Restoring rejects traversal and permits only allowlisted agent destinations. Claude Desktop uses the same platform-specific path resolver as `install-mcp`.++ - Archive entries are regular UTF-8 paths only, and entry count, manifest,++ per-file, and total expanded sizes are bounded before content is staged.++ - Every manifest entry must have exactly one body and a well-formed SHA-256;++ duplicate paths/destinations, missing bodies, unmanifested bodies, and++ checksum mismatches are refused. Checksums detect corruption or internal++ inconsistency; they do not authenticate an archive's author.+ 4. **Atomic Restores:**- - Target files are written using temporary files + rename + sync (`ai_memory_wiki::write_atomic`), avoiding partial or corrupted configurations.++ - The output archive is completed and synced in a private sibling tempfile++ before it replaces the requested destination.++ - Target files use temporary file + rename + sync++ (`ai_memory_wiki::write_atomic`). If a later write fails, earlier writes++ are rolled back; timestamped copies of overwritten files remain available.+ - Non-managed custom files are never overwritten without explicit `--force`.++ - Portable Unix execute/read/write bits are restored; set-id and sticky bits++ are never accepted from a manifest.++5. **Active Content:**++ - Skills, plugins, and instruction files can contain executable code or++ model-visible instructions. Restore is dry-run by default and prints this++ warning; only use `--apply` for an archive whose source and listed paths++ you trust. SHA-256 consistency is not a signature.++ ---+-## 6. Implementation Stages++## 6. Implementation Map++ 1. **`crates/ai-memory-core`**:+ - Add `agent_backup` module containing `AgentAssetKind`, `AgentAssetScope`, `AgentBackupEntry`, and `AgentBackupManifest`.+ 2. **`crates/ai-memory-cli`**:+ - `src/cli.rs`: Register `BackupAgents(BackupAgentsArgs)` and `RestoreAgents(RestoreAgentsArgs)`.+ - `src/commands/backup_agents.rs`: Scan host configs, package archive.+ - `src/commands/restore_agents.rs`: Validate manifest, present diffs, write files.+ 3. **Tests**:+ - Roundtrip tests: archive -> verify manifest -> extract into temporary directory -> assert equality.+ - Sanitization tests: ensure keys are redacted unless requested otherwise.+ - Security tests: reject path traversal payloads (`../../etc/passwd`).diff --cc docs/security-boundaries.mdindex 453a5e97,cbd79fc0..497309d1--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@@ -48,21 -44,15 +48,23 @@@ boundary not yet built| 10 | Destructive-op live-process refusal + confirm flags (invariant #9); `purge-project`'s `dry_run` always wins over `confirm` so a preview request can never become destructive | `ai-memory-cli/src/commands/process_guard.rs` `sibling_processes` + confirm flags in `reset`/`restore`/`reindex`/`uninstall --purge-data`/`purge_project`; `admin.rs` `handle_purge_project` checks `req.dry_run` unconditionally, before `req.confirm`, mirroring `reclaim-ledger-versions` | `admin_purge.rs` confirm→400; `removal.rs` — injected live-sibling makes each destructive command bail before touching the data dir; `admin_purge.rs` `purge_project_confirm_true_and_dry_run_true_still_only_previews` — `{"confirm": true, "dry_run": true}` deletes nothing (the regression this row now also covers); `ops.rs` `purge_project_dry_run_changes_nothing` — every project-scoped row count, the `purged_scopes` tombstone, and the `audit_log` row are identical before/after a `PurgeMode::Preview` run; `ops.rs` `purge_project_counts_collateral_damage_in_another_project` and `admin_purge.rs` `purge_project_dry_run_and_confirmed_purge_both_report_collateral_damage_in_another_project` — a purge of project P collaterally deletes an observation, and orphans a handoff's session reference, in a *different* project Q (via `sessions` cascading out of P), and both the preview and the confirmed report count it | STRONG || 10b | Session purge is scope+owner-bound (no cross-session/project over-delete); `purge-session`'s `dry_run` always wins over `confirm`, same as `purge-project` | `ai-memory-store/src/ops.rs` `purge_session` — selection scoped to `(workspace_id, project_id)` and keyed on this session's own `summary_page_id` **or** `path='sessions/<sid>.md'` + `json_extract(frontmatter_json,'$.session_id')=<sid>` (frontmatter owner, not the recursive latest-chain); `in_scope==0 → NotFound` fail-closed; whole op in one transaction; `admin.rs` `handle_purge_session` checks `req.dry_run` unconditionally, before `req.confirm` | `ops.rs` `purge_session_leaves_a_sibling_session_in_the_same_project_intact`, `…refuses_a_session_from_another_project_and_deletes_nothing`, `…refuses_a_session_from_another_workspace`, `…does_not_delete_an_identically_pathed_page_in_another_project`, `…removes_older_summary_versions_without_deleting_prior_manual_page` (#862); `admin_purge.rs` `purge_session_confirm_true_and_dry_run_true_still_only_previews` — `{"confirm": true, "dry_run": true}` deletes nothing; `ops.rs` `purge_session_dry_run_changes_nothing` — every table a session purge touches, the `purged_sessions` tombstone, and the `audit_log` row are identical before/after a `PurgeMode::Preview` run; `ops.rs` `purge_session_counts_collateral_damage_in_another_project` and `admin_purge.rs` `purge_session_dry_run_and_confirmed_purge_both_report_collateral_damage_in_another_project` — purging session S collaterally deletes an observation, and orphans a handoff's session reference, in a *different* project (via `S`'s own id cascading), and both the preview and the confirmed report count it; `admin_purge.rs` `purge_session_dry_run_refuses_a_session_outside_its_named_scope` — the same session previewed under a different real project (same workspace) or a different real workspace whose project shares the name both 404 with no counts in the body, with the session's own scope as the 200 control | STRONG || 10c | Ledger reclaim is content-gated, not filename-gated (invariant #16) | `ai-memory-store/src/ops.rs` `reclaim_ledger_versions` — a candidate row must pass `ai_memory_core::log_ledger::body_opens_with_log_ledger` on its own `body`, and only `is_latest=0 AND superseded_at IS NULL` rows are eligible, so decay-owned rows stay with `forget-sweep`; confirm gate in `admin.rs` `handle_reclaim_ledger_versions` | `reclaim_ledger_versions.rs` `a_prose_page_wearing_the_ledger_name_keeps_its_whole_version_chain`, `an_ordinary_page_chain_in_another_project_is_untouched`, `a_decay_tombstone_stays_with_the_sweep_that_owns_it`; `admin_reclaim_ledger_versions.rs` `deleting_without_confirm_is_refused_and_changes_nothing` (with dry-run and confirmed controls) | 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) | `capture_policy.rs` per-agent `…honors_exclusions` tests | STRONG |+| 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; 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 |-| 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 |+| 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` |+| 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 || 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; `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` `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 |-| 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are never taken from a caller (only derived from already-authorized hits), so there is no page-id entry point to guard | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository`; `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (18 tests) or the SQL filter (9 tests) neutralized | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them |+| 13b | Managed-run lease exclusivity (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and refuses any other `active` run on the workstream inside one transaction (`StoreError::WorkstreamBusy`), regardless of the `lease_owner` label; `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` `wait_out_held_lease` (interactive relaunch) only waits for a reported expiry and retries — it never cancels or claims another run, so the server's busy check stays the sole arbiter | `store/src/lib.rs` `managed_workstream_batches_are_idempotent_and_release_the_lease` (second prepare refused while active); `run.rs` `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over` (renewing holder is reported, never displaced), with controls `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 |+| 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are never taken from a caller (only derived from already-authorized hits), so there is no page-id entry point to guard; incremental `recent` resolves and authorizes the requested project before decoding its scope-bound cursor; batch outcomes do not bypass the capture grant or session owner check | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository`; `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (18 tests) or the SQL filter (9 tests) neutralized; `routes.rs` `api_recent_incremental_rechecks_restricted_scope_on_cursor` (a valid cursor cannot bypass a revoked grant; granted control passes), `api_recent_incremental_paginates_over_120_pages_and_binds_cursor`; `mcp_stateless_http.rs` `generic_machine_client_writes_queries_and_claims_a_handoff` (real machine key, foreign scope and partial scope refused); `router.rs` `an_unauthorized_batch_item_is_consumed_rather_than_retried`, `batch_acknowledges_foreign_collision_then_commits_next_item` (refused foreign item followed by a legitimate stored item) | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them |+| 14b | Repository identity routing (#708) | `ai-memory-store/src/ops.rs` `resolve_project_by_identity` — one transaction; an identity already on a project is never overwritten; an unclaimed project is claimed only when the capturing user may write it (the choke point's `resolve_project_authz` on the same transaction), otherwise it is returned unclaimed; a different identity under the same name splits into a new project with no shared `repo_path`; `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity too; `ai-memory-core/src/repository_identity.rs` strips credentials from remote URLs client-side, and the server accepts only the routing rungs (`explicit`, `git_remote`) from the wire | `tests/suite/identity_resolution.rs` `an_outsider_cannot_take_an_unclaimed_projects_identity` (control: `an_existing_project_is_claimed_in_place`), `two_unrelated_repositories_with_one_folder_name_stay_apart`, `a_created_or_split_project_admits_its_creator`; `router.rs` `one_path_with_two_remotes_is_two_projects`, `two_api_checkouts_with_different_remotes_get_two_projects` (a manifest rung on the wire is ignored); `repository_identity.rs` credential and normalisation tables — the claim guard and the cache key each proven to fail their test when removed | STRONG — first claimant wins: in a restricted workspace a user who creates a project under a remote identity first holds it until root grants others |+| 14c | Client-supplied event time is bounded and self-scoped (#919) | `ai-memory-hooks/src/payload.rs` `HookEnvelope::occurred_at_micros` — a `/hook` caller's optional `occurred_at` must be `> 0` and `<= now + 5min`; it only sets the caller's *own* admitted session's `started_at`/`ended_at`/`created_at`, never another session/project/user, and the ingest dedup `seen_at`/TTL stays on `now` | `payload.rs` `occurred_at_micros_rejects_a_far_future_timestamp`, `…_rejects_non_positive_values`, `…_rejects_garbage_strings` | MEDIUM — self-scoped numeric bound; no cross-tenant surface (a client already controls its own content) |+| 14d | `include_related` shows and walks only readable projects (#708) | `ai-memory-store/src/reader.rs` `related_walk(.., viewer)` — both the outgoing and incoming hop queries carry `readable_repository_predicate("pg.project_id", viewer)`, the same far-end filter `page_links` applies, so a page in a project the viewer cannot read is neither returned nor expanded; `ai-memory-mcp/src/server.rs` `memory_read_page` passes `viewer_from_parts`, and the access bump only touches the filtered nodes | `related_walk.rs` `the_walk_hides_and_does_not_cross_projects_the_viewer_cannot_read` (an outgoing and an incoming neighbour in an ungranted restricted project are absent, and so is a granted page reachable only through one; control: a granted restricted project is shown, and no viewer walks the whole graph) — fails with the predicate removed; `ai-memory-mcp` `server.rs` `bob_does_not_see_restricted_pages_through_the_related_walk` (an ungranted user's `memory_read_page{include_related}` omits the restricted page; control: no viewer still reaches it) — fails with `memory_read_page` passing `None` instead of `viewer_from_parts` | STRONG |-| 15 | Agent-archive restore path confinement and integrity | `ai-memory-cli/src/commands/restore_agents.rs` validates archive paths, allowlists destination paths by scope, verifies provided SHA-256 hashes, and writes atomically | `backup_agents.rs` `restore_agents_rejects_path_traversal`, `restore_agents_rejects_unauthorized_destination_path`, `restore_agents_verifies_sha256_integrity`; `backup_and_restore_agents_round_trip` is the valid-path control | STRONG |++| 15 | Agent-archive restore path confinement, resource bounds, and consistency | `ai-memory-cli/src/commands/restore_agents.rs` stages only bounded regular UTF-8 entries; requires a one-to-one manifest/body/checksum/target mapping; allowlists destinations by scope; rejects symlinked descendants; writes each file atomically and rolls back earlier writes after a later failure. `backup_agents.rs` skips direct and directory-root source symlinks, bounds individual assets, and atomically replaces a private archive only after gzip completion | `backup_agents.rs` `restore_agents_rejects_path_traversal`, `restore_agents_rejects_unauthorized_destination_path`, `restore_agents_verifies_sha256_integrity`, `restore_agents_requires_a_complete_one_to_one_manifest`, `restore_agents_rejects_oversized_entries_from_the_header`, `restore_agents_rejects_a_symlinked_destination_parent`, `backup_agents_does_not_follow_config_or_asset_root_symlinks`, and `failed_backup_leaves_the_previous_archive_intact`; `backup_and_restore_agents_round_trip` is the valid-path control; `restore_agents::tests::rollback_removes_new_files_and_restores_overwrites` covers recovery | STRONG |+## Keeping this current (the standing protocol)1. **Touch a guard, add/extend its adversarial test.** Any change to code in the