pi-dev-flow 0.72.0 → 0.74.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/src/core.ts CHANGED
@@ -4,17 +4,17 @@
4
4
  * Pure(ish) logic only — no pi imports here so it is unit-testable with
5
5
  * `node --test`. The extension in extensions/dev-flow.ts is thin wiring.
6
6
  */
7
- import { existsSync, readdirSync, readFileSync, readlinkSync, realpathSync } from "node:fs";
7
+ import { existsSync, readdirSync, readFileSync, realpathSync } from "node:fs";
8
8
  import { createHash } from "node:crypto";
9
9
  import os from "node:os";
10
10
  import path from "node:path";
11
11
 
12
- export type Stage = "plan" | "implement" | "pre-release" | "release" | "done";
12
+ /** A feature's stage. There is no "done": flow finish deletes the feature's state outright. */
13
+ export type Stage = "plan" | "implement" | "pre-release" | "release";
13
14
 
14
15
  export interface Check {
15
16
  ok: boolean;
16
17
  at: string;
17
- note?: string;
18
18
  /** The worktree state this check actually ran against (see checkFingerprint). A record whose
19
19
  * fingerprint differs from the current tree at gate time was measured against code that no
20
20
  * longer exists — green is not enough when the tree moved under it. Absent = recorded by an
@@ -101,10 +101,10 @@ export interface Config {
101
101
  versioning: Versioning;
102
102
  /** Seconds the post-deploy health probe may keep retrying before the gate gives up (0 = single shot). */
103
103
  healthWait: number;
104
- release: { review: string; changelog?: string; tagPattern?: string; releases?: boolean; artifact?: string; merge?: MergeStyle | "any" };
104
+ release: { review: string; changelog?: string; releases?: boolean; artifact?: string; preflight?: string; merge?: MergeStyle | "any" };
105
105
  mainHook: boolean; // flow init installs a pre-commit hook blocking main commits
106
- /** `require` (default): a shell call must carry its own visible timeout — the injected class
107
- * default is armed silently and never shows in the transcript. `inject`: arm it silently. */
106
+ /** `inject` (default): the class default timeout is armed silently on every shell call.
107
+ * `require`: a shell call without its own visible timeout is refused (costs a turn per miss). */
108
108
  bashTimeout: "require" | "inject";
109
109
  /** Operator safety rules from the project.md flow-guard block — stage-independent. */
110
110
  guard: GuardRules;
@@ -124,7 +124,7 @@ export const DEFAULTS: Config = {
124
124
  healthWait: 30,
125
125
  release: { review: "/flow-review", changelog: "CHANGELOG.md", releases: true },
126
126
  mainHook: true,
127
- bashTimeout: "require",
127
+ bashTimeout: "inject",
128
128
  guard: { deny: [], confirm: [], protect: [], forbid: [] },
129
129
  };
130
130
 
@@ -168,17 +168,11 @@ export function extractSkillCore(md: string): string | null {
168
168
  return core || null;
169
169
  }
170
170
 
171
- /** The playbook file carrying one stage's detail, relative to the skill directory. `done` has
172
- * none (nothing left to read). The state machine has no finish stage — closing out happens inside
173
- * `release`, and release.md hands over to finish.md there. The pre-flow brief is `start`. */
174
- const STAGE_REFERENCE: Partial<Record<Stage, string>> = {
175
- plan: "references/plan.md",
176
- implement: "references/implement.md",
177
- "pre-release": "references/pre-release.md",
178
- release: "references/release.md",
179
- };
180
- export function stageReference(stage: Stage): string | null {
181
- return STAGE_REFERENCE[stage] ?? null;
171
+ /** The playbook file carrying one stage's detail, relative to the skill directory. The state machine
172
+ * has no finish stage — closing out happens inside `release`, and release.md hands over to finish.md
173
+ * there. The pre-flow brief is `start`. */
174
+ export function stageReference(stage: Stage): string {
175
+ return `references/${stage}.md`;
182
176
  }
183
177
 
184
178
  /** The project's own "running and healthy" probe — `commands.health` or a flow-check block named
@@ -480,9 +474,6 @@ export function freshenChecks(state: FlowState, fp: string | null, keep: (name:
480
474
  if (!fp) return [];
481
475
  const stale: string[] = [];
482
476
  for (const [name, rec] of Object.entries(state.checks)) {
483
- // the verify stamp answers to a WIDER fingerprint (worktree + plan/), so plain worktree
484
- // comparison must never speak for it — the verify gate voids it against that fingerprint.
485
- if (name === VERIFY_STAMP) continue;
486
477
  if (rec.wt && rec.wt !== fp && !keep(name)) {
487
478
  delete state.checks[name];
488
479
  stale.push(name);
@@ -571,9 +562,8 @@ export function githubSlug(ref: string): string {
571
562
  return m ? m[1].replace(/\.git$/, "") : "";
572
563
  }
573
564
 
574
- /** Gate: the tag derived from the manifest version must exist among local tags. */
575
- export function versionTagGate(manifestVersion: string | null, tagPattern: string, tags: string[]): string[] {
576
- if (!manifestVersion) return ["versioning.file is set but its version could not be parsed — fix versioning config"];
565
+ /** Gate: the tag derived from the manifest version must exist among the given tags. */
566
+ export function versionTagGate(manifestVersion: string, tagPattern: string, tags: string[]): string[] {
577
567
  const expected = tagPattern.replace("{version}", manifestVersion);
578
568
  if (tags.includes(expected)) return [];
579
569
  return [`expected release tag "${expected}" (from manifest version ${manifestVersion}) not found; recent tags: ${tags.slice(0, 5).join(", ") || "none"}`];
@@ -658,16 +648,6 @@ export function changelogEntry(content: string, version: string): string {
658
648
  return out.join("\n").trim();
659
649
  }
660
650
 
661
- /**
662
- * Cleanup safety for `flow finish`. Returns { errors, unmerged }: errors hard-block;
663
- * unmerged is a warning list the operator can confirm through (e.g. squash merges).
664
- */
665
- export function cleanupAssess(porcelain: string, unmerged: string[]): { errors: string[]; unmerged: string[] } {
666
- const errors: string[] = [];
667
- if (porcelain.trim()) errors.push("worktree has uncommitted changes — commit or discard them first");
668
- return { errors, unmerged: unmerged.filter(Boolean) };
669
- }
670
-
671
651
  /* -------------------------------------------------------------- merge policy */
672
652
 
673
653
  /** Past tense of a style, for the wording of a refusal. */
@@ -885,14 +865,11 @@ export function parsePushRefs(pushes: string[][]): PushRef[] {
885
865
  return out;
886
866
  }
887
867
 
888
- /** Flow control files by full path — state.json, claim.json and the delegation ledger — or a bare
889
- * name when the command also touches `.dev-flow` (that is how `cd .dev-flow/<slug> && mv state.json …`
890
- * reaches it). The claim is the live-session lock: deleting it is as much theft as forging a stage.
891
- * `delegations.log` joins the two because the verify gate reads it as proof of WHO worked the stage:
892
- * refusing it to the edit/write tools only while `echo >>` still reaches it would guard the honest
893
- * session and none other (writeGuard is the same rule for the other half of the tool surface). */
894
- const STATE_PATH = /(^|[\s'"\/])(?:(?:state|claim)\.json|delegations\.log)$/;
895
- const STATE_PATH_ABS = /\.dev-flow\/[\w./-]*(?:(?:state|claim)\.json|delegations\.log)$/;
868
+ /** Flow control files by full path — state.json and claim.json — or a bare name when the command
869
+ * also touches `.dev-flow` (that is how `cd .dev-flow/<slug> && mv state.json …` reaches it).
870
+ * The claim is the live-session lock: deleting it is as much theft as forging a stage. */
871
+ const STATE_PATH = /(^|[\s'"\/])(?:state|claim)\.json$/;
872
+ const STATE_PATH_ABS = /\.dev-flow\/[\w./-]*(?:state|claim)\.json$/;
896
873
  const PLAYBOOK_PATH = /\.dev-flow\/[\w./-]*project\.md/;
897
874
  const DF_ANYWHERE = /\.dev-flow\b/;
898
875
  /** The `.dev-flow/` folder itself or one feature directory under it — deleting either destroys the flow
@@ -1040,9 +1017,58 @@ export function bashFlowGuard(o: GuardCtx): string | null {
1040
1017
  if (writesDefault && o.stage !== "release") return `pushing to ${o.defaultBranch} requires stage "release" (verified feature)${attr}`;
1041
1018
  }
1042
1019
  if (git("merge") && onMain && o.stage !== "release") return `merging into ${o.defaultBranch} requires stage "release"${attr}`;
1020
+ // Shipping belongs to the release stage: a tag cut (or pushed) while the feature is still before release
1021
+ // leaves the gates unable to record it — flow release then refuses "already tagged" and the flow cannot close.
1022
+ if (o.stage && BEFORE_RELEASE.has(o.stage)) {
1023
+ if (git("tag") && tagCreates(c)) return `tagging is release work — the feature is at ${o.stage}; run flow release first (it gates the version, then tags)${judgedIn}`;
1024
+ if (git("push")) {
1025
+ const refs = o.pushRefs ?? parsePushRefs(gitInvocation(c).pushes);
1026
+ if (/\s--(?:tags|follow-tags)\b/.test(c) || /refs\/tags\//.test(c) || refs.some((r) => r.kind === "tag")) return `pushing tags is release work — the feature is at ${o.stage}; run flow release first${judgedIn}`;
1027
+ }
1028
+ }
1043
1029
  return null;
1044
1030
  }
1045
1031
 
1032
+ const BEFORE_RELEASE = new Set<Stage>(["plan", "implement", "pre-release"]);
1033
+
1034
+ /** Does this `git tag` invocation create (or move) a tag? Bare `git tag` and the listing/verify forms only read. */
1035
+ export function tagCreates(command: string): boolean {
1036
+ const m = command.match(/\bgit\s+(?:-C\s+\S+\s+)?tag\b([^;|&\n]*)/);
1037
+ if (!m) return false;
1038
+ const tok = m[1].trim().split(/\s+/).filter(Boolean);
1039
+ if (!tok.length) return false;
1040
+ if (tok.some((t) => /^(-l|--list|-n\d*|--contains|--no-contains|--points-at|--merged|--no-merged|-v|--verify|-d|--delete)$/.test(t))) return false;
1041
+ return true;
1042
+ }
1043
+
1044
+ /** Forge-side shipping (`gh pr merge`, `glab mr merge`, `gh|glab release create`) before the release stage, or null.
1045
+ * Quoted text is prose except inside a head that execs its argument — the same reading as mergeStyleInvocation. */
1046
+ export function releaseOrderInvocation(command: string, stage: Stage | null): string | null {
1047
+ if (!stage || !BEFORE_RELEASE.has(stage)) return null;
1048
+ for (const seg of bashSegments(command)) {
1049
+ if (READ_ONLY_HEADS.has(segHead(seg))) continue;
1050
+ const hay = REEXEC_HEADS.has(segHead(seg)) ? `${seg} ${maskQuoted(seg)}` : maskQuoted(seg);
1051
+ if (/\bgh\s+pr\s+merge\b/.test(hay) || /\bglab\s+mr\s+merge\b/.test(hay))
1052
+ return `merging the PR is release work — the feature is at ${stage}; ask the operator Release? and run flow release first (yolo pre-answers the question, it does not skip the gate)`;
1053
+ if (/\b(?:gh|glab)\s+release\s+create\b/.test(hay))
1054
+ return `publishing a forge release is release work — the feature is at ${stage}; run flow release, then flow release-done creates it`;
1055
+ }
1056
+ return null;
1057
+ }
1058
+
1059
+ /** The branch a `git checkout` / `git switch` targets, and whether it creates it (`-b/-B/-c/-C/--create/
1060
+ * --force-create/--orphan`), or null. Leading flags are skipped; `--` ends the branch part (paths follow). */
1061
+ export function checkoutInvocation(command: string): { target: string; creates: boolean } | null {
1062
+ const m = command.match(/\bgit\s+(?:-C\s+\S+\s+)?(?:checkout|switch)\b([^;|&\n]*)/);
1063
+ if (!m) return null;
1064
+ const all = m[1].trim().split(/\s+/).filter(Boolean);
1065
+ const tok = all.includes("--") ? all.slice(0, all.indexOf("--")) : all;
1066
+ const i = tok.findIndex((t) => /^(-[bBcC]|--create|--force-create|--orphan)$/.test(t));
1067
+ if (i >= 0) return tok[i + 1] ? { target: unquote(tok[i + 1]), creates: true } : null;
1068
+ const target = tok.find((t) => !t.startsWith("-"));
1069
+ return target ? { target: unquote(target), creates: false } : null;
1070
+ }
1071
+
1046
1072
  // ------------------------------------------------------- project safety rules
1047
1073
 
1048
1074
  /** One flow-guard rule: `pattern` is a JS regex source (deny/confirm) or a repo-relative path (protect/forbid). */
@@ -1198,7 +1224,7 @@ function compile(source: string): RegExp | null {
1198
1224
  try {
1199
1225
  regexCache.set(source, new RegExp(source));
1200
1226
  } catch {
1201
- regexCache.set(source, null); // unreachable through project.md (parse validates); project.json is not
1227
+ regexCache.set(source, null); // unreachable through project.md (parse validates) — kept so a bad rule never throws in a hook
1202
1228
  }
1203
1229
  }
1204
1230
  return regexCache.get(source)!;
@@ -1289,32 +1315,23 @@ const within = (abs: string, dir: string | null) => !!dir && (abs === dir || abs
1289
1315
  * the guarded checkout, and `repoRoot` keeps a repository that merely lives under the temp dir (every
1290
1316
  * smoke-test repo) under the normal stage rules.
1291
1317
  */
1292
- export function inScratchDir(abs: string, repoRoot?: string | null): boolean {
1293
- const real = realAbs(abs);
1294
- if (repoRoot) {
1295
- const root = realAbs(path.resolve(repoRoot));
1296
- if (real === root || real.startsWith(root + path.sep)) return false;
1297
- }
1298
- const tmp = realAbs(path.resolve(os.tmpdir()));
1299
- return real === tmp || real.startsWith(tmp + path.sep);
1300
- }
1301
-
1302
1318
  /** The main checkout a linked worktree shares its history with, from git's answer for the common dir
1303
1319
  * (`<main>/.git`), or null when there is nothing to remap: git did not answer, or cwd already is that
1304
- * checkout (a plain clone answers its own dir). Pure — the caller decides whether to trust the root it
1305
- * gets (dev-flow's `flowRoot` keeps cwd unless the main checkout is dev-flow-initiated). */
1320
+ * checkout (a plain clone answers its own dir). */
1306
1321
  export function mainCheckoutRoot(cwd: string, commonDir: string | null): string | null {
1307
1322
  if (!commonDir) return null;
1308
1323
  const main = path.resolve(path.dirname(path.resolve(cwd, commonDir)));
1309
1324
  return main === path.resolve(cwd) ? null : main;
1310
1325
  }
1311
1326
 
1312
- /** True when the path is a feature's delegation ledger (.dev-flow/<slug>/stage-sessions/delegations.log)
1313
- * — the file the verify gate reads to prove a worker ran. Matched by shape, not just filename, so a
1314
- * source file that merely happens to be named delegations.log stays writable anywhere, including inside
1315
- * a worktree that lives under .dev-flow/. */
1316
- export function isDelegationLedger(abs: string, dfDir: string): boolean {
1317
- return path.basename(abs) === DELEGATIONS_FILE && path.basename(path.dirname(abs)) === STAGE_SESSIONS_DIR && abs.includes(dfDir + path.sep);
1327
+ export function inScratchDir(abs: string, repoRoot?: string | null): boolean {
1328
+ const real = realAbs(abs);
1329
+ if (repoRoot) {
1330
+ const root = realAbs(path.resolve(repoRoot));
1331
+ if (real === root || real.startsWith(root + path.sep)) return false;
1332
+ }
1333
+ const tmp = realAbs(path.resolve(os.tmpdir()));
1334
+ return real === tmp || real.startsWith(tmp + path.sep);
1318
1335
  }
1319
1336
 
1320
1337
  /**
@@ -1323,44 +1340,25 @@ export function isDelegationLedger(abs: string, dfDir: string): boolean {
1323
1340
  * (release+ may touch it; plan/implement may not); with no binding and unfinished features
1324
1341
  * the session must bind first (`flow use`). Flow-by-default: a session with no flow may not
1325
1342
  * touch the checkout at all — a bound feature is the only way in.
1326
- * `byWorker` says the writing session is a flow_stage worker: a normal feature's worktree stays
1327
- * closed to its driver at implement (implement work is delegated — see delegationErrors), open to
1328
- * the worker that was sent to do it.
1329
1343
  * Returns a reason or null (allowed).
1330
1344
  */
1331
- export function writeGuard(o: { abs: string; dfDir: string; features: FeatureRef[]; boundSlug: string | null; repoRoot?: string | null; byWorker?: boolean }): string | null {
1345
+ export function writeGuard(o: { abs: string; dfDir: string; features: FeatureRef[]; boundSlug: string | null; repoRoot?: string | null }): string | null {
1332
1346
  // Judge where the bytes land, not where the path pretends: a symlink inside the worktree pointing
1333
1347
  // out of it is the same write as the target path (realAbs walks the deepest existing ancestor, so
1334
1348
  // a brand-new file under a real directory resolves right, and a never-existing one is stable).
1335
1349
  const abs = realAbs(o.abs);
1336
1350
  const dfDir = realAbs(o.dfDir);
1337
- if (abs === path.join(dfDir, "project.json")) return ".dev-flow/project.json is legacy — it is no longer read; fold its values into project.md and delete it";
1338
1351
  if (abs === path.join(dfDir, "project.md")) return "project.md is the operator playbook — change it with flow init --write (setup) or inside a docs/patch flow's worktree";
1339
1352
  if (abs.endsWith("state.json") && abs.includes(dfDir + path.sep)) return "state.json is dev-flow-owned — advance stages with the flow tool only";
1340
1353
  if (abs.endsWith("claim.json") && abs.includes(dfDir + path.sep)) return "claim.json is dev-flow-owned — the live-session lock is not an edit target; take a feature over with flow use <slug>";
1341
- // The delegation ledger is the fact the verify gate trusts about *who* worked — and the session it
1342
- // constrains is the one holding the pen. Left writable, one hand-written line covering the driver's
1343
- // own shas collapses "zero bypass", so it is dev-flow-owned like state.json. Worker runs append it
1344
- // from flow_stage's completion code (appendFileSync, which never passes through this guard), and
1345
- // flow verify only ever reads it — no sanctioned channel needs it to be an edit target.
1346
- if (isDelegationLedger(abs, dfDir)) return `${DELEGATIONS_FILE} is dev-flow-owned — the delegation ledger is written by flow_stage worker runs and read by flow verify; a session cannot sign its own proof`;
1347
1354
  // Owner attribution BEFORE the .dev-flow allow: with the default worktreeDir inside .dev-flow,
1348
1355
  // a worktree must still be judged by its owning feature's stage, not treated as free plan space.
1349
1356
  const owner = o.features.find((f) => within(abs, f.worktreeAbs ? realAbs(f.worktreeAbs) : null));
1350
1357
  if (owner) {
1351
1358
  if (owner.state.stage === "plan") return `feature ${owner.state.slug} is in plan — code is read-only until its plan is approved`;
1352
- if (owner.state.stage === "done") return `feature ${owner.state.slug} is done`;
1353
1359
  // the playbook copy inside a worktree: only operator-granted lightweight modes may change it
1354
1360
  if (path.basename(abs) === "project.md" && abs.includes(path.join(".dev-flow", "project.md")) && !owner.state.docs && !owner.state.patch)
1355
1361
  return `project.md changes belong to a docs or patch flow — ${owner.state.slug} is a normal feature (flow start <slug> --docs --confirmed)`;
1356
- // At implement the driver drives and a worker authors: the verify gate refuses a branch whose
1357
- // commits fall outside a worker's run window (delegationErrors), so an inline edit here is work
1358
- // that cannot be proven later. Saying it at the write is cheaper than letting a session author a
1359
- // branch and hitting the gate with it — and unlike the gate, this knows who is holding the pen:
1360
- // workers are registered sessions (byWorker), and --docs/--patch are the operator-granted inline
1361
- // modes. Pre-release stays in-session by design (review, changelog, bump are judgment calls).
1362
- if (owner.state.stage === "implement" && !owner.state.docs && !owner.state.patch && !o.byWorker)
1363
- return `implement work is delegated — ${owner.state.slug} is a normal feature at implement: a flow_stage { stage: "implement" } worker edits and commits in this worktree, not this session (the driver keeps the gates, the checkpoint, flow check and running the app)`;
1364
1362
  return null; // implement/pre-release/release: own worktree is the working area
1365
1363
  }
1366
1364
  // Scratch outside the checkout is not a repo write: every stage (and an unbound session) may use it. It
@@ -1390,12 +1388,6 @@ export function writeGuard(o: { abs: string; dfDir: string; features: FeatureRef
1390
1388
  return `unfinished features: ${o.features.map((f) => f.state.slug).join(", ")} — bind this session with flow use <slug> (or pass an explicit slug to gates)`;
1391
1389
  }
1392
1390
 
1393
- /** Branch targeted by a `git checkout`/`git switch` in the command, or null. */
1394
- export function checkoutTarget(command: string): string | null {
1395
- const m = command.match(/\bgit\s+(?:-C\s+\S+\s+)?(?:checkout|switch)\s+(?:-[bBc]\s+)?([^\s;|&]+)/);
1396
- return m ? m[1] : null;
1397
- }
1398
-
1399
1391
  /** Prefix feature branches match: branchPattern up to `{slug}` — used to keep feature branches out of the main checkout. */
1400
1392
  export function featureBranchPrefix(cfg: Config): string {
1401
1393
  return cfg.branchPattern.split("{")[0];
@@ -1406,11 +1398,6 @@ export interface SessionClaim {
1406
1398
  key: string;
1407
1399
  pid: number;
1408
1400
  at: string;
1409
- /** The claiming process's start identity (`processStart`), when the platform has one. A pid is
1410
- * recycled — a claim left by a crashed pi can name a pid some unrelated process now holds — so a
1411
- * live pid only counts as the claimant when its start identity still matches. Absent on legacy
1412
- * claims and on platforms without /proc, which keep the pid-only judgement. */
1413
- start?: string;
1414
1401
  }
1415
1402
 
1416
1403
  /** Whether a process is running (kill 0 only probes existence; EPERM means it exists, foreign-owned). */
@@ -1423,47 +1410,13 @@ export function pidAlive(pid: number): boolean {
1423
1410
  }
1424
1411
  }
1425
1412
 
1426
- /** A process's start identity: field 22 (`starttime`, clock ticks since boot) of `/proc/<pid>/stat`.
1427
- * Two processes that share a pid never share it. `undefined` where there is no procfs. The comm
1428
- * field (2) may itself hold spaces or parens, so the fields are counted from the LAST `)`. */
1429
- export function processStart(pid: number, read: (file: string) => string = (f) => readFileSync(f, "utf8")): string | undefined {
1430
- try {
1431
- const stat = read(`/proc/${pid}/stat`);
1432
- const rest = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
1433
- // rest[0] is field 3 (state), so field 22 sits at index 19
1434
- const st = rest[19];
1435
- return st && /^\d+$/.test(st) ? st : undefined;
1436
- } catch {
1437
- return undefined;
1438
- }
1439
- }
1440
-
1441
- /** True only when another live session holds the claim — its feature can only be taken by an explicit `flow use`, never quietly.
1442
- * A claim whose pid is alive but whose recorded start identity no longer matches belongs to a dead
1443
- * session whose pid was recycled: it does not block. */
1444
- export function claimBlocks(claim: SessionClaim | null, myKey: string, alive: (pid: number) => boolean = pidAlive, startOf: (pid: number) => string | undefined = processStart): boolean {
1445
- if (!claim || claim.key === myKey || !alive(claim.pid)) return false;
1446
- if (claim.start) {
1447
- const now = startOf(claim.pid);
1448
- if (now !== undefined && now !== claim.start) return false;
1449
- }
1450
- return true;
1451
- }
1452
-
1453
- /** How old a claim is, in words, for a refusal: "claimed 3 days ago" lets the operator tell a live
1454
- * session from a stale pid at a glance. Empty when the stamp is unreadable. */
1455
- export function claimAge(claim: SessionClaim, nowMs: number = Date.now()): string {
1456
- const t = Date.parse(claim.at);
1457
- if (!Number.isFinite(t)) return "";
1458
- const min = Math.max(0, Math.round((nowMs - t) / 60000));
1459
- if (min < 60) return `${min} min old`;
1460
- const h = Math.round(min / 60);
1461
- if (h < 48) return `${h} h old`;
1462
- return `${Math.round(h / 24)} days old`;
1413
+ /** True only when another live session holds the claim — its feature can only be taken by an explicit `flow use`, never quietly. */
1414
+ export function claimBlocks(claim: SessionClaim | null, myKey: string, alive: (pid: number) => boolean = pidAlive): boolean {
1415
+ return !!claim && claim.key !== myKey && alive(claim.pid);
1463
1416
  }
1464
1417
 
1465
1418
  /** Footer glyph per stage: the footer has no room for stage words and no legend of its own (README:Status bar is the legend). */
1466
- export const STAGE_EMOJI: Record<Stage, string> = { plan: "📝", implement: "🔨", "pre-release": "🔍", release: "🚀", done: "🏁" };
1419
+ export const STAGE_EMOJI: Record<Stage, string> = { plan: "📝", implement: "🔨", "pre-release": "🔍", release: "🚀" };
1467
1420
 
1468
1421
  export function statusCompact(state: FlowState): { text: string; failed: boolean } {
1469
1422
  const failed = Object.values(state.checks).some((c) => !c.ok);
@@ -1479,7 +1432,7 @@ export function statusCompact(state: FlowState): { text: string; failed: boolean
1479
1432
  * 💬 is the legend's "operator, your turn": an unbound session is parked on the operator by definition (an
1480
1433
  * answer to start, or nothing to do until they say), so the pre-flow glyph is the honest one there too. */
1481
1434
  export function statusFor(bound: FlowState | null, openCount: number): { text: string } {
1482
- if (bound && bound.stage !== "done") {
1435
+ if (bound) {
1483
1436
  const { text, failed } = statusCompact(bound);
1484
1437
  return { text: failed ? `${text} ⚠️` : text };
1485
1438
  }
@@ -1492,13 +1445,8 @@ export function openChecklistItems(text: string): string[] {
1492
1445
  return text.split("\n").map((l) => l.trim()).filter((l) => l.startsWith("- [ ] "));
1493
1446
  }
1494
1447
 
1495
- /** Open (unchecked) reflection items in reflections.md content — the agent's suggestion queue. */
1496
- export function openReflections(text: string): string[] {
1497
- return openChecklistItems(text);
1498
- }
1499
-
1500
- /** Closed (checked-off) reflection items — what `flow reflect tidy` drops (roadmap shares the checkbox test). */
1501
- export const closedReflectionCount = (text: string) => text.split("\n").filter(isDoneItem).length;
1448
+ /** Checked-off (`- [x]`) items — what `flow reflect tidy` and `flow roadmap tidy` drop. */
1449
+ export const doneItemCount = (text: string) => text.split("\n").filter(isDoneItem).length;
1502
1450
 
1503
1451
  /** Drop the closed (`- [x]`) reflection items: the preamble and the open lines stay verbatim
1504
1452
  * (a line filter — no re-bucketing like appendReflection's rewrite), and a `## section` heading
@@ -1633,11 +1581,6 @@ export function guessReflectSections(note: string): ReflectGuess {
1633
1581
  return { sections: ["playbook"], why: "nothing plugin-shaped in the note — if it is a dev-flow bug: flow reflect move <n> --plugin" };
1634
1582
  }
1635
1583
 
1636
- /** The section(s) a note belongs to, decided from its wording (primary home only — see guessReflectSections). */
1637
- export function reflectSections(note: string): ReflectSection[] {
1638
- return guessReflectSections(note).sections;
1639
- }
1640
-
1641
1584
  /** Where a fix must be implemented: every fix runs through a flow whose gates confirm it —
1642
1585
  * playbook-only change → docs flow; code in the dev-flow repo → patch/normal flow;
1643
1586
  * plugin feedback in someone else's repo → upstream issue (dev-flow files nothing itself). */
@@ -1730,10 +1673,9 @@ export function reflectProtocol(items: ReflectItem[], selfRepo: boolean, facts:
1730
1673
  * Rewrite reflections.md as a preamble + one section per non-empty bucket, with `line` appended to
1731
1674
  * the end of each named section. Everything above the first item (title, comment, operator notes) is
1732
1675
  * kept verbatim. Below the first item a `## section` heading owns the lines under it, so an existing
1733
- * line never changes section. Legacy flat lines carry their target inline (`- [ ] (plugin) …`,
1734
- * `— to playbook`); that marker buckets them and is then dropped, so an old file migrates on next
1735
- * write. A note already in a section is not written there again — an all-duplicate call returns the
1736
- * content untouched so the caller can say so.
1676
+ * line never changes section; an item under no known heading files under `## playbook` (where the
1677
+ * operator reads it — `flow reflect move` re-files it). A note already in a section is not written
1678
+ * there again — an all-duplicate call returns the content untouched so the caller can say so.
1737
1679
  */
1738
1680
  export function appendReflection(text: string, sections: ReflectSection[], line: string): string {
1739
1681
  const lines = text.split("\n");
@@ -1758,9 +1700,7 @@ export function appendReflection(text: string, sections: ReflectSection[], line:
1758
1700
  continue;
1759
1701
  }
1760
1702
  if (!l.startsWith("- [")) continue;
1761
- // items above every heading come from a legacy flat file, where the inline marker is the only clue.
1762
- const key: ReflectSection = section ?? (/\((plugin|doctor)\)/.test(l) || /\bto plugin\b/.test(l) ? "plugin" : "playbook");
1763
- buckets[key].push(l.replace(/\((plugin|playbook|doctor)\)/, "").replace(/\s*[—-]\s*to\s+(playbook|plugin|doctor)/, "").replace(/\s{2,}/g, " ").trim());
1703
+ buckets[section ?? "playbook"].push(l);
1764
1704
  }
1765
1705
  const note = line.trim();
1766
1706
  const body = reflectionBody(note);
@@ -1786,8 +1726,6 @@ export function appendRoadmapItem(text: string, item: string): string {
1786
1726
 
1787
1727
  /** Number of open roadmap items. */
1788
1728
  export const roadmapOpenCount = (text: string) => openChecklistItems(text).length;
1789
- /** Number of done roadmap items (tidy removes them). */
1790
- export const roadmapDoneCount = (text: string) => text.split("\n").filter(isDoneItem).length;
1791
1729
 
1792
1730
  /** Stamp the nth open item (1-based, open items only) with `(slug)` — the pick→finish handshake.
1793
1731
  * Returns null when n is out of range. Re-picking the same slug is a no-op stamp. */
@@ -1850,7 +1788,7 @@ export function shouldSelfCompact(
1850
1788
  reserve = PI_RESERVE_DEFAULT,
1851
1789
  ): boolean {
1852
1790
  if (d.compacting || d.tokens === null) return false;
1853
- if (!d.stage || d.stage === "done") return false;
1791
+ if (!d.stage) return false;
1854
1792
  if (d.checklistPending > 0) return false;
1855
1793
  if (d.stage === "plan" && d.planFiles === 0) return false;
1856
1794
  return d.tokens > d.contextWindow - reserve - COMPACT_MARGIN;
@@ -1864,18 +1802,13 @@ export function shouldTakeOverCompaction(d: { reason: "manual" | "threshold" | "
1864
1802
  return d.reason === "threshold" && d.bound && !d.inFlight;
1865
1803
  }
1866
1804
 
1867
- /** reflections.md line for a forced (non-manual) pi compaction while a flow is bound — advisory, never gates. */
1868
- export function compactionReflectionLine(slug: string, stage: Stage, reason: string, today: string): string {
1869
- return `- [ ] pi auto-compacted (${reason}) at stage ${stage} — pace gates so work lands on disk before compaction; draft plan discussion into plan/ early — ${slug} ${today}`;
1870
- }
1871
-
1872
- /** What the agent/user should do next, per stage. */
1873
1805
  /** The playbook's merge style spelled for a hint: "" when the project has no policy. */
1874
1806
  function mergeHintFor(cfg: Config): string {
1875
1807
  const m = cfg.release.merge;
1876
1808
  return m && m !== "any" ? ` (the playbook says merge = ${m} — gh pr merge <n> --${m === "merge" ? "merge" : m}, number before the flag: a trailing one reads as the PR selector)` : "";
1877
1809
  }
1878
1810
 
1811
+ /** What the agent/user should do next, per stage. */
1879
1812
  export function nextHint(state: FlowState, cfg: Config): string {
1880
1813
  switch (state.stage) {
1881
1814
  case "plan":
@@ -1884,10 +1817,7 @@ export function nextHint(state: FlowState, cfg: Config): string {
1884
1817
  return `investigate, present your direction and proposed mode to the operator and clarify in chat, then write the plan into .dev-flow/${state.slug}/plan/plan.md${state.ui ? ` and render mockups to plan/mockups/ (${cfg.mockupGlobs.join(", ")}) with headless chromium, embedded in plan.md` : ""}, then ask the operator Approve? in chat and run flow approve --confirmed when they answer`;
1885
1818
  case "implement":
1886
1819
  if (state.docs) return `implement in the worktree ${state.worktree} — docs mode runs no project command (no build, no dev deploy, no health probe); tick the tier-2 checklist with the operator, then ask them Verified? in chat and run flow verify --confirmed when they answer`;
1887
- // The hint is what `flow status` and the per-turn injection hand the driver every turn, so it must
1888
- // not order work the write guard refuses and the verify gate refuses: at implement a worker authors,
1889
- // the driver drives. (docs mode above stays inline — it is exempt from the delegation gate.)
1890
- return `delegate the implement work: flow_stage { stage: "implement" } sends a worker to edit, test and commit in the worktree ${state.worktree} (your own edits there are guard-refused, and flow verify refuses a branch whose commits fall outside a worker run); when it reports, rerun flow check (tier-1 checks, incl. health with seeded data) and get a fresh verify-worker PASS; tick the tier-2 checklist with the operator, then ask them Verified? in chat and run flow verify --confirmed when they answer — keep the app running when you ask Verified?: the operator reviews the live app; never clean up the test server before the checkpoint is answered (with no dev deploy configured, verify live-re-probes health itself and refuses while nothing is answering)`;
1820
+ return `implement in the worktree ${state.worktree}, add tests, run flow check (tier-1 checks, incl. health with seeded data); tick the tier-2 checklist with the operator, then ask them Verified? in chat and run flow verify --confirmed when they answer — keep the app running when you ask Verified?: the operator reviews the live app; never clean up the test server before the checkpoint is answered (with no dev deploy configured, verify live-re-probes health itself and refuses while nothing is answering)`;
1891
1821
  case "pre-release":
1892
1822
  return `${cfg.release.review} → fix must-have/should-have → update docs${cfg.release.changelog ? ` → prepare ${cfg.release.changelog} (a heading for the new version, carrying every pending Unreleased line over as it stands)` : ""}${cfg.versioning.file ? ` → bump version in ${cfg.versioning.file}` : ""}, re-run flow check, then show the operator the PR summary, version and changelog, ask Release? and run flow release`;
1893
1823
  case "release":
@@ -1896,8 +1826,6 @@ export function nextHint(state: FlowState, cfg: Config): string {
1896
1826
  : state.noVersion
1897
1827
  ? `publish: commit and push the branch, open the PR, merge only once CI is green (gh pr checks <n> --watch — a locally-green branch can still fail CI-only jobs)${mergeHintFor(cfg)} — unversioned release: no manifest bump, no tag, your changelog entry rides under Unreleased; then run flow release-done (no further question)`
1898
1828
  : `publish: commit and push the branch, open the PR, merge only once CI is green (gh pr checks <n> --watch — a locally-green branch can still fail CI-only jobs)${mergeHintFor(cfg)}, create the annotated tag from the manifest version and push it, then run flow release-done (no further question)`;
1899
- default:
1900
- return "feature finished";
1901
1829
  }
1902
1830
  }
1903
1831
 
@@ -1958,7 +1886,7 @@ export function gateHelpJson(gateHelp: string, version: string | null): string {
1958
1886
  );
1959
1887
  }
1960
1888
 
1961
- /** Write (or delete, on null) a dot-path value in a partial project.json object. */
1889
+ /** Write (or delete, on null) a dot-path value in a nested config object. */
1962
1890
  export function applyAnswer(partial: Record<string, unknown>, key: string, value: string | boolean | null): void {
1963
1891
  const segs = key.split(".");
1964
1892
  const leaf = segs.pop()!;
@@ -1981,867 +1909,93 @@ export function applyAnswer(partial: Record<string, unknown>, key: string, value
1981
1909
  }
1982
1910
 
1983
1911
 
1984
- // ------------------------------------------------------- stage worker (flow_stage)
1985
-
1986
- /** Stages whose *work* `flow_stage` may delegate to a disposable sub-session. plan is the
1987
- * operator dialogue; release/finish carry the Release?/Finish? words — only the heavy middle
1988
- * stages are delegated, and gates are never delegated: the driving session keeps every gate,
1989
- * every checkpoint and the claim, so gate integrity never depends on a worker behaving. */
1990
- export const DELEGABLE_STAGES = ["implement", "pre-release"] as const;
1991
- export type DelegableStage = (typeof DELEGABLE_STAGES)[number];
1992
- export function isDelegableStage(s: string): s is DelegableStage {
1993
- return (DELEGABLE_STAGES as readonly string[]).includes(s);
1994
- }
1995
-
1996
- /** Sentinel line that ends a stage worker's final message — the parent digests exactly this,
1997
- * not the whole run, so one stage's hundred tool calls cost the driving session one bounded block. */
1998
- export const STAGE_REPORT_HEAD = "STAGE REPORT";
1999
-
2000
- /** The sections of the report block. The preserve-list mirrors flowCompactInstructions' demands:
2001
- * a worker's nuance lives nowhere else, so what is not written here is lost on purpose. */
2002
- export const STAGE_REPORT_CONTRACT = `Write, as the very last lines of your final message, exactly this block (empty sections say \`none\`):
2003
- ${STAGE_REPORT_HEAD}
2004
- done:
2005
- - <what you actually did, one line per item>
2006
- files:
2007
- - <path> — <what changed there>
2008
- notes:
2009
- - <operator answers/decisions not yet recorded by a gate · reasons for uncommitted changes · the exact next action>
2010
- blockers:
2011
- - <what would fail Verified? right now> (or: none)`;
2012
-
2013
- export interface StageReport {
2014
- done: string[];
2015
- files: string[];
2016
- notes: string[];
2017
- blockers: string[];
2018
- /** true when the worker never emitted the block — the caller must treat the raw tail as suspect. */
2019
- missing: boolean;
2020
- /** bounded tail of the worker's final message (kept for the digest when missing, else for reference). */
2021
- rawTail: string;
2022
- }
2023
-
2024
- /** Digest a stage worker's final message into the report contract. Lenient by design: a worker
2025
- * that skipped the block yields `missing: true` plus its tail, never a throw at the end of a long stage. */
2026
- export function parseStageReport(text: string): StageReport {
2027
- const lines = (text ?? "").split("\n");
2028
- let start = -1;
2029
- for (let i = lines.length - 1; i >= 0; i--) {
2030
- if (/^\s*[*_#>\s]*STAGE\s+REPORT[*_\s]*$/i.test(lines[i])) { start = i; break; }
2031
- }
2032
- const rep: StageReport = {
2033
- done: [], files: [], notes: [], blockers: [],
2034
- missing: start < 0,
2035
- rawTail: lines.slice(-15).join("\n").slice(-600),
2036
- };
2037
- if (start < 0) return rep;
2038
- type Section = "done" | "files" | "notes" | "blockers";
2039
- let section: Section | null = null;
2040
- for (const line of lines.slice(start + 1)) {
2041
- const h = /^(done|files|notes|blockers)\s*[::]\s*$/i.exec(line.trim());
2042
- if (h) { section = h[1].toLowerCase() as Section; continue; }
2043
- const b = /^\s*[-*]\s+(.+)$/.exec(line);
2044
- if (b && section) rep[section].push(b[1].trim());
2045
- }
2046
- rep.blockers = rep.blockers.filter((b) => !/^(none|no blockers?|n\/a|nothing)[-.\s]*$/i.test(b));
2047
- return rep;
2048
- }
1912
+ // ------------------------------------------------------------- stage worker (flow_stage)
2049
1913
 
2050
- /** Bounded, parent-facing digest of a worker run. `cap` exists so one delegation cannot spend
2051
- * the context it just saved; the full transcript stays on disk, named in the caller's output. */
2052
- export function renderStageReport(r: StageReport, cap = 4000): string {
2053
- const parts: string[] = [];
2054
- if (r.missing) parts.push("worker ended WITHOUT the STAGE REPORT block — digesting its raw tail, verify before trusting it:", "```", r.rawTail, "```");
2055
- for (const s of ["done", "files", "notes"] as const)
2056
- if (r[s].length) parts.push(`${s}:`, ...r[s].map((x) => `- ${x}`));
2057
- if (r.blockers.length) parts.push("BLOCKERS:", ...r.blockers.map((x) => `- ${x}`));
2058
- if (!parts.length) parts.push("(report block was empty)");
2059
- const out = parts.join("\n");
2060
- return out.length <= cap ? out : `${out.slice(0, cap)}\n…(digest truncated — full worker transcript on disk)`;
2061
- }
1914
+ export type WorkerOp = "implement" | "review";
2062
1915
 
2063
- export interface StageBriefInput {
2064
- slug: string;
2065
- stage: DelegableStage;
2066
- /** absolute path of the feature worktree — the worker's whole world. */
2067
- workDir: string;
2068
- /** absolute path of plan/plan.md in the main checkout (the worktree does not carry it). */
2069
- planFile: string;
2070
- /** the stage playbook reference contents ("" when the stage has none). */
2071
- referenceText: string;
2072
- /** truth as the driving session saw it: `flow status --json` output. */
2073
- statusJson: string;
2074
- /** `git status --porcelain -b` taken in the worktree before the worker starts. */
2075
- gitSummary: string;
2076
- /** what the parent session passes on: operator answers, decisions, warnings, the next action. */
2077
- note?: string;
2078
- }
2079
-
2080
- /** The worker's complete brief: role, boundaries, on-disk truth, stage playbook, handoff note,
2081
- * and the closing contract. Pure — the wiring reads the files and runs the git/status calls. */
2082
- export function buildStageBrief(i: StageBriefInput): string {
2083
- return `You are a dev-flow stage worker: you do the ${i.stage} work for feature "${i.slug}" and then report back. The flow itself belongs to a DIFFERENT session (the driving session): it owns the gates, the operator's checkpoint answers, and the claim. Work only inside ${i.workDir} (the feature worktree, on its branch).
2084
-
2085
- Boundaries (the guard enforces these; do not work around them):
2086
- - No gate commands, no flow verbs, no questions to the operator — the driving session runs every gate and asks every checkpoint. You owe the work and the report at the end.
2087
- - .dev-flow state files (state.json, claim.json, project.md) are read-only.
2088
- - Commit to the current feature branch EACH TIME a unit of work is complete (one module, one file-group, one screen) — if you are interrupted, that must cost one unit, never a dirty worktree. Never push, never merge, never touch the default branch, never write outside ${i.workDir}.
2089
-
2090
- Start by reading the plan — ${i.planFile} — and whatever it points to.
2091
-
2092
- Flow truth (\`flow status --json\` from the driving session):
2093
- ${i.statusJson}
2094
-
2095
- Worktree state (\`git status --porcelain -b\`):
2096
- ${i.gitSummary || "(clean)"}
2097
-
2098
- The stage playbook — what this stage owes when it exits (the gates you cannot see):
2099
- ${i.referenceText || "(this stage has no playbook reference)"}
2100
-
2101
- Handoff note from the driving session (operator answers, decisions, warnings, the exact next action):
2102
- ${i.note?.trim() || "(none — the plan and the status above are your whole brief)"}
2103
-
2104
- When you are done — finished OR blocked — stop doing work and close with the report.
2105
- ${STAGE_REPORT_CONTRACT}`;
2106
- }
2107
-
2108
- /** Stage-worker budget bounds, in minutes. The default is deliberately generous (a gate may wait
2109
- * 15 min on one deploy; a stage is a whole stage); `budgetMin` is the per-call, operator-visible
2110
- * override. A playbook knob would move the default project-side — deliberately a later flow. */
2111
- export const STAGE_BUDGET_DEFAULT_MIN = 45;
2112
- export const STAGE_BUDGET_MIN_MIN = 5;
2113
- export const STAGE_BUDGET_MAX_MIN = 120;
2114
- export function clampStageBudgetMin(raw?: unknown): number {
2115
- const n = typeof raw === "number" && Number.isFinite(raw) ? Math.round(raw) : STAGE_BUDGET_DEFAULT_MIN;
2116
- return Math.min(STAGE_BUDGET_MAX_MIN, Math.max(STAGE_BUDGET_MIN_MIN, n));
2117
- }
2118
-
2119
- /** `mm:ss` for heartbeat, live-log and status lines. */
2120
- export function stageElapsedLabel(ms: number): string {
2121
- const s = Math.max(0, Math.floor(ms / 1000));
2122
- return `${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`;
2123
- }
2124
-
2125
- /** One-summarization of a tool call's args for the live line: bash shows the command, edit/write the
2126
- * path, anything else compact JSON — always capped. */
2127
- export function summarizeToolArgs(args: unknown): string {
2128
- const a = args as Record<string, unknown> | undefined;
2129
- let s = "";
2130
- if (a && typeof a === "object") {
2131
- if (typeof a.command === "string") s = a.command;
2132
- else if (typeof a.path === "string") s = a.path;
2133
- else { try { s = JSON.stringify(a); } catch { s = ""; } }
2134
- }
2135
- s = s.replace(/\s+/g, " ").trim();
2136
- return s.length > 60 ? `${s.slice(0, 57)}…` : s;
2137
- }
1916
+ /** Stages where each worker op is legal: implement edits only while the flow is at implement; a review
1917
+ * (read-only, advisory) is useful before verify and again before release. */
1918
+ export const WORKER_OP_STAGES: Record<WorkerOp, Stage[]> = { implement: ["implement"], review: ["implement", "pre-release"] };
2138
1919
 
2139
- /** One appended line of `.dev-flow/<slug>/stage-live.log` — the tail-able activity floor that works
2140
- * on hosts where no tool partial ever renders. */
2141
- export function stageLiveLine(elapsedMs: number, toolName: string, argsSummary: string): string {
2142
- return `[+${stageElapsedLabel(elapsedMs)}] ${toolName}${argsSummary ? ` — ${argsSummary}` : ""}`;
2143
- }
1920
+ /** Default wall-clock budget per op, in minutes. */
1921
+ export const WORKER_BUDGET_MIN: Record<WorkerOp, number> = { implement: 60, review: 30 };
2144
1922
 
2145
- /** The soft-landing order steered into a worker at 75% of its budget: commit what is done, report
2146
- * the truth, stop starting new units. Beats an abort by one clean commit. */
2147
- export function stageInterruptSteer(budgetMin: number): string {
2148
- return `Budget spent (${budgetMin} min) — stop planning new work now. Finish only the edit you are mid-way through, commit everything that is done to the feature branch (a "wip(stage): …" commit is fine and expected), then close with the STAGE REPORT block: done lists what is committed, notes says what was never started and what may not compile, blockers says "interrupted at budget". Do not start new units.`;
2149
- }
2150
-
2151
- // ------------------------------------------------------- worker ops beyond the stage work (verify / reflect / live card)
2152
-
2153
- /** Every `flow_stage` op. `run` is a stage's work; `verify` and `reflect` are check-only reviews —
2154
- * they read and run commands but hold no edit or write, so the driving session gets independent eyes
2155
- * without handing over a gate or a fix; `status` reads the live run and needs no worker at all. */
2156
- export const WORKER_OPS = ["run", "verify", "reflect", "status"] as const;
2157
- export type WorkerOp = (typeof WORKER_OPS)[number];
2158
- export function isWorkerOp(s: string): s is WorkerOp {
2159
- return (WORKER_OPS as readonly string[]).includes(s);
2160
- }
2161
-
2162
- /** Default budget per op, minutes (the shared 5–120 clamp still applies). An implement slice is a
2163
- * whole stage; a review run reads and executes and cannot land a unit, so its default is the
2164
- * operator-set 30 — smaller default, same steer at 75%. */
2165
- export const WORKER_OP_BUDGET_MIN: Record<WorkerOp, number> = { run: STAGE_BUDGET_DEFAULT_MIN, verify: 30, reflect: 30, status: STAGE_BUDGET_DEFAULT_MIN };
1923
+ /** Times a worker that stopped without its REPORT is told to keep going before the run gives up. */
1924
+ export const WORKER_NUDGES = 2;
2166
1925
 
2167
- /** Toolset per op — the guard still judges every write by the owning feature's stage, but a reviewer
2168
- * that carries no edit or write tool cannot even try to fix what it is judging (standing order:
2169
- * check, don't fix). `status` spawns nothing; the empty list is the marker, never a spawn. */
2170
- export const WORKER_OP_TOOLS: Record<WorkerOp, readonly string[]> = {
2171
- run: ["read", "bash", "edit", "write"],
2172
- verify: ["read", "bash"],
2173
- reflect: ["read", "bash"],
2174
- status: [],
1926
+ export const clampBudgetMin = (n: unknown, op: WorkerOp): number => {
1927
+ const v = typeof n === "number" && Number.isFinite(n) ? n : WORKER_BUDGET_MIN[op];
1928
+ return Math.min(180, Math.max(5, Math.round(v)));
2175
1929
  };
2176
1930
 
2177
- /** Op legality, judged on the bound flow's live state: null = legal, string = the tool's refusal.
2178
- * `verify` is scoped to implement — it is that stage's own independent proof, while pre-release
2179
- * already has its review (`/flow-review`) and release/finish carry checkpoint words. `reflect` runs
2180
- * once the release is recorded and before `flow finish` deletes the flow dir. Gates stay
2181
- * undelegable: a verify worker's PASS is an INPUT the gate demands, never a gate the worker runs. */
2182
- export function workerOpError(op: WorkerOp, st: { stage: Stage; approvals: Record<string, string> }): string | null {
2183
- if (op === "verify" && st.stage !== "implement")
2184
- return `a verify worker runs only while the feature is at implement (stage is "${st.stage}") — it proves the implement work before Verified?; pre-release review is the playbook's review command, and release/finish carry checkpoint words`;
2185
- if (op === "reflect" && !(st.stage === "release" && st.approvals.release))
2186
- return `a reflect worker runs at the release stage after release-done recorded the release (stage is "${st.stage}"${st.approvals.release ? "" : ", no release recorded"}) — it reviews the finished flow before flow finish deletes .dev-flow/<slug>/`;
2187
- return null;
2188
- }
2189
-
2190
- /** Sentinel line that ends a verify worker's final message — the sibling of STAGE_REPORT_HEAD. The
2191
- * verdict is machine-read: it is what the verify gate demands, so prose approval is never enough. */
2192
- export const VERIFY_REPORT_HEAD = "VERIFY REPORT";
2193
-
2194
- /** The verify worker's closing contract. `verdict` is a closed set on purpose: anything the parser
2195
- * cannot read as pass/fail is treated as NO pass, so a hedged report never stamps the gate. */
2196
- export const VERIFY_REPORT_CONTRACT = `Close your final message with exactly this block (empty sections say \`none\`):
2197
- ${VERIFY_REPORT_HEAD}
2198
- verdict: pass | fail
2199
- findings:
2200
- - <one line per problem: what the plan requires, what the code does instead, file:line>
2201
- evidence:
2202
- - <one line per thing you ran: the command and what it printed>`;
2203
-
2204
- export interface VerifyReport {
2205
- /** null = no readable verdict (missing block, or a hedge where pass|fail was demanded). */
2206
- verdict: "pass" | "fail" | null;
2207
- findings: string[];
2208
- evidence: string[];
2209
- /** true when the worker never emitted the block. */
2210
- missing: boolean;
2211
- rawTail: string;
2212
- }
2213
-
2214
- /** Digest a verify worker's final message. A missing block or an unreadable verdict is a NON-pass —
2215
- * the caller must not stamp the gate on anything it did not read. */
2216
- export function parseVerifyReport(text: string): VerifyReport {
2217
- const lines = (text ?? "").split("\n");
2218
- let start = -1;
2219
- for (let i = lines.length - 1; i >= 0; i--) {
2220
- if (/^\s*[*_#>\s]*VERIFY\s+REPORT[*_\s]*$/i.test(lines[i])) { start = i; break; }
2221
- }
2222
- const rep: VerifyReport = { verdict: null, findings: [], evidence: [], missing: start < 0, rawTail: lines.slice(-15).join("\n").slice(-600) };
2223
- if (start < 0) return rep;
2224
- type Section = "findings" | "evidence";
2225
- let section: Section | null = null;
2226
- for (const line of lines.slice(start + 1)) {
2227
- const v = /^\s*verdict\s*[:=]\s*([A-Za-z]+)/i.exec(line.trim());
2228
- if (v) {
2229
- const word = v[1].toLowerCase();
2230
- rep.verdict = word === "pass" || word === "passes" || word === "passed" ? "pass" : word === "fail" || word === "failed" || word === "failing" ? "fail" : null;
2231
- continue;
2232
- }
2233
- const h = /^(findings|evidence)\s*[:=]\s*$/i.exec(line.trim());
2234
- if (h) { section = h[1].toLowerCase() as Section; continue; }
2235
- const b = /^\s*[-*]\s+(.+)$/.exec(line);
2236
- if (b && section) rep[section].push(b[1].trim());
2237
- }
2238
- rep.findings = rep.findings.filter((f) => !/^(none|no findings?|n\/a|nothing)[-.\s]*$/i.test(f));
2239
- return rep;
2240
- }
2241
-
2242
- /** Parent-facing digest of a verify run — bounded like the stage digest; the full transcript is on
2243
- * disk and named by the caller. */
2244
- export function renderVerifyReport(r: VerifyReport, cap = 4000): string {
2245
- const parts: string[] = [];
2246
- if (r.missing) parts.push("verify worker ended WITHOUT the VERIFY REPORT block — there is NO verdict, the tree is not verified:", "```", r.rawTail, "```");
2247
- else if (!r.verdict) parts.push("VERIFY REPORT carried no readable verdict (pass | fail was required) — treated as NO pass:", "```", r.rawTail, "```");
2248
- else parts.push(`verdict: ${r.verdict.toUpperCase()}`);
2249
- if (r.findings.length) parts.push("findings:", ...r.findings.map((x) => `- ${x}`));
2250
- if (r.evidence.length) parts.push("evidence:", ...r.evidence.map((x) => `- ${x}`));
2251
- if (!parts.length) parts.push("(report block was empty)");
2252
- const out = parts.join("\n");
2253
- return out.length <= cap ? out : `${out.slice(0, cap)}\n…(digest truncated — full worker transcript on disk)`;
2254
- }
2255
-
2256
- /** Key the verify-worker PASS rides under inside state.checks. Living there is not a shortcut, it is
2257
- * the point: the PASS must die exactly when a tier-1 record dies (an edit-tool clear, a fingerprint
2258
- * that moved), so the friction is precise — one edit, one re-run — and never sticky. */
2259
- export const VERIFY_STAMP = "verify";
2260
-
2261
- /** Stamp a PASS over the tree as it is now (fp = worktreeFingerprint; null = git could not answer,
2262
- * and an unprovable stamp is a stamp that never looks stale — same rule as freshenChecks). */
2263
- export function recordVerifyPass(state: FlowState, at: string, fp: string | null): void {
2264
- state.checks[VERIFY_STAMP] = { ok: true, at, ...(fp ? { wt: fp } : {}) };
2265
- }
2266
-
2267
- /** How each op's session announces itself in the picker — the stage-line glyph vocabulary reused for
2268
- * worker names, so a row reads as a role at a glance instead of N identical "stage worker" lines. */
2269
- export const WORKER_OP_GLYPH: Record<WorkerOp, string> = { run: "🔨", verify: "🔍", reflect: "🏁", status: "👁" };
2270
-
2271
- /** A driver-supplied purpose, made safe for a session name: control chars gone, whitespace collapsed,
2272
- * clamped to ~32 chars on a word boundary. "" when nothing meaningful is left. */
2273
- export function sanitizeWorkerLabel(raw: string): string {
2274
- const s = raw.replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ").trim();
2275
- if (s.length <= 32) return s;
2276
- const cut = s.slice(0, 32);
2277
- const at = cut.lastIndexOf(" ");
2278
- return (at >= 16 ? cut.slice(0, at) : cut).trim();
2279
- }
2280
-
2281
- /** Session-name grammar: live `⏳ 🔨 #2 · wire ops`, done `✓ 🔨 #2 · 3 commits · wire ops`,
2282
- * `✓ 🔍 · stamp attack · PASS`, `✗ 🔨 #3 · hard-cut`. The final rename answers "how did it end?"
2283
- * without opening the row; the ordinal separates re-delegations when no label was given. */
2284
- export function workerName(mark: string, glyph: string, seq: number | null, label: string, outcome?: string | null): string {
2285
- const core = `${glyph}${seq ? ` #${seq}` : ""}${outcome ? ` · ${outcome}` : ""}${label ? ` · ${label}` : ""}`;
2286
- return `${mark} ${core}`;
2287
- }
2288
-
2289
- /** Content hash of a feature's plan/ dir (sorted relpath + bytes; "" stable when absent). The verify
2290
- * verdict was written AGAINST the plan, so a mid-stage plan edit must void the PASS exactly like a
2291
- * worktree edit — the stamp fingerprint hashes the worktree TOGETHER WITH this. */
2292
- export function planFingerprint(dir: string): string {
2293
- const h = createHash("sha256");
2294
- // absent and empty must not collide — an accidentally deleted plan dir is a different ground than an emptied one
2295
- h.update(existsSync(dir) ? "present\0" : "absent\0");
2296
- const walk = (d: string, rel: string) => {
2297
- // the entry kind rides as a control char after the name — a text marker ("@link") would collide
2298
- // with a real file literally named that, control chars in a name are the pathological remainder
2299
- for (const e of readdirSync(d, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
2300
- const p = path.join(d, e.name);
2301
- if (e.isDirectory()) {
2302
- h.update(`${rel}${e.name}\x01`);
2303
- walk(p, `${rel}${e.name}/`);
2304
- } else if (e.isSymbolicLink()) {
2305
- // a symlinked plan hides its content behind the entry — hash the link AND what it resolves to
2306
- h.update(`${rel}${e.name}\x02`).update(readlinkSync(p));
2307
- try {
2308
- h.update(readFileSync(p));
2309
- } catch {
2310
- /* dangling link: the target string is all there is */
2311
- }
2312
- } else if (e.isFile()) h.update(`${rel}${e.name}\x00`).update(readFileSync(p));
2313
- else h.update(`${rel}${e.name}\x03`);
2314
- }
2315
- };
2316
- if (existsSync(dir)) walk(dir, "");
2317
- return h.digest("hex").slice(0, 16);
2318
- }
2319
-
2320
- /** A PASS the verify gate may accept? docs-mode flows are exempt exactly like tier-1 checks: a docs
2321
- * flow runs no project command, so there is nothing for a checker to check beyond the operator. */
2322
- export function verifyStampMissing(state: FlowState): boolean {
2323
- if (state.docs) return false;
2324
- return !state.checks[VERIFY_STAMP]?.ok;
1931
+ /** Why an op is not legal for a feature at this stage, or null. */
1932
+ export function workerOpError(op: string, stage: Stage): string | null {
1933
+ if (op !== "implement" && op !== "review") return `unknown op "${op}" — flow_stage ops: implement (a worker edits and commits a slice), review (a fresh read-only reviewer)`;
1934
+ const ok = WORKER_OP_STAGES[op];
1935
+ return ok.includes(stage) ? null : `op "${op}" runs at ${ok.join(" or ")} — the feature is at ${stage}`;
2325
1936
  }
2326
1937
 
2327
- /** The verify gate's refusal line for a missing PASS — printed with the demand spelled out, because
2328
- * the operator's question must never be asked on a tree nothing independent has looked at. */
2329
- export const VERIFY_STAMP_REFUSAL = `no verify-worker PASS on this tree — run flow_stage { op: "verify" } and get its verdict: pass before asking Verified? (the PASS belongs to the tree it was read on: any worktree edit drops it like any tier-1 record; a docs flow is exempt)`;
2330
-
2331
- /** The durable worker index inside .dev-flow/<slug>/stage-sessions/ — one line per finished worker. */
2332
- export const TRANSCRIPTS_FILE = "transcripts.log";
2333
-
2334
- /** `worker transcript: …` line appended to .dev-flow/<slug>/stage-sessions/transcripts.log — the
2335
- * durable index the reflect worker reads (until now a transcript path lived only in the parent's
2336
- * tool result, i.e. only as long as that session's context). */
2337
- export function workerTranscriptLine(at: string, op: string, file: string): string {
2338
- return `[${at}] worker transcript (${op}): ${file}`;
2339
- }
2340
-
2341
- /** Parse transcripts.log back into entries; anything unrecognised is skipped, the log is append-only
2342
- * and hand-editable. Missing files are the caller's problem (a stale path still tells a reader a
2343
- * worker ran). */
2344
- export function parseWorkerTranscripts(text: string): { at: string; op: string; path: string }[] {
2345
- const out: { at: string; op: string; path: string }[] = [];
2346
- for (const line of (text ?? "").split("\n")) {
2347
- const m = /^\s*\[(.*?)\]\s*worker transcript(?: \(([^)]*)\))?:\s*(\S+)/.exec(line);
2348
- if (m) out.push({ at: m[1], op: m[2] ?? "run", path: m[3] });
2349
- }
2350
- return out;
2351
- }
2352
-
2353
- /** The durable delegation ledger inside .dev-flow/<slug>/stage-sessions/ — one line per finished
2354
- * `flow_stage` run worker, written by the same completion code that counts its commits. Read fresh
2355
- * at the gate, never folded into state.checks: those records mean "this tree was checked", a window
2356
- * means "this range was worked by a worker", and re-running a check must not erase the history the
2357
- * branch rests on (transcripts.log rides outside state for the same reason). */
2358
- export const DELEGATIONS_FILE = "delegations.log";
2359
-
2360
- /** The folder inside .dev-flow/<slug>/ that holds the worker logs (transcripts.log, delegations.log) —
2361
- * also half of what makes a delegations.log a delegation ledger (see isDelegationLedger). */
2362
- export const STAGE_SESSIONS_DIR = "stage-sessions";
2363
-
2364
- /** One finished worker run: the stage it worked and the commit range it left behind. */
2365
- export interface DelegationWindow {
2366
- stage: string;
2367
- start: string;
2368
- end: string;
2369
- }
2370
-
2371
- /** A delegations.log line. The line carries a **range**, not a count, because a range is what the
2372
- * gate can re-check: an amend or a rebase after the fact moves the sha out of every recorded window,
2373
- * which no write guard could ever see — bash-authored commits name no author, a rewritten sha does. */
2374
- export function delegationLine(at: string, stage: string, start: string, end: string, commits: number): string {
2375
- return `[${at}] run (${stage}): ${start}..${end} ${commits} commit(s)`;
2376
- }
2377
-
2378
- /** Parse delegations.log back into windows; anything unrecognised is skipped — the log is append-only
2379
- * and hand-editable, and an index that throws would take the gate down with it (transcripts.log's
2380
- * rule). Shas must look like shas so a typo'd line is simply not a window, rather than a window
2381
- * whose `git rev-list` fails for a reason the gate could only guess at. */
2382
- export function parseDelegationLedger(text: string): DelegationWindow[] {
2383
- const out: DelegationWindow[] = [];
2384
- for (const line of (text ?? "").split("\n")) {
2385
- const m = /^\s*\[(.*?)\]\s*run(?: \(([^)]*)\))?:\s*([0-9a-f]{7,40})\.\.([0-9a-f]{7,40})/i.exec(line);
2386
- if (m) out.push({ stage: m[2] ?? "run", start: m[3], end: m[4] });
2387
- }
2388
- return out;
2389
- }
2390
-
2391
- /** The verify gate's refusal when nobody did the stage's work — spelled out the way
2392
- * VERIFY_STAMP_REFUSAL spells its fix, so the driver reads its next action off the refusal line. */
2393
- export const DELEGATION_REFUSAL = `the implement work was not delegated — run flow_stage { stage: "implement" } and let the worker session do the edits and commits (this session keeps the gates, the checkpoint and flow check)`;
2394
-
2395
- /** Was the implement stage worked, or merely driven? The rule `flow verify` enforces: at least one
2396
- * implement-stage run window carries a commit, and every commit the branch holds over its default
2397
- * branch falls inside some implement-stage window. `windowCommits` resolves a window to its shas —
2398
- * git lives on the caller's side, so this stays a pure function under test.
2399
- * `branchCommits === null` (git could not answer) returns no errors: an unprovable answer is never
2400
- * proof of a violation, the BranchState.commitsAhead rule. `--docs` and `--patch` are exempt exactly
2401
- * like the verify stamp and the tier-1 checks — those two modes are the work the operator granted
2402
- * inline. Coverage is judged only here: commits the driver makes after verify (changelog, bump) are
2403
- * pre-release work and belong to the session by design. */
2404
- export function delegationErrors(
2405
- state: FlowState,
2406
- ledger: DelegationWindow[],
2407
- branchCommits: string[] | null,
2408
- windowCommits: (w: DelegationWindow) => string[],
2409
- ): string[] {
2410
- if (state.docs || state.patch) return [];
2411
- if (branchCommits === null) return [];
2412
- // Nothing on the branch to attribute: coverage is a claim about commits, and an empty branch has
2413
- // none. verifyGate already refuses a branch with nothing committed — one refusal per fact.
2414
- if (!branchCommits.length) return [];
2415
- const covered = new Set<string>();
2416
- for (const w of ledger.filter((x) => x.stage === "implement")) for (const sha of windowCommits(w) ?? []) covered.add(sha);
2417
- // A window whose range holds nothing proves a worker ran and delivered nothing: the stage is still
2418
- // undelivered, and "N commit(s) outside a window" on top of that names the same fact twice with
2419
- // worse advice — there is nothing to redo, there is nothing yet.
2420
- if (!covered.size) return [DELEGATION_REFUSAL];
2421
- const strays = branchCommits.filter((sha) => !covered.has(sha));
2422
- if (!strays.length) return [];
2423
- return [`${strays.length} commit(s) on the branch were made outside a worker run — delegate a fixer that redoes them (or reset them)`];
2424
- }
2425
-
2426
- /** How many live lines the card and `op: "status"` show: enough to see what the worker is doing,
2427
- * bounded so a long stage never spends the context the delegation just saved (R6). */
2428
- export const LIVE_TAIL_ITEMS = 8;
2429
- /** One live line's cap — worker output is signal in a tail, noise in bulk. */
2430
- const LIVE_LINE_CAP = 110;
2431
-
2432
- /** One line of a worker's assistant prose, for the live tail: last non-empty line only (a worker
2433
- * narrating a plan would otherwise drown its own tool activity). */
2434
- export function stageLiveAssistantLine(elapsedMs: number, text: string): string {
2435
- const lines = (text ?? "").split("\n").map((l) => l.trim()).filter(Boolean);
2436
- if (!lines.length) return "";
2437
- // its own shape, not stageLiveLine's: prose is not `tool — args`, an em dash in front of every
2438
- // sentence the worker wrote would read as a tool call that happened to talk
2439
- return `[+${stageElapsedLabel(elapsedMs)}] ✎ ${liveClip(lines[lines.length - 1])}`;
2440
- }
2441
- /** A finished tool call: ✓/✗ plus one line of what came back — the difference between "it is running"
2442
- * and "it is getting somewhere". */
2443
- export function stageLiveResultLine(elapsedMs: number, toolName: string, ok: boolean, summary: string): string {
2444
- return stageLiveLine(elapsedMs, `${ok ? "✓" : "✗"} ${toolName}`, liveClip(summary));
2445
- }
2446
-
2447
-
2448
- export function liveClip(s: string, cap = LIVE_LINE_CAP): string {
2449
- const one = (s ?? "").replace(/\s+/g, " ").trim();
2450
- return one.length > cap ? `${one.slice(0, cap - 1)}…` : one;
2451
- }
2452
-
2453
- /** The bounded tail: `… M earlier items` then the last `max` lines (empty lines never counted —
2454
- * a skipped assistant narration must not push real activity off the card). */
2455
- export function liveTail(lines: string[], max = LIVE_TAIL_ITEMS): string[] {
2456
- const kept = lines.filter(Boolean);
2457
- if (kept.length <= max) return kept;
2458
- return [`… ${kept.length - max} earlier items`, ...kept.slice(-max)];
2459
- }
2460
-
2461
-
2462
- /** Everything the live tool card needs to draw one frame. The card is the guaranteed visibility
2463
- * surface (it renders in the driver's own transcript on every host), so it is built from plain
2464
- * strings here and wrapped into components by the extension — the same lines reach a host that only
2465
- * shows the update's text (pi-web) and the no-UI fallback `op: "status"`. */
2466
- export interface StageCardView {
2467
- kind: string;
2468
- slug: string;
2469
- elapsedMs: number;
2470
- budgetMin: number;
2471
- softFired?: boolean;
2472
- tail?: string[];
2473
- usage?: string;
2474
- state?: "running" | "done" | "failed";
2475
- verdict?: "pass" | "fail" | null;
2476
- note?: string;
2477
- transcript?: string;
2478
- /** settled card only: the flow's other workers, already rendered by `workerFamily`. */
2479
- family?: string[];
2480
- /** heading for `family` when the rows came from somewhere coarser than pi's listing. */
2481
- familyHeading?: string;
2482
- }
2483
-
2484
- /** One frame of the worker card: header (what · where · clock against budget), the bounded live tail,
2485
- * the verdict once there is one, and what it cost. Expanded widens the tail and names the transcript. */
2486
- export function stageCardLines(v: StageCardView, expanded = false): string[] {
2487
- const glyph = v.state === "failed" ? "✗" : v.state === "done" ? "✓" : "⏳";
2488
- const out = [`${glyph} ${v.kind} · ${v.slug} · ${stageElapsedLabel(v.elapsedMs)}/${v.budgetMin}m${v.softFired ? " · closing out" : ""}`];
2489
- if (v.note) out.push(`note: ${liveClip(v.note, 80)}`);
2490
- out.push(...liveTail(v.tail ?? [], expanded ? LIVE_TAIL_ITEMS * 4 : LIVE_TAIL_ITEMS));
2491
- if (v.verdict) out.push(`verdict: ${v.verdict.toUpperCase()}`);
2492
- if (v.usage) out.push(v.usage);
2493
- if (expanded && v.transcript) out.push(`transcript: ${v.transcript}`);
2494
- // the family only on the settled card: listing a session directory is IO, and a live frame
2495
- // redraws on every worker tool call — a running run must not pay for a directory read
2496
- if (expanded && v.family?.length) out.push(v.familyHeading ?? familyHeading(), ...v.family);
2497
- return out;
2498
- }
2499
-
2500
- /** One worker session as pi's own session listing describes it. dev-flow keeps no lineage index
2501
- * of its own: the `parentSession` link in a session header *is* the record, and pi's picker threads
2502
- * on it. The extension reads pi's types and maps them onto this pi-free shape so the logic here
2503
- * stays unit-testable. */
2504
- export interface WorkerSessionRow {
2505
- /** the worker's session file */
2506
- path: string;
2507
- /** the parent link as pi recorded it (`parentSession`); absent = not somebody's child */
2508
- parent?: string | null;
2509
- /** the picker display name — it carries the ⏳/✓/✗ and the outcome the driver stamps on it */
2510
- name?: string;
2511
- messageCount?: number;
2512
- /** file mtime, however the host hands it over (pi gives a Date; tests give a number) */
2513
- modified?: Date | number | string;
2514
- }
2515
-
2516
- /** How many workers one render lists before it folds the older ones. */
2517
- export const WORKER_FAMILY_ITEMS = 12;
2518
-
2519
- /** Family rendering options: `exclude` drops one transcript — the live or just-finished run, which
2520
- * the caller already shows as its own section or its own line. */
2521
- export interface WorkerFamilyOptions {
2522
- exclude?: string;
2523
- }
2524
-
2525
- /** The heading over a family list — the one place the wording lives, so the status text and the card
2526
- * cannot drift, and so a list that came from the ledger (no message counts, no renames) says so. */
2527
- export function familyHeading(o: { live?: boolean; ledger?: boolean } = {}): string {
2528
- 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)" : ""}:`;
2529
- }
2530
-
2531
- /** The same session file written two ways is still one session (separators, trailing slash, and on
2532
- * Windows the case of the drive letter). pi's own picker canonicalizes the same idea. */
2533
- export function sessionPathKey(p: string): string {
2534
- const k = path.resolve(p).replace(/[\\/]+$/, "");
2535
- return process.platform === "win32" ? k.toLowerCase() : k;
2536
- }
2537
-
2538
- function sessionTime(row: WorkerSessionRow): number {
2539
- const raw = row.modified instanceof Date ? row.modified.getTime() : typeof row.modified === "number" ? row.modified : row.modified ? Date.parse(row.modified) : 0;
2540
- return Number.isFinite(raw) ? raw : 0;
2541
- }
2542
-
2543
- /**
2544
- * The family — every stage worker this session spawned, newest first, one line each.
2545
- *
2546
- * A stage worker is a real pi session whose header carries `parentSession` pointing at the driver's
2547
- * own file, so pi's picker nests it under the driver by itself (Threaded sort). This reads the same
2548
- * fact back for every surface that has no tree: the `flow_stage` card and `op: "status"`. Nothing is
2549
- * stored here, so a renamed worker (`✓ 🔍 · PASS · stamp attack`) reads back renamed, and workers a
2550
- * previous session already delegated show up next to this one's.
2551
- */
2552
- export function workerFamily(rows: WorkerSessionRow[], driverFile: string | null | undefined, opts: WorkerFamilyOptions = {}): string[] {
2553
- if (!driverFile) return [];
2554
- const max = WORKER_FAMILY_ITEMS;
2555
- const drop = opts.exclude ? sessionPathKey(opts.exclude) : null;
2556
- const mine = rows
2557
- .filter((r) => r.parent && sessionPathKey(r.parent) === sessionPathKey(driverFile) && (!drop || sessionPathKey(r.path) !== drop))
2558
- .sort((a, b) => sessionTime(b) - sessionTime(a));
2559
- const shown = mine.slice(0, max);
2560
- const lines = shown.map((r) => {
2561
- const at = sessionTime(r);
2562
- return `${r.name?.trim() || "(unnamed worker)"} · ${r.messageCount ?? 0} msgs · ${at ? localStamp(at) : "time unknown"} · ${r.path}`;
2563
- });
2564
- if (mine.length > shown.length) lines.push(familyFoldLine(mine.length - shown.length));
2565
- return lines;
2566
- }
2567
-
2568
- /** A transcript's header parent link, read from its first line alone — the cheap pass of the family
2569
- * scan. Returns `undefined` for a file that is not a pi session (or has no complete first line in
2570
- * the bytes read), `null` for a session that is nobody's child. */
2571
- export function sessionHeaderParent(head: string): string | null | undefined {
2572
- const nl = head.indexOf("\n");
2573
- if (nl < 0) return undefined;
2574
- try {
2575
- const h = JSON.parse(head.slice(0, nl)) as { type?: string; parentSession?: unknown };
2576
- if (h?.type !== "session") return undefined;
2577
- return typeof h.parentSession === "string" && h.parentSession ? h.parentSession : null;
2578
- } catch {
2579
- return undefined;
2580
- }
2581
- }
2582
-
2583
- /** The fields the family view needs, from one transcript's full text — the same rules pi's own
2584
- * session listing applies (latest `session_info` name wins, explicit clears included; messages are
2585
- * `message` entries; last activity is the newest user/assistant message, else the header time).
2586
- * Only the few files whose header names the driver reach this — that is what keeps a family read
2587
- * proportional to the family, not to the bucket's whole history. */
2588
- export function parseSessionSummary(text: string, file: string, mtimeMs?: number): WorkerSessionRow | null {
2589
- type Header = { timestamp?: unknown; parentSession?: unknown };
2590
- let header: Header | null = null;
2591
- let name: string | undefined;
2592
- let messageCount = 0;
2593
- let last: number | undefined;
2594
- for (const line of text.split("\n")) {
2595
- if (!line.trim()) continue;
2596
- let e: { type?: string; name?: unknown; timestamp?: unknown; message?: { role?: string; content?: unknown; timestamp?: unknown } };
2597
- try { e = JSON.parse(line); } catch { continue; }
2598
- if (!header) {
2599
- if (e?.type !== "session") return null;
2600
- header = e as Header;
2601
- continue;
2602
- }
2603
- if (e.type === "session_info") name = typeof e.name === "string" ? e.name.trim() || undefined : undefined;
2604
- if (e.type !== "message") continue;
2605
- messageCount++;
2606
- const m = e.message;
2607
- if (!m || m.content === undefined || (m.role !== "user" && m.role !== "assistant")) continue;
2608
- const t = typeof m.timestamp === "number" ? m.timestamp : Date.parse(String(e.timestamp));
2609
- if (Number.isFinite(t)) last = Math.max(last ?? 0, t);
2610
- }
2611
- if (!header) return null;
2612
- const headerTime = typeof header.timestamp === "string" ? Date.parse(header.timestamp) : NaN;
2613
- const modified = last && last > 0 ? last : Number.isFinite(headerTime) ? headerTime : mtimeMs;
2614
- return { path: file, parent: typeof header.parentSession === "string" ? header.parentSession : null, name, messageCount, modified };
2615
- }
2616
-
2617
- /** pi's bucket name for a working directory (`--home-me-repo--`), the same encoding pi applies
2618
- * (`getDefaultSessionDirPath`). Used only to RECOGNIZE buckets, never to choose where a session goes. */
2619
- export function sessionBucketName(cwd: string): string {
2620
- return `--${path.resolve(cwd).replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
2621
- }
2622
-
2623
- /** What the doctor needs to judge one feature's worktree bucket. */
2624
- export interface WorktreeBucketFeature {
2625
- /** the slug's state is gone, done or aborted — nothing will delegate into this worktree again */
2626
- finished: boolean;
2627
- worktreeExists: boolean;
2628
- }
2629
-
2630
- /**
2631
- * Session buckets stage workers left behind before 0.70 put workers in the driver's bucket. Such a
2632
- * worker ran with cwd = the feature worktree, so pi filed it under that worktree's own bucket — which
2633
- * no folder scope opened from the main checkout ever shows, and which outlives the worktree. A bucket
2634
- * is reported when it encodes `<root>/.dev-flow/<slug>/worktree` and that slug is finished or its
2635
- * worktree is gone. `features` is keyed by slug; a slug absent from it has no state at all (finished).
2636
- */
2637
- export function orphanWorktreeBuckets(buckets: string[], root: string, features: Map<string, WorktreeBucketFeature>): { bucket: string; slug: string }[] {
2638
- const prefix = sessionBucketName(path.join(root, ".dev-flow")).slice(0, -2) + "-";
2639
- const out: { bucket: string; slug: string }[] = [];
2640
- for (const b of buckets) {
2641
- if (!b.startsWith(prefix) || !b.endsWith("-worktree--")) continue;
2642
- const encSlug = b.slice(prefix.length, -"-worktree--".length);
2643
- if (!encSlug) continue;
2644
- // slugs are kebab-case, which the encoding leaves intact; a slug that is a known feature wins
2645
- const f = features.get(encSlug);
2646
- if (f && !f.finished && f.worktreeExists) continue;
2647
- out.push({ bucket: b, slug: encSlug });
2648
- }
2649
- return out;
2650
- }
2651
-
2652
- /** Stage workers spawned in THIS process, by session id. A worker loads the operator's extensions —
2653
- * dev-flow among them, because its guards must hold inside the worker too — but the driver's context
2654
- * (the playbook core, the unbound-session posture, "surface this to the operator") is wrong there:
2655
- * the brief is the worker's whole instruction. The worker's loader imports dev-flow as its own
2656
- * module instance, so the registry lives on a process-global symbol both instances can see. */
2657
- const WORKER_SESSIONS = Symbol.for("dev-flow.workerSessions");
2658
- function workerSessionSet(): Set<string> {
2659
- const g = globalThis as unknown as Record<symbol, Set<string> | undefined>;
2660
- return (g[WORKER_SESSIONS] ??= new Set<string>());
2661
- }
2662
- export function markWorkerSession(id: string | undefined | null): void {
2663
- if (id) workerSessionSet().add(id);
2664
- }
2665
- export function isWorkerSession(id: string | undefined | null): boolean {
2666
- return !!id && workerSessionSet().has(id);
2667
- }
2668
-
2669
- /** The line that stands in for the workers too old to list. It is not a worker, so anything counting
2670
- * the list has to know it — and both sources fold the same way, so the shape lives here. */
2671
- export function familyFoldLine(dropped: number): string {
2672
- return `… ${dropped} earlier workers`;
2673
- }
2674
-
2675
- export function isFamilyFoldLine(line: string): boolean {
2676
- return line.startsWith("… ");
2677
- }
2678
-
2679
- /** How many workers a rendered family list stands for: the fold line is a count, not a worker. */
2680
- export function workerFamilyCount(lines: string[] | null | undefined): number | null {
2681
- if (!lines) return null;
2682
- return lines.filter((l) => !isFamilyFoldLine(l)).length;
2683
- }
2684
-
2685
- /** Local wall-clock `YYYY-MM-DD HH:mm` — the convention every dev-flow timestamp follows (a UTC
2686
- * stamp next to the operator's own clock reads as a future or past session, and the family line is
2687
- * meant to be scanned, not converted). */
2688
- function localStamp(ms: number): string {
2689
- const d = new Date(ms);
2690
- const p = (n: number) => String(n).padStart(2, "0");
2691
- return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
2692
- }
2693
-
2694
- /** What the tool accumulated from a worker's assistant usage records. */
2695
- export interface StageUsage {
2696
- input: number;
2697
- output: number;
2698
- cacheRead: number;
2699
- cacheWrite: number;
2700
- totalTokens: number;
2701
- cost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };
2702
- }
2703
-
2704
- /** One compact usage line for the card and the result: what the run cost, at a glance. */
2705
- export function stageUsageLine(u: StageUsage, turns?: number): string {
2706
- const k = (n: number) => (n >= 1000 ? `${(n / 1000).toFixed(n >= 100_000 ? 0 : 1)}k` : String(n));
2707
- const ctx = u.cacheRead + u.input + u.output;
2708
- return `${turns ? `${turns} turns · ` : ""}↑${k(u.input)} ↓${k(u.output)} · ctx ${k(ctx)} · $${u.cost.total.toFixed(4)}`;
2709
- }
2710
-
2711
- export interface VerifyBriefInput {
1938
+ export interface WorkerBriefInput {
1939
+ op: WorkerOp;
2712
1940
  slug: string;
2713
- /** absolute path of the feature worktree — the reviewer's whole world. */
2714
1941
  workDir: string;
2715
- /** absolute path of plan/plan.md in the main checkout. */
2716
1942
  planFile: string;
2717
- statusJson: string;
2718
- /** `git status --porcelain -b` in the worktree, before the run. */
2719
- gitSummary: string;
2720
- /** `git diff --stat <default>…HEAD` — the shape of what is under review; the reviewer reads the
2721
- * full diff itself (pasting it here would spend the context the delegation saves). */
2722
- diffStat: string;
2723
- /** tier-1 commands the playbook says must be green (name + command). */
2724
- checks: { name: string; cmd: string }[];
2725
- /** the driver's default branch, for the diff range. */
2726
1943
  defaultBranch: string;
2727
- note?: string;
2728
- }
2729
-
2730
- /** The verify worker's brief: judge, never fix. The tree-identity clause is what makes the stamp
2731
- * honest — the tool proves the tree was untouched afterwards, so a PASS can only belong to the tree
2732
- * the gate is about to approve. */
2733
- export function buildVerifyBrief(i: VerifyBriefInput): string {
2734
- const checks = i.checks.length ? i.checks.map((c) => `- ${c.name}: ${c.cmd}`).join("\n") : "- (the playbook names no tier-1 commands — judge against the plan and the diff)";
2735
- return `You are a dev-flow VERIFY worker: an independent checker for feature "${i.slug}" at its implement stage. You did not write this code and you will not change it. The flow belongs to another session — gates, checkpoints and the operator conversation stay there; you owe one verdict.
2736
-
2737
- Work only inside ${i.workDir} (the feature worktree, on its branch).
2738
-
2739
- Standing order — CHECK, DON'T FIX:
2740
- - You have read and bash only. Do not edit, write, format, commit, stash, or clean anything. The tool compares \`git status --porcelain\`, \`git rev-parse HEAD\` and \`git symbolic-ref HEAD\` before and after your run: if the tree, HEAD or the branch pointer moved at all, your verdict is VOID and the run is reported as a violation.
2741
- - Running commands is allowed and expected (tests, build, the health probe, starting a throwaway process to read its output) — as long as nothing you run leaves the tree dirty. A command that rewrites tracked files is off-limits; say so in evidence instead.
2742
- - Never run a flow gate or a flow verb, never ask the operator anything.
2743
-
2744
- Read first: the plan — ${i.planFile} — then what the branch actually changed:
2745
- \`git diff ${i.defaultBranch}…HEAD\` (stat now: ${i.diffStat || "(no stat)"})
2746
-
2747
- Flow truth (\`flow status --json\` from the driving session):
2748
- ${i.statusJson}
2749
-
2750
- Worktree state at your start (\`git status --porcelain -b\`):
2751
- ${i.gitSummary || "(clean)"}
2752
-
2753
-
2754
- Tier-1 commands the playbook demands (run them yourself, do not trust the records):
2755
- ${checks}
2756
-
2757
- Note from the driving session (what it already knows, what it is unsure of, what to look at hardest):
2758
- ${i.note?.trim() || "(none — the plan and the diff are your whole brief)"}
2759
- Judge the diff against the plan, not against taste. Hunt for: plan items that were skipped or only half-done, behavior that contradicts the plan, missing or hollow tests for what changed, obvious bugs and unsafe paths, anything slow or wasteful under real use, leftover debug output, and docs that now lie. Report what you can prove; skip style preferences.
2760
-
2761
- Close with the verdict block. verdict: pass ONLY if you found nothing that should stop this from going to the operator — a plan gap, a real bug, or a missing test is a fail. Put the reasoning in findings (with file:line) and what you ran in evidence; the driving session reads ONLY this block, so a finding you did not write down does not exist.
2762
- ${VERIFY_REPORT_CONTRACT}`;
2763
- }
2764
-
2765
- /** Findings contract for the reflect worker: tagged, one line each, machine-split so the driver can
2766
- * print playbook items apart from plugin items without re-reading a whole run. */
2767
- export const REFLECT_FINDINGS_CONTRACT = `Close your final message with exactly this block (empty sections say \`none\`):
2768
- REFLECT FINDINGS
2769
- [playbook] <one line — what this project's playbook (project.md / its references) should say differently> — evidence: <what you saw>
2770
- [plugin] <one line — what dev-flow itself (a gate, guard, status, doc) should do differently> — evidence: <what you saw>
2771
- (one line per finding, repeat the tag as many times as you have findings; prefix a line with [neither] when it is real but belongs to neither — the driver routes it by hand)`;
2772
-
2773
- export interface ReflectFindings {
2774
- playbook: string[];
2775
- plugin: string[];
2776
- other: string[];
2777
- /** true when no tagged line was found at all — the reviewer produced prose, not findings. */
2778
- missing: boolean;
2779
- rawTail: string;
2780
- }
2781
-
2782
- /** Split a reflect worker's message into tagged findings. Bullets, bold and inline code around the
2783
- * tag are tolerated: a model decorates, and re-parsing prose by hand in the driver is worse. */
2784
- export function parseReflectFindings(text: string): ReflectFindings {
2785
- const out: ReflectFindings = { playbook: [], plugin: [], other: [], missing: true, rawTail: (text ?? "").split("\n").slice(-15).join("\n").slice(-600) };
2786
-
2787
- for (const line of (text ?? "").split("\n")) {
2788
- // bracketed tag (the contract) or a bare `plugin:` lead-in; markdown decoration is noise around it
2789
- const m = /^\s*(?:[-*>]\s*)?[*_`]*\s*\[\s*(playbook|plugin|neither|other)\s*\]\s*[*_`]*\s*(?:[:—-]\s*)?(.+)$|^\s*(?:[-*>]\s*)?[*_`]*\s*(playbook|plugin)\s*:\s*(.+)$/i.exec(line.trim());
2790
- if (!m) continue;
2791
- const body = (m[2] ?? m[4]).replace(/[*`\s]+$/, "").trim();
2792
- if (!body || /^(none|n\/a|nothing)[-.\s]*$/i.test(body)) continue;
2793
- const kind = (m[1] ?? m[3]).toLowerCase();
2794
- if (kind === "playbook") out.playbook.push(body);
2795
- else if (kind === "plugin") out.plugin.push(body);
2796
- else out.other.push(body);
1944
+ commits: string; // `git log --oneline <base>..HEAD`
1945
+ status: string; // `git status --short`
1946
+ checks: { name: string; command: string }[];
1947
+ note: string;
1948
+ }
1949
+
1950
+ /** The facts every worker needs, so the driver's note can be just the slice. The plan path is absolute:
1951
+ * it lives in the MAIN checkout's gitignored .dev-flow/, never inside the worktree. */
1952
+ export function buildWorkerBrief(o: WorkerBriefInput): string {
1953
+ const checks = o.checks.length ? o.checks.map((c) => `- ${c.name}: \`${c.command}\``).join("\n") : "- (the playbook defines no tier-1 commands)";
1954
+ const head = [
1955
+ `You are a ${o.op === "implement" ? "stage worker implementing a slice" : "fresh, independent reviewer"} for dev-flow feature \`${o.slug}\`.`,
1956
+ "",
1957
+ "## Facts",
1958
+ `- Worktree (your cwd; work only here): ${o.workDir}`,
1959
+ `- Approved plan (read it first; it is outside the worktree): ${o.planFile}`,
1960
+ `- Branch base: ${o.defaultBranch}`,
1961
+ `- Commits on the branch so far:\n${o.commits.trim() ? o.commits.trim().split("\n").map((l) => ` ${l}`).join("\n") : " (none)"}`,
1962
+ `- Uncommitted now: ${o.status.trim() ? `\n${o.status.trim().split("\n").map((l) => ` ${l}`).join("\n")}` : "clean"}`,
1963
+ `- Project checks (run them before you report):\n${checks}`,
1964
+ "- You hold no flow tool: gates, checkpoints and the operator stay with the driving session.",
1965
+ "",
1966
+ "## Your task",
1967
+ o.note.trim() || "(no note — do what the plan's next unfinished step asks)",
1968
+ "",
1969
+ ];
1970
+ const contract =
1971
+ o.op === "implement"
1972
+ ? [
1973
+ "## Contract",
1974
+ "- Use the edit/write tools for source changes. Commit as you go on the feature branch (small, meaningful commits).",
1975
+ "- Do not stop to narrate — keep working until the slice is done or you are blocked.",
1976
+ "- Finish with a final message whose last section starts with a line `REPORT` followed by: done, commits, open items, risks.",
1977
+ ]
1978
+ : [
1979
+ "## Contract",
1980
+ "- Check, don't fix: read the plan, the diff (`git diff " + o.defaultBranch + "...HEAD`) and the code; run the checks and any probe that proves a claim. Change no files, make no commits.",
1981
+ "- Look for correctness bugs, claims in docs/changelog the code does not back, missing tests for risky paths, and plan items not delivered.",
1982
+ "- Finish with a final message whose last section starts with a line `REPORT` followed by: `verdict: PASS` or `verdict: FAIL`, then findings (most severe first, each with file:line and how you proved it).",
1983
+ ];
1984
+ return [...head, ...contract].join("\n");
1985
+ }
1986
+
1987
+ /** The REPORT section of a worker's final message: everything after the last `REPORT` heading line. */
1988
+ export function parseWorkerReport(text: string): { found: boolean; body: string; verdict: "PASS" | "FAIL" | null } {
1989
+ const lines = (text ?? "").split("\n");
1990
+ let at = -1;
1991
+ for (let i = lines.length - 1; i >= 0; i--) {
1992
+ if (/^\s*[#*_>\s]*REPORT[*_:\s]*$/i.test(lines[i])) { at = i; break; }
2797
1993
  }
2798
- out.missing = !out.playbook.length && !out.plugin.length && !out.other.length;
2799
- return out;
1994
+ if (at < 0) return { found: false, body: lines.slice(-12).join("\n").slice(-800), verdict: null };
1995
+ const body = lines.slice(at + 1).join("\n").trim();
1996
+ const v = /verdict\s*[:=]\s*\**\s*(PASS|FAIL)/i.exec(body);
1997
+ return { found: true, body, verdict: v ? (v[1].toUpperCase() as "PASS" | "FAIL") : null };
2800
1998
  }
2801
1999
 
2802
- export interface ReflectBriefInput {
2803
- slug: string;
2804
- planFile: string;
2805
- statusJson: string;
2806
- /** The driver's own session file (JSONL) — pre-compaction turns live there even after the driver's
2807
- * context was summarized away, which is exactly what a finish review needs. */
2808
- driverSession: string | null;
2809
- /** Every worker transcript recorded in transcripts.log, oldest first. */
2810
- transcripts: { at: string; op: string; path: string }[];
2811
- /** Open reflection lines, so a finding already queued is not queued twice. */
2812
- openReflections: string[];
2813
- note?: string;
2814
- }
2815
-
2816
- /** The reflect worker's brief: an independent reviewer of the WHOLE flow — driver included. It
2817
- * cannot ask the operator anything and cannot write, so it returns tagged findings the driver puts to
2818
- * the operator (fold / fix / drop stays the operator's call, as always). */
2819
- export function buildReflectBrief(i: ReflectBriefInput): string {
2820
- const tlist = i.transcripts.length
2821
- ? i.transcripts.map((t) => `- ${t.op} worker (${t.at}): ${t.path}${existsSync(t.path) ? "" : " (file is gone — note it, do not invent it)"}`).join("\n")
2822
- : "- (this flow delegated nothing — review the driver session alone)";
2823
- const open = i.openReflections.length ? i.openReflections.map((l) => `- ${l}`).join("\n") : "- none";
2824
- return `You are a dev-flow REFLECT worker: an independent reviewer of the finished flow "${i.slug}". You review the DRIVER session — the session that drove the flow — plus every worker it delegated, and you report what the process should learn. You are not the driver, so nothing here is defensive: name the wasted turn, the gate that misfired, the playbook line that lied.
2825
-
2826
- Standing order — read-only: read and bash only. Never edit, write, commit, push, run a flow gate, or ask the operator anything. Reading git logs and files through bash is expected.
2827
-
2828
- Read the whole flow, in this order:
2829
- 1. the driver's own session transcript: ${i.driverSession ?? "(the driver's session file was not resolvable — review from the transcripts below and say so in your findings)"}
2830
- (a JSONL of every message, tool call and result. If it is large, read it in chunks and follow the turns, not the file.)
2831
- 2. every worker the flow delegated:
2832
- ${tlist}
2833
- 3. the plan the flow was held to: ${i.planFile}
2834
- 4. how the flow ended (\`flow status --json\` of the driving session):
2835
- ${i.statusJson}
2836
-
2837
- Then run the reflection itself, over what you read (this is the same protocol \`flow reflect\` prints, applied to the transcripts):
2838
- 1. every turn of the flow: friction, wrong turns, repeated failures, guards or gates that misfired or confused the agent, playbook drift, dead weight the flow added but never used. A finding must cite what happened — "the verify gate refused twice for X, the driver wasted N turns guessing why" is a finding; "the flow was slow" is not.
2839
- 2. classify each one: [playbook] = this project's own playbook/references/checklist wording should change; [plugin] = dev-flow itself (a gate, a guard, status, a doc) should change.
2840
- 3. dedupe against the open queue below — never report the same issue twice; if an open item already covers it, say "already queued: <item>" instead of a new finding.
2841
-
2842
- Open reflection queue (already filed):
2843
- ${open}
2844
-
2845
- ${i.note?.trim() ? `Note from the driver (context you cannot read elsewhere):\n${i.note.trim()}\n` : ""}
2846
- ${REFLECT_FINDINGS_CONTRACT}`;
2847
- }
2000
+ /** The nudge a worker gets when its turn ended without the REPORT block. */
2001
+ export const WORKER_NUDGE = "You stopped before finishing and without the REPORT section. Continue the task now (keep using tools; commit as you go). When it is done — or you are truly blocked — end with the `REPORT` section the contract asks for.";