# The control plane

The control plane is the local endpoint every running `micromux` opens. The TUI, the MCP server, and the `micromux ctl` client all speak to it, so any of them can inspect and steer a session with identical semantics.

`micromux --version` prints the control protocol's version beside the release, such as
`micromux-cli 0.5.3 (protocol 4.0)`. A client and a session from different releases work together
as long as their protocol's major version matches.

## `micromux ctl`

`ctl` is the shell client — the same control plane an agent uses, dogfooded from your terminal. It targets the session for the config in the current directory, or for the config you pass with `--config` or the session you name with `--session`. Like `micromux` itself, it looks for the config only in the current directory, not in its parents, so from a subdirectory of a project pass `--config`.

```console
$ micromux ctl ls
API server           id=api origin=configured desired=Enabled execution=Running health=Healthy generation=1
web                  id=web origin=configured desired=Enabled execution=Running health=- generation=1
worker               id=worker origin=configured desired=Enabled execution=Running health=- generation=1
postgres             id=postgres origin=configured desired=Enabled execution=Running health=Healthy generation=1
redis                id=redis origin=configured desired=Enabled execution=Running health=Healthy generation=1
migrate              id=migrate origin=configured kind=job desired=Enabled execution=Completed health=- generation=1
payments             id=payments origin=configured desired=Enabled execution=Running health=Unhealthy generation=1
checkout             id=checkout origin=configured desired=Enabled execution=Blocked health=- generation=0
seed                 id=seed origin=configured kind=job run=manual desired=Enabled execution=Pending health=- generation=0
E2E browser          id=e2e origin=configured resource=browser desired=Enabled execution=Running health=- generation=1
  resources:
    - browser: held by demo (~/dev/micromux/examples/demo), reason "taken to start e2e", granted just now (at 12:00 +00:00), must renew within 1h (by 13:00 +00:00)
```


Common actions:

```bash
micromux ctl ls                       # list services and their state
micromux ctl logs api --tail 50       # recent logs for a service
micromux ctl log-runs api             # retained run generations
micromux ctl logs api --run-generation 2 --tail 200
micromux ctl restart api              # restart (respecting deps + health)
micromux ctl restart-all
micromux ctl enable worker            # enable (and start)
micromux ctl disable worker
micromux ctl health payments          # latest healthcheck attempt (--history for all)
micromux ctl wait api                 # block until api is healthy (or fail fast)
micromux ctl wait migrate --exit      # block until a one-shot run exits
micromux ctl describe                 # session identity, browser URLs, allocated ports, resources
micromux ctl stop                     # stop the whole session, freeing its ports
micromux ctl reserve desktop-app      # reserve a shared resource (see below)
```

Because these go through the control plane, a restart re-applies dependency gating and reloads the latest service definition — the same reason restarting *through* micromux beats `kill` + rerun.

### Inspecting health

`micromux ctl health <id>` prints the latest probe for a service's live run — its command, exit status, and output:

```console
$ micromux ctl health payments
attempt 1 `sh -c "echo 'connect: connection refused'; exit 1"` -> success=false exit_code=1
  connect: connection refused
```


Add `--history` to see the retained attempts (oldest first) instead of only the latest — useful when a probe is flapping.

### Waiting from a script

`micromux ctl wait <id>` blocks until a service is up, and healthy if it has a healthcheck. With `--exit` it waits for the service's run to exit instead, for one-shot jobs such as migrations. It gives up after `--timeout` (default `60s`), and `--after-generation <n>` accepts only a run newer than generation `n`, such as the one `ctl restart` printed.

A wait does not hang on something that cannot happen. It fails at once when the service is disabled or retired, or when it is blocked behind a dependency that will not meet its condition without your help: one that exited and whose restart policy will not start it again, that is disabled or retired, or that is waited on as `healthy` but has no healthcheck, directly or further down the chain. The message names that dependency, its state, and its exit code.

The exit code tells the outcomes apart:

| Code | Meaning |
|---|---|
| `0` | The service is healthy, or the job completed; with `--exit`, its run exited with status 0. |
| `3` | The run exited instead, or the job failed; with `--exit`, it exited with a non-zero status. |
| `4` | The service is blocked behind a dependency that failed. |
| `5` | The service is disabled or retired, or the job finished or is a manual job that has not run, and nothing asked it to run again. |
| `124` | The timeout elapsed. |

After a restart, pass the generation `ctl restart` printed, so the wait cannot settle on the run the restart replaced:

```bash
generation=$(micromux ctl restart seed | sed -n 's/.*(generation \([0-9]*\)).*/\1/p')
micromux ctl wait seed --exit --after-generation "$generation" && micromux ctl wait api
```

The MCP `wait_for_healthy` and `wait_for_exit` tools follow the same rules; a dependency failure comes back as an error whose data names the failed dependency.

## Shared resources

A service that names a [`resource`](https://romnn.github.io/micromux/docs/configuration/services/#shared-resources) runs only in the session that holds the resource. `Enable` and `Restart` of such a service take the resource when it is free and otherwise queue the session for it, first in, first out, and record the start; the service then waits, with `waiting_for_resource` set in its snapshot, and starts on its own once the session gets the resource and its dependencies are ready. `RestartAll` and a dynamic service's start or replacement take only a free resource: while another session holds or queues for it, they fail with `Busy`, naming the holder, and change nothing; `RestartAll` leaves a service whose start waits for its resource waiting. Session startup and other automatic starts take a free resource when the service is ready to run, and otherwise disable the service with an event naming the holder and how to queue. `ctl` reserves, renews, and releases it for the session of the current project:

```bash
micromux ctl enable desktop                                # queue, and start it once granted
micromux ctl reserve desktop-app --for 1h --reason "why"   # the same for every service that starts with the session
micromux ctl wait --reservation desktop-app --timeout 2h   # block until the session holds it
micromux ctl renew desktop-app                             # move renew_by an hour out; lists the queue
micromux ctl release desktop-app                           # hand it over as soon as another session queues
```

The session keeps its own queued request alive while a service waits for it, and queues it again if it lapsed across a long suspend, so nothing has to run between queueing and the grant. Disabling the last service that waits gives the request up, and disabling the last one that runs gives the grant up once it stopped.

`ctl ls` marks each service that names a resource with `resource=<name>`, followed by `(queued)` while its start waits, and `ctl ls` and `ctl describe` end with each resource the session uses: its holder's session and worktree, its estimate and reason, when it was granted and must renew, then the waiting requests in order. Times read relative first, then as the local clock time with its UTC offset, such as `renews in 59m (at 23:22 +01:00)`. When the description would be too large, the resources are left out and the listing says so.

`wait --reservation` only looks at the request every two seconds, with the `ReservationStatus` request: it neither renews a queued request nor extends a grant, so waiting after a release keeps the release. It reports that the session holds the resource; `ctl wait SERVICE` reports when a service that waited is ready. A brief failure, a slow answer, or a broken connection does not end it; it keeps looking until the timeout. Waiting without a request fails and says how to queue. The exit code tells the outcomes apart:

| Code | Meaning |
|---|---|
| `0` | The session holds the resource. |
| `5` | The request can no longer be granted: it was released or replaced, the session hands the resource over, or the session stopped or was replaced. |
| `124` | The timeout elapsed; the request stays queued, and the last position and holder are printed. |

`release` of a grant keeps the services running while nobody waits, and the reply says the session still holds the resource and hands it over as soon as another session queues; once one does, within seconds, the session stops its services that need the resource and the next session gets it after they and their cleanups are gone. `release` of a queued request drops it, with the starts that waited for it.

Your working directory decides your project: the config found in it or the nearest directory above it, whatever `-c` selects. Unlike the lookup that picks the session `micromux`, `ctl`, `env`, and `exec` run or reach, which looks only in the current directory, this one walks up. A session lets only clients of its own project control its services that need a resource, reserve for it, or stop it while it holds, waits for, or runs one; it refuses everyone else, `ctl` and MCP clients in other worktrees included, and says which project may. A client whose working directory is outside any project names no project and is refused the same way:

```text
this connection did not name its project; run micromux from inside <project dir> (a client outside any project names none)
```

The MCP server offers the same operations for the session of the project it runs in, whatever `MICROMUX_SESSION` selects: `enable_service`, `reserve_resource`, `renew_reservation`, `release_resource`, and `wait_for_reservation`, whose timeout is bounded like `wait_for_healthy`'s and which only looks, like `ctl wait --reservation`. Their replies carry `renew_in_secs` next to the Unix-millisecond deadlines. A `wait_for_reservation` that times out returns the request's last position and the holder. `list_sessions` and `list_services` show each resource's holder and queue.

## Run commands in the session environment

A task you run yourself, such as a migration, a seed script, or a one-off `psql`, needs the ports and variables the session's services get. `micromux exec` runs it with them, and `micromux env` prints them:

```bash
micromux exec task migrations:reset                   # run with the session's environment
micromux exec --service api -- cargo run --bin seed   # run with what the `api` service gets
micromux env                                          # KEY=value lines, quoted for a shell
psql -p "$(micromux env POSTGRES_PORT)"               # one name prints just its value
eval "$(micromux env --export)"                       # load them into the current shell
micromux env --service api --format json
micromux env --file                                   # the path of a dotenv file with them
```

Both read the environment from the running session over the control plane, so they match what its services got, and `exec` and `env` never disagree. Without a running session they fail instead of falling back to `.env` files, unless you pass [`--if-running`](#without-a-session). On success they print nothing besides the requested output.

**Which session.** Like `ctl`, they use the session for the config in the current directory, or for `--config <path>`. They do not look in parent directories, so from a subdirectory of a project they fail with `missing config file` unless you pass `--config`; the MCP server, by contrast, finds the config at or above its directory. A session for any other config does not count, not even one in a subdirectory. `--session` selects a session by `name:`, `pid:`, or `hash:`, as [`micromux attach`](https://romnn.github.io/micromux/docs/tui/#attach-to-a-running-session) does.

**Which variables.**

- Without `--service`, the session's own environment: the [session-wide `env_file`](https://romnn.github.io/micromux/docs/configuration/services/#session-wide-env-files), with the variables the session injects into every service over it: `MICROMUX_SESSION`, `MICROMUX_SESSION_DOMAIN`, `MICROMUX_PROXY_PORT`, `MICROMUX_HOST_SUFFIX`, and every [allocated port](https://romnn.github.io/micromux/docs/configuration/sessions/#allocated-ports). The session reads the files from disk for every call, resolved exactly as for its services, so an edit or a new key shows at once, without a restart or a reconcile. Which files the list names follows the config the session last loaded. A session that predates protocol 3.20 has no session-wide `env_file`, so its variables are its whole environment.
- With `--service <id>`, that service's resolved session-wide `env_file`, own `env_file`, and `environment` entries, interpolated, with the session's variables applied. It takes the service id, not its display name. While the service runs, these are the values its process started with; when its config changed since, for example through `ctl reconcile`, a note on stderr says so. The variables micromux sets on every service process itself (`TERM`, `CLICOLOR`, `CLICOLOR_FORCE`, `FORCE_COLOR`) are not included.
- Variables your shell already has, such as `PATH`, `AWS_PROFILE`, or a `DATABASE_URL` from direnv, come from your shell. `exec` keeps them, and only the session's configured variables override variables of the same name. The environment micromux itself was started with, which its services also inherit, is not part of it.

### `micromux exec`

The command replaces the micromux process: it runs in your terminal with your stdin, stdout, and stderr, receives your signals directly, and its exit status is the exit status of `micromux exec`. Everything after the command name belongs to the command, so `micromux exec ls -la` needs no `--`, and `--` works as well.

| Code | Meaning |
|---|---|
| `125` | micromux failed before running the command: no session (unless `--if-running`), a session too old for it, an unknown service, or a control-plane error. |
| `126` | The command was found but cannot run. |
| `127` | The command was not found. |
| any other | The command's own exit status. |

### `micromux env`

- By default it prints sorted `KEY=value` lines. A value is single-quoted for a POSIX shell when it contains anything but letters, digits, and `_@%+=:,./-`.
- `--export`, or `--format shell`, prints `export KEY=value` lines for `eval`.
- `--format json` prints one JSON object.
- Names after the options print only those variables, and a single name in the default format prints its bare value. A name that is not set fails the command, and nothing goes to stdout, so a script never runs with an empty port.
- A key a shell cannot assign, anything but `[A-Za-z_][A-Za-z0-9_]*`, is left out of the line formats with a warning on stderr that names it. JSON keeps every key.
- `--file` has the session write the environment, or a service's with `--service`, to a dotenv file and prints the file's absolute path; see below.
- It exits 1 on any failure.

### Dotenv files for other tools

Some tools load dotenv files themselves and expand `${VAR}` from the file alone, ignoring the environment they run in. go-task's `dotenv:` is one: even under `micromux exec task …`, it rebuilds `DATABASE_URL=postgres://…:${POSTGRES_PORT}/app` with the file's default port. `micromux env --file` gives such a tool a file with the session's resolved values:

```yaml
# taskfile.yaml
vars:
  MICROMUX_ENV_FILE:
    sh: if command -v micromux >/dev/null 2>&1; then micromux env --file --if-running; fi
dotenv:
  - "{{.MICROMUX_ENV_FILE}}" # the session's resolved environment wins
  - .env.local
  - .env
```

- The session owns the file. It lives in a private directory next to the session's control socket, readable by your user only, and goes away when the session stops.
- Every call rewrites the same path with the environment as it is now, replacing the file in one step, so a reader never sees half of it.
- Each value is double-quoted, with quotes, backslashes, newlines, and `$` written as `\"`, `\\`, `\n`, and `\$`, so godotenv (go-task), Docker Compose, and dotenvy all read it back literally and expand nothing. godotenv misreads a double-quoted value that ends in `"`, so such a value is single-quoted instead.
- An environment the file cannot carry exactly fails the command, which names the variables but never their values, and leaves the file as it was: a key that is not a shell variable name, or a value no quoting carries through all three readers, one that ends in a backslash, or ends in `"` and contains `'` or a carriage return before a line feed. Leaving such a variable out would let the tool take its value from the next file it loads instead.
- It needs a session started by this micromux or a later one, protocol 3.20.

### Without a session

With `--if-running`, a project no session runs for is not an error: `micromux env` prints nothing and exits 0, and `micromux exec` runs the command with your environment unchanged. A script can then fall back to its own defaults when no session runs, and only then.

Every other failure still fails: a session that is starting, stopping, or runs without a control plane, a control plane that does not answer, a session too old for the command, an unknown service. micromux decides by two locks: the config's owner lock, which a session takes before anything else and releases as it starts stopping, and its port-registry lock, which it holds until its services have stopped. It asks about the second while it keeps a new session from claiming the config, so a session that cannot answer is never mistaken for none, not even while its services drain after `ctl stop` or a new session takes over. `--if-running` asks about the project's session, so it does not combine with `--session`.

> [!WARNING]
> Values can be secrets from env files. They reach stdout or the command only when you run one of these commands, and micromux never logs them, unless you replace its log filter with a `RUST_LOG` that turns on debug logging for the MCP library (`rmcp`), which records tool results. The control socket is reachable by your user only.

Agents read the same environment with the MCP `get_session_env` tool. It returns only the variable names unless the agent asks for `names`, since env files can hold secrets.

## Headless sessions: `micromux serve`

`micromux serve` runs the supervisor **without a TUI**, serving the control plane until stopped. It's how agent-managed sessions run: an agent calls the MCP `start_session` tool (which spawns a detached `serve`), works against it, and you can watch with [`micromux attach`](https://romnn.github.io/micromux/docs/tui/#attach-to-a-running-session) or steer it with `micromux ctl`.

```bash
micromux serve                    # headless; control plane only
micromux serve --config ./micromux.yaml
```

Stop a headless session with `micromux ctl stop` or the MCP `stop_session` tool.

## Reconcile on-disk changes

When you edit a live session's `micromux.yaml`, apply the changes without restarting the whole session:

```bash
micromux ctl reconcile --dry-run   # show the semantic diff
micromux ctl reconcile             # apply it
```

Reconciliation **adds** newly-defined services, **retires** removed ones, and **updates** changed definitions. Additions and removals take effect immediately; a changed definition is used on the service's **next restart** (manual, enable, or a due automatic restart). Reconciliation does not by itself restart a changed process. Until a restart applies the change, `micromux ctl ls` marks the service `config=stale`, the TUI says so in its service details, and `micromux env --service` notes it. That covers every change a restart would apply, including the contents of an `env_file`, which reconciliation reads again.

Reconciliation also applies the config's service order immediately, without restarting processes or clearing logs and health history. Dry runs report a relative order change as `changed` with a `service order` detail. Configured services appear first, in file order; dynamic services and retained removed services follow, keeping their relative order. A move alone does not mark the running definition stale.

> [!NOTE]
> Over MCP the same flow is `reconcile_config` — run it with `dry_run=true` first, then apply. For a config that has no running session, `validate_config` checks a candidate file without starting anything.

## Protocol compatibility

Protocol 3 peers accept additive fields from newer minor revisions. Revision 3.8 changed transient disk-log rotation and reader saturation failures from `LimitExceeded` to the retryable `Busy` code. Revision 3.9 distinguishes an uninitialized disk-reader pool and reports reads that still occupy workers after their callers leave. Revision 3.11 adds `session` to the session description: its name, [browser URLs and allocated ports](https://romnn.github.io/micromux/docs/configuration/sessions/), and whether the shared proxy serves its routes. Revision 3.12 adds `last_cleanup` to service snapshots and the `CleanupStarted`, `CleanupFinished`, and `CleanupFailed` event kinds for [cleanup commands](https://romnn.github.io/micromux/docs/configuration/services/#cleanup); older peers read the new kinds as `Unknown`. Revision 3.13 adds `dependency_failure` to service snapshots, naming the dependency that keeps a blocked service from ever starting on its own, and the `DependencyFailed` event kind. Revision 3.14 adds `depends_on` to service snapshots. Revision 3.15 adds the `GetEnvironment` request, which returns the session's variables or one service's resolved environment with their values; `micromux env`, `micromux exec`, and `get_session_env` refuse a session older than 3.15 and ask you to restart it. Revision 3.16 adds [jobs](https://romnn.github.io/micromux/docs/configuration/services/#jobs): `kind` and `manual` on service snapshots and dynamic-service definitions, the `Completed` and `Failed` execution states, and an optional dependency `condition` whose absence means the target's natural condition. Older peers read the new states as `Unknown`, so restart an attached TUI or a running `micromux mcp` after upgrading; an older session ignores `kind` and creates a dynamic job as a service. Revision 3.17 adds `path` and `strip_prefix` to the session's routes for [path routes](https://romnn.github.io/micromux/docs/configuration/sessions/#path-routes); a route's `url` already ends in its path. Revision 3.18 adds the `SendInput` and `ResizeTerminal` requests, which an [attached TUI](https://romnn.github.io/micromux/docs/tui/#attach-to-a-running-session) uses to type into services and resize their PTYs; it sends neither to an older session, and MCP never sends them. Revision 3.19 adds optional `session.git` context to session descriptions: the current Git branch and a cached open GitHub PR number. GitHub lookups run in the background and may be absent on the first response; no Git or GitHub tooling is required. Revision 3.20 adds the `GetSessionEnvironment` request, which returns the session's own environment, its session-wide `env_file` included, and the `WriteEnvironmentFile` request behind `micromux env --file`. `GetEnvironment` without a service still returns the session's variables alone, so an older client that shows those values unasked never shows an env file's. `micromux env`, `micromux exec`, and `get_session_env` without a service send the new request to a 3.20 session and the old one to an older session, which has no session-wide `env_file`; `micromux env --file` refuses a session older than 3.20 and asks you to restart it. Revision 3.21 adds [shared resources](#shared-resources): the `Identify`, `Reserve`, `RenewReservation`, and `ReleaseReservation` requests, `resource` on service snapshots, and `session.reservations` in descriptions. Clients identify only to a 3.21 session, and the reservation commands and tools refuse an older session and ask you to restart it.

Protocol 4.0 changes what three requests mean, so it starts a new major line: `Enable` and `Restart` of a service that names a resource queue for it instead of failing while another session holds it, `Reserve` also requests a start of the services that start with the session, and `ReleaseReservation` keeps the services running until another session queues. It adds the `ReservationStatus` request, `waiting_for_resource` on service snapshots, and the `ResourceGranted` event kind. A 4.0 client refuses a 3.x session and a 3.x client a 4.0 session, so restart running sessions, attached TUIs, and `micromux mcp` after upgrading. Every 4.x session answers every request the 3.x line added.
