pi-dev-flow 0.70.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,15 @@ 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
+
7
16
  ## [0.70.0] - 2026-10-31
8
17
 
9
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.
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
@@ -108,10 +115,14 @@ Around it, three mirrors:
108
115
  either layout. On a host with no file-backed session the stamp
109
116
  is skipped and the worker keeps pi's default location, unlinked. Named by role
110
117
  glyph, ordinal and purpose — `⏳ 🔨 #2 · wire ops` while it runs, renamed
111
- at the end with its outcome: `✓ 🔨 #2 · 3 commits · wire ops`, a verify `✓ 🔍 ·
112
- PASS · stamp attack`, a cut-off worker `✗ 🔨 #3 · hard-cut`; the verdict never
113
- depends on opening the row (a `label` on the call supplies the purpose; with
114
- none, a `run` is still separated by its ordinal). It appears in the `/resume`
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`
115
126
  picker, and its
116
127
  transcript grows live on disk, readable at any moment — whether a viewer
117
128
  tails a session still running is the viewer's choice, the card above is what
@@ -137,7 +148,7 @@ session has never spawned one:
137
148
 
138
149
  ```
139
150
  workers this session spawned:
140
- ✓ 🔍 · PASS · stamp attack · 7 msgs · 2026-10-30 12:04 · ~/.pi/agent/sessions/…/w2.jsonl
151
+ ✓ 🔍 #2 · PASS · stamp attack · 7 msgs · 2026-10-30 12:04 · ~/.pi/agent/sessions/…/w2.jsonl
141
152
  ✗ 🔨 #1 · hard-cut · 31 msgs · 2026-10-30 11:02 · ~/.pi/agent/sessions/…/w1.jsonl
142
153
  ```
143
154
 
@@ -145,9 +156,11 @@ It is read back from pi's session listing, not from a dev-flow index, so renames
145
156
  deletions and workers an earlier session already delegated all read correctly for
146
157
  free. A host that gives dev-flow no session file to be a parent of falls back to
147
158
  the lines the flow's own `transcripts.log` already holds — coarser (no message
148
- count, no rename), still the same answer. Reading a bucket costs about 15 ms per
149
- MB of its history, so the polled live view re-reads at most once every two seconds
150
- while the settled card and an idle status always read fresh.
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.
151
164
 
152
165
  Lifecycle is also on the bus: `dev-flow:worker-started` / `-completed` /
153
166
  `-failed` events (slug, op, elapsed, usage) let other extensions react without
@@ -178,7 +191,11 @@ knowing: a worker's header `cwd` is still the worktree, so after `flow finish`
178
191
  removes that worktree the row points at a directory that is gone (browsing and
179
192
  `pi export` still work — resuming it would not); and the bucket is shared with the
180
193
  driver's own history, so worker transcripts are only ever deleted by path, never
181
- by clearing a folder. Snapshots and the `transcripts.log` index live under
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
182
199
  `.dev-flow/<slug>/stage-sessions/` (gitignored, like all flow-owned state).
183
200
 
184
201
  ## Deliberate limits (v2)
@@ -22,6 +22,7 @@
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";
@@ -143,6 +144,14 @@ import {
143
144
  renderVerifyReport,
144
145
  verifyStampMissing,
145
146
  sessionPathKey,
147
+ sessionHeaderParent,
148
+ parseSessionSummary,
149
+ markWorkerSession,
150
+ isWorkerSession,
151
+ orphanWorktreeBuckets,
152
+ claimAge,
153
+ processStart,
154
+ type WorktreeBucketFeature,
146
155
  workerFamily,
147
156
  workerFamilyCount,
148
157
  WORKER_FAMILY_ITEMS,
@@ -241,7 +250,13 @@ function copyWarning(): string | null {
241
250
  }
242
251
  /** Test seam: the smoke suite cannot load a second copy of this module, so it plants registry
243
252
  * entries and asserts the warnings the real duplicate would print. */
244
- 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
+ };
245
260
 
246
261
  interface Ui {
247
262
  hasUI: boolean;
@@ -393,7 +408,8 @@ function writeState(root: string, state: FlowState): void {
393
408
  * truncated state.json — which reads as "no such feature", silently orphaning the worktree, the plan
394
409
  * and every recorded check, with the folder gitignored so nothing else could restore it. */
395
410
  function atomicWrite(file: string, text: string): void {
396
- 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`;
397
413
  writeFileSync(tmp, text);
398
414
  renameSync(tmp, file);
399
415
  }
@@ -447,9 +463,13 @@ export const compactionTakeover: { run: typeof compact } = { run: compact };
447
463
  * carries `parentSession` → the driver's own session file, and its transcript goes into the
448
464
  * driver's session bucket, so pi's picker nests it under the driver in its default Current Folder
449
465
  * scope (the Threaded sort reads that link — pi #1108 wrote it for exactly this, "extensions such
450
- * as /handoff can do the same"). Naming runs through an inline extension — `setSessionName` only
451
- * exists on a session's own extension API — handing back a rename channel the driver uses for the
452
- * ⏳ → ✓/✗ lifecycle. */
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`). */
453
473
 
454
474
  export interface StageWorkerHandle { session: AgentSession; rename: (name: string) => void }
455
475
 
@@ -464,26 +484,17 @@ export function workerSessionManager(work: string, parent?: string, dir?: string
464
484
 
465
485
  export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name: string; tools: string[]; parent?: string; dir?: string }) => Promise<StageWorkerHandle> } = {
466
486
  run: async ({ work, model, name, tools, parent, dir }) => {
467
- let rename: (name: string) => void = () => {};
468
- const loader = new DefaultResourceLoader({
469
- cwd: work,
470
- agentDir: getAgentDir(),
471
- extensionFactories: [{
472
- name: "dev-flow-stage-naming",
473
- hidden: true,
474
- factory: (childPi: ExtensionAPI) => {
475
- childPi.on("session_start", () => { try { childPi.setSessionName(name); } catch { /* naming is visibility, not function */ } });
476
- rename = (n: string) => { try { childPi.setSessionName(n); } catch { /* ditto */ } };
477
- },
478
- }],
479
- });
487
+ const loader = new DefaultResourceLoader({ cwd: work, agentDir: getAgentDir() });
480
488
  await loader.reload();
481
489
  const sessionManager = workerSessionManager(work, parent, dir);
482
490
  const { session } = await createAgentSession({ cwd: work, model: model as never, tools, excludeTools: ["flow", "flow_stage"], resourceLoader: loader, sessionManager });
483
491
  // the op's toolset decides what the worker can touch at all: an implement worker gets the coding
484
492
  // tools, a reviewer gets read + bash only (a checker with an edit tool is a second implementer).
485
493
  // excludeTools is the belt on the extension tools — a worker never holds a gate or a second flow_stage.
486
- 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 };
487
498
  },
488
499
  };
489
500
 
@@ -495,10 +506,51 @@ export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name:
495
506
  * creates. `listAll(dir)` is what the picker's Current Folder scope sees in the default layout, so
496
507
  * the family list and the tree agree there; under a configured session dir the text view stays
497
508
  * complete even where that scope hides the worker, which is the cheaper direction to err in. */
498
- export const sessionRowsScan: { run: (o: { cwd: string; dir?: string }) => Promise<WorkerSessionRow[]> } = {
499
- run: async ({ dir }) => (await SessionManager.listAll(dir)).map((s) => ({ path: s.path, parent: s.parentSessionPath, name: s.name, messageCount: s.messageCount, modified: s.modified })),
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
+ },
500
515
  };
501
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
+
502
554
  /** Where this session's own transcripts live, when it has any: the file the worker links to, and the
503
555
  * bucket it lands in. `null` on a host with no file-backed session — lineage is then unavailable,
504
556
  * which is a fact to print, never an error to raise. */
@@ -520,16 +572,15 @@ function ledgerFamilyLines(logPath: string, exclude?: string): string[] {
520
572
  } catch { return []; }
521
573
  }
522
574
 
523
- /** Bucket reads are the one expensive thing the family view does: pi parses every transcript in the
524
- * driver's bucket in full — measured here at ~15 ms per MB of bucket history (25 sessions / 10.4 MB
525
- * ≈ 150–200 ms, 48 MB ≈ 1.3 s). A host renders a running worker by calling status repeatedly, so
526
- * that path is allowed a slightly stale read; the places the operator draws a conclusion from — idle
527
- * status, the settled card — always re-read. */
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. */
528
579
  const BUCKET_FRESH_MS = 2000;
529
580
  const bucketCache = new Map<string, { at: number; rows: Awaited<ReturnType<typeof sessionRowsScan.run>> }>();
530
581
 
531
- async function bucketRows(ctx: ExtensionContext, dir: string | null, staleMs = 0) {
532
- const key = dir ?? "(default bucket)";
582
+ async function bucketRows(ctx: ExtensionContext, dir: string | null, parent: string, staleMs = 0) {
583
+ const key = `${dir ?? "(default bucket)"}\0${parent}`;
533
584
  const hit = bucketCache.get(key);
534
585
  // staleMs = 0 is not "a zero-length window", it is "no window: read now" — which is what idle status
535
586
  // and the settled card ask for, because that is where the operator draws a conclusion. With `<=` the
@@ -537,7 +588,7 @@ async function bucketRows(ctx: ExtensionContext, dir: string | null, staleMs = 0
537
588
  // as a fresh one (this made CI red: a status call answering "what is there now" in the same millisecond
538
589
  // as the call before it printed the family that had just gone empty).
539
590
  if (staleMs > 0 && hit && Date.now() - hit.at <= staleMs) return hit.rows;
540
- const rows = await sessionRowsScan.run({ cwd: ctx.cwd, dir: dir ?? undefined });
591
+ const rows = await sessionRowsScan.run({ cwd: ctx.cwd, dir: dir ?? undefined, parent });
541
592
  if (bucketCache.size > 8) bucketCache.clear(); // a session drives one bucket; anything bigger is stale keys
542
593
  bucketCache.set(key, { at: Date.now(), rows });
543
594
  return rows;
@@ -553,7 +604,7 @@ async function workerFamilyLines(ctx: ExtensionContext, exclude?: string, staleM
553
604
  const { file, dir } = lineageOf(ctx);
554
605
  if (!file) return null;
555
606
  try {
556
- return workerFamily(await bucketRows(ctx, dir, staleMs), file, { exclude });
607
+ return workerFamily(await bucketRows(ctx, dir, file, staleMs), file, { exclude });
557
608
  } catch { /* visibility again: a bucket we cannot read is not a reason to lose the run's own report */ return null; }
558
609
  }
559
610
 
@@ -636,7 +687,13 @@ function readClaim(root: string, slug: string): SessionClaim | null {
636
687
  }
637
688
 
638
689
  const writeClaim = (root: string, slug: string, key: string) =>
639
- 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
+ };
640
697
 
641
698
  /** Let go of everything one session held. In a shared-process host the pid on a claim is the server's and
642
699
  * never dies, so a claim left behind by a finished session keeps refusing every later session with
@@ -2035,6 +2092,7 @@ async function gateDoctor(o: GateCtx): Promise<RunResult> {
2035
2092
  const loaded = loadProject(df);
2036
2093
  const findings = doctorFindings(root, loaded.cfg, loaded.md);
2037
2094
  findings.push(...(await gitConsistency(root, loaded.cfg)));
2095
+ findings.push(...orphanBucketFindings(root));
2038
2096
  const refl = readReflections(root);
2039
2097
  const fold = await foldView(root, refl, isSelfRepo(root));
2040
2098
  if (refl.length) {
@@ -2056,6 +2114,35 @@ async function gateDoctor(o: GateCtx): Promise<RunResult> {
2056
2114
  return { text: investigationBrief(rest.filter((a) => !a.startsWith("--")).join(" "), isSelfRepo(root)).join("\n") };
2057
2115
  }
2058
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
+
2059
2146
  /** What a gate handler needs from the runFlow preamble. Bodies moved verbatim destructure
2060
2147
  * their own names back, so the bodies needed zero edits. */
2061
2148
  interface GateCtx {
@@ -2136,7 +2223,7 @@ async function gateUse(o: GateCtx): Promise<RunResult> {
2136
2223
  const st = readState(root, slugArg);
2137
2224
  if (!st || st.stage === "done") return { text: `no unfinished feature ${slugArg}`, isError: true };
2138
2225
  const prior = readClaim(root, slugArg);
2139
- 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!)})` : "";
2140
2227
  sess.bind(slugArg);
2141
2228
  sess.rename(slugArg);
2142
2229
  // a checkpoint that was still unanswered belongs to whoever asked; a session taking the feature over
@@ -2157,7 +2244,7 @@ async function gateAbort(o: GateCtx): Promise<RunResult> {
2157
2244
  // a live claim locks the whole feature, not only its gates: aborting it out from under the session
2158
2245
  // that works it erases the plan that session is still writing (same rule needState applies)
2159
2246
  const claim = readClaim(root, target);
2160
- 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 };
2161
2248
  if (sess.slug === target) sess.bind(null);
2162
2249
  if (st && !st.worktree) {
2163
2250
  // plan-stage abort = drop: no worktree/branch exists, so the state dir would linger
@@ -2170,6 +2257,14 @@ async function gateAbort(o: GateCtx): Promise<RunResult> {
2170
2257
  }
2171
2258
 
2172
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
+
2173
2268
  async function currentBranch(root: string): Promise<string> {
2174
2269
  const r = await sh("git branch --show-current", root);
2175
2270
  return r.ok ? r.out.split("\n")[0] : "";
@@ -2190,7 +2285,7 @@ function needState(root: string, sess: Session, slugArg?: string): { state: Flow
2190
2285
  // sessions overwrite one state file (last write wins) while both believe they own the stage.
2191
2286
  const claim = readClaim(root, slug);
2192
2287
  if (sess.slug !== slug && claimBlocks(claim, sess.key))
2193
- 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 } };
2194
2289
  return { state };
2195
2290
  }
2196
2291
 
@@ -2374,7 +2469,7 @@ export default function devFlow(pi: ExtensionAPI) {
2374
2469
  name: "flow_stage",
2375
2470
  label: "Stage worker",
2376
2471
  description:
2377
- '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.',
2378
2473
  promptSnippet:
2379
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',
2380
2475
  parameters: Type.Object({
@@ -2491,9 +2586,9 @@ export default function devFlow(pi: ExtensionAPI) {
2491
2586
  writeFileSync(logFile, `${stageLiveLine(0, "worker", `${op} started (${st.stage}, budget ${budgetMin} min)`)}\n`);
2492
2587
  const beat = (toolName: string) => { if (ctx.hasUI) ctx.ui.setStatus("dev-flow-stage", `⏳ ${kindCard} · ${st.slug} ${stageElapsedLabel(Date.now() - run.startedAt)} · ${toolName}`); };
2493
2588
  // ordinal among this feature's same-op workers, read from the durable index — re-delegations
2494
- // read #2, #3 in the list instead of identical rows (only run gets a seq; a verify is known
2495
- // by its verdict, a reflect is one per flow)
2496
- 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;
2497
2592
  const statusJsonText = (await runFlow(["status", "--json"], ctx.cwd, uiFrom(ctx), sessFor(ctx))).text;
2498
2593
  const git = await sh("git status --porcelain -b", work);
2499
2594
  const note = typeof params.note === "string" ? params.note : undefined;
@@ -2616,7 +2711,7 @@ export default function devFlow(pi: ExtensionAPI) {
2616
2711
  // rev-parse misses `checkout -b` at the same SHA, symbolic-ref misses a detached move,
2617
2712
  // and all three miss the plan the verdict was written against living outside the worktree
2618
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);
2619
- // 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
2620
2715
  // `✓ 🔨 #2 · 3 commits · wire ops` answers "how did it end?" without opening the session
2621
2716
  let outcome: string | null = null;
2622
2717
  if (clean) {
@@ -2947,6 +3042,10 @@ export default function devFlow(pi: ExtensionAPI) {
2947
3042
  // client attaches, and this is the earliest point the client is certainly listening
2948
3043
  refreshStatus(ctx);
2949
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;
2950
3049
  const key = sessionKey(ctx);
2951
3050
  // The playbook core rides along on the message this run writes anyway — once per session.
2952
3051
  const core = corePreamble(key);
@@ -2956,8 +3055,10 @@ export default function devFlow(pi: ExtensionAPI) {
2956
3055
  // Default posture for an unbound session in a dev-flow repo (guards make it stick; this makes it understood).
2957
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>.";
2958
3057
  const cb = claimBlocker(ctx.cwd, key);
2959
- 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.`;
2960
- 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);
2961
3062
  if (curBr && curBr !== cfg.defaultBranch) content += ` Also: main checkout is on ${curBr}, not ${cfg.defaultBranch} — surface this to the operator before starting work.`;
2962
3063
  const refl0 = readReflections(ctx.cwd);
2963
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.70.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). */
@@ -2412,6 +2451,107 @@ export function workerFamily(rows: WorkerSessionRow[], driverFile: string | null
2412
2451
  return lines;
2413
2452
  }
2414
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
+ }
2535
+ return out;
2536
+ }
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
+
2415
2555
  /** The line that stands in for the workers too old to list. It is not a worker, so anything counting
2416
2556
  * the list has to know it — and both sources fold the same way, so the shape lives here. */
2417
2557
  export function familyFoldLine(dropped: number): string {