From 4670d47d56c2a75ef9a522a934172b762660a463 Mon Sep 17 00:00:00 2001 From: Ben Vinegar <2153+benvinegar@users.noreply.github.com> Date: Sun, 8 Nov 2026 20:10:23 -0500 Subject: [PATCH 1/3] feat(controller): declare command execution contracts (stack 1/4) --- ARCHITECTURE.md | 2 +- CONTRIBUTING.md | 4 +- controller/cli.mjs | 144 +++++++++++++++++++------- test/cli-contracts.test.mjs | 200 ++++++++++++++++++++++++++++++++++++ 4 files changed, 309 insertions(+), 41 deletions(-) create mode 100644 test/cli-contracts.test.mjs diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 2cb25d6..678ae96 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -69,7 +69,7 @@ VM (Ubuntu 24.04; XFCE desktop unless --headless) | `guests/linux.mjs`, `guests/index.mjs` | agent machine and host | What's inside a VM, per guest OS: the agent's home and project, boxery's config and grants directories. `core/` and `host/` both import it instead of keeping their own copies; it imports nothing. Only `linux` exists ([plan](docs/plans/2026-11-03-guest-os-seam.md)) | | `mcp/boxery-mcp.mjs` | agent machine (stdio) or host (HTTP) | MCP server. stdio, or Streamable HTTP at `/mcp` (bearer token required, optional Tailscale user allowlist, Origin check; meant for `tailscale serve`, never funnel). Sessions keep their own host and VM. `vm_view` + `mcp/desktop-view.html` give MCP Apps clients a live desktop | | `extension/index.ts` | agent machine | pi extension: explicit `vm_*` tools next to pi's built-ins (which stay local), `--vm NAME/new/pool`, `--vm-host`, `/vm` commands, throwaway VMs and leases tied to the pi session | -| `controller/boxery` + `controller/*.mjs` | agent machine | The CLI. `controller/boxery` is a small Bash shim (it finds Node and passes arguments on byte for byte, like `host/boxery-host`); `controller/cli.mjs` parses commands and runs the same core code MCP and pi do. Its `COMMANDS` table is the one definition of routing and help (and of which long commands report their progress to the terminal, as OSC 7501 on stderr when it is a terminal: a `status` on the entry, run by `controller/status.mjs`): a command has a `run` handler, and a command family (`host`, `snapshot`, `agent`, `job`, `access`, `lease`; `pool` and `runners` parse their own actions) has `actions`, each naming an existing command whose handler it runs, so `boxery job ls` and `boxery jobs` are one code path and the older spellings need no second table. Family actions are resolved from the words alone, before any host or profile is read; `host`'s registry actions (`add`, `ls`, `show`, `use`, `rm`) have no command and run in `controller/hosts.mjs` before host selection, while its maintenance actions go through the ordinary selected-host path. The code behind the commands: `core/lifecycle.mjs` (new/fork/rm/start/stop/resize/snap/revert/pin/pool/patch, listings), `core/leases.mjs`, `core/grants.mjs`, `vm_copy` (`cp`), `core/versions.mjs`. What only the CLI has: argument parsing and output formats (unchanged, [cli.md](docs/cli.md)), `/dev/tty` grant approval (`controller/grants.mjs`), terminal commands (`ssh`, `attach`, `desktop`, `forward`, `run`, jobs in `controller/jobs.mjs`, `runners once` with your `gh` login), and the host registry's CLI (`controller/hosts.mjs`: `setup`, `host add/ls/show/use/rm`, over `core/registry.mjs`, which `vm_manage host_add/host_rm` use too). Profiles: `core/profile.mjs` (config, `hostRun` to boxery-host, ssh_config, shared connections) and `core/ssh-config.mjs` (quoting and the ssh_config text). A profile `config` that only assigns the controller's settings (`HOST`, `HOST_BIN`, `HOST_PROFILE`, `IDENTITY`, `GRANT_CONFIRM`, as `setup` writes them) is parsed; any other config is sourced by bash (`set -eu`, with `$CONF_DIR` and the defaults set), and its exported environment reaches host commands. `test/ssh-config.test.mjs` holds the ssh_config text and quoting to the Bash controller's (`test/fixtures/bash-profile.sh`), word for word. Each profile's `ssh_config`: `*.boxery` → `ProxyCommand ssh HOST boxery-host connect %h %p`, ControlMaster, per-lease identities, per-VM `ForwardAgent` | +| `controller/boxery` + `controller/*.mjs` | agent machine | The CLI. `controller/boxery` is a small Bash shim (it finds Node and passes arguments on byte for byte, like `host/boxery-host`); `controller/cli.mjs` parses commands and runs the same core code MCP and pi do. Its `COMMANDS` table is the one definition of routing and help (and of which long commands report their progress to the terminal, as OSC 7501 on stderr when it is a terminal: a `status` on the entry, run by `controller/status.mjs`): a command has a `run` handler, and a command family (`host`, `snapshot`, `agent`, `job`, `access`, `lease`; `pool` and `runners` parse their own actions) has `actions`, each naming an existing command whose handler it runs, so `boxery job ls` and `boxery jobs` are one code path and the older spellings need no second table. Commands carry an optional `contract` beside their handlers: selected-host or controller scope, help/payload boundaries, optional host selection, all-host listings, SSH-qualified targets and terminal needs. Ordinary commands use selected-host/legacy-help defaults; aliases and family actions inherit their handler's contract. Approval is conditional when granting (`new`, `fork`, `grant`, `agent-forward`); only `attach` unconditionally needs a terminal on stdin, after argument validation. Family actions are resolved before any host or profile is read; `host` registry actions (`add`, `ls`, `show`, `use`, `rm`) explicitly declare `scope: "registry"` and run before host selection. Registry scope is not an offline guarantee: `host add DEST` contacts DEST. Host maintenance uses the ordinary selected-host path. The code behind the commands: `core/lifecycle.mjs` (new/fork/rm/start/stop/resize/snap/revert/pin/pool/patch, listings), `core/leases.mjs`, `core/grants.mjs`, `vm_copy` (`cp`), `core/versions.mjs`. What only the CLI has: argument parsing and output formats (unchanged, [cli.md](docs/cli.md)), `/dev/tty` grant approval (`controller/grants.mjs`), terminal commands (`ssh`, `attach`, `desktop`, `forward`, `run`, jobs in `controller/jobs.mjs`, `runners once` with your `gh` login), and the host registry's CLI (`controller/hosts.mjs`: `setup`, `host add/ls/show/use/rm`, over `core/registry.mjs`, which `vm_manage host_add/host_rm` use too). Profiles: `core/profile.mjs` (config, `hostRun` to boxery-host, ssh_config, shared connections) and `core/ssh-config.mjs` (quoting and the ssh_config text). A profile `config` that only assigns the controller's settings (`HOST`, `HOST_BIN`, `HOST_PROFILE`, `IDENTITY`, `GRANT_CONFIRM`, as `setup` writes them) is parsed; any other config is sourced by bash (`set -eu`, with `$CONF_DIR` and the defaults set), and its exported environment reaches host commands. `test/ssh-config.test.mjs` holds the ssh_config text and quoting to the Bash controller's (`test/fixtures/bash-profile.sh`), word for word. Each profile's `ssh_config`: `*.boxery` → `ProxyCommand ssh HOST boxery-host connect %h %p`, ControlMaster, per-lease identities, per-VM `ForwardAgent` | | `host/boxery-host` + `host/*.mjs` | control plane | Backend-agnostic VM manager. Bash entry point; `connect` stays in Bash so the ProxyCommand never pays Node startup; everything else is Node. Ownership per module: [host-modules.md](docs/host-modules.md) | | `host/backends/*.sh` | control plane | Hypervisor effects only, one allowlisted function per process, arguments as argv ([contract](host/backends/README.md)). libvirt, Lima and exe.dev are stable; Cloud Hypervisor, boat.dev and OpenShell are experimental | | `proxy/boxery-proxy.mjs` | control plane | Credential proxy: checks the per-VM token, applies per-route method/path allowlists, body/concurrency/time limits, injects the real credential, refuses WebSocket upgrades (clients use SSE) | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1dfc167..48d0551 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -25,7 +25,7 @@ CI (`.github/workflows/ci.yml`) runs on PRs and pushes to `master`: lint and the | Change | Also | |---|---| | a `vm_*` tool or action | the table in `core/boxery-tools.mjs`, not one front-end (`test/frontends.test.mjs`); map it to a `boxery` command in `test/parity.test.mjs`, or say why it has none | -| a `boxery` command or flag | its `help` in `controller/cli.mjs`'s `COMMANDS`; map it in `test/parity.test.mjs` (and, if it can run for more than a few seconds, give its entry a `status`, which reports it to the terminal: `controller/status.mjs`; the test says so for a command with neither a `status` nor a `NO_STATUS` reason); `npm run docs:cli`; review the help change, then `BOXERY_UPDATE_GOLDEN=1 node --test test/help-drift.test.mjs` (it rewrites both `boxery help` and `boxery help --all`) | +| a `boxery` command or flag | its `help` in `controller/cli.mjs`'s `COMMANDS`, plus a `contract` if it differs from ordinary selected-host/legacy-help behavior (scope, payload, terminal needs, optional/all-host routing); `test/cli-contracts.test.mjs` checks these declarations; map it in `test/parity.test.mjs` (and, if it can run for more than a few seconds, give its entry a `status`, which reports it to the terminal: `controller/status.mjs`; the test says so for a command with neither a `status` nor a `NO_STATUS` reason); `npm run docs:cli`; review the help change, then `BOXERY_UPDATE_GOLDEN=1 node --test test/help-drift.test.mjs` (it rewrites both `boxery help` and `boxery help --all`) | | a family action (`boxery snapshot create`, `job ls`, …) | an entry in the family's `actions` naming the command whose handler it runs (no second handler; `help` is derived from that command's, with overrides only where its arguments differ), plus the same as for a command; test canonical and older spelling together in `test/cli-families.test.mjs` | | a `boxery-host` command or flag | its help in `host/help.mjs` (`host/cli.mjs` won't load without it); `npm run docs:cli`; output formats are pinned by `test/shell/logic/host-output.sh` | | a backend | `host/backends/NAME.sh` ([contract](host/backends/README.md)); a declaration in `backends/index.mjs` ([support contract](docs/backends.md), `test/backend-capabilities.test.mjs`); its `BOXERY_NAME_*` settings in `host/host-env.list`; tests like `test/shell/common/host-lima-backend.sh`; the README's platform lists | @@ -47,6 +47,8 @@ Types: the code is plain JavaScript typed with JSDoc comments (`/** @param {stri `boxery help`, `boxery help --all` and `boxery COMMAND [ACTION] --help` are rendered (`help/index.mjs`, through `controller/usage.mjs`) from the `help` each command carries in `controller/cli.mjs`'s `COMMANDS` table, next to its handler: a new command needs its help to exist at all. boxery-host's help is the same kind of table, in `host/help.mjs` (its handlers are in `host/cli.mjs`, which refuses to load with a command that has no help). Write the summary as one short line; longer explanations go in `details`, `flags` and `examples`, which only its own `--help` shows. `test/help-drift.test.mjs` keeps it honest: a command's help must list exactly the `--flags` its code compares against (flags the host parses are checked against `boxery-host help`), examples must use real commands and documented flags, the same holds for every `boxery-host` command, `docs` anchors must exist, the command reference in `docs/cli.md` must be current (`npm run docs:cli` regenerates it), and `boxery help` and `boxery help --all` are pinned in `test/fixtures/boxery-help.txt` and `boxery-help-all.txt` (`BOXERY_UPDATE_GOLDEN=1 node --test test/help-drift.test.mjs` rewrites it after you review the change). +`test/cli-contracts.test.mjs` checks contracts and their inheritance, scope routing, help boundaries, optional hosts and SSH-qualified targets against an unconfigured temporary home. + `test/cli-families.test.mjs` runs the real CLI against a stub `boxery-host` and a stub `ssh` in temporary profiles, and checks that every family action and its older spelling produce the same output, exit status, ssh and host calls and saved state; that help and mistakes touch no host, profile or grant; that `host`'s registry actions refuse `--host` while its maintenance actions follow it; that `access ls` is read-only; and that grant approval, grant stores and leases stay per profile. Add a pair there when you add an action. `test/frontends.test.mjs` does the same for the two agent front-ends, the MCP server and the pi extension: both must list exactly the shared tool table in `core/boxery-tools.mjs`. Put a new tool or action in the table (with its `run`), not in one front-end; something only one of them can offer goes in that test's `MCP_ONLY` or `PI_ONLY` with the reason. diff --git a/controller/cli.mjs b/controller/cli.mjs index b8dd3f5..a9dabfb 100644 --- a/controller/cli.mjs +++ b/controller/cli.mjs @@ -32,7 +32,7 @@ const grants = () => import("./grants.mjs"); // ---------------------------------------------------------------- commands -/** @typedef {(s: Selected, args: string[]) => Promise} Command */ +/** @typedef {(s: Selected, args: string[], how: Dispatch) => Promise} Command */ // (Commands are typed one by one below: their returns are void.) /** new NAME [--shape S] [--cpus N --mem MiB --disk GiB] [--from IMAGE] [--headless [--layers L,...]] [--grant SPEC]... [--agent-forward] @param {Selected} s @param {string[]} args @returns {Promise} */ @@ -178,7 +178,7 @@ async function cmdAttach(s, [name = "", tool = "pi", sess = tool]) { if (!Object.hasOwn(run, tool)) die(`unknown agent: ${tool} (pi, opencode or shell)`, 2); if (!/^[A-Za-z0-9._-]+$/.test(sess)) die(`invalid session name: ${sess}`); // (Without one, tmux says only "open terminal failed: not a terminal".) - if (!process.stdin.isTTY) die(`attach needs a terminal; for headless work use ${BOXERY} prompt ${name} "TASK" or ${BOXERY} run --bg ${name} CMD`); + if (contractOf("attach").terminal === "stdin" && !process.stdin.isTTY) die(`attach needs a terminal; for headless work use ${BOXERY} prompt ${name} "TASK" or ${BOXERY} run --bg ${name} CMD`); await (await grants()).reapplyQuiet(s, name); // tmux keeps the agent alive when you disconnect (laptop sleep, network change). const rc = await vmSsh(s, ["-t", `${name}.boxery`, `cd ~/project 2>/dev/null; tmux has-session -t '${sess}' 2>/dev/null || tmux new-session -d -s '${sess}' -c ~/project "bash -lc '${run[tool]}; exec bash -l'"; exec tmux attach -t '${sess}'`]); @@ -295,24 +295,48 @@ async function cmdSsh(s, [name = "", ...rest]) { } /** @typedef {import("./usage.mjs").Help} Help */ -/** A family action: a command's handler (`command`; `args` turns the action's arguments into the command's), with its help. @typedef {import("../help/index.mjs").Action & { args?: (args: string[]) => string[] }} FamilyAction */ -/** A command: its help and what it runs (with a selected host). Aliases name their command; pre-host commands - * (help, setup, version without a host) are dispatched in main() and have no `run` here. A family has `actions` - * instead of `run`: each runs another command's handler, except host's registry actions (add, ls, show, use, rm), - * which main() runs before any host is selected. - * @typedef {{ help: Help, run?: Command, status?: StatusSpec, preHost?: true, actions?: Record } | { alias: string }} Entry */ +/** What main() and the handlers read about a command, beside its handler: where it runs, what it owns of the + * words after its name, and what it needs of the terminal. Ordinary commands (a selected host, the legacy help + * convention) say nothing: CONTRACT_DEFAULTS. test/cli-contracts.test.mjs pins the table. + * - scope: `host` runs on the selected host; `controller` runs here (its `local` handler) and no host is + * selected; `registry` (a family action only) edits this machine's registry, though `host add DEST` contacts DEST. + * - noHost: the refusal when --host is given to a command that has no host to select. + * - hostOptional: with no --host and no default host, `local` runs instead of a handler needing a host. + * - allHosts: without --host, the handler lists every host (it is told: its third argument). + * - vmAtHost: the first word may be NAME@HOST, which selects HOST like --host. + * - help: how -h/--help is told from payload. `legacy`: a leading flag, or one word then the flag (snap demo + * --help). `leading`: only a leading flag; after that the words are the command's (run demo --help). `self`: + * the command renders help, so its words are never a help flag. + * - payload: words the command passes on instead of parsing. `argv`: exec'd as given. `shell`: joined and run by + * the VM's shell. `task`: free text for an agent. `agent`: an agent tool and session name. + * - terminal: `stdin`: needs a terminal on stdin (attach), whatever it is given. `approval`: asks a person on + * /dev/tty only when it grants something (controller/grants.mjs ask; GRANT_CONFIRM=off in the profile's config skips it). + * @typedef {{ scope: "host" | "controller" | "registry", help: "legacy" | "leading" | "self", noHost?: string, hostOptional?: true, allHosts?: true, vmAtHost?: true, payload?: "argv" | "shell" | "task" | "agent", terminal?: "stdin" | "approval" }} Contract */ +/** How each command is dispatched unless its `contract` says otherwise. @type {Contract} */ +const CONTRACT_DEFAULTS = { scope: "host", help: "legacy" }; +/** What a handler is told about how it was reached. @typedef {{ allHosts: boolean }} Dispatch */ +/** A family action: a command's handler (`command`; `args` turns the action's arguments into the command's), with its help. + * host's registry actions (add, ls, show, use, rm) have no command: they say `scope: "registry"` and `noHost`, and + * main() runs them before any host is selected. @typedef {import("../help/index.mjs").Action & { args?: (args: string[]) => string[], scope?: "registry", noHost?: string }} FamilyAction */ +/** A command: its help, its contract and what it runs (with a selected host). Aliases name their command. A + * `controller` command (help, setup) has no `run`, only `local`, which main() runs without selecting a host; so + * does version without a host. A family has `actions` instead of `run` (and `defaultAction` for a bare `boxery FAMILY`): + * each runs another command's handler, and the action inherits that command's contract. + * @typedef {{ help: Help, run?: Command, local?: (args: string[]) => unknown, status?: StatusSpec, contract?: Partial, defaultAction?: string, actions?: Record } | { alias: string }} Entry */ const JSON_FLAG = /** @type {[string, string]} */ (["--json", "Print JSON (fields: docs/cli.md#json-output)"]); // Captures differ by backend (#219; backends/index.mjs, diskSnapshots). const CAPTURE_NOTE = "Most backends capture a running VM live (libvirt and cloud-hypervisor in about a second, exe.dev in about 12 s); Lima stops it and starts it again (about 10 s on vz), so its processes, tmux sessions and jobs end."; const SIZE_FLAGS = /** @type {[string, string][]} */ ([["--shape S", "A size from boxery shapes"], ["--cpus N", "CPUs"], ["--mem MiB", "Memory, in MiB"], ["--disk GiB", "Disk, in GiB"]]); +const HOST_MGMT = "--host does not apply to host management"; const RUN_RULES = "Arguments are passed exactly as given, like docker exec: quotes, $, ~, globs and ; are not re-parsed in the VM. For pipes, &&, ~ or $VAR, run a shell: bash -c '...'."; /** Every boxery command and its help (boxery help and COMMAND --help are rendered from this). @type {Record} */ export const COMMANDS = { // ------------------------------------------------ setup & hosts setup: { - preHost: true, + contract: { scope: "controller", noHost: "setup takes --name NAME, not --host" }, + local: setupNamed, help: { group: "start", summary: "configure a VM host (local = this machine), register your ssh key", usage: ["setup user@host|local [--name NAME] [--key K.pub] [--host-bin PATH] [--profile P [--backend B]]", "setup local --backend openshell [OPTIONS]"], @@ -323,6 +347,7 @@ export const COMMANDS = { }, }, host: { + defaultAction: "ls", help: { group: "families", summary: "named hosts, and maintenance of the selected host", list: "host add|ls|show|use|rm|…", usage: [], details: ["add, ls, show, use and rm manage this machine's registry and take no --host. add NAME DEST runs setup on DEST; importing --config-dir and the other registry actions stay local. Maintenance actions act on the selected host (--host NAME, else the default)."], @@ -332,16 +357,17 @@ export const COMMANDS = { // (add, ls, show, use and rm have no command: controller/hosts.mjs runs them before any host is selected.) actions: { add: { + scope: "registry", noHost: HOST_MGMT, help: { summary: "register DEST (user@host or local) as NAME", usage: ["host add NAME DEST [--key K.pub] [--host-bin PATH] [--backend B | --profile P]", "host add NAME --config-dir DIR"], flags: [["--backend B", "Create a new profile on DEST for backend B (own state, proxy port and services)"], ["--profile P", "Use an existing profile on DEST"], ["--config-dir DIR", "Import an existing profile directory without setup"], ["--key K.pub", "The ssh public key VMs trust (default: ~/.ssh/id_ed25519.pub, id_ecdsa.pub or id_rsa.pub; else the key your registered hosts use; else another ~/.ssh/id_*.pub)"], ["--host-bin PATH", "boxery-host on the host, when it isn't on its PATH"]], examples: [["A machine you reach over ssh", "boxery host add hornet you@hornet"], ["A second backend on this machine", "boxery host add exe local --backend exe"]], docs: "hosts.md", }, }, - ls: { help: { summary: "list hosts: where each runs and its backend", usage: ["host ls [--json]"], flags: [JSON_FLAG], docs: "hosts.md" } }, - show: { help: { summary: "print a host's profile directory", usage: ["host show NAME"], docs: "hosts.md" } }, - use: { help: { summary: "make NAME the default host", usage: ["host use NAME"], docs: "hosts.md" } }, - rm: { help: { summary: "forget a host (its VMs and profile data stay)", usage: ["host rm NAME"], docs: "hosts.md" } }, + ls: { scope: "registry", noHost: HOST_MGMT, help: { summary: "list hosts: where each runs and its backend", usage: ["host ls [--json]"], flags: [JSON_FLAG], docs: "hosts.md" } }, + show: { scope: "registry", noHost: HOST_MGMT, help: { summary: "print a host's profile directory", usage: ["host show NAME"], docs: "hosts.md" } }, + use: { scope: "registry", noHost: HOST_MGMT, help: { summary: "make NAME the default host", usage: ["host use NAME"], docs: "hosts.md" } }, + rm: { scope: "registry", noHost: HOST_MGMT, help: { summary: "forget a host (its VMs and profile data stay)", usage: ["host rm NAME"], docs: "hosts.md" } }, "build-base": { command: "build-base" }, upgrade: { command: "upgrade-host" }, "proxy-log": { command: "proxy-log" }, @@ -365,7 +391,8 @@ export const COMMANDS = { examples: [["Every host's VMs", "boxery ls"], ["One host's running VMs", "boxery --host hornet ls --running"]], seeAlso: ["patch", "host"], docs: "cli.md#lifecycle", }, - run: async (s, args) => (await import("./ls.mjs")).ls(s, args, { allHosts: false }), + run: async (s, args, how) => (await import("./ls.mjs")).ls(s, args, { allHosts: how.allHosts }), + contract: { allHosts: true }, }, list: { alias: "ls" }, new: { @@ -377,6 +404,7 @@ export const COMMANDS = { }, status: { vm: true }, run: async (s, args) => { needHost(s); await cmdNew(s, args); }, + contract: { terminal: "approval" }, }, start: { help: { group: "vms", summary: "start a stopped VM (pins its ssh host key where it can)", usage: ["start NAME"], seeAlso: ["stop"] }, @@ -421,6 +449,7 @@ export const COMMANDS = { }, status: { vm: true }, run: async (s, args) => { needHost(s); await cmdFork(s, args); }, + contract: { terminal: "approval" }, }, patch: { help: { @@ -501,6 +530,7 @@ export const COMMANDS = { seeAlso: ["run"], }, run: async (s, args) => { needHost(s); await cmdSsh(s, args); }, + contract: { help: "leading", payload: "shell", vmAtHost: true }, }, run: { help: { @@ -512,6 +542,7 @@ export const COMMANDS = { }, status: { vm: true, when: (a) => !runsInBackground(a) }, // --bg returns at once run: async (s, args) => { needHost(s); await cmdRun(s, args); }, + contract: { help: "leading", payload: "argv" }, }, cp: { help: { @@ -537,10 +568,12 @@ export const COMMANDS = { details: ["The session keeps running when you detach (Ctrl-b d) or disconnect. It needs a terminal; for headless work use prompt or run --bg."], seeAlso: ["sessions", "prompt"], }, run: async (s, args) => { needHost(s); await cmdAttach(s, args); }, + contract: { terminal: "stdin", payload: "agent" }, }, prompt: { help: { group: "use", summary: "start a headless pi task in its own tmux session", usage: ['prompt NAME "TASK"'], details: ["It logs to ~/project/.boxery/task-*.log in the VM; attach with boxery attach NAME pi task-…", "pi needs the llm: grant for its provider (llm:chatgpt by default); without it prompt starts nothing and says what to grant."] }, run: async (s, args) => { needHost(s); await cmdPrompt(s, args); }, + contract: { payload: "task" }, }, sessions: { help: { group: "legacy", summary: "list a VM's tmux sessions", usage: ["sessions NAME [--json]"], flags: [JSON_FLAG] }, @@ -613,6 +646,7 @@ export const COMMANDS = { seeAlso: ["revoke", "grants"], docs: "grants.md", }, run: async (s, args) => { needHost(s); await (await grants()).grant(s, args); }, + contract: { terminal: "approval" }, }, revoke: { help: { group: "legacy", summary: "take access away (pushed values are deleted from the VM)", usage: ["revoke NAME SPEC...|all"], docs: "grants.md" }, @@ -625,6 +659,7 @@ export const COMMANDS = { "agent-forward": { help: { group: "legacy", summary: "same as access grant|revoke NAME ssh-agent", usage: ["agent-forward NAME on|off"] }, run: async (s, args) => (await grants()).agentForward(s, args), + contract: { terminal: "approval" }, }, access: { @@ -712,6 +747,8 @@ export const COMMANDS = { version: { help: { group: "more", summary: "controller and host versions; warns when the host is behind", usage: ["version [--json]"], details: ["boxery --version and boxery -V are the same as boxery version."], flags: [JSON_FLAG], seeAlso: ["upgrade-host"] }, run: async (s, args) => cmdVersion(s, args), + local: (args) => cmdVersion(null, args), + contract: { hostOptional: true }, }, "upgrade-host": { help: { @@ -740,7 +777,8 @@ export const COMMANDS = { run: async (s, args) => hostPass(s, ["proxy-log", ...args]), }, help: { - preHost: true, + contract: { scope: "controller", help: "self" }, + local: (args) => showHelp(args), help: { group: "start", summary: "show help for boxery, a command or a family action", list: "help [--all | COMMAND]", usage: ["help [--all | COMMAND [ACTION]]"], details: ["boxery help lists the everyday commands and the command families; help --all adds every family action and every older spelling."], @@ -750,8 +788,21 @@ export const COMMANDS = { }, }; +/** A command's contract, with the defaults for what it doesn't say (an alias is its command's). @param {string} name @returns {Contract} */ +export function contractOf(name) { + const e = COMMANDS[resolve(COMMANDS, name) ?? name]; + return { ...CONTRACT_DEFAULTS, ...(e && "contract" in e ? e.contract : undefined) }; +} +/** What a family action promises: a command's action runs that command's handler, so it has its contract, except + * that an action only recognises a leading help flag (after NAME the words may be prompt text or an agent command); + * a registry action says its own. @param {FamilyAction} a @returns {Contract} */ +export function actionContract(a) { + if (a.scope === "registry") return { ...CONTRACT_DEFAULTS, scope: "registry", help: "leading", noHost: a.noHost }; + return { ...contractOf(/** @type {string} */ (a.command)), help: "leading" }; +} + /** Commands handled before a host is selected. */ -export const PRE_HOST = Object.keys(COMMANDS).filter((n) => "preHost" in COMMANDS[n]); +export const PRE_HOST = Object.keys(COMMANDS).filter((n) => contractOf(n).scope === "controller"); registerCommands(COMMANDS); // ---------------------------------------------------------------- dispatch @@ -774,40 +825,48 @@ async function main(argv) { } } const [first = "help", ...rest] = argv; - const word = ["--version", "-V"].includes(first) ? "version" : first; - // Help needs no host: boxery help [--all | COMMAND [ACTION]], boxery -h, boxery COMMAND [ACTION] --help|-h. - if (["help", "-h", "--help"].includes(word)) return showHelp(rest); + // (-V, --version, -h and --help are the commands version and help: boxery -h COMMAND shows COMMAND's help.) + const flags = /** @type {Record} */ ({ "--version": "version", "-V": "version", "-h": "help", "--help": "help" }); + const word = Object.hasOwn(flags, first) ? flags[first] : first; let cmd = word.startsWith("__") ? word : resolve(COMMANDS, word); if (cmd === null) throw new CliError(unknownCommand(COMMANDS, word), 2); let args = rest; + let contract = contractOf(cmd); + // Help needs no host: boxery help [--all | COMMAND [ACTION]], boxery -h, boxery COMMAND [ACTION] --help|-h. + if (contract.help === "self") return localHandler(cmd)(args); const family = Object.hasOwn(COMMANDS, cmd) ? COMMANDS[cmd] : undefined; if (family && "actions" in family && family.actions) { // A family's action runs another command's handler, with the same host selection below. Everything here // is decided from the words alone: help and mistakes never reach a host, a profile or a grant. const [action, ...tail] = rest; - if (action === undefined && cmd !== "host") throw new CliError(unknownAction(COMMANDS, cmd), 2); + const key = action ?? family.defaultAction; + if (key === undefined) throw new CliError(unknownAction(COMMANDS, cmd), 2); if (["-h", "--help"].includes(action ?? "")) return showHelp([cmd]); - const a = Object.hasOwn(family.actions, action ?? "ls") ? family.actions[action ?? "ls"] : null; + const a = Object.hasOwn(family.actions, key) ? family.actions[key] : null; if (!a) throw new CliError(unknownAction(COMMANDS, cmd, action), 2); - // Only a leading help flag belongs to the action; after NAME it may be prompt text or an agent command. - if (["-h", "--help"].includes(tail[0] ?? "")) return showHelp([cmd, action ?? "ls"]); - if (!a.command) { + const ac = actionContract(a); + if (wantsHelp(ac, tail)) return showHelp([cmd, key]); + if (ac.scope === "registry") { // host's registry actions: this machine's registry, not a host - if (explicit) die("--host does not apply to host management"); + if (explicit && ac.noHost) die(ac.noHost); return hostCommand(rest); } - routedThrough(a.command, cmd, /** @type {string} */ (action)); - cmd = a.command; + routedThrough(/** @type {string} */ (a.command), cmd, key); + cmd = /** @type {string} */ (a.command); + contract = ac; args = a.args ? a.args(tail) : tail; - } else if (wantsHelp(cmd, args)) return showHelp([cmd]); - if (cmd === "setup") { if (explicit) die("setup takes --name NAME, not --host"); return setupNamed(args); } + } else if (wantsHelp(contract, args)) return showHelp([cmd]); + if (contract.scope === "controller") { + if (explicit && contract.noHost) die(contract.noHost); + return localHandler(cmd)(args); + } // Internal (tests): __skew CTL_VERSION CTL_DESCRIBE HOST_VERSION HOST_DESCRIBE [HOST_NAME] if (cmd === "__skew") { const n = skewNote({ version: args[0], describe: args[1] || null }, { version: args[2], describe: args[3] || null }, args[4] ?? ""); if (n) say(n); return; } // Before setup there is no host to select; version still reports the controller. - if (cmd === "version" && !explicit && defaultHost() == null) return cmdVersion(null, args); + if (contract.hostOptional && !explicit && defaultHost() == null) return localHandler(cmd)(args); // SSH's VM@HOST is CLI shorthand, not an SSH user or a new destination. Resolve the registered profile // before reading any config or reapplying grants; a conflicting selector must never reach either host. - if (cmd === "ssh" && args[0]?.includes("@")) { + if (contract.vmAtHost && args[0]?.includes("@")) { const [vm, host, ...extra] = args[0].split("@"); if (!VALID_VM.test(vm) || !VALID_VM.test(host ?? "") || extra.length) die(`invalid SSH target: ${args[0]} (use NAME@HOST; names: lowercase letters, digits and hyphens, starting with a letter, at most 31 characters)`); if (explicit && explicit !== host) die(`SSH target host ${host} conflicts with --host ${explicit}; use one host or matching selectors`); @@ -833,22 +892,29 @@ async function main(argv) { } const entry = COMMANDS[cmd]; // Plain `ls` lists every host; --host NAME ls just that one. - const command = cmd === "ls" && !explicit ? async (/** @type {Selected} */ s, /** @type {string[]} */ a) => (await import("./ls.mjs")).ls(s, a, { allHosts: true }) - : "run" in entry ? entry.run : undefined; + const command = "run" in entry ? entry.run : undefined; if (!command) throw new CliError(unknownCommand(COMMANDS, word), 2); const s = await select(name, dir); await withHost(s.host, async () => { await refreshSshConfig({ host: s.host, warn: note }); - await reporting(cmd, "status" in entry ? entry.status : undefined, args, () => command(s, args)); + await reporting(cmd, "status" in entry ? entry.status : undefined, args, () => command(s, args, { allHosts: !!contract.allHosts && !explicit })); }); } -/** The legacy command help convention: a leading flag, or alone after one word (snap demo --help). - * Keep it for existing spellings; new family actions only recognise a leading help flag. - * run and ssh always own their remote payload. @param {string} command @param {string[]} args */ -function wantsHelp(command, args) { +/** The command's own handler for the words with no host selected (a `controller` command, or version without a host). + * @param {string} cmd @returns {(args: string[]) => unknown} */ +function localHandler(cmd) { + const e = COMMANDS[cmd]; + if (!("local" in e) || !e.local) throw new Error(`internal: ${cmd} has no local handler`); + return e.local; +} + +/** Is this a request for help or payload, by the contract's convention (Contract.help)? The legacy one is kept for + * existing spellings; family actions (and run and ssh, which own their remote payload) only recognise a leading + * help flag. @param {Contract} contract @param {string[]} args */ +function wantsHelp(contract, args) { const help = (/** @type {string | undefined} */ w) => w === "-h" || w === "--help"; - return help(args[0]) || (command !== "run" && command !== "ssh" && args.length === 2 && /^[a-z]+$/.test(args[0]) && help(args[1])); + return help(args[0]) || (contract.help === "legacy" && args.length === 2 && /^[a-z]+$/.test(args[0]) && help(args[1])); } /** boxery help [--all | COMMAND [ACTION]]: the same pages as COMMAND --help. @param {string[]} words */ diff --git a/test/cli-contracts.test.mjs b/test/cli-contracts.test.mjs new file mode 100644 index 0000000..bba0388 --- /dev/null +++ b/test/cli-contracts.test.mjs @@ -0,0 +1,200 @@ +// The command contracts in controller/cli.mjs's COMMANDS (Contract: scope, help convention, payload, terminal), +// and that the dispatch reads them: routing is checked word by word against the real CLI with no host +// configured (an empty BOXERY_HOME), so nothing here reaches a host, a profile or a grant. End-to-end behaviour +// with stub hosts is test/cli-families.test.mjs. +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { fileURLToPath } from "node:url"; + +const ROOT = fileURLToPath(new URL("..", import.meta.url)); +const home = mkdtempSync(path.join(tmpdir(), "boxery-contracts-")); +after(() => rmSync(home, { recursive: true, force: true })); +const { COMMANDS, PRE_HOST, actionContract, contractOf } = await import("../controller/cli.mjs"); + +/** The controller with an empty BOXERY_HOME: no default host, none registered. @param {string[]} args */ +function boxery(...args) { + const r = spawnSync(path.join(ROOT, "controller/boxery"), args, { encoding: "utf8", input: "", timeout: 10_000, env: { ...process.env, HOME: path.join(home, "home"), BOXERY_HOME: home, SSH_AUTH_SOCK: "", NO_COLOR: "1" } }); + return { code: r.status, out: r.stdout, err: r.stderr }; +} +const NO_HOST = /no host configured/; + +/** Every command that has its own entry (not an alias), with its contract. */ +const commands = Object.entries(COMMANDS).flatMap(([name, e]) => ("alias" in e ? [] : [/** @type {const} */ ([name, e, contractOf(name)])])); +/** Every family action: [family, action, definition, its contract]. */ +const actions = Object.entries(COMMANDS).flatMap(([f, e]) => ("actions" in e && e.actions ? Object.entries(e.actions).map(([a, x]) => /** @type {const} */ ([f, a, x, actionContract(x)])) : [])); +const SCOPES = ["host", "controller", "registry"], HELP = ["legacy", "leading", "self"], PAYLOAD = ["argv", "shell", "task", "agent"], TERMINAL = ["stdin", "approval"]; + +test("every command has exactly one way to run, and a contract that says only what it means", () => { + for (const [name, e, c] of commands) { + const ways = ["run", "local", "actions"].filter((k) => k in e && /** @type {Record} */ (e)[k]); + if (c.scope === "controller") assert.deepEqual(ways, ["local"], `${name}: a controller command runs only its local handler`); + else if ("actions" in e) assert.deepEqual(ways, ["actions"], `${name}: a family has actions, not a handler`); + else assert.deepEqual(ways.filter((w) => w === "run"), ["run"], `${name}: has no handler`); + assert.ok(SCOPES.includes(c.scope) && c.scope !== "registry", `${name}: scope ${c.scope}`); + assert.ok(HELP.includes(c.help), `${name}: help ${c.help}`); + assert.ok(!c.payload || PAYLOAD.includes(c.payload), `${name}: payload ${c.payload}`); + assert.ok(!c.terminal || TERMINAL.includes(c.terminal), `${name}: terminal ${c.terminal}`); + if (c.scope === "controller") assert.ok(c.noHost || c.help === "self", `${name}: a controller command either refuses --host or ignores it knowingly (help renders anything)`); + else assert.equal(c.noHost, undefined, `${name}: only a command with no host to select refuses --host`); + if (c.hostOptional) assert.ok("local" in e && "run" in e, `${name}: hostOptional needs both a local handler and a host handler`); + if (c.allHosts) assert.ok("run" in e, `${name}: allHosts needs a handler to tell`); + if (c.help === "leading") assert.ok(c.payload === "argv" || c.payload === "shell", `${name}: it owns the words after its name, so it declares a payload`); + if (c.vmAtHost) assert.ok(c.payload, `${name}: NAME@HOST belongs to a command with payload`); + if ("actions" in e) assert.equal(Object.keys(c).filter((k) => !["scope", "help"].includes(k)).length, 0, `${name}: a family's actions carry the contracts`); + } + assert.deepEqual(contractOf("list"), contractOf("ls"), "an alias has its command's contract"); +}); + +test("every family action runs a host command, or declares itself a registry action with its refusal", () => { + for (const [f, a, x, c] of actions) { + const label = `${f} ${a}`; + if (x.scope === "registry") { + assert.equal(x.command, undefined, `${label}: a registry action has no command`); + assert.ok(x.noHost, `${label}: a registry action says what --host gets`); + assert.equal(c.scope, "registry"); + assert.equal(f, "host", `${label}: only host manages the registry`); + } else { + assert.ok(x.command && Object.hasOwn(COMMANDS, x.command), `${label}: runs ${x.command}`); + assert.equal(x.noHost, undefined, `${label}: it follows its command's host selection`); + const target = COMMANDS[x.command]; + assert.ok("run" in target && target.run, `${label}: ${x.command} has no handler`); + assert.equal(contractOf(x.command).scope, "host", `${label}: ${x.command} is not a host command`); + assert.deepEqual({ ...c, help: undefined }, { ...contractOf(x.command), help: undefined }, `${label}: inherits ${x.command}'s contract`); + } + assert.equal(c.help, "leading", `${label}: an action only recognises a leading help flag`); + } + for (const [f, e] of Object.entries(COMMANDS)) { + if (!("actions" in e) || !e.actions) continue; + if ("defaultAction" in e && e.defaultAction !== undefined) assert.ok(Object.hasOwn(e.actions, e.defaultAction), `${f}: unknown default action ${e.defaultAction}`); + assert.deepEqual(Object.entries(e.actions).filter(([, x]) => x.scope === "registry").length > 0, f === "host", `${f}: registry actions belong to host`); + } + assert.ok("actions" in COMMANDS.host); + assert.equal(COMMANDS.host.defaultAction, "ls", "a bare `boxery host` lists hosts"); +}); + +test("root flag aliases never resolve inherited object properties", () => { + for (const word of ["constructor", "toString", "hasOwnProperty"]) { + const r = boxery(word); + assert.equal(r.code, 2, r.err); + assert.match(r.err, new RegExp(`unknown command: ${word}`)); + assert.equal(r.out, ""); + } +}); + +test("PRE_HOST is the controller-scope commands: help and setup", () => { + assert.deepEqual([...PRE_HOST].sort(), commands.filter(([, , c]) => c.scope === "controller").map(([n]) => n).sort()); + assert.deepEqual([...PRE_HOST].sort(), ["help", "setup"]); +}); + +test("every host-scope command is dispatched to a host: --host ghost reaches the host lookup, whatever the words", () => { + for (const [name, e, c] of commands) { + if (c.scope !== "host" || "actions" in e) continue; + const r = boxery("--host", "ghost", name, "demo"); + assert.equal(r.err, "boxery: unknown host: ghost\n", `${name}: ${r.err}`); + assert.equal(r.out, ""); + } + for (const [f, a, x, c] of actions) { + if (c.scope === "registry") continue; + const r = boxery("--host", "ghost", f, a, "demo"); + assert.equal(r.err, "boxery: unknown host: ghost\n", `${f} ${a} (${x.command}): ${r.err}`); + } +}); + +test("registry actions refuse --host with the message they declare, before any host lookup", () => { + for (const [f, a, x, c] of actions) { + if (c.scope !== "registry") continue; + const r = boxery("--host", "ghost", f, a); + assert.equal(r.err, `boxery: ${x.noHost}\n`, `${f} ${a}`); + assert.equal(r.code, 1); + } + assert.equal(boxery("--host", "ghost", "host").err, "boxery: --host does not apply to host management\n", "bare host is host ls"); + // ...and a controller command refuses it too, except help, which has nothing to select + for (const [name, , c] of commands) { + if (c.scope !== "controller") continue; + const r = boxery("--host", "ghost", name); + if (c.noHost) assert.equal(r.err, `boxery: ${c.noHost}\n`, name); + else assert.equal(r.code, 0, `${name}: ${r.err}`); + } +}); + +test("a bare `boxery host` is `host ls`", () => { + const ls = boxery("host", "ls"), bare = boxery("host"); + assert.equal(ls.code, 0, ls.err); + assert.deepEqual(bare, ls); + assert.deepEqual(boxery("host", "--help"), boxery("host", "-h")); + assert.equal(boxery("snapshot").code, 2, "a family without a default action asks for one"); +}); + +test("the help convention is the contract's: legacy shows help after one word, leading owns its payload", () => { + for (const [name, e, c] of commands) { + if ("actions" in e || c.help === "self") continue; + const first = boxery(name, "--help"); + assert.match(first.out, new RegExp(`^Usage:\\n boxery ${name}\\b`), `${name} --help`); + const after = boxery(name, "demo", "--help"); + if (c.help === "legacy") assert.equal(after.out, first.out, `${name} demo --help is help (the older convention)`); + else { + assert.equal(after.out, "", `${name} demo --help: the words are the command's, not a help request`); + assert.match(after.err, NO_HOST, name); + } + } + for (const [f, a, , c] of actions) { + if (c.scope === "registry") continue; + const r = boxery(f, a, "demo", "--help"); + assert.doesNotMatch(r.out, /^Usage:/m, `${f} ${a} demo --help is not help`); + assert.match(boxery(f, a, "--help").out, new RegExp(`^Usage:\\n boxery ${f} ${a}\\b`), `${f} ${a} --help`); + } + // help itself: nothing after it is a help flag, so its own --help is an unknown command, as it always was + assert.equal(boxery("help", "--help").code, 2); + assert.equal(boxery("help", "help").out, boxery("--help", "help").out); +}); + +test("NAME@HOST is the contract's: only vmAtHost commands select a host from their first word", () => { + for (const [name, e, c] of commands) { + if (c.scope !== "host" || "actions" in e) continue; + const r = boxery(name, "demo@lab"); + if (c.vmAtHost) assert.equal(r.err, "boxery: unknown host: lab\n", name); + else assert.doesNotMatch(r.err, /unknown host: lab/, `${name} must leave demo@lab alone: ${r.err}`); + } + assert.match(boxery("--host", "ghost", "ssh", "demo@lab").err, /SSH target host lab conflicts with --host ghost/); + assert.match(boxery("ssh", "demo@Bad").err, /invalid SSH target/); +}); + +test("version needs no host (hostOptional) but follows --host when one is given", () => { + assert.equal(contractOf("version").hostOptional, true); + for (const flag of ["version", "--version", "-V"]) { + const r = boxery(flag); + assert.equal(r.code, 0, r.err); + assert.match(r.out, /^controller /); + } + assert.equal(JSON.parse(boxery("version", "--json").out).host, null); + assert.equal(boxery("--host", "ghost", "version").err, "boxery: unknown host: ghost\n"); + assert.equal(boxery("version", "--bogus").code, 2); + for (const [name, , c] of commands) if (name !== "version") assert.ok(!c.hostOptional, `${name}: only version runs without a host`); +}); + +test("approval and terminal contracts name the commands that reach grant approval or need a terminal", () => { + const src = readFileSync(path.join(ROOT, "controller/cli.mjs"), "utf8"); + /** The text of function NAME in the source, by brace matching. @param {string} name */ + const body = (name) => { + const m = new RegExp(`function ${name}\\b[^{]*\\{`).exec(src); + if (!m) return ""; + let i = m.index + m[0].length, d = 1; + for (; i < src.length && d; i++) { if (src[i] === "{") d++; else if (src[i] === "}") d--; } + return src.slice(m.index, i); + }; + /** A handler's source with the cmd* functions it calls. @param {string} name */ + const code = (name) => { + const e = COMMANDS[name]; + let t = "run" in e && e.run ? e.run.toString() : ""; + for (const [, f] of t.matchAll(/\b(cmd[A-Z]\w*)\(/g)) t += body(f); + return t; + }; + const asksAPerson = commands.filter(([n, e]) => "run" in e && /\b(?:confirm|confirmCopy|grant|agentForward)\(/.test(code(n))).map(([n]) => n).sort(); + assert.deepEqual(commands.filter(([, , c]) => c.terminal === "approval").map(([n]) => n).sort(), asksAPerson, "a command that reaches grant approval says so (terminal: \"approval\")"); + assert.deepEqual(commands.filter(([, , c]) => c.terminal === "stdin").map(([n]) => n), ["attach"]); + assert.match(body("cmdAttach"), /contractOf\("attach"\)\.terminal === "stdin"/, "attach's terminal check reads its contract"); +}); From 6ceab227fddabf11f0d19b6d052ff2eebc8afb2d Mon Sep 17 00:00:00 2001 From: Ben Vinegar <2153+benvinegar@users.noreply.github.com> Date: Sun, 8 Nov 2026 21:16:15 -0500 Subject: [PATCH 2/3] fix(controller): render canonical follow-up commands (stack 2/4) (#249) --- CONTRIBUTING.md | 2 + controller/cli.mjs | 42 ++++++------- controller/grants.mjs | 6 +- controller/hosts.mjs | 4 +- controller/jobs.mjs | 6 +- controller/leases.mjs | 4 +- controller/lib.mjs | 7 ++- controller/ls.mjs | 4 +- controller/usage.mjs | 4 ++ core/grants.mjs | 12 +++- docs/cli.md | 4 +- help/index.mjs | 16 +++++ test/cli-hints.test.mjs | 89 +++++++++++++++++++++++++++ test/grants.test.mjs | 4 +- test/help-drift.test.mjs | 4 +- test/shell/common/controller-local.sh | 2 +- 16 files changed, 167 insertions(+), 43 deletions(-) create mode 100644 test/cli-hints.test.mjs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 48d0551..d4c2032 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -47,6 +47,8 @@ Types: the code is plain JavaScript typed with JSDoc comments (`/** @param {stri `boxery help`, `boxery help --all` and `boxery COMMAND [ACTION] --help` are rendered (`help/index.mjs`, through `controller/usage.mjs`) from the `help` each command carries in `controller/cli.mjs`'s `COMMANDS` table, next to its handler: a new command needs its help to exist at all. boxery-host's help is the same kind of table, in `host/help.mjs` (its handlers are in `host/cli.mjs`, which refuses to load with a command that has no help). Write the summary as one short line; longer explanations go in `details`, `flags` and `examples`, which only its own `--help` shows. `test/help-drift.test.mjs` keeps it honest: a command's help must list exactly the `--flags` its code compares against (flags the host parses are checked against `boxery-host help`), examples must use real commands and documented flags, the same holds for every `boxery-host` command, `docs` anchors must exist, the command reference in `docs/cli.md` must be current (`npm run docs:cli` regenerates it), and `boxery help` and `boxery help --all` are pinned in `test/fixtures/boxery-help.txt` and `boxery-help-all.txt` (`BOXERY_UPDATE_GOLDEN=1 node --test test/help-drift.test.mjs` rewrites it after you review the change). +Controller-owned follow-up commands use `hint(COMMAND, ARGS, {host})` from `controller/lib.mjs`: it validates the canonical command/family action against `COMMANDS`, shell-quotes arguments and retains the explicit host. Name the action explicitly (`access ls` or `access apply`, not the ambiguous legacy `grants`); keep placeholders outside argument arrays. Do not rewrite subprocess output or import controller helpers into core/MCP/pi. Shared approval messages and `BOXERY_CLI` remain compatible. + `test/cli-contracts.test.mjs` checks contracts and their inheritance, scope routing, help boundaries, optional hosts and SSH-qualified targets against an unconfigured temporary home. `test/cli-families.test.mjs` runs the real CLI against a stub `boxery-host` and a stub `ssh` in temporary profiles, and checks that every family action and its older spelling produce the same output, exit status, ssh and host calls and saved state; that help and mistakes touch no host, profile or grant; that `host`'s registry actions refuse `--host` while its maintenance actions follow it; that `access ls` is read-only; and that grant approval, grant stores and leases stay per profile. Add a pair there when you add an action. diff --git a/controller/cli.mjs b/controller/cli.mjs index a9dabfb..46683e0 100644 --- a/controller/cli.mjs +++ b/controller/cli.mjs @@ -12,7 +12,7 @@ import { refreshSshConfig } from "../core/profile.mjs"; import { literal, literalArgs, remotePath } from "../core/ssh-config.mjs"; import { controllerVersion, hostVersion, skewNote, upgradeHint } from "../core/versions.mjs"; import { backendCommand, hostCommand, setupNamed } from "./hosts.mjs"; -import { BOXERY, CliError, USAGE, VALID_SNAP, VALID_VM, commandLine, die, invokedAs, usage, hasRawBytes, hostFailed, hostPass, inherit, needHost, needVm, note, rawTail, say, select, vmSsh, vmSshCapture, warn } from "./lib.mjs"; +import { CliError, USAGE, VALID_SNAP, VALID_VM, commandLine, die, invokedAs, usage, hasRawBytes, hint, hostFailed, hostPass, inherit, needHost, needVm, note, rawTail, say, select, vmSsh, vmSshCapture, warn } from "./lib.mjs"; import { reporting } from "./status.mjs"; import { actionHelp, registerCommands, renderCommand, renderFamily, renderTop, resolve, routedThrough, unknownAction, unknownCommand } from "./usage.mjs"; /** @import { Selected } from "./lib.mjs" */ @@ -104,19 +104,19 @@ async function cmdRun(s, args) { /** @type {Buffer} */ let cwdRaw = Buffer.alloc(0); for (; i < args.length; i++) { - if (args[i] === "--cwd") { if (!args[i + 1]) runUsage(); cwd = args[++i]; cwdRaw = raw[i]; } + if (args[i] === "--cwd") { if (!args[i + 1]) runUsage(name); cwd = args[++i]; cwdRaw = raw[i]; } else if (args[i] === "--bg") bg = true; else if (args[i] === "--") { i++; break; } else break; } const argv = args.slice(i), argvRaw = raw.slice(i); - if (!argv.length) runUsage(); + if (!argv.length) runUsage(name); if (bg) { await (await grants()).reapplyQuiet(s, name); const { startJob } = await import("./jobs.mjs"); const id = await startJob(s, name, argvRaw, cwd ? cwdRaw : null); say(id); - note(`boxery: started ${id} on ${name} logs: ${BOXERY} logs ${name} ${id} -f wait: ${BOXERY} wait ${name} ${id}`); + note(`boxery: started ${id} on ${name} logs: ${hint("job logs", [name, id, "-f"])} wait: ${hint("job wait", [name, id])}`); literalNote(name, argv); return; } @@ -128,7 +128,7 @@ async function cmdRun(s, args) { if (hasRawBytes([...argvRaw, cwdRaw])) line = `eval "$(printf %s ${rawLine(argvRaw, cwd ? cwdRaw : null).toString("base64")} | base64 -d)"`; const rc = await vmSsh(s, [`${name}.boxery`, line]); // The usual mistake is a whole command line in one argument; say how to run it instead. - if (rc === 127 && /\s/.test(argv[0])) warn(`hint: run takes the command and its arguments separately; for a shell line use: ${BOXERY} run ${name} bash -c ${literal(argv[0])}`); + if (rc === 127 && /\s/.test(argv[0])) warn(`hint: run takes the command and its arguments separately; for a shell line use: ${hint("run", [name, "bash", "-c", argv[0]])}`); literalNote(name, argv); if (rc) throw new CliError("", rc); } @@ -146,8 +146,8 @@ export function runsInBackground(args) { return false; } -/** @returns {never} */ -const runUsage = () => usage("run", { hint: "a shell line: ... bash -c 'A | B'; see: boxery run --help" }); +/** @param {string} name @returns {never} */ +const runUsage = (name) => usage("run", { hint: `a shell line: ${hint("run", [name, "bash", "-c", "A | B"])}; see: ${hint("help", ["run"])}` }); /** run's remote command line as bytes, for arguments that aren't UTF-8: the same line, built from bytes. * @param {Buffer[]} argv @param {Buffer | null} cwd */ @@ -168,7 +168,7 @@ function rawLine(argv, cwd) { function literalNote(name, argv) { if (["bash", "sh", "dash", "zsh", "awk", "gawk", "mawk", "perl", "jq", "sed", "python", "python3", "node", "ruby"].includes(path.basename(argv[0]))) return; const a = argv.find((x) => x === "~" || x.startsWith("~/") || /\$[A-Z]/.test(x) || x.includes("${")); - if (a !== undefined) warn(`note: ${literal(a)} was passed literally (run does not expand ~ or $VAR); to expand it in the VM: ${BOXERY} run ${name} bash -c '…'`); + if (a !== undefined) warn(`note: ${literal(a)} was passed literally (run does not expand ~ or $VAR); to expand it in the VM: ${hint("run", [name, "bash", "-c", "…"])}`); } /** attach NAME [pi|opencode|shell] [session] @param {Selected} s @param {string[]} args @returns {Promise} */ @@ -178,7 +178,7 @@ async function cmdAttach(s, [name = "", tool = "pi", sess = tool]) { if (!Object.hasOwn(run, tool)) die(`unknown agent: ${tool} (pi, opencode or shell)`, 2); if (!/^[A-Za-z0-9._-]+$/.test(sess)) die(`invalid session name: ${sess}`); // (Without one, tmux says only "open terminal failed: not a terminal".) - if (contractOf("attach").terminal === "stdin" && !process.stdin.isTTY) die(`attach needs a terminal; for headless work use ${BOXERY} prompt ${name} "TASK" or ${BOXERY} run --bg ${name} CMD`); + if (contractOf("attach").terminal === "stdin" && !process.stdin.isTTY) die(`attach needs a terminal; for headless work use ${hint("prompt", [name])} "TASK" or ${hint("run", ["--bg", name])} CMD`); await (await grants()).reapplyQuiet(s, name); // tmux keeps the agent alive when you disconnect (laptop sleep, network change). const rc = await vmSsh(s, ["-t", `${name}.boxery`, `cd ~/project 2>/dev/null; tmux has-session -t '${sess}' 2>/dev/null || tmux new-session -d -s '${sess}' -c ~/project "bash -lc '${run[tool]}; exec bash -l'"; exec tmux attach -t '${sess}'`]); @@ -238,7 +238,7 @@ async function cmdPrompt(s, [name = "", ...words]) { printf '%s\\n' '#!/bin/bash -l' 'cd ~/project' 'pi -p "$(cat .boxery/${id}.prompt)" &1 | tee .boxery/${id}.log' 'echo "[boxery] task finished (exit \${PIPESTATUS[0]})" | tee -a .boxery/${id}.log' 'exec bash -l' > $d/${id}.sh chmod +x $d/${id}.sh; tmux new-session -d -s ${id} -c ~/project $d/${id}.sh`; await exitWith(vmSsh(s, [`${name}.boxery`, script])); - say(`started ${id} on ${name} — watch: ${BOXERY} attach ${name} pi ${id} log: ${BOXERY} run ${name} cat .boxery/${id}.log`); + say(`started ${id} on ${name} — watch: ${hint("attach", [name, "pi", id])} log: ${hint("run", [name, "cat", `.boxery/${id}.log`])}`); } /** A VM has no LLM access until it is granted, and pi without it fails at once: say so before starting a @@ -251,7 +251,7 @@ async function needPiGrant(s, name) { if (r.code) throw new CliError("", r.code); // (ssh said why) const [settings, projectSettings, models] = r.stdout.split("\x1e").slice(-3); const spec = (await import("../core/grants.mjs")).missingPiGrant(name, { settings, projectSettings, models }); - if (spec) die(`pi in ${name} needs ${spec}, which ${name} has not been granted; grant it first: ${BOXERY} grant ${name} ${spec}`); + if (spec) die(`pi in ${name} needs ${spec}, which ${name} has not been granted; grant it first: ${hint("access grant", [name, spec])}`); } /** cp FROM TO: vm_copy's own code. Needs only the profile's ssh_config, not the host. @param {Selected} s @param {string[]} args @returns {Promise} */ @@ -343,7 +343,7 @@ export const COMMANDS = { details: ["OpenShell has its own options (gateway, image, policy, providers): boxery setup local --backend openshell --help."], flags: [["--name NAME", "Register the host as NAME (default: local, or the host part of user@host)"], ["--key K.pub", "The ssh public key VMs trust (default: ~/.ssh/id_ed25519.pub, id_ecdsa.pub or id_rsa.pub; else the key your registered hosts use; else another ~/.ssh/id_*.pub)"], ["--host-bin PATH", "boxery-host on the host, when it isn't on its PATH"], ["--profile P", "Use (or create, with --backend) profile P on the host"], ["--backend B", "The backend for a new profile (boxery host backends lists them)"]], examples: [["A Linux box you reach over ssh", "boxery setup you@my-host"], ["This machine", "boxery setup local"]], - seeAlso: ["host", "build-base", "backends"], docs: "install.md", + seeAlso: ["host", "host build-base", "host backends"], docs: "install.md", }, }, host: { @@ -398,7 +398,7 @@ export const COMMANDS = { new: { help: { group: "vms", summary: "create a VM", usage: ["new NAME [--shape S] [--cpus N --mem MiB --disk GiB] [--headless [--layers L,...]] [--grant SPEC]... [--agent-forward]", "new NAME --from VM@SNAP"], - flags: [...SIZE_FLAGS, ["--headless", "No desktop (shell and agents only); needs no build-base"], ["--layers L,...", "Extra image layers for a headless VM (github-runner)"], ["--from VM@SNAP", "Start from a snapshot (boxery snapshot images lists them)"], ["--grant SPEC", "Grant access at creation (asks first; see boxery grant)"], ["--agent-forward", "Same as --grant ssh-agent"]], + flags: [...SIZE_FLAGS, ["--headless", "No desktop (shell and agents only); needs no build-base"], ["--layers L,...", "Extra image layers for a headless VM (github-runner)"], ["--from VM@SNAP", "Start from a snapshot (boxery snapshot images lists them)"], ["--grant SPEC", "Grant access at creation (asks first; see boxery access grant)"], ["--agent-forward", "Same as --grant ssh-agent"]], examples: [["A desktop VM", "boxery new demo"], ["A larger, headless one", "boxery new ci-1 --headless --shape large"], ["A GitHub Actions runner VM", "boxery new runner-1 --headless --layers github-runner"]], seeAlso: ["shapes", "fork", "rm"], docs: "cli.md#lifecycle", }, @@ -445,7 +445,7 @@ export const COMMANDS = { group: "vms", summary: "copy a VM (running or not) into new VMs, ~10 s", usage: ["fork SRC DST... [--grants] [--shape S] [--cpus N --mem MiB --disk GiB]"], details: ["Each fork has SRC's disk (not its processes) with its own hostname, LLM token, ssh keys and network identity, and SRC's size unless --shape or size flags say otherwise.", CAPTURE_NOTE], flags: [["--grants", "Give the forks SRC's grants too (asks for each)"], ...SIZE_FLAGS], - examples: [["Two copies to try two approaches", "boxery fork demo try-a try-b"]], seeAlso: ["snap", "new"], docs: "cli.md#snapshots-and-forks", + examples: [["Two copies to try two approaches", "boxery fork demo try-a try-b"]], seeAlso: ["snapshot create", "new"], docs: "cli.md#snapshots-and-forks", }, status: { vm: true }, run: async (s, args) => { needHost(s); await cmdFork(s, args); }, @@ -480,7 +480,7 @@ export const COMMANDS = { // ------------------------------------------------ snapshots snap: { - help: { group: "legacy", summary: "snapshot a VM's disk (Lima restarts a running VM)", usage: ["snap NAME [SNAP]"], details: [CAPTURE_NOTE], seeAlso: ["snaps", "revert", "snap-rm"], docs: "cli.md#snapshots-and-forks" }, + help: { group: "legacy", summary: "snapshot a VM's disk (Lima restarts a running VM)", usage: ["snap NAME [SNAP]"], details: [CAPTURE_NOTE], seeAlso: ["snapshot ls", "snapshot restore", "snapshot rm"], docs: "cli.md#snapshots-and-forks" }, status: { vm: true }, run: async (s, args) => { needHost(s); @@ -538,7 +538,7 @@ export const COMMANDS = { details: [RUN_RULES, "The exit code is the command's. A relative --cwd is under ~/project; ~/ expands in the VM; absolute paths are used as is."], flags: [["--bg", "Run as a background job; prints the job id (see boxery job ls)"], ["--cwd DIR", "Working directory"], ["--", "End run's options"]], examples: [["Args are passed as-is: quotes, $, *, ; stay literal", "boxery run demo pnpm test"], ["In ~/project/modem", "boxery run demo --cwd modem git log -1"], ["Pipes, ~, $VAR and globs need bash -c", "boxery run demo bash -c 'ls ~ | wc -l; echo $HOME'"], ["Not this: one argument is one command name (fails with a hint)", "boxery run demo 'make test'"]], - seeAlso: ["jobs", "ssh"], docs: "cli.md#shell-and-in-vm-agents", + seeAlso: ["job ls", "ssh"], docs: "cli.md#shell-and-in-vm-agents", }, status: { vm: true, when: (a) => !runsInBackground(a) }, // --bg returns at once run: async (s, args) => { needHost(s); await cmdRun(s, args); }, @@ -565,7 +565,7 @@ export const COMMANDS = { attach: { help: { group: "use", summary: "attach to an agent in a persistent tmux session", list: "attach NAME [AGENT]", usage: ["attach NAME [pi|opencode|shell] [SESSION]"], - details: ["The session keeps running when you detach (Ctrl-b d) or disconnect. It needs a terminal; for headless work use prompt or run --bg."], seeAlso: ["sessions", "prompt"], + details: ["The session keeps running when you detach (Ctrl-b d) or disconnect. It needs a terminal; for headless work use prompt or run --bg."], seeAlso: ["agent ls", "prompt"], }, run: async (s, args) => { needHost(s); await cmdAttach(s, args); }, contract: { terminal: "stdin", payload: "agent" }, @@ -596,7 +596,7 @@ export const COMMANDS = { group: "legacy", summary: "list background jobs (run --bg starts one)", usage: ["jobs NAME [--json]", "jobs NAME --prune [--older-than 7d] [--json]"], details: ["States: running, exited, or lost (it stopped without recording an exit code). exited+ means it left processes running."], flags: [JSON_FLAG, ["--prune", "Delete finished jobs and their logs"], ["--older-than D", "With --prune: only jobs older than D (e.g. 7d)"]], - seeAlso: ["run", "logs", "wait", "kill"], docs: "cli.md#background-command-jobs", + seeAlso: ["run", "job logs", "job wait", "job kill"], docs: "cli.md#background-command-jobs", }, run: async (s, args) => { needHost(s); await (await import("./jobs.mjs")).jobs(s, args); }, }, @@ -643,7 +643,7 @@ export const COMMANDS = { details: ["SPEC is one of:\n llm:chatgpt|openai|anthropic|ollama LLM access (VMs have none without it)\n github [--readonly] GitHub over HTTPS; the token stays here\n http:HOST --cmd CMD [--auth bearer|basic:USER|header:NAME] [--readonly]\n an HTTP API; the secret never enters the VM\n ssh-agent forward your ssh agent\n env:VAR [--cmd CMD] push an environment variable\n file:LOCAL[=REMOTE] push a file", "Adding access prompts on your terminal and defaults to No."], flags: [["--cmd CMD", "env: and http: grants: the command on this machine that prints the secret"], ["--auth A", "http: grants: bearer (default), basic:USER or header:NAME"], ["--readonly", "http: and github grants: GET/HEAD and git fetch only"]], examples: [["Let the VM use your Anthropic subscription", "boxery grant demo llm:anthropic"], ["Read-only GitHub", "boxery grant demo github --readonly"]], - seeAlso: ["revoke", "grants"], docs: "grants.md", + seeAlso: ["access revoke", "access ls", "access apply"], docs: "grants.md", }, run: async (s, args) => { needHost(s); await (await grants()).grant(s, args); }, contract: { terminal: "approval" }, @@ -695,7 +695,7 @@ export const COMMANDS = { help: { group: "legacy", summary: "lease a VM from the shared pool (prints NAME LEASE_ID)", usage: ["acquire [--ttl S] [--wait S] [--holder H]"], flags: [["--ttl S", "Lease length in seconds (default 1800)"], ["--wait S", "Wait up to S seconds for a free VM"], ["--holder H", "Who holds the lease, as the host shows it (default: user@machine)"]], - seeAlso: ["renew", "release", "leases"], docs: "pool.md", + seeAlso: ["lease renew", "lease release", "lease ls"], docs: "pool.md", }, status: { when: (a) => a.some((w, i) => w === "--wait" && Number(a[i + 1]) > 0) }, // only waiting for a free VM takes a while run: async (s, args) => { needHost(s); await (await import("./leases.mjs")).leaseCommand(s, "acquire", args); }, @@ -745,7 +745,7 @@ export const COMMANDS = { // ------------------------------------------------ host & diagnostics version: { - help: { group: "more", summary: "controller and host versions; warns when the host is behind", usage: ["version [--json]"], details: ["boxery --version and boxery -V are the same as boxery version."], flags: [JSON_FLAG], seeAlso: ["upgrade-host"] }, + help: { group: "more", summary: "controller and host versions; warns when the host is behind", usage: ["version [--json]"], details: ["boxery --version and boxery -V are the same as boxery version."], flags: [JSON_FLAG], seeAlso: ["host upgrade"] }, run: async (s, args) => cmdVersion(s, args), local: (args) => cmdVersion(null, args), contract: { hostOptional: true }, diff --git a/controller/grants.mjs b/controller/grants.mjs index 679a64d..83ebb9a 100644 --- a/controller/grants.mjs +++ b/controller/grants.mjs @@ -6,9 +6,9 @@ import { closeSync, openSync, readFileSync, readSync, writeSync } from "node:fs" import path from "node:path"; import { formatGrants, hostBackend, vmGrants } from "../core/boxery-core.mjs"; import { parseGrantArgs } from "../core/grant-approval.mjs"; -import { addGrants, applyGrants, grantCommand, grantPrompt, listGrants, revokeGrants, storedSpecs } from "../core/grants.mjs"; +import { addGrants, applyGrants, grantArgs, grantPrompt, listGrants, revokeGrants, storedSpecs } from "../core/grants.mjs"; import { reapplyPushed } from "../core/grant-operations.mjs"; -import { CliError, VALID_VM, die, needHost, needVm, note, say, usage, warn } from "./lib.mjs"; +import { CliError, VALID_VM, die, hint, needHost, needVm, note, say, usage, warn } from "./lib.mjs"; import { blockedOnPerson } from "./status.mjs"; /** @import { GrantSpec } from "../core/boxery-core.mjs" */ /** @import { Selected } from "./lib.mjs" */ @@ -42,7 +42,7 @@ function ask(s, vm, specs) { if (unattended(s)) return; let tty; try { tty = openSync("/dev/tty", "r+"); } - catch { die(`grants need a person. Ask the user to run the command below, or use vm_grant:\n${specs.map((g) => grantCommand("grant", vm, s.host.name, g)).join("\n")}`); } + catch { die(`grants need a person. Ask the user to run the command below, or use vm_grant:\n${specs.map((g) => hint("access grant", grantArgs("grant", vm, g), { host: s.host.name })).join("\n")}`); } let answer = ""; // Blocked on the person: the terminal's status says so, and Ctrl-C ends the command here (controller/status.mjs). blockedOnPerson("permission", () => { diff --git a/controller/hosts.mjs b/controller/hosts.mjs index 7046a04..556d6bb 100644 --- a/controller/hosts.mjs +++ b/controller/hosts.mjs @@ -4,7 +4,7 @@ import { describeHosts, profileFromDirectory, registeredHosts, resolveHost } from "../core/boxery-core.mjs"; import { profileConfig } from "../core/profile.mjs"; import { RegistryError, VALID_ALIAS, addHostLocked, checkedDefault, destination, isRegistered, needAlias, recordBackend, removeHostLocked, setDefault, setup, withRegistryLock } from "../core/registry.mjs"; -import { BOXERY, CliError, USAGE, die, note, say, usage } from "./lib.mjs"; +import { CliError, USAGE, die, hint, note, say, usage } from "./lib.mjs"; /** @import { HostProfile } from "../core/boxery-core.mjs" */ /** @import { RegistryIO } from "../core/registry.mjs" */ @@ -78,7 +78,7 @@ export async function setupNamed(args) { export async function backendCommand(host, args) { if (args.length) usage("backend"); const b = await recordBackend(host); - if (!b) die(`could not read the host's backend (does it predate 'boxery-host backend'? see: ${BOXERY} version)`); + if (!b) die(`could not read the host's backend (does it predate 'boxery-host backend'? see: ${hint("version")})`); say(b); } diff --git a/controller/jobs.mjs b/controller/jobs.mjs index c5c7efa..9c4280c 100644 --- a/controller/jobs.mjs +++ b/controller/jobs.mjs @@ -7,7 +7,7 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import { JOBS_NODE, VALID_JOB } from "../core/boxery-core.mjs"; import { closeMaster } from "../core/profile.mjs"; -import { BOXERY, CliError, USAGE, die, duration, needVm, note, num, quit, say, usage, vmSsh, vmSshCapture, WAIT_LOST, WAIT_TIMEOUT, warn } from "./lib.mjs"; +import { CliError, USAGE, die, duration, hint, needVm, note, num, quit, say, usage, vmSsh, vmSshCapture, WAIT_LOST, WAIT_TIMEOUT, warn } from "./lib.mjs"; /** @import { Selected } from "./lib.mjs" */ @@ -34,7 +34,7 @@ const jobsVmCapture = (s, name, args, o) => vmSshCapture(s, helper(name, args), const exit = (rc) => { if (rc) throw new CliError("", rc); }; /** @param {string | undefined} id */ -const needJob = (id) => (VALID_JOB.test(id ?? "") ? /** @type {string} */ (id) : id ? die(`invalid job id: ${id} (see: ${BOXERY} jobs NAME)`) : die(`missing job id (see: ${BOXERY} jobs NAME)`, USAGE)); +const needJob = (id) => (VALID_JOB.test(id ?? "") ? /** @type {string} */ (id) : id ? die(`invalid job id: ${id} (see: ${hint("job ls")} NAME)`) : die(`missing job id (see: ${hint("job ls")} NAME)`, USAGE)); /** run --bg: start ARGV (each word's bytes) in the VM as a job, in CWD (bytes, or null: ~/project); its id. * @param {Selected} s @param {string} name @param {Buffer[]} argv @param {Buffer | null} cwd */ @@ -108,7 +108,7 @@ export async function waitJob(s, [vm, job, ...rest]) { // waiting doesn't affect the job (tmux in the VM): reconnect and keep waiting, within --timeout. if (!reached) die(`cannot reach ${name}`); if (deadline != null && Date.now() / 1000 >= deadline) { warn(`cannot reach ${name}; --timeout passed (the job may still be running)`); quit(WAIT_TIMEOUT); } - if (++drops > 60) die(`cannot reach ${name}; giving up (the job may still be running: ${BOXERY} jobs ${name})`); + if (++drops > 60) die(`cannot reach ${name}; giving up (the job may still be running: ${hint("job ls", [name])})`); warn(`lost the connection to ${name}; reconnecting (the job keeps running)`); await closeMaster(name); await new Promise((res) => setTimeout(res, 5000)); diff --git a/controller/leases.mjs b/controller/leases.mjs index 8a5fdd9..e66751b 100644 --- a/controller/leases.mjs +++ b/controller/leases.mjs @@ -3,7 +3,7 @@ import { execFileSync } from "node:child_process"; import { constants } from "node:os"; import { acquireLease, leaseRows, localLeases, releaseLease, renewLease } from "../core/leases.mjs"; -import { BOXERY, USAGE, die, hostFailed, note, quit, say, usage } from "./lib.mjs"; +import { USAGE, die, hint, hostFailed, note, quit, say, usage } from "./lib.mjs"; /** @import { Selected } from "./lib.mjs" */ /** Like `date`: the local format people read elsewhere in the CLI. @param {number} t unix seconds */ @@ -46,7 +46,7 @@ export async function leaseCommand(_s, command, args) { try { r = await acquireLease({ ttl: o.ttl ?? 1800, wait: o.wait ?? 0, ...(o.holder !== undefined ? { holder: o.holder } : {}) }, cli); } catch (e) { if (interrupted && /** @type {Error} */ (e).name === "AbortError") quit(interrupted); hostFailed(e); } finally { for (const [sig, h] of handlers) process.off(sig, h); } - note(`==> leased ${r.name} (lease ${r.id}, expires in ${r.expires - Math.floor(Date.now() / 1000)}s; renew with: ${BOXERY} renew ${r.name})`); + note(`==> leased ${r.name} (lease ${r.id}, expires in ${r.expires - Math.floor(Date.now() / 1000)}s; renew with: ${hint("lease renew", [r.name])})`); return say(`${r.name} ${r.id}`); } case "renew": { diff --git a/controller/lib.mjs b/controller/lib.mjs index d316422..8e5d340 100644 --- a/controller/lib.mjs +++ b/controller/lib.mjs @@ -1,6 +1,6 @@ // Shared plumbing for the controller CLI's commands (controller/cli.mjs): errors and exit codes, argument // checks, the selected host profile, and processes that share this terminal (ssh, boxery-host). -import { usageText } from "./usage.mjs"; +import { commandRef, usageText } from "./usage.mjs"; import { spawn } from "node:child_process"; import { constants } from "node:os"; import { profileFromDirectory, vmProblem, withHost } from "../core/boxery-core.mjs"; @@ -28,11 +28,16 @@ export const quit = (exitCode) => { throw new CliError("", exitCode); }; * get (core/ssh-config.mjs remoteCommand; host/util.mjs hint). (Plain ls asks every host with `boxery`: * its host output is --json, with no hints.) */ export let BOXERY = "boxery"; +let hintHost = ""; /** @param {string} explicitHost the NAME of --host NAME, or "" */ export function invokedAs(explicitHost) { + hintHost = explicitHost; BOXERY = explicitHost ? `boxery --host ${explicitHost}` : "boxery"; process.env.BOXERY_CLI = BOXERY; } +/** A canonical hint using the caller's explicit host, or a specific host for grouped output and grant requests. + * @param {string} command @param {string[]} [args] @param {{host?: string}} [options] */ +export const hint = (command, args = [], { host = hintHost } = {}) => commandRef(command, args, host ? ["--host", host] : []); /** @param {string} message */ export const warn = (message) => { process.stderr.write(`boxery: ${message}\n`); }; /** A line on stdout. @param {string} text */ diff --git a/controller/ls.mjs b/controller/ls.mjs index 6a64b87..74301dd 100644 --- a/controller/ls.mjs +++ b/controller/ls.mjs @@ -6,7 +6,7 @@ import { realpathSync } from "node:fs"; import { describeHosts, listGrants, withHost } from "../core/boxery-core.mjs"; import * as lifecycle from "../core/lifecycle.mjs"; -import { BOXERY, die, hostFailed, needHost, note, quit, say, select, usage, warn } from "./lib.mjs"; +import { die, hint, hostFailed, needHost, note, quit, say, select, usage, warn } from "./lib.mjs"; /** @import { Selected } from "./lib.mjs" */ /** A row of listVms, as docs/cli.md describes `ls --json`. @@ -119,7 +119,7 @@ function print(sections, { onlyRunning, refresh, grouped }) { const unchecked = sec.vms.filter((v) => running(v) && v.guest?.checked_at == null).map((v) => v.name); if (unchecked.length && !refresh) notes.push(`==> ${who}guest software not checked yet: ${unchecked.join(", ")} (ls --refresh reads it)`); const outdated = sec.vms.filter((v) => v.guest?.status === "outdated").map((v) => v.name); - if (outdated.length) notes.push(`==> ${who}outdated guest software on ${outdated.join(", ")}; update with: ${grouped ? `boxery --host ${sec.name}` : BOXERY} patch NAME|--all`); + if (outdated.length) notes.push(`==> ${who}outdated guest software on ${outdated.join(", ")}; update with: ${hint("patch", [], grouped ? { host: sec.name } : {})} NAME (or ${hint("patch", ["--all"], grouped ? { host: sec.name } : {})})`); } say(out.join("\n") || none); if (notes.length) note(notes.join("\n")); diff --git a/controller/usage.mjs b/controller/usage.mjs index 32770f9..51d772a 100644 --- a/controller/usage.mjs +++ b/controller/usage.mjs @@ -53,6 +53,10 @@ export const unknownCommand = (table, word) => help.unknownCommand(CLI, table, w /** The command table (cli.mjs registers it as it loads), for usage errors raised in the modules it calls. @type {Record} */ let TABLE = {}; +/** A copyable canonical command, checked against the same table used for dispatch and help. + * @param {string} command @param {string[]} [args] @param {string[]} [prefix] */ +export const commandRef = (command, args = [], prefix = []) => help.commandRef(CLI, TABLE, command, args, prefix); + /** A family's usage lines are its actions' (and its `list` the action names): filled in here, so the two can't differ. @param {Record} table */ export function registerCommands(table) { TABLE = table; diff --git a/core/grants.mjs b/core/grants.mjs index b90568d..13b8204 100644 --- a/core/grants.mjs +++ b/core/grants.mjs @@ -126,9 +126,15 @@ export function missingPiGrant(vm, { settings = "", projectSettings = "", models return `llm:${route}`; } -/** @param {"grant" | "revoke"} verb @param {string} vm @param {string} host @param {GrantSpec} g */ -export function grantCommand(verb, vm, host, g) { +/** Grant arguments shared by front-ends that choose their own command spelling. + * @param {"grant" | "revoke"} verb @param {string} vm @param {GrantSpec} g */ +export function grantArgs(verb, vm, g) { const spec = verb === "revoke" && g.kind === "file" ? `file:${g.local}` : g.spec; - return ["boxery", "--host", host, verb, vm, spec, ...(verb === "grant" ? [...(g.readonly ? ["--readonly"] : []), ...(g.cmd ? ["--cmd", g.cmd] : []), ...(g.auth ? ["--auth", g.auth] : [])] : [])].map(quoteWord).join(" "); + return [vm, spec, ...(verb === "grant" ? [...(g.readonly ? ["--readonly"] : []), ...(g.cmd ? ["--cmd", g.cmd] : []), ...(g.auth ? ["--auth", g.auth] : [])] : [])]; +} +/** Shared approval messages retain their existing command format. + * @param {"grant" | "revoke"} verb @param {string} vm @param {string} host @param {GrantSpec} g */ +export function grantCommand(verb, vm, host, g) { + return ["boxery", "--host", host, verb, ...grantArgs(verb, vm, g)].map(quoteWord).join(" "); } diff --git a/docs/cli.md b/docs/cli.md index f495efc..9d8a8e4 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -430,7 +430,9 @@ Generated from the help `boxery help --all` shows (`controller/cli.mjs`); edit i `boxery-host help` lists every command; `boxery-host COMMAND --help` shows one. Generated from the same help (`host/help.mjs`); edit it there, then `npm run docs:cli`. `--profile NAME` before any command runs it in a second profile on this host (`~/.config/boxery-NAME`: its own backend, state, proxy port and services); `--profile NAME init --backend B` creates it with a free proxy port. `upgrade` keeps the code and each profile's state from before in `$BOXERY_CONF/pre-upgrade/` after a success too. -Commands in messages name what you typed. The follow-up commands `boxery` prints (`run --bg`'s logs and wait, `prompt`, `acquire`, `ls`) keep your `--host NAME`; and when `boxery` runs a host command for you, it passes `BOXERY_CLI` (`boxery`, or `boxery --host NAME` if you gave one), so a host error suggests `boxery --host lab snap-rm demo s1` rather than `boxery-host snap-rm demo s1`. Commands only boxery-host has (`init`, …) keep its name. Called directly, boxery-host names itself. Messages about a VM that can't be reached (`no such vm`, not running, a pool VM without a lease) name `--host NAME` when you gave one or when the VM's host isn't the default (another host's VM in `cp`, an agent's host session), since a bare `boxery start NAME` would go to the default host. +Controller-generated follow-up hints use the canonical command families (`job logs`, `job wait`, `lease renew`, `access grant`) and shell-quote dynamic arguments so they can be copied safely. They keep an explicit `--host NAME`; grant approval requests name the host even when it was the default, so another controller cannot accidentally grant on a different host. Everyday `run`, `ssh`, `attach` and `prompt` stay short. Shared approval prompts and core/host messages may still name working legacy aliases. + +When `boxery` runs a host command, it passes the unchanged `BOXERY_CLI` prefix (`boxery`, or `boxery --host NAME` if you gave one), so a host error suggests `boxery --host lab snap-rm demo s1` rather than `boxery-host snap-rm demo s1`. Commands only boxery-host has (`init`, …) keep its name. Called directly, boxery-host names itself. Messages about a VM that can't be reached (`no such vm`, not running, a pool VM without a lease) name `--host NAME` when you gave one or when the VM's host isn't the default (another host's VM in `cp`, an agent's host session), since a bare `boxery start NAME` would go to the default host. diff --git a/help/index.mjs b/help/index.mjs index a65ab45..7829d98 100644 --- a/help/index.mjs +++ b/help/index.mjs @@ -212,6 +212,22 @@ export function resolve(table, name) { return e.alias ? (Object.hasOwn(table, e.alias) ? e.alias : null) : name; } +/** One shell word, safe to copy literally, including empty strings and embedded quotes. @param {string} value */ +export const shellWord = (value) => /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`; + +/** A validated command reference, not a rewrite of output. Callers choose the action explicitly: grants serves + * both access ls and access apply. PREFIX is argv (e.g. --host NAME), never an executable shell fragment. + * @param {Cli} cli @param {Record} table @param {string} command + * @param {string[]} [args] @param {string[]} [prefix] */ +export function commandRef(cli, table, command, args = [], prefix = []) { + const words = command.split(" "), name = resolve(table, words[0]); + if (!name || words.length > 2 || words.some((w) => !w)) throw new Error(`unknown command reference: ${command}`); + const e = table[name]; + if (words.length === 2 && (!e.actions || !Object.hasOwn(e.actions, words[1]))) throw new Error(`unknown command reference: ${command}`); + if (cli.hidden?.includes(e.help?.group ?? "")) throw new Error(`use a canonical family action instead of ${command}`); + return [cli.program, ...prefix, name, ...words.slice(1), ...args].map(shellWord).join(" "); +} + /** The name nearest WORD, when one is close. @param {string} word @param {string[]} names */ function nearest(word, names) { return names.map((n) => /** @type {const} */ ([n, distance(word, n)])).filter(([n, d]) => d <= Math.max(1, Math.floor(n.length / 3)) || (word.length >= 3 && n.startsWith(word))).sort((a, b) => a[1] - b[1] || a[0].localeCompare(b[0]))[0]; diff --git a/test/cli-hints.test.mjs b/test/cli-hints.test.mjs new file mode 100644 index 0000000..6f94bdd --- /dev/null +++ b/test/cli-hints.test.mjs @@ -0,0 +1,89 @@ +// Copyable controller hints; no real HOME, profile, credential, SSH destination or VM. +import assert from "node:assert/strict"; +import { execFileSync, spawnSync } from "node:child_process"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { after, test } from "node:test"; +import { hostTransport } from "./fixtures/host-transport.mjs"; +import { registerHost } from "./fixtures/register-host.mjs"; +import { commandRef, shellWord } from "../help/index.mjs"; + +const root = mkdtempSync(path.join(tmpdir(), "boxery-hints-")); +const home = path.join(root, "registry"), bin = path.join(root, "bin"); +const profile = (/** @type {string} */ name) => path.join(root, name); +process.env.BOXERY_HOME = home; +const { COMMANDS } = await import("../controller/cli.mjs"); +const { CLI } = await import("../controller/usage.mjs"); +const { hint, invokedAs } = await import("../controller/lib.mjs"); +const cli = path.resolve(import.meta.dirname, "../controller/boxery"); +const id = "job-20261109-000001-abcdef"; +mkdirSync(bin); +for (const name of ["alpha", "beta"]) registerHost(home, name, profile(name)); +hostTransport(root, [profile("alpha"), profile("beta")]); +writeFileSync(path.join(home, "default-host"), "alpha\n"); +writeFileSync(path.join(bin, "ssh"), `#!/usr/bin/env node +console.log(${JSON.stringify(id)}); +`); +writeFileSync(path.join(bin, "boxery"), "#!/usr/bin/env node\nconsole.log(JSON.stringify(process.argv.slice(2)));\n"); +for (const file of ["ssh", "boxery"]) chmodSync(path.join(bin, file), 0o755); +const env = { ...process.env, HOME: path.join(root, "home"), BOXERY_HOME: home, PATH: `${bin}:${process.env.PATH}`, SSH_AUTH_SOCK: "", BOXERY_STATUS: "0", NO_COLOR: "1" }; +/** @param {string[]} args */ +const run = (args) => { + const options = { env, encoding: /** @type {const} */ ("utf8"), input: "", timeout: 10_000, cwd: root, detached: true }; + return spawnSync(cli, args, options); +}; +after(() => { invokedAs(""); rmSync(root, { recursive: true, force: true }); }); + +/** A hint through a shell with a capture-only boxery executable, never a real host command. @param {string} line */ +const words = (line) => JSON.parse(execFileSync("/bin/sh", ["-c", line], { env, cwd: root, encoding: "utf8", timeout: 10_000 })); + +test("shell words round-trip empty strings, quotes, Unicode and metacharacters without execution", () => { + const values = ["", "a b", "it's", "$HOME", "$(touch SHOULD_NOT_EXIST)", "; touch SHOULD_NOT_EXIST", "line1\nline2", "@", "--help", "é"]; + const out = execFileSync("/bin/sh", ["-c", `printf '%s\\0' ${values.map(shellWord).join(" ")}`], { env, cwd: root, timeout: 10_000 }); + assert.deepEqual(out.toString().split("\0").slice(0, -1), values); + assert.equal(existsSync(path.join(root, "SHOULD_NOT_EXIST")), false); +}); + +test("references validate command paths, prefer canonical spellings, and quote every dynamic word", () => { + const args = ["demo", id, "-f", "", "a b", "'quoted'", "$HOME; false"]; + const line = commandRef(CLI, COMMANDS, "job logs", args, ["--host", "beta"]); + assert.deepEqual(words(line), ["--host", "beta", "job", "logs", ...args]); + assert.equal(commandRef(CLI, COMMANDS, "list"), "boxery ls"); + for (const ref of ["", "missing", "constructor", "job nope", "host __proto__", "job logs extra", "job logs", "run --bg"]) assert.throws(() => commandRef(CLI, COMMANDS, ref), /unknown command reference/); + for (const ref of ["jobs", "grants", "agent-forward"]) assert.throws(() => commandRef(CLI, COMMANDS, ref), /canonical family action/); +}); + +test("hint context is read at call time and supports a specific host without mutating the context", () => { + invokedAs("alpha"); + assert.equal(hint("job wait", ["demo", id]), `boxery --host alpha job wait demo ${id}`); + assert.equal(hint("lease renew", ["pool1"], { host: "beta" }), "boxery --host beta lease renew pool1"); + assert.equal(hint("version"), "boxery --host alpha version"); + invokedAs(""); + assert.equal(hint("version"), "boxery version"); +}); + +test("background-job hints use canonical actions and retain an explicit host, not the default", () => { + for (const prefix of [[], ["--host", "beta"]]) { + const r = run([...prefix, "run", "--bg", "demo", "true"]); + assert.equal(r.status, 0, r.stderr); + assert.equal(r.stdout, `${id}\n`); + const expected = ["boxery", ...prefix].join(" "); + assert.match(r.stderr, new RegExp(`logs: ${expected} job logs demo ${id} -f`)); + assert.match(r.stderr, new RegExp(`wait: ${expected} job wait demo ${id}`)); + } + assert.equal(readFileSync(path.join(home, "default-host"), "utf8"), "alpha\n"); +}); + +test("headless grant guidance is canonical, host-pinned and safely copyable; approval still refuses", () => { + const command = "printf '%s' 'a b;$HOME'"; + for (const prefix of [[], ["--host", "beta"]]) { + const r = run([...prefix, "access", "grant", "demo", "env:API_TOKEN", "--cmd", command]); + assert.equal(r.status, 1, r.stderr); + assert.match(r.stderr, /grants need a person/); + const line = r.stderr.split("\n").find((l) => l.startsWith("boxery --host ")); + assert.ok(line, r.stderr); + assert.deepEqual(words(line), ["--host", prefix.length ? "beta" : "alpha", "access", "grant", "demo", "env:API_TOKEN", "--cmd", command]); + assert.equal(existsSync(path.join(profile(prefix.length ? "beta" : "alpha"), "grants/demo")), false); + } +}); diff --git a/test/grants.test.mjs b/test/grants.test.mjs index 310cdc7..a2ea522 100644 --- a/test/grants.test.mjs +++ b/test/grants.test.mjs @@ -55,7 +55,7 @@ test("CLI without a controlling TTY refuses, including y on stdin and inherited for (const input of ["", "y\n", "yes\nyes\n"]) { const r = await headless(["grant", "demo", "ssh-agent"], input, { GRANT_CONFIRM: "off", BOXERY_ASSUME_YES: "1" }); assert.notEqual(r.code, 0); - assert.match(r.output, /grants need a person[\s\S]*vm_grant[\s\S]*boxery --host local grant demo ssh-agent/); + assert.match(r.output, /grants need a person[\s\S]*vm_grant[\s\S]*boxery --host local access grant demo ssh-agent/); assert.equal(existsSync(store), false); } }); @@ -231,7 +231,7 @@ test("text ls is drawn from ls --json: grants, pool leases and outdated guests i assert.match(r.stdout, /^pool1 +shut off +- +- +- +headless +pool free; outdated guest \(layers changed\)$/m); assert.match(r.stdout, /^pool2 +running .* leased by ben@mac, 2h left$/m); assert.match(r.stderr, /guest software not checked yet: pool2 \(ls --refresh reads it\)/); - assert.match(r.stderr, /outdated guest software on pool1; update with: boxery patch NAME\|--all/); + assert.match(r.stderr, /outdated guest software on pool1; update with: boxery patch NAME \(or boxery patch --all\)/); const running = await headless(["ls", "--running"]); assert.equal(running.code, 0, running.output); assert.doesNotMatch(running.stdout, /pool1/); diff --git a/test/help-drift.test.mjs b/test/help-drift.test.mjs index 2d1a372..967f8f4 100644 --- a/test/help-drift.test.mjs +++ b/test/help-drift.test.mjs @@ -29,10 +29,10 @@ const PARSED_IN = { }; // Flags in a handler that aren't its own options: arguments it gives ssh, gh or the VM helper. const NOT_OPTIONS = { - ssh: ["-t"], attach: ["-t"], forward: ["-o"], + ssh: ["-t"], attach: ["-t", "--bg"], forward: ["-o"], // --bg belongs to the suggested run command jobs: ["--text"], kill: ["--text"], runners: ["-c", "--hostname", "--jq", "--input"], // gh api - run: ["-h", "--help"], // its own --help, handled before NAME + run: ["-h", "--help", "-f", "-c"], // help before NAME; -f/-c belong to suggested logs/shell commands }; // Commands whose flags the host parses (passed through): their help is checked against the host's usage text. const HOST_PARSED = { patch: "patch", "upgrade-host": "upgrade", backends: "backends", capabilities: "capabilities", snaps: "snaps", images: "images", pool: "pool", runners: "runners" }; diff --git a/test/shell/common/controller-local.sh b/test/shell/common/controller-local.sh index 88bd31a..9b0cf62 100755 --- a/test/shell/common/controller-local.sh +++ b/test/shell/common/controller-local.sh @@ -129,7 +129,7 @@ mkdir -p "$tmp/vms/w1/home/.pi/agent"; printf '{"defaultProvider": "openai-codex printf '{"providers": {"openai-codex": {"baseUrl": "http://127.0.0.1:8088/chatgpt/backend-api"}}}\n' >"$tmp/vms/w1/home/.pi/agent/models.json" printf '#!/bin/sh\nexit 0\n' >"$tmp/bin/tmux" if out=$("$A" prompt w1 say hi 2>&1); then bad "prompt without an llm grant started: $out" -elif [[ $out == *"needs llm:chatgpt"*"boxery grant w1 llm:chatgpt"* ]] && ! ls "$tmp/vms/w1/home/project/.boxery/"task-* >/dev/null 2>&1; then ok "prompt without pi's llm grant: refused, with the grant to run" +elif [[ $out == *"needs llm:chatgpt"*"boxery access grant w1 llm:chatgpt"* ]] && ! ls "$tmp/vms/w1/home/project/.boxery/"task-* >/dev/null 2>&1; then ok "prompt without pi's llm grant: refused, with the grant to run" else bad "prompt without a grant: $out"; fi # (a login script that prints something first doesn't hide pi's settings) echo "welcome to the VM" >"$tmp/vms/w1/login-output" From c9370fac31889fc50e15a5f5dfb7616e66da56a9 Mon Sep 17 00:00:00 2001 From: Ben Vinegar <2153+benvinegar@users.noreply.github.com> Date: Sun, 8 Nov 2026 21:21:26 -0500 Subject: [PATCH 3/3] test(controller): preserve job error statuses after hint rebase --- test/cli-families.test.mjs | 4 ++-- test/cli-hints.test.mjs | 13 +++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/test/cli-families.test.mjs b/test/cli-families.test.mjs index 539e081..b2d386f 100644 --- a/test/cli-families.test.mjs +++ b/test/cli-families.test.mjs @@ -194,8 +194,8 @@ test("malformed actions say what the family has, before any host, ssh or saved s [["access", "apply", "demo", "--json"], 2, /usage: boxery access apply NAME/], [["access", "apply", "demo", "--quiet", "x"], 2, /usage: boxery access apply NAME/], [["access", "ls", "Demo"], 1, /invalid VM name: Demo/], - [["job", "kill", "demo"], 2, /^boxery: missing job id \(see: boxery jobs NAME\)\n$/], - [["job", "kill", "demo", "nope"], 1, /^boxery: invalid job id: nope \(see: boxery jobs NAME\)\n$/], + [["job", "kill", "demo"], 2, /^boxery: missing job id \(see: boxery job ls NAME\)\n$/], + [["job", "kill", "demo", "nope"], 1, /^boxery: invalid job id: nope \(see: boxery job ls NAME\)\n$/], [["job", "ls", "demo", "--frob"], 2, /^boxery: usage: boxery job ls NAME \[--json\]\n {7}boxery job ls NAME --prune/], [["lease", "ls", "--frob"], 2, /^boxery: usage: boxery lease ls \[--json\]\n$/], [["snapshot", "rm", "demo"], 2, /^boxery: usage: boxery snapshot rm NAME SNAP\n$/], diff --git a/test/cli-hints.test.mjs b/test/cli-hints.test.mjs index 6f94bdd..d2e82b3 100644 --- a/test/cli-hints.test.mjs +++ b/test/cli-hints.test.mjs @@ -75,6 +75,19 @@ test("background-job hints use canonical actions and retain an explicit host, no assert.equal(readFileSync(path.join(home, "default-host"), "utf8"), "alpha\n"); }); +test("job argument errors keep missing-id usage status and invalid-id failure status with scoped hints", () => { + for (const command of [["logs"], ["wait"], ["kill"], ["job", "logs"], ["job", "wait"], ["job", "kill"]]) { + for (const prefix of [[], ["--host", "beta"]]) for (const job of [undefined, "", "nope"]) { + const r = run([...prefix, ...command, "demo", ...(job === undefined ? [] : [job])]); + assert.equal(r.status, job ? 1 : 2, r.stderr); + assert.equal(r.stdout, ""); + const reason = job ? `invalid job id: ${job}` : "missing job id"; + assert.equal(r.stderr, `boxery: ${reason} (see: ${["boxery", ...prefix, "job", "ls", "NAME"].join(" ")})\n`); + } + } + assert.equal(readFileSync(path.join(home, "default-host"), "utf8"), "alpha\n"); +}); + test("headless grant guidance is canonical, host-pinned and safely copyable; approval still refuses", () => { const command = "printf '%s' 'a b;$HOME'"; for (const prefix of [[], ["--host", "beta"]]) {