Skip to content

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

Rust
232 KB
Raw Blame
//! Command-line interface definition (clap derive).

use std::ffi::OsString;
use std::path::PathBuf;

use clap::{Args, FromArgMatches, Parser, Subcommand};
use clap_complete::Shell;

/// Parse the process argv while making the documented `run` boundary real:
/// once the harness positional appears, every later token is native argv.
///
/// Clap normally keeps recognizing known wrapper flags after a positional,
/// even with `trailing_var_arg`. That would steal OMP's native `--profile`
/// as the launch-profile selector. Inserting clap's ordinary `--` delimiter
/// after the harness keeps the public no-delimiter UX and makes all existing
/// wrapper-after-harness recovery (`--yolo`, `--fresh`, etc.) explicit in the
/// run command rather than dependent on clap's option-name knowledge.
pub(crate) fn parse_process() -> Cli {
    try_parse_from(std::env::args_os()).unwrap_or_else(|error| error.exit())
}

pub(crate) fn try_parse_from<I, T>(args: I) -> Result<Cli, clap::Error>
where
    I: IntoIterator<Item = T>,
    T: Into<OsString> + Clone,
{
    let mut args = args.into_iter().map(Into::into).collect::<Vec<_>>();
    delimit_run_native_args(&mut args);
    let matches = <Cli as clap::CommandFactory>::command().try_get_matches_from(args)?;
    let mut cli = Cli::from_arg_matches(&matches)?;
    if let Command::Run(run) = &mut cli.command {
        // The value parser collapses every `claude*` spelling onto
        // `RunHarnessChoice::Claude`; keep the typed spelling so `run` can
        // prefer a same-named wrapper executable.
        run.claude_wrapper = matches
            .subcommand_matches("run")
            .and_then(|run_matches| run_matches.get_raw("harness"))
            .and_then(|mut raw| raw.next())
            .and_then(std::ffi::OsStr::to_str)
            .and_then(claude_wrapper_spelling)
            .map(str::to_owned);
    }
    Ok(cli)
}

fn delimit_run_native_args(args: &mut Vec<OsString>) {
    let mut index = 1;
    let run_index = loop {
        let Some(raw) = args.get(index).and_then(|arg| arg.to_str()) else {
            return;
        };
        if matches!(raw, "--data-dir" | "--config") {
            index += 2;
            continue;
        }
        if raw.starts_with("--data-dir=") || raw.starts_with("--config=") {
            index += 1;
            continue;
        }
        if raw == "run" {
            break index;
        }
        return;
    };

    index = run_index + 1;
    while index < args.len() {
        let Some(raw) = args[index].to_str() else {
            return;
        };
        if raw == "--" {
            return;
        }
        let key = raw.split_once('=').map_or(raw, |(key, _)| key);
        let takes_separate_value = matches!(
            key,
            "--workspace"
                | "--project"
                | "--workstream"
                | "--new"
                | "--executable"
                | "--profile"
                | "--env"
                | "--env-file"
                | "--data-dir"
                | "--config"
        ) && !raw.contains('=');
        if takes_separate_value {
            index += 2;
            continue;
        }
        if raw.starts_with('-') {
            index += 1;
            continue;
        }

        // No trailing tokens means there is nothing for clap to steal.
        if index + 1 < args.len() {
            args.insert(index + 1, OsString::from("--"));
        }
        return;
    }
}

/// Top-level CLI for the `ai-memory` binary.
#[derive(Debug, Parser)]
#[command(name = "ai-memory", version, about, long_about = None)]
pub struct Cli {
    /// Override the data directory.
    ///
    /// Defaults to a platform path under `dirs::data_local_dir()`. The
    /// config loader also honours `AI_MEMORY_DATA_DIR`.
    #[arg(long, global = true)]
    pub data_dir: Option<PathBuf>,

    /// Path to an explicit config file (defaults to `<data_dir>/config.toml`).
    #[arg(long, global = true)]
    pub config: Option<PathBuf>,

    /// Subcommand to run.
    #[command(subcommand)]
    pub command: Command,
}

/// Top-level subcommands.
#[derive(Debug, Subcommand)]
pub enum Command {
    /// Initialise the data directory layout.
    Init(InitArgs),
    /// Set up a native install in one step: `init`, a user service
    /// (systemd `--user` or a launchd LaunchAgent), and hooks, MCP and skills
    /// for every detected agent, then a read-only self-check. Shows the plan
    /// and asks first unless `--yes` is given. Re-running changes nothing.
    Setup(SetupArgs),
    /// Print runtime status (counts, paths, version).
    Status(StatusArgs),
    /// List every workspace/project pair the server knows about (plain,
    /// scriptable output — the read-only equivalent of hitting
    /// `GET /api/v1/projects` directly, falling back to `GET /admin/projects`
    /// when the server runs without `--enable-web` or `--enable-api`).
    ListProjects(ListProjectsArgs),
    /// Check capture coverage: compare local harness session stores for this
    /// project against what the server captured, and warn when a harness ran
    /// here recently but has no captured sessions (its hook is likely missing).
    /// Also reports agentmemory MCP entries and rules-file guideline blocks
    /// left after a migration; it only reads and prints the fix.
    Doctor(DoctorArgs),
    /// One-time import of this project's existing local harness session history
    /// into a brand-new (empty) ai-memory store, so installing hooks
    /// mid-project doesn't start amnesiac. No-op once the store has any
    /// sessions unless `--force`.
    Backfill(BackfillArgs),
    /// Correct `sessions.started_at`/`ended_at` for sessions that `backfill`
    /// already imported before it carried the transcript's own event times,
    /// by re-reading the local transcripts and matching them by session id.
    /// Dry-run by default; `--confirm` applies.
    RepairBackfillTimestamps(RepairBackfillTimestampsArgs),
    /// Launch an agent in an opt-in, cross-harness managed workstream.
    /// Native arguments are forwarded except exact wrapper flags such as
    /// `--yolo`, `--fresh`, and `--force-unlock`.
    Run(RunArgs),
    /// Pick a local project and installed harness, then launch from that
    /// checkout. Removes the `cd` step `run` requires.
    Show(ShowArgs),
    /// Resume the most recently launched managed checkout from anywhere,
    /// without `cd` and without picking from a list.
    Continue(ContinueArgs),
    /// Interactively pick a managed workstream in the current checkout and launch harness.
    Resume(ResumeArgs),
    /// List open cross-agent handoffs so a stale one can be cancelled by id.
    Handoffs(HandoffsArgs),
    /// Send, list, pop, or cancel cross-project agent messages (a directed,
    /// claim-once mailbox between two projects — see `docs/agent-messaging.md`).
    Message(MessageArgs),
    /// List recent managed workstreams selectable from the current checkout.
    Workstreams(WorkstreamsArgs),
    /// Rename a managed workstream in the current checkout. Metadata only:
    /// the ledger, linked harnesses, and which workstream a bare
    /// `ai-memory run` resumes are all unchanged.
    RenameWorkstream(RenameWorkstreamArgs),
    /// Search the complete visible event ledger for a managed workstream.
    WorkstreamSearch(WorkstreamSearchArgs),
    /// Audit the store for likely cross-project contamination (read-only,
    /// SQL-only). Flags sessions whose cwd resolves to a different project and
    /// observations whose project disagrees with their session.
    AuditContamination(AuditContaminationArgs),
    /// Full-text search the wiki via FTS5.
    Search(SearchArgs),
    /// List the most recently updated wiki pages.
    Recent(RecentArgs),
    /// Fetch and display the full body of a wiki page.
    /// Accepts either `--path` (exact path) or a positional query that
    /// searches FTS5 and fetches the top matching page.
    ReadPage(ReadPageArgs),
    /// Write or update a wiki page atomically (also indexes it in the store).
    WritePage(WritePageArgs),
    /// Delete a single wiki page. The server routes scope resolution
    /// through `resolve_ws_proj`, so a delete targeting a project that
    /// exists in multiple workspaces never silently lands in the wrong
    /// slot (the MCP `memory_delete_page` had that gap until this build).
    DeletePage(DeletePageArgs),
    /// Run the MCP server (with watcher) over stdio or HTTP.
    Serve(ServeArgs),
    /// Wipe the data directory's wiki/, db/, raw/ contents.
    Reset(ResetArgs),
    /// Reclaim free database pages. Deletes nothing.
    ///
    /// Rebuilds the FTS indexes and VACUUMs, returning free pages to the
    /// filesystem. `ai-memory status` reports how much there is to reclaim —
    /// check it first: this takes an exclusive lock and rewrites the whole
    /// database, so every write blocks until it finishes and it needs free
    /// disk space of roughly the database's own size.
    Compact(CompactArgs),
    /// Drop the superseded ledger versions the pre-2.1.1 indexer left behind.
    ///
    /// #660 stopped the indexer from rewriting the whole `log-YYYY-MM.md` row
    /// on every hook append. The fix stopped new rows; it did not remove the
    /// ones already written, and no other command reaches them — `compact`
    /// deletes nothing, `forget-sweep` only hard-deletes decay tombstones, and
    /// `reindex` loses the DB-only state. One reported store held 6,539
    /// versions of 101 live pages.
    ///
    /// Only paths whose *content* is a hook event ledger are considered, so a
    /// real page a human happened to name `log-2026-09.md` keeps its whole
    /// version chain. Each dropped version is a byte prefix of the one after
    /// it, so nothing the file on disk does not already hold is lost.
    ///
    /// Prints what it would remove and changes nothing unless `--confirm` is
    /// passed. See also `ai-memory status` for the reclaimable figure.
    ReclaimLedgerVersions(ReclaimLedgerVersionsArgs),
    /// Snapshot wiki/, db/, and an in-data-dir config.toml into a gzipped tarball.
    ///
    /// This is not a complete host-migration archive: root/hook credentials,
    /// external config files, raw workstream ledgers, logs, and models are
    /// intentionally excluded. See docs/lifecycle-ops.md before moving hosts.
    Backup(BackupArgs),
    /// Snapshot AI agent configurations, skills, and plugins into a portable archive.
    #[command(name = "backup-agents")]
    BackupAgents(BackupAgentsArgs),
    /// Export one project's wiki as an OKF v0.2 bundle tarball.
    ExportOkf(ExportOkfArgs),
    /// Restore a backup tarball into the data directory.
    Restore(RestoreArgs),
    /// Restore AI agent configurations, skills, and plugins from an archive.
    #[command(name = "restore-agents")]
    RestoreAgents(RestoreAgentsArgs),
    /// Rebuild the SQLite index from the wiki/ markdown (the "DB is
    /// rebuildable from files" guarantee). Recreates workspaces/projects from
    /// each scope's `_meta.md` manifest and reindexes every page. Run with the
    /// server stopped, against a freshly-migrated (clean) data dir.
    Reindex(ReindexArgs),
    /// Print (or apply) lifecycle-hook configuration for an agent CLI.
    InstallHooks(InstallHooksArgs),
    /// Emit a single lifecycle hook natively (reads the event payload
    /// from stdin), avoiding a shell spawn. Used by the WindowsNative
    /// hook config; mirrors hooks/<agent>/<event>.sh.
    Hook(HookArgs),
    /// Hidden hook spool drainer used by native session-end hooks.
    #[command(hide = true, name = "hook-drain")]
    HookDrain(HookDrainArgs),
    /// Hidden Windows background host the logon entry `setup` installs
    /// starts: it runs `serve` with no console window and restarts it after
    /// a failure.
    #[command(hide = true, name = "service-host")]
    ServiceHost(ServiceHostArgs),
    /// Generate the marketplace plugins under `plugins/` and their catalogs
    /// (maintainer tool: `bin/release` and the drift test call it).
    #[command(hide = true, name = "render-plugins")]
    RenderPlugins(RenderPluginsArgs),
    /// Print MCP server registration snippets for any supported client.
    /// Current values are listed under `--client`; see docs/mcp-install.md
    /// for the full guide.
    InstallMcp(InstallMcpArgs),
    /// Internal stdio-to-HTTP MCP bridge: session-aware for Claude Code, or
    /// session-less (`--no-session-id`) for every other stdio MCP client.
    #[command(hide = true)]
    McpBridge(McpBridgeArgs),
    /// Stage + commit the wiki tree under git.
    Commit(CommitArgs),
    /// List recent wiki git checkpoints for recovery.
    Checkpoints(CheckpointsArgs),
    /// Restore a single wiki page from a git checkpoint and reindex it.
    RestorePage(RestorePageArgs),
    /// Smoke-test an LLM provider by sending one prompt.
    LlmTest(LlmTestArgs),
    /// Run the M8 retention sweep over episodic pages.
    ForgetSweep(ForgetSweepArgs),
    /// Run the M8 lint pass (stale / duplicates + optional LLM contradiction).
    Lint(LintArgs),
    /// Run the rule-based curator report.
    Curator(CuratorArgs),
    /// Run a read-only auto-improvement telemetry report.
    AutoImproveReport(AutoImproveReportArgs),
    /// Run auto-improvement for one completed session.
    AutoImprove(AutoImproveArgs),
    /// Manually finalize the latest open session for one agent in this project.
    FinalizeSession(FinalizeSessionArgs),
    /// Recover history a server outage missed: drain the local hook spool,
    /// replay degraded-run transcripts through the hook backfill path, and
    /// finish managed runs whose transcript import failed. Safe to re-run.
    Recover(RecoverArgs),
    /// Review, approve, or reject staged auto-improvement proposals.
    PendingWrites(PendingWritesArgs),
    /// Compute + store embeddings for every latest page (M9).
    Embed(EmbedArgs),
    /// Generate a random hex bearer token for AI_MEMORY_AUTH_TOKEN.
    GenerateAuthToken(GenerateAuthTokenArgs),
    /// One-shot agent setup for docker deploys: extract the bundled
    /// hook scripts to a host-mounted directory AND print the matching
    /// config snippet. Replaces the "clone the repo + cargo build"
    /// workflow for users who never want a local Rust toolchain.
    SetupAgent(SetupAgentArgs),
    /// Pre-load an existing project's history into the wiki by
    /// LLM-summarising git log, README, docs/, and module headers
    /// into seed wiki pages. Run once when adopting ai-memory in a
    /// project that's been around for a while. Requires
    /// AI_MEMORY_LLM_PROVIDER configured on the server.
    Bootstrap(BootstrapArgs),
    /// Install the ai-memory usage snippet and managed Agent Skills into the
    /// project (or any markdown file / skill root you specify).
    /// Idempotent — bracketed by `<!-- ai-memory:start -->` /
    /// `<!-- ai-memory:end -->` markers so re-running replaces the
    /// block in place without duplicating.
    InstallInstructions(InstallInstructionsArgs),
    /// Install core-managed ai-memory Agent Skills into agent skill directories.
    InstallSkills(InstallSkillsArgs),
    /// Retro-fit existing sessions + observations to per-cwd projects
    /// based on the cwd captured at session-start. Pages are marked
    /// `is_latest=false` (they were a multi-project mash-up) so the
    /// next consolidation can regenerate them per-project. Idempotent.
    Reorg(ReorgArgs),
    /// Delete a project: its pages, sessions, observations, handoffs,
    /// embeddings, managed workstreams and on-disk wiki files.
    ///
    /// Irreversible — requires `--confirm`. By default this is a logical
    /// delete: the rows are gone and nothing can reach them through the API
    /// or search, but their bytes remain in free pages of the database file
    /// until it is rewritten, as with any SQLite delete. `--compact`
    /// reclaims them; neither mode is forensic erasure, because the wiki git
    /// history and any earlier backup still hold the content.
    PurgeProject(PurgeProjectArgs),
    /// Permanently delete ONE session and everything derived from it.
    ///
    /// Removes the session row, its observations, the handoffs it authored,
    /// its derived wiki page (every version) and their embeddings — scoped
    /// strictly to the named workspace and project. Handoffs this session
    /// only *accepted* are left alone: their text belongs to the session that
    /// wrote them.
    PurgeSession(PurgeSessionArgs),
    /// Rename a project within its workspace. No files move on disk —
    /// the wiki is flat and pages are differentiated by project_id only.
    /// Useful after renaming the project's directory on disk so the hook
    /// router keeps writing into the same logical project.
    RenameProject(RenameProjectArgs),
    /// Move a project into another workspace. A fresh destination is a
    /// lossless TRUE MOVE (re-stamp workspace_id, keep project_id, rename the
    /// dir) — sessions/observations/handoffs and history all survive. A
    /// destination that already holds a same-named project MERGES via
    /// copy+purge (only durable pages migrate, source purged). Either way the
    /// operation is irreversible — requires `--confirm`.
    MoveProject(MoveProjectArgs),
    /// Losslessly merge one project into another inside the same workspace.
    /// Without `--confirm`, prints an exact server-side dry run.
    MergeProject(MergeProjectArgs),
    /// Move one session (or every session of a project) to another project,
    /// re-stamping its observations, handoffs, consolidation jobs and its
    /// `sessions/<id>.md` page in one transaction. Without `--confirm` it
    /// prints what would move (a real dry run, rolled back server-side).
    MoveSession(MoveSessionArgs),
    /// Remove ai-memory's wiring (hooks, MCP, instructions, and default-root
    /// managed skills) from all detected agents. Dry-run unless `--apply`.
    Uninstall(UninstallArgs),
    /// Upgrade a GitHub-release native install: download the matching
    /// release asset, verify its `.sha256`, atomically replace this
    /// binary (and sibling `hooks/` when present), then re-stage hooks
    /// for agents already under the data-dir hooks tree. Docker-wrapper
    /// installs keep using the shell wrapper's `upgrade` (image pull);
    /// package-managed installs (Homebrew, AUR, …) are refused.
    Upgrade(UpgradeArgs),
    /// Re-render installed hooks from the replacement binary during upgrade.
    #[command(hide = true, name = "upgrade-refresh-hooks")]
    UpgradeRefreshHooks,
    /// Manage optional upstream LLM provider authentication.
    Auth(AuthArgs),
    /// Manage human users and their project grants. All subcommands
    /// require the root bearer token. API keys live under `api-key`.
    User(UserArgs),
    /// Manage native `aim_` API credentials. All subcommands require
    /// the root bearer token and `[auth].token_pepper`.
    #[command(name = "api-key")]
    ApiKey(ApiKeyArgs),
    /// Project settings. `project access` sets a project `open` (any user)
    /// or `restricted` (root and grant holders) (#708). Requires the root
    /// bearer token.
    Project(ProjectArgs),
    /// Inspect and curate the cross-project profile: how you usually work,
    /// delivered to every project as defaults below the repository's rules
    /// file. Requires the root bearer token on a multi-user server.
    Profile(ProfileArgs),
    /// Manage local server profiles, which a repository's `.ai-memory.toml`
    /// selects with `server = "<name>"` to route its hook capture to a
    /// different ai-memory server.
    Server(ServerArgs),
    /// Print a shell-completion script to stdout. Generated from this
    /// binary's own command tree, so it never drifts from the real CLI
    /// surface. See `docs/shell-completions.md` for install paths.
    Completions(CompletionsArgs),
}

/// Arguments for `run`. Wrapper-owned flags must precede `harness`; the
/// trailing native argv is deliberately opaque to clap.
#[derive(Debug, Clone, Args)]
#[command(trailing_var_arg = true)]
pub struct RunArgs {
    /// Workspace containing the managed workstream. Defaults to the nearest
    /// `.ai-memory.toml` marker's `workspace`, else `default`.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project override. Defaults to the current repository project.
    #[arg(long, conflicts_with = "project_id")]
    pub project: Option<String>,
    /// Select an existing project by ID and remember it for this checkout.
    /// Requires a server supporting managed project-ID selection.
    #[arg(long, conflicts_with = "project")]
    pub project_id: Option<ai_memory_core::ProjectId>,
    /// Select an existing named workstream instead of the current one.
    #[arg(long, conflicts_with = "new_workstream")]
    pub workstream: Option<String>,
    /// Create and select a fresh named workstream.
    #[arg(long = "new", conflicts_with = "workstream")]
    pub new_workstream: Option<String>,
    /// Override the native harness executable path.
    #[arg(long)]
    pub executable: Option<PathBuf>,
    /// Disable native permission prompts using the selected harness's
    /// equivalent dangerous-mode option.
    #[arg(long)]
    pub yolo: bool,
    /// Everything `--yolo` does, plus — for Claude — forcing
    /// `bypassPermissions` via `--settings` over any settings `defaultMode`.
    /// Claude still honors your own explicit `ask` rules in every mode. For
    /// every other harness it is interchangeable with `--yolo`; passing both
    /// is redundant but fine. Off by default; `[claude_true_yolo]` in
    /// config.toml applies the same Claude extra to an explicit `--yolo`
    /// launch. Best paired with ai-jail — see
    /// `docs/design-yolo-safety-ai-jail.md`.
    #[arg(long = "true-yolo")]
    pub true_yolo: bool,
    /// Re-run this session inside ai-jail without asking. Bare `--jail` uses
    /// the smart defaults (credentials present on this host, SSH for an SSH
    /// `origin`, worktree metadata in a linked worktree); `--jail=LIST` enables
    /// exactly the comma-separated ai-jail toggles listed (`github`, `aws`,
    /// `ssh`, `gpu`, `docker`, …; `no-X` forces one off; `all`; `none`) and
    /// forces every other checklist row off, so it is exact. A
    /// project `.ai-jail` in the launch directory replaces the smart defaults
    /// (a list still applies on top). Fails when ai-jail is not usable here;
    /// ignored inside ai-jail. Wrapper-owned
    /// like `--yolo`, never forwarded to the harness. See
    /// `docs/design-yolo-safety-ai-jail.md`.
    #[arg(
        long,
        value_name = "TOGGLES",
        num_args = 0..=1,
        require_equals = true,
        default_missing_value = "",
        conflicts_with = "no_jail"
    )]
    pub jail: Option<String>,
    /// Never re-run inside ai-jail: skips the `--yolo` ai-jail offer (the
    /// `--yolo` warning itself still shows).
    #[arg(long)]
    pub no_jail: bool,
    /// Start a new native session in the selected workstream instead of
    /// resuming or adopting an existing harness session.
    #[arg(long)]
    pub fresh: bool,
    /// Force-expire the selected workstream's active lease before launching.
    /// Use only when the previous launcher is gone: its later heartbeat or
    /// finish will be refused. The server permits takeover only for the same
    /// authenticated operator (or the single-user, unattributed owner).
    #[arg(long)]
    pub force_unlock: bool,
    /// Skip the one-time auto-install of this harness's ai-memory hooks + MCP.
    /// Auto-wire is on by default so a managed launch captures without a manual
    /// `install-hooks`/`install-mcp` step; pass this (or set
    /// `AI_MEMORY_RUN_AUTOWIRE=false`) to launch without touching harness config.
    #[arg(long)]
    pub no_autowire: bool,
    /// Return to the shell after the harness exits without offering the
    /// switch/rerun menu. Also set with `[run] exit_prompt = false` in
    /// config.toml or `AI_MEMORY_RUN_EXIT_PROMPT=false`.
    #[arg(long)]
    pub no_exit_prompt: bool,
    /// Refuse to launch when the ai-memory server is unreachable, restoring
    /// the pre-degraded-launch fail-closed behavior. Without this flag an
    /// unreachable server downgrades the launch: the harness still starts
    /// (hooks spool locally, no workstream lease or context is delivered) and
    /// the child's exit code is returned. Also set with `run.require_server
    /// = true` in config.toml or `AI_MEMORY_RUN_REQUIRE_SERVER=true`.
    #[arg(long)]
    pub require_server: bool,
    /// Apply a named env-only launch profile from
    /// `[run.profiles.<name>.env]` in config.toml. Must precede `harness`;
    /// a later `--env-file` or `--env` entry wins on the same key.
    #[arg(long, value_name = "NAME")]
    pub profile: Option<String>,
    /// Extra environment variable for the spawned harness, `KEY=VALUE`.
    /// Repeatable; wrapper-owned like `--yolo`/`--executable`, so it must
    /// precede `harness`. Reaches the spawned process, ai-memory's own
    /// native-session resolution and first-launch auto-wire (e.g.
    /// `CLAUDE_CONFIG_DIR`), so session store, hooks and MCP agree on one
    /// config home. A later `--env` wins over an earlier one and over a
    /// same-key `--env-file` entry.
    #[arg(long = "env", value_parser = parse_env_kv, value_name = "KEY=VALUE")]
    pub env: Vec<(String, String)>,
    /// Read `KEY=VALUE` lines from this file (blank lines and `#` comments
    /// skipped) and merge them into the launch environment (same reach as
    /// `--env`) before `--env` entries, which override a same-key line here.
    #[arg(long = "env-file", value_name = "PATH")]
    pub env_file: Option<PathBuf>,
    /// Agent harness to launch. When omitted, continue the newest managed or
    /// checkout-local session among the auto-detected harnesses. Any value
    /// starting with `claude` (e.g. `claude-corp`, `claude-personal`) also
    /// selects the Claude harness — see `parse_run_harness_choice` — and, when
    /// no `--executable` is given and an executable with that exact name is on
    /// `PATH`, launches it instead of plain `claude`.
    #[arg(value_parser = parse_run_harness_choice)]
    pub harness: Option<RunHarnessChoice>,
    /// The `claude*` spelling typed as `harness` when it is a wrapper name
    /// rather than a fixed alias (`claude`, `claude-code`). Filled by
    /// [`try_parse_from`]; `run` uses it as the default `--executable`.
    #[arg(skip)]
    pub claude_wrapper: Option<String>,
    /// Native harness arguments, forwarded byte-for-byte and in order.
    #[arg(allow_hyphen_values = true, trailing_var_arg = true)]
    pub native_args: Vec<OsString>,
}

/// Harnesses supported by managed workstreams.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum RunHarnessChoice {
    /// Anthropic Claude Code (`claude`). Any `claude*`-prefixed name (e.g.
    /// `claude-corp`, `claude-personal`) also selects this harness — see
    /// `parse_run_harness_choice`.
    #[value(alias = "claude-code")]
    Claude,
    /// OpenAI Codex CLI.
    Codex,
    /// OpenCode; probes the selected executable and uses its V1 or V2 contracts.
    #[value(name = "opencode", alias = "open-code")]
    OpenCode,
    /// OpenCode V2 compatibility alias; forces the V2 contracts.
    #[value(name = "opencode2", alias = "opencode-v2", alias = "open-code2")]
    OpenCode2,
    /// Pi coding agent.
    Pi,
    /// Charmbracelet Crush.
    Crush,
    /// Oh My Pi.
    #[value(alias = "oh-my-pi")]
    Omp,
    /// Moonshot AI Kimi Code.
    #[value(name = "kimi", alias = "kimi-code", alias = "kimi-cli")]
    Kimi,
    /// Command Code CLI.
    #[value(
        name = "command-code",
        alias = "commandcode",
        alias = "cmdc",
        alias = "cmd"
    )]
    CommandCode,
    /// Amazon Kiro CLI (v2 engine).
    #[value(name = "kiro", alias = "kiro-cli")]
    Kiro,
    /// Grok Build CLI (xAI).
    #[value(alias = "grok-build")]
    Grok,
    /// Google Antigravity CLI (`agy`).
    #[value(name = "antigravity", alias = "antigravity-cli", alias = "agy")]
    Antigravity,
    /// GitHub Copilot CLI (`copilot`). `run`'s positional names only
    /// command-line harnesses, so the bare name cannot mean VS Code Copilot
    /// here the way `install-mcp --client copilot` does.
    #[value(name = "copilot", alias = "copilot-cli")]
    Copilot,
}

/// Parses the `run` harness positional, additionally wildcarding every
/// `claude*` spelling onto [`RunHarnessChoice::Claude`].
///
/// Callers who juggle more than one Claude account (e.g. Corporate and
/// Personal) commonly resolve `claude` to different accounts through a
/// `PATH`-visible wrapper script per account (a plain shell `alias` is
/// invisible to us — `ai-memory run` execs directly, without going through
/// an interactive shell). Naming those wrappers `claude-corp` /
/// `claude-personal` makes the spelling itself readable in shell history, and
/// this parser stops it being rejected as an unknown value.
///
/// The typed spelling is kept (see [`RunArgs::claude_wrapper`]): when it names
/// an executable on the launch `PATH` and `--executable` is absent, `run`
/// launches that wrapper. Before, the spelling was dropped here and plain
/// `claude` started on the wrong account without any hint.
fn parse_run_harness_choice(value: &str) -> Result<RunHarnessChoice, String> {
    use clap::ValueEnum as _;
    if let Ok(choice) = RunHarnessChoice::from_str(value, true) {
        return Ok(choice);
    }
    if value.len() > "claude".len() && value.to_ascii_lowercase().starts_with("claude") {
        return Ok(RunHarnessChoice::Claude);
    }
    let known = RunHarnessChoice::value_variants()
        .iter()
        .filter_map(clap::ValueEnum::to_possible_value)
        .map(|value| value.get_name().to_string())
        .collect::<Vec<_>>()
        .join(", ");
    Err(format!(
        "invalid value '{value}' for harness; expected one of: {known}, or any `claude*` spelling"
    ))
}

/// The wrapper name behind a `claude*` harness spelling, or `None` for the
/// fixed names (`claude`, `claude-code`, any case) and non-Claude values.
fn claude_wrapper_spelling(value: &str) -> Option<&str> {
    use clap::ValueEnum as _;
    (RunHarnessChoice::from_str(value, true).is_err()
        && parse_run_harness_choice(value) == Ok(RunHarnessChoice::Claude))
    .then_some(value)
}

/// Parse one `KEY=VALUE` entry for `--env` (also reused for `--env-file`
/// lines). The value is taken literally — no expansion, no interpretation —
/// so a caller-supplied value reaches the harness exactly as written.
pub(crate) fn parse_env_kv(value: &str) -> Result<(String, String), String> {
    let Some((key, value)) = value.split_once('=') else {
        return Err(format!(
            "invalid value '{value}' for --env; expected KEY=VALUE"
        ));
    };
    if key.is_empty() {
        return Err(format!(
            "invalid value '{key}={value}' for --env; KEY must not be empty"
        ));
    }
    // Dotenv files are commonly written `KEY = value`. The caller trims the
    // line, not the halves, so that spelling yields a key with a trailing
    // space: nothing the harness or a shell can read, and the override
    // silently does nothing. Refuse it rather than guess, and leave the value
    // literal as documented above.
    if key.chars().any(char::is_whitespace) {
        return Err(format!(
            "invalid value '{key}={value}' for --env; KEY must not contain whitespace"
        ));
    }
    Ok((key.to_string(), value.to_string()))
}

/// Arguments for `show`.
#[derive(Debug, Args)]
pub struct ShowArgs {
    /// Only list local projects resolving to this workspace.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Use saved local checkout links only; skip the depth-1 directory scan.
    #[arg(long)]
    pub no_scan: bool,
    /// Print structured project and harness choices instead of opening menus.
    /// Required when stdin or stdout is not a terminal.
    #[arg(long)]
    pub json: bool,
    /// Disable native permission prompts using the selected harness's
    /// equivalent dangerous-mode option. Forwarded to `run`.
    #[arg(long)]
    pub yolo: bool,
    /// Claude-only true-yolo (see `RunArgs::true_yolo`). Forwarded to `run`.
    #[arg(long = "true-yolo")]
    pub true_yolo: bool,
    /// Start a new native session instead of resuming or adopting an existing
    /// harness session. Forwarded to `run`.
    #[arg(long)]
    pub fresh: bool,
    /// Native harness arguments, forwarded byte-for-byte and in order.
    #[arg(allow_hyphen_values = true, trailing_var_arg = true)]
    pub native_args: Vec<OsString>,
}

/// Arguments for `continue`.
///
/// Deliberately smaller than [`ShowArgs`]: `continue` always delegates to
/// `run`'s bare mode, which rejects native argv and `--executable` because
/// their meaning depends on a harness the user did not name.
#[derive(Debug, Args)]
pub struct ContinueArgs {
    /// Only consider checkouts resolving to this workspace.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Disable native permission prompts using the resolved harness's
    /// equivalent dangerous-mode option. Forwarded to `run`.
    #[arg(long)]
    pub yolo: bool,
    /// Claude-only true-yolo (see `RunArgs::true_yolo`). Forwarded to `run`.
    #[arg(long = "true-yolo")]
    pub true_yolo: bool,
    /// Start a new native session instead of resuming the linked one.
    /// Forwarded to `run`.
    #[arg(long)]
    pub fresh: bool,
}

/// Arguments for `resume`.
///
/// The picker deliberately accepts only wrapper-owned flags. Harness selection
/// happens interactively, then it delegates to `run --workstream NAME` in the
/// selected checkout (the current one unless `--all` is given).
#[derive(Debug, Args)]
pub struct ResumeArgs {
    /// Require the current checkout to resolve to this workspace; with
    /// `--all`, only consider checkouts resolving to it.
    #[arg(long)]
    pub workspace: Option<String>,
    /// List workstreams from every locally linked checkout instead of only
    /// the current one.
    #[arg(long)]
    pub all: bool,
    /// Maximum matching workstreams to show (defaults to all).
    #[arg(long, value_parser = clap::value_parser!(u32).range(1..))]
    pub limit: Option<u32>,
    /// Initial case-insensitive workstream-name search; type to edit it.
    #[arg(long)]
    pub search: Option<String>,
    /// Disable native permission prompts using the resolved harness's
    /// equivalent dangerous-mode option. Forwarded to `run`.
    #[arg(long)]
    pub yolo: bool,
    /// Claude-only true-yolo (see `RunArgs::true_yolo`). Forwarded to `run`.
    #[arg(long = "true-yolo")]
    pub true_yolo: bool,
    /// Start a new native session instead of resuming the linked one.
    /// Forwarded to `run`.
    #[arg(long)]
    pub fresh: bool,
}

/// Arguments for `workstreams`.
/// Arguments for `handoffs`.
#[derive(Debug, Args)]
pub struct HandoffsArgs {
    /// Workspace to inspect (defaults to the resolved scope).
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project to inspect (defaults to the resolved scope).
    #[arg(long)]
    pub project: Option<String>,
    /// Maximum handoffs to list.
    #[arg(long, default_value_t = 50, value_parser = clap::value_parser!(u16).range(1..=500))]
    pub limit: u16,
    /// Emit JSON instead of the human listing.
    #[arg(long)]
    pub json: bool,
    /// Expire every open handoff in the scope instead of listing them.
    ///
    /// Unlike the automatic sweep this does NOT spare manual handoffs or ones
    /// from another directory — those exemptions are exactly what a leftover
    /// backlog is made of, so honouring them would clear nothing. Pair with
    /// `--older-than-days` to keep recent batons.
    ///
    /// This is a state change, not a delete: the summary and provenance
    /// survive and the handoff simply stops being consumable. Requires
    /// `--confirm`.
    #[arg(long)]
    pub expire_all: bool,
    /// With `--expire-all`, only expire handoffs at least this many days old.
    #[arg(long)]
    pub older_than_days: Option<u32>,
    /// REQUIRED by `--expire-all`.
    #[arg(long)]
    pub confirm: bool,
}

/// Arguments for `message`.
#[derive(Debug, Args)]
pub struct MessageArgs {
    /// Cross-project message action to run.
    #[command(subcommand)]
    pub command: MessageCommand,
}

/// Subcommands for `message`.
#[derive(Debug, Subcommand)]
pub enum MessageCommand {
    /// Drop a message into another project's inbox.
    Send(MessageSendArgs),
    /// List pending messages in this project's mailbox.
    List(MessageListArgs),
    /// Claim (pop) exactly one pending message from this project's inbox.
    Pop(MessagePopArgs),
    /// Retract still-pending messages this project has sent.
    Cancel(MessageCancelArgs),
}

/// Arguments for `message send`.
#[derive(Debug, Args)]
pub struct MessageSendArgs {
    /// Recipient workspace.
    #[arg(long)]
    pub to_workspace: String,
    /// Recipient project.
    #[arg(long)]
    pub to_project: String,
    /// Optional one-line subject.
    #[arg(long)]
    pub subject: Option<String>,
    /// How the sender knows the claim.
    #[arg(long, default_value = "unknown", value_parser = ["unknown", "measured", "reported", "inferred"])]
    pub nature: String,
    /// Supporting evidence. Required by the server for `--nature measured`.
    #[arg(long)]
    pub evidence: Option<String>,
    /// Message body. Omitted reads the full body from stdin.
    pub body: Option<String>,
    /// Sender workspace (defaults to the resolved scope).
    #[arg(long)]
    pub from_workspace: Option<String>,
    /// Sender project (defaults to the resolved scope).
    #[arg(long)]
    pub from_project: Option<String>,
    /// Emit JSON instead of a human confirmation.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `message list`.
#[derive(Debug, Args)]
pub struct MessageListArgs {
    /// Workspace to inspect (defaults to the resolved scope).
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project to inspect (defaults to the resolved scope).
    #[arg(long)]
    pub project: Option<String>,
    /// List sent, still-cancellable mail instead of the inbox.
    #[arg(long)]
    pub outbox: bool,
    /// Maximum messages to list.
    #[arg(long, default_value_t = 50, value_parser = clap::value_parser!(u16).range(1..=200))]
    pub limit: u16,
    /// Emit JSON instead of the human listing.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `message pop`.
#[derive(Debug, Args)]
pub struct MessagePopArgs {
    /// Receive mail addressed to this harness (for example codex or claude-code).
    #[arg(long)]
    pub agent: Option<String>,
    /// Workspace to pop from (defaults to the resolved scope).
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project to pop from (defaults to the resolved scope).
    #[arg(long)]
    pub project: Option<String>,
    /// Pop this specific message instead of the oldest pending one.
    #[arg(long)]
    pub id: Option<String>,
    /// Emit JSON instead of the human rendering.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `message cancel`.
#[derive(Debug, Args)]
pub struct MessageCancelArgs {
    /// Workspace to cancel from (defaults to the resolved scope).
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project to cancel from (defaults to the resolved scope).
    #[arg(long)]
    pub project: Option<String>,
    /// Cancel this specific message.
    #[arg(long, conflicts_with = "all")]
    pub id: Option<String>,
    /// Cancel every pending message this project has sent. Requires exactly
    /// one of `--id` or `--all`.
    #[arg(long, conflicts_with = "id")]
    pub all: bool,
    /// Emit JSON instead of a human confirmation.
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Args)]
pub struct WorkstreamsArgs {
    /// Workspace containing the managed workstreams. Defaults to the nearest
    /// `.ai-memory.toml` marker's `workspace`, else `default`.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project override. Defaults to the current repository project.
    #[arg(long, conflicts_with = "project_id")]
    pub project: Option<String>,
    /// Select an existing project by ID instead of a name or cached binding.
    #[arg(long, conflicts_with = "project")]
    pub project_id: Option<ai_memory_core::ProjectId>,
    /// Maximum workstreams to return, current first then newest activity.
    #[arg(long, default_value_t = 20, value_parser = clap::value_parser!(u8).range(1..=100))]
    pub limit: u8,
    /// Emit JSON instead of readable rows.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `rename-workstream`.
#[derive(Debug, Args)]
pub struct RenameWorkstreamArgs {
    /// Workspace containing the managed workstream. Defaults to the nearest
    /// `.ai-memory.toml` marker's `workspace`, else `default`.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project override. Defaults to the current repository project.
    #[arg(long)]
    pub project: Option<String>,
    /// Current name of the workstream to rename. Names are unique within one
    /// checkout, so this is unambiguous wherever `run --workstream` works.
    #[arg(long, conflicts_with = "workstream_id")]
    pub from: Option<String>,
    /// Stable id of the workstream to rename, as printed by `workstreams`.
    /// Useful when the current name is awkward to retype.
    #[arg(long, conflicts_with = "from")]
    pub workstream_id: Option<ai_memory_core::WorkstreamId>,
    /// New name. Same rules as `run --new`: non-empty, at most 128
    /// characters, no control characters, no slashes.
    #[arg(long)]
    pub to: String,
    /// Emit JSON instead of a readable line.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `workstream-search`.
#[derive(Debug, Args)]
pub struct WorkstreamSearchArgs {
    /// Natural-language or FTS query. Omit to show the newest events.
    #[arg(default_value = "")]
    pub query: String,
    /// Workstream to search. Managed child processes receive this through the
    /// environment, so agents normally do not need to pass it.
    #[arg(long, env = "AI_MEMORY_WORKSTREAM_ID")]
    pub workstream_id: ai_memory_core::WorkstreamId,
    /// Maximum events to return.
    #[arg(long, default_value_t = 20, value_parser = clap::value_parser!(u8).range(1..=100))]
    pub limit: u8,
    /// Emit JSON instead of readable event blocks.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `user`.
#[derive(Debug, Args)]
pub struct UserArgs {
    /// User-management action to run.
    #[command(subcommand)]
    pub command: UserCommand,
}

/// Arguments for `user grant`.
#[derive(Debug, Args)]
pub struct UserGrantArgs {
    /// The user, by username.
    #[arg(long)]
    pub user: String,
    /// The workspace the project lives in.
    #[arg(long, default_value = "default")]
    pub workspace: String,
    /// The project, by name.
    #[arg(long)]
    pub project: String,
    /// `read` or `write`. Required: a level left unsaid is not guessed at.
    #[arg(long)]
    pub level: String,
}

/// Arguments for `user revoke`.
#[derive(Debug, Args)]
pub struct UserRevokeArgs {
    /// The user, by username.
    #[arg(long)]
    pub user: String,
    /// The workspace the project lives in.
    #[arg(long, default_value = "default")]
    pub workspace: String,
    /// The project, by name.
    #[arg(long)]
    pub project: String,
}

/// Arguments for `user grants`.
#[derive(Debug, Args)]
pub struct UserGrantsArgs {
    /// Only this user's grants. Omit for every grant on the server.
    #[arg(long)]
    pub user: Option<String>,
    /// Emit the response as JSON instead of a table.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `project`.
#[derive(Debug, Args)]
pub struct ProjectArgs {
    /// Project action to run.
    #[command(subcommand)]
    pub command: ProjectCommand,
}

/// `project` subcommands.
#[derive(Debug, Subcommand)]
pub enum ProjectCommand {
    /// Interactively create this checkout's `.ai-memory.toml` marker.
    Init(ProjectInitArgs),
    /// Set a project `open` or `restricted`.
    Access(ProjectAccessArgs),
    /// List who holds a grant on one project.
    Grants(ProjectGrantsArgs),
}

/// Arguments for `project init`.
#[derive(Debug, Args)]
pub struct ProjectInitArgs {}

/// Arguments for `profile`.
#[derive(Debug, Args)]
pub struct ProfileArgs {
    /// Profile action to run.
    #[command(subcommand)]
    pub command: ProfileCommand,
}

/// `profile` subcommands.
#[derive(Debug, Subcommand)]
pub enum ProfileCommand {
    /// Show whether the profile is on, where it lives, and its settings.
    Status(ProfileScopeArgs),
    /// List the profile's entries.
    List(ProfileScopeArgs),
    /// Print one entry (`profile/` prefix optional).
    Show {
        /// Entry path, e.g. `tools/pnpm.md`.
        path: String,
        #[command(flatten)]
        scope: ProfileScopeArgs,
    },
    /// Remove one entry (`profile/` prefix optional). Git keeps its history,
    /// and the harvester leaves the topic alone until you state it again.
    Forget {
        /// Entry path, e.g. `tools/pnpm.md`.
        path: String,
        #[command(flatten)]
        scope: ProfileScopeArgs,
    },
    /// Show each entry with its evidence, plus the habits still short of the
    /// bar and the entries the harvester leaves alone.
    Review(ProfileScopeArgs),
    /// Re-read every contributing project from the start and rebuild the
    /// profile from what it finds (safe to repeat).
    ///
    /// It adds and updates entries and never removes one, including an entry
    /// an earlier version admitted under rules it no longer applies: remove
    /// those with `profile forget`.
    Rebuild,
    /// Write the profile entries that fit this repository into a managed
    /// block of its rules file, turning your usual choices into hard rules
    /// here. Only the block between the `ai-memory:profile` delimiters is
    /// ever touched; re-running replaces it.
    Apply(ProfileApplyArgs),
}

/// Arguments for `profile apply`.
#[derive(Debug, Args)]
pub struct ProfileApplyArgs {
    /// Rules file to write, relative to the repository root unless absolute.
    /// Default: `AGENTS.md` when it exists, else `CLAUDE.md` unless it only
    /// imports `AGENTS.md`, else a new `AGENTS.md`.
    #[arg(long)]
    pub target: Option<PathBuf>,
    /// Print the block and the target instead of writing.
    #[arg(long)]
    pub dry_run: bool,
    /// Remove the managed block instead of writing it.
    #[arg(long, conflicts_with = "dry_run")]
    pub remove: bool,
    /// Operator whose private profile to use when the profile is per user
    /// (`share = "user"`).
    #[arg(long)]
    pub user: Option<String>,
}

/// Which profile a `profile` subcommand inspects.
#[derive(Debug, Args)]
pub struct ProfileScopeArgs {
    /// Workspace whose profile to inspect when `[profile] share = "workspace"`.
    #[arg(long, default_value = "default")]
    pub workspace: String,
    /// Operator whose private profile to inspect when the profile is per
    /// user (`share = "user"`).
    #[arg(long)]
    pub user: Option<String>,
}

/// Arguments for `project grants`.
#[derive(Debug, Args)]
pub struct ProjectGrantsArgs {
    /// The workspace the project lives in.
    #[arg(long, default_value = "default")]
    pub workspace: String,
    /// The project, by name.
    #[arg(long)]
    pub project: String,
    /// Emit the response as JSON instead of a table.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `project access`.
#[derive(Debug, Args)]
pub struct ProjectAccessArgs {
    /// The workspace the project lives in.
    #[arg(long, default_value = "default")]
    pub workspace: String,
    /// The project, by name.
    #[arg(long)]
    pub project: String,
    /// `open` (any authenticated user) or `restricted` (root and grant
    /// holders). Required: a mode left unsaid is not guessed at.
    #[arg(long)]
    pub mode: String,
}

/// Arguments for `completions`.
#[derive(Debug, Args)]
pub struct CompletionsArgs {
    /// Shell to generate a completion script for.
    #[arg(value_enum)]
    pub shell: Shell,
}

/// Subcommands for `user`.
#[derive(Debug, Subcommand)]
pub enum UserCommand {
    /// Create a human user and print a temporary password once. The user must
    /// change it on next login. Does not issue an API key.
    #[command(name = "add-human")]
    AddHuman(UserAddHumanArgs),
    /// List every registered identity. Passwords and hashes are never
    /// surfaced.
    List(UserListArgs),
    /// Replace the user's password with a new temporary one, revoke
    /// their web sessions, and force a change on next login. Does not
    /// revoke API credentials.
    #[command(name = "reset-password")]
    ResetPassword(UserResetPasswordArgs),
    /// Disable human login and revoke web sessions. API credentials
    /// stay valid.
    Disable(UserDisableArgs),
    /// Re-enable human login. Does not revive or revoke API credentials.
    Enable(UserEnableArgs),
    /// Update display name, email, and/or role (`root` or `user`).
    Patch(UserPatchArgs),
    /// Grant a user `read` or `write` on a project, or change the level they
    /// hold (#708). Grants decide access to `restricted` projects; an `open`
    /// project admits every user — see `ai-memory project access`.
    Grant(UserGrantArgs),
    /// Take away whatever a user holds on a project.
    Revoke(UserRevokeArgs),
    /// List grants: one user's with `--user`, else every grant on the server.
    Grants(UserGrantsArgs),
}

/// Arguments for `user add-human`.
#[derive(Debug, Args)]
pub struct UserAddHumanArgs {
    /// Stable username.
    #[arg(long)]
    pub username: String,
    /// Optional display name.
    #[arg(long)]
    pub name: Option<String>,
    /// Optional email.
    #[arg(long)]
    pub email: Option<String>,
    /// Role: `user` (default) or `root`.
    #[arg(long)]
    pub role: Option<String>,
    /// Emit JSON. The temporary password is included exactly once.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `user list`.
#[derive(Debug, Args)]
pub struct UserListArgs {
    /// Emit the response as JSON instead of a human-readable table.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `user reset-password`.
#[derive(Debug, Args)]
pub struct UserResetPasswordArgs {
    /// Username whose password to reset.
    pub username: String,
    /// Skip the interactive confirmation prompt.
    #[arg(long)]
    pub yes: bool,
    /// Emit the response as JSON instead of human-readable text.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `user disable`.
#[derive(Debug, Args)]
pub struct UserDisableArgs {
    /// Username whose human login to disable.
    pub username: String,
    /// Skip the interactive confirmation prompt.
    #[arg(long)]
    pub yes: bool,
}

/// Arguments for `user enable`.
#[derive(Debug, Args)]
pub struct UserEnableArgs {
    /// Username whose human login to re-enable.
    pub username: String,
}

/// Arguments for `user patch`.
#[derive(Debug, Args)]
pub struct UserPatchArgs {
    /// Username to update.
    pub username: String,
    /// New display name. Empty string clears it.
    #[arg(long)]
    pub name: Option<String>,
    /// New email. Empty string clears it.
    #[arg(long)]
    pub email: Option<String>,
    /// New role: `root` or `user`.
    #[arg(long)]
    pub role: Option<String>,
    /// Emit the response as JSON instead of human-readable text.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `api-key`.
#[derive(Debug, Args)]
pub struct ApiKeyArgs {
    /// API-credential action to run.
    #[command(subcommand)]
    pub command: ApiKeyCommand,
}

/// Arguments for `server`.
#[derive(Debug, Args)]
pub struct ServerArgs {
    /// Server-profile action to run.
    #[command(subcommand)]
    pub command: ServerCommand,
}

/// Subcommands for `server`.
#[derive(Debug, Subcommand)]
pub enum ServerCommand {
    /// Register a server profile, or replace one with the same name.
    Add(ServerAddArgs),
    /// List server profiles (never prints a token).
    List(ServerListArgs),
    /// Remove a server profile and its stored token.
    Remove(ServerRemoveArgs),
}

/// Arguments for `server add`.
#[derive(Debug, Args)]
pub struct ServerAddArgs {
    /// Profile name a marker selects: lowercase letters, digits, `-`, `_`.
    pub name: String,
    /// Server URL, e.g. `https://memory.example.com`.
    #[arg(long)]
    pub url: String,
    /// Directory allowed to select this profile (repeatable; absolute or
    /// `~/`). Required once more than one profile is registered.
    #[arg(long = "root")]
    pub roots: Vec<String>,
    /// Bearer token for this server. Prefer `--auth-token-stdin`, which
    /// keeps it out of shell history and the process table.
    #[arg(long, hide_env_values = true, conflicts_with = "auth_token_stdin")]
    pub auth_token: Option<String>,
    /// Read the bearer token from the first line of stdin.
    #[arg(long)]
    pub auth_token_stdin: bool,
}

/// Arguments for `server list`.
#[derive(Debug, Args)]
pub struct ServerListArgs {
    /// Emit the list as JSON.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `server remove`.
#[derive(Debug, Args)]
pub struct ServerRemoveArgs {
    /// Profile name to remove.
    pub name: String,
}

/// Subcommands for `api-key`.
#[derive(Debug, Subcommand)]
pub enum ApiKeyCommand {
    /// Issue a native `aim_` credential and print the secret once.
    Add(ApiKeyAddArgs),
    /// List native API credentials (metadata only; secrets are never shown).
    List(ApiKeyListArgs),
    /// Replace the secret. The previous plaintext 401s immediately.
    Rotate(ApiKeyRotateArgs),
    /// Revoke the credential. Idempotent.
    Revoke(ApiKeyRevokeArgs),
}

/// Arguments for `api-key add`.
#[derive(Debug, Args)]
pub struct ApiKeyAddArgs {
    /// Username the credential authenticates as (`AuthLevel::User`).
    #[arg(long)]
    pub username: String,
    /// Operator-facing label (e.g. `codex-laptop`).
    #[arg(long)]
    pub label: String,
    /// Emit the response as JSON instead of human-readable text.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `api-key list`.
#[derive(Debug, Args)]
pub struct ApiKeyListArgs {
    /// Emit the response as JSON instead of a human-readable table.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `api-key rotate`.
#[derive(Debug, Args)]
pub struct ApiKeyRotateArgs {
    /// Credential id to rotate.
    pub id: String,
    /// Skip the interactive confirmation prompt.
    #[arg(long)]
    pub yes: bool,
    /// Emit the response as JSON instead of human-readable text.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `api-key revoke`.
#[derive(Debug, Args)]
pub struct ApiKeyRevokeArgs {
    /// Credential id to revoke.
    pub id: String,
    /// Skip the interactive confirmation prompt.
    #[arg(long)]
    pub yes: bool,
}

/// Arguments for `auth`.
#[derive(Debug, Args)]
pub struct AuthArgs {
    /// Auth action to run.
    #[command(subcommand)]
    pub command: AuthCommand,
}

/// Subcommands for `auth`.
#[derive(Debug, Subcommand)]
pub enum AuthCommand {
    /// Sign in to an upstream provider.
    Login(AuthLoginArgs),
    /// Remove stored provider credentials.
    Logout(AuthLogoutArgs),
    /// Show stored provider auth state without printing secrets.
    Status(AuthStatusArgs),
    /// Require a bearer token on this install's server. Idempotent: mints
    /// `<data_dir>/auth-tokens/default` (owner-only) if missing, records
    /// `[auth].bearer_token_file`, gives the hooks the token through their
    /// credential files, and re-registers Claude Code's MCP entry as the
    /// `ai-memory mcp-bridge` stdio bridge. The token is never printed or
    /// written into a harness config. Restart the server afterwards.
    Enable(AuthEnableArgs),
}

/// Provider choices for `auth`.
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum AuthProviderChoice {
    /// OpenAI ChatGPT/Codex OAuth backend.
    OpenaiOauth,
    /// GitHub Copilot Chat backend.
    Copilot,
    /// Generic OIDC device-authorization grant (e.g. Keycloak). Stores a
    /// per-developer token the lifecycle hooks use to authenticate to the
    /// ai-memory server, instead of a shared static `--auth-token`.
    OidcDevice,
}

/// Arguments for `auth login`.
#[derive(Debug, Args)]
pub struct AuthLoginArgs {
    /// Provider to sign in to.
    #[arg(value_enum)]
    pub provider: AuthProviderChoice,
    /// Stop waiting for browser/device authorization after this many seconds.
    #[arg(long, default_value_t = 600)]
    pub timeout_secs: u64,
    /// GitHub token to persist for Copilot instead of running device auth.
    #[arg(long, hide_env_values = true)]
    pub github_token: Option<String>,
    /// OAuth/OIDC public client id. Required for `oidc-device`; an optional
    /// override for `copilot` device auth.
    #[arg(long)]
    pub client_id: Option<String>,
    /// OIDC issuer URL for `oidc-device` login, e.g. a Keycloak realm
    /// (`https://keycloak.example.com/realms/ai-memory`). Endpoints are
    /// discovered from `<issuer>/.well-known/openid-configuration`. The issuer
    /// and both endpoints must use `https`; plain `http` is accepted only on
    /// loopback.
    #[arg(long)]
    pub issuer: Option<String>,
}

/// Arguments for `auth logout`.
#[derive(Debug, Args)]
pub struct AuthLogoutArgs {
    /// Provider to sign out from.
    #[arg(value_enum)]
    pub provider: AuthProviderChoice,
}

/// Arguments for `auth status`.
#[derive(Debug, Args)]
pub struct AuthStatusArgs {}

/// Arguments for `auth enable`.
#[derive(Debug, Args)]
pub struct AuthEnableArgs {
    /// Leave harness MCP registrations alone; only provision the token,
    /// the config key and the hook credential files.
    #[arg(long)]
    pub no_mcp: bool,
}

/// Which concern `uninstall` should touch. Omitted = all four.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum UninstallOnly {
    Hooks,
    Mcp,
    Instructions,
    Skills,
}

/// Arguments for `uninstall`.
#[derive(Debug, Args)]
pub struct UninstallArgs {
    /// Actually modify files. Without it, prints the removal plan and
    /// exits (dry-run), mirroring `reset` without `--confirm`.
    #[arg(long)]
    pub apply: bool,
    /// After removing the wiring, wipe wiki/, db/, raw/ via the reset
    /// path (refuses if another ai-memory process is alive). Only
    /// meaningful with `--apply`.
    #[arg(long)]
    pub purge_data: bool,
    /// Limit to one concern. Omitted = hooks + mcp + instructions + skills.
    #[arg(long, value_enum)]
    pub only: Option<UninstallOnly>,
    /// Optional MCP server entry-name filter. Uninstall never matches by name
    /// alone; when this is set, the entry must match both name and `--mcp-url`.
    #[arg(long = "mcp-name")]
    pub mcp_name: Option<String>,
    /// MCP endpoint URL used to identify ai-memory server entries. Defaults to
    /// the standard local endpoint; pass this when you installed with a custom
    /// `install-mcp --server-url`.
    #[arg(long = "mcp-url", visible_alias = "server-url", default_value_t = crate::config::DEFAULT_MCP_URL.to_string())]
    pub mcp_url: String,
    /// Skip the interactive confirmation when a TTY is attached.
    #[arg(long)]
    pub yes: bool,
    /// OMP profile whose extension and MCP entry to remove, as `omp
    /// --profile` names it. Beats `OMP_PROFILE` and `PI_PROFILE`; the default
    /// profile's files are swept as well.
    #[arg(long)]
    pub profile: Option<String>,
}

/// Arguments for `upgrade`.
#[derive(Debug, Args)]
pub struct UpgradeArgs {
    /// Pin a specific release tag (with or without a leading `v`). Defaults
    /// to the latest GitHub Release for akitaonrails/ai-memory.
    #[arg(long)]
    pub version: Option<String>,
    /// Re-download and replace even when the installed version already
    /// matches the resolved release tag.
    #[arg(long)]
    pub force: bool,
}

/// Arguments for `reorg`.
#[derive(Debug, Args)]
pub struct ReorgArgs {
    /// Show what would change without writing.
    #[arg(long)]
    pub dry_run: bool,
}

/// Arguments for `compact`.
#[derive(Debug, Args)]
pub struct CompactArgs {
    /// REQUIRED. Not because compaction destroys anything — it deletes
    /// nothing — but because it blocks every write for as long as it runs.
    #[arg(long)]
    pub confirm: bool,
}

/// Arguments for `reclaim-ledger-versions`.
#[derive(Debug, Args)]
pub struct ReclaimLedgerVersionsArgs {
    /// Actually delete. Without this the command reports what it would remove
    /// — the ledger paths, the row count and the bytes — and changes nothing.
    #[arg(long)]
    pub confirm: bool,
    /// Also drop each ledger's *live* row, not just its superseded versions.
    ///
    /// Since #660 the indexer skips ledgers, so each ledger's live row is also
    /// left over from before the fix. It is kept by default: it is the
    /// version the file on disk corresponds to, and dropping it is the
    /// operator's call. Drop it only once the ledger file itself has been
    /// removed, or the next hook append starts a fresh chain.
    #[arg(long)]
    pub drop_latest: bool,
    /// Rebuild the FTS index and VACUUM afterwards, returning the freed bytes
    /// to the filesystem.
    ///
    /// Without this the reclaim is a logical delete — the rows are gone and
    /// nothing can reach them, but their bytes stay in free pages of the
    /// database file until it is next rewritten. `VACUUM` rewrites the whole
    /// file under an exclusive lock and needs free disk of roughly the
    /// database's own size, so it is opt-in.
    #[arg(long)]
    pub compact: bool,
}

/// Arguments for `purge-project`.
#[derive(Debug, Args)]
pub struct PurgeProjectArgs {
    /// Purge even when a managed workstream under this project still holds a
    /// live run lease. Workstreams cascade out of the project row, so without
    /// this the purge refuses rather than deleting a running session's lease.
    #[arg(long)]
    pub force: bool,
    /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
    /// `workspace`, else `default`.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project name. When omitted, taken from the nearest
    /// `.ai-memory.toml` marker's `project`, then from the git remote,
    /// then from the current directory's name.
    #[arg(long, conflicts_with = "project_id")]
    pub project: Option<String>,
    /// Project id (UUID) to purge, as an alternative to `--project`.
    ///
    /// Use this when the NAME lookup is ambiguous: a legacy row whose name
    /// collides with another project's `legacy_name` is refused by name, so
    /// only the id reaches it. Find it in the
    /// `list-projects` output. Mutually exclusive with `--project`.
    #[arg(long)]
    pub project_id: Option<String>,
    /// REQUIRED for the purge to run. Without this flag the CLI errors
    /// out — purging is destructive and irreversible.
    ///
    /// Before erroring, the CLI asks the server for a preview (bounded to a
    /// few seconds, auth refresh included): the reported counts (pages,
    /// sessions, observations, handoffs, embeddings, workstreams, managed
    /// runs, plus any collateral rows a purge of this project would delete
    /// or orphan in *another* project) come from the same queries a
    /// confirmed purge itself uses to decide what to delete. The preview is
    /// best-effort and never changes the outcome, only what gets printed
    /// before it: a 404/409/403 (or anything else unexpected) prints the
    /// server's own error first; a timeout, an unreachable server, or an
    /// older server that predates this preview just gets the plain refusal,
    /// same as before this existed.
    #[arg(long)]
    pub confirm: bool,
    /// Also reclaim the freed bytes: rebuild the FTS indexes and VACUUM the
    /// database after the delete commits.
    ///
    /// Without this the purge is a logical delete — the project is gone from
    /// the API and from search, but its bytes stay in free pages of the
    /// database file until it is next rewritten, as with any SQLite delete.
    ///
    /// This rewrites the WHOLE database and needs free disk space of about
    /// its size, so it takes minutes on a large store. It also does NOT make
    /// the content forensically unrecoverable: the wiki git history and any
    /// backup taken before the purge still contain it.
    #[arg(long)]
    pub compact: bool,
}

/// Arguments for `purge-session`.
#[derive(Debug, Args)]
pub struct PurgeSessionArgs {
    /// Full session UUID, exactly as `sessions.id` stores it.
    #[arg(long)]
    pub session_id: String,
    /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
    /// `workspace`, else `default`.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project name. When omitted, taken from the nearest
    /// `.ai-memory.toml` marker's `project`, then from the git remote,
    /// then from the current directory's name.
    #[arg(long)]
    pub project: Option<String>,
    /// REQUIRED for the purge to run. Without this flag the CLI errors
    /// out — purging is destructive and irreversible.
    ///
    /// Before erroring, the CLI asks the server for a preview (bounded to a
    /// few seconds, auth refresh included): the reported counts
    /// (observations, handoffs, pages, auto-improve runs, plus any
    /// collateral rows a purge of this session would delete or orphan in
    /// *another* project) come from the same queries a confirmed purge
    /// itself uses to decide what to delete. The preview is best-effort and
    /// never changes the outcome, only what gets printed before it: a
    /// 404/403 (or anything else unexpected) prints the server's own error
    /// first; a timeout, an unreachable server, or an older server that
    /// predates this preview just gets the plain refusal, same as before
    /// this existed.
    #[arg(long)]
    pub confirm: bool,
    /// Also reclaim the freed bytes: rebuild the affected FTS indexes and
    /// VACUUM the database after the delete commits.
    ///
    /// Without this the purge is a logical delete — the session is gone from
    /// the API and from search, but its bytes stay in free pages of the
    /// database file until it is next rewritten, as with any SQLite delete.
    ///
    /// This rewrites the WHOLE database and needs free disk space of about
    /// its size, so it takes minutes on a large store. It also does NOT make
    /// the content forensically unrecoverable: the wiki git history and any
    /// backup taken before the purge still contain it.
    #[arg(long)]
    pub compact: bool,
}

/// Arguments for `rename-project`.
#[derive(Debug, Args)]
pub struct RenameProjectArgs {
    /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
    /// `workspace`, else `default`.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Current project name. When omitted, taken from the nearest
    /// `.ai-memory.toml` marker's `project`, then from the git remote,
    /// then from the current directory's name. After renaming the
    /// directory itself, pass `--from`: a checkout with no marker or
    /// remote would resolve to the new name.
    #[arg(long, conflicts_with = "project_id")]
    pub from: Option<String>,
    /// Project id (UUID) to rename, as an alternative to `--from`.
    ///
    /// Use this when the NAME lookup is ambiguous: a legacy row whose name
    /// collides with another project's `legacy_name` is refused by name, so
    /// only the id reaches it. Find it in the
    /// `list-projects` output. Mutually exclusive with `--from`.
    #[arg(long)]
    pub project_id: Option<String>,
    /// New project name. Must be non-empty and contain no slashes.
    #[arg(long)]
    pub to: String,
}

/// Arguments for `move-project`.
#[derive(Debug, Args)]
pub struct MoveProjectArgs {
    /// Source workspace. Defaults to the nearest `.ai-memory.toml` marker's
    /// `workspace`, else `default`. Only the source is marker-resolved;
    /// `--to-workspace` names the destination and stays literal.
    #[arg(long)]
    pub from_workspace: Option<String>,
    /// Project name to move. When omitted, taken from the nearest
    /// `.ai-memory.toml` marker's `project`, then from the git remote,
    /// then from the current directory's name.
    #[arg(long, conflicts_with = "project_id")]
    pub project: Option<String>,
    /// Project id (UUID) to move, as an alternative to `--project`.
    ///
    /// Use this when the NAME lookup is ambiguous: a legacy row whose name
    /// collides with another project's `legacy_name` is refused by name, so
    /// only the id reaches it. Find it in the
    /// `list-projects` output. Mutually exclusive with `--project`.
    #[arg(long)]
    pub project_id: Option<String>,
    /// Destination workspace. Auto-created if it doesn't exist.
    #[arg(long)]
    pub to_workspace: String,
    /// REQUIRED — the move re-stamps (true-move) or copies+purges (merge) the
    /// source, both irreversible. Without this flag the CLI errors out.
    #[arg(long)]
    pub confirm: bool,
    /// Override the active-project guard. In a copy-purge merge this never
    /// overrides a live managed-workstream lease, because deleting that lease
    /// would strand the running agent's transcript.
    #[arg(long)]
    pub force: bool,
    /// Merge conflict policy (copy-purge path only): what to do when a source
    /// page's path already exists in the destination with different content.
    /// `block` (default) aborts and lists the conflicts; `overwrite` lets the
    /// source supersede the destination page; `duplicate` keeps both (source
    /// lands under a de-duplicated path).
    #[arg(long, value_parser = ["block", "overwrite", "duplicate"], default_value = "block")]
    pub on_conflict: String,
    /// Allow the copy+purge merge when the destination workspace already holds
    /// a project of the same name.
    ///
    /// That path is not a move: it copies the source's latest pages and
    /// deletes the project with its sessions, observations, handoffs and older
    /// page versions. Without this flag the server refuses and reports the
    /// counts it would discard (#1713).
    #[arg(long)]
    pub allow_lossy_merge: bool,
}

/// Arguments for `merge-project`.
#[derive(Debug, Args)]
pub struct MergeProjectArgs {
    /// Workspace containing both projects. Defaults to the nearest marker's
    /// workspace, then `default`.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Source project name. Mutually exclusive with `--from-project-id`.
    #[arg(long, conflicts_with = "from_project_id")]
    pub from: Option<String>,
    /// Source project UUID, for an ambiguous legacy name.
    #[arg(long)]
    pub from_project_id: Option<String>,
    /// Target project name. Mutually exclusive with `--into-project-id`.
    #[arg(long, conflicts_with = "into_project_id")]
    pub into: Option<String>,
    /// Target project UUID, for an ambiguous legacy name.
    #[arg(long)]
    pub into_project_id: Option<String>,
    /// Apply the merge. Omit for an exact dry-run preview.
    #[arg(long)]
    pub confirm: bool,
}

/// Arguments for `move-session`.
///
/// Exactly one of `<SESSION_ID>` and `--from-project` names what moves; the
/// `what` group makes clap's error name both when neither is given.
#[derive(Debug, Args)]
#[command(group = clap::ArgGroup::new("what").required(true).args(["session_id", "from_project"]))]
pub struct MoveSessionArgs {
    /// Session id (UUID) to move. Omit it and pass `--from-project` to move
    /// every session touching one project. A session already rooted in the
    /// destination is re-homed: its row stays and only its stray rows move.
    pub session_id: Option<ai_memory_core::SessionId>,
    /// Batch form: move every session touching this project (a session row
    /// here or observations stamped into it). Resolved like other commands
    /// (marker, else literal); the sessions move one at a time and the batch
    /// stops at the first refusal, reporting how far it got.
    #[arg(long)]
    pub from_project: Option<String>,
    /// Workspace of `--from-project`. Defaults to the nearest
    /// `.ai-memory.toml` marker's `workspace`, else `default`.
    #[arg(long, requires = "from_project")]
    pub from_workspace: Option<String>,
    /// Destination project name (literal, not marker-resolved).
    #[arg(long)]
    pub to: String,
    /// Destination workspace. Defaults to the source workspace.
    #[arg(long)]
    pub to_workspace: Option<String>,
    /// What happens to the session's `sessions/<id>.md` page: `move` carries
    /// the page and its history along (refused when the destination already
    /// has one at that path); `regenerate` retires it so the next
    /// consolidation writes a fresh page in the destination.
    #[arg(long, value_parser = ["move", "regenerate"], default_value = "move")]
    pub pages: String,
    /// REQUIRED to apply. Without it the command prints the dry-run summary
    /// and the exact command to re-run.
    #[arg(long)]
    pub confirm: bool,
    /// Skip the live-session guards (open session, pending consolidation job,
    /// active project of the hook router in the batch form).
    #[arg(long)]
    pub force: bool,
    /// Create the destination workspace/project when it does not exist yet.
    #[arg(long)]
    pub create: bool,
}

/// Arguments for `install-instructions`.
#[derive(Debug, Args)]
pub struct InstallInstructionsArgs {
    /// Markdown file to write into. When omitted, the command picks
    /// whichever of `CLAUDE.md` or `AGENTS.md` already exists in
    /// $PWD; if both exist it writes to both; if neither exists it
    /// creates `CLAUDE.md` (Claude Code's convention) and prints a
    /// hint that Codex / OpenCode / Cursor / Gemini users likely
    /// want `--target AGENTS.md` instead. Pass `--target` explicitly
    /// to override the auto-detection.
    #[arg(long)]
    pub target: Option<PathBuf>,
    /// Print the snippet to stdout instead of mutating files.
    /// The default IS mutation here (the print form is also
    /// available without this command — copy the block from the
    /// README). Pass `--print` to preview what would land in
    /// the file. This does not print skill payloads; use
    /// `install-skills --print` to preview managed Agent Skills.
    #[arg(long)]
    pub print: bool,
    /// Skip installing/updating the managed ai-memory Agent Skills.
    #[arg(long)]
    pub no_skills: bool,
    /// Write a compact routing snippet that delegates to installed Agent Skills
    /// instead of inlining full operational guidance.
    #[arg(long)]
    pub compact: bool,
    /// Scope for managed ai-memory skill installation.
    #[arg(long = "skills-scope", value_enum)]
    pub skills_scope: Option<InstallSkillsScope>,
    /// Agent skill directory family for managed ai-memory skill installation.
    #[arg(long = "skills-agent", value_enum)]
    pub skills_agent: Option<InstallSkillsAgent>,
    /// Override the managed skill root directory.
    #[arg(long = "skills-target-dir")]
    pub skills_target_dir: Option<PathBuf>,
    /// Overwrite same-named unmanaged skills while installing from `install-instructions`.
    #[arg(long = "skills-force")]
    pub skills_force: bool,
}

/// Skill install scope for `install-skills`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum InstallSkillsScope {
    /// Install into this project's agent skill directories.
    Project,
    /// Install into the user's global agent skill directories.
    Global,
}

/// Where `install-hooks` writes a hook configuration with user/project scope.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum HookInstallScope {
    /// The user-level hook location: Claude Code's settings file or Cline
    /// CLI's `~/.cline/hooks` directory. Hooks fire in every project.
    Global,
    /// This repository's hook location: Claude Code's gitignored
    /// `.claude/settings.local.json` or Cline CLI's `.cline/hooks` directory.
    /// Hooks fire only for sessions started in this checkout.
    Project,
}

/// Agent skill directory family for `install-skills`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum InstallSkillsAgent {
    /// Claude Code's `.claude/skills` directory.
    ClaudeCode,
    /// Cross-agent `.agents/skills` directory.
    Agents,
    /// Devin's `.devin/skills` directory.
    Devin,
    /// Grok Build CLI's `.grok/skills` directory.
    Grok,
    /// GitHub Copilot CLI's `.github/skills` (project) or
    /// `$COPILOT_HOME/skills` (global, default `~/.copilot/skills`) directory.
    CopilotCli,
    /// Hermes Agent's `.hermes/skills` directory.
    Hermes,
    /// Google Antigravity: the workspace `.agents/skills` (project), or both
    /// global directories, `~/.gemini/config/skills` (App and IDE) and
    /// `~/.gemini/antigravity-cli/skills` (CLI).
    #[value(alias = "antigravity-cli", alias = "agy")]
    Antigravity,
    /// Install into both Claude Code and `.agents` skill directories.
    Both,
}

/// Arguments for `install-skills`.
#[derive(Debug, Args)]
pub struct InstallSkillsArgs {
    /// Install project-local skills or global user skills.
    #[arg(long, value_enum, default_value_t = InstallSkillsScope::Project)]
    pub scope: InstallSkillsScope,
    /// Which agent skill directory family to install into.
    #[arg(long, value_enum, default_value_t = InstallSkillsAgent::ClaudeCode)]
    pub agent: InstallSkillsAgent,
    /// Override the skill root directory. When set, `--scope` and
    /// `--agent` are ignored and the managed skill directories are
    /// written below this root.
    #[arg(long)]
    pub target_dir: Option<PathBuf>,
    /// Print target paths and SKILL.md contents without writing files.
    #[arg(long)]
    pub print: bool,
    /// Overwrite same-named existing skills that do not contain the
    /// ai-memory managed marker. Without this flag, unmanaged skills
    /// are preserved and the command exits with an actionable error.
    #[arg(long)]
    pub force: bool,
}

/// Arguments for `bootstrap`.
#[derive(Debug, Args)]
pub struct BootstrapArgs {
    /// Path on this client whose history to collect (server never
    /// sees this path). Defaults to `git rev-parse --show-toplevel`
    /// resolved from the current directory (so running bootstrap from
    /// any subdir of the project works).
    #[arg(long)]
    pub repo_path: Option<PathBuf>,
    /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
    /// `workspace`, else `default` — the same resolution the lifecycle hooks
    /// use, so bootstrap pages land where the session captures do.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project name. When omitted, taken from the nearest
    /// `.ai-memory.toml` marker's `project`, then from the git remote,
    /// then from the current directory's name (not `--repo-path`), the
    /// same resolution the hook router uses, so the bootstrap pages land
    /// in the same project as future session captures.
    ///
    /// Dot-prefixed dirs are preserved verbatim — `~/.config` becomes
    /// project `.config`, matching what the router does for sessions
    /// launched from there. Pass `--project` explicitly to override.
    #[arg(long)]
    pub project: Option<String>,
    /// Maximum total tokens of source text sent to the LLM in one
    /// run. When the collected sources exceed this, lower-priority
    /// inputs (older git commits, then code module headers, then
    /// docs) are dropped first. Default is 150K, so the model sees as
    /// much of your project as possible; with chunking on (the
    /// default), each call carries at most `--chunk-input-tokens` of
    /// it plus up to 16K output tokens. Lower it if you're
    /// cost-sensitive. With `--chunk-input-tokens 0`, this whole
    /// budget goes into one call that also asks for up to 64K output
    /// tokens, so budget + 64K must fit the model's context window
    /// (the 150K default does not fit a 200K window).
    #[arg(long, default_value_t = 150_000)]
    pub max_input_tokens: usize,
    /// Max estimated input tokens per LLM call. When pruned sources exceed
    /// this, bootstrap runs multiple sequential LLM chunks instead of one
    /// giant prompt (avoids provider context limits / Cursor bridge failures).
    /// Set to `0` to disable chunking (single call with the full pruned bundle).
    #[arg(long, default_value_t = ai_memory_consolidate::DEFAULT_CHUNK_INPUT_TOKENS)]
    pub chunk_input_tokens: usize,
    /// Skip git-commit history ingestion.
    #[arg(long)]
    pub exclude_git: bool,
    /// Skip README ingestion.
    #[arg(long)]
    pub exclude_readme: bool,
    /// Skip docs/**/*.md ingestion.
    #[arg(long)]
    pub exclude_docs: bool,
    /// Skip code module headers (Rust `//!` doc-comments at the top
    /// of `**/*.rs` files).
    #[arg(long)]
    pub exclude_code: bool,
    /// git-log time filter (passed through to `git log --since`).
    /// Useful when a repo is years old and you only want recent
    /// history (e.g. `--since "180 days ago"`). Default: no limit.
    #[arg(long)]
    pub since: Option<String>,
    /// LLM-call dry run: collects sources, builds the prompt, and
    /// prints what *would* be sent — but never calls the provider
    /// and never writes to the wiki. Useful for verifying the source
    /// selection before paying for a real run.
    #[arg(long)]
    pub dry_run: bool,
    /// Re-bootstrap a project that already has a bootstrap manifest
    /// page. Without this flag, `bootstrap` refuses to run twice on
    /// the same project (the manifest is `wiki/bootstrap.md`).
    #[arg(long)]
    pub force: bool,
    /// Resume an interrupted bootstrap: reuse the chunks already completed
    /// for the same sources instead of re-running them.
    #[arg(long)]
    pub resume: bool,
}

/// OpenCode artifact dialect for container-only setup where the host executable
/// cannot be probed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum OpenCodeDialectChoice {
    /// OpenCode V1 function plugin and direct `mcp` entry.
    V1,
    /// OpenCode V2 `{ id, setup }` plugin and nested `mcp.servers` entry.
    V2,
}

impl OpenCodeDialectChoice {
    #[must_use]
    pub const fn dialect(self) -> ai_memory_workstream::OpenCodeDialect {
        match self {
            Self::V1 => ai_memory_workstream::OpenCodeDialect::V1,
            Self::V2 => ai_memory_workstream::OpenCodeDialect::V2,
        }
    }
}

/// Arguments for `setup-agent`.
#[derive(Debug, Args)]
pub struct SetupAgentArgs {
    /// Which agent's hook bundle to extract + render.
    #[arg(long, value_enum, default_value_t = AgentChoice::ClaudeCode)]
    pub agent: AgentChoice,
    /// OpenCode artifact dialect when `--agent opencode` is used. Required
    /// because setup-agent commonly runs in a container that cannot inspect the
    /// host's executable. The `opencode2` aliases force V2 and reject this flag.
    #[arg(long, value_enum)]
    pub opencode_dialect: Option<OpenCodeDialectChoice>,
    /// Filesystem directory the hook scripts get copied into. In a
    /// docker context this is the in-container path; mount a host
    /// directory there. Example:
    ///     docker run --rm -v $HOME/.ai-memory:/host ai-memory \
    ///       setup-agent --to /host/hooks ...
    #[arg(long)]
    pub to: PathBuf,
    /// Directory the rendered config JSON should reference for the
    /// hook commands. Defaults to `--to`. Set this when the path on
    /// the host (where the agent CLI runs) differs from the in-
    /// container path. Example:
    ///     --to /host/hooks  --host-prefix $HOME/.ai-memory/hooks
    #[arg(long)]
    pub host_prefix: Option<PathBuf>,
    /// MCP / hook ingress URL the agent should POST to. Defaults to the
    /// configured `server_url` / AI_MEMORY_SERVER_URL when set, else loopback.
    #[arg(long, default_value_t = crate::config::DEFAULT_SERVER_URL.to_string())]
    pub server_url: String,
    /// Bearer token embedded into each hook's env block. When omitted,
    /// uses the token resolved by the config loader.
    #[arg(long, hide_env_values = true)]
    pub auth_token: Option<String>,
    /// Source directory for the embedded hook bundle. Defaults to
    /// `/usr/local/share/ai-memory/hooks` (the docker image's
    /// bundled path) and falls back to a repo-local `hooks/` for
    /// `cargo run setup-agent` during development.
    #[arg(long)]
    pub source: Option<PathBuf>,
}

/// Arguments for `generate-auth-token`.
#[derive(Debug, Args)]
pub struct GenerateAuthTokenArgs {
    /// Number of random bytes of entropy. The token printed is hex-
    /// encoded, so the output length is 2× this value. 32 bytes
    /// (256 bits) is plenty for any homelab threat model.
    #[arg(long, default_value_t = 32)]
    pub bytes: usize,
}

/// Arguments for `init`.
#[derive(Debug, Args)]
pub struct InitArgs {
    /// Overwrite an existing `config.toml` if present.
    #[arg(long)]
    pub force: bool,
}

/// Arguments for `setup`.
#[derive(Debug, Args)]
pub struct SetupArgs {
    /// Apply the plan without asking. Without it, `setup` shows the plan and
    /// asks on a terminal, or exits non-zero when there is no terminal to
    /// ask on.
    #[arg(long, short = 'y')]
    pub yes: bool,
    /// Wire this agent instead of the detected ones. Repeat for several.
    /// Detection looks for each harness's session store or MCP config under
    /// your home. A detected or named `opencode` is wired for the major
    /// `opencode --version` reports (`opencode2` forces V2 without probing);
    /// the Kiro CLI v3 engine is only wired when named here.
    #[arg(long = "agent", value_enum)]
    pub agents: Vec<AgentChoice>,
    /// Do not install or start a user service; use this when the server
    /// already runs some other way (Docker, a packaged system unit).
    #[arg(long)]
    pub no_service: bool,
    /// Print the plan and change nothing: what would be created, which
    /// agents would be wired and why each was detected, and which supported
    /// agents are not in the plan.
    #[arg(long, conflicts_with = "yes")]
    pub plan: bool,
    /// With `--plan`, print the plan as a JSON document (its `format` field
    /// names the layout version) for a script or front end to render.
    #[arg(long, requires = "plan")]
    pub json: bool,
    /// Show the plan as a page in your browser, served on 127.0.0.1 behind a
    /// one-time address printed here, and apply the agents you pick there.
    /// Nothing changes until you press Apply.
    #[arg(long, conflicts_with_all = ["yes", "plan"])]
    pub web: bool,
    /// With `--web`, print the page's address without opening a browser.
    #[arg(long, requires = "web")]
    pub no_open: bool,
    /// With `--web`, stop when standard input closes. The desktop installer
    /// holds the write end, so the page goes away with the app.
    #[arg(long, requires = "web", hide = true)]
    pub stop_on_stdin_eof: bool,
}

/// Arguments for `status`.
#[derive(Debug, Args)]
pub struct StatusArgs {
    /// Emit the report as JSON instead of human-readable text.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `list-projects`.
#[derive(Debug, Args)]
pub struct ListProjectsArgs {
    /// Only list projects in this workspace. Omit to list every workspace.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Emit JSON instead of a plain table.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `backfill`.
#[derive(Debug, Args)]
pub struct BackfillArgs {
    /// Workspace name. Defaults to the current project's resolved scope.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project name. Defaults to the current project's resolved scope.
    #[arg(long)]
    pub project: Option<String>,
    /// Import only this one harness-native session id instead of every local
    /// session for the project.
    #[arg(long)]
    pub session: Option<String>,
    /// Import even when the store already has sessions. Off by default: the
    /// automatic path is a one-time bootstrap of an empty project only.
    #[arg(long)]
    pub force: bool,
    /// Report what would be imported without importing anything.
    #[arg(long)]
    pub dry_run: bool,
    /// Import at most this many of the newest local sessions.
    #[arg(long, default_value_t = 25)]
    pub max_sessions: usize,
    /// Emit the report as JSON instead of human-readable text.
    #[arg(long)]
    pub json: bool,
    /// Suppress the human summary line (used by the automatic SessionStart
    /// trigger, which runs detached).
    #[arg(long)]
    pub quiet: bool,
    /// Internal: this run was spawned by the SessionStart trigger. Honors the
    /// `backfill_on_start` opt-out and records that the automatic bootstrap has
    /// been attempted for this checkout. Not for interactive use.
    #[arg(long, hide = true)]
    pub auto: bool,
    /// Internal ownership token for the automatic backfill's in-flight marker.
    /// The SessionStart hook mints and passes it to its detached child.
    #[arg(long, hide = true, requires = "auto")]
    pub inflight_claim: Option<String>,
    /// Internal: deliver to the server the spawning hook is installed
    /// against, instead of the configured one. Set by the SessionStart
    /// trigger so the backfill cannot depend on the agent's environment.
    #[arg(long, hide = true, conflicts_with = "server_profile")]
    pub server_url: Option<String>,
    /// Internal: deliver to this registered server profile (#992), with the
    /// profile's own stored token. Set by the SessionStart trigger when the
    /// repository's marker selects a profile.
    #[arg(long, hide = true)]
    pub server_profile: Option<String>,
}

/// Arguments for `repair-backfill-timestamps`.
///
/// A thin client like every other lifecycle command: it reads the local
/// transcripts (read-only, reusing `backfill`'s own discovery) to compute
/// candidate `started_at`/`ended_at` values, then posts them to
/// `POST /admin/repair-session-times`, which validates each one against the
/// scope and the backfill bug's own signature, and applies (or, without
/// `--confirm`, only reports) the change.
#[derive(Debug, Args)]
pub struct RepairBackfillTimestampsArgs {
    /// Workspace name. Defaults to the current project's resolved scope.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project name. Defaults to the current project's resolved scope.
    #[arg(long)]
    pub project: Option<String>,
    /// Apply the computed times. Without this flag the command only reports
    /// what would change (sessions repaired/skipped, by reason, plus the
    /// before/after date range) — the server runs the write inside a
    /// rolled-back transaction, so this is a real dry run, not an estimate.
    #[arg(long)]
    pub confirm: bool,
    /// Emit the server's report(s) as JSON instead of the human summary.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `doctor`.
#[derive(Debug, Args)]
pub struct DoctorArgs {
    /// Workspace name. Defaults to the current project's resolved scope.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project name. Defaults to the current project's resolved scope.
    #[arg(long)]
    pub project: Option<String>,
    /// A local harness session counts as "recent" if it was updated within
    /// this many days. Set to 0 to consider every on-disk session recent.
    #[arg(long, default_value_t = 30)]
    pub since_days: u32,
    /// Emit the report as JSON instead of human-readable text.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `audit-contamination`.
#[derive(Debug, Args)]
pub struct AuditContaminationArgs {
    /// Restrict the audit to one workspace (use together with `--project`).
    #[arg(long)]
    pub workspace: Option<String>,
    /// Restrict the audit to one project (use together with `--workspace`).
    #[arg(long)]
    pub project: Option<String>,
    /// Emit the report as JSON instead of human-readable text.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `recent`.
#[derive(Debug, Args)]
pub struct RecentArgs {
    /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
    /// `workspace`, else `default`.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project name. When omitted, auto-derived from the current project.
    #[arg(long)]
    pub project: Option<String>,
    /// List the most recently updated pages of every project instead of the
    /// current one. Each hit is labelled with its `workspace/project`.
    #[arg(long, conflicts_with_all = ["workspace", "project"])]
    pub global: bool,
    /// Maximum number of pages to return.
    #[arg(short = 'n', long, default_value_t = 10)]
    pub limit: usize,
    /// Emit results as JSON.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `search`.
#[derive(Debug, Args)]
pub struct SearchArgs {
    /// FTS5 query string (e.g. `"karpathy wiki"` or `quick OR slow`).
    pub query: String,
    /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
    /// `workspace`, else `default`.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project name. When omitted, auto-derived from the current project.
    #[arg(long)]
    pub project: Option<String>,
    /// Search the wiki pages of every project instead of the current one.
    /// Each hit is labelled with its `workspace/project`.
    #[arg(long, conflicts_with_all = ["workspace", "project"])]
    pub global: bool,
    /// Maximum number of hits to return.
    #[arg(short = 'n', long, default_value_t = 10)]
    pub limit: usize,
    /// Emit results as JSON.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `read-page`.
#[derive(Debug, Args)]
pub struct ReadPageArgs {
    /// FTS5 query to find the page (searches and fetches the top hit).
    /// Ignored when `--path` is provided.
    pub query: Option<String>,
    /// Exact wiki path (e.g. `notes/foo.md`). Takes precedence over `query`.
    #[arg(long)]
    pub path: Option<String>,
    /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
    /// `workspace`, else `default`.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project name. When omitted, auto-derived from the current project.
    #[arg(long)]
    pub project: Option<String>,
    /// Emit the page as JSON (includes frontmatter).
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `delete-page`.
#[derive(Debug, Args)]
pub struct DeletePageArgs {
    /// Exact wiki path to delete (e.g. `notes/foo.md`).
    #[arg(long)]
    pub path: String,
    /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
    /// `workspace`, else `default`. Resolution is announced on stderr so a
    /// cross-workspace project-name collision can never silently route the
    /// delete to the wrong slot.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project name. When omitted, auto-derived from the current project
    /// (same heuristic write-page/read-page use).
    #[arg(long)]
    pub project: Option<String>,
}

/// Arguments for `reset`.
#[derive(Debug, Args)]
pub struct ResetArgs {
    /// Required to actually wipe data. Without this we just dry-run.
    #[arg(long)]
    pub confirm: bool,
}

/// Arguments for `backup`.
#[derive(Debug, Args)]
pub struct BackupArgs {
    /// Destination tarball (`.tar.gz`).
    #[arg(long, short = 'o')]
    pub 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.
    /// 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 {
    /// Workspace the project lives in.
    #[arg(long, default_value = "default")]
    pub workspace: String,
    /// Project to export.
    #[arg(long)]
    pub project: String,
    /// Destination tarball (`.tar.gz`).
    #[arg(long, short = 'o')]
    pub to: PathBuf,
}

/// Arguments for `restore`.
#[derive(Debug, Args)]
pub struct RestoreArgs {
    /// Source tarball.
    #[arg(long, short = 'i')]
    pub from: PathBuf,
    /// Overwrite an existing non-empty data dir.
    #[arg(long)]
    pub force: bool,
    /// Replace the live `config.toml` with the backup's. Without it an
    /// existing config is kept and the backup's is saved beside it as
    /// `config.toml.from-backup` for review: a config can run commands and
    /// redirect data, so adopt one only from a backup you trust.
    #[arg(long)]
    pub with_config: bool,
    /// Confirm that the configured token pepper is the original one for a
    /// pre-verifier backup that already contains native API keys.
    #[arg(long)]
    pub accept_legacy_api_key_pepper: bool,
}

/// Arguments for `restore-agents`.
#[derive(Debug, Args)]
pub struct RestoreAgentsArgs {
    /// Source archive (`.tar.gz`).
    #[arg(long, short = 'i')]
    pub from: PathBuf,
    /// Optional comma-separated list of agents to restore. Defaults to all present in archive.
    #[arg(long, value_delimiter = ',')]
    pub agents: Option<Vec<String>>,
    /// Scope of assets to restore: `global`, `project`, or `both`.
    #[arg(long, default_value = "both")]
    pub scope: AgentBackupScope,
    /// Actually write restored files to disk (default is dry-run inspection).
    #[arg(long)]
    pub apply: bool,
    /// Overwrite existing target files even if they differ.
    #[arg(long)]
    pub force: bool,
}

/// Arguments for `checkpoints`.
#[derive(Debug, Args)]
pub struct CheckpointsArgs {
    /// Maximum number of checkpoints to list.
    #[arg(short = 'n', long, default_value_t = 20)]
    pub limit: usize,
    /// Emit checkpoints as JSON instead of human-readable rows.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `restore-page`.
#[derive(Debug, Args)]
pub struct RestorePageArgs {
    /// Exact wiki path to restore (e.g. `notes/foo.md`).
    #[arg(long)]
    pub path: String,
    /// Git checkpoint/revision to restore from.
    #[arg(long, conflicts_with = "page_id", required_unless_present = "page_id")]
    pub from: Option<String>,
    /// Retained page-version UUID to restore, including a version preserved by
    /// `merge-project`. Mutually exclusive with `--from`.
    #[arg(long, conflicts_with = "from", required_unless_present = "from")]
    pub page_id: Option<String>,
    /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
    /// `workspace`, else `default`.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project name. When omitted, auto-derived from the current project.
    #[arg(long)]
    pub project: Option<String>,
    /// Emit the server response as JSON.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `reindex`.
#[derive(Debug, Args)]
pub struct ReindexArgs {}

/// Agent CLI to install hooks/extensions for. For MCP-only clients
/// (Claude Desktop), use `install-mcp --client <name>` instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum AgentChoice {
    /// Anthropic Claude Code.
    ClaudeCode,
    /// OpenAI Codex CLI.
    Codex,
    /// Cursor IDE agent — JSON-config hooks in `~/.cursor/hooks.json`.
    Cursor,
    /// Google Gemini CLI — JSON-config hooks in `~/.gemini/settings.json`.
    GeminiCli,
    /// OpenCode — probes `opencode --version`, then writes the compatible V1
    /// function plugin or V2 `{ id, setup }` plugin under
    /// `~/.config/opencode/plugins/`. Restart OpenCode for it to load.
    #[value(alias = "opencode")]
    OpenCode,
    /// OpenCode V2 compatibility alias; forces the V2 plugin contract and
    /// `ai-memory-opencode2.ts` path without probing. Shares V1's config dir,
    /// session store, and agent kind.
    #[value(name = "opencode2", alias = "opencode-v2", alias = "open-code2")]
    OpenCode2,
    /// Real Pi coding agent. The generated TypeScript extension provides
    /// lifecycle capture and bridges ai-memory's HTTP MCP tools into Pi.
    Pi,
    /// Oh My Pi (`omp`) — TypeScript extension
    /// under `~/.omp/agent/extensions/`, or the active profile's agent dir.
    /// `--apply` writes the extension file directly; restart `omp` for it to
    /// load.
    #[value(alias = "oh-my-pi")]
    Omp,
    /// OpenClaw personal AI gateway — native plugin package with
    /// session/tool/compaction hooks.
    Openclaw,
    /// Google Antigravity CLI (`agy`) — JSON-config hooks in
    /// `~/.gemini/config/hooks.json`.
    #[value(alias = "antigravity", alias = "agy")]
    AntigravityCli,
    /// xAI Grok Build CLI — JSON-config hooks in
    /// `~/.grok/hooks/ai-memory.json`. Native `ai-memory hook --event`
    /// integration using Grok-specific hook scripts. NOTE: Grok ignores
    /// hook stdout on `SessionStart`; `--apply` also writes
    /// `$GROK_HOME/rules/ai-memory-handoff.md` so the first turn calls
    /// `memory_handoff_list`, and the first `PostToolUse` injects the baton.
    Grok,
    /// Zero coding agent (Gitlawb/zero) — JSON-config lifecycle hooks in
    /// `$XDG_CONFIG_HOME/zero/hooks.json` (exec-form `command` + `args`,
    /// so ai-memory's native `hook` command runs with no shell). NOTE:
    /// Zero discards `sessionStart` hook stdout, so capture works but
    /// handoff injection does not — recover the prior session's handoff
    /// via the MCP `memory_handoff_accept` tool.
    Zero,
    /// Devin CLI — JSON-config hooks in
    /// `~/.devin/hooks.v1.json` or `~/.devin/config.json` hooks key.
    /// Native `ai-memory hook --event` integration using Devin-specific
    /// hook scripts. Devin consumes the handoff via
    /// `hookSpecificOutput.additionalContext` on `SessionStart`.
    Devin,
    /// Kimi Code CLI (Moonshot AI).
    #[value(alias = "kimi")]
    KimiCode,
    /// Kiro CLI (AWS), v2 agent engine — camelCase lifecycle hooks embedded
    /// in agent configs under `~/.kiro/agents/*.json`.
    #[value(alias = "kiro")]
    KiroCli,
    /// Kiro CLI (AWS), v3 agent engine — PascalCase lifecycle hooks in the
    /// standalone `$KIRO_HOME/hooks/ai-memory.json` registration file.
    #[value(alias = "kiro-v3")]
    KiroCliV3,
    /// Command Code CLI — stable JSON-config shell hooks in
    /// `~/.commandcode/settings.json`.
    #[value(alias = "commandcode", alias = "cmdc", alias = "cmd")]
    CommandCode,
    /// Pool (Poolside Agent CLI, `pool`) — project-scoped YAML hooks in
    /// the repo-root `.poolside/settings.yaml`. ai-memory stages the hook
    /// scripts and prints a ready-to-paste `hooks:` snippet; it does not
    /// write project-local files. NOTE: Pool's `SessionStart` stdout
    /// injection is not demonstrated, so capture works but handoff
    /// injection does not — recover the prior session's handoff via the
    /// MCP `memory_handoff_accept` tool, and close sessions with
    /// `ai-memory finalize-session --agent pool` (Pool has no true
    /// session-end event).
    #[value(alias = "poolside")]
    Pool,
    /// ZCode (z.ai) — JSON-config lifecycle hooks in the root `hooks` block
    /// of `~/.zcode/cli/config.json` (the same file `install-mcp --client
    /// zcode` registers MCP servers in). Entries are exec-form
    /// `type: "process"` (`command` + `args`, no shell), so ai-memory's
    /// native `hook` command runs directly. ZCode injects `SessionStart`
    /// stdout as model context (`hookSpecificOutput.additionalContext`,
    /// verified live against engine v0.16.5), so handoff delivery works.
    /// `Stop` fires at the end of every turn and there is no `SessionEnd`,
    /// so close sessions with `ai-memory finalize-session --agent zcode`.
    #[value(alias = "zai")]
    Zcode,
    /// Hermes Agent (Nous Research) — lifecycle hooks declared in the `hooks:`
    /// block of `~/.hermes/config.yaml`. Hermes runs each `command` through
    /// `shlex.split` with the event JSON on stdin and **no shell**, so
    /// ai-memory's native `hook` subcommand is invoked directly (exec form,
    /// like Zero and ZCode). ai-memory wires the tool events and the session
    /// lifecycle (`on_session_start`, `pre_llm_call`, `on_session_end` as a
    /// turn boundary, `on_session_finalize`); each primary-session
    /// `pre_llm_call` can bring a pending handoff into the upcoming turn,
    /// including after resuming an old native session. When the community
    /// memory-provider plugin is installed under `$HERMES_HOME/plugins`, only
    /// the tool events are wired, since the plugin owns the rest.
    /// `~/.hermes/config.yaml` is NOT written: it is YAML the installer would
    /// have to splice, and Hermes gates user hooks behind its own acceptance
    /// prompt (`hooks_auto_accept`), so `install-hooks --agent hermes` prints
    /// the ready-to-paste block.
    #[value(alias = "hermes-agent")]
    Hermes,
    /// GitHub Copilot CLI — JSON-config lifecycle hooks in
    /// `$COPILOT_HOME/hooks/ai-memory.json` (default
    /// `~/.copilot/hooks/ai-memory.json`). Configured with PascalCase event
    /// names, so Copilot sends the VS Code/Claude-compatible payload and the
    /// existing key-based extraction applies (#1040). No bare `copilot`
    /// alias: that word is already `install-mcp --client copilot`'s alias for
    /// the unrelated VS Code MCP client. NOTE: Copilot CLI reads a top-level
    /// `additionalContext` on `SessionStart`, not Claude Code's envelope, and
    /// the hook prints exactly that, so both capture and handoff injection
    /// work.
    #[value(name = "copilot-cli")]
    CopilotCli,
    /// Factory Droid CLI (`droid`) — lifecycle hooks merged into
    /// `~/.factory/hooks.json` (#1240). Droid sends Claude Code-shaped hook
    /// payloads on stdin, so each entry runs ai-memory's native `hook`
    /// command directly; there is no script bundle. Droid reads the `hooks`
    /// key of `~/.factory/settings.json` only while `hooks.json` is absent,
    /// so `--apply` refuses to create `hooks.json` over hooks still kept in
    /// `settings.json`. SessionStart stdout
    /// (`hookSpecificOutput.additionalContext`) carries the handoff, and
    /// Droid's own `SessionEnd` closes the session.
    #[value(alias = "factory-droid")]
    Droid,
    /// Meta Muse Code (`muse`) — lifecycle hooks merged into the `hooks` key
    /// of `${XDG_CONFIG_HOME:-~/.config}/muse/settings.json`, keeping its
    /// `schema_version` and every other key. Muse sends Claude Code-shaped
    /// hook payloads on stdin with a cleared environment, so each entry runs
    /// ai-memory's native `hook` command with the server, data dir and agent
    /// baked in; there is no script bundle. SessionStart stdout
    /// (`hookSpecificOutput.additionalContext`) carries the handoff, and
    /// Muse's own `SessionEnd` closes the session.
    #[value(alias = "muse-code", alias = "musecode")]
    Muse,
    /// Tencent CodeBuddy Code (`codebuddy`) — lifecycle hooks merged into the
    /// `hooks` key of `~/.codebuddy/settings.json`. CodeBuddy sends Claude
    /// Code-shaped hook payloads on stdin, so each entry runs ai-memory's
    /// native `hook` command directly; there is no script bundle. SessionStart
    /// stdout (`hookSpecificOutput.additionalContext`) carries the handoff.
    #[value(name = "codebuddy", alias = "code-buddy")]
    CodeBuddy,
    /// IBM Bob IDE — lifecycle hooks merged into the `hooks` key of
    /// `~/.bob/settings/settings.json`. Bob sends Claude Code-shaped payloads
    /// and injects plain `SessionStart` stdout into the model context.
    #[value(name = "ibm-bob", alias = "bob")]
    IbmBob,
    /// DeepSeek Harness (DSH) — lifecycle capture through the official
    /// `@deepseek-ai/dsh-hooks-claude-code` bridge, which consumes a Claude
    /// Code `hooks.json`. `install-hooks --agent dsh` stages the hook
    /// scripts, writes that generated `hooks.json`, and prints the Cordis
    /// patch fragment to merge into `$DSH_HOME/profiles/<profile>/
    /// cordis.patch.yml` (no fixed config file is written). The bridge
    /// delivers exactly seven events and no `SessionEnd`, so close sessions
    /// with `ai-memory finalize-session --agent dsh`; its detached
    /// `SessionStart` means handoff recovery goes through the MCP
    /// `memory_handoff_accept` tool.
    #[value(alias = "deepseek-harness", alias = "deepseek_harness")]
    Dsh,
    /// Cline CLI — lifecycle files under `~/.cline/hooks`. Cline runs
    /// TaskStart/TaskResume detached by default, so capture works but automatic
    /// handoff injection does not; accept the handoff through MCP instead.
    #[value(alias = "cline-cli")]
    Cline,
    /// Qwen Code (`qwen`) — lifecycle hooks merged into the `hooks` key of
    /// `~/.qwen/settings.json`. Qwen sends Claude Code-shaped hook payloads
    /// on stdin, so each entry runs ai-memory's native `hook` command
    /// directly; there is no script bundle. SessionStart stdout
    /// (`hookSpecificOutput.additionalContext`) carries the handoff, and
    /// Qwen's own `SessionEnd` closes the session.
    #[value(name = "qwen-code", alias = "qwen", alias = "qwencode")]
    QwenCode,
    /// Qoder CLI and IDE — lifecycle hooks merged into the `hooks` key of
    /// `~/.qoder/settings.json`. Qoder sends Claude Code-shaped JSON on stdin
    /// and consumes `SessionStart` additional context.
    Qoder,
}

impl AgentChoice {
    /// The core [`AgentKind`] this CLI choice selects — the single mapping
    /// point between the clap surface and the domain enum. Wire strings,
    /// hook-bundle directory names, and session attribution all derive from
    /// the returned kind's `as_str()`; adding an agent means extending this
    /// match once instead of hunting per-command copies.
    #[must_use]
    pub const fn kind(self) -> ai_memory_core::AgentKind {
        use ai_memory_core::AgentKind;
        match self {
            Self::ClaudeCode => AgentKind::ClaudeCode,
            Self::Codex => AgentKind::Codex,
            Self::Cursor => AgentKind::Cursor,
            Self::GeminiCli => AgentKind::GeminiCli,
            Self::OpenCode | Self::OpenCode2 => AgentKind::OpenCode,
            Self::Pi => AgentKind::Pi,
            Self::Omp => AgentKind::Omp,
            Self::Openclaw => AgentKind::OpenClaw,
            Self::AntigravityCli => AgentKind::AntigravityCli,
            Self::Grok => AgentKind::Grok,
            Self::Zero => AgentKind::Zero,
            Self::Devin => AgentKind::Devin,
            Self::KimiCode => AgentKind::KimiCode,
            Self::KiroCli | Self::KiroCliV3 => AgentKind::KiroCli,
            Self::CommandCode => AgentKind::CommandCode,
            Self::Pool => AgentKind::Pool,
            Self::Zcode => AgentKind::Zcode,
            Self::Hermes => AgentKind::Hermes,
            Self::CopilotCli => AgentKind::CopilotCli,
            Self::Droid => AgentKind::Droid,
            Self::Muse => AgentKind::Muse,
            Self::CodeBuddy => AgentKind::CodeBuddy,
            Self::IbmBob => AgentKind::IbmBob,
            Self::Dsh => AgentKind::Dsh,
            Self::Cline => AgentKind::Cline,
            Self::QwenCode => AgentKind::QwenCode,
            Self::Qoder => AgentKind::Qoder,
        }
    }

    /// `hooks/<subdir>` bundle name for agents that install script hooks.
    /// `None` for agents wired through a generated integration (plugin /
    /// extension / exec-form native commands) instead of a script
    /// directory. The subdir equals the kind's wire string for every
    /// script agent.
    #[must_use]
    pub const fn script_hook_subdir(self) -> Option<&'static str> {
        match self {
            Self::OpenCode
            | Self::OpenCode2
            | Self::Pi
            | Self::Omp
            | Self::Openclaw
            | Self::Zero
            | Self::Zcode
            | Self::Hermes
            | Self::Droid
            | Self::Muse
            | Self::CodeBuddy
            | Self::IbmBob
            | Self::Cline
            | Self::QwenCode => None,
            Self::Qoder => None,
            _ => Some(self.kind().as_str()),
        }
    }
}

/// Parse a `finalize-session --agent` value into an [`ai_memory_core::AgentKind`].
///
/// Unlike the install-oriented `AgentChoice` value-enum, this accepts every
/// agent the store's CHECK constraint permits, because finalize-session is
/// agent-agnostic and must be able to close a session for any captured harness
/// (#623). A genuine typo — which `from_wire` would silently map to `Other` —
/// is rejected so the operator gets a clear error instead of a mis-scoped
/// finalize.
fn parse_finalizable_agent(s: &str) -> Result<ai_memory_core::AgentKind, String> {
    use ai_memory_core::AgentKind;
    let kind = AgentKind::from_wire(s);
    if matches!(kind, AgentKind::Other) && !s.eq_ignore_ascii_case("other") {
        let known = AgentKind::ALL
            .iter()
            .map(|k| k.as_str())
            .collect::<Vec<_>>()
            .join(", ");
        return Err(format!("unknown agent '{s}'; expected one of: {known}"));
    }
    Ok(kind)
}

/// Arguments for `recover`.
#[derive(Debug, Args)]
pub struct RecoverArgs {
    /// Print the machine-readable report as JSON on stdout.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `finalize-session`.
#[derive(Debug, Args)]
pub struct FinalizeSessionArgs {
    /// Agent kind to finalize. Accepts any agent the store recognises — unlike
    /// `install-hooks`/`setup-agent`, which are limited to agents with a
    /// first-party installer. finalize-session is agent-agnostic (it just posts
    /// a synthetic session-end and summarises), so refusing a captured harness
    /// like `hermes` here only stranded its sessions unclosable (#623).
    /// Defaults to Codex for backward compatibility.
    #[arg(long, default_value = "codex", value_parser = parse_finalizable_agent)]
    pub agent: ai_memory_core::AgentKind,
    /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
    /// `workspace`, else `default`.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project name. When omitted, auto-derived from the current project.
    #[arg(long)]
    pub project: Option<String>,
    /// Finalize sessions belonging to OTHER operators too.
    ///
    /// By default only your own (and unattributed) sessions are considered, so
    /// finalizing cannot end a colleague's live session. Use this to recover a
    /// teammate's session that died without emitting SessionEnd.
    #[arg(long, default_value_t = false)]
    pub all_owners: bool,
    /// Finalize every matching open session instead of just the latest one.
    #[arg(long, conflicts_with = "session_id")]
    pub all: bool,
    /// Finalize exactly this session id instead of "the latest open one"
    /// (still subject to `--all-owners`). Use this when other sessions for
    /// the same agent may be open concurrently in the same project (e.g.
    /// multiple terminal tabs each running Kiro CLI against one repo) —
    /// picking "latest" in that case risks closing out the wrong
    /// (still-active) session.
    #[arg(long, conflicts_with = "all")]
    pub session_id: Option<ai_memory_core::SessionId>,
    /// Re-finalize a session that already ended (requires `--session-id`).
    ///
    /// Use this when the conversation continued after a first finalize and
    /// landed new observations: agents without a true session-end event
    /// (Antigravity CLI, Kiro, ZCode, Pool) keep capturing under the same
    /// session id, but the plain discovery step only sees open sessions, so
    /// a second finalize would silently find nothing. With `--reopen` the
    /// lookup also matches the ended session and the normal session-end
    /// path re-runs (updated summary page, handoff, opt-in consolidation).
    /// When nothing new landed since the first end, the re-run is a
    /// harmless no-op.
    #[arg(long, requires = "session_id")]
    pub reopen: bool,
    /// Emit a JSON summary.
    #[arg(long)]
    pub json: bool,
}

/// Tool-schema dialect to pin into the installed MCP URL, as the server's
/// `?flavor=` marker (docs/mcp-install.md → Schema dialects for strict
/// upstreams). `install-mcp` already picks one for the clients whose upstream
/// is fixed — Kimi Code is always Moonshot, Kiro is always Bedrock — but a
/// client that fronts several models cannot be pinned by its name alone. A
/// Command Code or OpenCode install routed to Vertex needs `gemini`; the same
/// client on another model does not, and forcing it there would narrow the
/// advertised schema for no reason. So this stays an explicit operator choice.
///
/// Every variant is at least as permissive as each client's built-in default,
/// so passing one can only relax the advertised schema further, never tighten
/// it below what the client already needs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum SchemaFlavor {
    /// Drop root-level `anyOf`/`oneOf`/`allOf` (Moonshot).
    Moonshot,
    /// Same rewrite, for Bedrock-backed clients.
    Bedrock,
    /// The above, plus nullable unions collapsed to a single `type` plus
    /// `nullable: true` (Gemini / Vertex).
    #[value(alias = "vertex")]
    Gemini,
}

impl SchemaFlavor {
    /// The `flavor=` query value the server matches in `restricted_schema_flavor`.
    pub fn marker(self) -> &'static str {
        match self {
            Self::Moonshot => "moonshot",
            Self::Bedrock => "bedrock",
            Self::Gemini => "gemini",
        }
    }
}

/// MCP client to render configuration for. Includes both the
/// hook-capable agents (Claude Code / Codex / OpenCode — same MCP
/// surface, also covered by `install-hooks`) and the MCP-only
/// clients researched in docs/mcp-install.md.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum McpClient {
    /// Anthropic Claude Code — `claude mcp add`.
    ClaudeCode,
    /// OpenAI Codex CLI — `$CODEX_HOME/config.toml` (default `~/.codex/config.toml`).
    Codex,
    /// OpenCode — probes `opencode --version`, then writes the compatible V1
    /// direct `mcp` entry or V2 nested `mcp.servers` entry.
    #[value(alias = "opencode")]
    OpenCode,
    /// OpenCode V2 compatibility alias; forces nested `mcp.servers` with
    /// `type: "remote"`, no V1 `enabled`, and `oauth: false`.
    #[value(name = "opencode2", alias = "opencode-v2", alias = "open-code2")]
    OpenCode2,
    /// Cursor IDE — `~/.cursor/mcp.json` or `.cursor/mcp.json`.
    Cursor,
    /// Anthropic Claude Desktop — uses the `mcp-remote` stdio shim
    /// to talk to ai-memory's HTTP endpoint (Claude Desktop's JSON
    /// config does not register HTTP transports directly).
    ClaudeDesktop,
    /// Google Gemini CLI — `~/.gemini/settings.json`.
    GeminiCli,
    /// OpenClaw personal AI gateway — `~/.openclaw/config.json`.
    Openclaw,
    /// Real Pi coding agent. Uses ai-memory's generated bridge extension
    /// because Pi has no native MCP config.
    Pi,
    /// Oh My Pi (`omp`) — `~/.omp/agent/mcp.json`, or the active profile's
    /// agent dir.
    #[value(alias = "oh-my-pi")]
    Omp,
    /// Google Antigravity CLI (`agy`) — `~/.gemini/config/mcp_config.json`.
    #[value(alias = "antigravity", alias = "agy")]
    AntigravityCli,
    /// Zero coding agent (Gitlawb/zero) — `~/.config/zero/config.json`,
    /// `mcp.servers` map with native HTTP transport + bearer headers.
    Zero,
    /// ZCode (z.ai) — `~/.zcode/cli/config.json`, nested `mcp.servers`
    /// map with `type: "http"` + `url` + optional `headers`. ZCode's
    /// entry schema is strict: unknown keys make it drop the server
    /// silently, so the generated entry carries nothing else.
    Zcode,
    /// Devin CLI — `~/.devin/config.json`.
    Devin,
    /// xAI Grok Build CLI — `~/.grok/config.toml` under
    /// `[mcp_servers.<name>]` with native HTTP `url` + `headers`.
    /// Pair with `install-hooks --agent grok` for lifecycle capture.
    /// Grok ignores SessionStart stdout; that apply also writes the
    /// first-turn `memory_handoff_list` rule under `$GROK_HOME/rules`.
    Grok,
    /// Kimi Code CLI (Moonshot AI).
    #[value(alias = "kimi")]
    KimiCode,
    /// Kiro CLI - `$KIRO_HOME/settings/mcp.json` (default
    /// `~/.kiro/settings/mcp.json`). Pair with
    /// `install-hooks --agent kiro-cli` for verified v2 lifecycle capture.
    #[value(alias = "kiro")]
    KiroCli,
    /// Command Code CLI — `~/.commandcode/mcp.json`.
    #[value(alias = "commandcode", alias = "cmdc", alias = "cmd")]
    CommandCode,
    /// IBM Bob IDE — `~/.bob/settings/mcp.json`, using native Streamable HTTP.
    /// Pair with `install-hooks --agent ibm-bob` for lifecycle capture and
    /// plain-text `SessionStart` handoff delivery.
    #[value(name = "ibm-bob", alias = "bob")]
    IbmBob,
    /// Qwen Code — `~/.qwen/settings.json`, servers under the root
    /// `mcpServers` map with `httpUrl` (streamable HTTP; the plain `url`
    /// key is legacy SSE). Qwen expands `$NAME` and `${NAME}` in every
    /// string. Pair with `install-hooks --agent qwen-code` for lifecycle
    /// capture and `SessionStart` handoff delivery.
    #[value(name = "qwen-code", alias = "qwen", alias = "qwencode")]
    QwenCode,
    /// Qoder CLI and IDE — user-level `~/.qoder/settings.json`, with a
    /// stdio `ai-memory mcp-bridge --no-session-id` entry under `mcpServers`.
    Qoder,
    /// GitHub Copilot CLI — `$COPILOT_HOME/mcp-config.json` (default
    /// `~/.copilot/mcp-config.json`), servers under the root `mcpServers` map
    /// with `type: "http"` + `url` + optional `headers` (#1040). Pair with
    /// `install-hooks --agent copilot-cli` for lifecycle capture and
    /// `SessionStart` handoff delivery via Copilot's top-level
    /// `additionalContext`. Not to be
    /// confused with `vscode-copilot` (alias `copilot`), the VS Code agent
    /// mode client.
    #[value(name = "copilot-cli")]
    CopilotCli,
    /// Factory Droid CLI — `~/.factory/mcp.json`, servers under the root
    /// `mcpServers` map with `type: "http"` + `url` (#1240). Droid expands
    /// `${VAR}` only in `headers`, never in `url`, so the URL is written
    /// literally and a bearer is referenced as `${AI_MEMORY_AUTH_TOKEN}`,
    /// which must be exported where droid runs. Pair with
    /// `install-hooks --agent droid` for lifecycle capture.
    #[value(alias = "factory-droid")]
    Droid,
    /// Swival CLI — project-scoped `.swival/mcp.json` using native HTTP.
    /// This integration is MCP-only; Swival's lifecycle callback does not
    /// expose a stable session identifier for reliable capture correlation.
    Swival,
    /// VS Code GitHub Copilot (agent mode) — per-workspace
    /// `.vscode/mcp.json`. Copilot's agent mode reads MCP servers
    /// from VS Code's own MCP framework (top-level `servers` key),
    /// so the same JSON file works for any MCP-capable VS Code
    /// extension, not just Copilot. Default scope is the current
    /// workspace; pass `--config-file ~/path/to/mcp.json` to target
    /// the user-level config instead.
    ///
    /// The hook surface (PreToolUse/PostToolUse/SessionStart) does
    /// not yet exist in VS Code Copilot — this is MCP-only by
    /// design. See `install-mcp --client vscode-copilot`.
    #[value(name = "vscode-copilot", alias = "copilot", alias = "github-copilot")]
    VsCodeCopilot,
    /// Zed editor - user-level `settings.json` under the platform config
    /// directory. Zed reads remote MCP servers from the top-level
    /// `context_servers` map. This integration is MCP-only because Zed
    /// does not expose ai-memory-compatible lifecycle hooks.
    Zed,
    /// Meta Muse Code — `${XDG_CONFIG_HOME:-~/.config}/muse/settings.json`.
    /// The entry is a stdio `ai-memory mcp-bridge --agent muse`, which
    /// forwards the `MUSE_SESSION_ID` Muse gives its stdio servers, so Muse
    /// is a session-aware client (a streamable-HTTP entry carries no session
    /// id).
    ///
    /// Muse reads servers from `mcpServers` (`type: "stdio"`) or the legacy
    /// `mcp_servers` (`transport: "stdio"`), and drops the whole MCP block
    /// when both are present. The writer uses `mcp_servers` when the file
    /// already has it, else `mcpServers`, never adds the second, and refuses
    /// a file that already holds both. The settings file must carry
    /// `"schema_version": 1` or every Muse command fails at startup, so the
    /// writer adds the key when it is absent and never rewrites an existing
    /// value. `mode` defaults to `required`, which aborts the whole Muse run
    /// when the server cannot start, so the entry sets `mode: "optional"`.
    /// Pair with `install-hooks --agent muse` for lifecycle capture.
    #[value(alias = "muse-code", alias = "musecode")]
    Muse,
    /// DeepSeek Harness (DSH) MCP writer. DSH has no fixed JSON/TOML MCP
    /// config: the client is a Cordis plugin entry
    /// (@deepseek-ai/dsh-mcp-client) inside a profile's cordis.patch.yml.
    /// This integration is print-only (--apply is refused); merge the
    /// rendered insert list into the profile patch. Lifecycle capture is
    /// installed separately with `install-hooks --agent dsh`.
    #[value(alias = "deepseek-harness", alias = "deepseek_harness")]
    Dsh,
    /// Hermes Agent (Nous Research) — the `mcp_servers:` map of
    /// `~/.hermes/config.yaml`. Print-only (--apply is refused): ai-memory has
    /// no YAML editor for that file, which the operator also edits. The entry
    /// is a stdio `ai-memory mcp-bridge --no-session-id`, so it carries no
    /// token. Lifecycle capture is installed separately with `install-hooks
    /// --agent hermes`.
    #[value(alias = "hermes-agent")]
    Hermes,
    /// Cline CLI — `~/.cline/data/settings/cline_mcp_settings.json` (or
    /// `CLINE_MCP_SETTINGS_PATH`) with an explicit Streamable HTTP transport.
    #[value(alias = "cline-cli")]
    Cline,
    /// FreeBuff CLI — `~/.agents/mcp.json`; MCP-only through ai-memory's
    /// sessionless stdio-to-HTTP bridge.
    Freebuff,
    /// Prime Agent (PrimeIntellect-ai/prime-agent) - the `mcpServers` map of
    /// `$PRIME_AGENT_CODING_AGENT_DIR/settings.json` (default
    /// `~/.prime/agent/settings.json`) with `type: "http"` + `url`. A token is
    /// referenced through `bearerTokenEnvVar: "AI_MEMORY_AUTH_TOKEN"`, never
    /// written literally: that is the only non-OAuth credential Prime Agent
    /// counts as connected and names to the model. MCP-only: Prime Agent 0.10
    /// has no lifecycle hooks (its earlier TypeScript extensions were removed).
    PrimeAgent,
}

/// Arguments for `commit`.
#[derive(Debug, Args)]
pub struct CommitArgs {
    /// Commit message.
    #[arg(long, short = 'm', default_value = "manual commit")]
    pub message: String,
}

/// LLM provider for `llm-test`.
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum LlmProviderChoice {
    /// Anthropic Messages API.
    Anthropic,
    /// Anthropic Messages API using a Claude subscription OAuth token.
    AnthropicOauth,
    /// OpenAI Chat Completions.
    Openai,
    /// Google Gemini (Generative Language API).
    Gemini,
    /// OpenAI-compatible local (Ollama, vLLM, LM Studio).
    OpenaiCompat,
    /// OpenAI ChatGPT/Codex OAuth backend.
    OpenaiOauth,
    /// Reuse Codex CLI authentication and delegated refresh.
    Codex,
    /// GitHub Copilot Chat backend.
    Copilot,
    /// OpenCode cloud API (Go by default; AI_MEMORY_LLM_BASE_URL selects Zen).
    Opencode,
    /// Cursor subscription via the logged-in `agent` CLI (`--print --mode ask`).
    Cursor,
}

/// Arguments for `embed`.
#[derive(Debug, Args)]
pub struct EmbedArgs {
    /// Report what would be embedded without actually mutating.
    #[arg(long)]
    pub dry_run: bool,
    /// Re-embed pages even when they already have a row with the
    /// currently-configured `(provider, model, dim)`.
    #[arg(long)]
    pub force: bool,
    /// Workspace name (auto-created if absent).
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project name. When omitted, taken from the nearest
    /// `.ai-memory.toml` marker's `project`, then from the git remote,
    /// then from the current directory's name. Matches the
    /// hook router's per-cwd convention so this command targets the
    /// same project sessions write into.
    #[arg(long)]
    pub project: Option<String>,
}

/// Arguments for `forget-sweep`.
#[derive(Debug, Args)]
pub struct ForgetSweepArgs {
    /// Report what would be evicted without actually mutating.
    #[arg(long)]
    pub dry_run: bool,
    /// Workspace name (auto-created if absent).
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project name. When omitted, taken from the nearest
    /// `.ai-memory.toml` marker's `project`, then from the git remote,
    /// then from the current directory's name.
    #[arg(long)]
    pub project: Option<String>,
}

/// Arguments for `lint`.
#[derive(Debug, Args)]
pub struct LintArgs {
    /// Compute findings but don't write `wiki/_lint/report.md`.
    #[arg(long)]
    pub dry_run: bool,
    /// Run only rule-based checks; skip the LLM contradiction pass.
    /// Lets you get fast results without consuming LLM tokens when a
    /// provider is configured.
    #[arg(long)]
    pub no_llm: bool,
    /// Workspace name (auto-created if absent).
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project name. When omitted, taken from the nearest
    /// `.ai-memory.toml` marker's `project`, then from the git remote,
    /// then from the current directory's name.
    #[arg(long)]
    pub project: Option<String>,
}

/// Arguments for `curator`.
#[derive(Debug, Args)]
pub struct CuratorArgs {
    /// Return a report without staging a pending write. Default when no mode flag is set.
    #[arg(long)]
    pub dry_run: bool,
    /// Stage one pending curator report page for approval.
    #[arg(long)]
    pub stage: bool,
    /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
    /// `workspace`, else `default`.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project name. When omitted, taken from the nearest
    /// `.ai-memory.toml` marker's `project`, then from the git remote,
    /// then from the current directory's name.
    #[arg(long)]
    pub project: Option<String>,
    /// Emit only machine-readable JSON.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `auto-improve-report`.
#[derive(Debug, Args)]
pub struct AutoImproveReportArgs {
    /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
    /// `workspace`, else `default`.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project name. When omitted, taken from the nearest
    /// `.ai-memory.toml` marker's `project`, then from the git remote,
    /// then from the current directory's name.
    #[arg(long)]
    pub project: Option<String>,
    /// Lookback window in days.
    #[arg(long, default_value_t = ai_memory_consolidate::DEFAULT_AUTO_IMPROVE_TELEMETRY_SINCE_DAYS)]
    pub days: u32,
    /// Maximum rows in each top-N count table.
    #[arg(long, default_value_t = ai_memory_consolidate::DEFAULT_AUTO_IMPROVE_TELEMETRY_TOP_LIMIT)]
    pub limit: usize,
    /// Stage one pending telemetry report page for later approval.
    #[arg(long)]
    pub stage: bool,
    /// Emit only machine-readable JSON.
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `auto-improve`.
#[derive(Debug, Args)]
pub struct AutoImproveArgs {
    /// Completed session UUID to review.
    #[arg(long)]
    pub session_id: String,
    /// Workspace name. Defaults to the nearest `.ai-memory.toml` marker's
    /// `workspace`, else `default`.
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project name. When omitted, taken from the nearest
    /// `.ai-memory.toml` marker's `project`, then from the git remote,
    /// then from the current directory's name.
    #[arg(long)]
    pub project: Option<String>,
    /// Override `[auto_improve].min_observations` for this run.
    #[arg(long)]
    pub min_observations: Option<usize>,
    /// Override `[auto_improve].min_session_duration_secs` for this run.
    #[arg(long)]
    pub min_session_duration_secs: Option<u64>,
    /// Override `[auto_improve].min_confidence` for this run.
    #[arg(long)]
    pub min_confidence: Option<f32>,
    /// Override `[auto_improve].max_input_tokens` for this run.
    #[arg(long)]
    pub max_input_tokens: Option<usize>,
    /// Override `[auto_improve].max_proposals_per_run` for this run.
    #[arg(long)]
    pub max_proposals: Option<usize>,
    /// Include raw fallback context when the reviewer supports it.
    #[arg(long)]
    pub include_raw_fallback: bool,
    /// Emit only the machine-readable JSON report.
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Args)]
pub struct PendingWritesArgs {
    #[command(subcommand)]
    pub command: PendingWritesCommand,
}

#[derive(Debug, Subcommand)]
pub enum PendingWritesCommand {
    List(PendingWritesListArgs),
    Show(PendingWriteIdArgs),
    Diff(PendingWriteIdArgs),
    Approve(PendingWriteIdArgs),
    Reject(PendingWriteRejectArgs),
}

#[derive(Debug, Args)]
pub struct PendingWritesListArgs {
    #[arg(long)]
    pub workspace: Option<String>,
    #[arg(long)]
    pub project: Option<String>,
    #[arg(long)]
    pub status: Option<String>,
    #[arg(long, default_value_t = 50)]
    pub limit: usize,
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Args)]
pub struct PendingWriteIdArgs {
    pub id: String,
    #[arg(long)]
    pub workspace: Option<String>,
    #[arg(long)]
    pub project: Option<String>,
    #[arg(long)]
    pub json: bool,
}

#[derive(Debug, Args)]
pub struct PendingWriteRejectArgs {
    pub id: String,
    #[arg(long)]
    pub workspace: Option<String>,
    #[arg(long)]
    pub project: Option<String>,
    #[arg(long, default_value = "rejected by reviewer")]
    pub reason: String,
    #[arg(long)]
    pub json: bool,
}

/// Arguments for `llm-test`.
#[derive(Debug, Args)]
pub struct LlmTestArgs {
    /// Probe the server's own configured provider instead of building one
    /// from this shell's environment.
    ///
    /// The retry hint the server and `/web` print uses this form: a server in
    /// a container or on another host holds the keys, so a client-side
    /// `llm-test` fails while the server is healthy (#1639). Takes no
    /// `--provider`/`--model`/`--prompt`/`--base-url`/`--api-key`: the probe
    /// runs what the server is configured with, and a client cannot point it
    /// at another URL or hand it a key.
    #[arg(
        long,
        conflicts_with_all = ["provider", "model", "prompt", "structured", "base_url", "api_key"]
    )]
    pub server: bool,
    /// Provider to test.
    #[arg(long, value_enum, required_unless_present = "server")]
    pub provider: Option<LlmProviderChoice>,
    /// Model identifier (e.g. `claude-haiku-4-5`, `gpt-5.4-mini`, `llama3.1:8b`).
    #[arg(long, required_unless_present = "server")]
    pub model: Option<String>,
    /// Prompt to send.
    #[arg(long, required_unless_present = "server")]
    pub prompt: Option<String>,
    /// Request a small JSON-schema response instead of plain text.
    #[arg(long)]
    pub structured: bool,
    /// Base URL override (required for openai-compat).
    #[arg(long)]
    pub base_url: Option<String>,
    /// Optional API key override (otherwise pulled from env).
    #[arg(long, hide_env_values = true)]
    pub api_key: Option<String>,
}

/// Project-resolution strategy to bake into installed hooks.
///
/// `basename` (the default) bakes nothing. `repo-root` bakes a remote-less
/// fallback that resolves from the main git repo root (collapsing subdirectories
/// and worktrees) without a per-repo `.ai-memory.toml` marker. A valid remote's
/// canonical path name wins while the project remains unpinned; a marker's
/// explicit `project` or `identity` and operator-home routing still win.
/// Which way capture fails when a repository has no `.ai-memory.toml`
/// marker (#446).
#[derive(Copy, Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum CaptureModeArg {
    /// Capture unless a marker excludes it — the historical default.
    Denylist,
    /// Capture only repositories that carry a marker. A repository without
    /// one emits no lifecycle events at all.
    Allowlist,
}

impl CaptureModeArg {
    /// The policy value this flag selects.
    #[must_use]
    pub const fn mode(self) -> ai_memory_hooks::CaptureMode {
        match self {
            Self::Denylist => ai_memory_hooks::CaptureMode::Denylist,
            Self::Allowlist => ai_memory_hooks::CaptureMode::Allowlist,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum ProjectStrategyArg {
    /// `project = basename(cwd)` — the default; bakes nothing.
    Basename,
    /// `project = basename(main git repo root)` — collapses subdirs/worktrees.
    /// clap renders this value as `repo-root`.
    RepoRoot,
}

impl ProjectStrategyArg {
    /// Normalize to what the hook command should bake. `None` bakes
    /// nothing (behavior unchanged); `Some("repo-root")` bakes the
    /// repo-root default into the generated hooks.
    #[must_use]
    pub fn baked(self) -> Option<&'static str> {
        match self {
            Self::Basename => None,
            Self::RepoRoot => Some("repo-root"),
        }
    }
}

/// Arguments for `hook` — emit one lifecycle event natively.
#[derive(Debug, Args)]
pub struct HookArgs {
    /// Lifecycle event, e.g. `pre-tool-use`, `session-start`.
    #[arg(long)]
    pub event: String,
    /// Agent name to attribute the event to, e.g. `claude-code`.
    #[arg(long)]
    pub agent: String,
    /// Base URL of the ai-memory hook server. Empty or omitted means the
    /// `server_url` of this install's config.
    #[arg(long, default_value = "")]
    pub server_url: String,
    /// Optional bearer token (`Authorization: Bearer <token>`).
    #[arg(long, hide_env_values = true)]
    pub auth_token: Option<String>,
    /// Default project strategy baked in by `install-hooks
    /// --project-strategy`. Applies only when a `.ai-memory.toml`
    /// marker does not pin its own `project_strategy`.
    #[arg(long, value_enum)]
    pub project_strategy: Option<ProjectStrategyArg>,
    /// Inspect capture policy without spooling, draining, or contacting the server.
    #[arg(long)]
    pub check_capture: bool,
    /// Capture failure mode baked in by `install-hooks --capture-mode`.
    /// Under `allowlist`, a repository with no `.ai-memory.toml` marker emits
    /// no lifecycle event at all — the event is dropped before it can reach
    /// the local spool or the wire.
    #[arg(long, value_enum)]
    pub capture_mode: Option<CaptureModeArg>,
    /// Opt in to assistant/Stop capture: on a supported agent's `stop` event, attach a
    /// sanitized, capped excerpt of the assistant's final turn as the Stop body.
    /// Baked onto the native `stop` command by
    /// `install-hooks --capture-assistant`; the server must also enable
    /// `capture_assistant`. No effect on other events (#196).
    #[arg(long)]
    pub capture_assistant: bool,
}

/// Arguments for hidden `hook-drain`.
#[derive(Debug, Args)]
pub struct HookDrainArgs {}

/// Arguments for hidden `service-host`.
#[derive(Debug, Args)]
pub struct ServiceHostArgs {
    /// Run the supervisor in this process instead of starting it detached.
    #[arg(long)]
    pub supervise: bool,
}

/// Arguments for hidden `render-plugins`.
#[derive(Debug, Args)]
pub struct RenderPluginsArgs {
    /// Repository root to write `plugins/` and the catalogs under.
    #[arg(long)]
    pub out: PathBuf,
}

/// Arguments for `install-hooks`.
#[derive(Debug, Args)]
pub struct InstallHooksArgs {
    /// Which agent's hooks to render.
    #[arg(long, value_enum, default_value_t = AgentChoice::ClaudeCode)]
    pub agent: AgentChoice,
    /// Filesystem root that contains the vendored hook scripts (defaults
    /// to the repo's `hooks/` if known, else `/usr/local/share/ai-memory/hooks`).
    /// Ignored for generated TypeScript integrations (OpenCode, OMP, Pi,
    /// OpenClaw).
    #[arg(long)]
    pub hooks_dir: Option<PathBuf>,
    /// Server URL the hooks will POST to. Defaults to the configured
    /// `server_url` / AI_MEMORY_SERVER_URL when set, else loopback. If neither
    /// is configured, apply-mode also reuses an ownership-verified ai-memory MCP
    /// entry from either known OpenCode major-version location when present.
    // Keep this optional so effective_hook_server_url can distinguish an
    // omitted flag from an explicit URL that equals the compiled default.
    #[arg(long)]
    pub server_url: Option<String>,
    /// Bearer token to embed in the hook config's `env` block. When
    /// set, every hook call carries `Authorization: Bearer <token>`,
    /// matching what the server requires when AI_MEMORY_AUTH_TOKEN
    /// is set there. Generate one with `ai-memory generate-auth-token`.
    #[arg(long, hide_env_values = true)]
    pub auth_token: Option<String>,
    /// Stamp the installed hooks with a registered username for operator
    /// visibility. This flag is metadata: the server resolves attribution
    /// from the API key passed via `--auth-token`. Recommended workflow:
    ///
    /// ```bash
    /// # 1. issue a native API key for the user (prints the key once)
    /// ai-memory api-key add --username alice --label claude-hooks
    ///
    /// # 2. wire that API key into the agent's hooks
    /// ai-memory install-hooks --apply --agent claude-code \
    ///     --as-user alice --auth-token <alice-api-key>
    /// ```
    ///
    /// Without this flag, the installer omits the username label;
    /// attribution still resolves from the bearer token at request time.
    #[arg(long)]
    pub as_user: Option<String>,
    /// **Mutate** the selected agent's hook config in place instead of
    /// printing the snippet/plugin. Idempotent — replaces the ai-memory
    /// hook entries or generated plugin and preserves unrelated config
    /// where the agent format supports merging. A timestamped backup is
    /// written next to the original before each modifying write.
    #[arg(long)]
    pub apply: bool,
    /// Override the settings/plugin/extension path for the selected agent.
    /// For OpenClaw this is the generated plugin package directory; for Cline
    /// CLI it is the hook directory.
    #[arg(long)]
    pub config_file: Option<PathBuf>,
    /// Where to write the hook configuration. For Claude Code, `project`
    /// targets the repository's `.claude/settings.local.json` (at the git
    /// root when available) and ignores `CLAUDE_CONFIG_DIR`. For Cline CLI,
    /// it targets `.cline/hooks` in the current checkout. Cannot be combined
    /// with `--config-file`, which names the target path directly.
    #[arg(
        long,
        value_enum,
        default_value_t = HookInstallScope::Global,
        conflicts_with = "config_file"
    )]
    pub scope: HookInstallScope,
    /// Default project strategy to bake into the installed hooks.
    /// `repo-root` makes every session resolve its project from the main
    /// git repo root (collapsing subdirectories and worktrees) without a
    /// per-repo `.ai-memory.toml` marker. A marker's own `project_strategy`
    /// still wins. `basename` bakes nothing and is identical to prior
    /// behavior. Omitting the flag leaves it unset: an `--apply` re-run then
    /// preserves whatever strategy an earlier `--apply` baked, so a bare
    /// re-apply (e.g. the auto-refresh in `ai-memory upgrade`) does not
    /// silently revert `repo-root` back to `basename`.
    #[arg(long, value_enum)]
    pub project_strategy: Option<ProjectStrategyArg>,
    /// Capture a sanitized excerpt of the assistant's final turn through the
    /// native Stop hook. Supported for Claude Code, Codex and OpenCode 2 on a
    /// native platform; the server must also set `capture_assistant = true`.
    /// A bare re-apply preserves an existing opt-in. Default off.
    #[arg(long)]
    pub capture_assistant: bool,
    /// Persist the capture failure mode for this install (#446). Under
    /// `allowlist`, a repository with no `.ai-memory.toml` marker emits no
    /// lifecycle event at all, for every agent. Stored in the data dir, so a
    /// later bare `--apply` — including the auto-refresh inside `upgrade` —
    /// cannot regenerate it away. Omitting the flag leaves the stored mode
    /// untouched; `--capture-mode denylist` restores the default.
    #[arg(long, value_enum)]
    pub capture_mode: Option<CaptureModeArg>,
    /// Do not install Claude Code's `UserPromptSubmit` capture hook. Prompt
    /// text is then excluded before it can enter the local spool or wire.
    /// A bare `--apply` re-run preserves an existing opt-out; use
    /// `--capture-prompts` to enable prompt capture again explicitly.
    #[arg(long, conflicts_with = "capture_prompts")]
    pub no_capture_prompts: bool,
    /// Explicitly enable Claude Code prompt capture after an earlier
    /// `--no-capture-prompts` install. Only valid for Claude Code.
    #[arg(long, conflicts_with = "no_capture_prompts")]
    pub capture_prompts: bool,
    /// OMP profile to install into, as `omp --profile` names it:
    /// `~/.omp/profiles/<profile>/agent/extensions/`. Beats `OMP_PROFILE` and
    /// `PI_PROFILE`; `default` selects the default profile.
    #[arg(long)]
    pub profile: Option<String>,
}

/// Arguments for `install-mcp`.
#[derive(Debug, Clone, Args)]
pub struct InstallMcpArgs {
    /// Which MCP client to render configuration for.
    #[arg(long, value_enum, default_value_t = McpClient::ClaudeCode)]
    pub client: McpClient,
    /// Server URL the client should connect to — either the base URL
    /// (`https://host:49374`, the same value `install-hooks --server-url`
    /// takes) or the full MCP endpoint (`…/mcp`); a missing `/mcp` suffix
    /// is appended automatically. Defaults to the configured
    /// `server_url` / AI_MEMORY_SERVER_URL plus `/mcp` when set, else
    /// loopback.
    // Keep this optional for the same explicit-URL precedence as hook install.
    #[arg(long)]
    pub server_url: Option<String>,
    /// Friendly name the client should show for this server entry.
    #[arg(long, default_value = "ai-memory")]
    pub name: String,
    /// Bearer token to embed in the client config. When set, the
    /// rendered snippet includes an `Authorization: Bearer <token>`
    /// header so the client can authenticate against a server that
    /// requires it. When omitted, uses the token resolved by the config loader.
    #[arg(long, hide_env_values = true)]
    pub auth_token: Option<String>,
    /// **Mutate** the client's config file in place instead of just
    /// printing the snippet. Idempotent: replaces any existing entry
    /// named `<name>` (default `ai-memory`); preserves every other
    /// MCP server the user has configured. A timestamped backup is
    /// written next to the original before each modifying write.
    #[arg(long)]
    pub apply: bool,
    /// Override the config-file path. Auto-detected per client when
    /// absent (e.g. `~/.claude.json` for Claude Code).
    #[arg(long)]
    pub config_file: Option<PathBuf>,
    /// For Claude Code, register an ai-memory stdio bridge that forwards the
    /// current lifecycle session id to the HTTP server. This enables
    /// `[auto_scope] mode = "per_session"` for concurrent Claude Code sessions.
    #[arg(long)]
    pub session_aware: bool,
    /// Pin the tool-schema dialect in the installed MCP URL, for a client
    /// whose upstream 400s on the schemas ai-memory advertises by default.
    /// Needed when the client fronts several models and its name alone does
    /// not say which — a Command Code or OpenCode install routed to Vertex
    /// wants `gemini`. Kimi Code and Kiro already get theirs; this overrides.
    #[arg(long, value_enum)]
    pub flavor: Option<SchemaFlavor>,
    /// Reference the token by the `AI_MEMORY_AUTH_TOKEN` variable name
    /// instead of embedding it (Codex `bearer_token_env_var`, Prime Agent
    /// `bearerTokenEnvVar`). Set by the installer, never a flag: it is how an
    /// install whose token lives in `[auth].bearer_token_file` keeps the token
    /// out of the harness config.
    #[arg(skip)]
    pub token_env_var: bool,
    /// Write a stdio entry that runs the session-less `ai-memory mcp-bridge`
    /// instead of an HTTP entry. Set by the installer, never a flag: it is how
    /// a client without env-var indirection reaches a server whose token lives
    /// in `[auth].bearer_token_file`.
    #[arg(skip)]
    pub stdio_bridge: bool,
    /// The data dir a bridge entry passes as `--data-dir`: always for a client
    /// that starts its MCP servers with a cleared environment (Muse Code), and
    /// for any other bridge entry when the install was given a data dir, so
    /// the bridge reads the same config and token as the install's hooks.
    /// Set by the installer, never a flag.
    #[arg(skip)]
    pub bridge_data_dir: Option<std::path::PathBuf>,
}

/// Arguments for the internal stdio-to-HTTP MCP bridge.
#[derive(Debug, Clone, Args)]
pub struct McpBridgeArgs {
    /// Remote ai-memory base URL or full `/mcp` endpoint.
    #[arg(long)]
    pub server_url: Option<String>,
    /// Run as a plain stdio-to-HTTP bridge that forwards no session identity,
    /// for MCP clients other than Claude Code and Muse Code. Without it the
    /// bridge forwards the session id of the `--agent` that launched it and
    /// refuses to start when it is missing.
    #[arg(long)]
    pub no_session_id: bool,
    /// The harness that launches this session-aware bridge, which names the
    /// one variable its session id is read from: `claude-code` (the default)
    /// reads `CLAUDE_CODE_SESSION_ID`, `muse` reads `MUSE_SESSION_ID`. The
    /// other variable is never consulted, so an id inherited from a
    /// different harness's terminal is not forwarded.
    #[arg(long, value_enum, default_value_t = BridgeAgent::ClaudeCode)]
    pub agent: BridgeAgent,
}

/// The harness a session-aware `mcp-bridge` forwards the session id of.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, clap::ValueEnum)]
pub enum BridgeAgent {
    /// Claude Code: `CLAUDE_CODE_SESSION_ID`.
    #[default]
    ClaudeCode,
    /// Meta Muse Code: `MUSE_SESSION_ID`.
    #[value(alias = "muse-code", alias = "musecode")]
    Muse,
}

impl BridgeAgent {
    /// The variable this harness puts its session id in.
    #[must_use]
    pub const fn session_env(self) -> &'static str {
        match self {
            Self::ClaudeCode => "CLAUDE_CODE_SESSION_ID",
            Self::Muse => "MUSE_SESSION_ID",
        }
    }
}

/// Transport for the MCP server.
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum TransportKind {
    /// Stdio — what `claude mcp add` uses.
    Stdio,
    /// Streamable HTTP — for HTTP clients and `mcp-inspector`.
    Http,
}

/// Arguments for `serve`.
#[derive(Debug, Args)]
pub struct ServeArgs {
    /// Serve the `/management/v1` session inspection and owned-purge routes to
    /// signed-in browser users. Off by default; requires `--transport http`.
    #[arg(long, env = "AI_MEMORY_ENABLE_SESSION_MANAGEMENT")]
    pub enable_session_management: bool,

    /// Let signed-in browser users issue and revoke their own `aim_` API keys
    /// under `/management/v1/credentials`. Off by default; requires
    /// `--transport http`.
    #[arg(long, env = "AI_MEMORY_ENABLE_SELF_SERVICE_KEYS")]
    pub enable_self_service_keys: bool,

    /// Transport to expose the MCP server on.
    #[arg(long, value_enum, default_value_t = TransportKind::Stdio)]
    pub transport: TransportKind,
    /// Bind address for `--transport http` (default: from config).
    #[arg(long)]
    pub bind: Option<String>,
    /// DANGEROUS: allow unauthenticated plain HTTP on a non-loopback bind.
    ///
    /// HTTP-only. Unnecessary for loopback binds; prefer AI_MEMORY_AUTH_TOKEN
    /// or a loopback bind instead.
    #[arg(long)]
    pub allow_insecure_no_auth: bool,
    /// DANGEROUS: allow human login over plain HTTP on a non-loopback bind.
    ///
    /// HTTP-only. Passwords, session cookies, API credentials, and memory data
    /// can be read or modified by anyone able to intercept the connection.
    #[arg(long, env = "AI_MEMORY_ALLOW_INSECURE_HUMAN_AUTH")]
    pub allow_insecure_human_auth: bool,
    /// Skip the filesystem watcher; useful for transient debugging.
    #[arg(long)]
    pub no_watcher: bool,
    /// DANGEROUS: start even when another process holds the single-instance
    /// serve lock.
    ///
    /// Only for an operator who is certain the previous server is gone (a
    /// hung holder, or a mount with unreliable locking): two live servers on
    /// one data directory corrupt wiki and index state.
    #[arg(long)]
    pub force: bool,
    /// Workspace name (auto-created).
    ///
    /// Not marker-aware, unlike the client commands: the server has no
    /// caller cwd to walk up from, and this is the baked fallback for hook
    /// events that arrive without a usable one.
    #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
    pub workspace: String,
    /// Project name within the workspace (auto-created).
    #[arg(long, default_value_t = crate::config::DEFAULT_PROJECT.to_string())]
    pub project: String,
    /// Mount the web surface at `/web`. Off by default. A custom SPA shell
    /// is public so it can render password login; `/api/v1` and the built-in
    /// server-rendered wiki remain protected by a web session or machine
    /// Bearer.
    #[arg(long, env = "AI_MEMORY_ENABLE_WEB")]
    pub enable_web: bool,
    /// Enable the server-rendered management console at /manage (requires management-ui build feature).
    #[cfg(feature = "management-ui")]
    #[arg(long, env = "AI_MEMORY_ENABLE_MANAGEMENT_UI")]
    pub enable_management_ui: bool,
    /// Mount only the read-only `/api/v1` JSON API. Off by default.
    ///
    /// `--enable-web` implies this API as before. Use this flag for
    /// non-browser companions that must not expose the web UI.
    #[arg(long, env = "AI_MEMORY_ENABLE_API")]
    pub enable_api: bool,
    /// Serve this static directory at /web instead of the built-in UI.
    ///
    /// The read-only /api/v1 frontend API is still mounted when
    /// --enable-web is set.
    #[arg(long, env = "AI_MEMORY_WEB_UI_DIR")]
    pub web_ui_dir: Option<PathBuf>,
    /// Base path the whole HTTP surface is served under (default: from config).
    /// Empty (the configuration default) keeps every route at the host root.
    /// Set e.g. `/wiki` to host ai-memory under a URL subpath
    /// behind a reverse proxy that preserves the prefix; then `/mcp`,
    /// `/api/v1`, `/hook` and the web UI all live under it (`/wiki/mcp`,
    /// `/wiki/api/v1`, …). The value is normalised to `/<core>` (leading
    /// slash, no trailing); `/` and `` both mean root.
    #[arg(long, env = "AI_MEMORY_BASE_PATH")]
    pub base_path: Option<String>,
    /// Slug the web UI is mounted at, WITHIN `--base-path`. Default `/web`
    /// (the read-only `/api/v1` API always stays at `<base>/api/v1`). Set
    /// `/` to serve the UI at the base root itself (e.g. `/wiki` instead of
    /// `/wiki/web`). The server injects a normalised `<base href>` into the
    /// served HTML so the built-in UI and a custom `--web-ui-dir` SPA both
    /// resolve their assets under the prefix without a rebuild.
    #[arg(long, env = "AI_MEMORY_WEB_SLUG", default_value = "/web")]
    pub web_slug: String,
    /// Run the HTTP transport in stateful (session) mode: the server
    /// issues an `Mcp-Session-Id` on `initialize` and requires it on
    /// every later request, with SSE-framed responses. Off by default —
    /// the HTTP transport is stateless and returns plain JSON, so
    /// stateless clients (OpenCode `type: "remote"`, `curl`) work without
    /// an `mcp-remote` stdio shim (issue #3). Enable this only for
    /// clients that need session continuity or server-initiated SSE
    /// streams. No effect on `--transport stdio`.
    #[arg(long)]
    pub http_stateful: bool,
    /// Origin allowed to call /api/v1 cross-origin (CORS). Repeat the flag
    /// for multiple origins, or set AI_MEMORY_CORS_ALLOW_ORIGINS to a
    /// comma-separated list. Must be a fully-qualified origin
    /// (e.g. https://app.example.com); `*` is rejected (CORS spec forbids
    /// credentials + wildcard). Empty = same-origin only.
    #[arg(long = "cors-allow-origin")]
    pub cors_allow_origin: Vec<String>,
}

/// Arguments for `write-page`.
#[derive(Debug, Args)]
pub struct WritePageArgs {
    /// Relative wiki path (e.g. `notes/foo.md`).
    #[arg(long, visible_alias = "p")]
    pub path: String,
    /// Markdown body. Use `-` to read from stdin.
    #[arg(long, visible_alias = "b")]
    pub body: String,
    /// Optional page title; otherwise derived from the first `# heading`
    /// in the body, or the path stem.
    #[arg(long)]
    pub title: Option<String>,
    /// Semantic kind: fact | rule | decision | gotcha (stored in frontmatter)
    #[arg(long)]
    pub kind: Option<String>,
    /// Repeatable tag to add to the frontmatter `tags` array.
    #[arg(long, short = 't')]
    pub tag: Vec<String>,
    /// Tier (`working`, `episodic`, `semantic`, `procedural`).
    #[arg(long, default_value = "semantic")]
    pub tier: String,
    /// Pin the page so the future decay sweep skips it.
    #[arg(long)]
    pub pinned: bool,
    /// Profile entries only (`profile/...` paths): repeatable stack tag
    /// (`rust`, `typescript`, ...) limiting the entry to projects on that
    /// stack.
    #[arg(long = "applies-to")]
    pub applies_to: Vec<String>,
    /// Profile entries only: what already enforces the entry (e.g.
    /// `pre-push hook`), which keeps it out of the session-start digest.
    #[arg(long = "enforced-by")]
    pub enforced_by: Option<String>,
    /// Workspace name (auto-created if absent).
    #[arg(long)]
    pub workspace: Option<String>,
    /// Project name within the workspace. When omitted, auto-detect from the
    /// current project using the same resolver as read-page/search.
    #[arg(long)]
    pub project: Option<String>,
}

#[cfg(test)]
mod tests {
    /// `--env-file` lines are trimmed as a whole, not per half, so the common
    /// dotenv spelling `KEY = value` used to produce a key with a trailing
    /// space — an entry no shell and no harness can read, so the override
    /// silently did nothing.
    #[test]
    fn env_entries_with_a_whitespace_key_are_refused() {
        for raw in [
            "CLAUDE_CONFIG_DIR = /accounts/work",
            "CLAUDE_CONFIG_DIR =/accounts/work",
            " CLAUDE_CONFIG_DIR=/accounts/work",
            "TWO WORDS=value",
        ] {
            let err = super::parse_env_kv(raw).expect_err(raw);
            assert!(
                err.contains("KEY must not contain whitespace"),
                "{raw}: {err}"
            );
        }
    }

    /// The controls: a well-formed entry still parses, the value stays
    /// literal (inner and trailing spaces preserved), and an empty key keeps
    /// its own distinct error.
    #[test]
    fn env_entries_keep_their_value_literal() {
        assert_eq!(
            super::parse_env_kv("KEY=VALUE").unwrap(),
            ("KEY".to_string(), "VALUE".to_string())
        );
        assert_eq!(
            super::parse_env_kv("KEY= two words ").unwrap(),
            ("KEY".to_string(), " two words ".to_string())
        );
        assert_eq!(
            super::parse_env_kv("KEY=").unwrap(),
            ("KEY".to_string(), String::new())
        );
        let err = super::parse_env_kv("=VALUE").expect_err("empty key");
        assert!(err.contains("KEY must not be empty"), "{err}");
        let err = super::parse_env_kv("NOVALUE").expect_err("no separator");
        assert!(err.contains("expected KEY=VALUE"), "{err}");
    }

    #[test]
    fn session_management_is_runtime_opt_in() {
        let parsed = Cli::try_parse_from(["ai-memory", "serve"]).unwrap();
        let Command::Serve(args) = parsed.command else {
            panic!("serve")
        };
        assert!(!args.enable_session_management);
        let parsed = Cli::try_parse_from([
            "ai-memory",
            "serve",
            "--transport",
            "http",
            "--enable-session-management",
        ])
        .unwrap();
        let Command::Serve(args) = parsed.command else {
            panic!("serve")
        };
        assert!(args.enable_session_management);
    }
    #[test]
    fn self_service_keys_is_runtime_opt_in() {
        let parsed = Cli::try_parse_from(["ai-memory", "serve"]).unwrap();
        let Command::Serve(args) = parsed.command else {
            panic!("serve")
        };
        assert!(!args.enable_self_service_keys);
        let parsed = Cli::try_parse_from([
            "ai-memory",
            "serve",
            "--transport",
            "http",
            "--enable-self-service-keys",
        ])
        .unwrap();
        let Command::Serve(args) = parsed.command else {
            panic!("serve")
        };
        assert!(args.enable_self_service_keys);
    }
    use super::*;
    use clap::{CommandFactory, Parser};
    use std::collections::BTreeSet;

    #[test]
    fn write_page_takes_the_profile_entry_fields() {
        let parsed = Cli::try_parse_from([
            "ai-memory",
            "write-page",
            "--path",
            "profile/style/types.md",
            "--body",
            "Never cast.",
            "--applies-to",
            "rust",
            "--applies-to",
            "typescript",
            "--enforced-by",
            "pre-push hook",
        ])
        .expect("write-page profile args parse");
        let Command::WritePage(args) = parsed.command else {
            panic!("expected write-page command");
        };
        assert_eq!(args.applies_to, ["rust", "typescript"]);
        assert_eq!(args.enforced_by.as_deref(), Some("pre-push hook"));
    }

    /// `search --global` drops the scope entirely, so naming one alongside it
    /// is a contradiction clap rejects rather than one flag silently winning.
    #[test]
    fn search_global_parses_and_conflicts_with_an_explicit_scope() {
        let parsed = Cli::try_parse_from(["ai-memory", "search", "wal", "--global"])
            .expect("search --global parses");
        let Command::Search(args) = parsed.command else {
            panic!("expected search command");
        };
        assert!(args.global);
        assert!(args.workspace.is_none() && args.project.is_none());

        let default = Cli::try_parse_from(["ai-memory", "search", "wal"]).expect("search parses");
        let Command::Search(args) = default.command else {
            panic!("expected search command");
        };
        assert!(!args.global, "global search stays opt-in");

        for flag in [["--workspace", "acme"], ["--project", "api"]] {
            let error =
                Cli::try_parse_from(["ai-memory", "search", "wal", "--global", flag[0], flag[1]])
                    .expect_err("--global must conflict with an explicit scope");
            assert_eq!(
                error.kind(),
                clap::error::ErrorKind::ArgumentConflict,
                "{flag:?}"
            );
        }
    }

    /// `recent --global` drops the scope entirely, so naming one alongside it
    /// is a contradiction clap rejects rather than one flag silently winning.
    #[test]
    fn recent_global_parses_and_conflicts_with_an_explicit_scope() {
        let parsed = Cli::try_parse_from(["ai-memory", "recent", "--global", "-n", "20"])
            .expect("recent --global parses");
        let Command::Recent(args) = parsed.command else {
            panic!("expected recent command");
        };
        assert!(args.global);
        assert_eq!(args.limit, 20);
        assert!(args.workspace.is_none() && args.project.is_none());

        let default = Cli::try_parse_from(["ai-memory", "recent"]).expect("recent parses");
        let Command::Recent(args) = default.command else {
            panic!("expected recent command");
        };
        assert!(!args.global, "global recent stays opt-in");
        assert_eq!(args.limit, 10);

        for flag in [["--workspace", "acme"], ["--project", "api"]] {
            let error = Cli::try_parse_from(["ai-memory", "recent", "--global", flag[0], flag[1]])
                .expect_err("--global must conflict with an explicit scope");
            assert_eq!(
                error.kind(),
                clap::error::ErrorKind::ArgumentConflict,
                "{flag:?}"
            );
        }
    }

    #[test]
    fn serve_api_only_flag_does_not_enable_the_web_ui() {
        let parsed =
            Cli::try_parse_from(["ai-memory", "serve", "--transport", "http", "--enable-api"])
                .expect("api-only serve args parse");
        let Command::Serve(args) = parsed.command else {
            panic!("expected serve command");
        };
        assert!(args.enable_api);
        assert!(!args.enable_web);
    }

    #[cfg(feature = "management-ui")]
    #[test]
    fn management_ui_requires_explicit_runtime_opt_in() {
        let parsed = Cli::try_parse_from(["ai-memory", "serve"]).unwrap();
        let Command::Serve(args) = parsed.command else {
            panic!("serve")
        };
        assert!(!args.enable_management_ui);
        let parsed = Cli::try_parse_from([
            "ai-memory",
            "serve",
            "--transport",
            "http",
            "--enable-management-ui",
        ])
        .unwrap();
        let Command::Serve(args) = parsed.command else {
            panic!("serve")
        };
        assert!(args.enable_management_ui);
        assert!(!args.enable_web);
    }

    #[cfg(not(feature = "management-ui"))]
    #[test]
    fn management_ui_flag_is_absent_from_default_builds() {
        assert!(Cli::try_parse_from(["ai-memory", "serve", "--enable-management-ui"]).is_err());
    }

    /// The management surface uses the design's spelling (#708):
    /// `user grant --user … --workspace … --project … --level …`, `user revoke`,
    /// and listings under `user grants` / `project grants`. A level is never
    /// defaulted, and the former top-level `grant` command is gone.
    #[test]
    fn grant_commands_use_the_designs_spelling() {
        let parsed = Cli::try_parse_from([
            "ai-memory",
            "user",
            "grant",
            "--user",
            "alice",
            "--workspace",
            "acme",
            "--project",
            "api",
            "--level",
            "write",
        ])
        .expect("user grant parses");
        let Command::User(UserArgs {
            command: UserCommand::Grant(args),
        }) = parsed.command
        else {
            panic!("expected user grant");
        };
        assert_eq!(
            (
                args.user.as_str(),
                args.workspace.as_str(),
                args.project.as_str(),
                args.level.as_str()
            ),
            ("alice", "acme", "api", "write")
        );
        assert!(
            Cli::try_parse_from([
                "ai-memory",
                "user",
                "grant",
                "--user",
                "alice",
                "--project",
                "api"
            ])
            .is_err(),
            "a level left unsaid is not guessed at"
        );
        for argv in [
            &[
                "ai-memory",
                "user",
                "revoke",
                "--user",
                "alice",
                "--project",
                "api",
            ][..],
            &["ai-memory", "user", "grants"][..],
            &["ai-memory", "user", "grants", "--user", "alice"][..],
            &["ai-memory", "project", "grants", "--project", "api"][..],
        ] {
            Cli::try_parse_from(argv).unwrap_or_else(|e| panic!("{argv:?}: {e}"));
        }
        assert!(Cli::try_parse_from(["ai-memory", "grant", "list"]).is_err());
    }

    #[test]
    fn project_init_parses_without_server_scope_flags() {
        let parsed =
            Cli::try_parse_from(["ai-memory", "project", "init"]).expect("project init parses");
        let Command::Project(args) = parsed.command else {
            panic!("expected project command");
        };
        assert!(matches!(args.command, ProjectCommand::Init(_)));
    }

    #[test]
    fn serve_parses_insecure_transport_overrides() {
        let parsed = Cli::try_parse_from([
            "ai-memory",
            "serve",
            "--transport",
            "http",
            "--allow-insecure-no-auth",
            "--allow-insecure-human-auth",
        ])
        .expect("serve override parses");
        let Command::Serve(args) = parsed.command else {
            panic!("expected serve command");
        };
        assert!(args.allow_insecure_no_auth);
        assert!(args.allow_insecure_human_auth);

        let command = Cli::command();
        let serve = command
            .get_subcommands()
            .find(|subcommand| subcommand.get_name() == "serve")
            .expect("serve subcommand exists");
        let human_override = serve
            .get_arguments()
            .find(|argument| argument.get_id() == "allow_insecure_human_auth")
            .expect("human-auth override exists");
        assert_eq!(
            human_override.get_env(),
            Some(std::ffi::OsStr::new("AI_MEMORY_ALLOW_INSECURE_HUMAN_AUTH"))
        );
    }

    #[test]
    fn finalize_session_parses_typed_id_and_rejects_ambiguous_selection() {
        let session_id = ai_memory_core::SessionId::new();
        let parsed = Cli::try_parse_from([
            "ai-memory",
            "finalize-session",
            "--session-id",
            &session_id.to_string(),
        ])
        .expect("valid session id parses");
        let Command::FinalizeSession(args) = parsed.command else {
            panic!("expected finalize-session command");
        };
        assert_eq!(args.session_id, Some(session_id));

        assert!(
            Cli::try_parse_from([
                "ai-memory",
                "finalize-session",
                "--session-id",
                "not-a-uuid",
            ])
            .is_err(),
            "malformed session ids must fail at the CLI boundary"
        );
        assert!(
            Cli::try_parse_from([
                "ai-memory",
                "finalize-session",
                "--all",
                "--session-id",
                &session_id.to_string(),
            ])
            .is_err(),
            "--all and --session-id must be mutually exclusive"
        );
    }

    #[test]
    fn finalize_session_accepts_hermes_and_every_captured_agent() {
        // #623: hermes is accepted for capture/storage but the install-oriented
        // AgentChoice enum lacked it, so finalize-session refused it and hermes
        // sessions could never be closed. finalize is agent-agnostic; it must
        // accept every AgentKind the store recognises.
        let parsed = Cli::try_parse_from(["ai-memory", "finalize-session", "--agent", "hermes"])
            .expect("hermes must be a valid finalize agent");
        let Command::FinalizeSession(args) = parsed.command else {
            panic!("expected finalize-session command");
        };
        assert_eq!(args.agent, ai_memory_core::AgentKind::Hermes);

        // Drift guard: every AgentKind must be finalizable, so the CLI accept
        // set can never again fall behind the store's CHECK set (the exact
        // drift that caused #623). `other` is included via its explicit spelling.
        for kind in ai_memory_core::AgentKind::ALL {
            let parsed =
                Cli::try_parse_from(["ai-memory", "finalize-session", "--agent", kind.as_str()])
                    .unwrap_or_else(|e| panic!("agent {} must finalize: {e}", kind.as_str()));
            let Command::FinalizeSession(args) = parsed.command else {
                panic!("expected finalize-session command");
            };
            assert_eq!(args.agent, kind, "wire round-trip for {}", kind.as_str());
        }

        // A genuine typo is rejected rather than silently mapped to Other.
        assert!(
            Cli::try_parse_from(["ai-memory", "finalize-session", "--agent", "hermez"]).is_err(),
            "an unknown agent must be rejected, not silently accepted as Other"
        );
    }

    #[test]
    fn architecture_lists_every_visible_cli_subcommand() {
        let architecture = include_str!("../../../docs/ARCHITECTURE.md");
        let cli_section = architecture
            .split_once("## CLI subcommand surface")
            .expect("architecture must have a CLI subcommand section")
            .1;
        let command_block = cli_section
            .split_once("```")
            .expect("CLI subcommand section must have a fenced block")
            .1
            .split_once("```")
            .expect("CLI subcommand fence must be closed")
            .0;
        let documented = command_block.split_whitespace().collect::<BTreeSet<_>>();
        let command = Cli::command();
        let visible = command
            .get_subcommands()
            .filter(|subcommand| !subcommand.is_hide_set())
            .map(|subcommand| subcommand.get_name())
            .collect::<BTreeSet<_>>();

        assert_eq!(
            documented, visible,
            "docs/ARCHITECTURE.md CLI subcommands must match `ai-memory --help`"
        );
    }

    /// `continue` always delegates to `run`'s bare mode, which refuses native
    /// argv and `--executable`. Rejecting them at parse time keeps that
    /// contract visible in `--help` instead of failing after the launch has
    /// already started resolving a workstream.
    #[test]
    fn continue_takes_wrapper_flags_only() {
        let parsed =
            Cli::try_parse_from(["ai-memory", "continue", "--workspace", "work", "--yolo"])
                .expect("continue parses wrapper flags");
        let Command::Continue(args) = parsed.command else {
            panic!("expected continue command");
        };
        assert_eq!(args.workspace.as_deref(), Some("work"));
        assert!(args.yolo);
        assert!(!args.fresh);

        for rejected in [
            vec!["ai-memory", "continue", "claude"],
            vec!["ai-memory", "continue", "--model", "opus"],
            vec!["ai-memory", "continue", "--executable", "/bin/claude"],
        ] {
            assert!(
                Cli::try_parse_from(&rejected).is_err(),
                "{rejected:?} must not parse"
            );
        }
    }

    /// `resume` is an interactive selector, so it keeps the same narrow
    /// wrapper-only command-line surface as `continue`; its picker selects the
    /// native harness without accepting harness-native arguments.
    #[test]
    fn resume_takes_picker_and_wrapper_flags_only() {
        let Command::Resume(defaults) = Cli::try_parse_from(["ai-memory", "resume"])
            .unwrap()
            .command
        else {
            panic!("expected resume");
        };
        assert!(defaults.limit.is_none());
        assert!(defaults.search.is_none());
        assert!(!defaults.all);
        let Command::Resume(wide) = Cli::try_parse_from(["ai-memory", "resume", "--limit", "500"])
            .unwrap()
            .command
        else {
            panic!("expected resume");
        };
        assert_eq!(wide.limit, Some(500));
        let parsed = Cli::try_parse_from([
            "ai-memory",
            "resume",
            "--workspace",
            "work",
            "--limit",
            "50",
            "--search",
            "refactor",
            "--all",
            "--yolo",
        ])
        .expect("resume parses picker flags");
        let Command::Resume(args) = parsed.command else {
            panic!("expected resume command");
        };
        assert_eq!(args.workspace.as_deref(), Some("work"));
        assert_eq!(args.limit, Some(50));
        assert_eq!(args.search.as_deref(), Some("refactor"));
        assert!(args.all);
        assert!(args.yolo);
        assert!(!args.fresh);

        for rejected in [
            vec!["ai-memory", "resume", "claude"],
            vec!["ai-memory", "resume", "--model", "opus"],
            vec!["ai-memory", "resume", "--executable", "/bin/claude"],
            vec!["ai-memory", "resume", "--limit", "0"],
        ] {
            assert!(
                Cli::try_parse_from(&rejected).is_err(),
                "{rejected:?} must not parse"
            );
        }
    }

    #[test]
    fn show_parses_listing_and_launch_flags_without_consuming_native_args() {
        let listing = Cli::try_parse_from(["ai-memory", "show", "--json", "--no-scan"])
            .expect("show listing parses");
        let Command::Show(listing) = listing.command else {
            panic!("expected show command");
        };
        assert!(listing.json);
        assert!(listing.no_scan);

        let launch = Cli::try_parse_from([
            "ai-memory",
            "show",
            "--workspace",
            "team",
            "--yolo",
            "--fresh",
            "--model",
            "fast",
        ])
        .expect("show launch parses");
        let Command::Show(launch) = launch.command else {
            panic!("expected show command");
        };
        assert_eq!(launch.workspace.as_deref(), Some("team"));
        assert!(launch.yolo);
        assert!(launch.fresh);
        assert_eq!(launch.native_args, ["--model", "fast"]);
    }

    #[test]
    fn claude_session_aware_mcp_flag_parses() {
        let cli = Cli::try_parse_from([
            "ai-memory",
            "install-mcp",
            "--client",
            "claude-code",
            "--session-aware",
            "--apply",
        ])
        .unwrap();

        let Command::InstallMcp(args) = cli.command else {
            panic!("expected install-mcp command");
        };
        assert!(args.session_aware);
        assert!(args.apply);
        assert!(matches!(args.client, McpClient::ClaudeCode));
    }

    #[test]
    fn pi_and_omp_mcp_clients_parse_to_distinct_variants() {
        for (alias, expected_pi) in [("pi", true), ("omp", false), ("oh-my-pi", false)] {
            let cli = Cli::try_parse_from([
                "ai-memory",
                "install-mcp",
                "--client",
                alias,
                "--server-url",
                "http://example.test:49374/mcp",
            ])
            .unwrap_or_else(|e| panic!("failed to parse install-mcp alias {alias}: {e}"));

            let Command::InstallMcp(args) = cli.command else {
                panic!("expected install-mcp command for alias {alias}");
            };
            assert!(
                matches!(args.client, McpClient::Pi) == expected_pi,
                "alias {alias} resolved to unexpected MCP client: {:?}",
                args.client
            );
        }
    }

    #[test]
    fn write_page_project_is_optional_for_shared_resolution() {
        let cli = Cli::try_parse_from([
            "ai-memory",
            "write-page",
            "--path",
            "notes/x.md",
            "--body",
            "hello",
        ])
        .expect("write-page parses without --project");

        let Command::WritePage(args) = cli.command else {
            panic!("expected write-page command");
        };
        assert_eq!(args.project, None);

        let cli = Cli::try_parse_from([
            "ai-memory",
            "write-page",
            "--path",
            "notes/x.md",
            "--body",
            "hello",
            "--project",
            "explicit",
        ])
        .expect("write-page parses with --project");

        let Command::WritePage(args) = cli.command else {
            panic!("expected write-page command");
        };
        assert_eq!(args.project.as_deref(), Some("explicit"));
    }

    #[test]
    fn auto_improve_parses_required_session() {
        let cli = Cli::try_parse_from([
            "ai-memory",
            "auto-improve",
            "--session-id",
            "00000000-0000-0000-0000-000000000000",
            "--project",
            "scratch",
            "--max-proposals",
            "2",
        ])
        .expect("auto-improve parses");

        let Command::AutoImprove(args) = cli.command else {
            panic!("expected auto-improve command");
        };
        assert_eq!(args.session_id, "00000000-0000-0000-0000-000000000000");
        assert_eq!(args.max_proposals, Some(2));
        assert_eq!(args.project.as_deref(), Some("scratch"));
    }

    #[test]
    fn curator_parses_default_dry_run_and_mode_flags() {
        let cli = Cli::try_parse_from(["ai-memory", "curator", "--project", "scratch"])
            .expect("curator parses without mode flags");
        let Command::Curator(args) = cli.command else {
            panic!("expected curator command");
        };
        assert!(!args.dry_run);
        assert!(!args.stage);
        assert_eq!(args.project.as_deref(), Some("scratch"));

        let cli = Cli::try_parse_from([
            "ai-memory",
            "curator",
            "--dry-run",
            "--workspace",
            "default",
        ])
        .expect("curator dry-run parses");
        let Command::Curator(args) = cli.command else {
            panic!("expected curator command");
        };
        assert!(args.dry_run);
        assert!(!args.stage);

        let cli =
            Cli::try_parse_from(["ai-memory", "curator", "--stage"]).expect("curator stage parses");
        let Command::Curator(args) = cli.command else {
            panic!("expected curator command");
        };
        assert!(args.stage);
        assert!(!args.dry_run);
    }

    #[test]
    fn auto_improve_report_parses_scope_window_limit_and_json() {
        let cli = Cli::try_parse_from([
            "ai-memory",
            "auto-improve-report",
            "--project",
            "scratch",
            "--days",
            "14",
            "--limit",
            "3",
            "--stage",
            "--json",
        ])
        .expect("auto-improve-report parses");

        let Command::AutoImproveReport(args) = cli.command else {
            panic!("expected auto-improve-report command");
        };
        assert_eq!(args.project.as_deref(), Some("scratch"));
        assert_eq!(args.days, 14);
        assert_eq!(args.limit, 3);
        assert!(args.stage);
        assert!(args.json);
    }

    #[test]
    fn pending_writes_subcommands_parse() {
        let id = "00000000-0000-0000-0000-000000000000";
        let list = Cli::try_parse_from([
            "ai-memory",
            "pending-writes",
            "list",
            "--project",
            "scratch",
            "--status",
            "pending",
            "--limit",
            "5",
        ])
        .expect("pending-writes list parses");
        let Command::PendingWrites(args) = list.command else {
            panic!("expected pending-writes command");
        };
        let PendingWritesCommand::List(args) = args.command else {
            panic!("expected list subcommand");
        };
        assert_eq!(args.project.as_deref(), Some("scratch"));
        assert_eq!(args.status.as_deref(), Some("pending"));
        assert_eq!(args.limit, 5);

        for subcommand in ["show", "diff", "approve"] {
            let cli = Cli::try_parse_from([
                "ai-memory",
                "pending-writes",
                subcommand,
                id,
                "--project",
                "scratch",
            ])
            .unwrap_or_else(|e| panic!("pending-writes {subcommand} parses: {e}"));
            let Command::PendingWrites(args) = cli.command else {
                panic!("expected pending-writes command");
            };
            match args.command {
                PendingWritesCommand::Show(args)
                | PendingWritesCommand::Diff(args)
                | PendingWritesCommand::Approve(args) => {
                    assert_eq!(args.id, id);
                    assert_eq!(args.project.as_deref(), Some("scratch"));
                }
                PendingWritesCommand::List(_) | PendingWritesCommand::Reject(_) => {
                    panic!("wrong subcommand parsed")
                }
            }
        }

        let reject = Cli::try_parse_from([
            "ai-memory",
            "pending-writes",
            "reject",
            id,
            "--project",
            "scratch",
            "--reason",
            "not now",
        ])
        .expect("pending-writes reject parses");
        let Command::PendingWrites(args) = reject.command else {
            panic!("expected pending-writes command");
        };
        let PendingWritesCommand::Reject(args) = args.command else {
            panic!("expected reject subcommand");
        };
        assert_eq!(args.id, id);
        assert_eq!(args.reason, "not now");
    }

    #[test]
    fn pi_and_omp_hook_agents_parse_to_distinct_variants() {
        for (alias, expected_pi) in [("pi", true), ("omp", false), ("oh-my-pi", false)] {
            let cli = Cli::try_parse_from([
                "ai-memory",
                "install-hooks",
                "--agent",
                alias,
                "--server-url",
                "http://example.test:49374",
            ])
            .unwrap_or_else(|e| panic!("failed to parse install-hooks alias {alias}: {e}"));

            let Command::InstallHooks(args) = cli.command else {
                panic!("expected install-hooks command for alias {alias}");
            };
            assert!(
                matches!(args.agent, AgentChoice::Pi) == expected_pi,
                "alias {alias} resolved to unexpected hook agent: {:?}",
                args.agent
            );
        }
    }

    #[test]
    fn install_hooks_scope_defaults_to_global_and_conflicts_with_config_file() {
        let cli =
            Cli::try_parse_from(["ai-memory", "install-hooks", "--agent", "claude-code"]).unwrap();
        let Command::InstallHooks(args) = cli.command else {
            panic!("expected install-hooks command");
        };
        assert_eq!(args.scope, HookInstallScope::Global);

        let cli = Cli::try_parse_from([
            "ai-memory",
            "install-hooks",
            "--agent",
            "claude-code",
            "--scope",
            "project",
        ])
        .unwrap();
        let Command::InstallHooks(args) = cli.command else {
            panic!("expected install-hooks command");
        };
        assert_eq!(args.scope, HookInstallScope::Project);

        // Both name the target file; accepting them together would silently
        // pick one.
        let err = Cli::try_parse_from([
            "ai-memory",
            "install-hooks",
            "--agent",
            "claude-code",
            "--scope",
            "project",
            "--config-file",
            "settings.json",
        ])
        .unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
    }

    #[test]
    fn antigravity_aliases_parse_to_same_variant() {
        for alias in ["antigravity-cli", "antigravity", "agy"] {
            let mcp_cli = Cli::try_parse_from([
                "ai-memory",
                "install-mcp",
                "--client",
                alias,
                "--server-url",
                "http://example.test:49374/mcp",
            ])
            .unwrap_or_else(|e| panic!("failed to parse install-mcp alias {alias}: {e}"));
            let Command::InstallMcp(mcp_args) = mcp_cli.command else {
                panic!("expected install-mcp command for alias {alias}");
            };
            assert!(matches!(mcp_args.client, McpClient::AntigravityCli));

            let hook_cli = Cli::try_parse_from([
                "ai-memory",
                "install-hooks",
                "--agent",
                alias,
                "--server-url",
                "http://example.test:49374",
            ])
            .unwrap_or_else(|e| panic!("failed to parse install-hooks alias {alias}: {e}"));
            let Command::InstallHooks(hook_args) = hook_cli.command else {
                panic!("expected install-hooks command for alias {alias}");
            };
            assert!(matches!(hook_args.agent, AgentChoice::AntigravityCli));

            let skills_cli = Cli::try_parse_from(["ai-memory", "install-skills", "--agent", alias])
                .unwrap_or_else(|e| panic!("failed to parse install-skills alias {alias}: {e}"));
            let Command::InstallSkills(skills_args) = skills_cli.command else {
                panic!("expected install-skills command for alias {alias}");
            };
            assert_eq!(skills_args.agent, InstallSkillsAgent::Antigravity);
        }
    }

    #[test]
    fn grok_hook_agent_parses() {
        let hook_cli = Cli::try_parse_from([
            "ai-memory",
            "install-hooks",
            "--agent",
            "grok",
            "--server-url",
            "http://example.test:49374",
        ])
        .unwrap_or_else(|e| panic!("failed to parse install-hooks --agent grok: {e}"));
        let Command::InstallHooks(hook_args) = hook_cli.command else {
            panic!("expected install-hooks command for grok");
        };
        assert!(matches!(hook_args.agent, AgentChoice::Grok));
    }

    #[test]
    fn grok_mcp_client_parses() {
        let mcp_cli = Cli::try_parse_from([
            "ai-memory",
            "install-mcp",
            "--client",
            "grok",
            "--server-url",
            "http://example.test:49374",
        ])
        .unwrap_or_else(|e| panic!("failed to parse install-mcp --client grok: {e}"));
        let Command::InstallMcp(mcp_args) = mcp_cli.command else {
            panic!("expected install-mcp command for grok");
        };
        assert!(matches!(mcp_args.client, McpClient::Grok));
    }

    #[test]
    fn kiro_mcp_aliases_parse() {
        for alias in ["kiro-cli", "kiro"] {
            let cli = Cli::try_parse_from([
                "ai-memory",
                "install-mcp",
                "--client",
                alias,
                "--server-url",
                "https://memory.example/mcp",
            ])
            .unwrap_or_else(|e| panic!("failed to parse Kiro MCP alias {alias}: {e}"));
            let Command::InstallMcp(args) = cli.command else {
                panic!("expected install-mcp command for Kiro alias {alias}");
            };
            assert!(matches!(args.client, McpClient::KiroCli));
        }
    }

    #[test]
    fn setup_agent_opencode_dialect_parses_for_container_generation() {
        for (value, expected) in [
            ("v1", OpenCodeDialectChoice::V1),
            ("v2", OpenCodeDialectChoice::V2),
        ] {
            let cli = Cli::try_parse_from([
                "ai-memory",
                "setup-agent",
                "--agent",
                "opencode",
                "--opencode-dialect",
                value,
                "--to",
                "/tmp/hooks",
            ])
            .unwrap();
            let Command::SetupAgent(args) = cli.command else {
                panic!("expected setup-agent command");
            };
            assert_eq!(args.opencode_dialect, Some(expected));
        }
    }

    #[test]
    fn opencode2_aliases_parse_to_the_v2_compatibility_variants() {
        for alias in ["opencode2", "opencode-v2", "open-code2"] {
            let cli = Cli::try_parse_from([
                "ai-memory",
                "install-hooks",
                "--agent",
                alias,
                "--server-url",
                "http://127.0.0.1:49374",
            ])
            .unwrap_or_else(|error| panic!("failed to parse opencode2 alias {alias}: {error}"));
            let Command::InstallHooks(args) = cli.command else {
                panic!("expected install-hooks for opencode2 alias {alias}");
            };
            assert_eq!(args.agent, AgentChoice::OpenCode2);
            assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::OpenCode);
            assert_eq!(args.agent.script_hook_subdir(), None);

            let cli = Cli::try_parse_from([
                "ai-memory",
                "install-mcp",
                "--client",
                alias,
                "--server-url",
                "http://127.0.0.1:49374/mcp",
            ])
            .unwrap_or_else(|error| panic!("failed to parse opencode2 alias {alias}: {error}"));
            let Command::InstallMcp(args) = cli.command else {
                panic!("expected install-mcp for opencode2 alias {alias}");
            };
            assert_eq!(args.client, McpClient::OpenCode2);

            let cli = Cli::try_parse_from(["ai-memory", "run", alias])
                .unwrap_or_else(|error| panic!("failed to parse run {alias}: {error}"));
            let Command::Run(args) = cli.command else {
                panic!("expected run for opencode2 alias {alias}");
            };
            assert!(matches!(args.harness, Some(RunHarnessChoice::OpenCode2)));
        }
    }

    #[test]
    fn claude_wildcard_names_parse_to_the_claude_harness() {
        // A caller juggling several Claude accounts (Corporate, Personal, ...)
        // names each account's PATH wrapper `claude-<account>`; every such
        // spelling must resolve to the Claude harness rather than being
        // rejected as an unknown value. Case is not significant, and this
        // covers both the fixed `claude`/`claude-code` names and the
        // `claude*` wildcard fallback so there is one alias mechanism, not
        // two overlapping ones.
        for name in [
            "claude",
            "claude-code",
            "claude-corp",
            "claude-personal",
            "CLAUDE-WORK",
            "claudex",
        ] {
            let cli = Cli::try_parse_from(["ai-memory", "run", name])
                .unwrap_or_else(|error| panic!("failed to parse run {name}: {error}"));
            let Command::Run(args) = cli.command else {
                panic!("expected run for claude wildcard name {name}");
            };
            assert!(matches!(args.harness, Some(RunHarnessChoice::Claude)));
        }
    }

    #[test]
    fn claude_wrapper_spelling_is_kept_only_for_non_fixed_names() {
        let wrapper = |name: &str| {
            let cli = crate::cli::try_parse_from(["ai-memory", "run", name]).unwrap();
            let Command::Run(args) = cli.command else {
                panic!("expected run for {name}");
            };
            args.claude_wrapper
        };
        assert_eq!(wrapper("claude-glm").as_deref(), Some("claude-glm"));
        assert_eq!(wrapper("CLAUDE-WORK").as_deref(), Some("CLAUDE-WORK"));
        assert_eq!(wrapper("claudex").as_deref(), Some("claudex"));
        for fixed in [
            "claude",
            "CLAUDE",
            "Claude-Code",
            "claude-code",
            "codex",
            "kiro",
        ] {
            assert_eq!(wrapper(fixed), None, "{fixed}");
        }

        // Wrapper-owned flags before the harness, native args after it.
        let cli = crate::cli::try_parse_from([
            "ai-memory",
            "run",
            "--executable",
            "/opt/claude-x",
            "claude-glm",
            "--model",
            "opus",
        ])
        .unwrap();
        let Command::Run(args) = cli.command else {
            panic!("expected run");
        };
        assert_eq!(args.claude_wrapper.as_deref(), Some("claude-glm"));
        assert_eq!(args.native_args, ["--model", "opus"]);
    }

    #[test]
    fn non_claude_unknown_harness_is_still_rejected() {
        let error = Cli::try_parse_from(["ai-memory", "run", "banana"])
            .expect_err("unknown non-claude harness must still be rejected");
        assert!(
            error.to_string().contains("expected one of"),
            "unexpected error: {error}"
        );
    }

    #[test]
    fn run_env_flag_parses_repeatable_key_value_pairs() {
        let cli = Cli::try_parse_from([
            "ai-memory",
            "run",
            "--env",
            "CLAUDE_CONFIG_DIR=/accounts/work",
            "--env",
            "FOO=bar=baz",
            "claude",
        ])
        .expect("valid --env pairs parse");
        let Command::Run(args) = cli.command else {
            panic!("expected run command");
        };
        assert_eq!(
            args.env,
            vec![
                (
                    "CLAUDE_CONFIG_DIR".to_string(),
                    "/accounts/work".to_string()
                ),
                ("FOO".to_string(), "bar=baz".to_string()),
            ]
        );
    }

    #[test]
    fn run_env_flag_rejects_a_pair_without_equals() {
        let error = Cli::try_parse_from(["ai-memory", "run", "--env", "NOEQUALS", "claude"])
            .expect_err("a value without '=' must be rejected");
        assert!(
            error.to_string().contains("expected KEY=VALUE"),
            "unexpected error: {error}"
        );
    }

    #[test]
    fn run_env_flag_rejects_an_empty_key() {
        let error = Cli::try_parse_from(["ai-memory", "run", "--env", "=value", "claude"])
            .expect_err("an empty key must be rejected");
        assert!(
            error.to_string().contains("KEY must not be empty"),
            "unexpected error: {error}"
        );
    }

    #[test]
    fn run_env_file_flag_parses_as_a_path() {
        let cli = Cli::try_parse_from([
            "ai-memory",
            "run",
            "--env-file",
            "/tmp/ai-memory-env-example.env",
            "claude",
        ])
        .expect("--env-file parses");
        let Command::Run(args) = cli.command else {
            panic!("expected run command");
        };
        assert_eq!(
            args.env_file,
            Some(PathBuf::from("/tmp/ai-memory-env-example.env"))
        );
    }

    #[test]
    fn parse_env_kv_accepts_pairs_and_rejects_malformed_entries() {
        assert_eq!(
            parse_env_kv("KEY=VALUE"),
            Ok(("KEY".to_string(), "VALUE".to_string()))
        );
        // The value is taken literally, including any further '=' signs.
        assert_eq!(
            parse_env_kv("KEY=a=b=c"),
            Ok(("KEY".to_string(), "a=b=c".to_string()))
        );
        assert_eq!(parse_env_kv("KEY="), Ok(("KEY".to_string(), String::new())));
        assert!(parse_env_kv("NOEQUALS").is_err());
        assert!(parse_env_kv("=value").is_err());
    }

    #[test]
    fn devin_hook_agent_parses() {
        let hook_cli = Cli::try_parse_from([
            "ai-memory",
            "install-hooks",
            "--agent",
            "devin",
            "--server-url",
            "http://example.test:49374",
        ])
        .unwrap_or_else(|e| panic!("failed to parse install-hooks --agent devin: {e}"));
        let Command::InstallHooks(hook_args) = hook_cli.command else {
            panic!("expected install-hooks command for devin");
        };
        assert!(matches!(hook_args.agent, AgentChoice::Devin));
    }

    #[test]
    fn kiro_hook_engine_aliases_parse_explicitly() {
        for alias in ["kiro-cli", "kiro"] {
            let cli = Cli::try_parse_from([
                "ai-memory",
                "install-hooks",
                "--agent",
                alias,
                "--server-url",
                "http://127.0.0.1:49374",
            ])
            .unwrap_or_else(|error| panic!("failed to parse Kiro v2 alias {alias}: {error}"));
            let Command::InstallHooks(args) = cli.command else {
                panic!("expected install-hooks for Kiro v2 alias {alias}");
            };
            assert_eq!(args.agent, AgentChoice::KiroCli);
        }
        for alias in ["kiro-cli-v3", "kiro-v3"] {
            let cli = Cli::try_parse_from([
                "ai-memory",
                "install-hooks",
                "--agent",
                alias,
                "--server-url",
                "http://127.0.0.1:49374",
            ])
            .unwrap_or_else(|error| panic!("failed to parse Kiro v3 alias {alias}: {error}"));
            let Command::InstallHooks(args) = cli.command else {
                panic!("expected install-hooks for Kiro v3 alias {alias}");
            };
            assert_eq!(args.agent, AgentChoice::KiroCliV3);
            assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::KiroCli);
        }
    }

    #[test]
    fn pool_hook_and_finalize_aliases_parse() {
        for alias in ["pool", "poolside"] {
            let cli = Cli::try_parse_from([
                "ai-memory",
                "install-hooks",
                "--agent",
                alias,
                "--server-url",
                "http://127.0.0.1:49374",
            ])
            .unwrap_or_else(|error| panic!("failed to parse Pool alias {alias}: {error}"));
            let Command::InstallHooks(args) = cli.command else {
                panic!("expected install-hooks for Pool alias {alias}");
            };
            assert_eq!(args.agent, AgentChoice::Pool);
            assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::Pool);
            assert_eq!(args.agent.script_hook_subdir(), Some("pool"));
        }
        let cli = Cli::try_parse_from(["ai-memory", "finalize-session", "--agent", "pool"])
            .expect("failed to parse finalize-session --agent pool");
        let Command::FinalizeSession(args) = cli.command else {
            panic!("expected finalize-session for pool");
        };
        assert_eq!(args.agent, ai_memory_core::AgentKind::Pool);
    }

    #[test]
    fn zcode_hook_and_finalize_aliases_parse() {
        for alias in ["zcode", "zai"] {
            let cli = Cli::try_parse_from([
                "ai-memory",
                "install-hooks",
                "--agent",
                alias,
                "--server-url",
                "http://127.0.0.1:49374",
            ])
            .unwrap_or_else(|error| panic!("failed to parse ZCode alias {alias}: {error}"));
            let Command::InstallHooks(args) = cli.command else {
                panic!("expected install-hooks for ZCode alias {alias}");
            };
            assert_eq!(args.agent, AgentChoice::Zcode);
            assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::Zcode);
            // Native exec-form integration: no script bundle to stage.
            assert_eq!(args.agent.script_hook_subdir(), None);
        }
        let cli = Cli::try_parse_from(["ai-memory", "finalize-session", "--agent", "zcode"])
            .expect("failed to parse finalize-session --agent zcode");
        let Command::FinalizeSession(args) = cli.command else {
            panic!("expected finalize-session for zcode");
        };
        assert_eq!(args.agent, ai_memory_core::AgentKind::Zcode);
    }

    /// Hermes is the second no-shell harness (after ZCode): it splits the
    /// configured `command` into argv itself, so the generated block invokes
    /// the native `hook` subcommand instead of a `.sh` bundle.
    #[test]
    fn hermes_hook_and_finalize_aliases_parse() {
        for alias in ["hermes", "hermes-agent"] {
            let cli = Cli::try_parse_from([
                "ai-memory",
                "install-hooks",
                "--agent",
                alias,
                "--server-url",
                "http://127.0.0.1:49374",
            ])
            .unwrap_or_else(|error| panic!("failed to parse Hermes alias {alias}: {error}"));
            let Command::InstallHooks(args) = cli.command else {
                panic!("expected install-hooks for Hermes alias {alias}");
            };
            assert_eq!(args.agent, AgentChoice::Hermes);
            assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::Hermes);
            // Native exec-form integration: no script bundle to stage.
            assert_eq!(args.agent.script_hook_subdir(), None);
        }
        let cli = Cli::try_parse_from(["ai-memory", "finalize-session", "--agent", "hermes"])
            .expect("failed to parse finalize-session --agent hermes");
        let Command::FinalizeSession(args) = cli.command else {
            panic!("expected finalize-session for hermes");
        };
        assert_eq!(args.agent, ai_memory_core::AgentKind::Hermes);
        for alias in ["hermes", "hermes-agent"] {
            let mcp = Cli::try_parse_from(["ai-memory", "install-mcp", "--client", alias])
                .unwrap_or_else(|error| panic!("{alias}: {error}"));
            let Command::InstallMcp(args) = mcp.command else {
                panic!("expected install-mcp for Hermes alias {alias}");
            };
            assert_eq!(args.client, McpClient::Hermes);
        }
    }

    #[test]
    fn command_code_mcp_and_hook_aliases_parse() {
        for alias in ["command-code", "commandcode", "cmdc", "cmd"] {
            let mcp = Cli::try_parse_from([
                "ai-memory",
                "install-mcp",
                "--client",
                alias,
                "--server-url",
                "http://memory.example:49374",
            ])
            .unwrap_or_else(|error| panic!("failed to parse MCP alias {alias}: {error}"));
            let Command::InstallMcp(args) = mcp.command else {
                panic!("expected install-mcp for {alias}");
            };
            assert_eq!(args.client, McpClient::CommandCode);

            let hooks = Cli::try_parse_from([
                "ai-memory",
                "install-hooks",
                "--agent",
                alias,
                "--server-url",
                "http://memory.example:49374",
            ])
            .unwrap_or_else(|error| panic!("failed to parse hook alias {alias}: {error}"));
            let Command::InstallHooks(args) = hooks.command else {
                panic!("expected install-hooks for {alias}");
            };
            assert_eq!(args.agent, AgentChoice::CommandCode);
        }
    }

    #[test]
    fn droid_install_hooks_and_install_mcp_parse_with_the_factory_alias() {
        for alias in ["droid", "factory-droid"] {
            let hooks = Cli::try_parse_from(["ai-memory", "install-hooks", "--agent", alias])
                .unwrap_or_else(|error| panic!("{alias}: {error}"));
            let Command::InstallHooks(args) = hooks.command else {
                panic!("expected install-hooks");
            };
            assert_eq!(args.agent, AgentChoice::Droid);
            assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::Droid);
            // Native commands only: there is no `hooks/droid` bundle.
            assert_eq!(args.agent.script_hook_subdir(), None);

            let mcp = Cli::try_parse_from(["ai-memory", "install-mcp", "--client", alias])
                .unwrap_or_else(|error| panic!("{alias}: {error}"));
            let Command::InstallMcp(args) = mcp.command else {
                panic!("expected install-mcp");
            };
            assert_eq!(args.client, McpClient::Droid);
        }
    }

    #[test]
    fn codebuddy_install_hooks_parses_with_the_kebab_alias() {
        for alias in ["codebuddy", "code-buddy"] {
            let hooks = Cli::try_parse_from(["ai-memory", "install-hooks", "--agent", alias])
                .unwrap_or_else(|error| panic!("{alias}: {error}"));
            let Command::InstallHooks(args) = hooks.command else {
                panic!("expected install-hooks");
            };
            assert_eq!(args.agent, AgentChoice::CodeBuddy);
            assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::CodeBuddy);
            assert_eq!(args.agent.script_hook_subdir(), None);
        }
    }

    #[test]
    fn qwen_code_install_hooks_and_mcp_parse_with_both_aliases() {
        for alias in ["qwen-code", "qwen", "qwencode"] {
            let hooks = Cli::try_parse_from(["ai-memory", "install-hooks", "--agent", alias])
                .unwrap_or_else(|error| panic!("{alias}: {error}"));
            let Command::InstallHooks(args) = hooks.command else {
                panic!("expected install-hooks");
            };
            assert_eq!(args.agent, AgentChoice::QwenCode);
            assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::QwenCode);
            assert_eq!(args.agent.script_hook_subdir(), None);

            let mcp = Cli::try_parse_from(["ai-memory", "install-mcp", "--client", alias])
                .unwrap_or_else(|error| panic!("{alias}: {error}"));
            let Command::InstallMcp(args) = mcp.command else {
                panic!("expected install-mcp");
            };
            assert_eq!(args.client, McpClient::QwenCode);
        }
    }

    #[test]
    fn qoder_install_hooks_and_mcp_parse() {
        let hooks =
            Cli::try_parse_from(["ai-memory", "install-hooks", "--agent", "qoder"]).unwrap();
        let Command::InstallHooks(args) = hooks.command else {
            panic!("expected install-hooks");
        };
        assert_eq!(args.agent, AgentChoice::Qoder);
        assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::Qoder);
        assert_eq!(args.agent.script_hook_subdir(), None);

        let mcp = Cli::try_parse_from(["ai-memory", "install-mcp", "--client", "qoder"]).unwrap();
        let Command::InstallMcp(args) = mcp.command else {
            panic!("expected install-mcp");
        };
        assert_eq!(args.client, McpClient::Qoder);
    }

    #[test]
    fn ibm_bob_install_hooks_and_mcp_parse_with_both_aliases() {
        for alias in ["ibm-bob", "bob"] {
            let hooks = Cli::try_parse_from(["ai-memory", "install-hooks", "--agent", alias])
                .unwrap_or_else(|error| panic!("{alias}: {error}"));
            let Command::InstallHooks(args) = hooks.command else {
                panic!("expected install-hooks");
            };
            assert_eq!(args.agent, AgentChoice::IbmBob);
            assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::IbmBob);
            assert_eq!(args.agent.script_hook_subdir(), None);

            let mcp = Cli::try_parse_from(["ai-memory", "install-mcp", "--client", alias])
                .unwrap_or_else(|error| panic!("{alias}: {error}"));
            let Command::InstallMcp(args) = mcp.command else {
                panic!("expected install-mcp");
            };
            assert_eq!(args.client, McpClient::IbmBob);
        }
    }

    #[test]
    fn dsh_install_hooks_and_mcp_parse_with_both_aliases() {
        for alias in ["dsh", "deepseek-harness", "deepseek_harness"] {
            let hooks = Cli::try_parse_from(["ai-memory", "install-hooks", "--agent", alias])
                .unwrap_or_else(|error| panic!("{alias}: {error}"));
            let Command::InstallHooks(args) = hooks.command else {
                panic!("expected install-hooks");
            };
            assert_eq!(args.agent, AgentChoice::Dsh);
            assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::Dsh);
            // DSH runs a staged script bundle through the Claude Code hooks
            // bridge, so it owns a `hooks/dsh` directory.
            assert_eq!(args.agent.script_hook_subdir(), Some("dsh"));

            let mcp = Cli::try_parse_from(["ai-memory", "install-mcp", "--client", alias])
                .unwrap_or_else(|error| panic!("{alias}: {error}"));
            let Command::InstallMcp(args) = mcp.command else {
                panic!("expected install-mcp");
            };
            assert_eq!(args.client, McpClient::Dsh);
        }
    }

    #[test]
    fn muse_install_hooks_install_mcp_and_mcp_bridge_parse_with_their_aliases() {
        for alias in ["muse", "muse-code", "musecode"] {
            let hooks = Cli::try_parse_from(["ai-memory", "install-hooks", "--agent", alias])
                .unwrap_or_else(|error| panic!("{alias}: {error}"));
            let Command::InstallHooks(args) = hooks.command else {
                panic!("expected install-hooks");
            };
            assert_eq!(args.agent, AgentChoice::Muse);
            assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::Muse);
            // Native commands only: there is no `hooks/muse` bundle.
            assert_eq!(args.agent.script_hook_subdir(), None);

            let mcp = Cli::try_parse_from(["ai-memory", "install-mcp", "--client", alias])
                .unwrap_or_else(|error| panic!("{alias}: {error}"));
            let Command::InstallMcp(args) = mcp.command else {
                panic!("expected install-mcp");
            };
            assert_eq!(args.client, McpClient::Muse);

            let bridge = Cli::try_parse_from(["ai-memory", "mcp-bridge", "--agent", alias])
                .unwrap_or_else(|error| panic!("{alias}: {error}"));
            let Command::McpBridge(args) = bridge.command else {
                panic!("expected mcp-bridge");
            };
            assert_eq!(args.agent, BridgeAgent::Muse);
            assert_eq!(args.agent.session_env(), "MUSE_SESSION_ID");
        }
        let bridge = Cli::try_parse_from(["ai-memory", "mcp-bridge"]).unwrap();
        let Command::McpBridge(args) = bridge.command else {
            panic!("expected mcp-bridge");
        };
        assert_eq!(args.agent, BridgeAgent::ClaudeCode);
        assert_eq!(args.agent.session_env(), "CLAUDE_CODE_SESSION_ID");
    }

    #[test]
    fn copilot_cli_install_hooks_agent_parses_without_a_bare_copilot_alias() {
        let hooks = Cli::try_parse_from(["ai-memory", "install-hooks", "--agent", "copilot-cli"])
            .expect("copilot-cli should parse");
        let Command::InstallHooks(args) = hooks.command else {
            panic!("expected install-hooks");
        };
        assert_eq!(args.agent, AgentChoice::CopilotCli);
        assert_eq!(args.agent.kind(), ai_memory_core::AgentKind::CopilotCli);
        assert_eq!(args.agent.script_hook_subdir(), Some("copilot-cli"));
        // `copilot` already means the VS Code MCP client on `install-mcp`;
        // it must not silently select the CLI hook agent here.
        assert!(Cli::try_parse_from(["ai-memory", "install-hooks", "--agent", "copilot"]).is_err());

        let mcp = Cli::try_parse_from(["ai-memory", "install-mcp", "--client", "copilot-cli"])
            .expect("install-mcp --client copilot-cli should parse");
        let Command::InstallMcp(args) = mcp.command else {
            panic!("expected install-mcp");
        };
        assert_eq!(args.client, McpClient::CopilotCli);
        // ...while the bare word keeps selecting the VS Code client.
        let vscode = Cli::try_parse_from(["ai-memory", "install-mcp", "--client", "copilot"])
            .expect("install-mcp --client copilot should parse");
        let Command::InstallMcp(args) = vscode.command else {
            panic!("expected install-mcp");
        };
        assert_eq!(args.client, McpClient::VsCodeCopilot);
    }

    #[test]
    fn swival_mcp_client_parses() {
        let cli = Cli::try_parse_from([
            "ai-memory",
            "install-mcp",
            "--client",
            "swival",
            "--server-url",
            "http://memory.example:49374",
        ])
        .unwrap_or_else(|error| panic!("failed to parse MCP client swival: {error}"));
        let Command::InstallMcp(args) = cli.command else {
            panic!("expected install-mcp for swival");
        };
        assert_eq!(args.client, McpClient::Swival);
    }

    #[test]
    fn prime_agent_mcp_client_parses() {
        let cli = Cli::try_parse_from(["ai-memory", "install-mcp", "--client", "prime-agent"])
            .unwrap_or_else(|error| panic!("failed to parse MCP client prime-agent: {error}"));
        let Command::InstallMcp(args) = cli.command else {
            panic!("expected install-mcp for prime-agent");
        };
        assert_eq!(args.client, McpClient::PrimeAgent);
    }

    #[test]
    fn zcode_mcp_client_parses() {
        let cli = Cli::try_parse_from([
            "ai-memory",
            "install-mcp",
            "--client",
            "zcode",
            "--server-url",
            "http://memory.example:49374",
        ])
        .unwrap_or_else(|error| panic!("failed to parse MCP client zcode: {error}"));
        let Command::InstallMcp(args) = cli.command else {
            panic!("expected install-mcp for zcode");
        };
        assert_eq!(args.client, McpClient::Zcode);
    }

    #[test]
    fn install_hooks_project_strategy_repo_root_parses() {
        let cli = Cli::try_parse_from([
            "ai-memory",
            "install-hooks",
            "--agent",
            "claude-code",
            "--project-strategy",
            "repo-root",
        ])
        .unwrap_or_else(|e| panic!("failed to parse --project-strategy repo-root: {e}"));
        let Command::InstallHooks(args) = cli.command else {
            panic!("expected install-hooks command");
        };
        assert!(matches!(
            args.project_strategy,
            Some(ProjectStrategyArg::RepoRoot)
        ));
        assert_eq!(
            args.project_strategy.and_then(ProjectStrategyArg::baked),
            Some("repo-root")
        );
    }

    #[test]
    fn install_hooks_prompt_capture_flags_parse_and_conflict() {
        let disabled = Cli::try_parse_from([
            "ai-memory",
            "install-hooks",
            "--agent",
            "claude-code",
            "--no-capture-prompts",
        ])
        .expect("--no-capture-prompts parses");
        let Command::InstallHooks(disabled) = disabled.command else {
            panic!("expected install-hooks command");
        };
        assert!(disabled.no_capture_prompts);
        assert!(!disabled.capture_prompts);

        let enabled = Cli::try_parse_from([
            "ai-memory",
            "install-hooks",
            "--agent",
            "claude-code",
            "--capture-prompts",
        ])
        .expect("--capture-prompts parses");
        let Command::InstallHooks(enabled) = enabled.command else {
            panic!("expected install-hooks command");
        };
        assert!(!enabled.no_capture_prompts);
        assert!(enabled.capture_prompts);

        assert!(
            Cli::try_parse_from([
                "ai-memory",
                "install-hooks",
                "--no-capture-prompts",
                "--capture-prompts",
            ])
            .is_err(),
            "the two prompt-capture choices must conflict"
        );
    }

    #[test]
    fn install_hooks_project_strategy_defaults_to_unset() {
        let cli = Cli::try_parse_from(["ai-memory", "install-hooks", "--agent", "claude-code"])
            .expect("install-hooks parses without --project-strategy");
        let Command::InstallHooks(args) = cli.command else {
            panic!("expected install-hooks command");
        };
        // No flag → None, so a re-apply preserves whatever is already baked.
        assert!(args.project_strategy.is_none());
        assert_eq!(
            args.project_strategy.and_then(ProjectStrategyArg::baked),
            None
        );
    }

    #[test]
    fn install_hooks_explicit_basename_still_parses() {
        let cli = Cli::try_parse_from([
            "ai-memory",
            "install-hooks",
            "--agent",
            "claude-code",
            "--project-strategy",
            "basename",
        ])
        .expect("install-hooks parses --project-strategy basename");
        let Command::InstallHooks(args) = cli.command else {
            panic!("expected install-hooks command");
        };
        // Explicit basename is distinct from "unset": it forces basename and
        // overrides an already-baked repo-root on re-apply.
        assert!(matches!(
            args.project_strategy,
            Some(ProjectStrategyArg::Basename)
        ));
        assert_eq!(
            args.project_strategy.and_then(ProjectStrategyArg::baked),
            None
        );
    }

    #[test]
    fn install_hooks_project_strategy_rejects_invalid_value() {
        let result =
            Cli::try_parse_from(["ai-memory", "install-hooks", "--project-strategy", "bogus"]);
        assert!(
            result.is_err(),
            "an unknown --project-strategy value must be rejected by value_enum"
        );
    }

    #[test]
    fn hook_project_strategy_rejects_invalid_value() {
        let result = Cli::try_parse_from([
            "ai-memory",
            "hook",
            "--event",
            "session-start",
            "--agent",
            "claude-code",
            "--server-url",
            "http://127.0.0.1:49374",
            "--project-strategy",
            "bogus",
        ]);
        assert!(
            result.is_err(),
            "an unknown hook --project-strategy value must be rejected by value_enum"
        );
    }

    #[test]
    fn vscode_copilot_aliases_parse_to_same_variant() {
        for alias in ["vscode-copilot", "copilot", "github-copilot"] {
            let cli = Cli::try_parse_from([
                "ai-memory",
                "install-mcp",
                "--client",
                alias,
                "--server-url",
                "http://example.test:49374/mcp",
            ])
            .unwrap_or_else(|e| panic!("failed to parse install-mcp alias {alias}: {e}"));

            let Command::InstallMcp(args) = cli.command else {
                panic!("expected install-mcp command for alias {alias}");
            };
            assert!(
                matches!(args.client, McpClient::VsCodeCopilot),
                "alias {alias} must resolve to the VS Code Copilot MCP client"
            );
        }
    }

    #[test]
    fn zed_mcp_client_parses() {
        let cli = Cli::try_parse_from([
            "ai-memory",
            "install-mcp",
            "--client",
            "zed",
            "--server-url",
            "http://example.test:49374/mcp",
        ])
        .unwrap();

        let Command::InstallMcp(args) = cli.command else {
            panic!("expected install-mcp command");
        };
        assert!(matches!(args.client, McpClient::Zed));
    }

    #[test]
    fn removed_user_token_commands_no_longer_parse() {
        for argv in [
            vec!["ai-memory", "user", "add", "--username", "alice"],
            vec!["ai-memory", "user", "expire", "alice", "--yes"],
            vec!["ai-memory", "user", "revive", "alice"],
            vec!["ai-memory", "user", "rotate-token", "alice", "--yes"],
        ] {
            let error =
                Cli::try_parse_from(&argv).expect_err("the 1.x token commands were removed in 3.0");
            assert_eq!(
                error.kind(),
                clap::error::ErrorKind::InvalidSubcommand,
                "{argv:?}"
            );
        }
        let parsed = Cli::try_parse_from([
            "ai-memory",
            "user",
            "add-human",
            "--username",
            "alice",
            "--role",
            "root",
        ])
        .expect("user add-human still parses");
        let Command::User(args) = parsed.command else {
            panic!("expected user command");
        };
        assert!(matches!(args.command, UserCommand::AddHuman(_)));
        for argv in [
            vec!["ai-memory", "api-key", "list"],
            vec![
                "ai-memory",
                "api-key",
                "rotate",
                "0190f0b8-0000-7000-8000-000000000000",
                "--yes",
            ],
            vec![
                "ai-memory",
                "api-key",
                "revoke",
                "0190f0b8-0000-7000-8000-000000000000",
                "--yes",
            ],
        ] {
            Cli::try_parse_from(&argv)
                .unwrap_or_else(|error| panic!("{argv:?} is the replacement path: {error}"));
        }
    }

    #[test]
    fn auth_login_openai_oauth_parses() {
        let cli = Cli::try_parse_from([
            "ai-memory",
            "auth",
            "login",
            "openai-oauth",
            "--timeout-secs",
            "30",
        ])
        .unwrap();

        let Command::Auth(args) = cli.command else {
            panic!("expected auth command");
        };
        let AuthCommand::Login(login) = args.command else {
            panic!("expected auth login command");
        };
        assert!(matches!(login.provider, AuthProviderChoice::OpenaiOauth));
        assert_eq!(login.timeout_secs, 30);
        assert!(login.github_token.is_none());
        assert!(login.client_id.is_none());
    }

    #[test]
    fn auth_login_copilot_parses_token_and_client_override() {
        let cli = Cli::try_parse_from([
            "ai-memory",
            "auth",
            "login",
            "copilot",
            "--github-token",
            "ghu-test",
            "--client-id",
            "Iv1.test",
        ])
        .unwrap();

        let Command::Auth(args) = cli.command else {
            panic!("expected auth command");
        };
        let AuthCommand::Login(login) = args.command else {
            panic!("expected auth login command");
        };
        assert!(matches!(login.provider, AuthProviderChoice::Copilot));
        assert_eq!(login.github_token.as_deref(), Some("ghu-test"));
        assert_eq!(login.client_id.as_deref(), Some("Iv1.test"));
    }

    #[test]
    fn llm_test_anthropic_oauth_parses() {
        let cli = Cli::try_parse_from([
            "ai-memory",
            "llm-test",
            "--provider",
            "anthropic-oauth",
            "--model",
            "claude-sonnet-4-6",
            "--prompt",
            "ping",
        ])
        .unwrap();

        let Command::LlmTest(args) = cli.command else {
            panic!("expected llm-test command");
        };
        assert!(matches!(
            args.provider,
            Some(LlmProviderChoice::AnthropicOauth)
        ));
        assert_eq!(args.model.as_deref(), Some("claude-sonnet-4-6"));
        assert_eq!(args.prompt.as_deref(), Some("ping"));
        assert!(!args.server);
    }

    #[test]
    fn llm_test_codex_structured_parses() {
        let cli = Cli::try_parse_from([
            "ai-memory",
            "llm-test",
            "--provider",
            "codex",
            "--model",
            "gpt-5.6-luna",
            "--prompt",
            "ping",
            "--structured",
        ])
        .unwrap();

        let Command::LlmTest(args) = cli.command else {
            panic!("expected llm-test command");
        };
        assert!(matches!(args.provider, Some(LlmProviderChoice::Codex)));
        assert!(args.structured);
    }

    /// `--server` runs the probe on the server, so none of the client-side
    /// provider flags apply and passing one is a parse error rather than a
    /// silently ignored key (#1639).
    #[test]
    fn llm_test_server_takes_no_client_side_provider_flags() {
        let cli = Cli::try_parse_from(["ai-memory", "llm-test", "--server"]).unwrap();
        let Command::LlmTest(args) = cli.command else {
            panic!("expected llm-test command");
        };
        assert!(args.server);
        assert!(args.provider.is_none() && args.model.is_none() && args.prompt.is_none());

        for flag in [
            "--provider",
            "--model",
            "--prompt",
            "--api-key",
            "--base-url",
        ] {
            let mut argv = vec!["ai-memory", "llm-test", "--server", flag];
            let value = match flag {
                "--provider" => "anthropic",
                "--api-key" => "sk-x",
                _ => "x",
            };
            argv.push(value);
            assert!(
                Cli::try_parse_from(&argv).is_err(),
                "`{flag}` must conflict with --server"
            );
        }
    }

    #[test]
    fn completions_parses_every_supported_shell() {
        for (arg, expected) in [
            ("bash", Shell::Bash),
            ("elvish", Shell::Elvish),
            ("fish", Shell::Fish),
            ("powershell", Shell::PowerShell),
            ("zsh", Shell::Zsh),
        ] {
            let cli = Cli::try_parse_from(["ai-memory", "completions", arg]).unwrap();
            let Command::Completions(args) = cli.command else {
                panic!("expected completions command for {arg}");
            };
            assert_eq!(args.shell, expected);
        }
    }

    #[test]
    fn completions_rejects_an_unknown_shell() {
        assert!(Cli::try_parse_from(["ai-memory", "completions", "nushell"]).is_err());
    }

    #[test]
    fn completions_requires_a_shell() {
        assert!(Cli::try_parse_from(["ai-memory", "completions"]).is_err());
    }

    #[test]
    fn upgrade_parses_version_and_force() {
        let cli = Cli::try_parse_from(["ai-memory", "upgrade", "--version", "v2.3.2", "--force"])
            .unwrap();
        let Command::Upgrade(args) = cli.command else {
            panic!("expected upgrade command");
        };
        assert_eq!(args.version.as_deref(), Some("v2.3.2"));
        assert!(args.force);
    }

    /// #1208: each destructive project op takes `--project-id` as an
    /// alternative to its name flag, and the two are mutually exclusive so an
    /// ambiguous request never reaches the server to be guessed at.
    #[test]
    fn project_id_flags_parse_and_conflict_with_their_name_flags() {
        let managed_id = ai_memory_core::ProjectId::new();
        let id_text = managed_id.to_string();
        let cli =
            Cli::try_parse_from(["ai-memory", "run", "--project-id", &id_text, "claude"]).unwrap();
        let Command::Run(run) = cli.command else {
            panic!("expected run");
        };
        assert_eq!(run.project_id, Some(managed_id));
        let cli =
            Cli::try_parse_from(["ai-memory", "workstreams", "--project-id", &id_text]).unwrap();
        let Command::Workstreams(workstreams) = cli.command else {
            panic!("expected workstreams");
        };
        assert_eq!(workstreams.project_id, Some(managed_id));
        for command in ["run", "workstreams"] {
            assert!(
                Cli::try_parse_from([
                    "ai-memory",
                    command,
                    "--project",
                    "api",
                    "--project-id",
                    &id_text
                ])
                .is_err()
            );
            assert!(
                Cli::try_parse_from(["ai-memory", command, "--project-id", "not-a-uuid"]).is_err()
            );
        }
        let id = "11111111-2222-3333-4444-555555555555";

        let cli = Cli::try_parse_from(["ai-memory", "purge-project", "--project-id", id]).unwrap();
        let Command::PurgeProject(args) = cli.command else {
            panic!("expected purge-project");
        };
        assert_eq!(args.project_id.as_deref(), Some(id));
        assert!(args.project.is_none());
        assert!(
            Cli::try_parse_from([
                "ai-memory",
                "purge-project",
                "--project",
                "doomed",
                "--project-id",
                id,
            ])
            .is_err(),
            "--project and --project-id must not both be accepted"
        );

        let cli = Cli::try_parse_from([
            "ai-memory",
            "rename-project",
            "--project-id",
            id,
            "--to",
            "new",
        ])
        .unwrap();
        let Command::RenameProject(args) = cli.command else {
            panic!("expected rename-project");
        };
        assert_eq!(args.project_id.as_deref(), Some(id));
        assert!(args.from.is_none());
        assert!(
            Cli::try_parse_from([
                "ai-memory",
                "rename-project",
                "--from",
                "old",
                "--project-id",
                id,
                "--to",
                "new",
            ])
            .is_err(),
            "--from and --project-id must not both be accepted"
        );

        let cli = Cli::try_parse_from([
            "ai-memory",
            "move-project",
            "--project-id",
            id,
            "--to-workspace",
            "elsewhere",
        ])
        .unwrap();
        let Command::MoveProject(args) = cli.command else {
            panic!("expected move-project");
        };
        assert_eq!(args.project_id.as_deref(), Some(id));
        assert!(args.project.is_none());
        assert!(
            Cli::try_parse_from([
                "ai-memory",
                "move-project",
                "--project",
                "movable",
                "--project-id",
                id,
                "--to-workspace",
                "elsewhere",
            ])
            .is_err(),
            "--project and --project-id must not both be accepted"
        );

        let cli = Cli::try_parse_from([
            "ai-memory",
            "merge-project",
            "--workspace",
            "default",
            "--from-project-id",
            id,
            "--into",
            "canonical",
        ])
        .unwrap();
        let Command::MergeProject(args) = cli.command else {
            panic!("expected merge-project");
        };
        assert_eq!(args.from_project_id.as_deref(), Some(id));
        assert_eq!(args.into.as_deref(), Some("canonical"));
        assert!(
            Cli::try_parse_from([
                "ai-memory",
                "merge-project",
                "--from",
                "old",
                "--from-project-id",
                id,
                "--into",
                "new",
            ])
            .is_err(),
            "--from and --from-project-id must not both be accepted"
        );

        let cli = Cli::try_parse_from([
            "ai-memory",
            "restore-page",
            "--path",
            "notes/example.md",
            "--page-id",
            id,
        ])
        .unwrap();
        let Command::RestorePage(args) = cli.command else {
            panic!("expected restore-page");
        };
        assert_eq!(args.page_id.as_deref(), Some(id));
        assert!(args.from.is_none());
        assert!(
            Cli::try_parse_from([
                "ai-memory",
                "restore-page",
                "--path",
                "notes/example.md",
                "--from",
                "HEAD",
                "--page-id",
                id,
            ])
            .is_err(),
            "--from and --page-id must not both be accepted"
        );
    }
}