pi-dev-flow 0.78.0 → 0.80.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 +24 -0
- package/docs/gates.md +3 -3
- package/docs/guardrails.md +1 -1
- package/docs/playbook.md +1 -1
- package/extensions/dev-flow.ts +189 -28
- package/package.json +1 -1
- package/skills/dev-flow/references/finish.md +5 -3
- package/skills/dev-flow/references/implement.md +10 -1
- package/skills/dev-flow/references/reflect.md +7 -4
- package/src/core.ts +206 -14
- package/src/projectmd.ts +11 -4
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,30 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
|
|
|
4
4
|
|
|
5
5
|
## [Unreleased]
|
|
6
6
|
|
|
7
|
+
## [0.80.0] - 2026-11-03
|
|
8
|
+
|
|
9
|
+
**A reflection that runs out of time still hands back its findings; release-only flows pass verify.**
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
- **A reflection cut at its budget no longer loses its findings.** `flow_stage` workers are steered at 75% of their budget to wrap up and write the REPORT (the gh#142 grace, lost in the 0.73 slim-down, is back for every op). A worker still cut at the budget gets one tool-less prompt for its REPORT, and the result comes back marked partial instead of "aborted".
|
|
13
|
+
- **The reflect worker reads instead of digging.** Before it starts, the tool writes a line-tagged digest of the driver and every worker transcript into `.dev-flow/<slug>/tmp/reflect/`: operator messages, flow calls and answers, tool errors, NEEDS-OPERATOR, repeated commands. A 2.5 MB driver transcript digests to about 25 KB. The upstream issue list (all states) is prefetched into the brief, the brief states the budget, and the worker is told it reviews the session, not the product.
|
|
14
|
+
- **Release refuses leftover merge-conflict markers** (#164). A `<<<<<<<` / `|||||||` / `>>>>>>>` line the branch adds is named with `file:line`; `--no-marker-check` is the operator's escape.
|
|
15
|
+
- **A review worker on a `--docs` / `--patch` flow is no longer sent after a missing plan.md** (#167). The brief says the flow has no plan file and to judge the work against the task.
|
|
16
|
+
- **`--docs --no-version` no longer owes a changelog line** (#163), and the pre-release hint for a docs flow says unversioned is the usual path instead of "bump version" (#166).
|
|
17
|
+
|
|
18
|
+
### Added
|
|
19
|
+
- `flow reflect done <n> ["<what>"]` checks a fixed item off, so doctor stops re-reporting it (#165).
|
|
20
|
+
- `- [ ] (versioned) item` in the playbook: a checklist item that only applies when the flow ships a version. It stands down on `--no-version`, so release-done stops listing tag/image proofs an unversioned flow can never satisfy (#166).
|
|
21
|
+
- **Release-only flows** (#161): on a versioned project, `flow verify` accepts an empty branch when the default branch has unreleased commits since the newest version tag. The version bump is the pre-release commit, as the playbook says, and the release gate does not count it as a post-verify change. With nothing unreleased, verify says there is nothing to release.
|
|
22
|
+
- `flow release` names commits made after the operator's Verified? (verify now stamps the HEAD it was given over). It warns and never refuses (#162).
|
|
23
|
+
|
|
24
|
+
## [0.79.0] - 2026-11-03
|
|
25
|
+
|
|
26
|
+
**Scratch files live in the feature folder and go away at finish.**
|
|
27
|
+
|
|
28
|
+
### Changed
|
|
29
|
+
- **Scratch files now go in the feature folder, not `/tmp`.** A bound session's bash calls, and every project command a gate runs (`flow test`, checks, build, dev, seed, health), now run with `TMPDIR` set to `.dev-flow/<slug>/tmp/`. Throwaway scripts, `mktemp` output and test fixtures created with `os.tmpdir()` (the smoke suite alone makes about 40 per run) land there instead of piling up in the OS temp dir. `flow finish` removes the folder with the feature, and `flow abort` drops it when it unbinds. The prefix goes on after the guards have judged the command, so no guard ever sees it. Unbound sessions are unchanged.
|
|
30
|
+
|
|
7
31
|
## [0.78.0] - 2026-11-03
|
|
8
32
|
|
|
9
33
|
**`flow init` asks better questions and writes your answers itself.**
|
package/docs/gates.md
CHANGED
|
@@ -15,11 +15,11 @@ 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 | 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
|
-
| `release [--yolo|--no-version|--no-fold-check]` | pre-release → release | checks re-greened after the prep edits; `release.preflight` (when set) passes in the worktree — the build the tag will trigger, proven before anything ships; **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) |
|
|
18
|
+
| `verify [--yolo]` | implement → pre-release | 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 — except a **release-only flow** (#161): on a versioned project an empty branch over unreleased commits on the default branch (since the newest local version tag, or all of them before the first release) passes, the line says `release-only flow: N unreleased commit(s)`, and the version bump is the pre-release commit; with nothing unreleased the refusal says there is nothing to release; 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
|
+
| `release [--yolo|--no-version|--no-fold-check|--no-marker-check]` | pre-release → release | checks re-greened after the prep edits; `release.preflight` (when set) passes in the worktree — the build the tag will trigger, proven before anything ships; **the branch adds no merge-conflict marker lines** vs its merge base (#164: a hand-resolved merge that kept a `<<<<<<<`/`>>>>>>>` line is refused with `file:line`; `--no-marker-check` on the operator's word when the lines are meant); **commits after Verified?** are named in the Release? question and the approved line (#162: the operator's word covers the HEAD verify stamped — a warning, never a refusal); **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`** (a `--docs` flow is exempt — #163: a playbook/docs change owes no user-facing entry; one it writes is welcome, not proven) (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` |
|
|
22
|
-
| `reflect ["<note>"|list|tidy|move <n> --playbook|--code]` | — | `reflect "<note>"` queues a suggestion in **this project's** `reflections.md` (never gates; gate flags such as `--confirmed` are ignored, they never become part of the note). `--playbook` (alias `--docs`) files it under `## playbook` — the fix lives only in `project.md`, a docs flow implements it; `--code` files it under `## code` — the fix touches project code, a patch flow implements it. `--plugin` **never writes**: dev-flow feedback is filed upstream, so it prints the recipe — `gh issue list --repo <dev-flow repo> --state all --search …` first, then `gh issue create` with a body ending `— reflection from <slug> <date>` (in the dev-flow repo itself plugin is code → `## code`). With no flag the wording guesses (plugin-shaped → the recipe; otherwise `## playbook`) and the echo prints why. `reflect list` numbers the open items with their section; `reflect move <n> --playbook|--code` re-files one; a legacy `## plugin` row is flagged by list and doctor (file it upstream, check it off `— filed: gh#NNN`). `reflect tidy` drops the closed (`- [x]`) items — the preamble and open items stay verbatim and a `## section` heading left empty goes with its items. **Nudges are timed, not constant**: `⚑ fix the open reflections now?` prints when an item recurred this session, is ≥ 14 days old, ≥ 3 playbook items wait, or a code item waits while between flows — at finish, in an unbound session and in doctor, never mid-feature; `↻ N closed reflection(s)` prints at ≥ 5 closed, closed ≥ open (≥ 3), or a closed item ≥ 30 days old. Bare `reflect` prints the **session-reflection protocol** (from the `/flow reflect` bar it additionally wakes the model): bound to a flow, delegate the review to `flow_stage` op `reflect`; unbound, review inline; re-check every open item against the playbook and **newer dev-flow versions** (`npm view pi-dev-flow version`; the operator performs updates); show the operator a numbered list with a fold/drop recommendation per finding and stop; fold docs/code → `reflect --playbook|--code`, fold plugin → the upstream issue, drop → nothing recorded |
|
|
22
|
+
| `reflect ["<note>"|list|tidy|move <n> --playbook|--code|done <n> ["<what>"]]` | — | `reflect "<note>"` queues a suggestion in **this project's** `reflections.md` (never gates; gate flags such as `--confirmed` are ignored, they never become part of the note). `--playbook` (alias `--docs`) files it under `## playbook` — the fix lives only in `project.md`, a docs flow implements it; `--code` files it under `## code` — the fix touches project code, a patch flow implements it. `--plugin` **never writes**: dev-flow feedback is filed upstream, so it prints the recipe — `gh issue list --repo <dev-flow repo> --state all --search …` first, then `gh issue create` with a body ending `— reflection from <slug> <date>` (in the dev-flow repo itself plugin is code → `## code`). With no flag the wording guesses (plugin-shaped → the recipe; otherwise `## playbook`) and the echo prints why. `reflect list` numbers the open items with their section; `reflect move <n> --playbook|--code` re-files one; `reflect done <n> ["<what>"]` checks a fixed one off (`— fixed: <date> <slug> — <what>`) so doctor stops re-reporting it; a legacy `## plugin` row is flagged by list and doctor (file it upstream, check it off `— filed: gh#NNN`). `reflect tidy` drops the closed (`- [x]`) items — the preamble and open items stay verbatim and a `## section` heading left empty goes with its items. **Nudges are timed, not constant**: `⚑ fix the open reflections now?` prints when an item recurred this session, is ≥ 14 days old, ≥ 3 playbook items wait, or a code item waits while between flows — at finish, in an unbound session and in doctor, never mid-feature; `↻ N closed reflection(s)` prints at ≥ 5 closed, closed ≥ open (≥ 3), or a closed item ≥ 30 days old. Bare `reflect` prints the **session-reflection protocol** (from the `/flow reflect` bar it additionally wakes the model): bound to a flow, delegate the review to `flow_stage` op `reflect`; unbound, review inline; re-check every open item against the playbook and **newer dev-flow versions** (`npm view pi-dev-flow version`; the operator performs updates); show the operator a numbered list with a fold/drop recommendation per finding and stop; fold docs/code → `reflect --playbook|--code`, fold plugin → the upstream issue, drop → nothing recorded |
|
|
23
23
|
| `roadmap [add "<feature>" \| pick <n> <slug> \| done <n> \| tidy]` | — | manages `.dev-flow/roadmap.md`, the gitignored backlog of future features (`- [ ]` checklist): bare prints the numbered open items, `add` appends one, `pick <n> <slug>` stamps open item n with `(slug)` so `flow start <slug>` can take it — **`finish` checks the stamped item off when that feature ships**; `done <n>` checks off by hand (items shipped outside a flow), `tidy` drops the checked lines. Never gates; the open count is surfaced in `status` and session context |
|
|
24
24
|
| `doctor ["<issue note>"]` | — | read-only findings: playbook drift, dead commands/scripts, untracked playbook, ghost feature dirs, orphan worktrees/branches — the state of an **aborted** feature is never a finding (its worktree cleanup is by design — gh#138) — **plus a review of every open reflection, each routed to the flow that should fix it** (playbook item → docs flow; plugin item → upstream issue, or a patch/normal flow inside the dev-flow repo) — every item is labelled from the `## section` it is filed under (the file is the record, so the table cannot disagree with it) and items sitting outside both sections are named rather than silently bucketed. It writes nothing and asks nothing, safe for agents and CI at any stage; the agent investigates, you confirm, the routed flow implements. `doctor "<note>"` prints an investigation brief and a fix route for a fresh observation, including the section it would be filed under and why |
|
|
25
25
|
| `status [slug]` / `abort [slug]` | — | — |
|
package/docs/guardrails.md
CHANGED
|
@@ -6,7 +6,7 @@ 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. For a bound feature that scratch lives in the feature itself: every bash call the guards let through, and every project command a gate runs (test, checks, build, dev, seed, health), gets `TMPDIR=.dev-flow/<slug>/tmp/`, so `mktemp`, `os.tmpdir()` and test-suite fixtures land there and `flow finish` (or `flow abort`) removes them. Unbound sessions keep the OS temp dir.
|
|
10
10
|
- **Shipping waits for `flow release`**: while a bound feature is at `plan`, `implement` or `pre-release`, cutting or pushing a tag (`git tag <name>`, `git push --tags`, `refs/tags/…`), merging its PR (`gh pr merge`, `glab mr merge`) and creating a forge release (`gh|glab release create`) are refused with "run flow release first". Shipping by hand first left `flow release` unable to record the release ("already tagged") and the flow unable to close. Reads (`git tag -l`, `gh pr view`) and opening the PR at pre-release are unaffected.
|
|
11
11
|
- **A feature worktree keeps its branch**: creating a branch inside a feature worktree (`git checkout -b`, `git switch -c`) is refused. An unrelated fix is its own flow (`flow start <slug> --patch --confirmed`), not a side branch in someone's worktree. A session whose cwd is a feature worktree is judged by the **main checkout's** `.dev-flow/` state, which is where the features live.
|
|
12
12
|
- **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.
|
package/docs/playbook.md
CHANGED
|
@@ -52,7 +52,7 @@ executable checks and hard safety rules:
|
|
|
52
52
|
|---|---|---|
|
|
53
53
|
| 1 — executable | ` ```flow` (`key = value`) config blocks; ` ```flow-check <name>` command blocks | gates run every check, record pass/fail against a worktree fingerprint, a changed tree makes them stale — hard |
|
|
54
54
|
| 1 — guard | ` ```flow-guard ` (`deny`/`confirm`/`protect`/`forbid`) rules in `## global` | enforced on every bash command and every edit/write path, at every stage — hard block or operator confirmation |
|
|
55
|
-
| 2 — checklist | `- [ ] item` lines (`- [ ] (ui) item` = only for `--ui` features) | gate confirms cover them as a set (hashed: changing the items asks again); `(ui)` items never appear for non-UI features |
|
|
55
|
+
| 2 — checklist | `- [ ] item` lines (`- [ ] (ui) item` = only for `--ui` features; `- [ ] (versioned) item` = only when the flow ships a version — it stands down on `--no-version`) | gate confirms cover them as a set (hashed: changing the items asks again); `(ui)` items never appear for non-UI features, `(versioned)` items never for an unversioned flow (a deploy proof of the tagged image, say) |
|
|
56
56
|
| 3 — prose | any other text | injected to the agent when its stage begins — advisory |
|
|
57
57
|
|
|
58
58
|
Example `## implement` section:
|
package/extensions/dev-flow.ts
CHANGED
|
@@ -25,7 +25,7 @@ import path from "node:path";
|
|
|
25
25
|
import { promisify } from "node:util";
|
|
26
26
|
import { Type } from "@earendil-works/pi-ai";
|
|
27
27
|
import { compact, createAgentSession, DefaultResourceLoader, defineTool, getAgentDir, isToolCallEventType, SessionManager, SettingsManager, type AgentSession, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
28
|
-
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
28
|
+
import type { ExtensionAPI, ToolCallEvent, ToolCallEventResult } from "@earendil-works/pi-coding-agent";
|
|
29
29
|
import {
|
|
30
30
|
ALLOW_REWRITE,
|
|
31
31
|
approveGate,
|
|
@@ -72,6 +72,7 @@ import {
|
|
|
72
72
|
guessReflectSections,
|
|
73
73
|
reflectItems,
|
|
74
74
|
reflectMove,
|
|
75
|
+
reflectDone,
|
|
75
76
|
reflectProtocol,
|
|
76
77
|
reflectUnfiledCount,
|
|
77
78
|
reflectLegacyPluginCount,
|
|
@@ -82,6 +83,13 @@ import {
|
|
|
82
83
|
parseReflectReport,
|
|
83
84
|
renderReflectFindings,
|
|
84
85
|
childSessionFiles,
|
|
86
|
+
conflictMarkerLines,
|
|
87
|
+
isReleaseOnly,
|
|
88
|
+
digestTranscript,
|
|
89
|
+
workerSteer,
|
|
90
|
+
WORKER_STEER_AT,
|
|
91
|
+
WORKER_SALVAGE,
|
|
92
|
+
WORKER_SALVAGE_MS,
|
|
85
93
|
WORKER_NUDGE_READONLY,
|
|
86
94
|
type SessionHeaderInfo,
|
|
87
95
|
reflectionLine,
|
|
@@ -114,6 +122,8 @@ import {
|
|
|
114
122
|
statusJson,
|
|
115
123
|
subst,
|
|
116
124
|
sq,
|
|
125
|
+
featureTmpDir,
|
|
126
|
+
withTmpDir,
|
|
117
127
|
tagNotesCommand,
|
|
118
128
|
validSlug,
|
|
119
129
|
verifyGate,
|
|
@@ -228,9 +238,9 @@ const now = () => new Date().toISOString();
|
|
|
228
238
|
|
|
229
239
|
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
230
240
|
|
|
231
|
-
async function sh(command: string, cwd: string, timeoutMs = 15 * 60_000): Promise<{ ok: boolean; out: string }> {
|
|
241
|
+
async function sh(command: string, cwd: string, timeoutMs = 15 * 60_000, env?: Record<string, string>): Promise<{ ok: boolean; out: string }> {
|
|
232
242
|
try {
|
|
233
|
-
const { stdout, stderr } = await execAsync(command, { cwd, timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024 });
|
|
243
|
+
const { stdout, stderr } = await execAsync(command, { cwd, timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024, ...(env ? { env: { ...process.env, ...env } } : {}) });
|
|
234
244
|
return { ok: true, out: `${stdout}\n${stderr}`.trim() };
|
|
235
245
|
} catch (e) {
|
|
236
246
|
const err = e as { stdout?: string; stderr?: string; message?: string };
|
|
@@ -345,12 +355,12 @@ async function writePlaybookMergePolicy(root: string, style: string): Promise<{
|
|
|
345
355
|
* container start can never pass a single shot, and hand-writing a poll loop into every playbook was
|
|
346
356
|
* the workaround; the gate waits and says how long it tried. Attempts/schedule: core.healthRetry.
|
|
347
357
|
*/
|
|
348
|
-
async function runHealthProbe(cmd: string, cwd: string, waitSec: number): Promise<{ ok: boolean; out: string; attempts: number }> {
|
|
358
|
+
async function runHealthProbe(cmd: string, cwd: string, waitSec: number, env?: Record<string, string>): Promise<{ ok: boolean; out: string; attempts: number }> {
|
|
349
359
|
const { attempts, delayMs } = healthRetry(waitSec);
|
|
350
360
|
const deadline = Date.now() + waitSec * 1000; // the budget is wall time: a slow probe must not multiply it by its own duration
|
|
351
361
|
let res = { ok: false, out: "" };
|
|
352
362
|
for (let i = 1; ; i++) {
|
|
353
|
-
res = await sh(cmd, cwd);
|
|
363
|
+
res = await sh(cmd, cwd, undefined, env);
|
|
354
364
|
if (res.ok || i >= attempts || Date.now() >= deadline) return { ...res, attempts: i };
|
|
355
365
|
await sleep(delayMs);
|
|
356
366
|
}
|
|
@@ -367,7 +377,7 @@ async function releaseTags(root: string): Promise<string[] | null> {
|
|
|
367
377
|
}
|
|
368
378
|
|
|
369
379
|
const GATE_HELP =
|
|
370
|
-
"help [--json] | init [--force|--draft|--write <text>|--write-file <path>|--answers key=value…|--answers-file <path>] [--confirmed] [--track] | reflect [<note>|list|tidy|move <n> --playbook|--code] | roadmap [add <text>|pick <n> <slug>|done <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui|--patch|--docs --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | approve [--yolo] | verify [--yolo] | release [--yolo|--no-version|--no-fold-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [slug] | abort [slug] | version [--check-upstream] — state gates take [slug] and --confirmed (the operator already answered in chat); without it they ask in a dialog, or refuse with NEEDS-OPERATOR when no UI is present — --ui/--patch/--docs and --merge=<style> on start are operator-granted (--confirmed); start refuses until the playbook has a merge policy and writes the answer into project.md — --yolo (with --confirmed) answers that checkpoint and pre-confirms every later one; checks and guardrails stay — release --no-version ships merge + changelog only (no bump, tag or forge release); --no-fold-check skips the changelog fold line proofs on the operator's word — release names a session running an older dev-flow build than the disk ships and asks update (/reload) or proceed — recorded, never a block — reflect <note> queues a project suggestion in reflections.md (--playbook = docs-flow fix, --code = patch-flow fix); --plugin never writes — dev-flow feedback goes upstream and it prints the GitHub issue recipe; bare reflect prints the session-reflection protocol (bound: run flow_stage op reflect); list numbers open items, move <n> re-files one, tidy drops closed ones — roadmap manages .dev-flow/roadmap.md: pick <n> <slug> stamps an item for flow start, finish checks it off — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — version prints the build the disk ships and any other dev-flow copies in this process (--check-upstream asks the registry)";
|
|
380
|
+
"help [--json] | init [--force|--draft|--write <text>|--write-file <path>|--answers key=value…|--answers-file <path>] [--confirmed] [--track] | reflect [<note>|list|tidy|move <n> --playbook|--code|done <n> [<what>]] | roadmap [add <text>|pick <n> <slug>|done <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui|--patch|--docs --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | approve [--yolo] | verify [--yolo] | release [--yolo|--no-version|--no-fold-check|--no-marker-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [slug] | abort [slug] | version [--check-upstream] — state gates take [slug] and --confirmed (the operator already answered in chat); without it they ask in a dialog, or refuse with NEEDS-OPERATOR when no UI is present — --ui/--patch/--docs and --merge=<style> on start are operator-granted (--confirmed); start refuses until the playbook has a merge policy and writes the answer into project.md — --yolo (with --confirmed) answers that checkpoint and pre-confirms every later one; checks and guardrails stay — release --no-version ships merge + changelog only (no bump, tag or forge release); --no-fold-check skips the changelog fold line proofs on the operator's word; --no-marker-check lets a branch add conflict-marker-shaped lines on purpose — release names a session running an older dev-flow build than the disk ships and asks update (/reload) or proceed — recorded, never a block — reflect <note> queues a project suggestion in reflections.md (--playbook = docs-flow fix, --code = patch-flow fix); --plugin never writes — dev-flow feedback goes upstream and it prints the GitHub issue recipe; bare reflect prints the session-reflection protocol (bound: run flow_stage op reflect); list numbers open items, move <n> re-files one, done <n> checks a fixed one off, tidy drops closed ones — roadmap manages .dev-flow/roadmap.md: pick <n> <slug> stamps an item for flow start, finish checks it off — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — version prints the build the disk ships and any other dev-flow copies in this process (--check-upstream asks the registry)";
|
|
371
381
|
const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
|
|
372
382
|
const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
|
|
373
383
|
const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
|
|
@@ -603,6 +613,14 @@ function gateCwd(root: string, state: FlowState): string {
|
|
|
603
613
|
return wt && existsSync(wt) ? wt : root;
|
|
604
614
|
}
|
|
605
615
|
|
|
616
|
+
/** TMPDIR for the project commands a gate runs: the feature's own scratch dir, removed at finish —
|
|
617
|
+
* a test suite's mkdtemp fixtures no longer pile up in the OS temp dir. */
|
|
618
|
+
function featureEnv(root: string, state: FlowState): Record<string, string> {
|
|
619
|
+
const dir = featureTmpDir(dfDir(root), state.slug);
|
|
620
|
+
mkdirSync(dir, { recursive: true });
|
|
621
|
+
return { TMPDIR: dir };
|
|
622
|
+
}
|
|
623
|
+
|
|
606
624
|
/** Tier-1 checks the gate still has to see green. Entering a stage — and every edit of the worktree —
|
|
607
625
|
* clears the records, so "run flow check first" cost three round trips to say what one could (#84).
|
|
608
626
|
* `health` is left to the post-deploy probe when there is a deploy to prove: probing twice only waits twice. */
|
|
@@ -618,7 +636,7 @@ async function runChecks(root: string, state: FlowState, cfg: Config, checks: St
|
|
|
618
636
|
const ran: string[] = [];
|
|
619
637
|
for (const c of checks) {
|
|
620
638
|
// health is the same probe `flow health` runs: seeded first, retried within healthWait
|
|
621
|
-
const res = c.name === "health" ? await seededProbe(root, state, cfg, c.cmd) : await sh(c.cmd, gateCwd(root, state));
|
|
639
|
+
const res = c.name === "health" ? await seededProbe(root, state, cfg, c.cmd) : await sh(c.cmd, gateCwd(root, state), undefined, featureEnv(root, state));
|
|
622
640
|
if ("seedFail" in res) {
|
|
623
641
|
lines.push(res.seedFail.text);
|
|
624
642
|
failed = true;
|
|
@@ -643,7 +661,7 @@ const healthRerunsAfterDeploy = (cfg: Config) => !!cfg.commands.dev && !!healthP
|
|
|
643
661
|
* deploy probe both do this). Returns an error result on failure, null when seeded or not configured. */
|
|
644
662
|
async function seedStep(root: string, state: FlowState, cfg: Config): Promise<{ text: string; isError: true } | null> {
|
|
645
663
|
if (!cfg.commands.seedData) return null;
|
|
646
|
-
const seed = await sh(cfg.commands.seedData, gateCwd(root, state));
|
|
664
|
+
const seed = await sh(cfg.commands.seedData, gateCwd(root, state), undefined, featureEnv(root, state));
|
|
647
665
|
state.checks.seedData = { ok: seed.ok, at: now() };
|
|
648
666
|
writeState(root, state);
|
|
649
667
|
return seed.ok ? null : { text: `seedData FAILED (${cfg.commands.seedData}):\n${tail(seed.out)}`, isError: true };
|
|
@@ -654,7 +672,7 @@ type HealthRun = { ok: boolean; out: string; attempts: number } | { seedFail: Ru
|
|
|
654
672
|
/** Seed (when configured), then run the health probe within the playbook's wait budget. */
|
|
655
673
|
async function seededProbe(root: string, state: FlowState, cfg: Config, probe: string): Promise<HealthRun> {
|
|
656
674
|
const seedFail = await seedStep(root, state, cfg);
|
|
657
|
-
return seedFail ? { seedFail } : runHealthProbe(probe, gateCwd(root, state), cfg.healthWait);
|
|
675
|
+
return seedFail ? { seedFail } : runHealthProbe(probe, gateCwd(root, state), cfg.healthWait, featureEnv(root, state));
|
|
658
676
|
}
|
|
659
677
|
|
|
660
678
|
/** seededProbe, recorded and stamped as the `health` check — `flow health` and both verify probes. */
|
|
@@ -706,10 +724,23 @@ async function branchState(cwd: string, defaultBranch: string): Promise<BranchSt
|
|
|
706
724
|
};
|
|
707
725
|
}
|
|
708
726
|
|
|
727
|
+
/** Commits HEAD carries since the newest local version tag (all of them before the first release) —
|
|
728
|
+
* local refs only, so the probe stays offline-safe. HEAD is the default branch's tip on an empty branch. */
|
|
729
|
+
async function unreleasedOnMain(cwd: string, pattern: string): Promise<{ count: number | null; since: string | null }> {
|
|
730
|
+
const tags = await sh("git tag --list", cwd);
|
|
731
|
+
const newest = tags.ok ? newestTaggedVersion(pattern, tags.out.split("\n").map((t) => t.trim()).filter(Boolean)) : null;
|
|
732
|
+
const since = newest ? pattern.replace("{version}", newest) : null;
|
|
733
|
+
const r = await sh(since ? `git rev-list --count ${sq(since)}..HEAD` : "git rev-list --count HEAD", cwd);
|
|
734
|
+
const n = Number.parseInt(r.out.trim(), 10);
|
|
735
|
+
return { count: r.ok && Number.isFinite(n) ? n : null, since };
|
|
736
|
+
}
|
|
737
|
+
|
|
709
738
|
function describeBranchState(b: BranchState, defaultBranch: string): string {
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
739
|
+
if (b.commitsAhead === null) return `commits: unknown (no merge base with ${defaultBranch} — the commit proof is skipped)`;
|
|
740
|
+
const line = `commits: ${b.commitsAhead} ahead of ${defaultBranch}, ${b.uncommitted} uncommitted path(s)`;
|
|
741
|
+
return b.commitsAhead === 0 && (b.unreleased?.count ?? 0) > 0
|
|
742
|
+
? `${line} — release-only flow: ${b.unreleased!.count} unreleased commit(s) on ${defaultBranch}${b.unreleased!.since ? ` since ${b.unreleased!.since}` : " (nothing tagged yet)"}; verify proves that tree, the version bump is the pre-release commit`
|
|
743
|
+
: line;
|
|
713
744
|
}
|
|
714
745
|
|
|
715
746
|
// ---------------------------------------------------------------- gate runner
|
|
@@ -931,6 +962,21 @@ function reflectMoveNote(root: string, args: string[], forced: ReflectTarget | n
|
|
|
931
962
|
return { text: twin ? `reflect: item ${n} was already recorded under ## ${section} — the duplicate is gone (${note})` : `reflect: item ${n} re-filed under ## ${section} — ${note}` };
|
|
932
963
|
}
|
|
933
964
|
|
|
965
|
+
/** `flow reflect done <n> [what fixed it]` — check a folded/fixed item off, so doctor stops re-reporting it (#165). */
|
|
966
|
+
function reflectDoneNote(root: string, sess: Session, args: string[]): RunResult {
|
|
967
|
+
const text = readReflectionsText(root);
|
|
968
|
+
const items = reflectItems(text);
|
|
969
|
+
const n = Number(args[0]);
|
|
970
|
+
if (!Number.isInteger(n) || n < 1 || n > items.length)
|
|
971
|
+
return { text: items.length ? `done: open item 1–${items.length} required — flow reflect list numbers them` : "done: nothing open in reflections.md", isError: true };
|
|
972
|
+
const stamp = [now().slice(0, 10), sess.slug].filter(Boolean).join(" ");
|
|
973
|
+
const what = args.slice(1).join(" ").trim();
|
|
974
|
+
const next = reflectDone(text, n, what ? `${stamp} — ${what}` : stamp)!;
|
|
975
|
+
writeFileSync(path.join(dfDir(root), "reflections.md"), next);
|
|
976
|
+
const { tidy } = reflectionNudges(next, now().slice(0, 10));
|
|
977
|
+
return { text: `reflect: item ${n} checked off — ${items[n - 1].body}` + (tidy ? `\n${tidy}` : "") };
|
|
978
|
+
}
|
|
979
|
+
|
|
934
980
|
/** `flow reflect tidy` — drop the closed (`- [x]`) items; the `— fixed:` note already recorded the outcome. */
|
|
935
981
|
function reflectTidy(root: string): RunResult {
|
|
936
982
|
const file = path.join(dfDir(root), "reflections.md");
|
|
@@ -1033,6 +1079,7 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
|
|
|
1033
1079
|
if (err) return err;
|
|
1034
1080
|
const items = applicableItems(cfg, state!, "implement");
|
|
1035
1081
|
const branch = await branchState(gateCwd(root, state!), cfg.defaultBranch);
|
|
1082
|
+
if (branch.commitsAhead === 0 && cfg.versioning.file) branch.unreleased = await unreleasedOnMain(gateCwd(root, state!), cfg.versioning.pattern);
|
|
1036
1083
|
const branchLine = describeBranchState(branch, cfg.defaultBranch);
|
|
1037
1084
|
// A green record belongs to the tree it ran against. A worktree change made through bash (sed,
|
|
1038
1085
|
// a formatter, codegen) fires no edit-tool invalidation — the fingerprint is what notices the
|
|
@@ -1055,7 +1102,7 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
|
|
|
1055
1102
|
did.push("docs mode: project commands skipped (build/dev/health)");
|
|
1056
1103
|
} else {
|
|
1057
1104
|
if (cfg.commands.build) {
|
|
1058
|
-
const res = await sh(cfg.commands.build, gateCwd(root, state!));
|
|
1105
|
+
const res = await sh(cfg.commands.build, gateCwd(root, state!), undefined, featureEnv(root, state!));
|
|
1059
1106
|
state!.checks.build = { ok: res.ok, at: now() };
|
|
1060
1107
|
writeState(root, state!);
|
|
1061
1108
|
if (!res.ok) return { text: `build FAILED (${cfg.commands.build}):\n${tail(res.out)}`, isError: true };
|
|
@@ -1064,7 +1111,7 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
|
|
|
1064
1111
|
// deploy to dev before asking — the operator reviews the running dev app, not a promise
|
|
1065
1112
|
const probe = healthProbe(cfg);
|
|
1066
1113
|
if (cfg.commands.dev) {
|
|
1067
|
-
const res = await sh(cfg.commands.dev, gateCwd(root, state!));
|
|
1114
|
+
const res = await sh(cfg.commands.dev, gateCwd(root, state!), undefined, featureEnv(root, state!));
|
|
1068
1115
|
state!.checks.dev = { ok: res.ok, at: now() };
|
|
1069
1116
|
writeState(root, state!);
|
|
1070
1117
|
if (!res.ok) return { text: `dev deploy FAILED (${cfg.commands.dev}):\n${tail(res.out)}`, isError: true };
|
|
@@ -1115,6 +1162,12 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
|
|
|
1115
1162
|
const final = verifyGate(state!, cfg, branch);
|
|
1116
1163
|
if (final.length) return { text: `verify gate FAILED:\n- ${final.join("\n- ")}`, isError: true };
|
|
1117
1164
|
state!.approvals.verify = now();
|
|
1165
|
+
if (isReleaseOnly(cfg, branch)) state!.releaseOnly = true;
|
|
1166
|
+
else delete state!.releaseOnly;
|
|
1167
|
+
// the tree the word was given over (#162) — a git that cannot answer leaves it unset, never a refusal
|
|
1168
|
+
const vHead = await sh("git rev-parse HEAD", gateCwd(root, state!));
|
|
1169
|
+
if (vHead.ok && vHead.out.trim()) state!.verifiedHead = vHead.out.trim();
|
|
1170
|
+
else delete state!.verifiedHead;
|
|
1118
1171
|
state!.stage = "pre-release";
|
|
1119
1172
|
delete state!.pendingAsk;
|
|
1120
1173
|
writeState(root, state!);
|
|
@@ -1125,9 +1178,10 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
|
|
|
1125
1178
|
const { root, ui, sess, cfg, flag, slugArg, takeYoloWord } = o;
|
|
1126
1179
|
const { state, err } = needState(root, sess, slugArg);
|
|
1127
1180
|
if (err) return err;
|
|
1128
|
-
const items = applicableItems(cfg, state!, "pre-release");
|
|
1129
1181
|
// operator's word at Release?: this flow ships without a version bump or tag — recorded only once Release? is answered
|
|
1130
1182
|
const noVersion = flag("no-version") || !!state!.noVersion;
|
|
1183
|
+
// (versioned) items stand down on an unversioned flow — the set confirmed here is the one that applies to it
|
|
1184
|
+
const items = applicableItems(cfg, { ...state!, noVersion }, "pre-release");
|
|
1131
1185
|
// yolo is the operator's word at Release? — pre-confirms Finish?; publishing guardrails stay enforced
|
|
1132
1186
|
const yoloWord = takeYoloWord(state!);
|
|
1133
1187
|
if (yoloWord) return { text: yoloWord, isError: true };
|
|
@@ -1180,7 +1234,11 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
|
|
|
1180
1234
|
}
|
|
1181
1235
|
}
|
|
1182
1236
|
}
|
|
1183
|
-
|
|
1237
|
+
// #164: a hand-resolved merge can commit a leftover marker — content to git, so nothing else catches it
|
|
1238
|
+
const markerBase = await mergeBase(wtCwd, cfg.defaultBranch);
|
|
1239
|
+
const markerDiff = markerBase ? await sh(`git diff -U0 --no-color --no-ext-diff ${sq(markerBase)} HEAD`, wtCwd) : null;
|
|
1240
|
+
const conflictMarkers = markerDiff?.ok ? conflictMarkerLines(markerDiff.out) : undefined;
|
|
1241
|
+
const prep = { manifestVersion: manifestVer, remoteTags, changelog, changelogChanged, changelogBase, noFoldCheck: flag("no-fold-check"), conflictMarkers, noMarkerCheck: flag("no-marker-check") };
|
|
1184
1242
|
// same freshness rule as verify: a green predating a worktree write may not stand for the tree this gate blesses
|
|
1185
1243
|
if (freshenChecks(state!, await worktreeFingerprint(wtCwd)).length) writeState(root, state!);
|
|
1186
1244
|
// tier-2 pre-release confirmation is recorded by this very command, so it is excluded here
|
|
@@ -1213,14 +1271,27 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
|
|
|
1213
1271
|
`Update (/reload, then re-run flow release on the current build) or proceed with the old release?`;
|
|
1214
1272
|
staleNote = `released under dev-flow ${behind} (${selfBuild.label} ${selfBuild.version ?? "?"}) by operator choice — proofs newer than ${behind} did not run`;
|
|
1215
1273
|
}
|
|
1274
|
+
// #162: Verified? was answered over one tree; commits after it ship under that word unless someone says
|
|
1275
|
+
// so. A warning, never a refusal — doc-only moves after verify are normal; the operator decides.
|
|
1276
|
+
let postVerify = "";
|
|
1277
|
+
if (state!.verifiedHead) {
|
|
1278
|
+
const since = await sh(`git log --oneline --no-decorate ${sq(state!.verifiedHead)}..HEAD`, wtCwd);
|
|
1279
|
+
const commits = since.ok ? since.out.split("\n").filter((l) => l.trim()) : [];
|
|
1280
|
+
// a release-only flow commits its bump and changelog after verify by design — only other files count
|
|
1281
|
+
const prepFiles = new Set([cfg.versioning.file, cfg.release.changelog, cfg.versioning.file === "package.json" ? "package-lock.json" : ""].filter(Boolean) as string[]);
|
|
1282
|
+
const touched = state!.releaseOnly && commits.length ? await sh(`git diff --name-only ${sq(state!.verifiedHead)} HEAD`, wtCwd) : null;
|
|
1283
|
+
const prepOnly = !!touched?.ok && touched.out.split("\n").filter((l) => l.trim()).every((f) => prepFiles.has(f.trim()));
|
|
1284
|
+
if (commits.length && !prepOnly)
|
|
1285
|
+
postVerify = `${commits.length} commit(s) landed after the operator's Verified? (given over ${state!.verifiedHead.slice(0, 7)}): ${commits.slice(0, 6).join(" | ")}${commits.length > 6 ? ` …(${commits.length - 6} more)` : ""} — the verify verdict does not cover them: if behaviour changed, have the operator check the current build before Release?, and either way say in the PR body which commit the verdict was given over`;
|
|
1286
|
+
}
|
|
1216
1287
|
const audit = flag("confirmed") ? " (confirmed by operator instruction)" : state!.yolo ? " (yolo: pre-confirmed)" : "";
|
|
1217
1288
|
const askPending = !flag("confirmed") && !state!.yolo;
|
|
1218
1289
|
if (askPending) {
|
|
1219
1290
|
markPendingAsk(root, state!, "Release?");
|
|
1220
1291
|
if (!ui.hasUI) {
|
|
1221
|
-
return { text: needsOperator(`release confirmation needs the operator: confirm interactively, or re-run with --confirmed once the operator answered 'Release?' in chat${stale ? ` — the operator must also answer the stale-build question: ${staleAsk}` : ""}`, "Release?"), isError: true };
|
|
1292
|
+
return { text: needsOperator(`release confirmation needs the operator: confirm interactively, or re-run with --confirmed once the operator answered 'Release?' in chat${stale ? ` — the operator must also answer the stale-build question: ${staleAsk}` : ""}${postVerify ? ` — tell them: ${postVerify}` : ""}`, "Release?"), isError: true };
|
|
1222
1293
|
}
|
|
1223
|
-
const ok = await ui.confirm("Enter release", `Release ${state!.slug}${manifestVer ? ` v${manifestVer}` : ""}${noVersion ? " (unversioned — merge + changelog entry only: no bump, no tag for this flow)" : ""}? Publishing starts: PR, merge${noVersion ? "" : ", tag"} — release-done afterwards needs no further answer.${staleAsk ? `\n\n${staleAsk}` : ""}`);
|
|
1294
|
+
const ok = await ui.confirm("Enter release", `Release ${state!.slug}${manifestVer ? ` v${manifestVer}` : ""}${noVersion ? " (unversioned — merge + changelog entry only: no bump, no tag for this flow)" : ""}? Publishing starts: PR, merge${noVersion ? "" : ", tag"} — release-done afterwards needs no further answer.${staleAsk ? `\n\n${staleAsk}` : ""}${postVerify ? `\n\n${postVerify}` : ""}`);
|
|
1224
1295
|
if (!ok) {
|
|
1225
1296
|
delete state!.pendingAsk;
|
|
1226
1297
|
writeState(root, state!);
|
|
@@ -1245,7 +1316,7 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
|
|
|
1245
1316
|
if (stale) state!.staleBuild = `${behind} (${selfBuild.label} ${selfBuild.version ?? "?"})`;
|
|
1246
1317
|
delete state!.pendingAsk;
|
|
1247
1318
|
writeState(root, state!);
|
|
1248
|
-
return { text: `release approved${audit}${state!.noVersion ? " — unversioned: no bump or tag; your changelog entry rides under Unreleased until the next versioned release folds it" : ""} — entering release stage.${manifestVer ? ` Version ${manifestVer}.` : ""}${foldNote}${staleNote ? ` ${staleNote}.` : ""}\n${describeBranchState(branchProof, cfg.defaultBranch)}\n${nextHint(state!, cfg)}` };
|
|
1319
|
+
return { text: `release approved${audit}${state!.noVersion ? " — unversioned: no bump or tag; your changelog entry rides under Unreleased until the next versioned release folds it" : ""} — entering release stage.${manifestVer ? ` Version ${manifestVer}.` : ""}${foldNote}${staleNote ? ` ${staleNote}.` : ""}${postVerify ? ` Warning: ${postVerify}.` : ""}\n${describeBranchState(branchProof, cfg.defaultBranch)}\n${nextHint(state!, cfg)}` };
|
|
1249
1320
|
}
|
|
1250
1321
|
|
|
1251
1322
|
async function gateReleaseDone(o: GateCtx): Promise<RunResult> {
|
|
@@ -1866,6 +1937,7 @@ async function gateReflect(o: GateCtx): Promise<RunResult> {
|
|
|
1866
1937
|
if (words.length === 1 && words[0] === "tidy") return reflectTidy(root);
|
|
1867
1938
|
if (words.length === 1 && words[0] === "list") return await reflectList(root);
|
|
1868
1939
|
if (words[0] === "move") return reflectMoveNote(root, words.slice(1), forced);
|
|
1940
|
+
if (words[0] === "done") return reflectDoneNote(root, sess, words.slice(1));
|
|
1869
1941
|
if (words.length) return await reflectNote(root, sess, words, forced);
|
|
1870
1942
|
const self = pluginVersion(import.meta.dirname);
|
|
1871
1943
|
const upstream = await pluginUpstream(root);
|
|
@@ -1992,7 +2064,7 @@ async function gateTest(o: GateCtx): Promise<RunResult> {
|
|
|
1992
2064
|
const { state, err } = needState(root, sess, slugArg);
|
|
1993
2065
|
if (err) return err;
|
|
1994
2066
|
if (!cfg.commands.test) return { text: "no commands.test configured — add `test = <command>` under ## implement in .dev-flow/project.md", isError: true };
|
|
1995
|
-
const res = await sh(cfg.commands.test, gateCwd(root, state!));
|
|
2067
|
+
const res = await sh(cfg.commands.test, gateCwd(root, state!), undefined, featureEnv(root, state!));
|
|
1996
2068
|
state!.checks.test = { ok: res.ok, at: now() };
|
|
1997
2069
|
await stampChecks(root, state!, ["test"]);
|
|
1998
2070
|
writeState(root, state!);
|
|
@@ -2068,6 +2140,8 @@ async function gateAbort(o: GateCtx): Promise<RunResult> {
|
|
|
2068
2140
|
return { text: `aborted ${target} — feature removed (nothing approved, nothing to recover)` };
|
|
2069
2141
|
}
|
|
2070
2142
|
if (sess.slug === target) sess.bind(null);
|
|
2143
|
+
// the scratch dir is the bound session's working junk — it does not outlive the binding
|
|
2144
|
+
rmSync(featureTmpDir(dfDir(root), target), { recursive: true, force: true });
|
|
2071
2145
|
if (st?.worktree) { st.aborted = now(); writeState(root, st); } // the doctor skips the removed worktree for stamped states (gh#138)
|
|
2072
2146
|
return { text: `session unbound from ${target}; state stays at .dev-flow/${target}/` + (st?.aborted ? " (marked aborted — the doctor leaves it alone once you clean the worktree up)" : "") + (st?.worktree ? `\nto remove the worktree and branch:\n git worktree remove ${st.worktree}\n git branch -D ${st.branch}` : "") };
|
|
2073
2147
|
}
|
|
@@ -2080,6 +2154,43 @@ const workerSessions = new Set<string>();
|
|
|
2080
2154
|
/** Toolset per worker op: an implementer codes, a reviewer reads and runs commands only. */
|
|
2081
2155
|
const WORKER_TOOLS: Record<WorkerOp, string[]> = { implement: ["read", "bash", "edit", "write"], review: ["read", "bash"], reflect: ["read", "bash"] };
|
|
2082
2156
|
|
|
2157
|
+
/** Test-only timer override: the smoke suite drives the steer, the hard cut and the salvage grace in ms. */
|
|
2158
|
+
export const workerTiming: { softMs?: number; hardMs?: number; graceMs?: number } = {};
|
|
2159
|
+
|
|
2160
|
+
/** The upstream dev-flow repo's issues in every state, for the reflect brief's dedupe — prefetched so
|
|
2161
|
+
* the worker reads a list instead of looping gh searches. null = gh could not answer (the brief then
|
|
2162
|
+
* falls back to the search recipe). */
|
|
2163
|
+
async function upstreamIssueList(root: string, repo: string): Promise<{ number: number; title: string; state: string }[] | null> {
|
|
2164
|
+
if (!repo || process.env.DEV_FLOW_NO_ISSUES) return null;
|
|
2165
|
+
const r = await sh(`gh issue list --repo ${sq(repo)} --state all --json number,title,state --limit 200`, root, 15_000);
|
|
2166
|
+
if (!r.ok) return null;
|
|
2167
|
+
try {
|
|
2168
|
+
const a = JSON.parse(r.out) as { number?: unknown; title?: unknown; state?: unknown }[];
|
|
2169
|
+
return Array.isArray(a) ? a.filter((i) => Number.isInteger(i?.number)).map((i) => ({ number: Number(i.number), title: String(i.title ?? ""), state: String(i.state ?? "") })) : null;
|
|
2170
|
+
} catch {
|
|
2171
|
+
return null;
|
|
2172
|
+
}
|
|
2173
|
+
}
|
|
2174
|
+
|
|
2175
|
+
/** Seam: the smoke suite stubs the prefetch instead of calling gh against the real upstream. */
|
|
2176
|
+
export const reflectSeams = { upstreamIssues: upstreamIssueList };
|
|
2177
|
+
|
|
2178
|
+
/** Build the reflect worker's transcript digests in the feature's scratch dir (driver first). A
|
|
2179
|
+
* transcript that cannot be read is skipped — the brief still names the raw file. */
|
|
2180
|
+
function writeTranscriptDigests(root: string, slug: string, files: string[]): { transcript: string; digest: string }[] {
|
|
2181
|
+
const dir = path.join(featureTmpDir(dfDir(root), slug), "reflect");
|
|
2182
|
+
const out: { transcript: string; digest: string }[] = [];
|
|
2183
|
+
for (const f of files) {
|
|
2184
|
+
try {
|
|
2185
|
+
mkdirSync(dir, { recursive: true });
|
|
2186
|
+
const digest = path.join(dir, `${path.basename(f, ".jsonl")}.digest.txt`);
|
|
2187
|
+
writeFileSync(digest, digestTranscript(readFileSync(f, "utf8")));
|
|
2188
|
+
out.push({ transcript: f, digest });
|
|
2189
|
+
} catch { /* unreadable transcript: the raw path stays in the brief */ }
|
|
2190
|
+
}
|
|
2191
|
+
return out;
|
|
2192
|
+
}
|
|
2193
|
+
|
|
2083
2194
|
/** Line 1 of every pi session file in `dir` — the header that names a worker's parent session. A
|
|
2084
2195
|
* file is read up to its first newline only (transcripts grow large); unreadable files are skipped. */
|
|
2085
2196
|
function sessionHeaders(dir: string | undefined): SessionHeaderInfo[] {
|
|
@@ -2455,15 +2566,20 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2455
2566
|
? await (async () => {
|
|
2456
2567
|
const items = readReflections(root);
|
|
2457
2568
|
const fold = await foldView(root, items);
|
|
2569
|
+
const upstream = await pluginUpstream(root);
|
|
2570
|
+
const children = lineage.file ? childSessionFiles(lineage.file, sessionHeaders(lineage.dir)) : [];
|
|
2458
2571
|
return buildReflectBrief({
|
|
2459
2572
|
slug: st.slug, root, today: now().slice(0, 10),
|
|
2460
2573
|
driverFile: lineage.file ?? null,
|
|
2461
|
-
children
|
|
2574
|
+
children,
|
|
2575
|
+
digests: lineage.file ? writeTranscriptDigests(root, st.slug, [lineage.file, ...children.map((c) => c.file)]) : [],
|
|
2576
|
+
upstreamIssues: (await reflectSeams.upstreamIssues(root, upstream)) ?? undefined,
|
|
2577
|
+
budgetMin,
|
|
2462
2578
|
reflectionsFile: path.join(dfDir(root), "reflections.md"),
|
|
2463
2579
|
items,
|
|
2464
2580
|
projectMd: path.join(dfDir(root), "project.md"),
|
|
2465
2581
|
version: pluginVersion(import.meta.dirname).version,
|
|
2466
|
-
upstream
|
|
2582
|
+
upstream,
|
|
2467
2583
|
selfRepo,
|
|
2468
2584
|
projectIssues: fold.state === "ok" && !selfRepo ? { repo: fold.slug, issues: fold.result.upstreamOnly.map((i) => ({ number: i.number, title: i.title })) } : undefined,
|
|
2469
2585
|
note: String(params.note ?? ""),
|
|
@@ -2471,7 +2587,7 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2471
2587
|
})()
|
|
2472
2588
|
: buildWorkerBrief({
|
|
2473
2589
|
op: wop, slug: st.slug, workDir: work,
|
|
2474
|
-
planFile: path.join(featDir(root, st.slug), "plan", "plan.md"),
|
|
2590
|
+
planFile: ((f) => (existsSync(f) ? f : null))(path.join(featDir(root, st.slug), "plan", "plan.md")),
|
|
2475
2591
|
defaultBranch: cfg.defaultBranch,
|
|
2476
2592
|
commits: await git(`git log --oneline ${sq(cfg.defaultBranch)}..HEAD`),
|
|
2477
2593
|
status: await git("git status --short"),
|
|
@@ -2483,11 +2599,20 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2483
2599
|
const subagent = !lineage.id || !lineage.file ? undefined : { parentId: lineage.id, parentFile: lineage.file, toolCallId: id, profile: `flow-${wop}`, description: name, task: brief };
|
|
2484
2600
|
let child: AgentSession | undefined;
|
|
2485
2601
|
let timedOut = false;
|
|
2602
|
+
let steered = false;
|
|
2603
|
+
let salvaged = false;
|
|
2486
2604
|
let crash: string | null = null;
|
|
2487
2605
|
let nudges = 0;
|
|
2488
2606
|
let report = parseWorkerReport("");
|
|
2489
2607
|
const abortChild = () => void Promise.resolve(child?.abort()).catch(() => {});
|
|
2490
|
-
const
|
|
2608
|
+
const hardMs = workerTiming.hardMs ?? budgetMin * 60_000;
|
|
2609
|
+
// grace before the cliff (gh#142): steered at 75% to wrap up, so a long run hands back a REPORT
|
|
2610
|
+
// instead of being cut mid-thought — the hard timer stays the backstop
|
|
2611
|
+
const softTimer = setTimeout(() => {
|
|
2612
|
+
steered = true;
|
|
2613
|
+
try { void Promise.resolve(child?.steer(workerSteer(wop, budgetMin))).catch(() => {}); } catch { /* the hard cut follows */ }
|
|
2614
|
+
}, workerTiming.softMs ?? Math.round(hardMs * WORKER_STEER_AT));
|
|
2615
|
+
const timer = setTimeout(() => { timedOut = true; abortChild(); }, hardMs);
|
|
2491
2616
|
signal?.addEventListener("abort", abortChild);
|
|
2492
2617
|
let unsub: (() => void) | undefined;
|
|
2493
2618
|
let releaseLive: (status: string) => void = () => {};
|
|
@@ -2512,9 +2637,24 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2512
2637
|
await child.prompt(wop === "implement" ? WORKER_NUDGE : WORKER_NUDGE_READONLY);
|
|
2513
2638
|
report = parseWorkerReport(child.getLastAssistantText() ?? "");
|
|
2514
2639
|
}
|
|
2640
|
+
// cut at the budget without a REPORT: one short, tool-less turn to hand back what it found —
|
|
2641
|
+
// an aborted reflection otherwise loses every finding it had already made
|
|
2642
|
+
if (!report.found && timedOut && !signal?.aborted) {
|
|
2643
|
+
salvaged = true;
|
|
2644
|
+
const grace = setTimeout(abortChild, workerTiming.graceMs ?? WORKER_SALVAGE_MS);
|
|
2645
|
+
try {
|
|
2646
|
+
await child.prompt(WORKER_SALVAGE);
|
|
2647
|
+
report = parseWorkerReport(child.getLastAssistantText() ?? "");
|
|
2648
|
+
} catch {
|
|
2649
|
+
/* a failed salvage is still an interrupted run, not a crash */
|
|
2650
|
+
} finally {
|
|
2651
|
+
clearTimeout(grace);
|
|
2652
|
+
}
|
|
2653
|
+
}
|
|
2515
2654
|
} catch (e) {
|
|
2516
2655
|
crash = e instanceof Error ? e.message : String(e);
|
|
2517
2656
|
} finally {
|
|
2657
|
+
clearTimeout(softTimer);
|
|
2518
2658
|
clearTimeout(timer);
|
|
2519
2659
|
signal?.removeEventListener("abort", abortChild);
|
|
2520
2660
|
unsub?.();
|
|
@@ -2524,14 +2664,20 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2524
2664
|
const headAfter = (await git("git rev-parse HEAD")).trim();
|
|
2525
2665
|
const newCommits = headBefore && headAfter && headBefore !== headAfter ? await git(`git log --oneline ${sq(headBefore)}..HEAD`) : "";
|
|
2526
2666
|
const dirty = (await git("git status --short")).trim();
|
|
2527
|
-
const outcome = crash
|
|
2667
|
+
const outcome = crash
|
|
2668
|
+
? `crashed: ${crash}`
|
|
2669
|
+
: timedOut
|
|
2670
|
+
? `interrupted at the ${budgetMin}-min budget${steered ? " (steered to wrap up at " + Math.round(WORKER_STEER_AT * 100) + "%)" : ""}${report.found ? " — REPORT salvaged after the cut, treat it as partial" : salvaged ? " — the salvage prompt got no REPORT either" : ""}`
|
|
2671
|
+
: report.found
|
|
2672
|
+
? `reported${steered ? " (after the wrap-up steer)" : ""}`
|
|
2673
|
+
: `ended without REPORT after ${nudges} nudge(s)`;
|
|
2528
2674
|
// the terminal entry is what settles the Agents menu row (a persisted `running` the host
|
|
2529
2675
|
// cannot prove live displays as `interrupted`); a no-REPORT run is a failure, not a ✓.
|
|
2530
2676
|
if (subagent) {
|
|
2531
2677
|
const doneAt = now();
|
|
2532
2678
|
const final = crash
|
|
2533
2679
|
? { version: 1, status: "failed", completedAt: doneAt, error: crash }
|
|
2534
|
-
:
|
|
2680
|
+
: signal?.aborted || (timedOut && !report.found)
|
|
2535
2681
|
? { version: 1, status: "aborted", completedAt: doneAt }
|
|
2536
2682
|
: report.found
|
|
2537
2683
|
? { version: 1, status: "completed", completedAt: doneAt, result: report.body }
|
|
@@ -2542,7 +2688,7 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2542
2688
|
}
|
|
2543
2689
|
releaseLive("failed"); // idempotent guard: a throw between claim and result must not leave a live row
|
|
2544
2690
|
try { if (child) workerSessions.delete(child.sessionManager.getSessionId()); } catch { /* id-less session: nothing was registered */ }
|
|
2545
|
-
try { child?.setSessionName(`${report.found && !crash && !
|
|
2691
|
+
try { child?.setSessionName(`${report.found && !crash && !signal?.aborted ? (timedOut ? "◐" : "✓") : "✗"} ${name}${report.verdict ? ` · ${report.verdict}` : ""}`); } catch { /* visibility only */ }
|
|
2546
2692
|
const parts = [`${glyph} ${wop} worker ${outcome} (${Math.round((Date.now() - started) / 60_000)} min)`];
|
|
2547
2693
|
let reflected: ReturnType<typeof parseReflectReport> | null = null;
|
|
2548
2694
|
if (wop === "reflect") {
|
|
@@ -2656,7 +2802,22 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2656
2802
|
pi.appendEntry("dev-flow-skill", { core: true, stale: true });
|
|
2657
2803
|
});
|
|
2658
2804
|
|
|
2805
|
+
// A bash call every guard let through runs with TMPDIR in its bound feature's scratch dir
|
|
2806
|
+
// (.dev-flow/<slug>/tmp/): mktemp, os.tmpdir() and test fixtures land there and flow finish removes
|
|
2807
|
+
// them. Prefixed only after the verdict, so no guard ever judges the prefix.
|
|
2659
2808
|
pi.on("tool_call", async (event, ctx) => {
|
|
2809
|
+
const verdict = await guardToolCall(event, ctx);
|
|
2810
|
+
if (verdict || !isToolCallEventType("bash", event) || !guardsAreMine() || !initiated(ctx.cwd)) return verdict;
|
|
2811
|
+
const root = await flowRoot(ctx.cwd);
|
|
2812
|
+
const bound = boundFeature(root, sessionKey(ctx));
|
|
2813
|
+
if (!bound) return undefined;
|
|
2814
|
+
const dir = featureTmpDir(dfDir(root), bound.slug);
|
|
2815
|
+
mkdirSync(dir, { recursive: true });
|
|
2816
|
+
event.input.command = withTmpDir(String(event.input.command ?? ""), dir);
|
|
2817
|
+
return undefined;
|
|
2818
|
+
});
|
|
2819
|
+
|
|
2820
|
+
async function guardToolCall(event: ToolCallEvent, ctx: ExtensionContext): Promise<ToolCallEventResult | undefined> {
|
|
2660
2821
|
if (!guardsAreMine()) return undefined; // election: only the newest loaded copy judges
|
|
2661
2822
|
// pi kills a shell call only when a timeout was passed, and the model omits it in ~75% of
|
|
2662
2823
|
// calls (observed hangs: hours). Deterministic class defaults, clamped ceilings — runs for
|
|
@@ -2786,7 +2947,7 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2786
2947
|
}
|
|
2787
2948
|
}
|
|
2788
2949
|
return undefined;
|
|
2789
|
-
}
|
|
2950
|
+
}
|
|
2790
2951
|
|
|
2791
2952
|
pi.on("before_agent_start", async (_event, ctx) => {
|
|
2792
2953
|
if (!guardsAreMine()) return undefined;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-dev-flow",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.80.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": [
|
|
@@ -14,7 +14,9 @@ the session context goes with it. Run the end-of-session reflection now:
|
|
|
14
14
|
**docs** (fix only in `project.md` → docs flow), **code** (fix in this
|
|
15
15
|
project's code, maybe the playbook too → patch flow) or **plugin** (dev-flow
|
|
16
16
|
itself → GitHub issue upstream), with a **fold** or **drop** recommendation.
|
|
17
|
-
`note` = anything the operator said about friction this session.
|
|
17
|
+
`note` = anything the operator said about friction this session. The tool
|
|
18
|
+
prebuilds a line-tagged digest of every transcript and prefetches the
|
|
19
|
+
upstream issues, so the worker reads instead of dumping and searching. If the
|
|
18
20
|
worker fails, run the review inline (bare `flow reflect` prints the protocol).
|
|
19
21
|
2. Show the operator the list with your recommendation per item and ask
|
|
20
22
|
**fold or drop** for each (`fold 1,3 drop 2` is a fine answer) — then stop.
|
|
@@ -43,8 +45,8 @@ unmerged. `flow finish [slug]`:
|
|
|
43
45
|
through `flow abort` instead;
|
|
44
46
|
- requires the main checkout **clean and pushed** — an uncommitted changelog or
|
|
45
47
|
a local-only release commit is exactly what it protects against;
|
|
46
|
-
- removes the worktree and branch, then deletes `.dev-flow/<slug>/`
|
|
47
|
-
unbinds the session. A feature branch still on `origin` is deleted **only on
|
|
48
|
+
- removes the worktree and branch, then deletes `.dev-flow/<slug>/` (its
|
|
49
|
+
`tmp/` scratch dir included) and unbinds the session. A feature branch still on `origin` is deleted **only on
|
|
48
50
|
proof it was merged** — ancestor of `origin/<default>`, or a merged PR via gh
|
|
49
51
|
or glab (what a squash leaves behind); otherwise kept with a note. Uncommitted worktree edits block
|
|
50
52
|
finish; commits that never reached the default branch are read against the playbook's `merge` policy —
|
|
@@ -17,11 +17,16 @@ feature).
|
|
|
17
17
|
the end faces review blind and is not crash-safe. The gate enforces the
|
|
18
18
|
habit: `flow verify` refuses while the branch holds **no commit** (checks
|
|
19
19
|
describe the working tree, so nothing committed means nothing reviewed was
|
|
20
|
-
ever recorded
|
|
20
|
+
ever recorded; a **release-only flow** — a versioned project whose code is
|
|
21
|
+
already on main, unreleased since the last tag — passes with an empty branch,
|
|
22
|
+
and its bump is the pre-release commit) and every verify line reports
|
|
21
23
|
`commits: N ahead of <default>, M uncommitted path(s)` — uncommitted paths
|
|
22
24
|
never block verify, they are what the operator sees they are approving.
|
|
23
25
|
2. Write tests as you go (project framework: the `test` key / `flow-check`
|
|
24
26
|
blocks).
|
|
27
|
+
Throwaway scripts and scratch output go in `$TMPDIR` (or `mktemp`), not a
|
|
28
|
+
hard-coded `/tmp/...`: in a bound session, and in every command a gate runs,
|
|
29
|
+
it is `.dev-flow/<slug>/tmp/`, and finish removes it with the feature.
|
|
25
30
|
3. `flow check` runs every tier-1 check (test, health, named `flow-check`
|
|
26
31
|
blocks) and records each against a fingerprint of the worktree; any later
|
|
27
32
|
worktree change makes them stale — verify reruns stale checks itself.
|
|
@@ -108,6 +113,10 @@ resending the same note.
|
|
|
108
113
|
- One worker at a time per session. The worker holds no flow tool, so gates
|
|
109
114
|
and checkpoints stay with you. Its transcript nests under this session in
|
|
110
115
|
pi's picker.
|
|
116
|
+
- Budget (`budgetMin`; default 60 implement, 30 review, 20 reflect): at 75% the
|
|
117
|
+
worker is steered to wrap up and report. A worker cut at the budget is asked
|
|
118
|
+
once, with no tools, for its REPORT, so what it found comes back marked
|
|
119
|
+
partial instead of being lost.
|
|
111
120
|
|
|
112
121
|
`flow verify` re-runs build, runs the `dev` deploy when configured (the
|
|
113
122
|
operator reviews the running app; the gate **prints what it ran** —
|
|
@@ -25,7 +25,9 @@ Gate flags are ignored (`flow reflect "<note>" --confirmed` queues the note
|
|
|
25
25
|
alone). With no flag the wording guesses (plugin-shaped → the upstream recipe,
|
|
26
26
|
otherwise `## playbook`) and the printed line says why; `flow reflect list`
|
|
27
27
|
numbers the queue and `flow reflect move <n> --playbook|--code` re-files an
|
|
28
|
-
item — never hand-retype it.
|
|
28
|
+
item — never hand-retype it. `flow reflect done <n> ["<what fixed it>"]` checks
|
|
29
|
+
an item off once a flow has fixed it (`— fixed: <date> <slug> — <what>`), so
|
|
30
|
+
doctor stops re-reporting it. A legacy `## plugin` row from an older dev-flow is
|
|
29
31
|
flagged by `flow doctor` / `reflect list`: file it upstream and check it off
|
|
30
32
|
`— filed: gh#NNN`. For a note to chase **now**: `flow doctor "<observation>"`
|
|
31
33
|
prints an investigation brief without queueing.
|
|
@@ -50,9 +52,10 @@ prints an investigation brief without queueing.
|
|
|
50
52
|
- Plain `flow doctor` reviews the open items and **routes** each — `## playbook`
|
|
51
53
|
→ docs flow, `## code` → patch flow. To fold items in on the operator's word:
|
|
52
54
|
investigate, propose the fix, get confirmation, open the routed flow and apply
|
|
53
|
-
it there — project.md is editable only in a docs/patch worktree.
|
|
54
|
-
off
|
|
55
|
-
|
|
55
|
+
it there — project.md is editable only in a docs/patch worktree. Once it is
|
|
56
|
+
merged, check the item off with `flow reflect done <n> "<what>"` (or by hand in
|
|
57
|
+
the gitignored `.dev-flow/reflections.md`: `- [x]` and a `— folded: <what>` or
|
|
58
|
+
`— fixed: <what>` note).
|
|
56
59
|
- **Open GitHub issues fold into the view** when the repo has a GitHub remote: `flow doctor` and
|
|
57
60
|
`flow reflect list` list them under the local queue (read-time fold — issues are never imported,
|
|
58
61
|
each item keeps one home). A local row an open issue already covers carries `⟷ gh#NNN` — fold it
|
package/src/core.ts
CHANGED
|
@@ -47,14 +47,18 @@ export interface FlowState {
|
|
|
47
47
|
forgeReleaseSkipped?: string; // a gh/glab release create that failed: release-done says so, finish names it so the missing forge release cannot slip past (#63)
|
|
48
48
|
staleBuild?: string; // release ran under an older dev-flow than the checkout by operator choice ("<loaded> (checkout <disk>)"); release-done repeats the acknowledgement
|
|
49
49
|
pendingAsk?: string; // the checkpoint word a gate asked for and has not been given ("Approve?", "Verified?", …) — presentation only (💬 in the footer), it never gates
|
|
50
|
+
releaseOnly?: boolean; // verify found nothing on the branch but unreleased work on main: this flow only cuts the version (#161)
|
|
51
|
+
verifiedHead?: string; // HEAD the operator's Verified? was given over — release names commits after it, so the word is not recorded as the verdict for a tree nobody looked at (#162)
|
|
50
52
|
reflectedAt?: string; // a flow_stage reflect worker reported for this flow — finish names a missing one (advisory, never a block)
|
|
51
53
|
aborted?: string; // flow abort on a feature whose worktree exists: the state is a deliberate abandoned-feature record (gh#138) — the doctor's git-consistency sweep must never flag its hand-removed worktree as drift
|
|
52
54
|
}
|
|
53
55
|
|
|
54
|
-
/** Tier-2 item: operator prose; uiOnly items ("(ui)" in project.md) apply only to --ui features
|
|
56
|
+
/** Tier-2 item: operator prose; uiOnly items ("(ui)" in project.md) apply only to --ui features;
|
|
57
|
+
* versionedOnly items ("(versioned)") presuppose a bump/tag and stand down on a --no-version flow (#166). */
|
|
55
58
|
export interface ChecklistItem {
|
|
56
59
|
text: string;
|
|
57
60
|
uiOnly: boolean;
|
|
61
|
+
versionedOnly?: boolean;
|
|
58
62
|
}
|
|
59
63
|
|
|
60
64
|
export interface Commands {
|
|
@@ -270,15 +274,29 @@ export function approveGate(state: FlowState, cfg: Config, planFiles: string[],
|
|
|
270
274
|
export interface BranchState {
|
|
271
275
|
commitsAhead: number | null;
|
|
272
276
|
uncommitted: number;
|
|
277
|
+
/** Only measured when nothing is committed on a versioned project: commits on the default branch since
|
|
278
|
+
* the newest version tag (every commit when none is tagged yet), and that tag. > 0 = a release-only
|
|
279
|
+
* flow — main carries the code, the flow only cuts the version (#161). null = git could not answer. */
|
|
280
|
+
unreleased?: { count: number | null; since: string | null };
|
|
273
281
|
}
|
|
274
282
|
|
|
283
|
+
/** A release-only flow: nothing on the branch, but the default branch holds unreleased work to version (#161). */
|
|
284
|
+
export const isReleaseOnly = (cfg: Config, branch?: BranchState | null): boolean =>
|
|
285
|
+
!!cfg.versioning.file && branch?.commitsAhead === 0 && (branch.unreleased?.count ?? 0) > 0;
|
|
286
|
+
|
|
275
287
|
/** Gate: implement → release. Tier 1: every parsed check green; tier 2: checklist confirmed;
|
|
276
288
|
* the branch must hold at least one commit — checks describe the working tree, so with nothing
|
|
277
289
|
* committed the operator is asked to approve state no gate has ever seen. */
|
|
278
290
|
export function verifyGate(state: FlowState, cfg: Config, branch?: BranchState | null): string[] {
|
|
279
291
|
const errs: string[] = [];
|
|
280
292
|
if (state.stage !== "implement") errs.push(`stage is "${state.stage}", verify only applies to "implement"`);
|
|
281
|
-
|
|
293
|
+
// a release-only flow (#161) proves main's committed tree here; its version bump is the pre-release commit
|
|
294
|
+
if (branch && branch.commitsAhead === 0 && !isReleaseOnly(cfg, branch))
|
|
295
|
+
errs.push(
|
|
296
|
+
cfg.versioning.file && branch.unreleased?.count === 0
|
|
297
|
+
? `nothing committed on the feature branch, and ${branch.unreleased.since ? `nothing landed on the default branch since ${branch.unreleased.since}` : "the default branch has nothing to release"} — there is nothing to verify or release`
|
|
298
|
+
: "nothing committed on the feature branch yet — commit as you go, verify proves a committed state",
|
|
299
|
+
);
|
|
282
300
|
if (!state.docs) for (const c of cfg.checkList) if (!state.checks[c.name]?.ok) errs.push(`check "${c.name}" has not passed — run flow check`);
|
|
283
301
|
const pend = checklistPending(cfg, state, "implement");
|
|
284
302
|
if (pend) errs.push(`tier-2 checklist not confirmed (${pend} item(s)) — run flow verify after ticking them off`);
|
|
@@ -301,6 +319,30 @@ export interface ReleasePrep {
|
|
|
301
319
|
changelogBase?: { pending: string[]; source: "tag" | "merge-base" | "none" };
|
|
302
320
|
/** Operator-granted escape from the line-level fold proofs (`flow release --no-fold-check`). */
|
|
303
321
|
noFoldCheck?: boolean;
|
|
322
|
+
/** Conflict-marker lines the branch adds vs its merge base (`file:line: text`) — a hand-resolved merge
|
|
323
|
+
* that kept one ships it otherwise (#164). Undefined = not measured (no merge base). */
|
|
324
|
+
conflictMarkers?: string[];
|
|
325
|
+
/** Operator-granted escape for a branch that adds marker-shaped lines on purpose (`--no-marker-check`). */
|
|
326
|
+
noMarkerCheck?: boolean;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** Added lines in a unified diff (`git diff -U0 <base>`) that are merge-conflict markers, as
|
|
330
|
+
* `file:line: text`. Only the unambiguous markers count — `<<<<<<<`, `|||||||`, `>>>>>>>` at the line start
|
|
331
|
+
* followed by a space or the end of the line; a bare `=======` is also a markdown heading underline. */
|
|
332
|
+
export function conflictMarkerLines(diff: string): string[] {
|
|
333
|
+
const out: string[] = [];
|
|
334
|
+
let file = "";
|
|
335
|
+
let line = 0;
|
|
336
|
+
for (const l of (diff ?? "").split("\n")) {
|
|
337
|
+
if (l.startsWith("+++ ")) { file = l.slice(4).replace(/^b\//, ""); continue; }
|
|
338
|
+
const h = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(l);
|
|
339
|
+
if (h) { line = Number(h[1]); continue; }
|
|
340
|
+
if (l.startsWith("+")) {
|
|
341
|
+
if (/^(<{7}|\|{7}|>{7})( |$)/.test(l.slice(1))) out.push(`${file}:${line}: ${l.slice(1).slice(0, 80)}`);
|
|
342
|
+
line++;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return out;
|
|
304
346
|
}
|
|
305
347
|
|
|
306
348
|
/** One changelog line as the fold proofs compare it: indentation, bullet style and whitespace runs are
|
|
@@ -386,10 +428,14 @@ export function preReleaseGate(state: FlowState, cfg: Config, prep: ReleasePrep)
|
|
|
386
428
|
if (!state.docs) for (const c of cfg.checkList) if (!state.checks[c.name]?.ok) errs.push(`check "${c.name}" has not passed — run flow check`);
|
|
387
429
|
const pend = checklistPending(cfg, state, "pre-release");
|
|
388
430
|
if (pend) errs.push(`tier-2 checklist not confirmed (${pend} item(s)) — run flow release after ticking them off`);
|
|
431
|
+
if (prep.conflictMarkers?.length && !prep.noMarkerCheck)
|
|
432
|
+
errs.push(`the branch adds ${prep.conflictMarkers.length} merge-conflict marker line(s) — a hand-resolved merge kept them; fix and commit (or, when the lines are meant, re-run with --no-marker-check on the operator's word):\n ${prep.conflictMarkers.slice(0, 5).join("\n ")}${prep.conflictMarkers.length > 5 ? `\n …(${prep.conflictMarkers.length - 5} more)` : ""}`);
|
|
389
433
|
if (state.noVersion) {
|
|
390
434
|
// unversioned flow (operator granted --no-version): no bump, no tag, no forge release —
|
|
391
|
-
// but the merge still owes a changelog line under Unreleased, folded by the next versioned release
|
|
392
|
-
|
|
435
|
+
// but the merge still owes a changelog line under Unreleased, folded by the next versioned release.
|
|
436
|
+
// A --docs flow does not (#163): it changes the playbook/docs, which many projects keep out of a
|
|
437
|
+
// user-facing changelog — an entry it writes is still welcome, just not proven.
|
|
438
|
+
if (cfg.release.changelog && !state.docs) {
|
|
393
439
|
if (!prep.changelog) errs.push(`release.changelog "${cfg.release.changelog}" does not exist — an unversioned release must record its entry there (under Unreleased)`);
|
|
394
440
|
else {
|
|
395
441
|
if (prep.changelogChanged === false) errs.push(`${prep.changelog.file} is unchanged on this branch — an unversioned release must add its entry (under Unreleased)`);
|
|
@@ -448,7 +494,7 @@ export function unreleasedPending(content: string): boolean {
|
|
|
448
494
|
|
|
449
495
|
export function checklistHash(items: ChecklistItem[]): string {
|
|
450
496
|
return createHash("sha1")
|
|
451
|
-
.update(items.map((i) => `${i.uiOnly ? "(ui) " : ""}${i.text}`).join("\n"))
|
|
497
|
+
.update(items.map((i) => `${i.uiOnly ? "(ui) " : ""}${i.versionedOnly ? "(versioned) " : ""}${i.text}`).join("\n"))
|
|
452
498
|
.digest("hex")
|
|
453
499
|
.slice(0, 12);
|
|
454
500
|
}
|
|
@@ -485,7 +531,7 @@ export function freshenChecks(state: FlowState, fp: string | null, keep: (name:
|
|
|
485
531
|
|
|
486
532
|
/** Items that apply to this feature — "(ui)" items only when the UI flag is set. */
|
|
487
533
|
export function applicableItems(cfg: Config, state: FlowState, stage: string): ChecklistItem[] {
|
|
488
|
-
return (cfg.checklist[stage] ?? []).filter((i) => !i.uiOnly || state.ui);
|
|
534
|
+
return (cfg.checklist[stage] ?? []).filter((i) => (!i.uiOnly || state.ui) && (!i.versionedOnly || !state.noVersion));
|
|
489
535
|
}
|
|
490
536
|
|
|
491
537
|
/** Items exist for the stage and current confirmation does not match their hash; returns pending count or 0. */
|
|
@@ -1325,6 +1371,18 @@ export function mainCheckoutRoot(cwd: string, commonDir: string | null): string
|
|
|
1325
1371
|
return main === path.resolve(cwd) ? null : main;
|
|
1326
1372
|
}
|
|
1327
1373
|
|
|
1374
|
+
/** A bound feature's scratch dir: every process the flow runs for it gets this as TMPDIR, so throwaways
|
|
1375
|
+
* and test fixtures land inside `.dev-flow/<slug>/` and `flow finish` removes them with the feature. */
|
|
1376
|
+
export function featureTmpDir(dfDir: string, slug: string): string {
|
|
1377
|
+
return path.join(dfDir, slug, "tmp");
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
/** The agent's shell command with TMPDIR pointed at the feature's scratch dir (newline-prefixed, the
|
|
1381
|
+
* shape pi's own commandPrefix uses — the command itself stays byte-for-byte what the guards judged). */
|
|
1382
|
+
export function withTmpDir(command: string, dir: string): string {
|
|
1383
|
+
return `export TMPDIR=${sq(dir)}\n${command}`;
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1328
1386
|
export function inScratchDir(abs: string, repoRoot?: string | null): boolean {
|
|
1329
1387
|
const real = realAbs(abs);
|
|
1330
1388
|
if (repoRoot) {
|
|
@@ -1382,7 +1440,7 @@ export function writeGuard(o: { abs: string; dfDir: string; features: FeatureRef
|
|
|
1382
1440
|
}
|
|
1383
1441
|
if (bound) {
|
|
1384
1442
|
if (bound.state.stage === "implement" || bound.state.stage === "pre-release")
|
|
1385
|
-
return `bound feature ${o.boundSlug} is at ${bound.state.stage} — edit its worktree (${bound.state.worktree}), not the main checkout; a throwaway script goes
|
|
1443
|
+
return `bound feature ${o.boundSlug} is at ${bound.state.stage} — edit its worktree (${bound.state.worktree}), not the main checkout; a throwaway script goes in $TMPDIR (.dev-flow/${o.boundSlug}/tmp/, removed at finish)`;
|
|
1386
1444
|
return null; // release: release chores may touch the main checkout
|
|
1387
1445
|
}
|
|
1388
1446
|
if (!o.features.length) return "no active flow — every request goes through flow: flow start <slug> for new work, flow use <slug> for an unfinished feature";
|
|
@@ -1691,6 +1749,20 @@ export function reflectMove(text: string, n: number, section: ReflectSection): s
|
|
|
1691
1749
|
return appendReflection(lines.join("\n"), [section], line.trim());
|
|
1692
1750
|
}
|
|
1693
1751
|
|
|
1752
|
+
/** Check open item `n` (the `flow reflect list` numbering) off: `- [x] … — fixed: <note>` — the convention
|
|
1753
|
+
* doctor reads as closed, so a folded item stops re-nagging (#165). null when there is no item `n`. */
|
|
1754
|
+
export function reflectDone(text: string, n: number, note: string): string | null {
|
|
1755
|
+
const lines = text.split("\n");
|
|
1756
|
+
let seen = 0;
|
|
1757
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1758
|
+
if (!isOpenItem(lines[i])) continue;
|
|
1759
|
+
if (++seen !== n) continue;
|
|
1760
|
+
lines[i] = `${lines[i].replace(/^(\s*)- \[ \] /, "$1- [x] ").trimEnd()} — fixed: ${note.trim()}`;
|
|
1761
|
+
return lines.join("\n");
|
|
1762
|
+
}
|
|
1763
|
+
return null;
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1694
1766
|
/** What `flow doctor <note>` prints: the note is an investigation order, not an answer —
|
|
1695
1767
|
* the plugin has no LLM; the agent investigates, the gates confirm, the flow implements. */
|
|
1696
1768
|
export function investigationBrief(note: string, selfRepo: boolean): string[] {
|
|
@@ -1952,6 +2024,8 @@ export function nextHint(state: FlowState, cfg: Config): string {
|
|
|
1952
2024
|
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`;
|
|
1953
2025
|
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)`;
|
|
1954
2026
|
case "pre-release":
|
|
2027
|
+
if (state.docs && (cfg.versioning.file || cfg.release.changelog))
|
|
2028
|
+
return `${cfg.release.review} → fix must-have/should-have → docs flow: it usually ships unversioned — ask the operator; with their word, flow release --no-version needs no bump, no tag and (docs mode) no changelog entry. Shipping it versioned instead:${cfg.release.changelog ? ` prepare ${cfg.release.changelog}` : ""}${cfg.versioning.file ? `${cfg.release.changelog ? " and" : ""} bump version in ${cfg.versioning.file}` : ""}. Then show the operator the PR summary, ask Release? and run flow release`;
|
|
1955
2029
|
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`;
|
|
1956
2030
|
case "release":
|
|
1957
2031
|
return state.approvals.release
|
|
@@ -2073,7 +2147,8 @@ export interface WorkerBriefInput {
|
|
|
2073
2147
|
op: Exclude<WorkerOp, "reflect">;
|
|
2074
2148
|
slug: string;
|
|
2075
2149
|
workDir: string;
|
|
2076
|
-
|
|
2150
|
+
/** null = no plan file on disk (a --docs / --patch flow needs none) — the brief says so instead of sending the worker after an ENOENT */
|
|
2151
|
+
planFile: string | null;
|
|
2077
2152
|
defaultBranch: string;
|
|
2078
2153
|
commits: string; // `git log --oneline <base>..HEAD`
|
|
2079
2154
|
status: string; // `git status --short`
|
|
@@ -2090,7 +2165,9 @@ export function buildWorkerBrief(o: WorkerBriefInput): string {
|
|
|
2090
2165
|
"",
|
|
2091
2166
|
"## Facts",
|
|
2092
2167
|
`- Worktree (your cwd; work only here): ${o.workDir}`,
|
|
2093
|
-
|
|
2168
|
+
o.planFile
|
|
2169
|
+
? `- Approved plan (read it first; it is outside the worktree): ${o.planFile}`
|
|
2170
|
+
: "- Plan: none — this flow (--docs / --patch) has no plan file by design; judge the work against the task below and the commits",
|
|
2094
2171
|
`- Branch base: ${o.defaultBranch}`,
|
|
2095
2172
|
`- Commits on the branch so far:\n${o.commits.trim() ? o.commits.trim().split("\n").map((l) => ` ${l}`).join("\n") : " (none)"}`,
|
|
2096
2173
|
`- Uncommitted now: ${o.status.trim() ? `\n${o.status.trim().split("\n").map((l) => ` ${l}`).join("\n")}` : "clean"}`,
|
|
@@ -2111,7 +2188,7 @@ export function buildWorkerBrief(o: WorkerBriefInput): string {
|
|
|
2111
2188
|
]
|
|
2112
2189
|
: [
|
|
2113
2190
|
"## Contract",
|
|
2114
|
-
|
|
2191
|
+
`- Check, don't fix: read ${o.planFile ? "the plan" : "the task"}, the diff (\`git diff ${o.defaultBranch}...HEAD\`) and the code; run the checks and any probe that proves a claim. Change no files, make no commits.`,
|
|
2115
2192
|
"- Look for correctness bugs, claims in docs/changelog the code does not back, missing tests for risky paths, and plan items not delivered.",
|
|
2116
2193
|
"- Finish with a final message whose last section starts with a line `REPORT` followed by: `verdict: PASS` or `verdict: FAIL`, then findings (most severe first, each with file:line and how you proved it).",
|
|
2117
2194
|
];
|
|
@@ -2137,8 +2214,107 @@ export const WORKER_NUDGE = "You stopped before finishing and without the REPORT
|
|
|
2137
2214
|
/** The nudge a read-only worker (review, reflect) gets — it has nothing to commit. */
|
|
2138
2215
|
export const WORKER_NUDGE_READONLY = "You stopped before finishing and without the REPORT section. Continue the task now (keep using tools; change no files). When it is done — or you are truly blocked — end with the `REPORT` section the contract asks for.";
|
|
2139
2216
|
|
|
2217
|
+
/** Share of the budget at which a worker is steered to wrap up (gh#142's grace, restored for every op). */
|
|
2218
|
+
export const WORKER_STEER_AT = 0.75;
|
|
2219
|
+
|
|
2220
|
+
/** Grace after the hard cut: one REPORT-only prompt, so an interrupted worker hands back what it found. */
|
|
2221
|
+
export const WORKER_SALVAGE_MS = 3 * 60_000;
|
|
2222
|
+
|
|
2223
|
+
/** The steer a worker gets at WORKER_STEER_AT of its budget — wrap up while there is time to. */
|
|
2224
|
+
export function workerSteer(op: WorkerOp, budgetMin: number): string {
|
|
2225
|
+
const left = Math.max(1, Math.round(budgetMin * (1 - WORKER_STEER_AT)));
|
|
2226
|
+
return op === "implement"
|
|
2227
|
+
? `Time check: about ${left} min of your ${budgetMin}-min budget are left. Finish the edit in hand, commit what works, and end with the REPORT section now (done, commits, open items, risks) — an honest partial report beats being cut off.`
|
|
2228
|
+
: `Time check: about ${left} min of your ${budgetMin}-min budget are left. Stop probing and write the REPORT section now with what you have — rows you could not fully prove say so in their evidence. Being cut off loses every finding.`;
|
|
2229
|
+
}
|
|
2230
|
+
|
|
2231
|
+
/** The prompt an interrupted worker gets once after the hard cut — report only, no more tools. */
|
|
2232
|
+
export const WORKER_SALVAGE = "Your time budget is spent and your last turn was interrupted. Do not call any more tools. Reply now with only the REPORT section the contract asks for, from what you already found (mark anything unfinished or unproven as such).";
|
|
2233
|
+
|
|
2140
2234
|
// ------------------------------------------------------------- reflect worker (flow_stage op "reflect")
|
|
2141
2235
|
|
|
2236
|
+
/** Compact, line-referenced digest of a pi session JSONL for the reflect worker. A driver transcript
|
|
2237
|
+
* runs to megabytes; the worker used to spend half its budget dumping and paging it. The digest keeps
|
|
2238
|
+
* what a reflection looks for — operator messages, flow gate calls and their answers, tool errors,
|
|
2239
|
+
* refusals, repeated commands — each tagged `L<n>` (the JSONL line) so the worker can open the raw
|
|
2240
|
+
* entry when one needs context. Pure: text in, text out. */
|
|
2241
|
+
export function digestTranscript(jsonl: string, opts: { maxChars?: number } = {}): string {
|
|
2242
|
+
const max = opts.maxChars ?? 80_000;
|
|
2243
|
+
const clip = (t: string, n: number) => {
|
|
2244
|
+
const one = t.replace(/\s+/g, " ").trim();
|
|
2245
|
+
return one.length > n ? `${one.slice(0, n)}…` : one;
|
|
2246
|
+
};
|
|
2247
|
+
const textOf = (c: unknown): string =>
|
|
2248
|
+
typeof c === "string" ? c : Array.isArray(c) ? c.filter((b) => b && (b as { type?: string }).type === "text").map((b) => String((b as { text?: unknown }).text ?? "")).join("\n") : "";
|
|
2249
|
+
const out: string[] = [];
|
|
2250
|
+
const calls = new Map<string, { line: number; name: string; args: string }>();
|
|
2251
|
+
const cmdCount = new Map<string, { n: number; first: number }>();
|
|
2252
|
+
let entries = 0, toolCalls = 0, errors = 0, first = "", last = "";
|
|
2253
|
+
const lines = (jsonl ?? "").split("\n");
|
|
2254
|
+
for (let i = 0; i < lines.length; i++) {
|
|
2255
|
+
const raw = lines[i].trim();
|
|
2256
|
+
if (!raw) continue;
|
|
2257
|
+
let e: Record<string, unknown>;
|
|
2258
|
+
try { e = JSON.parse(raw); } catch { continue; }
|
|
2259
|
+
entries++;
|
|
2260
|
+
const L = `L${i + 1}`;
|
|
2261
|
+
const ts = typeof e.timestamp === "string" ? e.timestamp : "";
|
|
2262
|
+
if (ts) { first ||= ts; last = ts; }
|
|
2263
|
+
if (e.type === "compaction") { out.push(`${L} ── compaction (earlier context summarized)`); continue; }
|
|
2264
|
+
if (e.type === "custom_message" && e.customType === "flow") { out.push(`${L} /flow → ${clip(textOf(e.content), 400)}`); continue; }
|
|
2265
|
+
if (e.type !== "message") continue;
|
|
2266
|
+
const m = (e.message ?? {}) as { role?: string; content?: unknown; toolCallId?: string; toolName?: string; isError?: boolean };
|
|
2267
|
+
if (m.role === "user") {
|
|
2268
|
+
const t = textOf(m.content);
|
|
2269
|
+
if (t.trim()) out.push(`${L} OPERATOR: ${clip(t, 900)}`);
|
|
2270
|
+
} else if (m.role === "assistant") {
|
|
2271
|
+
const blocks = Array.isArray(m.content) ? (m.content as Record<string, unknown>[]) : [];
|
|
2272
|
+
const said = blocks.filter((b) => b.type === "text").map((b) => String(b.text ?? "")).join(" ");
|
|
2273
|
+
if (said.trim()) out.push(`${L} agent: ${clip(said, 300)}`);
|
|
2274
|
+
for (const b of blocks) {
|
|
2275
|
+
if (b.type !== "toolCall") continue;
|
|
2276
|
+
toolCalls++;
|
|
2277
|
+
const name = String(b.name ?? "?");
|
|
2278
|
+
const a = (b.arguments ?? {}) as Record<string, unknown>;
|
|
2279
|
+
const args = name === "bash" ? String(a.command ?? "") : name === "flow" ? (Array.isArray(a.args) ? (a.args as unknown[]).join(" ") : JSON.stringify(a)) : JSON.stringify(a);
|
|
2280
|
+
calls.set(String(b.id ?? ""), { line: i + 1, name, args });
|
|
2281
|
+
if (name === "bash") {
|
|
2282
|
+
const k = clip(args, 200);
|
|
2283
|
+
const c = cmdCount.get(k);
|
|
2284
|
+
if (c) c.n++; else cmdCount.set(k, { n: 1, first: i + 1 });
|
|
2285
|
+
}
|
|
2286
|
+
if (name === "flow" || name === "flow_stage") out.push(`${L} ${name} ${clip(name === "flow" ? args : `${String(a.op ?? "")} ${String(a.note ?? "")}`, 300)}`);
|
|
2287
|
+
}
|
|
2288
|
+
} else if (m.role === "toolResult") {
|
|
2289
|
+
const call = calls.get(String(m.toolCallId ?? ""));
|
|
2290
|
+
const name = call?.name ?? m.toolName ?? "?";
|
|
2291
|
+
const res = textOf(m.content);
|
|
2292
|
+
if (m.isError) {
|
|
2293
|
+
errors++;
|
|
2294
|
+
out.push(`${L} ERROR ${name}${call ? ` (call L${call.line}: ${clip(call.args, 160)})` : ""} → ${clip(res, 400)}`);
|
|
2295
|
+
} else if (name === "flow" || name === "flow_stage") {
|
|
2296
|
+
out.push(`${L} ↳ ${clip(res, name === "flow_stage" ? 600 : 400)}`);
|
|
2297
|
+
} else if (/NEEDS-OPERATOR/.test(res.slice(0, 600))) {
|
|
2298
|
+
out.push(`${L} GUARD ${name}${call ? ` (call L${call.line}: ${clip(call.args, 160)})` : ""} → ${clip(res, 300)}`);
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
2301
|
+
}
|
|
2302
|
+
const repeats = [...cmdCount.entries()].filter(([, c]) => c.n >= 3).sort((a, b) => b[1].n - a[1].n).slice(0, 15);
|
|
2303
|
+
const head = [
|
|
2304
|
+
`digest: ${entries} entries, ${toolCalls} tool calls, ${errors} tool errors${first ? `, ${first} → ${last}` : ""}`,
|
|
2305
|
+
"(L<n> = line in the raw JSONL — open it with: sed -n '<n>p' <file> | jq . — only when a row needs context)",
|
|
2306
|
+
...(repeats.length ? ["repeated shell commands (≥3×):", ...repeats.map(([k, c]) => ` ×${c.n} from L${c.first}: ${k}`)] : []),
|
|
2307
|
+
"",
|
|
2308
|
+
];
|
|
2309
|
+
let body = out.join("\n");
|
|
2310
|
+
if (body.length > max) {
|
|
2311
|
+
// keep both ends: the start frames the task, the end holds the release and the operator's last words
|
|
2312
|
+
const half = Math.floor(max / 2);
|
|
2313
|
+
body = `${body.slice(0, half)}\n… (digest clipped — ${body.length - max} chars dropped from the middle; grep the raw JSONL for that span) …\n${body.slice(-half)}`;
|
|
2314
|
+
}
|
|
2315
|
+
return [...head, body].join("\n");
|
|
2316
|
+
}
|
|
2317
|
+
|
|
2142
2318
|
/** A pi session file and the `parentSession` its header names (line 1 of the JSONL). */
|
|
2143
2319
|
export interface SessionHeaderInfo {
|
|
2144
2320
|
file: string;
|
|
@@ -2180,6 +2356,12 @@ export interface ReflectBriefInput {
|
|
|
2180
2356
|
selfRepo: boolean;
|
|
2181
2357
|
/** open issues on this project's own GitHub repo (the read-time fold), when gh could list them */
|
|
2182
2358
|
projectIssues?: { repo: string; issues: { number: number; title: string }[] };
|
|
2359
|
+
/** the upstream dev-flow repo's issues (all states), prefetched so dedupe is a read, not a gh loop */
|
|
2360
|
+
upstreamIssues?: { number: number; title: string; state: string }[];
|
|
2361
|
+
/** pre-built transcript digests (driver first), one per transcript, in the feature's scratch dir */
|
|
2362
|
+
digests?: { transcript: string; digest: string }[];
|
|
2363
|
+
/** the wall-clock budget the worker runs under, in minutes */
|
|
2364
|
+
budgetMin?: number;
|
|
2183
2365
|
note: string;
|
|
2184
2366
|
}
|
|
2185
2367
|
|
|
@@ -2190,6 +2372,9 @@ export function buildReflectBrief(o: ReflectBriefInput): string {
|
|
|
2190
2372
|
const up = o.upstream || "(unknown — say so in the REPORT)";
|
|
2191
2373
|
const open = o.items.length ? o.items.map((it, i) => ` ${i + 1}. [${it.section}] ${it.line.replace(/^- \[ \] /, "")}`).join("\n") : " (none)";
|
|
2192
2374
|
const kids = o.children.length ? o.children.map((c) => ` - ${c.file}${c.name ? ` (${c.name})` : ""}`).join("\n") : " (none — no flow_stage worker ran in this session)";
|
|
2375
|
+
const digests = o.digests?.length ? o.digests.map((d) => ` - ${d.digest} (of ${path.basename(d.transcript)})`).join("\n") : "";
|
|
2376
|
+
const upIssues = o.upstreamIssues ? (o.upstreamIssues.length ? o.upstreamIssues.map((i) => ` gh#${i.number} [${i.state.toLowerCase()}] ${i.title}`).join("\n") : " (none)") : "";
|
|
2377
|
+
const budget = o.budgetMin ? `${o.budgetMin} min` : "a fixed wall-clock budget";
|
|
2193
2378
|
const issues = o.projectIssues ? (o.projectIssues.issues.length ? o.projectIssues.issues.map((i) => ` gh#${i.number} ${i.title}`).join("\n") : " (none open)") : "";
|
|
2194
2379
|
return [
|
|
2195
2380
|
`You are a fresh, independent reviewer of the dev-flow session for feature \`${o.slug}\`: find what went wrong or was slow, and say where each fix belongs.`,
|
|
@@ -2198,17 +2383,24 @@ export function buildReflectBrief(o: ReflectBriefInput): string {
|
|
|
2198
2383
|
`- Repo (your cwd): ${o.root} — today is ${o.today}`,
|
|
2199
2384
|
`- Driver session transcript (read it in full): ${o.driverFile ?? "(unknown — the session is not file-backed; say so and review what you can)"}`,
|
|
2200
2385
|
`- Sub-agent (flow_stage worker) transcripts:\n${kids}`,
|
|
2201
|
-
|
|
2386
|
+
...(digests
|
|
2387
|
+
? [`- **Start here — digests already built for you** (operator messages, flow calls and answers, tool errors, guard refusals, repeated commands; each row tagged L<n> = its line in the raw JSONL). Read these in full; open a raw entry only when a row needs context (sed -n '<n>p' <file> | jq .). Do not re-dump the raw transcripts:\n${digests}`]
|
|
2388
|
+
: ["- Transcripts are pi JSONL, one entry per line (type session / message / custom …; messages carry role, content, tool calls and tool results). Skim with jq or grep — e.g. jq -c 'select(.type==\"message\")' <file> — for tool errors, guard or gate refusals, NEEDS-OPERATOR, retries, repeated commands, operator corrections; then read the surrounding entries."]),
|
|
2202
2389
|
`- This project's playbook: ${o.projectMd}`,
|
|
2203
2390
|
`- This project's reflection queue: ${o.reflectionsFile} — open items:\n${open}`,
|
|
2204
2391
|
`- dev-flow ${o.version ?? "(version unknown)"}; upstream repo: ${up}${o.selfRepo ? " — this checkout IS dev-flow, so plugin findings are this project's code findings" : ""}`,
|
|
2205
|
-
...(o.
|
|
2392
|
+
...(o.upstreamIssues && o.upstream
|
|
2393
|
+
? [`- Issues on ${o.upstream} (all states) — dedupe plugin findings against this list; cite gh#N when one covers it. Run gh issue view <N> --repo ${o.upstream} only for a likely match:\n${upIssues}`]
|
|
2394
|
+
: o.upstream && !o.selfRepo
|
|
2395
|
+
? [`- Dedupe plugin findings upstream (read-only): gh issue list --repo ${o.upstream} --state all --search "<keywords>" — cite gh#N when one covers it (fixed / won't-fix / open).`]
|
|
2396
|
+
: []),
|
|
2206
2397
|
...(o.projectIssues ? [`- Open issues on this project's repo ${o.projectIssues.repo}:\n${issues}`] : []),
|
|
2207
|
-
"- You hold no flow tool and write nothing: no file edits, no commits, no gh issue create. The driving session and the operator decide.",
|
|
2398
|
+
"- You hold no flow tool and write nothing: no file edits, no commits, no gh issue create, no scratch dumps outside $TMPDIR. The driving session and the operator decide.",
|
|
2399
|
+
`- Budget: ${budget}, wall clock. Aim to write the REPORT by about 60% of it; an interrupted run loses every finding.`,
|
|
2208
2400
|
"",
|
|
2209
2401
|
"## Your task",
|
|
2210
2402
|
o.note.trim() ? `Operator context: ${o.note.trim()}` : "(no extra context from the driver)",
|
|
2211
|
-
"1. Review the transcripts for real friction only: wrong turns, repeated failures, misfiring guards or gates, playbook drift, slow paths with an obvious fix. One-off typos, environment hiccups and things already fixed later in the session are not findings.",
|
|
2403
|
+
"1. Review the transcripts for real friction only: wrong turns, repeated failures, misfiring guards or gates, playbook drift, slow paths with an obvious fix. One-off typos, environment hiccups and things already fixed later in the session are not findings. You review the session, not the product: evidence is a transcript line — do not re-audit the project's source to second-guess what the session shipped.",
|
|
2212
2404
|
`2. Classify each finding: docs — the fix lives only in this project's playbook (project.md) → docs flow; code — the fix touches this project's code (maybe the playbook too) → patch flow; plugin — dev-flow's own behaviour or wording → upstream GitHub issue${o.selfRepo ? " (here: report it as code)" : ""}.`,
|
|
2213
2405
|
"3. Dedupe each finding against the open items above and the issues; a finding an open item already covers is not new — mark that item recurred instead.",
|
|
2214
2406
|
"4. Recommend fold (worth recording / filing) or drop (one-off, environmental, operator choice, already covered) with a one-clause reason.",
|
package/src/projectmd.ts
CHANGED
|
@@ -189,9 +189,16 @@ export function parseProjectMd(text: string): ParsedMd {
|
|
|
189
189
|
if (!stage || stage === "global" || !MD_STAGES.includes(stage as MdStage)) return; // preamble/unknown → not injected
|
|
190
190
|
const item = line.match(CHECK_ITEM);
|
|
191
191
|
if (item) {
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
192
|
+
// qualifiers lead the item in any order: (ui) = --ui features only, (versioned) = not on a --no-version flow
|
|
193
|
+
let text = item[1].trim();
|
|
194
|
+
let uiOnly = false;
|
|
195
|
+
let versionedOnly = false;
|
|
196
|
+
for (let q = /^\((ui|versioned)\)\s+/.exec(text); q; q = /^\((ui|versioned)\)\s+/.exec(text)) {
|
|
197
|
+
if (q[1] === "ui") uiOnly = true;
|
|
198
|
+
else versionedOnly = true;
|
|
199
|
+
text = text.slice(q[0].length);
|
|
200
|
+
}
|
|
201
|
+
(p.checklist[stage] ??= []).push(versionedOnly ? { text, uiOnly, versionedOnly } : { text, uiOnly });
|
|
195
202
|
return;
|
|
196
203
|
}
|
|
197
204
|
if (/^(#|```|<!--|\s*$)/.test(line) && !line.startsWith("### ")) return; // h1/html comments/blank are not prose
|
|
@@ -508,7 +515,7 @@ export function mdDigest(text: string): string {
|
|
|
508
515
|
}
|
|
509
516
|
if (s === "pre-release" && !keys.file && !p.flow.release["versioning.file"]) bits.push("version: no version file set — releases cannot bump or tag");
|
|
510
517
|
const items = p.checklist[s] ?? [];
|
|
511
|
-
if (items.length) bits.push(`manual check: ${items.map((i) => `${i.uiOnly ? "(UI only) " : ""}\"${i.text}\"`).join(" · ")}`);
|
|
518
|
+
if (items.length) bits.push(`manual check: ${items.map((i) => `${i.uiOnly ? "(UI only) " : ""}${i.versionedOnly ? "(versioned only) " : ""}\"${i.text}\"`).join(" · ")}`);
|
|
512
519
|
if (p.prose[s]) bits.push(`guidance: "${p.prose[s].replace(/\s+/g, " ").trim()}"`);
|
|
513
520
|
if (bits.length) rows.push(`${label} — ${bits.join(" · ")}`);
|
|
514
521
|
}
|