# Repo guide for AI coding agents

This repo builds **mu**: a CLI that runs AI agents in tmux, herdr or
Rex panes, coordinated through a task DAG.

## Read these first

1. [docs/guide/README.md](docs/guide/README.md): what mu does for a user.
2. [CHANGELOG.md](CHANGELOG.md): the upcoming version's entry is the
   source of truth for verbs, schema, and env vars.
3. [docs/VISION.md](docs/VISION.md): design pillars you must not violate.
4. [docs/ROADMAP.md](docs/ROADMAP.md): what's next and the promotion
   criteria. Read [Anti-feature pledges](docs/ROADMAP.md#anti-feature-pledges)
   before you add a dependency, an abstraction, or a surface.
5. [docs/VOCABULARY.md](docs/VOCABULARY.md): canonical terms for code,
   docs, and error messages. [docs/reference/](docs/reference/) holds env vars and naming.
6. [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md): the module map (what
   lives where in `src/`), plus deep dives under [docs/architecture/](docs/architecture/).

## Build, test, lint

```bash
npm install
npm run build            # tsup → dist/
npm run typecheck
npm run lint
npm run test:fast        # unit tier; safe to run concurrently
npm run test             # full suite, including integration
npm run test:stress      # pre-release stability gate
```

`tsc` is TypeScript 7 (fast typecheck). The `typescript` package is
aliased to 6.x on purpose: `tsup --dts` needs the programmatic API that
TS 7.0 lacks. Revisit at TS 7.1.

## Gates

Both gates run over budget on a shared host; measurements are in
[the test-health record](docs/test-health/2026-10-23-surface.md).

| Gate | Command | Budget |
|---|---|---|
| fast | `npm run typecheck && npm run lint && npm run test:fast` | 30 s |
| slow | `npm run build && npm run test` | 5 min |
| targeted slow | `npm run build && npx vitest run <files>` | — |

Workers run fast while iterating, then targeted slow for the changed area,
and fast on the final commit. The orchestrator runs fast + slow once per
merged batch (`npm run test` excludes lint and typecheck). Record gates per
[test-health](skills/mu/recipes/test-health.md#gate-contract).
`test/spawn-parallel-race.integration.test.ts` needs `dist/`, hence build
first.

## Code style

- Strict TypeScript with `noUncheckedIndexedAccess`, ESM only. Use
  `unknown` instead of `any`, and early returns instead of `!`.
- Throw typed error classes (`AgentNotFoundError`, `CycleError`,
  `MuxError` and its `TmuxError` / `HerdrError` / `RexError` subclasses, …) so
  `handle()` maps each to an exit code.
- Auto-fix sort and format with `npx biome check --write src test`.
  Never add `--unsafe`: it rewrites `delete process.env.X` into
  `process.env.X = undefined`, which sets the string `"undefined"`.
  Delete env vars as `const key = "FOO"; delete process.env[key];`.
- Files: aim under 800 LOC, and split a file over 1500 when you next touch
  it (not enforced; `extension/delegate.ts`, `src/cli/agents.ts` and
  `src/hosts.ts` are over today). Do not grow them.
- Layout is flat at the `src/` root. One level of subdirectory is
  allowed for a cohesive cluster: one theme, imports only from the
  cluster to root files, and a row in the ARCHITECTURE module map.

## Tests

- Unit tests use real SQLite in a temp dir and a mocked multiplexer.
  Install mocks with `installMux()` from `test/_mux.ts`: it sets the
  backend and its executor together and returns one `restore()`.
- TUI tests render through `test/_ink-render.ts` (see `test/README.md`).
- The fast tier (`*.test.ts`) stays in-process: mocked tmux and VCS,
  per-test temp DBs, no real tmux/git/jj/sl, no sleeps over 50ms.
- Name full-only tests `*.integration.test.ts`. They may use real
  tmux, herdr, Rex, VCS fixtures, or subprocesses. Real-tmux tests run on the
  private socket and need no `$TMUX`. Set `process.env.MU_SPAWN_LIVENESS_MS = "0"` in
  `beforeEach` when the spawned process is meant to live long.
- Integration tests use unique session names
  (`mu-test-<pid>-<ts>-<rand>`), poll (50ms × 10) instead of sleeping,
  and wrap `afterEach` cleanup in `try {} catch {}`. Unit tests call
  `setSleepForTests(async () => {})`.
- **Never stop the herdr server or kill its process from a test.** It
  destroys the user's real panes. herdr isolation is only a named
  session (`MU_HERDR_SESSION`, enforced by `assertHerdrIsolated()`), so
  close only what you created.
- `openDb()` refuses the real DB under vitest. Use `MU_DB_PATH` or
  `{ path }`.
- In tests, `openDb` on a new path copies a template DB built once per
  run (`test/_db-template.ts`). A test that pins fresh-file behaviour
  (the DDL, a refusal leaving the file empty) calls
  `vi.unmock("../src/db.js")`.
- `test/_setup.ts` clears inherited `MU_*` vars except `MU_HERDR_SESSION`.
  Opt in per test with `withEnv()` from `test/_env.ts`.
- Register extra tmux sockets and start private Rex servers through
  `test/_server-registry.ts` so teardown can stop them after an aborted run.
  See [mux tests](test/README.md#mux-tests).
- Workers run fast while iterating and slow for their changed area (see
  [Gates](#gates)); the orchestrator runs fast + slow once per
  merged batch. Tests may run concurrently across workers. A test that fails
  under load but passes alone is a test-infra concurrency bug (shared
  `/tmp`, sockets, leaked subprocesses). One that also fails alone is a
  real bug.
- `test/acceptance.integration.test.ts` is the end-to-end gate. Keep it
  green.

## Change rules

- **VOCABULARY first.** Add or rename a term in
  [docs/VOCABULARY.md](docs/VOCABULARY.md) before or with the code.
- **Roadmap gate.** Build only what is on the roadmap or meets all
  three promotion criteria: a real user hit the gap ≥2 times, the
  current design makes it straightforward, and it fits in <300 LOC.
  Otherwise add a ROADMAP entry and move on.
- **Commits:** one logical change each, scope prefix when useful
  (`schema: …`). The body says what changed and why, cites the VISION
  pillar or ROADMAP item, and states that the green gate passed. Add a
  [CHANGELOG.md](CHANGELOG.md) entry under the upcoming version.
- **State directories.** A change that breaks on-disk state compatibility
  with the released version gets a new versioned directory under
  `~/.local/state` (`<tool><major>`, e.g. `mu5`, `murmur2`), never a
  `<tool>-next` name; additive changes stay in the current directory (mu's
  is `mu5` since schema 14; mu 4's `mu-next` is the state import's source,
  never written). Never run a development build
  against the real state directory: tests and manual runs use the state-dir
  override (`MU_STATE_DIR`, `MU_DB_PATH`, a blank `MU_SYNC_DIR`; for murmur,
  `MURMUR_STATE_DIR`) and a private tmux socket.

## Common tasks

### Add a CLI verb

1. Write the SDK function (`src/agents.ts`, `src/tasks.ts`, …) with a
   typed result (`{ changed, previousStatus, … }`). Test with mocks.
2. Wire it in `src/cli.ts` with commander inside `handle(...)`. For
   `--workstream`, read `this.optsWithGlobals()`; the top-level option
   otherwise swallows it.
3. Document it in the matching `docs/guide/` how-to, VOCABULARY if
   it adds a term, and CHANGELOG. Remove any `mu sql` workaround it
   replaces. Touch `skills/mu/SKILL.md` only for a gotcha `--help`
   cannot state.
4. Smoke-test against real tmux, and on herdr with `MU_MUX=herdr` plus
   a private `MU_HERDR_SESSION` (on Rex: `MU_MUX=rex` plus `MU_REX_SERVER`
   naming a private `rex server run`) if it touches agents:

   ```bash
   MU_SYNC_DIR= MU_DB_PATH=/tmp/mu-smoke.db MURMUR_STATE_DIR=/tmp/mu-smoke-murmur \
     node dist/cli.js <verb> ...
   ```

   Blank `MU_SYNC_DIR` too. Otherwise the first flush writes the
   throwaway DB's `machine_id` into your real sync folder, and `mu sync`
   lists that phantom peer forever. `MURMUR_STATE_DIR` keeps the
   `murmur status` calls of the state read and the dashboard off your real
   murmur, whose inbox they drain.

### Update the schema

The schema is v14 (`CURRENT_SCHEMA_VERSION` and `CURRENT_SCHEMA` in
`src/db-schema.ts`, the upgrade in `src/db.ts`). `openDb` runs `upgradeSchema(db)`: the idempotent CREATE-IF-NOT-EXISTS DDL, any
missing `ADDED_COLUMNS`, the schema stamp, and the capture triggers with
their stamp, in ONE transaction. It accepts only v14 (no upgrade chain; a v14
file missing a later addition is completed) and refuses older DBs
(`SchemaTooOldError`) and newer ones (`SchemaTooNewError`), both exit 4.
A mu 4 (v13) DB reaches v14 only through the state import
(`src/state-import.ts`): `upgradeSchema(db, { v13: true })` completes its
copy, then `step13To14` converts it; a rebuild a v13 file needs goes there.

1. Bump `CURRENT_SCHEMA_VERSION` and mirror the shape in
   `CURRENT_SCHEMA`. A column an existing DB lacks also goes in
   `ADDED_COLUMNS` (plain nullable or defaulted: SQLite adds nothing else
   in place); such a column alone needs no bump. Changing `CAPTURED_COLUMNS` or a trigger generator means
   bumping `CAPTURE_VERSION` and the pinned checksum in
   `test/capture-persistent.test.ts`. Test the upgrade on a populated
   file (`test/fixtures/v13-populated.db.gz`, converted by `test/_v13.ts`;
   `test/loop-storage.test.ts`).
2. Classify every new table in `PORTABLE_TABLES` or
   `MACHINE_LOCAL_TABLES`. `test/entities.test.ts` fails otherwise.
3. Update `test/db.test.ts` and CHANGELOG `### Changed`.

### Add a multiplexer operation

Call sites use `await activeMux()` and never name a backend.

1. Add the method to `MuxBackend` (`src/mux/types.ts`) with a comment
   saying what it means.
2. Implement it in `src/mux/tmux.ts`, `src/mux/herdr.ts` and `src/mux/rex.ts`. A backend
   with no equivalent no-ops instead of throwing.
3. If only one backend can do it, make it optional and branch on the
   method's presence, not on `mux.name`.
4. Let `NoMultiplexerError` propagate (exit 5) for load-bearing calls
   (spawn, send, kill). Wrap best-effort calls in try/catch, like
   `resolveWorkerIdentity` in `src/tasks/claim.ts`.

Run tmux only through `tmux(args)`, herdr only through
`herdr(args)` and Rex only through `rex(args)`. A send goes through the
channel the agent's row recorded at spawn (`src/channels/`). pi agents are
driven through the control socket (`ctl`), not the multiplexer. A hook
harness on tmux (claude, codex, cursor-agent, muse, and pi on its
`MU_PI_CHANNEL=hooks` fallback) is on `hooks`: mu presses the harness's
clear-input key, pastes once (`pasteToPane`), and counts a local send
confirmed when the harness's `run_count` in murmur's pane inbox rises; an
unconfirmed one reports `unknown` and is never resent. A `--host` worker's
send reports `ack: sent` without polling; the next wait or send gate reads
the node, which confirms it. Every other pane is on `mux`:
herdr's `agent prompt` is one atomic call, Rex pastes through its
`sendToPane`, and tmux refuses the send (`AgentSendUnsupportedError`; it has
no `sendToPane`).

## Known traps

- **Silent `node dist/cli.js --help`** with "Detected unsettled
  top-level await" is an import cycle: a file in `src/cli/tui/`
  imported `../../../cli.js`. Import from the real source module
  instead (`rg 'from "\.\./\.\./\.\./cli\.js"' src/cli/tui/`).
- **ANSI in ink `<Text>`** breaks wrap math. Size and cut styled lines
  by visual width with `fitLine` in `src/cli/tui/text.ts`, and keep
  frame lines exactly the box width (`frame.tsx`).

## Orchestrating on this repo

Follow [skills/mu/recipes/orchestrator-loop.md](skills/mu/recipes/orchestrator-loop.md). Repo specifics:

- Each worktree runs `npm install` into its own `node_modules`. Never
  symlink main's.
- A worker may fork from an old HEAD. Check `git log` in its worktree
  and cherry-pick only the new shas.
- CHANGELOG.md conflicts are routine: keep both halves in order.
  Resolve source conflicts by hand, never with `--ours` or `--theirs`.
- Fix a worker's bug in a separate commit after the cherry-pick. Do
  not amend it.
- Gate the merged tree with the fast gate and the slow gate (see
  [Gates](#gates)) plus `node dist/cli.js --help`.
- The installed `mu` may be older than the branch build. Confirm a
  worker received its brief (`mu agent read <w> -n 3`).

## Skill files are context, not documentation

`skills/mu/SKILL.md` loads into every orchestrator's context, and
the recipes in `skills/mu/recipes/` on demand. Every word competes with the
user's work. The recipes are written for an agent with no context;
[recipes/brief.md](skills/mu/recipes/brief.md) holds the rules, and
they apply to the skill files too.

- Leave verb lists, flags, and option tables to `--help`. The skill
  carries only what `--help` cannot: the gotcha, the reason, the trap.
- Say each thing once, next to where it applies.
- SKILL.md holds the trigger and the rule. Detail that only some
  branches need goes in a recipe under `skills/mu/recipes/`, with a
  row in SKILL.md's recipe index. Recipes reference only mu, never
  skills outside this repo.
- `docs/guide/` pages stay terse for humans and link to the recipe
  instead of restating it.
- Delete sentences the model obeys by default. State the target
  behaviour.

A commit that grows SKILL.md must say why. "The new verb needed
documenting" is not a reason.

## What not to do

- No config file. mu is CLI flags plus env vars.
- No daemon, watcher, or background process. Every invocation is
  short-lived.
- No abstraction without two real implementations today.
- No wrappers around wrappers, no JS-string codegen, no facade over
  SQLite (it is the canonical state; read it directly).
- No template or discovery system for agent roles.
- No render layer beyond `cli-table3` + `picocolors`, except `ink`
  inside `src/cli/tui/`. Never a second TUI stack.
- Don't bundle pi. It is an optional peer dependency.
- Write files only under `~/.local/state/mu5/`, `~/.cache/mu/`, or the
  repo. The one exception is `mu init`, which writes its own hook entries and
  skill copies into each harness's config, where `CLAUDE_CONFIG_DIR` and
  `CODEX_HOME` put it (spec D13, D17). The cache dir
  holds only files mu can lose at any time.

## When you're done

Run the fast gate, then the slow gate for your changed area (see
[Gates](#gates)):

```bash
npm run typecheck && npm run lint && npm run test:fast
npm run build && npx vitest run <files>
```

The orchestrator runs the fast gate and `npm run build && npm run test` on
each merged batch.

Then check that VOCABULARY, ARCHITECTURE, and CHANGELOG reflect the
change.
