pi-dev-flow 0.71.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 CHANGED
@@ -4,6 +4,11 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.72.0] - 2026-11-03
8
+
9
+ - **The implement stage must be worked, not just driven.** A session could always judge its own implement work too small to delegate and author it inline — `flow verify` proved the tree, never who wrote it. Now a normal feature's verify refuses unless every commit the branch holds falls inside a `flow_stage` worker's recorded run window: each finished worker appends its window to a dev-flow-owned `stage-sessions/delegations.log` (a session cannot sign its own proof — the ledger is refused to edit/write tools and counted as state tampering in bash), and an after-the-fact amend or rebase surfaces as an uncovered sha no write guard could ever see. While a normal feature is at implement, its own worktree is closed to its driver's edit/write tools and open to the worker that was sent to do it; the injected implement hint, the playbook and the skill no longer offer the inline escape. `--docs` and `--patch` — the operator-granted inline modes — are exempt, and there is no flag or yolo path around the rule. Heads-up for flows already at implement when you upgrade: their existing commits precede any ledger, so their next `flow verify` refuses — delegate a worker that finishes (or redoes) the work.
10
+ - **A session inside a feature worktree is judged by the main checkout's flow truth.** Workers run with cwd = the worktree, whose own tracked `.dev-flow/` holds only `project.md` — so the guard found zero features and every worker since worktrees existed heard `no active flow` when it reached for the edit tool: real workers authored everything through bash, the one surface the guard never policed. A linked worktree now resolves to its main checkout for feature, binding and state reads, and the write guard's worker half fires for the first time. A plain human session opened inside a worktree reads as a driver there — deliberate: worker-ness is a registration, not a location.
11
+
7
12
  ## [0.71.0] - 2026-11-02
8
13
 
9
14
  - **A running worker finally wears its `⏳` name.** pi fires `session_start` only for sessions a host binds, never for the SDK-built worker, so the live name dev-flow hung on that event never landed: every worker since 0.68 ran as whatever an auto-namer made of its brief (`you-are-a-dev`), and only the final `✓`/`✗` rename showed. The name is now written onto the session before its first prompt.
package/docs/gates.md CHANGED
@@ -15,7 +15,7 @@ so it needs no `--confirmed`.
15
15
  | `test` | records a check | — (runs the `test` command/check, records pass/fail) |
16
16
  | `check` | records all tier-1 checks | — (runs every `flow-check`/test/health from project.md `## implement`); a `--docs` feature runs none of them and says `docs mode: project commands skipped` — a docs flow builds nothing, so a fresh checkout must not read as a failed deploy (#96) |
17
17
  | `health` | records a check | — (runs `seedData` + the health command, retrying up to `healthWait` seconds; app must be up locally with real data) |
18
- | `verify [--yolo]` | implement → pre-release | a **verify-worker PASS over the current tree** first (`flow_stage { op: "verify" }`; the stamp belongs to the tree it read — any edit drops it like a tier-1 record and a fresh worker is owed; a docs flow is exempt), then all tier-1 checks green — a check with no passing record is **run by the gate itself** (`checks ran at the gate (test)`) rather than refused and pointed at `flow check`, since entering the stage or editing the worktree is what cleared it — and so is a record whose worktree fingerprint differs from the tree now (`stale record(s) rerun after a worktree change: …`): a change made through bash fires no edit-tool hook, the fingerprint is what notices the tree moved — and a failure there prints the run output, **the feature branch holds at least one commit** (verify refuses a branch with nothing committed — the checks describe the working tree, so an uncommitted state has never been recorded — and prints `commits: N ahead of <default>, M uncommitted path(s)` with what it ran; uncommitted paths are reported, never gated), build (if configured) green, `dev` deploy (if configured) runs first so you can review the running app **and the health probe (if configured) re-runs against what it just deployed, retrying every 2s up to `healthWait` seconds** (a failing probe refuses the gate and reports how many attempts it took: the `flow check` PASS predates the deploy, and a service that needs seconds after its container starts is not a broken deploy; with no probe the output says `health: none configured`); with **no `dev` command but a `health` probe configured the gate live-re-probes the app before asking** (`health: live re-probe PASS` — a killed server refuses with `live probe FAILED`, because process death dirties no worktree fingerprint and a green record alone cannot prove liveness: start the app and rerun), tier-2 checklist (ui-only items excluded for non-UI features) confirmed as a set; a `--docs` feature runs none of it (`docs mode: project commands skipped`) and only asks you; **one question** — or `--confirmed`; `--yolo --confirmed` = you answered 'yolo' at Verified? — answers it and pre-confirms the rest |
18
+ | `verify [--yolo]` | implement → pre-release | a **verify-worker PASS over the current tree** first (`flow_stage { op: "verify" }`; the stamp belongs to the tree it read — any edit drops it like a tier-1 record and a fresh worker is owed; a docs flow is exempt), **evidence that worker sessions did the implement work** (`.dev-flow/<slug>/stage-sessions/delegations.log` holds each finished `flow_stage` run's commit window, and is dev-flow-owned — a session may read it but never write it (the write guard and the bash tamper patterns both refuse it), so the session under test cannot sign its own proof; the gate refuses when no implement-stage window carried a commit — the refusal prints the `flow_stage { stage: "implement" }` call to run — and refuses by count when commits on the branch fall outside every window, naming the fix: delegate a fixer that redoes them, or reset them; a `--docs` or `--patch` flow is exempt, nothing measured, and a git answer that cannot be had is never proof of a violation, while a gate that holds prints `delegation proven: N worker commit(s) in M window(s)`; judged only here, so the driver's own pre-release commits — changelog, bump — stay legal), then all tier-1 checks green — a check with no passing record is **run by the gate itself** (`checks ran at the gate (test)`) rather than refused and pointed at `flow check`, since entering the stage or editing the worktree is what cleared it — and so is a record whose worktree fingerprint differs from the tree now (`stale record(s) rerun after a worktree change: …`): a change made through bash fires no edit-tool hook, the fingerprint is what notices the tree moved — and a failure there prints the run output, **the feature branch holds at least one commit** (verify refuses a branch with nothing committed — the checks describe the working tree, so an uncommitted state has never been recorded — and prints `commits: N ahead of <default>, M uncommitted path(s)` with what it ran; uncommitted paths are reported, never gated), build (if configured) green, `dev` deploy (if configured) runs first so you can review the running app **and the health probe (if configured) re-runs against what it just deployed, retrying every 2s up to `healthWait` seconds** (a failing probe refuses the gate and reports how many attempts it took: the `flow check` PASS predates the deploy, and a service that needs seconds after its container starts is not a broken deploy; with no probe the output says `health: none configured`); with **no `dev` command but a `health` probe configured the gate live-re-probes the app before asking** (`health: live re-probe PASS` — a killed server refuses with `live probe FAILED`, because process death dirties no worktree fingerprint and a green record alone cannot prove liveness: start the app and rerun), tier-2 checklist (ui-only items excluded for non-UI features) confirmed as a set; a `--docs` feature runs none of it (`docs mode: project commands skipped`) and only asks you; **one question** — or `--confirmed`; `--yolo --confirmed` = you answered 'yolo' at Verified? — answers it and pre-confirms the rest |
19
19
  | `release [--yolo|--no-version|--no-fold-check]` | pre-release → release | checks re-greened after the prep edits; **the worktree holds no uncommitted paths** (gh#131: a merge ships the branch, not the working tree — an uncommitted fix at this gate is a fix that never ships; the refusal lists the paths, and the approved line prints `commits: N ahead of <default>, M uncommitted path(s)` like verify's); with `versioning.file`: the manifest version parses and is **not tagged yet** (the bump must be ahead of the last release); with `release.changelog` the gate **proves the entry mechanically** (#97): a **heading names the version** (prose that mentions it, or a `1.2.0-beta` section when releasing `1.2.0`, is not an entry), **this branch touched the file** (an inherited changelog is not release prep), **every entry that was pending before the release survives inside the new section** — compared on normalized lines, so re-indenting a fold is free while rewording or deleting one is refused by naming the line — and **nothing is left under `Unreleased`**. The proofs guard the **baseline's** pending lines — they do not freeze the wording of the entry this flow writes, so a branch that landed as several iteration commits is free to state its result as one entry (see the changelog-writer rule in the pre-release reference). The pending baseline is the newest tag's changelog (what actually shipped), else the branch's merge base; when neither resolves, the two git-dependent proofs are skipped **with a printed advisory** rather than refusing a legal release for a topology reason, and the content proofs (the heading, its body) always run; tier-2 `## pre-release` checklist confirmed; the manifest version it validates is **stamped as the release's version of record** (`release-done` publishes that, whatever the checkouts say later); **one question** (Release?) — or `--confirmed`; `--no-version` (your call at Release?) ships this flow as **merge + changelog** — the bump/tag requirements and the tag checks at `release-done` are skipped for it, but the branch must still add its **own line under `Unreleased`** (editing an older section releases nothing) and it rides there until the next versioned release folds it (default: versioned); `--no-fold-check` is the operator-granted escape from the line-level fold proofs — one flow, stamped in the gate output, the heading and touched proofs stay; **stale session build** (loaded build behind the checkout): the gate prints both builds, lists what shipped between them (those proofs will not run this release) and folds *update (/reload, then re-run) or proceed with the old release?* into the Release? question — the operator's word, recorded in the release output, **never a block**: publishing under an older gate is a legitimate choice (hotfix, offline reload) |
20
20
  | `release-done` | records the release (the stage stays `release`) | **no question — the Release? answer covered the publication**; verify approval; the version published is the one `release` **stamped** from the manifest it validated (a main checkout still behind cannot republish the previous version), and it must not be older than the newest matching tag **on origin** (tag lists come from `git ls-remote`, so an unfetched clone does not decide what exists; when an origin exists but cannot be asked (offline, no ssh agent) **both release gates refuse** rather than answering with local tags); with `versioning.file`: that tag exists, is reachable from the default branch **and is on origin** (a local-only tag is not a release); with `release.artifact`: the published-artifact check runs (`{version}`/`{tag}` placeholders — the line it prints names the version it verified; skip once with `--no-artifact-check`, operator-instructed only) · creates the forge release from the tag, its body **the `release.changelog` entry for that version** — the changelog is the source of truth, and the tag's annotation stands in only when the changelog has no entry for the version, else nothing (and it says why — a body that is really a shell error is dropped, never shipped) — `gh` for GitHub, `glab` for GitLab) and then **proves the release exists**: it asks the forge (`gh release view <tag>` / `glab release view <tag>`) and refuses when nothing is there, because #51, #60 and #63 were three ways of ending `release recorded as complete` with nothing published — and when the changelog was the body it **reads the stored body back** and refuses a mismatch, so the release page and the changelog cannot drift (#97; normalized before comparing, skipped with a printed note on another forge). Skipping is deliberate and loud — `--no-release-create`, `release.releases = false` or `forge = self` each print that no forge release was created, and the view check is skipped for them; **with a `merge` policy** it also proves the merge that shipped matches it — branch ancestry plus what the forge says (`gh pr view` / `glab api`), so a squash under `merge = merge` (or a merge commit under `merge = squash`) refuses the release record, while a shape it cannot see prints an advisory instead (#97's split: an invisible topology never blocks a legal release); when the release went out on a stale build the operator acknowledged at the release gate, it prints that acknowledgement in place of the after-the-fact version-skew warning, and that warning prints the session vs disk version pair plus the duplicate-copy note when a second copy is registered (#117) |
21
21
  | `finish [--yolo] [slug]` | release → done (removes worktree + branch, deletes `.dev-flow/<slug>/`, and deletes `origin/<branch>` **only** when its merged state is verified — ancestor of the default branch or a merged PR/MR via `gh`/`glab`; unverifiable branches stay with a note) | a release is recorded (`release-done` ran), the main checkout is clean **and** pushed to `origin/<default>`, and the worktree has no uncommitted changes (the refusal lists the paths, not just the count — gh#131); when the clean checkout trails `origin/<default>` the gate **fast-forwards local main** as it closes out (never a merge — anything that cannot fast-forward prints the operator's exact `git pull --ff-only` command); **one question** (Finish? — mentions unmerged-looking commits with the playbook's `merge` policy in mind, and warns when the forge release create failed at `release-done` and no retry succeeded) — or `--confirmed`; under `merge = merge`, commits that never reached the default branch are a **policy violation**: `yolo` does not answer it, only your explicit answer does; to abandon an unreleased feature use `abort` |
@@ -6,9 +6,9 @@ While a feature is active, the extension intercepts every tool call:
6
6
 
7
7
  - **Nothing on main, ever** (until release): `git commit` on the default branch is blocked at every stage except `release` — where release chores commit in the main checkout (prefixed `DEV_FLOW_ALLOW_MAIN=1` for the hook) — and except one chore that needs no flow: a commit whose **only** change in the checkout is `.dev-flow/project.md`, because tracking the operator's playbook is setup, not feature work (any other dirty path closes that lane). pushes are judged by the ref they write — only pushing *to* the default branch (or a bare push while on it) requires stage `release`, so tag pushes and feature-branch pushes pass from any stage; `git merge` onto the default branch also requires stage `release`. Plus the standalone pre-commit hook for commits made outside Pi.
8
8
  - **No code before an approved plan**: at stage `plan`, edits are confined to `.dev-flow/<slug>/` — the session's **own** feature directory, so one session cannot write another feature's plan and have its gate rubber-stamp what it never wrote.
9
- - **Work stays in the worktree**: at stages `implement` and `pre-release`, edits are confined to that feature's worktree — judged per-path by the owning feature, so one session can never write into another session's worktree or into the main checkout. A throwaway **outside** the checkout is not feature work and stays free at every stage (the OS temp dir, e.g. a one-off rewrite script): both sides are realpath'd, so a symlink out of the temp dir is still judged as the repo path it writes, and a repository that merely lives under the temp dir (a test repo) keeps the stage rules.
9
+ - **Work stays in the worktree**: at stages `implement` and `pre-release`, edits are confined to that feature's worktree — judged per-path by the owning feature, so one session can never write into another session's worktree or into the main checkout. A throwaway **outside** the checkout is not feature work and stays free at every stage (the OS temp dir, e.g. a one-off rewrite script): both sides are realpath'd, so a symlink out of the temp dir is still judged as the repo path it writes, and a repository that merely lives under the temp dir (a test repo) keeps the stage rules. **At implement the driver drives**: for a normal feature the driving session's own edit/write tools are refused inside its own worktree — the `flow_stage` worker it sent (workers are registered when spawned) is the session allowed to author there, and `flow verify` proves the branch's commits fall inside a worker's recorded run window (`stage-sessions/delegations.log`); `--docs` and `--patch` flows stay inline because the operator granted those modes, and bash is left alone — running commands is driving, not authoring. Being a worker is a **registration**, not a location: a human session opened **inside** the worktree is not a registered worker, so it reads as a driver and its edit tools are refused at implement too — deliberate: at this stage the work goes out through `flow_stage` whoever is holding the editor, and the stages that stay the driver's own (pre-release prep, a `--docs`/`--patch` flow) open the same pen. Attribution reads the **main checkout's** `.dev-flow/` even when the session's cwd is the worktree: a linked worktree carries only the tracked playbook copy, so judging from the worktree's own copy saw no features and every guard answered "no active flow".
10
10
  - **Flow by default**: in a repo with `.dev-flow/`, an unbound session cannot touch source files at all — every request goes through `flow start`/`flow use`; there is no bypass. `flow start` refuses when the main checkout isn't on the default branch, worktrees are always created from the default branch, and the agent cannot check feature branches out in the main checkout.
11
- - **Gates can't be skipped**: flow state is untouchable by the agent (edit tool and bash) — writing `state.json` or `claim.json`, moving either away, or deleting a feature directory or the whole `.dev-flow/` folder all block, at a relative **or an absolute** path (an absolute path names the same folder); the `project.md` playbook is operator-owned — the main-checkout copy is blocked for the agent outright, and only a **docs or patch flow's** worktree copy may be edited (normal features route playbook changes to their own flow); every sanctioned playbook overwrite keeps the previous file as `project.md.bak`; every recorded check carries a fingerprint of the worktree it ran against (paths, uncommitted diff, HEAD) — an edit-tool change clears the records at once, and any other write (`sed -i`, a formatter, codegen through bash) is caught at the gate itself, which reruns what went stale and says so; edit/write paths are judged by realpath, so a symlink out of the worktree cannot launder a confined write.
11
+ - **Gates can't be skipped**: flow state is untouchable by the agent (edit tool and bash) — writing `state.json`, `claim.json` or the **delegation ledger** (`stage-sessions/delegations.log` — the file `flow verify` trusts about *who* worked the stage, so it is dev-flow-owned like the other two: the write guard refuses it to a session and the bash tamper patterns refuse a write, move or delete of it, while reading it and `git add`-ing it stay legal; the only writer is a finished `flow_stage` worker run, appending in-process where that code already computes the worker's commits — the session the gate constrains cannot sign its own proof), moving any of them away, or deleting a feature directory or the whole `.dev-flow/` folder all block, at a relative **or an absolute** path (an absolute path names the same folder); the `project.md` playbook is operator-owned — the main-checkout copy is blocked for the agent outright, and only a **docs or patch flow's** worktree copy may be edited (normal features route playbook changes to their own flow); every sanctioned playbook overwrite keeps the previous file as `project.md.bak`; every recorded check carries a fingerprint of the worktree it ran against (paths, uncommitted diff, HEAD) — an edit-tool change clears the records at once, and any other write (`sed -i`, a formatter, codegen through bash) is caught at the gate itself, which reruns what went stale and says so; edit/write paths are judged by realpath, so a symlink out of the worktree cannot launder a confined write.
12
12
  - **Your project's own rules**: every `deny`/`confirm`/`protect`/`forbid` rule from the `flow-guard` block in project.md `## global` runs on every bash command and every edit/write path — in every stage and binding, ahead of dev-flow's own verdicts. A block always carries the reason you wrote.
13
13
  - **The rules reach the agent, they are not left in a file it may never read**: pi advertises a skill and loads it only if the model chooses to, so the ground rules of the dev-flow skill are injected into every session once (and again after a compaction that summarized them away), and each stage's turn names the one playbook file that stage needs. The guards enforce the same discipline either way — this is what makes the agent follow it without being stuck.
14
14
  - **A forced push asks the operator**: `git push` carrying `--force`, `--force-with-lease…` or `-f` is confirmed before it runs — a rewritten branch is history CI and other sessions already have. The one spelling that answers for it is the prefix the refusal prints (`DEV_FLOW_ALLOW_REWRITE=1 git push -f …`), the same "the operator said so" contract as `DEV_FLOW_ALLOW_MAIN`. Local history rewrites (`git filter-branch --force`) are not pushes and stay free, so a project never needs a blunt flag-only deny of its own.
@@ -4,8 +4,8 @@ A big `implement` costs more context than the rest of the flow will ever need:
4
4
  the driving session carries those hundred tool calls into every later gate and
5
5
  checkpoint. `flow_stage` runs that work in a fresh, disposable session
6
6
  instead, and hands back one bounded report. The conversation that talks to you
7
- stays lean — which is why non-trivial implement work is **delegated by default**,
8
- not inlined (see `references/implement.md`). Three ops share one mechanism: `run` (a stage's work), `verify` (an
7
+ stays lean — which is why implement work is **delegated**, not inlined, and why
8
+ `flow verify` proves it from the ledger below (see `references/implement.md`). Three ops share one mechanism: `run` (a stage's work), `verify` (an
9
9
  independent, check-only reviewer of the implement work) and `reflect` (an
10
10
  independent review of the whole finished flow at release). Only the brief, the
11
11
  toolset, the budget default and the closing contract differ — the safety story
@@ -13,6 +13,24 @@ is identical, and a second mechanism would drift.
13
13
 
14
14
  ## What delegates, what does not
15
15
 
16
+ **The ledger proves who worked.** Every finished `run` worker appends its stage and its commit
17
+ range to `.dev-flow/<slug>/stage-sessions/delegations.log` — one line, `[<iso>] run (<stage>):
18
+ <start>..<end> <n> commit(s)` — written by the same completion code that renames the worker with
19
+ its commit count. The file is dev-flow-owned — the write guard refuses it to a session, the bash tamper patterns refuse a write, move or delete of it, and only a worker run's completion appends it, in-process — precisely so the session whose work it proves cannot sign its own proof. `flow verify` reads it fresh and refuses when it shows no implement-stage
20
+ delivery, or when a commit on the branch falls outside every implement window (the refusal counts
21
+ the strays and names the fix: delegate a fixer that redoes them, or reset them). A range, not a
22
+ count, is what makes it hold: an amend or a rebase after the fact moves the sha out of every window
23
+ the ledger recorded, which no write guard could see. `--docs` and `--patch` flows are exempt —
24
+ nothing to delegate in a docs pass or a one-file chore — and a git question that cannot be answered
25
+ is never proof of a violation. Coverage is judged only at verify: the driver's own commits after it
26
+ (changelog, bump) are pre-release work and belong to the session by design. The write guard is the
27
+ early nudge of the same rule — a driver's edit inside its own worktree at implement is refused, a
28
+ registered worker session's is not — while bash stays unguarded: running commands is driving, and
29
+ the ledger's commit ranges are what carry the proof. A worktree session is judged by the **main
30
+ checkout's** `.dev-flow/`, which is where the state actually lives: a linked worktree carries only the
31
+ tracked playbook copy, so reading the worktree's own copy found no features and every guard answered
32
+ "no active flow" — including for the worker it had to attribute.
33
+
16
34
  `flow_stage(stage: "implement" | "pre-release", note)` runs the **work** of
17
35
  the stage you are in; `flow_stage(op: "verify")` (legal only while the flow is
18
36
  at implement) and `flow_stage(op: "reflect")` (at release, after
@@ -128,7 +146,7 @@ Around it, three mirrors:
128
146
  tails a session still running is the viewer's choice, the card above is what
129
147
  the flow promises. Every finished worker appends its transcript path to
130
148
  `.dev-flow/<slug>/stage-sessions/transcripts.log` — the durable index the
131
- reflect worker reads;
149
+ reflect worker reads, next to `delegations.log` — the delegation ledger the verify gate reads;
132
150
  - the driving session's **footer** beats `⏳ 🔨 implement · <label> · <slug>
133
151
  mm:ss · <tool>` while a worker runs (cleared when it ends);
134
152
  - every line appends to `.dev-flow/<slug>/stage-live.log` — tail-able, and
@@ -201,7 +219,9 @@ those buckets once their feature is finished or its worktree is gone, with the
201
219
  ## Deliberate limits (v2)
202
220
 
203
221
  Same model for worker and driver (a per-stage model/tool policy is a playbook
204
- conversation for later); no delegating verify's fix loop — the checker is
205
- fresh each cycle, the fixing stays the driver's call (inline or via a fresh
206
- `run` worker); the worker cannot ask you anything — if it needed to, the note
222
+ conversation for later); the verify worker's fixing is delegated too — the
223
+ checker is fresh each cycle and so is the fixer, because at implement the guard
224
+ refuses the driver's own pen in its own worktree (the driver decides *what* the
225
+ fix is and sends the note; a `run` worker writes it, then a fresh verify worker
226
+ re-reads the tree); the worker cannot ask you anything — if it needed to, the note
207
227
  was too thin.
@@ -48,6 +48,13 @@ import {
48
48
  renderStageReport,
49
49
  checklistHash,
50
50
  checklistPending,
51
+ DELEGATIONS_FILE,
52
+ STAGE_SESSIONS_DIR,
53
+ delegationErrors,
54
+ delegationLine,
55
+ parseDelegationLedger,
56
+ mainCheckoutRoot,
57
+ type DelegationWindow,
51
58
  checkoutTarget,
52
59
  claimBlocks,
53
60
  clampStageBudgetMin,
@@ -910,9 +917,8 @@ async function stampChecks(root: string, state: FlowState, names: string[]): Pro
910
917
  * question. Local refs only — same offline-safe stance as the changelog proof — and an
911
918
  * unanswerable merge base reports null instead of refusing on a measurement failure. */
912
919
  async function branchState(cwd: string, defaultBranch: string): Promise<BranchState> {
913
- 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);
914
- const base = mb.out.trim();
915
- if (!mb.ok || !base) return { commitsAhead: null, uncommitted: 0 };
920
+ const base = await mergeBase(cwd, defaultBranch);
921
+ if (!base) return { commitsAhead: null, uncommitted: 0 };
916
922
  const ahead = await sh(`git rev-list --count ${sq(base)}..HEAD`, cwd);
917
923
  const n = Number.parseInt(ahead.out.trim(), 10);
918
924
  const dirty = await sh("git status --porcelain", cwd);
@@ -922,6 +928,54 @@ async function branchState(cwd: string, defaultBranch: string): Promise<BranchSt
922
928
  };
923
929
  }
924
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
+
925
979
  function describeBranchState(b: BranchState, defaultBranch: string): string {
926
980
  return b.commitsAhead === null
927
981
  ? `commits: unknown (no merge base with ${defaultBranch} — the commit proof is skipped)`
@@ -1197,6 +1251,17 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1197
1251
  writeState(root, state!);
1198
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 };
1199
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 };
1200
1265
  const pending = pendingChecks(state!, cfg);
1201
1266
  const gateRun = pending.length ? await runChecks(root, state!, cfg, pending) : null;
1202
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 };
@@ -1208,6 +1273,7 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
1208
1273
  const did: string[] = [];
1209
1274
  if (gateRun) did.push(`checks ran at the gate (${pending.map((c) => c.name).join(", ")})`);
1210
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)`);
1211
1277
  if (state!.docs) {
1212
1278
  // docs mode's contract: no tier-1 work happens, so a docs flow neither builds, deploys nor probes (#43 #49)
1213
1279
  did.push("docs mode: project commands skipped (build/dev/health)");
@@ -2265,6 +2331,36 @@ async function isLinkedWorktree(root: string): Promise<boolean> {
2265
2331
  return !!gitDir && !!common && path.resolve(gitDir) !== path.resolve(common);
2266
2332
  }
2267
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
+
2268
2364
  async function currentBranch(root: string): Promise<string> {
2269
2365
  const r = await sh("git branch --show-current", root);
2270
2366
  return r.ok ? r.out.split("\n")[0] : "";
@@ -2518,7 +2614,7 @@ export default function devFlow(pi: ExtensionAPI) {
2518
2614
  const inFlow = !!boundState;
2519
2615
  const fam = inFlow ? await workerFamilyLines(ctx, run?.transcript, run ? BUCKET_FRESH_MS : 0) : null;
2520
2616
  // the picker's rows when we have them; the ledger when the host gave us no file to be a parent of
2521
- const familyLines = fam ?? (boundState ? ledgerFamilyLines(path.join(featDir(ctx.cwd, boundState.slug), "stage-sessions", TRANSCRIPTS_FILE), run?.transcript) : null);
2617
+ const familyLines = fam ?? (boundState ? ledgerFamilyLines(path.join(featDir(ctx.cwd, boundState.slug), STAGE_SESSIONS_DIR, TRANSCRIPTS_FILE), run?.transcript) : null);
2522
2618
  const familySection = inFlow ? [familyHeading({ live: !!run, ledger: fam === null && !!familyLines?.length }), ...(familyLines && familyLines.length ? familyLines : ["(none yet)"])] : [];
2523
2619
  if (!run) {
2524
2620
  return { content: [{ type: "text", text: ["no stage worker is running in this session", ...familySection].join("\n") }], details: { running: false, ...(inFlow ? { workers: workerFamilyCount(familyLines) } : {}) } };
@@ -2568,7 +2664,8 @@ export default function devFlow(pi: ExtensionAPI) {
2568
2664
  stageRuns.set(key, run);
2569
2665
  const cfg = loadProject(dfDir(ctx.cwd)).cfg;
2570
2666
  const logFile = path.join(featDir(ctx.cwd, st.slug), "stage-live.log");
2571
- const transcriptLog = path.join(featDir(ctx.cwd, st.slug), "stage-sessions", TRANSCRIPTS_FILE);
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);
2572
2669
  // read once, used twice: the worker's header links to this file and lands in this bucket,
2573
2670
  // and the reflect brief names this session's own transcript to the reviewer
2574
2671
  const lineage = lineageOf(ctx);
@@ -2714,12 +2811,20 @@ export default function devFlow(pi: ExtensionAPI) {
2714
2811
  // the outcome goes INTO the final name — a picker row like `✓ 🔍 #3 · PASS · stamp attack` or
2715
2812
  // `✓ 🔨 #2 · 3 commits · wire ops` answers "how did it end?" without opening the session
2716
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
+ }
2717
2826
  if (clean) {
2718
- if (op === "run" && headBefore.ok) {
2719
- const c = await sh(`git rev-list --count ${sq(headBefore.out)}..HEAD`, work);
2720
- const n = c.ok ? c.out.trim() : "0";
2721
- if (n !== "0") outcome = `${n} commit${n === "1" ? "" : "s"}`;
2722
- }
2827
+ if (runCommits > 0) outcome = `${runCommits} commit${runCommits === 1 ? "" : "s"}`;
2723
2828
  if (verify?.verdict) outcome = moved ? "verdict VOID" : verify.verdict.toUpperCase();
2724
2829
  if (findings && !findings.missing) outcome = `${findings.playbook.length + findings.plugin.length + findings.other.length} findings`;
2725
2830
  } else {
@@ -2731,7 +2836,7 @@ export default function devFlow(pi: ExtensionAPI) {
2731
2836
  let snapshot: string | null = null;
2732
2837
  const dirty = await sh("git status --porcelain", work);
2733
2838
  if (dirty.ok && dirty.out.trim()) {
2734
- const snapDir = path.join(featDir(ctx.cwd, st.slug), "stage-sessions");
2839
+ const snapDir = path.join(featDir(ctx.cwd, st.slug), STAGE_SESSIONS_DIR);
2735
2840
  mkdirSync(snapDir, { recursive: true });
2736
2841
  const stamp = Date.now();
2737
2842
  const diffFile = path.join(snapDir, `${op}-${stamp}.diff`);
@@ -2914,7 +3019,11 @@ export default function devFlow(pi: ExtensionAPI) {
2914
3019
  // an uninitiated folder hears nothing from dev-flow at all — flow init is the opt-in that arms
2915
3020
  // the guards, the no-playbook bash-timeout default included
2916
3021
  if (noDf) return undefined;
2917
- const cfg = loadProject(dfDir(ctx.cwd)).cfg;
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;
2918
3027
  const mustStateTimeout = shellCmd !== "" && explicitTimeout === undefined && cfg.bashTimeout === "require";
2919
3028
  // for bash this verdict waits behind the operator's own deny/confirm rules further down;
2920
3029
  // powershell meets no project rules at all, so it is answered here
@@ -2923,8 +3032,8 @@ export default function devFlow(pi: ExtensionAPI) {
2923
3032
 
2924
3033
  if (isToolCallEventType("edit", event) || isToolCallEventType("write", event)) {
2925
3034
  const abs = path.resolve(ctx.cwd, String(event.input.path ?? ""));
2926
- const feats = featureRefs(ctx.cwd);
2927
- const bound = boundFeature(ctx.cwd, key);
3035
+ const feats = featureRefs(guardRoot);
3036
+ const bound = boundFeature(guardRoot, key);
2928
3037
  // operator safety rules from project.md run first — as in the bash guard, the operator's deny outranks flow discipline
2929
3038
  const pv = guardPath(abs, ctx.cwd, cfg.guard);
2930
3039
  if (pv.block) return { block: true, reason: pv.block };
@@ -2932,14 +3041,20 @@ export default function devFlow(pi: ExtensionAPI) {
2932
3041
  const why = await askOperator(ctx, `Editing ${path.relative(ctx.cwd, abs) || abs}`, pv.confirm);
2933
3042
  if (why) return { block: true, reason: why };
2934
3043
  }
2935
- const reason = writeGuard({ abs, dfDir: dfDir(ctx.cwd), features: feats, boundSlug: bound?.slug ?? null, repoRoot: ctx.cwd });
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?.()) });
2936
3050
  if (reason) return { block: true, reason };
2937
3051
  // Editing a worktree invalidates that feature's tier-1 checks and tier-2 confirmation until they rerun.
2938
3052
  const owner = feats.find((f) => f.worktreeAbs && abs.startsWith(f.worktreeAbs + path.sep));
2939
3053
  if (owner && (owner.state.stage === "implement" || owner.state.stage === "pre-release") && (Object.keys(owner.state.checks).length || owner.state.confirmations?.implement)) {
2940
3054
  owner.state.checks = {};
2941
3055
  delete owner.state.confirmations?.implement;
2942
- writeState(ctx.cwd, owner.state);
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);
2943
3058
  }
2944
3059
  return undefined;
2945
3060
  }
@@ -2977,7 +3092,7 @@ export default function devFlow(pi: ExtensionAPI) {
2977
3092
  }
2978
3093
  const inv = gitInvocation(command);
2979
3094
  if (!inv.subs.length) return undefined; // git is not invoked as a command — nothing to guard
2980
- const bound = boundFeature(ctx.cwd, key);
3095
+ const bound = boundFeature(guardRoot, key);
2981
3096
  // judge EACH git segment by the branch of the directory it runs in — a chain may cd across
2982
3097
  // directories; one last-cd-wins verdict misattributed mixed-dir chains and blocked legit worktree commits
2983
3098
  const branchCache = new Map<string, string>();
@@ -2991,7 +3106,7 @@ export default function devFlow(pi: ExtensionAPI) {
2991
3106
  }
2992
3107
  return branchCache.get(at)!;
2993
3108
  };
2994
- const worktrees = featureRefs(ctx.cwd).map((f) => f.worktreeAbs).filter((w): w is string => !!w);
3109
+ const worktrees = featureRefs(guardRoot).map((f) => f.worktreeAbs).filter((w): w is string => !!w);
2995
3110
  for (const g of inv.gitSegs) {
2996
3111
  const gitDir = g.dir ? path.resolve(ctx.cwd, g.dir) : ctx.cwd;
2997
3112
  const seg = gitInvocation(g.seg); // parsed once per segment — this runs on every bash call of every session
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dev-flow",
3
- "version": "0.71.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": [
@@ -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
@@ -9,10 +9,14 @@ 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.** Non-trivial implement is **delegated by default**: run it in
13
- a disposable worker session with `flow_stage` (`stage: "implement"`) — this session keeps its
14
- context for the gates and the checkpoint; stay inline only for a tail you can finish in a
15
- handful of file edits. The
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
@@ -22,11 +26,10 @@ 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 close the remaining
26
- loose ends yourself. A missing report block or a crashed worker means the
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. Delegate a real slice, not the tail: do not
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 — yours or
61
- a delegated fixer's — drops it like a tier-1 record, so fix → a **fresh** verify worker;
62
- a verdict from an interrupted or tree-touching worker never stamps (a reviewer that edits
63
- voids its own report). FAIL means: fix (or delegate), then rerun a fresh one — the report is
64
- a handoff, the gate's own rerun is the proof.
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 = iterate and re-verify; that loop is
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 and claim.json — or a bare name when the command
889
- * also touches `.dev-flow` (that is how `cd .dev-flow/<slug> && mv state.json …` reaches it).
890
- * The claim is the live-session lock: deleting it is as much theft as forging a stage. */
891
- const STATE_PATH = /(^|[\s'"\/])(?:state|claim)\.json$/;
892
- const STATE_PATH_ABS = /\.dev-flow\/[\w./-]*(?:state|claim)\.json$/;
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
@@ -1846,7 +1884,10 @@ export function nextHint(state: FlowState, cfg: Config): string {
1846
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`;
1847
1885
  case "implement":
1848
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`;
1849
- 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)`;
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)`;
1850
1891
  case "pre-release":
1851
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`;
1852
1893
  case "release":
@@ -2309,6 +2350,79 @@ export function parseWorkerTranscripts(text: string): { at: string; op: string;
2309
2350
  return out;
2310
2351
  }
2311
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
+
2312
2426
  /** How many live lines the card and `op: "status"` show: enough to see what the worker is doing,
2313
2427
  * bounded so a long stage never spends the context the delegation just saved (R6). */
2314
2428
  export const LIVE_TAIL_ITEMS = 8;