@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,997 @@
1
+ # Architecture
2
+
3
+ mu is one SQLite file, a crew of agents in multiplexer panes, a task
4
+ DAG, and one append-only op log everything else is derived from. It is
5
+ layered: callers on top, a shared TypeScript core in the middle,
6
+ SQLite + mux + VCS substrates at the base. The CLI verbs and the
7
+ programmatic SDK are thin facades over the same core modules.
8
+
9
+ - For canonical terms (*workstream*, *agent*, *task DAG*, *track*,
10
+ *claim*, *free*, *workspace*, *substrate*, ...) see
11
+ [VOCABULARY.md](VOCABULARY.md). It is the source of truth.
12
+ - For design rationale, rejected alternatives, and what's on the
13
+ roadmap, see [ROADMAP.md](ROADMAP.md).
14
+ - For principles, see [VISION.md](VISION.md).
15
+
16
+ ```
17
+ ┌─────────────────────────────────────────────────────────────────┐
18
+ │ Callers │
19
+ │ ┌──────────┐ ┌──────────┐ ┌──────────────┐ ┌─────────────┐ │
20
+ │ │ Pi │ │ Bash + │ │ Pi sub- │ │ mu log │ │
21
+ │ │ shell │ │ jq │ │ agent │ │ --tail subs │ │
22
+ │ └────┬─────┘ └────┬─────┘ └──────┬───────┘ └──────┬──────┘ │
23
+ │ │ │ │ │ │
24
+ └───────┼─────────────┼───────────────┼─────────────────┼─────────┘
25
+ │ in-proc │ subprocess │ subprocess │ in-proc
26
+ ▼ ▼ ▼ ▼
27
+ ┌─────────────────────────────────────────────────────────────────┐
28
+ │ mu core (shared TS modules) │
29
+ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌─────────────────┐ │
30
+ │ │ agents/ │ │ tasks/ │ │ vcs/ │ │ ops log/ │ │
31
+ │ │ mux/ │ │ schema │ │ jj │ │ capture │ │
32
+ │ │ tmux │ │ queries │ │ sapling │ │ apply/sync │ │
33
+ │ │ herdr │ │ tracks │ │ git │ │ doctor │ │
34
+ │ │ detect │ │ claim │ │ none │ │ │ │
35
+ │ │ state │ │ │ │ │ │ │ │
36
+ │ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────────┬────────┘ │
37
+ └───────┼─────────────┼─────────────┼─────────────────┼───────────┘
38
+ ▼ ▼ ▼ ▼
39
+ ┌─────────────────────────────────────────────────────────────────┐
40
+ │ Substrates │
41
+ │ SQLite (~/.local/state/mu/mu.db) · tmux/herdr panes · jj/sl/git│
42
+ └─────────────────────────────────────────────────────────────────┘
43
+ ```
44
+
45
+ ## The ops log (read this first)
46
+
47
+ Everything below rests on one append-only table. Read this section
48
+ before the rest of the file.
49
+
50
+ **Capture is a trigger, not a call site.** Every INSERT / UPDATE /
51
+ DELETE on a portable table (`workstreams`, `tasks`, `task_edges`,
52
+ `task_notes`) is recorded as an **op** by a SQLite trigger, in the
53
+ SAME transaction as the mutation. No SDK function decides to record
54
+ history, so no call site can forget to, and the log cannot drift from
55
+ the data — not even on power loss.
56
+
57
+ **The log is the record; the tables are the materialized view.**
58
+ Reads hit the tables, as ordinary indexed SQL. This is not
59
+ event-sourcing-on-read: nothing replays the log to answer a query.
60
+ The log is what the tables are *derived from* and what they can be
61
+ rebuilt from.
62
+
63
+ ```
64
+ mu task close t3
65
+ │
66
+ ▼
67
+ UPDATE tasks SET status=... ──┬──► tables (what reads see)
68
+ └──► ops (what everything else reads)
69
+ one transaction
70
+ ```
71
+
72
+ **Four features are queries or replays over that one log:**
73
+
74
+ - **history** — `mu log` is a typed reader over `ops`.
75
+ - **undo** — `mu undo <group>` emits the inverse ops for one group.
76
+ - **sync** — a machine appends its own ops to a JSONL segment in a
77
+ shared folder and applies each peer's from a watermark.
78
+
79
+ **Ops are semantic partial updates.** An UPDATE op carries only the
80
+ columns that actually changed. That is what makes per-field merge
81
+ free: two machines editing different fields of one task both keep
82
+ their edit, with no extra bookkeeping. A full-row payload would
83
+ silently regress this to row-level last-writer-wins.
84
+
85
+ **The cost, plainly:** one mechanism means one capture bug breaks
86
+ history, undo and sync at once, silently. That is why
87
+ `mu doctor --deep` rebuilds the log into a temp DB and diffs it
88
+ field-by-field against the live tables, and why the cheap tier
89
+ (every live row has at least one op naming it) runs by default.
90
+
91
+ Ordering across machines comes from the **HLC** on every op — a
92
+ hybrid logical clock serialized so that bytewise `ORDER BY hlc` is
93
+ causal order. Machine-local tables (`agents`, `vcs_workspaces`) have
94
+ no capture triggers: their contents are pane ids and absolute paths,
95
+ which mean nothing on another machine. Their changes are recorded as
96
+ log-only events via `emitEvent`.
97
+
98
+ Per-module detail is in [§ Modules](#modules-actual-src-layout).
99
+
100
+ ---
101
+
102
+ ## The task DAG
103
+
104
+ mu's coordination model is a **directed acyclic graph of tasks**. It
105
+ is the central organizing primitive, not a sidecar feature: without
106
+ it mu is just an agent runner.
107
+
108
+ ### Model
109
+
110
+ - **Tasks** are nodes with mandatory `impact (1-100)` and `effort_days`.
111
+ `ROI = impact / effort` drives prioritization.
112
+ - **One edge type**: `blocks`. `A → B` means A must close before B can
113
+ start. Multiple edge types create ambiguity that defeats the purpose.
114
+ - **Status lifecycle**: `OPEN → IN_PROGRESS → CLOSED`. Postponed or
115
+ won't-do rationale belongs in notes; `CLOSED` alone satisfies blockers.
116
+ - **Notes** are append-only per task; survive across LLM sessions and
117
+ agent restarts. The fix for context loss at the *task* level rather
118
+ than the agent level.
119
+
120
+ ### Built-in queries (SQL views)
121
+
122
+ | View | Returns |
123
+ | --------- | ---------------------------------------------------------------------- |
124
+ | `ready` | OPEN tasks with no unresolved blockers — work that can start *now* |
125
+ | `blocked` | OPEN tasks waiting on something |
126
+ | `goals` | Tasks with no dependents — graph endpoints |
127
+
128
+ Agents and humans both query these views directly via `mu sql`. No
129
+ separate query layer.
130
+
131
+ ### Parallel-track detection
132
+
133
+ The Tracks section in `mu state` / bare `mu` runs union-find on the
134
+ graph to identify independent subtrees that can be assigned to
135
+ different agents in parallel.
136
+
137
+ **Diamond patterns get merged automatically.** If two roots share a
138
+ prerequisite, they collapse into one track — preventing two agents
139
+ from colliding on the shared dependency:
140
+
141
+ ```
142
+ Independent (2 tracks): Diamond (1 merged track):
143
+
144
+ goal_a goal_b goal_a goal_b ← Spawn 2 agents
145
+ | | \ /
146
+ task_a task_b shared ← Spawn 1 (would
147
+ | | | collide otherwise)
148
+ leaf_a leaf_b leaf
149
+ ```
150
+
151
+ The graph algorithm decides, not the LLM.
152
+
153
+ ### Claim protocol via ambient identity
154
+
155
+ `mu task claim <task>` resolves who is claiming, then atomically:
156
+
157
+ 1. Sets `tasks.owner = <agent_name>`
158
+ 2. Flips `tasks.status = IN_PROGRESS`
159
+ 3. Emits a `task.claim` op carrying the resolved `actor`
160
+
161
+ Identity resolution is a two-rung ladder:
162
+
163
+ 1. **`$MU_AGENT_NAME`** — injected into the pane's environment at
164
+ spawn. Backend-independent, and more reliable than scraping even on
165
+ tmux.
166
+ 2. **`backend.currentAgentName()`** — the mux backend's fallback. On
167
+ tmux that is `display-message -p '#{pane_title}'`; on herdr the
168
+ agent name is registered with the mux and looked up by pane id.
169
+
170
+ The fallback earns its place because **adopted** panes
171
+ (`mu agent adopt`) predate the env injection and carry only a title.
172
+ Because it lives behind `MuxBackend`, the call site has no idea which
173
+ multiplexer it is running under.
174
+
175
+ When the tmux fallback runs, it reads pane title, **not** `#W` (window
176
+ name). Window names come from the `tab:` frontmatter and may group
177
+ multiple agents in one window.
178
+
179
+ Two agents can't claim the same task — atomic CAS in SQLite. The
180
+ agent doesn't have to know its own name.
181
+
182
+ ### Scoped subtree views
183
+
184
+ `mu task tree <id>` and task queries show the portion of the graph
185
+ reachable from a task. Subtree scoping is a `WHERE` clause, which is
186
+ what makes recursive delegation work: a sub-orchestrator inspects its
187
+ slice without an LLM inferring the scope.
188
+
189
+ ---
190
+
191
+ ## Mux session topology
192
+
193
+ mu organizes agents into **one mux session per workstream**. One mu
194
+ workstream = one mux session = one `session_id` partition in
195
+ `~/.local/state/mu/mu.db`. Multiple workstreams on one machine coexist as
196
+ independent mux sessions, fully isolated.
197
+
198
+ A **mux session** is a tmux session on the tmux backend and a herdr
199
+ *workspace* on the herdr backend (herdr's own "session" is
200
+ server-level — one socket — and is the wrong granularity). The
201
+ three-level shape is identical either way:
202
+
203
+ | mu term | tmux | herdr |
204
+ | ---------------- | ------------ | ----------------- |
205
+ | **mux session** | session | workspace |
206
+ | **window** | window | tab |
207
+ | **pane** | pane (`%15`) | pane (`w1:p1`) |
208
+
209
+ The diagram below uses the tmux spelling.
210
+
211
+ ```
212
+ tmux session: mu-auth-refactor (one mu workstream)
213
+ ┌───────────────────────────────────────────────────────────┐
214
+ │ Window: Backend Window: Review │
215
+ │ ┌──────────┐ ┌──────────┐ ┌────────────────────────┐ │
216
+ │ │ worker-1 │ │ worker-2 │ │ reviewer-1 │ │
217
+ │ │ (pi) │ │ (pi) │ │ (pi, role=read-only) │ │
218
+ │ └──────────┘ └──────────┘ └────────────────────────┘ │
219
+ │ │
220
+ │ Window: mu-orchestrator │
221
+ │ ┌────────────────────────────────────────────────────┐ │
222
+ │ │ pi (you, with mu extension loaded) │ │
223
+ │ └────────────────────────────────────────────────────┘ │
224
+ └───────────────────────────────────────────────────────────┘
225
+
226
+ tmux session: mu-migration-2024q4 (different workstream)
227
+ ┌───────────────────────────────────────────────────────────┐
228
+ │ ...different agents, different graph, no overlap │
229
+ └───────────────────────────────────────────────────────────┘
230
+ ```
231
+
232
+ ### Concretely
233
+
234
+ - **First `mu agent spawn` creates the tmux session** if you're not already
235
+ in one. Default name `mu-<auto>`. Override with `mu workstream init <name>` or
236
+ `MU_SESSION=<name>`.
237
+ - **Subsequent operations** in the same shell (or any child shell with
238
+ `MU_SESSION_ID` set) target the same session.
239
+ - **`tmux attach -t mu-<workstream>`** → attach to the whole
240
+ workstream's mux session (herdr: `herdr workspace focus <id>`)
241
+ - **`mu agent list`** is scoped to one workstream — the current one by
242
+ default; `mu agent list -w <workstream>` for another
243
+ - **`session_id`** is the partition key on the `agents` table
244
+ - **`mu doctor`** warns about cross-session pollution (orphan panes,
245
+ ghost rows, agents whose mux session no longer exists)
246
+
247
+ ### The `activeMux()` seam
248
+
249
+ Every call site reaches its multiplexer through
250
+ `(await activeMux()).<method>()`. Nothing outside `src/mux/` names a
251
+ backend, and `MU_MUX` is therefore load-bearing: an unknown value
252
+ fails the invocation rather than quietly running on tmux.
253
+
254
+ Call sites are classified, and the classification is the seam's real
255
+ content. With a second backend in play, "no reachable multiplexer"
256
+ stops being a broken-box edge case and becomes routine, so each site
257
+ has to have already decided what it means:
258
+
259
+ | | Behaviour on `NoMultiplexerError` | Examples |
260
+ | --- | --- | --- |
261
+ | **Load-bearing** | propagate; `handle()` maps it to exit 5 | spawn, send, read, kill, adopt, kick, reconcile, session create/destroy |
262
+ | **Best-effort** | `try`/`catch`, degrade | actor identity, pane titles, pane borders, workstream listings, liveness polls, TUI attach |
263
+
264
+ `resolveWorkerIdentity()` in `src/tasks/claim.ts` is the canonical
265
+ best-effort shape. `reconcile()` is pointedly load-bearing: treating
266
+ an unreachable mux as "zero panes exist" would prune every registered
267
+ agent as a ghost and reap its in-progress tasks.
268
+
269
+ Three things that look like caller concerns belong to the backend,
270
+ because each would otherwise hardcode a tmux string in a place a herdr
271
+ user can see: `attachHint()` / `attachCommands()` (the printed recipe
272
+ and the TUI's executed argv), `healthCheck()` (version + ambient env
273
+ facts as DATA — `mu doctor` owns rendering), and
274
+ `paneNotFoundNextSteps()` (borrowed by `PaneNotFoundError` from the
275
+ backend that raised it).
276
+
277
+ `src/tmux.ts` survives as a re-export for genuinely tmux-only
278
+ concerns: the `MU_TMUX_SOCKET` test-isolation seam and the shared
279
+ `sleep` / `setSleepForTests` poll seam.
280
+
281
+ ### The spawn seam: create-and-run vs create-then-start
282
+
283
+ Backends disagree on something structural: tmux creates a pane **and**
284
+ runs a command in one atomic call, while herdr has no create-and-run
285
+ form at all. Its creation verbs always start a plain shell, and `agent
286
+ start` requires an already-existing pane at its interactive prompt.
287
+
288
+ That difference is expressed as a **capability**, not a name check:
289
+
290
+ | | tmux | herdr |
291
+ | --- | --- | --- |
292
+ | `NewWindowOptions.command` etc. | carries the command | **refused** if non-empty |
293
+ | `startAgentInPane()` | not implemented | implemented |
294
+ | liveness / readiness wait | mu polls scrollback | the mux blocks until ready |
295
+
296
+ `spawnAgent` branches on `mux.startAgentInPane !== undefined`. When it
297
+ is absent (tmux) the command rides along on the creation verb and the
298
+ path is exactly what it always was. When present, mu creates the pane
299
+ bare, then calls `startAgentInPane` — and **skips**
300
+ `awaitSpawnLiveness` / `awaitSpawnReadiness`, because such a backend
301
+ returns only once it has itself detected the agent and judged it ready
302
+ for input, which is strictly stronger than what scrollback polling can
303
+ prove. `MU_SPAWN_LIVENESS_MS` / `MU_SPAWN_READINESS_MS` are therefore
304
+ tmux-tier knobs.
305
+
306
+ The creation verbs **refuse** a non-empty command on a backend that
307
+ cannot honour it rather than dropping it silently: a dropped command
308
+ leaves an empty shell mu believes hosts an agent, which is the worst
309
+ available failure mode. Both the refusal and every step-2 failure route
310
+ through `rollbackSpawn`, so no path records an agent row for a pane with
311
+ nothing running in it.
312
+
313
+ Both the pane-creation call and the agent start sit **outside** the
314
+ per-session spawn lock's slow half, so a parallel fan-out still
315
+ parallelises.
316
+
317
+ ### Window vs pane
318
+
319
+ By default each agent gets its own **window** (a tmux window, a herdr
320
+ tab — what most terminals call a "tab"), named after the agent's
321
+ `tab:` value; default, the agent name. Agents sharing a `tab:` value
322
+ share a window with multiple panes.
323
+
324
+ Claim/identity depends on the agent's name, not the window name:
325
+ every agent pane gets `$MU_AGENT_NAME` in its environment on spawn,
326
+ plus a **pane title** as fallback, regardless of how panes are grouped.
327
+ The title carries durable mu context only (agent identity plus owned tasks),
328
+ not sampled runtime status. Mu enables the top border but leaves
329
+ `pane-border-format` to the user's tmux configuration. The canonical tmux
330
+ protocol is in the comment block at the top of `src/mux/tmux.ts`.
331
+
332
+ ### Why one session per workstream
333
+
334
+ - **Visual co-location.** `tmux a -t mu-auth-refactor` shows the whole
335
+ crew at once.
336
+ - **Isolation.** Kill the tmux session = kill the workstream. No
337
+ leaked panes.
338
+ - **Detach and reattach freely.** The crew survives a closed laptop.
339
+ - **The claim protocol falls out.** Pane title = agent name =
340
+ ownership identity, with no configuration.
341
+ - **Multiple workstreams coexist.** `session_id` partitioning keeps
342
+ the auth-refactor crew out of the migration crew.
343
+
344
+ ---
345
+
346
+ ## Dual-audience CLI contract
347
+
348
+ The top-level `mu` binary serves two audiences without creating a
349
+ second namespace.
350
+
351
+ - **Human entrypoint:** bare `mu` launches the read-only TUI when
352
+ `process.stdout.isTTY === true`. It loads every workstream on the
353
+ machine and chooses the initial active tab with the shared focus
354
+ ladder (`$MU_SESSION` → tmux session name → cwd inside a workspace
355
+ → cwd equal to a workspace's VCS-derived project root, with latest
356
+ activity breaking project-root ties → tab 0). If no
357
+ workstreams exist, it prints `mu --help` plus the one-paste
358
+ `Get started: mu workstream init <name>` hint and exits 0.
359
+ - **Agent / script entrypoint:** typed verbs remain the API, with
360
+ `--json` on reads and structured errors. Bare `mu` on non-TTY
361
+ stdout (pipes, redirects, CI, most harnessed agent calls) prints
362
+ help instead of entering Ink. `MU_NO_TUI=1` forces that same path
363
+ for scripted use inside an otherwise-interactive terminal.
364
+ - **`mu state`** is the static state card; `mu state --tui` is the
365
+ explicit TUI selector. The split is stdout-is-TTY plus the opt-out
366
+ env var, not a second command namespace.
367
+
368
+ The TUI import stays dynamic (`await import("./cli/tui/index.js")`).
369
+ No module outside `src/cli/tui/` may statically import ink/react, or
370
+ the static CLI bundle pulls the TUI graph into help/version/json
371
+ paths.
372
+
373
+ ---
374
+
375
+ ## TUI architecture
376
+
377
+ The TUI is a 10-card live-updating dashboard on `ink`. It is
378
+ **read-only** and lives entirely under `src/cli/tui/` — CLI verbs
379
+ remain the canonical mutation API. The TUI yanks `mu` commands; the
380
+ operator runs them.
381
+
382
+ ### Cluster shape
383
+
384
+ `src/cli/tui/` is the only place ink/react are imported.
385
+
386
+ ```
387
+ src/cli/tui/
388
+ ├── index.ts # runTui entrypoint; alt-screen + mouse-mode lifecycle
389
+ ├── escapes.ts # pure ANSI byte sequences (alt-screen, SGR mouse mode)
390
+ ├── app.tsx # <App> root: popup state machine, global keymap, tabs
391
+ ├── state.ts # useDashboardSnapshot poll-loop hook (fast/slow tier split)
392
+ ├── keys.ts # pure dispatchGlobalKey + dispatchPopupKey + shouldSwallowGlobalKey
393
+ ├── keymap-spec.ts # canonical keymap source-of-truth (drives help overlay + dispatch)
394
+ ├── mouse.ts # vendored SGR mouse parser + double-click + useMouse hook
395
+ ├── yank.ts # clipboard probe + write (pbcopy/wl-copy/xclip/xsel/clip.exe + OSC-52)
396
+ ├── tuicr.ts # `t` shortcut: alt-screen handoff to tuicr -r <sha>
397
+ ├── layout.ts # responsive multi-column dashboard + per-card row budgets
398
+ ├── columns.ts # column-aligned row layout with protect/clip clipping
399
+ ├── wrap-ansi.ts # ANSI-aware visual-width line wrapper + SGR close-on-end
400
+ ├── format-helpers.ts # shared TUI formatters (relTime, sinceClaim, ROI)
401
+ ├── titled-box.tsx # rounded border with section-header / bottomLabel inset
402
+ ├── popup-shell.tsx # popup outer chrome (cyan TitledBox)
403
+ ├── list-row.tsx # centralised non-selected row primitive
404
+ ├── padded-rows.tsx # per-card body padder
405
+ ├── status-bar.tsx # bottom status bar (mode + active ws + tick + footer flash)
406
+ ├── tab-strip.tsx # multi-workstream tab switcher (N≥2)
407
+ ├── tab-strip-layout.ts # pure window-around-active layout helper
408
+ ├── help.tsx # ?/F1 keymap overlay (scrollable on short panes)
409
+ ├── use-popup-filter.tsx # shared '/' substring filter hook + applyFilter + FilterPrompt
410
+ ├── use-status-filter.tsx # task-status toggles (o/i/c) for task-list popups
411
+ ├── use-notes-drill.ts # shared notes-drill memo (5 task popups consume it)
412
+ ├── use-popup-action-queue.ts # consume mouse PopupAction queue once per render
413
+ ├── cards/ # 10 dashboard glance cards (one slot each)
414
+ │ ├── _placeholder.tsx # shared loading/empty body wrapper
415
+ │ └── {agents,tracks,ready,log,workspaces,inprogress,blocked,recent,commits,doctor}.tsx
416
+ └── popups/ # fullscreen drill-down popups
417
+ ├── {agents,tracks,ready,log,workspaces,inprogress,blocked,recent,commits,doctor}.tsx
418
+ ├── dag.tsx # keybind-only on `g`: full task DAG forest
419
+ ├── all-tasks.tsx # keybind-only on `t`: sortable / filterable list of every task
420
+ ├── task-list-popup.tsx # shared TaskListPopup scaffold (ready/inprogress/recent/blocked config-only)
421
+ ├── drill.tsx # DrillScrollView + useDrillKeymap (shared scrollable-text leaf)
422
+ ├── task-detail.tsx # TaskDetailDrill (notes timeline; the recursion sink)
423
+ ├── cursor-row.tsx # selected-row primitive (delegated to from list-row)
424
+ ├── scroll.ts # pure applyCursor / applyScroll / clampScrollTop / isNavAction
425
+ ├── viewport.ts # popupViewport + POPUP_CHROME_ROWS + POPUP_VIEWPORT_FLOOR
426
+ └── show-loader.ts # subprocess-preserving show loader (avoids blank-flash mid-refetch)
427
+ ```
428
+
429
+ ### State machine
430
+
431
+ `<App>` is the root. It owns:
432
+
433
+ - **Popup state** — `null` (dashboard) or one of the popup ids.
434
+ Single-popup invariant; `Esc` / `q` returns to dashboard.
435
+ - **Card visibility** — `Record<CardId, boolean>` toggled by `0`-`9`.
436
+ - **Tick rate** — fast tick interval (1s default; adjustable with
437
+ `+` / `-` / `=` / `0`).
438
+ - **Active workstream tab** — index into the launch-time workstream
439
+ set; `Tab` / `Shift-Tab` cycles when N≥2. The fast tick checks that
440
+ each row still exists. A torn-down workstream keeps its stable tab
441
+ position and renders dimmed with strikethrough until the same name is
442
+ recreated. A torn-down single workstream also renders its normally hidden
443
+ tab so the state remains visible.
444
+ - **Footer flash** — transient status-bar message (yank confirm,
445
+ tuicr exit, etc.).
446
+
447
+ Popups own their own local state (cursor, filter query, drill mode,
448
+ local modes like Workspaces' `list` / `commits` / `show`). Popups
449
+ NEVER mutate App-level state — they receive a read-only props bag
450
+ (`snapshot`, `db`, `workstream`, `fastTickNonce`, `slowTickNonce`,
451
+ `yank`, `onClose`, `onModeChange`, `onFilterEditingChange`,
452
+ `onFooter`).
453
+
454
+ ### Polling tiers (fast vs slow)
455
+
456
+ The poll loop in `state.ts` (`useDashboardSnapshot`) splits work
457
+ into two intervals:
458
+
459
+ - **Fast tick** (default 1s, adjustable): SQL-only. `loadWorkstreamSnapshotFast`
460
+ reads tasks, tracks, workspace registry rows, recent events,
461
+ workspace orphans. Cheap (~p50 <1ms).
462
+ - **Slow tick** (10s, hardcoded `SLOW_TICK_MS`): subprocess-backed.
463
+ `loadWorkstreamSnapshotSlow` runs tmux liveness, per-workspace
464
+ dirty status, recent project commits, and the Doctor summary.
465
+ Expensive (~p50 hundreds of ms).
466
+
467
+ The last slow result is merged into every fast render via
468
+ `mergeSnapshotFastSlow`, so cards never flicker through a loading
469
+ state. `r` / `F5` triggers both intervals immediately. A tab switch
470
+ clears the slow cache and eager-fetches, so cards are fresh within
471
+ 1s. The pure `snapshotKey` / `snapshotKeyString` guard returns the
472
+ SAME `data` reference across no-op ticks so React's diffing
473
+ short-circuits.
474
+
475
+ ### Render geometry
476
+
477
+ Responsive layout lives in `layout.ts`:
478
+
479
+ - **Breakpoint-driven columns**: stacked below 120 cols; 2 columns
480
+ at 120; 3 at 180; 4 at 240. Stream cards (Commits, Activity log)
481
+ trail; slot 0 (Commits) trails last.
482
+ - **Per-card row budgets**: each visible card gets a `min` /
483
+ `max` / `chrome` budget; the allocator distributes available
484
+ rows so a noisy list can't crowd siblings. Overflow surfaces as
485
+ `+N more · Shift+N` inset into the card's bottom border.
486
+ - **Cull-on-tight-pane**: when even minimum budgets don't fit,
487
+ cull cards by priority (Doctor → Recent → Workspaces → …) and
488
+ show `+N cards hidden · resize taller` at the bottom. Outer
489
+ height clip is the safety net.
490
+
491
+ Text rendering is ANSI-aware: `wrap-ansi.ts` wraps by visual width
492
+ (`string-width`) and closes open SGR state on both the early-return
493
+ and end-of-loop paths, so coloured fragments without a trailing
494
+ `\x1b[0m` can't bleed into adjacent ink chrome. Drill bodies are
495
+ space-padded to exact box width, or ink's `wrap="truncate"` ANSI
496
+ miscount eats the right-border glyph.
497
+
498
+ ### Read-only invariant + the `tuicr` escape
499
+
500
+ Every popup row exposes one canonical `mu` command via `y`. `yank.ts`
501
+ probes for a clipboard backend (pbcopy / wl-copy / xclip / xsel /
502
+ clip.exe) and falls back to OSC-52 over stderr if none is found.
503
+ The command goes to the clipboard; the operator runs it.
504
+
505
+ The one escape is `t` inside any `git show` drill: `tuicr.ts` writes
506
+ `ALT_SCREEN_EXIT` + the mouse-mode disable bytes, exec's
507
+ `tuicr -r <sha>` in the project root / workspace cwd as a foreground
508
+ subprocess, then restores both on exit. A handoff, not an in-process
509
+ mutation.
510
+
511
+ The read-only pledge is in `docs/ROADMAP.md`'s anti-feature list; a
512
+ TUI gesture that wants to mutate state needs a roadmap entry first.
513
+
514
+ ### Mouse + keyboard
515
+
516
+ Mouse support is opt-in via SGR mouse mode (`escapes.ts` provides
517
+ the enable/disable bytes). `mouse.ts` parses `ESC[<button;x;y;M/m`
518
+ from stdin, detects double-clicks, and exposes a `useMouse()` hook.
519
+
520
+ Keyboard dispatch flows through pure helpers in `keys.ts`:
521
+ `dispatchGlobalKey` (dashboard mode), `dispatchPopupKey` (popup
522
+ mode), and `shouldSwallowGlobalKey` (which keys popups consume
523
+ and do not bubble to the global dispatcher). The keymap source-of-
524
+ truth lives in `keymap-spec.ts` so the help overlay and the
525
+ dispatcher can never drift apart.
526
+
527
+ Double-click on a card emits `{kind: "setCursor", index}` followed
528
+ by `{kind: "drill"}` through `use-popup-action-queue.ts`, which
529
+ consumes one action per render (so the cursor update lands before
530
+ the drill resolves the focused row).
531
+
532
+ ### Drill recursion
533
+
534
+ List popups drill via `Enter` into entity-specific leaves. The
535
+ central primitive is `popups/drill.tsx`'s `DrillScrollView` (a
536
+ scrollable text leaf shared by Workspaces' git-show, Agents'
537
+ scrollback, the Activity log payload drill, and the Doctor
538
+ remediation drill). Task popups drill into
539
+ `popups/task-detail.tsx`'s `TaskDetailDrill` (the notes timeline);
540
+ the Tracks popup chains track → task list → TaskDetailDrill via
541
+ the same leaf.
542
+
543
+ `useDrillKeymap` owns the scroll state, takes an optional `resetKey`
544
+ (identity change resets scroll; a tick-driven body refresh preserves
545
+ it) and an optional `onScrollChange` (the DAG popup's focused-root
546
+ tracking), and shares ANSI-aware wrapped body metadata so the
547
+ scroll-clamp math and the painter can't desync.
548
+
549
+ Subprocess-backed drills (Workspaces git-show, Agents scrollback,
550
+ Commits show) use `popups/show-loader.ts`, which preserves the prior
551
+ body during a refetch — no blank flash on the slow tick.
552
+
553
+ ### Test seam
554
+
555
+ See `test/README.md`. The seam is `test/_ink-render.ts`'s
556
+ `createInkInputStream` + `createInkCaptureStream` + `simulateInput` +
557
+ `latestRenderedFrame`: mount a popup or `<App>` into a CaptureStream,
558
+ drive keystrokes, assert against the visible frame and spy callbacks.
559
+ Source-greps are for narrow structural guards only (App ↔ keys ↔
560
+ layout wiring; slot ↔ keymap glue), never behaviour.
561
+
562
+ ---
563
+
564
+ ## CLI / SDK surface
565
+
566
+ Every user-visible operation is a typed SDK function plus a thin
567
+ Commander wrapper. `src/cli.ts` and the verb-namespace files under
568
+ `src/cli/` are the canonical verb surface — no generated registry, no
569
+ DSL, no separate operation schema. Programmatic callers import the
570
+ same SDK functions from `src/index.ts`; agents and scripts compose
571
+ CLI verbs with `--json`.
572
+
573
+ The boundary rule: external surfaces accept operator-facing names
574
+ (workstream, task id, agent name); internal helpers resolve those to
575
+ surrogate INTEGER ids once and then stay on ids. See
576
+ [§ Surrogate-PK + SDK-boundary discipline](#surrogate-pk--sdk-boundary-discipline).
577
+
578
+ ---
579
+
580
+ ## Reconciliation
581
+
582
+ `mu agent list` always reconciles the registry against tmux reality before
583
+ returning. Three steps, in order:
584
+
585
+ 1. **Prune ghosts.** For each `agents` row, if its `pane_id` no longer
586
+ exists in tmux, delete the row.
587
+ 2. **Detect status from scrollback.** For each surviving agent, capture
588
+ the pane and run the per-CLI detector. Update `agents.status` if
589
+ the detected value differs from the stored one.
590
+ 3. **Surface orphans.** For each tmux pane in the workstream's session
591
+ that has no matching `agents` row but whose pane title looks like
592
+ an agent name, add it to the orphans list. **Do not auto-adopt** —
593
+ `mu agent list` shows orphans under a separate "(orphans)" section and
594
+ the user runs `mu agent adopt %15 [--name X]` to claim them.
595
+
596
+ `src/reconcile.ts` is the only implementation. Key properties:
597
+
598
+ - **Reality wins**: the mux is the source of truth for what panes
599
+ exist. The DB records what we last *observed*. Reconciliation closes
600
+ the gap on every `mu agent list`.
601
+ - **Status detection is backend-dependent**, expressed as the optional
602
+ `MuxBackend.paneStatus?()`. A backend that omits it (tmux) means "ask
603
+ the detector": `src/detect.ts` scrapes scrollback (`busy` /
604
+ `needs_input` / `needs_permission` via a known pi marker, with a
605
+ Braille-spinner fallback for other CLIs). A backend that implements it
606
+ (herdr) classifies panes natively across every agent kind it
607
+ recognises, and mu takes its word — `src/detect.ts` is bypassed
608
+ entirely on that backend. herdr's `working` → `busy`, `blocked` →
609
+ `needs_permission`, `idle` / `done` / `unknown` → `needs_input`.
610
+ `unknown` must never become `free`: herdr documents that it does not
611
+ prove completion, and no detector of either kind may mint `free`.
612
+ - **No silent adoption**: orphans are reported, never claimed.
613
+ - **`mu doctor` calls the same routine** and reports counts.
614
+
615
+ ---
616
+
617
+ ## Modules (actual src/ layout)
618
+
619
+ Mostly-flat `src/`: root `.ts` modules plus cohesive subclusters
620
+ (`src/agents/`, `src/tasks/`, `src/mux/`, and `src/cli/` wrappers with
621
+ their own `src/cli/tasks/` and `src/cli/tui/` sub-clusters). Cluster
622
+ files import from neighbours and root substrate modules, never from
623
+ the hub they're re-exported through. `src/tasks.ts`, `src/vcs.ts`,
624
+ `src/mux.ts` and `src/workspace.ts` are pure re-export hubs, kept so
625
+ external imports keep working; they hold no logic and are not listed
626
+ separately below.
627
+
628
+ | Module | Responsibility |
629
+ | --------------------- | ----------------------------------------------------------------------------------------- |
630
+ | `src/db.ts` | Connection (better-sqlite3, WAL), **schema v10** (10 tables + 3 views), `resolveWorkstreamId`. Installs capture on every writable open. Owns `SYNCED_ENTITIES` / `MACHINE_LOCAL_ENTITIES` / `PORTABLE_TABLES` / `MACHINE_LOCAL_TABLES`. Refuses a pre-v10 DB (exit 4). |
631
+ | `src/hlc.ts` | The **HLC** (VOCABULARY § HLC), serialized as sortable TEXT `<wall_ms:15>.<counter:6>.<machine_id>`. `nextHlc` / `receiveHlc` / `compareHlc` / `parseHlc` / `formatHlc`. Clock state lives in `machine_identity`. |
632
+ | `src/capture.ts` | **Op capture**: builds the triggers that record every write to a portable table as an op in the same transaction. |
633
+ | `src/apply.ts` | **The apply path** — capture's counterpart: given one op, local or from a peer, make the tables reflect it. Also owns `reprojectDeferredOps` ([§ ambient sync hook](#the-ambient-sync-hook)). |
634
+ | `src/undo.ts` + `src/cli/undo.ts` | **Undo as inverse ops**: inverses for one `group_id`, derived from log provenance, refusing a superseded group (exit 4; `--force` overrides). Bare form lists undoable groups (`-n` widens), a prefix previews, `--yes` applies. |
635
+ | `src/project-root.ts` | `detectProjectRoot` — the launch-cwd ladder bare `mu` uses to guess which workstream to focus. Pure filesystem walk; no DB. |
636
+ | `src/rebuild.ts` + `src/cli/rebuild.ts` | **Rebuild** — disaster recovery: `rebuildInto` replays the whole log into a NEW DB file via `applyOp`. The verb renders the report: counts, `--json`, an `mv`-swap `Next:` step, a warning that `agents` / `vcs_workspaces` are not reconstructible. |
637
+ | `src/legacy-ops.ts` | Permanent compatibility classifier for historical log-only intents whose entity looks projectable. Rebuild copies them without projection; segment flush never emits them. |
638
+ | `src/drift.ts` | **Drift detection**, two tiers: `checkDrift` (`mu doctor --deep`) rebuilds into a temp DB and diffs field-by-field; `checkCheapDriftInvariant` (the default) asserts every live row has ≥1 op naming its key. Plus `driftRemediation`. |
639
+ | `src/segments.ts` | **Segments** — the transport. `flushSegment` appends this machine's unflushed ops to `<MU_SYNC_DIR>/<machine_id>.jsonl`; `ingestSegment` reads a peer segment from its watermark into `applyOp`. Peer discovery is implicit: every non-self `*.jsonl`. |
640
+ | `src/sync.ts` + `src/cli/sync.ts` | **The sync seam**: `peerStatuses`, the ambient hook (`ambientIngest` / `ambientFlush` / `ambientSyncPass`), `ingestFromDb`, `repairPeer`. The verb is a peer status report; `--from <path>`, `--repair <peer>` (unique prefix, ambiguity is exit 4). |
641
+ | `src/cli/db.ts` | `mu db backup <file>` — one scp-able file via `VACUUM INTO`. Never overwrites: it is the pre-migration copy `SchemaTooOldError` tells you to take. |
642
+ | `src/file-lock.ts` | Cross-process advisory lock via atomic `fs.mkdir`; `src/agents/spawn-lock.ts` wraps it per tmux session. Flush takes it so two local `mu` processes cannot interleave partial lines. Best-effort: a non-contention failure runs the body unlocked. |
643
+ | `src/fleet-hazards.ts`| **Mixed-fleet hazards** — three environment checks in the default doctor: `MU_DB_PATH` inside `MU_SYNC_DIR` (fail), DB on a network mount (warn), two workstream names differing only by case (warn). All no-op when `MU_SYNC_DIR` is unset. |
644
+ | `src/dormant.ts` | **Dormant workstreams** — the `housekeeping` doctor section: which workstreams are **teardown** candidates. Two buckets with different remediation (`finished` = all closed + idle ≥14d, safe; `abandoned` = idle ≥60d with unclosed tasks, look first), because one merged list would invite sweeping away open work. Emits `FleetHazard` at `ok` severity, so it never makes doctor claim a fault. One indexed `GROUP BY` over `tasks`; idle is DERIVED from `MAX(tasks.updated_at)` rather than a new `workstreams.last_activity` column, which would be a second source of truth that can disagree with the rows it summarises. |
645
+ | `src/disk-recon.ts` | **Disk↔DB reconciliation** — the only module that reads the STATE DIR and compares it to the DB, in both directions: a `vcs_workspaces` row whose path is gone (`ws-rows`), a dir with no row (`ws-dirs`, reusing `listAllOrphanWorkspaces`), plus residue nothing references (`ws-empty` / `db-copies` / `exports` / `locks`). Emits `FleetHazard` so doctor's renderer, `--json` and the TUI card need no new shape. Default tier is `readdir` + `stat` at depth 2 (~1ms); `measureWorkspaceUsage` recurses for bytes and is `--disk` only, because its cost scales with the checkouts. **Report-only by construction** — every finding carries its cleanup command and the module runs none of them. |
646
+ | `src/op-context.ts` | The **op context** seam: `withOpContext(db, {intent, actor, group}, fn)` labels every op in a scope, restored in a `finally`. Nested scopes inherit the group, which puts a cascade under one `mu undo`. `withCaptureSuppressed` is the echo guard. |
647
+ | `src/mux.ts` | **Mux backend hub** — re-exports `src/mux/*`, same shape as `src/vcs.ts`. The public `MuxBackend` surface every call site imports. |
648
+ | `src/mux/*.ts` | **Multiplexer backends**: `types.ts` (the `MuxBackend` interface + `MuxError` / `PaneNotFoundError`), `detect.ts` (`MU_MUX` → `HERDR_ENV` → `$TMUX` → `PATH` ladder + test seam), `tmux.ts`, `herdr.ts`. The backend owns topology, the send protocol, capture, **pane id** validation (tmux `%15` vs herdr `w1:p1`), the identity fallback, and optionally native pane status (`paneStatus?()`) and agent start (`startAgentInPane?()`) — so no global pane-id regex and no per-call-site branching. The send protocol is where the two diverge most: tmux needs a six-step paste/Enter dance to survive a modal swallowing the Enter, while herdr's `agent prompt --wait` is one atomic call. |
649
+ | `src/tmux.ts` | Re-export of the tmux backend, kept for genuinely tmux-only concerns: the `MU_TMUX_SOCKET` test seam and the shared `sleep` / `setSleepForTests` poll seam. Everything else imports `src/mux.ts` and goes through `activeMux()`. |
650
+ | `src/detect.ts` | Pi status detector (`busy` / `needs_input` / `needs_permission`) + Braille-spinner fallback. Used when the mux cannot classify panes itself — i.e. always on tmux, never on herdr. |
651
+ | `src/reconcile.ts` | Ghost prune + status detect + orphan surface; "reality wins" |
652
+ | `src/agents.ts` | Hub: CRUD + send / read / list / close + liveness + reaper. Re-exports `src/agents/*`; pane-title composition (`composeAgentTitle`) lives here. |
653
+ | `src/agents/*.ts` | Agent-lifecycle internals: `spawn.ts` (spawn, CLI resolution, liveness wait *or* backend `startAgentInPane`, pane create-or-reuse, rollback), `spawn-lock.ts` (per-session lock around topology+finalize), `wait.ts`, `adopt.ts`, `kick.ts` (signal a wedged pane's pgid), `errors.ts`. |
654
+ | `src/dag.ts` | Shared DAG read/render helpers: `loadFullDag` plus pure `renderForest` / `renderTaskTree`, reused by `mu task tree` and the TUI DAG popup. |
655
+ | `src/tasks/*.ts` | Task-graph internals: `core.ts` (row shapes, id resolution), `id.ts`, `queries.ts` (reads), `edit.ts` (+ delete cascade preview), `edges.ts` (+ cycle check), `status.ts` (TaskStatus), `sort.ts`, `claim.ts` (atomic CAS), `lifecycle.ts` (close/open), `wait.ts`, `errors.ts`. |
656
+ | `src/tracks.ts` | Parallel-tracks union-find with diamond merge |
657
+ | `src/staleness.ts` | `WORKSPACE_STALE_THRESHOLD = 10` and the pure `isWorkspaceStale` predicate, shared by static state, the TUI Workspaces card, and dispatch-time checks. |
658
+ | `src/workstream.ts` | ensureWorkstream / list / summarize / destroy |
659
+ | `src/logs.ts` | Typed READER over `ops` (`listLogs` / `latestSeq`), plus the write paths triggers cannot cover: `appendLog` (operator prose) and `emitEvent` (changes mutating no portable table — `agent.*`, `workspace.*`), under a typed `LocalIntent`. |
660
+ | `src/log-render.ts` | **The ONE op → prose formatter.** `renderOp` maps an intent (+ key + payload fields) to `{verb, subject, detail}`; plus `renderOpLine`, `opSubject`, `parseOpKey`. Pure and colour-free, so CLI and TUI share one phrasing. |
661
+ | `src/vcs/*.ts` | One backend per file (`git.ts`, `jj.ts`, `sl.ts`, `none.ts`) plus `types.ts` (the `VcsBackend` interface), `helpers.ts`, and `index.ts` (detection precedence `jj` → `sl` → `git` → none; `backendByName`). |
662
+ | `src/workspace/*.ts` | Per-agent VCS workspaces, a registry on top of `vcs.ts`: `core.ts` (row shapes, paths, errors), `crud.ts`, `decorate.ts` (staleness + dirty), `orphans.ts`. |
663
+ | `src/glyphs.ts` | **The ONE glyph vocabulary.** `AGENT_STATUS_GLYPH` + `agentStatusGlyph()` for agent status, the `GLYPH` record for every other state symbol (blocked, dirty, stale, ok/warn/fail, filter toggles), and `superscriptDigit` for TUI card-header keys. All classic Nerd Font `nf-fa-*` — single-codepoint and one cell wide, so `cli-table3` columns line up. Keyed by MEANING, so re-pointing a symbol is a one-line edit. `busy` matches murmur's dash `running`: same panes, same symbol. |
664
+ | `src/output.ts` | NextStep type + `printNextSteps` + `errorNextSteps` plumbing for self-documenting output |
665
+ | `src/shell-quote.ts` | `shellQuote` — POSIX single-quoting for tokens interpolated into copy-pasteable next-step hints. |
666
+ | `src/state.ts` | SDK seam for `mu state`: `loadWorkstreamSnapshotFast` (pure SQL, TUI 1s tick), `loadWorkstreamSnapshotSlow` (subprocesses), `mergeSnapshotFastSlow`, `loadWorkstreamSnapshot`. Also parses exact `REMOTE:` task-note inventory and `REMOTE_BASE:` dispatch metadata. Opt-in: `withDirty`, `withDoctor`, `withRecentCommits`, `withAllTasks`. |
667
+ | `src/doctor-summary.ts` | The dashboard's doctor seam: `loadDoctorSummary` (pragmas and COUNT-shape selects only — cheap enough for the poll loop), `loadDoctorChecks` for the popup, plus `yankCommandForCheck` / `remediationParagraph`. |
668
+ | `src/cli.ts` | commander entry; `buildProgram()` (re-exports `format`/`handle` symbols for back-compat with existing import sites). |
669
+ | `src/cli/*.ts` | One file per verb-namespace; thin wrappers over the SDK; `--json` on every read verb. Two non-verb cluster-mates: `format.ts` (table renderers, status colourers) and `handle.ts` (typed-error → exit-code map). |
670
+ | `src/cli/tui/*.tsx` | The interactive ink TUI, lazy-imported by `src/cli/state.ts`. **The only place ink/react are imported** — a ROADMAP pledge. Per-file roles: [§ TUI architecture](#tui-architecture). |
671
+ | `src/cli/tasks/*.ts` | Sub-cluster of the `mu task` namespace: `queries.ts` (list/next/owned-by + `mu me tasks` / `mu me next`), `lifecycle.ts` (close/open), `edit.ts`, `edges.ts` (+ delete cascade preview), `claim.ts`, `tree.ts`, `wire.ts` (Commander glue). |
672
+ | `src/index.ts` | SDK entrypoint (re-exports) |
673
+ | `skills/mu/SKILL.md` | Bundled skill teaching the LLM the model + verb list + jq pipelines |
674
+
675
+ ### What the rows above leave out
676
+
677
+ - **Capture triggers are TEMP triggers**, reinstalled per connection —
678
+ SQLite refuses a main-schema trigger referencing the temp `_op_ctx`.
679
+ Hence two oddities: DELETE keys are captured inline, with the parent
680
+ stashing its natural key in `_op_dying` first (FK CASCADE fires child
681
+ triggers after the parent is gone), and the HLC is minted in SQL,
682
+ because a trigger cannot call into JS.
683
+ - **Merge is per entity**: notes and messages are grow-only sets, tasks
684
+ and workstreams merge per field by HLC, edges are an LWW-element-set.
685
+ A tombstone is an ordinary op carrying an HLC, so out-of-order
686
+ arrival is a comparison and resurrection falls out. Never
687
+ `json_patch` — RFC 7396 reads a null member as delete-the-key.
688
+ - **Note tombstones are the one SELF-DESCRIBING tombstone.** Every
689
+ other `del` carries `'{}'`, because its key plus the puts before it
690
+ describe the row. A note's key embeds its rowid
691
+ (`<ws>/<task>#<id>`), which is NOT stable — a rebuild or
692
+ reprojection reassigns it, leaving the puts under the old key and a
693
+ later `del` under the new one. Undo folds the puts for a key to
694
+ reconstruct a tombstoned row, so such a note folded to nothing and
695
+ was silently never restored (drift-641). The `task_notes` delete
696
+ trigger therefore records `OLD.*`, and `planUndo` falls back to the
697
+ tombstone's payload when the fold is empty. This is also why
698
+ `src/drift.ts` matches notes on the task-key PREFIX rather than the
699
+ exact key.
700
+ - **Undo and restore write through the tables**, so neither can be the
701
+ write path capture misses. `restore` records then applies under the
702
+ SAME HLC: `applyOp` excludes an op's own HLC from provenance, so a
703
+ fresher one makes the row outrank the op and lose every field to an
704
+ insert default.
705
+ - **Segments are single-writer per file** — a machine appends only to
706
+ its own, so nothing is contended and any folder-syncer is adequate
707
+ transport. Regenerable, so no fsync. Four layers stop at the first
708
+ bad record and advance the watermark only that far: `JSON.parse`
709
+ (torn write when the line lacks its trailing `,"crc"…}` framing,
710
+ malformed-shape when it has it — the same failure, but a transfer cut
711
+ short and a writer bug have different remediations), crc32 per line
712
+ (bit rot), monotonic HLC (reorder, duplicate, truncation), a
713
+ `.manifest` sidecar (truncation exactly on a line boundary).
714
+ `ops.payload` is TEXT that is usually but not always JSON (`mu log
715
+ "text"` writes prose), so the encoder passes valid JSON through
716
+ verbatim — the crc covers those exact bytes — and JSON-encodes
717
+ anything else, unwrapping on ingest. Only `SYNCED_ENTITIES` and only THIS machine's ops
718
+ are flushed, so pane ids and absolute paths never leave and peers
719
+ never echo each other's history.
720
+ - **Sync never fails a command**: a truncated segment, a garbage
721
+ segment, a sync dir that is a file, a vanished directory all warn on
722
+ stderr and return.
723
+ - **Damage halts; refusal skips.** Stopping at the first bad record is
724
+ right for DAMAGE, where a gap is indistinguishable from reordering.
725
+ It is wrong for a well-formed line mu merely declines to project: a
726
+ refusal lands nothing, so it leaves no hole, and halting made the
727
+ watermark unrecoverable by any means the CLI offers. One
728
+ `entity:"marker"` line at position 2533 of a 20,305-line peer segment
729
+ froze that peer's watermark permanently, and `mu sync --repair` (which
730
+ only resets the watermark) re-read straight back into the same line.
731
+ So ingest now distinguishes three cases: damage halts, a KNOWN
732
+ machine-local entity is a reported defect that is SKIPPED, and an
733
+ UNRECOGNISED entity applies as a no-op with no defect at all —
734
+ reader-behind-writer vocabulary is a fact of a mixed fleet, not
735
+ corruption. `--repair` is only suggested for defects a re-read can
736
+ clear.
737
+ - **Rebuild is not ingest**: ingest filters to `SYNCED_ENTITIES`, but
738
+ local recovery replays everything, so log-only entities are copied
739
+ verbatim or `mu log` comes back empty. `machine_identity` carries
740
+ across whole — id, hostname, HLC clock — or the rebuilt DB is a
741
+ different peer minting HLCs below every replayed op. Drift diffs by
742
+ natural key and excludes `owner_id`: a rebuild always has NULL
743
+ owners.
744
+
745
+ Why segments and not Litestream / cr-sqlite / a peer list, and why the
746
+ DB must never sit in `MU_SYNC_DIR`:
747
+ [ROADMAP § Rejected sync substrates](ROADMAP.md#rejected-sync-substrates).
748
+
749
+ ## Data flow
750
+
751
+ 1. **A caller invokes a verb** — the CLI subprocess, or in-proc SDK
752
+ use.
753
+ 2. **CLI handler dispatches to an SDK function** in `src/agents.ts`
754
+ / `src/tasks.ts` / etc.
755
+ 3. **For multi-statement writes, opens a transaction** via
756
+ better-sqlite3's `db.transaction(fn)()` wrapper.
757
+ 4. **Executes the operation** — agent ops shell out to tmux (and to
758
+ jj/sl/git for workspaces); task ops are pure SQL.
759
+ 5. **Reconciles with reality** — for read-paths that need accuracy
760
+ (`mu agent list`, state views), queries tmux for live pane
761
+ state and updates the DB (ghost prune + status detect).
762
+ 6. **Records ops** — automatically, per [§ The ops log](#the-ops-log-read-this-first);
763
+ machine-local changes go through `emitEvent`. `mu log --tail`
764
+ subscribers see the new ops on the next 1-second poll.
765
+ 7. **Commits or rolls back** — exception propagates after rollback
766
+ so the caller sees the real error and the typed error class
767
+ maps to a specific exit code in `handle()`.
768
+
769
+ ## Key seams
770
+
771
+ The extension points. A new impl of each is small.
772
+
773
+ | Seam | Add a new impl by... |
774
+ | ------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
775
+ | `VcsBackend` | Implementing `detect / createWorkspace / freeWorkspace / isClean / commitsBehind / rebaseTo / commitsSinceBase / recentCommits / showCommit` (~80–150 LOC; jj/sl/git/none are working examples) |
776
+ | Per-CLI `Detector` | Adding patterns to `detectPiStatus` (vanilla pi `to interrupt)`; pi-meta + every TUI wrapper covered by Braille spinner glyph fallback `[\u2800-\u28FF]`) |
777
+ | New typed verb | An SDK function in the relevant `src/*.ts`; a `cmd<Verb>` in the matching `src/cli/<namespace>.ts`; one commander block in `buildProgram()`, wrapped in `handle()` and routed through `printNextSteps` |
778
+ | New schema migration| Bump `CURRENT_SCHEMA_VERSION` in `src/db.ts` and mirror the shape in `CURRENT_SCHEMA`. Keep startup migration-free; extend the retained fresh-target sidecar only when an old released schema needs a bridge. Recipe: [scripts/README.md](../scripts/README.md) |
779
+ | New syncable field | Add the column to a portable table, extend the capture trigger's changed-column comparison, confirm the apply path writes it. The UPDATE trigger MUST emit only changed columns — a full-row payload silently regresses field merge to row-level LWW |
780
+ | Cross-machine sync | Nothing: every invocation already flushes local ops and ingests each peer segment from its watermark. No daemon, no network code, no membership config |
781
+
782
+ An importer must synthesize **ops, not rows**: the tables are a
783
+ projection of the log, so a direct INSERT is invisible to sync and
784
+ reported as drift.
785
+
786
+ ## The ambient sync hook
787
+
788
+ Sync is **ambient, not a daemon**: no watcher, no background process,
789
+ no polling loop outliving a command. It happens because you already
790
+ run `mu` constantly.
791
+
792
+ **The seam is `handle()`** (`src/cli/handle.ts`), the one place every
793
+ verb passes through, and the only seam that is already async —
794
+ `syncPass` is async (it takes the file lock) while most verb bodies
795
+ are synchronous better-sqlite3 code. One `await` before `fn(db)` and
796
+ one after covers all ~60 verbs; no verb learns that sync exists.
797
+
798
+ **Order matters**: ingest BEFORE the body, so the verb reads the
799
+ freshest state transport has delivered; flush AFTER, so this
800
+ invocation's ops reach the segment now rather than next invocation.
801
+ Flush also runs on the ERROR path — a verb may have committed ops
802
+ before throwing, and those ops are already canonical, so withholding
803
+ them would make this machine's history depend on the exit code.
804
+
805
+ Four carve-outs:
806
+
807
+ | Surface | Behaviour | Why |
808
+ | ------- | --------- | --- |
809
+ | `MU_SYNC_DIR` unset | One `if` on one env var. No promise, no filesystem touch. | The single-machine case must pay nothing. Measured indistinguishable from baseline; ~3ms with one peer. |
810
+ | `mu sql` | Opts out (`handle(..., { ambientSync: false })`). | It is the verb whose result an operator diffs against their own expectation; an ambient ingest changing a row count mid-inspection reads as a mu bug. |
811
+ | `mu sync` | Opts out and runs the pass itself. | Otherwise the report prints 'ingested 0' right after ingesting. |
812
+ | The TUI | On the SLOW tick (10s, `SLOW_TICK_MS`) only, guarded so N tabs run one pass per beat, `quiet: true`. | The fast tick can be wound down to 100ms — 10 passes/second on a shared folder. Quiet because the TUI owns the alternate screen; sync problems surface via the Doctor card. |
813
+
814
+ ### Out-of-order arrival: `reprojectDeferredOps`
815
+
816
+ An `edge` or `note` put whose task has not been ingested yet skips as
817
+ `absent` — correctly. But ingest advances the watermark past it
818
+ anyway, so without a second pass it never lands: a permanent silent
819
+ divergence, and a coin flip per fleet, since peers are discovered by
820
+ `localeCompare` over random-UUID filenames.
821
+
822
+ `reprojectDeferredOps` re-queries the log for note/edge puts that are
823
+ resolvable NOW but unprojected. No retry queue — that would be a
824
+ second source of truth, and it would not survive a short-lived mu
825
+ process when the parent often arrives days later. It excludes ops
826
+ whose parent task is gone and keys carrying a newer `del`,
827
+ so a deleted edge is never resurrected and an orphan is not retried
828
+ forever. On a healthy DB it is two indexed queries returning zero
829
+ rows. Called once per ingest pass, never per peer: an edge in one
830
+ segment may name a task in another.
831
+
832
+ ## Surrogate-PK + SDK-boundary discipline
833
+
834
+ A substrate-wide invariant; every entity table follows it.
835
+
836
+ **Schema shape — every entity table:**
837
+
838
+ ```
839
+ (
840
+ id INTEGER PRIMARY KEY AUTOINCREMENT, -- surrogate; internal
841
+ <scope_id> INTEGER NOT NULL REFERENCES <parent>(id) ON DELETE CASCADE,
842
+ <name> TEXT NOT NULL, -- operator-facing; mutable
843
+ -- ... domain attributes
844
+ UNIQUE (<scope_id>, <name>) -- per-scope unique
845
+ )
846
+ ```
847
+
848
+ FKs reference `<child>.<parent>_id` (INTEGER), never the TEXT name.
849
+ The TEXT name is an operator-facing attribute — searchable,
850
+ displayable, cheap to rename. The surrogate id is the identity.
851
+
852
+ **TEXT-by-design exceptions:** the
853
+ workstream's own `name` (it IS a tmux session name; globally
854
+ unique), `task_notes.author` / `ops.actor` (free-text actor
855
+ labels — `"orchestrator"`, `"user"`, `"system"`), `ops.entity`
856
+ (open enum — future entities need no migration), `agents.cli`
857
+ (adding a new CLI must not require a schema change), and every
858
+ column of `ops` (the ops log is FK-free by design and addresses
859
+ rows by their NATURAL key, so an op outlives the row — and the
860
+ workstream — it records).
861
+
862
+ **SDK boundary discipline** — same shape as REST: external API
863
+ uses business identifiers, internal layer uses primary keys.
864
+
865
+ > **Public SDK functions take operator-facing names.**
866
+ > **Internal helpers take surrogate ids.**
867
+ > **Resolution happens at the public-function entry, exactly once.**
868
+
869
+ ```ts
870
+ // PUBLIC: takes operator-facing names
871
+ export function claimTask(
872
+ db: Db,
873
+ workstream: string,
874
+ localId: string,
875
+ opts?: ClaimOptions,
876
+ ): ClaimResult {
877
+ const wsId = resolveWorkstreamId(db, workstream);
878
+ const taskId = tryResolveTaskId(db, wsId, localId);
879
+ if (taskId === null) throw new TaskNotFoundError(localId);
880
+ const agentId = resolveCurrentAgentId(db, wsId);
881
+ return claimTaskById(db, taskId, agentId, opts);
882
+ }
883
+
884
+ // INTERNAL: takes surrogate ids; never re-resolves
885
+ function claimTaskById(db, taskId, agentId, opts): ClaimResult { ... }
886
+ ```
887
+
888
+ Resolving exactly once at the boundary buys three things: no
889
+ double-resolution; no mid-function ambiguity (with surrogate ids in
890
+ hand, internal helpers need no workstream context — the FKs make
891
+ scope implicit); and one place for error mapping
892
+ (`WorkstreamNotFoundError` originates at resolve-time in
893
+ `src/db.ts`; `TaskNotFoundError` / `AgentNotFoundError` are raised by
894
+ SDK callers wrapping the `tryResolve*` null-return, so the typed
895
+ class and its exit-code 3 mapping hold whichever leg missed).
896
+
897
+ **`--json` output preserves operator-facing names.** Surrogate ids
898
+ never leak into `--json`, error payloads, log lines, or markdown
899
+ exports. Promoting them to the public shape would re-introduce a
900
+ global namespace by the back door (anti-feature pledge).
901
+
902
+ ## State of truth
903
+
904
+ - **`~/.local/state/mu/mu.db` is canonical.** Everything else is a
905
+ cache, including tmux pane titles (mu re-pushes their durable agent/task
906
+ context via `composeAgentTitle` after every relevant state change).
907
+ - **Reads are cheap** via SQLite views (`ready`, `blocked`, `goals`).
908
+ - **Writes go through the typed SDK functions** (`src/agents.ts`,
909
+ `src/tasks.ts`, …) which validate, transact, and reconcile. Op
910
+ capture is not their job — the triggers handle it.
911
+ - **Workstream scoping is mandatory at the CLI boundary.** TEXT names
912
+ (`tasks.local_id`, `agents.name`) are per-workstream unique — the
913
+ same name may legitimately exist in two workstreams. Every public
914
+ SDK function taking such a name also takes (or threads) the
915
+ workstream; internal SQL filters by `(workstream_id, name)`. Test
916
+ fixtures and `mu sql` read paths may omit it and fall back to
917
+ first-match-by-name. The schema enforces it structurally
918
+ (per-workstream UNIQUE on name + INTEGER FKs).
919
+ - **The ops log is the insurance and it IS version history** — see
920
+ [§ The ops log](#the-ops-log-read-this-first). `mu undo <group>`
921
+ reverts one action; `mu rebuild <file>` replays the whole log into
922
+ a fresh DB.
923
+ - **In-memory state is short-lived** — the CLI's per-command
924
+ connection. Gone on process exit.
925
+ - **Cross-process coordination** is via SQLite WAL — multiple `mu`
926
+ processes share the file safely.
927
+
928
+ ## Errors
929
+
930
+ Curated error classes per layer; no try/catch swallowing. CLI exit
931
+ codes:
932
+
933
+ | Code | Meaning |
934
+ | ---- | -------------------------------------------------------- |
935
+ | 0 | success |
936
+ | 1 | generic error |
937
+ | 2 | usage error (commander's default) |
938
+ | 3 | not found (no such agent / task / workspace) |
939
+ | 4 | conflict (name collision, double-claim, dirty tree) |
940
+ | 5 | substrate unavailable (`tmux` not running, DB locked) |
941
+
942
+ Errors carry structured context (operation name, target, attempted
943
+ action) so `mu doctor` can surface them readably.
944
+
945
+ ## Testing layers
946
+
947
+ | Layer | Test approach |
948
+ | ---------------------------------- | ------------------------------------------------------------------------------ |
949
+ | `src/db.ts` | Real SQLite in temp dir; schema/table-count assertions |
950
+ | `src/tasks.ts` | Real SQLite in temp dir; pure functions over fixture data |
951
+ | `src/tracks.ts` | Pure functions; union-find + diamond-merge properties |
952
+ | `src/agents.ts` | Mocked tmux executor via `setTmuxExecutor()`; reaper integration tests |
953
+ | `src/logs.ts` | Real SQLite; cursor semantics, AUTOINCREMENT durability, ops-outlive-workstream |
954
+ | `src/capture.ts` + `src/op-context.ts` | Real SQLite, no tmux: payloads hold ONLY changed columns (asserted by key COUNT), echo suppression, cascade grouping, FK-CASCADE tombstone keys, the null-intent fail-safe |
955
+ | `src/apply.ts` | Real SQLite, INJECTED HLCs, no sleeps: field-level convergence in both orders, same-field LWW determinism, all four put/del orderings, resurrection, grow-only notes, edge add/remove, the set-to-NULL trap, `owner_id` stripping, replay idempotence |
956
+ | `src/rebuild.ts` | Round trip asserted row-BY-ROW per portable table (a count-only check passes on a garbage rebuild), plus idempotence, tombstones, byte-identical ops, log-only entities copied, `machine_id` + clock carried. `cli-rebuild.integration` covers the verb |
957
+ | `src/drift.ts` + `src/fleet-hazards.ts` | Drift planted the way a capture bug would (`withCaptureSuppressed` + direct mutation), with equal weight on FALSE positives (cascade delete, resurrection, set-to-NULL, no-op update, claimed task). `classifyFsType` against synthetic magic numbers |
958
+ | `src/dormant.ts` | Task `updated_at` written directly in SQL (the verbs stamp `datetime('now')`, and the age IS the input under test). Weighted toward the BOUNDARY between the two buckets rather than detection: at an age between the thresholds, a closed-out workstream is reported and one with open tasks is not |
959
+ | `src/disk-recon.ts` | Per-test `MU_STATE_DIR` temp dir with the on-disk shape built by hand — the disagreements it detects cannot be produced through the normal verbs, since those keep disk and DB in step. Both directions covered (row without dir, dir without row), plus the live-WAL-triple exclusion and `stranded` marking |
960
+ | `src/segments.ts` | TWO temp DBs and one shared dir — the real deployment shape. Round trip; two machines editing different fields both surviving; idempotence; each robustness layer; machine-local ops never reaching a file; Syncthing conflict copies |
961
+ | `src/sync.ts` + `src/cli/sync.ts` | Fast tier covers decision logic in-process (staleness arithmetic, peer-prefix ambiguity, MU_SYNC_DIR unset, the never-throw contract against four breakages, hook order). `cli-sync.integration` re-checks it THROUGH THE VERB with two DBs and one dir |
962
+ | the whole sync path, as a SESSION | `sync-session.integration` simulates days of laptop↔devserver work: 8 rounds, two machines, no coordination beyond the folder. Asserts byte-identical portable content, no `--deep` drift, and a quiet round adding exactly zero ops |
963
+ | `src/hlc.ts` | Real SQLite + an INJECTED clock (no sleeps): backwards jumps, stalled milliseconds, sort order, durability, concurrent minting |
964
+ | `src/vcs.ts` + `src/workspace.ts` | `*.integration.test.ts` files use real git in `os.tmpdir()`; jj/sl tests feature-detect (skip if binary missing) |
965
+ | `src/cli.ts` / verb integration | `*.integration.test.ts` files; real tmux server, unique session per test |
966
+ | Fast unit/dev-loop tier | `npm run test:fast`; excludes `*.integration.test.ts` / `*.smoke.test.ts`, uses mocked tmux/VCS and per-test temp DBs |
967
+ | Stress / flake audit | `npm run test:stress`; repeats the full suite with per-run logs/timeouts, optionally in parallel waves (`MU_TEST_STRESS_MODE=parallel`) |
968
+ | End-to-end | `test/acceptance.integration.test.ts` — the canonical 10-task / 3-agent demo |
969
+
970
+ Two fixture traps: a convergence fixture must share ONE creation op
971
+ (two independent `task add`s for the same id make the later creation
972
+ legitimately win every field), and an ordering-sensitive test must
973
+ RENAME segments to pin ingest order, since peers are discovered by
974
+ `localeCompare` over random-UUID filenames.
975
+
976
+ Flake lessons: treat pass-alone/fail-under-load cases as
977
+ concurrency bugs first; use retrying temp-dir cleanup for VCS fixtures
978
+ whose subprocesses keep files alive briefly; drive wait/reaper
979
+ integration tests from poll-loop seams, not fixed timers; wait for
980
+ stable Ink output instead of sleeping.
981
+
982
+ ## Distribution
983
+
984
+ Single npm package `mu` (see `package.json`):
985
+
986
+ - `dist/cli.js` — CLI entry, executable (`bin: { mu: ./dist/cli.js }`; shebang preserved by `tsup`)
987
+ - `dist/index.js` + `dist/index.d.ts` — programmatic API + types for SDK callers
988
+ - `skills/mu/SKILL.md` — bundled skill (the only non-`dist` asset shipped)
989
+
990
+ `tsup` bundles two entries (`index`, `cli`) from `src/`. No runtime
991
+ build step on the user's machine. There is no pi-extension entry — pi
992
+ is a peer dep — and no bundled `agents/*.md` or `prompts/*.md`:
993
+ per-role agent guidance lives in the user's project repo.
994
+
995
+ The dependency list lives in `package.json`; the rule for adding
996
+ new ones is the anti-feature pledge in
997
+ [ROADMAP.md § Anti-feature pledges](ROADMAP.md#anti-feature-pledges).