pi-dev-flow 0.70.0 → 0.72.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 +14 -0
- package/docs/gates.md +2 -2
- package/docs/guardrails.md +2 -2
- package/docs/stage-agent.md +52 -15
- package/extensions/dev-flow.ts +275 -59
- package/package.json +1 -1
- package/skills/dev-flow/SKILL.md +2 -0
- package/skills/dev-flow/references/implement.md +21 -16
- package/src/core.ts +264 -10
|
@@ -9,24 +9,27 @@ or the injection line) — writes elsewhere are blocked; other sessions'
|
|
|
9
9
|
worktrees are theirs (attribution guards judge every path by its owning
|
|
10
10
|
feature).
|
|
11
11
|
|
|
12
|
-
**Delegating the stage's work.**
|
|
13
|
-
a disposable worker session with `flow_stage`
|
|
14
|
-
|
|
15
|
-
|
|
12
|
+
**Delegating the stage's work.** Implement **is delegated**: this session does not write the
|
|
13
|
+
feature at all — run the work in a disposable worker session with `flow_stage`
|
|
14
|
+
(`stage: "implement"`). That is enforced, not advised: the guard refuses a driver's own edit
|
|
15
|
+
inside its worktree at implement, and `flow verify` refuses a branch whose commits fall outside a
|
|
16
|
+
worker's run window (`.dev-flow/<slug>/stage-sessions/delegations.log` is the record it reads), so
|
|
17
|
+
inline work is work that cannot be verified. `--docs` and `--patch` flows are exempt and stay
|
|
18
|
+
inline — the operator granted those modes for exactly that. What stays the driver's own: the gates,
|
|
19
|
+
the checkpoint, `flow check`, running the app. The
|
|
16
20
|
worker gets a fresh context holding the plan, live git and `flow status
|
|
17
21
|
--json` — it keeps nothing from this conversation, so put every operator
|
|
18
22
|
answer, decision, warning and the exact next action into `note`, and a short
|
|
19
23
|
`label` — a few words of purpose — so the picker reads `⏳ 🔨 #2 · wire ops` and,
|
|
20
|
-
when it ends, `✓ 🔨 #2 · 3 commits · wire ops` (a verify: `✓ 🔍 · PASS · <label>`)
|
|
24
|
+
when it ends, `✓ 🔨 #2 · 3 commits · wire ops` (a verify: `✓ 🔍 #3 · PASS · <label>`)
|
|
21
25
|
instead of a column of identical rows. The worker
|
|
22
26
|
may edit and commit in the worktree but holds no flow tool: gates,
|
|
23
27
|
checkpoints and the claim stay with you. When it returns, digest its stage
|
|
24
28
|
report (done/files/notes/blockers — a handoff, never a verification), rerun
|
|
25
|
-
`flow check` (its edits invalidated tier-1 records), and
|
|
26
|
-
loose ends
|
|
29
|
+
`flow check` (its edits invalidated tier-1 records), and delegate the remaining
|
|
30
|
+
loose ends too — a second `run` worker is how a tail gets finished, there is no inline allowance to fall back to. A missing report block or a crashed worker means the
|
|
27
31
|
worktree is mid-stage: read the transcript path and (if it names one) the
|
|
28
|
-
snapshot `.diff` the result gives.
|
|
29
|
-
delegate a stage you are about to finish anyway. One worker per session at a
|
|
32
|
+
snapshot `.diff` the result gives. Every slice goes out, the small ones with the big ones. One worker per session at a
|
|
30
33
|
time — but **sequential re-delegation is legal and often right**: a second
|
|
31
34
|
worker whose `note` says what the first one proved is how a big stage is
|
|
32
35
|
sliced. While one runs, the **tool card streams the worker's live output into
|
|
@@ -57,11 +60,12 @@ the worker is steered to commit and report rather than cut off.
|
|
|
57
60
|
5. **The independent checker speaks before the operator does:** `flow_stage { op: "verify" }`
|
|
58
61
|
runs a read-only reviewer (toolset read + bash, standing order *check, don't fix*) over the
|
|
59
62
|
plan and the branch diff; it closes with a `VERIFY REPORT` verdict. Its **PASS is a
|
|
60
|
-
precondition of `flow verify`** and belongs to the tree it read: any edit after it
|
|
61
|
-
a
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
63
|
+
precondition of `flow verify`** and belongs to the tree it read: any edit after it drops it like
|
|
64
|
+
a tier-1 record, so the fix → a **fresh** verify worker; a verdict from an interrupted or
|
|
65
|
+
tree-touching worker never stamps (a reviewer that edits voids its own report). **FAIL means:
|
|
66
|
+
delegate the fix** — a fresh `flow_stage { stage: "implement" }` worker carries it out, because at
|
|
67
|
+
implement the guard refuses your own edit tool in your own worktree; then rerun a fresh verify
|
|
68
|
+
worker. The report is a handoff, the gate's own rerun is the proof.
|
|
65
69
|
6. Done means **running and healthy with pre-existing data**, not "compiles":
|
|
66
70
|
`commands.seedData` (if set) puts real data in place, the app starts with
|
|
67
71
|
the `run` command, and the health check passes — `flow check` covers it
|
|
@@ -76,8 +80,9 @@ the worker is steered to commit and report rather than cut off.
|
|
|
76
80
|
answered (with no `dev` deploy configured, `flow verify` live-re-probes
|
|
77
81
|
`health` itself and refuses while nothing is answering). Checkpoint report: stage line **🔨 implement ·
|
|
78
82
|
`<slug>`** — commits `N ahead, M uncommitted` · tier-1 · tier-2 · deploy/
|
|
79
|
-
health · `branch@sha`, then `Done:`/`Next steps:` per the Stage reports rule. Fixes =
|
|
80
|
-
free — but every fix re-owes the verify worker's PASS
|
|
83
|
+
health · `branch@sha`, then `Done:`/`Next steps:` per the Stage reports rule. Fixes = delegate,
|
|
84
|
+
iterate and re-verify; that loop is free — but every fix re-owes the verify worker's PASS, and a
|
|
85
|
+
fixer needs its own fresh worker: nothing at this stage comes off your own pen.
|
|
81
86
|
|
|
82
87
|
`flow verify` re-runs build, runs the `dev` deploy when configured (the
|
|
83
88
|
operator reviews the running app; the gate **prints what it ran** —
|
package/src/core.ts
CHANGED
|
@@ -885,11 +885,14 @@ export function parsePushRefs(pushes: string[][]): PushRef[] {
|
|
|
885
885
|
return out;
|
|
886
886
|
}
|
|
887
887
|
|
|
888
|
-
/** Flow control files by full path — state.json
|
|
889
|
-
* also touches `.dev-flow` (that is how `cd .dev-flow/<slug> && mv state.json …`
|
|
890
|
-
* The claim is the live-session lock: deleting it is as much theft as forging a stage.
|
|
891
|
-
|
|
892
|
-
|
|
888
|
+
/** Flow control files by full path — state.json, claim.json and the delegation ledger — or a bare
|
|
889
|
+
* name when the command also touches `.dev-flow` (that is how `cd .dev-flow/<slug> && mv state.json …`
|
|
890
|
+
* reaches it). The claim is the live-session lock: deleting it is as much theft as forging a stage.
|
|
891
|
+
* `delegations.log` joins the two because the verify gate reads it as proof of WHO worked the stage:
|
|
892
|
+
* refusing it to the edit/write tools only while `echo >>` still reaches it would guard the honest
|
|
893
|
+
* session and none other (writeGuard is the same rule for the other half of the tool surface). */
|
|
894
|
+
const STATE_PATH = /(^|[\s'"\/])(?:(?:state|claim)\.json|delegations\.log)$/;
|
|
895
|
+
const STATE_PATH_ABS = /\.dev-flow\/[\w./-]*(?:(?:state|claim)\.json|delegations\.log)$/;
|
|
893
896
|
const PLAYBOOK_PATH = /\.dev-flow\/[\w./-]*project\.md/;
|
|
894
897
|
const DF_ANYWHERE = /\.dev-flow\b/;
|
|
895
898
|
/** The `.dev-flow/` folder itself or one feature directory under it — deleting either destroys the flow
|
|
@@ -1296,15 +1299,36 @@ export function inScratchDir(abs: string, repoRoot?: string | null): boolean {
|
|
|
1296
1299
|
return real === tmp || real.startsWith(tmp + path.sep);
|
|
1297
1300
|
}
|
|
1298
1301
|
|
|
1302
|
+
/** The main checkout a linked worktree shares its history with, from git's answer for the common dir
|
|
1303
|
+
* (`<main>/.git`), or null when there is nothing to remap: git did not answer, or cwd already is that
|
|
1304
|
+
* checkout (a plain clone answers its own dir). Pure — the caller decides whether to trust the root it
|
|
1305
|
+
* gets (dev-flow's `flowRoot` keeps cwd unless the main checkout is dev-flow-initiated). */
|
|
1306
|
+
export function mainCheckoutRoot(cwd: string, commonDir: string | null): string | null {
|
|
1307
|
+
if (!commonDir) return null;
|
|
1308
|
+
const main = path.resolve(path.dirname(path.resolve(cwd, commonDir)));
|
|
1309
|
+
return main === path.resolve(cwd) ? null : main;
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
/** True when the path is a feature's delegation ledger (.dev-flow/<slug>/stage-sessions/delegations.log)
|
|
1313
|
+
* — the file the verify gate reads to prove a worker ran. Matched by shape, not just filename, so a
|
|
1314
|
+
* source file that merely happens to be named delegations.log stays writable anywhere, including inside
|
|
1315
|
+
* a worktree that lives under .dev-flow/. */
|
|
1316
|
+
export function isDelegationLedger(abs: string, dfDir: string): boolean {
|
|
1317
|
+
return path.basename(abs) === DELEGATIONS_FILE && path.basename(path.dirname(abs)) === STAGE_SESSIONS_DIR && abs.includes(dfDir + path.sep);
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1299
1320
|
/**
|
|
1300
1321
|
* Write guard with per-path attribution: writes inside a worktree are judged by that
|
|
1301
1322
|
* worktree's own feature; main-checkout writes are judged by the session's bound feature
|
|
1302
1323
|
* (release+ may touch it; plan/implement may not); with no binding and unfinished features
|
|
1303
1324
|
* the session must bind first (`flow use`). Flow-by-default: a session with no flow may not
|
|
1304
1325
|
* 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.
|
|
1305
1329
|
* Returns a reason or null (allowed).
|
|
1306
1330
|
*/
|
|
1307
|
-
export function writeGuard(o: { abs: string; dfDir: string; features: FeatureRef[]; boundSlug: string | null; repoRoot?: string | null }): string | null {
|
|
1331
|
+
export function writeGuard(o: { abs: string; dfDir: string; features: FeatureRef[]; boundSlug: string | null; repoRoot?: string | null; byWorker?: boolean }): string | null {
|
|
1308
1332
|
// Judge where the bytes land, not where the path pretends: a symlink inside the worktree pointing
|
|
1309
1333
|
// out of it is the same write as the target path (realAbs walks the deepest existing ancestor, so
|
|
1310
1334
|
// a brand-new file under a real directory resolves right, and a never-existing one is stable).
|
|
@@ -1314,6 +1338,12 @@ export function writeGuard(o: { abs: string; dfDir: string; features: FeatureRef
|
|
|
1314
1338
|
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";
|
|
1315
1339
|
if (abs.endsWith("state.json") && abs.includes(dfDir + path.sep)) return "state.json is dev-flow-owned — advance stages with the flow tool only";
|
|
1316
1340
|
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`;
|
|
1317
1347
|
// Owner attribution BEFORE the .dev-flow allow: with the default worktreeDir inside .dev-flow,
|
|
1318
1348
|
// a worktree must still be judged by its owning feature's stage, not treated as free plan space.
|
|
1319
1349
|
const owner = o.features.find((f) => within(abs, f.worktreeAbs ? realAbs(f.worktreeAbs) : null));
|
|
@@ -1323,6 +1353,14 @@ export function writeGuard(o: { abs: string; dfDir: string; features: FeatureRef
|
|
|
1323
1353
|
// the playbook copy inside a worktree: only operator-granted lightweight modes may change it
|
|
1324
1354
|
if (path.basename(abs) === "project.md" && abs.includes(path.join(".dev-flow", "project.md")) && !owner.state.docs && !owner.state.patch)
|
|
1325
1355
|
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)`;
|
|
1326
1364
|
return null; // implement/pre-release/release: own worktree is the working area
|
|
1327
1365
|
}
|
|
1328
1366
|
// Scratch outside the checkout is not a repo write: every stage (and an unbound session) may use it. It
|
|
@@ -1368,6 +1406,11 @@ export interface SessionClaim {
|
|
|
1368
1406
|
key: string;
|
|
1369
1407
|
pid: number;
|
|
1370
1408
|
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;
|
|
1371
1414
|
}
|
|
1372
1415
|
|
|
1373
1416
|
/** Whether a process is running (kill 0 only probes existence; EPERM means it exists, foreign-owned). */
|
|
@@ -1380,9 +1423,43 @@ export function pidAlive(pid: number): boolean {
|
|
|
1380
1423
|
}
|
|
1381
1424
|
}
|
|
1382
1425
|
|
|
1383
|
-
/**
|
|
1384
|
-
|
|
1385
|
-
|
|
1426
|
+
/** A process's start identity: field 22 (`starttime`, clock ticks since boot) of `/proc/<pid>/stat`.
|
|
1427
|
+
* Two processes that share a pid never share it. `undefined` where there is no procfs. The comm
|
|
1428
|
+
* field (2) may itself hold spaces or parens, so the fields are counted from the LAST `)`. */
|
|
1429
|
+
export function processStart(pid: number, read: (file: string) => string = (f) => readFileSync(f, "utf8")): string | undefined {
|
|
1430
|
+
try {
|
|
1431
|
+
const stat = read(`/proc/${pid}/stat`);
|
|
1432
|
+
const rest = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
|
1433
|
+
// rest[0] is field 3 (state), so field 22 sits at index 19
|
|
1434
|
+
const st = rest[19];
|
|
1435
|
+
return st && /^\d+$/.test(st) ? st : undefined;
|
|
1436
|
+
} catch {
|
|
1437
|
+
return undefined;
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
/** True only when another live session holds the claim — its feature can only be taken by an explicit `flow use`, never quietly.
|
|
1442
|
+
* A claim whose pid is alive but whose recorded start identity no longer matches belongs to a dead
|
|
1443
|
+
* session whose pid was recycled: it does not block. */
|
|
1444
|
+
export function claimBlocks(claim: SessionClaim | null, myKey: string, alive: (pid: number) => boolean = pidAlive, startOf: (pid: number) => string | undefined = processStart): boolean {
|
|
1445
|
+
if (!claim || claim.key === myKey || !alive(claim.pid)) return false;
|
|
1446
|
+
if (claim.start) {
|
|
1447
|
+
const now = startOf(claim.pid);
|
|
1448
|
+
if (now !== undefined && now !== claim.start) return false;
|
|
1449
|
+
}
|
|
1450
|
+
return true;
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
/** How old a claim is, in words, for a refusal: "claimed 3 days ago" lets the operator tell a live
|
|
1454
|
+
* session from a stale pid at a glance. Empty when the stamp is unreadable. */
|
|
1455
|
+
export function claimAge(claim: SessionClaim, nowMs: number = Date.now()): string {
|
|
1456
|
+
const t = Date.parse(claim.at);
|
|
1457
|
+
if (!Number.isFinite(t)) return "";
|
|
1458
|
+
const min = Math.max(0, Math.round((nowMs - t) / 60000));
|
|
1459
|
+
if (min < 60) return `${min} min old`;
|
|
1460
|
+
const h = Math.round(min / 60);
|
|
1461
|
+
if (h < 48) return `${h} h old`;
|
|
1462
|
+
return `${Math.round(h / 24)} days old`;
|
|
1386
1463
|
}
|
|
1387
1464
|
|
|
1388
1465
|
/** Footer glyph per stage: the footer has no room for stage words and no legend of its own (README:Status bar is the legend). */
|
|
@@ -1807,7 +1884,10 @@ export function nextHint(state: FlowState, cfg: Config): string {
|
|
|
1807
1884
|
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`;
|
|
1808
1885
|
case "implement":
|
|
1809
1886
|
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`;
|
|
1810
|
-
|
|
1887
|
+
// The hint is what `flow status` and the per-turn injection hand the driver every turn, so it must
|
|
1888
|
+
// not order work the write guard refuses and the verify gate refuses: at implement a worker authors,
|
|
1889
|
+
// the driver drives. (docs mode above stays inline — it is exempt from the delegation gate.)
|
|
1890
|
+
return `delegate the implement work: flow_stage { stage: "implement" } sends a worker to edit, test and commit in the worktree ${state.worktree} (your own edits there are guard-refused, and flow verify refuses a branch whose commits fall outside a worker run); when it reports, rerun flow check (tier-1 checks, incl. health with seeded data) and get a fresh verify-worker PASS; tick the tier-2 checklist with the operator, then ask them Verified? in chat and run flow verify --confirmed when they answer — keep the app running when you ask Verified?: the operator reviews the live app; never clean up the test server before the checkpoint is answered (with no dev deploy configured, verify live-re-probes health itself and refuses while nothing is answering)`;
|
|
1811
1891
|
case "pre-release":
|
|
1812
1892
|
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`;
|
|
1813
1893
|
case "release":
|
|
@@ -2270,6 +2350,79 @@ export function parseWorkerTranscripts(text: string): { at: string; op: string;
|
|
|
2270
2350
|
return out;
|
|
2271
2351
|
}
|
|
2272
2352
|
|
|
2353
|
+
/** The durable delegation ledger inside .dev-flow/<slug>/stage-sessions/ — one line per finished
|
|
2354
|
+
* `flow_stage` run worker, written by the same completion code that counts its commits. Read fresh
|
|
2355
|
+
* at the gate, never folded into state.checks: those records mean "this tree was checked", a window
|
|
2356
|
+
* means "this range was worked by a worker", and re-running a check must not erase the history the
|
|
2357
|
+
* branch rests on (transcripts.log rides outside state for the same reason). */
|
|
2358
|
+
export const DELEGATIONS_FILE = "delegations.log";
|
|
2359
|
+
|
|
2360
|
+
/** The folder inside .dev-flow/<slug>/ that holds the worker logs (transcripts.log, delegations.log) —
|
|
2361
|
+
* also half of what makes a delegations.log a delegation ledger (see isDelegationLedger). */
|
|
2362
|
+
export const STAGE_SESSIONS_DIR = "stage-sessions";
|
|
2363
|
+
|
|
2364
|
+
/** One finished worker run: the stage it worked and the commit range it left behind. */
|
|
2365
|
+
export interface DelegationWindow {
|
|
2366
|
+
stage: string;
|
|
2367
|
+
start: string;
|
|
2368
|
+
end: string;
|
|
2369
|
+
}
|
|
2370
|
+
|
|
2371
|
+
/** A delegations.log line. The line carries a **range**, not a count, because a range is what the
|
|
2372
|
+
* gate can re-check: an amend or a rebase after the fact moves the sha out of every recorded window,
|
|
2373
|
+
* which no write guard could ever see — bash-authored commits name no author, a rewritten sha does. */
|
|
2374
|
+
export function delegationLine(at: string, stage: string, start: string, end: string, commits: number): string {
|
|
2375
|
+
return `[${at}] run (${stage}): ${start}..${end} ${commits} commit(s)`;
|
|
2376
|
+
}
|
|
2377
|
+
|
|
2378
|
+
/** Parse delegations.log back into windows; anything unrecognised is skipped — the log is append-only
|
|
2379
|
+
* and hand-editable, and an index that throws would take the gate down with it (transcripts.log's
|
|
2380
|
+
* rule). Shas must look like shas so a typo'd line is simply not a window, rather than a window
|
|
2381
|
+
* whose `git rev-list` fails for a reason the gate could only guess at. */
|
|
2382
|
+
export function parseDelegationLedger(text: string): DelegationWindow[] {
|
|
2383
|
+
const out: DelegationWindow[] = [];
|
|
2384
|
+
for (const line of (text ?? "").split("\n")) {
|
|
2385
|
+
const m = /^\s*\[(.*?)\]\s*run(?: \(([^)]*)\))?:\s*([0-9a-f]{7,40})\.\.([0-9a-f]{7,40})/i.exec(line);
|
|
2386
|
+
if (m) out.push({ stage: m[2] ?? "run", start: m[3], end: m[4] });
|
|
2387
|
+
}
|
|
2388
|
+
return out;
|
|
2389
|
+
}
|
|
2390
|
+
|
|
2391
|
+
/** The verify gate's refusal when nobody did the stage's work — spelled out the way
|
|
2392
|
+
* VERIFY_STAMP_REFUSAL spells its fix, so the driver reads its next action off the refusal line. */
|
|
2393
|
+
export const DELEGATION_REFUSAL = `the implement work was not delegated — run flow_stage { stage: "implement" } and let the worker session do the edits and commits (this session keeps the gates, the checkpoint and flow check)`;
|
|
2394
|
+
|
|
2395
|
+
/** Was the implement stage worked, or merely driven? The rule `flow verify` enforces: at least one
|
|
2396
|
+
* implement-stage run window carries a commit, and every commit the branch holds over its default
|
|
2397
|
+
* branch falls inside some implement-stage window. `windowCommits` resolves a window to its shas —
|
|
2398
|
+
* git lives on the caller's side, so this stays a pure function under test.
|
|
2399
|
+
* `branchCommits === null` (git could not answer) returns no errors: an unprovable answer is never
|
|
2400
|
+
* proof of a violation, the BranchState.commitsAhead rule. `--docs` and `--patch` are exempt exactly
|
|
2401
|
+
* like the verify stamp and the tier-1 checks — those two modes are the work the operator granted
|
|
2402
|
+
* inline. Coverage is judged only here: commits the driver makes after verify (changelog, bump) are
|
|
2403
|
+
* pre-release work and belong to the session by design. */
|
|
2404
|
+
export function delegationErrors(
|
|
2405
|
+
state: FlowState,
|
|
2406
|
+
ledger: DelegationWindow[],
|
|
2407
|
+
branchCommits: string[] | null,
|
|
2408
|
+
windowCommits: (w: DelegationWindow) => string[],
|
|
2409
|
+
): string[] {
|
|
2410
|
+
if (state.docs || state.patch) return [];
|
|
2411
|
+
if (branchCommits === null) return [];
|
|
2412
|
+
// Nothing on the branch to attribute: coverage is a claim about commits, and an empty branch has
|
|
2413
|
+
// none. verifyGate already refuses a branch with nothing committed — one refusal per fact.
|
|
2414
|
+
if (!branchCommits.length) return [];
|
|
2415
|
+
const covered = new Set<string>();
|
|
2416
|
+
for (const w of ledger.filter((x) => x.stage === "implement")) for (const sha of windowCommits(w) ?? []) covered.add(sha);
|
|
2417
|
+
// A window whose range holds nothing proves a worker ran and delivered nothing: the stage is still
|
|
2418
|
+
// undelivered, and "N commit(s) outside a window" on top of that names the same fact twice with
|
|
2419
|
+
// worse advice — there is nothing to redo, there is nothing yet.
|
|
2420
|
+
if (!covered.size) return [DELEGATION_REFUSAL];
|
|
2421
|
+
const strays = branchCommits.filter((sha) => !covered.has(sha));
|
|
2422
|
+
if (!strays.length) return [];
|
|
2423
|
+
return [`${strays.length} commit(s) on the branch were made outside a worker run — delegate a fixer that redoes them (or reset them)`];
|
|
2424
|
+
}
|
|
2425
|
+
|
|
2273
2426
|
/** How many live lines the card and `op: "status"` show: enough to see what the worker is doing,
|
|
2274
2427
|
* bounded so a long stage never spends the context the delegation just saved (R6). */
|
|
2275
2428
|
export const LIVE_TAIL_ITEMS = 8;
|
|
@@ -2412,6 +2565,107 @@ export function workerFamily(rows: WorkerSessionRow[], driverFile: string | null
|
|
|
2412
2565
|
return lines;
|
|
2413
2566
|
}
|
|
2414
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
|
+
|
|
2415
2669
|
/** The line that stands in for the workers too old to list. It is not a worker, so anything counting
|
|
2416
2670
|
* the list has to know it — and both sources fold the same way, so the shape lives here. */
|
|
2417
2671
|
export function familyFoldLine(dropped: number): string {
|