pi-dev-flow 0.69.0 → 0.71.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,20 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.71.0] - 2026-11-02
8
+
9
+ - **A running worker finally wears its `⏳` name.** pi fires `session_start` only for sessions a host binds, never for the SDK-built worker, so the live name dev-flow hung on that event never landed: every worker since 0.68 ran as whatever an auto-namer made of its brief (`you-are-a-dev`), and only the final `✓`/`✗` rename showed. The name is now written onto the session before its first prompt.
10
+ - **Workers get their brief, not the driver's context.** A worker loads the operator's extensions, dev-flow included (its guards must hold there too), and dev-flow injected into it what it injects into an unbound driver: about 5k characters of playbook core, "pre-plan first… `flow start`", and a false "main checkout is on feat/…, not main — surface this to the operator" (it read the worktree as the checkout). dev-flow now registers each worker it spawns and stays silent in it. Separately, a human session opened in a linked worktree is no longer told the main checkout is on the wrong branch.
11
+ - **Verify rounds are numbered** like runs: `✓ 🔍 #3 · PASS · <label>`, so a feature that takes six rounds reads as a sequence.
12
+ - **The family view reads headers, not history.** Finding a session's workers used to parse every transcript in the driver's bucket (~15 ms per MB; the dev-flow checkout's bucket was 55 MB, so ~0.8 s for every idle status and settled card, growing with every worker). It now reads the first line of each transcript and only the workers in full.
13
+ - **A recycled pid no longer holds a dead session's claim.** A claim now records its process's start identity (`/proc/<pid>/stat` starttime); a live pid with a different start is somebody else's process and the claim is void. Refusals name the claim's age (`pid 854, claim 3 days old`), and atomic writes use a per-process temp name.
14
+ - **`flow doctor` names worker buckets nothing will show again.** Workers from before 0.70 sit in a session bucket per worktree, invisible from the checkout's folder scope and left behind by `flow finish`; the doctor lists those whose feature is finished or whose worktree is gone, with the `rm -r` that removes them. It never removes them.
15
+
16
+ ## [0.70.0] - 2026-10-31
17
+
18
+ - **A flow's workers are one family in the picker.** Every `flow_stage` worker is now stamped as a child of the session that delegated it: its header carries `parentSession` → the driver's session file, and its transcript lands in the driver's own session bucket. `pi --resume` therefore nests the whole family under the driver in its default **Current Folder** scope, Threaded sort, with no scope switch — and because the worker's name carries its outcome (`✓ 🔍 · PASS · stamp attack`, `✗ 🔨 #3 · hard-cut`), the tree reads without opening a single row. One layout boundary: with a configured session directory that is not the checkout's default, the folder scope filters by each session's own cwd, so workers — whose cwd is the worktree — sit one Tab away under **All**, still threaded.
19
+ - **The family has a text view for hosts without a tree.** The settled card and `flow_stage { op: "status" }` list every worker this session spawned: picker name, message count, last-write time (local wall-clock), transcript path, newest first, older ones folded behind one counted line. The run the card or status is reporting on is left out — it is the section above it — and the section appears only inside a flow. A host with no file-backed session gets the flow's own `transcripts.log` instead, labelled as the coarser source it is. Reading a bucket costs ~15 ms per MB of its history, so a polled live view re-reads at most once per two seconds while the settled card and an idle status always read fresh.
20
+
7
21
  ## [0.69.0] - 2026-10-30
8
22
 
9
23
  - **Workers, so the conversation that talks to you stays lean.** `flow_stage` now delegates to disposable worker sessions with a fresh context, and the skill makes delegation the default for non-trivial implement work: the driver keeps the claim, the gates and the checkpoints, and receives one bounded stage report. A **verify worker** (`op: "verify"`) is an independent, check-only checker of the implement work — and its PASS is now a hard precondition of `flow verify`: the stamp belongs to the exact tree it read (worktree *and* the plan dir it judged against), so any edit anywhere — including a mid-stage plan amendment — drops it like a tier-1 record; a fresh FAIL deletes a contradicted PASS; a reviewer that moves the tree through bash anyway (file, HEAD, branch pointer or plan) voids its own verdict and gets snapshotted. A **reflect worker** (`op: "reflect"`) reviews the finished flow — driver transcript plus every worker transcript, durably indexed in `stage-sessions/transcripts.log` — returning tagged findings to route through Fold?/Fix?/Drop?.
package/README.md CHANGED
@@ -244,6 +244,6 @@ shipped feature checks off the item it was picked from.
244
244
  | [docs/gates.md](docs/gates.md) | every gate and flag, what makes each refuse |
245
245
  | [docs/guardrails.md](docs/guardrails.md) | everything enforced, and the deliberate limits |
246
246
  | [docs/concurrency.md](docs/concurrency.md) | several agents, one repo: bindings, claims, attribution |
247
- | [docs/stage-agent.md](docs/stage-agent.md) | `flow_stage`: run a heavy stage in a disposable worker session |
247
+ | [docs/stage-agent.md](docs/stage-agent.md) | `flow_stage`: run a heavy stage in a disposable worker session — nested under the driver in pi's picker |
248
248
  | [docs/headless.md](docs/headless.md) | driving a session from a bot/UI/queue: `NEEDS-OPERATOR`, `--json` surfaces |
249
249
  | [docs/development.md](docs/development.md) | hacking on dev-flow itself: tests, self-hosting, `/reload` |
package/docs/gates.md CHANGED
@@ -21,7 +21,7 @@ so it needs no `--confirmed`.
21
21
  | `finish [--yolo] [slug]` | release → done (removes worktree + branch, deletes `.dev-flow/<slug>/`, and deletes `origin/<branch>` **only** when its merged state is verified — ancestor of the default branch or a merged PR/MR via `gh`/`glab`; unverifiable branches stay with a note) | a release is recorded (`release-done` ran), the main checkout is clean **and** pushed to `origin/<default>`, and the worktree has no uncommitted changes (the refusal lists the paths, not just the count — gh#131); when the clean checkout trails `origin/<default>` the gate **fast-forwards local main** as it closes out (never a merge — anything that cannot fast-forward prints the operator's exact `git pull --ff-only` command); **one question** (Finish? — mentions unmerged-looking commits with the playbook's `merge` policy in mind, and warns when the forge release create failed at `release-done` and no retry succeeded) — or `--confirmed`; under `merge = merge`, commits that never reached the default branch are a **policy violation**: `yolo` does not answer it, only your explicit answer does; to abandon an unreleased feature use `abort` |
22
22
  | `reflect ["<note>"|list|tidy|move <n> --plugin|--playbook]` | — | `reflect "<note>"` queues a suggestion in `reflections.md` (never gates; gate flags such as `--confirmed` are ignored, they never become part of the note). `--playbook` / `--plugin` files it in that section — the agent knows what its own note is about, so the wording guess is the fallback, and the echoed line prints the reason it landed where it did (`"gate" names dev-flow itself`, `playbook or project wording`, `nothing plugin-shaped in the note …`); a note is filed under **one** section, never both. `reflect list` numbers the open items with their section; `reflect move <n> --plugin|--playbook` re-files one of them. `reflect tidy` drops the closed (`- [x]`) items — the preamble and open items stay verbatim and a `## section` heading left empty goes with its items; every surface that queues or reviews reflections (`reflect "<note>"`, bare `reflect`, `doctor`) nudges with the closed count when the checked-off pile grows. Bare `reflect` prints the full **session-reflection protocol** for the agent (from the `/flow reflect` bar it additionally wakes the model, so the protocol executes immediately): review the whole session log, re-check every open item against the current playbook and **newer dev-flow versions** (`npm view pi-dev-flow version` vs the running version — dev-flow ships from npm; recommend `pi install npm:pi-dev-flow` + `/reload`, the operator performs updates), dedupe new findings against the open ones, then report playbook vs plugin items to the operator and ask whether to fix now — plugin items: search upstream issues first (`gh issue list --repo <upstream> --state all --search …`; an author-addressed match is reported back, no match → `gh issue create` with a detailed description and a suggested fix), playbook items: `flow doctor` routes each to the docs flow that implements it |
23
23
  | `roadmap [add "<feature>" \| pick <n> <slug> \| done <n> \| tidy]` | — | manages `.dev-flow/roadmap.md`, the gitignored backlog of future features (`- [ ]` checklist): bare prints the numbered open items, `add` appends one, `pick <n> <slug>` stamps open item n with `(slug)` so `flow start <slug>` can take it — **`finish` checks the stamped item off when that feature ships**; `done <n>` checks off by hand (items shipped outside a flow), `tidy` drops the checked lines. Never gates; the open count is surfaced in `status` and session context |
24
- | `doctor ["<issue note>"]` | — | read-only findings: playbook drift, dead commands/scripts, untracked playbook, ghost feature dirs, orphan worktrees/branches — the state of an **aborted** feature is never a finding (its worktree cleanup is by design — gh#138) — **plus a review of every open reflection, each routed to the flow that should fix it** (playbook item → docs flow; plugin item → upstream issue, or a patch/normal flow inside the dev-flow repo) — every item is labelled from the `## section` it is filed under (the file is the record, so the table cannot disagree with it) and items sitting outside both sections are named rather than silently bucketed. It writes nothing and asks nothing, safe for agents and CI at any stage; the agent investigates, you confirm, the routed flow implements. `doctor "<note>"` prints an investigation brief and a fix route for a fresh observation, including the section it would be filed under and why |
24
+ | `doctor ["<issue note>"]` | — | read-only findings: playbook drift, dead commands/scripts, untracked playbook, ghost feature dirs, orphan worktrees/branches, pi session buckets left by stage workers under finished or removed worktrees (named with their `rm -r`, never removed) — the state of an **aborted** feature is never a finding (its worktree cleanup is by design — gh#138) — **plus a review of every open reflection, each routed to the flow that should fix it** (playbook item → docs flow; plugin item → upstream issue, or a patch/normal flow inside the dev-flow repo) — every item is labelled from the `## section` it is filed under (the file is the record, so the table cannot disagree with it) and items sitting outside both sections are named rather than silently bucketed. It writes nothing and asks nothing, safe for agents and CI at any stage; the agent investigates, you confirm, the routed flow implements. `doctor "<note>"` prints an investigation brief and a fix route for a fresh observation, including the section it would be filed under and why |
25
25
  | `status [slug]` / `abort [slug]` | — | — |
26
26
  | `help` (`--help`, `-h`) | — | — (prints the gate help — answerable in any repo, at any stage, with no `.dev-flow/`) |
27
27
  | `version [--check-upstream]` | — | — (prints dev-flow's **own** version and the directory it was loaded from — which copy this session runs, this checkout vs an installed `pi-dev-flow`; when the checkout has moved past the build this session loaded it says so and names both, because the gates execute the loaded code — `/reload` to run the newer one; `--check-upstream` adds the published npm version; answerable in any repo, at any stage, with no `.dev-flow/`) |
@@ -64,6 +64,13 @@ binding of its own:
64
64
  reaching around them is a hardening decision, not a control this feature
65
65
  claims.
66
66
 
67
+ The worker loads your extensions like any session, dev-flow included — that is
68
+ how the guards above hold inside it. What it does **not** get is the driver's
69
+ context: dev-flow registers each worker it spawns and injects neither the
70
+ playbook core nor the unbound-session posture into it (that text told a worker
71
+ to pre-plan and `flow start`, and read its worktree as a main checkout on the
72
+ wrong branch). The brief is the worker's whole instruction.
73
+
67
74
  ## The handoff
68
75
 
69
76
  The worker receives a brief assembled by the tool. A `run` worker gets the
@@ -95,12 +102,27 @@ driver's transcript wherever the host renders streamed tool updates (the TUI
95
102
  does; expansion adds the fuller stream, the report and the transcript path).
96
103
  Around it, three mirrors:
97
104
 
98
- - a worker is a real pi session in pi's standard session directory, named by
99
- role glyph, ordinal and purpose — `⏳ 🔨 #2 · wire ops` while it runs, renamed
100
- at the end with its outcome: `✓ 🔨 #2 · 3 commits · wire ops`, a verify `✓ 🔍 ·
101
- PASS · stamp attack`, a cut-off worker `✗ 🔨 #3 · hard-cut`; the verdict never
102
- depends on opening the row (a `label` on the call supplies the purpose; with
103
- none, a `run` is still separated by its ordinal). It appears in the `/resume`
105
+ - a worker is a real pi session, **stamped as this session's child**: its header
106
+ carries `parentSession` → the driver's session file, and its transcript lands in
107
+ the driver's own session bucket — so `pi --resume` nests it under the driver in
108
+ its default **Current Folder** scope, in the Threaded sort, with no scope switch
109
+ (pi #1108 built that link for exactly this: extensions may stamp it on sessions
110
+ they create on a user's behalf). One layout exception: if you point pi at a
111
+ configured session directory (settings `sessionDir`, or `--session-dir`) that is
112
+ not the default for the folder you started it in, that scope filters by each
113
+ session's own cwd and a worker's cwd is its worktree — the family is still
114
+ threaded, one Tab away under **All**, and dev-flow's text view below lists it in
115
+ either layout. On a host with no file-backed session the stamp
116
+ is skipped and the worker keeps pi's default location, unlinked. Named by role
117
+ glyph, ordinal and purpose — `⏳ 🔨 #2 · wire ops` while it runs, renamed
118
+ at the end with its outcome: `✓ 🔨 #2 · 3 commits · wire ops`, a verify `✓ 🔍 #3 ·
119
+ PASS · stamp attack` (verify rounds are numbered like runs, so a feature that took
120
+ six rounds reads as a sequence), a cut-off worker `✗ 🔨 #3 · hard-cut`; the verdict
121
+ never depends on opening the row (a `label` on the call supplies the purpose; with
122
+ none, the ordinal still separates the rows). The live name is written onto the
123
+ session before its first prompt — pi fires `session_start` only for sessions a host
124
+ binds, never for an SDK-built worker, so a name hung on that event never landed and
125
+ an auto-namer was left to title the row from the brief. It appears in the `/resume`
104
126
  picker, and its
105
127
  transcript grows live on disk, readable at any moment — whether a viewer
106
128
  tails a session still running is the viewer's choice, the card above is what
@@ -113,6 +135,33 @@ Around it, three mirrors:
113
135
  `flow_stage { op: "status" }` prints the same tail plus elapsed time, budget,
114
136
  the worktree state and recent commits, on any host, no model call.
115
137
 
138
+ ### The family, on a host with no tree
139
+
140
+ The parent link makes pi's own picker the lineage view. Where a host has no tree
141
+ (or you want the answer in text), the settled card and
142
+ `flow_stage { op: "status" }` list the family instead: one line per worker this
143
+ session spawned — its picker name (so the outcome is right there), message count,
144
+ last-write time, transcript path, newest first, older ones folded behind one
145
+ counted line. The worker the card or status is reporting on is left out — it is the
146
+ section above it — and the section appears only inside a flow, because an unbound
147
+ session has never spawned one:
148
+
149
+ ```
150
+ workers this session spawned:
151
+ ✓ 🔍 #2 · PASS · stamp attack · 7 msgs · 2026-10-30 12:04 · ~/.pi/agent/sessions/…/w2.jsonl
152
+ ✗ 🔨 #1 · hard-cut · 31 msgs · 2026-10-30 11:02 · ~/.pi/agent/sessions/…/w1.jsonl
153
+ ```
154
+
155
+ It is read back from pi's session listing, not from a dev-flow index, so renames,
156
+ deletions and workers an earlier session already delegated all read correctly for
157
+ free. A host that gives dev-flow no session file to be a parent of falls back to
158
+ the lines the flow's own `transcripts.log` already holds — coarser (no message
159
+ count, no rename), still the same answer. A family read opens only the first line
160
+ of each transcript in the bucket to find the workers whose header names this
161
+ session, and reads only those in full — its cost follows the family, not the
162
+ bucket's history. The polled live view still re-reads at most once every two
163
+ seconds, while the settled card and an idle status always read fresh.
164
+
116
165
  Lifecycle is also on the bus: `dev-flow:worker-started` / `-completed` /
117
166
  `-failed` events (slug, op, elapsed, usage) let other extensions react without
118
167
  touching dev-flow. `pi export <file>` turns any finished transcript into
@@ -135,8 +184,18 @@ file to read before deciding what to keep.
135
184
 
136
185
  ## Transcripts
137
186
 
138
- Session JSONL lives where pi keeps sessions (standard dir, discoverable by the
139
- picker and `pi export`); snapshots and the `transcripts.log` index live under
187
+ Session JSONL lives in the **driver's own session bucket** (the directory pi already
188
+ uses for this session), which is what lets pi's picker show a flow's workers as one
189
+ nested family; `pi export` and the picker find them there. Two consequences worth
190
+ knowing: a worker's header `cwd` is still the worktree, so after `flow finish`
191
+ removes that worktree the row points at a directory that is gone (browsing and
192
+ `pi export` still work — resuming it would not); and the bucket is shared with the
193
+ driver's own history, so worker transcripts are only ever deleted by path, never
194
+ by clearing a folder. Workers from before 0.70 sit in a bucket of their own per
195
+ worktree, which no folder scope opened from the checkout shows; `flow doctor` names
196
+ those buckets once their feature is finished or its worktree is gone, with the
197
+ `rm -r` that removes them — it never removes them itself. Snapshots and the
198
+ `transcripts.log` index live under
140
199
  `.dev-flow/<slug>/stage-sessions/` (gitignored, like all flow-owned state).
141
200
 
142
201
  ## Deliberate limits (v2)
@@ -22,11 +22,12 @@
22
22
  import { exec } from "node:child_process";
23
23
  import { createHash } from "node:crypto";
24
24
  import { appendFileSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
25
+ import { open as openFile, readdir as readdirAsync, readFile as readFileAsync, stat as statAsync } from "node:fs/promises";
25
26
  import path from "node:path";
26
27
  import { promisify } from "node:util";
27
28
  import { Type } from "@earendil-works/pi-ai";
28
29
  import { Container, Text } from "@earendil-works/pi-tui";
29
- import { compact, createAgentSession, DefaultResourceLoader, defineTool, getAgentDir, isToolCallEventType, SettingsManager, type AgentSession, type ExtensionContext } from "@earendil-works/pi-coding-agent";
30
+ import { compact, createAgentSession, DefaultResourceLoader, defineTool, getAgentDir, isToolCallEventType, SessionManager, SettingsManager, type AgentSession, type ExtensionContext } from "@earendil-works/pi-coding-agent";
30
31
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
31
32
  import {
32
33
  ALLOW_REWRITE,
@@ -38,6 +39,8 @@ import {
38
39
  buildStageBrief,
39
40
  checkFingerprint,
40
41
  changelogVersionsBetween,
42
+ familyFoldLine,
43
+ familyHeading,
41
44
  normalizeReleaseBody,
42
45
  pendingEntryLines,
43
46
  pickReleaseNotes,
@@ -140,8 +143,21 @@ import {
140
143
  recordVerifyPass,
141
144
  renderVerifyReport,
142
145
  verifyStampMissing,
146
+ sessionPathKey,
147
+ sessionHeaderParent,
148
+ parseSessionSummary,
149
+ markWorkerSession,
150
+ isWorkerSession,
151
+ orphanWorktreeBuckets,
152
+ claimAge,
153
+ processStart,
154
+ type WorktreeBucketFeature,
155
+ workerFamily,
156
+ workerFamilyCount,
157
+ WORKER_FAMILY_ITEMS,
143
158
  workerOpError,
144
159
  workerTranscriptLine,
160
+ type WorkerSessionRow,
145
161
  workerName,
146
162
  sanitizeWorkerLabel,
147
163
  stateTamper,
@@ -234,7 +250,13 @@ function copyWarning(): string | null {
234
250
  }
235
251
  /** Test seam: the smoke suite cannot load a second copy of this module, so it plants registry
236
252
  * entries and asserts the warnings the real duplicate would print. */
237
- export const testSeams = { copies: COPIES, skillCore: { value: undefined as string | null | undefined } };
253
+ export const testSeams = {
254
+ copies: COPIES,
255
+ skillCore: { value: undefined as string | null | undefined },
256
+ /** Where `flow doctor` looks for pi's session buckets; tests point it at a scratch dir so the suite
257
+ * never reads the operator's real session store. `undefined` = `<agent dir>/sessions`. */
258
+ sessionsRoot: { value: undefined as string | null | undefined },
259
+ };
238
260
 
239
261
  interface Ui {
240
262
  hasUI: boolean;
@@ -386,7 +408,8 @@ function writeState(root: string, state: FlowState): void {
386
408
  * truncated state.json — which reads as "no such feature", silently orphaning the worktree, the plan
387
409
  * and every recorded check, with the folder gitignored so nothing else could restore it. */
388
410
  function atomicWrite(file: string, text: string): void {
389
- const tmp = `${file}.tmp`;
411
+ // per-process temp name: two sessions writing the same file must not rename each other's half-write
412
+ const tmp = `${file}.${process.pid}.tmp`;
390
413
  writeFileSync(tmp, text);
391
414
  renameSync(tmp, file);
392
415
  }
@@ -436,36 +459,155 @@ export const compactionTakeover: { run: typeof compact } = { run: compact };
436
459
 
437
460
  /** Seam that spawns the stage worker as a disposable REAL pi session — the smoke suite replaces
438
461
  * `.run` with a stub, so the worker contract stays testable without spending a model and tests
439
- * never touch the real session directory. The real spawn uses the DEFAULT session location (the
440
- * picker and `pi export` find it for free) and names the session through an inline extension —
441
- * `setSessionName` only exists on a session's own extension API — handing back a rename channel
442
- * the driver uses for the ⏳ → ✓/✗ lifecycle. */
462
+ * never touch the real session directory. The real spawn stamps lineage: the worker's header
463
+ * carries `parentSession` → the driver's own session file, and its transcript goes into the
464
+ * driver's session bucket, so pi's picker nests it under the driver in its default Current Folder
465
+ * scope (the Threaded sort reads that link — pi #1108 wrote it for exactly this, "extensions such
466
+ * as /handoff can do the same"). The live ⏳ name is written straight onto the session before its
467
+ * first prompt: pi emits `session_start` only from `bindExtensions()`, which an SDK-created worker
468
+ * never runs, so a name set from a `session_start` handler never lands — every worker used to run
469
+ * under whatever an auto-namer derived from its brief ("you-are-a-dev"). Named before the prompt,
470
+ * an auto-namer sees a name that is not its own and leaves it alone. The same channel carries the
471
+ * ⏳ → ✓/✗ rename. The worker is also registered as a worker, so the dev-flow copy its loader runs
472
+ * keeps its guards but injects none of the driver's context (see `isWorkerSession`). */
443
473
 
444
474
  export interface StageWorkerHandle { session: AgentSession; rename: (name: string) => void }
445
- export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name: string; tools: string[] }) => Promise<StageWorkerHandle> } = {
446
- run: async ({ work, model, name, tools }) => {
447
- let rename: (name: string) => void = () => {};
448
- const loader = new DefaultResourceLoader({
449
- cwd: work,
450
- agentDir: getAgentDir(),
451
- extensionFactories: [{
452
- name: "dev-flow-stage-naming",
453
- hidden: true,
454
- factory: (childPi: ExtensionAPI) => {
455
- childPi.on("session_start", () => { try { childPi.setSessionName(name); } catch { /* naming is visibility, not function */ } });
456
- rename = (n: string) => { try { childPi.setSessionName(n); } catch { /* ditto */ } };
457
- },
458
- }],
459
- });
475
+
476
+ /** The worker's session manager, built exactly as the real seam builds it — split out so a test can
477
+ * drive the production composition (header link + driver's bucket) without spawning a model.
478
+ * Both or neither: `dir` is the driver's own bucket read off the live manager, so a custom
479
+ * PI_CODING_AGENT_DIR can never strand a worker in a different agent dir from its driver, and pi's
480
+ * private `--<encoded cwd>--` directory encoding is never duplicated here. */
481
+ export function workerSessionManager(work: string, parent?: string, dir?: string): SessionManager | undefined {
482
+ return parent && dir ? SessionManager.create(work, dir, { parentSession: parent }) : undefined;
483
+ }
484
+
485
+ export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name: string; tools: string[]; parent?: string; dir?: string }) => Promise<StageWorkerHandle> } = {
486
+ run: async ({ work, model, name, tools, parent, dir }) => {
487
+ const loader = new DefaultResourceLoader({ cwd: work, agentDir: getAgentDir() });
460
488
  await loader.reload();
461
- const { session } = await createAgentSession({ cwd: work, model: model as never, tools, excludeTools: ["flow", "flow_stage"], resourceLoader: loader });
489
+ const sessionManager = workerSessionManager(work, parent, dir);
490
+ const { session } = await createAgentSession({ cwd: work, model: model as never, tools, excludeTools: ["flow", "flow_stage"], resourceLoader: loader, sessionManager });
462
491
  // the op's toolset decides what the worker can touch at all: an implement worker gets the coding
463
492
  // tools, a reviewer gets read + bash only (a checker with an edit tool is a second implementer).
464
493
  // excludeTools is the belt on the extension tools — a worker never holds a gate or a second flow_stage.
465
- return { session, rename: (n) => rename(n) };
494
+ try { markWorkerSession(session.sessionManager.getSessionId()); } catch { /* an id-less session just gets the driver context */ }
495
+ const rename = (n: string) => { try { session.setSessionName(n); } catch { /* naming is visibility, not function */ } };
496
+ rename(name);
497
+ return { session, rename };
466
498
  },
467
499
  };
468
500
 
501
+ /** Seam that reads the driver's session bucket the way the picker does — a stub in the smoke suite,
502
+ * because a test must not scan the operator's real session directory. `listAll(dir)`, not
503
+ * `list(cwd, dir)`: pi's `list` drops rows whose header cwd is not `cwd` whenever it is handed a
504
+ * directory that is not that cwd's default — which is precisely a stage worker (header cwd = the
505
+ * worktree, file in the driver's bucket), and precisely the layout a configured `sessionDir`
506
+ * creates. `listAll(dir)` is what the picker's Current Folder scope sees in the default layout, so
507
+ * the family list and the tree agree there; under a configured session dir the text view stays
508
+ * complete even where that scope hides the worker, which is the cheaper direction to err in. */
509
+ export const sessionRowsScan: { run: (o: { cwd: string; dir?: string; parent?: string }) => Promise<WorkerSessionRow[]> } = {
510
+ run: async ({ dir, parent }) => {
511
+ // no bucket or no driver file to match: the old full listing (a host that never reaches here in practice)
512
+ if (!dir || !parent) return (await SessionManager.listAll(dir)).map((s) => ({ path: s.path, parent: s.parentSessionPath, name: s.name, messageCount: s.messageCount, modified: s.modified }));
513
+ return scanFamilyRows(dir, parent);
514
+ },
515
+ };
516
+
517
+ /** Header bytes read per transcript in the family scan's cheap pass — the same budget pi gives its own
518
+ * header reads. A pi header line is a few hundred bytes. */
519
+ const SESSION_HEADER_BYTES = 4096;
520
+
521
+ /** The family read in two passes, so its cost follows the family, not the bucket: the first line of
522
+ * every transcript (≤ 4 KB each) names its parent; only the files whose parent is `parent` are read
523
+ * in full. `listAll(dir)` parsed every transcript in the bucket — ~15 ms per MB, and a driver bucket
524
+ * only grows (the dev-flow checkout's was 55 MB, ~0.8 s for every idle status and settled card).
525
+ * `fullReads` counts the second pass for the smoke suite. */
526
+ export async function scanFamilyRows(dir: string, parent: string, fullReads?: { n: number }): Promise<WorkerSessionRow[]> {
527
+ let names: string[];
528
+ try { names = (await readdirAsync(dir)).filter((f) => f.endsWith(".jsonl")); } catch { return []; }
529
+ const want = sessionPathKey(parent);
530
+ const rows: WorkerSessionRow[] = [];
531
+ await Promise.all(names.map(async (n) => {
532
+ const file = path.join(dir, n);
533
+ let head = "";
534
+ try {
535
+ const fh = await openFile(file, "r");
536
+ try {
537
+ const buf = Buffer.alloc(SESSION_HEADER_BYTES);
538
+ const { bytesRead } = await fh.read(buf, 0, SESSION_HEADER_BYTES, 0);
539
+ head = buf.subarray(0, bytesRead).toString("utf8");
540
+ } finally { await fh.close(); }
541
+ } catch { return; }
542
+ const p = sessionHeaderParent(head);
543
+ if (!p || sessionPathKey(p) !== want) return;
544
+ try {
545
+ if (fullReads) fullReads.n++;
546
+ const [text, st] = await Promise.all([readFileAsync(file, "utf8"), statAsync(file)]);
547
+ const row = parseSessionSummary(text, file, st.mtimeMs);
548
+ if (row) rows.push(row);
549
+ } catch { /* a transcript deleted mid-scan is simply not in the family */ }
550
+ }));
551
+ return rows;
552
+ }
553
+
554
+ /** Where this session's own transcripts live, when it has any: the file the worker links to, and the
555
+ * bucket it lands in. `null` on a host with no file-backed session — lineage is then unavailable,
556
+ * which is a fact to print, never an error to raise. */
557
+ function lineageOf(ctx: ExtensionContext): { file: string | null; dir: string | null } {
558
+ try {
559
+ return { file: ctx.sessionManager.getSessionFile() ?? null, dir: ctx.sessionManager.getSessionDir() ?? null };
560
+ } catch { /* an in-memory or otherwise unbacked session says so here */ return { file: null, dir: null }; }
561
+ }
562
+
563
+ /** With no file-backed lineage to read — an unbacked host, or a driver pi never wrote a file for —
564
+ * the ledger is what the flow knows: every worker it recorded, newest first. Coarser than the
565
+ * picker's data (no message count, no rename), so the status heading names the source. */
566
+ function ledgerFamilyLines(logPath: string, exclude?: string): string[] {
567
+ try {
568
+ const drop = exclude ? sessionPathKey(exclude) : null;
569
+ const mine = parseWorkerTranscripts(readFileSync(logPath, "utf8")).filter((r) => !drop || sessionPathKey(r.path) !== drop);
570
+ const shown = mine.slice(-WORKER_FAMILY_ITEMS).reverse().map((r) => `${r.op} · ${r.at} · ${r.path}`);
571
+ return mine.length > shown.length ? [...shown, familyFoldLine(mine.length - shown.length)] : shown;
572
+ } catch { return []; }
573
+ }
574
+
575
+ /** Bucket reads are the one IO-bound thing the family view does: one header read per transcript in
576
+ * the driver's bucket, plus a full read of each worker (`scanFamilyRows`). A host renders a running
577
+ * worker by calling status repeatedly, so that path is allowed a slightly stale read; the places the
578
+ * operator draws a conclusion from — idle status, the settled card — always re-read. */
579
+ const BUCKET_FRESH_MS = 2000;
580
+ const bucketCache = new Map<string, { at: number; rows: Awaited<ReturnType<typeof sessionRowsScan.run>> }>();
581
+
582
+ async function bucketRows(ctx: ExtensionContext, dir: string | null, parent: string, staleMs = 0) {
583
+ const key = `${dir ?? "(default bucket)"}\0${parent}`;
584
+ const hit = bucketCache.get(key);
585
+ // staleMs = 0 is not "a zero-length window", it is "no window: read now" — which is what idle status
586
+ // and the settled card ask for, because that is where the operator draws a conclusion. With `<=` the
587
+ // condition also holds inside the caller's own millisecond, and a fast host got the previous read back
588
+ // as a fresh one (this made CI red: a status call answering "what is there now" in the same millisecond
589
+ // as the call before it printed the family that had just gone empty).
590
+ if (staleMs > 0 && hit && Date.now() - hit.at <= staleMs) return hit.rows;
591
+ const rows = await sessionRowsScan.run({ cwd: ctx.cwd, dir: dir ?? undefined, parent });
592
+ if (bucketCache.size > 8) bucketCache.clear(); // a session drives one bucket; anything bigger is stale keys
593
+ bucketCache.set(key, { at: Date.now(), rows });
594
+ return rows;
595
+ }
596
+
597
+ /** The flow's workers as lines, newest first — `null` when this session has no file to be a parent of,
598
+ * which is when the caller reaches for `ledgerFamilyLines` instead.
599
+ * Deliberately read from the picker's own data, not from a dev-flow index: renames, deletions and
600
+ * workers an older session already delegated all read back correctly for free. `exclude` drops one
601
+ * transcript: the caller already shows that run, and meeting it again as an anonymous row under
602
+ * "other workers" reads like somebody else's work belongs to this flow. */
603
+ async function workerFamilyLines(ctx: ExtensionContext, exclude?: string, staleMs = 0): Promise<string[] | null> {
604
+ const { file, dir } = lineageOf(ctx);
605
+ if (!file) return null;
606
+ try {
607
+ return workerFamily(await bucketRows(ctx, dir, file, staleMs), file, { exclude });
608
+ } catch { /* visibility again: a bucket we cannot read is not a reason to lose the run's own report */ return null; }
609
+ }
610
+
469
611
  /** Test-only timer override so the smoke suite drives the soft-steer and the hard cut in ms. */
470
612
  export const stageTimingOverride: { softMs?: number; hardMs?: number } = {};
471
613
 
@@ -485,6 +627,9 @@ interface StageRun {
485
627
  slug: string;
486
628
  usage: StageUsage;
487
629
  turns: number;
630
+ /** the live worker's own session file, once spawned — a family listing leaves it out rather than
631
+ * meeting the run twice: once as the run, once as an unlabeled row under "other workers". */
632
+ transcript?: string;
488
633
  }
489
634
 
490
635
  const stageRuns = new Map<string, StageRun>();
@@ -542,7 +687,13 @@ function readClaim(root: string, slug: string): SessionClaim | null {
542
687
  }
543
688
 
544
689
  const writeClaim = (root: string, slug: string, key: string) =>
545
- atomicWrite(claimFile(root, slug), `${JSON.stringify({ key, pid: process.pid, at: now() })}\n`);
690
+ atomicWrite(claimFile(root, slug), `${JSON.stringify({ key, pid: process.pid, at: now(), start: processStart(process.pid) })}\n`);
691
+
692
+ /** "pid 854, claim 3 days old" — the age is what tells a live session from a recycled pid. */
693
+ const claimWho = (claim: SessionClaim): string => {
694
+ const age = claimAge(claim);
695
+ return `pid ${claim.pid}${age ? `, claim ${age}` : ""}`;
696
+ };
546
697
 
547
698
  /** Let go of everything one session held. In a shared-process host the pid on a claim is the server's and
548
699
  * never dies, so a claim left behind by a finished session keeps refusing every later session with
@@ -1941,6 +2092,7 @@ async function gateDoctor(o: GateCtx): Promise<RunResult> {
1941
2092
  const loaded = loadProject(df);
1942
2093
  const findings = doctorFindings(root, loaded.cfg, loaded.md);
1943
2094
  findings.push(...(await gitConsistency(root, loaded.cfg)));
2095
+ findings.push(...orphanBucketFindings(root));
1944
2096
  const refl = readReflections(root);
1945
2097
  const fold = await foldView(root, refl, isSelfRepo(root));
1946
2098
  if (refl.length) {
@@ -1962,6 +2114,35 @@ async function gateDoctor(o: GateCtx): Promise<RunResult> {
1962
2114
  return { text: investigationBrief(rest.filter((a) => !a.startsWith("--")).join(" "), isSelfRepo(root)).join("\n") };
1963
2115
  }
1964
2116
 
2117
+ /** Session buckets stage workers left under finished or vanished worktrees (see `orphanWorktreeBuckets`).
2118
+ * Information only: the doctor names them and the command that removes them; deleting transcripts is
2119
+ * the operator's call, never the doctor's. Silent when there is no session store to read. */
2120
+ function orphanBucketFindings(root: string): string[] {
2121
+ const sessionsRoot = testSeams.sessionsRoot.value === undefined ? path.join(getAgentDir(), "sessions") : testSeams.sessionsRoot.value;
2122
+ if (!sessionsRoot || !existsSync(sessionsRoot)) return [];
2123
+ let buckets: string[];
2124
+ try { buckets = readdirSync(sessionsRoot, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name); } catch { return []; }
2125
+ const features = new Map<string, WorktreeBucketFeature>();
2126
+ try {
2127
+ for (const d of readdirSync(dfDir(root), { withFileTypes: true })) {
2128
+ if (!d.isDirectory()) continue;
2129
+ const st = readState(root, d.name);
2130
+ if (!st) continue;
2131
+ const wt = st.worktree ? path.resolve(root, st.worktree) : null;
2132
+ features.set(d.name, { finished: st.stage === "done" || !!st.aborted, worktreeExists: !!wt && existsSync(wt) });
2133
+ }
2134
+ } catch { /* no .dev-flow dir: every matching bucket is an orphan */ }
2135
+ const orphans = orphanWorktreeBuckets(buckets, root, features);
2136
+ if (!orphans.length) return [];
2137
+ const rows = orphans.map((o) => {
2138
+ const dir = path.join(sessionsRoot, o.bucket);
2139
+ let n = 0;
2140
+ try { n = readdirSync(dir).filter((f) => f.endsWith(".jsonl")).length; } catch { /* count is cosmetic */ }
2141
+ return ` ${o.slug}: ${n} transcript(s) — rm -r ${sq(dir)}`;
2142
+ });
2143
+ return [`worker session buckets left by finished or removed worktrees (${orphans.length}) — stage workers before 0.70 filed under their worktree, where no picker scope opened from this checkout shows them; keep them for the record or remove:\n${rows.join("\n")}`];
2144
+ }
2145
+
1965
2146
  /** What a gate handler needs from the runFlow preamble. Bodies moved verbatim destructure
1966
2147
  * their own names back, so the bodies needed zero edits. */
1967
2148
  interface GateCtx {
@@ -2042,7 +2223,7 @@ async function gateUse(o: GateCtx): Promise<RunResult> {
2042
2223
  const st = readState(root, slugArg);
2043
2224
  if (!st || st.stage === "done") return { text: `no unfinished feature ${slugArg}`, isError: true };
2044
2225
  const prior = readClaim(root, slugArg);
2045
- const takeover = claimBlocks(prior, sess.key) ? ` — taken over from live session (pid ${prior!.pid})` : "";
2226
+ const takeover = claimBlocks(prior, sess.key) ? ` — taken over from live session (${claimWho(prior!)})` : "";
2046
2227
  sess.bind(slugArg);
2047
2228
  sess.rename(slugArg);
2048
2229
  // a checkpoint that was still unanswered belongs to whoever asked; a session taking the feature over
@@ -2063,7 +2244,7 @@ async function gateAbort(o: GateCtx): Promise<RunResult> {
2063
2244
  // a live claim locks the whole feature, not only its gates: aborting it out from under the session
2064
2245
  // that works it erases the plan that session is still writing (same rule needState applies)
2065
2246
  const claim = readClaim(root, target);
2066
- if (claimBlocks(claim, sess.key)) return { text: `${target} is claimed by another live session (pid ${claim!.pid}) — flow use ${target} takes it over explicitly`, isError: true };
2247
+ if (claimBlocks(claim, sess.key)) return { text: `${target} is claimed by another live session (${claimWho(claim!)}) — flow use ${target} takes it over explicitly`, isError: true };
2067
2248
  if (sess.slug === target) sess.bind(null);
2068
2249
  if (st && !st.worktree) {
2069
2250
  // plan-stage abort = drop: no worktree/branch exists, so the state dir would linger
@@ -2076,6 +2257,14 @@ async function gateAbort(o: GateCtx): Promise<RunResult> {
2076
2257
  }
2077
2258
 
2078
2259
 
2260
+ /** True inside a linked worktree (its git dir is not the common dir), false in a main checkout or on error. */
2261
+ async function isLinkedWorktree(root: string): Promise<boolean> {
2262
+ const r = await sh("git rev-parse --path-format=absolute --git-dir --git-common-dir", root);
2263
+ if (!r.ok) return false;
2264
+ const [gitDir, common] = r.out.split("\n").map((l) => l.trim());
2265
+ return !!gitDir && !!common && path.resolve(gitDir) !== path.resolve(common);
2266
+ }
2267
+
2079
2268
  async function currentBranch(root: string): Promise<string> {
2080
2269
  const r = await sh("git branch --show-current", root);
2081
2270
  return r.ok ? r.out.split("\n")[0] : "";
@@ -2096,7 +2285,7 @@ function needState(root: string, sess: Session, slugArg?: string): { state: Flow
2096
2285
  // sessions overwrite one state file (last write wins) while both believe they own the stage.
2097
2286
  const claim = readClaim(root, slug);
2098
2287
  if (sess.slug !== slug && claimBlocks(claim, sess.key))
2099
- return { state: null, err: { text: `${slug} is claimed by another live session (pid ${claim!.pid}) — flow use ${slug} takes it over explicitly`, isError: true } };
2288
+ return { state: null, err: { text: `${slug} is claimed by another live session (${claimWho(claim!)}) — flow use ${slug} takes it over explicitly`, isError: true } };
2100
2289
  return { state };
2101
2290
  }
2102
2291
 
@@ -2280,7 +2469,7 @@ export default function devFlow(pi: ExtensionAPI) {
2280
2469
  name: "flow_stage",
2281
2470
  label: "Stage worker",
2282
2471
  description:
2283
- 'Delegate to a disposable dev-flow worker session with a fresh context. op "run" (default) does the current stage\'s work (implement | pre-release) and edits + commits on the feature branch; op "verify" is an independent read-only checker of the implement work (read + bash, standing order "check, don\'t fix", closes with a VERIFY REPORT verdict — flow verify refuses until a PASS exists over the current tree); op "reflect" reviews the finished flow — the driver transcript plus every worker transcript — at the release stage after release-done. Everything the worker must know — operator answers not yet recorded by a gate, decisions, warnings, the exact next action — travels in `note`; otherwise it sees only plan, git and flow status. Give each delegation a short `label` (a few words of purpose) — session names then read `⏳ 🔍 · <label>` while running and `✓ 🔍 · <label> · PASS` (or `✗ … · hard-cut`, `✓ 🔨 #2 · 3 commits · <label>`) when done, so the picker is never a column of identical rows. A worker holds no flow tool: gates, checkpoints and the claim stay with you. At 75% of its budget (budgetMin: default 45 for run, 30 for verify/reflect) the worker is steered to commit and report instead of being cut. The tool card streams the live tail (current tool, last assistant line, ✓/✗ results, elapsed/budget, usage) and op "status" mirrors it on any host. When a worker returns: read its report, run flow check yourself, then ask the checkpoint — a stage report is a handoff, never a verification.',
2472
+ 'Delegate to a disposable dev-flow worker session with a fresh context. op "run" (default) does the current stage\'s work (implement | pre-release) and edits + commits on the feature branch; op "verify" is an independent read-only checker of the implement work (read + bash, standing order "check, don\'t fix", closes with a VERIFY REPORT verdict — flow verify refuses until a PASS exists over the current tree); op "reflect" reviews the finished flow — the driver transcript plus every worker transcript — at the release stage after release-done. Everything the worker must know — operator answers not yet recorded by a gate, decisions, warnings, the exact next action — travels in `note`; otherwise it sees only plan, git and flow status. Give each delegation a short `label` (a few words of purpose) — session names then read `⏳ 🔍 #1 · <label>` while running and `✓ 🔍 #1 · PASS · <label>` (or `✗ … · hard-cut`, `✓ 🔨 #2 · 3 commits · <label>`) when done, so the picker is never a column of identical rows. A worker holds no flow tool: gates, checkpoints and the claim stay with you. At 75% of its budget (budgetMin: default 45 for run, 30 for verify/reflect) the worker is steered to commit and report instead of being cut. The tool card streams the live tail (current tool, last assistant line, ✓/✗ results, elapsed/budget, usage) and op "status" mirrors it on any host. When a worker returns: read its report, run flow check yourself, then ask the checkpoint — a stage report is a handoff, never a verification.',
2284
2473
  promptSnippet:
2285
2474
  'flow_stage(op: "run"|"verify"|"reflect", note, budgetMin?) — delegate stage work, an independent read-only check, or the finish review to a fresh worker session; op: "status" reads the live run; gates and checkpoints stay with you',
2286
2475
  parameters: Type.Object({
@@ -2319,7 +2508,21 @@ export default function devFlow(pi: ExtensionAPI) {
2319
2508
  const op: WorkerOp = opRaw;
2320
2509
  if (op === "status") {
2321
2510
  const run = stageRuns.get(sessionKey(ctx));
2322
- if (!run) return { content: [{ type: "text", text: "no stage worker is running in this session" }], details: { running: false } };
2511
+ // The family is the question op:"status" gets when nothing is running — "what has this flow
2512
+ // spawned, and how did each end?". pi's picker threads the same rows into a tree; this is
2513
+ // that fact for a host with no tree, and for the moment between runs. A worker that is live
2514
+ // right now is the section above, not one of "the others" — so it is left out here. The whole
2515
+ // section is gated on a bound feature: an unbound session has never spawned a stage worker,
2516
+ // so there it would be noise paid for with a directory scan.
2517
+ const boundState = (() => { try { return initiated(ctx.cwd) ? boundFeature(ctx.cwd, sessionKey(ctx)) : null; } catch { return null; } })();
2518
+ const inFlow = !!boundState;
2519
+ const fam = inFlow ? await workerFamilyLines(ctx, run?.transcript, run ? BUCKET_FRESH_MS : 0) : null;
2520
+ // the picker's rows when we have them; the ledger when the host gave us no file to be a parent of
2521
+ const familyLines = fam ?? (boundState ? ledgerFamilyLines(path.join(featDir(ctx.cwd, boundState.slug), "stage-sessions", TRANSCRIPTS_FILE), run?.transcript) : null);
2522
+ const familySection = inFlow ? [familyHeading({ live: !!run, ledger: fam === null && !!familyLines?.length }), ...(familyLines && familyLines.length ? familyLines : ["(none yet)"])] : [];
2523
+ if (!run) {
2524
+ return { content: [{ type: "text", text: ["no stage worker is running in this session", ...familySection].join("\n") }], details: { running: false, ...(inFlow ? { workers: workerFamilyCount(familyLines) } : {}) } };
2525
+ }
2323
2526
  const elapsed = Date.now() - run.startedAt;
2324
2527
  const dirtyNow = await sh("git status --porcelain", run.work);
2325
2528
  const logNow = await sh("git log --oneline -5", run.work);
@@ -2329,8 +2532,9 @@ export default function devFlow(pi: ExtensionAPI) {
2329
2532
  stageUsageLine(run.usage, run.turns),
2330
2533
  `worktree now: ${dirtyNow.ok && dirtyNow.out.trim() ? `${dirtyNow.out.trim().split("\n").length} uncommitted path(s)` : "clean"}`,
2331
2534
  `recent commits:\n${logNow.ok && logNow.out.trim() ? logNow.out : "(none)"}`,
2535
+ ...(inFlow ? ["", ...familySection] : []),
2332
2536
  ].join("\n");
2333
- return { content: [{ type: "text", text }], details: { running: true, op: run.op, slug: run.slug, elapsedMs: elapsed, budgetMin: run.budgetMin, softFired: run.softFired, usage: run.usage, turns: run.turns } };
2537
+ return { content: [{ type: "text", text }], details: { running: true, op: run.op, slug: run.slug, elapsedMs: elapsed, budgetMin: run.budgetMin, softFired: run.softFired, usage: run.usage, turns: run.turns, workers: workerFamilyCount(familyLines) } };
2334
2538
  }
2335
2539
  if (!initiated(ctx.cwd)) return err("dev-flow is not initiated here — run flow init first");
2336
2540
  const st = boundFeature(ctx.cwd, sessionKey(ctx));
@@ -2365,6 +2569,9 @@ export default function devFlow(pi: ExtensionAPI) {
2365
2569
  const cfg = loadProject(dfDir(ctx.cwd)).cfg;
2366
2570
  const logFile = path.join(featDir(ctx.cwd, st.slug), "stage-live.log");
2367
2571
  const transcriptLog = path.join(featDir(ctx.cwd, st.slug), "stage-sessions", TRANSCRIPTS_FILE);
2572
+ // read once, used twice: the worker's header links to this file and lands in this bucket,
2573
+ // and the reflect brief names this session's own transcript to the reviewer
2574
+ const lineage = lineageOf(ctx);
2368
2575
  let child: AgentSession | undefined;
2369
2576
  let crash: string | null = null;
2370
2577
  let timedOut = false;
@@ -2379,9 +2586,9 @@ export default function devFlow(pi: ExtensionAPI) {
2379
2586
  writeFileSync(logFile, `${stageLiveLine(0, "worker", `${op} started (${st.stage}, budget ${budgetMin} min)`)}\n`);
2380
2587
  const beat = (toolName: string) => { if (ctx.hasUI) ctx.ui.setStatus("dev-flow-stage", `⏳ ${kindCard} · ${st.slug} ${stageElapsedLabel(Date.now() - run.startedAt)} · ${toolName}`); };
2381
2588
  // ordinal among this feature's same-op workers, read from the durable index — re-delegations
2382
- // read #2, #3 in the list instead of identical rows (only run gets a seq; a verify is known
2383
- // by its verdict, a reflect is one per flow)
2384
- const seq = op === "run" ? (existsSync(transcriptLog) ? parseWorkerTranscripts(readFileSync(transcriptLog, "utf8")).filter((x) => x.op === op).length : 0) + 1 : null;
2589
+ // read #2, #3 in the list instead of identical rows. A verify is numbered too: a feature that
2590
+ // takes six rounds to PASS reads as a sequence, not as six free-text labels. A reflect is one per flow.
2591
+ const seq = op !== "reflect" ? (existsSync(transcriptLog) ? parseWorkerTranscripts(readFileSync(transcriptLog, "utf8")).filter((x) => x.op === op).length : 0) + 1 : null;
2385
2592
  const statusJsonText = (await runFlow(["status", "--json"], ctx.cwd, uiFrom(ctx), sessFor(ctx))).text;
2386
2593
  const git = await sh("git status --porcelain -b", work);
2387
2594
  const note = typeof params.note === "string" ? params.note : undefined;
@@ -2400,10 +2607,8 @@ export default function devFlow(pi: ExtensionAPI) {
2400
2607
  });
2401
2608
  } else if (op === "reflect") {
2402
2609
  const transcripts = existsSync(transcriptLog) ? parseWorkerTranscripts(readFileSync(transcriptLog, "utf8")) : [];
2403
- let driverSession: string | null = null;
2404
- try { driverSession = ctx.sessionManager.getSessionFile() ?? null; } catch { /* a host without a file-backed session says so in the brief */ }
2405
2610
  brief = buildReflectBrief({
2406
- slug: st.slug, planFile, statusJson: statusJsonText, driverSession, transcripts,
2611
+ slug: st.slug, planFile, statusJson: statusJsonText, driverSession: lineage.file, transcripts,
2407
2612
  openReflections: readReflections(ctx.cwd).map((r) => r.line), note,
2408
2613
  });
2409
2614
  } else {
@@ -2426,8 +2631,9 @@ export default function devFlow(pi: ExtensionAPI) {
2426
2631
  // the worker is a REAL pi session in the default location — the pi/pi-web picker renders it
2427
2632
  // live from the append-only transcript (⏳ = resumable later; resuming a live one forks it,
2428
2633
  // browsing is read-only by construction); `pi export <file>` makes it readable HTML
2429
- const worker = await stageWorkerSpawn.run({ work, model: ctx.model, name: workerName("⏳", glyph, seq, label), tools: [...WORKER_OP_TOOLS[op]] });
2634
+ const worker = await stageWorkerSpawn.run({ work, model: ctx.model, name: workerName("⏳", glyph, seq, label), tools: [...WORKER_OP_TOOLS[op]], parent: lineage.file ?? undefined, dir: lineage.dir ?? undefined });
2430
2635
  child = worker.session;
2636
+ try { run.transcript = child.sessionManager.getSessionFile() ?? undefined; } catch { /* the family listing just won't know which row is this run */ }
2431
2637
  emit("dev-flow:worker-started", { budgetMin, startedAt: new Date().toISOString() });
2432
2638
  let lastBeat = 0;
2433
2639
  /** One live line: ledger, durable log, and the streamed card — same text on every host. */
@@ -2505,7 +2711,7 @@ export default function devFlow(pi: ExtensionAPI) {
2505
2711
  // rev-parse misses `checkout -b` at the same SHA, symbolic-ref misses a detached move,
2506
2712
  // and all three miss the plan the verdict was written against living outside the worktree
2507
2713
  const moved = op !== "run" && ((statusBefore.ok && statusAfter.ok && statusAfter.out !== statusBefore.out) || (headBefore.ok && headAfter.ok && headAfter.out !== headBefore.out) || (refBefore.ok && refAfter.ok && refAfter.out !== refBefore.out) || planFingerprint(planDir) !== planBefore);
2508
- // the outcome goes INTO the final name — a picker row like `✓ 🔍 · PASS · stamp attack` or
2714
+ // the outcome goes INTO the final name — a picker row like `✓ 🔍 #3 · PASS · stamp attack` or
2509
2715
  // `✓ 🔨 #2 · 3 commits · wire ops` answers "how did it end?" without opening the session
2510
2716
  let outcome: string | null = null;
2511
2717
  if (clean) {
@@ -2585,8 +2791,13 @@ export default function devFlow(pi: ExtensionAPI) {
2585
2791
  if (crash) parts.push(`worker run ended with an error: ${crash}`);
2586
2792
  if (snapshot && !verify) parts.push(`uncommitted worktree snapshotted (tracked + untracked): ${snapshot} — read it before deciding what to keep`);
2587
2793
  parts.push(check ? `tier-1 rerun after worker: ${check.text.replace(/\s+/g, " ").trim()}` : "tier-1 untouched: a check-only worker leaves the tree (and the records) as it found them — flow check / flow verify rerun what the tree still owes.");
2588
- parts.push(`worker transcript: ${transcript || "(session file unknown)"}${transcript ? `\nreadable as HTML: pi export ${transcript}` : ""}\nindexed in: ${transcriptLog}`);
2794
+ parts.push(`worker transcript: ${transcript || "(session file unknown)"}${transcript ? `\nreadable as HTML: pi export ${transcript}` : ""}\nindexed in: ${transcriptLog}${lineage.file && transcript ? `\nlineage: nested under ${lineage.file} in pi's picker (Threaded, Current Folder)` : ""}`);
2589
2795
  const failed = !!crash || timedOut || moved;
2796
+ // the family belongs on the settled card and the result only: a live frame redraws on every
2797
+ // worker tool call, and reading a session bucket is IO. This run is excluded — the card names
2798
+ // its transcript already, and repeating it as a bare row reads like a different worker.
2799
+ const famFromPicker = await workerFamilyLines(ctx, transcript || undefined);
2800
+ const fam = famFromPicker ?? ledgerFamilyLines(transcriptLog, transcript || undefined);
2590
2801
  emit(failed ? "dev-flow:worker-failed" : "dev-flow:worker-completed", {
2591
2802
  elapsedMs: Date.now() - run.startedAt, usage: run.usage, turns: run.turns, budgetMin, softFired: run.softFired, timedOut, crash,
2592
2803
  verdict: verify?.verdict ?? null, reportMissing: report?.missing ?? findings?.missing ?? false, transcript, snapshot,
@@ -2595,7 +2806,7 @@ export default function devFlow(pi: ExtensionAPI) {
2595
2806
  return {
2596
2807
  content: [{ type: "text" as const, text: parts.join("\n\n") }],
2597
2808
  details: {
2598
- op, slug: st.slug, stage: st.stage, card, cardFull: stageCardLines({ kind, slug: st.slug, elapsedMs: Date.now() - run.startedAt, budgetMin, softFired: run.softFired, tail: run.lastLines, usage: stageUsageLine(run.usage, run.turns), state: failed ? "failed" : "done", verdict: verify?.verdict ?? null, transcript }, true),
2809
+ op, slug: st.slug, stage: st.stage, card, cardFull: stageCardLines({ kind, slug: st.slug, elapsedMs: Date.now() - run.startedAt, budgetMin, softFired: run.softFired, tail: run.lastLines, usage: stageUsageLine(run.usage, run.turns), state: failed ? "failed" : "done", verdict: verify?.verdict ?? null, transcript, family: fam?.length ? fam : undefined, familyHeading: famFromPicker === null ? familyHeading({ ledger: true }) : undefined }, true),
2599
2810
  done: report?.done, files: report?.files, notes: report?.notes, blockers: report?.blockers, reportMissing: report?.missing ?? findings?.missing ?? false,
2600
2811
  verdict: verify?.verdict ?? null, stamped, clearedStamp: cleared, verdictVoided: moved, timedOut, softFired: run.softFired, budgetMin, elapsedMs: Date.now() - run.startedAt, error: crash, transcript, snapshot,
2601
2812
  },
@@ -2831,6 +3042,10 @@ export default function devFlow(pi: ExtensionAPI) {
2831
3042
  // client attaches, and this is the earliest point the client is certainly listening
2832
3043
  refreshStatus(ctx);
2833
3044
  if (!initiated(ctx.cwd)) return undefined;
3045
+ // A stage worker's whole instruction is its brief. The driver's context is wrong there twice over:
3046
+ // the unbound posture tells it to pre-plan and `flow start`, and the branch check reads its
3047
+ // worktree as a main checkout on the wrong branch. Guards still run — they hang off tool_call.
3048
+ if (isWorkerSession(ctx.sessionManager?.getSessionId?.())) return undefined;
2834
3049
  const key = sessionKey(ctx);
2835
3050
  // The playbook core rides along on the message this run writes anyway — once per session.
2836
3051
  const core = corePreamble(key);
@@ -2840,8 +3055,10 @@ export default function devFlow(pi: ExtensionAPI) {
2840
3055
  // Default posture for an unbound session in a dev-flow repo (guards make it stick; this makes it understood).
2841
3056
  let content = "[dev-flow] no flow bound. Every request goes through flow. New work — pre-plan first (see the skill): analyze read-only, bring findings + questions + a direction with a proposed slug/mode to the operator, and flow start <slug> only once they say start; unfinished feature: flow use <slug>.";
2842
3057
  const cb = claimBlocker(ctx.cwd, key);
2843
- if (cb) content += ` Also: ${cb.state.slug} is claimed by another live session (pid ${cb.claim.pid}) — flow use ${cb.state.slug} takes it over explicitly.`;
2844
- const curBr = await currentBranch(ctx.cwd);
3058
+ if (cb) content += ` Also: ${cb.state.slug} is claimed by another live session (${claimWho(cb.claim)}) — flow use ${cb.state.slug} takes it over explicitly.`;
3059
+ // only the main checkout has a "main checkout branch": a session opened in a linked worktree is
3060
+ // on its feature branch by construction, and calling that a drift misleads it
3061
+ const curBr = (await isLinkedWorktree(ctx.cwd)) ? "" : await currentBranch(ctx.cwd);
2845
3062
  if (curBr && curBr !== cfg.defaultBranch) content += ` Also: main checkout is on ${curBr}, not ${cfg.defaultBranch} — surface this to the operator before starting work.`;
2846
3063
  const refl0 = readReflections(ctx.cwd);
2847
3064
  if (refl0.length) content += ` Also: ${refl0.length} reflection(s) open — run flow doctor.`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dev-flow",
3
- "version": "0.69.0",
3
+ "version": "0.71.0",
4
4
  "description": "Enforced feature workflow for Pi: plan → implement → pre-release → release, gated checkpoints, self-improvement reflections, one git worktree per feature, changelog + publish as part of the release",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -17,7 +17,7 @@ worker gets a fresh context holding the plan, live git and `flow status
17
17
  --json` — it keeps nothing from this conversation, so put every operator
18
18
  answer, decision, warning and the exact next action into `note`, and a short
19
19
  `label` — a few words of purpose — so the picker reads `⏳ 🔨 #2 · wire ops` and,
20
- when it ends, `✓ 🔨 #2 · 3 commits · wire ops` (a verify: `✓ 🔍 · PASS · <label>`)
20
+ when it ends, `✓ 🔨 #2 · 3 commits · wire ops` (a verify: `✓ 🔍 #3 · PASS · <label>`)
21
21
  instead of a column of identical rows. The worker
22
22
  may edit and commit in the worktree but holds no flow tool: gates,
23
23
  checkpoints and the claim stay with you. When it returns, digest its stage
package/src/core.ts CHANGED
@@ -1368,6 +1368,11 @@ export interface SessionClaim {
1368
1368
  key: string;
1369
1369
  pid: number;
1370
1370
  at: string;
1371
+ /** The claiming process's start identity (`processStart`), when the platform has one. A pid is
1372
+ * recycled — a claim left by a crashed pi can name a pid some unrelated process now holds — so a
1373
+ * live pid only counts as the claimant when its start identity still matches. Absent on legacy
1374
+ * claims and on platforms without /proc, which keep the pid-only judgement. */
1375
+ start?: string;
1371
1376
  }
1372
1377
 
1373
1378
  /** Whether a process is running (kill 0 only probes existence; EPERM means it exists, foreign-owned). */
@@ -1380,9 +1385,43 @@ export function pidAlive(pid: number): boolean {
1380
1385
  }
1381
1386
  }
1382
1387
 
1383
- /** True only when another live session holds the claim — its feature can only be taken by an explicit `flow use`, never quietly. */
1384
- export function claimBlocks(claim: SessionClaim | null, myKey: string, alive: (pid: number) => boolean = pidAlive): boolean {
1385
- return !!claim && claim.key !== myKey && alive(claim.pid);
1388
+ /** A process's start identity: field 22 (`starttime`, clock ticks since boot) of `/proc/<pid>/stat`.
1389
+ * Two processes that share a pid never share it. `undefined` where there is no procfs. The comm
1390
+ * field (2) may itself hold spaces or parens, so the fields are counted from the LAST `)`. */
1391
+ export function processStart(pid: number, read: (file: string) => string = (f) => readFileSync(f, "utf8")): string | undefined {
1392
+ try {
1393
+ const stat = read(`/proc/${pid}/stat`);
1394
+ const rest = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
1395
+ // rest[0] is field 3 (state), so field 22 sits at index 19
1396
+ const st = rest[19];
1397
+ return st && /^\d+$/.test(st) ? st : undefined;
1398
+ } catch {
1399
+ return undefined;
1400
+ }
1401
+ }
1402
+
1403
+ /** True only when another live session holds the claim — its feature can only be taken by an explicit `flow use`, never quietly.
1404
+ * A claim whose pid is alive but whose recorded start identity no longer matches belongs to a dead
1405
+ * session whose pid was recycled: it does not block. */
1406
+ export function claimBlocks(claim: SessionClaim | null, myKey: string, alive: (pid: number) => boolean = pidAlive, startOf: (pid: number) => string | undefined = processStart): boolean {
1407
+ if (!claim || claim.key === myKey || !alive(claim.pid)) return false;
1408
+ if (claim.start) {
1409
+ const now = startOf(claim.pid);
1410
+ if (now !== undefined && now !== claim.start) return false;
1411
+ }
1412
+ return true;
1413
+ }
1414
+
1415
+ /** How old a claim is, in words, for a refusal: "claimed 3 days ago" lets the operator tell a live
1416
+ * session from a stale pid at a glance. Empty when the stamp is unreadable. */
1417
+ export function claimAge(claim: SessionClaim, nowMs: number = Date.now()): string {
1418
+ const t = Date.parse(claim.at);
1419
+ if (!Number.isFinite(t)) return "";
1420
+ const min = Math.max(0, Math.round((nowMs - t) / 60000));
1421
+ if (min < 60) return `${min} min old`;
1422
+ const h = Math.round(min / 60);
1423
+ if (h < 48) return `${h} h old`;
1424
+ return `${Math.round(h / 24)} days old`;
1386
1425
  }
1387
1426
 
1388
1427
  /** Footer glyph per stage: the footer has no room for stage words and no legend of its own (README:Status bar is the legend). */
@@ -2322,6 +2361,10 @@ export interface StageCardView {
2322
2361
  verdict?: "pass" | "fail" | null;
2323
2362
  note?: string;
2324
2363
  transcript?: string;
2364
+ /** settled card only: the flow's other workers, already rendered by `workerFamily`. */
2365
+ family?: string[];
2366
+ /** heading for `family` when the rows came from somewhere coarser than pi's listing. */
2367
+ familyHeading?: string;
2325
2368
  }
2326
2369
 
2327
2370
  /** One frame of the worker card: header (what · where · clock against budget), the bounded live tail,
@@ -2334,9 +2377,206 @@ export function stageCardLines(v: StageCardView, expanded = false): string[] {
2334
2377
  if (v.verdict) out.push(`verdict: ${v.verdict.toUpperCase()}`);
2335
2378
  if (v.usage) out.push(v.usage);
2336
2379
  if (expanded && v.transcript) out.push(`transcript: ${v.transcript}`);
2380
+ // the family only on the settled card: listing a session directory is IO, and a live frame
2381
+ // redraws on every worker tool call — a running run must not pay for a directory read
2382
+ if (expanded && v.family?.length) out.push(v.familyHeading ?? familyHeading(), ...v.family);
2383
+ return out;
2384
+ }
2385
+
2386
+ /** One worker session as pi's own session listing describes it. dev-flow keeps no lineage index
2387
+ * of its own: the `parentSession` link in a session header *is* the record, and pi's picker threads
2388
+ * on it. The extension reads pi's types and maps them onto this pi-free shape so the logic here
2389
+ * stays unit-testable. */
2390
+ export interface WorkerSessionRow {
2391
+ /** the worker's session file */
2392
+ path: string;
2393
+ /** the parent link as pi recorded it (`parentSession`); absent = not somebody's child */
2394
+ parent?: string | null;
2395
+ /** the picker display name — it carries the ⏳/✓/✗ and the outcome the driver stamps on it */
2396
+ name?: string;
2397
+ messageCount?: number;
2398
+ /** file mtime, however the host hands it over (pi gives a Date; tests give a number) */
2399
+ modified?: Date | number | string;
2400
+ }
2401
+
2402
+ /** How many workers one render lists before it folds the older ones. */
2403
+ export const WORKER_FAMILY_ITEMS = 12;
2404
+
2405
+ /** Family rendering options: `exclude` drops one transcript — the live or just-finished run, which
2406
+ * the caller already shows as its own section or its own line. */
2407
+ export interface WorkerFamilyOptions {
2408
+ exclude?: string;
2409
+ }
2410
+
2411
+ /** The heading over a family list — the one place the wording lives, so the status text and the card
2412
+ * cannot drift, and so a list that came from the ledger (no message counts, no renames) says so. */
2413
+ export function familyHeading(o: { live?: boolean; ledger?: boolean } = {}): string {
2414
+ return `${o.live ? "other workers this session spawned" : "workers this session spawned"}${o.ledger ? " (from the flow's ledger — this host has no session file to nest)" : ""}:`;
2415
+ }
2416
+
2417
+ /** The same session file written two ways is still one session (separators, trailing slash, and on
2418
+ * Windows the case of the drive letter). pi's own picker canonicalizes the same idea. */
2419
+ export function sessionPathKey(p: string): string {
2420
+ const k = path.resolve(p).replace(/[\\/]+$/, "");
2421
+ return process.platform === "win32" ? k.toLowerCase() : k;
2422
+ }
2423
+
2424
+ function sessionTime(row: WorkerSessionRow): number {
2425
+ const raw = row.modified instanceof Date ? row.modified.getTime() : typeof row.modified === "number" ? row.modified : row.modified ? Date.parse(row.modified) : 0;
2426
+ return Number.isFinite(raw) ? raw : 0;
2427
+ }
2428
+
2429
+ /**
2430
+ * The family — every stage worker this session spawned, newest first, one line each.
2431
+ *
2432
+ * A stage worker is a real pi session whose header carries `parentSession` pointing at the driver's
2433
+ * own file, so pi's picker nests it under the driver by itself (Threaded sort). This reads the same
2434
+ * fact back for every surface that has no tree: the `flow_stage` card and `op: "status"`. Nothing is
2435
+ * stored here, so a renamed worker (`✓ 🔍 · PASS · stamp attack`) reads back renamed, and workers a
2436
+ * previous session already delegated show up next to this one's.
2437
+ */
2438
+ export function workerFamily(rows: WorkerSessionRow[], driverFile: string | null | undefined, opts: WorkerFamilyOptions = {}): string[] {
2439
+ if (!driverFile) return [];
2440
+ const max = WORKER_FAMILY_ITEMS;
2441
+ const drop = opts.exclude ? sessionPathKey(opts.exclude) : null;
2442
+ const mine = rows
2443
+ .filter((r) => r.parent && sessionPathKey(r.parent) === sessionPathKey(driverFile) && (!drop || sessionPathKey(r.path) !== drop))
2444
+ .sort((a, b) => sessionTime(b) - sessionTime(a));
2445
+ const shown = mine.slice(0, max);
2446
+ const lines = shown.map((r) => {
2447
+ const at = sessionTime(r);
2448
+ return `${r.name?.trim() || "(unnamed worker)"} · ${r.messageCount ?? 0} msgs · ${at ? localStamp(at) : "time unknown"} · ${r.path}`;
2449
+ });
2450
+ if (mine.length > shown.length) lines.push(familyFoldLine(mine.length - shown.length));
2451
+ return lines;
2452
+ }
2453
+
2454
+ /** A transcript's header parent link, read from its first line alone — the cheap pass of the family
2455
+ * scan. Returns `undefined` for a file that is not a pi session (or has no complete first line in
2456
+ * the bytes read), `null` for a session that is nobody's child. */
2457
+ export function sessionHeaderParent(head: string): string | null | undefined {
2458
+ const nl = head.indexOf("\n");
2459
+ if (nl < 0) return undefined;
2460
+ try {
2461
+ const h = JSON.parse(head.slice(0, nl)) as { type?: string; parentSession?: unknown };
2462
+ if (h?.type !== "session") return undefined;
2463
+ return typeof h.parentSession === "string" && h.parentSession ? h.parentSession : null;
2464
+ } catch {
2465
+ return undefined;
2466
+ }
2467
+ }
2468
+
2469
+ /** The fields the family view needs, from one transcript's full text — the same rules pi's own
2470
+ * session listing applies (latest `session_info` name wins, explicit clears included; messages are
2471
+ * `message` entries; last activity is the newest user/assistant message, else the header time).
2472
+ * Only the few files whose header names the driver reach this — that is what keeps a family read
2473
+ * proportional to the family, not to the bucket's whole history. */
2474
+ export function parseSessionSummary(text: string, file: string, mtimeMs?: number): WorkerSessionRow | null {
2475
+ type Header = { timestamp?: unknown; parentSession?: unknown };
2476
+ let header: Header | null = null;
2477
+ let name: string | undefined;
2478
+ let messageCount = 0;
2479
+ let last: number | undefined;
2480
+ for (const line of text.split("\n")) {
2481
+ if (!line.trim()) continue;
2482
+ let e: { type?: string; name?: unknown; timestamp?: unknown; message?: { role?: string; content?: unknown; timestamp?: unknown } };
2483
+ try { e = JSON.parse(line); } catch { continue; }
2484
+ if (!header) {
2485
+ if (e?.type !== "session") return null;
2486
+ header = e as Header;
2487
+ continue;
2488
+ }
2489
+ if (e.type === "session_info") name = typeof e.name === "string" ? e.name.trim() || undefined : undefined;
2490
+ if (e.type !== "message") continue;
2491
+ messageCount++;
2492
+ const m = e.message;
2493
+ if (!m || m.content === undefined || (m.role !== "user" && m.role !== "assistant")) continue;
2494
+ const t = typeof m.timestamp === "number" ? m.timestamp : Date.parse(String(e.timestamp));
2495
+ if (Number.isFinite(t)) last = Math.max(last ?? 0, t);
2496
+ }
2497
+ if (!header) return null;
2498
+ const headerTime = typeof header.timestamp === "string" ? Date.parse(header.timestamp) : NaN;
2499
+ const modified = last && last > 0 ? last : Number.isFinite(headerTime) ? headerTime : mtimeMs;
2500
+ return { path: file, parent: typeof header.parentSession === "string" ? header.parentSession : null, name, messageCount, modified };
2501
+ }
2502
+
2503
+ /** pi's bucket name for a working directory (`--home-me-repo--`), the same encoding pi applies
2504
+ * (`getDefaultSessionDirPath`). Used only to RECOGNIZE buckets, never to choose where a session goes. */
2505
+ export function sessionBucketName(cwd: string): string {
2506
+ return `--${path.resolve(cwd).replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
2507
+ }
2508
+
2509
+ /** What the doctor needs to judge one feature's worktree bucket. */
2510
+ export interface WorktreeBucketFeature {
2511
+ /** the slug's state is gone, done or aborted — nothing will delegate into this worktree again */
2512
+ finished: boolean;
2513
+ worktreeExists: boolean;
2514
+ }
2515
+
2516
+ /**
2517
+ * Session buckets stage workers left behind before 0.70 put workers in the driver's bucket. Such a
2518
+ * worker ran with cwd = the feature worktree, so pi filed it under that worktree's own bucket — which
2519
+ * no folder scope opened from the main checkout ever shows, and which outlives the worktree. A bucket
2520
+ * is reported when it encodes `<root>/.dev-flow/<slug>/worktree` and that slug is finished or its
2521
+ * worktree is gone. `features` is keyed by slug; a slug absent from it has no state at all (finished).
2522
+ */
2523
+ export function orphanWorktreeBuckets(buckets: string[], root: string, features: Map<string, WorktreeBucketFeature>): { bucket: string; slug: string }[] {
2524
+ const prefix = sessionBucketName(path.join(root, ".dev-flow")).slice(0, -2) + "-";
2525
+ const out: { bucket: string; slug: string }[] = [];
2526
+ for (const b of buckets) {
2527
+ if (!b.startsWith(prefix) || !b.endsWith("-worktree--")) continue;
2528
+ const encSlug = b.slice(prefix.length, -"-worktree--".length);
2529
+ if (!encSlug) continue;
2530
+ // slugs are kebab-case, which the encoding leaves intact; a slug that is a known feature wins
2531
+ const f = features.get(encSlug);
2532
+ if (f && !f.finished && f.worktreeExists) continue;
2533
+ out.push({ bucket: b, slug: encSlug });
2534
+ }
2337
2535
  return out;
2338
2536
  }
2339
2537
 
2538
+ /** Stage workers spawned in THIS process, by session id. A worker loads the operator's extensions —
2539
+ * dev-flow among them, because its guards must hold inside the worker too — but the driver's context
2540
+ * (the playbook core, the unbound-session posture, "surface this to the operator") is wrong there:
2541
+ * the brief is the worker's whole instruction. The worker's loader imports dev-flow as its own
2542
+ * module instance, so the registry lives on a process-global symbol both instances can see. */
2543
+ const WORKER_SESSIONS = Symbol.for("dev-flow.workerSessions");
2544
+ function workerSessionSet(): Set<string> {
2545
+ const g = globalThis as unknown as Record<symbol, Set<string> | undefined>;
2546
+ return (g[WORKER_SESSIONS] ??= new Set<string>());
2547
+ }
2548
+ export function markWorkerSession(id: string | undefined | null): void {
2549
+ if (id) workerSessionSet().add(id);
2550
+ }
2551
+ export function isWorkerSession(id: string | undefined | null): boolean {
2552
+ return !!id && workerSessionSet().has(id);
2553
+ }
2554
+
2555
+ /** The line that stands in for the workers too old to list. It is not a worker, so anything counting
2556
+ * the list has to know it — and both sources fold the same way, so the shape lives here. */
2557
+ export function familyFoldLine(dropped: number): string {
2558
+ return `… ${dropped} earlier workers`;
2559
+ }
2560
+
2561
+ export function isFamilyFoldLine(line: string): boolean {
2562
+ return line.startsWith("… ");
2563
+ }
2564
+
2565
+ /** How many workers a rendered family list stands for: the fold line is a count, not a worker. */
2566
+ export function workerFamilyCount(lines: string[] | null | undefined): number | null {
2567
+ if (!lines) return null;
2568
+ return lines.filter((l) => !isFamilyFoldLine(l)).length;
2569
+ }
2570
+
2571
+ /** Local wall-clock `YYYY-MM-DD HH:mm` — the convention every dev-flow timestamp follows (a UTC
2572
+ * stamp next to the operator's own clock reads as a future or past session, and the family line is
2573
+ * meant to be scanned, not converted). */
2574
+ function localStamp(ms: number): string {
2575
+ const d = new Date(ms);
2576
+ const p = (n: number) => String(n).padStart(2, "0");
2577
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
2578
+ }
2579
+
2340
2580
  /** What the tool accumulated from a worker's assistant usage records. */
2341
2581
  export interface StageUsage {
2342
2582
  input: number;