@mu-crew/mu 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2615 @@
1
+ # mu — Usage Guide
2
+
3
+ A practical, copy-pasteable tour of mu. Terms are canonical — see
4
+ [VOCABULARY.md](VOCABULARY.md); the canonical verb list is
5
+ `mu --help`, with the gotchas in `## CLI overview` of
6
+ [skills/mu/SKILL.md](../skills/mu/SKILL.md).
7
+
8
+ > **Status:** 1.0 (pre-release). Typed verbs span 7 namespaces
9
+ > (`workstream`, `agent`, `task`, `workspace`, `log`, `me`, `db`) plus
10
+ > bare top-level verbs (`state`, `doctor`, `sql`, `undo`, `sync`,
11
+ > `rebuild`). Every verb accepts `--json`. Schema v10. See
12
+ > [CHANGELOG.md](../CHANGELOG.md).
13
+
14
+ **In a hurry? Start at [§ 0. Common scenarios](#0-common-scenarios).**
15
+
16
+ *If anything below disagrees with `mu --help`, trust `mu --help`.*
17
+
18
+ ---
19
+
20
+ ## Table of contents
21
+
22
+ 0. [Common scenarios (start here)](#0-common-scenarios)
23
+ 1. [Setup](#1-setup)
24
+ 2. [Get oriented (`mu doctor`)](#2-get-oriented)
25
+ 3. [Create a workstream (`mu workstream init`)](#3-create-a-workstream)
26
+ 4. [Plan some work as a DAG (`mu task add`)](#4-plan-some-work-as-a-dag)
27
+ 5. [See the graph (dashboard + state API)](#5-see-the-graph-dashboard--state-api)
28
+ 5b. [The TUI dashboard (interactive)](#5b-the-tui-dashboard-interactive)
29
+ 6. [Spawn a crew (`mu agent spawn`)](#6-spawn-a-crew)
30
+ 7. [Watch the crew live (`tmux attach`)](#7-watch-the-crew-live)
31
+ 8. [Send work to an agent (`mu agent send`)](#8-send-work-to-an-agent)
32
+ 9. [Read what an agent did (`mu agent read`)](#9-read-what-an-agent-did)
33
+ 10. [The claim protocol from inside a pane (`mu task claim`)](#10-the-claim-protocol--from-inside-an-agents-pane)
34
+ 11. [Drop notes (durable context) (`mu task note`)](#11-drop-notes-durable-context)
35
+ 12. [Close out a task](#12-close-out-a-task)
36
+ 13. [The SQL escape hatch (`mu sql`)](#13-the-sql-escape-hatch-is-your-friend)
37
+ 14. [Recovery scenarios](#14-recovery-scenarios)
38
+ 15. [Cleanup](#15-cleanup)
39
+ 15.6. [Multi-machine sync](#156-multi-machine-sync)
40
+ 16. [One-shot demo script](#16-one-shot-demo-script)
41
+ 17. [Mental model in three sentences](#mental-model-in-three-sentences)
42
+ 18. [What's NOT in mu](#whats-not-in-mu-and-how-to-work-around-it)
43
+ 19. [Where to go from here](#where-to-go-from-here)
44
+ 20. [Multiplexer backends (tmux and herdr)](#20-multiplexer-backends-tmux-and-herdr)
45
+
46
+ ---
47
+
48
+ ## 0. Common scenarios
49
+
50
+ Six worked paths, every command run live. Output is verbatim (colour
51
+ stripped). Set `MU_DB_PATH=/tmp/mu-play.db` first if you want to try
52
+ them without touching your real registry.
53
+
54
+ ### 0.1 First 5 minutes
55
+
56
+ Init a workstream, plan two tasks with a dependency, see what's ready.
57
+
58
+ ```bash
59
+ mu workstream init auth
60
+ mu task add design -w auth --title "Design auth module" --impact 80 --effort-days 2
61
+ mu task add build -w auth --title "Build auth module" --impact 80 --effort-days 5 --blocked-by design
62
+ mu task next -w auth
63
+ mu task tree build -w auth
64
+ ```
65
+
66
+ ```
67
+ Created workstream auth (mux session mu-auth)
68
+ Next:
69
+ Attach the session : tmux attach -t mu-auth
70
+ Plan tasks : mu task add -w auth --title "..." --impact 50 --effort-days 1
71
+ Spawn an agent : mu agent spawn <name> -w auth
72
+ See state : mu state -w auth
73
+
74
+ Added task design (workstream=auth, impact=80, effort=2)
75
+
76
+ Added task build (workstream=auth, impact=80, effort=5)
77
+ blocked by: design
78
+
79
+ ┌────────┬────────┬────────────────────┬────────┬────────┬──────┬───────┐
80
+ │ name │ status │ title │ impact │ effort │ ROI │ owner │
81
+ ├────────┼────────┼────────────────────┼────────┼────────┼──────┼───────┤
82
+ │ design │ OPEN │ Design auth module │ 80 │ 2 │ 40.0 │ — │
83
+ └────────┴────────┴────────────────────┴────────┴────────┴──────┴───────┘
84
+
85
+ Tree of build (blockers below; --down for dependents)
86
+ build OPEN Build auth module
87
+ └── design OPEN Design auth module
88
+ ```
89
+
90
+ `build` is absent from `mu task next` because `design` blocks it.
91
+ Close `design` and `build` becomes ready. Details: [§ 3](#3-create-a-workstream),
92
+ [§ 4](#4-plan-some-work-as-a-dag).
93
+
94
+ ### 0.2 The dispatch loop: spawn, claim, send, wait, close
95
+
96
+ ```bash
97
+ mu agent spawn worker-1 -w auth --cli sh # --cli pi for a real agent
98
+ mu task claim design -w auth --for worker-1
99
+ mu agent send worker-1 -w auth 'Design the auth module, then: mu task close design --evidence "..."'
100
+ mu task wait design -w auth --timeout 60 --on-stall exit # blocks until CLOSED
101
+ mu agent close worker-1 -w auth
102
+ ```
103
+
104
+ ```
105
+ Spawned worker-1 (sh) in window worker-1 of mu-auth, pane %88
106
+
107
+ Claimed design for worker-1 (OPEN → IN_PROGRESS)
108
+ Next:
109
+ Drop a note (single-quote to defer shell expansion) : mu task note design 'FILES: ...\nDECISION: ...' -w auth
110
+ Close with grounding : mu task close design --evidence "..." -w auth
111
+ Release if blocked : mu task release design -w auth
112
+
113
+ sent 23 bytes to worker-1
114
+
115
+ all-of 1 reached CLOSED in 4094ms
116
+ ✓ design (CLOSED)
117
+
118
+ Closed worker-1
119
+ ```
120
+
121
+ Exit codes from `mu task wait`: `0` met, `5` timeout, `6` the owning
122
+ pane died, `7` stalled (with `--on-stall exit`). See
123
+ [§ Wait exit codes](#wait-exit-codes-mu-task-wait).
124
+
125
+ `mu agent send` verifies delivery. If it prints `warning: ... was NOT
126
+ submitted`, the text is sitting unsubmitted in the pane — the agent has
127
+ not seen it. That is the failure mode `exit 0` used to hide; check
128
+ before you wait on the task.
129
+
130
+ ### 0.3 Laptop ↔ devserver
131
+
132
+ Same `MU_SYNC_DIR` on both machines. No export step, no import step, no
133
+ sync verb in the loop.
134
+
135
+ ```bash
136
+ # both machines, in your shell rc
137
+ export MU_SYNC_DIR=$HOME/Sync/mu
138
+
139
+ # laptop
140
+ mu workstream init app
141
+ mu task add auth_fix -w app -t "Fix the auth redirect" -i 80 -e 2
142
+
143
+ # devserver — the ordinary command already ingested it
144
+ mu task list -w app
145
+ mu task close auth_fix -w app --evidence "shipped in #412"
146
+
147
+ # laptop
148
+ mu task show auth_fix -w app
149
+ ```
150
+
151
+ ```
152
+ ┌──────────┬────────┬───────────────────────┬────────┬────────┬──────┬───────┐
153
+ │ name │ status │ title │ impact │ effort │ ROI │ owner │
154
+ ├──────────┼────────┼───────────────────────┼────────┼────────┼──────┼───────┤
155
+ │ auth_fix │ OPEN │ Fix the auth redirect │ 80 │ 2 │ 40.0 │ — │
156
+ └──────────┴────────┴───────────────────────┴────────┴────────┴──────┴───────┘
157
+
158
+ Closed auth_fix (OPEN → CLOSED)
159
+ evidence: shipped in #412
160
+
161
+ auth_fix — Fix the auth redirect
162
+ workstream : app
163
+ status : CLOSED
164
+ ...
165
+ Notes (1)
166
+ 2026-08-02T05:49:15.361Z worker-2
167
+ CLOSE: shipped in #412
168
+ ```
169
+
170
+ **Both machines edit at once.** Merges are per-FIELD, so different
171
+ fields of the same task both survive:
172
+
173
+ ```bash
174
+ # laptop # devserver
175
+ mu task update t1 -w app --impact 95 mu task close t1 -w app
176
+ ```
177
+
178
+ ```
179
+ # both machines, after both have synced:
180
+ t1 — Concurrent demo
181
+ status : CLOSED
182
+ impact : 95
183
+ ```
184
+
185
+ Same field on both machines: the newer HLC wins, silently. Peer status
186
+ is `mu sync`; a torn transfer is `mu sync --repair <peer-prefix>`. Full
187
+ section: [§ 15.6](#156-multi-machine-sync).
188
+
189
+ ### 0.4 I made a mistake
190
+
191
+ Every user-visible action is one **group** of ops. Find it, preview,
192
+ apply.
193
+
194
+ ```bash
195
+ mu task update build -w auth --impact 5 # oops
196
+ mu undo # what can I undo?
197
+ mu undo 6380dd3d # preview (dry run)
198
+ mu undo 6380dd3d --yes # apply
199
+ ```
200
+
201
+ ```
202
+ mu undo — most recent undoable action:
203
+ 6380dd3d task.update — 1 op
204
+
205
+ recent groups (newest first):
206
+ * 6380dd3d task.update — 1 op
207
+ 1abb5038 task.add — 2 ops
208
+ 4f93f1df task.add — 1 op
209
+ 70af8fb8 workstream.init — 1 op
210
+
211
+ mu undo 6380dd3d — would revert task.update
212
+ restore task auth/build impact=80 updated_at=2026-08-02T05:49:34.545Z
213
+
214
+ (dry-run; rerun with --yes to apply)
215
+
216
+ Undid 6380dd3d (task.update)
217
+ task auth/build impact=80 updated_at=2026-08-02T05:49:34.545Z
218
+ 1 row change(s), recorded as group 3814ed17
219
+ This undo is itself undoable: mu undo 3814ed17 --yes
220
+ ```
221
+
222
+ The undo is itself a group — `mu undo 3814ed17 --yes` is redo. Any
223
+ unique prefix of a group id works. Undo reverts ROWS: killed panes and
224
+ freed workspace dirs do not come back. See
225
+ [§ Undoing one action](#undoing-one-action-mu-undo).
226
+
227
+ ### 0.5 Something looks wrong
228
+
229
+ ```bash
230
+ mu doctor # exit 0 healthy, 5 on drift
231
+ mu doctor --deep # full rebuild + field diff; slower
232
+ mu doctor --disk # + per-workspace byte usage (walks every checkout)
233
+ ```
234
+
235
+ ```
236
+ mu doctor
237
+
238
+ environment
239
+ tmux : ok (tmux 3.7b)
240
+ $TMUX : set
241
+ $TMUX_PANE : %21
242
+ $MU_SESSION : auth
243
+
244
+ db
245
+ path : /tmp/mu-play.db
246
+ schema : ok (10 tables)
247
+ schema_version : 10
248
+ journal_mode : wal
249
+ foreign_keys : on
250
+
251
+ workstream
252
+ current : auth
253
+
254
+ state (workstream=auth)
255
+ agents : 0
256
+ tasks : 2 (ready 1, blocked 1, in-progress 0)
257
+ ops rows : 1
258
+ ghosts : none
259
+ orphan panes : 0
260
+
261
+ fleet
262
+ db-vs-sync : ok MU_SYNC_DIR not set (no sync configured)
263
+ db-filesystem : ok DB is on local (0x1021994)
264
+ name-case : ok no case-colliding workstream names
265
+
266
+ housekeeping
267
+ ws-dormant : note 2 dormant workstream(s): 2 with open tasks
268
+
269
+ Idle 60+ days but still holding UNCLOSED tasks — look before tearing down:
270
+ infer-rs 95d idle, 19 of 202 unclosed
271
+ modelbridge 89d idle, 8 of 75 unclosed
272
+
273
+ Removes the task rows and notes — the plan, not the code (no checkout
274
+ is touched, and `mu undo <group>` puts the rows back). The risk is
275
+ losing sight of what was left to do, so read it first:
276
+ mu task list -w infer-rs --status OPEN
277
+
278
+ disk
279
+ ws-rows : ok every workspace row has its dir
280
+ ws-dirs : ok no orphan workspace dirs
281
+ ws-empty : ok no empty workstream dirs
282
+ db-copies : WARN 7 stray DB file(s), 49M — nothing reads these
283
+ exports : ok no leftover export dirs
284
+ locks : ok no stale lock dirs
285
+ (run `mu doctor --disk` for per-workspace byte usage — walks every checkout)
286
+
287
+ ops log
288
+ drift (shallow) : ok every live row has ops (1ms) — run `mu doctor --deep` for the full rebuild diff
289
+ ```
290
+
291
+ The `disk` section is the only one that reads the filesystem, and it
292
+ reconciles **both directions** — the two can disagree either way:
293
+
294
+ | Row | Means | Why it matters |
295
+ | --- | --- | --- |
296
+ | `ws-rows` | a `vcs_workspaces` row whose path is gone | every read surface reports it as healthy; the next send fails inside the VCS backend instead of at the row that lied. Usually a hand-run `rm -rf` where `mu workspace free` was wanted |
297
+ | `ws-dirs` | a workspace dir with no row (**workspace orphan**) | blocks the next `--workspace` spawn for that agent name. `stranded` = the workstream row is gone too, so no workstream-scoped verb can reach it |
298
+ | `ws-empty` | a per-workstream dir holding no checkouts | `ok` severity — `workspace free` leaves the parent behind. Reported, not faulted |
299
+ | `db-copies` | `mu.db*` files that aren't the live WAL triple | hand-made copies and pre-upgrade saves. Nothing reads them, nothing prunes them, and they are usually the largest dead-byte category |
300
+ | `exports` | leftovers from the removed `mu workstream export` <!-- doc-cli-drift:skip --> | 1.0 deleted the verb, not its output directory |
301
+ | `locks` | advisory-lock dirs older than 1h | not a deadlock (`withFileLock` steals at 30s) but evidence of a spawn or flush that died mid-critical-section |
302
+
303
+ **Report-only, always.** Every row names its own cleanup command in the
304
+ remediation block and mu runs none of them. An orphan or stranded dir
305
+ may hold the only copy of uncommitted work, so the decision is yours (or
306
+ your agent's) — a diagnostic that deleted checkouts because a readdir
307
+ raced a spawn would be a worse bug than the residue.
308
+
309
+ ### Which workstreams can I tear down? (`housekeeping`)
310
+
311
+ `mu workstream list` prints row counts and no dates, so the workstream
312
+ you finished in June looks exactly like the one you worked on an hour
313
+ ago. The `housekeeping` section answers "what can go" — and splits it
314
+ in two, because one list would give actively bad advice:
315
+
316
+ | Bucket | Test | Advice |
317
+ | --- | --- | --- |
318
+ | **finished** | every task `CLOSED`, idle ≥ 14 days | safe to tear down; the remediation is the `teardown` command |
319
+ | **abandoned** | idle ≥ 60 days *with* unclosed tasks | look first; the remediation lists the open tasks, because those are the record of what was left to do |
320
+
321
+ The thresholds differ on purpose. A fortnight away from a project is a
322
+ holiday, not abandonment, so anything still holding open tasks has to be
323
+ cold for two months before it is mentioned at all. A closed-out
324
+ workstream is not suspicious — that is the success state — so it earns
325
+ its row by the work also being cold.
326
+
327
+ Excluded: the workstream you are in right now, `scratch` (ephemeral by
328
+ design), anything with a live agent or a registered workspace, and
329
+ task-less workstreams (those are `mu workstream teardown --empty`'s job,
330
+ which sweeps test litter — zero tasks, agents and workspaces — and never
331
+ matches a workstream with real history).
332
+
333
+ Neither bucket is a data-loss warning. Teardown removes **task rows and
334
+ notes — the plan, not the code**: no commit, branch or checkout is
335
+ touched, and `mu undo <group>` puts the rows back. (That claim holds
336
+ because this list excludes anything with a registered workspace;
337
+ teardown *does* free real checkouts when they exist.) The reason to look
338
+ before tearing down an abandoned workstream is that its unclosed tasks
339
+ are the only record of what was still outstanding — lose sight of them
340
+ and you re-derive that context from scratch later.
341
+
342
+ Severity is always `ok`: a tidy-up opportunity is not a fault, so this
343
+ section never makes `mu doctor` claim something needs attention.
344
+ Teardown is reversible — tombstone ops are written, so `mu undo <group>`
345
+ puts the rows back and `mu workstream list --torn-down` finds the group
346
+ months later.
347
+
348
+ `--disk` adds recursive byte accounting per checkout, with the orphan
349
+ share called out as reclaimable:
350
+
351
+ ```
352
+ workspace bytes : 758M across 4 checkout(s) — 212M in orphan dirs
353
+ 212M auth-peers/worker-2
354
+ 212M auth-peers/worker-1
355
+ 167M leanhl-runner/worker-1
356
+ 167M leanhl-runner/worker-2
357
+ ```
358
+
359
+ It is a separate flag because its cost scales with the size of your
360
+ checkouts rather than with mu's own state (~2s for 758M here), and
361
+ `mu doctor` has to stay cheap enough to run reflexively. The
362
+ reconciliation rows above always run: they are `readdir` + `stat` only,
363
+ depth 2, ~1ms.
364
+
365
+ **On drift**, `--deep` names the exact table, key and field:
366
+
367
+ ```
368
+ ops log
369
+ drift : FAIL 1 divergence(s) (16ms)
370
+ tasks auth/build.title: live=TAMPERED log=Build auth module
371
+ ```
372
+
373
+ Do not rebuild reflexively — which side is right depends on the cause.
374
+ In order:
375
+
376
+ ```bash
377
+ mu db backup /tmp/mu-drift-evidence.db # 1. preserve the evidence
378
+ mu rebuild /tmp/mu-rebuilt.db # 2. materialize what the log believes
379
+ MU_DB_PATH=/tmp/mu-rebuilt.db mu sql "SELECT local_id, title FROM tasks" # 3. compare
380
+ ```
381
+
382
+ Then report it: drift is a capture/apply bug, and the named
383
+ table/key/field is the reproduction. See
384
+ [§ What to do when drift is reported](#what-to-do-when-drift-is-reported).
385
+
386
+ ### 0.6 Upgrading an older DB
387
+
388
+ `mu` refuses to open a pre-v10 DB (`SchemaTooOldError`, exit 4) and
389
+ leaves the file alone. The retained `scripts/migrate.ts` sidecar
390
+ auto-detects v7, v8, or v9 and writes a fresh v10 DB. It never migrates
391
+ in place. Legacy `REJECTED` / `DEFERRED` tasks become `OPEN` with a
392
+ migration note while their original op payloads remain unchanged.
393
+ Pre-1.0 archives restore as live workstreams under their original
394
+ `source_workstream` names unless you pass `--drop-archives`.
395
+
396
+ Full backup, migration, verification, and swap recipe:
397
+ [scripts/README.md](../scripts/README.md).
398
+
399
+ ---
400
+
401
+ ## 1. Setup
402
+
403
+ From npm (the common path):
404
+
405
+ ```bash
406
+ npm install -g @mu-crew/mu
407
+ mu --version # → the current version
408
+ ```
409
+
410
+ Update later via `npm install -g @mu-crew/mu@latest`.
411
+
412
+ From a local checkout (when hacking on mu itself):
413
+
414
+ ```bash
415
+ npm install -g . # `prepare` script auto-builds; `mu` lands on $PATH
416
+ mu --version # → the current version (see package.json)
417
+ ```
418
+
419
+ To update the source-installed copy: pull from upstream, then
420
+ `npm install -g .` from inside the checkout. The `prepare` script
421
+ rebuilds before linking the new dist/.
422
+
423
+ ### Install the bundled skill
424
+
425
+ Mu ships a skill at `skills/mu/SKILL.md` that teaches the LLM running
426
+ inside an agent pane how to use mu. The canonical install path is the
427
+ [skills CLI](https://github.com/vercel-labs/skills), which auto-detects
428
+ every supported agent (pi, claude-code, codex, opencode, cursor, ...)
429
+ and installs into the right per-agent location:
430
+
431
+ ```bash
432
+ npx skills add mu-crew/mu # interactive: pick scope + agents
433
+ npx skills add mu-crew/mu -g -y # global, no prompts (pi: ~/.pi/agent/skills/mu/)
434
+ npx skills update mu # later, to refresh
435
+ ```
436
+
437
+ Hacking on the skill itself? Point the skills CLI at your checkout so
438
+ edits flow straight through:
439
+
440
+ ```bash
441
+ npx skills add ./skills/mu # local-path source format (symlinks)
442
+ ```
443
+
444
+ Without the skills CLI, the skill is just a directory with a
445
+ `SKILL.md` — symlink or copy it into the agent's skills dir. For pi:
446
+ `~/.pi/agent/skills/mu/` (global) or `.pi/skills/mu/` (per-project).
447
+ The cross-tool `~/.agents/skills/mu/` is picked up by pi and several
448
+ others:
449
+
450
+ ```bash
451
+ # From an npm-global install
452
+ mkdir -p ~/.agents/skills
453
+ ln -sf "$(npm root -g)/@mu-crew/mu/skills/mu" ~/.agents/skills/mu
454
+
455
+ # Or from a checkout
456
+ ln -sf "$PWD/skills/mu" ~/.agents/skills/mu
457
+ ```
458
+
459
+ ### For mu hackers: alias to the build output
460
+
461
+ Fastest iteration when hacking on mu itself:
462
+
463
+ ```bash
464
+ npm install # deps only
465
+ npm run build # produces dist/
466
+ alias mu="node $PWD/dist/cli.js"
467
+ ```
468
+
469
+ See [README.md § Install](../README.md#install) for the full set of
470
+ install patterns.
471
+
472
+ mu requires a terminal multiplexer. tmux ≥ 3.0 is the complete
473
+ backend and what the rest of this guide assumes; herdr is supported
474
+ for topology but not yet for spawn/send/read (see
475
+ [§ 20](#20-multiplexer-backends-tmux-and-herdr)). Make sure you're
476
+ inside a session before proceeding:
477
+
478
+ ```bash
479
+ tmux # if you're not already in one
480
+ ```
481
+
482
+ ---
483
+
484
+ ## 2. Get oriented
485
+
486
+ For a human at a terminal, bare `mu` is the home base: it launches the
487
+ read-only TUI with every workstream on the machine loaded as tabs.
488
+ Initial tab focus ladder: `$MU_SESSION` naming a loaded workstream →
489
+ current tmux session named `mu-<workstream>` → cwd inside a registered
490
+ workspace → cwd at the VCS-derived project root of any loaded
491
+ workstream (newest activity wins ties) → tab 0. With no workstream yet
492
+ it prints help plus the start command:
493
+
494
+ ```bash
495
+ mu
496
+ # Get started: mu workstream init <name>
497
+ ```
498
+
499
+ For scripts, agents, CI, and pipes, bare `mu` does NOT enter the TUI:
500
+ when stdout is not a TTY it prints `mu --help`. Use explicit typed
501
+ verbs and `--json` for the API surface:
502
+
503
+ ```bash
504
+ mu state -w <workstream> --json
505
+ MU_NO_TUI=1 mu # force the non-TTY/help path even in a terminal
506
+ ```
507
+
508
+ Run `mu doctor` to check tmux + DB health — full annotated output in
509
+ [§ 0.5 Something looks wrong](#05-something-looks-wrong). Three families
510
+ of checks are the ones to know.
511
+
512
+ **Mixed-fleet hazards** (the `fleet` section) — cheap, and every one is
513
+ something you can fix before it costs you data:
514
+
515
+ | Row | Means |
516
+ | --- | --- |
517
+ | `db-vs-sync` | **FAIL** if `MU_DB_PATH` is inside `MU_SYNC_DIR`. Never do this: a live WAL-mode SQLite DB is three files (`mu.db`, `-wal`, `-shm`) whose mutual consistency IS its durability, and a file-syncer copying them out of order — or resurrecting a peer's stale `-wal` — silently corrupts the database. mu syncs append-only per-machine **segments** so the DB file never has to travel. |
518
+ | `db-filesystem` | **WARN** if the DB is on NFS/SMB/sshfs. WAL needs working advisory locks and a shared-memory file; network mounts provide neither reliably. Symptom is `database is locked` with no contention, or corruption with it. |
519
+ | `name-case` | **WARN** if two workstream names differ only by case. They coexist on Linux but collide on macOS (APFS) and Windows, and a workstream name IS a tmux session name and seeds workspace paths — so a Mac joining the fleet sees one session where Linux sees two. |
520
+
521
+ **Disk↔DB reconciliation** (the `disk` section) — the state dir and the
522
+ database can disagree in both directions, and mu had no surface for
523
+ either before. Row-by-row table in
524
+ [§ 0.5](#05-something-looks-wrong); the short version is `ws-rows` for a
525
+ row whose directory is gone, `ws-dirs` for a directory with no row, and
526
+ `db-copies` / `exports` / `locks` for bytes nothing references. Always
527
+ report-only — the remediation block names the command, you or your agent
528
+ run it. `--disk` adds per-checkout byte usage.
529
+
530
+ **Ops-log drift** (the `ops log` section) — is the projection still
531
+ faithful to the log? Undo, sync and history are all
532
+ projections of the ops log, so a capture bug breaks all four at once,
533
+ silently. Two tiers:
534
+
535
+ ```bash
536
+ mu doctor # shallow: every live row must have >=1 op. ~3ms.
537
+ mu doctor --deep # full rebuild + field-level diff. ~0.6ms per op.
538
+ ```
539
+
540
+ The default is shallow so `mu doctor` stays reflexive; the deep check
541
+ rebuilds the whole log (~2.3s on a 1000-task DB). Shallow catches an
542
+ uncaptured INSERT or DELETE and is blind to an uncaptured UPDATE (the
543
+ row's key still has ops). Run `--deep` when you suspect something, in
544
+ CI, or before a release. Either tier exits **5** on drift.
545
+
546
+ ### What to do when drift is reported
547
+
548
+ Drift names the exact table, key and field, e.g.:
549
+
550
+ ```
551
+ drift : FAIL 2 divergence(s) (12ms)
552
+ tasks demo/a.title: live=TAMPERED log=A
553
+ tasks demo/a.impact: live=7 log=60
554
+ ```
555
+
556
+ **Do not rebuild reflexively.** Drift means the log and the tables
557
+ disagree, and which side is right depends on the cause:
558
+
559
+ - If **capture** missed a mutation, the LIVE tables hold real work the
560
+ log never recorded — rebuilding would discard it.
561
+ - If **apply** is lossy, the log is authoritative and a rebuild fixes it.
562
+
563
+ So, in order:
564
+
565
+ ```bash
566
+ mu db backup /tmp/mu-drift-evidence.db # 1. preserve the evidence FIRST
567
+ mu rebuild /tmp/mu-rebuilt.db # 2. materialize what the log believes
568
+ # 3. compare the named keys in both files and decide which side is correct:
569
+ MU_DB_PATH=/tmp/mu-rebuilt.db mu sql "SELECT local_id, title, impact FROM tasks"
570
+ ```
571
+
572
+ Then report it. Drift is a capture/apply **bug**, not operator error, and
573
+ the named table/key/field is the reproduction.
574
+
575
+ ### Undoing one action (`mu undo`)
576
+
577
+ Undo emits **inverse ops** for one **group** (one user-visible action).
578
+
579
+ ```bash
580
+ mu undo # what would I undo? lists recent groups + ids
581
+ mu undo 1a2a94eb # preview the inverse (dry run)
582
+ mu undo 1a2a94eb --yes # apply it
583
+ ```
584
+
585
+ Three properties:
586
+
587
+ - **Granular.** Only the rows that action touched. A cascade close wrote
588
+ N task ops under one group, so undoing it reopens exactly those N.
589
+ - **Itself an op.** The undo lands in its own group, so it syncs to peers
590
+ and is **itself undoable** — that is redo:
591
+ `mu undo <the-undo-group> --yes`.
592
+ - **Refuses to clobber newer work.** If a later action changed the same
593
+ fields, undo exits 4 and names the conflict:
594
+
595
+ ```
596
+ WARNING: this group has been SUPERSEDED by later work.
597
+ demo/a: impact was changed since by e04df0d5 (task.update)
598
+ Undoing would DISCARD that newer work. Pass --force with --yes to do it anyway.
599
+ ```
600
+
601
+ `--force` is the override, and it says what it destroys.
602
+
603
+ Rows only: undo does not resurrect killed tmux panes or freed workspace
604
+ directories. For whole-DB recovery from the log, use `mu rebuild <file>`.
605
+
606
+ Get the full command list:
607
+
608
+ ```bash
609
+ mu --help
610
+ ```
611
+
612
+ Every verb's `--help` is exhaustive (flags, defaults,
613
+ interactions). Every successful invocation also prints a dim
614
+ `Next:` block of suggested follow-up commands at the bottom —
615
+ you never have to leave the terminal to learn what to do next.
616
+
617
+ Every verb accepts `--json` for machine-readable output. Errors
618
+ in `--json` mode emit a `{ error, message, nextSteps, exitCode }`
619
+ record to stderr; the `nextSteps` array carries resolutions you can
620
+ `eval` directly.
621
+
622
+ ### CLI conventions: validation errors
623
+
624
+ Every operator-error path — missing required option, unknown option,
625
+ unknown subcommand, missing positional, type-coercion failure, mutex
626
+ flags, range checks — produces a uniform surface:
627
+
628
+ - **Human path**: red `error: <msg>` on stderr, then the failing
629
+ subcommand's `--help` block (same text as `mu <verb> --help`),
630
+ then exit **2**.
631
+ - **`--json` path**: a structured envelope on stderr:
632
+
633
+ ```json
634
+ {
635
+ "error": "UsageError",
636
+ "message": "--self and --for are mutually exclusive",
637
+ "nextSteps": [],
638
+ "exitCode": 2,
639
+ "usage": {
640
+ "command": "mu task claim",
641
+ "synopsis": "mu task claim [options] <id>",
642
+ "description": "...",
643
+ "args": [{"name": "id", "required": true, "variadic": false, "description": ""}],
644
+ "options": [{"flags": "--self", "description": "...", "mandatory": false, "valueRequired": false}, ...]
645
+ }
646
+ }
647
+ ```
648
+
649
+ `usage.options[].mandatory` is `true` when the operator MUST pass
650
+ the option (`.requiredOption()` in commander terms). `valueRequired`
651
+ is `true` when the option's argument can't be omitted if the flag
652
+ IS passed (`<value>` form vs bare flag). The two are independent.
653
+
654
+ Exit 2 is the consistent code for the whole operator-error class —
655
+ commander mistakes and handler-thrown `UsageError`s alike. Other
656
+ classes keep their own codes (3 = not found, 4 = conflict, 5 =
657
+ substrate, 6 = reaper, 7 = stall).
658
+
659
+ ### CLI conventions: `--json` collection envelope
660
+
661
+ Collection-read verbs emit a canonical `{items: T[], count: number}`
662
+ shape on stdout:
663
+
664
+ ```bash
665
+ $ mu task list -w foo --json
666
+ {"items":[{"name":"a",...},{"name":"b",...}],"count":2}
667
+ ```
668
+
669
+ `count` is `items.length` pre-computed so `jq '.count'` is one less hop
670
+ than `jq '.items | length'`. `mu workspace commits --json` adds `vcs`,
671
+ `baseRef`, and `workspacePath` siblings.
672
+
673
+ Applies to: `mu task list / next / owned-by / notes`,
674
+ `mu workstream list`, `mu workstream teardown --empty` (dry-run),
675
+ `mu workspace list / orphans / commits`,
676
+ `mu undo` (group list), `mu log -n N` (read).
677
+
678
+ Two carve-outs:
679
+ - **`mu sql --json`** keeps bare-array rows. The verb is the typed-
680
+ escape hatch; row shape is per-query, not part of the typed
681
+ contract.
682
+ - **`mu log --tail --json`** emits NDJSON (one JSON object per line)
683
+ because it's a stream, not a collection. Stream consumers want one
684
+ envelope per row, not a single envelope that grows forever.
685
+
686
+ Singleton verbs (`mu task show`, `mu agent show`, `mu workstream init`,
687
+ `mu task close`, ...) use object envelopes with named top-level fields
688
+ (`{task, blockers, dependents, notes}`, `{taskName, ..., nextSteps}`).
689
+ `items + count` is for collection reads only.
690
+
691
+ ### CLI conventions: multi-value flags
692
+
693
+ Multi-value flags accept repeated invocations
694
+ (`--blocked-by a --blocked-by b`), a comma-separated value
695
+ (`--blocked-by a,b`), or any mix. The signal is `<value...>` in the
696
+ help-text metavar. Variadic positionals (`mu task wait a b c`) stay
697
+ space-separated — operands are not commas, and single-valued flags
698
+ (`-w`, `--title`) stay single.
699
+
700
+ - `--by` on `mu task block` / `mu task unblock` is multi-value:
701
+ `mu task block c --by a,b` adds both edges in one call.
702
+ - `--status` on `mu task list` / `mu task next` is multi-value and
703
+ returns the union. Omitting it applies no filter.
704
+ - `mu task wait --status` stays single — "wait until reaches THIS
705
+ status".
706
+
707
+ **Empty vs blank fragments.** An *empty* fragment is dropped: a
708
+ trailing or doubled comma is a typing artifact, so `--status "OPEN,"`
709
+ means `[OPEN]`, and `mu task reparent --blocked-by ''` is the
710
+ documented "clear every blocker" sentinel. A *blank* fragment — one
711
+ that is entirely whitespace, like `--status " "` or the tail of
712
+ `--status "OPEN, "` — is a usage error (exit 2) naming the flag. Nobody
713
+ means "filter by the space character", and dropping it silently would
714
+ return a different answer than the one typed. Same rule for `-w`,
715
+ `--by`, and `--blocked-by`; see docs/VOCABULARY.md § Empty vs blank
716
+ flag fragments.
717
+
718
+ ### CLI conventions: flag vs positional
719
+
720
+ The rule the CLI follows:
721
+
722
+ > **The primary entity a verb acts on is POSITIONAL. Everything
723
+ > else — scoping, modifiers, payload — is a flag.**
724
+
725
+ So `mu task close <id>`, `mu agent send <name> <text>`,
726
+ `mu workstream init <name>`. The workstream
727
+ is a *scope* for most verbs (`-w`) — but for `mu workstream <verb>` it
728
+ IS the primary entity, so it may be positional:
729
+
730
+ ```bash
731
+ mu workstream init v2 # positional
732
+ mu workstream teardown v2 --yes # positional (aliases -w)
733
+ mu workstream teardown -w v2 --yes # -w still works
734
+ ```
735
+
736
+ Passing both a positional and a disagreeing `-w` is a usage error
737
+ (exit 2), not a silent pick-one.
738
+
739
+ Where sibling verbs supply a payload two ways, the flag form is an
740
+ ADDITIVE alias so muscle memory carries across:
741
+
742
+ ```bash
743
+ mu task add t -t T -i 5 -e 1 --note "context" # note as a flag
744
+ mu task note t "more context" # positional
745
+ mu task note t --text "more context" # --text alias
746
+ ```
747
+
748
+ Supplying both shapes at once is a usage error (exit 2).
749
+
750
+ ---
751
+
752
+ ## 3. Create a workstream
753
+
754
+ A **workstream** is mu's unit of organization. One workstream = one
755
+ tmux session = one logical project. Multiple workstreams on the same
756
+ machine are isolated (partitioned in the SQLite registry by
757
+ `session_id`); they never see each other's agents.
758
+
759
+ ```bash
760
+ mu workstream init auth-refactor
761
+ ```
762
+
763
+ ```
764
+ Created workstream auth-refactor (mux session mu-auth-refactor)
765
+ Next:
766
+ Attach the session : tmux attach -t mu-auth-refactor
767
+ Plan tasks : mu task add -w auth-refactor --title "..." --impact 50 --effort-days 1
768
+ Spawn an agent : mu agent spawn <name> -w auth-refactor
769
+ See state : mu state -w auth-refactor
770
+ ```
771
+
772
+ Behind the scenes: `tmux new-session -d -s mu-auth-refactor` plus a
773
+ placeholder window so the session is non-empty. It sits detached,
774
+ waiting for agents.
775
+
776
+ To see what's already on the machine before picking a name:
777
+
778
+ ```bash
779
+ mu workstream list
780
+ ```
781
+
782
+ ```
783
+ ┌────────────────────────────────────────┬───────┬────────┬───────┬───────┬───────┐
784
+ │ name │ tmux │ agents │ tasks │ edges │ notes │
785
+ ├────────────────────────────────────────┼───────┼────────┼───────┼───────┼───────┤
786
+ │ auth │ — │ 0 │ 2 │ 1 │ 0 │
787
+ ├────────────────────────────────────────┼───────┼────────┼───────┼───────┼───────┤
788
+ │ mu │ alive │ 0 │ 0 │ 0 │ 0 │
789
+ └────────────────────────────────────────┴───────┴────────┴───────┴───────┴───────┘
790
+ ```
791
+
792
+ The list is the **union** of three sources: distinct workstreams in
793
+ `agents`, in `tasks`, and tmux sessions matching `mu-*`. A freshly
794
+ `init`'d workstream with no tasks shows up via its session; one whose
795
+ session was killed externally shows up via its surviving DB rows, so
796
+ you can still `mu workstream teardown` it.
797
+
798
+ ### How mu finds your active workstream
799
+
800
+ Every command after `init` needs to know which workstream you're in.
801
+ Resolution order, first match wins:
802
+
803
+ 1. **`--workstream <name>` flag** explicitly
804
+ 2. **`MU_SESSION` env var** (`export MU_SESSION=auth-refactor`)
805
+ 3. **Current tmux session name** (mu reads `tmux display-message -p '#S'` and strips the `mu-` prefix)
806
+ 4. Error if none of the above
807
+
808
+ The third option is the most ergonomic. Once you `tmux attach -t
809
+ mu-auth-refactor`, every command "just works" without flags.
810
+
811
+ ### Off-the-cuff agents: the `scratch` workstream
812
+
813
+ When you just want one helper agent you can keep talking to — not a
814
+ crew, not a task DAG, not per-agent workspaces — skip the `init` step
815
+ entirely and spawn into the reserved `scratch` workstream:
816
+
817
+ ```bash
818
+ mu agent spawn helper -w scratch # auto-creates mu-scratch
819
+ mu agent send helper 'Investigate the failing test in foo.spec.ts'
820
+ mu agent read helper -n 50 # check on it anytime
821
+ mu agent close helper -w scratch # done
822
+ ```
823
+
824
+ `scratch` is a shared, ephemeral bucket: it auto-creates on first
825
+ spawn, tasks are optional, and idle scratch agents get a staleness
826
+ nudge in `mu state` and the TUI so they don't pile up. The name is
827
+ **reserved** — `mu workstream init scratch` is rejected;
828
+ `mu workstream teardown scratch` works normally.
829
+
830
+ ```
831
+ $ mu workstream init scratch
832
+ error: workstream name "scratch" is reserved: it is the off-the-cuff bucket and auto-creates on first spawn. Don't 'init' it.
833
+ Next:
834
+ Just spawn into it (auto-creates) : mu agent spawn <name> -w scratch
835
+ Use a durable workstream instead : mu workstream init <name>
836
+ ```
837
+
838
+ **When to use which:** `mu workstream init <name>` the moment
839
+ coordination *is* the work — multiple agents, dependencies, gated
840
+ review. `scratch` for a single driveable helper.
841
+ [`pi-subagents`](https://github.com/nicobailon/pi-subagents) when you
842
+ only need a one-shot result back.
843
+
844
+ ### The log ledger: durable watcher dedupe + memory
845
+
846
+ A watcher loop reacting to external state — a PR's CI status, a queue
847
+ depth, a file's mtime — must remember *what it last saw* so it doesn't
848
+ act twice. Don't keep that in the agent's chat context: it evaporates
849
+ on compaction and dies with the loop. Use a custom `--kind` tag on the
850
+ activity log as an append-only **ledger**:
851
+
852
+ ```bash
853
+ # Watcher tick: record what you saw and what you did about it.
854
+ mu log -w scratch --kind pr-state 'pr=1234 sha=abc ci=red -> spawned fixer-1'
855
+
856
+ # Next tick: reconstruct the last-seen state (latest entry of that kind).
857
+ mu log -w scratch --kind pr-state -n 1 --json
858
+ # {"items":[{"seq":8695,...,"kind":"pr-state",
859
+ # "payload":"pr=1234 sha=abc ci=red -> spawned fixer-1"}],"count":1}
860
+ ```
861
+
862
+ The dedupe rule: read the latest `pr-state`, compare its `sha`/`ci` to
863
+ what you observed, act only on a difference. The ledger lives in the
864
+ `ops` log, so it survives loop death and context compaction.
865
+
866
+ - **Pick a stable `--kind`** per ledger (`pr-state`, `queue-depth`).
867
+ `mu log --kind <tag>` filters to it, so ledgers coexist in one
868
+ workstream.
869
+ - **One line per tick, latest wins.** `-n 1` for the most recent;
870
+ `--since <seq>` replays history a dead watcher missed.
871
+ - **Free-form payload.** mu doesn't parse it. Ledger lines have no
872
+ **intent**, so `mu log` prints them verbatim rather than rendering
873
+ them as a verb.
874
+
875
+ A *convention*, not a feature — `mu log` already has `--kind`,
876
+ `--since`, and `--json`. See **log ledger** in
877
+ [VOCABULARY.md](VOCABULARY.md).
878
+
879
+ `--kind` is the operator's channel tag; `--intent` filters on what *mu*
880
+ recorded (`--intent task.close`). Two axes, two flags.
881
+
882
+ ---
883
+
884
+ ## 4. Plan some work as a DAG
885
+
886
+ Tasks have **mandatory** `impact` (1–100) and `effort-days` (>0).
887
+ Edges are blocks-relationships, expressed as **`--blocked-by`** on
888
+ `mu task add` (and `mu task reparent`): `--blocked-by design` means
889
+ "can't start until `design` closes". Tasks are **scoped to a
890
+ workstream**.
891
+
892
+ ```bash
893
+ # -w can be omitted inside the workstream's tmux session, or with
894
+ # $MU_SESSION exported.
895
+ mu task add design -w auth-refactor --title "Design auth module" --impact 80 --effort-days 2
896
+ mu task add build -w auth-refactor --title "Build auth module" --impact 80 --effort-days 5 --blocked-by design
897
+ mu task add review -w auth-refactor --title "Review auth module" --impact 60 --effort-days 1 --blocked-by build
898
+ ```
899
+
900
+ See [§ 0.1](#01-first-5-minutes) for the output. Add initial context at
901
+ creation time with `--note` (shell escapes like `\n` are translated as
902
+ in `mu task note`); `--note-author <name>` overrides the actor label:
903
+
904
+ ```bash
905
+ mu task add bugfix \
906
+ --workstream auth-refactor \
907
+ --title "Fix token refresh race" \
908
+ --impact 70 --effort-days 1 \
909
+ --note 'REPRO: login, wait 24h, refresh\nSCOPE: auth refresh only' \
910
+ --note-author orchestrator
911
+ ```
912
+
913
+ Task creation + the initial note are one transaction: if either part
914
+ fails, neither lands.
915
+
916
+ Ids validate against `/^[a-z][a-z0-9_-]{0,63}$/` and reject duplicates.
917
+ `mu task add x --blocked-by y` when `y` already transitively depends on
918
+ `x` refuses with a `CycleError`.
919
+
920
+ **Task ids are per-workstream unique.** Cross-workstream references use
921
+ the qualified form `<workstream>/<id>`. Blocks-edges are always
922
+ same-workstream — a blocker outside the target workstream is a
923
+ `CrossWorkstreamEdgeError`.
924
+
925
+ ### Modeling external dependencies
926
+
927
+ When a task is waiting on something outside this repo (an upstream PR
928
+ shipping, a vendor releasing v3 of an API, a coworker's review), don't
929
+ reach for a new status — add a **placeholder task** for the external
930
+ thing and `--blocked-by` it. The DAG already encodes "blocked":
931
+
932
+ ```bash
933
+ mu task add upstream_react_19_lands -w gchatui-node \
934
+ --title "Wait for React 19 release (vendor)" \
935
+ --impact 30 --effort-days 0.1
936
+ mu task note upstream_react_19_lands -w gchatui-node \
937
+ "Tracking https://github.com/facebook/react/issues/...
938
+ Last checked: 2026-05-15.
939
+ When this lands: bump react in package.json + re-run upgrade tasks."
940
+
941
+ mu task add migrate_to_use_action -w gchatui-node \
942
+ --title "Migrate ChatInput to React 19 useActionState" \
943
+ --impact 60 --effort-days 1 \
944
+ --blocked-by upstream_react_19_lands
945
+ ```
946
+
947
+ When the upstream lands, `mu task close upstream_react_19_lands
948
+ --evidence "shipped 2026-08-12"` — the dependent flips from blocked
949
+ to ready in the same render. If the upstream gets cancelled, close the
950
+ placeholder anyway (`mu task close upstream_react_19_lands --evidence
951
+ "cancelled, won't ship"`) and note the reason on each dependent, or
952
+ `mu task delete` the placeholder and its dependents' edges if the work
953
+ is truly abandoned.
954
+
955
+ Why this beats a `BLOCKED` status: the placeholder's notes are the
956
+ audit trail, one placeholder blocks N downstream tasks, and the
957
+ placeholder's own status carries the detail (`OPEN` = someone external
958
+ is on it, a note records a parked reason, `IN_PROGRESS` = you're
959
+ chasing it).
960
+
961
+ ---
962
+
963
+ ## 5. See the graph (dashboard + state API)
964
+
965
+ `mu` exposes one logical "what's going on?" view with two renderers:
966
+
967
+ | Surface | Use it for |
968
+ | -------------------- | --------------------------------------------------------------- |
969
+ | **bare `mu`** | A human at a terminal — launches the interactive TUI dashboard. |
970
+ | **`mu state --tui`** | Same TUI, explicitly opt-in. Useful in scripts / aliases. |
971
+ | **`mu state`** | Static text card. JSON-friendly; pipeable; `watch`-able. |
972
+ | **`mu state --json`** | The canonical full snapshot. Agents and scripts read this. |
973
+
974
+ The interactive surface has its own section:
975
+ [§ 5b. The TUI dashboard](#5b-the-tui-dashboard-interactive), below.
976
+ The rest of this section is the static / JSON contract.
977
+
978
+ ### Static state card (`mu state`)
979
+
980
+ For an agent/script or a static capture, use explicit `mu state`:
981
+
982
+ ```bash
983
+ mu state -w auth-refactor # human-readable card
984
+ mu state -w auth-refactor --json # full snapshot
985
+ mu state --all --json # every workstream on this machine
986
+ ```
987
+
988
+ The static card carries every section the TUI cards summarize: agents +
989
+ orphans + tracks + ready / in-progress / blocked / recent-closed tasks
990
+ + workspaces + recent events. It also lists **remote workers** recorded by
991
+ exact `REMOTE: <host>:<path>` task-note lines; malformed lines and prose that
992
+ merely mentions `REMOTE:` are ignored.
993
+
994
+ **JSON shapes**
995
+
996
+ - single-ws: flat `{ workstreamName, agents, orphans, tracks, ready,
997
+ blocked, inProgress, recentClosed, workspaces, remoteWorkers, recent }`.
998
+ - multi-ws: wrapped `{ workstreams: [{...}, ...] }`.
999
+ - bare `mu --json` prints `--help`; use `mu state --json`.
1000
+ - `--tui` is render-only and incompatible with `--json`.
1001
+
1002
+ **Multi-workstream**: repeat `-w`, or `--all`. In static mode N≥2
1003
+ stacks one card per workstream.
1004
+
1005
+ `tmux display-popup -E 'mu state -w X'` works for popup-card use.
1006
+
1007
+ ---
1008
+
1009
+ ## 5b. The TUI dashboard (interactive)
1010
+
1011
+ The interactive TUI is mu's human surface. It is **read-only** —
1012
+ every act-intent `y`anks the canonical `mu` command to
1013
+ your clipboard so you run mutations from your shell, with one
1014
+ documented escape (`t` in git-show drills runs `tuicr` in the project
1015
+ root, see below).
1016
+
1017
+ ### Launch
1018
+
1019
+ ```bash
1020
+ mu # bare; opens the TUI when stdout is a TTY
1021
+ mu state --tui # explicit; same surface
1022
+ mu state --tui -w a,b # restrict to specific workstreams
1023
+ mu state --tui --all # all workstreams (default for bare `mu`)
1024
+ MU_NO_TUI=1 mu # force the help path even in a TTY
1025
+ mu --json # also forces help; pipe `mu state --json`
1026
+ ```
1027
+
1028
+ Quit with `q` or `Ctrl-C`. The dashboard restores your scrollback
1029
+ on exit (alt-screen).
1030
+
1031
+ **Initial active tab** is picked from this ladder:
1032
+ `$MU_SESSION` → current tmux session name (`mu-<ws>`) → cwd inside a
1033
+ registered workspace → cwd at the VCS-derived project root of any
1034
+ workstream (newest activity wins ties) → tab 0.
1035
+
1036
+ ### Layout: 10 cards, responsive columns
1037
+
1038
+ The dashboard renders 10 toggleable cards with rounded borders and
1039
+ section headers inset into the top border line (lazygit / btop / k9s
1040
+ convention):
1041
+
1042
+ | Slot | Card | Toggle | Popup | Content |
1043
+ | ---- | ------------- | ------ | --------- | ---------------------------------------------------- |
1044
+ | 0 | Commits | `0` | `Shift+0` | Recent project-root commits (git / jj / sl) |
1045
+ | 1 | Agents | `1` | `Shift+1` | Active agents + status + cli + role |
1046
+ | 2 | Tracks | `2` | `Shift+2` | Parallel tracks (union-find clusters) |
1047
+ | 3 | Ready (Tasks) | `3` | `Shift+3` | Ready-to-claim tasks (no open blockers) |
1048
+ | 4 | Activity log | `4` | `Shift+4` | Recent ops rendered as prose |
1049
+ | 5 | Workspaces | `5` | `Shift+5` | Per-agent VCS workspaces + behind/dirty status |
1050
+ | 6 | In-progress | `6` | `Shift+6` | IN_PROGRESS tasks owned by agents |
1051
+ | 7 | Blocked | `7` | `Shift+7` | Tasks with at least one open blocker |
1052
+ | 8 | Recent | `8` | `Shift+8` | Recently CLOSED tasks |
1053
+ | 9 | Doctor | `9` | `Shift+9` | Cheap health checks (schema, ghosts, orphans, …) |
1054
+ | — | DAG | — | `g` | Full task DAG forest (keybind-only) |
1055
+ | — | All tasks | — | `t` | Sortable / filterable list of every task |
1056
+
1057
+ Digit toggles HIDE / SHOW the card on the dashboard; `Shift+digit`
1058
+ opens the matching fullscreen popup. **Single-popup invariant**: only
1059
+ one popup is visible at a time; `Esc` / `q` returns to the dashboard
1060
+ with all toggles + tick rate preserved.
1061
+
1062
+ **Responsive layout**: cards stack below 120 cols, then reflow into
1063
+ pair-aware 2 / 3 / 4-column layouts at 120 / 180 / 240 cols. Each
1064
+ visible card gets a dynamic row budget so a noisy list cannot crowd
1065
+ out its siblings; overflow shows as `+N more · Shift+N` inset into
1066
+ the bottom border. On short panes the dashboard culls low-priority
1067
+ cards (Doctor → Recent → Workspaces → …) and shows
1068
+ `+N cards hidden · resize taller`.
1069
+
1070
+ Ordering is slot-stable: within each column, non-stream cards go by
1071
+ toggle digit ascending; stream cards (Commits, Activity log) trail,
1072
+ with slot 0 last.
1073
+
1074
+ ### Multi-workstream tabs
1075
+
1076
+ With N≥2 workstreams (bare `mu` on a multi-workstream machine, or
1077
+ `mu state --tui -w a,b,c`), a tab strip renders above the cards:
1078
+
1079
+ ```
1080
+ workstreams: ▸ auth-refactor · ui-rewrite · demo (Tab / Shift-Tab)
1081
+ ```
1082
+
1083
+ - `Tab` cycles forward, `Shift-Tab` backward (suppressed inside popups
1084
+ that bind the key locally).
1085
+ - The active tab name shows in the status bar next to the tick rate.
1086
+ - Cards / popups operate on the active tab — no per-row workstream
1087
+ column. For N=1 the strip renders nothing.
1088
+ - Wider than the terminal: the strip windows around the active tab and
1089
+ shows `‹N` / `›N` counters for hidden workstreams.
1090
+ - `*` prefix (e.g. `*scratch`) marks the ephemeral `scratch` bucket.
1091
+ - If a loaded workstream is torn down while the TUI runs, its launch-time tab
1092
+ remains in place but appears dimmed with strikethrough. This also surfaces the
1093
+ otherwise hidden tab in a single-workstream TUI. Recreating the same name
1094
+ restores the tab on the next fast tick.
1095
+
1096
+ ### Popup drills
1097
+
1098
+ `Enter` in any list popup drills into the focused row. Where the
1099
+ row is itself an entity (a task), a further `Enter` chains into the
1100
+ shared read-only task-detail leaf (notes timeline):
1101
+
1102
+ - **Tracks popup (`Shift+2`)**: list of tracks → `Enter` opens the
1103
+ track's task list → `Enter` opens that task's notes timeline.
1104
+ - **Ready / In-progress / Blocked / Recent / All-tasks**:
1105
+ list of tasks → `Enter` opens notes; `y` yanks `mu task show <id>`
1106
+ (or `mu task claim` / `mu task close` / `mu task tree` depending
1107
+ on popup).
1108
+ - **Activity log popup (`Shift+4`)**: list of events → `Enter`
1109
+ drills into the full untruncated payload of the focused event;
1110
+ `y` yanks `mu log --since <seq-1> -n 1 -w <ws>`.
1111
+ - **Workspaces popup (`Shift+5`)**: list of workspaces → `Enter`
1112
+ opens the commits-since-fork list → `Enter` on a commit opens
1113
+ the inline `git show <sha> --stat -p` view; `y` yanks `git show
1114
+ <sha>`; `t` launches `tuicr -r <sha>`.
1115
+ - **Commits popup (`Shift+0`)**: project-root recent commits →
1116
+ `Enter` opens the backend's show view; `y` yanks the show
1117
+ command; `t` launches `tuicr`.
1118
+ - **Doctor popup (`Shift+9`)**: list of checks → `Enter` opens
1119
+ the remediation paragraph for the focused check.
1120
+ - **DAG popup (`g`)**: keybind-only; renders the active workstream's
1121
+ full task DAG forest (one ASCII subtree per root, diamond-collapse
1122
+ marker on repeated nodes).
1123
+
1124
+ One `Esc` / `q` backs out per recursion level. Drills auto-refresh in
1125
+ step with the dashboard tick (fast 1s for SQL bodies like notes, slow
1126
+ 10s for subprocess git-show / scrollback). Scroll position survives
1127
+ refreshes, and subprocess loaders keep the prior body visible until the
1128
+ new one arrives.
1129
+
1130
+ ### Search / filter
1131
+
1132
+ `/` inside any list popup enters an incremental case-insensitive
1133
+ substring filter (lazygit / k9s convention). Printable characters
1134
+ append, `Backspace` pops, `Esc` cancels, `Enter` commits (keeps the
1135
+ filter, resumes `j/k` navigation), and `/` again refines. The filter
1136
+ blob is per-popup — agent name/status/cli/role; track head id + title;
1137
+ task name/title/status/owner; log verb/payload/source — and dies with
1138
+ the popup.
1139
+
1140
+ Task-list popups add **per-status toggles** (`o` / `i` / `c` for OPEN /
1141
+ IN_PROGRESS / CLOSED; default all-on). The All-tasks popup adds **sort
1142
+ cycle** on `s`: `roi` → `recency` → `age` → `id`.
1143
+
1144
+ ### Mouse
1145
+
1146
+ Navigation-in only: double-click a dashboard card to open its popup,
1147
+ double-click a popup row to drill one level deeper, and scroll-wheel
1148
+ inside a popup list / drill body to move the cursor or scroll. There is
1149
+ **no mouse back binding** — use `Esc` / `q`.
1150
+
1151
+ ### Yank contract (`y`) and the `tuicr` escape (`t`)
1152
+
1153
+ Every popup row exposes one canonical `mu` command via `y`, which goes
1154
+ to your system clipboard (pbcopy / wl-copy / xclip / xsel / clip.exe,
1155
+ OSC-52 fallback). You run it in your shell; the TUI never mutates.
1156
+
1157
+ The one escape is **`t`** inside a `git show` drill (Workspaces or
1158
+ Commits popup): mu suspends its alt-screen, runs `tuicr -r <sha>` in
1159
+ the project root / workspace cwd, and restores the dashboard when tuicr
1160
+ exits. The operator drives another TUI tool; mu still performs no
1161
+ mutation.
1162
+
1163
+ Status cells colour-code as in the static CLI tables: OPEN cyan,
1164
+ IN_PROGRESS yellow, CLOSED green.
1165
+
1166
+ ### Polling tiers
1167
+
1168
+ The dashboard has two refresh tiers:
1169
+
1170
+ - **Fast tick** (default 1s, adjustable with `+` / `-` / `=` /
1171
+ `0`): SQL-only. Refreshes tasks, tracks, workspace registry rows,
1172
+ and the activity log.
1173
+ - **Slow tick** (10s, fixed): subprocess-backed. Refreshes
1174
+ tmux-derived agent liveness / orphans, workspace dirty flags,
1175
+ recent project commits, and the Doctor summary.
1176
+
1177
+ The last slow-tier result is merged into every fast render so cards
1178
+ do not flicker through a loading state. `r` / F5 refreshes both
1179
+ tiers immediately. Tab / Shift-Tab triggers an eager slow refresh
1180
+ for the newly active workstream.
1181
+
1182
+ ### Keymap reference
1183
+
1184
+ | Mode | Keys | Action |
1185
+ | --------- | ---------------------------- | -------------------------------------------------------------- |
1186
+ | dashboard | `0`-`9` | toggle card visibility |
1187
+ | dashboard | `Shift+0`-`Shift+9` | open the matching popup |
1188
+ | dashboard | `g` | open DAG popup (keybind-only) |
1189
+ | dashboard | `t` | open All-tasks popup (keybind-only) |
1190
+ | dashboard | `Tab` / `Shift-Tab` | cycle workstream tabs (N≥2) |
1191
+ | dashboard | `+` / `-` / `=` / `0` | adjust fast tick rate (faster / slower / default / pause) |
1192
+ | dashboard | `r` / `F5` | force refresh both tiers |
1193
+ | dashboard | `c` | clear footer (last yank) |
1194
+ | dashboard | `?` / `F1` | open help overlay |
1195
+ | any | `q` / `Ctrl-C` | quit (or back out of popup; quits at dashboard) |
1196
+ | popup | `j` / `k` | move cursor / scroll |
1197
+ | popup | `g` / `G` | jump top / bottom |
1198
+ | popup | `Ctrl-D` / `Ctrl-U` | half-page down / up |
1199
+ | popup | `PgDn` / `PgUp` | full page |
1200
+ | popup | `Enter` | drill into focused row |
1201
+ | popup | `Esc` / `q` | back out one level |
1202
+ | popup | `y` | yank canonical `mu` command for focused row |
1203
+ | popup | `/` | enter filter mode |
1204
+ | popup | `a` | attach to focused agent's mux pane (Agents popup only) |
1205
+ | popup | `l` | launch lazygit in the project root (Commits popup only) |
1206
+ | filter | (printable) / `Backspace` | edit query |
1207
+ | filter | `Esc` | cancel (clear query) |
1208
+ | filter | `Enter` | commit (keep filter, return to nav) |
1209
+ | task popup| `o` / `i` / `c` | toggle OPEN / IN_PROGRESS / CLOSED |
1210
+ | All-tasks | `b` | blocked filter cycle (all → only → hide) |
1211
+ | All-tasks | `s` | cycle sort key (roi → recency → age → id) |
1212
+ | git-show | `t` | launch `tuicr -r <sha>` (alt-screen handoff) |
1213
+
1214
+ `?` shows the same table as a scrollable overlay (j/k/Ctrl-D/U/g/G
1215
+ also work inside the overlay).
1216
+
1217
+ ### Read-only invariant
1218
+
1219
+ The TUI never executes a mutation — a load-bearing pledge in
1220
+ `docs/ROADMAP.md`, not an implementation detail. If a TUI gesture
1221
+ tempts you to mutate state from the SDK, file a roadmap entry first.
1222
+ Yank-and-run is the cost of keeping the TUI inspectable, scriptable
1223
+ and recoverable from any shell.
1224
+
1225
+ ---
1226
+
1227
+ ## 6. Spawn a crew
1228
+
1229
+ For a demo with live status detection, spawn pi agents:
1230
+
1231
+ ```bash
1232
+ mu agent spawn worker-1 --workstream auth-refactor # default --cli is pi
1233
+ ```
1234
+
1235
+ To play around without needing pi installed, use `--cli sh`:
1236
+
1237
+ ```bash
1238
+ mu agent spawn worker-1 --workstream auth-refactor --cli sh
1239
+ mu agent spawn worker-2 --workstream auth-refactor --cli sh
1240
+ ```
1241
+
1242
+ ```
1243
+ Spawned worker-1 (sh) in window worker-1 of mu-auth-refactor, pane %15
1244
+ ```
1245
+
1246
+ What just happened:
1247
+
1248
+ 1. mu checked the agents table — no `worker-1` yet, OK to proceed
1249
+ 2. mu created a tmux window named `worker-1` in the `mu-auth-refactor`
1250
+ session
1251
+ 3. mu set the pane title to `worker-1` via `tmux select-pane -T worker-1`
1252
+ — **this is the claim protocol identity**
1253
+ 4. mu inserted a row in `agents` with `pane_id=%15`, `status=spawning`
1254
+
1255
+ If the DB insert fails after the pane was created, mu kills the pane
1256
+ to avoid leaking. If the same name was already taken, mu rejects
1257
+ **before** calling tmux.
1258
+
1259
+ ### Naming convention (lint, not a rule)
1260
+
1261
+ mu accepts any name matching `/^[a-z][a-z0-9_-]{0,31}$/`, but the
1262
+ recommended shape is **`<role>-<n>`** — a lowercase role plus the
1263
+ smallest unused integer suffix (e.g. `worker-1`, `reviewer-2`,
1264
+ `scout-12`). Names that diverge (`worker-tests`, `alice`, `db-leader`,
1265
+ `x-y-1`) still spawn successfully but trigger a one-line stderr hint:
1266
+
1267
+ ```
1268
+ hint: agent name "worker-tests" does not match the smallest-unused-suffix
1269
+ convention (<role>-<n>; e.g. worker-1, reviewer-2). Accepted; consider
1270
+ renaming if you spawn additional workers.
1271
+ ```
1272
+
1273
+ The hint is suppressed under `--json` so script callers stay clean.
1274
+
1275
+ ### Multiple agents in one window (split panes)
1276
+
1277
+ Give them a shared `--tab`:
1278
+
1279
+ ```bash
1280
+ mu agent spawn reviewer-1 --workstream auth-refactor --cli sh --tab Review --role read-only
1281
+ mu agent spawn audit --workstream auth-refactor --cli sh --tab Review
1282
+ ```
1283
+
1284
+ The `Review` window holds whichever agents share `--tab Review`.
1285
+
1286
+ ### Spawn options
1287
+
1288
+ | Flag | Meaning |
1289
+ | ---------------------------- | ------------------------------------------------------- |
1290
+ | `--cli <name>` | Logical CLI family (effectively always `pi`; the flag exists as a key for `MU_<UPPER_CLI>_COMMAND` resolution) |
1291
+ | `--command <cmd>` | Executable launched in the pane. Defaults to `$MU_<UPPER_CLI>_COMMAND` (e.g. `MU_PI_COMMAND=pi-alt`) and finally to the `--cli` value |
1292
+ | `--tab <name>` | Group with other agents under this window name |
1293
+ | `--role <full-access\|read-only>` | Capability flag; stored but not yet enforced |
1294
+ | `--cwd <path>` | Initial working directory for the pane |
1295
+ | `-w, --workstream <name>` | Required if not auto-detectable |
1296
+
1297
+ If your `pi` binary lives under a different name, set
1298
+ `MU_PI_COMMAND=<name>` once in your shell rc: every
1299
+ `mu agent spawn --cli pi` execs it, and reconcile treats that binary's
1300
+ panes as agent-worthy when surfacing orphans. `MU_PI_COMMAND` (and
1301
+ `--command`) accept a multi-word string — tmux execs it via a shell, so
1302
+ `MU_PI_COMMAND="pi-alt --some-flag"` works. Same pattern for
1303
+ `MU_CLAUDE_COMMAND` / `MU_CODEX_COMMAND`.
1304
+
1305
+ **Project-trust prompt (gotcha).** pi asks whether to trust a project
1306
+ folder on interactive startup, before loading `AGENTS.md` and `.pi/`
1307
+ resources. A freshly-spawned agent stuck at `needs_input` is usually
1308
+ waiting on this. Spawn with `--command 'pi --approve'` (or
1309
+ `MU_PI_COMMAND="pi --approve"`) to auto-trust. Caveat: `--approve`
1310
+ trusts whatever directory the pane lands in — including `--workspace`
1311
+ forks — so use it for crews on your own code only. Otherwise the
1312
+ decision is saved per-directory in `~/.pi/agent/trust.json`, or run
1313
+ `/trust` in the pane once.
1314
+
1315
+ ### Adopt an existing tmux pane
1316
+
1317
+ You launched a `pi` by hand and decided mid-flow it belongs in the
1318
+ graph, or `mu` crashed mid-spawn and left an orphan pane with no DB
1319
+ row. Either way:
1320
+
1321
+ ```bash
1322
+ mu agent list -w auth-refactor # surfaces orphans at the bottom
1323
+ # Orphan panes (1)
1324
+ # %15 title=worker-2 cli=pi
1325
+
1326
+ mu agent adopt %15 -w auth-refactor # adopt by pane id
1327
+ mu agent adopt worker-2 -w auth-refactor # adopt by pane title (same effect)
1328
+ mu agent adopt %15 --name investigator -w auth-refactor # adopt and rename the pane
1329
+ ```
1330
+
1331
+ The pane title becomes the agent name (the claim-protocol invariant),
1332
+ so a pane titled `worker-2` registers as agent `worker-2` with no
1333
+ further config. Use `--name` when the title isn't a valid agent name.
1334
+
1335
+ Adopt is **idempotent** (twice on the same pane is a no-op) and
1336
+ **scope-aware**: the pane must be in the `mu-<workstream>` tmux
1337
+ session, or the adopt is rejected — no silent cross-session moves.
1338
+
1339
+ ---
1340
+
1341
+ ## 7. Watch the crew live
1342
+
1343
+ Attach the workstream's tmux session and you see everything.
1344
+
1345
+ ```bash
1346
+ tmux attach -t mu-auth-refactor
1347
+ ```
1348
+
1349
+ You see one tmux window per agent (or a window with split panes if
1350
+ they share a `--tab`).
1351
+
1352
+ | Tmux key | What it does |
1353
+ | -------------- | --------------------------------------------- |
1354
+ | `Ctrl+b w` | Pick a window (interactive list) |
1355
+ | `Ctrl+b n`/`p` | Cycle next/previous window |
1356
+ | `Ctrl+b d` | Detach from the session (mu doesn't care) |
1357
+
1358
+ mu does not require you to be attached. Detach freely.
1359
+
1360
+ ---
1361
+
1362
+ ## 8. Send work to an agent
1363
+
1364
+ From any shell with mu on `$PATH`:
1365
+
1366
+ ```bash
1367
+ mu agent send worker-1 "echo hello from outside"
1368
+ ```
1369
+
1370
+ mu uses the **canonical bracketed-paste protocol** internally:
1371
+
1372
+ 0. wait for the pane to stop being mid-modal (`MU_SEND_READINESS_MS`,
1373
+ default 15000; 0 disables)
1374
+ 1. `tmux copy-mode -q` (silent if not in copy mode)
1375
+ 2. `tmux set-buffer` (loads text into a uniquely-named buffer)
1376
+ 3. `tmux paste-buffer -p -d -r` (`-p` = bracketed paste, `-d` = delete
1377
+ buffer after paste, `-r` = preserve LF)
1378
+ 4. wait `MU_SEND_DELAY_MS` ms (default 500)
1379
+ 5. `tmux send-keys Enter`
1380
+ 6. confirm the Enter took; re-send it if the text is still sitting
1381
+ unsubmitted in the input box
1382
+ 7. when the text is exactly `/new`, wait for the pane to visibly change and
1383
+ stabilize before returning, so a following send cannot race the delayed
1384
+ session replacement
1385
+
1386
+ Special characters (`/`, `?`, `!`, `$`, `&&`, `|`, `*`, …) therefore
1387
+ arrive at the agent's CLI **literally**. Naive `tmux send-keys` would
1388
+ let the agent's TUI hijack `/` for "search forward" and similar.
1389
+
1390
+ The send delay is configurable per call:
1391
+
1392
+ ```bash
1393
+ MU_SEND_DELAY_MS=300 mu agent send worker-1 "..." # faster, less safe
1394
+ MU_SEND_DELAY_MS=1000 mu agent send worker-1 "..." # slow remote
1395
+ ```
1396
+
1397
+ **Steps 0, 6, and 7 make `exit 0` mean "submitted" and safe for a
1398
+ following send.** A TUI rendering a modal accepts a bracketed paste but
1399
+ *swallows the Enter after it*,
1400
+ leaving the prompt typed-but-unsubmitted. The visible symptom is an
1401
+ agent idle at `needs_input` with 0.0% context on work it never
1402
+ received. No `sleep` between a clear and a prompt is needed.
1403
+
1404
+ If a send cannot be confirmed it prints `warning: ... was NOT
1405
+ submitted` to stderr (and `"delivered": false` under `--json`).
1406
+ **Check for that warning before you wait on the task.**
1407
+
1408
+ Sending to a **busy** agent is not delayed — that input queues
1409
+ normally; only a modal/re-init spinner is waited out.
1410
+
1411
+ A **stale** target workspace (≥10 commits behind main — the red bucket
1412
+ in `mu workspace list` and the TUI Workspaces card) warns on stderr but
1413
+ still sends:
1414
+
1415
+ ```bash
1416
+ WARN: worker-1 workspace is 14 commits behind main (≥10 = stale)
1417
+ Next:
1418
+ Refresh first : mu workspace refresh worker-1 -w auth-refactor
1419
+ ```
1420
+
1421
+ `--strict-staleness` refuses instead:
1422
+
1423
+ ```bash
1424
+ mu agent send worker-1 "..." -w auth-refactor --strict-staleness
1425
+ ```
1426
+
1427
+ Agents without workspaces are skipped (common for read-only roles).
1428
+ `--json` carries `staleness: null` or `{agentName, workstreamName,
1429
+ commitsBehindMain, isStale}`.
1430
+
1431
+ ---
1432
+
1433
+ ## 9. Read what an agent did
1434
+
1435
+ ```bash
1436
+ mu agent read worker-1 # full scrollback
1437
+ mu agent read worker-1 -n 50 # last 50 lines
1438
+ ```
1439
+
1440
+ Both go through `tmux capture-pane`. No state change.
1441
+
1442
+ ---
1443
+
1444
+ ## 10. The claim protocol — from inside an agent's pane
1445
+
1446
+ An agent (the LLM running in a pane) runs `mu task claim foo` **with no
1447
+ agent name argument** — mu derives "worker-1" from the pane title. In
1448
+ worker-1's pane:
1449
+
1450
+ ```bash
1451
+ mu task claim design
1452
+ ```
1453
+
1454
+ ```
1455
+ Claimed design for worker-1 (OPEN → IN_PROGRESS)
1456
+ ```
1457
+
1458
+ Behind the scenes: mu reads `$TMUX_PANE`, asks tmux for that pane's
1459
+ title (`tmux display-message -t %15 -p '#{pane_title}'`), and runs one
1460
+ atomic conditional UPDATE guarded on `owner IS NULL OR owner = <me>`.
1461
+ If 0 rows change, mu distinguishes "task doesn't exist" from "already
1462
+ owned by someone else" and throws the right typed error.
1463
+
1464
+ Two agents claiming the same task → the second fails with "already
1465
+ owned by worker-1". Re-claim by the same agent is idempotent.
1466
+
1467
+ You can also claim explicitly from outside any pane:
1468
+
1469
+ ```bash
1470
+ mu task claim build --for worker-2
1471
+ ```
1472
+
1473
+ `--for` accepts either a bare worker name (`worker-2`, resolved in
1474
+ the task's workstream) or a qualified ref `<workstream>/<name>` for
1475
+ **cross-workstream dispatch**:
1476
+
1477
+ ```bash
1478
+ # Task lives in mufeedback-v03; worker-1 lives in roadmap-v0-3.
1479
+ mu task claim some-task -w mufeedback-v03 --for roadmap-v0-3/worker-1
1480
+ ```
1481
+
1482
+ The agent stays in its own workstream — only `tasks.owner_id` points
1483
+ across the boundary (an INTEGER FK to `agents.id`). A bad qualifier
1484
+ surfaces typed errors and writes nothing:
1485
+ `WorkstreamNotFoundError` (exit 3) on a missing prefix,
1486
+ `AgentNotFoundError` (exit 3) when the worker doesn't live there.
1487
+
1488
+ When `--for` targets an agent with a **stale** workspace (≥10 commits
1489
+ behind main), the claim warns on stderr and succeeds:
1490
+
1491
+ ```bash
1492
+ mu task claim build -w auth-refactor --for worker-2
1493
+ # stderr: WARN: worker-2 workspace is 14 commits behind main (≥10 = stale)
1494
+ # Next: Refresh first : mu workspace refresh worker-2 -w auth-refactor
1495
+ ```
1496
+
1497
+ `--strict-staleness` refuses instead with `TaskClaimStaleWorkspaceError`
1498
+ (exit 4) — for scripts that must never dispatch onto a stale parent.
1499
+ `--json` carries `staleness: null` or `{agentName, workstreamName,
1500
+ commitsBehindMain, isStale}`. Bare in-pane and `--self` claims skip the
1501
+ check; they don't assign work to a named agent.
1502
+
1503
+ ### The orchestrator pattern: `--self`
1504
+
1505
+ Not every action comes from a registered worker pane. An
1506
+ *orchestrator* (a top-level pi session, a human at a shell, a deploy
1507
+ script) often does small work directly. Two roles:
1508
+
1509
+ - **Worker** — a pane mu spawned (or you adopted). Has a row in the
1510
+ `agents` table. Identity = pane title. Claims with bare
1511
+ `mu task claim <id>`. `tasks.owner_id` points at the worker row.
1512
+
1513
+ - **Actor** — anything that *causes* a state change, including the
1514
+ orchestrator. May or may not have a row in `agents`. Always recorded
1515
+ on the op (`ops.actor`).
1516
+
1517
+ If the orchestrator tries `mu task claim some-task` directly:
1518
+
1519
+ ```
1520
+ conflict: claimer 'pi-mu' (pane %6441) is not a registered mu agent.
1521
+ Working directly? Pass --self to attribute via log instead.
1522
+ Dispatching to a worker? Pass --for <worker> to assign.
1523
+ Want full registration? Run: mu agent adopt %6441
1524
+ ```
1525
+
1526
+ Pick one based on intent:
1527
+
1528
+ ```bash
1529
+ # Orchestrator does the work itself (most common):
1530
+ mu task claim some-task --self --evidence "trivial 5-line fix"
1531
+ # -> tasks.owner_id stays NULL
1532
+ # -> the task.claim op records actor='pi-mu' (anonymous claim)
1533
+ # -> mu task show surfaces it as 'owner: (self: pi-mu)'
1534
+
1535
+ # Orchestrator dispatches to a worker:
1536
+ mu task claim some-task --for worker-1
1537
+ # -> tasks.owner_id points at worker-1
1538
+
1539
+ # Orchestrator wants to BE a registered worker (rare):
1540
+ mu agent adopt %6441 -w <ws> # only if pane is in mu-<ws> session
1541
+ mu task claim some-task # now works as a normal worker claim
1542
+ ```
1543
+
1544
+ `--self` is **only** for unregistered actors. Workers continue to
1545
+ claim with bare `mu task claim` — nothing changes for them. The
1546
+ `--actor <name>` flag overrides the auto-detected actor name (defaults
1547
+ to pane title, or `$USER`, or `unknown`):
1548
+
1549
+ ```bash
1550
+ mu task claim deploy --self --actor deploy-bot --evidence "prod release"
1551
+ ```
1552
+
1553
+ When `tasks.owner_id IS NULL` because of `--self`, `mu task show` looks
1554
+ up the most recent `task claim` event for that task and surfaces it:
1555
+
1556
+ ```
1557
+ owner : (self: pi-mu)
1558
+ ```
1559
+
1560
+ So provenance is preserved — it just lives in `ops.actor` rather
1561
+ than being conflated with the FK that points at registered workers.
1562
+
1563
+ ---
1564
+
1565
+ ## 11. Drop notes (durable context)
1566
+
1567
+ Notes are append-only and survive sessions and agent restarts — the
1568
+ cure for LLM context loss: the next agent reads the full history.
1569
+
1570
+ ```bash
1571
+ mu task note design "DECISION: JWT, 24h expiry, refresh via cookie"
1572
+ mu task note design "FILES: src/auth.rs:45-120"
1573
+ ```
1574
+
1575
+ Read them via the typed verb:
1576
+
1577
+ ```bash
1578
+ mu task notes design # all notes, oldest first
1579
+ mu task notes design --tail 3 # only the last 3 (alias --last)
1580
+ mu task notes design --since 2026-01-01 # only notes after an ISO 8601 cutoff
1581
+ mu task notes design --since-claim # only notes since the most recent
1582
+ # 'task claim' event for this task
1583
+ # (auto-resolved from the ops log)
1584
+ mu task notes design --tail 5 --json # collection envelope {items, count}
1585
+ ```
1586
+
1587
+ Filters compose: `--tail` slices the last N of whatever survived
1588
+ the timestamp filter. `--since` and `--since-claim` are mutually
1589
+ exclusive (both define a cutoff) — pick one. With no filters you get
1590
+ every note, oldest-first.
1591
+
1592
+ `--since-claim` is the orchestrator form: dispatch flows drop a
1593
+ multi-screen SPEC note BEFORE claiming, then the worker appends
1594
+ progress notes AFTER. `--since-claim` slices off the SPEC so you see
1595
+ only the worker's reports. With no claim event it degrades to no
1596
+ filter.
1597
+
1598
+ For ad-hoc shape, the SQL escape hatch:
1599
+
1600
+ ```bash
1601
+ mu sql "SELECT n.author, n.content, n.created_at
1602
+ FROM task_notes n
1603
+ JOIN tasks t ON t.id = n.task_id
1604
+ JOIN workstreams w ON w.id = t.workstream_id
1605
+ WHERE t.local_id='design' AND w.name='auth-refactor'
1606
+ ORDER BY n.id"
1607
+ ```
1608
+
1609
+ Convention for note content: `KEY: value` lines. Common keys are
1610
+ `FILES`, `DECISION`, `VERIFIED`, `BLOCKED`, `NEXT`. Mu doesn't
1611
+ enforce these — they're for the agents reading them.
1612
+
1613
+ ---
1614
+
1615
+ ## 12. Close out a task
1616
+
1617
+ ```bash
1618
+ mu task close design # OPEN/IN_PROGRESS → CLOSED
1619
+ mu task close umbrella --if-ready # close ONLY if every blocker
1620
+ # is CLOSED; else no-op + list
1621
+ # the still-blocking ids
1622
+ mu task open design # CLOSED → OPEN (e.g. closed by mistake)
1623
+ ```
1624
+
1625
+ Both are idempotent (closing an already-CLOSED task prints a no-op and
1626
+ exits 0). Owner is left intact — use `mu task release <id>` to clear
1627
+ ownership when an agent bails mid-flight. `IN_PROGRESS` flips back to
1628
+ `OPEN` so the task re-enters the ready set. `--reopen` forces `OPEN`
1629
+ from `CLOSED`.
1630
+
1631
+ When the closing actor has a per-agent workspace and that workspace
1632
+ has uncommitted edits, a successful close adds one extra `Next:` hint
1633
+ reminding the actor to commit before the next wave:
1634
+
1635
+ ```bash
1636
+ cd $(mu workspace path worker-1 -w auth-refactor) && git commit -am 'Design auth module'
1637
+ ```
1638
+
1639
+ The hint is best-effort: no workspace, a clean workspace, the `none`
1640
+ backend, or a failed VCS dirty check simply omit it. The same
1641
+ `nextSteps` entry is present in `--json` output.
1642
+
1643
+ `--if-ready` is the umbrella-on-wave-done shape: fire
1644
+ `mu task close <umbrella> --if-ready` after each wave-task finishes.
1645
+ It's a no-op while any blocker is OPEN / IN_PROGRESS, printing the
1646
+ still-blocking ids + a `mu task wait` hint; once the last blocker is
1647
+ CLOSED, the same command closes the umbrella. JSON on the no-op path:
1648
+ `{ skipped: "not_ready", changed: false, blockingIds: ["..."], ... }`.
1649
+ Exit 0 either way — the no-op is success.
1650
+
1651
+ ```bash
1652
+ mu task release design # clear owner; IN_PROGRESS → OPEN
1653
+ # (CLOSED preserved)
1654
+ mu task release design --reopen # clear owner AND force status to OPEN
1655
+ # (un-close + release in one verb)
1656
+ ```
1657
+
1658
+ With `design` closed, `build` is ready:
1659
+
1660
+ ```
1661
+ $ mu task next -w auth-refactor
1662
+ ┌───────┬────────┬───────────────────┬────────┬────────┬──────┬───────┐
1663
+ │ name │ status │ title │ impact │ effort │ ROI │ owner │
1664
+ ├───────┼────────┼───────────────────┼────────┼────────┼──────┼───────┤
1665
+ │ build │ OPEN │ Build auth module │ 80 │ 5 │ 16.0 │ — │
1666
+ └───────┴────────┴───────────────────┴────────┴────────┴──────┴───────┘
1667
+ ```
1668
+
1669
+ ---
1670
+
1671
+ ## 13. The SQL escape hatch is your friend
1672
+
1673
+ Most routine operations have a typed verb — prefer those, with `--json`
1674
+ for scripting. `mu sql` covers ad-hoc joins, manual recovery, and
1675
+ schema exploration. The schema is 10 tables — 4 **portable**
1676
+ (`workstreams`, `tasks`, `task_edges`, `task_notes`: what crosses
1677
+ machines) and 6 **machine-local** (`agents`, `vcs_workspaces`,
1678
+ `machine_identity`, `sync_peers`, `schema_version`, and the `ops` log,
1679
+ which is carrier not cargo) — plus three views (`ready`, `blocked`,
1680
+ `goals`):
1681
+
1682
+ ```bash
1683
+ mu sql "SELECT name FROM sqlite_master WHERE type IN ('table','view') ORDER BY type, name"
1684
+ ```
1685
+
1686
+ ### Prefer the typed verb where one exists
1687
+
1688
+ | Want | Typed verb |
1689
+ | ----------------------------------------------------- | --------------------------------------- |
1690
+ | Tasks owned by an agent (current workstream) | `mu task owned-by <agent> [--json]` |
1691
+ | Tasks owned by ANY same-named worker (all workstreams)| `mu task owned-by <agent> --all [--json]`|
1692
+ | Highest-ROI ready task | `mu task next [-w] [-n K] [--json]` |
1693
+ | What did I touch most recently / what's stale | `mu task list --sort recency` / `--sort age` |
1694
+ | Visualise what blocks what | `mu task tree <id> [--json]` |
1695
+ | Show row + edges + notes | `mu task show <id> [--json]` |
1696
+ | Delete + cascade edges/notes (two-phase: bare = dry-run; `--yes` commits) | `mu task delete <id>` / `mu task delete <id> --yes` |
1697
+ | Add / remove a single edge | `mu task block` / `mu task unblock` |
1698
+ | Replace all blockers atomically | `mu task reparent <id> --blocked-by ...` |
1699
+ | Modify scalar fields | `mu task update <id> [--title ...]` |
1700
+ | Read the activity log / subscribe to events | `mu log [--tail] [--intent task.close]` |
1701
+ | Block until tasks reach a status (orchestrator wait) | `mu task wait <ref> [<ref>...] [--first|--any] [--timeout S] --on-stall exit` |
1702
+ | Block until agents finish working (task-less wait) | `mu agent wait <name> [<name>...] [--first|--any] [--timeout S]` |
1703
+ ### `mu agent wait`: the task-less counterpart to `mu task wait`
1704
+
1705
+ Scratch helpers usually own no task, so `mu task wait` has nothing to
1706
+ watch. `mu agent wait` blocks on the agent's runtime status: an agent
1707
+ **fires** when it goes **busy → any other state**. It must be observed
1708
+ busy first, so an already-idle agent does NOT fire instantly — you're
1709
+ waiting for *this* work to finish. Replaces `sleep` polling loops.
1710
+
1711
+ ```bash
1712
+ mu agent spawn helper-1 -w scratch
1713
+ mu agent send helper-1 'Investigate X. Report findings.'
1714
+ mu agent wait helper-1 -w scratch --first # blocks until pi finishes
1715
+ mu agent read helper-1 -w scratch -n 80 # now read the result
1716
+ ```
1717
+
1718
+ Mirrors `mu task wait`'s shape: `--any`/`--first` fire on the first
1719
+ agent (default: all must finish); `--first` prints the firing agent's
1720
+ ref; `--json` carries `nextSteps`; refs may be qualified
1721
+ `<workstream>/<name>`. Exit codes: `0` met, `5` timeout, `6` a watched
1722
+ agent's pane died. Status detection is pi-only (a non-pi pane always
1723
+ reads `needs_input`, so it never goes busy and the wait times out).
1724
+
1725
+ **Don't reach for this verb to catch a worker that asked a question.**
1726
+ It fires on `busy → needs_input`, so it does detect the case — but it
1727
+ keys on **agents**, which means a task-DAG orchestrator would have to
1728
+ track the task→agent mapping itself and run two waits concurrently to
1729
+ catch both "task closed" and "worker asked something". `mu task wait
1730
+ --stuck-after` / `--on-stall` covers that from the task side; see
1731
+ [attention detection](#mu-task-wait-attention-detection---stuck-after----on-stall).
1732
+
1733
+ ### `mu task wait`: cross-workstream refs + `--first` returns WHICH
1734
+
1735
+ Each `<ref>` is either a bare task name (resolves via `-w` /
1736
+ `$MU_SESSION` / tmux session) or a qualified `<workstream>/<name>`
1737
+ ref. When all refs are qualified, `-w` is not required; mixed lists
1738
+ are allowed (bare uses `-w`, qualified uses its prefix).
1739
+
1740
+ ```bash
1741
+ # All-bare with -w
1742
+ mu task wait build_a build_b -w mufeedback-v03 --timeout 1200 --on-stall exit
1743
+
1744
+ # All-qualified — cross-workstream wait, no -w needed
1745
+ mu task wait roadmap-v0-3/archive_phase2 mufeedback-v03/cli_audit --timeout 1800 --on-stall exit
1746
+
1747
+ # Mixed — bare uses -w; qualified ignores it
1748
+ mu task wait cli_audit roadmap-v0-3/archive_phase2 -w mufeedback-v03 --on-stall exit
1749
+ ```
1750
+
1751
+ `--first` is an alias for `--any` that ALSO prints the firing ref's
1752
+ qualified id to stdout (and populates the `firing` field in `--json`,
1753
+ which `--any` leaves null). Use
1754
+ it to drive a single-shot dispatch loop — one wait, one cherry-pick,
1755
+ one verify, one workspace recycle:
1756
+
1757
+ ```bash
1758
+ # The dispatch-pipeline recipe: cycle until in_flight is empty.
1759
+ in_flight=( mufeedback-v03/foo mufeedback-v03/bar roadmap-v0-3/baz )
1760
+ while (( ${#in_flight[@]} > 0 )); do
1761
+ res=$(mu task wait "${in_flight[@]}" --first --timeout 90 --on-stall exit --json)
1762
+ closed=$(jq -r '.firing.qualifiedId // empty' <<<"$res")
1763
+ if [[ -z "$closed" ]]; then break; fi # timeout or exit 6 — see below
1764
+
1765
+ worker=$(jq -r '.firing.owner // empty' <<<"$res")
1766
+ ws=${closed%%/*}
1767
+
1768
+ # 1. Inspect, then run, the sha-pinned apply hint from nextSteps.
1769
+ # When the worker has commits since its fork point, the command is
1770
+ # `git cherry-pick <sha>` (or `<first>^..<last>` for multiple
1771
+ # commits). When the worker closed without committing, nextSteps
1772
+ # says so and points at manual `git diff` / `git apply` rescue.
1773
+ apply=$(jq -r '.nextSteps[0].command' <<<"$res")
1774
+ printf 'apply hint: %s\n' "$apply"
1775
+ if [[ "$apply" == git\ cherry-pick* ]]; then
1776
+ eval "$apply"
1777
+ else
1778
+ echo "manual rescue required; inspect the worker workspace before continuing"
1779
+ break
1780
+ fi
1781
+
1782
+ # 2. Verify
1783
+ npm run typecheck && npm run lint && npm run test:fast && npm run test && npm run build
1784
+
1785
+ # 3. Refresh the workspace for the next dispatch (rebases onto
1786
+ # fresh main WITHOUT killing the worker's LLM context). Default
1787
+ # base = origin/HEAD (git) / trunk() (jj/sl); --from <ref>
1788
+ # overrides. Refuses on dirty WC; conflicts exit 5 with a `cd`
1789
+ # hint to resolve in-place.
1790
+ mu workspace refresh "$worker" -w "$ws"
1791
+ # Alt: `mu workspace free "$worker" -w "$ws"` throws the workspace
1792
+ # away entirely (the lossy escape). The next
1793
+ # `mu agent spawn --workspace` allocates a fresh one. Use when
1794
+ # you don't care about replaying the worker's commits.
1795
+
1796
+ # 4. Drop $closed from in_flight, dispatch the next task, repeat.
1797
+ in_flight=( "${in_flight[@]/$closed}" )
1798
+ done
1799
+ ```
1800
+
1801
+ The `--json` shape on success is `{ firing, all, timedOut, nextSteps,
1802
+ ... }`:
1803
+
1804
+ * `firing` — `{ workstreamName, name, qualifiedId, status, owner }`
1805
+ on **`--first`** success. `null` in every other case: on `--any`
1806
+ success, on `--all` success, and on timeout. `--any` exits `0` with
1807
+ `firing: null`, so a script that reads `.firing.qualifiedId` after
1808
+ `--any` dereferences null on a **successful** wait. Pass `--first`
1809
+ when you need to know WHICH ref fired; `--any` only tells you that
1810
+ one did.
1811
+ * `all` — array of refs that REACHED the target (with
1812
+ `qualifiedId` + `reachedAt`).
1813
+ * `timedOut` — array of refs that did NOT reach the target. Empty on
1814
+ clean success; populated on partial-progress timeout.
1815
+ * `nextSteps`— the same hint list printed to stdout (cherry-pick,
1816
+ verify, refresh, or `mu task show` for unmet refs — except a
1817
+ `stuck` ref, which gets `mu agent read <owner>` because its pane,
1818
+ not its task row, holds the reason it stopped).
1819
+
1820
+ ### Wait exit codes (`mu task wait`)
1821
+
1822
+ `mu task wait` polls the watched tasks every second (cheap indexed
1823
+ SELECT + a per-poll reconcile of every workstream in the wait set)
1824
+ and exits with one of:
1825
+
1826
+ | Exit | Meaning |
1827
+ |------|-------------------------------------------------------------------------|
1828
+ | `0` | The wait condition was met (`--all` reached, or `--any` / `--first` saw at least one). |
1829
+ | `5` | `--timeout` expired before the condition was met. `--json` payload still includes `all` (refs that did reach) and `timedOut` (refs that didn't). |
1830
+ | `6` | **REAPER_DETECTED.** A WATCHED task transitioned `IN_PROGRESS → OPEN` between polls because the reconciler detected the owning pane was dead and the reaper flipped the task back. Scoped to the wait set: a reaper-flip in some other workstream (or some other task in the same workstream) does NOT trigger exit 6. Fires only when the wait target is `CLOSED` (the default) — with `--status OPEN` a reaper-flip TO open IS the success and the wait returns `0`. Re-dispatch a worker (`mu agent spawn ... && mu task claim --for ...`) and re-run the wait. (`task_wait_reconcile_dead_panes` + `task_wait_cross_workstream`) |
1831
+ | `7` | **STALL_DETECTED.** Only with `--on-stall exit`. The existing `--stuck-after` predicate fired on a watched task (IN_PROGRESS, owner alive but in `needs_input` for `>= --stuck-after` seconds) and the wait threw instead of polling forward. Same target=CLOSED carve-out as exit 6 (with `--status OPEN`/etc the worker reaching `needs_input` might BE the success path; `--on-stall exit` is downgraded to warn-only). Stderr names the task + owner + age. Exit 7 is the **ambiguous** sibling of exit 6: dead pane (6) is unambiguous (re-dispatch); idle agent (7) might be transient, or be waiting on an answer — read the pane before deciding. If both fire in the same poll, exit 6 wins (reaper-flip moves status off `IN_PROGRESS`, so the stuck-check's predicate naturally fails). (`task_wait_stall_action_flag`) |
1832
+
1833
+ The per-poll reconcile means a worker pane that died **before** you
1834
+ ran `mu task wait` is also reaped on the first tick — you'll see exit
1835
+ `6` in well under a second instead of running out the `--timeout`.
1836
+ For cross-workstream waits the reconcile loops over every workstream
1837
+ in the wait set (so a dead pane in workstream B is reaped while you
1838
+ wait on its task there too).
1839
+
1840
+ ### `mu task wait`: attention detection (`--stuck-after` + `--on-stall`)
1841
+
1842
+ For unattended waits, always pass `--on-stall exit`; otherwise the default
1843
+ warning leaves the wait polling. Two orthogonal flags govern the behaviour:
1844
+
1845
+ * `--stuck-after <seconds>` — the **trigger**. An IN_PROGRESS task
1846
+ whose owner has been in `needs_input` for `>= N` seconds is marked
1847
+ as needing attention. Default `300` (5 min); pass `0` to disable
1848
+ detection entirely (no warn AND no exit).
1849
+ * `--on-stall <action>` — the **action** when the trigger fires.
1850
+ Two values:
1851
+ * `warn` (default) — yellow attention warning to stderr (deduped per
1852
+ task per wait call), corroborating `agent stalled <name> owns
1853
+ <task> for <secs>s` event in the ops log, and `wait` keeps
1854
+ polling.
1855
+
1856
+ **`needs_input` has at least three causes, and the trigger cannot tell
1857
+ them apart:**
1858
+
1859
+ | Cause | Response |
1860
+ | --- | --- |
1861
+ | Worker finished and committed, skipped `mu task close` | close it, merge the work |
1862
+ | Worker asked a question and is waiting on an answer | read the pane, answer it |
1863
+ | Worker hit an approval prompt or a wedged tool call | intervene or `mu agent kick` |
1864
+
1865
+ So the warning states the observation and points at `mu agent read
1866
+ <owner>`, which is the next move in all three cases — the evidence is
1867
+ in the pane, not in the task row. `--json` carries `"stuck": true` per
1868
+ task, and a stuck ref's `nextSteps` entry reads the owner's pane
1869
+ instead of offering `mu task show`.
1870
+
1871
+ A worker stopping to ask is **desirable behaviour**, not negligence:
1872
+ the questions that get asked are usually the ones that prevent
1873
+ rework. Treat an attention warning as "go look", not "the worker
1874
+ misbehaved".
1875
+ * `exit` — same emit + persist, then **exit 7**
1876
+ (`STALL_DETECTED`). The unattended-orchestrator escape: a
1877
+ wrapping policy can branch on 7 (idle, ambiguous — poke vs
1878
+ release) vs 6 (dead pane, unambiguous — re-dispatch). Suppressed
1879
+ when `--status` is anything other than `CLOSED` (mirrors
1880
+ exit-6's carve-out: with `--status OPEN` reaching `needs_input`
1881
+ might BE the success path).
1882
+
1883
+ ```bash
1884
+ # Default: warn at 5 min, keep polling.
1885
+ mu task wait build_a build_b -w mufeedback-v03 --timeout 1800
1886
+
1887
+ # Tune the trigger; same warn-only action.
1888
+ mu task wait build_a -w mufeedback-v03 --stuck-after 60
1889
+
1890
+ # Exit on stall (cron-driven wrapper):
1891
+ mu task wait build_a -w mufeedback-v03 --on-stall exit
1892
+ # exit 0 → closed
1893
+ # exit 5 → timeout
1894
+ # exit 6 → dead pane (re-dispatch)
1895
+ # exit 7 → idle agent (poke or release — inspect first)
1896
+
1897
+ # Tune both. Exit at 60s of needs_input:
1898
+ mu task wait build_a -w mufeedback-v03 --stuck-after 60 --on-stall exit
1899
+
1900
+ # Disable both warn AND exit (--stuck-after 0 wins):
1901
+ mu task wait build_a -w mufeedback-v03 --stuck-after 0 --on-stall exit
1902
+ ```
1903
+
1904
+ ### Common ad-hoc queries
1905
+
1906
+ ```bash
1907
+ # Set task to IN_PROGRESS without claiming (claim does this automatically;
1908
+ # this covers the rare manual case). local_id is per-workstream unique,
1909
+ # so always scope by workstream_id to avoid hitting a same-named task in
1910
+ # another workstream.
1911
+ mu sql "UPDATE tasks SET status='IN_PROGRESS'
1912
+ WHERE local_id='build'
1913
+ AND workstream_id=(SELECT id FROM workstreams WHERE name='mufeedback-v03')"
1914
+
1915
+ # What's blocking what (open tasks only) — same data as `mu task tree`
1916
+ # but as a flat join when you want a wider report. task_edges is keyed
1917
+ # by tasks.id, not local_id; join workstreams to scope the report.
1918
+ mu sql "SELECT b.local_id AS blocked, t.local_id AS by_task
1919
+ FROM tasks b
1920
+ JOIN workstreams w ON w.id = b.workstream_id
1921
+ JOIN task_edges e ON e.to_task_id = b.id
1922
+ JOIN tasks t ON t.id = e.from_task_id
1923
+ WHERE w.name='mufeedback-v03'
1924
+ AND t.status != 'CLOSED' AND b.status = 'OPEN'"
1925
+
1926
+ # Recursive CTE: every task that transitively blocks `launch` in a
1927
+ # given workstream (or use `mu task tree launch --json` for the same
1928
+ # data structured). local_id is per-workstream, so resolve the seed
1929
+ # under a workstream filter.
1930
+ mu sql "WITH RECURSIVE prereqs(id) AS (
1931
+ SELECT t.id FROM tasks t
1932
+ JOIN workstreams w ON w.id = t.workstream_id
1933
+ WHERE t.local_id='launch' AND w.name='mufeedback-v03'
1934
+ UNION
1935
+ SELECT e.from_task_id FROM task_edges e, prereqs
1936
+ WHERE e.to_task_id = prereqs.id
1937
+ )
1938
+ SELECT t.local_id, t.title, t.status
1939
+ FROM prereqs JOIN tasks t ON t.id = prereqs.id"
1940
+ ```
1941
+
1942
+ `mu sql` accepts both reads and writes. Reads are pretty-printed as a
1943
+ table; writes report `<n> rows affected`.
1944
+
1945
+ ---
1946
+
1947
+ ## 14. Recovery scenarios
1948
+
1949
+ ### An agent's pane dies externally
1950
+
1951
+ You killed it from another tmux client, or its CLI crashed:
1952
+
1953
+ ```bash
1954
+ mu agent list # worker-1's row prunes itself (ghost detected)
1955
+ ```
1956
+
1957
+ Reconciliation runs on every `mu agent list` / `mu`. Three steps:
1958
+
1959
+ 1. **Prune ghost rows** — DB row whose `pane_id` no longer exists in
1960
+ tmux gets deleted
1961
+ 2. **Detect status from scrollback** — for survivors, capture the
1962
+ pane and re-derive status (busy / needs_input / needs_permission /
1963
+ spawning) per the pi-status detector
1964
+ 3. **Surface orphan panes** — panes in the workstream's session whose
1965
+ `pane.command` looks like an agent CLI but that aren't in the
1966
+ registry. **Not** auto-adopted; mu lists them under "Orphan panes"
1967
+ with the `mu agent adopt <pane-id>` hint
1968
+
1969
+ ### A worker is wedged on an unbounded tool subprocess
1970
+
1971
+ A worker ran `find / -maxdepth 6 ...` (30-60 minutes on a populated
1972
+ home directory) or a busy-wait loop. `mu agent send` queues steering
1973
+ messages until the tool returns; `tmux send-keys C-c` against the
1974
+ pane doesn't propagate (the wrapping pi/claude/codex CLI catches it
1975
+ as TUI input). The escape hatch:
1976
+
1977
+ ```bash
1978
+ mu agent kick worker-1 # SIGINT (graceful, default)
1979
+ mu agent kick worker-1 --signal SIGTERM # polite escalation
1980
+ mu agent kick worker-1 --signal SIGKILL # hammer
1981
+ ```
1982
+
1983
+ `mu agent kick` looks up the pane's TTY (`tmux display-message -p
1984
+ '#{pane_tty}'`), asks `ps -t <tty>` for the foreground process group
1985
+ (the row whose `stat` contains `+`), and signals the whole pgrp.
1986
+ Refuses with `NoForegroundProcessError` when the foreground IS the
1987
+ wrapping CLI — use `mu agent close` then.
1988
+
1989
+ Prevention: don't prompt workers to run filesystem-wide `find`, broad
1990
+ `grep -r /`, or unbounded busy-wait loops. Scope to `$WORKSPACE`.
1991
+
1992
+ ### You closed your terminal session
1993
+
1994
+ The workstream's tmux session keeps running detached. Reconnect with
1995
+ `tmux a -t mu-auth-refactor`. Agents are alive; the DB has the
1996
+ registry; everything resumes. mu is daemon-free — every `mu`
1997
+ invocation is a short-lived process that re-reads from
1998
+ `~/.local/state/mu/mu.db`.
1999
+
2000
+ ### The mu DB seems wrong
2001
+
2002
+ ```bash
2003
+ mu doctor # quick health check (exit 5 = drift)
2004
+ mu doctor --deep # rebuild + field-level diff
2005
+ mu doctor --disk # + per-workspace byte usage
2006
+ sqlite3 ~/.local/state/mu/mu.db .schema # inspect
2007
+ rm ~/.local/state/mu/mu.db # nuke (last resort; loses task graph and registry)
2008
+ ```
2009
+
2010
+ ### You ran a destructive verb and want to undo it
2011
+
2012
+ Every change any verb makes is captured as **ops** under one
2013
+ **group**, so undo is per-action rather than per-file.
2014
+
2015
+ ```bash
2016
+ mu undo # list recent undoable groups (newest first)
2017
+ mu undo 4a1a6305 # preview the inverse of one group (dry run)
2018
+ mu undo 4a1a6305 --yes # apply it
2019
+ mu undo -n 20 # list more groups
2020
+ ```
2021
+
2022
+ A group id may be given as any unique prefix. Full semantics —
2023
+ granularity, undo-as-an-op (which is also "redo"), and the
2024
+ superseded-work refusal plus its `--force` override — are in
2025
+ [§ Undoing one action](#undoing-one-action-mu-undo).
2026
+
2027
+ Two important caveats:
2028
+
2029
+ - **Only rows are reverted.** Undo emits inverse ops against the
2030
+ portable tables. It does not resurrect a killed tmux pane, an
2031
+ agent registry row, or a workspace directory `mu workspace free`
2032
+ removed — none of those are portable state, so none of them are
2033
+ in the log.
2034
+ - **For whole-DB recovery, use `mu rebuild <file>`**, which replays
2035
+ the entire ops log into a NEW file. It never writes in place.
2036
+
2037
+ ### Workspace orphans (dirs on disk with no DB row)
2038
+
2039
+ A `--workspace` spawn that aborted partway, or a manual `rm` of
2040
+ `vcs_workspaces` rows, can leave dirs in
2041
+ `<state-dir>/workspaces/<workstream>/<agent>/` with no DB row. They're
2042
+ invisible to `mu workspace list` but they BLOCK subsequent
2043
+ `--workspace` spawns under the same name.
2044
+
2045
+ ```bash
2046
+ mu state -w <workstream> # 'Workspace orphans' section in yellow
2047
+ mu workspace orphans -w <workstream> # focused list + cleanup recipe
2048
+ ```
2049
+
2050
+ For each orphan, the cleanup is one of:
2051
+
2052
+ ```bash
2053
+ # git-backed workspace: also prunes the worktree registry
2054
+ (cd <project-root> && git worktree remove --force <orphan-path>)
2055
+
2056
+ # any backend (last resort)
2057
+ rm -rf <orphan-path>
2058
+ ```
2059
+
2060
+ The `Next:` block from `mu workspace orphans` interpolates the
2061
+ actual paths so you can copy-paste.
2062
+
2063
+ ### You typo'd a workstream name and want to rename it
2064
+
2065
+ The `workstreams.name` column has `ON UPDATE CASCADE` on every
2066
+ child-table foreign key, so renaming a workstream is a single SQL
2067
+ statement that propagates atomically through `agents`, `tasks`,
2068
+ `task_notes`, and `vcs_workspaces`:
2069
+
2070
+ ```bash
2071
+ # 1. Validate the new name fits the rules (or mu will reject it on
2072
+ # next use). Lowercase alpha first, then alnum/_/-, ≤32 chars,
2073
+ # no '.' or ':' (tmux mangles them), no 'mu-' prefix.
2074
+ # 2. Rename in the DB. Single statement; cascades to every child.
2075
+ mu sql "UPDATE workstreams SET name='auth-refactor' WHERE name='auth-refator'"
2076
+
2077
+ # 3. Rename the tmux session too (only if it's currently alive).
2078
+ tmux rename-session -t mu-auth-refator mu-auth-refactor
2079
+ ```
2080
+
2081
+ There is no typed `mu workstream rename` verb <!-- doc-cli-drift:skip -->: the
2082
+ schema does the work, and wrapping one safe statement buys nothing (no
2083
+ atomicity to preserve, no validation to add). The recipe above is the
2084
+ canonical answer, and the same `ON UPDATE CASCADE` makes `mu sql`
2085
+ renames safe for `tasks.local_id` and `agents.name` too.
2086
+
2087
+ ---
2088
+
2089
+ ## 15. Cleanup
2090
+
2091
+ ### Close individual agents
2092
+
2093
+ ```bash
2094
+ mu agent close worker-1 # kills pane + drops registry row
2095
+ ```
2096
+
2097
+ Idempotent: a missing pane and a missing row are both fine.
2098
+
2099
+ If the agent has a workspace:
2100
+
2101
+ - **Clean** (no uncommitted changes AND no commits since fork) —
2102
+ auto-freed alongside the close.
2103
+ - **Dirty** — close refuses with `WorkspacePreservedError` (exit 4).
2104
+ Either `mu workspace free <agent>` first (optionally `--commit` to
2105
+ capture pending changes) then close, or
2106
+ `mu agent close <agent> --discard-workspace` to do both (lossy).
2107
+
2108
+ ### Tear down the whole workstream
2109
+
2110
+ `mu workstream teardown` is the counterpart of `mu workstream init`: it
2111
+ kills the workstream's tmux session AND deletes every DB row tagged
2112
+ with the workstream name (edges and notes go via FK cascade on tasks).
2113
+ The workstream resolves as everywhere else: `--workstream <name>` >
2114
+ `$MU_SESSION` > current tmux session (`mu-` prefix stripped).
2115
+
2116
+ Two-phase by default: a bare `mu workstream teardown` prints a dry-run
2117
+ summary and exits without touching anything. Pass `-y` / `--yes` to
2118
+ tear it down.
2119
+
2120
+ ```bash
2121
+ mu workstream teardown --workstream auth-refactor # dry-run: shows counts, exits
2122
+ mu workstream teardown --workstream auth-refactor --yes # actually does it
2123
+
2124
+ # Or, from inside the workstream's tmux session:
2125
+ mu workstream teardown --yes # workstream auto-detected
2126
+
2127
+ # Sweep every empty workstream (zero tasks, agents, vcs_workspaces)
2128
+ # in one call. Tmux session presence and audit-only log entries do NOT
2129
+ # disqualify. Also surfaces unregistered `mu-*` tmux sessions (test
2130
+ # litter, or a partial teardown that dropped the DB row but left the
2131
+ # session). ONLY `mu-`-prefixed sessions are touched. Mutually
2132
+ # exclusive with -w. Dry-run lists what WOULD go
2133
+ # (created_at renders `—` for mux-only entries); --yes tears them down.
2134
+ mu workstream teardown --empty # dry-run: table of empties
2135
+ mu workstream teardown --empty --yes # tear them all down
2136
+ ```
2137
+
2138
+ ```
2139
+ Workstream auth-refactor (mux session mu-auth-refactor)
2140
+ mux session : alive (will be killed)
2141
+ agents : 1
2142
+ tasks : 1 (edges: 0, notes: 0)
2143
+ workspaces : 0
2144
+
2145
+ Destroyed auth-refactor: killed mux=true, agents=1, tasks=1, edges=0, notes=0, workspaces=0/0
2146
+ ```
2147
+
2148
+ Idempotent on every leg: a missing tmux session is fine, zero DB rows
2149
+ is fine, and a repeat teardown prints "nothing to tear down" and exits 0.
2150
+
2151
+ Destroy writes TOMBSTONE ops rather than erasing history, so the work
2152
+ stays in the ops log. `mu undo <group> --yes` reverses the row
2153
+ deletions — but not the killed tmux session or freed workspace dirs.
2154
+ See
2155
+ [§ 14: You ran a destructive verb and want to undo it](#you-ran-a-destructive-verb-and-want-to-undo-it).
2156
+
2157
+ The tmux session is killed BEFORE the DB rows so an unexpected tmux
2158
+ failure leaves the registry intact (you can retry); if you only want
2159
+ the DB cleared, use `mu sql` directly:
2160
+
2161
+ ```bash
2162
+ mu sql "DELETE FROM tasks
2163
+ WHERE workstream_id=(SELECT id FROM workstreams WHERE name='auth-refactor')" # cascades
2164
+ mu sql "DELETE FROM agents
2165
+ WHERE workstream_id=(SELECT id FROM workstreams WHERE name='auth-refactor')"
2166
+ ```
2167
+
2168
+ Or nuke the entire DB:
2169
+
2170
+ ```bash
2171
+ rm ~/.local/state/mu/mu.db # next mu invocation re-creates an empty schema
2172
+ ```
2173
+
2174
+ ### Before tearing down a workstream
2175
+
2176
+ A workstream's task graph + notes IS the project memory.
2177
+ `mu workstream teardown` removes the live rows; the ops log keeps them,
2178
+ and `mu undo <group> --yes` reverses the row deletions. **A pre-flight
2179
+ `mu db backup` is not warranted for a teardown** — the log already is
2180
+ the backup.
2181
+
2182
+ Finding the group id later is what `--torn-down` is for:
2183
+
2184
+ ```bash
2185
+ mu workstream list --torn-down
2186
+ # name group torn down tasks edges notes
2187
+ # gchatui-node 7a40e6cc 52m ago 220 103 714
2188
+ # surface-audit 98007873 3d ago 51 51 201 ← recreated since
2189
+
2190
+ mu undo 7a40e6cc # preview
2191
+ mu undo 7a40e6cc --yes # restore the rows
2192
+ ```
2193
+
2194
+ One entry per teardown, newest first, read straight from the ops log —
2195
+ so a name torn down twice lists twice (the group is the identity, not
2196
+ the name) and teardowns from before the 1.2.0 rename are included.
2197
+ `← recreated since` means a later op put that name back, so undoing it
2198
+ would be a no-op; the printed `Next:` hint always names the newest
2199
+ entry that is still restorable. What does NOT come back is what was
2200
+ never in the DB: killed panes and freed workspace dirs.
2201
+
2202
+ There is no markdown export. Use the typed surfaces instead:
2203
+
2204
+ | Need | Verb |
2205
+ | ---- | ---- |
2206
+ | A safety copy before a destructive change | `mu db backup <file>` (`VACUUM INTO`; never overwrites) |
2207
+ | Find a past teardown's group id | `mu workstream list --torn-down` |
2208
+ | Reverse a teardown you regret | `mu undo <group> --yes` |
2209
+ | Laptop ↔ devserver handoff | Ambient **sync** — set `MU_SYNC_DIR` and every command carries it (§ 15.6) |
2210
+ | Peer status / a torn segment | `mu sync`, `mu sync --repair <peer>` |
2211
+ | Disaster recovery from the ops log | `mu rebuild <file>` |
2212
+
2213
+ Anything else — reading the graph out for grep, review or a git-checked-in
2214
+ artifact — goes through `--json` and whatever renderer you prefer:
2215
+
2216
+ ```bash
2217
+ mu task list -w auth-refactor --json
2218
+ mu task notes <id> -w auth-refactor --json
2219
+ ```
2220
+
2221
+ ---
2222
+
2223
+ ## 15.6 Multi-machine sync
2224
+
2225
+ **One env var, on every machine.** That is the whole configuration:
2226
+
2227
+ ```bash
2228
+ export MU_SYNC_DIR=$HOME/Sync/mu # a folder something else keeps in step
2229
+ ```
2230
+
2231
+ Now every `mu` invocation flushes your ops into
2232
+ `$MU_SYNC_DIR/<machine_id>.jsonl` and reads every OTHER `.jsonl` in that
2233
+ folder. Nothing else to set up: no peer list, no host names, no daemon.
2234
+ Drop a third machine in and it appears.
2235
+
2236
+ The end-to-end walkthrough with real output is
2237
+ [§ 0.3 Laptop ↔ devserver](#03-laptop--devserver). There is no export
2238
+ step, no import step, and no "which side is authoritative" decision.
2239
+
2240
+ ### `mu sync` — the status report
2241
+
2242
+ Sync already happened on your last command, so `mu sync`'s job is to
2243
+ tell you *who your peers are and whether transport is working*:
2244
+
2245
+ ```console
2246
+ $ mu sync
2247
+ flushed 14 ops · ingested 22 from 1 peer
2248
+ ┌──────────┬───────────┬────────┬─────────┐
2249
+ │ machine │ last seen │ behind │ │
2250
+ ├──────────┼───────────┼────────┼─────────┤
2251
+ │ 7f3a91c2 │ 2m ago │ 0 │ │
2252
+ ├──────────┼───────────┼────────┼─────────┤
2253
+ │ c8ec0feb │ 3d ago │ 47 │ ← stale │
2254
+ └──────────┴───────────┴────────┴─────────┘
2255
+ Next:
2256
+ Pull fresh segments (1 stale peer) : rsync -av <host>:/home/me/Sync/mu/ /home/me/Sync/mu/
2257
+ Or stop doing it by hand : # share /home/me/Sync/mu with Syncthing
2258
+ ```
2259
+
2260
+ Machines are named by `machine_id` prefix, not hostname — a hostname is
2261
+ machine-local and never travels. `behind` is how many lines of that
2262
+ peer's segment you *hold but have not applied*; non-zero means either a
2263
+ transfer caught mid-flight (it resolves itself) or a defect that
2264
+ stopped the read (see `--repair`).
2265
+
2266
+ Two flags, and only two:
2267
+
2268
+ ```bash
2269
+ # Read a peer's DB directly — an sshfs mount, or a file you scp'd.
2270
+ # A different READER: its SQLite ops table, not a JSONL segment.
2271
+ mu sync --from /mnt/devserver/.local/state/mu/mu.db
2272
+
2273
+ # Re-read a peer's segment from zero, after a torn transfer.
2274
+ # Safe to run any time: ingest is idempotent.
2275
+ mu sync --repair c8ec
2276
+ ```
2277
+
2278
+ A one-off directory needs no flag at all — the env var already does it:
2279
+
2280
+ ```bash
2281
+ MU_SYNC_DIR=/media/usb-stick mu state # ingest from a USB stick
2282
+ ```
2283
+
2284
+ ### Transport is yours
2285
+
2286
+ mu reads and writes files. It never runs `ssh`, `scp`, or `rsync` for
2287
+ you — that would mean owning ssh config, jump hosts, `ProxyCommand`,
2288
+ non-standard ports, identity files, and password prompts. When a peer
2289
+ looks stale, mu prints the command and you paste it.
2290
+
2291
+ Pick any file-mover; segments are **append-only and
2292
+ single-writer-per-file**, so anything works:
2293
+
2294
+ | Tier | How | Notes |
2295
+ | ---- | --- | ----- |
2296
+ | **Recommended: Syncthing** | Share `$MU_SYNC_DIR` on every machine | Continuous, peer-to-peer, no server, no cloud account. Its `*.sync-conflict-*` copies are ingested rather than ignored — they are still valid op logs, and dedupe makes reading them free. |
2297
+ | `rsync` in a loop or cron | `rsync -av host:$MU_SYNC_DIR/ $MU_SYNC_DIR/` | Fine. Run it in both directions, or one way from each box. |
2298
+ | sshfs / NFS mount of the FOLDER | Point `MU_SYNC_DIR` at the mount | OK for segments. **Never** for `MU_DB_PATH`. |
2299
+ | Fully manual (`scp`, USB stick) | Copy the `.jsonl` files whenever | Still converges, just less often. |
2300
+
2301
+ Manual copying is a first-class tier, not a fallback:
2302
+
2303
+ 1. **Direction-free.** No source-vs-target decision. Copy either way,
2304
+ or both ways. You converge.
2305
+ 2. **Idempotent.** Copying the same file ten times equals copying it
2306
+ once, so re-copy freely when unsure.
2307
+ 3. **Interruption-safe.** A killed `scp` leaves a truncated last line
2308
+ that the parser skips; the next copy completes it.
2309
+
2310
+ ### Two things not to do
2311
+
2312
+ **Never put `MU_DB_PATH` inside `MU_SYNC_DIR`.** THE footgun of the
2313
+ design. `mu doctor` reports it, with the full remediation paragraph:
2314
+
2315
+ ```console
2316
+ $ mu doctor
2317
+ fleet
2318
+ db-vs-sync : FAIL DB is INSIDE MU_SYNC_DIR — this WILL corrupt it (/tmp/mu-sync-demo/mu.db)
2319
+ ```
2320
+
2321
+ A live WAL-mode SQLite database is three files (`mu.db`, `-wal`,
2322
+ `-shm`) whose mutual consistency *is* its durability. A file-syncer
2323
+ copies them whole-file and out of order, and will resurrect a peer's
2324
+ stale `-wal` — yielding a database that opens fine and is silently
2325
+ corrupt. Two machines writing the same synced file is worse:
2326
+ last-writer-wins on the whole FILE, so one machine's entire history
2327
+ disappears. Keep the DB on local disk; only the regenerable segments
2328
+ travel.
2329
+
2330
+ **Avoid iCloud Drive and Dropbox for `MU_SYNC_DIR` on macOS.** Both do
2331
+ *dataless-placeholder eviction*: an untouched file becomes a stub, and
2332
+ the `stat()` that materialises it blocks on the network. mu stats the
2333
+ sync dir at the top of *every* command, so `mu task add` becomes a
2334
+ multi-second hang — or a failure when offline. Syncthing keeps real
2335
+ bytes on disk. (Google Drive File Stream and OneDrive Files On-Demand
2336
+ have the same problem.)
2337
+
2338
+ ### What does and does not travel
2339
+
2340
+ Only **portable** state syncs: workstreams, tasks, edges, notes. Ops
2341
+ about **agents** and **workspaces** are recorded locally — `mu log`
2342
+ still shows them — but never leave the machine, because a `pane_id`
2343
+ like `%17` and a path like `/home/me/...` are meaningless (and often
2344
+ actively wrong) on another box.
2345
+
2346
+ One consequence: **task ownership does not sync.**
2347
+ `tasks.owner_id` points into the machine-local `agents` table, so a
2348
+ task claimed by `worker-2` on the devserver shows as unowned on your
2349
+ laptop. That is correct — `worker-2` is a tmux pane that does not exist
2350
+ there.
2351
+
2352
+ ### Concurrent editing
2353
+
2354
+ Edit one workstream on two machines at once. Ops are semantic partial
2355
+ updates merged by **per-field last-writer-wins**, so a devserver crew
2356
+ closing a task while you re-prioritise it on the laptop keeps *both*
2357
+ edits:
2358
+
2359
+ ```bash
2360
+ # laptop # devserver
2361
+ mu task update t1 --impact 95 -w app mu task close t1 -w app
2362
+ # after both sync: impact=95 AND status=CLOSED, on both machines
2363
+ ```
2364
+
2365
+ Only the same *field* of the same row edited on two machines needs a
2366
+ winner, and the newer HLC takes it.
2367
+
2368
+ ---
2369
+
2370
+ ## 15.7 Upgrading a v7, v8, or v9 DB
2371
+
2372
+ `mu` refuses to write a pre-v10 DB and leaves it untouched. Use the
2373
+ single retained sidecar against a backup:
2374
+
2375
+ ```bash
2376
+ DB=${MU_DB_PATH:-$HOME/.local/state/mu/mu.db}
2377
+ BACKUP="$HOME/mu-old-backup-$(date +%Y%m%d-%H%M%S).db"
2378
+ sqlite3 "$DB" ".backup '$BACKUP'"
2379
+ npx tsx scripts/migrate.ts "$BACKUP" --out "${DB}.v10"
2380
+ MU_DB_PATH="${DB}.v10" mu doctor --deep
2381
+ mv "$DB" "${DB}.old-kept" && mv "${DB}.v10" "$DB"
2382
+ mu doctor
2383
+ ```
2384
+
2385
+ The script auto-detects v7, v8, or v9, opens it read-only, compares its
2386
+ SHA-256 before and after, and never overwrites a target unless `--force`
2387
+ is explicit. v9 history is retained unchanged; legacy statuses normalize
2388
+ only while projecting into v10, with one durable migration note per
2389
+ currently affected task. Valid v9 agents, workspaces, owners, peer
2390
+ watermarks, and machine identity carry across, but pane ids and absolute
2391
+ workspace paths cannot be proven live until `mu doctor` reconciles them.
2392
+ The v7/v8 path keeps the older conservative omissions for agents and
2393
+ workspaces, and restores pre-1.0 `archived_*` rows as live workstreams
2394
+ by default (`--drop-archives` to skip).
2395
+
2396
+ **Full recipe, every flag, and the precise carry/omit rules:
2397
+ [scripts/README.md](../scripts/README.md).**
2398
+
2399
+ ---
2400
+
2401
+ ## 16. One-shot demo script
2402
+
2403
+ End-to-end against a throwaway DB, so your real registry is untouched.
2404
+
2405
+ ```bash
2406
+ export MU_DB_PATH=/tmp/mu-demo.db
2407
+ tmux kill-session -t mu-demo 2>/dev/null
2408
+
2409
+ # Plan
2410
+ mu workstream init demo
2411
+ mu task add design --title "Design" -w demo --impact 80 --effort-days 2
2412
+ mu task add build --title "Build" -w demo --impact 80 --effort-days 5 --blocked-by design
2413
+ mu task add ship --title "Ship" -w demo --impact 90 --effort-days 1 --blocked-by build
2414
+
2415
+ # Crew
2416
+ mu agent spawn worker-1 --workstream demo --cli sh
2417
+ mu agent spawn worker-2 --workstream demo --cli sh
2418
+
2419
+ # Assign + observe
2420
+ mu task claim design -w demo --for worker-1 --evidence "demo assignment"
2421
+ mu state -w demo
2422
+
2423
+ # Watch live (Ctrl+b d to detach)
2424
+ tmux attach -t mu-demo
2425
+
2426
+ # Cleanup
2427
+ mu workstream teardown --workstream demo --yes
2428
+ rm -f /tmp/mu-demo.db
2429
+ ```
2430
+
2431
+ ---
2432
+
2433
+ ## Mental model in three sentences
2434
+
2435
+ 1. **One workstream is one tmux session full of agent panes.** Mu
2436
+ manages the lifecycle; tmux is the substrate. Workstreams on the
2437
+ same machine are isolated by `session_id` in the SQLite registry.
2438
+
2439
+ 2. **The task DAG decides what can be worked on.** The `Ready` table +
2440
+ parallel-tracks union-find answer "what's next?" and "what can I
2441
+ parallelize?" deterministically. Diamond patterns (two goals sharing
2442
+ a prerequisite) collapse into one merged track so two agents never
2443
+ collide on shared deps.
2444
+
2445
+ 3. **Agents claim tasks via their pane title — zero config.**
2446
+ `mu task claim foo` from inside `worker-1`'s pane sets the task's
2447
+ `owner_id` to the `worker-1` agent row atomically. mu reads the pane
2448
+ title via `tmux display-message -t $TMUX_PANE -p '#{pane_title}'`,
2449
+ set on spawn. Two agents cannot claim the same task.
2450
+
2451
+ Everything else (`mu sql`, send/read, the bracketed-paste protocol,
2452
+ ghost reconciliation) is plumbing in service of those three.
2453
+
2454
+ ---
2455
+
2456
+ ## What's NOT in mu (and how to work around it)
2457
+
2458
+ The full roadmap with promotion criteria lives in
2459
+ [ROADMAP.md](ROADMAP.md). The short list of gaps you might hit
2460
+ in real use:
2461
+
2462
+ | Want | Workaround | Status |
2463
+ | --------------------------------------------- | ----------------------------------------------------------------------- | ------------- |
2464
+ | Multi-CLI status detection (per-CLI prompts) | Braille spinner fallback covers pi/pi-meta + every TUI wrapper using standard spinner glyphs. Per-CLI permission-prompt patterns are pi-only. | partially shipped |
2465
+ | Pi extension (typed tools, HUD, wakeups) | `mu state --tui` (interactive) covers the dashboard use-case; plain `mu state` (static) is the `watch` / `tmux display-popup` / `status-right` substrate. Other extension tools deferred. | partially shipped |
2466
+ | Markdown agent-definition discovery | Spawn accepts `--cli` and `--command` directly; no template registry | dropped |
2467
+ <!-- doc-cli-drift:skip-start -->
2468
+ | `mu run script.ts` (JS DSL) | Use `--json` + bash + jq | rejected |
2469
+ | Sync to GitHub Issues / Linear / Asana | Not in scope; explicitly rejected | — |
2470
+ | ~~`mu task blocked`~~ (removed; the `blocked` SQL view is the abstraction) | `mu sql "SELECT b.local_id, b.status, b.title FROM blocked b JOIN workstreams w ON w.id=b.workstream_id WHERE w.name='X'"` | removed-with-recipe |
2471
+ | ~~`mu task goals`~~ (removed; same shape as `blocked` — view is the abstraction) | `mu sql "SELECT g.local_id, g.status, g.title FROM goals g JOIN workstreams w ON w.id=g.workstream_id WHERE w.name='X'"` | removed-with-recipe |
2472
+ | ~~`mu task search <pat>`~~ (removed; case-insensitive LIKE is one SQL line) | `mu sql "SELECT t.local_id, t.status, t.title FROM tasks t JOIN workstreams w ON w.id=t.workstream_id WHERE w.name='X' AND LOWER(t.title) LIKE '%pat%'"` (add `LEFT JOIN task_notes` for the old `--in-notes`; drop the workstream join/filter for the old `--all`) | removed-with-recipe |
2473
+ <!-- doc-cli-drift:skip-end -->
2474
+
2475
+ Anything in this table that bites you in real use is a candidate
2476
+ for **promotion**. Criteria: proven friction in ≥2 real workflows +
2477
+ fits in <300 LOC + no major refactor of the load-bearing pillars.
2478
+ The most useful feedback is "I tried to do X and had to fall back
2479
+ to `mu sql`, twice in one session". File it in [ROADMAP.md](ROADMAP.md).
2480
+
2481
+ ---
2482
+
2483
+ ## Where to go from here
2484
+
2485
+ | Doc | What's in it |
2486
+ | -------------------------------------------- | ------------------------------------------------------- |
2487
+ | [README.md](../README.md) | Project overview, install, comparison vs `pi-subagents` |
2488
+ | [CHANGELOG.md](../CHANGELOG.md) | Release notes |
2489
+ | [ROADMAP.md](ROADMAP.md) | What's next, with promotion criteria + rejected ideas |
2490
+ | [VOCABULARY.md](VOCABULARY.md) | Canonical terms — source of truth for every word |
2491
+ | [VISION.md](VISION.md) | The eight load-bearing pillars + design principles |
2492
+ | [ARCHITECTURE.md](ARCHITECTURE.md) | Module map, reconciliation algorithm, layered design |
2493
+ | [skills/mu/SKILL.md](../skills/mu/SKILL.md) | What an LLM running inside an agent pane sees |
2494
+
2495
+ If you're trying mu and something doesn't work as documented, file an
2496
+ issue with: the exact `mu` command, the full output (set
2497
+ `MU_DB_PATH=/tmp/mu-debug.db` to isolate from your real registry),
2498
+ your multiplexer version (the `environment` block of `mu doctor`), and
2499
+ your platform.
2500
+
2501
+ ---
2502
+
2503
+ ## 20. Multiplexer backends (tmux and herdr)
2504
+
2505
+ mu drives exactly one multiplexer per invocation. tmux is the
2506
+ incumbent; [herdr](https://github.com/herdrdev/herdr) is the second
2507
+ backend, and spawn, send, read and status detection all work on it. The
2508
+ remaining gaps are narrow and listed under
2509
+ [Known limits on herdr](#known-limits-on-herdr) — the notable one is
2510
+ that `mu agent kick` is Linux-only there.
2511
+
2512
+ ### Which backend am I on?
2513
+
2514
+ ```bash
2515
+ mu doctor # the `environment` block names the active backend
2516
+ mu doctor --json # .environment.mux = { name, ok, version, env, remediation }
2517
+ ```
2518
+
2519
+ `.environment.tmux` is kept in `--json` as an alias reporting the
2520
+ *active* backend, so existing scripts keep working. Read
2521
+ `.environment.mux.name` if you care which one it is.
2522
+
2523
+ ### The detection ladder
2524
+
2525
+ 1. `MU_MUX=<name>` — explicit override, wins over everything. An
2526
+ unknown value fails the invocation (`error: unknown mux backend:
2527
+ nope`, exit 1) rather than quietly running on tmux.
2528
+ 2. `HERDR_ENV=1` → herdr. Compared literally against `1`, as herdr
2529
+ documents.
2530
+ 3. `$TMUX` or `$TMUX_PANE` set → tmux. Either one proves the caller is
2531
+ in a tmux pane; some setups (`sudo -E`, ssh with a restrictive
2532
+ `SendEnv`) pass one and not the other.
2533
+ 4. Availability — whichever binary actually runs, tmux first.
2534
+ 5. `NoMultiplexerError`, exit 5.
2535
+
2536
+ Rung 2 outranks rung 3 because it is the narrower claim: herdr panes
2537
+ routinely host a tmux server, so both signals can be live at once, and
2538
+ only `HERDR_ENV` says "herdr manages *this* pane". Rungs 2–3 answer
2539
+ "which mux is the caller in", rung 4 answers "which mux works here" —
2540
+ mu can create a detached session from a plain shell, so rung 4 alone
2541
+ is enough to operate.
2542
+
2543
+ The backend is resolved once per process and cached.
2544
+
2545
+ ### What differs between the two
2546
+
2547
+ | | tmux | herdr |
2548
+ | --- | --- | --- |
2549
+ | Mux session (holds one workstream) | tmux session `mu-<ws>` | herdr *workspace* labelled `mu-<ws>`. herdr's own "session" is server-level and is NOT the workstream unit. |
2550
+ | Window | tmux window | herdr tab |
2551
+ | Agent | pane | pane |
2552
+ | Pane id | `%15` | `w1:p1` (workspace-qualified, so a pane moved between workspaces gets a new id) |
2553
+ | Pane title | `select-pane -T` | `herdr pane rename` writes the pane *label* |
2554
+ | Attach hint | `tmux a -t mu-<ws>` | `herdr session attach mu-<ws>` |
2555
+ | Pane borders | 4-side border showing agent name + status glyph | no-op — herdr owns its pane chrome; mu-managed panes carry the label instead |
2556
+ | Layout | `select-layout` | no-op — herdr splits are explicit, geometry is yours |
2557
+ | Status detection | scrollback scraping (`src/detect.ts`) | herdr classifies panes natively via `paneStatus()`; the scraper is bypassed |
2558
+ | Focus | mu creates detached | `--no-focus` on every mutating call, always. `detached: false` still gets you a detached workspace; run `herdr workspace focus` yourself. |
2559
+ | Isolation seam | `MU_TMUX_SOCKET` (`-L <name>`) | `MU_HERDR_SESSION` (`--session <name>`, its own socket) |
2560
+ | `mu agent send` / `read` | six-step paste/Enter protocol | one atomic `agent prompt --wait` |
2561
+ | `mu agent spawn` | one `new-window`/`split-window` carrying the command | create-then-start: bare pane, then `agent start` |
2562
+
2563
+ `MU_TMUX_SOCKET` is tmux-only and ignored under herdr;
2564
+ `MU_HERDR_SESSION` is its herdr analogue. Both exist so a test run can
2565
+ never observe or destroy your real panes.
2566
+
2567
+ ### Known limits on herdr
2568
+
2569
+ - **Spawn is two steps, not one.** herdr has no create-and-run form, so
2570
+ mu creates a bare pane and then calls `agent start` in it. The
2571
+ creation verbs refuse a command rather than silently dropping it —
2572
+ dropping would leave an empty shell that mu records as an agent,
2573
+ which is the worst available failure. If step two fails, mu closes
2574
+ the pane and writes no agent row.
2575
+ - **`--lines` cannot recover scrolled-off rows from an
2576
+ alternate-screen pane.** A pane on the alternate screen does not
2577
+ spill into host scrollback, so there is nothing behind the viewport
2578
+ to read.
2579
+ - **`mu agent kick` is Linux-only on herdr.** herdr reports a shell
2580
+ pid, not a tty, so `paneTTY` resolves `/proc/<pid>/fd/0`. On macOS
2581
+ that path does not exist and the call fails with a `HerdrError`
2582
+ naming the limitation rather than lying about the tty.
2583
+ - **`herdr pane list` has no foreground-command field**, so a pane's
2584
+ command reads as empty from a listing. The authoritative answer
2585
+ costs one `herdr pane process-info` round trip per pane. mu does not
2586
+ fake it.
2587
+ - **`MU_<UPPER_CLI>_COMMAND` has no herdr equivalent.** herdr resolves
2588
+ the agent binary itself by kind. The override is honoured on tmux
2589
+ only; on herdr it stays moot while spawn is unimplemented, and the
2590
+ spawn work has to either pass it through or refuse it explicitly.
2591
+
2592
+ ### A degraded backend reports, it does not crash
2593
+
2594
+ With no herdr server running, `mu doctor` still prints a full report
2595
+ (exit 0) and any verb that genuinely needs the mux fails with exit 5
2596
+ and herdr's own message plus remediation steps:
2597
+
2598
+ ```bash
2599
+ MU_MUX=herdr mu doctor # exit 0; `herdr: ok (0.9.0)` from the client
2600
+ MU_MUX=herdr mu agent list -w foo # exit 5: no herdr server is running at ...
2601
+ MU_MUX=herdr mu task claim t1 -w foo --self # exit 0 — identity is best-effort
2602
+ ```
2603
+
2604
+ That last line is the load-bearing / best-effort split. Verbs that ARE
2605
+ the mux (spawn, send, kill, reconcile, session create/destroy) fail
2606
+ loudly. Verbs where the mux is decoration (identity fallback, pane
2607
+ titles, banners, `mu workstream list`) degrade and carry on. Reconcile
2608
+ is pointedly in the first group: treating an unreachable mux as "zero
2609
+ panes" would prune every agent as a ghost.
2610
+
2611
+ One error is deliberately outside that scheme. herdr returns argument
2612
+ errors with exit 2, which mu raises as `HerdrSyntaxError` — not a
2613
+ `MuxError`. That is CLI drift after a herdr upgrade, i.e. a bug in mu,
2614
+ and bucketing it as "herdr is down" would send you chasing a healthy
2615
+ server.