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
package/extensions/dev-flow.ts
CHANGED
|
@@ -22,6 +22,7 @@
|
|
|
22
22
|
import { exec } from "node:child_process";
|
|
23
23
|
import { createHash } from "node:crypto";
|
|
24
24
|
import { appendFileSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
25
|
+
import { open as openFile, readdir as readdirAsync, readFile as readFileAsync, stat as statAsync } from "node:fs/promises";
|
|
25
26
|
import path from "node:path";
|
|
26
27
|
import { promisify } from "node:util";
|
|
27
28
|
import { Type } from "@earendil-works/pi-ai";
|
|
@@ -47,6 +48,13 @@ import {
|
|
|
47
48
|
renderStageReport,
|
|
48
49
|
checklistHash,
|
|
49
50
|
checklistPending,
|
|
51
|
+
DELEGATIONS_FILE,
|
|
52
|
+
STAGE_SESSIONS_DIR,
|
|
53
|
+
delegationErrors,
|
|
54
|
+
delegationLine,
|
|
55
|
+
parseDelegationLedger,
|
|
56
|
+
mainCheckoutRoot,
|
|
57
|
+
type DelegationWindow,
|
|
50
58
|
checkoutTarget,
|
|
51
59
|
claimBlocks,
|
|
52
60
|
clampStageBudgetMin,
|
|
@@ -143,6 +151,14 @@ import {
|
|
|
143
151
|
renderVerifyReport,
|
|
144
152
|
verifyStampMissing,
|
|
145
153
|
sessionPathKey,
|
|
154
|
+
sessionHeaderParent,
|
|
155
|
+
parseSessionSummary,
|
|
156
|
+
markWorkerSession,
|
|
157
|
+
isWorkerSession,
|
|
158
|
+
orphanWorktreeBuckets,
|
|
159
|
+
claimAge,
|
|
160
|
+
processStart,
|
|
161
|
+
type WorktreeBucketFeature,
|
|
146
162
|
workerFamily,
|
|
147
163
|
workerFamilyCount,
|
|
148
164
|
WORKER_FAMILY_ITEMS,
|
|
@@ -241,7 +257,13 @@ function copyWarning(): string | null {
|
|
|
241
257
|
}
|
|
242
258
|
/** Test seam: the smoke suite cannot load a second copy of this module, so it plants registry
|
|
243
259
|
* entries and asserts the warnings the real duplicate would print. */
|
|
244
|
-
export const testSeams = {
|
|
260
|
+
export const testSeams = {
|
|
261
|
+
copies: COPIES,
|
|
262
|
+
skillCore: { value: undefined as string | null | undefined },
|
|
263
|
+
/** Where `flow doctor` looks for pi's session buckets; tests point it at a scratch dir so the suite
|
|
264
|
+
* never reads the operator's real session store. `undefined` = `<agent dir>/sessions`. */
|
|
265
|
+
sessionsRoot: { value: undefined as string | null | undefined },
|
|
266
|
+
};
|
|
245
267
|
|
|
246
268
|
interface Ui {
|
|
247
269
|
hasUI: boolean;
|
|
@@ -393,7 +415,8 @@ function writeState(root: string, state: FlowState): void {
|
|
|
393
415
|
* truncated state.json — which reads as "no such feature", silently orphaning the worktree, the plan
|
|
394
416
|
* and every recorded check, with the folder gitignored so nothing else could restore it. */
|
|
395
417
|
function atomicWrite(file: string, text: string): void {
|
|
396
|
-
|
|
418
|
+
// per-process temp name: two sessions writing the same file must not rename each other's half-write
|
|
419
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
397
420
|
writeFileSync(tmp, text);
|
|
398
421
|
renameSync(tmp, file);
|
|
399
422
|
}
|
|
@@ -447,9 +470,13 @@ export const compactionTakeover: { run: typeof compact } = { run: compact };
|
|
|
447
470
|
* carries `parentSession` → the driver's own session file, and its transcript goes into the
|
|
448
471
|
* driver's session bucket, so pi's picker nests it under the driver in its default Current Folder
|
|
449
472
|
* scope (the Threaded sort reads that link — pi #1108 wrote it for exactly this, "extensions such
|
|
450
|
-
* as /handoff can do the same").
|
|
451
|
-
*
|
|
452
|
-
*
|
|
473
|
+
* as /handoff can do the same"). The live ⏳ name is written straight onto the session before its
|
|
474
|
+
* first prompt: pi emits `session_start` only from `bindExtensions()`, which an SDK-created worker
|
|
475
|
+
* never runs, so a name set from a `session_start` handler never lands — every worker used to run
|
|
476
|
+
* under whatever an auto-namer derived from its brief ("you-are-a-dev"). Named before the prompt,
|
|
477
|
+
* an auto-namer sees a name that is not its own and leaves it alone. The same channel carries the
|
|
478
|
+
* ⏳ → ✓/✗ rename. The worker is also registered as a worker, so the dev-flow copy its loader runs
|
|
479
|
+
* keeps its guards but injects none of the driver's context (see `isWorkerSession`). */
|
|
453
480
|
|
|
454
481
|
export interface StageWorkerHandle { session: AgentSession; rename: (name: string) => void }
|
|
455
482
|
|
|
@@ -464,26 +491,17 @@ export function workerSessionManager(work: string, parent?: string, dir?: string
|
|
|
464
491
|
|
|
465
492
|
export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name: string; tools: string[]; parent?: string; dir?: string }) => Promise<StageWorkerHandle> } = {
|
|
466
493
|
run: async ({ work, model, name, tools, parent, dir }) => {
|
|
467
|
-
|
|
468
|
-
const loader = new DefaultResourceLoader({
|
|
469
|
-
cwd: work,
|
|
470
|
-
agentDir: getAgentDir(),
|
|
471
|
-
extensionFactories: [{
|
|
472
|
-
name: "dev-flow-stage-naming",
|
|
473
|
-
hidden: true,
|
|
474
|
-
factory: (childPi: ExtensionAPI) => {
|
|
475
|
-
childPi.on("session_start", () => { try { childPi.setSessionName(name); } catch { /* naming is visibility, not function */ } });
|
|
476
|
-
rename = (n: string) => { try { childPi.setSessionName(n); } catch { /* ditto */ } };
|
|
477
|
-
},
|
|
478
|
-
}],
|
|
479
|
-
});
|
|
494
|
+
const loader = new DefaultResourceLoader({ cwd: work, agentDir: getAgentDir() });
|
|
480
495
|
await loader.reload();
|
|
481
496
|
const sessionManager = workerSessionManager(work, parent, dir);
|
|
482
497
|
const { session } = await createAgentSession({ cwd: work, model: model as never, tools, excludeTools: ["flow", "flow_stage"], resourceLoader: loader, sessionManager });
|
|
483
498
|
// the op's toolset decides what the worker can touch at all: an implement worker gets the coding
|
|
484
499
|
// tools, a reviewer gets read + bash only (a checker with an edit tool is a second implementer).
|
|
485
500
|
// excludeTools is the belt on the extension tools — a worker never holds a gate or a second flow_stage.
|
|
486
|
-
|
|
501
|
+
try { markWorkerSession(session.sessionManager.getSessionId()); } catch { /* an id-less session just gets the driver context */ }
|
|
502
|
+
const rename = (n: string) => { try { session.setSessionName(n); } catch { /* naming is visibility, not function */ } };
|
|
503
|
+
rename(name);
|
|
504
|
+
return { session, rename };
|
|
487
505
|
},
|
|
488
506
|
};
|
|
489
507
|
|
|
@@ -495,10 +513,51 @@ export const stageWorkerSpawn: { run: (o: { work: string; model: unknown; name:
|
|
|
495
513
|
* creates. `listAll(dir)` is what the picker's Current Folder scope sees in the default layout, so
|
|
496
514
|
* the family list and the tree agree there; under a configured session dir the text view stays
|
|
497
515
|
* complete even where that scope hides the worker, which is the cheaper direction to err in. */
|
|
498
|
-
export const sessionRowsScan: { run: (o: { cwd: string; dir?: string }) => Promise<WorkerSessionRow[]> } = {
|
|
499
|
-
run: async ({ dir }) =>
|
|
516
|
+
export const sessionRowsScan: { run: (o: { cwd: string; dir?: string; parent?: string }) => Promise<WorkerSessionRow[]> } = {
|
|
517
|
+
run: async ({ dir, parent }) => {
|
|
518
|
+
// no bucket or no driver file to match: the old full listing (a host that never reaches here in practice)
|
|
519
|
+
if (!dir || !parent) return (await SessionManager.listAll(dir)).map((s) => ({ path: s.path, parent: s.parentSessionPath, name: s.name, messageCount: s.messageCount, modified: s.modified }));
|
|
520
|
+
return scanFamilyRows(dir, parent);
|
|
521
|
+
},
|
|
500
522
|
};
|
|
501
523
|
|
|
524
|
+
/** Header bytes read per transcript in the family scan's cheap pass — the same budget pi gives its own
|
|
525
|
+
* header reads. A pi header line is a few hundred bytes. */
|
|
526
|
+
const SESSION_HEADER_BYTES = 4096;
|
|
527
|
+
|
|
528
|
+
/** The family read in two passes, so its cost follows the family, not the bucket: the first line of
|
|
529
|
+
* every transcript (≤ 4 KB each) names its parent; only the files whose parent is `parent` are read
|
|
530
|
+
* in full. `listAll(dir)` parsed every transcript in the bucket — ~15 ms per MB, and a driver bucket
|
|
531
|
+
* only grows (the dev-flow checkout's was 55 MB, ~0.8 s for every idle status and settled card).
|
|
532
|
+
* `fullReads` counts the second pass for the smoke suite. */
|
|
533
|
+
export async function scanFamilyRows(dir: string, parent: string, fullReads?: { n: number }): Promise<WorkerSessionRow[]> {
|
|
534
|
+
let names: string[];
|
|
535
|
+
try { names = (await readdirAsync(dir)).filter((f) => f.endsWith(".jsonl")); } catch { return []; }
|
|
536
|
+
const want = sessionPathKey(parent);
|
|
537
|
+
const rows: WorkerSessionRow[] = [];
|
|
538
|
+
await Promise.all(names.map(async (n) => {
|
|
539
|
+
const file = path.join(dir, n);
|
|
540
|
+
let head = "";
|
|
541
|
+
try {
|
|
542
|
+
const fh = await openFile(file, "r");
|
|
543
|
+
try {
|
|
544
|
+
const buf = Buffer.alloc(SESSION_HEADER_BYTES);
|
|
545
|
+
const { bytesRead } = await fh.read(buf, 0, SESSION_HEADER_BYTES, 0);
|
|
546
|
+
head = buf.subarray(0, bytesRead).toString("utf8");
|
|
547
|
+
} finally { await fh.close(); }
|
|
548
|
+
} catch { return; }
|
|
549
|
+
const p = sessionHeaderParent(head);
|
|
550
|
+
if (!p || sessionPathKey(p) !== want) return;
|
|
551
|
+
try {
|
|
552
|
+
if (fullReads) fullReads.n++;
|
|
553
|
+
const [text, st] = await Promise.all([readFileAsync(file, "utf8"), statAsync(file)]);
|
|
554
|
+
const row = parseSessionSummary(text, file, st.mtimeMs);
|
|
555
|
+
if (row) rows.push(row);
|
|
556
|
+
} catch { /* a transcript deleted mid-scan is simply not in the family */ }
|
|
557
|
+
}));
|
|
558
|
+
return rows;
|
|
559
|
+
}
|
|
560
|
+
|
|
502
561
|
/** Where this session's own transcripts live, when it has any: the file the worker links to, and the
|
|
503
562
|
* bucket it lands in. `null` on a host with no file-backed session — lineage is then unavailable,
|
|
504
563
|
* which is a fact to print, never an error to raise. */
|
|
@@ -520,16 +579,15 @@ function ledgerFamilyLines(logPath: string, exclude?: string): string[] {
|
|
|
520
579
|
} catch { return []; }
|
|
521
580
|
}
|
|
522
581
|
|
|
523
|
-
/** Bucket reads are the one
|
|
524
|
-
* driver's bucket
|
|
525
|
-
*
|
|
526
|
-
*
|
|
527
|
-
* status, the settled card — always re-read. */
|
|
582
|
+
/** Bucket reads are the one IO-bound thing the family view does: one header read per transcript in
|
|
583
|
+
* the driver's bucket, plus a full read of each worker (`scanFamilyRows`). A host renders a running
|
|
584
|
+
* worker by calling status repeatedly, so that path is allowed a slightly stale read; the places the
|
|
585
|
+
* operator draws a conclusion from — idle status, the settled card — always re-read. */
|
|
528
586
|
const BUCKET_FRESH_MS = 2000;
|
|
529
587
|
const bucketCache = new Map<string, { at: number; rows: Awaited<ReturnType<typeof sessionRowsScan.run>> }>();
|
|
530
588
|
|
|
531
|
-
async function bucketRows(ctx: ExtensionContext, dir: string | null, staleMs = 0) {
|
|
532
|
-
const key = dir ?? "(default bucket)"
|
|
589
|
+
async function bucketRows(ctx: ExtensionContext, dir: string | null, parent: string, staleMs = 0) {
|
|
590
|
+
const key = `${dir ?? "(default bucket)"}\0${parent}`;
|
|
533
591
|
const hit = bucketCache.get(key);
|
|
534
592
|
// staleMs = 0 is not "a zero-length window", it is "no window: read now" — which is what idle status
|
|
535
593
|
// and the settled card ask for, because that is where the operator draws a conclusion. With `<=` the
|
|
@@ -537,7 +595,7 @@ async function bucketRows(ctx: ExtensionContext, dir: string | null, staleMs = 0
|
|
|
537
595
|
// as a fresh one (this made CI red: a status call answering "what is there now" in the same millisecond
|
|
538
596
|
// as the call before it printed the family that had just gone empty).
|
|
539
597
|
if (staleMs > 0 && hit && Date.now() - hit.at <= staleMs) return hit.rows;
|
|
540
|
-
const rows = await sessionRowsScan.run({ cwd: ctx.cwd, dir: dir ?? undefined });
|
|
598
|
+
const rows = await sessionRowsScan.run({ cwd: ctx.cwd, dir: dir ?? undefined, parent });
|
|
541
599
|
if (bucketCache.size > 8) bucketCache.clear(); // a session drives one bucket; anything bigger is stale keys
|
|
542
600
|
bucketCache.set(key, { at: Date.now(), rows });
|
|
543
601
|
return rows;
|
|
@@ -553,7 +611,7 @@ async function workerFamilyLines(ctx: ExtensionContext, exclude?: string, staleM
|
|
|
553
611
|
const { file, dir } = lineageOf(ctx);
|
|
554
612
|
if (!file) return null;
|
|
555
613
|
try {
|
|
556
|
-
return workerFamily(await bucketRows(ctx, dir, staleMs), file, { exclude });
|
|
614
|
+
return workerFamily(await bucketRows(ctx, dir, file, staleMs), file, { exclude });
|
|
557
615
|
} catch { /* visibility again: a bucket we cannot read is not a reason to lose the run's own report */ return null; }
|
|
558
616
|
}
|
|
559
617
|
|
|
@@ -636,7 +694,13 @@ function readClaim(root: string, slug: string): SessionClaim | null {
|
|
|
636
694
|
}
|
|
637
695
|
|
|
638
696
|
const writeClaim = (root: string, slug: string, key: string) =>
|
|
639
|
-
atomicWrite(claimFile(root, slug), `${JSON.stringify({ key, pid: process.pid, at: now() })}\n`);
|
|
697
|
+
atomicWrite(claimFile(root, slug), `${JSON.stringify({ key, pid: process.pid, at: now(), start: processStart(process.pid) })}\n`);
|
|
698
|
+
|
|
699
|
+
/** "pid 854, claim 3 days old" — the age is what tells a live session from a recycled pid. */
|
|
700
|
+
const claimWho = (claim: SessionClaim): string => {
|
|
701
|
+
const age = claimAge(claim);
|
|
702
|
+
return `pid ${claim.pid}${age ? `, claim ${age}` : ""}`;
|
|
703
|
+
};
|
|
640
704
|
|
|
641
705
|
/** Let go of everything one session held. In a shared-process host the pid on a claim is the server's and
|
|
642
706
|
* never dies, so a claim left behind by a finished session keeps refusing every later session with
|
|
@@ -853,9 +917,8 @@ async function stampChecks(root: string, state: FlowState, names: string[]): Pro
|
|
|
853
917
|
* question. Local refs only — same offline-safe stance as the changelog proof — and an
|
|
854
918
|
* unanswerable merge base reports null instead of refusing on a measurement failure. */
|
|
855
919
|
async function branchState(cwd: string, defaultBranch: string): Promise<BranchState> {
|
|
856
|
-
const
|
|
857
|
-
|
|
858
|
-
if (!mb.ok || !base) return { commitsAhead: null, uncommitted: 0 };
|
|
920
|
+
const base = await mergeBase(cwd, defaultBranch);
|
|
921
|
+
if (!base) return { commitsAhead: null, uncommitted: 0 };
|
|
859
922
|
const ahead = await sh(`git rev-list --count ${sq(base)}..HEAD`, cwd);
|
|
860
923
|
const n = Number.parseInt(ahead.out.trim(), 10);
|
|
861
924
|
const dirty = await sh("git status --porcelain", cwd);
|
|
@@ -865,6 +928,54 @@ async function branchState(cwd: string, defaultBranch: string): Promise<BranchSt
|
|
|
865
928
|
};
|
|
866
929
|
}
|
|
867
930
|
|
|
931
|
+
/** The branch's merge base with the default branch, or "" when git cannot answer (no such ref, a
|
|
932
|
+
* shallow clone). Callers read "" as "unprovable", never as "nothing ahead". Local refs only —
|
|
933
|
+
* the same offline-safe stance as the changelog proof. */
|
|
934
|
+
async function mergeBase(cwd: string, defaultBranch: string): Promise<string> {
|
|
935
|
+
const mb = await sh(`git merge-base origin/${sq(defaultBranch)} HEAD 2>/dev/null || git merge-base ${sq(defaultBranch)} HEAD 2>/dev/null || true`, cwd);
|
|
936
|
+
return mb.ok ? mb.out.trim() : "";
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
/** What the branch proves about *who* worked it: the flow's delegation ledger, the commits the branch
|
|
940
|
+
* holds over the default branch, and the sha set each recorded **implement** window covers. Returns null for a
|
|
941
|
+
* --docs or --patch flow — those modes are exempt, so nothing is measured and no git call is spent.
|
|
942
|
+
* A window whose shas git cannot resolve covers nothing rather than excusing itself: a hand-written
|
|
943
|
+
* line must not be able to exempt the commits lying next to it. */
|
|
944
|
+
async function delegationProof(root: string, state: FlowState, defaultBranch: string): Promise<{ ledger: DelegationWindow[]; branchCommits: string[] | null; windowCommits: (w: DelegationWindow) => string[]; covered: number; windows: number } | null> {
|
|
945
|
+
if (state.docs || state.patch) return null;
|
|
946
|
+
const work = gateCwd(root, state);
|
|
947
|
+
let ledger: DelegationWindow[] = [];
|
|
948
|
+
try {
|
|
949
|
+
ledger = parseDelegationLedger(readFileSync(path.join(featDir(root, state.slug), STAGE_SESSIONS_DIR, DELEGATIONS_FILE), "utf8"));
|
|
950
|
+
} catch { /* no ledger yet: nobody delegated, which the gate reports rather than throwing on */ }
|
|
951
|
+
const shas = async (cmd: string) => {
|
|
952
|
+
const r = await sh(cmd, work);
|
|
953
|
+
return r.ok ? r.out.split("\n").map((l) => l.trim()).filter(Boolean) : null;
|
|
954
|
+
};
|
|
955
|
+
const base = await mergeBase(work, defaultBranch);
|
|
956
|
+
let branchCommits = base ? await shas(`git rev-list ${sq(base)}..HEAD`) : null;
|
|
957
|
+
// Only implement windows are ever consulted (delegationErrors filters the same way), so a pre-release
|
|
958
|
+
// or release worker's line resolves to nothing instead of costing a `git rev-list` per line — the
|
|
959
|
+
// ledger grows with every worker the feature runs, and the gate reads it on every verify.
|
|
960
|
+
// The `?? []` stays: a window whose objects git cannot resolve covers nothing, it does not excuse
|
|
961
|
+
// itself — otherwise a hand-written line about a garbage range would exempt the commits beside it.
|
|
962
|
+
const impl = ledger.filter((w) => w.stage === "implement");
|
|
963
|
+
const ranges = new Map<string, string[]>();
|
|
964
|
+
const key = (w: DelegationWindow) => `${w.start}..${w.end}`;
|
|
965
|
+
for (const w of impl) ranges.set(key(w), (await shas(`git rev-list ${sq(w.start)}..${sq(w.end)}`)) ?? []);
|
|
966
|
+
const windowCommits = (w: DelegationWindow) => ranges.get(key(w)) ?? [];
|
|
967
|
+
// What the gate prints as proven is what the operator is approving, so the count is intersected with
|
|
968
|
+
// the branch: a reset or an amend leaves the window's shas resolvable as loose objects while they are
|
|
969
|
+
// no longer on the branch, and "delegation proven: 2 worker commit(s)" over a branch of one is a
|
|
970
|
+
// claim about commits nobody is verifying. Coverage itself is delegationErrors' business — it reads
|
|
971
|
+
// the branch, so nothing here can widen it.
|
|
972
|
+
const onBranch = branchCommits ? new Set(branchCommits) : null;
|
|
973
|
+
const proves = (w: DelegationWindow) => windowCommits(w).some((sha) => !onBranch || onBranch.has(sha));
|
|
974
|
+
const covered = new Set<string>();
|
|
975
|
+
for (const w of impl) for (const sha of windowCommits(w)) if (!onBranch || onBranch.has(sha)) covered.add(sha);
|
|
976
|
+
return { ledger, branchCommits, windowCommits, covered: covered.size, windows: impl.filter(proves).length };
|
|
977
|
+
}
|
|
978
|
+
|
|
868
979
|
function describeBranchState(b: BranchState, defaultBranch: string): string {
|
|
869
980
|
return b.commitsAhead === null
|
|
870
981
|
? `commits: unknown (no merge base with ${defaultBranch} — the commit proof is skipped)`
|
|
@@ -1140,6 +1251,17 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
|
|
|
1140
1251
|
writeState(root, state!);
|
|
1141
1252
|
return { text: `verify gate FAILED:\n- ${VERIFY_STAMP_REFUSAL}${staleAtGate.includes(VERIFY_STAMP) || stampVoided ? " (a PASS was recorded, but the tree or its plan moved since — that is why it no longer counts)" : ""}\n${branchLine}`, isError: true };
|
|
1142
1253
|
}
|
|
1254
|
+
// The implement stage has to have been *worked*, not just driven: every commit the branch holds
|
|
1255
|
+
// must fall inside a worker's run window, as recorded in stage-sessions/delegations.log. Refused
|
|
1256
|
+
// before any command runs, like the stamp — and judged only here, because the driver's own commits
|
|
1257
|
+
// after this gate (changelog, bump) are pre-release work and belong to the session by design.
|
|
1258
|
+
// Coverage is an implement-stage claim. The stage check is verifyGate's and it sits AFTER this one,
|
|
1259
|
+
// so a re-run at pre-release would otherwise answer "verify only applies to implement" with a
|
|
1260
|
+
// delegation accusation about the driver's own changelog and bump commits — commits that are
|
|
1261
|
+
// in-session work by design. Measuring only at implement keeps the refusal honest.
|
|
1262
|
+
const deleg = state!.stage === "implement" ? await delegationProof(root, state!, cfg.defaultBranch) : null;
|
|
1263
|
+
const delegErrs = deleg ? delegationErrors(state!, deleg.ledger, deleg.branchCommits, deleg.windowCommits) : [];
|
|
1264
|
+
if (delegErrs.length) return { text: `verify gate FAILED:\n- ${delegErrs.join("\n- ")}\n${branchLine}`, isError: true };
|
|
1143
1265
|
const pending = pendingChecks(state!, cfg);
|
|
1144
1266
|
const gateRun = pending.length ? await runChecks(root, state!, cfg, pending) : null;
|
|
1145
1267
|
if (gateRun?.failed) return { text: `verify gate FAILED — a check run at the gate failed:\n${gateRun.lines.join("\n")}\n${branchLine}`, isError: true };
|
|
@@ -1151,6 +1273,7 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
|
|
|
1151
1273
|
const did: string[] = [];
|
|
1152
1274
|
if (gateRun) did.push(`checks ran at the gate (${pending.map((c) => c.name).join(", ")})`);
|
|
1153
1275
|
if (staleAtGate.length) did.push(`stale record(s) rerun after a worktree change: ${staleAtGate.join(", ")}`);
|
|
1276
|
+
if (deleg) did.push(`delegation proven: ${deleg.covered} worker commit(s) in ${deleg.windows} window(s)`);
|
|
1154
1277
|
if (state!.docs) {
|
|
1155
1278
|
// docs mode's contract: no tier-1 work happens, so a docs flow neither builds, deploys nor probes (#43 #49)
|
|
1156
1279
|
did.push("docs mode: project commands skipped (build/dev/health)");
|
|
@@ -2035,6 +2158,7 @@ async function gateDoctor(o: GateCtx): Promise<RunResult> {
|
|
|
2035
2158
|
const loaded = loadProject(df);
|
|
2036
2159
|
const findings = doctorFindings(root, loaded.cfg, loaded.md);
|
|
2037
2160
|
findings.push(...(await gitConsistency(root, loaded.cfg)));
|
|
2161
|
+
findings.push(...orphanBucketFindings(root));
|
|
2038
2162
|
const refl = readReflections(root);
|
|
2039
2163
|
const fold = await foldView(root, refl, isSelfRepo(root));
|
|
2040
2164
|
if (refl.length) {
|
|
@@ -2056,6 +2180,35 @@ async function gateDoctor(o: GateCtx): Promise<RunResult> {
|
|
|
2056
2180
|
return { text: investigationBrief(rest.filter((a) => !a.startsWith("--")).join(" "), isSelfRepo(root)).join("\n") };
|
|
2057
2181
|
}
|
|
2058
2182
|
|
|
2183
|
+
/** Session buckets stage workers left under finished or vanished worktrees (see `orphanWorktreeBuckets`).
|
|
2184
|
+
* Information only: the doctor names them and the command that removes them; deleting transcripts is
|
|
2185
|
+
* the operator's call, never the doctor's. Silent when there is no session store to read. */
|
|
2186
|
+
function orphanBucketFindings(root: string): string[] {
|
|
2187
|
+
const sessionsRoot = testSeams.sessionsRoot.value === undefined ? path.join(getAgentDir(), "sessions") : testSeams.sessionsRoot.value;
|
|
2188
|
+
if (!sessionsRoot || !existsSync(sessionsRoot)) return [];
|
|
2189
|
+
let buckets: string[];
|
|
2190
|
+
try { buckets = readdirSync(sessionsRoot, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name); } catch { return []; }
|
|
2191
|
+
const features = new Map<string, WorktreeBucketFeature>();
|
|
2192
|
+
try {
|
|
2193
|
+
for (const d of readdirSync(dfDir(root), { withFileTypes: true })) {
|
|
2194
|
+
if (!d.isDirectory()) continue;
|
|
2195
|
+
const st = readState(root, d.name);
|
|
2196
|
+
if (!st) continue;
|
|
2197
|
+
const wt = st.worktree ? path.resolve(root, st.worktree) : null;
|
|
2198
|
+
features.set(d.name, { finished: st.stage === "done" || !!st.aborted, worktreeExists: !!wt && existsSync(wt) });
|
|
2199
|
+
}
|
|
2200
|
+
} catch { /* no .dev-flow dir: every matching bucket is an orphan */ }
|
|
2201
|
+
const orphans = orphanWorktreeBuckets(buckets, root, features);
|
|
2202
|
+
if (!orphans.length) return [];
|
|
2203
|
+
const rows = orphans.map((o) => {
|
|
2204
|
+
const dir = path.join(sessionsRoot, o.bucket);
|
|
2205
|
+
let n = 0;
|
|
2206
|
+
try { n = readdirSync(dir).filter((f) => f.endsWith(".jsonl")).length; } catch { /* count is cosmetic */ }
|
|
2207
|
+
return ` ${o.slug}: ${n} transcript(s) — rm -r ${sq(dir)}`;
|
|
2208
|
+
});
|
|
2209
|
+
return [`worker session buckets left by finished or removed worktrees (${orphans.length}) — stage workers before 0.70 filed under their worktree, where no picker scope opened from this checkout shows them; keep them for the record or remove:\n${rows.join("\n")}`];
|
|
2210
|
+
}
|
|
2211
|
+
|
|
2059
2212
|
/** What a gate handler needs from the runFlow preamble. Bodies moved verbatim destructure
|
|
2060
2213
|
* their own names back, so the bodies needed zero edits. */
|
|
2061
2214
|
interface GateCtx {
|
|
@@ -2136,7 +2289,7 @@ async function gateUse(o: GateCtx): Promise<RunResult> {
|
|
|
2136
2289
|
const st = readState(root, slugArg);
|
|
2137
2290
|
if (!st || st.stage === "done") return { text: `no unfinished feature ${slugArg}`, isError: true };
|
|
2138
2291
|
const prior = readClaim(root, slugArg);
|
|
2139
|
-
const takeover = claimBlocks(prior, sess.key) ? ` — taken over from live session (
|
|
2292
|
+
const takeover = claimBlocks(prior, sess.key) ? ` — taken over from live session (${claimWho(prior!)})` : "";
|
|
2140
2293
|
sess.bind(slugArg);
|
|
2141
2294
|
sess.rename(slugArg);
|
|
2142
2295
|
// a checkpoint that was still unanswered belongs to whoever asked; a session taking the feature over
|
|
@@ -2157,7 +2310,7 @@ async function gateAbort(o: GateCtx): Promise<RunResult> {
|
|
|
2157
2310
|
// a live claim locks the whole feature, not only its gates: aborting it out from under the session
|
|
2158
2311
|
// that works it erases the plan that session is still writing (same rule needState applies)
|
|
2159
2312
|
const claim = readClaim(root, target);
|
|
2160
|
-
if (claimBlocks(claim, sess.key)) return { text: `${target} is claimed by another live session (
|
|
2313
|
+
if (claimBlocks(claim, sess.key)) return { text: `${target} is claimed by another live session (${claimWho(claim!)}) — flow use ${target} takes it over explicitly`, isError: true };
|
|
2161
2314
|
if (sess.slug === target) sess.bind(null);
|
|
2162
2315
|
if (st && !st.worktree) {
|
|
2163
2316
|
// plan-stage abort = drop: no worktree/branch exists, so the state dir would linger
|
|
@@ -2170,6 +2323,44 @@ async function gateAbort(o: GateCtx): Promise<RunResult> {
|
|
|
2170
2323
|
}
|
|
2171
2324
|
|
|
2172
2325
|
|
|
2326
|
+
/** True inside a linked worktree (its git dir is not the common dir), false in a main checkout or on error. */
|
|
2327
|
+
async function isLinkedWorktree(root: string): Promise<boolean> {
|
|
2328
|
+
const r = await sh("git rev-parse --path-format=absolute --git-dir --git-common-dir", root);
|
|
2329
|
+
if (!r.ok) return false;
|
|
2330
|
+
const [gitDir, common] = r.out.split("\n").map((l) => l.trim());
|
|
2331
|
+
return !!gitDir && !!common && path.resolve(gitDir) !== path.resolve(common);
|
|
2332
|
+
}
|
|
2333
|
+
|
|
2334
|
+
/** Per-cwd cache for flowRoot: consulted on every tool call of every session, and a git probe per call
|
|
2335
|
+
* is not acceptable there. A cwd's answer never changes while the process lives (a worktree that gets
|
|
2336
|
+
* removed stops being anyone's cwd; a plain clone does not become one). */
|
|
2337
|
+
const flowRootCache = new Map<string, string>();
|
|
2338
|
+
|
|
2339
|
+
/** The root whose .dev-flow/ is the flow truth for a session cwd.
|
|
2340
|
+
*
|
|
2341
|
+
* A feature worktree is a **linked git worktree**, and the default worktreeDir (.dev-flow/<slug>/worktree)
|
|
2342
|
+
* makes its own tracked .dev-flow/ hold one file: project.md. The state, the claims, the plans and the
|
|
2343
|
+
* delegation ledger all live in the main checkout, so judging a worker by its own cwd found zero features
|
|
2344
|
+
* and every guard answered "no active flow" — the write-guard's worker half never fired, because byWorker
|
|
2345
|
+
* was only ever consulted after owner attribution, and owner attribution had nothing to attribute. A
|
|
2346
|
+
* worker fell back to bash authoring, which is the half the guard was never meant to police.
|
|
2347
|
+
*
|
|
2348
|
+
* So: a linked worktree resolves to its main checkout (git's common dir is <main>/.git), and only when
|
|
2349
|
+
* that checkout is actually initiated — otherwise the cwd answer stands, which keeps plain clones, scratch
|
|
2350
|
+
* repos and every test fixture behaving exactly as before. */
|
|
2351
|
+
async function flowRoot(cwd: string): Promise<string> {
|
|
2352
|
+
const hit = flowRootCache.get(cwd);
|
|
2353
|
+
if (hit !== undefined) return hit;
|
|
2354
|
+
let root = cwd;
|
|
2355
|
+
if (await isLinkedWorktree(cwd)) {
|
|
2356
|
+
const r = await sh("git rev-parse --path-format=absolute --git-common-dir", cwd);
|
|
2357
|
+
const main = mainCheckoutRoot(cwd, r.ok ? r.out.trim() : null);
|
|
2358
|
+
if (main && initiated(main)) root = main;
|
|
2359
|
+
}
|
|
2360
|
+
flowRootCache.set(cwd, root);
|
|
2361
|
+
return root;
|
|
2362
|
+
}
|
|
2363
|
+
|
|
2173
2364
|
async function currentBranch(root: string): Promise<string> {
|
|
2174
2365
|
const r = await sh("git branch --show-current", root);
|
|
2175
2366
|
return r.ok ? r.out.split("\n")[0] : "";
|
|
@@ -2190,7 +2381,7 @@ function needState(root: string, sess: Session, slugArg?: string): { state: Flow
|
|
|
2190
2381
|
// sessions overwrite one state file (last write wins) while both believe they own the stage.
|
|
2191
2382
|
const claim = readClaim(root, slug);
|
|
2192
2383
|
if (sess.slug !== slug && claimBlocks(claim, sess.key))
|
|
2193
|
-
return { state: null, err: { text: `${slug} is claimed by another live session (
|
|
2384
|
+
return { state: null, err: { text: `${slug} is claimed by another live session (${claimWho(claim!)}) — flow use ${slug} takes it over explicitly`, isError: true } };
|
|
2194
2385
|
return { state };
|
|
2195
2386
|
}
|
|
2196
2387
|
|
|
@@ -2374,7 +2565,7 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2374
2565
|
name: "flow_stage",
|
|
2375
2566
|
label: "Stage worker",
|
|
2376
2567
|
description:
|
|
2377
|
-
'Delegate to a disposable dev-flow worker session with a fresh context. op "run" (default) does the current stage\'s work (implement | pre-release) and edits + commits on the feature branch; op "verify" is an independent read-only checker of the implement work (read + bash, standing order "check, don\'t fix", closes with a VERIFY REPORT verdict — flow verify refuses until a PASS exists over the current tree); op "reflect" reviews the finished flow — the driver transcript plus every worker transcript — at the release stage after release-done. Everything the worker must know — operator answers not yet recorded by a gate, decisions, warnings, the exact next action — travels in `note`; otherwise it sees only plan, git and flow status. Give each delegation a short `label` (a few words of purpose) — session names then read `⏳ 🔍 · <label>` while running and `✓ 🔍 ·
|
|
2568
|
+
'Delegate to a disposable dev-flow worker session with a fresh context. op "run" (default) does the current stage\'s work (implement | pre-release) and edits + commits on the feature branch; op "verify" is an independent read-only checker of the implement work (read + bash, standing order "check, don\'t fix", closes with a VERIFY REPORT verdict — flow verify refuses until a PASS exists over the current tree); op "reflect" reviews the finished flow — the driver transcript plus every worker transcript — at the release stage after release-done. Everything the worker must know — operator answers not yet recorded by a gate, decisions, warnings, the exact next action — travels in `note`; otherwise it sees only plan, git and flow status. Give each delegation a short `label` (a few words of purpose) — session names then read `⏳ 🔍 #1 · <label>` while running and `✓ 🔍 #1 · PASS · <label>` (or `✗ … · hard-cut`, `✓ 🔨 #2 · 3 commits · <label>`) when done, so the picker is never a column of identical rows. A worker holds no flow tool: gates, checkpoints and the claim stay with you. At 75% of its budget (budgetMin: default 45 for run, 30 for verify/reflect) the worker is steered to commit and report instead of being cut. The tool card streams the live tail (current tool, last assistant line, ✓/✗ results, elapsed/budget, usage) and op "status" mirrors it on any host. When a worker returns: read its report, run flow check yourself, then ask the checkpoint — a stage report is a handoff, never a verification.',
|
|
2378
2569
|
promptSnippet:
|
|
2379
2570
|
'flow_stage(op: "run"|"verify"|"reflect", note, budgetMin?) — delegate stage work, an independent read-only check, or the finish review to a fresh worker session; op: "status" reads the live run; gates and checkpoints stay with you',
|
|
2380
2571
|
parameters: Type.Object({
|
|
@@ -2423,7 +2614,7 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2423
2614
|
const inFlow = !!boundState;
|
|
2424
2615
|
const fam = inFlow ? await workerFamilyLines(ctx, run?.transcript, run ? BUCKET_FRESH_MS : 0) : null;
|
|
2425
2616
|
// the picker's rows when we have them; the ledger when the host gave us no file to be a parent of
|
|
2426
|
-
const familyLines = fam ?? (boundState ? ledgerFamilyLines(path.join(featDir(ctx.cwd, boundState.slug),
|
|
2617
|
+
const familyLines = fam ?? (boundState ? ledgerFamilyLines(path.join(featDir(ctx.cwd, boundState.slug), STAGE_SESSIONS_DIR, TRANSCRIPTS_FILE), run?.transcript) : null);
|
|
2427
2618
|
const familySection = inFlow ? [familyHeading({ live: !!run, ledger: fam === null && !!familyLines?.length }), ...(familyLines && familyLines.length ? familyLines : ["(none yet)"])] : [];
|
|
2428
2619
|
if (!run) {
|
|
2429
2620
|
return { content: [{ type: "text", text: ["no stage worker is running in this session", ...familySection].join("\n") }], details: { running: false, ...(inFlow ? { workers: workerFamilyCount(familyLines) } : {}) } };
|
|
@@ -2473,7 +2664,8 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2473
2664
|
stageRuns.set(key, run);
|
|
2474
2665
|
const cfg = loadProject(dfDir(ctx.cwd)).cfg;
|
|
2475
2666
|
const logFile = path.join(featDir(ctx.cwd, st.slug), "stage-live.log");
|
|
2476
|
-
const transcriptLog = path.join(featDir(ctx.cwd, st.slug),
|
|
2667
|
+
const transcriptLog = path.join(featDir(ctx.cwd, st.slug), STAGE_SESSIONS_DIR, TRANSCRIPTS_FILE);
|
|
2668
|
+
const delegationLog = path.join(featDir(ctx.cwd, st.slug), STAGE_SESSIONS_DIR, DELEGATIONS_FILE);
|
|
2477
2669
|
// read once, used twice: the worker's header links to this file and lands in this bucket,
|
|
2478
2670
|
// and the reflect brief names this session's own transcript to the reviewer
|
|
2479
2671
|
const lineage = lineageOf(ctx);
|
|
@@ -2491,9 +2683,9 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2491
2683
|
writeFileSync(logFile, `${stageLiveLine(0, "worker", `${op} started (${st.stage}, budget ${budgetMin} min)`)}\n`);
|
|
2492
2684
|
const beat = (toolName: string) => { if (ctx.hasUI) ctx.ui.setStatus("dev-flow-stage", `⏳ ${kindCard} · ${st.slug} ${stageElapsedLabel(Date.now() - run.startedAt)} · ${toolName}`); };
|
|
2493
2685
|
// ordinal among this feature's same-op workers, read from the durable index — re-delegations
|
|
2494
|
-
// read #2, #3 in the list instead of identical rows
|
|
2495
|
-
//
|
|
2496
|
-
const seq = op
|
|
2686
|
+
// read #2, #3 in the list instead of identical rows. A verify is numbered too: a feature that
|
|
2687
|
+
// takes six rounds to PASS reads as a sequence, not as six free-text labels. A reflect is one per flow.
|
|
2688
|
+
const seq = op !== "reflect" ? (existsSync(transcriptLog) ? parseWorkerTranscripts(readFileSync(transcriptLog, "utf8")).filter((x) => x.op === op).length : 0) + 1 : null;
|
|
2497
2689
|
const statusJsonText = (await runFlow(["status", "--json"], ctx.cwd, uiFrom(ctx), sessFor(ctx))).text;
|
|
2498
2690
|
const git = await sh("git status --porcelain -b", work);
|
|
2499
2691
|
const note = typeof params.note === "string" ? params.note : undefined;
|
|
@@ -2616,15 +2808,23 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2616
2808
|
// rev-parse misses `checkout -b` at the same SHA, symbolic-ref misses a detached move,
|
|
2617
2809
|
// and all three miss the plan the verdict was written against living outside the worktree
|
|
2618
2810
|
const moved = op !== "run" && ((statusBefore.ok && statusAfter.ok && statusAfter.out !== statusBefore.out) || (headBefore.ok && headAfter.ok && headAfter.out !== headBefore.out) || (refBefore.ok && refAfter.ok && refAfter.out !== refBefore.out) || planFingerprint(planDir) !== planBefore);
|
|
2619
|
-
// the outcome goes INTO the final name — a picker row like `✓ 🔍 · PASS · stamp attack` or
|
|
2811
|
+
// the outcome goes INTO the final name — a picker row like `✓ 🔍 #3 · PASS · stamp attack` or
|
|
2620
2812
|
// `✓ 🔨 #2 · 3 commits · wire ops` answers "how did it end?" without opening the session
|
|
2621
2813
|
let outcome: string | null = null;
|
|
2814
|
+
// The delegation ledger: this run's commit window, recorded however it ended — a
|
|
2815
|
+
// hard-cut worker's commits still sit on the branch, and a window the gate never learned
|
|
2816
|
+
// about reads as driver-authored work at flow verify. One count serves both: the picker row and the ledger.
|
|
2817
|
+
let runCommits = 0;
|
|
2818
|
+
if (op === "run" && headBefore.ok && headAfter.ok) {
|
|
2819
|
+
const c = await sh(`git rev-list --count ${sq(headBefore.out)}..HEAD`, work);
|
|
2820
|
+
runCommits = c.ok ? Number.parseInt(c.out.trim(), 10) || 0 : 0;
|
|
2821
|
+
try {
|
|
2822
|
+
mkdirSync(path.dirname(delegationLog), { recursive: true });
|
|
2823
|
+
appendFileSync(delegationLog, `${delegationLine(now(), st.stage, headBefore.out.trim(), headAfter.out.trim(), runCommits)}\n`);
|
|
2824
|
+
} catch { /* an index that failed to append is never a reason to lose the run */ }
|
|
2825
|
+
}
|
|
2622
2826
|
if (clean) {
|
|
2623
|
-
if (
|
|
2624
|
-
const c = await sh(`git rev-list --count ${sq(headBefore.out)}..HEAD`, work);
|
|
2625
|
-
const n = c.ok ? c.out.trim() : "0";
|
|
2626
|
-
if (n !== "0") outcome = `${n} commit${n === "1" ? "" : "s"}`;
|
|
2627
|
-
}
|
|
2827
|
+
if (runCommits > 0) outcome = `${runCommits} commit${runCommits === 1 ? "" : "s"}`;
|
|
2628
2828
|
if (verify?.verdict) outcome = moved ? "verdict VOID" : verify.verdict.toUpperCase();
|
|
2629
2829
|
if (findings && !findings.missing) outcome = `${findings.playbook.length + findings.plugin.length + findings.other.length} findings`;
|
|
2630
2830
|
} else {
|
|
@@ -2636,7 +2836,7 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2636
2836
|
let snapshot: string | null = null;
|
|
2637
2837
|
const dirty = await sh("git status --porcelain", work);
|
|
2638
2838
|
if (dirty.ok && dirty.out.trim()) {
|
|
2639
|
-
const snapDir = path.join(featDir(ctx.cwd, st.slug),
|
|
2839
|
+
const snapDir = path.join(featDir(ctx.cwd, st.slug), STAGE_SESSIONS_DIR);
|
|
2640
2840
|
mkdirSync(snapDir, { recursive: true });
|
|
2641
2841
|
const stamp = Date.now();
|
|
2642
2842
|
const diffFile = path.join(snapDir, `${op}-${stamp}.diff`);
|
|
@@ -2819,7 +3019,11 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2819
3019
|
// an uninitiated folder hears nothing from dev-flow at all — flow init is the opt-in that arms
|
|
2820
3020
|
// the guards, the no-playbook bash-timeout default included
|
|
2821
3021
|
if (noDf) return undefined;
|
|
2822
|
-
|
|
3022
|
+
// Everything below that reads flow truth reads it from here: in a feature worktree that is the main
|
|
3023
|
+
// checkout (see flowRoot), which is what makes owner attribution — and the worker half of the
|
|
3024
|
+
// implement guard — reachable for the session that was actually sent to do the work.
|
|
3025
|
+
const guardRoot = await flowRoot(ctx.cwd);
|
|
3026
|
+
const cfg = loadProject(dfDir(guardRoot)).cfg;
|
|
2823
3027
|
const mustStateTimeout = shellCmd !== "" && explicitTimeout === undefined && cfg.bashTimeout === "require";
|
|
2824
3028
|
// for bash this verdict waits behind the operator's own deny/confirm rules further down;
|
|
2825
3029
|
// powershell meets no project rules at all, so it is answered here
|
|
@@ -2828,8 +3032,8 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2828
3032
|
|
|
2829
3033
|
if (isToolCallEventType("edit", event) || isToolCallEventType("write", event)) {
|
|
2830
3034
|
const abs = path.resolve(ctx.cwd, String(event.input.path ?? ""));
|
|
2831
|
-
const feats = featureRefs(
|
|
2832
|
-
const bound = boundFeature(
|
|
3035
|
+
const feats = featureRefs(guardRoot);
|
|
3036
|
+
const bound = boundFeature(guardRoot, key);
|
|
2833
3037
|
// operator safety rules from project.md run first — as in the bash guard, the operator's deny outranks flow discipline
|
|
2834
3038
|
const pv = guardPath(abs, ctx.cwd, cfg.guard);
|
|
2835
3039
|
if (pv.block) return { block: true, reason: pv.block };
|
|
@@ -2837,14 +3041,20 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2837
3041
|
const why = await askOperator(ctx, `Editing ${path.relative(ctx.cwd, abs) || abs}`, pv.confirm);
|
|
2838
3042
|
if (why) return { block: true, reason: why };
|
|
2839
3043
|
}
|
|
2840
|
-
|
|
3044
|
+
// A registered worker session is the one allowed to write a normal feature's worktree at
|
|
3045
|
+
// implement — that is what it was sent to do (see writeGuard's byWorker).
|
|
3046
|
+
// repoRoot stays the session's own checkout: the scratch rule asks where the BYTES land, and a
|
|
3047
|
+
// project that parks its worktrees outside the checkout (or under the temp dir) must not have
|
|
3048
|
+
// those writes read as a throwaway because the flow truth was resolved elsewhere.
|
|
3049
|
+
const reason = writeGuard({ abs, dfDir: dfDir(guardRoot), features: feats, boundSlug: bound?.slug ?? null, repoRoot: ctx.cwd, byWorker: isWorkerSession(ctx.sessionManager?.getSessionId?.()) });
|
|
2841
3050
|
if (reason) return { block: true, reason };
|
|
2842
3051
|
// Editing a worktree invalidates that feature's tier-1 checks and tier-2 confirmation until they rerun.
|
|
2843
3052
|
const owner = feats.find((f) => f.worktreeAbs && abs.startsWith(f.worktreeAbs + path.sep));
|
|
2844
3053
|
if (owner && (owner.state.stage === "implement" || owner.state.stage === "pre-release") && (Object.keys(owner.state.checks).length || owner.state.confirmations?.implement)) {
|
|
2845
3054
|
owner.state.checks = {};
|
|
2846
3055
|
delete owner.state.confirmations?.implement;
|
|
2847
|
-
|
|
3056
|
+
// the owner's state lives in the flow-truth root, not in the worktree's own .dev-flow/ copy
|
|
3057
|
+
writeState(guardRoot, owner.state);
|
|
2848
3058
|
}
|
|
2849
3059
|
return undefined;
|
|
2850
3060
|
}
|
|
@@ -2882,7 +3092,7 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2882
3092
|
}
|
|
2883
3093
|
const inv = gitInvocation(command);
|
|
2884
3094
|
if (!inv.subs.length) return undefined; // git is not invoked as a command — nothing to guard
|
|
2885
|
-
const bound = boundFeature(
|
|
3095
|
+
const bound = boundFeature(guardRoot, key);
|
|
2886
3096
|
// judge EACH git segment by the branch of the directory it runs in — a chain may cd across
|
|
2887
3097
|
// directories; one last-cd-wins verdict misattributed mixed-dir chains and blocked legit worktree commits
|
|
2888
3098
|
const branchCache = new Map<string, string>();
|
|
@@ -2896,7 +3106,7 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2896
3106
|
}
|
|
2897
3107
|
return branchCache.get(at)!;
|
|
2898
3108
|
};
|
|
2899
|
-
const worktrees = featureRefs(
|
|
3109
|
+
const worktrees = featureRefs(guardRoot).map((f) => f.worktreeAbs).filter((w): w is string => !!w);
|
|
2900
3110
|
for (const g of inv.gitSegs) {
|
|
2901
3111
|
const gitDir = g.dir ? path.resolve(ctx.cwd, g.dir) : ctx.cwd;
|
|
2902
3112
|
const seg = gitInvocation(g.seg); // parsed once per segment — this runs on every bash call of every session
|
|
@@ -2947,6 +3157,10 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2947
3157
|
// client attaches, and this is the earliest point the client is certainly listening
|
|
2948
3158
|
refreshStatus(ctx);
|
|
2949
3159
|
if (!initiated(ctx.cwd)) return undefined;
|
|
3160
|
+
// A stage worker's whole instruction is its brief. The driver's context is wrong there twice over:
|
|
3161
|
+
// the unbound posture tells it to pre-plan and `flow start`, and the branch check reads its
|
|
3162
|
+
// worktree as a main checkout on the wrong branch. Guards still run — they hang off tool_call.
|
|
3163
|
+
if (isWorkerSession(ctx.sessionManager?.getSessionId?.())) return undefined;
|
|
2950
3164
|
const key = sessionKey(ctx);
|
|
2951
3165
|
// The playbook core rides along on the message this run writes anyway — once per session.
|
|
2952
3166
|
const core = corePreamble(key);
|
|
@@ -2956,8 +3170,10 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2956
3170
|
// Default posture for an unbound session in a dev-flow repo (guards make it stick; this makes it understood).
|
|
2957
3171
|
let content = "[dev-flow] no flow bound. Every request goes through flow. New work — pre-plan first (see the skill): analyze read-only, bring findings + questions + a direction with a proposed slug/mode to the operator, and flow start <slug> only once they say start; unfinished feature: flow use <slug>.";
|
|
2958
3172
|
const cb = claimBlocker(ctx.cwd, key);
|
|
2959
|
-
if (cb) content += ` Also: ${cb.state.slug} is claimed by another live session (
|
|
2960
|
-
|
|
3173
|
+
if (cb) content += ` Also: ${cb.state.slug} is claimed by another live session (${claimWho(cb.claim)}) — flow use ${cb.state.slug} takes it over explicitly.`;
|
|
3174
|
+
// only the main checkout has a "main checkout branch": a session opened in a linked worktree is
|
|
3175
|
+
// on its feature branch by construction, and calling that a drift misleads it
|
|
3176
|
+
const curBr = (await isLinkedWorktree(ctx.cwd)) ? "" : await currentBranch(ctx.cwd);
|
|
2961
3177
|
if (curBr && curBr !== cfg.defaultBranch) content += ` Also: main checkout is on ${curBr}, not ${cfg.defaultBranch} — surface this to the operator before starting work.`;
|
|
2962
3178
|
const refl0 = readReflections(ctx.cwd);
|
|
2963
3179
|
if (refl0.length) content += ` Also: ${refl0.length} reflection(s) open — run flow doctor.`;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-dev-flow",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.72.0",
|
|
4
4
|
"description": "Enforced feature workflow for Pi: plan → implement → pre-release → release, gated checkpoints, self-improvement reflections, one git worktree per feature, changelog + publish as part of the release",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
package/skills/dev-flow/SKILL.md
CHANGED
|
@@ -69,6 +69,8 @@ Ground rules:
|
|
|
69
69
|
`flow status` is your view. **project.md is the operator-owned playbook**:
|
|
70
70
|
read freely, **never edit** — it changes through `flow init --write` on the
|
|
71
71
|
operator's word (`flow doctor` reviews what it lacks).
|
|
72
|
+
- **At implement the driver drives, a worker writes** — `flow verify` proves the branch's
|
|
73
|
+
commits fall inside a `flow_stage` run window (`--docs`/`--patch` stay inline).
|
|
72
74
|
- **Every bash/shell call states its own `timeout`** or the guard refuses it.
|
|
73
75
|
- **A guard blocking you means you are skipping a stage or writing outside your
|
|
74
76
|
feature** — run the gate instead of working around it. The guard reads
|