@mu-crew/mu 4.1.1 → 4.2.1
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.
- package/dist/{chunk-L7I3BLXP.js → chunk-4ZWBLTZK.js} +1512 -411
- package/dist/chunk-4ZWBLTZK.js.map +1 -0
- package/dist/{chunk-DEYBQDTO.js → chunk-FVRIKUBR.js} +2 -2
- package/dist/{chunk-B74N2EAS.js → chunk-RJQNDFBU.js} +8 -4
- package/dist/chunk-RJQNDFBU.js.map +1 -0
- package/dist/{chunk-LBBZAG5C.js → chunk-U2QLTREB.js} +26 -23
- package/dist/chunk-U2QLTREB.js.map +1 -0
- package/dist/{cli-H2PWJAJN.js → cli-H3VVCP7M.js} +146 -31
- package/dist/cli-H3VVCP7M.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/{errors-G5IVXSMY.js → errors-MDQZHB42.js} +8 -2
- package/dist/extension/mu-pi.js +20 -3
- package/dist/extension/mu-pi.js.map +1 -1
- package/dist/index.d.ts +2574 -2288
- package/dist/index.js +58 -4
- package/dist/index.js.map +1 -1
- package/dist/{tui-EN2CDP6G.js → tui-5ZARE7RS.js} +14 -15
- package/dist/tui-5ZARE7RS.js.map +1 -0
- package/docs/ARCHITECTURE.md +15 -8
- package/docs/VOCABULARY.md +14 -6
- package/docs/guide/remote.md +113 -4
- package/docs/guide/sql.md +1 -1
- package/docs/reference/env.md +1 -0
- package/package.json +1 -1
- package/skills/mu/recipes/remote-workers.md +7 -6
- package/dist/chunk-B74N2EAS.js.map +0 -1
- package/dist/chunk-L7I3BLXP.js.map +0 -1
- package/dist/chunk-LBBZAG5C.js.map +0 -1
- package/dist/cli-H2PWJAJN.js.map +0 -1
- package/dist/tui-EN2CDP6G.js.map +0 -1
- /package/dist/{chunk-DEYBQDTO.js.map → chunk-FVRIKUBR.js.map} +0 -0
- /package/dist/{errors-G5IVXSMY.js.map → errors-MDQZHB42.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/rebuild.ts","../src/drift.ts","../src/fleet-hazards.ts","../src/glyphs.ts","../src/wait-types.ts","../src/wait-regex.ts","../src/close-block.ts","../src/wait-db.ts","../src/wait-item.ts","../src/wait-latch.ts","../src/wait.ts","../src/wait-action-receipts.ts","../src/wait-actions.ts","../src/wait-ctl.ts","../src/next-recover.ts","../src/next-refute.ts","../src/next.ts","../src/pi-migrate.ts","../src/pi-known-skills.ts","../src/remote-collect.ts","../src/tasks/sort.ts","../src/state.ts","../src/wait-resume.ts"],"sourcesContent":["// mu — rebuild: materialize a fresh DB by replaying the ops log.\n//\n// The third leg of the ops-log substrate, after capture (write side) and\n// apply (read side). This is the DISASTER-RECOVERY story that replaces\n// the snapshot files mu no longer keeps: given an intact `ops` table, every\n// portable row is reconstructable, because the log is the canonical\n// record and the tables are a projection of it.\n//\n// It is also the foundation the doctor drift check stands on. \"Is the\n// projection still faithful to the log?\" is answered by rebuilding into\n// a temp DB and diffing — which is why `rebuildInto` takes the target\n// path as a PARAMETER and prints nothing. All human output lives in the\n// CLI layer (src/cli/rebuild.ts).\n//\n// REBUILD INTO A NEW FILE, NEVER IN PLACE\n// ---------------------------------------\n// Locked decision. A rebuild that overwrote the live DB would be a\n// destructive operation whose failure mode is \"no database at all\", and\n// it would have to hold a write lock over the whole replay. Writing a\n// new file and PRINTING THE SWAP COMMAND keeps the operator in control:\n// they can diff, inspect, and swap when ready. It also means a rebuild\n// is safe to run at any time, including from the drift check, with no\n// risk to live state.\n//\n// REBUILD IS NOT INGEST\n// ---------------------\n// The distinction is load-bearing and easy to get backwards.\n//\n// ingest = \"absorb a PEER's ops\". Only SYNCED_ENTITIES may cross a\n// machine boundary, so ingest filters. A peer's agent rows\n// are meaningless here (`pane_id` '%17' names a pane on\n// their box), so they must never arrive.\n// rebuild = \"reconstruct MY OWN database\". A local recovery\n// operation, so it must replay EVERYTHING the log knows,\n// including machine-local ops. Dropping them would silently\n// discard this machine's own log history — `mu log` would\n// come back empty after a recovery.\n//\n// So this module deliberately does NOT filter by SYNCED_ENTITIES. It\n// copies every op verbatim and projects the ones that have a portable\n// table to project into.\n//\n// WHAT A REBUILT DB LEGITIMATELY LOSES\n// ------------------------------------\n// The ops log only contains what capture recorded, and capture has\n// triggers on the PORTABLE tables only. `agents`, `task_auto` and\n// `worktrees` have no triggers, so they leave no ops and cannot be\n// reconstructed.\n//\n// That is CORRECT, not a gap. These tables hold values that are\n// meaningless after recovery: `agents.pane_id` names a tmux pane in a\n// server that no longer has it, and `worktrees.path` is an absolute\n// path whose working copy may be gone. Resurrecting either would produce\n// rows that lie about reality, and `mu doctor` would immediately flag\n// them as ghosts.\n//\n// But it must be REPORTED, never silent. An operator who rebuilds and\n// does not realise their agent registry is empty will wonder why\n// `mu agent list` is blank. `RebuildReport.machineLocalLost` carries the\n// per-table counts so the CLI can say so explicitly and tell them to\n// re-spawn.\n\nimport { existsSync, mkdirSync, rmSync, statSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { projectLog } from \"./apply.js\";\nimport { type Db, openDb, SYNCED_ENTITIES } from \"./db.js\";\nimport { compareHlc, type Hlc, parseHlc } from \"./hlc.js\";\nimport { say } from \"./messages.js\";\nimport { withCaptureSuppressed } from \"./op-context.js\";\n\n/** Raised when the rebuild target already exists. Never overwrite: the\n * operator may have pointed at their live DB by mistake, and a rebuild\n * is supposed to be the SAFE recovery path. */\nexport class RebuildTargetExistsError extends Error {\n constructor(readonly path: string) {\n super(say(\"rebuild.target_exists\", path));\n this.name = \"RebuildTargetExistsError\";\n }\n}\n\n/** Raised when the target path resolves to the source DB. Rebuilding a\n * DB onto itself would truncate the very log being replayed. */\nexport class RebuildTargetIsSourceError extends Error {\n constructor(readonly path: string) {\n super(say(\"rebuild.target_is_source\", path));\n this.name = \"RebuildTargetIsSourceError\";\n }\n}\n\n/** Per-table counts of rows a rebuild cannot reconstruct, because the\n * table has no capture triggers and therefore leaves no ops. */\nexport interface MachineLocalLoss {\n table: string;\n /** Rows present in the SOURCE that will be absent from the rebuild. */\n rows: number;\n}\n\n/** What a rebuild did. Returned rather than printed so the drift check\n * can consume it programmatically. */\nexport interface RebuildReport {\n /** Absolute-ish path written (as given by the caller). */\n targetPath: string;\n /** Ops copied into the target's log. Every op, not just synced ones. */\n opsCopied: number;\n /** Ops that projected into a portable table. Always <= opsCopied:\n * log-only entities (message / event / broadcast), machine-local\n * agent ops are copied but have no table to land in. */\n opsProjected: number;\n /** Table rows the projection wrote (workstreams, tasks, note sets, edges\n * that changed). Far lower than opsProjected: the fold writes each key\n * once, however many ops named it. */\n opsChangedRows: number;\n /** Ops skipped as non-projectable, by entity. Diagnostic only. */\n logOnlyByEntity: Record<string, number>;\n /** Row counts per portable table in the rebuilt DB. */\n rebuiltRows: Record<string, number>;\n /** Tables that cannot be rebuilt, with the row counts being lost. */\n machineLocalLost: MachineLocalLoss[];\n /** The machine identity carried across, so the rebuilt DB remains the\n * SAME peer rather than becoming a new one. */\n machineId: string;\n}\n\n/** Tables that hold real state but leave no ops, so a rebuild cannot\n * reconstruct them. Both are machine-local by nature — see the module\n * comment for why resurrecting them would be wrong even if we could. */\nconst UNREBUILDABLE_TABLES = [\n \"agents\",\n \"task_auto\",\n \"worktrees\",\n \"delegate_calls\",\n \"wait_cursors\",\n \"wait_registrations\",\n // The condition sets behind `mu wait --resume <id>`: a handle is worthless on a rebuilt DB.\n \"wait_resumes\",\n \"agent_settles\",\n \"host_profiles\",\n \"host_channels\",\n \"spawn_receipts\",\n // The stall actions a wait took (steer exclusion, release record): no op carries them.\n \"wait_action_receipts\",\n // A remote worker's worktree, kept when its row was deleted: no op carries it.\n \"remote_recovery\",\n // The human task and its reason rebuild from ops; WHO recorded it does\n // not. Ownership is never inferred from a note author.\n \"human_needs\",\n] as const;\n\n/** Entities that exist only in the log: there is no portable table to\n * project them into, so copying the op IS applying it.\n *\n * 'message' / 'event' / 'broadcast' are log lines (src/logs.ts writes\n * them). All three are copied verbatim and deliberately not passed to\n * applyOp, which would reject the log kinds as non-synced. */\nconst LOG_ONLY_ENTITIES = new Set([\"message\", \"event\", \"broadcast\"]);\n\n/** Ops that `applyOp` knows how to project into a portable table. This\n * is the intersection of \"synced\" and \"has a table\", which excludes\n * 'message' even though it is in SYNCED_ENTITIES. */\nfunction isProjectable(entity: string): boolean {\n if (LOG_ONLY_ENTITIES.has(entity)) return false;\n return (SYNCED_ENTITIES as readonly string[]).includes(entity);\n}\n\ninterface RawOpRow {\n hlc: string;\n machine_id: string;\n group_id: string;\n actor: string | null;\n intent: string | null;\n entity: string;\n key: string;\n op: string;\n payload: string;\n created_at: string;\n}\n\nexport interface RebuildOptions {\n /** Path for the new DB. Must not exist. */\n targetPath: string;\n /** Overwrite an existing target. Off by default so a mistyped path\n * cannot clobber a real file; the drift check sets it because it\n * owns a temp path it just created. */\n force?: boolean;\n}\n\n/**\n * Replay `source`'s ops log into a brand-new DB at `opts.targetPath`.\n *\n * Prints nothing and returns a report, so both `mu rebuild` and the\n * (forthcoming) doctor drift check can use it — the latter rebuilds into\n * a temp path and diffs rather than showing a human anything.\n *\n * SYNCHRONOUS, matching applyOp and withOpContext: the op context is the\n * shared main-DB `op_ctx` row, so interleaved async scopes would clobber\n * each other's suppression flag.\n */\nexport function rebuildInto(source: Db, opts: RebuildOptions): RebuildReport {\n const { targetPath } = opts;\n\n // Refuse to touch the source. `sqlite_master`-level identity is not\n // enough — the caller may pass a different string for the same file —\n // so compare the resolved filename SQLite itself reports.\n const sourceFile = (source.pragma(\"database_list\") as Array<{ name: string; file: string }>).find(\n (row) => row.name === \"main\",\n )?.file;\n if (sourceFile !== undefined && sourceFile.length > 0) {\n const sameFile =\n sourceFile === targetPath ||\n (existsSync(targetPath) && existsSync(sourceFile) && sameInode(sourceFile, targetPath));\n if (sameFile) throw new RebuildTargetIsSourceError(targetPath);\n }\n if (existsSync(targetPath) && opts.force !== true) {\n throw new RebuildTargetExistsError(targetPath);\n }\n\n mkdirSync(dirname(targetPath), { recursive: true });\n\n // Read everything we need from the source FIRST, so the target is only\n // opened once we know the replay can proceed.\n // ONE read transaction (a WAL snapshot): a concurrent ingest between\n // separate SELECTs could otherwise copy an op whose HLC is ahead of the\n // clock we read.\n const snapshot = source.transaction(() => {\n const identity = source\n .prepare(\n \"SELECT machine_id, hostname, created_at, last_wall, last_counter FROM machine_identity WHERE id = 1\",\n )\n .get() as\n | {\n machine_id: string;\n hostname: string | null;\n created_at: string;\n last_wall: number;\n last_counter: number;\n }\n | undefined;\n if (!identity) throw new Error(say(\"rebuild.no_identity\"));\n\n const opRows = source\n .prepare(\n `SELECT hlc, machine_id, group_id, actor, intent, entity, key, op, payload, created_at\n FROM ops`,\n )\n .all() as RawOpRow[];\n\n // HLC ORDER, not seq order. seq is a local append cursor, so it\n // reflects the order ops were RECORDED, which for ingested peer ops is\n // arrival order rather than causal order. Replaying in HLC order is\n // what makes per-field LWW resolve correctly (see src/apply.ts), and\n // it is why the rebuild converges to the same state regardless of how\n // the log happened to be assembled.\n opRows.sort((a, b) => compareHlc(a.hlc, b.hlc));\n\n const peerRows = source\n .prepare(\"SELECT machine_id, last_applied_seq, last_seen_at FROM sync_peers\")\n .all() as Array<{\n machine_id: string;\n last_applied_seq: number;\n last_seen_at: string | null;\n }>;\n\n const machineLocalLost: MachineLocalLoss[] = [];\n for (const table of UNREBUILDABLE_TABLES) {\n const row = source.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get() as { n: number };\n if (row.n > 0) machineLocalLost.push({ table, rows: row.n });\n }\n return { identity, opRows, peerRows, machineLocalLost };\n });\n const { identity, opRows, peerRows, machineLocalLost } = snapshot();\n\n // `force` replaces the target, never merges into it: replaying over an\n // existing DB would keep its foreign rows and ops under our identity.\n if (opts.force === true) {\n for (const suffix of [\"\", \"-wal\", \"-shm\"]) rmSync(`${targetPath}${suffix}`, { force: true });\n }\n const target = openDb({ path: targetPath });\n try {\n // Carry the machine identity across BEFORE replaying.\n //\n // A fresh openDb seeds a NEW uuid, which would make the rebuilt DB a\n // DIFFERENT PEER: its own historical ops would look foreign to it,\n // the UNIQUE (machine_id, hlc) identity of every op would no longer\n // match its author, and peers tracking watermarks against the old id\n // would treat it as an unknown machine. Recovery must preserve who\n // this machine IS.\n //\n // The HLC clock (last_wall / last_counter) comes too. Without it the\n // rebuilt DB starts at 0 and the next local edit would mint an HLC\n // BELOW every op already in its log — so a brand-new change would\n // sort as older than history and lose every LWW comparison against\n // it. Monotonicity is a property of the machine, not of the file.\n target\n .prepare(\n `UPDATE machine_identity\n SET machine_id = @machineId, hostname = @hostname, created_at = @createdAt,\n last_wall = @lastWall, last_counter = @lastCounter\n WHERE id = 1`,\n )\n .run({\n machineId: identity.machine_id,\n hostname: identity.hostname,\n createdAt: identity.created_at,\n lastWall: identity.last_wall,\n lastCounter: identity.last_counter,\n });\n\n const insertOp = target.prepare(\n `INSERT OR IGNORE INTO ops\n (hlc, machine_id, group_id, actor, intent, entity, key, op, payload, created_at)\n VALUES (@hlc, @machineId, @groupId, @actor, @intent, @entity, @key, @op, @payload, @createdAt)`,\n );\n const insertPeer = target.prepare(\n `INSERT OR REPLACE INTO sync_peers (machine_id, last_applied_seq, last_seen_at)\n VALUES (@machineId, @lastAppliedSeq, @lastSeenAt)`,\n );\n\n const logOnlyByEntity: Record<string, number> = {};\n let opsProjected = 0;\n let opsChangedRows = 0;\n\n // ONE transaction for the whole replay. A rebuild is all-or-nothing:\n // a half-replayed DB is worse than no DB, because it looks usable.\n const replay = target.transaction(() => {\n // Capture-suppressed for the entire replay. Without this, writing\n // each row would fire the capture triggers and mint a SECOND op per\n // row, so the rebuilt log would be roughly double the original and\n // full of ops with fresh HLCs that never happened. The suppression\n // wraps the op INSERTs too, so nothing here can mint.\n withCaptureSuppressed(target, () => {\n for (const row of opRows) {\n // Copy the op verbatim, whatever its entity. This is the\n // rebuild-is-not-ingest rule: the log is this machine's own\n // history and every row of it survives recovery, including\n // machine-local entities that would never cross a peer\n // boundary.\n insertOp.run({\n hlc: row.hlc,\n machineId: row.machine_id,\n groupId: row.group_id,\n actor: row.actor,\n intent: row.intent,\n entity: row.entity,\n key: row.key,\n op: row.op,\n payload: row.payload,\n createdAt: row.created_at,\n });\n if (isProjectable(row.entity)) opsProjected += 1;\n else logOnlyByEntity[row.entity] = (logOnlyByEntity[row.entity] ?? 0) + 1;\n }\n // Move the clock past the newest copied op, whatever the carried\n // clock says (a stale identity read, a clock-skewed peer): the next\n // local mint must sort above everything in the log.\n advanceClockPast(target, opRows);\n\n // Project through the SAME fold a live apply uses (src/fold.ts):\n // each key is folded once from the whole log, so a rebuild and an\n // ingest cannot disagree. Not replayed op by op.\n opsChangedRows = projectLog(target);\n\n // sync_fingerprints is NOT copied: it is a cache that vouches for\n // the old DB's last reads, and without it the next ingest of\n // each peer simply reads its segment in full once.\n for (const peer of peerRows) {\n insertPeer.run({\n machineId: peer.machine_id,\n lastAppliedSeq: peer.last_applied_seq,\n lastSeenAt: peer.last_seen_at,\n });\n }\n });\n });\n replay.immediate();\n\n const rebuiltRows: Record<string, number> = {};\n for (const table of [\"workstreams\", \"tasks\", \"task_edges\", \"task_notes\", \"ops\"]) {\n const row = target.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get() as { n: number };\n rebuiltRows[table] = row.n;\n }\n\n return {\n targetPath,\n opsCopied: rebuiltRows.ops ?? 0,\n opsProjected,\n opsChangedRows,\n logOnlyByEntity,\n rebuiltRows,\n machineLocalLost,\n machineId: identity.machine_id,\n };\n } finally {\n target.close();\n }\n}\n\n/** Raise `machine_identity`'s clock to the newest parseable HLC in `rows`\n * when it is behind; never lowers it. */\nfunction advanceClockPast(target: Db, rows: RawOpRow[]): void {\n let newest: Hlc | undefined;\n for (const row of rows) {\n let h: Hlc;\n try {\n h = parseHlc(row.hlc);\n } catch {\n continue; // an unparseable HLC cannot order anything\n }\n if (\n !newest ||\n h.wallMs > newest.wallMs ||\n (h.wallMs === newest.wallMs && h.counter > newest.counter)\n ) {\n newest = h;\n }\n }\n if (!newest) return;\n target\n .prepare(\n `UPDATE machine_identity SET last_wall = @wall, last_counter = @counter\n WHERE id = 1 AND (last_wall < @wall OR (last_wall = @wall AND last_counter < @counter))`,\n )\n .run({ wall: newest.wallMs, counter: newest.counter });\n}\n\n/** True iff both paths name the same file on disk. Guards the\n * rebuild-onto-itself case when the caller passes a different string\n * for the same file (a symlink, or ./x vs x). */\nfunction sameInode(a: string, b: string): boolean {\n try {\n const sa = statSync(a);\n const sb = statSync(b);\n return sa.ino === sb.ino && sa.dev === sb.dev;\n } catch {\n // A path we cannot stat is not the source by definition.\n return false;\n }\n}\n","// mu — drift detection: is the projection still faithful to the ops log?\n//\n// WHY THIS IS LOAD-BEARING, NOT DIAGNOSTICS GARNISH\n// ------------------------------------------------\n// mu collapsed four independent change-recording mechanisms into ONE\n// ops log. The upside is coherence. The cost, stated plainly in\n// docs/VISION.md § 2b, is that a capture bug is no longer \"sync is\n// broken\" — it is sync AND history broken,\n// simultaneously and silently, because all four are projections of the\n// same table.\n//\n// This module is what converts that from a hazard into a DETECTABLE\n// CONDITION. It is the reason the consolidation was defensible at all,\n// so it is production code: it must name what diverged precisely enough\n// to act on at 3am, and it must not cry wolf on shapes that are\n// legitimately asymmetric.\n//\n// HOW IT WORKS\n// ------------\n// Rebuild the log into a throwaway DB (src/rebuild.ts, whose target path\n// is a parameter precisely so this can point it at a temp file), then\n// diff the rebuilt tables against the live ones. The log is canonical by\n// definition, so any divergence means either capture missed a mutation\n// or apply is lossy. Both are bugs; neither is recoverable by guessing.\n//\n// TWO TIERS, AND WHY\n// ------------------\n// Measured on this machine (better-sqlite3 3.49, NVMe):\n//\n// tasks ops rebuild\n// 100 353 258ms\n// 500 1742 1146ms\n// 1000 3461 2178ms\n//\n// Linear in ops, ~0.6ms per op. `mu doctor` is expected to be fast and\n// is run reflexively, so a 2s+ hit on a realistic DB is not acceptable\n// as a default. Hence:\n//\n// DEFAULT (`mu doctor`) — `checkCheapDriftInvariant`, ~1ms: every\n// live row must have at least one op naming\n// its key. Catches an uncaptured INSERT or a\n// row that exists with no history at all,\n// which is the most common shape of a\n// capture bug (a new mutation path that\n// bypassed the triggers).\n// DEEP (`mu doctor --deep`) — full rebuild + field-level diff. Catches\n// everything, including an uncaptured UPDATE,\n// which the cheap check is structurally blind\n// to because the key still has ops.\n//\n// That blindness is real and measured, not assumed: an uncaptured UPDATE\n// leaves the cheap invariant reporting zero orphans. So the cheap check\n// is a smoke alarm, not a proof, and the default run says so by pointing\n// at --deep.\n\nimport { mkdtempSync, rmSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { type Db, openDb } from \"./db.js\";\nimport { rebuildInto } from \"./rebuild.js\";\n\n/** One field-level divergence between the live tables and the rebuild. */\nexport interface DriftRecord {\n /** Portable table the divergence is in. */\n table: string;\n /** NATURAL key of the row (never a surrogate id), so the report is\n * meaningful to an operator and stable across machines. */\n key: string;\n /** Field that differs, or a marker for whole-row presence:\n * '<row>' means the row exists on one side only. */\n field: string;\n /** Value in the LIVE tables — what mu is currently showing. */\n live: string | null;\n /** Value the ops log says it should be. The log is canonical. */\n expected: string | null;\n /** Which side is missing the row entirely, when field is '<row>'. */\n presence?: \"missing-in-live\" | \"missing-in-rebuild\";\n}\n\nexport interface DriftReport {\n /** True iff the projection matches the log exactly. */\n clean: boolean;\n /** Every divergence found, capped (see DRIFT_REPORT_CAP). */\n records: readonly DriftRecord[];\n /** Total divergences found, which may exceed records.length. */\n totalDrift: number;\n /** Rows compared, per table. Context for \"clean\" — a clean report on\n * an empty DB proves less than one on 900 rows. */\n rowsCompared: Record<string, number>;\n /** Wall-clock cost, so `mu doctor --deep` can be honest about it. */\n elapsedMs: number;\n}\n\n/** Cap on reported records. A systematic capture bug can diverge every\n * row; printing 900 lines buries the signal. The count is always exact\n * (`totalDrift`) even when the list is truncated. */\nexport const DRIFT_REPORT_CAP = 20;\n\n/** Result of the cheap invariant that runs in the DEFAULT doctor. */\nexport interface CheapDriftReport {\n clean: boolean;\n /** Live rows with NO op naming their key — i.e. rows whose existence\n * the log cannot explain. */\n unexplainedRows: readonly { table: string; key: string }[];\n totalUnexplained: number;\n elapsedMs: number;\n}\n\n// ─── the cheap invariant (default doctor) ─────────────────────────────\n\n/**\n * Every live row must have at least one op naming its natural key.\n *\n * Four indexed NOT EXISTS scans, no rebuild, no temp file: ~10 ms on a\n * 2.3k-task, 10.7k-note, 67k-op DB. Cheap enough to run on every `mu\n * doctor` and the TUI slow tick.\n *\n * WHAT IT CATCHES: a row that exists with no history — an uncaptured\n * INSERT, or a mutation path that bypassed the triggers entirely.\n *\n * WHAT IT CANNOT CATCH, by construction: an uncaptured UPDATE. The key\n * still has ops from the original insert, so the invariant holds while\n * the field value has silently diverged. Verified empirically. Only the\n * full rebuild-diff finds that, which is exactly why `--deep` exists and\n * why the default run points at it rather than claiming to be a proof.\n */\nexport function checkCheapDriftInvariant(db: Db): CheapDriftReport {\n const started = Date.now();\n const unexplained: { table: string; key: string }[] = [];\n\n // One query per portable table, each resolving the row to its natural\n // key so the report is actionable.\n const probes: Array<{ table: string; sql: string }> = [\n {\n table: \"workstreams\",\n sql: `SELECT w.name AS key FROM workstreams w\n WHERE NOT EXISTS (\n SELECT 1 FROM ops o WHERE o.entity = 'workstream' AND o.key = w.name)`,\n },\n {\n table: \"tasks\",\n sql: `SELECT w.name || '/' || t.local_id AS key\n FROM tasks t JOIN workstreams w ON w.id = t.workstream_id\n WHERE NOT EXISTS (\n SELECT 1 FROM ops o\n WHERE o.entity = 'task' AND o.key = w.name || '/' || t.local_id)`,\n },\n {\n table: \"task_edges\",\n sql: `SELECT wf.name || '/' || f.local_id || '->' || wt.name || '/' || t.local_id AS key\n FROM task_edges e\n JOIN tasks f ON f.id = e.from_task_id\n JOIN tasks t ON t.id = e.to_task_id\n JOIN workstreams wf ON wf.id = f.workstream_id\n JOIN workstreams wt ON wt.id = t.workstream_id\n WHERE NOT EXISTS (\n SELECT 1 FROM ops o\n WHERE o.entity = 'edge'\n AND o.key = wf.name || '/' || f.local_id || '->' || wt.name || '/' || t.local_id)`,\n },\n {\n // Notes are keyed <task-key>#<origin-id> and the origin id is the\n // AUTHORING machine's surrogate id, which need not match ours (see\n // src/apply.ts § syncNotes). So match on the task-key PREFIX\n // rather than the exact key: the question here is \"does the log\n // know about a note on this task at all\", not \"which note\".\n //\n // Express the prefix as an indexed half-open range. A correlated\n // `LIKE task_key || '#%'` made SQLite scan every note op for every\n // live note (seconds on the dogfood DB); '#'..'$' contains exactly\n // the strings beginning with `task_key || '#'` because task ids\n // cannot contain either delimiter.\n //\n // The answer is per TASK, so probe each task that has notes once\n // (2.3k probes, not 10.7k on the dogfood DB), then list the notes\n // of the tasks that fail. MATERIALIZED stops SQLite flattening the\n // probe back into a per-note subquery.\n table: \"task_notes\",\n sql: `WITH bare AS MATERIALIZED (\n SELECT t.id AS task_id, w.name || '/' || t.local_id AS task_key\n FROM tasks t\n JOIN workstreams w ON w.id = t.workstream_id\n WHERE t.id IN (SELECT task_id FROM task_notes)\n AND NOT EXISTS (\n SELECT 1 FROM ops o\n WHERE o.entity = 'note'\n AND o.key >= w.name || '/' || t.local_id || '#'\n AND o.key < w.name || '/' || t.local_id || '$'))\n SELECT b.task_key || '#' || n.id AS key\n FROM bare b\n JOIN task_notes n ON n.task_id = b.task_id\n ORDER BY n.task_id, n.id`,\n },\n ];\n\n for (const probe of probes) {\n const rows = db.prepare(probe.sql).all() as { key: string }[];\n for (const row of rows) unexplained.push({ table: probe.table, key: row.key });\n }\n\n return {\n clean: unexplained.length === 0,\n unexplainedRows: unexplained.slice(0, DRIFT_REPORT_CAP),\n totalUnexplained: unexplained.length,\n elapsedMs: Date.now() - started,\n };\n}\n\n// ─── the deep check (rebuild + diff) ──────────────────────────────────\n\n/** Columns compared per table, keyed by natural key.\n *\n * DELIBERATE OMISSIONS, each of which would otherwise be a false\n * positive:\n *\n * surrogate ids (`tasks.id`, `task_notes.id`) — assigned by\n * AUTOINCREMENT in replay order, which need not\n * match the original insert order. The natural key\n * is the identity; the rowid is an implementation\n * detail.\n * owner_id — an FK into machine-local `agents`, so it is\n * captured but never APPLIED (src/apply.ts strips\n * it: a peer's value would violate the FK). A\n * rebuild therefore legitimately has NULL owners\n * while the live DB has claims. Comparing it would\n * make every claimed task report drift.\n * created_at on\n * task_notes/edges — kept, since capture records it and apply\n * replays it verbatim.\n */\nconst COMPARED: Record<string, readonly string[]> = {\n workstreams: [\"created_at\", \"torn_down_at\"],\n tasks: [\n \"title\",\n \"status\",\n \"substate\",\n \"impact\",\n \"effort_days\",\n \"scored\",\n \"dispatch_host\",\n \"kind\",\n \"wave\",\n \"created_at\",\n \"updated_at\",\n ],\n task_notes: [\"author\", \"content\", \"created_at\", \"kind\"],\n task_edges: [\"created_at\"],\n};\n\n/** SELECTs that project each portable table to (key, ...COMPARED) so\n * both sides can be compared by natural key. */\nconst SNAPSHOT_SQL: Record<string, string> = {\n workstreams: `SELECT w.name AS key, w.created_at, w.torn_down_at\n FROM workstreams w`,\n tasks: `SELECT w.name || '/' || t.local_id AS key,\n t.title, t.status, t.substate, t.impact, t.effort_days, t.scored,\n t.dispatch_host, t.kind, t.wave, t.created_at, t.updated_at\n FROM tasks t JOIN workstreams w ON w.id = t.workstream_id`,\n // Notes are a GROW-ONLY SET whose local surrogate id is not portable,\n // so identity for diffing is (task, author, content, created_at) —\n // exactly the identity syncNotes (src/apply.ts) folds notes by. Using the\n // '#<id>' key here would report drift on every note that replayed to a\n // different rowid, which is normal and not drift.\n //\n // char(31) (ASCII Unit Separator) joins the parts: it cannot occur in a\n // workstream/task id and is vanishingly unlikely in note prose, so two\n // distinct notes cannot collide into one composite key. A literal NUL\n // would be the textbook choice but SQLite truncates TEXT at NUL.\n task_notes: `SELECT w.name || '/' || t.local_id || char(31) ||\n COALESCE(n.author, '') || char(31) || n.content || char(31) ||\n n.created_at AS key,\n n.author, n.content, n.created_at, n.kind\n FROM task_notes n\n JOIN tasks t ON t.id = n.task_id\n JOIN workstreams w ON w.id = t.workstream_id`,\n task_edges: `SELECT wf.name || '/' || f.local_id || '->' || wt.name || '/' || t.local_id AS key,\n e.created_at\n FROM task_edges e\n JOIN tasks f ON f.id = e.from_task_id\n JOIN tasks t ON t.id = e.to_task_id\n JOIN workstreams wf ON wf.id = f.workstream_id\n JOIN workstreams wt ON wt.id = t.workstream_id`,\n};\n\ntype Row = Record<string, string | number | null>;\n\nfunction snapshot(db: Db, table: string): Map<string, Row> {\n const sql = SNAPSHOT_SQL[table];\n if (sql === undefined) throw new Error(`no drift snapshot defined for table ${table}`);\n const out = new Map<string, Row>();\n for (const row of db.prepare(sql).all() as Row[]) {\n const key = row.key;\n if (typeof key !== \"string\") continue;\n out.set(key, row);\n }\n return out;\n}\n\n/** Render a value for the report. Distinguishes SQL NULL from the string\n * \"null\", which matters when the drift IS a set-to-NULL. */\nfunction show(v: string | number | null | undefined): string | null {\n if (v === null || v === undefined) return null;\n return String(v);\n}\n\n/**\n * Rebuild the log into a temp DB and diff it against the live tables.\n *\n * Any divergence is a bug in capture (a mutation that left no op) or in\n * apply (an op that does not reproduce its mutation). The log is\n * canonical, so `expected` is always the rebuilt value.\n *\n * SYNCHRONOUS, matching rebuildInto / applyOp: the op context is a\n * per-connection temp table, so interleaved async scopes would clobber\n * each other's capture-suppression flag.\n *\n * Cleans up its temp directory even on throw — a doctor run that leaked\n * a DB copy per invocation into /tmp would be its own bug.\n */\nexport function checkDrift(db: Db): DriftReport {\n const started = Date.now();\n const dir = mkdtempSync(join(tmpdir(), \"mu-drift-\"));\n const target = join(dir, \"rebuilt.db\");\n\n try {\n rebuildInto(db, { targetPath: target });\n const rebuilt = openDb({ path: target });\n try {\n const records: DriftRecord[] = [];\n const rowsCompared: Record<string, number> = {};\n let total = 0;\n\n const push = (record: DriftRecord): void => {\n total += 1;\n if (records.length < DRIFT_REPORT_CAP) records.push(record);\n };\n\n for (const table of Object.keys(SNAPSHOT_SQL)) {\n const live = snapshot(db, table);\n const expected = snapshot(rebuilt, table);\n rowsCompared[table] = live.size;\n\n for (const [key, liveRow] of live) {\n const expectedRow = expected.get(key);\n if (expectedRow === undefined) {\n // Live has a row the log cannot account for: capture missed\n // its creation, or a tombstone that should not have applied.\n push({\n table,\n key,\n field: \"<row>\",\n live: \"present\",\n expected: null,\n presence: \"missing-in-rebuild\",\n });\n continue;\n }\n for (const field of COMPARED[table] ?? []) {\n const a = liveRow[field];\n const b = expectedRow[field];\n // Compare rendered values so 1 and 1.0 (INTEGER vs REAL\n // affinity across a replay) do not read as drift.\n if (show(a) !== show(b)) {\n push({ table, key, field, live: show(a), expected: show(b) });\n }\n }\n }\n\n for (const key of expected.keys()) {\n if (live.has(key)) continue;\n // The log says this row should exist but it is gone from live:\n // a delete that left no tombstone.\n push({\n table,\n key,\n field: \"<row>\",\n live: null,\n expected: \"present\",\n presence: \"missing-in-live\",\n });\n }\n }\n\n return {\n clean: total === 0,\n records,\n totalDrift: total,\n rowsCompared,\n elapsedMs: Date.now() - started,\n };\n } finally {\n rebuilt.close();\n }\n } finally {\n rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 25 });\n }\n}\n\n/** One-line-per-record rendering shared by the CLI and the TUI popup, so\n * the wording of a drift report lives in exactly one place. */\nexport function formatDriftRecord(record: DriftRecord): string {\n if (record.field === \"<row>\") {\n return record.presence === \"missing-in-live\"\n ? `${record.table} ${record.key}: row MISSING from live tables (the log says it exists)`\n : `${record.table} ${record.key}: row present in live tables but the log cannot explain it`;\n }\n const live = record.live === null ? \"NULL\" : record.live;\n const expected = record.expected === null ? \"NULL\" : record.expected;\n return `${record.table} ${record.key}.${record.field}: live=${live} log=${expected}`;\n}\n\n/** What an operator should DO about drift. Detection without remediation\n * is just an alarm; this is the part that matters at 3am.\n *\n * Deliberately does NOT tell them to swap the rebuild in blindly. Drift\n * means one of the two sides is wrong and we cannot know which from\n * here: if capture missed a mutation, the LIVE tables hold the truth and\n * the log is incomplete, so rebuilding would DISCARD real work. If apply\n * is lossy, the log is right. So the guidance is: capture the evidence,\n * then choose deliberately. */\nexport function driftRemediation(): readonly string[] {\n return [\n \"Drift means the ops log and the live tables disagree. One of them is wrong.\",\n \"\",\n \" * If CAPTURE missed a mutation, the LIVE tables hold work the log never\",\n \" recorded. Rebuilding would DISCARD it. Do not rebuild reflexively.\",\n \" * If APPLY is lossy, the log is authoritative and a rebuild is the fix.\",\n \"\",\n \"Do this, in order:\",\n \" 1. Back up first, before anything else: mu db backup /tmp/mu-drift-evidence.db\",\n \" 2. Materialize what the log believes: mu rebuild /tmp/mu-rebuilt.db\",\n \" 3. Compare the two by hand for the keys named above, and decide which\",\n \" side is correct. `mu db query` against both files is the fastest way.\",\n \" 4. Report it: drift is a capture/apply BUG, not operator error. The\",\n \" named table/key/field above is the reproduction.\",\n ];\n}\n\n// ─── the typed error ──────────────────────────────────────────────────\n\n/**\n * Thrown by `mu doctor` when drift is found, so the verb exits non-zero\n * and a CI job or a wrapper script notices.\n *\n * Drift is not operator error and not a transient condition: it means the\n * ops log and the tables disagree, which is a capture or apply BUG. An\n * exit code is how that reaches automation; the printed report is how it\n * reaches a human.\n */\nexport class DriftDetectedError extends Error {\n constructor(\n readonly totalDrift: number,\n readonly records: readonly DriftRecord[],\n ) {\n super(\n `ops-log drift: ${totalDrift} divergence${totalDrift === 1 ? \"\" : \"s\"} between the live tables and the ops log`,\n );\n this.name = \"DriftDetectedError\";\n }\n}\n","// mu — mixed-fleet hazard detection.\n//\n// Three environment conditions that silently corrupt or diverge state on\n// a multi-machine fleet. All three are cheap, pure-ish checks that run in\n// the DEFAULT `mu doctor`, because unlike drift they cost microseconds\n// and unlike drift they are PREVENTABLE — the operator can fix each one\n// before it costs them data.\n//\n// (a) DB inside the sync dir -> corruption. THE footgun of the design.\n// (b) DB on a network mount -> broken WAL locking.\n// (c) case-colliding names -> collide on macOS, coexist on Linux.\n//\n// The checks that need MU_SYNC_DIR read it if set and no-op otherwise,\n// so a single-machine install pays nothing.\n\nimport { existsSync, lstatSync, readlinkSync, realpathSync, statfsSync } from \"node:fs\";\nimport { basename, dirname, join, resolve, sep } from \"node:path\";\nimport type { Db } from \"./db.js\";\nimport { countUnpublishedOps, ownSegmentForeignLine } from \"./segments.js\";\nimport { foreignVersionMessage } from \"./sync.js\";\n\nexport type HazardSeverity = \"ok\" | \"warn\" | \"fail\";\n\nexport interface FleetHazard {\n /** Stable token, used as the doctor row label. */\n name: string;\n severity: HazardSeverity;\n /** One-line summary for the row. */\n detail: string;\n /** Multi-line explanation + remediation, shown when non-ok. */\n remediation?: readonly string[];\n}\n\n/**\n * `mu doctor` found at least one `fail`-severity row. Thrown after the\n * whole report is printed (or the --json payload emitted) so scripts and\n * CI see a non-zero exit; maps to exit 5 like drift, because a `fail`\n * row means the substrate is unsafe, not that a hint is pending.\n */\nexport class HazardFailError extends Error {\n override readonly name = \"HazardFailError\";\n constructor(readonly failedRows: readonly string[]) {\n super(\n `doctor: ${failedRows.length} row${failedRows.length === 1 ? \"\" : \"s\"} failed (${failedRows.join(\", \")}); see the remediation above`,\n );\n }\n}\n\n/**\n * Raised by `handle()` before the DB is opened when it would live inside\n * MU_SYNC_DIR. Exit 4 (conflict): the two settings contradict each other\n * and only the operator can pick which one moves. Nothing was written.\n * `mu doctor` still reports the same condition as a `db-vs-sync` row.\n */\nexport class DbInsideSyncDirError extends Error {\n override readonly name = \"DbInsideSyncDirError\";\n constructor(\n readonly dbPath: string,\n readonly syncDir: string,\n ) {\n super(\n `DB ${dbPath} is inside MU_SYNC_DIR ${syncDir}: move it out (WAL files do not sync safely)`,\n );\n }\n}\n\n// ─── (a) DB inside the sync dir ───────────────────────────────────────\n\n/**\n * `path` with every EXISTING component resolved through symlinks, and the\n * not-yet-existing tail appended verbatim. Nothing is created. A first\n * run (no DB file, maybe no directory) therefore still canonicalises via\n * its nearest existing ancestor, so a symlinked parent cannot hide a\n * location inside the sync dir.\n */\nexport function canonicalPath(path: string, hops = 0): string {\n const abs = resolve(path);\n const tail: string[] = [];\n let cur = abs;\n for (;;) {\n try {\n return join(realpathSync(cur), ...tail);\n } catch {\n // A dangling link: opening it creates its target, so follow it.\n try {\n if (hops < 32 && lstatSync(cur).isSymbolicLink()) {\n return join(canonicalPath(resolve(dirname(cur), readlinkSync(cur)), hops + 1), ...tail);\n }\n } catch {\n // not a link either: plain missing\n }\n // Missing: resolve the parent and re-append.\n const parent = dirname(cur);\n if (parent === cur) return abs;\n tail.unshift(basename(cur));\n cur = parent;\n }\n }\n}\n\n/**\n * True iff `child` is inside `parent` (or is `parent`).\n *\n * Both sides are canonicalised (symlinks resolved through the nearest\n * existing ancestor) and the check stays path-based: it must fire even\n * when the DB file does not exist yet, so it cannot rely on inode\n * identity. A separator is appended so `/sync-data` does not read as the\n * parent of `/sync-database`.\n */\nexport function isPathInside(child: string, parent: string): boolean {\n const c = canonicalPath(child);\n const p = canonicalPath(parent);\n if (c === p) return true;\n return c.startsWith(p.endsWith(sep) ? p : p + sep);\n}\n\n/**\n * THE footgun of the whole sync design, and the reason it is `fail` rather\n * than `warn`.\n *\n * Sync tools (Syncthing, Dropbox, iCloud, rsync loops) copy files\n * whole-file and out of order. A live SQLite DB in WAL mode is THREE\n * files — `mu.db`, `mu.db-wal`, `mu.db-shm` — whose mutual consistency is\n * the entire basis of durability. A sync daemon that copies the main file\n * while the WAL is mid-checkpoint, or that resurrects a stale `-wal` from\n * another machine, produces a DB that opens fine and is silently corrupt.\n * Two machines writing the same synced file is worse still: last-writer\n * wins on the FILE, so an entire machine's history vanishes.\n *\n * mu's sync design specifically avoids this by shipping append-only\n * per-machine SEGMENTS (one writer per file, never contended) rather than\n * the DB itself. Putting the DB inside the sync dir defeats that on\n * purpose-built-to-be-safe transport, so it is a hard failure.\n */\nexport function checkDbInsideSyncDir(dbPath: string, syncDir: string | undefined): FleetHazard {\n if (syncDir === undefined || syncDir.trim() === \"\") {\n return {\n name: \"db-vs-sync\",\n severity: \"ok\",\n detail: \"MU_SYNC_DIR not set (no sync configured)\",\n };\n }\n if (!isPathInside(dbPath, syncDir)) {\n return { name: \"db-vs-sync\", severity: \"ok\", detail: \"DB is outside the sync dir\" };\n }\n return {\n name: \"db-vs-sync\",\n severity: \"fail\",\n detail: `DB is INSIDE MU_SYNC_DIR — this WILL corrupt it (${dbPath})`,\n remediation: [\n \"The mu database must never live inside the synced folder.\",\n \"\",\n \"A live WAL-mode SQLite DB is three files (mu.db, -wal, -shm) whose mutual\",\n \"consistency is the basis of durability. File-sync tools copy whole files,\",\n \"out of order, and across machines: a stale -wal resurrected from a peer, or\",\n \"a main file copied mid-checkpoint, yields a DB that OPENS FINE and is\",\n \"silently corrupt. Two machines writing the same synced file is worse — last\",\n \"writer wins on the whole FILE, so one machine's entire history disappears.\",\n \"\",\n \"mu syncs append-only per-machine SEGMENTS precisely to avoid this: one\",\n \"writer per file, never contended, so any file-mover is adequate transport.\",\n \"\",\n \"Fix: move the DB out of the sync dir, e.g.\",\n \" export MU_DB_PATH=$HOME/.local/state/mu-next/mu.db\",\n \"and keep MU_SYNC_DIR pointing at the shared folder for segments only.\",\n ],\n };\n}\n\n// ─── (b) DB on a network mount ────────────────────────────────────────\n\n/** Linux `statfs.f_type` magic numbers for filesystems where POSIX\n * advisory locking is unreliable or absent. SQLite's WAL mode needs\n * working locks AND shared memory; neither is dependable here.\n *\n * Values from linux/magic.h. Kept as a table rather than inline so the\n * list is auditable and extendable. */\nconst NETWORK_FS_MAGIC = new Map<number, string>([\n // Every value here is transcribed from linux/magic.h, not recalled.\n // An invented magic is worse than a missing one: it would either never\n // match (silent no-op) or match the wrong filesystem and warn falsely.\n [0x6969, \"NFS\"], // NFS_SUPER_MAGIC\n [0xff534d42, \"CIFS/SMB\"], // CIFS_SUPER_MAGIC\n [0xfe534d42, \"SMB2\"], // SMB2_SUPER_MAGIC\n [0x517b, \"SMBFS\"], // SMB_SUPER_MAGIC\n [0x65735546, \"FUSE (may be sshfs/rclone/cloud drive)\"], // FUSE_SUPER_MAGIC\n [0x00c36400, \"Ceph\"], // CEPH_SUPER_MAGIC\n]);\n\n/** Result of a filesystem probe. `unknown` is a first-class outcome:\n * telling the operator \"cannot determine\" is honest, whereas claiming\n * \"ok\" on a platform we cannot inspect would be a false assurance. */\nexport interface FsProbe {\n kind: \"local\" | \"network\" | \"unknown\";\n /** Human label for the detected fs, when known. */\n label: string;\n}\n\n/**\n * Classify the filesystem a path lives on.\n *\n * PORTABILITY, and why this degrades rather than guesses:\n *\n * Linux — `statfsSync().type` is a documented magic number, so the\n * classification is exact.\n * macOS — `f_type` is a small driver INDEX, not a stable magic, so\n * the same number means different things across releases.\n * Comparing it would produce confident nonsense, so we do\n * not; macOS falls through to `unknown`.\n * Other — `unknown`.\n *\n * Exported separately from the check so it can be unit-tested against\n * SYNTHETIC input: mounting NFS in a test suite is not feasible, so the\n * tests exercise `classifyFsType` (pure, takes the magic number) rather\n * than the syscall. Stated plainly because an untested detector is worse\n * than no detector.\n */\nexport function classifyFsType(magic: number, platform: string = process.platform): FsProbe {\n if (platform !== \"linux\") {\n // See above: f_type is not a portable magic off Linux.\n return { kind: \"unknown\", label: `unrecognised (${platform})` };\n }\n const network = NETWORK_FS_MAGIC.get(magic);\n if (network !== undefined) return { kind: \"network\", label: network };\n return { kind: \"local\", label: `local (0x${magic.toString(16)})` };\n}\n\n/** Probe the real filesystem for a path, falling back to `unknown` when\n * the syscall is unavailable or the path does not exist yet. */\nexport function probeFilesystem(path: string): FsProbe {\n try {\n // Probe the nearest existing ancestor: the DB file may not exist on a\n // first run, but its directory tells us the same thing.\n let probeTarget = resolve(path);\n while (!existsSync(probeTarget)) {\n const parent = resolve(probeTarget, \"..\");\n if (parent === probeTarget) break;\n probeTarget = parent;\n }\n const stats = statfsSync(probeTarget);\n return classifyFsType(Number(stats.type));\n } catch {\n return { kind: \"unknown\", label: \"probe failed\" };\n }\n}\n\n/**\n * WARN rather than fail on a network mount.\n *\n * Warn, not fail, because it is not always fatal: a single machine using\n * an NFS home with no concurrent access often works, and refusing\n * outright would lock such an operator out of their own tool. But it IS\n * the second-most-common corruption cause after (a), because WAL needs\n * both advisory locking and a shared-memory file, and NFS/SMB/sshfs\n * deliver neither reliably. Symptoms are 'database is locked' under no\n * contention, or silent corruption under real contention.\n */\nexport function checkNetworkMount(\n dbPath: string,\n probe: FsProbe = probeFilesystem(dbPath),\n): FleetHazard {\n if (probe.kind === \"network\") {\n return {\n name: \"db-filesystem\",\n severity: \"warn\",\n detail: `DB is on a network mount (${probe.label}) — WAL locking is unreliable there`,\n remediation: [\n `The DB appears to live on ${probe.label}.`,\n \"\",\n \"SQLite's WAL mode needs working POSIX advisory locks AND a shared-memory\",\n \"file. NFS, SMB/CIFS and FUSE mounts (sshfs, rclone, cloud drives) provide\",\n \"neither dependably. Expect 'database is locked' with no contention, or\",\n \"silent corruption with real contention from parallel mu invocations.\",\n \"\",\n \"Fix: keep the DB on local disk and sync SEGMENTS instead —\",\n \" export MU_DB_PATH=$HOME/.local/state/mu-next/mu.db\",\n \"That is what the segment design is for: append-only, single-writer files\",\n \"that any file-mover can carry safely.\",\n ],\n };\n }\n if (probe.kind === \"unknown\") {\n return {\n name: \"db-filesystem\",\n severity: \"ok\",\n detail: `filesystem not classifiable on this platform (${probe.label}); assuming local`,\n };\n }\n return { name: \"db-filesystem\", severity: \"ok\", detail: `DB is on ${probe.label}` };\n}\n\n// ─── (c) case-colliding workstream names ──────────────────────────────\n\nexport interface CaseCollision {\n /** The names, as stored, that fold to the same lowercase form. */\n names: readonly string[];\n /** The shared case-folded form. */\n folded: string;\n}\n\n/**\n * Workstream names differing only by case.\n *\n * On ext4 these coexist happily. On APFS (macOS default,\n * case-INSENSITIVE though case-preserving) and on NTFS they collide, so\n * the same fleet reaches different states depending on which machine\n * applies an op first. Concretely: `workstreams.name` is UNIQUE and IS\n * the tmux session name, so on a Mac 'Foo' and 'foo' are one session and\n * one directory but two DB rows — and every worktree path derived from\n * the name aliases onto one directory.\n *\n * Detected in the DB rather than at write time on purpose: the rows may\n * have been created on Linux and only become a hazard when the fleet\n * gains a Mac, so this must be a standing check rather than a validation.\n *\n * SQL-side `LOWER()` is ASCII-only in SQLite, which is the right\n * comparison here: workstream names are already constrained to\n * `[a-z0-9_-]` by `isValidWorkstreamName`, so any collision within the\n * legal charset is ASCII. Names that predate the rule (or were inserted\n * via `mu sql`) still get caught because we fold in JS too.\n */\nexport function findCaseCollisions(db: Db): CaseCollision[] {\n const rows = db.prepare(\"SELECT name FROM workstreams ORDER BY name\").all() as {\n name: string;\n }[];\n const byFolded = new Map<string, string[]>();\n for (const row of rows) {\n // toLocaleLowerCase would be locale-dependent (Turkish dotless i);\n // toLowerCase is stable, which is what a cross-machine check needs.\n const folded = row.name.toLowerCase();\n const bucket = byFolded.get(folded);\n if (bucket === undefined) byFolded.set(folded, [row.name]);\n else bucket.push(row.name);\n }\n const collisions: CaseCollision[] = [];\n for (const [folded, names] of byFolded) {\n if (names.length > 1) collisions.push({ folded, names });\n }\n return collisions;\n}\n\nexport function checkCaseCollisions(db: Db): FleetHazard {\n const collisions = findCaseCollisions(db);\n if (collisions.length === 0) {\n return {\n name: \"name-case\",\n severity: \"ok\",\n detail: \"no case-colliding workstream names\",\n };\n }\n const shown = collisions\n .slice(0, 5)\n .map((c) => c.names.join(\" / \"))\n .join(\", \");\n return {\n name: \"name-case\",\n severity: \"warn\",\n detail: `${collisions.length} case-colliding workstream name(s): ${shown}`,\n remediation: [\n \"These workstream names differ only by letter case:\",\n ...collisions.map((c) => ` ${c.names.join(\" / \")}`),\n \"\",\n \"They coexist on Linux (ext4 is case-sensitive) but COLLIDE on macOS (APFS\",\n \"is case-insensitive) and on Windows (NTFS). Because a workstream name IS a\",\n \"tmux session name and seeds every worktree path, a Mac in the fleet sees\",\n \"one session and one directory where Linux sees two — so the fleet reaches\",\n \"different states depending on which machine applies an op first.\",\n \"\",\n \"Fix: rename one side to a distinct name before adding a Mac to the fleet.\",\n \"There is no in-place rename verb; back the DB up, re-init under the new\",\n \"name, and tear down the old one:\",\n \" mu db backup <file>\",\n \" mu workstream init <new-name>\",\n \" mu workstream teardown <old-name> # preview; then apply with --if <rev>\",\n ],\n };\n}\n\n// ─── the aggregate ────────────────────────────────────────────────────\n\n/**\n * Run all three mixed-fleet checks. Cheap enough for the default doctor:\n * two path/string comparisons, one statfs, one indexed table scan.\n */\nexport function checkFleetHazards(\n db: Db,\n opts: { dbPath: string; syncDir?: string | undefined } = { dbPath: \"\" },\n): FleetHazard[] {\n const syncDir = opts.syncDir !== undefined ? opts.syncDir : process.env.MU_SYNC_DIR;\n return [\n checkDbInsideSyncDir(opts.dbPath, syncDir),\n checkNetworkMount(opts.dbPath),\n checkCaseCollisions(db),\n ];\n}\n\n// ─── (d) own segment written by a newer mu ────────────────────────────\n\n/**\n * Own segment holds a line of a version this build cannot read: it is\n * read-only here, so this machine's new ops stay in SQLite. Not part of\n * `checkFleetHazards`: it reads the whole segment, which the TUI's\n * per-tick summary must not do. `mu doctor` adds it.\n */\nexport function checkSegmentVersion(db: Db, syncDir: string | undefined): FleetHazard {\n if (syncDir === undefined || syncDir.trim() === \"\") {\n return { name: \"segment-version\", severity: \"ok\", detail: \"MU_SYNC_DIR not set\" };\n }\n const found = ownSegmentForeignLine(db, syncDir);\n if (found === null) {\n return { name: \"segment-version\", severity: \"ok\", detail: \"own segment readable by this mu\" };\n }\n return {\n name: \"segment-version\",\n severity: \"warn\",\n detail: foreignVersionMessage({ segmentPath: found.path, foreignVersion: found.version }),\n remediation: [\n `Line ${found.line} of the segment was written by a newer mu. This mu appends nothing`,\n \"and repairs nothing there; new ops stay in the local DB and are written\",\n \"once mu is upgraded on this machine.\",\n ],\n };\n}\n\n// ─── (e) states the local-write close guards would refuse ─────────────\n\n/** Ids listed per check. */\nconst GUARD_LIST_CAP = 10;\n\nfunction listIds(rows: { id: string }[]): string {\n const shown = rows.slice(0, GUARD_LIST_CAP).map((r) => r.id);\n return rows.length > GUARD_LIST_CAP\n ? `${shown.join(\", \")}, … (${rows.length} total)`\n : shown.join(\", \");\n}\n\n/**\n * Agent rows that outlive their workstream: it is torn down (here, with the\n * pane still alive, or by a peer) and the row is still registered. One warn\n * row; the fix is `mu agent close`, which kills the pane and deletes the\n * row only once the pane is gone. Cheap (one indexed join): `mu doctor` runs it.\n */\nexport function checkOrphanedAgents(db: Db): FleetHazard {\n const rows = db\n .prepare(\n `SELECT w.name AS ws, a.name AS agent, a.pane_id AS pane\n FROM agents a JOIN workstreams w ON w.id = a.workstream_id\n WHERE w.torn_down_at IS NOT NULL\n ORDER BY w.name, a.name`,\n )\n .all() as { ws: string; agent: string; pane: string }[];\n if (rows.length === 0) {\n return {\n name: \"orphaned-agents\",\n severity: \"ok\",\n detail: \"no agent rows in torn-down workstreams\",\n };\n }\n const shown = rows.slice(0, GUARD_LIST_CAP).map((r) => `${r.ws}/${r.agent} (${r.pane})`);\n return {\n name: \"orphaned-agents\",\n severity: \"warn\",\n detail: `${rows.length} agent row(s) in torn-down workstreams: ${shown.join(\", \")}${rows.length > GUARD_LIST_CAP ? \", …\" : \"\"}`,\n remediation: [\n \"Their panes may still run. Per row: `mu agent close <agent> -w <ws>` (kills the pane; keeps the row while it lives).\",\n ],\n };\n}\n\n/**\n * CLOSED tasks that the local-write guards (src/capture.ts) would never\n * have produced. Ingest accepts what the log says, so a peer can merge\n * into them (a close and its evidence are separate ops; a blocker can be\n * added or reopened after the close). Two warn rows, never fail: they\n * report a state, not a hazard to the substrate. Not part of\n * `checkFleetHazards` (the TUI's per-tick summary): two indexed-ish\n * scans of CLOSED tasks, run by `mu doctor` only.\n */\nexport function checkCloseGuards(db: Db): FleetHazard[] {\n const key = \"w.name || '/' || t.local_id\";\n const openBlockers = db\n .prepare(\n `SELECT ${key} AS id\n FROM tasks t JOIN workstreams w ON w.id = t.workstream_id AND w.torn_down_at IS NULL\n WHERE t.status = 'CLOSED' AND t.substate = 'done'\n AND EXISTS (SELECT 1 FROM blockers b WHERE b.task_id = t.id)\n ORDER BY 1`,\n )\n .all() as { id: string }[];\n const noEvidence = db\n .prepare(\n `SELECT ${key} AS id\n FROM tasks t JOIN workstreams w ON w.id = t.workstream_id AND w.torn_down_at IS NULL\n WHERE t.status = 'CLOSED'\n AND NOT EXISTS (SELECT 1 FROM task_notes n WHERE n.task_id = t.id AND n.kind = 'close')\n ORDER BY 1`,\n )\n .all() as { id: string }[];\n const row = (name: string, found: { id: string }[], what: string, fix: string): FleetHazard =>\n found.length === 0\n ? { name, severity: \"ok\", detail: `no ${what}` }\n : {\n name,\n severity: \"warn\",\n detail: `${found.length} ${what}: ${listIds(found)}`,\n remediation: [fix],\n };\n return [\n row(\n \"closed-blockers\",\n openBlockers,\n \"CLOSED/done task(s) with open blockers\",\n \"A peer merged these states (the local guard refuses them). Inspect with `mu task tree <id>`; reopen or close the blockers.\",\n ),\n row(\n \"closed-evidence\",\n noEvidence,\n \"CLOSED task(s) with no close note\",\n 'A peer merged the close without its evidence note. Per listed task: `mu task open <ws>/<id>`, then `mu task close <ws>/<id> --evidence \"<command + result>\"` (close its open blockers first).',\n ),\n ];\n}\n\n// ─── (f) own ops not yet in the own segment ───────────────────────────\n\n/**\n * Own synced ops that never reached this machine's segment: a flush gave\n * up on a busy lock (it prints one line and exits 0), the segment is\n * read-only (newer mu), or the sync dir was unwritable. Peers cannot see\n * these ops until a flush appends them. Not in `checkFleetHazards`: it\n * reads the segment tail, which the TUI's per-tick summary must not do.\n */\nexport function checkUnpublishedOps(db: Db, syncDir: string | undefined): FleetHazard {\n if (syncDir === undefined || syncDir.trim() === \"\") {\n return { name: \"unpublished-ops\", severity: \"ok\", detail: \"MU_SYNC_DIR not set\" };\n }\n const n = countUnpublishedOps(db, syncDir);\n if (n === 0) {\n return { name: \"unpublished-ops\", severity: \"ok\", detail: \"every own op is in the segment\" };\n }\n return {\n name: \"unpublished-ops\",\n severity: \"warn\",\n detail: `${n} own op(s) not yet in this machine's segment; peers cannot see them`,\n remediation: [\n \"Run `mu sync`: it flushes the backlog. If it reports the segment as locked,\",\n \"another mu process holds the lock (a stale one is broken after 30s).\",\n ],\n };\n}\n","// The one glyph vocabulary. Every symbol mu paints as *state* is\n// defined here and nowhere else.\n//\n// WHY ONE FILE\n// Glyphs were previously inlined at each render site: \"✓\" in the\n// Recent card, \"✓\" again in the Worktrees card, \"✓\" a third time in\n// the doctor card, \"⛓\" in Blocked, \"⚠\" in two CLI formatters. Three\n// spellings of \"ok\" drifted apart once already (the busy gear vs\n// murmur's play glyph), and each inline literal is a place the next\n// drift can start. One meaning, one constant.\n//\n// WHY ONE FAMILY\n// All state glyphs are classic Nerd Font `nf-fa-*` (Font Awesome 4)\n// codepoints. Two properties matter:\n//\n// 1. SINGLE CODEPOINT, SINGLE CELL. Unicode emoji like ⚙️ are two\n// codepoints (base + variation selector) that terminals draw one\n// cell wide. cli-table3 sizes columns by string length, so a\n// table mixing 1- and 2-codepoint glyphs misaligns. nf-fa slots\n// are private-use, all length-1, all one cell.\n// 2. STABLE SLOTS. Avoid `nf-md-*`: those PUA codepoints move\n// between Nerd Font releases and silently render as the wrong\n// icon (mu's `idle` once looked like a red shield under md-sleep).\n//\n// This matches murmur's dash (`src/dash-paint.ts` in ../murmur), which\n// drives the same tmux panes from the other side. `busy` here and\n// `running` there are both nf-fa-play on purpose: one symbol, one\n// meaning, across both surfaces.\n//\n// Requires a Nerd Font on the operator's terminal. mu's substrate is\n// pi, which assumes one. Without it every glyph renders as a\n// placeholder box — and the columns still line up, which is the bug\n// the family rule exists to prevent.\n//\n// NOT IN HERE\n// Typographic punctuation that carries no state: the `•` list bullet,\n// the `—` empty-cell dash, `…` truncation, box-drawing borders. Those\n// are text, not vocabulary, and stay at their call sites.\n\nimport type { RuntimeState } from \"./agent-state.js\";\n\nexport const AGENT_STATE_GLYPH: Record<RuntimeState, string> = {\n busy: \"\\uf04b\", // nf-fa-play\n needs_input: \"\\uf186\", // nf-fa-moon_o\n needs_permission: \"\\uf023\", // nf-fa-lock\n unknown: \"\\uf059\", // nf-fa-question_circle\n};\n\nexport function agentStateGlyph(state: RuntimeState): string {\n return AGENT_STATE_GLYPH[state] ?? GLYPH.unknown;\n}\n\n/**\n * Non-agent state glyphs, keyed by what they MEAN rather than what\n * they look like. A call site asks for `GLYPH.blocked`, never for a\n * chain — so re-pointing the chain is a one-line edit here.\n *\n * `ok` / `fail` / `warn` deliberately reuse the same codepoints as the\n * agent statuses they rhyme with (`free`, `terminated`): a check-circle\n * means \"fine\" whether the row is an agent, a worktree or a doctor\n * check.\n */\nexport const GLYPH = {\n /** Healthy, clean, passing, closed-successfully. */\n ok: \"\\uf058\", // nf-fa-check_circle\n /** Failed check. */\n fail: \"\\uf057\", // nf-fa-times_circle\n /** Needs attention but not broken (idle-but-assigned, stale warning). */\n warn: \"\\uf071\", // nf-fa-warning\n /** Task is blocked by an incoming edge. */\n blocked: \"\\uf0c1\", // nf-fa-link (chain)\n /** Task is parked (OPEN/parked): open, but set aside on purpose. */\n parked: \"\\uf04c\", // nf-fa-pause\n /** Track whose roots merged (diamond dependency). */\n merge: \"\\uf074\", // nf-fa-random\n /** Agent owns more than one task (pane-title multi-count slot). */\n multi: \"\\uf055\", // nf-fa-plus_circle\n /** Filter toggle: enabled / disabled. */\n on: \"\\uf111\", // nf-fa-circle\n off: \"\\uf10c\", // nf-fa-circle_o\n /** Status outside the known enum. */\n unknown: \"\\uf059\", // nf-fa-question_circle\n} as const;\n","// mu — the types and errors of waitForEvents (src/wait.ts): refs, events,\n// snapshots, results, the options and the agent reader/watch shapes.\n\nimport type { RuntimeState, StateReading } from \"./agent-state.js\";\nimport type { AgentObservation } from \"./agents/observe.js\";\nimport type { CtlBlocked } from \"./ctl/protocol.js\";\nimport type { VerdictTally } from \"./delegates.js\";\nimport type { HumanNeeded } from \"./human-needed.js\";\nimport { say } from \"./messages.js\";\nimport type { TaskStatus } from \"./tasks/status.js\";\nimport type { CursorToken } from \"./wait-cursor.js\";\nimport type { WaitRefKind } from \"./wait-registration.js\";\n\n/** The heartbeat cap: no wait outlives it; a requested 0 means this. */\nexport const WAIT_HEARTBEAT_CAP_MS = 1_500_000;\n\n/** Default `stuckAfterMs`: how long an IN_PROGRESS task's owner may sit needs_input before the wait reports a stall. */\nexport const DEFAULT_STUCK_AFTER_MS = 120_000;\n/** The same for an owner read over a working control socket: ctl's idle is exact, so only an `orchestrator send` racing the settle needs the grace. */\nexport const DEFAULT_CTL_STUCK_AFTER_MS = 5_000;\n\nexport interface WaitRef {\n kind: WaitRefKind;\n workstream: string;\n /** Task or agent local id; a delegate's call id. */\n id: string;\n /** Agent: ctl settled-run baseline (a `send` reply's `runs`). */\n afterRuns?: number;\n /** Agent: pin pi's process incarnation; another one is AgentRestartedError. */\n incarnation?: string;\n}\n\nexport type WaitEventKind =\n | \"closed\"\n | \"settled\"\n | \"input\"\n | \"dead\"\n | \"stall\"\n | \"delegate\"\n | \"pane-exit\"\n /** A remote command gate's command ended with a numeric status (`WaitResult.exit`, `snapshot.exit`). */\n | \"exited\"\n /** An agent with no control socket: its pane tail matched `until.text`. Never a settled run. */\n | \"pane-text\"\n | \"heartbeat\"\n | \"interrupted\";\n\nexport interface WaitEvent {\n kind: WaitEventKind;\n ref: WaitRef | null;\n incarnation?: string;\n runs?: number;\n}\n\nexport interface CloseOutcome {\n applied: boolean;\n task: string | null;\n reason: string;\n}\n\n/** The facts of one ref at the moment the wait returned. */\nexport interface WaitSnapshot {\n ref: WaitRef;\n /** Task: its status. Agent: runtime state (null = pane gone). Delegate: the call's state. */\n status: string | null;\n substate?: string;\n owner?: string | null;\n ownerWorkstream?: string;\n incarnation?: string;\n runs?: number;\n lastText?: string;\n lastError?: string;\n sessionFile?: string;\n blocked?: CtlBlocked;\n unknownReason?: string;\n /** Agent: the registry row id (a number; never pi's incarnation string). */\n agentId?: number;\n paneId?: string;\n /** Agent: true only for a ctl run that ended `settled`. */\n settled?: boolean;\n /** Agent: `lastText` lost its head to the cap, so a CLOSE block in it cannot be trusted. */\n lastTextTruncated?: boolean;\n /** Agent: `pane` when `lastText` is a non-pi pane's tail (no ctl text exists for it). */\n textSource?: \"pane\";\n /** Agent: the ctl run count this wait counted from. */\n afterRuns?: number;\n /** Agent: observed busy during this wait. */\n wasBusy?: boolean;\n /** Agent: owed with no fence and no cursor, so counted from the run count probed now: an earlier run is NOT reported as completion. */\n unknownBaseline?: boolean;\n /** Delegate: the parsed verdict label of a done answer. */\n verdict?: string | null;\n /** Delegate: its own task's local id (the answer is that task's report note), the `<ws>/<task>` it judges, its wave. */\n callTask?: string;\n record?: string;\n wave?: string;\n /** Task: its owner has been stalled long enough to report (IN_PROGRESS, owner needs_input or ctl broken). */\n stuck?: boolean;\n /** Task, stuck: why (`needs_input`, or the broken control socket's reason) and how long, in seconds. */\n stuckWhy?: string;\n stuckSecs?: number;\n /** Task, stuck: the owner's ctl settled-run count, when its socket answered (pi owners). */\n ownerRuns?: number;\n /** Agent (a remote command gate): the command's own numeric exit status, authoritative. */\n exit?: number;\n /** The ref's completion condition is met (task at target, agent settled, delegate terminal). */\n fired: boolean;\n dead: boolean;\n /** What applying the settled run's CLOSE block did (agent refs; absent when none was tried). On a stuck task: the owner's refused CLOSE. */\n close?: CloseOutcome;\n}\n\n/** What a handled stall did; `disposition` says whether the wait goes on. */\nexport interface StallActionResult {\n /** `continue`: keep waiting (the ref is not consumed). `return`: end the wait with the stall. */\n disposition: \"continue\" | \"return\";\n action: \"steer\" | \"release\";\n state: \"sent\" | \"released\" | \"refused\" | \"unknown\" | \"budget-exhausted\";\n msgId?: string;\n incarnation?: string;\n /** The ctl run baseline after a send: the wait counts the owner's next run from here. */\n afterRuns?: number;\n reason?: string;\n}\n\n/** What the engine knows when it hands a stall to `handleStall`. The hook owns policy and effects. */\nexport interface WaitStallContext {\n /** The caller that owns the stalled ref (the first of the set when none does). */\n caller: string;\n /** That caller's registration generation; null for an unregistered explicit wait (not a bypass of ownership). */\n generation: number | null;\n /** The stalled TASK (its owner is `owner`). */\n ref: WaitRef;\n /** `tasks.id` of the stalled task. */\n taskId: number;\n /** The task's revision when the stall was seen. */\n revision: number;\n /** The task's owner: registry id, pane and the authoritative ctl facts. */\n owner: AgentObservation;\n /** Stable for one observation of one stall: task, owner id, ctl incarnation, runs, since. */\n stallToken: string;\n /** Milliseconds left to the wait's deadline when the hook was called. */\n deadlineMs: number;\n /** Aborts when the wait aborts or returns: a not-yet-written action must not be written. */\n signal: AbortSignal;\n}\n\nexport interface WaitResult {\n /** The event that ended the wait; `heartbeat` on a timeout, `interrupted` on an abort. */\n event: WaitEvent;\n /** Targets in input order, then the delivered refs that are not targets. */\n refs: WaitSnapshot[];\n timedOut: boolean;\n interrupted: boolean;\n /** 0 fired or timed out, 6 dead, 7 input or stall, 130 interrupted; an `exited` gate's own status (23 stays 23), the first nonzero of the gates that ended. */\n exit: number;\n /**\n * The refs this wait's event actually handed over as COMPLETED (closed, settled, delegate, ...):\n * what a resume may drop. Never an input or stall (still owed its completion) and never a target\n * an early urgent return did not name.\n */\n delivered: WaitRef[];\n /** The callers' consumed tokens after this wait (empty without callers). */\n cursor: Record<string, CursorToken>;\n /** Open human needs of the callers (never another caller's). */\n humanNeeds: HumanNeeded[];\n /** The wave's tally over the callers' calls, when `wave` was given. */\n tally?: VerdictTally;\n /** What `handleStall` did for a returned stall. */\n action?: StallActionResult;\n /** True when a newer wait of the same caller superseded this one: nothing was consumed. */\n superseded?: boolean;\n /** Everything watched is done and was already delivered: nothing is owed. */\n drained?: boolean;\n /** The reaper-flip anchor this wait used: a resume of it keeps it. */\n sinceSeq?: number;\n}\n\n/** What an agent read or watch reports; an AgentObservation satisfies it. */\nexport interface AgentReading {\n status: RuntimeState | null;\n /** A remote command gate that ended: its numeric exit status (status is then null; `exit` decides, not \"dead\"). */\n exit?: number;\n settled?: boolean;\n reason?: string;\n incarnation?: string;\n runs?: number;\n pending?: boolean;\n blocked?: CtlBlocked;\n lastText?: string;\n lastTextTruncated?: boolean;\n /** `pane`: `lastText` is the tail of a NON-pi pane (it has no control socket, so no ctl text): matched by `until.text` only, never a CLOSE source. */\n textSource?: \"pane\";\n lastError?: string;\n sessionFile?: string;\n agentId?: number;\n paneId?: string;\n /** When the state began (ms epoch); stall detection reads it. */\n since?: number | null;\n source?: StateReading[\"source\"];\n /** How the control socket answered (pi agents). */\n ctl?: StateReading[\"ctl\"];\n}\n\n/** The unconsumed run baseline a producer registered for an agent ref. */\nexport interface AgentBaseline {\n afterRuns: number;\n incarnation?: string;\n agentId?: number;\n}\n\nexport interface AgentWatchHandle {\n initial: AgentReading;\n afterRuns?: number;\n /** Set when an owed ref had no fence and no cursor: the baseline the watch probed and counted from. */\n unknownBaseline?: AgentBaseline;\n /** Resolves when the run ends. A REJECTION is fatal (the agent restarted). */\n settled: Promise<AgentReading>;\n}\n\nexport interface WaitOptions {\n /**\n * Who owns this wait: a SET, because one orchestrator is known under two\n * names: the managed `<ws>/<agent>` (spawned workers, human needs) and\n * `pi:<session>` (delegate calls). Owned refs, delegates, human needs and\n * the wave tally are the union over the set. `[]` is an explicit-refs wait:\n * no registration, no cursors, no owned refs, never an all-caller fallback.\n * See `currentCallers`.\n */\n callers: readonly string[];\n /** `first` (default): the first event ends the wait. `all`: every target must be done. */\n mode?: \"first\" | \"all\";\n /** `owned` (default): the callers' owned refs also end the wait. `refs`: only the listed refs do. */\n eventScope?: \"owned\" | \"refs\";\n /** Delegate calls of this wave (the callers' only, never narrowed by `scope`) are targets; the result carries their tally. A name none of their calls carry throws WaveNotFoundError. */\n wave?: { workstream?: string; name: string };\n /** The open transitive blockers of this task are targets, re-read each iteration. */\n blockersOf?: { workstream: string; id: string };\n /** Task target status (default CLOSED). */\n status?: TaskStatus;\n /** `idle` (default): a run ending. `text`: a bounded regex over a settled run's lastText or a done task's report. */\n until?: \"idle\" | { text: string };\n /** Default and cap WAIT_HEARTBEAT_CAP_MS; 0 means the cap. */\n timeoutMs?: number;\n /** Ops seq a reaper flip must come after to be a death this wait reports (default: the ops head at start; a resume passes the stored one). */\n sinceSeq?: number;\n pollMs?: number;\n signal?: AbortSignal;\n /**\n * How long an IN_PROGRESS work task's owner may sit needs_input (or with a\n * dead control socket) before the wait reports a `stall`. Default 120 s,\n * 5 s for an owner read over a working ctl socket; an explicit value\n * applies to both; 0 disables detection.\n */\n stuckAfterMs?: number;\n /**\n * `exit` (default): a stall ends the wait. `warn`: the stall is flagged\n * (`stuck` on the snapshot, an `agent.stall` event) and the wait goes on.\n * `steer`/`release`: call `handleStall` (no handler: same as exit).\n */\n onStall?: \"exit\" | \"warn\" | \"steer\" | \"release\";\n /**\n * Narrow what the callers OWN to one workstream: registered and discovered\n * refs by their workstream, delegate calls by their own or their record's.\n * Explicit refs, a wave and `blockersOf` are never narrowed.\n */\n scope?: string;\n /** Raced with the loop, never awaited serially; called once per `stallToken`. */\n handleStall?: (ctx: WaitStallContext) => Promise<StallActionResult>;\n /** Called before every iteration; a throw propagates. */\n beforePoll?: () => Promise<void>;\n /** One batched, non-blocking read per iteration, keyed `<workstream>/<name>`. */\n readAgents?: (\n refs: readonly WaitRef[],\n signal: AbortSignal,\n ) => Promise<ReadonlyMap<string, AgentReading>>;\n /**\n * The blocking read of a future settle (the ctl `wait`): raced, never\n * awaited serially. undefined = poll the agent instead. `ctx.owed` marks a\n * ref the callers have registered (explicit or not): its unconsumed runs\n * still count, from the fence, else the cursor, else the probed run count.\n * `ctx.baseline` is the producer's registered unconsumed baseline (already\n * checked against the registry id; the hook checks the incarnation) and\n * `ctx.cursor` the consumed token.\n */\n watchAgent?: (\n ref: WaitRef,\n signal: AbortSignal,\n ctx: { owed: boolean; cursor?: CursorToken; baseline?: AgentBaseline },\n ) => Promise<AgentWatchHandle | undefined>;\n /** Apply settled CLOSE blocks (default true). Needs ctl facts: a polled reading never closes. */\n applyClose?: boolean;\n /** Ingest peers every iteration and flush before returning (default true). */\n sync?: boolean;\n /** Called every iteration with the snapshots of everything the wait is watching (the CLI's heartbeat and stall warning). */\n onPicture?: (snaps: readonly WaitSnapshot[]) => void;\n /** Called once when every watched agent target reads unknown on the first iteration. */\n onInitialUnknown?: (agents: readonly WaitSnapshot[]) => void;\n /** Poll sleep seam. Default: an abortable timer. */\n sleep?: (ms: number) => Promise<void>;\n /** `mu agent wait`: timeoutMs 0 means forever and there is no heartbeat cap. */\n uncapped?: boolean;\n}\n\n/** A wait with nothing to wait for. */\nexport class WaitNothingError extends Error {\n override readonly name = \"WaitNothingError\";\n constructor() {\n super(\"wait: nothing to wait for (no refs given and none owed to this caller)\");\n }\n}\n\n/** `--wave <name>` that none of the callers' delegate calls carry (a typo, or another session's wave). */\nexport class WaveNotFoundError extends Error {\n override readonly name = \"WaveNotFoundError\";\n constructor(\n public readonly wave: string,\n yours: readonly (string | null)[],\n ) {\n super(say(\"wait.wave_not_found\", wave, yours));\n }\n}\n\n/** A ref the caller may not wait on (another caller's delegate call). */\nexport class WaitRefError extends Error {\n override readonly name = \"WaitRefError\";\n}\n","// mu — the bounded regex behind `mu wait --until-text`.\n//\n// A JavaScript RegExp can run for minutes on a pathological pattern\n// (`(a+)+$`), and length limits do not change that. Two guards, no\n// dependency:\n//\n// 1. A grammar. Only literals, classes, `.`, anchors, groups,\n// alternation and quantifiers are accepted. Backreferences, lookaround,\n// named groups and counts over 1000 are refused, and so is a quantified\n// group whose body holds a quantifier or an alternation (`(a+)+`,\n// `(a|aa)*`): the shapes that backtrack exponentially.\n// 2. A budget. The match runs in a `node:vm` context with a hard timeout,\n// on at most the last WAIT_TEXT_MAX characters. What the grammar misses\n// (polynomial `a*a*a*b`) ends in a typed error, never a hang.\n//\n// The text matched is a ctl `lastText`, a task report, or (non-pi agents)\n// captured pane text (wait-ctl.ts, wait.ts); the caller passes it already\n// bounded or we tail it.\n\nimport { createContext, Script } from \"node:vm\";\n\nexport const WAIT_REGEX_MAX_LEN = 200;\n/** Only this many trailing characters of a text are matched. */\nexport const WAIT_TEXT_MAX = 8192;\nexport const WAIT_REGEX_TIMEOUT_MS = 50;\nconst MAX_COUNT = 1000;\n\n/** The pattern is refused (grammar, size, syntax) or its match ran out of budget. */\nexport class WaitRegexError extends Error {\n override readonly name = \"WaitRegexError\";\n}\n\nexport interface TextMatcher {\n readonly source: string;\n /** Does the (tail of the) text match? Throws WaitRegexError past the time budget. */\n test(text: string): boolean;\n}\n\ninterface Group {\n quant: boolean;\n alt: boolean;\n}\n\n/** The quantifier at `i` (`*`, `+`, `?`, `{n}`, `{n,}`, `{n,m}`): its length and counts, or undefined. */\nfunction quantifierAt(src: string, i: number): { len: number; counts: number[] } | undefined {\n const c = src[i];\n if (c === \"*\" || c === \"+\" || c === \"?\") return { len: 1, counts: [] };\n if (c !== \"{\") return undefined;\n const m = /^\\{(\\d+)(?:,(\\d*))?\\}/.exec(src.slice(i, i + 24));\n if (m === null) return undefined;\n const counts = [Number(m[1])];\n if (m[2] !== undefined && m[2] !== \"\") counts.push(Number(m[2]));\n return { len: m[0].length, counts };\n}\n\nfunction refuse(why: string): never {\n throw new WaitRegexError(`--until-text: ${why}`);\n}\n\n/** Throws WaitRegexError unless `src` is inside the accepted grammar. */\nexport function checkRegexGrammar(src: string): void {\n if (src === \"\") refuse(\"the pattern is empty\");\n if (src.length > WAIT_REGEX_MAX_LEN) {\n refuse(`the pattern is ${src.length} characters; the limit is ${WAIT_REGEX_MAX_LEN}`);\n }\n // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are the point\n if (/[\\u0000-\\u001f\\u007f]/.test(src)) refuse(\"the pattern has control characters\");\n const stack: Group[] = [];\n let top: Group = { quant: false, alt: false };\n let inClass = false;\n for (let i = 0; i < src.length; i++) {\n const c = src[i] as string;\n if (c === \"\\\\\") {\n const n = src[i + 1] ?? \"\";\n if (/[1-9k]/.test(n)) refuse(\"backreferences are not supported\");\n i++;\n continue;\n }\n if (inClass) {\n if (c === \"]\") inClass = false;\n continue;\n }\n if (c === \"[\") {\n inClass = true;\n continue;\n }\n if (c === \"(\") {\n if (src[i + 1] === \"?\") {\n if (src[i + 2] !== \":\") refuse(\"lookaround and named groups are not supported\");\n i += 2;\n }\n stack.push(top);\n top = { quant: false, alt: false };\n continue;\n }\n if (c === \")\") {\n const parent = stack.pop();\n if (parent === undefined) refuse(\"unbalanced `)`\");\n const q = quantifierAt(src, i + 1);\n if (q !== undefined && (top.quant || top.alt)) {\n refuse(\"a repeated group may not contain a repeat or an alternation\");\n }\n parent.quant ||= top.quant || q !== undefined;\n parent.alt ||= top.alt;\n top = parent;\n continue;\n }\n if (c === \"|\") {\n top.alt = true;\n continue;\n }\n const q = quantifierAt(src, i);\n if (q !== undefined) {\n if (q.counts.some((n) => n > MAX_COUNT)) refuse(`a repeat count is over ${MAX_COUNT}`);\n top.quant = true;\n i += q.len - 1;\n }\n }\n if (stack.length > 0) refuse(\"unbalanced `(`\");\n}\n\nconst SCRIPT = new Script(\"new RegExp(src).test(text)\");\n\n/** Validate `src` and return a matcher with the time and size budget applied. */\nexport function compileTextMatcher(src: string): TextMatcher {\n checkRegexGrammar(src);\n try {\n new RegExp(src);\n } catch (e) {\n refuse(`not a valid regular expression (${e instanceof Error ? e.message : String(e)})`);\n }\n const ctx = createContext({ src, text: \"\" });\n return {\n source: src,\n test(text: string): boolean {\n ctx.text = text.length > WAIT_TEXT_MAX ? text.slice(-WAIT_TEXT_MAX) : text;\n try {\n return SCRIPT.runInContext(ctx, { timeout: WAIT_REGEX_TIMEOUT_MS }) === true;\n } catch (e) {\n throw new WaitRegexError(\n `--until-text: matching exceeded ${WAIT_REGEX_TIMEOUT_MS} ms (${e instanceof Error ? e.message : String(e)}); use a simpler pattern`,\n );\n }\n },\n };\n}\n","// mu — the CLOSE block of a settled pi run: parse it, apply it once.\n//\n// A pi worker ends its final message with\n//\n// CLOSE: task=<id> evidence=\"<command + result>\"\n// REPORT:\n// <report, any number of lines>\n//\n// `applySettledClose` reads that block from the run's authoritative ctl\n// `lastText` (never the pane) and, when `task=` is a task the agent owns,\n// writes the report note, the close note and the status flip in ONE op\n// group, once per (agent, incarnation, runs). Everything else is ignored\n// or recorded as \"no close (malformed)\": the block never closes by guess.\n//\n// Grammar (the only definition; the README names the shape, not the escapes).\n// A CLOSE applies only if the whole tail of the message fits it exactly:\n//\n// CLOSE: task=<id> evidence=\"<escaped text>\" (column 0, outside a fence)\n// REPORT: (the very next line)\n// <report: every byte to the end of the message>\n//\n// - The tail starts at the LAST column-0 line outside any fence that begins\n// `CLOSE:` (the quoted template `task=<...>` is not one). Earlier blocks\n// are never considered. No such line: no block.\n// - Fence state (``` / ~~~, CommonMark open/close rules) is tracked over the\n// WHOLE message. A message that ends inside a fence has no block; a fence\n// line or a line inside a fence is never a marker.\n// - Both marker lines are exact: single spaces, no indentation, no trailing\n// blanks (a CR before the LF is the only tolerance). `REPORT:` must be the\n// line right after the header. Anything else is malformed.\n// - <id> is a task id. Inside the quotes `\\\"`, `\\\\` and `\\n` are escapes; any\n// other backslash is literal; a bare `\"` ends the evidence and so must be\n// the last character of the line. Evidence and report must not be blank.\n// - The report is the exact bytes after the `REPORT:` line. Only the\n// run of trailing newlines is normalized: it becomes exactly one `\\n`\n// (none stays none; spaces and TABs are report bytes).\n// - Whatever is not a valid block applies nothing and carries a one-line\n// reason; a start line whose tail does not fit is \"malformed\".\n\nimport type { Db } from \"./db.js\";\nimport { withOpContext } from \"./op-context.js\";\nimport { addNote } from \"./tasks/edit.js\";\nimport { isValidTaskId } from \"./tasks/id.js\";\nimport { closeTask } from \"./tasks/lifecycle.js\";\n\nexport type CloseBlock =\n | { kind: \"valid\"; task: string; evidence: string; report: string }\n | { kind: \"malformed\"; reason: string }\n | { kind: \"none\"; reason: string };\n\nconst HEADER = /^CLOSE: task=(\\S+) evidence=\"(.*)\"$/;\nconst TEMPLATE = /^CLOSE:[ \\t]+task=<[^>\\s]*>/;\n\nconst FENCE_OPEN = /^ {0,3}(`{3,}|~{3,})(.*)$/;\nconst FENCE_CLOSE = /^ {0,3}(`{3,}|~{3,})[ \\t]*$/;\n\n/** Per line: true when it is a fence line or sits inside a fence. */\nfunction quotedLines(lines: string[]): { quoted: boolean[]; unclosed: boolean } {\n const quoted: boolean[] = [];\n let open: { ch: string; len: number } | undefined;\n for (const line of lines) {\n if (open) {\n quoted.push(true);\n const c = FENCE_CLOSE.exec(line);\n const run = c?.[1] ?? \"\";\n if (run[0] === open.ch && run.length >= open.len) open = undefined;\n continue;\n }\n const o = FENCE_OPEN.exec(line);\n const run = o?.[1] ?? \"\";\n if (o && !(run[0] === \"`\" && (o[2] ?? \"\").includes(\"`\"))) {\n open = { ch: run[0] as string, len: run.length };\n quoted.push(true);\n } else {\n quoted.push(false);\n }\n }\n return { quoted, unclosed: open !== undefined };\n}\n\nconst isStart = (line: string): boolean => line.startsWith(\"CLOSE:\") && !TEMPLATE.test(line);\n\nconst none = (reason: string): CloseBlock => ({ kind: \"none\", reason });\nconst malformed = (reason: string): CloseBlock => ({ kind: \"malformed\", reason });\n\n/** Parse the CLOSE block at the tail of a settled run's final message. */\nexport function parseCloseBlock(text: string): CloseBlock {\n if (text.trim() === \"\") return none(\"empty message\");\n const body = text.replace(/(?:\\r?\\n)+$/, \"\");\n const raw = body.split(\"\\n\");\n const offsets: number[] = [];\n let at = 0;\n for (const l of raw) {\n offsets.push(at);\n at += l.length + 1;\n }\n const lines = raw.map((l) => l.replace(/\\r$/, \"\"));\n const { quoted, unclosed } = quotedLines(lines);\n if (unclosed) return none(\"the message ends inside a code fence\");\n let start = -1;\n for (let i = 0; i < lines.length; i++) {\n if (!quoted[i] && isStart(lines[i] ?? \"\")) start = i;\n }\n if (start < 0) return none(\"no CLOSE: line at column 0\");\n const m = HEADER.exec(lines[start] ?? \"\");\n if (!m) return malformed('the CLOSE: line is not `CLOSE: task=<id> evidence=\"<text>\"`');\n const task = m[1] ?? \"\";\n if (!isValidTaskId(task)) return malformed(\"task= is not a valid task id\");\n const evidence = unescapeEvidence(m[2] ?? \"\");\n if (evidence === undefined) return malformed(\"evidence has a bare or unterminated quote\");\n if (evidence.trim() === \"\") return malformed(\"evidence is empty\");\n if (start + 1 >= lines.length || lines[start + 1] !== \"REPORT:\") {\n return malformed(\"the line after CLOSE: is not exactly REPORT:\");\n }\n const report = body.slice(offsets[start + 2] ?? body.length);\n if (report.trim() === \"\") return malformed(\"the report is empty\");\n const normalized = body.length < text.length ? `${report}\\n` : report;\n return { kind: \"valid\", task, evidence, report: normalized };\n}\n\n/** `body` is the text between the opening and the closing quote. Undefined\n * when it holds a bare quote or ends in a backslash that escaped the closer. */\nfunction unescapeEvidence(body: string): string | undefined {\n let out = \"\";\n for (let i = 0; i < body.length; i++) {\n const c = body[i] as string;\n if (c === '\"') return undefined;\n if (c !== \"\\\\\") {\n out += c;\n continue;\n }\n const n = body[i + 1];\n if (n === '\"' || n === \"\\\\\") {\n out += n;\n i++;\n } else if (n === \"n\") {\n out += \"\\n\";\n i++;\n } else if (n === undefined) {\n return undefined;\n } else {\n out += c;\n }\n }\n return out;\n}\n\nexport const CLOSE_MALFORMED = \"no close (malformed)\";\nexport const CLOSE_TRUNCATED =\n \"CLOSE block not applied: the final message was truncated; close with mu task close\";\n\nexport interface SettledCloseInput {\n /** The agent's workstream, and the workstream of the task it may close. */\n workstream: string;\n agent: string;\n agentId: number;\n incarnation: string;\n /** The settled run's count from ctl (not a wait baseline). */\n runs: number;\n lastText: string;\n /** Ctl `lastTextTruncated`: the head was cut, so the block cannot be trusted. */\n lastTextTruncated?: boolean;\n /** ctl `ended === \"settled\"`; a blocked or unknown observation is false. */\n settled: boolean;\n lastError?: string;\n}\n\nexport interface SettledCloseResult {\n applied: boolean;\n task: string | null;\n reason: string;\n}\n\nconst no = (reason: string, task: string | null = null): SettledCloseResult => ({\n applied: false,\n task,\n reason,\n});\n\n/**\n * Apply a settled pi run's CLOSE block exactly once. One transaction owns\n * the decision, the notes, the status flip and the replay row (inserted\n * last), so a refused or failed close leaves nothing and a retry is safe.\n * Guard errors (open blockers) propagate and roll everything back.\n */\nexport function applySettledClose(db: Db, input: SettledCloseInput): SettledCloseResult {\n if (!input.settled) return no(\"not settled\");\n if (input.lastError !== undefined) return no(\"run ended on an error\");\n return withOpContext(db, { intent: \"close.apply\", actor: input.agent, group: \"new\" }, () =>\n applyInTxn(db, input),\n );\n}\n\nfunction applyInTxn(db: Db, input: SettledCloseInput): SettledCloseResult {\n const agent = db\n .prepare(\n `SELECT a.cli FROM agents a JOIN workstreams w ON w.id = a.workstream_id\n WHERE a.id = ? AND a.name = ? AND w.name = ? AND w.torn_down_at IS NULL`,\n )\n .get(input.agentId, input.agent, input.workstream) as { cli: string } | undefined;\n if (!agent) return no(\"unknown agent\");\n if (agent.cli !== \"pi\") return no(\"not a pi agent\");\n const seen = db\n .prepare(\"SELECT 1 FROM agent_settles WHERE agent_id = ? AND incarnation = ? AND runs = ?\")\n .get(input.agentId, input.incarnation, input.runs);\n if (seen) return no(\"already applied\");\n const record = (taskId: number | null): void => {\n db.prepare(\n \"INSERT INTO agent_settles (agent_id, incarnation, runs, task_id) VALUES (?, ?, ?, ?)\",\n ).run(input.agentId, input.incarnation, input.runs, taskId);\n };\n const diagnose = (reason: string): SettledCloseResult => {\n const open = db\n .prepare(\n `SELECT t.local_id FROM tasks t JOIN workstreams w ON w.id = t.workstream_id\n WHERE t.owner_id = ? AND t.status = 'IN_PROGRESS' AND w.name = ?`,\n )\n .all(input.agentId, input.workstream) as { local_id: string }[];\n const only = open.length === 1 ? (open[0]?.local_id ?? null) : null;\n if (only !== null) {\n addNote(db, only, reason, {\n workstream: input.workstream,\n author: input.agent,\n group: \"inherit\",\n });\n }\n record(null);\n return no(reason, only);\n };\n if (input.lastTextTruncated === true) return diagnose(CLOSE_TRUNCATED);\n const block = parseCloseBlock(input.lastText);\n if (block.kind === \"none\") return no(`no CLOSE block: ${block.reason}`);\n if (block.kind === \"malformed\") return diagnose(`${CLOSE_MALFORMED}: ${block.reason}`);\n const task = db\n .prepare(\n `SELECT t.id, t.status, t.owner_id, t.kind FROM tasks t JOIN workstreams w ON w.id = t.workstream_id\n WHERE w.name = ? AND w.torn_down_at IS NULL AND t.local_id = ?`,\n )\n .get(input.workstream, block.task) as\n | { id: number; status: string; owner_id: number | null; kind: string }\n | undefined;\n if (task?.kind === \"human\") {\n record(task.id);\n return no(\n `human task: close it with \\`mu task close ${block.task} -w ${input.workstream}\\``,\n block.task,\n );\n }\n if (task?.kind === \"delegate\") {\n // The delegate's recorder (finishDelegate) writes the verdict, the report\n // and this close in one group; a CLOSE block in a delegate's answer must\n // never beat it to the close.\n record(task.id);\n return no(\"delegate task: its call records the answer and closes it\", block.task);\n }\n if (!task || task.owner_id !== input.agentId) {\n record(null);\n return no(\"task is not owned by this agent\", block.task);\n }\n if (task.status === \"CLOSED\") {\n record(task.id);\n return no(\"task already closed\", block.task);\n }\n closeTask(db, block.task, {\n workstream: input.workstream,\n evidence: block.evidence,\n report: block.report,\n author: input.agent,\n group: \"inherit\",\n });\n record(task.id);\n return { applied: true, task: block.task, reason: \"closed\" };\n}\n","// mu — the database reads and writes behind waitForEvents that need no loop\n// state: the CLOSE application of a settled run, the existence check, and\n// the open-blocker traversal.\n\nimport { settledCloseInput } from \"./agents/observe.js\";\nimport { applySettledClose } from \"./close-block.js\";\nimport type { Db } from \"./db.js\";\nimport type { AgentReading, CloseOutcome, WaitRef } from \"./wait-types.js\";\n\n/**\n * Apply the CLOSE block of a settled ctl run, once; never throws.\n * undefined when there is nothing to apply: closing is off, the reading is\n * not a ctl-settled run, or it lacks the incarnation or run count.\n * applySettledClose refuses delegate and human tasks.\n */\nexport function closeSettledRun(\n db: Db,\n ref: WaitRef,\n r: AgentReading,\n enabled: boolean,\n): CloseOutcome | undefined {\n if (!enabled || r.settled !== true) return undefined;\n const row = db\n .prepare(\n `SELECT a.id FROM agents a JOIN workstreams w ON w.id = a.workstream_id\n WHERE a.name = ? AND w.name = ?`,\n )\n .get(ref.id, ref.workstream) as { id: number } | undefined;\n const facts = settledCloseInput({\n workstream: ref.workstream,\n name: ref.id,\n agentId: r.agentId ?? row?.id ?? 0,\n status: r.status,\n settled: true,\n ...(r.incarnation !== undefined ? { incarnation: r.incarnation } : {}),\n ...(r.runs !== undefined ? { runs: r.runs } : {}),\n ...(r.lastText !== undefined ? { lastText: r.lastText } : {}),\n ...(r.lastTextTruncated !== undefined ? { lastTextTruncated: r.lastTextTruncated } : {}),\n ...(r.lastError !== undefined ? { lastError: r.lastError } : {}),\n });\n if (facts === undefined) return undefined;\n try {\n const res = applySettledClose(db, facts);\n return { applied: res.applied, task: res.task, reason: res.reason };\n } catch (e) {\n return { applied: false, task: null, reason: e instanceof Error ? e.message : String(e) };\n }\n}\n\nexport function agentExists(db: Db, ref: Pick<WaitRef, \"workstream\" | \"id\">): boolean {\n return (\n db\n .prepare(\n `SELECT 1 FROM agents a JOIN workstreams ws ON ws.id = a.workstream_id\n WHERE a.name = ? AND ws.name = ?`,\n )\n .get(ref.id, ref.workstream) !== undefined\n );\n}\n\nexport * from \"./wait-types.js\";\n\n/** The open transitive blockers of task row `umbrella`, uncapped, in a stable order. */\nexport function openBlockers(db: Db, umbrella: number): { id: string; ws: string }[] {\n return db.prepare(BLOCKERS_SQL).all(umbrella) as { id: string; ws: string }[];\n}\n\nconst BLOCKERS_SQL = `\n WITH RECURSIVE reach(node) AS (\n SELECT e.from_task_id FROM task_edges e WHERE e.to_task_id = ?\n UNION\n SELECT e.from_task_id FROM task_edges e\n JOIN reach r ON e.to_task_id = r.node\n JOIN tasks t ON t.id = r.node\n WHERE t.status <> 'CLOSED'\n )\n SELECT t.local_id AS id, w.name AS ws FROM reach r\n JOIN tasks t ON t.id = r.node JOIN workstreams w ON w.id = t.workstream_id\n ORDER BY w.name, t.local_id`;\n\n/** The registry row id of an agent ref (0 when it has no row): the identity a death or dialog token is pinned to. */\nexport function agentRowId(db: Db, ref: Pick<WaitRef, \"workstream\" | \"id\">): number {\n const row = db\n .prepare(\n `SELECT a.id FROM agents a JOIN workstreams ws ON ws.id = a.workstream_id\n WHERE a.name = ? AND ws.name = ?`,\n )\n .get(ref.id, ref.workstream) as { id: number } | undefined;\n return row?.id ?? 0;\n}\n\n/** The ops log head: what a wait that owns no cursor anchors a reaper flip to. */\nexport function opsHead(db: Db): number {\n return (db.prepare(\"SELECT COALESCE(MAX(seq), 0) AS s FROM ops\").get() as { s: number }).s;\n}\n\n/**\n * The reaper's flip of a task, read from the ops log (durable, never a wait's memory): when the\n * task's LATEST status or substate change is the reaper's (`task.reap`) and came after ops seq `since`, its owner\n * died with the work undone. A later claim, release, park, open or close is a decision, not a\n * death: it is the latest change then, and this returns undefined. `ownerId` is the row the reaper\n * removed (the last owner the log names before the flip; 0 if none), the same token a live wait pins.\n * `ownerName` is the actor of the op that set that owner (a claim records the claiming agent's name).\n */\nexport function reapFlip(\n db: Db,\n ref: Pick<WaitRef, \"workstream\" | \"id\">,\n since: number,\n): { seq: number; ownerId: number; ownerName?: string } | undefined {\n const key = `${ref.workstream}/${ref.id}`;\n const last = db\n .prepare(\n `SELECT seq, intent FROM ops WHERE entity = 'task' AND key = ?\n AND (json_extract(payload, '$.status') IS NOT NULL OR json_extract(payload, '$.substate') IS NOT NULL)\n ORDER BY seq DESC LIMIT 1`,\n )\n .get(key) as { seq: number; intent: string | null } | undefined;\n if (last === undefined || last.intent !== \"task.reap\" || last.seq <= since) return undefined;\n const owner = db\n .prepare(\n `SELECT json_extract(payload, '$.owner_id') AS id, actor FROM ops\n WHERE entity = 'task' AND key = ? AND seq < ? AND json_extract(payload, '$.owner_id') IS NOT NULL\n ORDER BY seq DESC LIMIT 1`,\n )\n .get(key, last.seq) as { id: number; actor: string | null } | undefined;\n return {\n seq: last.seq,\n ownerId: Number(owner?.id ?? 0),\n ...(owner?.actor != null ? { ownerName: owner.actor } : {}),\n };\n}\n\n/** The registry row id of a task's current owner (0 when it has none). */\nexport function taskOwnerRowId(db: Db, ref: Pick<WaitRef, \"workstream\" | \"id\">): number {\n const row = db\n .prepare(\n `SELECT COALESCE(t.owner_id, 0) AS id FROM tasks t JOIN workstreams ws ON ws.id = t.workstream_id\n WHERE t.local_id = ? AND ws.name = ?`,\n )\n .get(ref.id, ref.workstream) as { id: number } | undefined;\n return row?.id ?? 0;\n}\n","// mu — the wait loop's items: what one watched ref can deliver now (`Item`), and the pure helpers\n// that build and rank items and snapshots without the loop's state. Moved out of src/wait.ts\n// (the loop itself) under the file cap; see that file's comment for the semantics.\n\nimport { type DelegateRow, TERMINAL_DELEGATE_STATES } from \"./delegates.js\";\nimport { type CursorToken, cursorKey, DELEGATE_TOKEN } from \"./wait-cursor.js\";\nimport type { AgentTrack } from \"./wait-latch.js\";\nimport type { RegisteredRef } from \"./wait-registration.js\";\nimport type {\n AgentReading,\n CloseOutcome,\n StallActionResult,\n WaitEventKind,\n WaitRef,\n WaitSnapshot,\n} from \"./wait-types.js\";\n\nexport interface Item {\n key: string;\n ref: WaitRef;\n snap: WaitSnapshot;\n /** Counts toward `all`; explicit refs, wave calls and blockers. */\n target: boolean;\n /** An already-consumed event is hidden (owned refs, waves, blockers); explicit refs ignore the cursor. */\n suppressible: boolean;\n order: number;\n /** The event this ref can deliver now, when any. */\n kind?: WaitEventKind;\n token?: CursorToken;\n /** The cursor key `token` is recorded under: the ref's own key, or an urgent observation's (`input|<key>`). */\n ckey?: string;\n /** The event was already returned once (its token is consumed): it never outranks a never-returned one. */\n seen?: boolean;\n /**\n * Who died, on a `dead` item: the registry row (0 when it is gone and unknown) and, when known,\n * its name and workstream. A task's is its owner's; an agent ref's is its own.\n */\n death?: { rowId: number; name?: string; workstream?: string };\n /** An owned event that was already returned: hidden until its state changes. */\n hidden?: boolean;\n /** Completed: closed, settled, delegate terminal, dead. */\n done: boolean;\n ready: boolean;\n /** A task whose owner stalled: what the stall hook needs. */\n stall?: {\n token: string;\n owner: AgentReading;\n ownerRef: { name: string; workstreamName: string };\n /** How long the owner had been stalled when seen (the snapshot's `stuckSecs`). */\n ageSecs: number;\n /** The owner's settled run was refused its CLOSE (a malformed block): the snapshot's `close`. */\n close?: CloseOutcome;\n };\n}\n\n/** One handled stall: the job, its result, and what to report if the handler removed the condition. */\nexport interface StallState {\n job?: Promise<void>;\n result?: StallActionResult;\n carry?: { key: string; stall: Item[\"stall\"] };\n}\n\nexport const refKey = (r: Pick<WaitRef, \"kind\" | \"workstream\" | \"id\">): string =>\n cursorKey(r.kind, r.workstream, r.id);\nexport const registered = (r: WaitRef): RegisteredRef => ({\n kind: r.kind,\n workstream: r.workstream,\n id: r.id,\n});\nconst URGENCY: Partial<Record<WaitEventKind, number>> = {\n dead: 0,\n input: 1,\n stall: 2,\n delegate: 3,\n};\nexport const urgency = (k: WaitEventKind | undefined): number =>\n k === undefined ? 9 : (URGENCY[k] ?? 4);\n/** A delivered item that finishes its ref (urgent input, stall and a dead task stay owed). */\nexport const isCompletion = (i: Item): boolean =>\n i.kind === \"closed\" ||\n i.kind === \"settled\" ||\n i.kind === \"pane-text\" ||\n i.kind === \"exited\" ||\n i.kind === \"delegate\" ||\n (i.kind === \"dead\" && i.ref.kind === \"agent\");\nexport const exitFor = (k: WaitEventKind): number =>\n k === \"dead\" ? 6 : k === \"input\" || k === \"stall\" ? 7 : k === \"interrupted\" ? 130 : 0;\n\nexport const inputToken = (r: AgentReading): CursorToken => ({\n incarnation: `input:${r.incarnation ?? \"\"}`,\n runs: r.blocked?.since ?? 0,\n});\n\nexport const agentSnapshot = (t: AgentTrack): WaitSnapshot => {\n const r = t.latched?.reading ?? t.reading;\n const status =\n t.latched?.kind === \"dead\" || t.latched?.kind === \"exited\" ? null : (r?.status ?? \"unknown\");\n return {\n ref: t.ref,\n status,\n ...(r?.agentId !== undefined ? { agentId: r.agentId } : {}),\n ...(r?.paneId !== undefined ? { paneId: r.paneId } : {}),\n ...(r?.settled !== undefined ? { settled: r.settled } : {}),\n ...(r?.lastTextTruncated !== undefined ? { lastTextTruncated: r.lastTextTruncated } : {}),\n ...(r?.textSource !== undefined ? { textSource: r.textSource } : {}),\n ...(r?.incarnation !== undefined ? { incarnation: r.incarnation } : {}),\n ...(r?.runs !== undefined ? { runs: r.runs } : {}),\n ...(r?.lastText !== undefined ? { lastText: r.lastText } : {}),\n ...(r?.lastError !== undefined ? { lastError: r.lastError } : {}),\n ...(r?.sessionFile !== undefined ? { sessionFile: r.sessionFile } : {}),\n ...(r?.blocked !== undefined ? { blocked: r.blocked } : {}),\n ...(t.latched?.kind === \"exited\" && r?.exit !== undefined ? { exit: r.exit } : {}),\n ...(status === \"unknown\" && r?.reason !== undefined ? { unknownReason: r.reason } : {}),\n ...(t.baseline !== undefined ? { afterRuns: t.baseline } : {}),\n wasBusy: t.wasBusy,\n ...(t.unknownBaseline ? { unknownBaseline: true } : {}),\n fired:\n t.latched?.kind === \"settled\" ||\n t.latched?.kind === \"pane-text\" ||\n t.latched?.kind === \"exited\",\n dead: t.latched?.kind === \"dead\",\n ...(t.close !== undefined ? { close: t.close } : {}),\n };\n};\n\nexport const delegateItem = (\n call: DelegateRow,\n isTarget: boolean,\n suppressible: boolean,\n order: number,\n): Item => {\n const ref: WaitRef = { kind: \"delegate\", workstream: call.workstream, id: call.callId };\n const terminal = TERMINAL_DELEGATE_STATES.includes(call.state);\n const item: Item = {\n key: refKey(ref),\n ref,\n snap: {\n ref,\n status: call.state,\n verdict: call.verdict,\n owner: call.agent,\n // Which finding this is: the delegate's own task, the task it judges, its wave.\n callTask: call.task,\n ...(call.record !== null ? { record: `${call.record.workstream}/${call.record.task}` } : {}),\n ...(call.wave !== null ? { wave: call.wave } : {}),\n fired: terminal,\n dead: false,\n },\n target: isTarget,\n suppressible,\n order,\n done: terminal,\n ready: false,\n };\n if (terminal) {\n item.kind = \"delegate\";\n item.token = DELEGATE_TOKEN;\n }\n return item;\n};\n\n/**\n * One death, one event: a dead task and a dead agent ref name the same death when the agent is the\n * task's owner that died. The same registry row; or, the agent's row being gone (reaped), the\n * owner the task names by name (and workstream, when the task knows it). A respawn under the name\n * is another row: its death is its own.\n */\nexport const sameDeath = (a: Item, b: Item): boolean => {\n const task = a.ref.kind === \"task\" ? a : b;\n const agent = task === a ? b : a;\n const t = task.death;\n const g = agent.death;\n if (a.kind !== \"dead\" || b.kind !== \"dead\" || t === undefined || g === undefined) return false;\n if (task.ref.kind !== \"task\" || agent.ref.kind !== \"agent\") return false;\n if (g.rowId !== 0) return g.rowId === t.rowId;\n return (\n t.name === agent.ref.id && (t.workstream === undefined || t.workstream === agent.ref.workstream)\n );\n};\n\nexport const failedGate = (i: Item): boolean =>\n i.kind === \"exited\" && i.snap.exit !== undefined && i.snap.exit !== 0;\n\nexport const snapshotsOf = (items: Item[], extra: Item[] = []): WaitSnapshot[] => {\n const targets = items.filter((i) => i.target);\n const base = targets.length > 0 ? targets : items;\n const shown = [...base];\n for (const e of extra) if (!shown.includes(e)) shown.push(e);\n return shown.map((i) => i.snap);\n};\n","// mu — the settled latch of a waited agent: what it holds and when it is history.\n//\n// A wait that sees an agent's run settle latches that reading (its CLOSE is already applied) until\n// the run is acted on. One rule decides when the latch is history: it is valid ONLY for the exact\n// (agentId, incarnation, runs) it captured. `supersededBy` is that predicate, and `rearmLatch` is\n// the one way to drop a latch (src/wait.ts calls both, from refresh and from a steer).\n\nimport type { AgentReading, AgentWatchHandle, CloseOutcome, WaitRef } from \"./wait-types.js\";\n\nexport interface AgentTrack {\n ref: WaitRef;\n explicit: boolean;\n wasBusy: boolean;\n /** The ctl run count a (re)watch counts past. */\n baseline: number | undefined;\n handle: AgentWatchHandle | undefined;\n needWatch: boolean;\n result: AgentReading | undefined;\n reading: AgentReading | undefined;\n latched:\n | { kind: \"settled\" | \"dead\" | \"input\" | \"pane-text\" | \"exited\"; reading: AgentReading }\n | undefined;\n close: CloseOutcome | undefined;\n /** The dialog already returned once is still open: not news again until it changes. */\n muted: boolean;\n /** Owed with no fence, no cursor: counted from now, said so in the snapshot. */\n unknownBaseline: boolean;\n}\n\n/**\n * Drop a settled latch (its close, handle, result) and watch again past `baseline`. A latch holds\n * one settled run until it is acted on; a newer identity or a later run always supersedes it\n * (refresh), and a steer that answers it rearms from the send baseline (driveStalls).\n */\nexport function rearmLatch(t: AgentTrack, baseline: number, watching: boolean): void {\n t.latched = undefined;\n t.close = undefined;\n t.handle = undefined;\n t.result = undefined;\n t.needWatch = watching;\n t.baseline = baseline;\n t.wasBusy = false;\n}\n\n/**\n * THE latch rule (one predicate): a settled latch is valid only for the exact (agentId,\n * incarnation, runs) it captured. An owner reading of another registry row (a respawn under the\n * same name) or another pi process supersedes it from that identity's own run 0; a later run of\n * the same identity supersedes it from the latched run. Returns the rewatch baseline, or undefined\n * while the latch holds. A reading with no run count (dead, unknown) says nothing about it.\n */\nexport function supersededBy(t: AgentTrack, r: AgentReading): number | undefined {\n const held = t.latched?.kind === \"settled\" ? t.latched.reading : undefined;\n if (held === undefined || r.runs === undefined) return undefined;\n const differs = <T>(a: T | undefined, b: T | undefined): boolean =>\n a !== undefined && b !== undefined && a !== b;\n if (differs(held.agentId, r.agentId) || differs(held.incarnation, r.incarnation)) return 0;\n if (held.runs !== undefined && r.runs > held.runs) return held.runs;\n return undefined;\n}\n","// mu — waitForEvents: the one owned-event wait.\n//\n// Before this there were two poll loops (one for tasks, one for agents) and a\n// shell loop above them; none could see a delegate's report or end on any\n// event but its own. This is the single loop.\n//\n// One iteration: beforePoll, a bounded sync ingest, the DB reads (tasks,\n// delegates, the caller's registration), ONE batched agent read, apply the\n// CLOSE blocks of settled pi runs, then pick. Then it races an agent watch\n// settling (ctl `wait`, never awaited serially), a poll sleep, the caller's\n// abort signal and the deadline. Every await inside an iteration is raced\n// with abort and deadline too, so no read can hold the wait past either.\n// No database transaction spans an await.\n//\n// What a wait watches:\n// targets the explicit refs, a wave's delegate calls (this caller's) and\n// the open transitive blockers of `blockersOf` (re-read each\n// iteration, so graph edits count).\n// owned what the caller's registration owes it, plus its in-flight\n// delegate calls (registered the first time a wait sees them).\n// Owned refs are observed even while explicit targets are waited\n// on; another caller's work is never seen.\n//\n// first vs all. `first` returns the best ready event over targets and owned\n// refs. `all` returns once every target is done (no targets: every owned\n// ref); an urgent event (an owned ref that died, an agent blocked on a\n// dialog, a stall, an owned delegate report) ends it early without counting\n// toward \"all\". Order: never-returned events first, then dead, input, stall,\n// delegate, then closed/settled; targets before owned refs. One fact is one\n// event: a settled run and the close its CLOSE block made, or a dead task and\n// its dead owner (`sameDeath`), are delivered (and consumed) together.\n//\n// Delivery is durable, never in-memory. Every event has a cursor key\n// (src/wait-cursor.ts): a close or settle under the ref's own key, an urgent\n// observation under `input|`, `dead|` or `stall|` + the ref key with a token\n// that names ITS state (the dialog's `since`, the owner's registry id, the\n// stall token), a blockersOf blocker seen open under `open|` + key. An event\n// is consumed only when it is the one returned, in ONE short transaction\n// guarded by the registration's generation (endWait) that first re-reads the\n// cursors: an event another process consumed meanwhile is skipped and the\n// wait selects again. A sibling that `first`\n// did not return stays owed (a timeout or interrupt delivers nothing), a\n// returned event is never delivered again, and an unchanged urgent\n// observation is news once per state change: it never outranks a\n// never-returned event, so it cannot starve a delegate report. Explicit refs\n// ignore the cursor of their completion (waiting on a closed task returns at\n// once); owned refs obey it.\n//\n// Owed vs done (src/wait-owed.ts). An owned agent ref is owed only while the agent owns open work or a\n// run it was sent is unsettled. Each tick keeps a DONE mark per owned agent true to what it read; a\n// registered agent whose row is gone and which is marked done is dropped from the registration with\n// no event. `dead` is a pane lost while work or a run is owed (or never read).\n//\n// The fence. An agent ref the caller registered, explicit or owned, counts\n// its runs from the stored UNCONSUMED baseline, maxed with the consumed\n// cursor of the same pi process; with neither it counts from the run count\n// probed now, stores that as the fence and says `unknownBaseline`: a\n// historical run is never mistaken for completion.\n//\n// CLOSE. A settled pi run's CLOSE block is applied once (applySettledClose)\n// before the snapshot returns. The close-block refuses delegate and human\n// tasks, so a delegate answer never closes its own task ahead of\n// finishDelegate's recorder.\n//\n// Stalls. The engine detects them (an IN_PROGRESS work task whose owner needs\n// input or has a broken control socket, `stuckAfterMs`); `handleStall` (raced,\n// once per stallToken) owns the policy and effects.\n//\n// Not here: the CLI and signal wiring, arming from spawn/send/claim\n// (v_wait_cli).\n\nimport { agentKey } from \"./agent-state.js\";\nimport { AgentNotFoundError, AgentRestartedError } from \"./agents/errors.js\";\nimport type { Db } from \"./db.js\";\nimport {\n DelegateNotFoundError,\n type DelegateRow,\n getDelegateCall,\n listDelegatesOf,\n tallyCalls,\n type VerdictTally,\n} from \"./delegates.js\";\nimport { openHumanNeeds } from \"./human-needed.js\";\nimport { emitEvent } from \"./logs.js\";\nimport { taskRevision } from \"./revision.js\";\nimport { ambientFlush, ambientIngest } from \"./sync.js\";\nimport { taskIdFor } from \"./tasks/core.js\";\nimport { TaskNotFoundError } from \"./tasks/errors.js\";\nimport { getTask, getTaskOwner } from \"./tasks/queries.js\";\nimport { DEFAULT_SUBSTATE, type TaskStatus } from \"./tasks/status.js\";\nimport {\n type CursorToken,\n closedToken,\n isConsumed,\n logStallOnce,\n readCursors,\n recordCursors,\n} from \"./wait-cursor.js\";\nimport {\n agentExists,\n agentRowId,\n closeSettledRun,\n openBlockers,\n opsHead,\n reapFlip,\n taskOwnerRowId,\n} from \"./wait-db.js\";\nimport {\n agentSnapshot,\n delegateItem,\n exitFor,\n failedGate,\n type Item,\n inputToken,\n isCompletion,\n refKey,\n registered,\n type StallState,\n sameDeath,\n snapshotsOf,\n urgency,\n} from \"./wait-item.js\";\nimport { type AgentTrack, rearmLatch, supersededBy } from \"./wait-latch.js\";\nimport { agentOwed, hasDoneMark, setAgentDone } from \"./wait-owed.js\";\nimport { compileTextMatcher, type TextMatcher } from \"./wait-regex.js\";\nimport {\n beginWait,\n checkCaller,\n dropOwnedRefs,\n endWait,\n fenceAgentRef,\n type RefBaseline,\n type RegisteredRef,\n readWaitRegistration,\n registerOwnedWait,\n} from \"./wait-registration.js\";\nimport {\n type AgentReading,\n DEFAULT_CTL_STUCK_AFTER_MS,\n DEFAULT_STUCK_AFTER_MS,\n type StallActionResult,\n WAIT_HEARTBEAT_CAP_MS,\n type WaitEventKind,\n WaitNothingError,\n type WaitOptions,\n type WaitRef,\n WaitRefError,\n type WaitResult,\n type WaitSnapshot,\n type WaitStallContext,\n WaveNotFoundError,\n} from \"./wait-types.js\";\n\nlet sleepSeam: ((ms: number) => Promise<void>) | undefined;\n/** Test seam: replace the poll sleep of every wait (undefined restores the abortable timer); returns the previous one. */\nexport function setWaitSleepForTests(\n impl: ((ms: number) => Promise<void>) | undefined,\n): ((ms: number) => Promise<void>) | undefined {\n const previous = sleepSeam;\n sleepSeam = impl;\n return previous;\n}\n\n/** Wait for the next owned event (or all targets). See the file comment. */\nexport async function waitForEvents(\n db: Db,\n input: readonly WaitRef[],\n opts: WaitOptions,\n): Promise<WaitResult> {\n const callers = [...new Set(opts.callers ?? [])];\n for (const c of callers) checkCaller(c);\n const all = opts.mode === \"all\";\n const ownedScope = opts.eventScope !== \"refs\";\n const stuckExplicit = opts.stuckAfterMs;\n const stuckEnabled =\n stuckExplicit !== 0 && opts.status !== \"OPEN\" && opts.status !== \"IN_PROGRESS\";\n const stuckAfter = (viaCtl: boolean): number =>\n stuckExplicit ?? (viaCtl ? DEFAULT_CTL_STUCK_AFTER_MS : DEFAULT_STUCK_AFTER_MS);\n // A wait that owns events (a caller set, or any owned-scope wait: a plain shell or CI\n // naming refs) sees an owner die; the refs-scope adapters never did.\n const watchDeaths = callers.length > 0 || ownedScope;\n const scope = opts.scope;\n const inScope = (workstream: string): boolean => scope === undefined || workstream === scope;\n /** A delegate call is in scope by its own workstream or the workstream of the task it records on. */\n const callInScope = (c: DelegateRow): boolean =>\n scope === undefined || c.workstream === scope || c.record?.workstream === scope;\n // Owners of watched tasks are read for death and for stalls.\n const observeOwners = (watchDeaths || stuckEnabled) && opts.readAgents !== undefined;\n /** The callers consume what they are handed (cursors, registration) only for owned-scope waits. */\n const consumes = ownedScope && callers.length > 0;\n /** An owned-scope wait owns what its callers spawned: the provenance discovery. */\n const target: TaskStatus = opts.status ?? \"CLOSED\";\n const discover = consumes && target === \"CLOSED\";\n const matcher: TextMatcher | undefined =\n typeof opts.until === \"object\" ? compileTextMatcher(opts.until.text) : undefined;\n const applyClose = opts.applyClose !== false;\n const pollMs = opts.pollMs ?? 1000;\n const requested = opts.timeoutMs ?? 0;\n const timeoutMs = opts.uncapped\n ? requested\n : requested === 0\n ? WAIT_HEARTBEAT_CAP_MS\n : Math.min(requested, WAIT_HEARTBEAT_CAP_MS);\n const deadline = timeoutMs > 0 ? Date.now() + timeoutMs : Number.POSITIVE_INFINITY;\n // A reaper flip after this ops seq is news to this wait even if no tick of it saw the owner (a\n // death between two waits, or across a resume): a resume replays the stored anchor.\n const sinceSeq = opts.sinceSeq ?? opsHead(db);\n\n // ─── resolve every ref upfront: typed, exact, nothing ambiguous ───\n for (const ref of input) {\n if (ref.kind === \"task\") {\n if (getTask(db, ref.id, ref.workstream) === undefined) {\n throw new TaskNotFoundError(`${ref.workstream}/${ref.id}`);\n }\n } else if (ref.kind === \"agent\") {\n if (!agentExists(db, ref)) throw new AgentNotFoundError(ref.id);\n } else {\n const call = getDelegateCall(db, ref.id);\n if (call === undefined || call.workstream !== ref.workstream) {\n throw new DelegateNotFoundError(ref.id);\n }\n if (callers.length > 0 && !callers.includes(call.caller)) {\n throw new WaitRefError(`delegate call ${ref.id} belongs to another caller`);\n }\n // A refused call never started and nothing will start it: waiting on it would never end.\n if (call.state === \"refused\") {\n throw new WaitRefError(\n `delegate call ${ref.id} was refused (it never started): reissue it, mu_delegate_reissue`,\n );\n }\n }\n }\n const umbrella =\n opts.blockersOf === undefined\n ? undefined\n : taskIdFor(db, opts.blockersOf.id, opts.blockersOf.workstream);\n if (opts.blockersOf !== undefined && umbrella === null) {\n throw new TaskNotFoundError(`${opts.blockersOf.workstream}/${opts.blockersOf.id}`);\n }\n const explicit = new Map<string, WaitRef>();\n for (const r of input) explicit.set(refKey(r), r);\n if (opts.wave !== undefined && callers.length === 0) {\n throw new WaitRefError(\"wait: a wave belongs to callers; none given (no all-caller fallback)\");\n }\n if (input.length === 0 && !opts.wave && !opts.blockersOf && callers.length === 0) {\n throw new WaitNothingError();\n }\n // A wave is the callers' (never narrowed by the scope): a name none of their calls carry is a typo.\n if (opts.wave !== undefined) {\n const mine = listDelegatesOf(db, callers, opts.wave.workstream);\n if (!mine.some((c) => c.wave === opts.wave?.name)) {\n throw new WaveNotFoundError(\n opts.wave.name,\n mine.map((c) => c.wave),\n );\n }\n }\n\n // ─── one active wait per caller; cursors read before any await ────\n const begun = new Map<string, NonNullable<ReturnType<typeof beginWait>>>();\n if (consumes) {\n for (const c of callers) {\n const b = beginWait(db, c);\n if (b !== undefined) begun.set(c, b);\n }\n }\n const cursorsBy = new Map<string, Map<string, CursorToken>>(\n (consumes ? callers : []).map((c) => [c, readCursors(db, c)]),\n );\n /** Whose registration or delegate call holds `key` (else the first caller: where its token is written). */\n const ownerOfKey = new Map<string, string>();\n /** An urgent observation's cursor key -> the ref key it observes. */\n const baseOfCkey = new Map<string, string>();\n const urgentKey = (kind: string, key: string): string => {\n const k = `${kind}|${key}`;\n baseOfCkey.set(k, key);\n return k;\n };\n const ownerOf = (key: string): string | undefined =>\n ownerOfKey.get(baseOfCkey.get(key) ?? key) ?? callers[0];\n const cursorOf = (key: string): CursorToken | undefined => {\n const o = ownerOf(key);\n return o === undefined ? undefined : cursorsBy.get(o)?.get(key);\n };\n const baselineOf = new Map<string, RefBaseline>();\n /** The agent refs some caller has registered (explicit or not). */\n const ownedKeys = new Set<string>();\n\n // ─── stop signals: abort and the deadline race every await ────────\n const watchAbort = new AbortController();\n let stopReason: \"abort\" | \"deadline\" | undefined;\n let stopNow: (why: \"abort\" | \"deadline\") => void = () => {};\n const stopP = new Promise<void>((resolve) => {\n stopNow = (why) => {\n stopReason ??= why;\n resolve();\n };\n });\n const onAbort = (): void => {\n watchAbort.abort();\n stopNow(\"abort\");\n };\n if (opts.signal?.aborted) onAbort();\n else opts.signal?.addEventListener(\"abort\", onAbort, { once: true });\n const deadlineTimer =\n deadline === Number.POSITIVE_INFINITY\n ? undefined\n : setTimeout(() => stopNow(\"deadline\"), Math.max(0, deadline - Date.now()));\n type Raced<T> = { lost: false; v: T } | { lost: true };\n const within = <T>(p: Promise<T>): Promise<Raced<T>> =>\n Promise.race([\n p.then((v): Raced<T> => ({ lost: false, v })),\n stopP.then((): Raced<T> => ({ lost: true })),\n ]);\n\n // A watch settling wakes the loop; a watch that rejected is fatal.\n let fatal: { error: unknown } | undefined;\n let wake: () => void = () => {};\n let woken = new Promise<void>((resolve) => {\n wake = resolve;\n });\n\n const tracks = new Map<string, AgentTrack>();\n const ownerReadings = new Map<string, AgentReading>();\n /** A wait with no caller owns no durable state: its blockers seen open are remembered for this wait only. */\n const openLocal = new Set<string>();\n const priorTask = new Map<\n string,\n { status: string; owner: string | null; ownerWs: string; ownerId: number }\n >();\n let firstRefresh = true;\n const delivered: Item[] = [];\n\n /**\n * Provenance: the agents a caller spawned (`agents.spawner`) that own an IN_PROGRESS\n * work task, and those tasks, are owed to that caller. They are registered (durably,\n * with a zero run baseline: a worker the caller spawned has no earlier run it must\n * not be handed), so a worker that dies and is reaped is still seen dead.\n */\n const discoverSpawned = (): void => {\n if (!discover) return;\n const rows = db\n .prepare(\n `SELECT a.name AS agent, a.id AS agentId, a.spawner AS spawner, aws.name AS agentWs,\n t.local_id AS task, tws.name AS taskWs\n FROM agents a\n JOIN workstreams aws ON aws.id = a.workstream_id\n JOIN tasks t ON t.owner_id = a.id AND t.status = 'IN_PROGRESS' AND t.kind = 'work'\n JOIN workstreams tws ON tws.id = t.workstream_id AND tws.torn_down_at IS NULL\n WHERE a.spawner IN (${callers.map(() => \"?\").join(\",\")})\n ORDER BY a.id, t.id`,\n )\n .all(...callers) as {\n agent: string;\n agentId: number;\n spawner: string;\n agentWs: string;\n task: string;\n taskWs: string;\n }[];\n const bySpawner = new Map<string, (RegisteredRef & { baseline?: RefBaseline })[]>();\n for (const r of rows) {\n if (!inScope(r.taskWs) && !inScope(r.agentWs)) continue;\n const list = bySpawner.get(r.spawner) ?? [];\n list.push(\n {\n kind: \"agent\",\n workstream: r.agentWs,\n id: r.agent,\n baseline: { afterRuns: 0, agentId: r.agentId },\n },\n { kind: \"task\", workstream: r.taskWs, id: r.task },\n );\n bySpawner.set(r.spawner, list);\n }\n for (const [spawner, refs] of bySpawner) {\n const reg = readWaitRegistration(db, spawner);\n const have = new Set((reg?.refs ?? []).map((r) => refKey(r)));\n const fresh = refs.filter((r) => !have.has(refKey(r)));\n if (fresh.length === 0) continue;\n try {\n registerOwnedWait(db, spawner, fresh);\n } catch {\n // A full or refused registration never fails the wait: what it holds is still waited on.\n }\n }\n };\n\n /** The callers' registered refs, merged (each ref once); records which caller owes which. */\n const ownedRefs = (): WaitRef[] => {\n if (!consumes) return [];\n const out = new Map<string, WaitRef>();\n ownedKeys.clear();\n for (const c of callers) {\n const reg = readWaitRegistration(db, c);\n if (reg === undefined) continue;\n // Owed only while work or a run is owed (src/wait-owed.ts): an agent whose row is gone and\n // which was marked finished is DONE, not dead. Its ref leaves the registration, no event.\n const done = reg.refs.filter(\n (r) => r.kind === \"agent\" && !agentExists(db, r) && hasDoneMark(db, c, r),\n );\n if (done.length > 0) dropOwnedRefs(db, c, done);\n for (const r of reg.refs) {\n if (done.includes(r)) continue;\n if (r.kind !== \"delegate\" && !inScope(r.workstream)) continue;\n const key = refKey(r);\n ownedKeys.add(key);\n if (!out.has(key)) {\n out.set(key, { ...r });\n ownerOfKey.set(key, c);\n }\n const b = reg.baselines[key];\n if (b !== undefined) {\n const old = baselineOf.get(key);\n if (\n old === undefined ||\n (old.incarnation === b.incarnation && b.afterRuns < old.afterRuns)\n ) {\n baselineOf.set(key, b);\n }\n }\n }\n }\n return [...out.values()];\n };\n\n const track = (ref: WaitRef, isExplicit: boolean): AgentTrack => {\n const key = refKey(ref);\n let t = tracks.get(key);\n if (t === undefined) {\n t = {\n ref,\n explicit: isExplicit,\n wasBusy: false,\n baseline: ref.afterRuns,\n handle: undefined,\n needWatch: opts.watchAgent !== undefined,\n result: undefined,\n reading: undefined,\n latched: undefined,\n close: undefined,\n muted: false,\n unknownBaseline: false,\n };\n tracks.set(key, t);\n } else if (isExplicit) t.explicit = true;\n return t;\n };\n\n const setupWatches = async (): Promise<void> => {\n const watch = opts.watchAgent;\n const want = [...tracks.values()].filter((t) => t.needWatch && t.latched === undefined);\n if (watch === undefined || want.length === 0) return;\n for (const t of want) t.needWatch = false;\n const got = await within(\n Promise.all(\n want.map((t) => {\n const key = refKey(t.ref);\n const cur = cursorOf(key);\n const base = baselineOf.get(key);\n return watch(\n { ...t.ref, ...(t.baseline !== undefined ? { afterRuns: t.baseline } : {}) },\n watchAbort.signal,\n {\n owed: ownedKeys.has(key),\n ...(cur !== undefined ? { cursor: cur } : {}),\n ...(base !== undefined ? { baseline: base } : {}),\n },\n );\n }),\n ),\n );\n if (got.lost) return;\n got.v.forEach((h, i) => {\n const t = want[i];\n if (t === undefined || h === undefined) return;\n t.handle = h;\n t.reading = h.initial;\n if (t.baseline === undefined && h.afterRuns !== undefined) t.baseline = h.afterRuns;\n if (h.unknownBaseline !== undefined) {\n // Owed with no fence and no cursor: counted from what the watch probed, and\n // that is stored as the fence so a run settling between waits is still caught.\n t.unknownBaseline = true;\n const key = refKey(t.ref);\n const owner = ownerOf(key);\n if (owner !== undefined && consumes)\n fenceAgentRef(db, owner, registered(t.ref), h.unknownBaseline);\n }\n if (h.initial.status === \"busy\") t.wasBusy = true;\n void h.settled.then(\n (r) => {\n if (t.handle === h) t.result = r;\n wake();\n },\n (error: unknown) => {\n fatal ??= { error };\n wake();\n },\n );\n });\n };\n\n const settle = (t: AgentTrack, r: AgentReading): void => {\n const consumed =\n !t.explicit &&\n r.runs !== undefined &&\n isConsumed(cursorOf(refKey(t.ref)), { incarnation: r.incarnation ?? \"\", runs: r.runs });\n const close = consumed ? undefined : closeSettledRun(db, t.ref, r, applyClose);\n const textOk =\n matcher === undefined ||\n (r.lastError === undefined &&\n (r.lastText ?? \"\").trim() !== \"\" &&\n matcher.test(r.lastText ?? \"\"));\n if (!textOk || consumed) {\n // Not the text asked for, or already delivered: count past this run and wait for the next.\n if (r.runs !== undefined) t.baseline = r.runs;\n t.wasBusy = false;\n t.handle = undefined;\n t.result = undefined;\n t.needWatch = opts.watchAgent !== undefined;\n return;\n }\n t.latched = { kind: \"settled\", reading: r };\n if (close !== undefined) t.close = close;\n };\n\n const rearm = (t: AgentTrack, baseline: number): void =>\n rearmLatch(t, baseline, opts.watchAgent !== undefined);\n\n /** Fold a watch result (`fromWatch`) or a poll reading into the track. */\n const advance = (t: AgentTrack, r: AgentReading, fromWatch: boolean): void => {\n if (t.latched !== undefined) return;\n const pinned = t.ref.incarnation;\n if (pinned !== undefined && r.incarnation !== undefined && r.incarnation !== pinned) {\n throw new AgentRestartedError(t.ref.id, t.ref.workstream, pinned, r.incarnation);\n }\n if (r.blocked === undefined && t.muted) {\n // The dialog is gone: the run goes on; count it again from the same baseline.\n t.muted = false;\n if (opts.watchAgent !== undefined && r.status !== null) {\n t.needWatch = true;\n return;\n }\n }\n if (r.exit !== undefined) {\n // A gate's command ended: its numeric status is the result, never \"dead\", and no busy-first rule applies.\n t.latched = { kind: \"exited\", reading: r };\n } else if (r.status === null) {\n t.latched = { kind: \"dead\", reading: r };\n } else if (r.blocked !== undefined) {\n if (!t.explicit && isConsumed(cursorOf(urgentKey(\"input\", refKey(t.ref))), inputToken(r))) {\n // This dialog was already returned once and is unchanged: not news. The\n // run is polled (a held watch would return blocked again at once).\n t.muted = true;\n t.wasBusy = true;\n t.handle = undefined;\n t.result = undefined;\n t.needWatch = false;\n } else t.latched = { kind: \"input\", reading: r };\n } else if (\n !fromWatch &&\n matcher !== undefined &&\n r.textSource === \"pane\" &&\n r.lastText !== undefined &&\n matcher.test(r.lastText)\n ) {\n // A non-pi pane has no settle and no ctl text: what it printed is the only condition\n // there is. It is its OWN event, never `settled` (no run finished), and it never closes a task.\n t.latched = { kind: \"pane-text\", reading: r };\n } else if (fromWatch) {\n // No settle seen (`unknown`): the watch ends and the agent is polled instead.\n if (r.status === \"unknown\") t.handle = undefined;\n else settle(t, r);\n } else if (r.status === \"busy\") {\n t.wasBusy = true;\n } else if (r.status !== \"unknown\" && t.wasBusy) {\n settle(t, r);\n }\n };\n\n /**\n * Keep each owned agent's DONE mark true to what this tick read (src/wait-owed.ts): done when it\n * owes nothing more (a lost pane is then not a death), cleared when it owes again, left alone\n * when the reading cannot say.\n */\n const ownerOfAgent = (t: AgentTrack): { name: string; workstreamName: string } => ({\n name: t.ref.id,\n workstreamName: t.ref.workstream,\n });\n const markOwed = (): void => {\n if (!consumes) return;\n for (const t of tracks.values()) {\n const key = refKey(t.ref);\n const caller = ownerOfKey.get(key);\n const r = t.latched === undefined ? ownerReadings.get(agentKey(ownerOfAgent(t))) : undefined;\n if (caller === undefined || !ownedKeys.has(key) || r === undefined) continue;\n const id = agentRowId(db, t.ref);\n if (id === 0) continue;\n const owed = agentOwed(db, id, r, baselineOf.get(key), t.unknownBaseline, t.wasBusy);\n if (owed !== \"unsure\")\n setAgentDone(db, t.ref.workstream, t.ref.id, owed === \"done\", [caller]);\n }\n };\n\n /** The async half of an iteration: everything that may take time. */\n const refresh = async (): Promise<void> => {\n if (opts.beforePoll) {\n const b = await within(opts.beforePoll());\n if (b.lost) return;\n }\n if (opts.sync !== false) await ambientIngest(db, { quiet: true });\n discoverSpawned();\n const owned = ownedRefs();\n for (const r of explicit.values()) if (r.kind === \"agent\") track(r, true);\n for (const r of owned) if (r.kind === \"agent\") track(r, explicit.has(refKey(r)));\n await setupWatches();\n if (stopReason !== undefined) return;\n // Owners of watched in-progress tasks ride on the same batched read.\n const reads = new Map<string, WaitRef>();\n for (const t of tracks.values()) {\n // A settled latch is read too: a later run supersedes it.\n if ((t.latched === undefined && t.handle === undefined) || t.latched?.kind === \"settled\") {\n reads.set(refKey(t.ref), t.ref);\n }\n }\n // Owned agents are read for real too (a watch's `initial` is only \"busy\"): what a reading says\n // decides whether the ref is still owed (src/wait-owed.ts).\n if (consumes && opts.readAgents !== undefined) {\n for (const r of owned) {\n const t = r.kind === \"agent\" ? tracks.get(refKey(r)) : undefined;\n if (t !== undefined && t.latched === undefined) reads.set(refKey(r), r);\n }\n }\n if (observeOwners) {\n const taskRefs = [...explicit.values(), ...owned].filter((r) => r.kind === \"task\");\n for (const r of taskRefs) {\n const row = getTask(db, r.id, r.workstream);\n const o = row?.status === \"IN_PROGRESS\" ? getTaskOwner(db, r.id, r.workstream) : undefined;\n if (o !== undefined) {\n const ref: WaitRef = { kind: \"agent\", workstream: o.workstreamName, id: o.name };\n reads.set(refKey(ref), ref);\n }\n }\n }\n for (const t of tracks.values()) {\n const r = t.result;\n if (r === undefined || t.handle === undefined) continue;\n t.result = undefined;\n t.reading = r;\n advance(t, r, true);\n }\n if (reads.size > 0) {\n if (opts.readAgents === undefined) throw new Error(\"wait: an agent reader is required\");\n const got = await within(opts.readAgents([...reads.values()], watchAbort.signal));\n if (got.lost) return;\n ownerReadings.clear();\n for (const ref of reads.values()) {\n const key = agentKey({ name: ref.id, workstreamName: ref.workstream });\n let r = got.v.get(key);\n if (r === undefined) {\n // A caller's own refs: an agent that is gone is dead, not unknown.\n r =\n watchDeaths && !agentExists(db, ref)\n ? { status: null, reason: \"agent is no longer registered\" }\n : { status: \"unknown\", reason: \"state reader returned no row\" };\n }\n ownerReadings.set(key, r);\n const t = tracks.get(refKey(ref));\n const held = t === undefined ? undefined : supersededBy(t, r);\n if (t !== undefined && held !== undefined) {\n // The owner is another identity, or settled a run past the one latched: the latched run is\n // history. Watch again from the new baseline, so the newer run is read and its CLOSE\n // applied; a polled agent latches it now.\n rearm(t, held);\n if (t.needWatch) continue;\n t.wasBusy = true;\n }\n if (t !== undefined && t.latched === undefined && t.handle === undefined) {\n t.reading = r;\n advance(t, r, false);\n }\n }\n }\n markOwed();\n if (firstRefresh) {\n firstRefresh = false;\n const watched = [...tracks.values()].filter((t) => t.explicit);\n if (\n watched.length > 0 &&\n watched.every((t) => (t.latched?.reading ?? t.reading)?.status === \"unknown\")\n ) {\n opts.onInitialUnknown?.(watched.map((t) => agentSnapshot(t)));\n }\n }\n };\n\n // ─── stall detection (the engine's; the policy is handleStall's) ───\n /** Owners whose control socket is broken: first-seen time (the age runs from here). */\n const ctlBrokenSince = new Map<string, number>();\n const stallEmitted = new Set<string>();\n const stallStates = new Map<\n string,\n {\n job?: Promise<void>;\n result?: StallActionResult;\n carry?: { key: string; stall: Item[\"stall\"] };\n }\n >();\n\n /** How long (ms) the owner has needed attention, or null when it does not. */\n const stallAgeMs = (ownerKey: string, r: AgentReading | undefined): number | null => {\n if (r === undefined || r.status === null) return null;\n const alive = true;\n // A pi owner whose control socket does not answer (pane alive): nothing will report it settling.\n if (alive && (r.ctl === \"missing\" || r.ctl === \"refused\")) {\n const first = ctlBrokenSince.get(ownerKey) ?? Date.now();\n ctlBrokenSince.set(ownerKey, first);\n const age = Date.now() - first;\n return age >= stuckAfter(false) ? age : null;\n }\n ctlBrokenSince.delete(ownerKey);\n if (r.status !== \"needs_input\" || r.since === undefined || r.since === null) return null;\n const viaCtl = r.source === \"ctl\" && r.ctl === \"ok\";\n if (viaCtl && r.pending === true) return null;\n const age = Date.now() - r.since;\n return age >= stuckAfter(viaCtl) ? age : null;\n };\n\n /** Make `item` the stall `stall` describes (also how a handled stall outlives its own effect). */\n const markStall = (item: Item, stall: NonNullable<Item[\"stall\"]>): void => {\n const r = stall.owner;\n item.snap.stuck = true;\n item.snap.stuckWhy =\n r.ctl === \"missing\" || r.ctl === \"refused\"\n ? (r.reason ?? `ctl ${r.ctl}`)\n : (r.status ?? \"needs_input\");\n item.snap.stuckSecs = stall.ageSecs;\n if (r.runs !== undefined) item.snap.ownerRuns = r.runs;\n item.kind = \"stall\";\n item.ckey = urgentKey(\"stall\", item.key);\n item.token = { incarnation: `stall:${stall.token}`, runs: 1 };\n item.stall = stall;\n // A stall carried past its own effect (a release cleared the owner) still says whose and why.\n item.snap.owner ??= stall.ownerRef.name;\n item.snap.ownerWorkstream ??= stall.ownerRef.workstreamName;\n if (stall.close !== undefined) item.snap.close = stall.close;\n };\n\n const taskItem = (\n ref: WaitRef,\n want: TaskStatus,\n isTarget: boolean,\n suppressible: boolean,\n order: number,\n ): Item => {\n const row = getTask(db, ref.id, ref.workstream);\n // A task deleted mid-wait reads as OPEN: never reached.\n const status = row?.status ?? \"OPEN\";\n const ownerRef = row === undefined ? undefined : getTaskOwner(db, ref.id, ref.workstream);\n const ownerName = ownerRef?.name ?? row?.ownerName ?? null;\n const snap: WaitSnapshot = {\n ref,\n status,\n substate: row?.substate ?? DEFAULT_SUBSTATE.OPEN,\n owner: ownerName,\n ...(ownerRef !== undefined ? { ownerWorkstream: ownerRef.workstreamName } : {}),\n fired: false,\n dead: false,\n };\n const item: Item = {\n key: refKey(ref),\n ref,\n snap,\n target: isTarget,\n suppressible,\n order,\n done: false,\n ready: false,\n };\n if (row === undefined) return item;\n // The owner died before the task closed: reaper precedence over closure.\n if (watchDeaths && want === \"CLOSED\" && status !== \"CLOSED\") {\n const prior = priorTask.get(item.key);\n const ownerKey = ownerRef === undefined ? undefined : agentKey(ownerRef);\n // The reaper's flip in the ops log (durable): the task's latest status change, after the anchor.\n // A ref a caller registered owes every flip since it was registered (its cursor hides the\n // delivered one); an explicit or blocker ref, those since this wait (or the handle) began.\n const flip =\n status === \"OPEN\" ? reapFlip(db, ref, ownedKeys.has(item.key) ? 0 : sinceSeq) : undefined;\n const dead =\n (ownerKey !== undefined && ownerReadings.get(ownerKey)?.status === null) ||\n // The reaper flip seen live: IN_PROGRESS -> OPEN while the owner's row (that very row) is\n // gone. A release leaves the owner registered; a replaced agent is another row.\n (prior?.status === \"IN_PROGRESS\" &&\n status === \"OPEN\" &&\n prior.owner !== null &&\n prior.ownerId !== 0 &&\n agentRowId(db, { workstream: prior.ownerWs, id: prior.owner }) !== prior.ownerId) ||\n flip !== undefined;\n if (dead) {\n snap.dead = true;\n item.kind = \"dead\";\n item.done = true;\n item.ckey = urgentKey(\"dead\", item.key);\n const rowId =\n ownerRef !== undefined ? taskOwnerRowId(db, ref) : prior?.ownerId || flip?.ownerId || 0;\n item.token = { incarnation: `dead:${rowId}`, runs: 1 };\n const name = ownerRef?.name ?? prior?.owner ?? flip?.ownerName;\n const workstream =\n ownerRef?.workstreamName ?? (prior?.owner != null ? prior.ownerWs : undefined);\n item.death = {\n rowId,\n ...(name != null ? { name } : {}),\n ...(workstream !== undefined ? { workstream } : {}),\n };\n return item;\n }\n }\n // A work task whose owner needs attention: a stall (exit 7), never a close.\n if (\n stuckEnabled &&\n status === \"IN_PROGRESS\" &&\n row.kind === \"work\" &&\n ownerRef !== undefined &&\n want === \"CLOSED\"\n ) {\n const ownerKey = agentKey(ownerRef);\n const r = ownerReadings.get(ownerKey);\n // An owner whose settled run is still on its way (a watched agent with runs past its\n // baseline) is not stalled: the watch delivers that run, and with it the CLOSE block\n // that may close this very task. A stall must never beat an unprocessed settle.\n const watched = tracks.get(\n refKey({ kind: \"agent\", workstream: ownerRef.workstreamName, id: ownerRef.name }),\n );\n const settleOwed =\n watched !== undefined &&\n // the settle is in hand but not delivered yet: under --first it goes first, the stall\n // (if the task is still open after its CLOSE block) is the NEXT wait's news. Under --all\n // a settle is no target and is never delivered before the end: its CLOSE is already\n // applied (settle()), so a task it left open (a malformed block) is a stall NOW.\n ((!all && watched.latched?.kind === \"settled\") ||\n (watched.latched === undefined &&\n (watched.handle !== undefined || watched.needWatch) &&\n r?.runs !== undefined &&\n (watched.baseline ?? 0) < r.runs));\n const age = settleOwed ? null : stallAgeMs(ownerKey, r);\n if (age !== null && r !== undefined) {\n const token = [\n row.workstreamId,\n row.name,\n ownerKey,\n r.incarnation ?? \"\",\n r.runs ?? \"\",\n r.since ?? \"\",\n ].join(\"|\");\n markStall(item, {\n token,\n owner: r,\n ownerRef,\n ageSecs: Math.round(age / 1000),\n // The owner's settled run was refused its CLOSE (a malformed block): say why on the task.\n ...(watched?.close?.applied === false ? { close: watched.close } : {}),\n });\n if (!stallEmitted.has(token)) {\n stallEmitted.add(token);\n // Once per (owner row, pi incarnation, runs) across waits and processes, not per wait. An\n // owner with no run count (no ctl) has only its state's start to tell stalls apart.\n const identity = {\n agentId: r.agentId ?? taskOwnerRowId(db, ref),\n incarnation: `${r.incarnation ?? \"\"}${r.runs === undefined ? `|since:${r.since ?? \"\"}` : \"\"}`,\n runs: r.runs ?? 0,\n };\n logStallOnce(db, ref, identity, () =>\n emitEvent(\n db,\n ref.workstream,\n \"agent.stall\",\n `agent stalled ${ownerRef.name} owns ${ref.id} for ${Math.round(age / 1000)}s`,\n ownerRef.name,\n ),\n );\n }\n return item;\n }\n }\n if (status !== want) return item;\n if (matcher !== undefined) {\n const rep = db\n .prepare(\n `SELECT n.content FROM task_notes n JOIN tasks t ON t.id = n.task_id\n JOIN workstreams w ON w.id = t.workstream_id\n WHERE w.name = ? AND t.local_id = ? AND n.kind = 'report' ORDER BY n.id DESC LIMIT 1`,\n )\n .get(ref.workstream, ref.id) as { content: string } | undefined;\n if (row.substate !== \"done\" || rep === undefined || !matcher.test(rep.content)) return item;\n }\n const note = db\n .prepare(\n `SELECT COALESCE(MAX(n.id), 0) AS n FROM task_notes n JOIN tasks t ON t.id = n.task_id\n JOIN workstreams w ON w.id = t.workstream_id WHERE w.name = ? AND t.local_id = ?`,\n )\n .get(ref.workstream, ref.id) as { n: number };\n snap.fired = true;\n item.kind = \"closed\";\n item.done = true;\n item.token = closedToken(note.n);\n return item;\n };\n\n const agentItem = (t: AgentTrack, isTarget: boolean, order: number): Item => {\n const l = t.latched;\n const r = l?.reading;\n const key = refKey(t.ref);\n let token: CursorToken | undefined;\n let ckey: string | undefined;\n let death: Item[\"death\"];\n if (l?.kind === \"settled\" && r?.runs !== undefined) {\n token = { incarnation: r.incarnation ?? \"\", runs: r.runs };\n } else if (l?.kind === \"input\" && r !== undefined) {\n ckey = urgentKey(\"input\", key);\n token = inputToken(r);\n } else if (l?.kind === \"dead\") {\n ckey = urgentKey(\"dead\", key);\n const rowId = agentRowId(db, t.ref);\n token = { incarnation: `dead:${rowId}`, runs: 1 };\n // A reaped row reads 0: the reading may still say which row it was.\n death = { rowId: rowId || (r?.agentId ?? 0), name: t.ref.id, workstream: t.ref.workstream };\n } else if (l?.kind === \"exited\") {\n // One token per registry row: an owned cursor consumes the result once; a replacement is a new row.\n token = { incarnation: `exited:${agentRowId(db, t.ref)}`, runs: 1 };\n }\n return {\n key,\n ref: t.ref,\n snap: agentSnapshot(t),\n target: isTarget,\n suppressible: !t.explicit,\n order,\n done:\n l?.kind === \"settled\" ||\n l?.kind === \"pane-text\" ||\n l?.kind === \"dead\" ||\n l?.kind === \"exited\",\n ready: false,\n ...(l !== undefined ? { kind: l.kind } : {}),\n ...(token !== undefined ? { token } : {}),\n ...(ckey !== undefined ? { ckey } : {}),\n ...(death !== undefined ? { death } : {}),\n };\n };\n\n const OPEN_TOKEN: CursorToken = { incarnation: \"open\", runs: 1 };\n /** Record (once, durably) that this caller has seen the blocker open. */\n const markOpen = (okey: string): void => {\n if (cursorOf(okey) !== undefined) return;\n const owner = ownerOf(okey);\n if (owner === undefined) return;\n recordCursors(db, owner, [{ key: okey, token: OPEN_TOKEN }]);\n cursorsBy.get(owner)?.set(okey, OPEN_TOKEN);\n };\n\n /** The synchronous half: the current picture, from the DB and what refresh saw. */\n let tally: VerdictTally | undefined;\n const evaluate = (): Item[] => {\n const items: Item[] = [];\n const byKey = new Map<string, Item>();\n let order = 0;\n const push = (it: Item): void => {\n const prev = byKey.get(it.key);\n if (prev !== undefined) {\n prev.target ||= it.target;\n prev.suppressible &&= it.suppressible;\n return;\n }\n byKey.set(it.key, it);\n items.push(it);\n };\n const owned = ownedRefs();\n const calls = new Map<string, { call: DelegateRow; target: boolean; suppressible: boolean }>();\n const addCall = (\n c: DelegateRow | undefined,\n isTarget: boolean,\n suppressible: boolean,\n ): void => {\n // A refused call is not owed (no run will answer it; the tally still counts it).\n if (c === undefined || c.state === \"refused\") return;\n const prev = calls.get(c.callId);\n calls.set(c.callId, {\n call: c,\n target: (prev?.target ?? false) || isTarget,\n suppressible: (prev?.suppressible ?? true) && suppressible,\n });\n };\n for (const r of input) {\n if (r.kind === \"task\") push(taskItem(r, target, true, false, order++));\n else if (r.kind === \"agent\") push(agentItem(track(r, true), true, order++));\n else addCall(getDelegateCall(db, r.id), true, false);\n }\n if (opts.wave !== undefined) {\n // The caller's own calls of the wave, whatever the scope: a delegate lives in `scratch`\n // unless told otherwise, so `-w <ws>` narrowing it would hide the whole wave.\n const waveCalls = listDelegatesOf(db, callers, opts.wave.workstream, {\n wave: opts.wave.name,\n });\n for (const c of waveCalls) addCall(c, true, !all);\n tally = tallyCalls(waveCalls);\n }\n for (const r of owned) {\n if (r.kind !== \"delegate\") continue;\n const c = getDelegateCall(db, r.id);\n if (c !== undefined && callInScope(c)) addCall(c, false, true);\n }\n // Every call the callers made is owed its report; the cursor hides the consumed ones.\n if (consumes) {\n for (const c of listDelegatesOf(db, callers)) {\n if (!callInScope(c)) continue;\n addCall(c, false, true);\n ownerOfKey.set(\n refKey({ kind: \"delegate\", workstream: c.workstream, id: c.callId }),\n c.caller,\n );\n }\n }\n for (const { call, target: isTarget, suppressible } of calls.values()) {\n push(delegateItem(call, isTarget, suppressible, order++));\n }\n if (opts.blockersOf !== undefined && umbrella !== undefined && umbrella !== null) {\n const rows = openBlockers(db, umbrella);\n let open = false;\n let readyBlocker = false;\n for (const b of rows) {\n const ref: WaitRef = { kind: \"task\", workstream: b.ws, id: b.id };\n const it = taskItem(ref, \"CLOSED\", true, !all, order++);\n const okey = urgentKey(\"open\", it.key);\n if (!it.done) {\n open = true;\n // Seen open is durable (the caller's cursor), so a close that a `first`\n // did not return is still owed to the next wait.\n if (consumes) markOpen(okey);\n else openLocal.add(it.key);\n } else if (!all && !(consumes ? cursorOf(okey) !== undefined : openLocal.has(it.key))) {\n // First: a blocker that was never seen open is history, not news.\n it.suppressible = true;\n it.token = undefined;\n it.kind = undefined;\n } else if (it.token === undefined || !isConsumed(cursorOf(it.key), it.token)) {\n readyBlocker = true;\n }\n push(it);\n }\n if (!open && !readyBlocker) {\n const ref: WaitRef = { kind: \"task\", ...opts.blockersOf };\n push({\n key: `blockers:${refKey(ref)}`,\n ref,\n snap: { ref, status: \"CLOSED\", fired: true, dead: false },\n target: true,\n suppressible: false,\n order: order++,\n kind: \"closed\",\n done: true,\n ready: false,\n // A state (\"nothing is left to wait on\"), never news: behind every real event.\n seen: true,\n });\n }\n }\n for (const r of owned) {\n if (r.kind === \"task\") push(taskItem(r, target, false, true, order++));\n }\n for (const r of owned) {\n if (r.kind === \"agent\") push(agentItem(track(r, false), false, order++));\n }\n // Remember each task's owner, to tell a reaper flip from a release.\n for (const it of items) {\n if (it.ref.kind !== \"task\") continue;\n const owner = it.snap.owner ?? null;\n const before = priorTask.get(it.key);\n // Only a tick that SAW an owner records it: after the flip the owner is null.\n const keep = owner === null && it.snap.status === \"OPEN\" ? before : undefined;\n priorTask.set(it.key, {\n status: it.snap.status ?? \"OPEN\",\n owner: owner ?? keep?.owner ?? null,\n ownerWs: it.snap.ownerWorkstream ?? keep?.ownerWs ?? it.ref.workstream,\n ownerId: owner === null ? (keep?.ownerId ?? 0) : taskOwnerRowId(db, it.ref),\n });\n }\n const shown: Item[] = [];\n for (const it of items) {\n const consumed = it.token !== undefined && isConsumed(cursorOf(it.ckey ?? it.key), it.token);\n it.seen ||= consumed;\n const hidden = it.suppressible && consumed;\n it.hidden = hidden;\n it.ready = it.kind !== undefined && !hidden;\n const urgent = it.kind === \"input\" || it.kind === \"stall\" || it.kind === \"dead\";\n // An unchanged urgent observation that was returned is not news again, and\n // not \"done\": the ref is still owed its completion.\n if (hidden && urgent) it.done = false;\n // Consumed owned history is no longer owed: it is not part of the picture.\n if (hidden && !it.target && !urgent) continue;\n shown.push(it);\n }\n return shown;\n };\n\n /**\n * Hand each stall to `handleStall` (raced: the job runs beside the loop and\n * wakes it), once per stallToken. A stall stays unselectable while its job is\n * out or after a `continue`; `return` (or no handler) makes it the event.\n */\n const driveStalls = (items: Item[]): void => {\n const handler = opts.handleStall;\n // A handler that returned `return` may have removed the very condition (a\n // release leaves the task OPEN and unowned): the stall is still what this\n // wait reports, with the task as it is now.\n for (const st of stallStates.values()) {\n if (st.job !== undefined || st.result?.disposition !== \"return\" || st.carry === undefined) {\n continue;\n }\n const { key, stall } = st.carry;\n const gone = items.find((i) => i.key === key && i.kind !== \"stall\");\n if (gone !== undefined && stall !== undefined) {\n markStall(gone, stall);\n gone.hidden = false;\n }\n }\n for (const it of items) {\n if (it.stall === undefined || it.kind !== \"stall\" || it.hidden === true) continue;\n // `warn`: flagged (`stuck`, the agent.stall event), never returned: the wait goes on.\n if (opts.onStall === \"warn\") {\n it.ready = false;\n continue;\n }\n const steering = opts.onStall === \"steer\" || opts.onStall === \"release\";\n const caller = ownerOf(it.key);\n if (!steering || handler === undefined || caller === undefined) {\n it.ready = true;\n continue;\n }\n const { token, owner, ownerRef } = it.stall;\n let st = stallStates.get(token);\n if (st === undefined) {\n const own = db\n .prepare(\n `SELECT a.id, a.pane_id FROM agents a JOIN workstreams w ON w.id = a.workstream_id\n WHERE a.name = ? AND w.name = ?`,\n )\n .get(ownerRef.name, ownerRef.workstreamName) as\n | { id: number; pane_id: string }\n | undefined;\n const taskId = taskIdFor(db, it.ref.id, it.ref.workstream);\n if (own === undefined || taskId === null) {\n it.ready = true;\n continue;\n }\n const ctx: WaitStallContext = {\n caller,\n generation: begun.get(caller)?.generation ?? null,\n ref: it.ref,\n taskId,\n revision: taskRevision(db, it.ref.workstream, it.ref.id),\n owner: {\n workstream: ownerRef.workstreamName,\n name: ownerRef.name,\n agentId: owner.agentId ?? own.id,\n paneId: owner.paneId ?? own.pane_id,\n status: owner.status,\n source: owner.source ?? \"none\",\n since: owner.since ?? null,\n settled: false,\n ...(owner.ctl !== undefined ? { ctl: owner.ctl } : {}),\n ...(owner.incarnation !== undefined ? { incarnation: owner.incarnation } : {}),\n ...(owner.runs !== undefined ? { runs: owner.runs } : {}),\n ...(owner.pending !== undefined ? { pending: owner.pending } : {}),\n ...(owner.reason !== undefined ? { reason: owner.reason } : {}),\n },\n stallToken: token,\n deadlineMs: Number.isFinite(deadline)\n ? Math.max(0, deadline - Date.now())\n : Number.MAX_SAFE_INTEGER,\n signal: watchAbort.signal,\n };\n const fresh: StallState = {};\n const action = opts.onStall === \"release\" ? \"release\" : \"steer\";\n fresh.job = Promise.resolve()\n .then(() => handler(ctx))\n .catch(\n (e: unknown): StallActionResult => ({\n disposition: \"return\",\n action,\n state: \"unknown\",\n reason: e instanceof Error ? e.message : String(e),\n }),\n )\n .then((res) => {\n fresh.result = res;\n fresh.job = undefined;\n // The owner's next run counts from the actual send baseline.\n const t = tracks.get(\n refKey({\n kind: \"agent\",\n ...{ workstream: ownerRef.workstreamName, id: ownerRef.name },\n }),\n );\n if (t !== undefined && res.afterRuns !== undefined) {\n // A latched settle is the run this steer answers (under --all a stall may stand past\n // it): drop it and watch again from the send baseline, or the owner's NEXT run (and its\n // CLOSE) is never read. Any other latch (dead, input, ...) stays.\n if (t.latched?.kind === \"settled\") rearm(t, res.afterRuns);\n else if (t.latched === undefined) {\n t.baseline = res.afterRuns;\n t.wasBusy = false;\n }\n }\n wake();\n });\n fresh.carry = { key: it.key, stall: it.stall };\n st = fresh;\n stallStates.set(token, st);\n }\n it.ready = st.job === undefined && st.result?.disposition === \"return\";\n }\n };\n\n const select = (items: Item[]): { event: Item; fired: Item[] } | undefined => {\n const rank = (a: Item, b: Item): number =>\n // Never-returned events first: an event that was already returned once (an\n // unchanged dialog, a dead pane, a stall) never outranks one that was not.\n Number(a.seen === true) - Number(b.seen === true) ||\n urgency(a.kind) - urgency(b.kind) ||\n // Under --all a failed gate is the firing event, so its code is the exit.\n Number(failedGate(b)) - Number(failedGate(a)) ||\n Number(b.target) - Number(a.target) ||\n a.order - b.order;\n const ready = items.filter((i) => i.ready).sort(rank);\n if (!all) {\n const best = ready[0];\n if (best === undefined) return undefined;\n // One fact, one event: a settled run whose CLOSE block closed task T, and T's own close,\n // are the same news. Delivering either consumes the other, so the second is not owed.\n const same = (a: Item, b: Item): boolean =>\n a.kind === \"settled\" &&\n a.ref.kind === \"agent\" &&\n a.snap.close?.applied === true &&\n a.snap.close.task === b.ref.id &&\n a.ref.workstream === b.ref.workstream &&\n b.ref.kind === \"task\" &&\n b.kind === \"closed\";\n const companions = ready.filter(\n (i) => i !== best && (same(i, best) || same(best, i) || sameDeath(i, best)),\n );\n return { event: best, fired: [best, ...companions] };\n }\n const urgent = ready.find(\n (i) =>\n i.kind === \"input\" ||\n i.kind === \"stall\" ||\n (!i.target && (i.kind === \"dead\" || i.kind === \"delegate\")),\n );\n if (urgent !== undefined) {\n const companions = ready.filter((i) => i !== urgent && sameDeath(i, urgent));\n return { event: urgent, fired: [urgent, ...companions] };\n }\n const targets = items.some((i) => i.target) ? items.filter((i) => i.target) : items;\n if (targets.length === 0 || !targets.every((i) => i.done)) return undefined;\n const sorted = [...targets].sort(rank);\n const best = sorted.find((i) => i.ready) ?? sorted[0];\n return best === undefined ? undefined : { event: best, fired: targets.filter((i) => i.done) };\n };\n\n const build = (\n kind: WaitEventKind,\n items: Item[],\n chosen?: { event: Item; fired: Item[] },\n drained = false,\n ): WaitResult => {\n const e = chosen?.event;\n for (const f of chosen?.fired ?? []) delivered.push(f);\n return {\n event: {\n kind,\n ref: e?.ref ?? null,\n ...(e?.snap.incarnation !== undefined ? { incarnation: e.snap.incarnation } : {}),\n ...(e?.snap.runs !== undefined ? { runs: e.snap.runs } : {}),\n },\n refs: snapshotsOf(items, chosen?.fired ?? []),\n delivered: (chosen?.fired ?? []).filter(isCompletion).map((i) => i.ref),\n timedOut: kind === \"heartbeat\" && !drained,\n interrupted: kind === \"interrupted\",\n exit:\n exitFor(kind) !== 0\n ? exitFor(kind)\n : ((chosen?.fired ?? []).find(failedGate)?.snap.exit ?? 0),\n cursor: {},\n ...(e?.stall !== undefined && stallStates.get(e.stall.token)?.result !== undefined\n ? { action: stallStates.get(e.stall.token)?.result as StallActionResult }\n : {}),\n humanNeeds: callers.flatMap((c) => openHumanNeeds(db, c)),\n sinceSeq,\n ...(tally !== undefined ? { tally } : {}),\n ...(drained ? { drained: true } : {}),\n };\n };\n\n const rethrow = (): void => {\n if (fatal === undefined) return;\n watchAbort.abort();\n throw fatal.error;\n };\n\n let committed = false;\n let applied = true;\n /**\n * Deliver what `build` handed out, in ONE immediate transaction: re-read the callers' cursors (a\n * wait in another process may have consumed `event` since this one read them), then end each\n * caller's wait and record the tokens. A returned event is consumed (its token written); a\n * completed one also leaves the registration; an urgent one (input, stall, a dead task) stays\n * owed. false = `event` is already consumed: nothing is written, `delivered` is cleared and the\n * caller selects again (with the cursors just read). Without a consuming caller: a no-op.\n */\n const commit = (event?: Item): boolean => {\n if (!consumes) return true;\n const ok = db\n .transaction((): boolean => {\n for (const c of callers) cursorsBy.set(c, readCursors(db, c));\n if (\n // Only news this wait saw as unconsumed can turn stale; the re-read hides it next time.\n event?.token !== undefined &&\n event.ready &&\n event.suppressible &&\n isConsumed(cursorOf(event.ckey ?? event.key), event.token)\n ) {\n return false;\n }\n const completed = delivered.filter(isCompletion);\n // Each delivered ref is consumed by the caller that owns it, guarded by that caller's\n // wait generation.\n for (const c of callers) {\n const mine = completed.filter((i) => ownerOf(i.key) === c);\n const tokens = delivered\n .filter((i) => i.token !== undefined && ownerOf(i.ckey ?? i.key) === c)\n .flatMap((i) =>\n i.token === undefined ? [] : [{ key: i.ckey ?? i.key, token: i.token }],\n );\n const b = begun.get(c);\n if (b !== undefined) {\n const ended = endWait(\n db,\n c,\n b.generation,\n mine.map((i) => ({\n ...registered(i.ref),\n ...(i.kind === \"settled\" && i.snap.runs !== undefined\n ? {\n runs: i.snap.runs,\n ...(i.snap.incarnation !== undefined\n ? { incarnation: i.snap.incarnation }\n : {}),\n }\n : {}),\n })),\n );\n if (!ended.applied) {\n applied = false;\n continue;\n }\n }\n recordCursors(db, c, tokens);\n }\n return true;\n })\n .immediate();\n if (ok) committed = true;\n else delivered.length = 0;\n return ok;\n };\n\n let result: WaitResult | undefined;\n try {\n for (;;) {\n if (stopReason === \"abort\") {\n // The final snapshot is the state NOW (a DB read), not the last tick's picture:\n // a task that closed while the signal was on its way is reported closed.\n result = build(\"interrupted\", evaluate());\n break;\n }\n if (stopReason === \"deadline\" || Date.now() >= deadline) {\n const items = evaluate();\n driveStalls(items);\n const chosen = select(items);\n const r = chosen\n ? build(chosen.event.kind ?? \"closed\", items, chosen)\n : build(\"heartbeat\", items);\n if (!commit(chosen?.event)) continue;\n result = r;\n break;\n }\n await refresh();\n rethrow();\n if (stopReason === \"abort\") continue;\n const items = evaluate();\n driveStalls(items);\n opts.onPicture?.(items.map((i) => i.snap));\n if (items.length === 0) throw new WaitNothingError();\n const chosen = select(items);\n if (chosen !== undefined) {\n const r = build(chosen.event.kind ?? \"closed\", items, chosen);\n // Consumed by another process since this wait read its cursors: select again.\n if (!commit(chosen.event)) continue;\n result = r;\n break;\n }\n if (!all && items.every((i) => i.done)) {\n // Everything is done and already delivered: nothing is owed.\n result = build(\"heartbeat\", items, undefined, true);\n break;\n }\n if (stopReason !== undefined) continue;\n // Poll only what a watch does not cover: DB-backed refs, a caller's\n // registration and polled agents. All agents watched: sleep until a\n // settle, the deadline or an abort.\n const polled =\n watchDeaths ||\n observeOwners ||\n items.some((i) => i.ref.kind !== \"agent\") ||\n [...tracks.values()].some((t) => t.latched === undefined && t.handle === undefined);\n const left = deadline - Date.now();\n const ms = polled ? Math.min(pollMs, left) : left;\n if (ms <= 0) continue;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const sleeper = opts.sleep ?? sleepSeam;\n const slept = !polled\n ? new Promise<void>(() => {})\n : sleeper\n ? sleeper(ms)\n : new Promise<void>((resolve) => {\n timer = setTimeout(resolve, ms);\n });\n await Promise.race([woken, slept, stopP]);\n clearTimeout(timer);\n woken = new Promise<void>((resolve) => {\n wake = resolve;\n });\n rethrow();\n }\n } finally {\n clearTimeout(deadlineTimer);\n opts.signal?.removeEventListener(\"abort\", onAbort);\n watchAbort.abort();\n if (consumes) {\n if (!committed) commit();\n if (result !== undefined) {\n result.cursor = Object.fromEntries(callers.flatMap((c) => [...readCursors(db, c)]));\n if (!applied) result.superseded = true;\n }\n } else if (result !== undefined) result.cursor = {};\n if (opts.sync !== false) await ambientFlush(db, { quiet: true });\n }\n return result as WaitResult;\n}\n\nexport * from \"./wait-types.js\";\n","// mu — wait action receipts: the exclusion and journal of stall actions.\n//\n// One row per (task, owner, ctl incarnation, action) in the machine-local\n// `wait_action_receipts` table. The identity is deliberately NOT the wait\n// generation, the task revision or the caller: every caller, restart and\n// generation of a wait shares one exclusion, so a stalled worker is nudged\n// once and released once per incarnation, however many waits see the stall.\n//\n// `task_id` and `owner_id` are `tasks.id` / `agents.id` with NO foreign key:\n// the row is evidence that an effect may have happened and must outlive both.\n// `incarnation` is pi's process incarnation ('' when ctl named none).\n//\n// States and their edges (anything else throws; history is never rewritten):\n// reserved -> sending | refused | released\n// sending -> sent | unknown | refused\n// (sending is \"the write MAY have happened\";\n// refused = pi answered ok:false, so it did not)\n// unknown -> sent (a receipt probe on the SAME saved registry,\n// pane and incarnation confirmed it)\n// Pure SQL: no mux, no ctl, no transaction of its own (each call is one\n// statement; callers that need more wrap their own).\n\nimport type { Db, WaitAction, WaitActionState } from \"./db.js\";\n\nexport interface ActionKey {\n /** `tasks.id`. */\n taskId: number;\n /** `agents.id` of the owner when the action was taken. */\n ownerId: number;\n /** pi's ctl incarnation; '' when none. */\n incarnation: string;\n action: WaitAction;\n}\n\n/** What a reservation records about the situation. */\nexport interface ActionInfo {\n /** Who asked (one of the caller set); attribution only, not identity. */\n caller: string;\n /** `<workstream>/<task>`. */\n taskRef: string;\n /** `<workstream>/<agent>`. */\n ownerRef: string;\n paneId: string;\n /** The task revision the action was decided against. */\n previewRevision: number;\n}\n\nexport interface ActionReceipt extends ActionKey, ActionInfo {\n msgId: string | null;\n state: WaitActionState;\n runs: number | null;\n detail: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\ninterface Raw {\n task_id: number;\n owner_id: number;\n incarnation: string;\n action: WaitAction;\n caller: string;\n task_ref: string;\n owner_ref: string;\n pane_id: string;\n preview_revision: number;\n msg_id: string | null;\n state: WaitActionState;\n runs: number | null;\n detail: string | null;\n created_at: string;\n updated_at: string;\n}\n\nconst fromRaw = (r: Raw): ActionReceipt => ({\n taskId: r.task_id,\n ownerId: r.owner_id,\n incarnation: r.incarnation,\n action: r.action,\n caller: r.caller,\n taskRef: r.task_ref,\n ownerRef: r.owner_ref,\n paneId: r.pane_id,\n previewRevision: r.preview_revision,\n msgId: r.msg_id,\n state: r.state,\n runs: r.runs,\n detail: r.detail,\n createdAt: r.created_at,\n updatedAt: r.updated_at,\n});\n\nconst EDGES: Record<WaitActionState, readonly WaitActionState[]> = {\n reserved: [\"sending\", \"refused\", \"released\"],\n sending: [\"sent\", \"unknown\", \"refused\"],\n unknown: [\"sent\"],\n sent: [],\n refused: [],\n released: [],\n};\n\nexport function getActionReceipt(db: Db, key: ActionKey): ActionReceipt | undefined {\n const row = db\n .prepare(\n `SELECT * FROM wait_action_receipts\n WHERE task_id = ? AND owner_id = ? AND incarnation = ? AND action = ?`,\n )\n .get(key.taskId, key.ownerId, key.incarnation, key.action) as Raw | undefined;\n return row === undefined ? undefined : fromRaw(row);\n}\n\n/**\n * Reserve the exclusion. `created: true` means THIS call made the row and\n * owns the action; `false` returns the row that is already there (whoever\n * wrote it, in whatever state). One statement: concurrent connections race\n * on the primary key and exactly one wins.\n */\nexport function reserveActionReceipt(\n db: Db,\n key: ActionKey,\n info: ActionInfo & {\n /** The id a ctl send will carry: reserved WITH the row, so a resumer reuses it and a crash leaves one to probe. */\n msgId?: string;\n },\n): { created: boolean; receipt: ActionReceipt } {\n const now = new Date().toISOString();\n const res = db\n .prepare(\n `INSERT OR IGNORE INTO wait_action_receipts\n (task_id, owner_id, incarnation, action, caller, task_ref, owner_ref, pane_id,\n preview_revision, msg_id, state, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'reserved', ?, ?)`,\n )\n .run(\n key.taskId,\n key.ownerId,\n key.incarnation,\n key.action,\n info.caller,\n info.taskRef,\n info.ownerRef,\n info.paneId,\n info.previewRevision,\n info.msgId ?? null,\n now,\n now,\n );\n const receipt = getActionReceipt(db, key);\n if (receipt === undefined) throw new Error(\"wait action receipt vanished after reservation\");\n return { created: res.changes === 1, receipt };\n}\n\n/**\n * Compare-and-set `from` -> `to`: true iff this call moved the row. False\n * when the row is absent or no longer in `from` (someone else won). A\n * `from`/`to` pair that is not an edge throws. Patch fields left undefined\n * keep their stored value.\n */\nexport function transitionActionReceipt(\n db: Db,\n key: ActionKey,\n from: WaitActionState,\n to: WaitActionState,\n patch: { msgId?: string; runs?: number; detail?: string } = {},\n): boolean {\n if (!EDGES[from].includes(to)) {\n throw new Error(`wait action receipt: illegal transition ${from} -> ${to}`);\n }\n const res = db\n .prepare(\n `UPDATE wait_action_receipts\n SET state = ?, msg_id = COALESCE(?, msg_id), runs = COALESCE(?, runs),\n detail = COALESCE(?, detail), updated_at = ?\n WHERE task_id = ? AND owner_id = ? AND incarnation = ? AND action = ? AND state = ?`,\n )\n .run(\n to,\n patch.msgId ?? null,\n patch.runs ?? null,\n patch.detail ?? null,\n new Date().toISOString(),\n key.taskId,\n key.ownerId,\n key.incarnation,\n key.action,\n from,\n );\n return res.changes === 1;\n}\n","// mu — stall actions of a wait: the guarded release (C1) and the crash-safe\n// steer (C2).\n//\n// The engine (wait.ts) DETECTS a stall and hands it to `handleStall`; this\n// module is the policy and the effect. `releaseStall` frees the stalled\n// task so another worker can take it; it never closes the task, spawns or\n// kills. `steerStall` sends the owner ONE fixed reminder over its ctl socket\n// (see below).\n//\n// Every guard is evaluated in the SAME immediate transaction as the write\n// (`withOpContext` owns BEGIN IMMEDIATE), synchronously: no await sits inside,\n// so permission, ownership and the revision cannot change between the check\n// and the release. A refused release writes NOTHING (no op, no note, no\n// receipt). A throw inside rolls the whole transaction back, so \"refused\" with\n// the error is exact: nothing happened. The runtime state (`needs_input`) is\n// the engine's observation at the stall; the revision fence is what proves the\n// task did not move since.\n//\n// Eligible only when ALL hold: the aborted flag is clear; ctx.caller is in the\n// caller set; its wait is still the registered generation (null = an\n// unregistered explicit wait, which is NOT a bypass of the ownership checks);\n// the task (by primary key, matching ctx.ref) is an IN_PROGRESS `work` task at\n// the revision the stall saw, owned by the very agent row of ctx.owner (same\n// registry id, name, workstream and pane) that one of the callers spawned; the\n// owner needs attention (needs_input, or a broken ctl on a live pane; never a\n// permission dialog, a dead pane or a busy run); `autoPermitted` (enabled\n// task_auto, work, this host); and none of the callers has an open human stop.\n// One release per (task, owner, ctl incarnation): a second is\n// `budget-exhausted`, shared across callers, restarts and generations.\n//\n// STEER is at-most-once by SQLite, never by the msgId: the real extension\n// remembers msgIds but does NOT dedupe sends. One synchronous immediate\n// transaction guards and reserves the row (state `reserved`, msgId saved with\n// it). Then, over ctl, hello and incarnation bind first; the LAST step before\n// the write is `beforeWrite` (client.ts, on connect, synchronous): it re-runs\n// every guard and compare-and-sets reserved -> sending in one immediate\n// transaction. Only that CAS winner writes; a guard that fails there leaves the\n// row `reserved` (nothing was sent: the budget is not burned). After the CAS the\n// write MAY have happened, so every failure but pi's own ok:false is `unknown`\n// and stays that way: a row found in `sending`/`unknown` (a crash, a timeout)\n// is only ever PROBED (`status {msgId}` on the same saved registry id, pane and\n// incarnation), never resent, and never turned into a release. Reserved and\n// then crashed before the CAS: a resumer contends for the CAS with the saved\n// msgId. Post-send storage failure keeps `sending`: the exclusion survives.\n\nimport { AgentReplacedError, AgentSendRefusedError } from \"./agents/errors.js\";\nimport { agentCtlSocket, checkMessage, recordSend, sendViaTransport } from \"./agents/transport.js\";\nimport { getAgent } from \"./agents.js\";\nimport { CTL_DEFAULT_TIMEOUT_MS, CtlWriteVetoedError, newMsgId } from \"./ctl/client.js\";\nimport type { Db } from \"./db.js\";\nimport { openHumanNeeds } from \"./human-needed.js\";\nimport { withOpContext } from \"./op-context.js\";\nimport { taskRevision } from \"./revision.js\";\nimport { autoPermitted } from \"./task-auto.js\";\nimport { releaseTask } from \"./tasks/claim.js\";\nimport { type WaitOptions, type WaitResult, waitForEvents } from \"./wait.js\";\nimport {\n type ActionKey,\n getActionReceipt,\n reserveActionReceipt,\n transitionActionReceipt,\n} from \"./wait-action-receipts.js\";\nimport { currentCallers } from \"./wait-callers.js\";\nimport { readWaitRegistration } from \"./wait-registration.js\";\nimport type { StallActionResult, WaitRef, WaitStallContext } from \"./wait-types.js\";\n\nexport interface StallActionOptions {\n /** The caller set of this process (default: `currentCallers()`). */\n callers?: readonly string[];\n}\n\nconst refused = (reason: string, action: StallActionResult[\"action\"]): StallActionResult => ({\n disposition: \"return\",\n action,\n state: \"refused\",\n reason,\n});\n\ninterface TaskGuardRow {\n local_id: string;\n workstream: string;\n status: string;\n kind: string;\n owner_id: number | null;\n}\n\ninterface AgentGuardRow {\n name: string;\n pane_id: string;\n spawner: string | null;\n}\n\n/** What a passed guard found, for the action to use. */\ninterface Guarded {\n localId: string;\n workstream: string;\n ownerId: number;\n ownerName: string;\n paneId: string;\n}\n\n/**\n * Every condition a stall action needs, evaluated synchronously (the caller\n * holds an immediate transaction) against the DB as it is NOW. `null` reason =\n * eligible. Shared by release and steer; steer additionally needs a readable,\n * healthy ctl (it can only be sent through it).\n */\nfunction guardStall(\n db: Db,\n ctx: WaitStallContext,\n callers: readonly string[],\n action: StallActionResult[\"action\"],\n): { ok: true; found: Guarded } | { ok: false; reason: string } {\n const no = (reason: string) => ({ ok: false as const, reason });\n if (ctx.signal.aborted) return no(\"the wait was aborted\");\n if (!callers.includes(ctx.caller)) {\n return no(`caller ${ctx.caller} is not one of this process's callers`);\n }\n if (ctx.generation !== null) {\n const reg = readWaitRegistration(db, ctx.caller);\n if (reg === undefined || reg.generation !== ctx.generation) {\n return no(\"the wait was superseded (generation changed)\");\n }\n }\n const task = db\n .prepare(\n `SELECT t.local_id, w.name AS workstream, t.status, t.kind, t.owner_id\n FROM tasks t JOIN workstreams w ON w.id = t.workstream_id WHERE t.id = ?`,\n )\n .get(ctx.taskId) as TaskGuardRow | undefined;\n if (task === undefined) return no(\"the task no longer exists\");\n if (task.local_id !== ctx.ref.id || task.workstream !== ctx.ref.workstream) {\n return no(\"the ref does not name this task\");\n }\n if (task.kind !== \"work\") return no(`a ${task.kind} task is never ${action}d`);\n if (task.status !== \"IN_PROGRESS\") return no(`the task is ${task.status}, not IN_PROGRESS`);\n if (task.owner_id === null || task.owner_id !== ctx.owner.agentId) {\n return no(\"the task's owner is no longer the stalled agent\");\n }\n // The owner is the registry row the stall saw (id), still on the pane it saw.\n const agent = db\n .prepare(\"SELECT a.name, a.pane_id, a.spawner FROM agents a WHERE a.id = ?\")\n .get(task.owner_id) as AgentGuardRow | undefined;\n if (agent === undefined) return no(\"the owner is no longer registered\");\n if (agent.pane_id !== ctx.owner.paneId) return no(\"the owner's pane changed (pane mismatch)\");\n if (agent.spawner === null || !callers.includes(agent.spawner)) {\n return no(\"the owner was not spawned by this caller (not yours to act on)\");\n }\n if (action === \"steer\") {\n if (ctx.owner.status !== \"needs_input\" || ctx.owner.ctl !== \"ok\") {\n return no(`the owner is not idle on a healthy control socket (state ${ctx.owner.status})`);\n }\n if (ctx.owner.incarnation === undefined || ctx.owner.incarnation === \"\") {\n return no(\"the owner's pi named no incarnation: a steer could not be bound to it\");\n }\n } else {\n const brokenCtl = ctx.owner.ctl === \"missing\" || ctx.owner.ctl === \"refused\";\n const needsAttention =\n ctx.owner.status === \"needs_input\" ||\n (brokenCtl && (ctx.owner.status === \"unknown\" || ctx.owner.status === \"busy\"));\n if (!needsAttention) {\n return no(`the owner is not waiting on anyone (runtime state ${ctx.owner.status})`);\n }\n }\n if (!autoPermitted(db, ctx.taskId)) {\n return no(\"the task is not permitted for auto action on this machine (mu task auto)\");\n }\n if (callers.some((c) => openHumanNeeds(db, c).length > 0)) {\n return no(\"a human stop is open for this caller: leave the stall to the human\");\n }\n const revision = taskRevision(db, task.workstream, task.local_id);\n if (revision !== ctx.revision) {\n return no(\n `the task changed since the stall was seen (revision ${ctx.revision} -> ${revision})`,\n );\n }\n return {\n ok: true,\n found: {\n localId: task.local_id,\n workstream: task.workstream,\n ownerId: task.owner_id,\n ownerName: agent.name,\n paneId: agent.pane_id,\n },\n };\n}\n\nconst keyOf = (ctx: WaitStallContext, ownerId: number, action: ActionKey[\"action\"]): ActionKey => ({\n taskId: ctx.taskId,\n ownerId,\n incarnation: ctx.owner.incarnation ?? \"\",\n action,\n});\n\nconst infoOf = (ctx: WaitStallContext, f: Guarded) => ({\n caller: ctx.caller,\n taskRef: `${f.workstream}/${f.localId}`,\n ownerRef: `${ctx.owner.workstream}/${f.ownerName}`,\n paneId: f.paneId,\n previewRevision: ctx.revision,\n});\n\n/** The release body: runs inside one immediate transaction. */\nfunction releaseBody(db: Db, ctx: WaitStallContext, callers: readonly string[]): StallActionResult {\n const g = guardStall(db, ctx, callers, \"release\");\n if (!g.ok) return refused(g.reason, \"release\");\n const { found } = g;\n const key = keyOf(ctx, found.ownerId, \"release\");\n if (getActionReceipt(db, key) !== undefined) {\n return {\n disposition: \"return\",\n action: \"release\",\n state: \"budget-exhausted\",\n reason: \"this owner incarnation was already released once for this task\",\n };\n }\n const res = releaseTask(db, found.localId, {\n workstream: found.workstream,\n expectedOwnerId: found.ownerId,\n ifRevision: ctx.revision,\n author: ctx.caller,\n evidence: `stall: ${found.ownerName} needed attention (stall ${ctx.stallToken}); released for another worker`,\n });\n // Defence: the guards above already hold in this transaction.\n if (!res.changed) return refused(\"the release changed nothing\", \"release\");\n reserveActionReceipt(db, key, infoOf(ctx, found));\n transitionActionReceipt(db, key, \"reserved\", \"released\", {\n detail: `released from ${found.ownerName}`,\n });\n return {\n disposition: \"return\",\n action: \"release\",\n state: \"released\",\n ...(ctx.owner.incarnation !== undefined ? { incarnation: ctx.owner.incarnation } : {}),\n reason: `released ${found.localId} from ${found.ownerName}`,\n };\n}\n\n/**\n * Release the stalled task if every guard still holds, atomically; else report\n * why not and change nothing. Always `disposition: \"return\"`: the caller gets\n * an actionable snapshot, the wait does not go on watching a freed task.\n */\nexport async function releaseStall(\n db: Db,\n ctx: WaitStallContext,\n opts: StallActionOptions = {},\n): Promise<StallActionResult> {\n const callers = opts.callers ?? currentCallers();\n try {\n return withOpContext(db, { intent: \"task.release\", actor: ctx.caller, group: \"new\" }, () =>\n releaseBody(db, ctx, callers),\n );\n } catch (e) {\n // The transaction rolled back: nothing was written.\n return refused(\n `release failed, nothing changed: ${e instanceof Error ? e.message : String(e)}`,\n \"release\",\n );\n }\n}\n\n/** `handleStall` for `onStall: 'release'`. */\nexport function releaseStallHandler(\n db: Db,\n opts: StallActionOptions = {},\n): (ctx: WaitStallContext) => Promise<StallActionResult> {\n return (ctx) => releaseStall(db, ctx, opts);\n}\n\n// ─── steer ───────────────────────────────────────────────────────────────\n\n/**\n * The one reminder a stalled worker gets: fixed, plain text, bounded (a task\n * id is a short name). Never carries worker output, notes or free text.\n */\nexport function steerText(workstream: string, taskId: string): string {\n return `[mu] ${workstream}/${taskId} is still yours (IN_PROGRESS) and mu is waiting on it. If the work is done and verified, close it: mu task close ${taskId} -w ${workstream} --evidence \"<what you verified>\". If you are blocked or need an answer, say so in one line and stop.`;\n}\n\nconst steerResult = (\n state: StallActionResult[\"state\"],\n disposition: StallActionResult[\"disposition\"],\n extra: Partial<StallActionResult> = {},\n): StallActionResult => ({ disposition, action: \"steer\", state, ...extra });\n\ntype SteerPlan =\n | { kind: \"done\"; result: StallActionResult }\n | { kind: \"probe\"; msgId: string; key: ActionKey; paneId: string; state: \"sending\" | \"unknown\" }\n | { kind: \"send\"; msgId: string; key: ActionKey; found: Guarded };\n\n/**\n * Plan the steer in ONE synchronous immediate transaction (no await): what the\n * receipt says decides, then the guards, then the reservation. A row past\n * `reserved` is never sent again, whatever the guards say now.\n */\nfunction planSteer(db: Db, ctx: WaitStallContext, callers: readonly string[]): SteerPlan {\n return db\n .transaction((): SteerPlan => {\n const key = keyOf(ctx, ctx.owner.agentId, \"steer\");\n const have = getActionReceipt(db, key);\n if (have !== undefined && have.state !== \"reserved\") {\n if (have.state === \"sending\" || have.state === \"unknown\") {\n if (have.msgId === null) {\n return {\n kind: \"done\",\n result: steerResult(\"unknown\", \"return\", {\n reason: \"a steer may have been written but its id was lost: not resent\",\n }),\n };\n }\n return {\n kind: \"probe\",\n msgId: have.msgId,\n key,\n paneId: have.paneId,\n state: have.state,\n };\n }\n return {\n kind: \"done\",\n result: steerResult(have.state === \"refused\" ? \"refused\" : \"budget-exhausted\", \"return\", {\n reason:\n have.state === \"refused\"\n ? `pi refused the steer for this owner incarnation (${have.detail ?? \"no reason\"}); not retried`\n : \"this owner incarnation was already nudged once for this task\",\n ...(have.msgId !== null ? { msgId: have.msgId } : {}),\n }),\n };\n }\n const g = guardStall(db, ctx, callers, \"steer\");\n if (!g.ok) return { kind: \"done\", result: refused(g.reason, \"steer\") };\n const msgId = have?.msgId ?? newMsgId();\n if (have === undefined) {\n reserveActionReceipt(db, key, { ...infoOf(ctx, g.found), msgId });\n }\n return { kind: \"send\", msgId, key, found: g.found };\n })\n .immediate();\n}\n\n/** Ask a pi whether it accepted `msgId`; only the SAME incarnation's answer counts. */\nasync function probeSteer(\n db: Db,\n ctx: WaitStallContext,\n plan: Extract<SteerPlan, { kind: \"probe\" }>,\n timeoutMs: number,\n): Promise<StallActionResult> {\n const unknown = (reason: string): StallActionResult => {\n if (plan.state === \"sending\") {\n try {\n transitionActionReceipt(db, plan.key, \"sending\", \"unknown\", { detail: reason });\n } catch {}\n }\n return steerResult(\"unknown\", \"return\", { msgId: plan.msgId, reason });\n };\n const agent = getAgent(db, ctx.owner.name, ctx.owner.workstream);\n if (\n agent === undefined ||\n agent.incarnation !== plan.key.ownerId ||\n agent.paneId !== plan.paneId\n ) {\n return unknown(\"the owner was replaced: the earlier steer cannot be confirmed (not resent)\");\n }\n if (ctx.signal.aborted) return unknown(\"the wait was aborted before the receipt probe\");\n const check = await checkMessage(agentCtlSocket(db, agent), plan.msgId, timeoutMs);\n if (check.state !== \"accepted\" || check.incarnation !== plan.key.incarnation) {\n return unknown(\n check.state === \"accepted\"\n ? \"the receipt came from another pi incarnation: not confirmed\"\n : \"the earlier steer is not confirmed (receipt absent or unreachable): not resent\",\n );\n }\n try {\n transitionActionReceipt(db, plan.key, plan.state, \"sent\", {\n ...(check.runs !== undefined ? { runs: check.runs } : {}),\n detail: \"confirmed by receipt probe\",\n });\n } catch {\n // Storage failed: the row keeps its state (still an exclusion); the fact stands.\n }\n // The steer's run is still ahead of the stall observation only when the\n // receipt's run count has not fallen behind the owner's: otherwise that run\n // already settled and the owner is idle again, so return the stall (a\n // continue would wait on a token that can never change).\n if (check.runs !== undefined && ctx.owner.runs !== undefined && check.runs < ctx.owner.runs) {\n return steerResult(\"sent\", \"return\", {\n msgId: plan.msgId,\n incarnation: plan.key.incarnation,\n afterRuns: check.runs,\n reason: \"nudged earlier, owner idle again\",\n });\n }\n return sentResult(plan.msgId, plan.key.incarnation, check.runs);\n}\n\nfunction sentResult(msgId: string, incarnation: string, runs: number | undefined) {\n return steerResult(\"sent\", runs === undefined ? \"return\" : \"continue\", {\n msgId,\n incarnation,\n ...(runs !== undefined ? { afterRuns: runs } : {}),\n ...(runs === undefined ? { reason: \"sent, but pi reported no run baseline to wait from\" } : {}),\n });\n}\n\n/**\n * Nudge the stalled owner once. See the file header for the protocol. The\n * result is never a thrown error: `sent` (+ the real run baseline) continues\n * the wait; everything else returns the stall with the reason.\n */\nexport async function steerStall(\n db: Db,\n ctx: WaitStallContext,\n opts: StallActionOptions = {},\n): Promise<StallActionResult> {\n const callers = opts.callers ?? currentCallers();\n const timeoutMs = Math.min(CTL_DEFAULT_TIMEOUT_MS, Math.max(1, ctx.deadlineMs));\n let plan: SteerPlan;\n try {\n plan = planSteer(db, ctx, callers);\n } catch (e) {\n return refused(`steer failed, nothing sent: ${errText(e)}`, \"steer\");\n }\n if (plan.kind === \"done\") return plan.result;\n if (plan.kind === \"probe\") return probeSteer(db, ctx, plan, timeoutMs);\n\n const { key, msgId, found } = plan;\n const agent = getAgent(db, found.ownerName, ctx.owner.workstream);\n if (agent === undefined || agent.incarnation !== found.ownerId) {\n return refused(\"the owner is no longer registered\", \"steer\");\n }\n let won = false;\n let vetoed: StallActionResult | undefined;\n // The last synchronous step before the write: guards again, then the CAS.\n const beforeWrite = (): boolean => {\n const go = db\n .transaction((): boolean => {\n const g = guardStall(db, ctx, callers, \"steer\");\n if (!g.ok) {\n vetoed = refused(g.reason, \"steer\");\n return false;\n }\n if (!transitionActionReceipt(db, key, \"reserved\", \"sending\", { msgId })) {\n vetoed = steerResult(\"budget-exhausted\", \"return\", {\n reason: \"another waiter owns this nudge\",\n });\n return false;\n }\n return true;\n })\n .immediate();\n won = go;\n return go;\n };\n try {\n const sent = await sendViaTransport(agent, steerText(found.workstream, found.localId), {\n socket: agentCtlSocket(db, agent),\n mode: \"steer\",\n msgId,\n expectIncarnation: key.incarnation,\n ctlGuard: { signal: ctx.signal, timeoutMs, beforeWrite },\n });\n try {\n const patch = {\n ...(sent.runs !== undefined ? { runs: sent.runs } : {}),\n detail: sent.receipt ?? \"accepted\",\n };\n // A concurrent probe may have parked the row at `unknown` meanwhile.\n if (!transitionActionReceipt(db, key, \"sending\", \"sent\", patch)) {\n transitionActionReceipt(db, key, \"unknown\", \"sent\", patch);\n }\n recordSend(\n db,\n agent,\n \"steer\",\n Buffer.byteLength(steerText(found.workstream, found.localId)),\n {\n transport: \"ctl\",\n state: sent.state,\n },\n ctx.caller,\n );\n } catch {\n // Storage failed after the send: the row stays `sending`, the exclusion survives.\n }\n return sentResult(msgId, key.incarnation, sent.runs);\n } catch (e) {\n if (e instanceof CtlWriteVetoedError || !won) {\n // Nothing was written. The row stays `reserved`: the budget is not spent.\n return vetoed ?? refused(`steer not sent: ${errText(e)}`, \"steer\");\n }\n // The CAS passed, so the write may have happened.\n const definite = e instanceof AgentSendRefusedError || e instanceof AgentReplacedError;\n const to = definite ? \"refused\" : \"unknown\";\n try {\n transitionActionReceipt(db, key, \"sending\", to, { detail: errText(e) });\n } catch {}\n return steerResult(to, \"return\", { msgId, reason: errText(e) });\n }\n}\n\nconst errText = (e: unknown): string => (e instanceof Error ? e.message : String(e));\n\n/** `handleStall` for `onStall: 'steer'`. */\nexport function steerStallHandler(\n db: Db,\n opts: StallActionOptions = {},\n): (ctx: WaitStallContext) => Promise<StallActionResult> {\n return (ctx) => steerStall(db, ctx, opts);\n}\n\n/**\n * `waitForEvents` with the stall actions wired: `onStall: 'steer' | 'release'`\n * picks the handler (a `handleStall` you pass wins). A composition, not a loop.\n */\nexport function waitWithActions(\n db: Db,\n refs: readonly WaitRef[],\n opts: WaitOptions,\n): Promise<WaitResult> {\n if (opts.handleStall !== undefined) return waitForEvents(db, refs, opts);\n const actionOpts = { callers: opts.callers };\n const handleStall =\n opts.onStall === \"steer\"\n ? steerStallHandler(db, actionOpts)\n : opts.onStall === \"release\"\n ? releaseStallHandler(db, actionOpts)\n : undefined;\n return waitForEvents(db, refs, handleStall === undefined ? opts : { ...opts, handleStall });\n}\n","// mu — the ctl-backed agent readers for waitForEvents.\n//\n// `readAgents` is one `readAgentStates` pass (one batched probe per tick);\n// `watchAgent` is the ctl `wait` (`watchAgentRun`) that the extension answers\n// on `agent_settled`. They live apart from src/wait.ts so the engine imports\n// neither the registry nor the ctl client.\n\nimport { observeAgentStates, watchAgentRun } from \"./agents/observe.js\";\nimport { agentCtlSocket, expectsCtl } from \"./agents/transport.js\";\nimport { getAgent } from \"./agents.js\";\nimport { ctlProbe } from \"./ctl/client.js\";\nimport type { Db } from \"./db.js\";\nimport { activeMux } from \"./mux.js\";\nimport { WAIT_TEXT_MAX } from \"./wait-regex.js\";\nimport type { AgentBaseline, AgentReading, WaitOptions } from \"./wait-types.js\";\n\n/**\n * `paneText` (a wait with `--until-text`): also read the pane tail of an agent whose control\n * socket does not answer (a non-pi command, a `--no-ctl` pane). A pi agent that answers has\n * authoritative ctl `lastText` and is never read from its pane. Best effort: a pane the mux\n * cannot read just has no text and never matches.\n */\nexport function ctlAgentHooks(\n db: Db,\n opts: { paneText?: boolean } = {},\n): Required<Pick<WaitOptions, \"readAgents\" | \"watchAgent\">> {\n return {\n readAgents: async (refs) => {\n const agents = refs.flatMap((r) => {\n const a = getAgent(db, r.id, r.workstream);\n return a === undefined ? [] : [a];\n });\n const observed = await observeAgentStates(db, agents);\n if (opts.paneText !== true) return observed;\n const out = new Map<string, AgentReading>(observed);\n for (const a of agents) {\n const key = `${a.workstreamName}/${a.name}`;\n const base = out.get(key);\n if (base === undefined || base.status === null) continue;\n // A pi agent whose control socket ANSWERS has authoritative ctl text: never its pane.\n // Only an agent with no answering socket (a non-pi command, `--no-ctl`) has none.\n if (base.ctl === \"ok\") continue;\n try {\n const text = await (await activeMux()).capture(a.paneId, { lines: 200 });\n out.set(key, { ...base, lastText: text.slice(-WAIT_TEXT_MAX), textSource: \"pane\" });\n } catch {\n // no pane text: the agent just never matches\n }\n }\n return out;\n },\n watchAgent: async (ref, signal, ctx) => {\n const agent = getAgent(db, ref.id, ref.workstream);\n if (agent === undefined) return undefined;\n const sock = agentCtlSocket(db, agent);\n let afterRuns = ref.afterRuns;\n let unknownBaseline: AgentBaseline | undefined;\n if (\n afterRuns === undefined &&\n (ctx.owed || ctx.baseline !== undefined || ctx.cursor !== undefined)\n ) {\n // Explicit or owned, the same rule: count from the producer's UNCONSUMED\n // baseline (a send that settles before this wait started is still\n // caught), maxed with the last consumed run of THIS pi process. A\n // baseline of another incarnation or registry row is not this agent's.\n // With neither, an owed ref counts from the run count probed now and\n // says so (`unknownBaseline`): a historical run is never completion.\n if (!expectsCtl(agent, sock)) return undefined;\n const probe = await ctlProbe(sock);\n if (probe.kind !== \"ok\") return undefined;\n const inc = probe.incarnation;\n const b = ctx.baseline;\n const baseOk =\n b !== undefined &&\n (b.agentId === undefined || b.agentId === agent.incarnation) &&\n (b.incarnation === undefined || (inc !== undefined && b.incarnation === inc));\n const cursorOk =\n ctx.cursor !== undefined && inc !== undefined && ctx.cursor.incarnation === inc;\n const fromCursor = cursorOk && ctx.cursor !== undefined ? ctx.cursor.runs : undefined;\n if (baseOk && b !== undefined) {\n // The consumed cursor only ever raises the baseline: never re-deliver.\n afterRuns = Math.max(b.afterRuns, fromCursor ?? 0);\n } else if (fromCursor !== undefined) afterRuns = fromCursor;\n else if (ctx.owed) {\n afterRuns = probe.status.runs;\n unknownBaseline = {\n afterRuns,\n ...(inc !== undefined ? { incarnation: inc } : {}),\n agentId: agent.incarnation,\n };\n }\n }\n const handle = await watchAgentRun(agent, sock, signal, {\n ...(afterRuns !== undefined ? { afterRuns } : {}),\n ...(ref.incarnation !== undefined ? { inc: ref.incarnation } : {}),\n });\n return handle !== undefined && unknownBaseline !== undefined\n ? { ...handle, unknownBaseline }\n : handle;\n },\n };\n}\n","// mu — `executeNext` slice B (recovery): which authorised workers died and\n// which stopped on an API error, and the one safe move for each.\n//\n// A worker that DIED (its pane is gone: `status null`, an authoritative\n// liveness reading) is reaped through `deleteAgent` with the saved registry id\n// + pane as the compare-and-swap, never a new reaper: the task reopens with\n// the reaper's note, and the ordinary allocation then retries it as a NEW\n// attempt (a new charge, a brief that says the previous attempt died). A\n// worker that is ALIVE but whose last settled run ended in an API error is\n// never reaped, replaced or duplicated: it is retried IN PLACE (`reserveRetry`\n// in src/auto-attempt.ts): one run charged, the stored brief sent again to the\n// same pane under a reserved msgId bound to pi's incarnation, over the\n// journaled send of `spawnAutoAttempt` (a send that may have landed is only\n// ever probed, never resent). The error text lives only on the ctl `wait`\n// reply (a status read does not carry it), so it is read there, bounded.\n//\n// Never acted on, only reported (`attention`): a remote worker (its tree and\n// host channel are not ours to reap or collect; the recovery record keeps\n// the tree), an error at the run ceiling or with no run baseline, and any\n// reading that is not authoritative (`unknown` is degraded observation, never\n// permission). A busy, pending, dialog-blocked or merely idle worker is left\n// to the wait engine (steer, input). Pure observation here: the effects are\n// executeNext's, each re-validated in its own transaction.\n\nimport type { RuntimeState } from \"./agent-state.js\";\nimport { observeAgentStates, watchAgentRun } from \"./agents/observe.js\";\nimport { savedIdentity } from \"./agents/task-spawn.js\";\nimport { agentCtlSocket, expectsCtl } from \"./agents/transport.js\";\nimport type { AgentRow } from \"./agents.js\";\nimport { deliveredOf, type RetryTarget } from \"./auto-attempt.js\";\nimport type { CtlBlocked } from \"./ctl/protocol.js\";\nimport type { Db } from \"./db.js\";\nimport { localMachineId } from \"./segments.js\";\nimport { autoPermitted, getAutoConfig } from \"./task-auto.js\";\n\n/** What one observation of a worker says (only what the decision uses). */\nexport interface WorkerFacts {\n /** null = the pane is gone. */\n status: RuntimeState | null;\n ctl?: \"ok\" | \"missing\" | \"refused\";\n pending?: boolean;\n blocked?: CtlBlocked;\n /** pi's process incarnation. */\n incarnation?: string;\n /** The settled run's count when `lastError` was read, else the current count. */\n runs?: number;\n /** The error that ended the latest settled run (ctl `wait` reply only). */\n lastError?: string;\n}\n\n/** Reads the facts of `agents` (keyed `<workstream>/<name>`), within `ms`. Injected by tests. */\nexport type ObserveWorkers = (\n agents: readonly AgentRow[],\n opts: { signal?: AbortSignal; ms: number },\n) => Promise<ReadonlyMap<string, WorkerFacts>>;\n\n/** The ctl `wait` that reads a settled run's error: a reply is immediate, so this only bounds a dead socket. */\nexport const OBSERVE_MS = 3000;\n\n/** Idle on a healthy control socket: nothing queued, no dialog. The only state a worker's last error is acted on from. */\nexport const idleOnCtl = (\n f: Pick<WorkerFacts, \"status\" | \"ctl\" | \"pending\" | \"blocked\">,\n): boolean =>\n f.status === \"needs_input\" && f.ctl === \"ok\" && f.pending !== true && f.blocked === undefined;\n\nexport const workerKey = (a: Pick<AgentRow, \"workstreamName\" | \"name\">): string =>\n `${a.workstreamName}/${a.name}`;\n\n/** The production reader: one batched state read, then the error of each idle pi worker. */\nexport const observeWorkers =\n (db: Db): ObserveWorkers =>\n async (agents, { signal, ms }) => {\n const states = await observeAgentStates(db, agents);\n const out = new Map<string, WorkerFacts>();\n await Promise.all(\n agents.map(async (agent) => {\n const key = workerKey(agent);\n const s = states.get(key);\n if (s === undefined) return;\n const facts: WorkerFacts = {\n status: s.status,\n ...(s.ctl !== undefined ? { ctl: s.ctl } : {}),\n ...(s.pending !== undefined ? { pending: s.pending } : {}),\n ...(s.blocked !== undefined ? { blocked: s.blocked } : {}),\n ...(s.incarnation !== undefined ? { incarnation: s.incarnation } : {}),\n ...(s.runs !== undefined ? { runs: s.runs } : {}),\n };\n out.set(key, facts);\n const sock = agentCtlSocket(db, agent);\n if (!idleOnCtl(s) || s.runs === undefined || s.runs < 1 || !expectsCtl(agent, sock)) return;\n // A settled run is answered at once: the bound only covers a socket that stops answering.\n const stop = new AbortController();\n const timer = setTimeout(() => stop.abort(), ms);\n const onAbort = (): void => stop.abort();\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n try {\n const watch = await watchAgentRun(agent, sock, stop.signal, {\n afterRuns: s.runs - 1,\n ...(s.incarnation !== undefined ? { inc: s.incarnation } : {}),\n });\n if (watch === undefined) return;\n const settled = await watch.settled;\n if (settled.settled) {\n out.set(key, {\n ...facts,\n ...(settled.runs !== undefined ? { runs: settled.runs } : {}),\n ...(settled.incarnation !== undefined ? { incarnation: settled.incarnation } : {}),\n ...(settled.lastError !== undefined ? { lastError: settled.lastError } : {}),\n });\n }\n } catch {\n // A restarted pi, a dropped socket: no error read, and no action on a guess.\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n }\n }),\n );\n return out;\n };\n\nexport type RecoveryAction =\n | { kind: \"reap\"; task: string; agent: AgentRow; why: string }\n | { kind: \"retry\"; task: string; target: RetryTarget; error: string }\n | { kind: \"attention\"; task: string; reason: string; agent?: string };\n\n/** A task whose delivered attempt's worker still owns it. */\nexport interface InFlightWorker {\n task: string;\n taskId: number;\n agent: AgentRow;\n /** The delivered attempt's run baseline and pi process, for a receipt-bound wait. */\n runs: number | null;\n incarnation: string | null;\n}\n\n/**\n * The permitted IN_PROGRESS tasks of `workstream` held by the very registry row\n * (id + pane) their latest DELIVERED attempt saved. Anything else (not ours,\n * replaced, ended, a task a human claimed) is not recovered here.\n */\nexport function inFlightWorkers(db: Db, workstream: string): InFlightWorker[] {\n const rows = db\n .prepare(\n `SELECT t.id AS id, t.local_id AS local_id\n FROM task_auto a\n JOIN tasks t ON t.id = a.task_id\n JOIN workstreams w ON w.id = t.workstream_id AND w.name = ?\n WHERE a.enabled = 1 AND t.kind = 'work' AND t.dispatch_host = ?\n AND t.status = 'IN_PROGRESS' AND t.owner_id IS NOT NULL\n ORDER BY t.id`,\n )\n .all(workstream, localMachineId(db)) as { id: number; local_id: string }[];\n const out: InFlightWorker[] = [];\n for (const r of rows) {\n if (!autoPermitted(db, r.id)) continue;\n const delivered = deliveredOf(db, r.id);\n if (delivered === undefined) continue;\n const { receipt } = delivered;\n const id = savedIdentity(db, receipt);\n if (id.agent === undefined) continue;\n const owner = db.prepare(\"SELECT owner_id FROM tasks WHERE id = ?\").get(r.id) as {\n owner_id: number | null;\n };\n if (owner.owner_id !== id.agent.incarnation) continue;\n out.push({\n task: r.local_id,\n taskId: r.id,\n agent: id.agent,\n runs: receipt.runs,\n incarnation: receipt.incarnation,\n });\n }\n return out;\n}\n\n/** Delivered attempts whose worker is gone and whose task is open again, but with no run left: the retry that cannot happen. */\nexport function exhaustedAfterDeath(\n db: Db,\n workstream: string,\n): { task: string; reason: string }[] {\n const rows = db\n .prepare(\n `SELECT t.id AS id, t.local_id AS local_id, a.max_runs AS max\n FROM task_auto a\n JOIN tasks t ON t.id = a.task_id\n JOIN workstreams w ON w.id = t.workstream_id AND w.name = ?\n WHERE a.enabled = 1 AND t.kind = 'work' AND t.dispatch_host = ?\n AND t.status = 'OPEN' AND a.runs >= a.max_runs\n ORDER BY t.id`,\n )\n .all(workstream, localMachineId(db)) as { id: number; local_id: string; max: number }[];\n const out: { task: string; reason: string }[] = [];\n for (const r of rows) {\n if (!autoPermitted(db, r.id)) continue;\n const delivered = deliveredOf(db, r.id);\n if (delivered === undefined) continue;\n if (savedIdentity(db, delivered.receipt).stale === undefined) continue;\n out.push({\n task: r.local_id,\n reason: `its worker is gone and it used its ${r.max} run(s): raise the ceiling (mu task auto --max) or take it over`,\n });\n }\n return out;\n}\n\n/**\n * Observe every in-flight worker once and decide (no writes, no mux effects\n * beyond the reads). The decision, per worker:\n * pane gone, local reap (the CAS is deleteAgent's, at the effect)\n * pane gone, remote attention: the tree is not ours to touch\n * alive, last run API error retry in place (needs a run baseline, a pi\n * incarnation, a free run and a local host)\n * anything else nothing (busy, dialog, pending, idle, unknown)\n */\nexport async function scanRecovery(\n db: Db,\n workstream: string,\n observe: ObserveWorkers,\n opts: { signal?: AbortSignal; ms?: number } = {},\n): Promise<RecoveryAction[]> {\n const workers = inFlightWorkers(db, workstream);\n const out: RecoveryAction[] = [];\n if (workers.length > 0) {\n const facts = await observe(\n workers.map((w) => w.agent),\n { ...(opts.signal !== undefined ? { signal: opts.signal } : {}), ms: opts.ms ?? OBSERVE_MS },\n );\n for (const w of workers) {\n const f = facts.get(workerKey(w.agent));\n if (f === undefined) continue;\n if (f.status === null) {\n if (w.agent.host !== null) {\n out.push({\n kind: \"attention\",\n task: w.task,\n agent: w.agent.name,\n reason: `remote worker ${w.agent.name} on ${w.agent.host} has no pane: its tree is kept, not reaped (mu agent collect, then close it)`,\n });\n } else {\n out.push({\n kind: \"reap\",\n task: w.task,\n agent: w.agent,\n why: \"its pane is gone\",\n });\n }\n continue;\n }\n if (f.lastError === undefined) continue;\n if (!idleOnCtl(f)) continue;\n const attention = (reason: string): void => {\n out.push({ kind: \"attention\", task: w.task, agent: w.agent.name, reason });\n };\n if (w.agent.host !== null) {\n attention(`remote worker ${w.agent.name} stopped on an API error: not retried from here`);\n continue;\n }\n if (f.incarnation === undefined || f.runs === undefined || w.runs === null) {\n attention(\n `${w.agent.name} stopped on an API error but no run baseline or pi incarnation is known: not retried`,\n );\n continue;\n }\n if (f.runs <= w.runs) continue; // the error run was already answered\n const auto = getAutoConfig(db, w.taskId);\n if (auto !== undefined && auto.runs >= auto.maxRuns) {\n attention(\n `${w.agent.name} stopped on an API error and ${w.task} used its ${auto.maxRuns} run(s): raise the ceiling (mu task auto --max) or take it over`,\n );\n continue;\n }\n out.push({\n kind: \"retry\",\n task: w.task,\n error: f.lastError,\n target: {\n agent: { incarnation: w.agent.incarnation, paneId: w.agent.paneId, name: w.agent.name },\n pi: f.incarnation,\n errorRuns: f.runs,\n },\n });\n }\n }\n return out;\n}\n\n/**\n * Workers occupying a slot of `workstream`: registered agents that own an\n * IN_PROGRESS task, or hold an executor attempt in flight (pane up, not yet\n * delivered or unconfirmed) for a task that is not CLOSED. An idle worker whose\n * task is CLOSED (its close not yet reaped) is FREE: the slot is what is\n * working, not what still has a pane. A dead pane counts until reaped (the\n * recovery scan runs first).\n */\nexport function liveWorkers(db: Db, workstream: string): number {\n const row = db\n .prepare(\n `SELECT COUNT(*) AS n FROM agents a\n JOIN workstreams w ON w.id = a.workstream_id AND w.name = ?\n WHERE EXISTS (SELECT 1 FROM tasks t WHERE t.owner_id = a.id AND t.status = 'IN_PROGRESS')\n OR EXISTS (SELECT 1 FROM spawn_receipts r JOIN tasks t ON t.id = r.task_id\n WHERE r.agent_id = a.id AND r.pane_id = a.pane_id\n AND r.attempt_key LIKE 'auto:%'\n AND r.state IN ('pane', 'claimed', 'sending', 'unknown')\n AND t.status != 'CLOSED')`,\n )\n .get(workstream) as { n: number };\n return row.n;\n}\n","// mu — `executeNext --refute`, slice C: the opt-in durable checker.\n//\n// Each CLOSED/done attempt of an authorised task gets ONE checker (a delegate\n// call, src/delegates.ts), launched and recorded by `mu next --refute`; a\n// non-done close (wontfix, rejected, ...) has no claim to check and gets none.\n// The durable once-key is the call id `refute:<ws>:<task>:<attempt key>`: a\n// second invocation, a crash or a second `mu next` finds the row and resumes\n// it, never registers another. No pi extension runs here, so the executor\n// drives the whole lifecycle with the existing writers, one effect per step:\n// launch registerDelegateCall (state `starting`, BEFORE any pane) then\n// `spawnForTask` for the delegate's own task (journaled, claim +\n// first prompt, replay-safe); `sent` marks the call `running`.\n// An unsent failure ends the call `failed`; a send that may have\n// landed stays `starting` and is probed ONCE by the next step (it\n// is never resent), then ends `failed` if still unknown.\n// read the checker's settled run (or its death) is read once, bounded;\n// `finishDelegate` is the only recorder: the verdict note lands on\n// the judged task BEFORE the delegate's report and close.\n// The checker is briefed from the pinned brief and the worker's report (note\n// numbers named), runs with the task's stored cli unless one is given (no\n// router), lives in `scratch` with the other delegates, and never grants auto\n// permission, reopens, accepts or closes the judged work. Its pane is kept.\n// The call belongs to the caller: another caller's identical wave is never\n// mixed in, and its calls are never touched.\n\nimport { agentKey } from \"./agent-state.js\";\nimport { delegateOutcome } from \"./agents/delegate.js\";\nimport { AgentRestartedError, SpawnAttemptBusyError } from \"./agents/errors.js\";\nimport { observeAgentStates, watchAgentRun } from \"./agents/observe.js\";\nimport { getReceipt } from \"./agents/receipts.js\";\nimport { resolveCliCommand, speaksMuCtl } from \"./agents/spawn.js\";\nimport { savedIdentity, spawnForTask } from \"./agents/task-spawn.js\";\nimport { agentCtlSocket } from \"./agents/transport.js\";\nimport type { AgentRow } from \"./agents.js\";\nimport { deliveredOf } from \"./auto-attempt.js\";\nimport type { Db } from \"./db.js\";\nimport {\n DelegateCallConflictError,\n type DelegateRow,\n DelegateStateError,\n finishDelegate,\n getDelegateCall,\n markDelegate,\n registerDelegateCall,\n} from \"./delegates.js\";\nimport { NoMultiplexerError } from \"./mux/types.js\";\nimport type { NextMove } from \"./next.js\";\nimport { idleOnCtl } from \"./next-recover.js\";\nimport { autoPermitted, getAutoConfig } from \"./task-auto.js\";\nimport { pinnedNotes } from \"./task-brief.js\";\nimport { taskIdFor } from \"./tasks/core.js\";\nimport { getTaskNote } from \"./tasks/queries.js\";\nimport type { WaitRef } from \"./wait-types.js\";\n\n/** Where checkers (like every delegate) live: never counted against a crew's worker ceiling. */\nexport const REFUTE_WORKSTREAM = \"scratch\";\nconst READ_MS = 3000;\n/** A checker still running after this long is recorded `timeout` (a hung checker never blocks its wave). */\nconst CHECK_TIMEOUT_S = 1800;\n\n/** What reading a checker found. */\nexport type CheckerReading =\n | { kind: \"running\" }\n | { kind: \"died\" }\n | { kind: \"answer\"; outcome: string; text?: string };\n\n/** Reads one checker once. `afterRuns` is the send's run baseline. Injected by tests. */\nexport type ReadChecker = (\n db: Db,\n agent: AgentRow,\n base: { afterRuns: number; inc: string | null },\n o: { signal?: AbortSignal; ms: number },\n) => Promise<CheckerReading>;\n\n/** The production reader: liveness from one state read, then (idle, past the baseline) the settled run over ctl. */\nexport const readChecker: ReadChecker = async (db, agent, base, { signal, ms }) => {\n const live = (await observeAgentStates(db, [agent])).get(agentKey(agent));\n if (live === undefined) return { kind: \"running\" };\n if (live.status === null) return { kind: \"died\" };\n if (!idleOnCtl(live) || live.runs === undefined || live.runs <= base.afterRuns) {\n return { kind: \"running\" };\n }\n const stop = new AbortController();\n const timer = setTimeout(() => stop.abort(), ms);\n const onAbort = (): void => stop.abort();\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n try {\n const watch = await watchAgentRun(agent, agentCtlSocket(db, agent), stop.signal, {\n afterRuns: base.afterRuns,\n ...(base.inc !== null ? { inc: base.inc } : {}),\n });\n const done = watch === undefined ? undefined : await watch.settled;\n if (done === undefined || !done.settled) return { kind: \"running\" };\n const outcome = delegateOutcome({ fired: true, dead: false, ...done }, false);\n return { kind: \"answer\", outcome, text: done.lastText ?? done.lastError };\n } catch (err) {\n if (err instanceof AgentRestartedError) return { kind: \"died\" };\n throw err;\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n }\n};\n\n/** One checker step still owed. */\nexport interface Check {\n /** The durable once-key. */\n callId: string;\n /** The judged task and its delivered attempt. */\n task: string;\n attempt: string;\n workstream: string;\n /** The stored call, when one exists (this caller's). */\n call?: DelegateRow;\n}\n\n/**\n * The next check owed to `caller` not in `skip`: a CLOSED/done permitted task\n * whose delivered attempt has no call yet, or this caller's call that is\n * still `starting`, `running` or `recording`. Read-only.\n */\nexport function nextCheck(\n db: Db,\n workstream: string,\n caller: string,\n skip: ReadonlySet<string>,\n): Check | undefined {\n const rows = db\n .prepare(\n `SELECT t.id AS id, t.local_id AS local_id\n FROM task_auto a\n JOIN tasks t ON t.id = a.task_id\n JOIN workstreams w ON w.id = t.workstream_id AND w.name = ?\n WHERE t.status = 'CLOSED' AND t.substate = 'done' ORDER BY t.id`,\n )\n .all(workstream) as { id: number; local_id: string }[];\n for (const r of rows) {\n if (!autoPermitted(db, r.id)) continue;\n const attempt = deliveredOf(db, r.id)?.receipt.attemptKey;\n if (attempt === undefined) continue;\n const callId = `refute:${workstream}:${r.local_id}:${attempt}`;\n if (skip.has(callId)) continue;\n const call = getDelegateCall(db, callId);\n if (call === undefined) return { callId, task: r.local_id, attempt, workstream };\n if (call.caller !== caller) continue;\n if ([\"starting\", \"running\", \"recording\"].includes(call.state)) {\n return { callId, task: r.local_id, attempt, workstream, call };\n }\n }\n return undefined;\n}\n\n/** The checker's journaled delivery and the agent still holding it (undefined: gone or replaced). */\nfunction checkerOf(db: Db, c: DelegateRow) {\n const taskId = taskIdFor(db, c.task, c.workstream);\n const receipt = taskId === null ? undefined : getReceipt(db, taskId, `manual:${c.task}`);\n const agent = receipt === undefined ? undefined : savedIdentity(db, receipt).agent;\n return receipt !== undefined && agent !== undefined ? { receipt, agent } : undefined;\n}\n\n/** This caller's running checkers as wait refs (a hold ends their wait on a settle or death). */\nexport function checkerRefs(db: Db, workstream: string, caller: string): WaitRef[] {\n const refs: WaitRef[] = [];\n for (const c of liveCalls(db, workstream, caller)) {\n const held = checkerOf(db, c);\n if (held === undefined) continue;\n const { receipt, agent } = held;\n refs.push({\n kind: \"agent\",\n workstream: agent.workstreamName,\n id: agent.name,\n afterRuns: receipt.runs ?? 0,\n ...(receipt.incarnation !== null ? { incarnation: receipt.incarnation } : {}),\n });\n }\n return refs;\n}\n\nfunction liveCalls(db: Db, workstream: string, caller: string): DelegateRow[] {\n return db\n .prepare(\n \"SELECT call_id FROM delegate_calls WHERE caller = ? AND call_id LIKE ? AND state IN ('running','recording')\",\n )\n .all(caller, `refute:${workstream}:%`)\n .map((r) => getDelegateCall(db, (r as { call_id: string }).call_id))\n .filter((c): c is DelegateRow => c !== undefined);\n}\n\nconst stem = (s: string): string =>\n s\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .slice(0, 13)\n .replace(/^-+|-+$/g, \"\");\n\nfunction checkerText(db: Db, ws: string, task: string, attempt: string): string {\n const { briefN, reportN } = pinnedNotes(db, ws, task);\n const part = (what: string, n: number): string =>\n n < 1\n ? `${what}: (none)`\n : `${what} (note #${n}):\\n${getTaskNote(db, task, ws, n).content.trimEnd()}`;\n return [\n `You are an independent checker of the work on task ${task} (workstream ${ws}), attempt ${attempt}. Read only: do not edit, commit, merge, close or accept anything.`,\n part(\"Pinned brief\", briefN),\n part(\"The worker's report\", reportN),\n \"Try to refute the claim that the work meets the brief: read the code and run the checks yourself. End your final message with a line starting `VERDICT:` and one of CONFIRMED, REFUTED, UNVERIFIED, then `EVIDENCE:` lines naming what you ran and saw.\",\n ].join(\"\\n\\n\");\n}\n\n/** What `--dry` says of one check. */\nexport const planCheck = (\n c: Check,\n): { kind: \"refute\"; task: string; key: string; state: string } => ({\n kind: \"refute\",\n task: c.task,\n key: c.callId,\n state: c.call?.state ?? \"new\",\n});\n\nexport interface RunCheckDeps {\n /** The checker's cli: the task's stored key unless the caller chose one. */\n cli?: string;\n caller: string;\n read: ReadChecker;\n signal?: AbortSignal;\n}\n\n/** One effect of one check: launch (register + spawn), or read and record. Throws `NoMultiplexerError`; everything else is a move. */\nexport async function runCheck(db: Db, c: Check, deps: RunCheckDeps): Promise<NextMove> {\n const base = { task: c.task, key: c.callId };\n const taskId = taskIdFor(db, c.task, c.workstream);\n const auto = taskId === null ? undefined : getAutoConfig(db, taskId);\n let call = c.call;\n if (call === undefined) {\n const cli = deps.cli ?? auto?.cli ?? \"pi\";\n if (!speaksMuCtl(cli, resolveCliCommand(cli))) {\n return {\n kind: \"skip\",\n ...base,\n cli,\n reason: `cli ${cli} cannot report an answer over ctl: pass --refute-cli pi`,\n };\n }\n try {\n call = registerDelegateCall(db, {\n callId: c.callId,\n caller: deps.caller,\n workstream: REFUTE_WORKSTREAM,\n wave: `refute-${c.workstream}`,\n record: { workstream: c.workstream, task: c.task },\n state: \"starting\",\n request: {\n text: checkerText(db, c.workstream, c.task, c.attempt),\n label: `refute-${c.task}`,\n cli,\n timeoutS: CHECK_TIMEOUT_S,\n },\n }).call;\n } catch (err) {\n if (err instanceof DelegateCallConflictError) {\n return { kind: \"skip\", ...base, reason: \"another mu registered this check first\" };\n }\n throw err;\n }\n }\n if (call.state === \"starting\") return launch(db, call, base);\n return readOne(db, call, base, deps);\n}\n\nasync function launch(\n db: Db,\n call: DelegateRow,\n base: { task: string; key: string },\n): Promise<NextMove> {\n const cli = call.request.cli ?? \"pi\";\n try {\n const out = await spawnForTask(db, {\n task: call.task,\n text: call.request.text,\n spawn: {\n name: `delegate-refute-${stem(base.task)}`,\n workstream: call.workstream,\n cli,\n nextFree: true,\n },\n });\n const agent = out.agent?.name ?? out.receipt.name;\n if (out.state === \"unknown\") {\n // A first send that may have landed is probed once (the replay); still unknown ends the call, never a resend.\n if (!out.replay)\n return {\n kind: \"refute\",\n ...base,\n agent,\n cli,\n state: \"starting\",\n reason: out.reason ?? \"delivery unknown\",\n };\n return end(\n db,\n call,\n base,\n \"error\",\n `delivery unknown after one probe (${out.reason ?? \"no reply\"}); pane ${agent} kept`,\n );\n }\n try {\n markDelegate(db, call.callId, \"running\", { agent });\n } catch (err) {\n if (!(err instanceof DelegateStateError)) throw err; // another mu already marked it\n }\n return { kind: \"refute\", ...base, agent, cli, state: \"running\" };\n } catch (err) {\n if (err instanceof NoMultiplexerError) throw err;\n if (err instanceof SpawnAttemptBusyError) {\n return { kind: \"skip\", ...base, reason: \"another mu is launching this checker\" };\n }\n const reason = err instanceof Error ? err.message : String(err);\n const done = end(db, call, base, \"error\", `the checker could not be started: ${reason}`);\n return { ...done, kind: \"failed\", reason };\n }\n}\n\nfunction end(\n db: Db,\n call: DelegateRow,\n base: { task: string; key: string },\n outcome: string,\n text?: string,\n agent?: string,\n): NextMove {\n const r = finishDelegate(db, call.callId, {\n outcome,\n ...(text !== undefined ? { text } : {}),\n elapsedMs: Math.max(0, Date.now() - Date.parse(call.updatedAt)),\n author: agent ?? call.agent ?? \"next\",\n });\n return {\n kind: \"refute\",\n ...base,\n ...(call.agent !== null ? { agent: call.agent } : {}),\n state: r.state,\n ...(r.verdict !== null ? { verdict: r.verdict } : {}),\n ...(r.error !== undefined ? { reason: r.error } : {}),\n };\n}\n\nasync function readOne(\n db: Db,\n call: DelegateRow,\n base: { task: string; key: string },\n deps: RunCheckDeps,\n): Promise<NextMove> {\n const held = checkerOf(db, call);\n if (held === undefined) {\n return end(db, call, base, \"died\", \"the checker's agent is gone\", call.agent ?? \"next\");\n }\n const { receipt, agent } = held;\n const got = await deps.read(\n db,\n agent,\n { afterRuns: receipt.runs ?? 0, inc: receipt.incarnation },\n { ...(deps.signal !== undefined ? { signal: deps.signal } : {}), ms: READ_MS },\n );\n if (got.kind === \"running\") {\n const late =\n Date.now() - Date.parse(call.updatedAt) > (call.request.timeoutS ?? CHECK_TIMEOUT_S) * 1000;\n if (!late) return { kind: \"refute\", ...base, agent: agent.name, state: \"running\" };\n return end(db, call, base, \"timeout\", undefined, agent.name);\n }\n return end(\n db,\n call,\n base,\n got.kind === \"died\" ? \"died\" : got.outcome,\n got.kind === \"answer\" ? got.text : undefined,\n agent.name,\n );\n}\n","// mu — `executeNext`: the executor, slice A (dispatch).\n//\n// `mu next` performs the judgement-free moves for tasks the orchestrator\n// authorised HERE (`mu task auto`): it recovers dead and API-errored workers,\n// resumes stored attempts, then spawns, claims and briefs ready ones. It never\n// grants or widens permission (`authorizeTasks` is not called; `autoPermitted`\n// is only read), never decides acceptance, merge or teardown.\n//\n// One pass, one ordered rule per iteration (cap check, signal, ingest, this\n// caller's human needs, then selection from FRESH state):\n// 0. once per pass, a scan of the in-flight workers (src/next-recover.ts): a\n// DEAD local one is reaped through `deleteAgent`'s id + pane CAS (its task\n// reopens and falls to rule 2 as a retried attempt); a LIVE one whose last\n// run ended in an API error is retried IN PLACE (one run charged, the same\n// pane, a reserved msgId bound to pi's incarnation). A remote worker's\n// tree is never touched; what cannot be acted on is an `attention` move;\n// 1. a stored attempt in flight (reserved … unknown) of a permitted task is\n// RESUMED under its own key, even at its run ceiling (`pendingAttempts`);\n// 2. else the first `authorisedReady` task gets a NEW attempt: the run is\n// charged and the attempt reserved in one transaction (src/auto-attempt.ts),\n// then spawned through the guarded `spawnAutoAttempt`.\n// `hold` then waits (waitWithActions, bounded) for the first event on the\n// in-flight workers: a death or an API-errored settle is the executor's own\n// (recover, then wait again, all inside the cap and deadline); any other event\n// is the orchestrator's and ends the invocation. `signal` stops it between\n// effects: an effect in flight finishes (it is journaled, never half-done) and\n// the one result says `interrupted`.\n// `refute` (opt-in, src/next-refute.ts) adds one more rule after dispatch: ONE\n// checker per CLOSED/done attempt, launched and recorded with the delegate\n// writers (verdict before the call closes); it never accepts, reopens or closes.\n// Every stored attempt reaches a terminal state on the FIRST invocation that\n// sees it unreconcilable (`endAttempt`): `abandoned` (task closed, agent gone\n// before anything was sent) or `needs_human` (the prompt may have landed and\n// cannot be confirmed: never resent; a one-line human need is recorded for\n// the caller). It is then never replayed and never counted again. A replay\n// sends the STORED prompt, never a rebuild. The cap counts every effect\n// (replays, probes, spawns, failures, a spawn rolled back by the guard); the\n// default is finite. This caller's human need is checked at the top of the\n// loop AND right before each spawn and send. `dry` is the same selection over\n// the shared read-only planner: no ingest, lock, mux call, receipt probe or\n// write.\n\nimport {\n AgentRestartedError,\n SpawnAttemptBusyError,\n SpawnAttemptGuardError,\n} from \"./agents/errors.js\";\nimport { getReceipt, type SpawnReceipt } from \"./agents/receipts.js\";\nimport { savedIdentity, spawnAutoAttempt, type TaskSpawnOutcome } from \"./agents/task-spawn.js\";\nimport { deleteAgent, getAgent as getAgentRow } from \"./agents.js\";\nimport {\n type AttemptEnd,\n type AttemptRecord,\n endAttempt,\n IN_FLIGHT_STATES,\n pendingAttempts,\n planAttempt,\n readAttempt,\n reserveAttempt,\n reserveRetry,\n} from \"./auto-attempt.js\";\nimport type { Db } from \"./db.js\";\nimport { type HumanNeeded, openHumanNeeds, recordHumanNeeded } from \"./human-needed.js\";\nimport { NoMultiplexerError } from \"./mux/types.js\";\nimport {\n exhaustedAfterDeath,\n idleOnCtl,\n inFlightWorkers,\n liveWorkers,\n OBSERVE_MS,\n type ObserveWorkers,\n observeWorkers,\n type RecoveryAction,\n scanRecovery,\n workerKey,\n} from \"./next-recover.js\";\nimport {\n checkerRefs,\n nextCheck,\n planCheck,\n type ReadChecker,\n readChecker,\n runCheck,\n} from \"./next-refute.js\";\nimport { ambientIngest } from \"./sync.js\";\nimport { authorisedReady, autoPermitted } from \"./task-auto.js\";\nimport { taskIdFor } from \"./tasks/core.js\";\nimport { getTask, listReady } from \"./tasks/queries.js\";\nimport { waitWithActions } from \"./wait-actions.js\";\nimport { ctlAgentHooks } from \"./wait-ctl.js\";\nimport {\n WAIT_HEARTBEAT_CAP_MS,\n type WaitOptions,\n type WaitRef,\n type WaitResult,\n} from \"./wait-types.js\";\n\n/** Bad `--cap`: exit 2, nothing done. */\nexport class NextArgError extends Error {\n override readonly name = \"NextArgError\";\n}\n\n/** Effects one invocation may perform unless `cap` says otherwise. */\nexport const DEFAULT_NEXT_CAP = 5;\n/** The largest `cap` accepted. */\nexport const MAX_NEXT_CAP = 100;\n\nexport interface ExecuteNextOptions {\n workstream: string;\n /** Who is asking (`spawnerFromEnv()`): its open human needs stop dispatch. */\n caller: string;\n /** Plan only: zero writes. */\n dry?: boolean;\n /** Effect budget, an integer 1..100 (default 5). */\n cap?: number;\n /**\n * Worker ceiling: no new pane while this many workers are working (an\n * IN_PROGRESS task, or an attempt in flight); a worker whose task is CLOSED\n * is free. Default: none. Recovery in place and replays that need no pane\n * are never held back.\n */\n workers?: number;\n /** Pull peer state before each effect. Default: the ambient sync ingest. */\n ingest?: () => Promise<unknown>;\n /** After the pass, wait (bounded) for the first event on the in-flight workers; recover and go on while the event is the executor's own. */\n hold?: boolean;\n /** `hold`'s total deadline in ms (default and cap: the wait heartbeat, 1500 s). */\n timeoutMs?: number;\n /** `hold`: what a stall does (default `exit`: the stall ends the invocation). */\n onStall?: \"exit\" | \"warn\" | \"steer\" | \"release\";\n /** Stop between effects; an effect in flight finishes. The result says `interrupted`. */\n signal?: AbortSignal;\n /**\n * Opt in to ONE checker per CLOSED/done attempt of an authorised task (a\n * delegate call in `scratch`, src/next-refute.ts); its verdict is recorded\n * on the judged task before the call closes. Never accepts, reopens or closes.\n */\n refute?: boolean;\n /** The checker's cli key. Default: the judged task's stored key (it must speak ctl). */\n refuteCli?: string;\n /** Test seams: the worker reader, the checker reader and the wait. */\n observe?: ObserveWorkers;\n readChecker?: ReadChecker;\n wait?: (db: Db, refs: readonly WaitRef[], o: WaitOptions) => Promise<WaitResult>;\n}\n\nexport interface NextMove {\n /**\n * `spawn` (new attempt), `replay` (stored attempt resumed), `skip` (nothing\n * done), `failed` (unsent), `rolled_back` (a pane was spawned, then the guard\n * stopped the send: undone, charged), `abandoned` (a stored attempt ended:\n * nothing left to do), `needs_human` (a stored attempt that may have landed\n * and cannot be confirmed: never resent, a human need recorded), `retry`\n * (a live worker that stopped on an API error was sent its brief again, in\n * place), `reap` (a dead worker's row was removed; its task is open again),\n * `attention` (something that needs the orchestrator and was NOT acted on),\n * `refute` (a checker launched, read or recorded: `state` is its call's).\n */\n kind:\n | \"spawn\"\n | \"replay\"\n | \"retry\"\n | \"refute\"\n | \"reap\"\n | \"attention\"\n | \"skip\"\n | \"failed\"\n | \"rolled_back\"\n | \"abandoned\"\n | \"needs_human\";\n task: string;\n attempt?: number;\n key?: string;\n agent?: string;\n cli?: string;\n /** `sent`, `unknown`, or (dry replay) the receipt state it would resume from. */\n state?: string;\n reason?: string;\n /** `refute`: the checker's parsed verdict, once recorded. */\n verdict?: string;\n stale?: \"deleted\" | \"replaced\";\n /** The one receipt probe a replay made, when it made one. */\n checked?: \"accepted\" | \"not-accepted\" | \"unreachable\";\n}\n\nexport interface NextResult {\n workstream: string;\n dry: boolean;\n cap: number;\n /** Effects counted against the cap. */\n used: number;\n moves: NextMove[];\n /** Why the loop ended early: the cap with work left, this caller's human need, an unsent failure, or a signal. */\n stopped?: \"cap\" | \"human\" | \"failed\" | \"interrupted\" | \"workers\";\n /** Dry only: the in-flight workers a live run would observe (a dry run reads no pane and no socket). */\n inFlight?: string[];\n human_needed?: HumanNeeded[];\n /** `hold`: the wait(s) that ended the invocation. */\n held?: {\n /** Waits taken (each recovered event starts another pass). */\n waits: number;\n /** The event that ended the hold: the engine's kind, or `none` (nothing in flight). */\n event: string;\n ref: string | null;\n exit: number;\n timedOut: boolean;\n /** The ended wait's snapshots of the in-flight workers, cut to what a reader needs. */\n open: { ref: string; status: string | null; lastError?: string }[];\n };\n}\n\nfunction checkCap(cap: number | undefined): number {\n if (cap === undefined) return DEFAULT_NEXT_CAP;\n if (!Number.isInteger(cap) || cap < 1 || cap > MAX_NEXT_CAP) {\n throw new NextArgError(`--cap must be an integer from 1 to ${MAX_NEXT_CAP} (got ${cap})`);\n }\n return cap;\n}\n\nfunction checkWorkers(n: number | undefined): number | undefined {\n if (n === undefined) return undefined;\n if (!Number.isInteger(n) || n < 1 || n > MAX_NEXT_CAP) {\n throw new NextArgError(`--workers must be an integer from 1 to ${MAX_NEXT_CAP} (got ${n})`);\n }\n return n;\n}\n\nfunction checkTimeout(ms: number | undefined): number {\n if (ms === undefined) return WAIT_HEARTBEAT_CAP_MS;\n if (!Number.isFinite(ms) || ms < 0) {\n throw new NextArgError(`--timeout must be a number of seconds, 0 or more (got ${ms / 1000})`);\n }\n return ms === 0 ? WAIT_HEARTBEAT_CAP_MS : Math.min(ms, WAIT_HEARTBEAT_CAP_MS);\n}\n\n/** The first candidate not yet handled this invocation: stored attempts, then fresh ready work. */\nfunction select(\n db: Db,\n ws: string,\n done: ReadonlySet<string>,\n): { task: string; resume: boolean } | undefined {\n const pending = pendingAttempts(db, ws).find((t) => !done.has(t));\n if (pending !== undefined) return { task: pending, resume: true };\n const ready = authorisedReady(db, ws).find((t) => !done.has(t.name));\n return ready === undefined ? undefined : { task: ready.name, resume: false };\n}\n\n/** Would running this candidate create a pane? A fresh attempt, or a stored one that never got one. */\nfunction needsPane(db: Db, ws: string, c: { task: string; resume: boolean }): boolean {\n if (!c.resume) return true;\n const id = taskIdFor(db, c.task, ws);\n const receipt = id === null ? undefined : readAttempt(db, id).receipt;\n return receipt?.state === \"reserved\";\n}\n\n/** Does this move cost an external effect (a spawn, send, probe or rollback)? */\nfunction counts(m: NextMove): boolean {\n if (m.kind === \"skip\" || m.kind === \"abandoned\" || m.kind === \"attention\") return false;\n if (m.kind === \"needs_human\") return m.checked !== undefined;\n return true;\n}\n\n/** What one live invocation shares with its steps. */\ninterface Ctx {\n db: Db;\n ws: string;\n caller: string;\n /** This caller's open human need? Records the stop on the result when so. */\n humanStop: () => boolean;\n /** The worker ceiling, when one was given. */\n workers: number | undefined;\n}\n\n/** Thrown out of a hold's `beforePoll` when this caller's human need opened mid-wait. */\nclass HoldHumanStop extends Error {}\n\nconst DEAD_OR_ERRORED = (r: WaitResult): boolean => {\n const e = r.event;\n if (e.kind === \"dead\") return true;\n if (e.kind !== \"settled\" || e.ref === null) return false;\n const snap = r.refs.find(\n (s) =>\n s.ref.kind === e.ref?.kind && s.ref.workstream === e.ref.workstream && s.ref.id === e.ref.id,\n );\n return snap?.lastError !== undefined && snap.close?.applied !== true;\n};\n\nconst refText = (r: WaitRef): string =>\n r.kind === \"delegate\" ? `delegate:${r.id}` : `${r.kind}:${r.workstream}/${r.id}`;\n\nexport async function executeNext(db: Db, opts: ExecuteNextOptions): Promise<NextResult> {\n const cap = checkCap(opts.cap);\n const timeoutMs = checkTimeout(opts.timeoutMs);\n const workers = checkWorkers(opts.workers);\n const refute = opts.refute === true;\n if (refute && opts.caller === \"\") {\n throw new NextArgError(\n \"--refute needs a caller identity (a managed agent, or PI_SESSION_ID): a checker belongs to the caller that launched it\",\n );\n }\n const ws = opts.workstream;\n const out: NextResult = { workstream: ws, dry: opts.dry === true, cap, used: 0, moves: [] };\n const done = new Set<string>();\n const ingest = opts.ingest ?? (() => ambientIngest(db, { quiet: true }));\n const humanStop = (): boolean => {\n const needs = openHumanNeeds(db, opts.caller);\n if (needs.length === 0) return false;\n out.stopped = \"human\";\n out.human_needed = needs;\n return true;\n };\n const ctx: Ctx = { db, ws, caller: opts.caller, humanStop, workers };\n const observe = opts.observe ?? observeWorkers(db);\n const deadline = Date.now() + timeoutMs;\n const aborted = (): boolean => {\n if (opts.signal?.aborted !== true) return false;\n out.stopped = \"interrupted\";\n return true;\n };\n\n /** What is left that only the orchestrator can fix: a dead worker whose task has no run left. Once per task per invocation. */\n const told = new Set<string>();\n const tell = (task: string, reason: string, agent?: string): void => {\n if (told.has(`${task}|${reason}`)) return;\n told.add(`${task}|${reason}`);\n out.moves.push({ kind: \"attention\", task, ...(agent !== undefined ? { agent } : {}), reason });\n };\n const attend = (): void => {\n for (const a of exhaustedAfterDeath(db, ws)) tell(a.task, a.reason);\n };\n\n /** One pass: recover, resume, then allocate, until nothing is left, the cap, a human need, a failure or a signal. */\n const pass = async (): Promise<void> => {\n let actions: Extract<RecoveryAction, { kind: \"reap\" | \"retry\" }>[] | undefined;\n for (;;) {\n if (aborted()) return;\n if (out.used >= cap) {\n if (\n out.stopped === undefined &&\n (select(db, ws, done) !== undefined ||\n (actions?.length ?? 0) > 0 ||\n (refute && nextCheck(db, ws, opts.caller, done) !== undefined))\n ) {\n out.stopped = \"cap\";\n }\n return;\n }\n if (!out.dry) await ingest();\n if (aborted()) return;\n if (humanStop()) return;\n if (actions === undefined) {\n // One scan per pass, after the first ingest: attention is free, effects are queued.\n const found: RecoveryAction[] = out.dry\n ? []\n : await scanRecovery(\n db,\n ws,\n observe,\n opts.signal !== undefined ? { signal: opts.signal } : {},\n );\n if (aborted()) return;\n if (out.dry) out.inFlight = inFlightWorkers(db, ws).map((w) => w.task);\n actions = [];\n for (const a of found) {\n if (a.kind === \"attention\") tell(a.task, a.reason, a.agent);\n else actions.push(a);\n }\n }\n const act = actions.shift();\n if (act !== undefined && !out.dry) {\n const move = await recover(ctx, act, observe, opts.signal);\n // A retried worker is done for this pass: its own unknown send is probed by the NEXT invocation.\n if (act.kind === \"retry\") done.add(act.task);\n out.moves.push(move);\n if (counts(move)) out.used++;\n if (move.kind === \"failed\") {\n out.stopped = \"failed\";\n return;\n }\n continue;\n }\n const next = select(db, ws, done);\n if (next === undefined) {\n // Dispatch first; a checker is the last thing a pass does.\n const check = refute ? nextCheck(db, ws, opts.caller, done) : undefined;\n if (check !== undefined) {\n done.add(check.callId);\n const move = out.dry\n ? planCheck(check)\n : await runCheck(db, check, {\n caller: opts.caller,\n read: opts.readChecker ?? readChecker,\n ...(opts.refuteCli !== undefined ? { cli: opts.refuteCli } : {}),\n ...(opts.signal !== undefined ? { signal: opts.signal } : {}),\n });\n out.moves.push(move);\n if (counts(move)) out.used++;\n if (move.kind === \"failed\" && !out.dry) {\n out.stopped = \"failed\";\n return;\n }\n continue;\n }\n attend();\n return;\n }\n if (workers !== undefined && needsPane(db, ws, next) && liveWorkers(db, ws) >= workers) {\n // Nothing reserved, nothing charged: a slot frees when a worker's task closes.\n tell(\n next.task,\n `worker ceiling ${workers} reached (${liveWorkers(db, ws)} working): no new pane until one finishes`,\n );\n out.stopped = \"workers\";\n return;\n }\n done.add(next.task);\n const move = out.dry\n ? planMove(db, ws, next.task, next.resume)\n : next.resume\n ? await resume(ctx, next.task)\n : await allocate(ctx, next.task);\n out.moves.push(move);\n if (counts(move)) out.used++;\n if (move.kind === \"failed\" && !out.dry) {\n out.stopped = \"failed\";\n return;\n }\n }\n };\n\n for (let waits = 0; ; ) {\n const before = out.used;\n await pass();\n // A ceiling stop is what `--hold` is for: a worker closing frees the slot.\n const atCeiling = out.stopped === \"workers\";\n if (opts.hold !== true || out.dry || (out.stopped !== undefined && !atCeiling)) return out;\n if (waits > 0 && out.used === before) return out; // the event was the executor's, and it could do nothing\n const inFlight = inFlightWorkers(db, ws);\n const checkers = refute ? checkerRefs(db, ws, opts.caller) : [];\n if (inFlight.length === 0 && checkers.length === 0) {\n out.held = { waits, event: \"none\", ref: null, exit: 0, timedOut: false, open: [] };\n return out;\n }\n const left = deadline - Date.now();\n if (left <= 0) {\n out.held = { waits, event: \"heartbeat\", ref: null, exit: 0, timedOut: true, open: [] };\n return out;\n }\n const refs: WaitRef[] = checkers.concat(\n inFlight.flatMap((w): WaitRef[] => [\n { kind: \"task\", workstream: ws, id: w.task },\n {\n kind: \"agent\",\n workstream: w.agent.workstreamName,\n id: w.agent.name,\n ...(w.runs !== null ? { afterRuns: w.runs } : {}),\n ...(w.incarnation !== null ? { incarnation: w.incarnation } : {}),\n },\n ]),\n );\n waits++;\n let res: WaitResult;\n try {\n res = await (opts.wait ?? waitWithActions)(db, refs, {\n callers: opts.caller === \"\" ? [] : [opts.caller],\n mode: \"first\",\n eventScope: \"refs\",\n timeoutMs: left,\n ...(opts.signal !== undefined ? { signal: opts.signal } : {}),\n onStall: opts.onStall ?? \"exit\",\n ...ctlAgentHooks(db),\n beforePoll: async () => {\n if (humanStop()) throw new HoldHumanStop();\n },\n });\n } catch (err) {\n if (err instanceof HoldHumanStop) return out;\n if (err instanceof AgentRestartedError) {\n out.moves.push({ kind: \"attention\", task: \"\", reason: err.message });\n out.held = { waits, event: \"restarted\", ref: null, exit: 7, timedOut: false, open: [] };\n return out;\n }\n throw err;\n }\n out.held = {\n waits,\n event: res.event.kind,\n ref: res.event.ref === null ? null : refText(res.event.ref),\n exit: res.exit,\n timedOut: res.timedOut,\n open: res.refs\n .filter((x) => !x.fired && !x.dead)\n .slice(0, 8)\n .map((x) => ({\n ref: refText(x.ref),\n status: x.status,\n ...(x.lastError !== undefined ? { lastError: x.lastError.slice(0, 200) } : {}),\n })),\n };\n if (res.interrupted) {\n out.stopped = \"interrupted\";\n return out;\n }\n const freed = atCeiling && res.event.kind === \"closed\";\n // A checker settling or dying is the executor's own: read and record it, then wait again.\n const checkerEvent = checkers.some(\n (c) => res.event.ref?.kind === \"agent\" && res.event.ref.id === c.id,\n );\n if (res.event.kind === \"heartbeat\" || (!DEAD_OR_ERRORED(res) && !freed && !checkerEvent)) {\n return out;\n }\n if (atCeiling) out.stopped = undefined;\n done.clear();\n }\n}\n\n/** The dry plan of one candidate: what a live run would do, read-only. */\nfunction planMove(db: Db, ws: string, task: string, resume: boolean): NextMove {\n const taskId = taskIdFor(db, task, ws);\n if (resume && taskId !== null) {\n const { record, receipt } = readAttempt(db, taskId);\n if (record !== undefined && receipt !== undefined) {\n const base = { task, attempt: record.attempt, key: record.key, cli: record.cli };\n const end = unreconcilable(db, ws, task, receipt);\n if (end !== undefined) return { kind: end.state, ...base, reason: end.reason };\n return {\n kind: \"replay\",\n ...base,\n agent: receipt.name,\n state: receipt.state,\n };\n }\n }\n const planned = planAttempt(db, ws, task);\n if (!planned.ok) return { kind: \"skip\", task, reason: planned.reason };\n const p = planned.plan;\n return { kind: \"spawn\", task, attempt: p.attempt, key: p.key, agent: p.name, cli: p.cli };\n}\n\n/**\n * Can the stored attempt never progress? Read-only. `abandoned`: nothing was\n * sent, or the task is over. `needs_human`: the prompt may have landed and\n * there is nothing to ask. Undefined: it can still be resumed (or probed).\n */\nfunction unreconcilable(\n db: Db,\n ws: string,\n task: string,\n receipt: SpawnReceipt,\n): AttemptEnd | undefined {\n const t = getTask(db, task, ws);\n if (t === undefined) return { state: \"abandoned\", reason: \"the task is gone\" };\n if (t.status === \"CLOSED\") return { state: \"abandoned\", reason: \"the task is closed\" };\n const sent = receipt.state === \"sending\" || receipt.state === \"unknown\";\n const lost = (reason: string): AttemptEnd => ({\n state: sent ? \"needs_human\" : \"abandoned\",\n reason,\n });\n if (receipt.state === \"reserved\") {\n return t.ownerId === null ? undefined : lost(\"the task is owned by another agent\");\n }\n const id = savedIdentity(db, receipt);\n if (id.stale !== undefined) {\n return lost(`the agent of this attempt is ${id.stale}`);\n }\n if (sent && receipt.transport !== \"ctl\") {\n return lost(\"the send went through the pane: there is no receipt to ask\");\n }\n return undefined;\n}\n\n/**\n * End a stored attempt (terminal: never replayed or counted again). A\n * `needs_human` end first records the caller's one-line human need (a repeat\n * is a no-op), so a crash between the two leaves the attempt retryable.\n */\nfunction park(ctx: Ctx, task: string, record: AttemptRecord, end: AttemptEnd): NextMove {\n // A caller with no identity (a plain shell) has no human-need record to keep: the move says it.\n if (end.state === \"needs_human\" && ctx.caller !== \"\") {\n recordHumanNeeded(ctx.db, {\n workstream: ctx.ws,\n caller: ctx.caller,\n reason: `attempt ${record.key} of task ${task} may have been delivered and cannot be confirmed (${end.reason}); never resent`,\n });\n }\n const taskId = taskIdFor(ctx.db, task, ctx.ws);\n if (taskId !== null) endAttempt(ctx.db, taskId, record.key, end);\n return {\n kind: end.state,\n task,\n attempt: record.attempt,\n key: record.key,\n cli: record.cli,\n reason: end.reason,\n };\n}\n\n/** The guard of an attempt: this caller's human need and permission (and, before the pane, still ready) just before each effect. */\nfunction guardOf(ctx: Ctx, task: string, key: string) {\n let refusedAt: \"spawn\" | \"send\" | undefined;\n const guard = (phase: \"spawn\" | \"send\"): void => {\n const stop = (why: string): never => {\n refusedAt = phase;\n throw new SpawnAttemptGuardError(task, key, why);\n };\n if (ctx.humanStop()) stop(\"this caller has an open human need\");\n const taskId = taskIdFor(ctx.db, task, ctx.ws);\n if (taskId === null || !autoPermitted(ctx.db, taskId)) {\n stop(\"it is no longer authorised for this machine\");\n }\n if (phase === \"spawn\" && !listReady(ctx.db, ctx.ws).some((t) => t.name === task)) {\n stop(\"it is no longer ready\");\n }\n if (\n phase === \"spawn\" &&\n ctx.workers !== undefined &&\n liveWorkers(ctx.db, ctx.ws) >= ctx.workers\n ) {\n stop(`the worker ceiling ${ctx.workers} is reached`);\n }\n };\n return { guard, refusedAt: () => refusedAt };\n}\n\nfunction outcomeMove(\n kind: \"spawn\" | \"replay\" | \"retry\",\n task: string,\n rec: Pick<AttemptRecord, \"attempt\" | \"key\" | \"cli\">,\n out: TaskSpawnOutcome,\n): NextMove {\n const reason = out.reason;\n return {\n kind,\n task,\n attempt: rec.attempt,\n key: rec.key,\n agent: out.agent?.name ?? out.receipt.name,\n cli: rec.cli,\n state: out.state,\n ...(out.stale !== undefined ? { stale: out.stale } : {}),\n ...(reason !== undefined ? { reason } : {}),\n ...(out.checked !== undefined ? { checked: out.checked } : {}),\n };\n}\n\n/** Run one reserved or stored attempt through the guarded spawn, sending its STORED prompt; map its errors to moves. */\nasync function drive(\n ctx: Ctx,\n task: string,\n kind: \"spawn\" | \"replay\" | \"retry\",\n rec: AttemptRecord,\n): Promise<NextMove> {\n const { db, ws } = ctx;\n const g = guardOf(ctx, task, rec.key);\n try {\n const out = await spawnAutoAttempt(db, {\n task,\n text: rec.text,\n key: rec.key,\n guard: g.guard,\n ...(rec.inPlace === true ? { keepAgent: true } : {}),\n spawn: {\n name: rec.name,\n workstream: ws,\n cli: rec.cli,\n ...(rec.worktree ? { worktree: true } : {}),\n nextFree: true,\n },\n });\n const move = outcomeMove(kind, task, rec, out);\n // A replay's probe that still cannot say: the attempt is parked, not probed again.\n if (kind === \"replay\" && out.state === \"unknown\") {\n return {\n ...park(ctx, task, rec, {\n state: \"needs_human\",\n reason: out.reason ?? \"the send could not be confirmed\",\n }),\n ...(out.checked !== undefined ? { checked: out.checked } : {}),\n };\n }\n return move;\n } catch (err) {\n if (err instanceof NoMultiplexerError) throw err;\n const base = { task, attempt: rec.attempt, key: rec.key, cli: rec.cli };\n if (err instanceof SpawnAttemptBusyError) {\n // Another mu holds this attempt: nothing was done here.\n return { kind: \"skip\", ...base, reason: `attempt in flight: ${err.message}` };\n }\n if (err instanceof SpawnAttemptGuardError) {\n // Before the pane nothing was done and the reservation stays resumable.\n // At the send a pane was spawned and rolled back: an effect, charged.\n const kind = g.refusedAt() === \"send\" ? \"rolled_back\" : \"skip\";\n return { kind, ...base, reason: err.message };\n }\n const reason = err instanceof Error ? err.message : String(err);\n // An error before any effect (a receipt that disagrees with its stored\n // request, a bad row) leaves the receipt in flight: end it now, or it\n // would be selected and fail on every invocation.\n const taskId = taskIdFor(db, task, ws);\n const left = taskId === null ? undefined : getReceipt(db, taskId, rec.key);\n if (left !== undefined && IN_FLIGHT_STATES.has(left.state)) {\n const sent = left.state === \"sending\" || left.state === \"unknown\";\n park(ctx, task, rec, { state: sent ? \"needs_human\" : \"abandoned\", reason });\n }\n return { kind: \"failed\", ...base, reason };\n }\n}\n\nasync function resume(ctx: Ctx, task: string): Promise<NextMove> {\n const { db, ws } = ctx;\n const taskId = taskIdFor(db, task, ws);\n const { record, receipt } = taskId === null ? {} : readAttempt(db, taskId);\n if (record === undefined || receipt === undefined) {\n return { kind: \"skip\", task, reason: \"no stored attempt\" };\n }\n const end = unreconcilable(db, ws, task, receipt);\n if (end !== undefined) return park(ctx, task, record, end);\n return drive(ctx, task, \"replay\", record);\n}\n\nasync function allocate(ctx: Ctx, task: string): Promise<NextMove> {\n const reserved = reserveAttempt(ctx.db, ctx.ws, task);\n if (!reserved.ok) {\n return {\n kind: \"skip\",\n task,\n reason: `attempt ${reserved.code === \"in-flight\" ? \"in flight\" : reserved.code}: ${reserved.reason}`,\n };\n }\n return drive(ctx, task, \"spawn\", reserved.plan);\n}\n\n/**\n * One recovery effect, re-validated at the effect (the scan was a moment ago).\n * reap the saved registry id + pane compare-and-swap of `deleteAgent` (a\n * replaced name is kept); the task reopens with the reaper's note and\n * is allocated again by the same pass, with the brief saying the\n * previous attempt died. Local workers only.\n * retry re-read the worker (still idle on the same pi, at the errored run,\n * nothing pending, no dialog), then one transaction charges the run\n * and reserves the in-place attempt, then the guarded journaled send.\n */\nasync function recover(\n ctx: Ctx,\n act: Extract<RecoveryAction, { kind: \"reap\" | \"retry\" }>,\n observe: ObserveWorkers,\n signal: AbortSignal | undefined,\n): Promise<NextMove> {\n const { db, ws } = ctx;\n const skip = (reason: string): NextMove => ({ kind: \"skip\", task: act.task, reason });\n if (ctx.humanStop()) return skip(\"this caller has an open human need\");\n const taskId = taskIdFor(db, act.task, ws);\n if (taskId === null || !autoPermitted(db, taskId)) {\n return skip(\"it is no longer authorised for this machine\");\n }\n if (act.kind === \"reap\") {\n // The CAS is the scan's saved id + pane (a replaced name is kept); the host is read NOW:\n // a worker that became remote since the scan is not ours to reap.\n const a = act.agent;\n const now = getAgentRow(db, a.name, a.workstreamName);\n if (now?.host != null) return skip(\"a remote worker is never reaped from here\");\n const deleted = deleteAgent(db, a.name, a.workstreamName, {\n paneId: a.paneId,\n incarnation: a.incarnation,\n });\n return deleted\n ? { kind: \"reap\", task: act.task, agent: a.name, reason: act.why }\n : skip(\"the worker was replaced before it could be reaped\");\n }\n const { agent } = act.target;\n const row = getAgentRow(db, agent.name, ws);\n if (row === undefined) return skip(\"the worker is gone\");\n const now = (\n await observe([row], { ms: OBSERVE_MS, ...(signal !== undefined ? { signal } : {}) })\n ).get(workerKey(row));\n if (\n now === undefined ||\n !idleOnCtl(now) ||\n now.incarnation !== act.target.pi ||\n now.runs !== act.target.errorRuns ||\n now.lastError === undefined\n ) {\n return skip(\"the worker is no longer idle at the errored run: left to the wait\");\n }\n const reserved = reserveRetry(db, ws, act.task, act.target);\n if (!reserved.ok) {\n return skip(\n `retry ${reserved.code === \"ceiling\" ? \"ceiling\" : reserved.code}: ${reserved.reason}`,\n );\n }\n const { task: _t, taskId: _i, workstream: _w, revision: _r, ...rec } = reserved.plan;\n const move = await drive(ctx, act.task, \"retry\", rec);\n return { ...move, reason: move.reason ?? `API error: ${act.error.slice(0, 200)}` };\n}\n","// mu — `mu pi migrate`: retire the pre-package `mu link pi` installs.\n//\n// pi now loads mu as a package (`pi install npm:@mu-crew/mu`). A leftover\n// ~/.pi/agent/extensions/mu.ts shim would load a SECOND copy of the\n// extension, so it must leave pi's discovery path first. Only files mu\n// itself generated are moved, and moved aside, never deleted. Ownership is\n// proven, never inferred from a name or a marker mentioned somewhere:\n// extension: a regular file byte-identical to the shim template every\n// released `mu link pi` generated; only the import URL may differ, and\n// only in its generated form (a file:// URL to dist/extension/mu-pi.js).\n// skill: a symlink resolving into THIS install's skills/mu, or a real\n// directory byte-identical to a released mu skill (KNOWN_SKILL_DIGESTS).\n// Everything else is reported with a one-line note and left alone.\n//\n// Destinations live under `MU_PI_HOME ?? homedir()`; tests pass `home`.\n\nimport { createHash } from \"node:crypto\";\nimport { lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { KNOWN_SKILL_DIGESTS } from \"./pi-known-skills.js\";\n\n/** First line of every shim the old `mu link pi` generated. */\nexport const MU_SHIM_MARKER = \"// mu:shim\";\n\nexport type MigrateState = \"absent\" | \"shim\" | \"foreign\";\n\nexport interface MigrateEntry {\n path: string;\n state: MigrateState;\n moved: boolean;\n /** Where it went (apply only). */\n to?: string;\n}\n\nexport interface MigrateResult {\n extension: MigrateEntry;\n skill: MigrateEntry;\n guidance: string[];\n}\n\nexport interface MigrateOptions {\n home?: string;\n /** Move what is verified mu-owned. Default: report only. */\n apply?: boolean;\n /** This install's root (holds skills/mu). Default: the package root. */\n packageRoot?: string;\n /** Digests of released skill dirs. Default: KNOWN_SKILL_DIGESTS. */\n knownSkillDigests?: readonly string[];\n}\n\nfunction lstatOrUndefined(path: string): ReturnType<typeof lstatSync> | undefined {\n try {\n return lstatSync(path);\n } catch {\n return undefined;\n }\n}\n\n/** A name next to `dest` that does not exist yet, so a parked file is never overwritten. */\nfunction freeName(dest: string): string {\n if (!lstatOrUndefined(dest)) return dest;\n for (let i = 1; ; i++) {\n const candidate = `${dest}.${i}`;\n if (!lstatOrUndefined(candidate)) return candidate;\n }\n}\n\nfunction park(from: string, dest: string): string {\n const to = freeName(dest);\n mkdirSync(join(to, \"..\"), { recursive: true });\n renameSync(from, to);\n return to;\n}\n\n/** The shim every released `mu link pi` (v3.2.0 to v3.13.3) generated: one\n * template, byte for byte, with only the import line varying. Fixture:\n * test/fixtures/link-shim-v3.txt, produced by the old src/link.ts. */\nconst SHIM_HEAD = `${MU_SHIM_MARKER}\n// Generated by \\`mu link pi\\`. Do not edit.\n//\n// A re-export, not a copy: the extension code lives in the mu install, so\n// upgrading mu upgrades the extension. Re-run \\`mu link pi\\` only if the\n// install path itself moves.\nconst { default: extension } = await import(`;\nconst SHIM_TAIL = `);\nexport default extension;\n`;\n\n/** The generated import argument: JSON.stringify(pathToFileURL(entry).href)\n * of the built extension. Anything else (relative path, other file, a\n * non-canonical URL) is not what mu wrote. */\nfunction isGeneratedImport(arg: string): boolean {\n try {\n const url: unknown = JSON.parse(arg);\n return (\n typeof url === \"string\" &&\n JSON.stringify(url) === arg &&\n new URL(url).href === url &&\n url.startsWith(\"file:///\") &&\n url.endsWith(\"/dist/extension/mu-pi.js\")\n );\n } catch {\n return false;\n }\n}\n\nexport function isMuShimText(text: string): boolean {\n return (\n text.startsWith(SHIM_HEAD) &&\n text.endsWith(SHIM_TAIL) &&\n isGeneratedImport(text.slice(SHIM_HEAD.length, text.length - SHIM_TAIL.length))\n );\n}\n\nfunction isMuShim(path: string): boolean {\n try {\n return isMuShimText(readFileSync(path, \"utf8\"));\n } catch {\n return false;\n }\n}\n\n/** This file's package root: src/ and the bundled dist/ both sit one level below it. */\nfunction defaultPackageRoot(): string {\n return resolve(dirname(fileURLToPath(import.meta.url)), \"..\");\n}\n\n/** SHA-256 over the sorted `relative path NUL file-sha256` lines of a\n * directory tree. undefined if it holds anything but regular files and\n * directories (a symlink is never part of a released skill). */\nexport function skillDirDigest(dir: string): string | undefined {\n const lines: string[] = [];\n const walk = (d: string): boolean => {\n for (const ent of readdirSync(d, { withFileTypes: true })) {\n const p = join(d, ent.name);\n if (ent.isDirectory()) {\n if (!walk(p)) return false;\n } else if (ent.isFile()) {\n const sum = createHash(\"sha256\").update(readFileSync(p)).digest(\"hex\");\n lines.push(`${relative(dir, p).split(sep).join(\"/\")}\\0${sum}\\n`);\n } else return false;\n }\n return true;\n };\n try {\n if (!walk(dir)) return undefined;\n } catch {\n return undefined;\n }\n return createHash(\"sha256\").update(lines.sort().join(\"\")).digest(\"hex\");\n}\n\nfunction isMuSkill(\n path: string,\n st: NonNullable<ReturnType<typeof lstatSync>>,\n root: string,\n known: readonly string[],\n): boolean {\n try {\n if (st.isSymbolicLink()) {\n const own = realpathSync(join(root, \"skills\", \"mu\"));\n const rel = relative(own, realpathSync(path));\n return rel === \"\" || (!rel.startsWith(\"..\") && !isAbsolute(rel));\n }\n if (!st.isDirectory()) return false;\n const digest = skillDirDigest(path);\n return digest !== undefined && known.includes(digest);\n } catch {\n return false;\n }\n}\n\nexport function migratePi(opts: MigrateOptions = {}): MigrateResult {\n const home = opts.home ?? process.env.MU_PI_HOME ?? homedir();\n const extPath = join(home, \".pi\", \"agent\", \"extensions\", \"mu.ts\");\n const skillPath = join(home, \".agents\", \"skills\", \"mu\");\n\n // The shim must be a regular file: a symlink (e.g. to a dev checkout) is foreign.\n const extSt = lstatOrUndefined(extPath);\n const extension: MigrateEntry = {\n path: extPath,\n state: !extSt ? \"absent\" : extSt.isFile() && isMuShim(extPath) ? \"shim\" : \"foreign\",\n moved: false,\n };\n const skSt = lstatOrUndefined(skillPath);\n const skill: MigrateEntry = {\n path: skillPath,\n state: !skSt\n ? \"absent\"\n : isMuSkill(\n skillPath,\n skSt,\n opts.packageRoot ?? defaultPackageRoot(),\n opts.knownSkillDigests ?? KNOWN_SKILL_DIGESTS,\n )\n ? \"shim\"\n : \"foreign\",\n moved: false,\n };\n\n if (opts.apply === true) {\n if (extension.state === \"shim\") {\n // `.shim`, not `.ts`: pi loads every *.ts under extensions/ and ignores the rest.\n extension.to = park(extPath, join(home, \".pi\", \"agent\", \"disabled\", \"mu.ts.shim\"));\n extension.moved = true;\n }\n if (skill.state === \"shim\") {\n skill.to = park(skillPath, join(home, \".agents\", \"disabled\", \"skills\", \"mu\"));\n skill.moved = true;\n }\n }\n\n const guidance: string[] = [];\n if (opts.apply !== true && (extension.state === \"shim\" || skill.state === \"shim\")) {\n guidance.push(\"Nothing moved. Re-run with --apply to move the mu-owned files aside.\");\n }\n for (const e of [extension, skill]) {\n if (e.state === \"foreign\") {\n guidance.push(\n `Left ${e.path} in place: not proven mu's. If it duplicates the package, move it aside yourself.`,\n );\n }\n }\n if (extension.moved || skill.moved) {\n guidance.push(\n \"Running pi agents keep the old extension until they restart: restart pi or run /reload.\",\n );\n }\n guidance.push(\"Install the package once: pi install npm:@mu-crew/mu\");\n return { extension, skill, guidance };\n}\n","// SHA-256 digests (see skillDirDigest in pi-migrate.ts) of `skills/mu` as\n// every released mu tag shipped it. `mu pi migrate` treats a copied skill\n// directory as mu-owned only if it hashes to one of these: a copy someone\n// edited, or a skill of the same name from elsewhere, never matches.\n// Append a new release by hashing its `skills/mu` tree the same way.\n\nexport const KNOWN_SKILL_DIGESTS: readonly string[] = [\n \"bab34e7d50b31dd9960f64a8192f78f023ce3e9a5dd6a080bda3c7d3aaf68ba8\", // v0.2.0\n \"a76d272878cb90afc4f5a64ef903a0e80dd3eb7fd92dda23bcbba03854786051\", // v0.3.0\n \"cb4116919f86bff5c61268cce5059c0965b6c5673d92fb1466ebe654c560425d\", // v0.3.1\n \"1fc6a019ee71c06d311070058ba76572f6b778e160a5ebd93faeef32002a67dd\", // v0.3.2\n \"4029bcea85a7470798261041c3626b7fea16f9c84d195a3c4266221e7af4fafb\", // v0.4.0\n \"272984f7db1812241f8659a71deeac1e7d81367ecf843d6436385d6cec410000\", // v0.4.1\n \"7d58aebec9bbb40cad90b6da9e9a369cee0aebed03d194ea153c8e4229fbfe16\", // v0.4.5\n \"e4645a869fbd5153a7390d1cbfe2f3842038f895b4f754a4c44e23512270b5c7\", // v1.0.0\n \"41479003fe7f7a7d757413dcf31eb46330b9689c70aa0200347aaf6bafd972f1\", // v1.0.1\n \"1ba368054d76b931639e3dfe02bd53ed8277e47ab28d989ce3bfb7df7497dc7e\", // v1.1.0\n \"e10e2cf93a31a6b24ce1f19951e1a278299b0c33f8020bd293eff807b24fb20f\", // v1.1.1\n \"b38c8da4c685b9478aebb13905607bf295af9d9880c7da2aa1e750f24d508e28\", // v1.2.0\n \"82c14d2c9cbe7bf81f89e4031aeccee8284ffd4ddddea298547b31e1f78bef39\", // v1.3.0\n \"f787792a820b08aaa7cc338931bf239b5b54e3b536d06127aa8da2d9c938ef5a\", // v1.3.2\n \"9c5ac614ff9bf3db7d8c5aca3d2d422f8c175efa35533d0c2e174bd74682e073\", // v1.4.0\n \"6aa1d11a96d9ccd7587e979b8ef2d48d55d9b486f2ccfd160e228c57671cf340\", // v1.6.0\n \"c33778ae1c9efbb3306395e970c2e9d4a859e19aea11d6ba0429c38ea7f9d05a\", // v2.0.0\n \"8aabe979d125399274e6ed42c40353f775be61730e4c07c882d16f68d6fd3da8\", // v3.0.0\n \"bce15b51a9d8b1d0d277e7e3a79ff902d7ab306085c51eb5cb7e8e126b92564c\", // v3.1.0\n \"7dba4e5b3058e14c4314f886a26a5b5f50b99a3180d5fbe81b4751ac4e187f49\", // v3.10.0\n \"177fdc1ab4c273eef1ad004732c35fc4820a72b57991e4754d5f53063d782e49\", // v3.10.1\n \"a648aed46f7e1120ef8fbf021748a40c5434621e036fc443a817899a87dbb028\", // v3.11.0\n \"ace13205c56b40bb8de0265e4f524eec18a0583b508d7951eb6185c102e4470a\", // v3.13.0\n \"ff47c6b99435f0b30ef9fea3f6d8384c5718d7c952bbe3cada79b82ea70680fc\", // v3.13.2\n \"76e5b12be5e78f4b53981718938c33377f896be41b70be88c6feedc0e101af2b\", // v3.13.3\n \"3bd49e0b22440bd670e915683409e8929579128a9ea3f50d6c7ea3eb6ea124cc\", // v3.2.0\n \"13428e619c423d8e3dc39772343ac6be12b08b0e648113d791364c447d4f6dee\", // v3.2.1\n \"258fc3f9212387669f4b8a9442cdebfd04736378fedc4055acf2096b7759e962\", // v3.3.0\n \"f1a31d16d644bc484b3755ad9019e760098e8f089359cbd12dad3e4570ef14c0\", // v3.4.0\n \"75cb30f7291b5613df1ffa11d497ff91972c576c625141c6cb7a5ac34f206d6b\", // v3.5.0\n \"4123cd6e5a19b27bae298a1b56896e06237e8187ace51ccd8aef99c6486a6800\", // v3.7.0\n \"848eb0fe7fff3108162027f65fe1482675e5ecf074312e9799e6056c6212800f\", // v3.8.0\n \"7d9784b1c881f545e376a5ddb37da66b589e12b4dadbb204db69767835887546\", // v3.8.1\n];\n","// mu — `agent collect`: bring a remote worker's commits home (v_remote_collect).\n//\n// The PANE is the transport (src/remote-agent.ts), so a live worker holds its\n// host's channel: at `--max-sessions 1` collect is refused beside it by the one\n// admission every remote command passes (a one-line HostChannelBusyError naming\n// the holder), and works once the pane is gone or the cap is raised. mu never\n// connects: the work is the profile's `fetch` template, run LOCALLY with the\n// local repo as its working directory, under one transient channel.\n//\n// What \"collected\" means, so a template cannot fake it: FETCH_HEAD is removed\n// first, the template runs, and the commit is whatever `FETCH_HEAD^{commit}`\n// resolves to afterwards (no commit: a failed collect, nothing recorded). That\n// commit is pinned under `refs/mu/collect/<ws>/<agent>` (a ref git's gc keeps)\n// and only then recorded as `agents.collected_head` (compare-and-set on the\n// agent's id, pane, host, cwd and base). The merge command printed names the\n// exact sha, never FETCH_HEAD. A per-repo lock stops two collects from sharing\n// one FETCH_HEAD. mu never merges.\n\nimport { createHash } from \"node:crypto\";\nimport { rm } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { AgentLockBusyError, AgentNotFoundError, AgentReplacedError } from \"./agents/errors.js\";\nimport { withAgentLock } from \"./agents/lock.js\";\nimport { type AgentRow, getAgent } from \"./agents.js\";\nimport type { Db } from \"./db.js\";\nimport { locksDir, withFileLock } from \"./file-lock.js\";\nimport { runLeasedTemplate, withHostChannel } from \"./hosts.js\";\nimport { say } from \"./messages.js\";\nimport { localPaneAlive } from \"./remote-agent.js\";\nimport {\n assertRecoveryProfile,\n assertRecoveryUnchanged,\n assertRecoveryUsable,\n pinnedByOthers,\n type RemoteRecovery,\n RemoteRecoveryRefusedError,\n recoveryGone,\n recoveryHolds,\n selectRemoteRecovery,\n setRecoveryCollectedHead,\n} from \"./remote-recovery.js\";\nimport { git } from \"./vcs/git.js\";\n\n/** Budget for the local fetch (it moves objects, so it may take a while). */\nexport const REMOTE_COLLECT_TIMEOUT_MS = 300_000;\n\n/** `agent collect` on an agent that has no remote worktree to collect from. Exit 2. */\nexport class RemoteCollectUnsupportedError extends Error {\n override readonly name = \"RemoteCollectUnsupportedError\";\n constructor(agent: string, why: string) {\n super(say(\"remote.collect_unsupported\", agent, why));\n }\n}\n\n/** The fetch failed or produced no commit: nothing was recorded. Exit 5 (substrate). */\nexport class RemoteCollectError extends Error {\n override readonly name = \"RemoteCollectError\";\n constructor(\n public readonly host: string,\n detail: string,\n ) {\n super(say(\"remote.collect_failed\", host, detail));\n }\n}\n\nexport interface CollectResult {\n /** The collected commit, as fetched. */\n head: string;\n /** The durable ref holding it in the local repo. */\n ref: string;\n /** A command for the user to run; mu never runs it. */\n merge: string;\n /** False when this HEAD is the one already collected (or still the base). */\n changed: boolean;\n /** Set when the commits were collected for a removed agent's recovery record (its id), not a live agent. */\n recoveryId?: number;\n}\n\n/** What a collect works on: a live agent's row, or a removed agent's recovery record. */\ninterface CollectTarget {\n host: string;\n cwd: string;\n base: string;\n collectedHead: string | null;\n /** The agent or record id: never another incarnation's pin owner. */\n ownerId: number;\n /** Record `head` as the collected one (compare-and-set on the captured identity); false when it moved. */\n record(head: string): boolean;\n /** Refuse (throw) unless the target is still exactly what was captured. */\n recheck(): void;\n /** The refusal for a target that changed between the capture and the write. */\n lost(): Error;\n}\n\n/** The record a collect on `<workstream>/<name>` means, when there is no live agent (or one is asked for by id). */\nfunction recoveryTarget(db: Db, rec: RemoteRecovery): CollectTarget {\n return {\n host: rec.host,\n cwd: rec.cwd,\n base: rec.base,\n collectedHead: rec.collectedHead,\n ownerId: rec.agentId,\n record: (head) =>\n head === rec.collectedHead ? recoveryHolds(db, rec) : setRecoveryCollectedHead(db, rec, head),\n recheck: () => {\n assertRecoveryUnchanged(db, rec);\n assertRecoveryUsable(db, rec);\n },\n lost: () =>\n new RemoteRecoveryRefusedError(\n rec.workstream,\n rec.name,\n \"changed\",\n `recovery ${rec.agentId} changed while its commits were being collected; the pin was restored`,\n [rec.agentId],\n ),\n };\n}\n\nexport function collectRef(workstream: string, name: string): string {\n return `refs/mu/collect/${workstream}/${name}`;\n}\n\nconst firstLine = (s: string): string =>\n s\n .split(\"\\n\")\n .find((l) => l.trim() !== \"\")\n ?.trim() ?? \"\";\n\nfunction repoLockPath(db: Db, repo: string): string {\n const base = db.memory || db.name === \"\" ? locksDir() : join(dirname(db.name), \"locks\");\n return join(base, `collect-${createHash(\"sha256\").update(repo).digest(\"hex\").slice(0, 16)}.lock`);\n}\n\n/**\n * Fetch `name`'s remote worktree into the local repo `opts.repo` (a git\n * checkout) and record the collected HEAD. Idempotent: the same remote HEAD\n * twice records once and says `changed: false`.\n */\nexport async function collectRemoteAgent(\n db: Db,\n opts: { workstream: string; name: string; repo: string; recoveryId?: number },\n): Promise<CollectResult> {\n const { workstream, name, repo } = opts;\n return withAgentLock(db, workstream, name, () =>\n withFileLock(\n repoLockPath(db, repo),\n `collect ${repo}`,\n async () => {\n const agent = getAgent(db, name, workstream);\n // A removed agent's worktree (`remote_recovery`): by id, or the one\n // left when no agent holds the name. A live agent beside a named id\n // refuses in assertRecoveryUsable.\n const rec =\n opts.recoveryId !== undefined || agent === undefined\n ? selectRemoteRecovery(db, workstream, name, opts.recoveryId)\n : undefined;\n if (rec === undefined && opts.recoveryId !== undefined) {\n throw recoveryGone(workstream, name, opts.recoveryId);\n }\n let target: CollectTarget;\n if (rec !== undefined) {\n assertRecoveryUsable(db, rec);\n target = recoveryTarget(db, rec);\n } else if (agent !== undefined) {\n target = agentTarget(db, agent);\n } else {\n throw new AgentNotFoundError(name, workstream);\n }\n const { host, cwd, base } = target;\n const r = await withHostChannel(\n db,\n host,\n `collect:${workstream}/${name}`,\n async (profile, lease) => {\n if (rec !== undefined) assertRecoveryProfile(rec, profile);\n // Under the lease, so a refused collect touches nothing. A stale\n // FETCH_HEAD must not pass for this fetch's answer.\n const fetchHead = await git([\"rev-parse\", \"--git-path\", \"FETCH_HEAD\"], repo);\n await rm(resolve(repo, fetchHead), { force: true });\n return runLeasedTemplate(\n db,\n lease,\n profile,\n \"fetch\",\n { cwd },\n REMOTE_COLLECT_TIMEOUT_MS,\n repo,\n );\n },\n { paneAlive: localPaneAlive },\n );\n if (r.exitCode === null) {\n throw new RemoteCollectError(\n host,\n `timed out after ${REMOTE_COLLECT_TIMEOUT_MS}ms; nothing recorded`,\n );\n }\n if (r.exitCode !== 0) {\n const why = firstLine(r.stderr) || firstLine(r.stdout);\n throw new RemoteCollectError(\n host,\n `fetch exited ${r.exitCode}${why === \"\" ? \"\" : `: ${why}`}; nothing recorded`,\n );\n }\n let head: string;\n try {\n head = await git([\"rev-parse\", \"--verify\", \"FETCH_HEAD^{commit}\"], repo);\n } catch {\n throw new RemoteCollectError(\n host,\n \"the fetch template succeeded but left no commit in FETCH_HEAD (does it `git fetch`?); nothing recorded\",\n );\n }\n // The fetch was slow: the identity must still hold before a ref is moved.\n target.recheck();\n const ref = collectRef(workstream, name);\n const prior = await git([\"rev-parse\", \"--verify\", \"-q\", ref], repo).catch(() => undefined);\n // The ref is ONE per (workstream, name), not per incarnation: moving it\n // would drop the pin another unresolved recovery's commit relies on.\n if (prior !== undefined && prior !== head) {\n const holders = pinnedByOthers(db, { workstream, name, agentId: target.ownerId }, prior);\n if (holders.length > 0) {\n throw new RemoteRecoveryRefusedError(\n workstream,\n name,\n \"pin\",\n `${ref} pins ${prior.slice(0, 12)}, the collected HEAD of recovery ${holders.join(\", \")}; close that recovery first, then collect`,\n holders,\n );\n }\n }\n await git([\"update-ref\", ref, head], repo);\n if ((await git([\"rev-parse\", \"--verify\", ref], repo)) !== head) {\n throw new RemoteCollectError(host, `could not pin ${ref}; nothing recorded`);\n }\n const changed = head !== (target.collectedHead ?? base);\n await recordCollected(target, head, ref, repo, prior);\n return {\n head,\n ref,\n merge: `git merge ${head}`,\n changed,\n ...(rec === undefined ? {} : { recoveryId: rec.agentId }),\n };\n },\n {\n strict: true,\n onUnavailable: () => {\n throw new AgentLockBusyError(name, workstream);\n },\n },\n ),\n );\n}\n\n/** A live agent as a collect target: remote worktree rows only. */\nfunction agentTarget(db: Db, agent: AgentRow): CollectTarget {\n const { host, cwd, base } = agent;\n if (host === null || cwd === null) {\n throw new RemoteCollectUnsupportedError(agent.name, \"it is a local agent\");\n }\n if (base === null) {\n throw new RemoteCollectUnsupportedError(\n agent.name,\n \"it was spawned with --cwd, not --worktree: there is no remote worktree of its own\",\n );\n }\n const fence = \"id = ? AND pane_id = ? AND host IS ? AND cwd IS ? AND base IS ?\";\n const who = [agent.incarnation, agent.paneId, agent.host, agent.cwd, agent.base];\n return {\n host,\n cwd,\n base,\n collectedHead: agent.collectedHead,\n ownerId: agent.incarnation,\n // An unchanged head writes nothing, but is still fenced: success names this incarnation.\n record: (head) =>\n head === agent.collectedHead\n ? db.prepare(`SELECT 1 FROM agents WHERE ${fence}`).all(...who).length === 1\n : db\n .prepare(`UPDATE agents SET collected_head = ?, updated_at = ? WHERE ${fence}`)\n .run(head, new Date().toISOString(), ...who).changes === 1,\n recheck: () => {\n const now = getAgent(db, agent.name, agent.workstreamName);\n if (now?.incarnation !== agent.incarnation || now.paneId !== agent.paneId) {\n throw new AgentReplacedError(agent.name, agent.workstreamName, \"collected\");\n }\n },\n lost: () => new AgentReplacedError(agent.name, agent.workstreamName, \"collected\"),\n };\n}\n\n/** Compare-and-set the record on the target captured before the awaits (also for an unchanged head: the fence is the same); restore the ref when it was replaced. */\nasync function recordCollected(\n target: CollectTarget,\n head: string,\n ref: string,\n repo: string,\n prior: string | undefined,\n): Promise<void> {\n if (target.record(head)) return;\n // Undo only this attempt's pin: the ref goes back to what it held (an earlier collect's commit stays pinned).\n await (prior === undefined\n ? git([\"update-ref\", \"-d\", ref, head], repo)\n : git([\"update-ref\", ref, prior, head], repo)\n ).catch(() => {});\n throw target.lost();\n}\n","// Shared task sort keys and comparators.\n//\n// Used by the CLI task list/next verbs and by the TUI all-tasks popup.\n// Keep this below the CLI layer so TUI files never import from src/cli.ts\n// (that bundle cycle previously made `node dist/cli.js --help` exit\n// silently).\n\nimport { compareStrings } from \"../compare.js\";\nimport type { TaskRow } from \"./core.js\";\n\nexport const TASK_SORT_KEYS = [\"roi\", \"recency\", \"age\", \"id\"] as const;\nexport type TaskSortKey = (typeof TASK_SORT_KEYS)[number];\n\nexport function isTaskSortKey(s: string): s is TaskSortKey {\n return (TASK_SORT_KEYS as readonly string[]).includes(s);\n}\n\nfunction roiOf(t: TaskRow): number {\n return t.effortDays > 0 ? t.impact / t.effortDays : Number.POSITIVE_INFINITY;\n}\n\n/** The `ready` order (README: \"scored tasks by impact/effort desc, then\n * the rest oldest first\"). A task whose impact/effort were only\n * defaulted never outranks a scored one. Scored ties: smaller effort,\n * then name. Unscored: oldest created_at, then name. The `roi` sort key,\n * `task next`, `my next` and `mu state` all use it. */\nexport function byRoiDesc(a: TaskRow, b: TaskRow): number {\n if (a.scored !== b.scored) return a.scored ? -1 : 1;\n if (!a.scored) {\n const byCreated = compareStrings(a.createdAt, b.createdAt);\n return byCreated !== 0 ? byCreated : compareStrings(a.name, b.name);\n }\n const ra = roiOf(a);\n const rb = roiOf(b);\n if (rb !== ra) return rb - ra;\n if (a.effortDays !== b.effortDays) return a.effortDays - b.effortDays;\n return compareStrings(a.name, b.name);\n}\n\n/** Sort a copy of `tasks` by `key`. Pure (does not mutate input). */\nexport function sortTasks(tasks: readonly TaskRow[], key: TaskSortKey): TaskRow[] {\n const out = tasks.slice();\n switch (key) {\n case \"roi\":\n return out.sort(byRoiDesc);\n case \"recency\":\n // updated_at DESC: most-recently-touched first.\n return out.sort((a, b) => {\n const byUpdated = compareStrings(b.updatedAt, a.updatedAt);\n return byUpdated !== 0 ? byUpdated : compareStrings(a.name, b.name);\n });\n case \"age\":\n // created_at ASC: oldest first (\"what's gone stale\").\n return out.sort((a, b) => {\n const byCreated = compareStrings(a.createdAt, b.createdAt);\n return byCreated !== 0 ? byCreated : compareStrings(a.name, b.name);\n });\n case \"id\":\n return out.sort((a, b) => compareStrings(a.name, b.name));\n }\n}\n\n/** Which timestamp basis the table's relative-time column should use\n * for the active sort, or `null` if no time column should be shown. */\nexport function relTimeBasisForSort(key: TaskSortKey): \"updatedAt\" | \"createdAt\" | null {\n if (key === \"recency\") return \"updatedAt\";\n if (key === \"age\") return \"createdAt\";\n return null;\n}\n","// SDK seam for `mu state`, `mu me` and the dashboard.\n//\n// `stateSnapshot` is the canonical read: one stable, READ-ONLY shape (SQL\n// column names; no reconcile, no reap, no write) that `mu state` bounds and\n// prints as JSON and the dashboard projects. Pure data — no rendering.\n\nimport { type AgentOutput, liveAgentToOutput } from \"./agent-output.js\";\nimport { type AgentRow, readLiveAgents } from \"./agents.js\";\nimport { type Db, tryResolveLiveWorkstreamId, WorkstreamNotFoundError } from \"./db.js\";\nimport { type DelegateRow, listDelegates, type VerdictTally, verdictTally } from \"./delegates.js\";\nimport { openHumanNeeds } from \"./human-needed.js\";\nimport { byRoiDesc } from \"./tasks/sort.js\";\nimport {\n listBlocked,\n listInProgress,\n listReady,\n listTasks,\n listTasksByOwner,\n type TaskRow,\n} from \"./tasks.js\";\n\n// ─── stateSnapshot: the canonical read ────────────────────────────\n\n/** One task in a state read: SQL column names, `id` = `local_id`. */\nexport interface StateTask {\n id: string;\n title: string;\n status: string;\n substate: string;\n impact: number;\n effort_days: number;\n /** Owner's name; only while IN_PROGRESS (a CLOSED task's owner is history). */\n owner: string | null;\n kind: string;\n wave: string | null;\n updated_at: string;\n /** `MAX(ops.seq)` over the task's own ops, its notes' and its edges' (raw log, db/sql writes included); 0 when none. */\n activity_seq: number;\n}\n\n/** A delegate call that has not finished (`done`/`failed`/`cancelled` are in the wave tally). */\nexport interface StateDelegate {\n call_id: string;\n /** The delegate task's local id, in this workstream. */\n task: string;\n state: string;\n wave: string | null;\n /** The task judged, `<workstream>/<task>`; null with no record target. */\n judges: string | null;\n agent: string | null;\n verdict: string | null;\n error: string | null;\n updated_at: string;\n}\n\n/** One wave of the caller's own calls in this workstream, tallied per call (`verdictTally`'s findings summed). */\nexport interface StateWave {\n wave: string;\n calls: number;\n confirmed: number;\n refuted: number;\n unverified: number;\n pending: number;\n queued: number;\n running: number;\n /** Call ids refused past the cap, still to reissue. */\n refused: string[];\n}\n\n/** An OPEN `human` task of the caller. */\nexport interface StateHumanNeed {\n id: string;\n /** The brief notes joined with \"; \" (whole; the CLI bounds it). */\n reason: string;\n}\n\nexport interface StateCounts {\n tasks: number;\n open: number;\n parked: number;\n triage: number;\n ready: number;\n blocked: number;\n in_progress: number;\n closed: number;\n}\n\nexport interface WorkstreamState {\n workstream: string;\n workstream_id: number;\n counts: StateCounts;\n /** `scored` order (`byRoiDesc`). */\n ready: StateTask[];\n /** Newest activity first. Absent in a `me` read, which narrows to counts, ready, delegates, waves and human needs. */\n in_progress?: StateTask[];\n blocked?: StateTask[];\n triage?: StateTask[];\n recent_closed?: StateTask[];\n /** Registry rows (host/cwd/base/collected_head included) with their runtime state; unknown stays unknown. */\n agents?: AgentOutput[];\n delegates: StateDelegate[];\n waves: StateWave[];\n human_needs: StateHumanNeed[];\n /** Set when the workstream is mostly history (past BIG_WORKSTREAM_TASKS tasks, under 10% open): start the next effort in a new one. */\n hint?: string;\n /** Panes in the workstream's mux session that look like agents but are not registered. Set only by `mu state`, which reconciles first (the snapshot itself reads no mux). */\n orphans?: { pane_id: string; command: string }[];\n}\n\n/** `mu me`: the caller's own identity and the tasks it owns. */\nexport interface StateMe {\n caller: string;\n /** The managed agent's record; null for a pi session (`pi:<session>`), which has no agent row. */\n agent: AgentOutput | null;\n /** Non-CLOSED tasks the agent owns in its workstream. */\n owned_tasks: StateTask[];\n}\n\nexport interface StateSnapshot {\n /** `spawnerFromEnv()` identity: `<ws>/<agent>`, `pi:<session>`, or null (delegates and human needs then stay empty). */\n caller: string | null;\n me: StateMe | null;\n workstreams: WorkstreamState[];\n}\n\nexport interface StateSnapshotOptions {\n /** The scope, already resolved (variadic/comma/repeated `-w` and `--all` live in the CLI). Empty is legal. */\n workstreams: readonly string[];\n caller: string | null;\n /** A `me` read: adds the caller's identity block (`agent` is its registry row, null for a pi session) and narrows each workstream. */\n me?: { agent: AgentRow | null };\n}\n\nconst RECENT_CLOSED = 5;\n/** Past this many tasks, a workstream that is under 10% open gets the one-per-effort hint. */\nconst BIG_WORKSTREAM_TASKS = 300;\n\nfunction taskActivity(db: Db, workstream: string): Map<string, number> {\n const prefix = `${workstream}/`;\n const rows = db\n .prepare(\n `SELECT entity, key, MAX(seq) AS seq FROM ops\n WHERE entity IN ('task', 'note', 'edge') AND key >= ? AND key < ?\n GROUP BY entity, key`,\n )\n .all(prefix, `${workstream}0`) as { entity: string; key: string; seq: number }[];\n const out = new Map<string, number>();\n const bump = (id: string, seq: number): void => {\n if (seq > (out.get(id) ?? 0)) out.set(id, seq);\n };\n for (const r of rows) {\n if (r.entity === \"task\") bump(r.key.slice(prefix.length), r.seq);\n else if (r.entity === \"note\") bump(r.key.slice(prefix.length).split(\"#\")[0] ?? \"\", r.seq);\n else {\n const [from, to] = r.key.split(\"->\");\n if (from !== undefined) bump(from.slice(prefix.length), r.seq);\n if (to !== undefined) bump(to.slice(prefix.length), r.seq);\n }\n }\n return out;\n}\n\nfunction stateTask(row: TaskRow, activity: ReadonlyMap<string, number>): StateTask {\n return {\n id: row.name,\n title: row.title,\n status: row.status,\n substate: row.substate,\n impact: row.impact,\n effort_days: row.effortDays,\n owner: row.status === \"IN_PROGRESS\" ? row.ownerName : null,\n kind: row.kind,\n wave: row.wave,\n updated_at: row.updatedAt,\n activity_seq: activity.get(row.name) ?? 0,\n };\n}\n\n/** Newest activity first; no ops (capture suppressed) falls back to `updated_at`, then id. */\nfunction byActivityDesc(a: StateTask, b: StateTask): number {\n if (a.activity_seq !== b.activity_seq) return b.activity_seq - a.activity_seq;\n if (a.updated_at !== b.updated_at) return a.updated_at < b.updated_at ? 1 : -1;\n return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;\n}\n\nconst FINISHED_CALL: readonly string[] = [\"done\", \"failed\", \"cancelled\"];\n\nfunction delegatesOf(\n db: Db,\n workstream: string,\n caller: string | null,\n): { delegates: StateDelegate[]; waves: StateWave[] } {\n if (caller === null) return { delegates: [], waves: [] };\n const calls: DelegateRow[] = listDelegates(db, caller, workstream);\n const delegates = calls\n .filter((c) => !FINISHED_CALL.includes(c.state))\n .map((c) => ({\n call_id: c.callId,\n task: c.task,\n state: c.state,\n wave: c.wave,\n judges: c.record ? `${c.record.workstream}/${c.record.task}` : null,\n agent: c.agent,\n verdict: c.verdict,\n error: c.error,\n updated_at: c.updatedAt,\n }));\n const labels = [...new Set(calls.flatMap((c) => (c.wave === null ? [] : [c.wave])))].reverse();\n const waves = labels.map((wave) => waveOf(verdictTally(db, workstream, wave, [caller]), wave));\n return { delegates, waves };\n}\n\nfunction waveOf(t: VerdictTally, wave: string): StateWave {\n const sum = (k: \"confirmed\" | \"refuted\" | \"unverified\" | \"pending\"): number =>\n t.findings.reduce((n, f) => n + f[k], 0);\n const w = {\n wave,\n confirmed: sum(\"confirmed\"),\n refuted: sum(\"refuted\"),\n unverified: sum(\"unverified\"),\n pending: sum(\"pending\"),\n };\n return {\n ...w,\n calls: w.confirmed + w.refuted + w.unverified + w.pending,\n queued: t.queued,\n running: t.running,\n refused: t.refused,\n };\n}\n\nfunction countsOf(db: Db, wsId: number): StateCounts {\n const n = (sql: string): number => (db.prepare(sql).get(wsId) as { n: number }).n;\n const by = (cond: string): number =>\n n(`SELECT count(*) AS n FROM tasks WHERE workstream_id = ? AND ${cond}`);\n return {\n tasks: by(\"1 = 1\"),\n open: by(\"status = 'OPEN'\"),\n parked: by(\"status = 'OPEN' AND substate = 'parked'\"),\n triage: by(\"status = 'OPEN' AND substate = 'triage'\"),\n ready: n(\"SELECT count(*) AS n FROM ready WHERE workstream_id = ?\"),\n blocked: n(\"SELECT count(*) AS n FROM blocked WHERE workstream_id = ?\"),\n in_progress: by(\"status = 'IN_PROGRESS'\"),\n closed: by(\"status = 'CLOSED'\"),\n };\n}\n\nasync function meOf(db: Db, caller: string | null, self: AgentRow | null): Promise<StateMe> {\n if (self === null) return { caller: caller ?? \"\", agent: null, owned_tasks: [] };\n const ws = self.workstreamName;\n const wsRow = db.prepare(\"SELECT id, torn_down_at FROM workstreams WHERE name = ?\").get(ws) as\n | { id: number; torn_down_at: string | null }\n | undefined;\n const [live] = await readLiveAgents(db, ws, self.name);\n const live_ = live === undefined ? null : liveAgentToOutput(live, wsRow?.id ?? 0);\n const alive = wsRow !== undefined && wsRow.torn_down_at === null;\n const activity = alive ? taskActivity(db, ws) : new Map<string, number>();\n return {\n caller: caller ?? `${ws}/${self.name}`,\n agent: live_,\n owned_tasks: alive\n ? listTasksByOwner(db, ws, self.name)\n .map((r) => stateTask(r, activity))\n .sort(byActivityDesc)\n : [],\n };\n}\n\n/** Live workstreams where `caller` has a delegate call or an open human need (a pi session has no workstream of its own). */\nexport function callerWorkstreams(db: Db, caller: string): string[] {\n const live = new Set(\n (\n db.prepare(\"SELECT name FROM workstreams WHERE torn_down_at IS NULL\").all() as {\n name: string;\n }[]\n ).map((r) => r.name),\n );\n const names = new Set([\n ...listDelegates(db, caller).map((c) => c.workstream),\n ...openHumanNeeds(db, caller).map((h) => h.workstream),\n ]);\n return [...names].filter((n) => live.has(n)).sort();\n}\n\n/**\n * The canonical state read: tasks, agents, the caller's delegate queue and\n * waves, and its open human needs, per workstream, under SQL column names.\n * READ-ONLY: it never reconciles or reaps (`mu state` reconciles first, on its\n * own), so the dashboard can reuse it. Async only for the ctl probes. The\n * result is whole; the CLI bounds it (`mu state`).\n *\n * `me` narrows each workstream to counts, ready, delegates, waves and human\n * needs, and adds the caller's identity block. The delegate queue and human\n * needs are the CALLER's own, never another session's.\n */\nexport async function stateSnapshot(db: Db, opts: StateSnapshotOptions): Promise<StateSnapshot> {\n const needs = opts.caller === null ? [] : openHumanNeeds(db, opts.caller);\n const workstreams: WorkstreamState[] = [];\n let me: StateMe | null = null;\n for (const ws of opts.workstreams) {\n const wsId = tryResolveLiveWorkstreamId(db, ws);\n if (wsId === null) throw new WorkstreamNotFoundError(ws);\n const activity = taskActivity(db, ws);\n const task = (r: TaskRow): StateTask => stateTask(r, activity);\n const state: WorkstreamState = {\n workstream: ws,\n workstream_id: wsId,\n counts: countsOf(db, wsId),\n ready: listReady(db, ws).sort(byRoiDesc).map(task),\n ...delegatesOf(db, ws, opts.caller),\n human_needs: needs\n .filter((h) => h.workstream === ws)\n .map((h) => ({ id: h.id, reason: h.reason })),\n };\n if (opts.me === undefined) {\n state.in_progress = listInProgress(db, ws).map(task).sort(byActivityDesc);\n state.blocked = listBlocked(db, ws).map(task).sort(byActivityDesc);\n state.triage = listTasks(db, ws, { status: \"OPEN\", substate: \"triage\" })\n .map(task)\n .sort(byActivityDesc);\n state.recent_closed = listTasks(db, ws, { status: \"CLOSED\" })\n .map(task)\n .sort(byActivityDesc)\n .slice(0, RECENT_CLOSED);\n state.agents = (await readLiveAgents(db, ws)).map((a) => liveAgentToOutput(a, wsId));\n const { tasks, open, in_progress } = state.counts;\n const unfinished = open + in_progress;\n if (tasks >= BIG_WORKSTREAM_TASKS && unfinished * 10 < tasks) {\n state.hint = `${tasks} tasks, ${unfinished} open; start the next effort in a new <project>-<purpose> workstream`;\n }\n }\n workstreams.push(state);\n }\n if (opts.me !== undefined) me = await meOf(db, opts.caller, opts.me.agent);\n return { caller: opts.caller, me, workstreams };\n}\n","// mu — wait resumes: the stored condition set behind `mu wait --resume <id>`.\n//\n// A `mu wait` that ends with something still owed (a timeout, a signal, an event\n// that left siblings open) prints ONE handle, `mu wait --resume <id>`, instead of\n// a command that spells every ref and flag. The row (`wait_resumes`,\n// machine-local) holds what the wait was: the refs still owed with the run\n// baseline and pi incarnation each was last seen at, the mode, every filter, the\n// deadline the caller asked for, and the callers the wait ran for. So a resume is\n// lossless (no ref is dropped, an agent that restarted meanwhile is refused, not\n// miscounted) and its size does not grow with the wait.\n//\n// Pure SQLite, one short synchronous write per saved handle. Rows older than\n// RESUME_KEEP_DAYS go on the next save (no daemon). No foreign keys: a handle\n// outlives the tasks and agents it names.\n\nimport { randomBytes } from \"node:crypto\";\nimport type { Db } from \"./db.js\";\nimport { say } from \"./messages.js\";\nimport { type WaitRef, WaitRefError } from \"./wait-types.js\";\n\n/** What a wait asked for, whatever spelling it came in; a resume replays exactly this. */\nexport interface ResumeSpec {\n refs: WaitRef[];\n mode: \"first\" | \"all\";\n scope?: string;\n status?: string;\n untilText?: string;\n stuckAfter?: number;\n onStall: \"exit\" | \"warn\" | \"steer\" | \"release\";\n wave?: string;\n blockersOf?: { workstream: string; id: string };\n /** Seconds as the caller gave them; absent = the default. */\n timeout?: number;\n /** The reaper-flip anchor (ops seq) of the wait that saved it: a worker that died since is still dead. */\n since?: number;\n}\n\nexport interface StoredResume {\n id: string;\n /** The callers the wait ran for (see `currentCallers`): the identity is part of the condition set. */\n callers: string[];\n spec: ResumeSpec;\n}\n\n/** Handles older than this are dropped when the next one is saved. */\nexport const RESUME_KEEP_DAYS = 14;\n\n/** `mu wait --resume <id>` names a handle that does not exist (never saved, or older than RESUME_KEEP_DAYS). */\nexport class WaitResumeNotFoundError extends Error {\n override readonly name = \"WaitResumeNotFoundError\";\n constructor(public readonly resumeId: string) {\n super(say(\"wait.resume_not_found\", resumeId, RESUME_KEEP_DAYS));\n }\n}\n\n/** Save the condition set; returns the handle. */\nexport function saveResume(db: Db, callers: readonly string[], spec: ResumeSpec): string {\n const now = new Date();\n const cutoff = new Date(now.getTime() - RESUME_KEEP_DAYS * 86_400_000).toISOString();\n for (let attempt = 0; ; attempt++) {\n const id = randomBytes(5).toString(\"hex\");\n try {\n db.transaction(() => {\n db.prepare(\"DELETE FROM wait_resumes WHERE created_at < ?\").run(cutoff);\n db.prepare(\n \"INSERT INTO wait_resumes (id, callers_json, spec_json, created_at) VALUES (?, ?, ?, ?)\",\n ).run(id, JSON.stringify(callers), JSON.stringify(spec), now.toISOString());\n }).immediate();\n return id;\n } catch (e) {\n // 40 bits of id: a collision is a retry, anything else is real.\n if (attempt < 3 && /UNIQUE|PRIMARY KEY/i.test(String(e))) continue;\n throw e;\n }\n }\n}\n\n/** The stored wait, or WaitResumeNotFoundError. */\nexport function loadResume(db: Db, id: string): StoredResume {\n const row = db\n .prepare(\"SELECT callers_json AS callers, spec_json AS spec FROM wait_resumes WHERE id = ?\")\n .get(id) as { callers: string; spec: string } | undefined;\n if (row === undefined) throw new WaitResumeNotFoundError(id);\n try {\n const callers = JSON.parse(row.callers) as string[];\n const spec = JSON.parse(row.spec) as ResumeSpec;\n if (!Array.isArray(callers) || !Array.isArray(spec.refs)) throw new Error(\"bad shape\");\n return { id, callers, spec };\n } catch {\n throw new WaitRefError(`wait resume handle ${id} is unreadable (its stored row is damaged)`);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,SAAS,YAAY,WAAW,QAAQ,gBAAgB;AACxD,SAAS,eAAe;AAUjB,IAAM,2BAAN,cAAuC,MAAM;AAAA,EAClD,YAAqB,MAAc;AACjC,UAAM,IAAI,yBAAyB,IAAI,CAAC;AADrB;AAEnB,SAAK,OAAO;AAAA,EACd;AAAA,EAHqB;AAIvB;AAIO,IAAM,6BAAN,cAAyC,MAAM;AAAA,EACpD,YAAqB,MAAc;AACjC,UAAM,IAAI,4BAA4B,IAAI,CAAC;AADxB;AAEnB,SAAK,OAAO;AAAA,EACd;AAAA,EAHqB;AAIvB;AAuCA,IAAM,uBAAuB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA;AAAA,EAGA;AACF;AAQA,IAAM,oBAAoB,oBAAI,IAAI,CAAC,WAAW,SAAS,WAAW,CA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,4CAA4C;AAAA,EAC7F;AACF;","names":["snapshot","identity","opRows","peerRows","machineLocalLost","rmSync","rmSync","existsSync","dirname","join","join","dirname","existsSync","openBlockers","counts","q","run","resolve","age","select","best","items","chosen","no","move","resume","end","kind","now","lstatSync","mkdirSync","realpathSync","dirname","join","resolve","sep","lstatSync","park","mkdirSync","join","resolve","dirname","sep","realpathSync","createHash","dirname","join","resolve","join","dirname","createHash","resolve"]}
|