pi-dev-flow 0.68.1 → 0.70.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,7 +4,7 @@
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, realpathSync } from "node:fs";
7
+ import { existsSync, readdirSync, readFileSync, readlinkSync, 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";
@@ -480,6 +480,9 @@ export function freshenChecks(state: FlowState, fp: string | null, keep: (name:
480
480
  if (!fp) return [];
481
481
  const stale: string[] = [];
482
482
  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;
483
486
  if (rec.wt && rec.wt !== fp && !keep(name)) {
484
487
  delete state.checks[name];
485
488
  stale.push(name);
@@ -2064,3 +2067,527 @@ export function stageLiveLine(elapsedMs: number, toolName: string, argsSummary:
2064
2067
  export function stageInterruptSteer(budgetMin: number): string {
2065
2068
  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.`;
2066
2069
  }
2070
+
2071
+ // ------------------------------------------------------- worker ops beyond the stage work (verify / reflect / live card)
2072
+
2073
+ /** Every `flow_stage` op. `run` is a stage's work; `verify` and `reflect` are check-only reviews —
2074
+ * they read and run commands but hold no edit or write, so the driving session gets independent eyes
2075
+ * without handing over a gate or a fix; `status` reads the live run and needs no worker at all. */
2076
+ export const WORKER_OPS = ["run", "verify", "reflect", "status"] as const;
2077
+ export type WorkerOp = (typeof WORKER_OPS)[number];
2078
+ export function isWorkerOp(s: string): s is WorkerOp {
2079
+ return (WORKER_OPS as readonly string[]).includes(s);
2080
+ }
2081
+
2082
+ /** Default budget per op, minutes (the shared 5–120 clamp still applies). An implement slice is a
2083
+ * whole stage; a review run reads and executes and cannot land a unit, so its default is the
2084
+ * operator-set 30 — smaller default, same steer at 75%. */
2085
+ export const WORKER_OP_BUDGET_MIN: Record<WorkerOp, number> = { run: STAGE_BUDGET_DEFAULT_MIN, verify: 30, reflect: 30, status: STAGE_BUDGET_DEFAULT_MIN };
2086
+
2087
+ /** Toolset per op — the guard still judges every write by the owning feature's stage, but a reviewer
2088
+ * that carries no edit or write tool cannot even try to fix what it is judging (standing order:
2089
+ * check, don't fix). `status` spawns nothing; the empty list is the marker, never a spawn. */
2090
+ export const WORKER_OP_TOOLS: Record<WorkerOp, readonly string[]> = {
2091
+ run: ["read", "bash", "edit", "write"],
2092
+ verify: ["read", "bash"],
2093
+ reflect: ["read", "bash"],
2094
+ status: [],
2095
+ };
2096
+
2097
+ /** Op legality, judged on the bound flow's live state: null = legal, string = the tool's refusal.
2098
+ * `verify` is scoped to implement — it is that stage's own independent proof, while pre-release
2099
+ * already has its review (`/flow-review`) and release/finish carry checkpoint words. `reflect` runs
2100
+ * once the release is recorded and before `flow finish` deletes the flow dir. Gates stay
2101
+ * undelegable: a verify worker's PASS is an INPUT the gate demands, never a gate the worker runs. */
2102
+ export function workerOpError(op: WorkerOp, st: { stage: Stage; approvals: Record<string, string> }): string | null {
2103
+ if (op === "verify" && st.stage !== "implement")
2104
+ 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`;
2105
+ if (op === "reflect" && !(st.stage === "release" && st.approvals.release))
2106
+ 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>/`;
2107
+ return null;
2108
+ }
2109
+
2110
+ /** Sentinel line that ends a verify worker's final message — the sibling of STAGE_REPORT_HEAD. The
2111
+ * verdict is machine-read: it is what the verify gate demands, so prose approval is never enough. */
2112
+ export const VERIFY_REPORT_HEAD = "VERIFY REPORT";
2113
+
2114
+ /** The verify worker's closing contract. `verdict` is a closed set on purpose: anything the parser
2115
+ * cannot read as pass/fail is treated as NO pass, so a hedged report never stamps the gate. */
2116
+ export const VERIFY_REPORT_CONTRACT = `Close your final message with exactly this block (empty sections say \`none\`):
2117
+ ${VERIFY_REPORT_HEAD}
2118
+ verdict: pass | fail
2119
+ findings:
2120
+ - <one line per problem: what the plan requires, what the code does instead, file:line>
2121
+ evidence:
2122
+ - <one line per thing you ran: the command and what it printed>`;
2123
+
2124
+ export interface VerifyReport {
2125
+ /** null = no readable verdict (missing block, or a hedge where pass|fail was demanded). */
2126
+ verdict: "pass" | "fail" | null;
2127
+ findings: string[];
2128
+ evidence: string[];
2129
+ /** true when the worker never emitted the block. */
2130
+ missing: boolean;
2131
+ rawTail: string;
2132
+ }
2133
+
2134
+ /** Digest a verify worker's final message. A missing block or an unreadable verdict is a NON-pass —
2135
+ * the caller must not stamp the gate on anything it did not read. */
2136
+ export function parseVerifyReport(text: string): VerifyReport {
2137
+ const lines = (text ?? "").split("\n");
2138
+ let start = -1;
2139
+ for (let i = lines.length - 1; i >= 0; i--) {
2140
+ if (/^\s*[*_#>\s]*VERIFY\s+REPORT[*_\s]*$/i.test(lines[i])) { start = i; break; }
2141
+ }
2142
+ const rep: VerifyReport = { verdict: null, findings: [], evidence: [], missing: start < 0, rawTail: lines.slice(-15).join("\n").slice(-600) };
2143
+ if (start < 0) return rep;
2144
+ type Section = "findings" | "evidence";
2145
+ let section: Section | null = null;
2146
+ for (const line of lines.slice(start + 1)) {
2147
+ const v = /^\s*verdict\s*[:=]\s*([A-Za-z]+)/i.exec(line.trim());
2148
+ if (v) {
2149
+ const word = v[1].toLowerCase();
2150
+ rep.verdict = word === "pass" || word === "passes" || word === "passed" ? "pass" : word === "fail" || word === "failed" || word === "failing" ? "fail" : null;
2151
+ continue;
2152
+ }
2153
+ const h = /^(findings|evidence)\s*[:=]\s*$/i.exec(line.trim());
2154
+ if (h) { section = h[1].toLowerCase() as Section; continue; }
2155
+ const b = /^\s*[-*]\s+(.+)$/.exec(line);
2156
+ if (b && section) rep[section].push(b[1].trim());
2157
+ }
2158
+ rep.findings = rep.findings.filter((f) => !/^(none|no findings?|n\/a|nothing)[-.\s]*$/i.test(f));
2159
+ return rep;
2160
+ }
2161
+
2162
+ /** Parent-facing digest of a verify run — bounded like the stage digest; the full transcript is on
2163
+ * disk and named by the caller. */
2164
+ export function renderVerifyReport(r: VerifyReport, cap = 4000): string {
2165
+ const parts: string[] = [];
2166
+ if (r.missing) parts.push("verify worker ended WITHOUT the VERIFY REPORT block — there is NO verdict, the tree is not verified:", "```", r.rawTail, "```");
2167
+ else if (!r.verdict) parts.push("VERIFY REPORT carried no readable verdict (pass | fail was required) — treated as NO pass:", "```", r.rawTail, "```");
2168
+ else parts.push(`verdict: ${r.verdict.toUpperCase()}`);
2169
+ if (r.findings.length) parts.push("findings:", ...r.findings.map((x) => `- ${x}`));
2170
+ if (r.evidence.length) parts.push("evidence:", ...r.evidence.map((x) => `- ${x}`));
2171
+ if (!parts.length) parts.push("(report block was empty)");
2172
+ const out = parts.join("\n");
2173
+ return out.length <= cap ? out : `${out.slice(0, cap)}\n…(digest truncated — full worker transcript on disk)`;
2174
+ }
2175
+
2176
+ /** Key the verify-worker PASS rides under inside state.checks. Living there is not a shortcut, it is
2177
+ * the point: the PASS must die exactly when a tier-1 record dies (an edit-tool clear, a fingerprint
2178
+ * that moved), so the friction is precise — one edit, one re-run — and never sticky. */
2179
+ export const VERIFY_STAMP = "verify";
2180
+
2181
+ /** Stamp a PASS over the tree as it is now (fp = worktreeFingerprint; null = git could not answer,
2182
+ * and an unprovable stamp is a stamp that never looks stale — same rule as freshenChecks). */
2183
+ export function recordVerifyPass(state: FlowState, at: string, fp: string | null): void {
2184
+ state.checks[VERIFY_STAMP] = { ok: true, at, ...(fp ? { wt: fp } : {}) };
2185
+ }
2186
+
2187
+ /** How each op's session announces itself in the picker — the stage-line glyph vocabulary reused for
2188
+ * worker names, so a row reads as a role at a glance instead of N identical "stage worker" lines. */
2189
+ export const WORKER_OP_GLYPH: Record<WorkerOp, string> = { run: "🔨", verify: "🔍", reflect: "🏁", status: "👁" };
2190
+
2191
+ /** A driver-supplied purpose, made safe for a session name: control chars gone, whitespace collapsed,
2192
+ * clamped to ~32 chars on a word boundary. "" when nothing meaningful is left. */
2193
+ export function sanitizeWorkerLabel(raw: string): string {
2194
+ const s = raw.replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ").trim();
2195
+ if (s.length <= 32) return s;
2196
+ const cut = s.slice(0, 32);
2197
+ const at = cut.lastIndexOf(" ");
2198
+ return (at >= 16 ? cut.slice(0, at) : cut).trim();
2199
+ }
2200
+
2201
+ /** Session-name grammar: live `⏳ 🔨 #2 · wire ops`, done `✓ 🔨 #2 · 3 commits · wire ops`,
2202
+ * `✓ 🔍 · stamp attack · PASS`, `✗ 🔨 #3 · hard-cut`. The final rename answers "how did it end?"
2203
+ * without opening the row; the ordinal separates re-delegations when no label was given. */
2204
+ export function workerName(mark: string, glyph: string, seq: number | null, label: string, outcome?: string | null): string {
2205
+ const core = `${glyph}${seq ? ` #${seq}` : ""}${outcome ? ` · ${outcome}` : ""}${label ? ` · ${label}` : ""}`;
2206
+ return `${mark} ${core}`;
2207
+ }
2208
+
2209
+ /** Content hash of a feature's plan/ dir (sorted relpath + bytes; "" stable when absent). The verify
2210
+ * verdict was written AGAINST the plan, so a mid-stage plan edit must void the PASS exactly like a
2211
+ * worktree edit — the stamp fingerprint hashes the worktree TOGETHER WITH this. */
2212
+ export function planFingerprint(dir: string): string {
2213
+ const h = createHash("sha256");
2214
+ // absent and empty must not collide — an accidentally deleted plan dir is a different ground than an emptied one
2215
+ h.update(existsSync(dir) ? "present\0" : "absent\0");
2216
+ const walk = (d: string, rel: string) => {
2217
+ // the entry kind rides as a control char after the name — a text marker ("@link") would collide
2218
+ // with a real file literally named that, control chars in a name are the pathological remainder
2219
+ for (const e of readdirSync(d, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
2220
+ const p = path.join(d, e.name);
2221
+ if (e.isDirectory()) {
2222
+ h.update(`${rel}${e.name}\x01`);
2223
+ walk(p, `${rel}${e.name}/`);
2224
+ } else if (e.isSymbolicLink()) {
2225
+ // a symlinked plan hides its content behind the entry — hash the link AND what it resolves to
2226
+ h.update(`${rel}${e.name}\x02`).update(readlinkSync(p));
2227
+ try {
2228
+ h.update(readFileSync(p));
2229
+ } catch {
2230
+ /* dangling link: the target string is all there is */
2231
+ }
2232
+ } else if (e.isFile()) h.update(`${rel}${e.name}\x00`).update(readFileSync(p));
2233
+ else h.update(`${rel}${e.name}\x03`);
2234
+ }
2235
+ };
2236
+ if (existsSync(dir)) walk(dir, "");
2237
+ return h.digest("hex").slice(0, 16);
2238
+ }
2239
+
2240
+ /** A PASS the verify gate may accept? docs-mode flows are exempt exactly like tier-1 checks: a docs
2241
+ * flow runs no project command, so there is nothing for a checker to check beyond the operator. */
2242
+ export function verifyStampMissing(state: FlowState): boolean {
2243
+ if (state.docs) return false;
2244
+ return !state.checks[VERIFY_STAMP]?.ok;
2245
+ }
2246
+
2247
+ /** The verify gate's refusal line for a missing PASS — printed with the demand spelled out, because
2248
+ * the operator's question must never be asked on a tree nothing independent has looked at. */
2249
+ 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)`;
2250
+
2251
+ /** The durable worker index inside .dev-flow/<slug>/stage-sessions/ — one line per finished worker. */
2252
+ export const TRANSCRIPTS_FILE = "transcripts.log";
2253
+
2254
+ /** `worker transcript: …` line appended to .dev-flow/<slug>/stage-sessions/transcripts.log — the
2255
+ * durable index the reflect worker reads (until now a transcript path lived only in the parent's
2256
+ * tool result, i.e. only as long as that session's context). */
2257
+ export function workerTranscriptLine(at: string, op: string, file: string): string {
2258
+ return `[${at}] worker transcript (${op}): ${file}`;
2259
+ }
2260
+
2261
+ /** Parse transcripts.log back into entries; anything unrecognised is skipped, the log is append-only
2262
+ * and hand-editable. Missing files are the caller's problem (a stale path still tells a reader a
2263
+ * worker ran). */
2264
+ export function parseWorkerTranscripts(text: string): { at: string; op: string; path: string }[] {
2265
+ const out: { at: string; op: string; path: string }[] = [];
2266
+ for (const line of (text ?? "").split("\n")) {
2267
+ const m = /^\s*\[(.*?)\]\s*worker transcript(?: \(([^)]*)\))?:\s*(\S+)/.exec(line);
2268
+ if (m) out.push({ at: m[1], op: m[2] ?? "run", path: m[3] });
2269
+ }
2270
+ return out;
2271
+ }
2272
+
2273
+ /** How many live lines the card and `op: "status"` show: enough to see what the worker is doing,
2274
+ * bounded so a long stage never spends the context the delegation just saved (R6). */
2275
+ export const LIVE_TAIL_ITEMS = 8;
2276
+ /** One live line's cap — worker output is signal in a tail, noise in bulk. */
2277
+ const LIVE_LINE_CAP = 110;
2278
+
2279
+ /** One line of a worker's assistant prose, for the live tail: last non-empty line only (a worker
2280
+ * narrating a plan would otherwise drown its own tool activity). */
2281
+ export function stageLiveAssistantLine(elapsedMs: number, text: string): string {
2282
+ const lines = (text ?? "").split("\n").map((l) => l.trim()).filter(Boolean);
2283
+ if (!lines.length) return "";
2284
+ // its own shape, not stageLiveLine's: prose is not `tool — args`, an em dash in front of every
2285
+ // sentence the worker wrote would read as a tool call that happened to talk
2286
+ return `[+${stageElapsedLabel(elapsedMs)}] ✎ ${liveClip(lines[lines.length - 1])}`;
2287
+ }
2288
+ /** A finished tool call: ✓/✗ plus one line of what came back — the difference between "it is running"
2289
+ * and "it is getting somewhere". */
2290
+ export function stageLiveResultLine(elapsedMs: number, toolName: string, ok: boolean, summary: string): string {
2291
+ return stageLiveLine(elapsedMs, `${ok ? "✓" : "✗"} ${toolName}`, liveClip(summary));
2292
+ }
2293
+
2294
+
2295
+ export function liveClip(s: string, cap = LIVE_LINE_CAP): string {
2296
+ const one = (s ?? "").replace(/\s+/g, " ").trim();
2297
+ return one.length > cap ? `${one.slice(0, cap - 1)}…` : one;
2298
+ }
2299
+
2300
+ /** The bounded tail: `… M earlier items` then the last `max` lines (empty lines never counted —
2301
+ * a skipped assistant narration must not push real activity off the card). */
2302
+ export function liveTail(lines: string[], max = LIVE_TAIL_ITEMS): string[] {
2303
+ const kept = lines.filter(Boolean);
2304
+ if (kept.length <= max) return kept;
2305
+ return [`… ${kept.length - max} earlier items`, ...kept.slice(-max)];
2306
+ }
2307
+
2308
+
2309
+ /** Everything the live tool card needs to draw one frame. The card is the guaranteed visibility
2310
+ * surface (it renders in the driver's own transcript on every host), so it is built from plain
2311
+ * strings here and wrapped into components by the extension — the same lines reach a host that only
2312
+ * shows the update's text (pi-web) and the no-UI fallback `op: "status"`. */
2313
+ export interface StageCardView {
2314
+ kind: string;
2315
+ slug: string;
2316
+ elapsedMs: number;
2317
+ budgetMin: number;
2318
+ softFired?: boolean;
2319
+ tail?: string[];
2320
+ usage?: string;
2321
+ state?: "running" | "done" | "failed";
2322
+ verdict?: "pass" | "fail" | null;
2323
+ note?: string;
2324
+ transcript?: string;
2325
+ /** settled card only: the flow's other workers, already rendered by `workerFamily`. */
2326
+ family?: string[];
2327
+ /** heading for `family` when the rows came from somewhere coarser than pi's listing. */
2328
+ familyHeading?: string;
2329
+ }
2330
+
2331
+ /** One frame of the worker card: header (what · where · clock against budget), the bounded live tail,
2332
+ * the verdict once there is one, and what it cost. Expanded widens the tail and names the transcript. */
2333
+ export function stageCardLines(v: StageCardView, expanded = false): string[] {
2334
+ const glyph = v.state === "failed" ? "✗" : v.state === "done" ? "✓" : "⏳";
2335
+ const out = [`${glyph} ${v.kind} · ${v.slug} · ${stageElapsedLabel(v.elapsedMs)}/${v.budgetMin}m${v.softFired ? " · closing out" : ""}`];
2336
+ if (v.note) out.push(`note: ${liveClip(v.note, 80)}`);
2337
+ out.push(...liveTail(v.tail ?? [], expanded ? LIVE_TAIL_ITEMS * 4 : LIVE_TAIL_ITEMS));
2338
+ if (v.verdict) out.push(`verdict: ${v.verdict.toUpperCase()}`);
2339
+ if (v.usage) out.push(v.usage);
2340
+ if (expanded && v.transcript) out.push(`transcript: ${v.transcript}`);
2341
+ // the family only on the settled card: listing a session directory is IO, and a live frame
2342
+ // redraws on every worker tool call — a running run must not pay for a directory read
2343
+ if (expanded && v.family?.length) out.push(v.familyHeading ?? familyHeading(), ...v.family);
2344
+ return out;
2345
+ }
2346
+
2347
+ /** One worker session as pi's own session listing describes it. dev-flow keeps no lineage index
2348
+ * of its own: the `parentSession` link in a session header *is* the record, and pi's picker threads
2349
+ * on it. The extension reads pi's types and maps them onto this pi-free shape so the logic here
2350
+ * stays unit-testable. */
2351
+ export interface WorkerSessionRow {
2352
+ /** the worker's session file */
2353
+ path: string;
2354
+ /** the parent link as pi recorded it (`parentSession`); absent = not somebody's child */
2355
+ parent?: string | null;
2356
+ /** the picker display name — it carries the ⏳/✓/✗ and the outcome the driver stamps on it */
2357
+ name?: string;
2358
+ messageCount?: number;
2359
+ /** file mtime, however the host hands it over (pi gives a Date; tests give a number) */
2360
+ modified?: Date | number | string;
2361
+ }
2362
+
2363
+ /** How many workers one render lists before it folds the older ones. */
2364
+ export const WORKER_FAMILY_ITEMS = 12;
2365
+
2366
+ /** Family rendering options: `exclude` drops one transcript — the live or just-finished run, which
2367
+ * the caller already shows as its own section or its own line. */
2368
+ export interface WorkerFamilyOptions {
2369
+ exclude?: string;
2370
+ }
2371
+
2372
+ /** The heading over a family list — the one place the wording lives, so the status text and the card
2373
+ * cannot drift, and so a list that came from the ledger (no message counts, no renames) says so. */
2374
+ export function familyHeading(o: { live?: boolean; ledger?: boolean } = {}): string {
2375
+ 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)" : ""}:`;
2376
+ }
2377
+
2378
+ /** The same session file written two ways is still one session (separators, trailing slash, and on
2379
+ * Windows the case of the drive letter). pi's own picker canonicalizes the same idea. */
2380
+ export function sessionPathKey(p: string): string {
2381
+ const k = path.resolve(p).replace(/[\\/]+$/, "");
2382
+ return process.platform === "win32" ? k.toLowerCase() : k;
2383
+ }
2384
+
2385
+ function sessionTime(row: WorkerSessionRow): number {
2386
+ const raw = row.modified instanceof Date ? row.modified.getTime() : typeof row.modified === "number" ? row.modified : row.modified ? Date.parse(row.modified) : 0;
2387
+ return Number.isFinite(raw) ? raw : 0;
2388
+ }
2389
+
2390
+ /**
2391
+ * The family — every stage worker this session spawned, newest first, one line each.
2392
+ *
2393
+ * A stage worker is a real pi session whose header carries `parentSession` pointing at the driver's
2394
+ * own file, so pi's picker nests it under the driver by itself (Threaded sort). This reads the same
2395
+ * fact back for every surface that has no tree: the `flow_stage` card and `op: "status"`. Nothing is
2396
+ * stored here, so a renamed worker (`✓ 🔍 · PASS · stamp attack`) reads back renamed, and workers a
2397
+ * previous session already delegated show up next to this one's.
2398
+ */
2399
+ export function workerFamily(rows: WorkerSessionRow[], driverFile: string | null | undefined, opts: WorkerFamilyOptions = {}): string[] {
2400
+ if (!driverFile) return [];
2401
+ const max = WORKER_FAMILY_ITEMS;
2402
+ const drop = opts.exclude ? sessionPathKey(opts.exclude) : null;
2403
+ const mine = rows
2404
+ .filter((r) => r.parent && sessionPathKey(r.parent) === sessionPathKey(driverFile) && (!drop || sessionPathKey(r.path) !== drop))
2405
+ .sort((a, b) => sessionTime(b) - sessionTime(a));
2406
+ const shown = mine.slice(0, max);
2407
+ const lines = shown.map((r) => {
2408
+ const at = sessionTime(r);
2409
+ return `${r.name?.trim() || "(unnamed worker)"} · ${r.messageCount ?? 0} msgs · ${at ? localStamp(at) : "time unknown"} · ${r.path}`;
2410
+ });
2411
+ if (mine.length > shown.length) lines.push(familyFoldLine(mine.length - shown.length));
2412
+ return lines;
2413
+ }
2414
+
2415
+ /** The line that stands in for the workers too old to list. It is not a worker, so anything counting
2416
+ * the list has to know it — and both sources fold the same way, so the shape lives here. */
2417
+ export function familyFoldLine(dropped: number): string {
2418
+ return `… ${dropped} earlier workers`;
2419
+ }
2420
+
2421
+ export function isFamilyFoldLine(line: string): boolean {
2422
+ return line.startsWith("… ");
2423
+ }
2424
+
2425
+ /** How many workers a rendered family list stands for: the fold line is a count, not a worker. */
2426
+ export function workerFamilyCount(lines: string[] | null | undefined): number | null {
2427
+ if (!lines) return null;
2428
+ return lines.filter((l) => !isFamilyFoldLine(l)).length;
2429
+ }
2430
+
2431
+ /** Local wall-clock `YYYY-MM-DD HH:mm` — the convention every dev-flow timestamp follows (a UTC
2432
+ * stamp next to the operator's own clock reads as a future or past session, and the family line is
2433
+ * meant to be scanned, not converted). */
2434
+ function localStamp(ms: number): string {
2435
+ const d = new Date(ms);
2436
+ const p = (n: number) => String(n).padStart(2, "0");
2437
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
2438
+ }
2439
+
2440
+ /** What the tool accumulated from a worker's assistant usage records. */
2441
+ export interface StageUsage {
2442
+ input: number;
2443
+ output: number;
2444
+ cacheRead: number;
2445
+ cacheWrite: number;
2446
+ totalTokens: number;
2447
+ cost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };
2448
+ }
2449
+
2450
+ /** One compact usage line for the card and the result: what the run cost, at a glance. */
2451
+ export function stageUsageLine(u: StageUsage, turns?: number): string {
2452
+ const k = (n: number) => (n >= 1000 ? `${(n / 1000).toFixed(n >= 100_000 ? 0 : 1)}k` : String(n));
2453
+ const ctx = u.cacheRead + u.input + u.output;
2454
+ return `${turns ? `${turns} turns · ` : ""}↑${k(u.input)} ↓${k(u.output)} · ctx ${k(ctx)} · $${u.cost.total.toFixed(4)}`;
2455
+ }
2456
+
2457
+ export interface VerifyBriefInput {
2458
+ slug: string;
2459
+ /** absolute path of the feature worktree — the reviewer's whole world. */
2460
+ workDir: string;
2461
+ /** absolute path of plan/plan.md in the main checkout. */
2462
+ planFile: string;
2463
+ statusJson: string;
2464
+ /** `git status --porcelain -b` in the worktree, before the run. */
2465
+ gitSummary: string;
2466
+ /** `git diff --stat <default>…HEAD` — the shape of what is under review; the reviewer reads the
2467
+ * full diff itself (pasting it here would spend the context the delegation saves). */
2468
+ diffStat: string;
2469
+ /** tier-1 commands the playbook says must be green (name + command). */
2470
+ checks: { name: string; cmd: string }[];
2471
+ /** the driver's default branch, for the diff range. */
2472
+ defaultBranch: string;
2473
+ note?: string;
2474
+ }
2475
+
2476
+ /** The verify worker's brief: judge, never fix. The tree-identity clause is what makes the stamp
2477
+ * honest — the tool proves the tree was untouched afterwards, so a PASS can only belong to the tree
2478
+ * the gate is about to approve. */
2479
+ export function buildVerifyBrief(i: VerifyBriefInput): string {
2480
+ 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)";
2481
+ 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.
2482
+
2483
+ Work only inside ${i.workDir} (the feature worktree, on its branch).
2484
+
2485
+ Standing order — CHECK, DON'T FIX:
2486
+ - 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.
2487
+ - 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.
2488
+ - Never run a flow gate or a flow verb, never ask the operator anything.
2489
+
2490
+ Read first: the plan — ${i.planFile} — then what the branch actually changed:
2491
+ \`git diff ${i.defaultBranch}…HEAD\` (stat now: ${i.diffStat || "(no stat)"})
2492
+
2493
+ Flow truth (\`flow status --json\` from the driving session):
2494
+ ${i.statusJson}
2495
+
2496
+ Worktree state at your start (\`git status --porcelain -b\`):
2497
+ ${i.gitSummary || "(clean)"}
2498
+
2499
+
2500
+ Tier-1 commands the playbook demands (run them yourself, do not trust the records):
2501
+ ${checks}
2502
+
2503
+ Note from the driving session (what it already knows, what it is unsure of, what to look at hardest):
2504
+ ${i.note?.trim() || "(none — the plan and the diff are your whole brief)"}
2505
+ 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.
2506
+
2507
+ 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.
2508
+ ${VERIFY_REPORT_CONTRACT}`;
2509
+ }
2510
+
2511
+ /** Findings contract for the reflect worker: tagged, one line each, machine-split so the driver can
2512
+ * print playbook items apart from plugin items without re-reading a whole run. */
2513
+ export const REFLECT_FINDINGS_CONTRACT = `Close your final message with exactly this block (empty sections say \`none\`):
2514
+ REFLECT FINDINGS
2515
+ [playbook] <one line — what this project's playbook (project.md / its references) should say differently> — evidence: <what you saw>
2516
+ [plugin] <one line — what dev-flow itself (a gate, guard, status, doc) should do differently> — evidence: <what you saw>
2517
+ (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)`;
2518
+
2519
+ export interface ReflectFindings {
2520
+ playbook: string[];
2521
+ plugin: string[];
2522
+ other: string[];
2523
+ /** true when no tagged line was found at all — the reviewer produced prose, not findings. */
2524
+ missing: boolean;
2525
+ rawTail: string;
2526
+ }
2527
+
2528
+ /** Split a reflect worker's message into tagged findings. Bullets, bold and inline code around the
2529
+ * tag are tolerated: a model decorates, and re-parsing prose by hand in the driver is worse. */
2530
+ export function parseReflectFindings(text: string): ReflectFindings {
2531
+ const out: ReflectFindings = { playbook: [], plugin: [], other: [], missing: true, rawTail: (text ?? "").split("\n").slice(-15).join("\n").slice(-600) };
2532
+
2533
+ for (const line of (text ?? "").split("\n")) {
2534
+ // bracketed tag (the contract) or a bare `plugin:` lead-in; markdown decoration is noise around it
2535
+ 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());
2536
+ if (!m) continue;
2537
+ const body = (m[2] ?? m[4]).replace(/[*`\s]+$/, "").trim();
2538
+ if (!body || /^(none|n\/a|nothing)[-.\s]*$/i.test(body)) continue;
2539
+ const kind = (m[1] ?? m[3]).toLowerCase();
2540
+ if (kind === "playbook") out.playbook.push(body);
2541
+ else if (kind === "plugin") out.plugin.push(body);
2542
+ else out.other.push(body);
2543
+ }
2544
+ out.missing = !out.playbook.length && !out.plugin.length && !out.other.length;
2545
+ return out;
2546
+ }
2547
+
2548
+ export interface ReflectBriefInput {
2549
+ slug: string;
2550
+ planFile: string;
2551
+ statusJson: string;
2552
+ /** The driver's own session file (JSONL) — pre-compaction turns live there even after the driver's
2553
+ * context was summarized away, which is exactly what a finish review needs. */
2554
+ driverSession: string | null;
2555
+ /** Every worker transcript recorded in transcripts.log, oldest first. */
2556
+ transcripts: { at: string; op: string; path: string }[];
2557
+ /** Open reflection lines, so a finding already queued is not queued twice. */
2558
+ openReflections: string[];
2559
+ note?: string;
2560
+ }
2561
+
2562
+ /** The reflect worker's brief: an independent reviewer of the WHOLE flow — driver included. It
2563
+ * cannot ask the operator anything and cannot write, so it returns tagged findings the driver puts to
2564
+ * the operator (fold / fix / drop stays the operator's call, as always). */
2565
+ export function buildReflectBrief(i: ReflectBriefInput): string {
2566
+ const tlist = i.transcripts.length
2567
+ ? 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")
2568
+ : "- (this flow delegated nothing — review the driver session alone)";
2569
+ const open = i.openReflections.length ? i.openReflections.map((l) => `- ${l}`).join("\n") : "- none";
2570
+ 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.
2571
+
2572
+ 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.
2573
+
2574
+ Read the whole flow, in this order:
2575
+ 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)"}
2576
+ (a JSONL of every message, tool call and result. If it is large, read it in chunks and follow the turns, not the file.)
2577
+ 2. every worker the flow delegated:
2578
+ ${tlist}
2579
+ 3. the plan the flow was held to: ${i.planFile}
2580
+ 4. how the flow ended (\`flow status --json\` of the driving session):
2581
+ ${i.statusJson}
2582
+
2583
+ Then run the reflection itself, over what you read (this is the same protocol \`flow reflect\` prints, applied to the transcripts):
2584
+ 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.
2585
+ 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.
2586
+ 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.
2587
+
2588
+ Open reflection queue (already filed):
2589
+ ${open}
2590
+
2591
+ ${i.note?.trim() ? `Note from the driver (context you cannot read elsewhere):\n${i.note.trim()}\n` : ""}
2592
+ ${REFLECT_FINDINGS_CONTRACT}`;
2593
+ }