pi-dev-flow 0.72.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 +21 -0
- package/README.md +5 -3
- package/docs/gates.md +4 -4
- package/docs/guardrails.md +5 -3
- package/docs/playbook.md +3 -8
- package/extensions/dev-flow.ts +160 -814
- package/package.json +1 -1
- package/skills/dev-flow/SKILL.md +4 -9
- package/skills/dev-flow/references/finish.md +3 -7
- package/skills/dev-flow/references/implement.md +25 -43
- 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 +143 -946
- package/src/projectmd.ts +4 -2
- package/docs/stage-agent.md +0 -227
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);
|
|
@@ -885,14 +882,11 @@ export function parsePushRefs(pushes: string[][]): PushRef[] {
|
|
|
885
882
|
return out;
|
|
886
883
|
}
|
|
887
884
|
|
|
888
|
-
/** Flow control files by full path — state.json
|
|
889
|
-
*
|
|
890
|
-
*
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
* session and none other (writeGuard is the same rule for the other half of the tool surface). */
|
|
894
|
-
const STATE_PATH = /(^|[\s'"\/])(?:(?:state|claim)\.json|delegations\.log)$/;
|
|
895
|
-
const STATE_PATH_ABS = /\.dev-flow\/[\w./-]*(?:(?:state|claim)\.json|delegations\.log)$/;
|
|
885
|
+
/** Flow control files by full path — state.json and claim.json — or a bare name when the command
|
|
886
|
+
* also touches `.dev-flow` (that is how `cd .dev-flow/<slug> && mv state.json …` reaches it).
|
|
887
|
+
* The claim is the live-session lock: deleting it is as much theft as forging a stage. */
|
|
888
|
+
const STATE_PATH = /(^|[\s'"\/])(?:state|claim)\.json$/;
|
|
889
|
+
const STATE_PATH_ABS = /\.dev-flow\/[\w./-]*(?:state|claim)\.json$/;
|
|
896
890
|
const PLAYBOOK_PATH = /\.dev-flow\/[\w./-]*project\.md/;
|
|
897
891
|
const DF_ANYWHERE = /\.dev-flow\b/;
|
|
898
892
|
/** The `.dev-flow/` folder itself or one feature directory under it — deleting either destroys the flow
|
|
@@ -1040,9 +1034,54 @@ export function bashFlowGuard(o: GuardCtx): string | null {
|
|
|
1040
1034
|
if (writesDefault && o.stage !== "release") return `pushing to ${o.defaultBranch} requires stage "release" (verified feature)${attr}`;
|
|
1041
1035
|
}
|
|
1042
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
|
+
}
|
|
1043
1073
|
return null;
|
|
1044
1074
|
}
|
|
1045
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
|
+
|
|
1046
1085
|
// ------------------------------------------------------- project safety rules
|
|
1047
1086
|
|
|
1048
1087
|
/** One flow-guard rule: `pattern` is a JS regex source (deny/confirm) or a repo-relative path (protect/forbid). */
|
|
@@ -1289,32 +1328,23 @@ const within = (abs: string, dir: string | null) => !!dir && (abs === dir || abs
|
|
|
1289
1328
|
* the guarded checkout, and `repoRoot` keeps a repository that merely lives under the temp dir (every
|
|
1290
1329
|
* smoke-test repo) under the normal stage rules.
|
|
1291
1330
|
*/
|
|
1292
|
-
export function inScratchDir(abs: string, repoRoot?: string | null): boolean {
|
|
1293
|
-
const real = realAbs(abs);
|
|
1294
|
-
if (repoRoot) {
|
|
1295
|
-
const root = realAbs(path.resolve(repoRoot));
|
|
1296
|
-
if (real === root || real.startsWith(root + path.sep)) return false;
|
|
1297
|
-
}
|
|
1298
|
-
const tmp = realAbs(path.resolve(os.tmpdir()));
|
|
1299
|
-
return real === tmp || real.startsWith(tmp + path.sep);
|
|
1300
|
-
}
|
|
1301
|
-
|
|
1302
1331
|
/** The main checkout a linked worktree shares its history with, from git's answer for the common dir
|
|
1303
1332
|
* (`<main>/.git`), or null when there is nothing to remap: git did not answer, or cwd already is that
|
|
1304
|
-
* checkout (a plain clone answers its own dir).
|
|
1305
|
-
* gets (dev-flow's `flowRoot` keeps cwd unless the main checkout is dev-flow-initiated). */
|
|
1333
|
+
* checkout (a plain clone answers its own dir). */
|
|
1306
1334
|
export function mainCheckoutRoot(cwd: string, commonDir: string | null): string | null {
|
|
1307
1335
|
if (!commonDir) return null;
|
|
1308
1336
|
const main = path.resolve(path.dirname(path.resolve(cwd, commonDir)));
|
|
1309
1337
|
return main === path.resolve(cwd) ? null : main;
|
|
1310
1338
|
}
|
|
1311
1339
|
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1340
|
+
export function inScratchDir(abs: string, repoRoot?: string | null): boolean {
|
|
1341
|
+
const real = realAbs(abs);
|
|
1342
|
+
if (repoRoot) {
|
|
1343
|
+
const root = realAbs(path.resolve(repoRoot));
|
|
1344
|
+
if (real === root || real.startsWith(root + path.sep)) return false;
|
|
1345
|
+
}
|
|
1346
|
+
const tmp = realAbs(path.resolve(os.tmpdir()));
|
|
1347
|
+
return real === tmp || real.startsWith(tmp + path.sep);
|
|
1318
1348
|
}
|
|
1319
1349
|
|
|
1320
1350
|
/**
|
|
@@ -1323,12 +1353,9 @@ export function isDelegationLedger(abs: string, dfDir: string): boolean {
|
|
|
1323
1353
|
* (release+ may touch it; plan/implement may not); with no binding and unfinished features
|
|
1324
1354
|
* the session must bind first (`flow use`). Flow-by-default: a session with no flow may not
|
|
1325
1355
|
* touch the checkout at all — a bound feature is the only way in.
|
|
1326
|
-
* `byWorker` says the writing session is a flow_stage worker: a normal feature's worktree stays
|
|
1327
|
-
* closed to its driver at implement (implement work is delegated — see delegationErrors), open to
|
|
1328
|
-
* the worker that was sent to do it.
|
|
1329
1356
|
* Returns a reason or null (allowed).
|
|
1330
1357
|
*/
|
|
1331
|
-
export function writeGuard(o: { abs: string; dfDir: string; features: FeatureRef[]; boundSlug: string | null; repoRoot?: string | null
|
|
1358
|
+
export function writeGuard(o: { abs: string; dfDir: string; features: FeatureRef[]; boundSlug: string | null; repoRoot?: string | null }): string | null {
|
|
1332
1359
|
// Judge where the bytes land, not where the path pretends: a symlink inside the worktree pointing
|
|
1333
1360
|
// out of it is the same write as the target path (realAbs walks the deepest existing ancestor, so
|
|
1334
1361
|
// a brand-new file under a real directory resolves right, and a never-existing one is stable).
|
|
@@ -1338,12 +1365,6 @@ export function writeGuard(o: { abs: string; dfDir: string; features: FeatureRef
|
|
|
1338
1365
|
if (abs === path.join(dfDir, "project.md")) return "project.md is the operator playbook — change it with flow init --write (setup) or inside a docs/patch flow's worktree";
|
|
1339
1366
|
if (abs.endsWith("state.json") && abs.includes(dfDir + path.sep)) return "state.json is dev-flow-owned — advance stages with the flow tool only";
|
|
1340
1367
|
if (abs.endsWith("claim.json") && abs.includes(dfDir + path.sep)) return "claim.json is dev-flow-owned — the live-session lock is not an edit target; take a feature over with flow use <slug>";
|
|
1341
|
-
// The delegation ledger is the fact the verify gate trusts about *who* worked — and the session it
|
|
1342
|
-
// constrains is the one holding the pen. Left writable, one hand-written line covering the driver's
|
|
1343
|
-
// own shas collapses "zero bypass", so it is dev-flow-owned like state.json. Worker runs append it
|
|
1344
|
-
// from flow_stage's completion code (appendFileSync, which never passes through this guard), and
|
|
1345
|
-
// flow verify only ever reads it — no sanctioned channel needs it to be an edit target.
|
|
1346
|
-
if (isDelegationLedger(abs, dfDir)) return `${DELEGATIONS_FILE} is dev-flow-owned — the delegation ledger is written by flow_stage worker runs and read by flow verify; a session cannot sign its own proof`;
|
|
1347
1368
|
// Owner attribution BEFORE the .dev-flow allow: with the default worktreeDir inside .dev-flow,
|
|
1348
1369
|
// a worktree must still be judged by its owning feature's stage, not treated as free plan space.
|
|
1349
1370
|
const owner = o.features.find((f) => within(abs, f.worktreeAbs ? realAbs(f.worktreeAbs) : null));
|
|
@@ -1353,14 +1374,6 @@ export function writeGuard(o: { abs: string; dfDir: string; features: FeatureRef
|
|
|
1353
1374
|
// the playbook copy inside a worktree: only operator-granted lightweight modes may change it
|
|
1354
1375
|
if (path.basename(abs) === "project.md" && abs.includes(path.join(".dev-flow", "project.md")) && !owner.state.docs && !owner.state.patch)
|
|
1355
1376
|
return `project.md changes belong to a docs or patch flow — ${owner.state.slug} is a normal feature (flow start <slug> --docs --confirmed)`;
|
|
1356
|
-
// At implement the driver drives and a worker authors: the verify gate refuses a branch whose
|
|
1357
|
-
// commits fall outside a worker's run window (delegationErrors), so an inline edit here is work
|
|
1358
|
-
// that cannot be proven later. Saying it at the write is cheaper than letting a session author a
|
|
1359
|
-
// branch and hitting the gate with it — and unlike the gate, this knows who is holding the pen:
|
|
1360
|
-
// workers are registered sessions (byWorker), and --docs/--patch are the operator-granted inline
|
|
1361
|
-
// modes. Pre-release stays in-session by design (review, changelog, bump are judgment calls).
|
|
1362
|
-
if (owner.state.stage === "implement" && !owner.state.docs && !owner.state.patch && !o.byWorker)
|
|
1363
|
-
return `implement work is delegated — ${owner.state.slug} is a normal feature at implement: a flow_stage { stage: "implement" } worker edits and commits in this worktree, not this session (the driver keeps the gates, the checkpoint, flow check and running the app)`;
|
|
1364
1377
|
return null; // implement/pre-release/release: own worktree is the working area
|
|
1365
1378
|
}
|
|
1366
1379
|
// Scratch outside the checkout is not a repo write: every stage (and an unbound session) may use it. It
|
|
@@ -1406,11 +1419,6 @@ export interface SessionClaim {
|
|
|
1406
1419
|
key: string;
|
|
1407
1420
|
pid: number;
|
|
1408
1421
|
at: string;
|
|
1409
|
-
/** The claiming process's start identity (`processStart`), when the platform has one. A pid is
|
|
1410
|
-
* recycled — a claim left by a crashed pi can name a pid some unrelated process now holds — so a
|
|
1411
|
-
* live pid only counts as the claimant when its start identity still matches. Absent on legacy
|
|
1412
|
-
* claims and on platforms without /proc, which keep the pid-only judgement. */
|
|
1413
|
-
start?: string;
|
|
1414
1422
|
}
|
|
1415
1423
|
|
|
1416
1424
|
/** Whether a process is running (kill 0 only probes existence; EPERM means it exists, foreign-owned). */
|
|
@@ -1423,43 +1431,9 @@ export function pidAlive(pid: number): boolean {
|
|
|
1423
1431
|
}
|
|
1424
1432
|
}
|
|
1425
1433
|
|
|
1426
|
-
/**
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
export function processStart(pid: number, read: (file: string) => string = (f) => readFileSync(f, "utf8")): string | undefined {
|
|
1430
|
-
try {
|
|
1431
|
-
const stat = read(`/proc/${pid}/stat`);
|
|
1432
|
-
const rest = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
1433
|
-
// rest[0] is field 3 (state), so field 22 sits at index 19
|
|
1434
|
-
const st = rest[19];
|
|
1435
|
-
return st && /^\d+$/.test(st) ? st : undefined;
|
|
1436
|
-
} catch {
|
|
1437
|
-
return undefined;
|
|
1438
|
-
}
|
|
1439
|
-
}
|
|
1440
|
-
|
|
1441
|
-
/** True only when another live session holds the claim — its feature can only be taken by an explicit `flow use`, never quietly.
|
|
1442
|
-
* A claim whose pid is alive but whose recorded start identity no longer matches belongs to a dead
|
|
1443
|
-
* session whose pid was recycled: it does not block. */
|
|
1444
|
-
export function claimBlocks(claim: SessionClaim | null, myKey: string, alive: (pid: number) => boolean = pidAlive, startOf: (pid: number) => string | undefined = processStart): boolean {
|
|
1445
|
-
if (!claim || claim.key === myKey || !alive(claim.pid)) return false;
|
|
1446
|
-
if (claim.start) {
|
|
1447
|
-
const now = startOf(claim.pid);
|
|
1448
|
-
if (now !== undefined && now !== claim.start) return false;
|
|
1449
|
-
}
|
|
1450
|
-
return true;
|
|
1451
|
-
}
|
|
1452
|
-
|
|
1453
|
-
/** How old a claim is, in words, for a refusal: "claimed 3 days ago" lets the operator tell a live
|
|
1454
|
-
* session from a stale pid at a glance. Empty when the stamp is unreadable. */
|
|
1455
|
-
export function claimAge(claim: SessionClaim, nowMs: number = Date.now()): string {
|
|
1456
|
-
const t = Date.parse(claim.at);
|
|
1457
|
-
if (!Number.isFinite(t)) return "";
|
|
1458
|
-
const min = Math.max(0, Math.round((nowMs - t) / 60000));
|
|
1459
|
-
if (min < 60) return `${min} min old`;
|
|
1460
|
-
const h = Math.round(min / 60);
|
|
1461
|
-
if (h < 48) return `${h} h old`;
|
|
1462
|
-
return `${Math.round(h / 24)} days old`;
|
|
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);
|
|
1463
1437
|
}
|
|
1464
1438
|
|
|
1465
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). */
|
|
@@ -1884,10 +1858,7 @@ export function nextHint(state: FlowState, cfg: Config): string {
|
|
|
1884
1858
|
return `investigate, present your direction and proposed mode to the operator and clarify in chat, then write the plan into .dev-flow/${state.slug}/plan/plan.md${state.ui ? ` and render mockups to plan/mockups/ (${cfg.mockupGlobs.join(", ")}) with headless chromium, embedded in plan.md` : ""}, then ask the operator Approve? in chat and run flow approve --confirmed when they answer`;
|
|
1885
1859
|
case "implement":
|
|
1886
1860
|
if (state.docs) return `implement in the worktree ${state.worktree} — docs mode runs no project command (no build, no dev deploy, no health probe); tick the tier-2 checklist with the operator, then ask them Verified? in chat and run flow verify --confirmed when they answer`;
|
|
1887
|
-
|
|
1888
|
-
// not order work the write guard refuses and the verify gate refuses: at implement a worker authors,
|
|
1889
|
-
// the driver drives. (docs mode above stays inline — it is exempt from the delegation gate.)
|
|
1890
|
-
return `delegate the implement work: flow_stage { stage: "implement" } sends a worker to edit, test and commit in the worktree ${state.worktree} (your own edits there are guard-refused, and flow verify refuses a branch whose commits fall outside a worker run); when it reports, rerun flow check (tier-1 checks, incl. health with seeded data) and get a fresh verify-worker PASS; tick the tier-2 checklist with the operator, then ask them Verified? in chat and run flow verify --confirmed when they answer — keep the app running when you ask Verified?: the operator reviews the live app; never clean up the test server before the checkpoint is answered (with no dev deploy configured, verify live-re-probes health itself and refuses while nothing is answering)`;
|
|
1861
|
+
return `implement in the worktree ${state.worktree}, add tests, run flow check (tier-1 checks, incl. health with seeded data); tick the tier-2 checklist with the operator, then ask them Verified? in chat and run flow verify --confirmed when they answer — keep the app running when you ask Verified?: the operator reviews the live app; never clean up the test server before the checkpoint is answered (with no dev deploy configured, verify live-re-probes health itself and refuses while nothing is answering)`;
|
|
1891
1862
|
case "pre-release":
|
|
1892
1863
|
return `${cfg.release.review} → fix must-have/should-have → update docs${cfg.release.changelog ? ` → prepare ${cfg.release.changelog} (a heading for the new version, carrying every pending Unreleased line over as it stands)` : ""}${cfg.versioning.file ? ` → bump version in ${cfg.versioning.file}` : ""}, re-run flow check, then show the operator the PR summary, version and changelog, ask Release? and run flow release`;
|
|
1893
1864
|
case "release":
|
|
@@ -1981,867 +1952,93 @@ export function applyAnswer(partial: Record<string, unknown>, key: string, value
|
|
|
1981
1952
|
}
|
|
1982
1953
|
|
|
1983
1954
|
|
|
1984
|
-
//
|
|
1985
|
-
|
|
1986
|
-
/** Stages whose *work* `flow_stage` may delegate to a disposable sub-session. plan is the
|
|
1987
|
-
* operator dialogue; release/finish carry the Release?/Finish? words — only the heavy middle
|
|
1988
|
-
* stages are delegated, and gates are never delegated: the driving session keeps every gate,
|
|
1989
|
-
* every checkpoint and the claim, so gate integrity never depends on a worker behaving. */
|
|
1990
|
-
export const DELEGABLE_STAGES = ["implement", "pre-release"] as const;
|
|
1991
|
-
export type DelegableStage = (typeof DELEGABLE_STAGES)[number];
|
|
1992
|
-
export function isDelegableStage(s: string): s is DelegableStage {
|
|
1993
|
-
return (DELEGABLE_STAGES as readonly string[]).includes(s);
|
|
1994
|
-
}
|
|
1995
|
-
|
|
1996
|
-
/** Sentinel line that ends a stage worker's final message — the parent digests exactly this,
|
|
1997
|
-
* not the whole run, so one stage's hundred tool calls cost the driving session one bounded block. */
|
|
1998
|
-
export const STAGE_REPORT_HEAD = "STAGE REPORT";
|
|
1999
|
-
|
|
2000
|
-
/** The sections of the report block. The preserve-list mirrors flowCompactInstructions' demands:
|
|
2001
|
-
* a worker's nuance lives nowhere else, so what is not written here is lost on purpose. */
|
|
2002
|
-
export const STAGE_REPORT_CONTRACT = `Write, as the very last lines of your final message, exactly this block (empty sections say \`none\`):
|
|
2003
|
-
${STAGE_REPORT_HEAD}
|
|
2004
|
-
done:
|
|
2005
|
-
- <what you actually did, one line per item>
|
|
2006
|
-
files:
|
|
2007
|
-
- <path> — <what changed there>
|
|
2008
|
-
notes:
|
|
2009
|
-
- <operator answers/decisions not yet recorded by a gate · reasons for uncommitted changes · the exact next action>
|
|
2010
|
-
blockers:
|
|
2011
|
-
- <what would fail Verified? right now> (or: none)`;
|
|
2012
|
-
|
|
2013
|
-
export interface StageReport {
|
|
2014
|
-
done: string[];
|
|
2015
|
-
files: string[];
|
|
2016
|
-
notes: string[];
|
|
2017
|
-
blockers: string[];
|
|
2018
|
-
/** true when the worker never emitted the block — the caller must treat the raw tail as suspect. */
|
|
2019
|
-
missing: boolean;
|
|
2020
|
-
/** bounded tail of the worker's final message (kept for the digest when missing, else for reference). */
|
|
2021
|
-
rawTail: string;
|
|
2022
|
-
}
|
|
2023
|
-
|
|
2024
|
-
/** Digest a stage worker's final message into the report contract. Lenient by design: a worker
|
|
2025
|
-
* that skipped the block yields `missing: true` plus its tail, never a throw at the end of a long stage. */
|
|
2026
|
-
export function parseStageReport(text: string): StageReport {
|
|
2027
|
-
const lines = (text ?? "").split("\n");
|
|
2028
|
-
let start = -1;
|
|
2029
|
-
for (let i = lines.length - 1; i >= 0; i--) {
|
|
2030
|
-
if (/^\s*[*_#>\s]*STAGE\s+REPORT[*_\s]*$/i.test(lines[i])) { start = i; break; }
|
|
2031
|
-
}
|
|
2032
|
-
const rep: StageReport = {
|
|
2033
|
-
done: [], files: [], notes: [], blockers: [],
|
|
2034
|
-
missing: start < 0,
|
|
2035
|
-
rawTail: lines.slice(-15).join("\n").slice(-600),
|
|
2036
|
-
};
|
|
2037
|
-
if (start < 0) return rep;
|
|
2038
|
-
type Section = "done" | "files" | "notes" | "blockers";
|
|
2039
|
-
let section: Section | null = null;
|
|
2040
|
-
for (const line of lines.slice(start + 1)) {
|
|
2041
|
-
const h = /^(done|files|notes|blockers)\s*[::]\s*$/i.exec(line.trim());
|
|
2042
|
-
if (h) { section = h[1].toLowerCase() as Section; continue; }
|
|
2043
|
-
const b = /^\s*[-*]\s+(.+)$/.exec(line);
|
|
2044
|
-
if (b && section) rep[section].push(b[1].trim());
|
|
2045
|
-
}
|
|
2046
|
-
rep.blockers = rep.blockers.filter((b) => !/^(none|no blockers?|n\/a|nothing)[-.\s]*$/i.test(b));
|
|
2047
|
-
return rep;
|
|
2048
|
-
}
|
|
1955
|
+
// ------------------------------------------------------------- stage worker (flow_stage)
|
|
2049
1956
|
|
|
2050
|
-
|
|
2051
|
-
* the context it just saved; the full transcript stays on disk, named in the caller's output. */
|
|
2052
|
-
export function renderStageReport(r: StageReport, cap = 4000): string {
|
|
2053
|
-
const parts: string[] = [];
|
|
2054
|
-
if (r.missing) parts.push("worker ended WITHOUT the STAGE REPORT block — digesting its raw tail, verify before trusting it:", "```", r.rawTail, "```");
|
|
2055
|
-
for (const s of ["done", "files", "notes"] as const)
|
|
2056
|
-
if (r[s].length) parts.push(`${s}:`, ...r[s].map((x) => `- ${x}`));
|
|
2057
|
-
if (r.blockers.length) parts.push("BLOCKERS:", ...r.blockers.map((x) => `- ${x}`));
|
|
2058
|
-
if (!parts.length) parts.push("(report block was empty)");
|
|
2059
|
-
const out = parts.join("\n");
|
|
2060
|
-
return out.length <= cap ? out : `${out.slice(0, cap)}\n…(digest truncated — full worker transcript on disk)`;
|
|
2061
|
-
}
|
|
1957
|
+
export type WorkerOp = "implement" | "review";
|
|
2062
1958
|
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
/** absolute path of the feature worktree — the worker's whole world. */
|
|
2067
|
-
workDir: string;
|
|
2068
|
-
/** absolute path of plan/plan.md in the main checkout (the worktree does not carry it). */
|
|
2069
|
-
planFile: string;
|
|
2070
|
-
/** the stage playbook reference contents ("" when the stage has none). */
|
|
2071
|
-
referenceText: string;
|
|
2072
|
-
/** truth as the driving session saw it: `flow status --json` output. */
|
|
2073
|
-
statusJson: string;
|
|
2074
|
-
/** `git status --porcelain -b` taken in the worktree before the worker starts. */
|
|
2075
|
-
gitSummary: string;
|
|
2076
|
-
/** what the parent session passes on: operator answers, decisions, warnings, the next action. */
|
|
2077
|
-
note?: string;
|
|
2078
|
-
}
|
|
2079
|
-
|
|
2080
|
-
/** The worker's complete brief: role, boundaries, on-disk truth, stage playbook, handoff note,
|
|
2081
|
-
* and the closing contract. Pure — the wiring reads the files and runs the git/status calls. */
|
|
2082
|
-
export function buildStageBrief(i: StageBriefInput): string {
|
|
2083
|
-
return `You are a dev-flow stage worker: you do the ${i.stage} work for feature "${i.slug}" and then report back. The flow itself belongs to a DIFFERENT session (the driving session): it owns the gates, the operator's checkpoint answers, and the claim. Work only inside ${i.workDir} (the feature worktree, on its branch).
|
|
2084
|
-
|
|
2085
|
-
Boundaries (the guard enforces these; do not work around them):
|
|
2086
|
-
- No gate commands, no flow verbs, no questions to the operator — the driving session runs every gate and asks every checkpoint. You owe the work and the report at the end.
|
|
2087
|
-
- .dev-flow state files (state.json, claim.json, project.md) are read-only.
|
|
2088
|
-
- Commit to the current feature branch EACH TIME a unit of work is complete (one module, one file-group, one screen) — if you are interrupted, that must cost one unit, never a dirty worktree. Never push, never merge, never touch the default branch, never write outside ${i.workDir}.
|
|
2089
|
-
|
|
2090
|
-
Start by reading the plan — ${i.planFile} — and whatever it points to.
|
|
2091
|
-
|
|
2092
|
-
Flow truth (\`flow status --json\` from the driving session):
|
|
2093
|
-
${i.statusJson}
|
|
2094
|
-
|
|
2095
|
-
Worktree state (\`git status --porcelain -b\`):
|
|
2096
|
-
${i.gitSummary || "(clean)"}
|
|
2097
|
-
|
|
2098
|
-
The stage playbook — what this stage owes when it exits (the gates you cannot see):
|
|
2099
|
-
${i.referenceText || "(this stage has no playbook reference)"}
|
|
2100
|
-
|
|
2101
|
-
Handoff note from the driving session (operator answers, decisions, warnings, the exact next action):
|
|
2102
|
-
${i.note?.trim() || "(none — the plan and the status above are your whole brief)"}
|
|
2103
|
-
|
|
2104
|
-
When you are done — finished OR blocked — stop doing work and close with the report.
|
|
2105
|
-
${STAGE_REPORT_CONTRACT}`;
|
|
2106
|
-
}
|
|
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"] };
|
|
2107
1962
|
|
|
2108
|
-
/**
|
|
2109
|
-
|
|
2110
|
-
* override. A playbook knob would move the default project-side — deliberately a later flow. */
|
|
2111
|
-
export const STAGE_BUDGET_DEFAULT_MIN = 45;
|
|
2112
|
-
export const STAGE_BUDGET_MIN_MIN = 5;
|
|
2113
|
-
export const STAGE_BUDGET_MAX_MIN = 120;
|
|
2114
|
-
export function clampStageBudgetMin(raw?: unknown): number {
|
|
2115
|
-
const n = typeof raw === "number" && Number.isFinite(raw) ? Math.round(raw) : STAGE_BUDGET_DEFAULT_MIN;
|
|
2116
|
-
return Math.min(STAGE_BUDGET_MAX_MIN, Math.max(STAGE_BUDGET_MIN_MIN, n));
|
|
2117
|
-
}
|
|
2118
|
-
|
|
2119
|
-
/** `mm:ss` for heartbeat, live-log and status lines. */
|
|
2120
|
-
export function stageElapsedLabel(ms: number): string {
|
|
2121
|
-
const s = Math.max(0, Math.floor(ms / 1000));
|
|
2122
|
-
return `${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`;
|
|
2123
|
-
}
|
|
2124
|
-
|
|
2125
|
-
/** One-summarization of a tool call's args for the live line: bash shows the command, edit/write the
|
|
2126
|
-
* path, anything else compact JSON — always capped. */
|
|
2127
|
-
export function summarizeToolArgs(args: unknown): string {
|
|
2128
|
-
const a = args as Record<string, unknown> | undefined;
|
|
2129
|
-
let s = "";
|
|
2130
|
-
if (a && typeof a === "object") {
|
|
2131
|
-
if (typeof a.command === "string") s = a.command;
|
|
2132
|
-
else if (typeof a.path === "string") s = a.path;
|
|
2133
|
-
else { try { s = JSON.stringify(a); } catch { s = ""; } }
|
|
2134
|
-
}
|
|
2135
|
-
s = s.replace(/\s+/g, " ").trim();
|
|
2136
|
-
return s.length > 60 ? `${s.slice(0, 57)}…` : s;
|
|
2137
|
-
}
|
|
1963
|
+
/** Default wall-clock budget per op, in minutes. */
|
|
1964
|
+
export const WORKER_BUDGET_MIN: Record<WorkerOp, number> = { implement: 60, review: 30 };
|
|
2138
1965
|
|
|
2139
|
-
/**
|
|
2140
|
-
|
|
2141
|
-
export function stageLiveLine(elapsedMs: number, toolName: string, argsSummary: string): string {
|
|
2142
|
-
return `[+${stageElapsedLabel(elapsedMs)}] ${toolName}${argsSummary ? ` — ${argsSummary}` : ""}`;
|
|
2143
|
-
}
|
|
2144
|
-
|
|
2145
|
-
/** The soft-landing order steered into a worker at 75% of its budget: commit what is done, report
|
|
2146
|
-
* the truth, stop starting new units. Beats an abort by one clean commit. */
|
|
2147
|
-
export function stageInterruptSteer(budgetMin: number): string {
|
|
2148
|
-
return `Budget spent (${budgetMin} min) — stop planning new work now. Finish only the edit you are mid-way through, commit everything that is done to the feature branch (a "wip(stage): …" commit is fine and expected), then close with the STAGE REPORT block: done lists what is committed, notes says what was never started and what may not compile, blockers says "interrupted at budget". Do not start new units.`;
|
|
2149
|
-
}
|
|
2150
|
-
|
|
2151
|
-
// ------------------------------------------------------- worker ops beyond the stage work (verify / reflect / live card)
|
|
2152
|
-
|
|
2153
|
-
/** Every `flow_stage` op. `run` is a stage's work; `verify` and `reflect` are check-only reviews —
|
|
2154
|
-
* they read and run commands but hold no edit or write, so the driving session gets independent eyes
|
|
2155
|
-
* without handing over a gate or a fix; `status` reads the live run and needs no worker at all. */
|
|
2156
|
-
export const WORKER_OPS = ["run", "verify", "reflect", "status"] as const;
|
|
2157
|
-
export type WorkerOp = (typeof WORKER_OPS)[number];
|
|
2158
|
-
export function isWorkerOp(s: string): s is WorkerOp {
|
|
2159
|
-
return (WORKER_OPS as readonly string[]).includes(s);
|
|
2160
|
-
}
|
|
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;
|
|
2161
1968
|
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
|
|
2165
|
-
export const WORKER_OP_BUDGET_MIN: Record<WorkerOp, number> = { run: STAGE_BUDGET_DEFAULT_MIN, verify: 30, reflect: 30, status: STAGE_BUDGET_DEFAULT_MIN };
|
|
2166
|
-
|
|
2167
|
-
/** Toolset per op — the guard still judges every write by the owning feature's stage, but a reviewer
|
|
2168
|
-
* that carries no edit or write tool cannot even try to fix what it is judging (standing order:
|
|
2169
|
-
* check, don't fix). `status` spawns nothing; the empty list is the marker, never a spawn. */
|
|
2170
|
-
export const WORKER_OP_TOOLS: Record<WorkerOp, readonly string[]> = {
|
|
2171
|
-
run: ["read", "bash", "edit", "write"],
|
|
2172
|
-
verify: ["read", "bash"],
|
|
2173
|
-
reflect: ["read", "bash"],
|
|
2174
|
-
status: [],
|
|
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)));
|
|
2175
1972
|
};
|
|
2176
1973
|
|
|
2177
|
-
/**
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
export function workerOpError(op: WorkerOp, st: { stage: Stage; approvals: Record<string, string> }): string | null {
|
|
2183
|
-
if (op === "verify" && st.stage !== "implement")
|
|
2184
|
-
return `a verify worker runs only while the feature is at implement (stage is "${st.stage}") — it proves the implement work before Verified?; pre-release review is the playbook's review command, and release/finish carry checkpoint words`;
|
|
2185
|
-
if (op === "reflect" && !(st.stage === "release" && st.approvals.release))
|
|
2186
|
-
return `a reflect worker runs at the release stage after release-done recorded the release (stage is "${st.stage}"${st.approvals.release ? "" : ", no release recorded"}) — it reviews the finished flow before flow finish deletes .dev-flow/<slug>/`;
|
|
2187
|
-
return null;
|
|
2188
|
-
}
|
|
2189
|
-
|
|
2190
|
-
/** Sentinel line that ends a verify worker's final message — the sibling of STAGE_REPORT_HEAD. The
|
|
2191
|
-
* verdict is machine-read: it is what the verify gate demands, so prose approval is never enough. */
|
|
2192
|
-
export const VERIFY_REPORT_HEAD = "VERIFY REPORT";
|
|
2193
|
-
|
|
2194
|
-
/** The verify worker's closing contract. `verdict` is a closed set on purpose: anything the parser
|
|
2195
|
-
* cannot read as pass/fail is treated as NO pass, so a hedged report never stamps the gate. */
|
|
2196
|
-
export const VERIFY_REPORT_CONTRACT = `Close your final message with exactly this block (empty sections say \`none\`):
|
|
2197
|
-
${VERIFY_REPORT_HEAD}
|
|
2198
|
-
verdict: pass | fail
|
|
2199
|
-
findings:
|
|
2200
|
-
- <one line per problem: what the plan requires, what the code does instead, file:line>
|
|
2201
|
-
evidence:
|
|
2202
|
-
- <one line per thing you ran: the command and what it printed>`;
|
|
2203
|
-
|
|
2204
|
-
export interface VerifyReport {
|
|
2205
|
-
/** null = no readable verdict (missing block, or a hedge where pass|fail was demanded). */
|
|
2206
|
-
verdict: "pass" | "fail" | null;
|
|
2207
|
-
findings: string[];
|
|
2208
|
-
evidence: string[];
|
|
2209
|
-
/** true when the worker never emitted the block. */
|
|
2210
|
-
missing: boolean;
|
|
2211
|
-
rawTail: string;
|
|
2212
|
-
}
|
|
2213
|
-
|
|
2214
|
-
/** Digest a verify worker's final message. A missing block or an unreadable verdict is a NON-pass —
|
|
2215
|
-
* the caller must not stamp the gate on anything it did not read. */
|
|
2216
|
-
export function parseVerifyReport(text: string): VerifyReport {
|
|
2217
|
-
const lines = (text ?? "").split("\n");
|
|
2218
|
-
let start = -1;
|
|
2219
|
-
for (let i = lines.length - 1; i >= 0; i--) {
|
|
2220
|
-
if (/^\s*[*_#>\s]*VERIFY\s+REPORT[*_\s]*$/i.test(lines[i])) { start = i; break; }
|
|
2221
|
-
}
|
|
2222
|
-
const rep: VerifyReport = { verdict: null, findings: [], evidence: [], missing: start < 0, rawTail: lines.slice(-15).join("\n").slice(-600) };
|
|
2223
|
-
if (start < 0) return rep;
|
|
2224
|
-
type Section = "findings" | "evidence";
|
|
2225
|
-
let section: Section | null = null;
|
|
2226
|
-
for (const line of lines.slice(start + 1)) {
|
|
2227
|
-
const v = /^\s*verdict\s*[:=]\s*([A-Za-z]+)/i.exec(line.trim());
|
|
2228
|
-
if (v) {
|
|
2229
|
-
const word = v[1].toLowerCase();
|
|
2230
|
-
rep.verdict = word === "pass" || word === "passes" || word === "passed" ? "pass" : word === "fail" || word === "failed" || word === "failing" ? "fail" : null;
|
|
2231
|
-
continue;
|
|
2232
|
-
}
|
|
2233
|
-
const h = /^(findings|evidence)\s*[:=]\s*$/i.exec(line.trim());
|
|
2234
|
-
if (h) { section = h[1].toLowerCase() as Section; continue; }
|
|
2235
|
-
const b = /^\s*[-*]\s+(.+)$/.exec(line);
|
|
2236
|
-
if (b && section) rep[section].push(b[1].trim());
|
|
2237
|
-
}
|
|
2238
|
-
rep.findings = rep.findings.filter((f) => !/^(none|no findings?|n\/a|nothing)[-.\s]*$/i.test(f));
|
|
2239
|
-
return rep;
|
|
2240
|
-
}
|
|
2241
|
-
|
|
2242
|
-
/** Parent-facing digest of a verify run — bounded like the stage digest; the full transcript is on
|
|
2243
|
-
* disk and named by the caller. */
|
|
2244
|
-
export function renderVerifyReport(r: VerifyReport, cap = 4000): string {
|
|
2245
|
-
const parts: string[] = [];
|
|
2246
|
-
if (r.missing) parts.push("verify worker ended WITHOUT the VERIFY REPORT block — there is NO verdict, the tree is not verified:", "```", r.rawTail, "```");
|
|
2247
|
-
else if (!r.verdict) parts.push("VERIFY REPORT carried no readable verdict (pass | fail was required) — treated as NO pass:", "```", r.rawTail, "```");
|
|
2248
|
-
else parts.push(`verdict: ${r.verdict.toUpperCase()}`);
|
|
2249
|
-
if (r.findings.length) parts.push("findings:", ...r.findings.map((x) => `- ${x}`));
|
|
2250
|
-
if (r.evidence.length) parts.push("evidence:", ...r.evidence.map((x) => `- ${x}`));
|
|
2251
|
-
if (!parts.length) parts.push("(report block was empty)");
|
|
2252
|
-
const out = parts.join("\n");
|
|
2253
|
-
return out.length <= cap ? out : `${out.slice(0, cap)}\n…(digest truncated — full worker transcript on disk)`;
|
|
2254
|
-
}
|
|
2255
|
-
|
|
2256
|
-
/** Key the verify-worker PASS rides under inside state.checks. Living there is not a shortcut, it is
|
|
2257
|
-
* the point: the PASS must die exactly when a tier-1 record dies (an edit-tool clear, a fingerprint
|
|
2258
|
-
* that moved), so the friction is precise — one edit, one re-run — and never sticky. */
|
|
2259
|
-
export const VERIFY_STAMP = "verify";
|
|
2260
|
-
|
|
2261
|
-
/** Stamp a PASS over the tree as it is now (fp = worktreeFingerprint; null = git could not answer,
|
|
2262
|
-
* and an unprovable stamp is a stamp that never looks stale — same rule as freshenChecks). */
|
|
2263
|
-
export function recordVerifyPass(state: FlowState, at: string, fp: string | null): void {
|
|
2264
|
-
state.checks[VERIFY_STAMP] = { ok: true, at, ...(fp ? { wt: fp } : {}) };
|
|
2265
|
-
}
|
|
2266
|
-
|
|
2267
|
-
/** How each op's session announces itself in the picker — the stage-line glyph vocabulary reused for
|
|
2268
|
-
* worker names, so a row reads as a role at a glance instead of N identical "stage worker" lines. */
|
|
2269
|
-
export const WORKER_OP_GLYPH: Record<WorkerOp, string> = { run: "🔨", verify: "🔍", reflect: "🏁", status: "👁" };
|
|
2270
|
-
|
|
2271
|
-
/** A driver-supplied purpose, made safe for a session name: control chars gone, whitespace collapsed,
|
|
2272
|
-
* clamped to ~32 chars on a word boundary. "" when nothing meaningful is left. */
|
|
2273
|
-
export function sanitizeWorkerLabel(raw: string): string {
|
|
2274
|
-
const s = raw.replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ").trim();
|
|
2275
|
-
if (s.length <= 32) return s;
|
|
2276
|
-
const cut = s.slice(0, 32);
|
|
2277
|
-
const at = cut.lastIndexOf(" ");
|
|
2278
|
-
return (at >= 16 ? cut.slice(0, at) : cut).trim();
|
|
2279
|
-
}
|
|
2280
|
-
|
|
2281
|
-
/** Session-name grammar: live `⏳ 🔨 #2 · wire ops`, done `✓ 🔨 #2 · 3 commits · wire ops`,
|
|
2282
|
-
* `✓ 🔍 · stamp attack · PASS`, `✗ 🔨 #3 · hard-cut`. The final rename answers "how did it end?"
|
|
2283
|
-
* without opening the row; the ordinal separates re-delegations when no label was given. */
|
|
2284
|
-
export function workerName(mark: string, glyph: string, seq: number | null, label: string, outcome?: string | null): string {
|
|
2285
|
-
const core = `${glyph}${seq ? ` #${seq}` : ""}${outcome ? ` · ${outcome}` : ""}${label ? ` · ${label}` : ""}`;
|
|
2286
|
-
return `${mark} ${core}`;
|
|
2287
|
-
}
|
|
2288
|
-
|
|
2289
|
-
/** Content hash of a feature's plan/ dir (sorted relpath + bytes; "" stable when absent). The verify
|
|
2290
|
-
* verdict was written AGAINST the plan, so a mid-stage plan edit must void the PASS exactly like a
|
|
2291
|
-
* worktree edit — the stamp fingerprint hashes the worktree TOGETHER WITH this. */
|
|
2292
|
-
export function planFingerprint(dir: string): string {
|
|
2293
|
-
const h = createHash("sha256");
|
|
2294
|
-
// absent and empty must not collide — an accidentally deleted plan dir is a different ground than an emptied one
|
|
2295
|
-
h.update(existsSync(dir) ? "present\0" : "absent\0");
|
|
2296
|
-
const walk = (d: string, rel: string) => {
|
|
2297
|
-
// the entry kind rides as a control char after the name — a text marker ("@link") would collide
|
|
2298
|
-
// with a real file literally named that, control chars in a name are the pathological remainder
|
|
2299
|
-
for (const e of readdirSync(d, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
2300
|
-
const p = path.join(d, e.name);
|
|
2301
|
-
if (e.isDirectory()) {
|
|
2302
|
-
h.update(`${rel}${e.name}\x01`);
|
|
2303
|
-
walk(p, `${rel}${e.name}/`);
|
|
2304
|
-
} else if (e.isSymbolicLink()) {
|
|
2305
|
-
// a symlinked plan hides its content behind the entry — hash the link AND what it resolves to
|
|
2306
|
-
h.update(`${rel}${e.name}\x02`).update(readlinkSync(p));
|
|
2307
|
-
try {
|
|
2308
|
-
h.update(readFileSync(p));
|
|
2309
|
-
} catch {
|
|
2310
|
-
/* dangling link: the target string is all there is */
|
|
2311
|
-
}
|
|
2312
|
-
} else if (e.isFile()) h.update(`${rel}${e.name}\x00`).update(readFileSync(p));
|
|
2313
|
-
else h.update(`${rel}${e.name}\x03`);
|
|
2314
|
-
}
|
|
2315
|
-
};
|
|
2316
|
-
if (existsSync(dir)) walk(dir, "");
|
|
2317
|
-
return h.digest("hex").slice(0, 16);
|
|
2318
|
-
}
|
|
2319
|
-
|
|
2320
|
-
/** A PASS the verify gate may accept? docs-mode flows are exempt exactly like tier-1 checks: a docs
|
|
2321
|
-
* flow runs no project command, so there is nothing for a checker to check beyond the operator. */
|
|
2322
|
-
export function verifyStampMissing(state: FlowState): boolean {
|
|
2323
|
-
if (state.docs) return false;
|
|
2324
|
-
return !state.checks[VERIFY_STAMP]?.ok;
|
|
2325
|
-
}
|
|
2326
|
-
|
|
2327
|
-
/** The verify gate's refusal line for a missing PASS — printed with the demand spelled out, because
|
|
2328
|
-
* the operator's question must never be asked on a tree nothing independent has looked at. */
|
|
2329
|
-
export const VERIFY_STAMP_REFUSAL = `no verify-worker PASS on this tree — run flow_stage { op: "verify" } and get its verdict: pass before asking Verified? (the PASS belongs to the tree it was read on: any worktree edit drops it like any tier-1 record; a docs flow is exempt)`;
|
|
2330
|
-
|
|
2331
|
-
/** The durable worker index inside .dev-flow/<slug>/stage-sessions/ — one line per finished worker. */
|
|
2332
|
-
export const TRANSCRIPTS_FILE = "transcripts.log";
|
|
2333
|
-
|
|
2334
|
-
/** `worker transcript: …` line appended to .dev-flow/<slug>/stage-sessions/transcripts.log — the
|
|
2335
|
-
* durable index the reflect worker reads (until now a transcript path lived only in the parent's
|
|
2336
|
-
* tool result, i.e. only as long as that session's context). */
|
|
2337
|
-
export function workerTranscriptLine(at: string, op: string, file: string): string {
|
|
2338
|
-
return `[${at}] worker transcript (${op}): ${file}`;
|
|
2339
|
-
}
|
|
2340
|
-
|
|
2341
|
-
/** Parse transcripts.log back into entries; anything unrecognised is skipped, the log is append-only
|
|
2342
|
-
* and hand-editable. Missing files are the caller's problem (a stale path still tells a reader a
|
|
2343
|
-
* worker ran). */
|
|
2344
|
-
export function parseWorkerTranscripts(text: string): { at: string; op: string; path: string }[] {
|
|
2345
|
-
const out: { at: string; op: string; path: string }[] = [];
|
|
2346
|
-
for (const line of (text ?? "").split("\n")) {
|
|
2347
|
-
const m = /^\s*\[(.*?)\]\s*worker transcript(?: \(([^)]*)\))?:\s*(\S+)/.exec(line);
|
|
2348
|
-
if (m) out.push({ at: m[1], op: m[2] ?? "run", path: m[3] });
|
|
2349
|
-
}
|
|
2350
|
-
return out;
|
|
2351
|
-
}
|
|
2352
|
-
|
|
2353
|
-
/** The durable delegation ledger inside .dev-flow/<slug>/stage-sessions/ — one line per finished
|
|
2354
|
-
* `flow_stage` run worker, written by the same completion code that counts its commits. Read fresh
|
|
2355
|
-
* at the gate, never folded into state.checks: those records mean "this tree was checked", a window
|
|
2356
|
-
* means "this range was worked by a worker", and re-running a check must not erase the history the
|
|
2357
|
-
* branch rests on (transcripts.log rides outside state for the same reason). */
|
|
2358
|
-
export const DELEGATIONS_FILE = "delegations.log";
|
|
2359
|
-
|
|
2360
|
-
/** The folder inside .dev-flow/<slug>/ that holds the worker logs (transcripts.log, delegations.log) —
|
|
2361
|
-
* also half of what makes a delegations.log a delegation ledger (see isDelegationLedger). */
|
|
2362
|
-
export const STAGE_SESSIONS_DIR = "stage-sessions";
|
|
2363
|
-
|
|
2364
|
-
/** One finished worker run: the stage it worked and the commit range it left behind. */
|
|
2365
|
-
export interface DelegationWindow {
|
|
2366
|
-
stage: string;
|
|
2367
|
-
start: string;
|
|
2368
|
-
end: string;
|
|
2369
|
-
}
|
|
2370
|
-
|
|
2371
|
-
/** A delegations.log line. The line carries a **range**, not a count, because a range is what the
|
|
2372
|
-
* gate can re-check: an amend or a rebase after the fact moves the sha out of every recorded window,
|
|
2373
|
-
* which no write guard could ever see — bash-authored commits name no author, a rewritten sha does. */
|
|
2374
|
-
export function delegationLine(at: string, stage: string, start: string, end: string, commits: number): string {
|
|
2375
|
-
return `[${at}] run (${stage}): ${start}..${end} ${commits} commit(s)`;
|
|
2376
|
-
}
|
|
2377
|
-
|
|
2378
|
-
/** Parse delegations.log back into windows; anything unrecognised is skipped — the log is append-only
|
|
2379
|
-
* and hand-editable, and an index that throws would take the gate down with it (transcripts.log's
|
|
2380
|
-
* rule). Shas must look like shas so a typo'd line is simply not a window, rather than a window
|
|
2381
|
-
* whose `git rev-list` fails for a reason the gate could only guess at. */
|
|
2382
|
-
export function parseDelegationLedger(text: string): DelegationWindow[] {
|
|
2383
|
-
const out: DelegationWindow[] = [];
|
|
2384
|
-
for (const line of (text ?? "").split("\n")) {
|
|
2385
|
-
const m = /^\s*\[(.*?)\]\s*run(?: \(([^)]*)\))?:\s*([0-9a-f]{7,40})\.\.([0-9a-f]{7,40})/i.exec(line);
|
|
2386
|
-
if (m) out.push({ stage: m[2] ?? "run", start: m[3], end: m[4] });
|
|
2387
|
-
}
|
|
2388
|
-
return out;
|
|
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}`;
|
|
2389
1979
|
}
|
|
2390
1980
|
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
export const DELEGATION_REFUSAL = `the implement work was not delegated — run flow_stage { stage: "implement" } and let the worker session do the edits and commits (this session keeps the gates, the checkpoint and flow check)`;
|
|
2394
|
-
|
|
2395
|
-
/** Was the implement stage worked, or merely driven? The rule `flow verify` enforces: at least one
|
|
2396
|
-
* implement-stage run window carries a commit, and every commit the branch holds over its default
|
|
2397
|
-
* branch falls inside some implement-stage window. `windowCommits` resolves a window to its shas —
|
|
2398
|
-
* git lives on the caller's side, so this stays a pure function under test.
|
|
2399
|
-
* `branchCommits === null` (git could not answer) returns no errors: an unprovable answer is never
|
|
2400
|
-
* proof of a violation, the BranchState.commitsAhead rule. `--docs` and `--patch` are exempt exactly
|
|
2401
|
-
* like the verify stamp and the tier-1 checks — those two modes are the work the operator granted
|
|
2402
|
-
* inline. Coverage is judged only here: commits the driver makes after verify (changelog, bump) are
|
|
2403
|
-
* pre-release work and belong to the session by design. */
|
|
2404
|
-
export function delegationErrors(
|
|
2405
|
-
state: FlowState,
|
|
2406
|
-
ledger: DelegationWindow[],
|
|
2407
|
-
branchCommits: string[] | null,
|
|
2408
|
-
windowCommits: (w: DelegationWindow) => string[],
|
|
2409
|
-
): string[] {
|
|
2410
|
-
if (state.docs || state.patch) return [];
|
|
2411
|
-
if (branchCommits === null) return [];
|
|
2412
|
-
// Nothing on the branch to attribute: coverage is a claim about commits, and an empty branch has
|
|
2413
|
-
// none. verifyGate already refuses a branch with nothing committed — one refusal per fact.
|
|
2414
|
-
if (!branchCommits.length) return [];
|
|
2415
|
-
const covered = new Set<string>();
|
|
2416
|
-
for (const w of ledger.filter((x) => x.stage === "implement")) for (const sha of windowCommits(w) ?? []) covered.add(sha);
|
|
2417
|
-
// A window whose range holds nothing proves a worker ran and delivered nothing: the stage is still
|
|
2418
|
-
// undelivered, and "N commit(s) outside a window" on top of that names the same fact twice with
|
|
2419
|
-
// worse advice — there is nothing to redo, there is nothing yet.
|
|
2420
|
-
if (!covered.size) return [DELEGATION_REFUSAL];
|
|
2421
|
-
const strays = branchCommits.filter((sha) => !covered.has(sha));
|
|
2422
|
-
if (!strays.length) return [];
|
|
2423
|
-
return [`${strays.length} commit(s) on the branch were made outside a worker run — delegate a fixer that redoes them (or reset them)`];
|
|
2424
|
-
}
|
|
2425
|
-
|
|
2426
|
-
/** How many live lines the card and `op: "status"` show: enough to see what the worker is doing,
|
|
2427
|
-
* bounded so a long stage never spends the context the delegation just saved (R6). */
|
|
2428
|
-
export const LIVE_TAIL_ITEMS = 8;
|
|
2429
|
-
/** One live line's cap — worker output is signal in a tail, noise in bulk. */
|
|
2430
|
-
const LIVE_LINE_CAP = 110;
|
|
2431
|
-
|
|
2432
|
-
/** One line of a worker's assistant prose, for the live tail: last non-empty line only (a worker
|
|
2433
|
-
* narrating a plan would otherwise drown its own tool activity). */
|
|
2434
|
-
export function stageLiveAssistantLine(elapsedMs: number, text: string): string {
|
|
2435
|
-
const lines = (text ?? "").split("\n").map((l) => l.trim()).filter(Boolean);
|
|
2436
|
-
if (!lines.length) return "";
|
|
2437
|
-
// its own shape, not stageLiveLine's: prose is not `tool — args`, an em dash in front of every
|
|
2438
|
-
// sentence the worker wrote would read as a tool call that happened to talk
|
|
2439
|
-
return `[+${stageElapsedLabel(elapsedMs)}] ✎ ${liveClip(lines[lines.length - 1])}`;
|
|
2440
|
-
}
|
|
2441
|
-
/** A finished tool call: ✓/✗ plus one line of what came back — the difference between "it is running"
|
|
2442
|
-
* and "it is getting somewhere". */
|
|
2443
|
-
export function stageLiveResultLine(elapsedMs: number, toolName: string, ok: boolean, summary: string): string {
|
|
2444
|
-
return stageLiveLine(elapsedMs, `${ok ? "✓" : "✗"} ${toolName}`, liveClip(summary));
|
|
2445
|
-
}
|
|
2446
|
-
|
|
2447
|
-
|
|
2448
|
-
export function liveClip(s: string, cap = LIVE_LINE_CAP): string {
|
|
2449
|
-
const one = (s ?? "").replace(/\s+/g, " ").trim();
|
|
2450
|
-
return one.length > cap ? `${one.slice(0, cap - 1)}…` : one;
|
|
2451
|
-
}
|
|
2452
|
-
|
|
2453
|
-
/** The bounded tail: `… M earlier items` then the last `max` lines (empty lines never counted —
|
|
2454
|
-
* a skipped assistant narration must not push real activity off the card). */
|
|
2455
|
-
export function liveTail(lines: string[], max = LIVE_TAIL_ITEMS): string[] {
|
|
2456
|
-
const kept = lines.filter(Boolean);
|
|
2457
|
-
if (kept.length <= max) return kept;
|
|
2458
|
-
return [`… ${kept.length - max} earlier items`, ...kept.slice(-max)];
|
|
2459
|
-
}
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
/** Everything the live tool card needs to draw one frame. The card is the guaranteed visibility
|
|
2463
|
-
* surface (it renders in the driver's own transcript on every host), so it is built from plain
|
|
2464
|
-
* strings here and wrapped into components by the extension — the same lines reach a host that only
|
|
2465
|
-
* shows the update's text (pi-web) and the no-UI fallback `op: "status"`. */
|
|
2466
|
-
export interface StageCardView {
|
|
2467
|
-
kind: string;
|
|
1981
|
+
export interface WorkerBriefInput {
|
|
1982
|
+
op: WorkerOp;
|
|
2468
1983
|
slug: string;
|
|
2469
|
-
elapsedMs: number;
|
|
2470
|
-
budgetMin: number;
|
|
2471
|
-
softFired?: boolean;
|
|
2472
|
-
tail?: string[];
|
|
2473
|
-
usage?: string;
|
|
2474
|
-
state?: "running" | "done" | "failed";
|
|
2475
|
-
verdict?: "pass" | "fail" | null;
|
|
2476
|
-
note?: string;
|
|
2477
|
-
transcript?: string;
|
|
2478
|
-
/** settled card only: the flow's other workers, already rendered by `workerFamily`. */
|
|
2479
|
-
family?: string[];
|
|
2480
|
-
/** heading for `family` when the rows came from somewhere coarser than pi's listing. */
|
|
2481
|
-
familyHeading?: string;
|
|
2482
|
-
}
|
|
2483
|
-
|
|
2484
|
-
/** One frame of the worker card: header (what · where · clock against budget), the bounded live tail,
|
|
2485
|
-
* the verdict once there is one, and what it cost. Expanded widens the tail and names the transcript. */
|
|
2486
|
-
export function stageCardLines(v: StageCardView, expanded = false): string[] {
|
|
2487
|
-
const glyph = v.state === "failed" ? "✗" : v.state === "done" ? "✓" : "⏳";
|
|
2488
|
-
const out = [`${glyph} ${v.kind} · ${v.slug} · ${stageElapsedLabel(v.elapsedMs)}/${v.budgetMin}m${v.softFired ? " · closing out" : ""}`];
|
|
2489
|
-
if (v.note) out.push(`note: ${liveClip(v.note, 80)}`);
|
|
2490
|
-
out.push(...liveTail(v.tail ?? [], expanded ? LIVE_TAIL_ITEMS * 4 : LIVE_TAIL_ITEMS));
|
|
2491
|
-
if (v.verdict) out.push(`verdict: ${v.verdict.toUpperCase()}`);
|
|
2492
|
-
if (v.usage) out.push(v.usage);
|
|
2493
|
-
if (expanded && v.transcript) out.push(`transcript: ${v.transcript}`);
|
|
2494
|
-
// the family only on the settled card: listing a session directory is IO, and a live frame
|
|
2495
|
-
// redraws on every worker tool call — a running run must not pay for a directory read
|
|
2496
|
-
if (expanded && v.family?.length) out.push(v.familyHeading ?? familyHeading(), ...v.family);
|
|
2497
|
-
return out;
|
|
2498
|
-
}
|
|
2499
|
-
|
|
2500
|
-
/** One worker session as pi's own session listing describes it. dev-flow keeps no lineage index
|
|
2501
|
-
* of its own: the `parentSession` link in a session header *is* the record, and pi's picker threads
|
|
2502
|
-
* on it. The extension reads pi's types and maps them onto this pi-free shape so the logic here
|
|
2503
|
-
* stays unit-testable. */
|
|
2504
|
-
export interface WorkerSessionRow {
|
|
2505
|
-
/** the worker's session file */
|
|
2506
|
-
path: string;
|
|
2507
|
-
/** the parent link as pi recorded it (`parentSession`); absent = not somebody's child */
|
|
2508
|
-
parent?: string | null;
|
|
2509
|
-
/** the picker display name — it carries the ⏳/✓/✗ and the outcome the driver stamps on it */
|
|
2510
|
-
name?: string;
|
|
2511
|
-
messageCount?: number;
|
|
2512
|
-
/** file mtime, however the host hands it over (pi gives a Date; tests give a number) */
|
|
2513
|
-
modified?: Date | number | string;
|
|
2514
|
-
}
|
|
2515
|
-
|
|
2516
|
-
/** How many workers one render lists before it folds the older ones. */
|
|
2517
|
-
export const WORKER_FAMILY_ITEMS = 12;
|
|
2518
|
-
|
|
2519
|
-
/** Family rendering options: `exclude` drops one transcript — the live or just-finished run, which
|
|
2520
|
-
* the caller already shows as its own section or its own line. */
|
|
2521
|
-
export interface WorkerFamilyOptions {
|
|
2522
|
-
exclude?: string;
|
|
2523
|
-
}
|
|
2524
|
-
|
|
2525
|
-
/** The heading over a family list — the one place the wording lives, so the status text and the card
|
|
2526
|
-
* cannot drift, and so a list that came from the ledger (no message counts, no renames) says so. */
|
|
2527
|
-
export function familyHeading(o: { live?: boolean; ledger?: boolean } = {}): string {
|
|
2528
|
-
return `${o.live ? "other workers this session spawned" : "workers this session spawned"}${o.ledger ? " (from the flow's ledger — this host has no session file to nest)" : ""}:`;
|
|
2529
|
-
}
|
|
2530
|
-
|
|
2531
|
-
/** The same session file written two ways is still one session (separators, trailing slash, and on
|
|
2532
|
-
* Windows the case of the drive letter). pi's own picker canonicalizes the same idea. */
|
|
2533
|
-
export function sessionPathKey(p: string): string {
|
|
2534
|
-
const k = path.resolve(p).replace(/[\\/]+$/, "");
|
|
2535
|
-
return process.platform === "win32" ? k.toLowerCase() : k;
|
|
2536
|
-
}
|
|
2537
|
-
|
|
2538
|
-
function sessionTime(row: WorkerSessionRow): number {
|
|
2539
|
-
const raw = row.modified instanceof Date ? row.modified.getTime() : typeof row.modified === "number" ? row.modified : row.modified ? Date.parse(row.modified) : 0;
|
|
2540
|
-
return Number.isFinite(raw) ? raw : 0;
|
|
2541
|
-
}
|
|
2542
|
-
|
|
2543
|
-
/**
|
|
2544
|
-
* The family — every stage worker this session spawned, newest first, one line each.
|
|
2545
|
-
*
|
|
2546
|
-
* A stage worker is a real pi session whose header carries `parentSession` pointing at the driver's
|
|
2547
|
-
* own file, so pi's picker nests it under the driver by itself (Threaded sort). This reads the same
|
|
2548
|
-
* fact back for every surface that has no tree: the `flow_stage` card and `op: "status"`. Nothing is
|
|
2549
|
-
* stored here, so a renamed worker (`✓ 🔍 · PASS · stamp attack`) reads back renamed, and workers a
|
|
2550
|
-
* previous session already delegated show up next to this one's.
|
|
2551
|
-
*/
|
|
2552
|
-
export function workerFamily(rows: WorkerSessionRow[], driverFile: string | null | undefined, opts: WorkerFamilyOptions = {}): string[] {
|
|
2553
|
-
if (!driverFile) return [];
|
|
2554
|
-
const max = WORKER_FAMILY_ITEMS;
|
|
2555
|
-
const drop = opts.exclude ? sessionPathKey(opts.exclude) : null;
|
|
2556
|
-
const mine = rows
|
|
2557
|
-
.filter((r) => r.parent && sessionPathKey(r.parent) === sessionPathKey(driverFile) && (!drop || sessionPathKey(r.path) !== drop))
|
|
2558
|
-
.sort((a, b) => sessionTime(b) - sessionTime(a));
|
|
2559
|
-
const shown = mine.slice(0, max);
|
|
2560
|
-
const lines = shown.map((r) => {
|
|
2561
|
-
const at = sessionTime(r);
|
|
2562
|
-
return `${r.name?.trim() || "(unnamed worker)"} · ${r.messageCount ?? 0} msgs · ${at ? localStamp(at) : "time unknown"} · ${r.path}`;
|
|
2563
|
-
});
|
|
2564
|
-
if (mine.length > shown.length) lines.push(familyFoldLine(mine.length - shown.length));
|
|
2565
|
-
return lines;
|
|
2566
|
-
}
|
|
2567
|
-
|
|
2568
|
-
/** A transcript's header parent link, read from its first line alone — the cheap pass of the family
|
|
2569
|
-
* scan. Returns `undefined` for a file that is not a pi session (or has no complete first line in
|
|
2570
|
-
* the bytes read), `null` for a session that is nobody's child. */
|
|
2571
|
-
export function sessionHeaderParent(head: string): string | null | undefined {
|
|
2572
|
-
const nl = head.indexOf("\n");
|
|
2573
|
-
if (nl < 0) return undefined;
|
|
2574
|
-
try {
|
|
2575
|
-
const h = JSON.parse(head.slice(0, nl)) as { type?: string; parentSession?: unknown };
|
|
2576
|
-
if (h?.type !== "session") return undefined;
|
|
2577
|
-
return typeof h.parentSession === "string" && h.parentSession ? h.parentSession : null;
|
|
2578
|
-
} catch {
|
|
2579
|
-
return undefined;
|
|
2580
|
-
}
|
|
2581
|
-
}
|
|
2582
|
-
|
|
2583
|
-
/** The fields the family view needs, from one transcript's full text — the same rules pi's own
|
|
2584
|
-
* session listing applies (latest `session_info` name wins, explicit clears included; messages are
|
|
2585
|
-
* `message` entries; last activity is the newest user/assistant message, else the header time).
|
|
2586
|
-
* Only the few files whose header names the driver reach this — that is what keeps a family read
|
|
2587
|
-
* proportional to the family, not to the bucket's whole history. */
|
|
2588
|
-
export function parseSessionSummary(text: string, file: string, mtimeMs?: number): WorkerSessionRow | null {
|
|
2589
|
-
type Header = { timestamp?: unknown; parentSession?: unknown };
|
|
2590
|
-
let header: Header | null = null;
|
|
2591
|
-
let name: string | undefined;
|
|
2592
|
-
let messageCount = 0;
|
|
2593
|
-
let last: number | undefined;
|
|
2594
|
-
for (const line of text.split("\n")) {
|
|
2595
|
-
if (!line.trim()) continue;
|
|
2596
|
-
let e: { type?: string; name?: unknown; timestamp?: unknown; message?: { role?: string; content?: unknown; timestamp?: unknown } };
|
|
2597
|
-
try { e = JSON.parse(line); } catch { continue; }
|
|
2598
|
-
if (!header) {
|
|
2599
|
-
if (e?.type !== "session") return null;
|
|
2600
|
-
header = e as Header;
|
|
2601
|
-
continue;
|
|
2602
|
-
}
|
|
2603
|
-
if (e.type === "session_info") name = typeof e.name === "string" ? e.name.trim() || undefined : undefined;
|
|
2604
|
-
if (e.type !== "message") continue;
|
|
2605
|
-
messageCount++;
|
|
2606
|
-
const m = e.message;
|
|
2607
|
-
if (!m || m.content === undefined || (m.role !== "user" && m.role !== "assistant")) continue;
|
|
2608
|
-
const t = typeof m.timestamp === "number" ? m.timestamp : Date.parse(String(e.timestamp));
|
|
2609
|
-
if (Number.isFinite(t)) last = Math.max(last ?? 0, t);
|
|
2610
|
-
}
|
|
2611
|
-
if (!header) return null;
|
|
2612
|
-
const headerTime = typeof header.timestamp === "string" ? Date.parse(header.timestamp) : NaN;
|
|
2613
|
-
const modified = last && last > 0 ? last : Number.isFinite(headerTime) ? headerTime : mtimeMs;
|
|
2614
|
-
return { path: file, parent: typeof header.parentSession === "string" ? header.parentSession : null, name, messageCount, modified };
|
|
2615
|
-
}
|
|
2616
|
-
|
|
2617
|
-
/** pi's bucket name for a working directory (`--home-me-repo--`), the same encoding pi applies
|
|
2618
|
-
* (`getDefaultSessionDirPath`). Used only to RECOGNIZE buckets, never to choose where a session goes. */
|
|
2619
|
-
export function sessionBucketName(cwd: string): string {
|
|
2620
|
-
return `--${path.resolve(cwd).replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
|
|
2621
|
-
}
|
|
2622
|
-
|
|
2623
|
-
/** What the doctor needs to judge one feature's worktree bucket. */
|
|
2624
|
-
export interface WorktreeBucketFeature {
|
|
2625
|
-
/** the slug's state is gone, done or aborted — nothing will delegate into this worktree again */
|
|
2626
|
-
finished: boolean;
|
|
2627
|
-
worktreeExists: boolean;
|
|
2628
|
-
}
|
|
2629
|
-
|
|
2630
|
-
/**
|
|
2631
|
-
* Session buckets stage workers left behind before 0.70 put workers in the driver's bucket. Such a
|
|
2632
|
-
* worker ran with cwd = the feature worktree, so pi filed it under that worktree's own bucket — which
|
|
2633
|
-
* no folder scope opened from the main checkout ever shows, and which outlives the worktree. A bucket
|
|
2634
|
-
* is reported when it encodes `<root>/.dev-flow/<slug>/worktree` and that slug is finished or its
|
|
2635
|
-
* worktree is gone. `features` is keyed by slug; a slug absent from it has no state at all (finished).
|
|
2636
|
-
*/
|
|
2637
|
-
export function orphanWorktreeBuckets(buckets: string[], root: string, features: Map<string, WorktreeBucketFeature>): { bucket: string; slug: string }[] {
|
|
2638
|
-
const prefix = sessionBucketName(path.join(root, ".dev-flow")).slice(0, -2) + "-";
|
|
2639
|
-
const out: { bucket: string; slug: string }[] = [];
|
|
2640
|
-
for (const b of buckets) {
|
|
2641
|
-
if (!b.startsWith(prefix) || !b.endsWith("-worktree--")) continue;
|
|
2642
|
-
const encSlug = b.slice(prefix.length, -"-worktree--".length);
|
|
2643
|
-
if (!encSlug) continue;
|
|
2644
|
-
// slugs are kebab-case, which the encoding leaves intact; a slug that is a known feature wins
|
|
2645
|
-
const f = features.get(encSlug);
|
|
2646
|
-
if (f && !f.finished && f.worktreeExists) continue;
|
|
2647
|
-
out.push({ bucket: b, slug: encSlug });
|
|
2648
|
-
}
|
|
2649
|
-
return out;
|
|
2650
|
-
}
|
|
2651
|
-
|
|
2652
|
-
/** Stage workers spawned in THIS process, by session id. A worker loads the operator's extensions —
|
|
2653
|
-
* dev-flow among them, because its guards must hold inside the worker too — but the driver's context
|
|
2654
|
-
* (the playbook core, the unbound-session posture, "surface this to the operator") is wrong there:
|
|
2655
|
-
* the brief is the worker's whole instruction. The worker's loader imports dev-flow as its own
|
|
2656
|
-
* module instance, so the registry lives on a process-global symbol both instances can see. */
|
|
2657
|
-
const WORKER_SESSIONS = Symbol.for("dev-flow.workerSessions");
|
|
2658
|
-
function workerSessionSet(): Set<string> {
|
|
2659
|
-
const g = globalThis as unknown as Record<symbol, Set<string> | undefined>;
|
|
2660
|
-
return (g[WORKER_SESSIONS] ??= new Set<string>());
|
|
2661
|
-
}
|
|
2662
|
-
export function markWorkerSession(id: string | undefined | null): void {
|
|
2663
|
-
if (id) workerSessionSet().add(id);
|
|
2664
|
-
}
|
|
2665
|
-
export function isWorkerSession(id: string | undefined | null): boolean {
|
|
2666
|
-
return !!id && workerSessionSet().has(id);
|
|
2667
|
-
}
|
|
2668
|
-
|
|
2669
|
-
/** The line that stands in for the workers too old to list. It is not a worker, so anything counting
|
|
2670
|
-
* the list has to know it — and both sources fold the same way, so the shape lives here. */
|
|
2671
|
-
export function familyFoldLine(dropped: number): string {
|
|
2672
|
-
return `… ${dropped} earlier workers`;
|
|
2673
|
-
}
|
|
2674
|
-
|
|
2675
|
-
export function isFamilyFoldLine(line: string): boolean {
|
|
2676
|
-
return line.startsWith("… ");
|
|
2677
|
-
}
|
|
2678
|
-
|
|
2679
|
-
/** How many workers a rendered family list stands for: the fold line is a count, not a worker. */
|
|
2680
|
-
export function workerFamilyCount(lines: string[] | null | undefined): number | null {
|
|
2681
|
-
if (!lines) return null;
|
|
2682
|
-
return lines.filter((l) => !isFamilyFoldLine(l)).length;
|
|
2683
|
-
}
|
|
2684
|
-
|
|
2685
|
-
/** Local wall-clock `YYYY-MM-DD HH:mm` — the convention every dev-flow timestamp follows (a UTC
|
|
2686
|
-
* stamp next to the operator's own clock reads as a future or past session, and the family line is
|
|
2687
|
-
* meant to be scanned, not converted). */
|
|
2688
|
-
function localStamp(ms: number): string {
|
|
2689
|
-
const d = new Date(ms);
|
|
2690
|
-
const p = (n: number) => String(n).padStart(2, "0");
|
|
2691
|
-
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
|
|
2692
|
-
}
|
|
2693
|
-
|
|
2694
|
-
/** What the tool accumulated from a worker's assistant usage records. */
|
|
2695
|
-
export interface StageUsage {
|
|
2696
|
-
input: number;
|
|
2697
|
-
output: number;
|
|
2698
|
-
cacheRead: number;
|
|
2699
|
-
cacheWrite: number;
|
|
2700
|
-
totalTokens: number;
|
|
2701
|
-
cost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };
|
|
2702
|
-
}
|
|
2703
|
-
|
|
2704
|
-
/** One compact usage line for the card and the result: what the run cost, at a glance. */
|
|
2705
|
-
export function stageUsageLine(u: StageUsage, turns?: number): string {
|
|
2706
|
-
const k = (n: number) => (n >= 1000 ? `${(n / 1000).toFixed(n >= 100_000 ? 0 : 1)}k` : String(n));
|
|
2707
|
-
const ctx = u.cacheRead + u.input + u.output;
|
|
2708
|
-
return `${turns ? `${turns} turns · ` : ""}↑${k(u.input)} ↓${k(u.output)} · ctx ${k(ctx)} · $${u.cost.total.toFixed(4)}`;
|
|
2709
|
-
}
|
|
2710
|
-
|
|
2711
|
-
export interface VerifyBriefInput {
|
|
2712
|
-
slug: string;
|
|
2713
|
-
/** absolute path of the feature worktree — the reviewer's whole world. */
|
|
2714
1984
|
workDir: string;
|
|
2715
|
-
/** absolute path of plan/plan.md in the main checkout. */
|
|
2716
1985
|
planFile: string;
|
|
2717
|
-
statusJson: string;
|
|
2718
|
-
/** `git status --porcelain -b` in the worktree, before the run. */
|
|
2719
|
-
gitSummary: string;
|
|
2720
|
-
/** `git diff --stat <default>…HEAD` — the shape of what is under review; the reviewer reads the
|
|
2721
|
-
* full diff itself (pasting it here would spend the context the delegation saves). */
|
|
2722
|
-
diffStat: string;
|
|
2723
|
-
/** tier-1 commands the playbook says must be green (name + command). */
|
|
2724
|
-
checks: { name: string; cmd: string }[];
|
|
2725
|
-
/** the driver's default branch, for the diff range. */
|
|
2726
1986
|
defaultBranch: string;
|
|
2727
|
-
|
|
2728
|
-
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
2748
|
-
|
|
2749
|
-
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
|
|
2769
|
-
|
|
2770
|
-
|
|
2771
|
-
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
|
|
2775
|
-
|
|
2776
|
-
other: string[];
|
|
2777
|
-
/** true when no tagged line was found at all — the reviewer produced prose, not findings. */
|
|
2778
|
-
missing: boolean;
|
|
2779
|
-
rawTail: string;
|
|
2780
|
-
}
|
|
2781
|
-
|
|
2782
|
-
/** Split a reflect worker's message into tagged findings. Bullets, bold and inline code around the
|
|
2783
|
-
* tag are tolerated: a model decorates, and re-parsing prose by hand in the driver is worse. */
|
|
2784
|
-
export function parseReflectFindings(text: string): ReflectFindings {
|
|
2785
|
-
const out: ReflectFindings = { playbook: [], plugin: [], other: [], missing: true, rawTail: (text ?? "").split("\n").slice(-15).join("\n").slice(-600) };
|
|
2786
|
-
|
|
2787
|
-
for (const line of (text ?? "").split("\n")) {
|
|
2788
|
-
// bracketed tag (the contract) or a bare `plugin:` lead-in; markdown decoration is noise around it
|
|
2789
|
-
const m = /^\s*(?:[-*>]\s*)?[*_`]*\s*\[\s*(playbook|plugin|neither|other)\s*\]\s*[*_`]*\s*(?:[:—-]\s*)?(.+)$|^\s*(?:[-*>]\s*)?[*_`]*\s*(playbook|plugin)\s*:\s*(.+)$/i.exec(line.trim());
|
|
2790
|
-
if (!m) continue;
|
|
2791
|
-
const body = (m[2] ?? m[4]).replace(/[*`\s]+$/, "").trim();
|
|
2792
|
-
if (!body || /^(none|n\/a|nothing)[-.\s]*$/i.test(body)) continue;
|
|
2793
|
-
const kind = (m[1] ?? m[3]).toLowerCase();
|
|
2794
|
-
if (kind === "playbook") out.playbook.push(body);
|
|
2795
|
-
else if (kind === "plugin") out.plugin.push(body);
|
|
2796
|
-
else out.other.push(body);
|
|
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; }
|
|
2797
2036
|
}
|
|
2798
|
-
|
|
2799
|
-
|
|
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 };
|
|
2800
2041
|
}
|
|
2801
2042
|
|
|
2802
|
-
|
|
2803
|
-
|
|
2804
|
-
planFile: string;
|
|
2805
|
-
statusJson: string;
|
|
2806
|
-
/** The driver's own session file (JSONL) — pre-compaction turns live there even after the driver's
|
|
2807
|
-
* context was summarized away, which is exactly what a finish review needs. */
|
|
2808
|
-
driverSession: string | null;
|
|
2809
|
-
/** Every worker transcript recorded in transcripts.log, oldest first. */
|
|
2810
|
-
transcripts: { at: string; op: string; path: string }[];
|
|
2811
|
-
/** Open reflection lines, so a finding already queued is not queued twice. */
|
|
2812
|
-
openReflections: string[];
|
|
2813
|
-
note?: string;
|
|
2814
|
-
}
|
|
2815
|
-
|
|
2816
|
-
/** The reflect worker's brief: an independent reviewer of the WHOLE flow — driver included. It
|
|
2817
|
-
* cannot ask the operator anything and cannot write, so it returns tagged findings the driver puts to
|
|
2818
|
-
* the operator (fold / fix / drop stays the operator's call, as always). */
|
|
2819
|
-
export function buildReflectBrief(i: ReflectBriefInput): string {
|
|
2820
|
-
const tlist = i.transcripts.length
|
|
2821
|
-
? i.transcripts.map((t) => `- ${t.op} worker (${t.at}): ${t.path}${existsSync(t.path) ? "" : " (file is gone — note it, do not invent it)"}`).join("\n")
|
|
2822
|
-
: "- (this flow delegated nothing — review the driver session alone)";
|
|
2823
|
-
const open = i.openReflections.length ? i.openReflections.map((l) => `- ${l}`).join("\n") : "- none";
|
|
2824
|
-
return `You are a dev-flow REFLECT worker: an independent reviewer of the finished flow "${i.slug}". You review the DRIVER session — the session that drove the flow — plus every worker it delegated, and you report what the process should learn. You are not the driver, so nothing here is defensive: name the wasted turn, the gate that misfired, the playbook line that lied.
|
|
2825
|
-
|
|
2826
|
-
Standing order — read-only: read and bash only. Never edit, write, commit, push, run a flow gate, or ask the operator anything. Reading git logs and files through bash is expected.
|
|
2827
|
-
|
|
2828
|
-
Read the whole flow, in this order:
|
|
2829
|
-
1. the driver's own session transcript: ${i.driverSession ?? "(the driver's session file was not resolvable — review from the transcripts below and say so in your findings)"}
|
|
2830
|
-
(a JSONL of every message, tool call and result. If it is large, read it in chunks and follow the turns, not the file.)
|
|
2831
|
-
2. every worker the flow delegated:
|
|
2832
|
-
${tlist}
|
|
2833
|
-
3. the plan the flow was held to: ${i.planFile}
|
|
2834
|
-
4. how the flow ended (\`flow status --json\` of the driving session):
|
|
2835
|
-
${i.statusJson}
|
|
2836
|
-
|
|
2837
|
-
Then run the reflection itself, over what you read (this is the same protocol \`flow reflect\` prints, applied to the transcripts):
|
|
2838
|
-
1. every turn of the flow: friction, wrong turns, repeated failures, guards or gates that misfired or confused the agent, playbook drift, dead weight the flow added but never used. A finding must cite what happened — "the verify gate refused twice for X, the driver wasted N turns guessing why" is a finding; "the flow was slow" is not.
|
|
2839
|
-
2. classify each one: [playbook] = this project's own playbook/references/checklist wording should change; [plugin] = dev-flow itself (a gate, a guard, status, a doc) should change.
|
|
2840
|
-
3. dedupe against the open queue below — never report the same issue twice; if an open item already covers it, say "already queued: <item>" instead of a new finding.
|
|
2841
|
-
|
|
2842
|
-
Open reflection queue (already filed):
|
|
2843
|
-
${open}
|
|
2844
|
-
|
|
2845
|
-
${i.note?.trim() ? `Note from the driver (context you cannot read elsewhere):\n${i.note.trim()}\n` : ""}
|
|
2846
|
-
${REFLECT_FINDINGS_CONTRACT}`;
|
|
2847
|
-
}
|
|
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.";
|