pi-dev-flow 0.71.0 → 0.73.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/README.md +5 -3
- package/docs/gates.md +4 -4
- package/docs/guardrails.md +3 -1
- package/docs/playbook.md +3 -8
- package/extensions/dev-flow.ts +179 -718
- package/package.json +1 -1
- package/skills/dev-flow/SKILL.md +4 -7
- package/skills/dev-flow/references/finish.md +3 -7
- package/skills/dev-flow/references/implement.md +24 -37
- package/skills/dev-flow/references/plan.md +0 -4
- package/skills/dev-flow/references/pre-release.md +0 -5
- package/skills/dev-flow/references/reflect.md +1 -6
- package/skills/dev-flow/references/release.md +3 -1
- package/skills/dev-flow/references/start.md +2 -13
- package/src/core.ts +136 -825
- package/src/projectmd.ts +4 -2
- package/docs/stage-agent.md +0 -207
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,
|
|
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";
|
|
@@ -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; tagPattern?: 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
|
-
/** `
|
|
107
|
-
*
|
|
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: "
|
|
127
|
+
bashTimeout: "inject",
|
|
128
128
|
guard: { deny: [], confirm: [], protect: [], forbid: [] },
|
|
129
129
|
};
|
|
130
130
|
|
|
@@ -480,9 +480,6 @@ 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;
|
|
486
483
|
if (rec.wt && rec.wt !== fp && !keep(name)) {
|
|
487
484
|
delete state.checks[name];
|
|
488
485
|
stale.push(name);
|
|
@@ -1037,9 +1034,54 @@ export function bashFlowGuard(o: GuardCtx): string | null {
|
|
|
1037
1034
|
if (writesDefault && o.stage !== "release") return `pushing to ${o.defaultBranch} requires stage "release" (verified feature)${attr}`;
|
|
1038
1035
|
}
|
|
1039
1036
|
if (git("merge") && onMain && o.stage !== "release") return `merging into ${o.defaultBranch} requires stage "release"${attr}`;
|
|
1037
|
+
// Shipping belongs to the release stage: a tag cut (or pushed) while the feature is still before release
|
|
1038
|
+
// leaves the gates unable to record it — flow release then refuses "already tagged" and the flow cannot close.
|
|
1039
|
+
if (o.stage && BEFORE_RELEASE.has(o.stage)) {
|
|
1040
|
+
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}`;
|
|
1041
|
+
if (git("push")) {
|
|
1042
|
+
const refs = o.pushRefs ?? parsePushRefs(gitInvocation(c).pushes);
|
|
1043
|
+
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}`;
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
return null;
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
const BEFORE_RELEASE = new Set<Stage>(["plan", "implement", "pre-release"]);
|
|
1050
|
+
|
|
1051
|
+
/** Does this `git tag` invocation create (or move) a tag? Bare `git tag` and the listing/verify forms only read. */
|
|
1052
|
+
export function tagCreates(command: string): boolean {
|
|
1053
|
+
const m = command.match(/\bgit\s+(?:-C\s+\S+\s+)?tag\b([^;|&\n]*)/);
|
|
1054
|
+
if (!m) return false;
|
|
1055
|
+
const tok = m[1].trim().split(/\s+/).filter(Boolean);
|
|
1056
|
+
if (!tok.length) return false;
|
|
1057
|
+
if (tok.some((t) => /^(-l|--list|-n\d*|--contains|--no-contains|--points-at|--merged|--no-merged|-v|--verify|-d|--delete)$/.test(t))) return false;
|
|
1058
|
+
return true;
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
/** Forge-side shipping (`gh pr merge`, `glab mr merge`, `gh|glab release create`) before the release stage, or null.
|
|
1062
|
+
* Quoted text is prose except inside a head that execs its argument — the same reading as mergeStyleInvocation. */
|
|
1063
|
+
export function releaseOrderInvocation(command: string, stage: Stage | null): string | null {
|
|
1064
|
+
if (!stage || !BEFORE_RELEASE.has(stage)) return null;
|
|
1065
|
+
for (const seg of bashSegments(command)) {
|
|
1066
|
+
if (READ_ONLY_HEADS.has(segHead(seg))) continue;
|
|
1067
|
+
const hay = REEXEC_HEADS.has(segHead(seg)) ? `${seg} ${maskQuoted(seg)}` : maskQuoted(seg);
|
|
1068
|
+
if (/\bgh\s+pr\s+merge\b/.test(hay) || /\bglab\s+mr\s+merge\b/.test(hay))
|
|
1069
|
+
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)`;
|
|
1070
|
+
if (/\b(?:gh|glab)\s+release\s+create\b/.test(hay))
|
|
1071
|
+
return `publishing a forge release is release work — the feature is at ${stage}; run flow release, then flow release-done creates it`;
|
|
1072
|
+
}
|
|
1040
1073
|
return null;
|
|
1041
1074
|
}
|
|
1042
1075
|
|
|
1076
|
+
/** Name of a branch a `git checkout -b/-B` / `git switch -c/-C` creates, or null. */
|
|
1077
|
+
export function branchCreateTarget(command: string): string | null {
|
|
1078
|
+
const m = command.match(/\bgit\s+(?:-C\s+\S+\s+)?(?:checkout|switch)\b([^;|&\n]*)/);
|
|
1079
|
+
if (!m) return null;
|
|
1080
|
+
const tok = m[1].trim().split(/\s+/).filter(Boolean);
|
|
1081
|
+
const i = tok.findIndex((t) => /^(-[bBcC]|--create|--force-create|--orphan)$/.test(t));
|
|
1082
|
+
return i >= 0 && tok[i + 1] ? unquote(tok[i + 1]) : null;
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1043
1085
|
// ------------------------------------------------------- project safety rules
|
|
1044
1086
|
|
|
1045
1087
|
/** One flow-guard rule: `pattern` is a JS regex source (deny/confirm) or a repo-relative path (protect/forbid). */
|
|
@@ -1286,6 +1328,15 @@ const within = (abs: string, dir: string | null) => !!dir && (abs === dir || abs
|
|
|
1286
1328
|
* the guarded checkout, and `repoRoot` keeps a repository that merely lives under the temp dir (every
|
|
1287
1329
|
* smoke-test repo) under the normal stage rules.
|
|
1288
1330
|
*/
|
|
1331
|
+
/** The main checkout a linked worktree shares its history with, from git's answer for the common dir
|
|
1332
|
+
* (`<main>/.git`), or null when there is nothing to remap: git did not answer, or cwd already is that
|
|
1333
|
+
* checkout (a plain clone answers its own dir). */
|
|
1334
|
+
export function mainCheckoutRoot(cwd: string, commonDir: string | null): string | null {
|
|
1335
|
+
if (!commonDir) return null;
|
|
1336
|
+
const main = path.resolve(path.dirname(path.resolve(cwd, commonDir)));
|
|
1337
|
+
return main === path.resolve(cwd) ? null : main;
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1289
1340
|
export function inScratchDir(abs: string, repoRoot?: string | null): boolean {
|
|
1290
1341
|
const real = realAbs(abs);
|
|
1291
1342
|
if (repoRoot) {
|
|
@@ -1368,11 +1419,6 @@ export interface SessionClaim {
|
|
|
1368
1419
|
key: string;
|
|
1369
1420
|
pid: number;
|
|
1370
1421
|
at: string;
|
|
1371
|
-
/** The claiming process's start identity (`processStart`), when the platform has one. A pid is
|
|
1372
|
-
* recycled — a claim left by a crashed pi can name a pid some unrelated process now holds — so a
|
|
1373
|
-
* live pid only counts as the claimant when its start identity still matches. Absent on legacy
|
|
1374
|
-
* claims and on platforms without /proc, which keep the pid-only judgement. */
|
|
1375
|
-
start?: string;
|
|
1376
1422
|
}
|
|
1377
1423
|
|
|
1378
1424
|
/** Whether a process is running (kill 0 only probes existence; EPERM means it exists, foreign-owned). */
|
|
@@ -1385,43 +1431,9 @@ export function pidAlive(pid: number): boolean {
|
|
|
1385
1431
|
}
|
|
1386
1432
|
}
|
|
1387
1433
|
|
|
1388
|
-
/**
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
export function processStart(pid: number, read: (file: string) => string = (f) => readFileSync(f, "utf8")): string | undefined {
|
|
1392
|
-
try {
|
|
1393
|
-
const stat = read(`/proc/${pid}/stat`);
|
|
1394
|
-
const rest = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
1395
|
-
// rest[0] is field 3 (state), so field 22 sits at index 19
|
|
1396
|
-
const st = rest[19];
|
|
1397
|
-
return st && /^\d+$/.test(st) ? st : undefined;
|
|
1398
|
-
} catch {
|
|
1399
|
-
return undefined;
|
|
1400
|
-
}
|
|
1401
|
-
}
|
|
1402
|
-
|
|
1403
|
-
/** True only when another live session holds the claim — its feature can only be taken by an explicit `flow use`, never quietly.
|
|
1404
|
-
* A claim whose pid is alive but whose recorded start identity no longer matches belongs to a dead
|
|
1405
|
-
* session whose pid was recycled: it does not block. */
|
|
1406
|
-
export function claimBlocks(claim: SessionClaim | null, myKey: string, alive: (pid: number) => boolean = pidAlive, startOf: (pid: number) => string | undefined = processStart): boolean {
|
|
1407
|
-
if (!claim || claim.key === myKey || !alive(claim.pid)) return false;
|
|
1408
|
-
if (claim.start) {
|
|
1409
|
-
const now = startOf(claim.pid);
|
|
1410
|
-
if (now !== undefined && now !== claim.start) return false;
|
|
1411
|
-
}
|
|
1412
|
-
return true;
|
|
1413
|
-
}
|
|
1414
|
-
|
|
1415
|
-
/** How old a claim is, in words, for a refusal: "claimed 3 days ago" lets the operator tell a live
|
|
1416
|
-
* session from a stale pid at a glance. Empty when the stamp is unreadable. */
|
|
1417
|
-
export function claimAge(claim: SessionClaim, nowMs: number = Date.now()): string {
|
|
1418
|
-
const t = Date.parse(claim.at);
|
|
1419
|
-
if (!Number.isFinite(t)) return "";
|
|
1420
|
-
const min = Math.max(0, Math.round((nowMs - t) / 60000));
|
|
1421
|
-
if (min < 60) return `${min} min old`;
|
|
1422
|
-
const h = Math.round(min / 60);
|
|
1423
|
-
if (h < 48) return `${h} h old`;
|
|
1424
|
-
return `${Math.round(h / 24)} days old`;
|
|
1434
|
+
/** True only when another live session holds the claim — its feature can only be taken by an explicit `flow use`, never quietly. */
|
|
1435
|
+
export function claimBlocks(claim: SessionClaim | null, myKey: string, alive: (pid: number) => boolean = pidAlive): boolean {
|
|
1436
|
+
return !!claim && claim.key !== myKey && alive(claim.pid);
|
|
1425
1437
|
}
|
|
1426
1438
|
|
|
1427
1439
|
/** Footer glyph per stage: the footer has no room for stage words and no legend of its own (README:Status bar is the legend). */
|
|
@@ -1940,794 +1952,93 @@ export function applyAnswer(partial: Record<string, unknown>, key: string, value
|
|
|
1940
1952
|
}
|
|
1941
1953
|
|
|
1942
1954
|
|
|
1943
|
-
//
|
|
1944
|
-
|
|
1945
|
-
/** Stages whose *work* `flow_stage` may delegate to a disposable sub-session. plan is the
|
|
1946
|
-
* operator dialogue; release/finish carry the Release?/Finish? words — only the heavy middle
|
|
1947
|
-
* stages are delegated, and gates are never delegated: the driving session keeps every gate,
|
|
1948
|
-
* every checkpoint and the claim, so gate integrity never depends on a worker behaving. */
|
|
1949
|
-
export const DELEGABLE_STAGES = ["implement", "pre-release"] as const;
|
|
1950
|
-
export type DelegableStage = (typeof DELEGABLE_STAGES)[number];
|
|
1951
|
-
export function isDelegableStage(s: string): s is DelegableStage {
|
|
1952
|
-
return (DELEGABLE_STAGES as readonly string[]).includes(s);
|
|
1953
|
-
}
|
|
1954
|
-
|
|
1955
|
-
/** Sentinel line that ends a stage worker's final message — the parent digests exactly this,
|
|
1956
|
-
* not the whole run, so one stage's hundred tool calls cost the driving session one bounded block. */
|
|
1957
|
-
export const STAGE_REPORT_HEAD = "STAGE REPORT";
|
|
1958
|
-
|
|
1959
|
-
/** The sections of the report block. The preserve-list mirrors flowCompactInstructions' demands:
|
|
1960
|
-
* a worker's nuance lives nowhere else, so what is not written here is lost on purpose. */
|
|
1961
|
-
export const STAGE_REPORT_CONTRACT = `Write, as the very last lines of your final message, exactly this block (empty sections say \`none\`):
|
|
1962
|
-
${STAGE_REPORT_HEAD}
|
|
1963
|
-
done:
|
|
1964
|
-
- <what you actually did, one line per item>
|
|
1965
|
-
files:
|
|
1966
|
-
- <path> — <what changed there>
|
|
1967
|
-
notes:
|
|
1968
|
-
- <operator answers/decisions not yet recorded by a gate · reasons for uncommitted changes · the exact next action>
|
|
1969
|
-
blockers:
|
|
1970
|
-
- <what would fail Verified? right now> (or: none)`;
|
|
1971
|
-
|
|
1972
|
-
export interface StageReport {
|
|
1973
|
-
done: string[];
|
|
1974
|
-
files: string[];
|
|
1975
|
-
notes: string[];
|
|
1976
|
-
blockers: string[];
|
|
1977
|
-
/** true when the worker never emitted the block — the caller must treat the raw tail as suspect. */
|
|
1978
|
-
missing: boolean;
|
|
1979
|
-
/** bounded tail of the worker's final message (kept for the digest when missing, else for reference). */
|
|
1980
|
-
rawTail: string;
|
|
1981
|
-
}
|
|
1982
|
-
|
|
1983
|
-
/** Digest a stage worker's final message into the report contract. Lenient by design: a worker
|
|
1984
|
-
* that skipped the block yields `missing: true` plus its tail, never a throw at the end of a long stage. */
|
|
1985
|
-
export function parseStageReport(text: string): StageReport {
|
|
1986
|
-
const lines = (text ?? "").split("\n");
|
|
1987
|
-
let start = -1;
|
|
1988
|
-
for (let i = lines.length - 1; i >= 0; i--) {
|
|
1989
|
-
if (/^\s*[*_#>\s]*STAGE\s+REPORT[*_\s]*$/i.test(lines[i])) { start = i; break; }
|
|
1990
|
-
}
|
|
1991
|
-
const rep: StageReport = {
|
|
1992
|
-
done: [], files: [], notes: [], blockers: [],
|
|
1993
|
-
missing: start < 0,
|
|
1994
|
-
rawTail: lines.slice(-15).join("\n").slice(-600),
|
|
1995
|
-
};
|
|
1996
|
-
if (start < 0) return rep;
|
|
1997
|
-
type Section = "done" | "files" | "notes" | "blockers";
|
|
1998
|
-
let section: Section | null = null;
|
|
1999
|
-
for (const line of lines.slice(start + 1)) {
|
|
2000
|
-
const h = /^(done|files|notes|blockers)\s*[::]\s*$/i.exec(line.trim());
|
|
2001
|
-
if (h) { section = h[1].toLowerCase() as Section; continue; }
|
|
2002
|
-
const b = /^\s*[-*]\s+(.+)$/.exec(line);
|
|
2003
|
-
if (b && section) rep[section].push(b[1].trim());
|
|
2004
|
-
}
|
|
2005
|
-
rep.blockers = rep.blockers.filter((b) => !/^(none|no blockers?|n\/a|nothing)[-.\s]*$/i.test(b));
|
|
2006
|
-
return rep;
|
|
2007
|
-
}
|
|
2008
|
-
|
|
2009
|
-
/** Bounded, parent-facing digest of a worker run. `cap` exists so one delegation cannot spend
|
|
2010
|
-
* the context it just saved; the full transcript stays on disk, named in the caller's output. */
|
|
2011
|
-
export function renderStageReport(r: StageReport, cap = 4000): string {
|
|
2012
|
-
const parts: string[] = [];
|
|
2013
|
-
if (r.missing) parts.push("worker ended WITHOUT the STAGE REPORT block — digesting its raw tail, verify before trusting it:", "```", r.rawTail, "```");
|
|
2014
|
-
for (const s of ["done", "files", "notes"] as const)
|
|
2015
|
-
if (r[s].length) parts.push(`${s}:`, ...r[s].map((x) => `- ${x}`));
|
|
2016
|
-
if (r.blockers.length) parts.push("BLOCKERS:", ...r.blockers.map((x) => `- ${x}`));
|
|
2017
|
-
if (!parts.length) parts.push("(report block was empty)");
|
|
2018
|
-
const out = parts.join("\n");
|
|
2019
|
-
return out.length <= cap ? out : `${out.slice(0, cap)}\n…(digest truncated — full worker transcript on disk)`;
|
|
2020
|
-
}
|
|
2021
|
-
|
|
2022
|
-
export interface StageBriefInput {
|
|
2023
|
-
slug: string;
|
|
2024
|
-
stage: DelegableStage;
|
|
2025
|
-
/** absolute path of the feature worktree — the worker's whole world. */
|
|
2026
|
-
workDir: string;
|
|
2027
|
-
/** absolute path of plan/plan.md in the main checkout (the worktree does not carry it). */
|
|
2028
|
-
planFile: string;
|
|
2029
|
-
/** the stage playbook reference contents ("" when the stage has none). */
|
|
2030
|
-
referenceText: string;
|
|
2031
|
-
/** truth as the driving session saw it: `flow status --json` output. */
|
|
2032
|
-
statusJson: string;
|
|
2033
|
-
/** `git status --porcelain -b` taken in the worktree before the worker starts. */
|
|
2034
|
-
gitSummary: string;
|
|
2035
|
-
/** what the parent session passes on: operator answers, decisions, warnings, the next action. */
|
|
2036
|
-
note?: string;
|
|
2037
|
-
}
|
|
2038
|
-
|
|
2039
|
-
/** The worker's complete brief: role, boundaries, on-disk truth, stage playbook, handoff note,
|
|
2040
|
-
* and the closing contract. Pure — the wiring reads the files and runs the git/status calls. */
|
|
2041
|
-
export function buildStageBrief(i: StageBriefInput): string {
|
|
2042
|
-
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).
|
|
2043
|
-
|
|
2044
|
-
Boundaries (the guard enforces these; do not work around them):
|
|
2045
|
-
- 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.
|
|
2046
|
-
- .dev-flow state files (state.json, claim.json, project.md) are read-only.
|
|
2047
|
-
- 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}.
|
|
2048
|
-
|
|
2049
|
-
Start by reading the plan — ${i.planFile} — and whatever it points to.
|
|
2050
|
-
|
|
2051
|
-
Flow truth (\`flow status --json\` from the driving session):
|
|
2052
|
-
${i.statusJson}
|
|
2053
|
-
|
|
2054
|
-
Worktree state (\`git status --porcelain -b\`):
|
|
2055
|
-
${i.gitSummary || "(clean)"}
|
|
2056
|
-
|
|
2057
|
-
The stage playbook — what this stage owes when it exits (the gates you cannot see):
|
|
2058
|
-
${i.referenceText || "(this stage has no playbook reference)"}
|
|
2059
|
-
|
|
2060
|
-
Handoff note from the driving session (operator answers, decisions, warnings, the exact next action):
|
|
2061
|
-
${i.note?.trim() || "(none — the plan and the status above are your whole brief)"}
|
|
2062
|
-
|
|
2063
|
-
When you are done — finished OR blocked — stop doing work and close with the report.
|
|
2064
|
-
${STAGE_REPORT_CONTRACT}`;
|
|
2065
|
-
}
|
|
2066
|
-
|
|
2067
|
-
/** Stage-worker budget bounds, in minutes. The default is deliberately generous (a gate may wait
|
|
2068
|
-
* 15 min on one deploy; a stage is a whole stage); `budgetMin` is the per-call, operator-visible
|
|
2069
|
-
* override. A playbook knob would move the default project-side — deliberately a later flow. */
|
|
2070
|
-
export const STAGE_BUDGET_DEFAULT_MIN = 45;
|
|
2071
|
-
export const STAGE_BUDGET_MIN_MIN = 5;
|
|
2072
|
-
export const STAGE_BUDGET_MAX_MIN = 120;
|
|
2073
|
-
export function clampStageBudgetMin(raw?: unknown): number {
|
|
2074
|
-
const n = typeof raw === "number" && Number.isFinite(raw) ? Math.round(raw) : STAGE_BUDGET_DEFAULT_MIN;
|
|
2075
|
-
return Math.min(STAGE_BUDGET_MAX_MIN, Math.max(STAGE_BUDGET_MIN_MIN, n));
|
|
2076
|
-
}
|
|
2077
|
-
|
|
2078
|
-
/** `mm:ss` for heartbeat, live-log and status lines. */
|
|
2079
|
-
export function stageElapsedLabel(ms: number): string {
|
|
2080
|
-
const s = Math.max(0, Math.floor(ms / 1000));
|
|
2081
|
-
return `${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`;
|
|
2082
|
-
}
|
|
2083
|
-
|
|
2084
|
-
/** One-summarization of a tool call's args for the live line: bash shows the command, edit/write the
|
|
2085
|
-
* path, anything else compact JSON — always capped. */
|
|
2086
|
-
export function summarizeToolArgs(args: unknown): string {
|
|
2087
|
-
const a = args as Record<string, unknown> | undefined;
|
|
2088
|
-
let s = "";
|
|
2089
|
-
if (a && typeof a === "object") {
|
|
2090
|
-
if (typeof a.command === "string") s = a.command;
|
|
2091
|
-
else if (typeof a.path === "string") s = a.path;
|
|
2092
|
-
else { try { s = JSON.stringify(a); } catch { s = ""; } }
|
|
2093
|
-
}
|
|
2094
|
-
s = s.replace(/\s+/g, " ").trim();
|
|
2095
|
-
return s.length > 60 ? `${s.slice(0, 57)}…` : s;
|
|
2096
|
-
}
|
|
2097
|
-
|
|
2098
|
-
/** One appended line of `.dev-flow/<slug>/stage-live.log` — the tail-able activity floor that works
|
|
2099
|
-
* on hosts where no tool partial ever renders. */
|
|
2100
|
-
export function stageLiveLine(elapsedMs: number, toolName: string, argsSummary: string): string {
|
|
2101
|
-
return `[+${stageElapsedLabel(elapsedMs)}] ${toolName}${argsSummary ? ` — ${argsSummary}` : ""}`;
|
|
2102
|
-
}
|
|
1955
|
+
// ------------------------------------------------------------- stage worker (flow_stage)
|
|
2103
1956
|
|
|
2104
|
-
|
|
2105
|
-
* the truth, stop starting new units. Beats an abort by one clean commit. */
|
|
2106
|
-
export function stageInterruptSteer(budgetMin: number): string {
|
|
2107
|
-
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.`;
|
|
2108
|
-
}
|
|
1957
|
+
export type WorkerOp = "implement" | "review";
|
|
2109
1958
|
|
|
2110
|
-
|
|
1959
|
+
/** Stages where each worker op is legal: implement edits only while the flow is at implement; a review
|
|
1960
|
+
* (read-only, advisory) is useful before verify and again before release. */
|
|
1961
|
+
export const WORKER_OP_STAGES: Record<WorkerOp, Stage[]> = { implement: ["implement"], review: ["implement", "pre-release"] };
|
|
2111
1962
|
|
|
2112
|
-
/**
|
|
2113
|
-
|
|
2114
|
-
* without handing over a gate or a fix; `status` reads the live run and needs no worker at all. */
|
|
2115
|
-
export const WORKER_OPS = ["run", "verify", "reflect", "status"] as const;
|
|
2116
|
-
export type WorkerOp = (typeof WORKER_OPS)[number];
|
|
2117
|
-
export function isWorkerOp(s: string): s is WorkerOp {
|
|
2118
|
-
return (WORKER_OPS as readonly string[]).includes(s);
|
|
2119
|
-
}
|
|
1963
|
+
/** Default wall-clock budget per op, in minutes. */
|
|
1964
|
+
export const WORKER_BUDGET_MIN: Record<WorkerOp, number> = { implement: 60, review: 30 };
|
|
2120
1965
|
|
|
2121
|
-
/**
|
|
2122
|
-
|
|
2123
|
-
* operator-set 30 — smaller default, same steer at 75%. */
|
|
2124
|
-
export const WORKER_OP_BUDGET_MIN: Record<WorkerOp, number> = { run: STAGE_BUDGET_DEFAULT_MIN, verify: 30, reflect: 30, status: STAGE_BUDGET_DEFAULT_MIN };
|
|
1966
|
+
/** Times a worker that stopped without its REPORT is told to keep going before the run gives up. */
|
|
1967
|
+
export const WORKER_NUDGES = 2;
|
|
2125
1968
|
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
export const WORKER_OP_TOOLS: Record<WorkerOp, readonly string[]> = {
|
|
2130
|
-
run: ["read", "bash", "edit", "write"],
|
|
2131
|
-
verify: ["read", "bash"],
|
|
2132
|
-
reflect: ["read", "bash"],
|
|
2133
|
-
status: [],
|
|
1969
|
+
export const clampBudgetMin = (n: unknown, op: WorkerOp): number => {
|
|
1970
|
+
const v = typeof n === "number" && Number.isFinite(n) ? n : WORKER_BUDGET_MIN[op];
|
|
1971
|
+
return Math.min(180, Math.max(5, Math.round(v)));
|
|
2134
1972
|
};
|
|
2135
1973
|
|
|
2136
|
-
/**
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
export function workerOpError(op: WorkerOp, st: { stage: Stage; approvals: Record<string, string> }): string | null {
|
|
2142
|
-
if (op === "verify" && st.stage !== "implement")
|
|
2143
|
-
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`;
|
|
2144
|
-
if (op === "reflect" && !(st.stage === "release" && st.approvals.release))
|
|
2145
|
-
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>/`;
|
|
2146
|
-
return null;
|
|
2147
|
-
}
|
|
2148
|
-
|
|
2149
|
-
/** Sentinel line that ends a verify worker's final message — the sibling of STAGE_REPORT_HEAD. The
|
|
2150
|
-
* verdict is machine-read: it is what the verify gate demands, so prose approval is never enough. */
|
|
2151
|
-
export const VERIFY_REPORT_HEAD = "VERIFY REPORT";
|
|
2152
|
-
|
|
2153
|
-
/** The verify worker's closing contract. `verdict` is a closed set on purpose: anything the parser
|
|
2154
|
-
* cannot read as pass/fail is treated as NO pass, so a hedged report never stamps the gate. */
|
|
2155
|
-
export const VERIFY_REPORT_CONTRACT = `Close your final message with exactly this block (empty sections say \`none\`):
|
|
2156
|
-
${VERIFY_REPORT_HEAD}
|
|
2157
|
-
verdict: pass | fail
|
|
2158
|
-
findings:
|
|
2159
|
-
- <one line per problem: what the plan requires, what the code does instead, file:line>
|
|
2160
|
-
evidence:
|
|
2161
|
-
- <one line per thing you ran: the command and what it printed>`;
|
|
2162
|
-
|
|
2163
|
-
export interface VerifyReport {
|
|
2164
|
-
/** null = no readable verdict (missing block, or a hedge where pass|fail was demanded). */
|
|
2165
|
-
verdict: "pass" | "fail" | null;
|
|
2166
|
-
findings: string[];
|
|
2167
|
-
evidence: string[];
|
|
2168
|
-
/** true when the worker never emitted the block. */
|
|
2169
|
-
missing: boolean;
|
|
2170
|
-
rawTail: string;
|
|
2171
|
-
}
|
|
2172
|
-
|
|
2173
|
-
/** Digest a verify worker's final message. A missing block or an unreadable verdict is a NON-pass —
|
|
2174
|
-
* the caller must not stamp the gate on anything it did not read. */
|
|
2175
|
-
export function parseVerifyReport(text: string): VerifyReport {
|
|
2176
|
-
const lines = (text ?? "").split("\n");
|
|
2177
|
-
let start = -1;
|
|
2178
|
-
for (let i = lines.length - 1; i >= 0; i--) {
|
|
2179
|
-
if (/^\s*[*_#>\s]*VERIFY\s+REPORT[*_\s]*$/i.test(lines[i])) { start = i; break; }
|
|
2180
|
-
}
|
|
2181
|
-
const rep: VerifyReport = { verdict: null, findings: [], evidence: [], missing: start < 0, rawTail: lines.slice(-15).join("\n").slice(-600) };
|
|
2182
|
-
if (start < 0) return rep;
|
|
2183
|
-
type Section = "findings" | "evidence";
|
|
2184
|
-
let section: Section | null = null;
|
|
2185
|
-
for (const line of lines.slice(start + 1)) {
|
|
2186
|
-
const v = /^\s*verdict\s*[:=]\s*([A-Za-z]+)/i.exec(line.trim());
|
|
2187
|
-
if (v) {
|
|
2188
|
-
const word = v[1].toLowerCase();
|
|
2189
|
-
rep.verdict = word === "pass" || word === "passes" || word === "passed" ? "pass" : word === "fail" || word === "failed" || word === "failing" ? "fail" : null;
|
|
2190
|
-
continue;
|
|
2191
|
-
}
|
|
2192
|
-
const h = /^(findings|evidence)\s*[:=]\s*$/i.exec(line.trim());
|
|
2193
|
-
if (h) { section = h[1].toLowerCase() as Section; continue; }
|
|
2194
|
-
const b = /^\s*[-*]\s+(.+)$/.exec(line);
|
|
2195
|
-
if (b && section) rep[section].push(b[1].trim());
|
|
2196
|
-
}
|
|
2197
|
-
rep.findings = rep.findings.filter((f) => !/^(none|no findings?|n\/a|nothing)[-.\s]*$/i.test(f));
|
|
2198
|
-
return rep;
|
|
2199
|
-
}
|
|
2200
|
-
|
|
2201
|
-
/** Parent-facing digest of a verify run — bounded like the stage digest; the full transcript is on
|
|
2202
|
-
* disk and named by the caller. */
|
|
2203
|
-
export function renderVerifyReport(r: VerifyReport, cap = 4000): string {
|
|
2204
|
-
const parts: string[] = [];
|
|
2205
|
-
if (r.missing) parts.push("verify worker ended WITHOUT the VERIFY REPORT block — there is NO verdict, the tree is not verified:", "```", r.rawTail, "```");
|
|
2206
|
-
else if (!r.verdict) parts.push("VERIFY REPORT carried no readable verdict (pass | fail was required) — treated as NO pass:", "```", r.rawTail, "```");
|
|
2207
|
-
else parts.push(`verdict: ${r.verdict.toUpperCase()}`);
|
|
2208
|
-
if (r.findings.length) parts.push("findings:", ...r.findings.map((x) => `- ${x}`));
|
|
2209
|
-
if (r.evidence.length) parts.push("evidence:", ...r.evidence.map((x) => `- ${x}`));
|
|
2210
|
-
if (!parts.length) parts.push("(report block was empty)");
|
|
2211
|
-
const out = parts.join("\n");
|
|
2212
|
-
return out.length <= cap ? out : `${out.slice(0, cap)}\n…(digest truncated — full worker transcript on disk)`;
|
|
2213
|
-
}
|
|
2214
|
-
|
|
2215
|
-
/** Key the verify-worker PASS rides under inside state.checks. Living there is not a shortcut, it is
|
|
2216
|
-
* the point: the PASS must die exactly when a tier-1 record dies (an edit-tool clear, a fingerprint
|
|
2217
|
-
* that moved), so the friction is precise — one edit, one re-run — and never sticky. */
|
|
2218
|
-
export const VERIFY_STAMP = "verify";
|
|
2219
|
-
|
|
2220
|
-
/** Stamp a PASS over the tree as it is now (fp = worktreeFingerprint; null = git could not answer,
|
|
2221
|
-
* and an unprovable stamp is a stamp that never looks stale — same rule as freshenChecks). */
|
|
2222
|
-
export function recordVerifyPass(state: FlowState, at: string, fp: string | null): void {
|
|
2223
|
-
state.checks[VERIFY_STAMP] = { ok: true, at, ...(fp ? { wt: fp } : {}) };
|
|
2224
|
-
}
|
|
2225
|
-
|
|
2226
|
-
/** How each op's session announces itself in the picker — the stage-line glyph vocabulary reused for
|
|
2227
|
-
* worker names, so a row reads as a role at a glance instead of N identical "stage worker" lines. */
|
|
2228
|
-
export const WORKER_OP_GLYPH: Record<WorkerOp, string> = { run: "🔨", verify: "🔍", reflect: "🏁", status: "👁" };
|
|
2229
|
-
|
|
2230
|
-
/** A driver-supplied purpose, made safe for a session name: control chars gone, whitespace collapsed,
|
|
2231
|
-
* clamped to ~32 chars on a word boundary. "" when nothing meaningful is left. */
|
|
2232
|
-
export function sanitizeWorkerLabel(raw: string): string {
|
|
2233
|
-
const s = raw.replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ").trim();
|
|
2234
|
-
if (s.length <= 32) return s;
|
|
2235
|
-
const cut = s.slice(0, 32);
|
|
2236
|
-
const at = cut.lastIndexOf(" ");
|
|
2237
|
-
return (at >= 16 ? cut.slice(0, at) : cut).trim();
|
|
2238
|
-
}
|
|
2239
|
-
|
|
2240
|
-
/** Session-name grammar: live `⏳ 🔨 #2 · wire ops`, done `✓ 🔨 #2 · 3 commits · wire ops`,
|
|
2241
|
-
* `✓ 🔍 · stamp attack · PASS`, `✗ 🔨 #3 · hard-cut`. The final rename answers "how did it end?"
|
|
2242
|
-
* without opening the row; the ordinal separates re-delegations when no label was given. */
|
|
2243
|
-
export function workerName(mark: string, glyph: string, seq: number | null, label: string, outcome?: string | null): string {
|
|
2244
|
-
const core = `${glyph}${seq ? ` #${seq}` : ""}${outcome ? ` · ${outcome}` : ""}${label ? ` · ${label}` : ""}`;
|
|
2245
|
-
return `${mark} ${core}`;
|
|
2246
|
-
}
|
|
2247
|
-
|
|
2248
|
-
/** Content hash of a feature's plan/ dir (sorted relpath + bytes; "" stable when absent). The verify
|
|
2249
|
-
* verdict was written AGAINST the plan, so a mid-stage plan edit must void the PASS exactly like a
|
|
2250
|
-
* worktree edit — the stamp fingerprint hashes the worktree TOGETHER WITH this. */
|
|
2251
|
-
export function planFingerprint(dir: string): string {
|
|
2252
|
-
const h = createHash("sha256");
|
|
2253
|
-
// absent and empty must not collide — an accidentally deleted plan dir is a different ground than an emptied one
|
|
2254
|
-
h.update(existsSync(dir) ? "present\0" : "absent\0");
|
|
2255
|
-
const walk = (d: string, rel: string) => {
|
|
2256
|
-
// the entry kind rides as a control char after the name — a text marker ("@link") would collide
|
|
2257
|
-
// with a real file literally named that, control chars in a name are the pathological remainder
|
|
2258
|
-
for (const e of readdirSync(d, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
2259
|
-
const p = path.join(d, e.name);
|
|
2260
|
-
if (e.isDirectory()) {
|
|
2261
|
-
h.update(`${rel}${e.name}\x01`);
|
|
2262
|
-
walk(p, `${rel}${e.name}/`);
|
|
2263
|
-
} else if (e.isSymbolicLink()) {
|
|
2264
|
-
// a symlinked plan hides its content behind the entry — hash the link AND what it resolves to
|
|
2265
|
-
h.update(`${rel}${e.name}\x02`).update(readlinkSync(p));
|
|
2266
|
-
try {
|
|
2267
|
-
h.update(readFileSync(p));
|
|
2268
|
-
} catch {
|
|
2269
|
-
/* dangling link: the target string is all there is */
|
|
2270
|
-
}
|
|
2271
|
-
} else if (e.isFile()) h.update(`${rel}${e.name}\x00`).update(readFileSync(p));
|
|
2272
|
-
else h.update(`${rel}${e.name}\x03`);
|
|
2273
|
-
}
|
|
2274
|
-
};
|
|
2275
|
-
if (existsSync(dir)) walk(dir, "");
|
|
2276
|
-
return h.digest("hex").slice(0, 16);
|
|
2277
|
-
}
|
|
2278
|
-
|
|
2279
|
-
/** A PASS the verify gate may accept? docs-mode flows are exempt exactly like tier-1 checks: a docs
|
|
2280
|
-
* flow runs no project command, so there is nothing for a checker to check beyond the operator. */
|
|
2281
|
-
export function verifyStampMissing(state: FlowState): boolean {
|
|
2282
|
-
if (state.docs) return false;
|
|
2283
|
-
return !state.checks[VERIFY_STAMP]?.ok;
|
|
2284
|
-
}
|
|
2285
|
-
|
|
2286
|
-
/** The verify gate's refusal line for a missing PASS — printed with the demand spelled out, because
|
|
2287
|
-
* the operator's question must never be asked on a tree nothing independent has looked at. */
|
|
2288
|
-
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)`;
|
|
2289
|
-
|
|
2290
|
-
/** The durable worker index inside .dev-flow/<slug>/stage-sessions/ — one line per finished worker. */
|
|
2291
|
-
export const TRANSCRIPTS_FILE = "transcripts.log";
|
|
2292
|
-
|
|
2293
|
-
/** `worker transcript: …` line appended to .dev-flow/<slug>/stage-sessions/transcripts.log — the
|
|
2294
|
-
* durable index the reflect worker reads (until now a transcript path lived only in the parent's
|
|
2295
|
-
* tool result, i.e. only as long as that session's context). */
|
|
2296
|
-
export function workerTranscriptLine(at: string, op: string, file: string): string {
|
|
2297
|
-
return `[${at}] worker transcript (${op}): ${file}`;
|
|
2298
|
-
}
|
|
2299
|
-
|
|
2300
|
-
/** Parse transcripts.log back into entries; anything unrecognised is skipped, the log is append-only
|
|
2301
|
-
* and hand-editable. Missing files are the caller's problem (a stale path still tells a reader a
|
|
2302
|
-
* worker ran). */
|
|
2303
|
-
export function parseWorkerTranscripts(text: string): { at: string; op: string; path: string }[] {
|
|
2304
|
-
const out: { at: string; op: string; path: string }[] = [];
|
|
2305
|
-
for (const line of (text ?? "").split("\n")) {
|
|
2306
|
-
const m = /^\s*\[(.*?)\]\s*worker transcript(?: \(([^)]*)\))?:\s*(\S+)/.exec(line);
|
|
2307
|
-
if (m) out.push({ at: m[1], op: m[2] ?? "run", path: m[3] });
|
|
2308
|
-
}
|
|
2309
|
-
return out;
|
|
2310
|
-
}
|
|
2311
|
-
|
|
2312
|
-
/** How many live lines the card and `op: "status"` show: enough to see what the worker is doing,
|
|
2313
|
-
* bounded so a long stage never spends the context the delegation just saved (R6). */
|
|
2314
|
-
export const LIVE_TAIL_ITEMS = 8;
|
|
2315
|
-
/** One live line's cap — worker output is signal in a tail, noise in bulk. */
|
|
2316
|
-
const LIVE_LINE_CAP = 110;
|
|
2317
|
-
|
|
2318
|
-
/** One line of a worker's assistant prose, for the live tail: last non-empty line only (a worker
|
|
2319
|
-
* narrating a plan would otherwise drown its own tool activity). */
|
|
2320
|
-
export function stageLiveAssistantLine(elapsedMs: number, text: string): string {
|
|
2321
|
-
const lines = (text ?? "").split("\n").map((l) => l.trim()).filter(Boolean);
|
|
2322
|
-
if (!lines.length) return "";
|
|
2323
|
-
// its own shape, not stageLiveLine's: prose is not `tool — args`, an em dash in front of every
|
|
2324
|
-
// sentence the worker wrote would read as a tool call that happened to talk
|
|
2325
|
-
return `[+${stageElapsedLabel(elapsedMs)}] ✎ ${liveClip(lines[lines.length - 1])}`;
|
|
2326
|
-
}
|
|
2327
|
-
/** A finished tool call: ✓/✗ plus one line of what came back — the difference between "it is running"
|
|
2328
|
-
* and "it is getting somewhere". */
|
|
2329
|
-
export function stageLiveResultLine(elapsedMs: number, toolName: string, ok: boolean, summary: string): string {
|
|
2330
|
-
return stageLiveLine(elapsedMs, `${ok ? "✓" : "✗"} ${toolName}`, liveClip(summary));
|
|
2331
|
-
}
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
export function liveClip(s: string, cap = LIVE_LINE_CAP): string {
|
|
2335
|
-
const one = (s ?? "").replace(/\s+/g, " ").trim();
|
|
2336
|
-
return one.length > cap ? `${one.slice(0, cap - 1)}…` : one;
|
|
2337
|
-
}
|
|
2338
|
-
|
|
2339
|
-
/** The bounded tail: `… M earlier items` then the last `max` lines (empty lines never counted —
|
|
2340
|
-
* a skipped assistant narration must not push real activity off the card). */
|
|
2341
|
-
export function liveTail(lines: string[], max = LIVE_TAIL_ITEMS): string[] {
|
|
2342
|
-
const kept = lines.filter(Boolean);
|
|
2343
|
-
if (kept.length <= max) return kept;
|
|
2344
|
-
return [`… ${kept.length - max} earlier items`, ...kept.slice(-max)];
|
|
2345
|
-
}
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
/** Everything the live tool card needs to draw one frame. The card is the guaranteed visibility
|
|
2349
|
-
* surface (it renders in the driver's own transcript on every host), so it is built from plain
|
|
2350
|
-
* strings here and wrapped into components by the extension — the same lines reach a host that only
|
|
2351
|
-
* shows the update's text (pi-web) and the no-UI fallback `op: "status"`. */
|
|
2352
|
-
export interface StageCardView {
|
|
2353
|
-
kind: string;
|
|
2354
|
-
slug: string;
|
|
2355
|
-
elapsedMs: number;
|
|
2356
|
-
budgetMin: number;
|
|
2357
|
-
softFired?: boolean;
|
|
2358
|
-
tail?: string[];
|
|
2359
|
-
usage?: string;
|
|
2360
|
-
state?: "running" | "done" | "failed";
|
|
2361
|
-
verdict?: "pass" | "fail" | null;
|
|
2362
|
-
note?: string;
|
|
2363
|
-
transcript?: string;
|
|
2364
|
-
/** settled card only: the flow's other workers, already rendered by `workerFamily`. */
|
|
2365
|
-
family?: string[];
|
|
2366
|
-
/** heading for `family` when the rows came from somewhere coarser than pi's listing. */
|
|
2367
|
-
familyHeading?: string;
|
|
2368
|
-
}
|
|
2369
|
-
|
|
2370
|
-
/** One frame of the worker card: header (what · where · clock against budget), the bounded live tail,
|
|
2371
|
-
* the verdict once there is one, and what it cost. Expanded widens the tail and names the transcript. */
|
|
2372
|
-
export function stageCardLines(v: StageCardView, expanded = false): string[] {
|
|
2373
|
-
const glyph = v.state === "failed" ? "✗" : v.state === "done" ? "✓" : "⏳";
|
|
2374
|
-
const out = [`${glyph} ${v.kind} · ${v.slug} · ${stageElapsedLabel(v.elapsedMs)}/${v.budgetMin}m${v.softFired ? " · closing out" : ""}`];
|
|
2375
|
-
if (v.note) out.push(`note: ${liveClip(v.note, 80)}`);
|
|
2376
|
-
out.push(...liveTail(v.tail ?? [], expanded ? LIVE_TAIL_ITEMS * 4 : LIVE_TAIL_ITEMS));
|
|
2377
|
-
if (v.verdict) out.push(`verdict: ${v.verdict.toUpperCase()}`);
|
|
2378
|
-
if (v.usage) out.push(v.usage);
|
|
2379
|
-
if (expanded && v.transcript) out.push(`transcript: ${v.transcript}`);
|
|
2380
|
-
// the family only on the settled card: listing a session directory is IO, and a live frame
|
|
2381
|
-
// redraws on every worker tool call — a running run must not pay for a directory read
|
|
2382
|
-
if (expanded && v.family?.length) out.push(v.familyHeading ?? familyHeading(), ...v.family);
|
|
2383
|
-
return out;
|
|
2384
|
-
}
|
|
2385
|
-
|
|
2386
|
-
/** One worker session as pi's own session listing describes it. dev-flow keeps no lineage index
|
|
2387
|
-
* of its own: the `parentSession` link in a session header *is* the record, and pi's picker threads
|
|
2388
|
-
* on it. The extension reads pi's types and maps them onto this pi-free shape so the logic here
|
|
2389
|
-
* stays unit-testable. */
|
|
2390
|
-
export interface WorkerSessionRow {
|
|
2391
|
-
/** the worker's session file */
|
|
2392
|
-
path: string;
|
|
2393
|
-
/** the parent link as pi recorded it (`parentSession`); absent = not somebody's child */
|
|
2394
|
-
parent?: string | null;
|
|
2395
|
-
/** the picker display name — it carries the ⏳/✓/✗ and the outcome the driver stamps on it */
|
|
2396
|
-
name?: string;
|
|
2397
|
-
messageCount?: number;
|
|
2398
|
-
/** file mtime, however the host hands it over (pi gives a Date; tests give a number) */
|
|
2399
|
-
modified?: Date | number | string;
|
|
2400
|
-
}
|
|
2401
|
-
|
|
2402
|
-
/** How many workers one render lists before it folds the older ones. */
|
|
2403
|
-
export const WORKER_FAMILY_ITEMS = 12;
|
|
2404
|
-
|
|
2405
|
-
/** Family rendering options: `exclude` drops one transcript — the live or just-finished run, which
|
|
2406
|
-
* the caller already shows as its own section or its own line. */
|
|
2407
|
-
export interface WorkerFamilyOptions {
|
|
2408
|
-
exclude?: string;
|
|
2409
|
-
}
|
|
2410
|
-
|
|
2411
|
-
/** The heading over a family list — the one place the wording lives, so the status text and the card
|
|
2412
|
-
* cannot drift, and so a list that came from the ledger (no message counts, no renames) says so. */
|
|
2413
|
-
export function familyHeading(o: { live?: boolean; ledger?: boolean } = {}): string {
|
|
2414
|
-
return `${o.live ? "other workers this session spawned" : "workers this session spawned"}${o.ledger ? " (from the flow's ledger — this host has no session file to nest)" : ""}:`;
|
|
2415
|
-
}
|
|
2416
|
-
|
|
2417
|
-
/** The same session file written two ways is still one session (separators, trailing slash, and on
|
|
2418
|
-
* Windows the case of the drive letter). pi's own picker canonicalizes the same idea. */
|
|
2419
|
-
export function sessionPathKey(p: string): string {
|
|
2420
|
-
const k = path.resolve(p).replace(/[\\/]+$/, "");
|
|
2421
|
-
return process.platform === "win32" ? k.toLowerCase() : k;
|
|
2422
|
-
}
|
|
2423
|
-
|
|
2424
|
-
function sessionTime(row: WorkerSessionRow): number {
|
|
2425
|
-
const raw = row.modified instanceof Date ? row.modified.getTime() : typeof row.modified === "number" ? row.modified : row.modified ? Date.parse(row.modified) : 0;
|
|
2426
|
-
return Number.isFinite(raw) ? raw : 0;
|
|
2427
|
-
}
|
|
2428
|
-
|
|
2429
|
-
/**
|
|
2430
|
-
* The family — every stage worker this session spawned, newest first, one line each.
|
|
2431
|
-
*
|
|
2432
|
-
* A stage worker is a real pi session whose header carries `parentSession` pointing at the driver's
|
|
2433
|
-
* own file, so pi's picker nests it under the driver by itself (Threaded sort). This reads the same
|
|
2434
|
-
* fact back for every surface that has no tree: the `flow_stage` card and `op: "status"`. Nothing is
|
|
2435
|
-
* stored here, so a renamed worker (`✓ 🔍 · PASS · stamp attack`) reads back renamed, and workers a
|
|
2436
|
-
* previous session already delegated show up next to this one's.
|
|
2437
|
-
*/
|
|
2438
|
-
export function workerFamily(rows: WorkerSessionRow[], driverFile: string | null | undefined, opts: WorkerFamilyOptions = {}): string[] {
|
|
2439
|
-
if (!driverFile) return [];
|
|
2440
|
-
const max = WORKER_FAMILY_ITEMS;
|
|
2441
|
-
const drop = opts.exclude ? sessionPathKey(opts.exclude) : null;
|
|
2442
|
-
const mine = rows
|
|
2443
|
-
.filter((r) => r.parent && sessionPathKey(r.parent) === sessionPathKey(driverFile) && (!drop || sessionPathKey(r.path) !== drop))
|
|
2444
|
-
.sort((a, b) => sessionTime(b) - sessionTime(a));
|
|
2445
|
-
const shown = mine.slice(0, max);
|
|
2446
|
-
const lines = shown.map((r) => {
|
|
2447
|
-
const at = sessionTime(r);
|
|
2448
|
-
return `${r.name?.trim() || "(unnamed worker)"} · ${r.messageCount ?? 0} msgs · ${at ? localStamp(at) : "time unknown"} · ${r.path}`;
|
|
2449
|
-
});
|
|
2450
|
-
if (mine.length > shown.length) lines.push(familyFoldLine(mine.length - shown.length));
|
|
2451
|
-
return lines;
|
|
2452
|
-
}
|
|
2453
|
-
|
|
2454
|
-
/** A transcript's header parent link, read from its first line alone — the cheap pass of the family
|
|
2455
|
-
* scan. Returns `undefined` for a file that is not a pi session (or has no complete first line in
|
|
2456
|
-
* the bytes read), `null` for a session that is nobody's child. */
|
|
2457
|
-
export function sessionHeaderParent(head: string): string | null | undefined {
|
|
2458
|
-
const nl = head.indexOf("\n");
|
|
2459
|
-
if (nl < 0) return undefined;
|
|
2460
|
-
try {
|
|
2461
|
-
const h = JSON.parse(head.slice(0, nl)) as { type?: string; parentSession?: unknown };
|
|
2462
|
-
if (h?.type !== "session") return undefined;
|
|
2463
|
-
return typeof h.parentSession === "string" && h.parentSession ? h.parentSession : null;
|
|
2464
|
-
} catch {
|
|
2465
|
-
return undefined;
|
|
2466
|
-
}
|
|
2467
|
-
}
|
|
2468
|
-
|
|
2469
|
-
/** The fields the family view needs, from one transcript's full text — the same rules pi's own
|
|
2470
|
-
* session listing applies (latest `session_info` name wins, explicit clears included; messages are
|
|
2471
|
-
* `message` entries; last activity is the newest user/assistant message, else the header time).
|
|
2472
|
-
* Only the few files whose header names the driver reach this — that is what keeps a family read
|
|
2473
|
-
* proportional to the family, not to the bucket's whole history. */
|
|
2474
|
-
export function parseSessionSummary(text: string, file: string, mtimeMs?: number): WorkerSessionRow | null {
|
|
2475
|
-
type Header = { timestamp?: unknown; parentSession?: unknown };
|
|
2476
|
-
let header: Header | null = null;
|
|
2477
|
-
let name: string | undefined;
|
|
2478
|
-
let messageCount = 0;
|
|
2479
|
-
let last: number | undefined;
|
|
2480
|
-
for (const line of text.split("\n")) {
|
|
2481
|
-
if (!line.trim()) continue;
|
|
2482
|
-
let e: { type?: string; name?: unknown; timestamp?: unknown; message?: { role?: string; content?: unknown; timestamp?: unknown } };
|
|
2483
|
-
try { e = JSON.parse(line); } catch { continue; }
|
|
2484
|
-
if (!header) {
|
|
2485
|
-
if (e?.type !== "session") return null;
|
|
2486
|
-
header = e as Header;
|
|
2487
|
-
continue;
|
|
2488
|
-
}
|
|
2489
|
-
if (e.type === "session_info") name = typeof e.name === "string" ? e.name.trim() || undefined : undefined;
|
|
2490
|
-
if (e.type !== "message") continue;
|
|
2491
|
-
messageCount++;
|
|
2492
|
-
const m = e.message;
|
|
2493
|
-
if (!m || m.content === undefined || (m.role !== "user" && m.role !== "assistant")) continue;
|
|
2494
|
-
const t = typeof m.timestamp === "number" ? m.timestamp : Date.parse(String(e.timestamp));
|
|
2495
|
-
if (Number.isFinite(t)) last = Math.max(last ?? 0, t);
|
|
2496
|
-
}
|
|
2497
|
-
if (!header) return null;
|
|
2498
|
-
const headerTime = typeof header.timestamp === "string" ? Date.parse(header.timestamp) : NaN;
|
|
2499
|
-
const modified = last && last > 0 ? last : Number.isFinite(headerTime) ? headerTime : mtimeMs;
|
|
2500
|
-
return { path: file, parent: typeof header.parentSession === "string" ? header.parentSession : null, name, messageCount, modified };
|
|
2501
|
-
}
|
|
2502
|
-
|
|
2503
|
-
/** pi's bucket name for a working directory (`--home-me-repo--`), the same encoding pi applies
|
|
2504
|
-
* (`getDefaultSessionDirPath`). Used only to RECOGNIZE buckets, never to choose where a session goes. */
|
|
2505
|
-
export function sessionBucketName(cwd: string): string {
|
|
2506
|
-
return `--${path.resolve(cwd).replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
|
|
2507
|
-
}
|
|
2508
|
-
|
|
2509
|
-
/** What the doctor needs to judge one feature's worktree bucket. */
|
|
2510
|
-
export interface WorktreeBucketFeature {
|
|
2511
|
-
/** the slug's state is gone, done or aborted — nothing will delegate into this worktree again */
|
|
2512
|
-
finished: boolean;
|
|
2513
|
-
worktreeExists: boolean;
|
|
2514
|
-
}
|
|
2515
|
-
|
|
2516
|
-
/**
|
|
2517
|
-
* Session buckets stage workers left behind before 0.70 put workers in the driver's bucket. Such a
|
|
2518
|
-
* worker ran with cwd = the feature worktree, so pi filed it under that worktree's own bucket — which
|
|
2519
|
-
* no folder scope opened from the main checkout ever shows, and which outlives the worktree. A bucket
|
|
2520
|
-
* is reported when it encodes `<root>/.dev-flow/<slug>/worktree` and that slug is finished or its
|
|
2521
|
-
* worktree is gone. `features` is keyed by slug; a slug absent from it has no state at all (finished).
|
|
2522
|
-
*/
|
|
2523
|
-
export function orphanWorktreeBuckets(buckets: string[], root: string, features: Map<string, WorktreeBucketFeature>): { bucket: string; slug: string }[] {
|
|
2524
|
-
const prefix = sessionBucketName(path.join(root, ".dev-flow")).slice(0, -2) + "-";
|
|
2525
|
-
const out: { bucket: string; slug: string }[] = [];
|
|
2526
|
-
for (const b of buckets) {
|
|
2527
|
-
if (!b.startsWith(prefix) || !b.endsWith("-worktree--")) continue;
|
|
2528
|
-
const encSlug = b.slice(prefix.length, -"-worktree--".length);
|
|
2529
|
-
if (!encSlug) continue;
|
|
2530
|
-
// slugs are kebab-case, which the encoding leaves intact; a slug that is a known feature wins
|
|
2531
|
-
const f = features.get(encSlug);
|
|
2532
|
-
if (f && !f.finished && f.worktreeExists) continue;
|
|
2533
|
-
out.push({ bucket: b, slug: encSlug });
|
|
2534
|
-
}
|
|
2535
|
-
return out;
|
|
2536
|
-
}
|
|
2537
|
-
|
|
2538
|
-
/** Stage workers spawned in THIS process, by session id. A worker loads the operator's extensions —
|
|
2539
|
-
* dev-flow among them, because its guards must hold inside the worker too — but the driver's context
|
|
2540
|
-
* (the playbook core, the unbound-session posture, "surface this to the operator") is wrong there:
|
|
2541
|
-
* the brief is the worker's whole instruction. The worker's loader imports dev-flow as its own
|
|
2542
|
-
* module instance, so the registry lives on a process-global symbol both instances can see. */
|
|
2543
|
-
const WORKER_SESSIONS = Symbol.for("dev-flow.workerSessions");
|
|
2544
|
-
function workerSessionSet(): Set<string> {
|
|
2545
|
-
const g = globalThis as unknown as Record<symbol, Set<string> | undefined>;
|
|
2546
|
-
return (g[WORKER_SESSIONS] ??= new Set<string>());
|
|
2547
|
-
}
|
|
2548
|
-
export function markWorkerSession(id: string | undefined | null): void {
|
|
2549
|
-
if (id) workerSessionSet().add(id);
|
|
2550
|
-
}
|
|
2551
|
-
export function isWorkerSession(id: string | undefined | null): boolean {
|
|
2552
|
-
return !!id && workerSessionSet().has(id);
|
|
1974
|
+
/** Why an op is not legal for a feature at this stage, or null. */
|
|
1975
|
+
export function workerOpError(op: string, stage: Stage): string | null {
|
|
1976
|
+
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)`;
|
|
1977
|
+
const ok = WORKER_OP_STAGES[op];
|
|
1978
|
+
return ok.includes(stage) ? null : `op "${op}" runs at ${ok.join(" or ")} — the feature is at ${stage}`;
|
|
2553
1979
|
}
|
|
2554
1980
|
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
export function familyFoldLine(dropped: number): string {
|
|
2558
|
-
return `… ${dropped} earlier workers`;
|
|
2559
|
-
}
|
|
2560
|
-
|
|
2561
|
-
export function isFamilyFoldLine(line: string): boolean {
|
|
2562
|
-
return line.startsWith("… ");
|
|
2563
|
-
}
|
|
2564
|
-
|
|
2565
|
-
/** How many workers a rendered family list stands for: the fold line is a count, not a worker. */
|
|
2566
|
-
export function workerFamilyCount(lines: string[] | null | undefined): number | null {
|
|
2567
|
-
if (!lines) return null;
|
|
2568
|
-
return lines.filter((l) => !isFamilyFoldLine(l)).length;
|
|
2569
|
-
}
|
|
2570
|
-
|
|
2571
|
-
/** Local wall-clock `YYYY-MM-DD HH:mm` — the convention every dev-flow timestamp follows (a UTC
|
|
2572
|
-
* stamp next to the operator's own clock reads as a future or past session, and the family line is
|
|
2573
|
-
* meant to be scanned, not converted). */
|
|
2574
|
-
function localStamp(ms: number): string {
|
|
2575
|
-
const d = new Date(ms);
|
|
2576
|
-
const p = (n: number) => String(n).padStart(2, "0");
|
|
2577
|
-
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
|
|
2578
|
-
}
|
|
2579
|
-
|
|
2580
|
-
/** What the tool accumulated from a worker's assistant usage records. */
|
|
2581
|
-
export interface StageUsage {
|
|
2582
|
-
input: number;
|
|
2583
|
-
output: number;
|
|
2584
|
-
cacheRead: number;
|
|
2585
|
-
cacheWrite: number;
|
|
2586
|
-
totalTokens: number;
|
|
2587
|
-
cost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };
|
|
2588
|
-
}
|
|
2589
|
-
|
|
2590
|
-
/** One compact usage line for the card and the result: what the run cost, at a glance. */
|
|
2591
|
-
export function stageUsageLine(u: StageUsage, turns?: number): string {
|
|
2592
|
-
const k = (n: number) => (n >= 1000 ? `${(n / 1000).toFixed(n >= 100_000 ? 0 : 1)}k` : String(n));
|
|
2593
|
-
const ctx = u.cacheRead + u.input + u.output;
|
|
2594
|
-
return `${turns ? `${turns} turns · ` : ""}↑${k(u.input)} ↓${k(u.output)} · ctx ${k(ctx)} · $${u.cost.total.toFixed(4)}`;
|
|
2595
|
-
}
|
|
2596
|
-
|
|
2597
|
-
export interface VerifyBriefInput {
|
|
1981
|
+
export interface WorkerBriefInput {
|
|
1982
|
+
op: WorkerOp;
|
|
2598
1983
|
slug: string;
|
|
2599
|
-
/** absolute path of the feature worktree — the reviewer's whole world. */
|
|
2600
1984
|
workDir: string;
|
|
2601
|
-
/** absolute path of plan/plan.md in the main checkout. */
|
|
2602
1985
|
planFile: string;
|
|
2603
|
-
statusJson: string;
|
|
2604
|
-
/** `git status --porcelain -b` in the worktree, before the run. */
|
|
2605
|
-
gitSummary: string;
|
|
2606
|
-
/** `git diff --stat <default>…HEAD` — the shape of what is under review; the reviewer reads the
|
|
2607
|
-
* full diff itself (pasting it here would spend the context the delegation saves). */
|
|
2608
|
-
diffStat: string;
|
|
2609
|
-
/** tier-1 commands the playbook says must be green (name + command). */
|
|
2610
|
-
checks: { name: string; cmd: string }[];
|
|
2611
|
-
/** the driver's default branch, for the diff range. */
|
|
2612
1986
|
defaultBranch: string;
|
|
2613
|
-
|
|
2614
|
-
|
|
2615
|
-
|
|
2616
|
-
|
|
2617
|
-
|
|
2618
|
-
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
|
|
2642
|
-
|
|
2643
|
-
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
|
|
2651
|
-
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
|
|
2662
|
-
other: string[];
|
|
2663
|
-
/** true when no tagged line was found at all — the reviewer produced prose, not findings. */
|
|
2664
|
-
missing: boolean;
|
|
2665
|
-
rawTail: string;
|
|
2666
|
-
}
|
|
2667
|
-
|
|
2668
|
-
/** Split a reflect worker's message into tagged findings. Bullets, bold and inline code around the
|
|
2669
|
-
* tag are tolerated: a model decorates, and re-parsing prose by hand in the driver is worse. */
|
|
2670
|
-
export function parseReflectFindings(text: string): ReflectFindings {
|
|
2671
|
-
const out: ReflectFindings = { playbook: [], plugin: [], other: [], missing: true, rawTail: (text ?? "").split("\n").slice(-15).join("\n").slice(-600) };
|
|
2672
|
-
|
|
2673
|
-
for (const line of (text ?? "").split("\n")) {
|
|
2674
|
-
// bracketed tag (the contract) or a bare `plugin:` lead-in; markdown decoration is noise around it
|
|
2675
|
-
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());
|
|
2676
|
-
if (!m) continue;
|
|
2677
|
-
const body = (m[2] ?? m[4]).replace(/[*`\s]+$/, "").trim();
|
|
2678
|
-
if (!body || /^(none|n\/a|nothing)[-.\s]*$/i.test(body)) continue;
|
|
2679
|
-
const kind = (m[1] ?? m[3]).toLowerCase();
|
|
2680
|
-
if (kind === "playbook") out.playbook.push(body);
|
|
2681
|
-
else if (kind === "plugin") out.plugin.push(body);
|
|
2682
|
-
else out.other.push(body);
|
|
1987
|
+
commits: string; // `git log --oneline <base>..HEAD`
|
|
1988
|
+
status: string; // `git status --short`
|
|
1989
|
+
checks: { name: string; command: string }[];
|
|
1990
|
+
note: string;
|
|
1991
|
+
}
|
|
1992
|
+
|
|
1993
|
+
/** The facts every worker needs, so the driver's note can be just the slice. The plan path is absolute:
|
|
1994
|
+
* it lives in the MAIN checkout's gitignored .dev-flow/, never inside the worktree. */
|
|
1995
|
+
export function buildWorkerBrief(o: WorkerBriefInput): string {
|
|
1996
|
+
const checks = o.checks.length ? o.checks.map((c) => `- ${c.name}: \`${c.command}\``).join("\n") : "- (the playbook defines no tier-1 commands)";
|
|
1997
|
+
const head = [
|
|
1998
|
+
`You are a ${o.op === "implement" ? "stage worker implementing a slice" : "fresh, independent reviewer"} for dev-flow feature \`${o.slug}\`.`,
|
|
1999
|
+
"",
|
|
2000
|
+
"## Facts",
|
|
2001
|
+
`- Worktree (your cwd; work only here): ${o.workDir}`,
|
|
2002
|
+
`- Approved plan (read it first; it is outside the worktree): ${o.planFile}`,
|
|
2003
|
+
`- Branch base: ${o.defaultBranch}`,
|
|
2004
|
+
`- Commits on the branch so far:\n${o.commits.trim() ? o.commits.trim().split("\n").map((l) => ` ${l}`).join("\n") : " (none)"}`,
|
|
2005
|
+
`- Uncommitted now: ${o.status.trim() ? `\n${o.status.trim().split("\n").map((l) => ` ${l}`).join("\n")}` : "clean"}`,
|
|
2006
|
+
`- Project checks (run them before you report):\n${checks}`,
|
|
2007
|
+
"- You hold no flow tool: gates, checkpoints and the operator stay with the driving session.",
|
|
2008
|
+
"",
|
|
2009
|
+
"## Your task",
|
|
2010
|
+
o.note.trim() || "(no note — do what the plan's next unfinished step asks)",
|
|
2011
|
+
"",
|
|
2012
|
+
];
|
|
2013
|
+
const contract =
|
|
2014
|
+
o.op === "implement"
|
|
2015
|
+
? [
|
|
2016
|
+
"## Contract",
|
|
2017
|
+
"- Use the edit/write tools for source changes. Commit as you go on the feature branch (small, meaningful commits).",
|
|
2018
|
+
"- Do not stop to narrate — keep working until the slice is done or you are blocked.",
|
|
2019
|
+
"- Finish with a final message whose last section starts with a line `REPORT` followed by: done, commits, open items, risks.",
|
|
2020
|
+
]
|
|
2021
|
+
: [
|
|
2022
|
+
"## Contract",
|
|
2023
|
+
"- 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.",
|
|
2024
|
+
"- Look for correctness bugs, claims in docs/changelog the code does not back, missing tests for risky paths, and plan items not delivered.",
|
|
2025
|
+
"- 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).",
|
|
2026
|
+
];
|
|
2027
|
+
return [...head, ...contract].join("\n");
|
|
2028
|
+
}
|
|
2029
|
+
|
|
2030
|
+
/** The REPORT section of a worker's final message: everything after the last `REPORT` heading line. */
|
|
2031
|
+
export function parseWorkerReport(text: string): { found: boolean; body: string; verdict: "PASS" | "FAIL" | null } {
|
|
2032
|
+
const lines = (text ?? "").split("\n");
|
|
2033
|
+
let at = -1;
|
|
2034
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
2035
|
+
if (/^\s*[#*_>\s]*REPORT[*_:\s]*$/i.test(lines[i])) { at = i; break; }
|
|
2683
2036
|
}
|
|
2684
|
-
|
|
2685
|
-
|
|
2037
|
+
if (at < 0) return { found: false, body: lines.slice(-12).join("\n").slice(-800), verdict: null };
|
|
2038
|
+
const body = lines.slice(at + 1).join("\n").trim();
|
|
2039
|
+
const v = /verdict\s*[:=]\s*\**\s*(PASS|FAIL)/i.exec(body);
|
|
2040
|
+
return { found: true, body, verdict: v ? (v[1].toUpperCase() as "PASS" | "FAIL") : null };
|
|
2686
2041
|
}
|
|
2687
2042
|
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
planFile: string;
|
|
2691
|
-
statusJson: string;
|
|
2692
|
-
/** The driver's own session file (JSONL) — pre-compaction turns live there even after the driver's
|
|
2693
|
-
* context was summarized away, which is exactly what a finish review needs. */
|
|
2694
|
-
driverSession: string | null;
|
|
2695
|
-
/** Every worker transcript recorded in transcripts.log, oldest first. */
|
|
2696
|
-
transcripts: { at: string; op: string; path: string }[];
|
|
2697
|
-
/** Open reflection lines, so a finding already queued is not queued twice. */
|
|
2698
|
-
openReflections: string[];
|
|
2699
|
-
note?: string;
|
|
2700
|
-
}
|
|
2701
|
-
|
|
2702
|
-
/** The reflect worker's brief: an independent reviewer of the WHOLE flow — driver included. It
|
|
2703
|
-
* cannot ask the operator anything and cannot write, so it returns tagged findings the driver puts to
|
|
2704
|
-
* the operator (fold / fix / drop stays the operator's call, as always). */
|
|
2705
|
-
export function buildReflectBrief(i: ReflectBriefInput): string {
|
|
2706
|
-
const tlist = i.transcripts.length
|
|
2707
|
-
? 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")
|
|
2708
|
-
: "- (this flow delegated nothing — review the driver session alone)";
|
|
2709
|
-
const open = i.openReflections.length ? i.openReflections.map((l) => `- ${l}`).join("\n") : "- none";
|
|
2710
|
-
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.
|
|
2711
|
-
|
|
2712
|
-
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.
|
|
2713
|
-
|
|
2714
|
-
Read the whole flow, in this order:
|
|
2715
|
-
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)"}
|
|
2716
|
-
(a JSONL of every message, tool call and result. If it is large, read it in chunks and follow the turns, not the file.)
|
|
2717
|
-
2. every worker the flow delegated:
|
|
2718
|
-
${tlist}
|
|
2719
|
-
3. the plan the flow was held to: ${i.planFile}
|
|
2720
|
-
4. how the flow ended (\`flow status --json\` of the driving session):
|
|
2721
|
-
${i.statusJson}
|
|
2722
|
-
|
|
2723
|
-
Then run the reflection itself, over what you read (this is the same protocol \`flow reflect\` prints, applied to the transcripts):
|
|
2724
|
-
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.
|
|
2725
|
-
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.
|
|
2726
|
-
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.
|
|
2727
|
-
|
|
2728
|
-
Open reflection queue (already filed):
|
|
2729
|
-
${open}
|
|
2730
|
-
|
|
2731
|
-
${i.note?.trim() ? `Note from the driver (context you cannot read elsewhere):\n${i.note.trim()}\n` : ""}
|
|
2732
|
-
${REFLECT_FINDINGS_CONTRACT}`;
|
|
2733
|
-
}
|
|
2043
|
+
/** The nudge a worker gets when its turn ended without the REPORT block. */
|
|
2044
|
+
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.";
|