import type { Capability } from "./capability-types";

/** Verified existing handlers only; local operations never claim management routes. */
export const ACCESS_REMOTE_CAPABILITIES: readonly Capability[] = [
  {
    command: ["disconnect"], summary: "Disconnect a client or preserve orphaned token files for recovery.",
    usage: "ocx disconnect [--keep-catalog] [--recover-config --yes] [--json] [--expect-link <linkId>] | ocx disconnect --orphaned-token --yes [--json]",
    routes: [],
    flags: [
      { name: "--keep-catalog", value: "boolean", summary: "Keep the connected client's catalog during ordinary disconnect." },
      { name: "--recover-config", value: "boolean", summary: "With --yes, snapshot current Codex artifacts and recover only evidenced owned keys; unknown ownership still refuses." },
      { name: "--expect-link", value: "string", summary: "Disconnect only when this machine is the connected Child of that link, or finish its unfinished disconnect once the connection is cleared; otherwise exit 5 with child_link_mismatch and change nothing." },
      { name: "--orphaned-token", value: "boolean", summary: "Preserve unowned service-token files in a private backup when disconnected." },
      { name: "--yes", value: "boolean", summary: "Explicitly confirm --recover-config or --orphaned-token recovery." },
      { name: "--json", value: "boolean", summary: "Emit the local result and backup location as JSON." },
    ],
    mutates: true, json: "payload",
    details: ["Orphan recovery requires a disconnected durable state, no pending connect or disconnect, no Hub or admission-secret use, no installed or unverified service, and verified absence of a client runtime. It preserves rather than deletes token files and does not establish their ownership.", "If refused, inspect the bind, API keys, token environment and service status; manage a Hub secret through its service. Stop OpenCodex and move saved files back only when their original names are absent. Never print their contents."],
  },
  {
    command: ["hub", "disable"], summary: "Return a hub to standalone in one validated config write.",
    usage: "ocx hub disable [--revoke-clients --client-key <id> ...] [--json]",
    routes: [],
    flags: [{ name: "--revoke-clients", value: "boolean", summary: "Revoke only explicitly selected saved client key IDs." }, { name: "--client-key", value: "string", summary: "Exact saved key ID to revoke; repeatable, requires --revoke-clients." }, { name: "--json", value: "boolean", summary: "Emit the result and restart guidance as JSON." }],
    mutates: true, json: "envelope",
    details: ["Removes hub, unauthenticatedLoopbackListener, runtimeRole and hostname atomically after validation; non-hub roles refuse without changes.", "Existing keys have no verified client origin. Names never select keys; --revoke-clients requires exact --client-key IDs when keys exist. Unselected keys remain.", "Prints only safe key metadata, never plaintext keys or pending rotations. Restart advice is informational; the running proxy and external publishing are unchanged."],
  },
  {
    command: ["access", "key"], summary: "Manage API access keys and inspect masked metadata.",
    usage: "ocx access key list [--json]",
    routes: [{"method": "GET", "path": "/api/keys"}, {"method": "POST", "path": "/api/keys"}, {"method": "PATCH", "path": "/api/keys"}, {"method": "DELETE", "path": "/api/keys"}, {"method": "POST", "path": "/api/keys/rotate"}, {"method": "POST", "path": "/api/keys/rotate/commit"}, {"method": "DELETE", "path": "/api/keys/rotate"}],
    flags: [{"name": "--json", "value": "boolean", "summary": "Emit the result as JSON."}],
    mutates: true, json: "payload",
    details: ["Mixed family: list/get read masked metadata; scope edits, revocation and rotation change authorization.", "Creation and rotation initiation return plaintext secrets once and are human-only handoffs. Ask the operator to perform them in their terminal or dashboard; never capture the returned credential.", "Use the separately documented safe follow-up leaves. keys and top-level api-key are aliases."],
  },
  {
    command: ["access", "key", "list"], summary: "List masked access keys, usage, endpoints and pending rotations.",
    usage: "ocx access key list [--json]",
    routes: [{"method": "GET", "path": "/api/keys"}],
    flags: [{"name": "--json", "value": "boolean", "summary": "Emit the result as JSON."}],
    mutates: false, json: "payload",
    details: ["No plaintext secret is returned by the list route."],
  },
  {
    command: ["access", "key", "get"], summary: "Read one masked key and its access scope.",
    usage: "ocx access key get <id-or-name> [--json]",
    routes: [{"method": "GET", "path": "/api/keys"}],
    flags: [{"name": "--json", "value": "boolean", "summary": "Emit the result as JSON."}],
    mutates: false, json: "payload",
    details: ["Case-insensitive ID takes precedence over name; ambiguous names are refused."],
  },
  {
    command: ["access", "key", "set"], summary: "Replace selected provider/model scope dimensions.",
    usage: "ocx access key set <id-or-name> [--allow-provider <name>]... [--allow-model <id>]... [--clear] [--json]",
    routes: [{"method": "GET", "path": "/api/keys"}, {"method": "PATCH", "path": "/api/keys"}],
    flags: [{"name": "--allow-provider", "value": "string", "summary": "Provider scope; repeatable, replaces that dimension."}, {"name": "--allow-model", "value": "string", "summary": "Model scope; repeatable, replaces that dimension."}, {"name": "--clear", "value": "boolean", "summary": "Clear both dimensions; submitted allow options then override their dimension."}, {"name": "--json", "value": "boolean", "summary": "Emit the result as JSON."}],
    mutates: true, json: "payload",
    details: ["At least one scope option is required. Unspecified dimensions are preserved; this command does not rename keys."],
  },
  {
    command: ["access", "key", "rotate", "commit"], summary: "Commit a pending key rotation.",
    usage: "ocx access key rotate commit <id> <rotation-id> [--json]",
    routes: [{"method": "POST", "path": "/api/keys/rotate/commit"}],
    flags: [{"name": "--json", "value": "boolean", "summary": "Emit the result as JSON."}],
    mutates: true, json: "payload",
    details: ["Use IDs from the human-authorized rotation. Commit only after the client accepts the replacement; the old credential is retired."],
  },
  {
    command: ["access", "key", "rotate", "abort"], summary: "Abort a pending key rotation.",
    usage: "ocx access key rotate abort <id> <rotation-id> [--json]",
    routes: [{"method": "DELETE", "path": "/api/keys/rotate"}],
    flags: [{"name": "--json", "value": "boolean", "summary": "Emit the result as JSON."}],
    mutates: true, json: "payload",
    details: ["Use IDs from the human-authorized rotation. Abort discards the pending replacement credential."],
  },
  {
    command: ["access", "key", "remove"], summary: "Revoke one API access key.",
    usage: "ocx access key remove <id> --yes [--json]",
    routes: [{"method": "DELETE", "path": "/api/keys"}],
    flags: [{"name": "--yes", "value": "boolean", "summary": "Required confirmation before revoking the key.", "required": true}, {"name": "--json", "value": "boolean", "summary": "Emit the result as JSON."}],
    mutates: true, json: "payload",
    details: ["Uses the exact ID, not name resolution; delete is an alias."],
  },
  {
    command: ["access", "endpoints"], summary: "Read endpoint URLs from the access-key metadata.",
    usage: "ocx access endpoints [--json]",
    routes: [{"method": "GET", "path": "/api/keys"}],
    flags: [{"name": "--json", "value": "boolean", "summary": "Emit the result as JSON."}],
    mutates: false, json: "envelope",
    details: ["Projects only baseUrl, endpoint and fields ending in Endpoint; use key list for the full metadata payload."],
  },
  {
    command: ["access", "models"], summary: "Read the public external-model catalog.",
    usage: "ocx access models [--json]",
    routes: [],
    flags: [{"name": "--json", "value": "boolean", "summary": "Emit the result as JSON."}],
    mutates: false, json: "payload",
    details: ["Data-plane GET /v1/models via the runtime client; differs from management models live. The routes field indexes management API routes only."],
  },
  {
    command: ["access","test"],
    summary: "Send a small inference request through the selected protocol.",
    usage: "ocx access test <model> [--protocol <chat|responses|messages>] [--api-key-stdin] [--json]",
    routes: [],
    flags: [{"name":"--protocol","value":"string","summary":"chat | responses | messages; default chat."},{"name":"--json","value":"boolean","summary":"Emit the result as JSON."},{"name":"--api-key-stdin","value":"boolean","summary":"Read one explicit data key from bounded piped stdin; no secret argv/env or management/enrolled-key fallback."}],
    mutates: true,
    json: "envelope",
    details: ["Data-plane model POSTs are not management routes. The request may spend provider quota; run only for an explicitly authorized model probe. Legacy unkeyed behavior/JSON remains unchanged.","Explicit-key mode first sends a credentialless malformed-body control to the same protocol endpoint. Only the native key-required401 permits one16-token keyed request. Authless/unrecognized targets refuse before inference.","Version1 selected-key JSON reports control/request observations and a safe text/completion/usage projection. Limited output stays limited; neither control nor response certifies billing identity, key scopes or atomic policy stability.","Keys use explicit bounded stdin and printableASCII input compatible with issued keys. Same-target identity checks, deadlines, redirect refusal, exact-key redaction and cancellation apply; no retries or fallback credential."],
  },
  {
    command: ["remote-workspace","hub","status"],
    usage: "ocx remote-workspace hub status [--json]",
    summary: "Read Hub devices, runtime availability and sessions.",
    routes: [{"method":"GET","path":"/api/remote-workspace"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit one validated task result as JSON."}],
    mutates: false,
    json: "payload",
    details: ["Existing remote-workspace status remains executor-local. These fixed reads use the selected management Hub; they do not create pairing grants, sessions or remote commands.","Available empty lists succeed. Disabled Hub observations return explicit available:false and exit1; malformed or refused responses are not presented as empty success. Runtime reads can perform availability probes."],
  },
  {
    command: ["remote-workspace","hub","runtimes"],
    usage: "ocx remote-workspace hub runtimes [--json]",
    summary: "Read Codex, Claude and Pi availability on the Hub.",
    routes: [{"method":"GET","path":"/api/remote-workspace/runtimes"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit one validated task result as JSON."}],
    mutates: false,
    json: "payload",
    details: ["Existing remote-workspace status remains executor-local. These fixed reads use the selected management Hub; they do not create pairing grants, sessions or remote commands.","Available empty lists succeed. Disabled Hub observations return explicit available:false and exit1; malformed or refused responses are not presented as empty success. Runtime reads can perform availability probes."],
  },
  {
    command: ["remote-workspace","hub","sessions"],
    usage: "ocx remote-workspace hub sessions [--json]",
    summary: "Read Hub sessions and their public recent events.",
    routes: [{"method":"GET","path":"/api/remote-workspace/sessions"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit one validated task result as JSON."}],
    mutates: false,
    json: "payload",
    details: ["Existing remote-workspace status remains executor-local. These fixed reads use the selected management Hub; they do not create pairing grants, sessions or remote commands.","Available empty lists succeed. Disabled Hub observations return explicit available:false and exit1; malformed or refused responses are not presented as empty success. Runtime reads can perform availability probes."],
  },
  {
    command: ["access","key","rename"],
    usage: "ocx access key rename <id-or-name> <name> [--json]",
    summary: "Rename an unambiguously selected API key while preserving its scopes.",
    routes: [{"method":"GET","path":"/api/keys"},{"method":"PATCH","path":"/api/keys"}],
    flags: [{"name":"--json","value":"boolean","summary":"Emit the command result as JSON."}],
    mutates: true,
    json: "payload",
    details: ["Resolves a unique ID/name from the pinned management roster and sends only id/name. Duplicate-ID ambiguity is refused; no plaintext, scope clear, rotation or deletion is involved.","Name follows existing trimmed nonempty64-unit/control-character rules. Resolution is not revision CAS; API-key root alias shares the operation."],
  },
  {
    command: ["access","audio","transcribe"],
    usage: "ocx access audio transcribe <file> --model <gpt-4o-transcribe|gpt-4o-mini-transcribe|whisper-1> --api-key-stdin [--json]",
    summary: "Transcribe an explicitly chosen bounded audio file with a supplied data key.",
    routes: [],
    flags: [{"name":"--model","value":"string","summary":"Required supported transcription model; no silent model fallback.","required":true},{"name":"--api-key-stdin","value":"boolean","summary":"Required bounded explicit data key on piped stdin; no management/enrolled-key substitution.","required":true},{"name":"--json","value":"boolean","summary":"Emit the command result as JSON."}],
    mutates: true,
    json: "payload",
    details: ["Fixed data-plane POST /v1/audio/transcriptions with file/model/response_format=json. May use provider quota; requires explicit upload/inference authority.","File must be nonempty regular input≤25,000,000bytes; multipart≤32MiB, response≤2MiB, request130s. Only the requested text result is returned, with exact supplied-key redaction.","Audio uses its own explicit-key admission, including on an otherwise authless model listener. No generic model control, retries, secret argv/env or redirect following."],
  },
  {
    command: ["access","audio","live-check"],
    usage: "ocx access audio live-check --model <id> --api-key-stdin [--json]",
    summary: "Check actual live-session readiness, then close the connection.",
    routes: [],
    flags: [{"name":"--model","value":"string","summary":"Required live model; sent to the existing live route.","required":true},{"name":"--api-key-stdin","value":"boolean","summary":"Required bounded printableASCII key, encoded only in the established audio subprotocol.","required":true},{"name":"--json","value":"boolean","summary":"Emit the command result as JSON."}],
    mutates: true,
    json: "envelope",
    details: ["Fixed data-plane WebSocket /v1/live with the existing audio key carrier and session.update, then session.close. It contacts upstream and may incur provider usage; no microphone, audio upload, tool execution or voice-roundtrip claim.","Version1 report distinguishes readiness from confirmed normal close. Socket-open alone is not ready.15s readiness,2s close deadline; stuck/abnormal closure remains unverified/nonzero, with local socket termination.","No raw frames/session IDs/encoded credentials are printed. NativeWebSocket redirect refusal is verified separately from HTTP upload behavior."],
  },
  {
    command: ["link","check"],
    usage: "ocx link check (--link-id <id> | --all) [--no-wait] [--json]",
    summary: "Read each Home-initiated Child's installed version, install kind and update route.",
    routes: [{"method":"POST","path":"/api/link/children/operations"},{"method":"GET","path":"/api/link/children/jobs/{jobId}"}],
    flags: [{"name":"--link-id","value":"string","summary":"Link id to check; repeatable, up to 64."},{"name":"--all","value":"boolean","summary":"Check every link in the Home's store."},{"name":"--no-wait","value":"boolean","summary":"Print the queued job and return without polling it."},{"name":"--json","value":"boolean","summary":"Emit the ocx.link.child-job/1 document as JSON (always JSON)."}],
    mutates: true,
    json: "payload",
    details: ["Requires loopback admin authority on the Home. Starts one observe job; the CLI polls it every 2 s and prints the final ocx.link.child-job/1 document. Exit 0 when every item succeeded, 6 when an item is busy, offline, refused, owner-action or unsupported, 1 on a failure, 4 when the link is unknown or the Home predates Child operations, 5 on a conflict: the link already has an operation running, the Home has no links, or the command ran on a Child.","Changes no install on the Child: it runs the gated update --plan, which only computes. An npm Child without a census pair runs it through its ocx shim, so the launcher's ordinary bootstrap (sync-guard bookkeeping, Bun resolution) runs first, as for any pinned sync; the gated script disables the Desktop handoff. On an npm or pnpm Child served through its census pair it also runs node --version (bounded to 10 s, read-only) to report whether the package launcher can apply an update. Writes the Home's Child observation cache.","One SSH call per Child, up to 60 s, three at a time; a POSIX Child older than 2.97.0 costs one more read-only call for its version. Home-initiated links only: client-initiated and ocx-child links are reported without SSH. One operation per link per running Home."],
  },
  {
    command: ["link", "update"], summary: "Update a Home-initiated Child's OpenCodex to this Home's version.",
    usage: "ocx link update (--link-id <id> | --all) --yes [--no-wait] [--json]",
    routes: [{ method: "POST", path: "/api/link/children/operations" }, { method: "GET", path: "/api/link/children/jobs/{jobId}" }],
    flags: [{ name: "--link-id", value: "string", summary: "Home-initiated link to update; repeatable, up to 64." }, { name: "--all", value: "boolean", summary: "Every link in the Home's store, one Child at a time; Child-initiated links report unsupported." },
      { name: "--yes", value: "boolean", required: true, summary: "Confirms that each updated Child's OpenCodex restarts and its relayed turns end." },
      { name: "--no-wait", value: "boolean", summary: "Print the queued job and return." }, { name: "--json", value: "boolean", summary: "Emit the ocx.link.child-job/1 document (always JSON)." }],
    mutates: true, json: "payload",
    details: ["Runs a pinned sync --expect-link first to confirm the Child still belongs to this link, then the Child's own ocx update --plan through the served entry, then --yes with --expect-plan and a --not-after 120 s after the plan on the Child's own clock, through the link's pinned SSH trust. npm and pnpm installs apply through their Node launcher; Bun installs plan and apply on their served Bun entry. The target is always this Home's version; the Child refuses a downgrade.", "Children below 2.97.0 receive no update command: from 2.93.0 they still get the identity sync, then report owner-action legacy-ocx; ocx-child and GOAT-managed Children report unsupported or owner-action; Windows Children are refused orchestrated apply (unsupported windows-apply). An update restarts the Child's OpenCodex and ends any turn currently relayed for it, so --yes is required. A pinned sync follows a successful, failed or rolled-back apply; an apply whose result is unknown is recorded and neither retried nor resynced, so re-check it with ocx link check.", "Exit 0 all succeeded or up-to-date (with --no-wait: the job was accepted and may still be running), 6 partial (including a kept update whose follow-up sync failed), 1 failed, uncertain or an unknown state, 5 another operation holds the link, the only link named was started from the Child, the Home has no links or the command ran on a Child, 4 the link is unknown or the Home lacks Child operations. On a Home not bound to loopback it exits 1: these operations are not available there, and the dashboard has no controls for them."],
  },
  {
    command: ["link", "sync"], summary: "Run the pinned catalog and settings sync on Home-initiated Children.",
    usage: "ocx link sync (--link-id <id> | --all) [--no-wait] [--json] | ocx link sync --link-id <id> (--restart-app-server-only | --restart-codex --yes) [--ignore-activity] [--no-wait] [--json]",
    routes: [{ method: "POST", path: "/api/link/children/operations" }, { method: "GET", path: "/api/link/children/jobs/{jobId}" }],
    flags: [{ name: "--link-id", value: "string", summary: "Home-initiated link to sync; repeatable, up to 64, exactly one with a restart." }, { name: "--all", value: "boolean", summary: "Every link in the Home's store, three at a time; refused with a restart." },
      { name: "--restart-app-server-only", value: "boolean", summary: "Also restart the Child's Codex app-servers after the sync writes." }, { name: "--restart-codex", value: "boolean", summary: "Also quit and relaunch the Child's Codex desktop app; ends live turns." },
      { name: "--yes", value: "boolean", summary: "Confirms --restart-codex." }, { name: "--ignore-activity", value: "boolean", summary: "Restart even while the Child is busy or held; ends its running work (operator override, never automatic)." }, { name: "--no-wait", value: "boolean", summary: "Print the queued job and return." }, { name: "--json", value: "boolean", summary: "Emit the ocx.link.child-job/1 document (always JSON)." }],
    mutates: true, json: "payload",
    details: ["The same sync --expect-link the ocx sync fan-out runs, gated at 2.93.0. Restart flags are refused on Windows and ignored by ocx-child; the item reports restart unsupported.", "A restart needs one --link-id (--all is refused) and --restart-codex needs --yes. The sync runs first; the restart then goes out as a second pinned sync and is withheld (restart skipped, reason restart-skipped:link-active) while a relayed model request for that Child is in flight. A restarting call whose result is unknown ends uncertain (restart-result-unknown).", "--ignore-activity restarts past that check and past held link WebSocket activity (ocx link status, child.holds); the job records ignoreActivity: true and the Home logs the link id and its in-flight count. Platform and Child-kind refusals still apply, and no automatic path sets it.", "Exit codes as for ocx link update; a withheld or unconfirmed restart exits 6 or 1."],
  },
  {
    command: ["link", "restart-codex"], summary: "Restart Codex on one Home-initiated Child so it reloads the catalog.",
    usage: "ocx link restart-codex --link-id <id> [--scope app-server|codex] --yes [--ignore-activity] [--no-wait] [--json]",
    routes: [{ method: "POST", path: "/api/link/children/operations" }, { method: "GET", path: "/api/link/children/jobs/{jobId}" }],
    flags: [{ name: "--link-id", value: "string", required: true, summary: "Home-initiated link." }, { name: "--scope", value: "string", summary: "app-server (default) or codex (also relaunches the desktop app)." },
      { name: "--yes", value: "boolean", required: true, summary: "Confirms that running Codex turns on the Child end." }, { name: "--ignore-activity", value: "boolean", summary: "Restart even while the Child is busy or held; ends its running work (operator override, never automatic)." },
      { name: "--no-wait", value: "boolean", summary: "Print the queued job and return." }, { name: "--json", value: "boolean", summary: "Emit the ocx.link.child-job/1 document (always JSON)." }],
    mutates: true, json: "payload",
    details: ["A pinned sync, then a second pinned sync with the restart flag; works on full Children from 2.93.0. app-server scope leaves the Codex desktop app's own app-server running. While a relayed model request for that Child is in flight nothing is sent and the item is busy (restart-skipped:link-active), unless --ignore-activity overrides that check.", "Refused on Windows Children (unsupported windows-restart) and reported unsupported for ocx-child. The codex scope needs a logged-in GUI session on the Child; its outcome is requested, not confirmed. Exit codes as for ocx link update."],
  },
  {
    command: ["link", "capture", "start"], summary: "Open a short window in which this machine's link tunnels log sanitized SSH diagnostics.",
    usage: "ocx link capture start [--minutes <1-60>] [--json]",
    routes: [],
    flags: [{ name: "--minutes", value: "number", summary: "Window length, 15 by default and 60 at most; starting again while open moves the expiry." },
      { name: "--json", value: "boolean", summary: "Emit the capture status as JSON." }],
    mutates: true, json: "envelope",
    details: ["A local file operation under <OPENCODEX_HOME>/link/ssh-capture/ on a Home or a Child; it needs no running proxy and no admin token, and no sync, management route or remote input can start it. While the window is open, the next ssh attempt of each Home (-R) or Child (-L) tunnel runs with LogLevel=DEBUG1; an already connected tunnel keeps its level until it reconnects.", "Every stderr line passes an allowlist of OpenSSH line shapes before it is stored: host names, addresses, users, ports, paths, keys, fingerprints, commands and server messages become fixed placeholders and an unknown line is stored only as the category unrecognized. One file per window, at most 1 MiB, deleted 72 h after its last write; at most four files are kept, the oldest deleted first. Admission is unchanged and lines ssh prints only above LogLevel=ERROR are kept out of the failure classification; an unrecognized line such as a server banner still counts and can change the reported cause."],
  },
  {
    command: ["link", "capture", "stop"], summary: "Close the SSH capture window; capture files stay until their retention passes.",
    usage: "ocx link capture stop [--json]",
    routes: [],
    flags: [{ name: "--json", value: "boolean", summary: "Emit the capture status as JSON." }],
    mutates: true, json: "envelope",
    details: ["Removes only the control file, so nothing more is stored and the next tunnel attempt runs ssh with LogLevel=ERROR again. Capture files are kept for sharing and deleted 72 h after their last write; status and later starts apply that retention."],
  },
  {
    command: ["link", "capture", "status"], summary: "Show whether SSH capture is on, its expiry and the retained capture files.",
    usage: "ocx link capture status [--json]",
    routes: [],
    flags: [{ name: "--json", value: "boolean", summary: "Emit the capture status as JSON." }],
    mutates: true, json: "envelope",
    details: ["Reads the local capture directory. It also applies retention: capture files 72 h past their last write and an expired control file are deleted, and the count is reported as removed."],
  },
  {
    command: ["link", "policy"], summary: "Read or change how this Home keeps its Children current.",
    usage: "ocx link policy [--updates off|notify|auto-when-idle] [--catalog-fanout auto|manual] [--child-codex-restart never|app-server-when-idle] [--idle-after-minutes <1-60>] [--json]",
    routes: [{ method: "GET", path: "/api/link/children/policy" }, { method: "PUT", path: "/api/link/children/policy" }],
    flags: [{ name: "--updates", value: "string", summary: "off, notify, or auto-when-idle (default)." }, { name: "--catalog-fanout", value: "string", summary: "auto (default) or manual." },
      { name: "--child-codex-restart", value: "string", summary: "never (default) or app-server-when-idle." }, { name: "--idle-after-minutes", value: "number", summary: "Minutes without a relayed model request before a Child counts as idle; default 10." },
      { name: "--json", value: "boolean", summary: "Emit {policy, warning} as JSON." }],
    mutates: true, json: "payload",
    details: ["Without flags it reads the policy; with flags it changes only those knobs. Stored in <configDir>/link/child-policy.json on the Home, never in config.json. An invalid file turns automatic catalog fan-out and updates off; saving merges onto that, so pass --catalog-fanout auto and an --updates mode to turn them back on.", "--updates stores the update mode only; this release starts no automatic update (notify and auto-when-idle take effect when the automatic update sweep ships). Catalog fan-out syncs Home-initiated Children 60 s after a Home catalog change; it restarts Codex on a Child only with app-server-when-idle, and only while that Child is idle. A Home without links runs none of it."],
  },
  {
    command: ["link", "routes"], summary: "List the SSH routes a Home-initiated link may use, in the order the Home tries them.",
    usage: "ocx link routes --link-id <id> [--json]",
    routes: [{ method: "GET", path: "/api/link/{id}/routes" }],
    flags: [{ name: "--link-id", value: "string", required: true, summary: "Home-initiated link id." }, { name: "--json", value: "boolean", summary: "Emit {linkId, pin, routes} as JSON." }],
    mutates: false, json: "payload",
    details: ["Requires loopback admin authority on the Home, like ocx link reconnect; the local control socket does not serve it. The pin is the link's own alias: its host key is the one every route must present, and it is always in the list. A link with one route lists its alias only. Read ocx link status for the route in use and since when."],
  },
  {
    command: ["link", "routes", "add"], summary: "Add an SSH route to a Home-initiated link after proving the link's pinned host key over it.",
    usage: "ocx link routes add --link-id <id> --route <alias> [--position <n>] [--json]",
    routes: [{ method: "POST", path: "/api/link/{id}/routes" }],
    flags: [{ name: "--link-id", value: "string", required: true, summary: "Home-initiated link id." }, { name: "--route", value: "string", required: true, summary: "SSH host alias or destination of the new route." },
      { name: "--position", value: "number", summary: "Index in the list; by default just before the alias, so direct routes come first and the alias stays last." }, { name: "--json", value: "boolean", summary: "Emit {linkId, pin, routes} as JSON." }],
    mutates: true, json: "payload",
    details: ["The Home first checks that its link known_hosts file trusts only the link's recorded key for the alias (every entry for it, in any case or hashed by an older release, carries that key), then connects over the new route with strict checking against that one key and stores the route only if the same machine answers. Refusals: route_unproven with a cause (hostkey, auth, forward, transient), pin_mismatch, trust_file_unexpected, link_changed, pin_changed, route_exists, route_limit (8 routes), link_operation_in_progress (removal or a Child job holds the link), link_retirement_pending (an unfinished removal of the link holds it; finish that revoke first). Exit 5 on a refusal, 4 for an unknown link, 1 when the routes were stored but the running proxy did not apply them (routes_stored_reload_failed; ocx link routes --link-id <id> reads what was stored).", "Adding a route does not move a running tunnel; the Home tries the list in order from the next connection on (ocx link reconnect starts one now). Requires loopback admin authority on the Home."],
  },
  {
    command: ["link", "routes", "remove"], summary: "Remove an SSH route from a Home-initiated link.",
    usage: "ocx link routes remove --link-id <id> --route <alias> [--json]",
    routes: [{ method: "POST", path: "/api/link/{id}/routes" }],
    flags: [{ name: "--link-id", value: "string", required: true, summary: "Home-initiated link id." }, { name: "--route", value: "string", required: true, summary: "Route to remove." }, { name: "--json", value: "boolean", summary: "Emit {linkId, pin, routes} as JSON." }],
    mutates: true, json: "payload",
    details: ["The alias is the link's pin and cannot be removed (route_is_pin). Removing the route the tunnel uses restarts the tunnel on the remaining list; removing the last extra route returns the link to one route. Exit 4 for an unknown link or route (link_not_found, route_not_found), 5 on a refusal (route_is_pin, link_operation_in_progress, link_retirement_pending: an unfinished removal of the link holds it), 1 when the routes were stored but the running proxy did not apply them (routes_stored_reload_failed). Requires loopback admin authority on the Home."],
  },
  {
    command: ["link", "routes", "order"], summary: "Reorder a Home-initiated link's SSH routes.",
    usage: "ocx link routes order --link-id <id> --routes <alias,alias,...> [--json]",
    routes: [{ method: "POST", path: "/api/link/{id}/routes" }],
    flags: [{ name: "--link-id", value: "string", required: true, summary: "Home-initiated link id." }, { name: "--routes", value: "string", required: true, summary: "The current routes, comma separated, in the new order." }, { name: "--json", value: "boolean", summary: "Emit {linkId, pin, routes} as JSON." }],
    mutates: true, json: "payload",
    details: ["The list must name exactly the current routes (route_order_mismatch otherwise), so no route enters unproven. While an unfinished removal of the link holds it, the reorder is refused (link_retirement_pending); finish that revoke first. A reorder does not move a running tunnel. Requires loopback admin authority on the Home."],
  },
  {
    command: ["link", "operations"], summary: "List or read the enrollments and revokes journalled under an operation id.",
    usage: "ocx link operations [--operation-id <id>] [--json]",
    routes: [{ method: "GET", path: "/api/link/operations" }, { method: "GET", path: "/api/link/operations/{id}" }],
    flags: [{ name: "--operation-id", value: "string", summary: "Read one operation." }, { name: "--json", value: "boolean", summary: "Emit {operations} or the one entry as JSON." }],
    mutates: false, json: "payload",
    details: ["Each entry names its reserved link and key ids, the intent and completion of every effect and its outcome: open, committed, failed_clean, residual (the Child may still hold an enrollment or a plant) or unknown. Committed and failed_clean entries stay 30 days; residual and unknown entries stay until resolved, then 30 days. Past 256 settled entries the oldest go early, never before 2 hours plus the alias-lock wait: a repeat with the same operation id and parameters (another set answers operation_mismatch) that reaches the journal within 2 hours of the answer gets the recorded outcome, except that a revoke whose own removal was interrupted resumes it first and answers that attempt (retry a transient refusal such as link_operation_in_progress), and later the id may be treated as a new operation, which enrolls a machine again if its link was removed meanwhile; at 256 open or unresolved residual or unknown entries a new journalled operation is refused (operation_journal_full) until some are resolved, and so is one after 1024 operations settled within 2 hours and three minutes, a limit of about 500 journalled operations per hour sustained. Requires loopback admin authority on the Home."],
  },
  {
    command: ["link", "operations", "resolve"], summary: "Mark a residual or unknown link operation resolved.",
    usage: "ocx link operations resolve --operation-id <id> --yes [--json]",
    routes: [{ method: "POST", path: "/api/link/operations/{id}/resolve" }],
    flags: [{ name: "--operation-id", value: "string", required: true, summary: "The residual or unknown operation." }, { name: "--yes", value: "boolean", required: true, summary: "Confirms that the Child is clean or the loss is accepted." }, { name: "--json", value: "boolean", summary: "Emit the resolved entry as JSON." }],
    mutates: true, json: "payload",
    details: ["Changes nothing on the Child or in links.json: it records the resolution, and the entry's 30 days of retention start then. operation_not_resolvable (exit 5) for any other state, operation_not_found (exit 4). Requires loopback admin authority on the Home.", "A journalled revoke past its remote_cleanup intent (the Child's cleanup may have started) that then ended unknown, or that stayed open with no revoke running it (the Home stopped or the revoke failed before writing its outcome), keeps that link's tunnel down across restarts (ocx link status: reason revoke_unsettled; ocx link reconnect: link_suspended). Resolving the revoke reloads the tunnels, so the link reconnects. An open revoke cannot be resolved: repeat it with the same --operation-id and the flags of its first attempt (the journal keeps only a digest of them, so a different --purge answers operation_mismatch), then resolve it if it ends unknown."],
  },
  {
    command: ["link", "activity", "clear"], summary: "Clear one link's held activity so automatic and activity-gated Child restarts may run again.",
    usage: "ocx link activity clear --link-id <id> [--json]",
    routes: [{ method: "POST", path: "/api/link/children/activity/clear" }],
    flags: [{ name: "--link-id", value: "string", required: true, summary: "The link whose holds to clear." },
      { name: "--json", value: "boolean", summary: "Emit {linkId, cleared} as JSON." }],
    mutates: true, json: "payload",
    details: ["A link Responses WebSocket that closes while Codex was busy leaves a hold, and so does a Home that stopped without a clean shutdown; a hold keeps the Child in flight so automatic and activity-gated restarts wait. ocx link status lists each held link's holds and their reasons under child.holds. Holds that only the operator can release (an unknown running turn, untracked results, no thread id, or an unknown state after a crash) end here.", "Clears every hold of that one link and nothing else; nothing clears holds automatically. The holds file is saved before anything is forgotten, so a failed save clears nothing (503). It does not touch live sockets or relayed requests."],
  },
];
