pi-dev-flow 0.84.0 → 0.85.1
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 +25 -0
- package/docs/concurrency.md +15 -0
- package/docs/gates.md +5 -3
- package/docs/guardrails.md +1 -1
- package/docs/playbook.md +18 -0
- package/extensions/dev-flow.ts +267 -20
- package/package.json +4 -2
- package/skills/dev-flow/SKILL.md +6 -5
- package/skills/dev-flow/references/implement.md +13 -3
- package/src/core.ts +56 -1
- package/src/projectmd.ts +15 -1
- package/src/timeouts.ts +52 -17
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,31 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
|
|
|
4
4
|
|
|
5
5
|
## [Unreleased]
|
|
6
6
|
|
|
7
|
+
## [0.85.1] - 2026-11-08
|
|
8
|
+
|
|
9
|
+
**dev-flow's bash timeout says so when it kills a command, and a command's own `timeout N` sets the cap.**
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
- **A command's own `timeout N` sets its cap.** `timeout 600 bun test` used to get the 120s default class, because `timeout` was read as the command, so dev-flow would kill a long test run at two minutes even though the agent had asked for ten. A `timeout`/`gtimeout` wrapper now gives N + 15s, so the shell's own timer fires first. Option forms such as `-k 5` and `-s KILL` and `s`/`m`/`h` suffixes are understood, and an unreadable N falls back to the wrapped command's class.
|
|
13
|
+
- **dev-flow loads outside pi on pi 1.5.0.** The extension imported TypeBox's `Type` from `@earendil-works/pi-ai`, which the published 1.5.0 package no longer exports; only pi's own loader still provided it. It now imports from `typebox`, which is declared as a peer dependency, and the tests run against pi 1.5.0, the version pi-web runs.
|
|
14
|
+
|
|
15
|
+
### Changed
|
|
16
|
+
- **dev-flow's silent bash timeout says so when it kills a command.** The timeout dev-flow arms on a call that states none never appears in the transcript or pi-web's tool card, so since 0.73.0 it looked as if no timeout was being set. It was: an end-to-end run under pi 1.5.0 killed a 60s command at 30s. Now a kill by that default appends `[dev-flow] stopped at <N>s: dev-flow's default for <class> commands…` to the result, and the always-on ground rules tell the agent the default exists and how to ask for longer. A new end-to-end test drives a real pi session to prove the kill happens.
|
|
17
|
+
|
|
18
|
+
## [0.85.0] - 2026-11-08
|
|
19
|
+
|
|
20
|
+
**`flow verify` deploys for review without a dialog, catches up with main first, and asks before taking another flow's dev port.**
|
|
21
|
+
|
|
22
|
+
### Fixed
|
|
23
|
+
- **The agent's `flow` call never opens a dialog** (fixes #181). In pi-web a bare `flow verify` deployed, then sat in a Yes/No dialog inside the tool call: once for 87 minutes, during which nobody could talk to the agent. Another time the operator clicked Yes, the result did not say so, and the agent reported that the stage had advanced on its own. Now every gate the agent calls answers with `NEEDS-OPERATOR <Question?>` and the agent asks in chat. A `/flow` command you type still asks in a dialog, and its answer is labelled `(confirmed in dialog)`.
|
|
24
|
+
- **`flow verify` reviews the tree that ships.** A branch 18 commits behind main was deployed for review, without the two releases that had just shipped, and verified that way. Now `flow verify` fetches and rebases a branch that is behind before it deploys. A conflict aborts the rebase and leaves the branch as it was. `flow verify --confirmed` refuses when main moved since the review deploy.
|
|
25
|
+
- **The post-Verified? warning at `flow release` lists only the branch's own commits** (fixes #180). Commits merged in from main are a count (`+N merged in from main, not listed`).
|
|
26
|
+
|
|
27
|
+
### Added
|
|
28
|
+
- **The bare `flow verify` is the review deploy.** It runs checks, build, `dev` and the health probe, then returns `deployed for review` with the question to ask. `flow verify --confirmed` records the answer.
|
|
29
|
+
- **Parallel flows no longer overwrite each other's dev deploy silently.** `flow verify` records who deployed on which port, and `flow status` shows it. When the port belongs to another live flow, verify asks first, with the free RAM and disk against the playbook's `instanceMem`/`instanceDisk`. The options are: run alongside on the next free port (`--port=<n>`), replace (`--replace`), or wait. New `## implement` keys: `port`, `parallelDev`, `instanceMem`, `instanceDisk`, `devDown` (run by `flow finish` for a side-port instance) and `servedBuild`. `dev`, `health` and `servedBuild` get `$DEV_FLOW_PORT`, `$DEV_FLOW_INSTANCE` and `$DEV_FLOW_SUFFIX`.
|
|
30
|
+
- **`servedBuild`** proves the deployed app serves the worktree's HEAD. Verify refuses when it doesn't.
|
|
31
|
+
|
|
7
32
|
## [0.84.0] - 2026-11-05
|
|
8
33
|
|
|
9
34
|
**A yolo given early no longer ships commits nobody saw, and per-machine ignored files are writable without a flow.**
|
package/docs/concurrency.md
CHANGED
|
@@ -28,6 +28,21 @@ binding, so `flow status` prints the key and says so instead of leaving a shared
|
|
|
28
28
|
guessed from a path. Dev-flow keeps no per-process session state beyond that keyed map, released on
|
|
29
29
|
shutdown; the one other process-wide cache (`compile()` in `src/core.ts`) holds flag-less regexes,
|
|
30
30
|
which carry no mutable state to leak between sessions.
|
|
31
|
+
**One dev stack, several flows.** A dev deploy is machine state, not branch state, so `flow verify`
|
|
32
|
+
keeps a small registry (`.dev-flow/dev-ports.json`: port → slug, commit, time) and `flow status` prints
|
|
33
|
+
it (`dev: port 8090 → <slug> @ <sha>`). Before deploying, verify checks whether its port was last
|
|
34
|
+
deployed by **another live flow**. If so it does not deploy: it returns `NEEDS-OPERATOR Dev port?` with
|
|
35
|
+
who holds the port (stage, commit, age), the available RAM and free disk against the playbook's
|
|
36
|
+
`instanceMem` / `instanceDisk`, and the options — run alongside on the next free port
|
|
37
|
+
(`flow verify --port=<n>`), replace that deploy (`--replace`), or wait. Running alongside is offered
|
|
38
|
+
only when the playbook allows it (`parallelDev` is not `no`, `dev`/`health` read `$DEV_FLOW_PORT`) and
|
|
39
|
+
the resources fit. A finished or aborted flow holds no port. `flow finish` stops a flow's
|
|
40
|
+
non-default-port instance with `devDown`.
|
|
41
|
+
|
|
42
|
+
**The review is of the tree that ships.** Parallel flows release while others are still implementing,
|
|
43
|
+
so `flow verify` rebases a branch that fell behind the default branch before it deploys for review,
|
|
44
|
+
and `flow verify --confirmed` refuses if the default branch moved again before the answer.
|
|
45
|
+
|
|
31
46
|
Enforcement is by attribution: a write inside worktree X is judged
|
|
32
47
|
by X's own feature stage no matter which session touches it; main-checkout code stays closed
|
|
33
48
|
while your bound feature is in `plan`/`implement` and while any feature is unbound-and-ambiguous.
|
package/docs/gates.md
CHANGED
|
@@ -4,8 +4,10 @@ Every gate, what it advances, and what makes it refuse.
|
|
|
4
4
|
|
|
5
5
|
You normally type none of this: the agent runs the gates and you answer words in chat. `/flow <sub>` is
|
|
6
6
|
your **manual surface** — read state when the agent is confused, or advance a gate yourself when it is
|
|
7
|
-
stuck or claims a result it never ran. Same gates either way;
|
|
8
|
-
so it needs no `--confirmed`.
|
|
7
|
+
stuck or claims a result it never ran. Same gates either way; a `/flow` command you type asks you in a dialog,
|
|
8
|
+
so it needs no `--confirmed`. The agent's own `flow` call never opens a dialog (#181): it returns
|
|
9
|
+
`NEEDS-OPERATOR <Question?>` and the agent asks you in chat. A dialog answer is labelled
|
|
10
|
+
`(confirmed in dialog)`, a chat answer `(confirmed by operator instruction)`.
|
|
9
11
|
|
|
10
12
|
| Gate | Advances | Refuses unless |
|
|
11
13
|
|---|---|---|
|
|
@@ -15,7 +17,7 @@ so it needs no `--confirmed`.
|
|
|
15
17
|
| `test` | records a check | — (runs the `test` command/check, records pass/fail) |
|
|
16
18
|
| `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
19
|
| `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 — 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 |
|
|
20
|
+
| `verify [--yolo] [--port=<n>\|--replace]` | implement → pre-release | **without `--confirmed` it is the review deploy**: it fetches and, when the branch is behind `origin/<default>` (or local `<default>` with no remote), **rebases** it — untracked files never block, uncommitted tracked edits and conflicts refuse (the rebase is aborted, the branch untouched); when the dev port (playbook `port`, or the whole stack when none is set) was last deployed by **another live flow** it refuses with `NEEDS-OPERATOR Dev port?`, the measured RAM/disk against `instanceMem`/`instanceDisk`, and the options: run alongside on the next free port (offered only when `parallelDev` is not `no`, `dev`/`health` read `$DEV_FLOW_PORT`, and the resources fit), `--replace`, or wait — nothing is built first; then it deploys and returns `deployed for review` with the chat question. **With `--confirmed`** it never rewrites history: a default branch that moved since refuses (re-run `flow verify`). With `servedBuild` set the served commit must be the worktree's HEAD. Otherwise: 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
21
|
| `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); a **standing yolo** (given at an earlier checkpoint) does not answer Release? when such commits exist, nor ever under `yolo = until-release` in `## release` — the gate returns NEEDS-OPERATOR Release? (gh#176), while `--confirmed` (the operator's answer, a yolo said at Release? included) still passes; **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
22
|
| `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
23
|
| `finish [--yolo] [--no-reflect] [--note=<text>] [slug]` | release → done — **first run the closing reflection**: while no reflection is recorded for the flow, finish starts the reflect worker before it touches anything and stops for the operator's fold/drop (or Finish? when nothing was found); the re-run with `--confirmed` does the cleanup. `--no-reflect --confirmed` skips it on the operator's explicit word (yolo never does); `--note=` hands the worker the operator's friction notes. Cleanup (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` |
|
package/docs/guardrails.md
CHANGED
|
@@ -14,7 +14,7 @@ While a feature is active, the extension intercepts every tool call:
|
|
|
14
14
|
- **Your project's own rules**: every `deny`/`confirm`/`protect`/`forbid` rule from the `flow-guard` block in project.md `## global` runs on every bash command and every edit/write path — in every stage and binding, ahead of dev-flow's own verdicts. A block always carries the reason you wrote.
|
|
15
15
|
- **The rules reach the agent, they are not left in a file it may never read**: pi advertises a skill and loads it only if the model chooses to, so the ground rules of the dev-flow skill are injected into every session once (and again after a compaction that summarized them away), and each stage's turn names the one playbook file that stage needs. The guards enforce the same discipline either way — this is what makes the agent follow it without being stuck.
|
|
16
16
|
- **A forced push asks the operator**: `git push` carrying `--force`, `--force-with-lease…` or `-f` is confirmed before it runs — a rewritten branch is history CI and other sessions already have. The one spelling that answers for it is the prefix the refusal prints (`DEV_FLOW_ALLOW_REWRITE=1 git push -f …`), the same "the operator said so" contract as `DEV_FLOW_ALLOW_MAIN`. Local history rewrites (`git filter-branch --force`) are not pushes and stay free, so a project never needs a blunt flag-only deny of its own.
|
|
17
|
-
- **Shell calls can't hang forever**: pi kills a shell command only when the model passed a `timeout` — it omits one in ~75% of calls, so a `gh` waiting on a prompt or a dead `curl` froze sessions for hours. In an initiated repo (`.dev-flow/project.md` exists) every shell call without one therefore gets the class default armed silently (30s quick inspection · 120s local git and unknown · 180s network · 300s containers/services · 900s builds/tests/installs · 1,200s watchers like `gh run watch`), and absurd explicit values clamp to 1,800s. A project that wants the timeout visible on every call line sets `bashTimeout = require` in `## global` — then a call without one is refused, naming the value it would have armed (each refusal costs a turn, which is why it is no longer the default). Uninitiated folders hear nothing at all: without the playbook dev-flow enforces no rules.
|
|
17
|
+
- **Shell calls can't hang forever**: pi kills a shell command only when the model passed a `timeout` — it omits one in ~75% of calls, so a `gh` waiting on a prompt or a dead `curl` froze sessions for hours. In an initiated repo (`.dev-flow/project.md` exists) every shell call without one therefore gets the class default armed silently (30s quick inspection · 120s local git and unknown · 180s network · 300s containers/services · 900s builds/tests/installs · 1,200s watchers like `gh run watch`), and absurd explicit values clamp to 1,800s. A command that carries its own `timeout N` (coreutils, any option form, `s`/`m`/`h` suffixes) gets N + 15s, so its own timer fires first; an unreadable N falls back to the wrapped command's class. The armed value is **invisible in the call's arguments**: the transcript and pi-web's tool card show what the model wrote, and dev-flow sets the timeout after that. So when it is dev-flow's default that kills a command, the result gets a line saying so (`[dev-flow] stopped at 30s: dev-flow's default for quick commands, armed because the call stated no timeout…`), and the session's injected ground rules tell the agent the default exists. `test/e2e-timeout.test.ts` proves the kill end to end through a real pi session, so a host release that stopped honouring the hook would fail the suite. A project that wants the timeout visible on every call line sets `bashTimeout = require` in `## global` — then a call without one is refused, naming the value it would have armed (each refusal costs a turn, which is why it is no longer the default). Uninitiated folders hear nothing at all: without the playbook dev-flow enforces no rules.
|
|
18
18
|
- **Compact-aware**: dev-flow paces compaction the way pi counts it: the self-compaction trigger uses the *effective* `reserveTokens` (settings and per-model overrides, not the built-in default) and is checked at every turn end, not only when a run settles. When pi force-compacts on its threshold anyway — the chat-only states (open tier-2 dialog, plan discussion not yet in `plan/`) refuse to self-compact by design — dev-flow takes the compaction over and redoes it with flow-aware summary instructions (overflow recovery keeps pi's compact-and-retry and is left alone). Auto-compaction turned off in settings is honored.
|
|
19
19
|
- The active stage is injected into the model's context every turn; the bundled `dev-flow` skill is the agent's playbook, including the recommended sequences: pre-release — review (`/flow-review`) → fixes → docs → changelog/version bump; release — PR → merge → tag → `release-done`. The package also bundles the review skills themselves — `/flow-review` (a change, read against its `plan/plan.md`), `/flow-audit` (the whole repo) and `/flow-simplify` (the operative cut: deletes dead and duplicated code, one verified commit at a time) — and injects a built-in senior-discipline guidance at implement stage unless the playbook sets its own `prose.implement`.
|
|
20
20
|
- **Status bar**: an initiated repo (`.dev-flow/project.md` exists) always carries the dev-flow footer; while the session **is bound** to a feature it shows `<stage glyph> <slug>` plus mode markers — stages 📝 plan, 🔨 implement, 🔍 pre-release, 🚀 release; markers ⚡ patch, 📚 docs, 🎱 yolo, `💬` while a checkpoint (Approve?/Verified?/Release?/Finish?) still waits on the operator's word — the legend's "operator, your turn" glyph, the same one stage lines open with — and `⚠️` while a check of the bound feature fails (emoji render in their own color, so the footer carries no theme coloring). An **unbound** session never sees a slug — it shows `💬 N flow(s) open` (unfinished-feature count only, no warning marker) or `💬 no flows` when nothing is in flight: the pre-flow glyph, because an unbound session is parked on the operator by definition; a session binds only via `flow start`/`flow use`, never by opening. In **pi-web** status text is not clickable, so there the footer is a widget chip instead: the chip carries the footer's content packed to fit pi-web's fixed-width chip — bound: every glyph up front with no spaces, then the slug (`🔨⚡⚠️my-feature`, so only the slug's tail can clip); unbound: `💬 2 open` (hover shows a clipped label whole) and expands (click again to collapse) to one lean line per *other* unfinished flow — the bound flow is already the chip's label, so it is not repeated (alone in the repo, the panel says `no other flows open`); the stage word is spelled out, markers and `⚠️` follow the footer vocabulary; with nothing open (`💬 no flows`) it is a plain chip with nothing to expand. The TUI never shows it: a widget there is an always-present block, and in a terminal the footer stays the legend. The footer repaints at session start, at the start of every agent run (the earliest a late-attaching web client is listening) and after every gate; an uninitiated folder gets no footer at all. `flow status` is the spelled-out surface: `stage=implement`, the per-feature mode tags (`[ui]`, `[yolo]`, `[no-version]`), the `💬 <word>` marker of a checkpoint the operator has not answered, and the `flow=<ver>` stamp of the build that started the feature.
|
package/docs/playbook.md
CHANGED
|
@@ -76,6 +76,24 @@ Prefer feature flags for risky paths.
|
|
|
76
76
|
whose readiness lags its container start needs a wait, not a poll loop hand-written into the playbook.
|
|
77
77
|
`healthWait = 0` restores the single shot.
|
|
78
78
|
|
|
79
|
+
**Dev port and parallel flows.** Two flows on one machine share one dev stack unless you say otherwise:
|
|
80
|
+
|
|
81
|
+
```flow
|
|
82
|
+
port = 8090 # the default dev port — exported to dev/health/servedBuild as $DEV_FLOW_PORT
|
|
83
|
+
parallelDev = yes # can two instances run side by side? (no = only replace or wait are offered)
|
|
84
|
+
instanceMem = 2G # what one instance needs — checked against available RAM
|
|
85
|
+
instanceDisk = 5G # …and against free disk
|
|
86
|
+
dev = BFF_PORT=$DEV_FLOW_PORT COMPOSE_PROJECT_NAME=app$DEV_FLOW_SUFFIX docker compose up -d
|
|
87
|
+
devDown = COMPOSE_PROJECT_NAME=app$DEV_FLOW_SUFFIX docker compose down
|
|
88
|
+
servedBuild = curl -fsS http://127.0.0.1:$DEV_FLOW_PORT/version # must print the served commit
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`$DEV_FLOW_SUFFIX` is empty on the default port and `-<slug>` on any other, so a second instance gets its own
|
|
92
|
+
compose project. `flow verify` records who deployed on which port in `.dev-flow/dev-ports.json`; when the
|
|
93
|
+
port it would use belongs to another live flow it asks you first (see [concurrency](concurrency.md)).
|
|
94
|
+
`flow finish` runs `devDown` for an instance on a non-default port. `servedBuild` turns "something answers"
|
|
95
|
+
into "this branch answers": verify refuses when its output names no prefix of the worktree's HEAD.
|
|
96
|
+
|
|
79
97
|
Your project's own safety rules are a `flow-guard` block in `## global` — the reason a project
|
|
80
98
|
adopting dev-flow can delete its own guard extension:
|
|
81
99
|
|
package/extensions/dev-flow.ts
CHANGED
|
@@ -20,10 +20,12 @@
|
|
|
20
20
|
* Inactive (fully pass-through) in repos without a .dev-flow/ directory.
|
|
21
21
|
*/
|
|
22
22
|
import { exec } from "node:child_process";
|
|
23
|
-
import { closeSync, copyFileSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
23
|
+
import { closeSync, copyFileSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statfsSync, writeFileSync } from "node:fs";
|
|
24
|
+
import { createServer } from "node:net";
|
|
25
|
+
import { freemem } from "node:os";
|
|
24
26
|
import path from "node:path";
|
|
25
27
|
import { promisify } from "node:util";
|
|
26
|
-
import { Type } from "
|
|
28
|
+
import { Type } from "typebox";
|
|
27
29
|
import { compact, createAgentSession, DefaultResourceLoader, defineTool, getAgentDir, isToolCallEventType, SessionManager, SettingsManager, type AgentSession, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
28
30
|
import type { ExtensionAPI, ToolCallEvent, ToolCallEventResult } from "@earendil-works/pi-coding-agent";
|
|
29
31
|
import {
|
|
@@ -147,6 +149,10 @@ import {
|
|
|
147
149
|
releaseOrderInvocation,
|
|
148
150
|
type BranchState,
|
|
149
151
|
type Config,
|
|
152
|
+
type DevSlot,
|
|
153
|
+
formatSize,
|
|
154
|
+
servedBuildMatches,
|
|
155
|
+
sideBySide,
|
|
150
156
|
type FeatureRef,
|
|
151
157
|
type FlowState,
|
|
152
158
|
type StageCheck,
|
|
@@ -155,7 +161,7 @@ import {
|
|
|
155
161
|
} from "../src/core.ts";
|
|
156
162
|
import { applyAnswers, buildDraft, doctorFindings, ghostFeatureDirs, lineDiff, loadProject, mdDigest, parseAnswers, parseProjectMd, setPlaybookKey } from "../src/projectmd.ts";
|
|
157
163
|
import { dedupeReflections, linkedTag, parseGhIssues, similarNote, type FoldResult, type GhIssue } from "../src/fold.ts";
|
|
158
|
-
import { bashTimeout, requireTimeout } from "../src/timeouts.ts";
|
|
164
|
+
import { bashTimeout, requireTimeout, timeoutClass } from "../src/timeouts.ts";
|
|
159
165
|
import { detectProject, type Detection } from "../src/detect.ts";
|
|
160
166
|
|
|
161
167
|
const execAsync = promisify(exec);
|
|
@@ -235,7 +241,7 @@ function copyWarning(): string | null {
|
|
|
235
241
|
}
|
|
236
242
|
/** Test seam: the smoke suite cannot load a second copy of this module, so it plants registry
|
|
237
243
|
* entries and asserts the warnings the real duplicate would print. */
|
|
238
|
-
export const testSeams = { copies: COPIES, skillCore: { value: undefined as string | null | undefined }, piweb: { meta: piwebWorkerMeta, stamp: piwebStamp, liveClaim: piwebLiveClaim, workerName } };
|
|
244
|
+
export const testSeams = { copies: COPIES, skillCore: { value: undefined as string | null | undefined }, bashTimeout: { cap: undefined as number | undefined }, piweb: { meta: piwebWorkerMeta, stamp: piwebStamp, liveClaim: piwebLiveClaim, workerName } };
|
|
239
245
|
|
|
240
246
|
interface Ui {
|
|
241
247
|
hasUI: boolean;
|
|
@@ -385,7 +391,7 @@ async function releaseTags(root: string): Promise<string[] | null> {
|
|
|
385
391
|
}
|
|
386
392
|
|
|
387
393
|
const GATE_HELP =
|
|
388
|
-
"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> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|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] [--no-reflect] [--note=<text>] [slug] | abort [slug] | version [--check-upstream] — state gates take [slug] and --confirmed (the operator already answered in chat); without it
|
|
394
|
+
"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> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|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] [--port=<n>|--replace] | release [--yolo|--no-version|--no-fold-check|--no-marker-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [--no-reflect] [--note=<text>] [slug] | abort [slug] | version [--check-upstream] — state gates take [slug] and --confirmed (the operator already answered in chat); without it the agent's call returns NEEDS-OPERATOR with the question to ask in chat (it never opens a dialog), and the /flow slash command asks in a dialog — verify without --confirmed rebases a branch that is behind the default branch and deploys for review; --port=<n> / --replace answer its Dev port? question when another flow holds the stack — --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 — finish runs the closing reflection worker first (before removing anything) and stops for the operator's fold/drop; the re-run with --confirmed cleans up; --no-reflect --confirmed skips it on the operator's explicit word (yolo never does), --note= hands the worker the operator's friction notes — 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> (or add --slug=) stamps an item for flow start, which seeds the new plan from its brief; finish checks it off — a new feature asked for mid-flow is parked there, never as a hand-made .dev-flow/<slug>/; start <slug> --confirmed adopts such a ghost dir — 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)";
|
|
389
395
|
const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
|
|
390
396
|
const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
|
|
391
397
|
const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
|
|
@@ -629,6 +635,159 @@ function featureEnv(root: string, state: FlowState): Record<string, string> {
|
|
|
629
635
|
return featureTmpEnv(dir);
|
|
630
636
|
}
|
|
631
637
|
|
|
638
|
+
/** The port this flow's dev deploy uses: the operator's pick for it, else the playbook default. */
|
|
639
|
+
const devPortOf = (state: FlowState, cfg: Config): number | undefined => state.devPort ?? cfg.devPort;
|
|
640
|
+
|
|
641
|
+
/** featureEnv plus where this flow's dev instance lives: $DEV_FLOW_PORT, $DEV_FLOW_INSTANCE (the slug) and
|
|
642
|
+
* $DEV_FLOW_SUFFIX — "" on the default port, "-<slug>" on another — for a compose project name or container
|
|
643
|
+
* prefix that must not collide with the instance already running. */
|
|
644
|
+
function devEnv(root: string, state: FlowState, cfg: Config): Record<string, string> {
|
|
645
|
+
const port = devPortOf(state, cfg);
|
|
646
|
+
const side = state.devPort !== undefined && state.devPort !== cfg.devPort;
|
|
647
|
+
return { ...featureEnv(root, state), ...(port !== undefined ? { DEV_FLOW_PORT: String(port) } : {}), DEV_FLOW_INSTANCE: state.slug, DEV_FLOW_SUFFIX: side ? `-${state.slug}` : "" };
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// ---------------------------------------------------------------- dev stack registry
|
|
651
|
+
// One machine, one dev port, several flows: who deployed last is what decides whether a verify may
|
|
652
|
+
// redeploy there or must ask first. Keyed by port ("default" when the playbook names none).
|
|
653
|
+
const devPortsFile = (root: string) => path.join(dfDir(root), "dev-ports.json");
|
|
654
|
+
const slotKey = (port: number | undefined) => (port === undefined ? "default" : String(port));
|
|
655
|
+
|
|
656
|
+
/** Live slots only: a slot whose flow finished (state.json gone) or was aborted holds nothing. */
|
|
657
|
+
function readDevPorts(root: string): Record<string, DevSlot> {
|
|
658
|
+
let raw: Record<string, DevSlot>;
|
|
659
|
+
try {
|
|
660
|
+
raw = JSON.parse(readFileSync(devPortsFile(root), "utf8")) as Record<string, DevSlot>;
|
|
661
|
+
} catch {
|
|
662
|
+
return {};
|
|
663
|
+
}
|
|
664
|
+
return Object.fromEntries(
|
|
665
|
+
Object.entries(raw).filter(([, v]) => {
|
|
666
|
+
const st = v?.slug ? readState(root, v.slug) : null;
|
|
667
|
+
return !!st && !st.aborted;
|
|
668
|
+
}),
|
|
669
|
+
);
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
function writeDevPorts(root: string, reg: Record<string, DevSlot>): void {
|
|
673
|
+
atomicWrite(devPortsFile(root), `${JSON.stringify(reg, null, "\t")}\n`);
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
function portFree(port: number): Promise<boolean> {
|
|
677
|
+
return new Promise((resolve) => {
|
|
678
|
+
const srv = createServer();
|
|
679
|
+
srv.once("error", () => resolve(false));
|
|
680
|
+
srv.listen(port, "127.0.0.1", () => srv.close(() => resolve(true)));
|
|
681
|
+
});
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
async function nextFreePort(from: number, taken: Set<number>): Promise<number | null> {
|
|
685
|
+
for (let p = from + 1; p < Math.min(from + 50, 65536); p++) if (!taken.has(p) && (await portFree(p))) return p;
|
|
686
|
+
return null;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/** MemAvailable (what a new process can really get) where Linux reports it, else the OS free figure. */
|
|
690
|
+
function memAvailable(): number | null {
|
|
691
|
+
try {
|
|
692
|
+
const m = readFileSync("/proc/meminfo", "utf8").match(/^MemAvailable:\s+(\d+)\s*kB/m);
|
|
693
|
+
if (m) return Number(m[1]) * 1024;
|
|
694
|
+
} catch {
|
|
695
|
+
/* not Linux */
|
|
696
|
+
}
|
|
697
|
+
const f = freemem();
|
|
698
|
+
return Number.isFinite(f) ? f : null;
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
function diskFreeAt(dir: string): number | null {
|
|
702
|
+
try {
|
|
703
|
+
const st = statfsSync(dir);
|
|
704
|
+
return Number(st.bavail) * Number(st.bsize);
|
|
705
|
+
} catch {
|
|
706
|
+
return null;
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
function ago(iso: string): string {
|
|
711
|
+
const min = Math.round((Date.now() - Date.parse(iso)) / 60_000);
|
|
712
|
+
if (!Number.isFinite(min)) return "at an unknown time";
|
|
713
|
+
return min < 1 ? "just now" : min < 90 ? `${min} min ago` : `${Math.round(min / 60)} h ago`;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
const portLabel = (port: number | undefined) => (port === undefined ? "the dev stack" : `port ${port}`);
|
|
717
|
+
|
|
718
|
+
/** Before a verify deploys: is the stack it would replace held by another live flow? Applies the
|
|
719
|
+
* operator's `--port=<n>` / `--replace` answer, or asks — with the measured resources — which to do. */
|
|
720
|
+
async function devSlotCheck(o: GateCtx, state: FlowState): Promise<RunResult | { note: string }> {
|
|
721
|
+
const { root, cfg, flag, rest } = o;
|
|
722
|
+
const portArg = flagValue(rest, "port");
|
|
723
|
+
if (portArg !== null) {
|
|
724
|
+
const n = Number(portArg);
|
|
725
|
+
if (!Number.isInteger(n) || n < 1 || n > 65535) return { text: `--port=${portArg} is not a port`, isError: true };
|
|
726
|
+
if (cfg.devPort === undefined) return { text: "--port needs a default `port` in the playbook's ## implement flow block — dev-flow exports the chosen one to dev/health as $DEV_FLOW_PORT", isError: true };
|
|
727
|
+
if (n === cfg.devPort) delete state.devPort;
|
|
728
|
+
else state.devPort = n;
|
|
729
|
+
writeState(root, state);
|
|
730
|
+
}
|
|
731
|
+
const port = devPortOf(state, cfg);
|
|
732
|
+
const reg = readDevPorts(root);
|
|
733
|
+
const slot = reg[slotKey(port)];
|
|
734
|
+
if (!slot || slot.slug === state.slug) return { note: "" };
|
|
735
|
+
if (flag("replace")) return { note: `dev: replaced ${slot.slug}'s deploy on ${portLabel(port)} (operator's answer)` };
|
|
736
|
+
const other = readState(root, slot.slug);
|
|
737
|
+
const taken = new Set(Object.keys(reg).map(Number).filter(Number.isFinite));
|
|
738
|
+
const nextPort = port !== undefined ? await nextFreePort(port, taken) : null;
|
|
739
|
+
const mem = memAvailable();
|
|
740
|
+
const disk = diskFreeAt(root);
|
|
741
|
+
const side = sideBySide({ cfg, nextPort, memAvail: mem, diskFree: disk });
|
|
742
|
+
const res = [
|
|
743
|
+
`RAM available ${mem !== null ? formatSize(mem) : "unknown"}${cfg.instanceMem !== undefined ? ` (one instance needs ${formatSize(cfg.instanceMem)})` : ""}`,
|
|
744
|
+
`disk free ${disk !== null ? formatSize(disk) : "unknown"}${cfg.instanceDisk !== undefined ? ` (one instance needs ${formatSize(cfg.instanceDisk)})` : ""}`,
|
|
745
|
+
].join(", ");
|
|
746
|
+
const caveat = side.ok
|
|
747
|
+
? cfg.parallelDev === undefined
|
|
748
|
+
? " The playbook does not say whether two instances can share this machine (parallelDev = yes|no) — tell the operator that when you ask."
|
|
749
|
+
: ""
|
|
750
|
+
: ` Running alongside is not offered: ${side.why.join("; ")}.`;
|
|
751
|
+
const opts = [
|
|
752
|
+
...(side.ok ? [`run alongside on port ${nextPort}: flow verify --port=${nextPort}`] : []),
|
|
753
|
+
`replace ${slot.slug}'s deploy: flow verify --replace`,
|
|
754
|
+
`wait until ${slot.slug} is done with it`,
|
|
755
|
+
];
|
|
756
|
+
const held = `${portLabel(port)} is serving ${slot.slug} (stage ${other?.stage ?? "?"}${other?.pendingAsk ? `, waiting on ${other.pendingAsk}` : ""}, ${slot.head.slice(0, 7)}, deployed ${ago(slot.at)})`;
|
|
757
|
+
return { text: needsOperator(`${held} — this verify would replace it. Resources: ${res}.${caveat} Ask the operator which: ${opts.join(" | ")} — nothing was built or deployed yet.`, "Dev port?"), isError: true };
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/** Before a review deploy: bring the branch up to date with the default branch, so the operator reviews
|
|
761
|
+
* the tree that will ship. Rebases a clean branch that is behind; refuses on a conflict (aborted, branch
|
|
762
|
+
* untouched) or on uncommitted work. With the operator's answer in hand (--confirmed) it never rewrites
|
|
763
|
+
* history: a default branch that moved since the review deploy sends the flow back to `flow verify`. */
|
|
764
|
+
async function catchUp(root: string, state: FlowState, cfg: Config, confirmed: boolean): Promise<RunResult | { note: string }> {
|
|
765
|
+
const cwd = gateCwd(root, state);
|
|
766
|
+
if (cwd === root) return { note: "" };
|
|
767
|
+
const d = cfg.defaultBranch;
|
|
768
|
+
const hasOrigin = !!(await originUrl(root));
|
|
769
|
+
let fetchNote = "";
|
|
770
|
+
if (hasOrigin && !(await sh(`git fetch -q origin ${sq(d)}`, cwd, 60_000)).ok) fetchNote = ` (fetch of origin/${d} failed — compared with the last fetched state)`;
|
|
771
|
+
const base = hasOrigin && (await sh(`git rev-parse --verify -q ${sq(`refs/remotes/origin/${d}`)}`, cwd)).ok ? `origin/${d}` : d;
|
|
772
|
+
const r = await sh(`git rev-list --count HEAD..${sq(base)}`, cwd);
|
|
773
|
+
const behind = Number.parseInt(r.out.trim(), 10);
|
|
774
|
+
if (!r.ok || !Number.isFinite(behind)) return { note: `behind ${base}: unknown${fetchNote}` };
|
|
775
|
+
if (behind === 0) return { note: fetchNote ? `up to date with ${base}${fetchNote}` : "" };
|
|
776
|
+
if (confirmed)
|
|
777
|
+
return { text: `verify gate FAILED:\n- ${base} moved ${behind} commit(s) past this branch — the operator's answer would cover a tree that is not the one that ships. Run flow verify (it rebases and redeploys for review), then ask Verified? again`, isError: true };
|
|
778
|
+
// untracked build output (a deploy's artifacts) does not stop a rebase; uncommitted tracked edits do
|
|
779
|
+
const dirty = await sh("git status --porcelain --untracked-files=no", cwd);
|
|
780
|
+
if (dirty.ok && dirty.out.trim()) return { text: `verify gate FAILED:\n- the branch is ${behind} commit(s) behind ${base} and has uncommitted changes — commit them, then re-run flow verify (it rebases before the review deploy)`, isError: true };
|
|
781
|
+
const rb = await sh(`git rebase ${sq(base)}`, cwd, 120_000);
|
|
782
|
+
if (!rb.ok) {
|
|
783
|
+
const conflicts = (await sh("git diff --name-only --diff-filter=U", cwd)).out.split("\n").filter(Boolean);
|
|
784
|
+
await sh("git rebase --abort", cwd);
|
|
785
|
+
return { text: `verify gate FAILED:\n- the branch is ${behind} commit(s) behind ${base} and the rebase stopped on conflicts${conflicts.length ? ` (${conflicts.join(", ")})` : ""} — aborted, the branch is as it was. Rebase by hand in ${state.worktree} (git rebase ${base}), resolve, then re-run flow verify\n${tail(rb.out)}`, isError: true };
|
|
786
|
+
}
|
|
787
|
+
const pushed = hasOrigin && state.branch && (await sh(`git rev-parse --verify -q ${sq(`refs/remotes/origin/${state.branch}`)}`, cwd)).ok;
|
|
788
|
+
return { note: `rebased onto ${base} (was ${behind} commit(s) behind)${fetchNote}${pushed ? ` — origin/${state.branch} now differs: the next push needs --force-with-lease (dev-flow asks the operator)` : ""}` };
|
|
789
|
+
}
|
|
790
|
+
|
|
632
791
|
/** Tier-1 checks the gate still has to see green. Entering a stage — and every edit of the worktree —
|
|
633
792
|
* clears the records, so "run flow check first" cost three round trips to say what one could (#84).
|
|
634
793
|
* `health` is left to the post-deploy probe when there is a deploy to prove: probing twice only waits twice. */
|
|
@@ -669,7 +828,7 @@ const healthRerunsAfterDeploy = (cfg: Config) => !!cfg.commands.dev && !!healthP
|
|
|
669
828
|
* deploy probe both do this). Returns an error result on failure, null when seeded or not configured. */
|
|
670
829
|
async function seedStep(root: string, state: FlowState, cfg: Config): Promise<{ text: string; isError: true } | null> {
|
|
671
830
|
if (!cfg.commands.seedData) return null;
|
|
672
|
-
const seed = await sh(cfg.commands.seedData, gateCwd(root, state), undefined,
|
|
831
|
+
const seed = await sh(cfg.commands.seedData, gateCwd(root, state), undefined, devEnv(root, state, cfg));
|
|
673
832
|
state.checks.seedData = { ok: seed.ok, at: now() };
|
|
674
833
|
writeState(root, state);
|
|
675
834
|
return seed.ok ? null : { text: `seedData FAILED (${cfg.commands.seedData}):\n${tail(seed.out)}`, isError: true };
|
|
@@ -680,7 +839,7 @@ type HealthRun = { ok: boolean; out: string; attempts: number } | { seedFail: Ru
|
|
|
680
839
|
/** Seed (when configured), then run the health probe within the playbook's wait budget. */
|
|
681
840
|
async function seededProbe(root: string, state: FlowState, cfg: Config, probe: string): Promise<HealthRun> {
|
|
682
841
|
const seedFail = await seedStep(root, state, cfg);
|
|
683
|
-
return seedFail ? { seedFail } : runHealthProbe(probe, gateCwd(root, state), cfg.healthWait,
|
|
842
|
+
return seedFail ? { seedFail } : runHealthProbe(probe, gateCwd(root, state), cfg.healthWait, devEnv(root, state, cfg));
|
|
684
843
|
}
|
|
685
844
|
|
|
686
845
|
/** seededProbe, recorded and stamped as the `health` check — `flow health` and both verify probes. */
|
|
@@ -1091,6 +1250,9 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
|
|
|
1091
1250
|
const { state, err } = needState(root, sess, slugArg);
|
|
1092
1251
|
if (err) return err;
|
|
1093
1252
|
const items = applicableItems(cfg, state!, "implement");
|
|
1253
|
+
// the operator reviews the tree that ships: catch up with the default branch before anything runs
|
|
1254
|
+
const caught = state!.stage === "implement" ? await catchUp(root, state!, cfg, flag("confirmed")) : { note: "" };
|
|
1255
|
+
if ("text" in caught) return caught;
|
|
1094
1256
|
const branch = await branchState(gateCwd(root, state!), cfg.defaultBranch);
|
|
1095
1257
|
if (branch.commitsAhead === 0 && cfg.versioning.file) branch.unreleased = await unreleasedOnMain(gateCwd(root, state!), cfg.versioning.pattern);
|
|
1096
1258
|
const branchLine = describeBranchState(branch, cfg.defaultBranch);
|
|
@@ -1105,9 +1267,14 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
|
|
|
1105
1267
|
// tier-1 gate first (tier-2 confirmation is recorded by this very command, so it is excluded here)
|
|
1106
1268
|
const preGate = verifyGate({ ...state!, confirmations: { ...state!.confirmations, implement: { hash: checklistHash(items), at: now() } } }, cfg, branch);
|
|
1107
1269
|
if (preGate.length) return { text: `verify gate FAILED:\n- ${preGate.join("\n- ")}\n${branchLine}`, isError: true };
|
|
1270
|
+
// a stack another flow is reviewing or releasing on is not this gate's to take — ask before deploying
|
|
1271
|
+
const slotted = cfg.commands.dev && !state!.docs ? await devSlotCheck(o, state!) : { note: "" };
|
|
1272
|
+
if ("text" in slotted) return slotted;
|
|
1108
1273
|
// commands that take minutes and touch live services must say so (#38): a terse gate let the
|
|
1109
1274
|
// agent tell the operator the dev deploy had never run, right after it recreated a container.
|
|
1110
1275
|
const did: string[] = [];
|
|
1276
|
+
if (caught.note) did.push(caught.note);
|
|
1277
|
+
if (slotted.note) did.push(slotted.note);
|
|
1111
1278
|
if (gateRun) did.push(`checks ran at the gate (${pending.map((c) => c.name).join(", ")})`);
|
|
1112
1279
|
if (staleAtGate.length) did.push(`stale record(s) rerun after a worktree change: ${staleAtGate.join(", ")}`);
|
|
1113
1280
|
if (state!.docs) {
|
|
@@ -1115,7 +1282,7 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
|
|
|
1115
1282
|
did.push("docs mode: project commands skipped (build/dev/health)");
|
|
1116
1283
|
} else {
|
|
1117
1284
|
if (cfg.commands.build) {
|
|
1118
|
-
const res = await sh(cfg.commands.build, gateCwd(root, state!), undefined,
|
|
1285
|
+
const res = await sh(cfg.commands.build, gateCwd(root, state!), undefined, devEnv(root, state!, cfg));
|
|
1119
1286
|
state!.checks.build = { ok: res.ok, at: now() };
|
|
1120
1287
|
writeState(root, state!);
|
|
1121
1288
|
if (!res.ok) return { text: `build FAILED (${cfg.commands.build}):\n${tail(res.out)}`, isError: true };
|
|
@@ -1124,11 +1291,11 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
|
|
|
1124
1291
|
// deploy to dev before asking — the operator reviews the running dev app, not a promise
|
|
1125
1292
|
const probe = healthProbe(cfg);
|
|
1126
1293
|
if (cfg.commands.dev) {
|
|
1127
|
-
const res = await sh(cfg.commands.dev, gateCwd(root, state!), undefined,
|
|
1294
|
+
const res = await sh(cfg.commands.dev, gateCwd(root, state!), undefined, devEnv(root, state!, cfg));
|
|
1128
1295
|
state!.checks.dev = { ok: res.ok, at: now() };
|
|
1129
1296
|
writeState(root, state!);
|
|
1130
1297
|
if (!res.ok) return { text: `dev deploy FAILED (${cfg.commands.dev}):\n${tail(res.out)}`, isError: true };
|
|
1131
|
-
did.push(`dev ran (${cfg.commands.dev})`);
|
|
1298
|
+
did.push(`dev ran (${cfg.commands.dev})${devPortOf(state!, cfg) !== undefined ? ` on port ${devPortOf(state!, cfg)}` : ""}`);
|
|
1132
1299
|
// the deploy is what must be proven, not just run: a container that came back unhealthy, or
|
|
1133
1300
|
// still serves the previous build, must not pass on a health PASS recorded before it was
|
|
1134
1301
|
// recreated. What "the expected version" means is the project's business — the probe runs in
|
|
@@ -1152,17 +1319,32 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
|
|
|
1152
1319
|
did.push(`health: live re-probe PASS (${probe}${triedNote(probed.attempts)})`);
|
|
1153
1320
|
}
|
|
1154
1321
|
}
|
|
1322
|
+
if (!state!.docs && cfg.commands.servedBuild) {
|
|
1323
|
+
// "something answers" is not "this branch answers": the served commit must be the worktree's HEAD
|
|
1324
|
+
const head = (await sh("git rev-parse HEAD", gateCwd(root, state!))).out.trim();
|
|
1325
|
+
const sb = await sh(cfg.commands.servedBuild, gateCwd(root, state!), 60_000, devEnv(root, state!, cfg));
|
|
1326
|
+
if (!sb.ok || !servedBuildMatches(sb.out, head))
|
|
1327
|
+
return { text: `served-build check FAILED (${cfg.commands.servedBuild}) — the app is up but does not serve this branch's HEAD ${head.slice(0, 12)}:\n${tail(sb.out)}`, isError: true };
|
|
1328
|
+
did.push(`serves ${head.slice(0, 7)} (HEAD)`);
|
|
1329
|
+
}
|
|
1330
|
+
if (!state!.docs && cfg.commands.dev) {
|
|
1331
|
+
const head = (await sh("git rev-parse HEAD", gateCwd(root, state!))).out.trim();
|
|
1332
|
+
writeDevPorts(root, { ...readDevPorts(root), [slotKey(devPortOf(state!, cfg))]: { slug: state!.slug, head, at: now() } });
|
|
1333
|
+
}
|
|
1155
1334
|
const ran = [branchLine, ...did].join("; ");
|
|
1156
1335
|
// yolo is the operator's word at Verified? — answers this question and pre-confirms the later ones
|
|
1157
1336
|
const yoloWord = takeYoloWord(state!);
|
|
1158
1337
|
if (yoloWord) return { text: yoloWord, isError: true };
|
|
1159
|
-
|
|
1338
|
+
let audit = flag("confirmed") ? " (confirmed by operator instruction)" : state!.yolo ? " (yolo: pre-confirmed)" : "";
|
|
1160
1339
|
const askPending = !flag("confirmed") && !state!.yolo;
|
|
1161
1340
|
if (askPending) {
|
|
1162
1341
|
markPendingAsk(root, state!, "Verified?"); // pending however it is asked — a chat question or a dialog
|
|
1163
|
-
//
|
|
1342
|
+
// the agent's call never opens a dialog (#181): this is the review deploy — the app is up for the
|
|
1343
|
+
// operator, and the answer comes back in chat as flow verify --confirmed
|
|
1164
1344
|
if (!ui.hasUI) {
|
|
1165
|
-
|
|
1345
|
+
const port = devPortOf(state!, cfg);
|
|
1346
|
+
const what = state!.docs ? "ready for review" : cfg.commands.dev ? `deployed for review${port !== undefined ? ` on port ${port}` : ""}` : "live app re-probed for review";
|
|
1347
|
+
return { text: `${needsOperator(`${what} — look at the change in the running app yourself first (the playbook's self-check), then ask the operator Verified? in chat and run flow verify --confirmed once they answer. Keep it running until they answer.`, "Verified?")}\n${ran}` };
|
|
1166
1348
|
}
|
|
1167
1349
|
const ok = await ui.confirm("Operator verification", `Verified? All checks green${cfg.commands.dev && !state!.docs ? `; dev deploy is up for review (${cfg.commands.dev})` : ""} \u2014 does it work?`);
|
|
1168
1350
|
if (!ok) {
|
|
@@ -1170,6 +1352,7 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
|
|
|
1170
1352
|
writeState(root, state!);
|
|
1171
1353
|
return { text: "verification declined — stay in implement and fix what failed" };
|
|
1172
1354
|
}
|
|
1355
|
+
audit = " (confirmed in dialog)";
|
|
1173
1356
|
}
|
|
1174
1357
|
state!.confirmations = { ...state!.confirmations, implement: { hash: checklistHash(items), at: now() } };
|
|
1175
1358
|
const final = verifyGate(state!, cfg, branch);
|
|
@@ -1288,14 +1471,20 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
|
|
|
1288
1471
|
// so. A warning, never a refusal — doc-only moves after verify are normal; the operator decides.
|
|
1289
1472
|
let postVerify = "";
|
|
1290
1473
|
if (state!.verifiedHead) {
|
|
1291
|
-
|
|
1474
|
+
// gh#180: upstream work merged in after the verdict was approved on its own branch — only the branch's
|
|
1475
|
+
// own commits are news to the operator; the merged-in ones are a count, not a list to wade through
|
|
1476
|
+
const d = cfg.defaultBranch;
|
|
1477
|
+
const upstream = (await sh(`git rev-parse --verify -q ${sq(`refs/remotes/origin/${d}`)}`, wtCwd)).ok ? `origin/${d}` : (await sh(`git rev-parse --verify -q ${sq(`refs/heads/${d}`)}`, wtCwd)).ok ? d : "";
|
|
1478
|
+
const since = await sh(`git log --oneline --no-decorate ${upstream ? "--no-merges " : ""}${sq(state!.verifiedHead)}..HEAD${upstream ? ` --not ${sq(upstream)}` : ""}`, wtCwd);
|
|
1292
1479
|
const commits = since.ok ? since.out.split("\n").filter((l) => l.trim()) : [];
|
|
1480
|
+
const all = upstream ? await sh(`git rev-list --count ${sq(state!.verifiedHead)}..HEAD`, wtCwd) : null;
|
|
1481
|
+
const mergedIn = all?.ok ? Math.max(0, Number.parseInt(all.out.trim(), 10) - commits.length) : 0;
|
|
1293
1482
|
// a release-only flow commits its bump and changelog after verify by design — only other files count
|
|
1294
1483
|
const prepFiles = new Set([cfg.versioning.file, cfg.release.changelog, cfg.versioning.file === "package.json" ? "package-lock.json" : ""].filter(Boolean) as string[]);
|
|
1295
1484
|
const touched = state!.releaseOnly && commits.length ? await sh(`git diff --name-only ${sq(state!.verifiedHead)} HEAD`, wtCwd) : null;
|
|
1296
1485
|
const prepOnly = !!touched?.ok && touched.out.split("\n").filter((l) => l.trim()).every((f) => prepFiles.has(f.trim()));
|
|
1297
1486
|
if (commits.length && !prepOnly)
|
|
1298
|
-
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`;
|
|
1487
|
+
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)` : ""}${mergedIn ? ` (+${mergedIn} merged in from ${upstream}, not listed)` : ""} — 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`;
|
|
1299
1488
|
}
|
|
1300
1489
|
// a standing yolo (given at an earlier checkpoint) stops short of Release? when the playbook says so, or
|
|
1301
1490
|
// when commits landed after Verified? — the word was given before those commits existed (gh#176).
|
|
@@ -1307,7 +1496,7 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
|
|
|
1307
1496
|
: postVerify
|
|
1308
1497
|
? "a yolo given earlier does not cover commits that landed after Verified? — ask Release? with them named"
|
|
1309
1498
|
: "";
|
|
1310
|
-
|
|
1499
|
+
let audit = flag("confirmed") ? " (confirmed by operator instruction)" : state!.yolo ? " (yolo: pre-confirmed)" : "";
|
|
1311
1500
|
const askPending = !flag("confirmed") && (!state!.yolo || !!yoloHeld);
|
|
1312
1501
|
if (askPending) {
|
|
1313
1502
|
markPendingAsk(root, state!, "Release?");
|
|
@@ -1320,6 +1509,7 @@ async function gateRelease(o: GateCtx): Promise<RunResult> {
|
|
|
1320
1509
|
writeState(root, state!);
|
|
1321
1510
|
return { text: "release declined — keep preparing in pre-release" };
|
|
1322
1511
|
}
|
|
1512
|
+
audit = " (confirmed in dialog)";
|
|
1323
1513
|
}
|
|
1324
1514
|
if (noVersion) state!.noVersion = true;
|
|
1325
1515
|
state!.confirmations = { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } };
|
|
@@ -1593,6 +1783,21 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
|
|
|
1593
1783
|
return { text: "finish declined" };
|
|
1594
1784
|
}
|
|
1595
1785
|
}
|
|
1786
|
+
// a side-by-side dev instance (a port the operator picked at verify) is this flow's to stop; the default
|
|
1787
|
+
// port's stack stays up — it is the machine's shared app, and the next flow redeploys over it
|
|
1788
|
+
let devDownNote = "";
|
|
1789
|
+
if (state!.devPort !== undefined && state!.devPort !== cfg.devPort) {
|
|
1790
|
+
if (cfg.commands.devDown) {
|
|
1791
|
+
const down = await sh(cfg.commands.devDown, gateCwd(root, state!), 5 * 60_000, devEnv(root, state!, cfg));
|
|
1792
|
+
devDownNote = down.ok ? ` dev instance on port ${state!.devPort} stopped (${cfg.commands.devDown}).` : ` dev instance on port ${state!.devPort} did NOT stop (${cfg.commands.devDown}) — stop it by hand:\n${tail(down.out)}\n`;
|
|
1793
|
+
} else devDownNote = ` dev instance on port ${state!.devPort} is still running — the playbook has no devDown to stop it; stop it by hand.`;
|
|
1794
|
+
}
|
|
1795
|
+
const reg = readDevPorts(root);
|
|
1796
|
+
const mine = Object.keys(reg).filter((k) => reg[k].slug === state!.slug);
|
|
1797
|
+
if (mine.length) {
|
|
1798
|
+
for (const k of mine) delete reg[k];
|
|
1799
|
+
writeDevPorts(root, reg);
|
|
1800
|
+
}
|
|
1596
1801
|
if (wt && existsSync(wt)) {
|
|
1597
1802
|
const rm = await sh(`git worktree remove ${sq(wt)} && git branch -D ${sq(state!.branch)}`, root);
|
|
1598
1803
|
if (!rm.ok) return { text: `worktree removal failed:\n${rm.out}\nif files are owned by another user (e.g. root-owned docker build output), remove ${state!.worktree} manually and rerun flow finish`, isError: true };
|
|
@@ -1636,7 +1841,7 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
|
|
|
1636
1841
|
// finish is the moment between flows: name the fix / tidy suggestion when a rule fires, nothing otherwise
|
|
1637
1842
|
const nudge = reflectionNudges(readReflectionsText(root), now().slice(0, 10), { between: true });
|
|
1638
1843
|
const nudgeNote = [nudge.fix, nudge.tidy].filter(Boolean).map((n) => ` ${n} — offer it to the operator.`).join("");
|
|
1639
|
-
return { text: `feature ${state!.slug} done — ${closeNote}${remoteNote}; .dev-flow/${state!.slug}/ removed.${roadmapNote}${forgeSkipNote}${reflectSkipNote}${syncNote}${nudgeNote} Re-read flow status before reporting open flows — a sibling feature may have finished while this session ran.` };
|
|
1844
|
+
return { text: `feature ${state!.slug} done — ${closeNote}${remoteNote}; .dev-flow/${state!.slug}/ removed.${devDownNote}${roadmapNote}${forgeSkipNote}${reflectSkipNote}${syncNote}${nudgeNote} Re-read flow status before reporting open flows — a sibling feature may have finished while this session ran.` };
|
|
1640
1845
|
}
|
|
1641
1846
|
|
|
1642
1847
|
/** The main-branch guard as a hook body — installed into .git/hooks, or printed for a hook manager to carry. */
|
|
@@ -1915,7 +2120,7 @@ async function gateApprove(o: GateCtx): Promise<RunResult> {
|
|
|
1915
2120
|
const errs = approveGate(state!, cfg, planFiles, existsSync(planMd) ? readFileSync(planMd, "utf8") : undefined, foreignWorktreeLinks(dfDir(root), state!.slug, mockupHtml));
|
|
1916
2121
|
if (errs.length) return { text: `plan gate FAILED:\n- ${errs.join("\n- ")}`, isError: true };
|
|
1917
2122
|
const planItems = applicableItems(cfg, state!, "plan");
|
|
1918
|
-
|
|
2123
|
+
let audit = flag("confirmed") ? " (confirmed by operator instruction)" : "";
|
|
1919
2124
|
const askPending = !flag("confirmed");
|
|
1920
2125
|
if (askPending) {
|
|
1921
2126
|
markPendingAsk(root, state!, "Approve?");
|
|
@@ -1928,6 +2133,7 @@ async function gateApprove(o: GateCtx): Promise<RunResult> {
|
|
|
1928
2133
|
writeState(root, state!);
|
|
1929
2134
|
return { text: "approval declined — keep iterating on the plan" };
|
|
1930
2135
|
}
|
|
2136
|
+
audit = " (confirmed in dialog)";
|
|
1931
2137
|
}
|
|
1932
2138
|
// the operator's word at Approve?, recorded only once given: every later gate question is pre-confirmed; checks and guardrails stay
|
|
1933
2139
|
if (flag("yolo")) state!.yolo = true;
|
|
@@ -1992,6 +2198,8 @@ async function gateStatus(o: GateCtx): Promise<RunResult> {
|
|
|
1992
2198
|
` next: ${nextHint(st, cfg)}`,
|
|
1993
2199
|
];
|
|
1994
2200
|
});
|
|
2201
|
+
// who holds the dev stack: the one thing two parallel flows on one machine must not guess
|
|
2202
|
+
for (const [k, v] of Object.entries(readDevPorts(root))) lines.push(`dev: ${k === "default" ? "stack" : `port ${k}`} → ${v.slug} @ ${v.head.slice(0, 7)}, deployed ${ago(v.at)}`);
|
|
1995
2203
|
if (warn.length) lines.push(...warn);
|
|
1996
2204
|
// which identity this session's state is keyed by: a claim fight is undiagnosable when the key
|
|
1997
2205
|
// could be a session id or a shared directory and the output does not say which
|
|
@@ -2500,6 +2708,14 @@ async function askOperator(ctx: ExtensionContext, what: string, why: string): Pr
|
|
|
2500
2708
|
return ok ? null : `operator declined — ${why}`;
|
|
2501
2709
|
}
|
|
2502
2710
|
|
|
2711
|
+
/** What a kill by dev-flow's own timeout tells the agent (and the operator reading the transcript). */
|
|
2712
|
+
export function timeoutKillNote(armed: { s: number; cls: string }): string {
|
|
2713
|
+
const why = armed.cls.startsWith("its own timeout")
|
|
2714
|
+
? `the command's ${armed.cls.replace(/^its own /, "")} plus a 15s margin — it outlived its own timer`
|
|
2715
|
+
: `dev-flow's default for ${armed.cls} commands, armed because the call stated no timeout`;
|
|
2716
|
+
return `[dev-flow] stopped at ${armed.s}s: ${why}. If it needs longer, rerun with an explicit timeout (seconds) on the call.`;
|
|
2717
|
+
}
|
|
2718
|
+
|
|
2503
2719
|
export default function devFlow(pi: ExtensionAPI) {
|
|
2504
2720
|
registerCopy(); // which copy of dev-flow this is — see COPIES
|
|
2505
2721
|
/** Parse "flow <sub> [slug] [--flags]" args shared by command and tool. */
|
|
@@ -2508,6 +2724,7 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2508
2724
|
return String(input ?? "").trim().split(/\s+/).filter(Boolean);
|
|
2509
2725
|
};
|
|
2510
2726
|
|
|
2727
|
+
const NO_DIALOGS: Ui = { hasUI: false, confirm: async () => false };
|
|
2511
2728
|
const uiFrom = (ctx: ExtensionContext): Ui => ({
|
|
2512
2729
|
hasUI: ctx.hasUI,
|
|
2513
2730
|
confirm: async (title, message) => (ctx.hasUI ? ctx.ui.confirm(title, message) : Promise.resolve(false)),
|
|
@@ -2606,7 +2823,10 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2606
2823
|
}),
|
|
2607
2824
|
execute: async (id, params, signal, onUpdate, ctx) => {
|
|
2608
2825
|
const root = await flowRoot(ctx.cwd);
|
|
2609
|
-
|
|
2826
|
+
// the agent's call never opens a dialog (#181): a dialog inside a tool call blocks the turn, so nobody
|
|
2827
|
+
// can talk to the agent while it waits, and the agent cannot see who answered. Gates answer with the
|
|
2828
|
+
// chat word to ask instead; the /flow slash command (a human at the keyboard) keeps its dialogs.
|
|
2829
|
+
const res = await runFlow(params.args, root, NO_DIALOGS, sessFor(ctx, root), finishReflectHook(id, ctx, root, signal, onUpdate));
|
|
2610
2830
|
if (!res.isError) maybeCompactNow(ctx, root);
|
|
2611
2831
|
return { content: [{ type: "text", text: res.text }], details: undefined, isError: res.isError };
|
|
2612
2832
|
},
|
|
@@ -2959,6 +3179,26 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2959
3179
|
return undefined;
|
|
2960
3180
|
});
|
|
2961
3181
|
|
|
3182
|
+
// A kill by dev-flow's silent default must say so: the transcript shows the call without a timeout, so
|
|
3183
|
+
// "Command timed out after 30 seconds" otherwise reads like pi misbehaving, and the agent cannot tell a
|
|
3184
|
+
// policy cap from a hang. Keyed by tool call id; a call blocked before it ran never reports, so the map
|
|
3185
|
+
// is bounded rather than trusted to drain.
|
|
3186
|
+
const armedTimeouts = new Map<string, { s: number; cls: string }>();
|
|
3187
|
+
const rememberArmed = (id: string, v: { s: number; cls: string }) => {
|
|
3188
|
+
armedTimeouts.set(id, v);
|
|
3189
|
+
if (armedTimeouts.size > 500) armedTimeouts.delete(armedTimeouts.keys().next().value as string);
|
|
3190
|
+
};
|
|
3191
|
+
pi.on("tool_result", async (event) => {
|
|
3192
|
+
const armed = armedTimeouts.get(event.toolCallId);
|
|
3193
|
+
if (!armed) return undefined;
|
|
3194
|
+
armedTimeouts.delete(event.toolCallId);
|
|
3195
|
+
if (!event.isError) return undefined;
|
|
3196
|
+
const text = event.content.map((c) => (c.type === "text" ? c.text : "")).join("");
|
|
3197
|
+
const m = text.match(/timed out after (\d+) seconds/);
|
|
3198
|
+
if (!m || Number(m[1]) !== armed.s) return undefined;
|
|
3199
|
+
return { content: [...event.content, { type: "text" as const, text: `\n${timeoutKillNote(armed)}` }] };
|
|
3200
|
+
});
|
|
3201
|
+
|
|
2962
3202
|
async function guardToolCall(event: ToolCallEvent, ctx: ExtensionContext): Promise<ToolCallEventResult | undefined> {
|
|
2963
3203
|
if (!guardsAreMine()) return undefined; // election: only the newest loaded copy judges
|
|
2964
3204
|
// pi kills a shell call only when a timeout was passed, and the model omits it in ~75% of
|
|
@@ -2970,7 +3210,14 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2970
3210
|
const noDf = !initiated(ctx.cwd);
|
|
2971
3211
|
// in an initiated repo the silent default stays armed either way: it is the safety net for an
|
|
2972
3212
|
// `inject` project and the number the refusal quotes; an uninitiated folder is not touched at all
|
|
2973
|
-
if (shellCmd && shellInput && !noDf)
|
|
3213
|
+
if (shellCmd && shellInput && !noDf) {
|
|
3214
|
+
// the e2e test shortens only the silent default — an explicit timeout is never touched
|
|
3215
|
+
const cls = explicitTimeout === undefined && testSeams.bashTimeout.cap !== undefined ? { ...timeoutClass(shellCmd), s: testSeams.bashTimeout.cap } : timeoutClass(shellCmd);
|
|
3216
|
+
shellInput.timeout = explicitTimeout === undefined ? cls.s : bashTimeout(shellCmd, explicitTimeout);
|
|
3217
|
+
// the armed value never reaches the transcript (the call records what the model wrote), so a kill
|
|
3218
|
+
// by it would read as a mystery hang — remember it, and the tool_result hook names it on a kill
|
|
3219
|
+
if (explicitTimeout === undefined) rememberArmed(event.toolCallId, cls);
|
|
3220
|
+
}
|
|
2974
3221
|
// an uninitiated folder hears nothing from dev-flow at all — flow init is the opt-in that arms
|
|
2975
3222
|
// the guards, the no-playbook bash-timeout default included
|
|
2976
3223
|
if (noDf) return undefined;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-dev-flow",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.85.1",
|
|
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": [
|
|
@@ -46,13 +46,15 @@
|
|
|
46
46
|
"peerDependencies": {
|
|
47
47
|
"@earendil-works/pi-ai": "*",
|
|
48
48
|
"@earendil-works/pi-coding-agent": "*",
|
|
49
|
-
"@earendil-works/pi-tui": "*"
|
|
49
|
+
"@earendil-works/pi-tui": "*",
|
|
50
|
+
"typebox": "*"
|
|
50
51
|
},
|
|
51
52
|
"devDependencies": {
|
|
52
53
|
"@earendil-works/pi-ai": "*",
|
|
53
54
|
"@earendil-works/pi-coding-agent": "*",
|
|
54
55
|
"@earendil-works/pi-tui": "*",
|
|
55
56
|
"@types/node": "^22.0.0",
|
|
57
|
+
"typebox": "*",
|
|
56
58
|
"typescript": "^7.0.2"
|
|
57
59
|
},
|
|
58
60
|
"scripts": {
|
package/skills/dev-flow/SKILL.md
CHANGED
|
@@ -54,10 +54,8 @@ Ground rules:
|
|
|
54
54
|
version heading (default is versioned: bump + tag).
|
|
55
55
|
- **One session = exactly one feature** (flow + branch + worktree); parallel
|
|
56
56
|
sessions, one feature each, are the model. A session binds **explicitly and
|
|
57
|
-
only**: `flow start <slug>` binds its own feature
|
|
58
|
-
|
|
59
|
-
Both bind commands rename the Pi session to the slug, so the picker names each
|
|
60
|
-
session after its feature. Unbound: gates demand an explicit slug and main-checkout writes stay
|
|
57
|
+
only**: `flow start <slug>` binds its own feature; `flow use <slug>` takes
|
|
58
|
+
one over. Nothing auto-binds. Unbound: gates demand an explicit slug and main-checkout writes stay
|
|
61
59
|
blocked — there is no bypass, an unbound session cannot edit source.
|
|
62
60
|
- **Project `flow-guard` rules** (`deny`/`confirm`/`protect`/`forbid` in
|
|
63
61
|
project.md `## global`) apply at **every** stage and are judged ahead of
|
|
@@ -67,12 +65,15 @@ Ground rules:
|
|
|
67
65
|
- **`.dev-flow/<slug>/state.json` is flow-owned** — never read or write it;
|
|
68
66
|
`flow status` is your view. **project.md is the operator-owned playbook**:
|
|
69
67
|
read freely, **never edit** — it changes through `flow init --write` on the
|
|
70
|
-
operator's word
|
|
68
|
+
operator's word.
|
|
71
69
|
- **A guard blocking you means you are skipping a stage or writing outside your
|
|
72
70
|
feature** — run the gate instead of working around it. The guard reads
|
|
73
71
|
**commands**: quoted text is an argument's prose (a PR body discussing a
|
|
74
72
|
commit is not a commit), and a wrapper that execs its argument
|
|
75
73
|
(`sh -c "git push origin main"`) is judged on its payload.
|
|
74
|
+
- **Every bash call has a timeout**: none stated → dev-flow arms its class
|
|
75
|
+
default (quick 30s … build 900s, a `timeout N` wrapper → N+15s). Pass
|
|
76
|
+
`timeout` (seconds) when a run needs longer.
|
|
76
77
|
- Abandon a feature with `flow abort <slug>` — never unbind by hand. A gate
|
|
77
78
|
refusal lists exactly what is missing: fix that, rerun the gate.
|
|
78
79
|
- Also obey the repo's own AGENTS.md and project skills: dev-flow sequences
|
|
@@ -42,8 +42,15 @@ feature).
|
|
|
42
42
|
up to `healthWait` (default 30s) — a service needing a moment after its
|
|
43
43
|
container starts is not a failed deploy; say so rather than declaring a
|
|
44
44
|
healthy deploy broken. Walk the **tier-2 checklist** (`- [ ]`) with the
|
|
45
|
-
operator honestly — it cannot be scripted.
|
|
46
|
-
|
|
45
|
+
operator honestly — it cannot be scripted. **Verify is two steps.**
|
|
46
|
+
`flow verify` prepares the review: it rebases onto the default branch when
|
|
47
|
+
the branch is behind (a conflict aborts and hands it to you), deploys, and
|
|
48
|
+
returns `deployed for review` — it never opens a dialog. If another flow
|
|
49
|
+
holds the dev port it returns `NEEDS-OPERATOR Dev port?` with the free RAM
|
|
50
|
+
and disk instead of deploying: put the options to the operator and re-run
|
|
51
|
+
with their answer (`--port=<n>` alongside, or `--replace`). Then look at the
|
|
52
|
+
change yourself, keep the app **running** while you ask **Verified?**, and
|
|
53
|
+
record the answer with `flow verify --confirmed` — the operator reviews
|
|
47
54
|
the live app, so never tear the test server down before the checkpoint is
|
|
48
55
|
answered (with no `dev` deploy configured, `flow verify` live-re-probes
|
|
49
56
|
`health` itself and refuses while nothing is answering). Checkpoint report: stage line **🔨 implement ·
|
|
@@ -132,7 +139,10 @@ runs past 15 min), re-runs the health probe **against what it just deployed**
|
|
|
132
139
|
`healthWait`, then refuses the gate reporting its attempts — a pre-deploy PASS
|
|
133
140
|
describes a container that no longer exists; no probe prints
|
|
134
141
|
`health: none configured` and the doctor flags it), and demands all tier-1
|
|
135
|
-
checks green before the single question.
|
|
142
|
+
checks green before the single question. With `servedBuild` set it also proves
|
|
143
|
+
the app serves the worktree's HEAD, not just that something answers. A
|
|
144
|
+
`--confirmed` run refuses when the default branch moved since the review
|
|
145
|
+
deploy: run `flow verify` again so the answer covers the tree that ships. The operator's confirm covers the
|
|
136
146
|
tier-2 list as a set (hashed; edits reset it). A `--docs` feature prints
|
|
137
147
|
`docs mode: project commands skipped` and asks only the verify question.
|
|
138
148
|
Verify lands the feature in **pre-release**.
|
package/src/core.ts
CHANGED
|
@@ -50,6 +50,7 @@ export interface FlowState {
|
|
|
50
50
|
releaseOnly?: boolean; // verify found nothing on the branch but unreleased work on main: this flow only cuts the version (#161)
|
|
51
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)
|
|
52
52
|
reflectedAt?: string; // a reflect worker reported for this flow — finish runs one first while this is unset (only --no-reflect --confirmed skips it)
|
|
53
|
+
devPort?: number; // the port the operator chose for this flow's dev deploy when the default was held by another flow — finish stops it (devDown)
|
|
53
54
|
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
|
|
54
55
|
}
|
|
55
56
|
|
|
@@ -71,6 +72,10 @@ export interface Commands {
|
|
|
71
72
|
run?: string;
|
|
72
73
|
/** Deploy to a dev/staging environment before verification — operator reviews the running dev app. */
|
|
73
74
|
dev?: string;
|
|
75
|
+
/** Stop a dev instance this flow started on a non-default port (run by flow finish). */
|
|
76
|
+
devDown?: string;
|
|
77
|
+
/** Print the commit the deployed app serves — verify refuses when it is not the worktree's HEAD. */
|
|
78
|
+
servedBuild?: string;
|
|
74
79
|
}
|
|
75
80
|
|
|
76
81
|
/** How a merged feature branch lands on the default branch (playbook key `merge`).
|
|
@@ -106,6 +111,13 @@ export interface Config {
|
|
|
106
111
|
versioning: Versioning;
|
|
107
112
|
/** Seconds the post-deploy health probe may keep retrying before the gate gives up (0 = single shot). */
|
|
108
113
|
healthWait: number;
|
|
114
|
+
/** The dev deploy's default port (playbook `port`). Unset: dev-flow cannot run a second instance, only name who holds the stack. */
|
|
115
|
+
devPort?: number;
|
|
116
|
+
/** Can two dev instances run side by side (playbook `parallelDev`)? undefined = the playbook does not say. */
|
|
117
|
+
parallelDev?: boolean;
|
|
118
|
+
/** Bytes one dev instance needs (playbook `instanceMem` / `instanceDisk`, e.g. 2G) — the side-by-side feasibility check. */
|
|
119
|
+
instanceMem?: number;
|
|
120
|
+
instanceDisk?: number;
|
|
109
121
|
release: { review: string; changelog?: string; releases?: boolean; artifact?: string; preflight?: string; merge?: MergeStyle | "any"; /** `until-release`: a standing yolo never answers Release? (gh#176) */ yolo?: "all" | "until-release" };
|
|
110
122
|
mainHook: boolean; // flow init installs a pre-commit hook blocking main commits
|
|
111
123
|
/** `inject` (default): the class default timeout is armed silently on every shell call.
|
|
@@ -192,6 +204,49 @@ export function toSeconds(raw: unknown): number | undefined {
|
|
|
192
204
|
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : undefined;
|
|
193
205
|
}
|
|
194
206
|
|
|
207
|
+
/** A playbook size (`2G`, `512M`, `1.5GB`, plain bytes) in bytes; undefined for junk. */
|
|
208
|
+
export function parseSize(raw: unknown): number | undefined {
|
|
209
|
+
const m = typeof raw === "string" ? raw.trim().match(/^(\d+(?:\.\d+)?)\s*([kmgt]?)i?b?$/i) : null;
|
|
210
|
+
if (typeof raw === "number" && Number.isFinite(raw) && raw >= 0) return Math.floor(raw);
|
|
211
|
+
if (!m) return undefined;
|
|
212
|
+
const mult = { "": 1, k: 1024, m: 1024 ** 2, g: 1024 ** 3, t: 1024 ** 4 }[m[2].toLowerCase() as "" | "k" | "m" | "g" | "t"];
|
|
213
|
+
return Math.floor(Number(m[1]) * mult);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Bytes as the operator reads them: 9.1G, 512M. */
|
|
217
|
+
export function formatSize(n: number): string {
|
|
218
|
+
for (const [u, d] of [["T", 1024 ** 4], ["G", 1024 ** 3], ["M", 1024 ** 2], ["K", 1024]] as const) if (n >= d) return `${(n / d).toFixed(1).replace(/\.0$/, "")}${u}`;
|
|
219
|
+
return `${n}B`;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Does a `servedBuild` printout name this HEAD? Any hex token of 7+ characters that is a prefix of the full sha counts. */
|
|
223
|
+
export function servedBuildMatches(out: string, head: string): boolean {
|
|
224
|
+
const full = head.trim().toLowerCase();
|
|
225
|
+
if (full.length < 7) return false;
|
|
226
|
+
return (out.toLowerCase().match(/[0-9a-f]{7,40}/g) ?? []).some((t) => full.startsWith(t));
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Who last deployed dev on a port (`.dev-flow/dev-ports.json`, key = port or "default"). */
|
|
230
|
+
export interface DevSlot {
|
|
231
|
+
slug: string;
|
|
232
|
+
head: string;
|
|
233
|
+
at: string;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** What the clash question offers, from measured resources and the playbook's declared costs. */
|
|
237
|
+
export function sideBySide(o: { cfg: Config; nextPort: number | null; memAvail: number | null; diskFree: number | null }): { ok: boolean; why: string[] } {
|
|
238
|
+
const { cfg } = o;
|
|
239
|
+
const why: string[] = [];
|
|
240
|
+
if (cfg.devPort === undefined) why.push("the playbook names no `port`, so dev-flow cannot place a second instance");
|
|
241
|
+
if (cfg.parallelDev === false) why.push("the playbook says `parallelDev = no` (instances would share state)");
|
|
242
|
+
const dev = `${cfg.commands.dev ?? ""}\n${cfg.commands.health ?? ""}`;
|
|
243
|
+
if (cfg.devPort !== undefined && !/DEV_FLOW_PORT/.test(dev)) why.push("the playbook's `dev`/`health` commands do not read $DEV_FLOW_PORT, so a second instance would land on the same port");
|
|
244
|
+
if (o.nextPort === null && cfg.devPort !== undefined) why.push("no free port found above the default");
|
|
245
|
+
if (cfg.instanceMem !== undefined && o.memAvail !== null && o.memAvail < cfg.instanceMem) why.push(`RAM available ${formatSize(o.memAvail)} < ${formatSize(cfg.instanceMem)} one instance needs`);
|
|
246
|
+
if (cfg.instanceDisk !== undefined && o.diskFree !== null && o.diskFree < cfg.instanceDisk) why.push(`disk free ${formatSize(o.diskFree)} < ${formatSize(cfg.instanceDisk)} one instance needs`);
|
|
247
|
+
return { ok: why.length === 0, why };
|
|
248
|
+
}
|
|
249
|
+
|
|
195
250
|
/**
|
|
196
251
|
* Retry schedule for the health probe (#42): a service whose readiness lags its container start can
|
|
197
252
|
* never pass a single shot, so the gate waits instead of failing the deploy. One immediate attempt
|
|
@@ -2113,7 +2168,7 @@ export function nextHint(state: FlowState, cfg: Config): string {
|
|
|
2113
2168
|
return `investigate, present your direction and proposed mode to the operator and clarify in chat, then write the plan into .dev-flow/${state.slug}/plan/plan.md${state.ui ? ` and render mockups to plan/mockups/ (${cfg.mockupGlobs.join(", ")}) with headless chromium, embedded in plan.md` : ""}, then ask the operator Approve? in chat and run flow approve --confirmed when they answer`;
|
|
2114
2169
|
case "implement":
|
|
2115
2170
|
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`;
|
|
2116
|
-
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
|
|
2171
|
+
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 run flow verify — it rebases onto the default branch when behind and deploys for review (asking first when another flow holds the dev port) — look at the change yourself, then ask the operator 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)`;
|
|
2117
2172
|
case "pre-release":
|
|
2118
2173
|
if (state.docs && (cfg.versioning.file || cfg.release.changelog))
|
|
2119
2174
|
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`;
|
package/src/projectmd.ts
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
9
9
|
import path from "node:path";
|
|
10
|
-
import { applyAnswer, type ChecklistItem, type Config, DEFAULTS, healthProbe, parseMergeStyle, parseVersion, toSeconds, type GuardRules, type StageCheck } from "./core.ts";
|
|
10
|
+
import { applyAnswer, type ChecklistItem, type Config, DEFAULTS, healthProbe, parseMergeStyle, parseVersion, parseSize, toSeconds, type GuardRules, type StageCheck } from "./core.ts";
|
|
11
11
|
|
|
12
12
|
export const MD_STAGES = ["global", "plan", "implement", "pre-release", "release"] as const;
|
|
13
13
|
export type MdStage = (typeof MD_STAGES)[number];
|
|
@@ -46,6 +46,12 @@ const KEYMAP: Record<string, Record<string, string>> = {
|
|
|
46
46
|
health: "commands.health",
|
|
47
47
|
dev: "commands.dev",
|
|
48
48
|
healthWait: "healthWait", // seconds the post-deploy probe may keep retrying (#42)
|
|
49
|
+
port: "devPort", // the dev deploy's default port — exported to dev/health as $DEV_FLOW_PORT
|
|
50
|
+
parallelDev: "parallelDev", // yes | no — can two dev instances run side by side?
|
|
51
|
+
instanceMem: "instanceMem", // what one dev instance needs, e.g. 2G — the side-by-side check
|
|
52
|
+
instanceDisk: "instanceDisk",
|
|
53
|
+
devDown: "commands.devDown", // stops a flow's non-default-port instance at finish
|
|
54
|
+
servedBuild: "commands.servedBuild", // prints the commit the deployed app serves — verify proves it is HEAD
|
|
49
55
|
},
|
|
50
56
|
release: {
|
|
51
57
|
versionFile: "versioning.file",
|
|
@@ -258,6 +264,13 @@ function mergeInto(c: Config, r: Record<string, unknown>): void {
|
|
|
258
264
|
// playbook values arrive as strings; a junk healthWait must not make the gate wait forever
|
|
259
265
|
const wait = toSeconds(r.healthWait);
|
|
260
266
|
if (wait !== undefined) c.healthWait = wait;
|
|
267
|
+
const port = toSeconds(r.devPort);
|
|
268
|
+
if (port !== undefined && port > 0 && port < 65536) c.devPort = port;
|
|
269
|
+
if (typeof r.parallelDev === "string") c.parallelDev = /^(yes|true)$/i.test(r.parallelDev) ? true : /^(no|false)$/i.test(r.parallelDev) ? false : undefined;
|
|
270
|
+
const mem = parseSize(r.instanceMem);
|
|
271
|
+
if (mem !== undefined) c.instanceMem = mem;
|
|
272
|
+
const disk = parseSize(r.instanceDisk);
|
|
273
|
+
if (disk !== undefined) c.instanceDisk = disk;
|
|
261
274
|
}
|
|
262
275
|
|
|
263
276
|
/**
|
|
@@ -335,6 +348,7 @@ export function setPlaybookCheck(text: string, name: string, cmd: string): { tex
|
|
|
335
348
|
const ANSWER_STAGE: Record<string, MdStage> = {
|
|
336
349
|
defaultBranch: "global", forge: "global", worktreeDir: "global", branchPattern: "global", mainHook: "global", mockupGlobs: "global", bashTimeout: "global",
|
|
337
350
|
setup: "implement", test: "implement", build: "implement", run: "implement", seedData: "implement", health: "implement", dev: "implement", healthWait: "implement",
|
|
351
|
+
port: "implement", parallelDev: "implement", instanceMem: "implement", instanceDisk: "implement", devDown: "implement", servedBuild: "implement",
|
|
338
352
|
versionFile: "pre-release", versionTag: "pre-release", changelog: "pre-release", review: "pre-release",
|
|
339
353
|
releases: "release", artifact: "release", preflight: "release", merge: "release", yolo: "release",
|
|
340
354
|
};
|
package/src/timeouts.ts
CHANGED
|
@@ -31,28 +31,65 @@ const GIT_NETWORK = new Set(["push", "pull", "fetch", "clone", "ls-remote", "sub
|
|
|
31
31
|
// wrappers/prefixes that never decide the class of a segment
|
|
32
32
|
const SKIP_HEADS = new Set(["cd", "export", "source", ".", "set", "unset", "if", "then", "else", "fi", "do", "done", "while", "for", "case", "esac", "{", "}", "(", "!", "test", "[[", "time", "nohup", "env", "command", "sudo"]);
|
|
33
33
|
|
|
34
|
-
/**
|
|
35
|
-
|
|
34
|
+
/** Margin over a command's own `timeout N`: the shell's timer fires first, with its own message;
|
|
35
|
+
* dev-flow's kill stays the backstop. */
|
|
36
|
+
export const WRAPPER_MARGIN_S = 15;
|
|
37
|
+
|
|
38
|
+
/** `timeout`'s options that take a value as the next token (`-s KILL`, `-k 5`). */
|
|
39
|
+
const TIMEOUT_VALUE_OPTS = new Set(["-s", "--signal", "-k", "--kill-after"]);
|
|
40
|
+
|
|
41
|
+
/** A coreutils duration (`600`, `90s`, `2m`, `1.5h`, `1d`) in seconds; null when unreadable or 0 (= no limit). */
|
|
42
|
+
function parseDuration(tok: string): number | null {
|
|
43
|
+
const m = tok.match(/^(\d+(?:\.\d+)?)([smhd]?)$/);
|
|
44
|
+
if (!m) return null;
|
|
45
|
+
const n = Number(m[1]) * { "": 1, s: 1, m: 60, h: 3600, d: 86400 }[m[2] as "" | "s" | "m" | "h" | "d"];
|
|
46
|
+
return n > 0 ? Math.ceil(n) : null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Class of one command segment: its ceiling in seconds and the class name the timeout note reports;
|
|
50
|
+
* 0 = contributes nothing (a wrapper like `cd x`). */
|
|
51
|
+
function segClass(seg: string): { s: number; cls: string } {
|
|
36
52
|
// watchers run by design until done — they get their own ceiling no matter what head they carry
|
|
37
|
-
if (/\bgh\s+run\s+watch\b/.test(seg)) return WATCH_S;
|
|
38
|
-
if (/(logs?|tail|journalctl)/.test(seg) && /(^|\s)(-f|--follow)(\s|$)/.test(seg)) return WATCH_S;
|
|
39
|
-
if (/\bcompose\b.*\bup\b/.test(seg) && !/(^|\s)(-d|--detach)(\s|$)/.test(seg)) return WATCH_S;
|
|
53
|
+
if (/\bgh\s+run\s+watch\b/.test(seg)) return { s: WATCH_S, cls: "watch" };
|
|
54
|
+
if (/(logs?|tail|journalctl)/.test(seg) && /(^|\s)(-f|--follow)(\s|$)/.test(seg)) return { s: WATCH_S, cls: "watch" };
|
|
55
|
+
if (/\bcompose\b.*\bup\b/.test(seg) && !/(^|\s)(-d|--detach)(\s|$)/.test(seg)) return { s: WATCH_S, cls: "watch" };
|
|
40
56
|
const tok = seg.trim().split(/\s+/);
|
|
41
57
|
let i = 0;
|
|
42
58
|
while (i < tok.length && (/^[\w.]+=/.test(tok[i]) || SKIP_HEADS.has(tok[i]))) i++;
|
|
43
59
|
const base = (tok[i] ?? "").split("/").pop() ?? "";
|
|
44
|
-
if (SKIP_HEADS.has(base) || !base) return 0;
|
|
60
|
+
if (SKIP_HEADS.has(base) || !base) return { s: 0, cls: "" };
|
|
61
|
+
// `timeout N cmd`: the command already says how long it may run — honour that, plus a margin, instead
|
|
62
|
+
// of judging the segment by the head `timeout` (which fell to the 120s default and killed a
|
|
63
|
+
// `timeout 600 bun test` at two minutes). An unreadable duration falls back to the wrapped command.
|
|
64
|
+
if (base === "timeout" || base === "gtimeout") {
|
|
65
|
+
let j = i + 1;
|
|
66
|
+
while (j < tok.length && tok[j].startsWith("-")) j += TIMEOUT_VALUE_OPTS.has(tok[j]) ? 2 : 1;
|
|
67
|
+
const n = parseDuration(tok[j] ?? "");
|
|
68
|
+
if (n !== null) return { s: Math.min(n + WRAPPER_MARGIN_S, CLAMP_S), cls: `its own timeout ${tok[j]}` };
|
|
69
|
+
const inner = segClass(tok.slice(j + 1).join(" "));
|
|
70
|
+
return inner.s ? inner : { s: DEFAULT_S, cls: "default" };
|
|
71
|
+
}
|
|
45
72
|
if (base === "git") {
|
|
46
73
|
const sub = tok[i + 1] ?? "";
|
|
47
|
-
if (GIT_QUICK.has(sub)) return QUICK_S;
|
|
48
|
-
if (GIT_NETWORK.has(sub)) return NETWORK_S;
|
|
49
|
-
return LOCAL_GIT_S;
|
|
74
|
+
if (GIT_QUICK.has(sub)) return { s: QUICK_S, cls: "quick" };
|
|
75
|
+
if (GIT_NETWORK.has(sub)) return { s: NETWORK_S, cls: "network" };
|
|
76
|
+
return { s: LOCAL_GIT_S, cls: "local git" };
|
|
77
|
+
}
|
|
78
|
+
if (NETWORK.has(base)) return { s: NETWORK_S, cls: "network" };
|
|
79
|
+
if (SERVICE.has(base)) return /\bbuild\b/.test(seg) ? { s: BUILD_S, cls: "build" } : { s: SERVICE_S, cls: "service" }; // docker/compose build is an image build, not a service poke
|
|
80
|
+
if (BUILD.has(base)) return { s: BUILD_S, cls: "build" };
|
|
81
|
+
if (QUICK.has(base)) return { s: QUICK_S, cls: "quick" };
|
|
82
|
+
return { s: DEFAULT_S, cls: "default" };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The slowest segment's class — what decides a command's default timeout, and what the kill note names. */
|
|
86
|
+
export function timeoutClass(command: string): { s: number; cls: string } {
|
|
87
|
+
let best = { s: 0, cls: "" };
|
|
88
|
+
for (const seg of bashSegments(command)) {
|
|
89
|
+
const c = segClass(seg);
|
|
90
|
+
if (c.s > best.s) best = c;
|
|
50
91
|
}
|
|
51
|
-
|
|
52
|
-
if (SERVICE.has(base)) return /\bbuild\b/.test(seg) ? BUILD_S : SERVICE_S; // docker/compose build is an image build, not a service poke
|
|
53
|
-
if (BUILD.has(base)) return BUILD_S;
|
|
54
|
-
if (QUICK.has(base)) return QUICK_S;
|
|
55
|
-
return DEFAULT_S;
|
|
92
|
+
return best.s ? best : { s: DEFAULT_S, cls: "default" };
|
|
56
93
|
}
|
|
57
94
|
|
|
58
95
|
/**
|
|
@@ -61,9 +98,7 @@ function segTimeout(seg: string): number {
|
|
|
61
98
|
*/
|
|
62
99
|
export function bashTimeout(command: string, explicit?: number): number {
|
|
63
100
|
if (typeof explicit === "number" && Number.isFinite(explicit) && explicit > 0) return Math.min(explicit, CLAMP_S);
|
|
64
|
-
|
|
65
|
-
for (const seg of bashSegments(command)) t = Math.max(t, segTimeout(seg));
|
|
66
|
-
return t || DEFAULT_S;
|
|
101
|
+
return timeoutClass(command).s;
|
|
67
102
|
}
|
|
68
103
|
|
|
69
104
|
/**
|