# `@nice-code/commander`

Your dev environment, declared once: one typed `commander.config.ts`, one daemon, and one control
surface shared by a CLI and a live web UI. The replacement for ten terminal tabs, a tmux script, or
a `concurrently` line that has grown a comment explaining itself.

> **Docs:** [nicecode.io](https://nicecode.io/nice-commander/dev-environments/)

```bash
bun add -d @nice-code/commander
```

```ts
// commander.config.ts
import { defineCommanderConfig } from "@nice-code/commander/config";

export default defineCommanderConfig({
  name: "my-app",
  processes: [
    {
      id: "api",
      run: ["bun", "run", "dev"],
      cwd: "./services/api",
      endpoints: [{ name: "http", protocol: "http", port: 8787, ownership: "exclusive" }],
      ready: { kind: "endpoint", endpoint: "http" },
    },
    { id: "web", run: ["bun", "run", "dev"], cwd: "./apps/web", dependsOn: ["api"] },
    { id: "types", kind: "task", run: ["bunx", "tsc", "--noEmit"], timeoutMs: 120_000 },
  ],
  defaultSelection: "web",
});
```

```bash
bunx nice-commander up        # `web` → starts api first, waits for it to be READY, then web
                              #   ✓ api ready → http://127.0.0.1:8787
bunx nice-commander up --json # the same generation as data: outcome, state, pid, urls per id
bunx nice-commander status    # live table
bunx nice-commander ui        # the browser view
bunx nice-commander down web
```

> ⚠ The binary is **`nice-commander`** — always the full name. `bunx commander` fetches a
> different, extremely popular npm package (an argument parser), and it will not error usefully;
> it will just quietly not be this tool. If you want something shorter in a script, alias
> `nice-commander`, never `commander`.

Every acting command takes the same selector — ids, suite names, `@pin` names, or `tag=value` terms
(AND across terms; `--any` ORs them). `up --dry-run` and `explain` show exactly what would be
touched, without touching it.

Tags organise processes; a **suite** is a declared run-unit (`suites: { verify: { where, include,
parallel, failFast } }`) for the things you mean to run as one. Mark a process `optIn: true` and no
tag selection, suite query or `--all` will ever start it.

The GUI’s **shutdown daemon** button stops every task and service managed by that daemon,
including processes hidden by filters or suites, then exits the daemon. Confirm the dialog to
proceed. Run `nice-commander ui` to start it again.

`nice-commander ui` attaches to the daemon already running for the project, even one started by
an older build: each daemon serves the web UI it was built with, so upgrading the package never
breaks the open dashboard. `nice-commander ui --fresh` stops that daemon (and everything it runs)
and starts one on the installed build. If a page ever can't connect, it offers **reload** and
**shut down daemon** instead of a dead end.

## What it does that a script does not

- **`dependsOn` waits for *ready*, not for *spawned*** — a real readiness contract (port, HTTP,
  log marker), so `web` never starts against an API that is still compiling.
- **Stopping ends the tree.** Killing `npm run dev`'s pid leaves the actual server holding the
  port; a POSIX process group / Windows Job Object does not.
- **Starts never kill an unknown port owner.** An occupied exclusive port blocks startup.
  Inspect its owner and explicitly confirm a stop using `ports` or the UI; automatic orphan
  reaping remains limited to verified ledger entries.
- **`down` and `restart` leave a shared dependency running.** `down web` stops `web` and the
  dependencies only `web` was using. A dependency another live process still needs stays up, and
  the command names it with what needs it. `down web --only` stops `web` and nothing else.
  `restart web` restarts `web` alone.
- **A broken config keeps the last good one live.** Nothing restarts silently; changed processes
  are marked stale until you restart them.
- **A changed definition reaches the next start.** Editing the config, or a module it imports,
  reloads it in the daemon. A stale process keeps running the old definition until its next start,
  so `restart <id>` (or `down` then `up`) applies the change. `up`, `restart` and `run` also make
  the daemon reload first when the config on disk is newer than the one it holds.
- **`required` env vars are enforced.** A start refuses until each one has a value (an override,
  a default, or the environment the process inherits), and names the variable and the
  `env <id> --set NAME=…` command that sets it.
- **Merged logs that actually order.** The daemon stamps every line at receipt, so the timeline is
  correct across processes and across daemon restarts — and search runs server-side over the
  on-disk history, not over what your browser happens to be holding.

Node ≥ 22 or Bun. The web UI is pre-built into the package; Vite and React are not installed on
your machine. Built on [`@nice-code/process`](https://www.npmjs.com/package/@nice-code/process).

`bunx nice-commander` follows the executable's Node shebang, so it still needs Node ≥ 22.
Use `bunx --bun nice-commander` to explicitly run with Bun. An older Node can serve the UI
but fail its authenticated WebSocket handshake, leaving the CLI and browser waiting for the
status realm. After upgrading your runtime, run `nice-commander shutdown` (this stops managed
processes), then retry, so an existing daemon is replaced too. No extra environment variables
are needed.

## Reading process status

The UI uses the same indicators in process rows, dependency dots, tag groups and suite cards:

- A gently pulsing solid green dot means running or ready.
- A green circle with a check means the run completed successfully.
- A red circle with a cross means failed, crashed or timed out.
- Amber marks readiness issues, retry backoff or blocked dependencies.
- A blue dashed ring means starting or stopping; a muted ring means idle or deliberately stopped.

Task results remain visible after cleanup, and a new run takes precedence over its previous
result. Tag group and suite summaries distinguish pending, blocked and stopped tasks from running ones.
The process overview follows the current filters. Reduced-motion preferences disable animation.

## Finding and stopping port owners

```bash
nice-commander doctor                        # occupied, inactive endpoints — each owner marked STRAY or not
nice-commander ports                         # inspect all configured exclusive TCP endpoints
nice-commander ports journey-backend journey-web
nice-commander ports journey-backend --kill 12345    # review and confirm this PID
nice-commander ports journey-backend --kill-owner    # stop whatever holds its endpoints, no PID needed
nice-commander up journey-backend --replace-same     # take the port from a stray, then start
nice-commander doctor --reap-strays                  # stop every stray on a configured port
```

Inspection shows each listener's PID, executable, parent PID, working directory, process-start
identity and whether it is a **stray**: this definition's own command (argv and cwd both equal),
running outside the daemon — typically something you started by hand in a terminal that has since
gone away. The match walks up the listener's parents, so `bun run dev` → vite → the socket still
matches a definition of `bun run dev`. Anything else is a **stranger**: another application may use
the same port, and inspection does not guess. Command arguments are read for the match and are not
shown or stored.

A start that finds a stray on an exclusive port refuses and says so, naming the pid and the fix.
`up --replace-same` (or `replaceSame: true` on the definition, or under `defaults`) stops the stray
as a tree — root command first, so its wrapper cannot respawn it — with the same SIGTERM → grace →
SIGKILL ladder a stop uses, then starts the definition. A stranger on the port is named and always
refused, with or without the flag; nothing is ever killed on the strength of a port alone.

`--kill PID` sends SIGTERM after confirmation; `--yes` supplies explicit noninteractive consent.
`--kill-owner` does the same for every verified listener on the selection's exclusive endpoints
without your having to copy a PID first. If the listener will not stop, inspect again and add
`--force` to choose SIGKILL. A stray is signalled as its tree; a stranger only as the selected
listener, so a watcher may restart it — inspect again to see the replacement. Multiple listeners
are listed individually.

In the UI, **inspect ports** appears on inactive process rows (including failed starts), and in
expanded details for active rows. Each listener carries its stray verdict; a stray offers
**replace stray and start** (the same as `--replace-same`). Otherwise review the owner, choose
**stop PID** or **force kill PID**, and confirm. Once the port is free, **retry start** runs the
normal startup checks again.

The identity and endpoint are rechecked before termination. Inspection tokens expire after five
minutes and can be used once. Active configured port owners must be stopped with their ordinary
stop control first; Commander and its ancestors are protected. `ports` works without starting a
daemon. `doctor` remains read-only unless `--reap` (a crashed daemon's ledger orphans) or
`--reap-strays` (strays on configured ports, confirmed one by one, `--yes` for scripts) is
explicitly requested; strangers are listed and left alone by both.

A refused start stays readable: `status` shows `start failed: …` on the row until a later start
succeeds or the process is stopped, and a `blocked: dependency "x" is not running` note clears by
itself once `x` is ready.

Owner inspection currently supports macOS and Linux with `lsof` and `ps` available. Visibility
is limited by OS permissions. Remote, shared and observed endpoints are never termination
targets. A missing tool or unknown identity produces a diagnostic instead of authorizing a kill.
Windows owner inspection is not supported yet, so on Windows every port owner is a stranger.

## Developing the web UI (`bun run dev`)

Editing the UI needs a fast loop, so the package ships a dev harness: `bun run dev` (from
`packages/nice-commander`) serves the client **source** with Vite hot reload and proxies its
auth/websocket lanes to a throwaway daemon running the `dev/showroom.config.ts` demo. Open the
printed URL, edit `src/client/**`, and watch it hot-reload live against a real backend.

- `NICE_COMMANDER_DEV_PORT` changes the vite port (default 5196). The daemon runs on its own
  `showroom` data dir and port range, so it never touches your real environment.
- `NICE_COMMANDER_DEV_OPEN=0` skips auto-opening a browser (headless runs).
- Ctrl+C (or closing the vite server) stops the showroom daemon and its processes too.
- The demo needs `build/cli.mjs`; the harness runs `bun run build:server` itself if it is missing.

## Security posture

Loopback only. The browser takes a capability from a same-origin bootstrap and keeps it in memory —
never in a URL, a cookie, or localStorage — and burns a single-use ticket per socket. Process
output is rendered as text, always. Configured `env` values never reach the realm, the ledger, or a
log.
