# AGENTS.md — using Orckit (for LLM agents)

This file is for AI agents (Claude, Cursor, Codex, etc.) helping a user write `orckit.yaml` configs or integrate `@orckit/cli` programmatically. For the human-facing reference see [README.md](README.md). For runnable configs see [examples/](examples) — each subdirectory is a self-contained example you can `orc start` against.

## What Orckit is

A CLI that takes a YAML file describing local-dev processes (db, api, web, workers...), starts them in dependency order, watches health checks for readiness, applies restart policies, and tears them down on Ctrl-C.

Use it when a developer needs `db → api → web` started in order with health checks between them. Do **not** use it for: production deployments, container orchestration, build pipelines, daemonized services, or as a "process manager" for already-running processes. Every process Orckit knows about is spawned and owned by Orckit.

## Workflow when generating a config

1. Identify the processes the developer needs running (look at `package.json` scripts, `docker-compose.yml`, READMEs, existing shell scripts).
2. Identify real runtime dependencies between them (api needs db, web needs api).
3. Pick a ready check per process — see the decision tree below.
4. Write `orckit.yaml`.
5. Run `npx orc validate -c orckit.yaml`. It parses the file, builds the dependency graph, prints both, and exits non-zero on any problem. **Always run this before declaring the config done.**
6. Optionally `npx orc start` to verify the boot sequence actually works — on a TTY this pins a persistent dashboard (brand + wave-grouped graph + counters footer) to the bottom of the terminal. Process state, build progress, and timing render live in the graph; `--show-output` adds streamed stdout/stderr above it. Pass `--no-live` if you need plain line-by-line output (e.g. capturing to a log file).

When you run `orc start` yourself (non-interactively, output captured), stdin isn't a TTY, so a port left bound by a previous run aborts the boot instead of prompting. Pass `--kill-blocked-ports` to reclaim those ports unattended, or `--fail-on-blocked-ports` to make the abort explicit. Never work around a blocked port by editing the config to use a different port — that hides a leftover process the user still has running.

## Minimal valid config

```yaml
processes:
  api:
    command: npm run dev
    ready:
      type: http
      url: http://localhost:3000/health
```

`processes` is required and must have at least one entry. Everything else has defaults. There is no required top-level `project` field (it defaults to `orckit`).

## Decision tree: which `ready` check?

A process is "ready" the moment it spawns *unless* it has a `ready` block. Pick the cheapest check that actually proves the process can serve traffic.

| Situation | Use |
|---|---|
| Process exposes HTTP with a `/health` (or any) endpoint | `type: http` |
| Process listens on a TCP port but has no HTTP (postgres, redis, raw sockets) | `type: tcp` |
| Process is a dev/build server that prints a known string on success (`compiled successfully`, `Local: http://...`) | `type: log-pattern` |
| One-shot command that must exit 0 (migrations, seed scripts, codegen) | `type: exit-code` |
| Custom shell probe (CLI tool, complex condition) | `type: custom` (`command:` runs on the interval and must exit 0) |
| Truly fire-and-forget (cosmetic tailer, screen banner) | omit `ready` |

**Common mistakes to avoid:**
- Using `type: tcp` for a Node/Python web server that has an HTTP endpoint. TCP only proves "port is bound"; HTTP proves "the app responds." Prefer HTTP when available.
- Using `type: log-pattern` against a server that *also* has a health endpoint. Log patterns are brittle — pick HTTP unless you have no choice.
- Setting any ready type *other than* `exit-code` on a one-shot command (migrations, codegen). The process exits and the orchestrator treats the early exit as failure. One-shots must use `type: exit-code` or be modelled as a `pre_start` hook on the process that needs them.
- Omitting `ready` on a process other consumers depend on. Without a ready check, "ready" fires immediately on spawn and dependents start before the upstream is actually serving.

**Port-conflict guard.** Before spawning a process with a `tcp` or `http` ready check on a localhost port, orckit verifies the port is actually free. If something is already bound there (stale process from a previous run, leftover container, port-forward, etc.), the process is failed immediately with a clear error — *without* spawning. This prevents the otherwise-confusing "`✓ ready (8ms)` then `✗ failed: port taken`" sequence where the probe matches the stale listener while the new command can't bind. If you intentionally want to point a ready check at something not owned by this process, use `type: custom` or `type: log-pattern` instead.

## `depends_on`

Lists other process names that must reach `ready` before this one starts. Use it for real runtime dependencies only — not cosmetic ordering.

```yaml
processes:
  db:    { command: ..., ready: { type: tcp, port: 5432 } }
  api:   { command: ..., ready: { type: http, url: ... }, depends_on: [db] }
  web:   { command: ..., depends_on: [api] }
  worker:{ command: ..., depends_on: [db, api] }
```

Waves are computed automatically — `api` and `worker` would run in parallel if they didn't both depend on `db`. Cycles are rejected at validate time.

## `type`

- `type: bash` — default. Use unless one of the next three applies.
- `type: webpack` — only when *this process's* stdout is real webpack output. Adds a parser that emits `build:start`/`build:complete` events the reporter uses for progress display. Wrong `type` is not fatal — you just lose the progress UI.
- `type: angular` — same idea for Angular CLI output.
- `type: docker` — the process **is** a `docker run --name <X> ...`. Requires `container_name: <X>` (must match the `--name=`). Orckit runs `docker rm -f <X>` both (a) before every spawn, to nuke a container leftover from a previous crashed run, and (b) after the process is stopped or killed, so the daemon-owned container doesn't outlive orckit and keep its ports bound. On shutdown the `docker run` CLI gets a normal SIGTERM (Docker forwards it to the container) and the post-stop `docker rm -f` guarantees removal even on force-kill. Prefer this over `type: bash` + a manual `stop_command` for plain `docker run` — less to keep in sync. Stay on `type: bash` for `docker compose up` (use `stop_command: docker compose down`) or anything where you don't have a single container_name.

Do not pick `webpack`/`angular` just because the project uses webpack/angular somewhere. Pick it based on what the *command in this process* prints.

## `restart`

| Policy | When |
|---|---|
| `never` (default) | The default. A crashed process stays crashed. Use this for almost everything in local dev — when something dies, the user wants to see the error, not a retry loop that obscures it. |
| `on-failure` | Opt in when the process is genuinely transient-flaky (e.g. waits for a slow network mount) and a re-spawn is the right reflex. Restarts on crash, leaves alone on clean exit. |
| `always` | Background daemons you want kept alive regardless. Rare in dev. |

`max_retries: 3` is the default (only meaningful when `restart` is not `never`); `restart_delay_ms: 2000`. After `max_retries`, the process goes `failed`. What happens next is governed by `manual_retry` — see below.

Do **not** set `restart: always` on a command that exits 0 quickly — you get a tight respawn loop. Do **not** set `restart: on-failure` on a process whose failure mode is "config is wrong" (port taken, missing env var, syntax error) — retries will all fail the same way and just create noise. Prefer the default `never` and let the user fix it and rerun.

## `manual_retry`

Per-process boolean, default `false`. Controls what happens when a process fails at boot time after exhausting its auto-restart budget.

| `manual_retry` | Behavior on boot failure |
|---|---|
| `false` (default) | `orc start` aborts with exit 1. Use for normal services where a failure should fail the whole boot loudly. |
| `true` | Orckit stays alive with the process in `failed` and its dependents `pending`. The user fixes the issue and types `r <name>` at the REPL prompt to retry; cascade restart unblocks the dependents. |

Set `manual_retry: true` only for processes that legitimately need user intervention to recover — typically those depending on external infrastructure the user controls locally:

- a Docker container when the Docker daemon may not be running
- a service that needs a VPN connection, port-forward, or SSH tunnel
- a process requiring a USB device or hardware that may not be plugged in
- anything where "fix the thing and continue" is a normal workflow

Do **not** set it on a process whose failure means "my code is broken" — that's exactly when you want the boot to fail fast and surface the error. Restart-on-failure already covers transient flakiness.

Output is still captured the same way regardless of `manual_retry` — don't suppress useful error output that would help the user debug what they need to fix.

## `preflight`

Top-level checks that must pass *before* any process starts (docker running, env file present, port free). Run in parallel; any failure aborts boot.

```yaml
preflight:
  - name: docker-up
    command: docker info >/dev/null 2>&1
    on_fail: start Docker Desktop
```

Always include an `on_fail` with a one-line action the developer can take. Don't put process-specific setup in preflight — use `hooks.pre_start` on that process instead.

## `hooks` (per-process)

All four are shell strings, run synchronously, block the lifecycle phase they're in. Keep them fast.

- `pre_start` — before spawn. Use for `pnpm install`, `prisma generate`, etc. Failure aborts the process.
- `post_start` — after `ready`. Use for "open the URL" banners or notifications.
- `pre_stop` / `post_stop` — symmetric around shutdown.

For "install on first run," prefer commands that no-op when up-to-date (`pnpm install --silent`).

Each hook is killed after `hook_timeout_ms` (default 60s) and the timeout is reported as a failure with a `(exit ?)` (null) code. A cold `pre_start` install of a heavy toolchain (Angular, Next) can exceed a minute — set `hook_timeout_ms` higher on that process (e.g. `600000`) so the install isn't killed mid-flight.

## `stop_command` — clean shutdown for CLI clients

A process whose visible command is just a *client* of something else — the resource is owned by a daemon and survives the local CLI being killed — needs an explicit stop verb. Set `stop_command` to that verb; orckit runs it during shutdown instead of SIGTERM:

```yaml
processes:
  stack:
    command: docker compose up
    stop_command: docker compose down
    ready: { type: tcp, port: 5432 }
```

The flow on Ctrl-C: orckit runs `docker compose down` → dockerd stops the containers → `docker compose up` exits. If the main process is still alive after the grace window (`stop_grace_ms`, default 10s), orckit SIGKILLs as a last resort.

Use it for `docker compose up`, `kubectl port-forward`, `ngrok http`, or any other foreground CLI that proxies a daemon-managed resource. For a single `docker run --name X`, do **not** use this — use `type: docker` + `container_name` (see below); validation rejects the `stop_command` form.

**`type: docker` is required** for the plain `docker run --name X ...` case — config validation *rejects* a `docker run --name X` command on any other type, because orckit can only `docker rm -f X` the container (before every spawn and after every stop) when it knows the container name. Without it, a SIGTERM the container's entrypoint ignores — MySQL does exactly this during its init phase — leaves the container running with its ports bound after orckit exits, and `--rm` never fires because the container never stopped. Fall back to `type: bash` + `stop_command` only for shapes the docker type can't express (compose, multi-container, no stable container name).

Don't set it on plain processes (node, python, etc.) — SIGTERM is correct there and `stop_command` would just be extra config to keep in sync.

## `kill_orphan_ports` — reclaim ports from escaped children

Orckit's normal teardown signals the **whole process group**, which reaps almost everything — including grandchildren that reparented to init. The one shape it can't reach is a child that escapes into its *own* session/group (`setsid`) AND detaches: it survives the group/tree kill and keeps its port bound for the next boot. The classic offender is the **JVM-based Firebase emulator suite** (firestore, auth, database, pub/sub), where the Java processes routinely outlive the `firebase emulators:start` CLI.

For those, list the bound ports and opt in:

```yaml
emulators:
  command: firebase emulators:start
  ports: [8080, 9099, 9000, 4000]
  kill_orphan_ports: true
```

After the normal stop path completes, orckit checks each port and force-kills whatever still holds it (via `lsof`). Caveats to flag when suggesting it:
- **POSIX-only** — needs `lsof`; it's a silent no-op on platforms without it (Windows).
- **Resource-based, not tree-based** — it kills *whatever* owns the port, including an unrelated process you started by hand. Only enable it for ports the process genuinely owns.
- A local `tcp`/`http` ready-check port is swept automatically — don't repeat it in `ports`.
- Only **listeners** are killed; a process that merely holds a client connection to the port is left alone.

Don't reach for this by default. Orckit's normal teardown snapshots the whole descendant tree before signalling and signals every process group in it, so even `set -m` wrapper scripts and JVM emulators come down. `kill_orphan_ports` is the last-resort check for a tool that still manages to leak.

**Do declare `ports` even without `kill_orphan_ports`.** They feed the pre-boot blocked-port check, which is what turns "a leftover process from yesterday silently holds this port" into a prompt at startup. Any process that binds a well-known port is worth listing.

## `output` filters

```yaml
output:
  suppress: ['^DEBUG', 'webpack-dev-middleware']   # regex; drop matches
  include:  ['^ERROR']                             # regex; if set, ONLY matching lines survive
  highlight:
    - { pattern: 'ERROR|WARN', color: red }
    - { pattern: 'ready in',   color: green }
```

Applied in order: `suppress` drops matches first, then `include` (if non-empty) keeps only matches of what remains, then `highlight` colors what survives. Most configs only need `suppress` + `highlight`. Valid colors: `red green yellow blue magenta cyan gray`.

## `logs` (top-level, optional)

Off by default. Enable it when the terminal output isn't enough — e.g. flaky processes whose failures need post-mortem analysis, or stacks where multiple noisy services would interleave on stdout but each needs to be readable on its own.

```yaml
logs:
  enabled: true
  dir: .orckit/logs   # default; relative to cwd
```

Each process gets its own file. Sessions within a file are separated by a banner on every spawn (initial start, auto-restart, manual retry), so restart history is preserved. `output.suppress` / `include` still apply — log files contain exactly what the CLI reporter would show with `--show-output`. Suggest the user add `.orckit/` to `.gitignore` when enabling.

Do **not** enable it just because you can — for short-lived dev sessions, the in-memory `buffer_size` is usually enough and avoids leftover files. Enable when sessions are long, processes are flaky, or the user has asked for persistent logs.

## `ide` (top-level, optional)

On by default; you rarely need to touch it. When a `.idea` folder exists at or above the config, the web dashboard turns file references in logs/errors (`src/app.ts:42:10`) into clickable links. Clicking POSTs to orckit's `/api/open`, which makes the path absolute against the process's `cwd` and then routes: files **inside the project root** (the `.idea` dir) open in the IDE via its command-line launcher (`<command> --line N --column C <abs-file>`); files **outside it** (temp files, generated artifacts) open in the OS default app; missing files error. No Toolbox, no plugin. No `.idea` → no links; never affects orchestration or the terminal UI.

```yaml
ide:
  command: webstorm   # default; the IDE's CLI launcher. Set to idea / pycharm /
                      # phpstorm / goland / … to match the user's IDE.
  # enabled: false    # disable the links entirely
```

Set `command` to match the user's IDE if it isn't WebStorm. If a user says clicks don't open anything, the usual fix is creating the launcher (IDE → Tools → "Create Command-Line Launcher") so `command` is on `PATH` — not a different config.

## `sandbox` (top-level, optional)

Add it when the user wants to run the same environment once per git worktree (parallel feature branches, agents working side by side). With the block present, `orc start` in a linked worktree runs the stack in an isolated OrbStack container reachable at `<worktree>.<project>.local`, on the same ports; the main checkout stays native unless `main_checkout: true` (then it runs as `main.<project>.local`). macOS + OrbStack only. Details and every field: [README.md → Worktree sandboxes](README.md#worktree-sandboxes).

Shape the config for it:

- `copy_files` for git-ignored files the stack needs (`.env.local` and friends) — a fresh worktree has none.
- `copy_home` for CLI logins the processes use (`.config/stripe`, `.config/gcloud`).
- `dockerfile` (starting `ARG ORCKIT_BASE` / `FROM ${ORCKIT_BASE}`) for tools the processes call that aren't Node: Java for Firebase emulators, a pinned CLI version matching the team's Macs.
- Package-manager store: the sandbox installs into its own `node_modules` (`isolate_node_modules`, default on), so mount the Mac's store to avoid re-downloading — pnpm: `mounts: [{ source: ~/Library/pnpm/store }]` + `env: { npm_config_store_dir: ~/Library/pnpm/store }`. Leave the project's pnpm/npm config alone; no cross-platform install settings are needed.

The app usually needs two changes too, which you should make or point out: dev servers with a Host-header check allow the sandbox hostname (`allowedHosts: [".local", ".test"]`), and browser-side URLs to local services derive from `location.hostname` rather than `localhost`. Memory is shared across all sandboxes (OrbStack's VM); a stack with several Angular/webpack dev servers needs ~10 GB.

When you run `orc start` yourself in a worktree that has `sandbox:` (or in the main checkout with `main_checkout: true`), it runs sandboxed; `--no-sandbox` runs natively. Manage leftovers with `orc sandbox list | stop | rm | prune`.

`.test` names: OrbStack only resolves `.local`, so `domain` must stay under `.local` — don't change it to `.test` or `.localhost` (neither reaches the container). If the user wants sandboxes on `.test` (e.g. for tools that treat `.test` as a local development host), point them at `orc sandbox dns install` (one-time, needs their sudo password; you can't run it for them). `orc start` then prints `<name>.<project>.test` URLs; `orc sandbox dns status` diagnoses it.

## Environment and secrets

`env` is a `{ KEY: value }` map merged into the spawned process's environment. **Do not put secrets in `env`** — the YAML is checked in. Tell the user to:

- source from a local `.env` (using their own shell or a wrapper command), or
- reference shell variables in `command` (`command: API_KEY=$API_KEY node server.js`) and rely on the parent shell to provide them.

## Anti-patterns — push back on these

- "Can you model our production k8s setup in Orckit?" → wrong tool. Orckit is local dev only.
- "Can Orckit attach to a server I started in another terminal?" → no, every process is spawned by Orckit.
- "Make these two processes' logs print in order." → within a wave processes start in parallel; logs interleave.
- "Add a process that just `sleep`s to delay startup." → use `depends_on` and `ready` instead.
- Hardcoded secrets in `env`.

## Validation checklist (run before handing back)

1. `npx orc validate -c <path>` exits 0.
2. Every process either has a `ready` check appropriate to its nature, or is intentionally fire-and-forget.
3. `depends_on` reflects real runtime dependencies, not preferences.
4. Every preflight check has an actionable `on_fail` message.
5. `restart` policy matches the process's nature (long-running vs one-shot).
6. `manual_retry: true` only on processes whose failure means "external thing isn't ready" — not on regular services.
7. Plain `docker run --name X` processes use `type: docker` + `container_name: X` (not `type: bash` + manual `stop_command`). The `container_name` must match the `--name=` in `command`. Validation now rejects the `type: bash` form outright.
8. Anything that must flush on shutdown (databases, caches) has a `stop_grace_ms` large enough to finish — the default is 10s, after which orckit escalates to SIGKILL. `firebase emulators:start` in particular stops its emulators in sequence and regularly needs more.
9. A process whose `command` is a wrapper script (`pnpm foo` → `./scripts/foo`) that runs `docker run --name X` inside still needs `type: docker` + `container_name: X` — validation can only see the command string, so it cannot catch this one for you. Without it the container outlives the shutdown and keeps its ports bound.
10. Hooks that "clean up a port" must never kill the holder of a *published container port* — that is the container platform's proxy (Docker Desktop, OrbStack), and killing it takes down the whole Docker daemon without freeing the port. Remove the container instead, or let `type: docker` do it.
11. No secrets in `env`.
12. With a `sandbox:` block: every git-ignored file a process reads is in `copy_files`, and every non-Node tool a process or hook calls (`java`, `stripe`, `gcloud`, …) is installed by `sandbox.dockerfile`.

## Programmatic API

```ts
import { Orckit, loadConfig } from '@orckit/cli';

const orckit = new Orckit(loadConfig('./orckit.yaml'));

orckit.on('process:ready', (name, ms) => console.log(`${name} ready in ${ms}ms`));
orckit.on('process:failed', (name, err) => console.error(`${name} failed`, err));

await orckit.start(['api']);       // starts api + its transitive deps
// ... do work ...
await orckit.dispose();            // graceful tear-down in reverse dep order
```

All config types come from Zod schemas and are re-exported from the package root (`OrckitConfig`, `ProcessConfig`, `ReadyCheck`, etc.). The lifecycle state machine is exported as a pure function:

```ts
import { transition } from '@orckit/cli';
const next = transition('starting', { kind: 'ready' });  // -> 'ready'
```

Full event list and CLI flag reference: [README.md](README.md).

## Querying a running orckit

If the user is already running `orc start` in another terminal, prefer querying its MCP server over spawning a new `orc`. `orc start` exposes read-only tools by default (`get_status`, `get_errors`, `get_logs`, `get_build_status`, `wait_for_build`) on `http://127.0.0.1:7676/mcp`. The user only needs to register it once with `claude mcp add --transport http orckit http://127.0.0.1:7676/mcp`.

- "Is the build running?" / "what's failing?" → call `get_status` (and `get_errors` if anything is in a failed state).
- "Show me the recent api output" → call `get_logs` with `{ name: 'api', lines: 100 }`.
- **Before running your own build/typecheck to verify a change** → call `get_build_status` (or `wait_for_build` with `{ name: 'web' }`) and use orckit's result. orckit already runs the project's watch build; spawning a duplicate `webpack`/`ng build`/`tsc` is wasteful and can race the watcher. Build phase is only tracked for `webpack`/`angular` process types — for others, fall back to running the check yourself.
- If the tools aren't connectable, the user hasn't started orckit — tell them to run `orc start` rather than silently spawning your own.

The port can be changed via `mcp.port` in YAML or `--mcp-port`; disable entirely with `mcp.enabled: false` or `--no-mcp`.

## Where to look

- **Schema (authoritative for every field, every default):** [src/config/schema.ts](src/config/schema.ts)
- **Runnable examples:** [examples/](examples) — minimal → fullstack, each with its own YAML and README. Best way to ground a generated config in something known-good.
- **Human reference + CLI flags + REPL commands:** [README.md](README.md)
