pi-dev-flow 0.60.0 → 0.61.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 +24 -0
- package/README.md +6 -2
- package/docs/concurrency.md +3 -1
- package/docs/development.md +8 -4
- package/docs/gates.md +1 -1
- package/docs/guardrails.md +1 -1
- package/docs/headless.md +6 -2
- package/extensions/dev-flow.ts +79 -11
- package/package.json +1 -1
- package/src/core.ts +63 -73
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,30 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
|
|
|
4
4
|
|
|
5
5
|
## [Unreleased]
|
|
6
6
|
|
|
7
|
+
## [0.61.1] - 2026-10-23
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
|
|
11
|
+
- **The newest dev-flow copy judges the guards alone.** When one process runs several copies (the documented two-sources situation — a checkout's own `pi.extensions` manifest beside the npm install is the common one), every copy's event hooks now run an election first: a copy with a lower registered version answers nothing — no guard vetoes, no context injection, no footer, no compaction takeover. Stale code judging alongside fresh was the real hazard the two-sources warning hinted at: on a 22-hour-old pi-web server a 0.57.0-era copy blocked tool calls beside the current one, and nobody could say which copy answered. Node cannot unload a loaded module and pi cannot unregister its hooks, so silence is the most in-package removal can be — only a host restart drops the stale code, and the warnings now say so. Equal versions both judge; a copy whose version cannot be read is never outranked; gate tool handlers stay live on every copy (the host dispatches those per session, and the stale-build warnings already cover them).
|
|
12
|
+
|
|
13
|
+
### Fixed
|
|
14
|
+
|
|
15
|
+
- **The duplicate-copy warning names its speaker** — `this call served by <dir> (v); this copy is the newest and judges the guards` (or admits it is the older one and stays silent) — and the stale-build notes across `start`, `status` and `version` tell the truth about what fixes skew: `/reload` re-binds session state, but in a shared-process host (pi-web) only restarting the host swaps loaded code; docs/development.md and the README's two-sources section now say the same. Proven on the live server: a working-tree stamp frozen at 0.57.0 survived a day of reloads while the checkout shipped two versions.
|
|
16
|
+
|
|
17
|
+
## [0.61.0] - 2026-10-23
|
|
18
|
+
|
|
19
|
+
### Fixed
|
|
20
|
+
|
|
21
|
+
- **A green now belongs to the tree it ran against.** Every recorded check carries a fingerprint of its worktree — `status --porcelain`, a hash of the uncommitted diff, and HEAD — and `verify`/`release` drop records the tree has outgrown before deciding what is pending, then rerun them at the gate and say so (`stale record(s) rerun after a worktree change: …`). Edits through the edit tools already cleared records at once, but a write through bash — `sed -i`, a formatter, codegen — fires no hook, and the whole #84 sequence (check green, a bash-side fix, `verify`) rode a PASS measured against code that no longer existed. A commit after the check now re-proves at the gate too, so a green standing at a gate means the committed state. A record with no fingerprint (older build, or git could not answer) is never proven stale — the same measurement-failure stance as `commitsAhead`.
|
|
22
|
+
- **The delete guard reads absolute paths.** `rm -rf /abs/repo/.dev-flow/<slug>` deleted a feature — plan included — while the relative form was refused: `DF_FOLDER` demanded whitespace or a quote before `.dev-flow`, and absolute paths are the shape harnesses hand the agent. The boundary now accepts `/` too; quoted prose stays prose (the masked-payload exemption, #53, survives).
|
|
23
|
+
- **`flow abort` honors a live claim, and `claim.json` is now guarded.** Every gate refused another session's in-flight feature — except the one verb that deletes the whole feature: an unbound or other-session abort could erase a plan-stage directory while its owner was still writing it. The claim now locks `abort` exactly as it locks the gates (`flow use` remains the only takeover), and `claim.json` joins `state.json` as flow-owned in both guards — a lock is not unlocked by whoever it locks out.
|
|
24
|
+
- **`writeGuard` judges where the bytes land, not where the path points.** A symlink inside the worktree laundered a write anywhere: the stage rules compared lexical strings, so a worktree symlink into the main checkout passed a main-checkout write as confined — while `guardPath` had resolved the same symlink through realpath all along. The target, the feature worktrees and `.dev-flow` are now compared as realpaths (`realAbs`), and a symlinked escape gets the refusal its real target deserves.
|
|
25
|
+
|
|
26
|
+
### Changed
|
|
27
|
+
|
|
28
|
+
- **The UI plan hint names its file instead of eating it.** With `--ui`, the hint's mockup clause replaced the sentence's tail, leaving "write the plan into .dev-flow/<slug>/plan/" pointing at a directory; it now reads `plan/plan.md` and appends the mockup clause. Approval always demanded a real file — the hint just stopped saying so.
|
|
29
|
+
- **`buildConfig` leaves production code.** Nothing at runtime has built a `Config` from a raw object since `project.md` became the only config source — the tests keep the shorthand as a test helper. `getPath` (dead once the `project.json` loader was gone) and `gitInvocation`'s unused top-level last-cd-wins `dir` (the guard judges each segment's own dir) were deleted with it.
|
|
30
|
+
|
|
7
31
|
## [0.60.0] - 2026-10-23
|
|
8
32
|
|
|
9
33
|
### Changed
|
package/README.md
CHANGED
|
@@ -52,8 +52,12 @@ pi install ./pi-dev-flow # or a local checkout
|
|
|
52
52
|
Later releases arrive with `pi update --extensions` (an npm install reconciles to the newest version);
|
|
53
53
|
then `/reload` — a running session keeps the code it loaded at startup. Two sources at once (a project
|
|
54
54
|
`git:` pin beside the global `npm:` package) load two copies — pi dedupes extensions by path, not by
|
|
55
|
-
package — so keep the one you actually update from
|
|
56
|
-
|
|
55
|
+
package — so keep the one you actually update from. **The newest copy judges alone:** every copy's
|
|
56
|
+
guard hooks check which registered version is highest, and a stale duplicate answers nothing — the
|
|
57
|
+
most in-package removal can be, because Node cannot unload a loaded module and pi cannot unregister
|
|
58
|
+
its hooks. Only a host restart drops stale code; `/reload` re-binds session state, it never swaps
|
|
59
|
+
code. `flow version` lists every dev-flow copy registered in the process and names the copy serving
|
|
60
|
+
the call, and the on-disk session claim keeps the guard of a copy that never served
|
|
57
61
|
a flow call attributing your commands correctly.
|
|
58
62
|
|
|
59
63
|
Until `flow init` writes the playbook (`.dev-flow/project.md`), dev-flow says nothing in a repo — no
|
package/docs/concurrency.md
CHANGED
|
@@ -8,7 +8,9 @@ case. The binding lives with the session (persisted via session entries, restore
|
|
|
8
8
|
resume/fork), so nothing is repo-global. A session binds **explicitly, never automatically**:
|
|
9
9
|
`flow start` binds its own feature, `flow use <slug>` takes one over — even the lone unfinished
|
|
10
10
|
feature waits to be claimed. Every bind leaves a claim (`claim.json`, session + pid),
|
|
11
|
-
and the gates honor the claim too
|
|
11
|
+
and the gates honor the claim too — `flow abort` included, so the verb that erases a feature cannot
|
|
12
|
+
erase one a live session is working. The claim file is as guarded as `state.json`: neither the write
|
|
13
|
+
tools nor bash may change or delete it — a lock is not unlocked by whoever it locks out.
|
|
12
14
|
passing another session's slug to `flow approve`/`verify`/`finish` is refused until you take over,
|
|
13
15
|
or two sessions quietly overwrite one state file. `flow use <slug>` switches, and ambiguous sessions must
|
|
14
16
|
bind or pass explicit slugs. With nothing unfinished and no binding, the session must start a
|
package/docs/development.md
CHANGED
|
@@ -8,14 +8,18 @@ pi -e . run /flow status # try it against any repo
|
|
|
8
8
|
```
|
|
9
9
|
|
|
10
10
|
Sessions in this checkout load the **single global dev-flow install** (`pi update --extensions`
|
|
11
|
-
reconciles it after a release
|
|
11
|
+
reconciles it after a release; loaded code swaps only when the process re-imports — `/reload` in a
|
|
12
|
+
per-session host, a host restart in a shared-process host like pi-web) — there is deliberately no
|
|
12
13
|
`.pi/extensions/` pointer here: a committed shim beside the global package loads two copies of the
|
|
13
14
|
extension in one process (pi dedupes by path, not by package — see the README's two-sources
|
|
14
|
-
warning), which is what the shim used to cause.
|
|
15
|
-
|
|
15
|
+
warning), which is what the shim used to cause. The package's own `pi.extensions` manifest remains a
|
|
16
|
+
second source for any session opened in this checkout — deliberate dogfooding, made safe by the guard
|
|
17
|
+
election: the newest registered copy judges, older loaded copies answer nothing. To dogfood the
|
|
18
|
+
working tree instead of the installed copy, point pi at it explicitly for that run: `pi -e .`.
|
|
16
19
|
|
|
17
20
|
A release cannot update a session that is already running — pi keeps the code it loaded at startup.
|
|
18
|
-
After merging and tagging, `/reload` in every session that must carry the new behavior
|
|
21
|
+
After merging and tagging, `/reload` in every session that must carry the new behavior; shared-process
|
|
22
|
+
hosts (pi-web) keep stale code until restarted, so reload there re-binds state but does not swap code.
|
|
19
23
|
|
|
20
24
|
## The skill: an injected core, plus references a stage reads
|
|
21
25
|
|
package/docs/gates.md
CHANGED
|
@@ -15,7 +15,7 @@ so it needs no `--confirmed`.
|
|
|
15
15
|
| `test` | records a check | — (runs the `test` command/check, records pass/fail) |
|
|
16
16
|
| `check` | records all tier-1 checks | — (runs every `flow-check`/test/health from project.md `## implement`); a `--docs` feature runs none of them and says `docs mode: project commands skipped` — a docs flow builds nothing, so a fresh checkout must not read as a failed deploy (#96) |
|
|
17
17
|
| `health` | records a check | — (runs `seedData` + the health command, retrying up to `healthWait` seconds; app must be up locally with real data) |
|
|
18
|
-
| `verify [--yolo]` | implement → pre-release | 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 a failure there prints the run output, **the feature branch holds at least one commit** (verify refuses a branch with nothing committed — the checks describe the working tree, so an uncommitted state has never been recorded — and prints `commits: N ahead of <default>, M uncommitted path(s)` with what it ran; uncommitted paths are reported, never gated), build (if configured) green, `dev` deploy (if configured) runs first so you can review the running app **and the health probe (if configured) re-runs against what it just deployed, retrying every 2s up to `healthWait` seconds** (a failing probe refuses the gate and reports how many attempts it took: the `flow check` PASS predates the deploy, and a service that needs seconds after its container starts is not a broken deploy; with no probe the output says `health: none configured`), tier-2 checklist (ui-only items excluded for non-UI features) confirmed as a set; a `--docs` feature runs none of it (`docs mode: project commands skipped`) and only asks you; **one question** — or `--confirmed`; `--yolo --confirmed` = you answered 'yolo' at Verified? — answers it and pre-confirms the rest |
|
|
18
|
+
| `verify [--yolo]` | implement → pre-release | all tier-1 checks green — a check with no passing record is **run by the gate itself** (`checks ran at the gate (test)`) rather than refused and pointed at `flow check`, since entering the stage or editing the worktree is what cleared it — and so is a record whose worktree fingerprint differs from the tree now (`stale record(s) rerun after a worktree change: …`): a change made through bash fires no edit-tool hook, the fingerprint is what notices the tree moved — and a failure there prints the run output, **the feature branch holds at least one commit** (verify refuses a branch with nothing committed — the checks describe the working tree, so an uncommitted state has never been recorded — and prints `commits: N ahead of <default>, M uncommitted path(s)` with what it ran; uncommitted paths are reported, never gated), build (if configured) green, `dev` deploy (if configured) runs first so you can review the running app **and the health probe (if configured) re-runs against what it just deployed, retrying every 2s up to `healthWait` seconds** (a failing probe refuses the gate and reports how many attempts it took: the `flow check` PASS predates the deploy, and a service that needs seconds after its container starts is not a broken deploy; with no probe the output says `health: none configured`), tier-2 checklist (ui-only items excluded for non-UI features) confirmed as a set; a `--docs` feature runs none of it (`docs mode: project commands skipped`) and only asks you; **one question** — or `--confirmed`; `--yolo --confirmed` = you answered 'yolo' at Verified? — answers it and pre-confirms the rest |
|
|
19
19
|
| `release [--yolo|--no-version|--no-fold-check]` | pre-release → release | checks re-greened after the prep edits; 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 pending baseline is the newest tag's changelog (what actually shipped), else the branch's merge base; when neither resolves, the two git-dependent proofs are skipped **with a printed advisory** rather than refusing a legal release for a topology reason, and the content proofs (the heading, its body) always run; tier-2 `## pre-release` checklist confirmed; the manifest version it validates is **stamped as the release's version of record** (`release-done` publishes that, whatever the checkouts say later); **one question** (Release?) — or `--confirmed`; `--no-version` (your call at Release?) ships this flow as **merge + changelog** — the bump/tag requirements and the tag checks at `release-done` are skipped for it, but the branch must still add its **own line under `Unreleased`** (editing an older section releases nothing) and it rides there until the next versioned release folds it (default: versioned); `--no-fold-check` is the operator-granted escape from the line-level fold proofs — one flow, stamped in the gate output, the heading and touched proofs stay; **stale session build** (loaded build behind the checkout): the gate prints both builds, lists what shipped between them (those proofs will not run this release) and folds *update (/reload, then re-run) or proceed with the old release?* into the Release? question — the operator's word, recorded in the release output, **never a block**: publishing under an older gate is a legitimate choice (hotfix, offline reload) |
|
|
20
20
|
| `release-done` | records the release (the stage stays `release`) | **no question — the Release? answer covered the publication**; verify approval; the version published is the one `release` **stamped** from the manifest it validated (a main checkout still behind cannot republish the previous version), and it must not be older than the newest matching tag **on origin** (tag lists come from `git ls-remote`, so an unfetched clone does not decide what exists; when an origin exists but cannot be asked (offline, no ssh agent) **both release gates refuse** rather than answering with local tags); with `versioning.file`: that tag exists, is reachable from the default branch **and is on origin** (a local-only tag is not a release); with `release.artifact`: the published-artifact check runs (`{version}`/`{tag}` placeholders — the line it prints names the version it verified; skip once with `--no-artifact-check`, operator-instructed only) · creates the forge release from the tag, its body **the `release.changelog` entry for that version** — the changelog is the source of truth, and the tag's annotation stands in only when the changelog has no entry for the version, else nothing (and it says why — a body that is really a shell error is dropped, never shipped) — `gh` for GitHub, `glab` for GitLab) and then **proves the release exists**: it asks the forge (`gh release view <tag>` / `glab release view <tag>`) and refuses when nothing is there, because #51, #60 and #63 were three ways of ending `release recorded as complete` with nothing published — and when the changelog was the body it **reads the stored body back** and refuses a mismatch, so the release page and the changelog cannot drift (#97; normalized before comparing, skipped with a printed note on another forge). Skipping is deliberate and loud — `--no-release-create`, `release.releases = false` or `forge = self` each print that no forge release was created, and the view check is skipped for them; **with a `merge` policy** it also proves the merge that shipped matches it — branch ancestry plus what the forge says (`gh pr view` / `glab api`), so a squash under `merge = merge` (or a merge commit under `merge = squash`) refuses the release record, while a shape it cannot see prints an advisory instead (#97's split: an invisible topology never blocks a legal release); when the release went out on a stale build the operator acknowledged at the release gate, it prints that acknowledgement in place of the after-the-fact version-skew warning |
|
|
21
21
|
| `finish [--yolo] [slug]` | release → done (removes worktree + branch, deletes `.dev-flow/<slug>/`, and deletes `origin/<branch>` **only** when its merged state is verified — ancestor of the default branch or a merged PR/MR via `gh`/`glab`; unverifiable branches stay with a note) | a release is recorded (`release-done` ran), the main checkout is clean **and** pushed to `origin/<default>`, and the worktree has no uncommitted changes; 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
|
@@ -8,7 +8,7 @@ While a feature is active, the extension intercepts every tool call:
|
|
|
8
8
|
- **No code before an approved plan**: at stage `plan`, edits are confined to `.dev-flow/<slug>/` — the session's **own** feature directory, so one session cannot write another feature's plan and have its gate rubber-stamp what it never wrote.
|
|
9
9
|
- **Work stays in the worktree**: at stages `implement` and `pre-release`, edits are confined to that feature's worktree — judged per-path by the owning feature, so one session can never write into another session's worktree or into the main checkout. A throwaway **outside** the checkout is not feature work and stays free at every stage (the OS temp dir, e.g. a one-off rewrite script): both sides are realpath'd, so a symlink out of the temp dir is still judged as the repo path it writes, and a repository that merely lives under the temp dir (a test repo) keeps the stage rules.
|
|
10
10
|
- **Flow by default**: in a repo with `.dev-flow/`, an unbound session cannot touch source files at all — every request goes through `flow start`/`flow use`; there is no bypass. `flow start` refuses when the main checkout isn't on the default branch, worktrees are always created from the default branch, and the agent cannot check feature branches out in the main checkout.
|
|
11
|
-
- **Gates can't be skipped**: flow state is untouchable by the agent (edit tool and bash) — writing `state.json`, moving
|
|
11
|
+
- **Gates can't be skipped**: flow state is untouchable by the agent (edit tool and bash) — writing `state.json` or `claim.json`, moving either away, or deleting a feature directory or the whole `.dev-flow/` folder all block, at a relative **or an absolute** path (an absolute path names the same folder); the `project.md` playbook is operator-owned — the main-checkout copy is blocked for the agent outright, and only a **docs or patch flow's** worktree copy may be edited (normal features route playbook changes to their own flow); every sanctioned playbook overwrite keeps the previous file as `project.md.bak`; every recorded check carries a fingerprint of the worktree it ran against (paths, uncommitted diff, HEAD) — an edit-tool change clears the records at once, and any other write (`sed -i`, a formatter, codegen through bash) is caught at the gate itself, which reruns what went stale and says so; edit/write paths are judged by realpath, so a symlink out of the worktree cannot launder a confined write.
|
|
12
12
|
- **Your project's own rules**: every `deny`/`confirm`/`protect`/`forbid` rule from the `flow-guard` block in project.md `## global` runs on every bash command and every edit/write path — in every stage and binding, ahead of dev-flow's own verdicts. A block always carries the reason you wrote.
|
|
13
13
|
- **The rules reach the agent, they are not left in a file it may never read**: pi advertises a skill and loads it only if the model chooses to, so the ground rules of the dev-flow skill are injected into every session once (and again after a compaction that summarized them away), and each stage's turn names the one playbook file that stage needs. The guards enforce the same discipline either way — this is what makes the agent follow it without being stuck.
|
|
14
14
|
- **A forced push asks the operator**: `git push` carrying `--force`, `--force-with-lease…` or `-f` is confirmed before it runs — a rewritten branch is history CI and other sessions already have. The one spelling that answers for it is the prefix the refusal prints (`DEV_FLOW_ALLOW_REWRITE=1 git push -f …`), the same "the operator said so" contract as `DEV_FLOW_ALLOW_MAIN`. Local history rewrites (`git filter-branch --force`) are not pushes and stay free, so a project never needs a blunt flag-only deny of its own.
|
package/docs/headless.md
CHANGED
|
@@ -35,8 +35,12 @@ The contract a headless driver (a session with no UI) relies on:
|
|
|
35
35
|
`dev` deploy (runs are killed past 15 min) and re-probes health with `healthWait` retries.
|
|
36
36
|
A remote timeout must be minutes, not seconds — the gate prints progress lines while it
|
|
37
37
|
runs.
|
|
38
|
-
- **Edits invalidate checks.**
|
|
39
|
-
confirmation
|
|
38
|
+
- **Edits invalidate checks.** An edit-tool write clears recorded checks and the tier-2
|
|
39
|
+
confirmation at once; any other worktree write (bash: `sed -i`, a formatter, codegen) is caught
|
|
40
|
+
at the gate — every check carries a fingerprint of the tree it ran against, and verify/release
|
|
41
|
+
rerun records the tree has outgrown (`stale record(s) rerun after a worktree change: …`).
|
|
42
|
+
Re-running `flow check` before `verify` after the last edit is still the tidy order; the gate no
|
|
43
|
+
longer trusts a stale PASS if you skip it.
|
|
40
44
|
- **Version skew.** Gates execute the dev-flow build the session loaded at start; `flow version`
|
|
41
45
|
reports when the checkout has moved ahead of it. `flow release` turns the skew into a question —
|
|
42
46
|
update (`/reload`, then re-run) or proceed with the old release — never a block: publishing under
|
package/extensions/dev-flow.ts
CHANGED
|
@@ -33,6 +33,7 @@ import {
|
|
|
33
33
|
appendReflection,
|
|
34
34
|
appendRoadmapItem,
|
|
35
35
|
bashFlowGuard,
|
|
36
|
+
checkFingerprint,
|
|
36
37
|
changelogEntry,
|
|
37
38
|
changelogVersionsBetween,
|
|
38
39
|
normalizeReleaseBody,
|
|
@@ -53,6 +54,7 @@ import {
|
|
|
53
54
|
FLOW_SHELL_HINT,
|
|
54
55
|
flowShellInvocation,
|
|
55
56
|
forcePushInvocation,
|
|
57
|
+
freshenChecks,
|
|
56
58
|
gateHelpJson,
|
|
57
59
|
gitInvocation,
|
|
58
60
|
githubSlug,
|
|
@@ -165,11 +167,24 @@ function registerCopy(): void {
|
|
|
165
167
|
function otherCopies(): CopyEntry[] {
|
|
166
168
|
return COPIES.filter((r) => r.pid === process.pid && r.dir !== SELF_BUILD.dir);
|
|
167
169
|
}
|
|
170
|
+
/** Election: when one process runs several dev-flow copies (the documented two-sources hazard, or a
|
|
171
|
+
* copy whose loaded code predates an update), only the highest-version copy may judge — stale code
|
|
172
|
+
* must not veto tool calls with a build nobody reviewed. Node cannot unload a loaded module and pi
|
|
173
|
+
* cannot unregister its hooks, so silence is the most removal can be from inside the package; only
|
|
174
|
+
* a host restart truly drops stale code. Equal versions both judge (same code, same verdicts); a
|
|
175
|
+
* copy whose version cannot be read is never outranked. Gate tool/command handlers stay live on
|
|
176
|
+
* every copy: the host dispatches a session's flow calls to whichever copy loaded that session,
|
|
177
|
+
* and staleness there is what the /reload warnings address. */
|
|
178
|
+
function guardsAreMine(): boolean {
|
|
179
|
+
const mine = SELF_BUILD.version;
|
|
180
|
+
if (!mine) return true; // an unreadable version is never outranked
|
|
181
|
+
return !otherCopies().some((r) => r.version && cmpVersions(r.version, mine) > 0);
|
|
182
|
+
}
|
|
168
183
|
function copyWarning(): string | null {
|
|
169
184
|
const dup = otherCopies();
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
185
|
+
if (!dup.length) return null;
|
|
186
|
+
const verdict = guardsAreMine() ? "this copy is the newest and judges the guards" : "this copy is older and stays silent \u2014 the newest copy judges";
|
|
187
|
+
return `warning: ${dup.length} other dev-flow cop${dup.length === 1 ? "y" : "ies"} registered in this process: ${dup.map((d) => `${d.dir} (${d.version ?? "?"})`).join(", ")} \u2014 this call served by ${SELF_BUILD.dir} (${SELF_BUILD.version ?? "?"}); ${verdict}. Keep only one source you intend; a host restart drops stale code (README: two sources at once)`;
|
|
173
188
|
}
|
|
174
189
|
/** Test seam: the smoke suite cannot load a second copy of this module, so it plants registry
|
|
175
190
|
* entries and asserts the warnings the real duplicate would print. */
|
|
@@ -554,13 +569,14 @@ function gateCwd(root: string, state: FlowState): string {
|
|
|
554
569
|
* `health` is left to the post-deploy probe when there is a deploy to prove: probing twice only waits twice. */
|
|
555
570
|
function pendingChecks(state: FlowState, cfg: Config): StageCheck[] {
|
|
556
571
|
if (state.docs) return [];
|
|
557
|
-
return cfg.checkList.filter((c) => !state.checks[c.name]?.ok && !(c.name === "health" &&
|
|
572
|
+
return cfg.checkList.filter((c) => !state.checks[c.name]?.ok && !(c.name === "health" && healthRerunsAfterDeploy(cfg)));
|
|
558
573
|
}
|
|
559
574
|
|
|
560
575
|
/** Run tier-1 checks in the feature cwd and record each result (health seeds first, as `flow health` does). */
|
|
561
576
|
async function runChecks(root: string, state: FlowState, cfg: Config, checks: StageCheck[]): Promise<{ lines: string[]; failed: boolean }> {
|
|
562
577
|
const lines: string[] = [];
|
|
563
578
|
let failed = false;
|
|
579
|
+
const ran: string[] = [];
|
|
564
580
|
for (const c of checks) {
|
|
565
581
|
if (c.name === "health" && cfg.commands.seedData) {
|
|
566
582
|
const seed = await sh(cfg.commands.seedData, gateCwd(root, state));
|
|
@@ -572,13 +588,39 @@ async function runChecks(root: string, state: FlowState, cfg: Config, checks: St
|
|
|
572
588
|
}
|
|
573
589
|
const res = await sh(c.cmd, gateCwd(root, state));
|
|
574
590
|
state.checks[c.name] = { ok: res.ok, at: now() };
|
|
591
|
+
ran.push(c.name);
|
|
575
592
|
lines.push(`${c.name}: ${res.ok ? "PASS" : "FAIL"} (${c.cmd})${res.ok ? "" : `\n${tail(res.out)}`}`);
|
|
576
593
|
if (!res.ok) failed = true;
|
|
577
594
|
}
|
|
595
|
+
await stampChecks(root, state, ran);
|
|
578
596
|
writeState(root, state);
|
|
579
597
|
return { lines, failed };
|
|
580
598
|
}
|
|
581
599
|
|
|
600
|
+
/** Which health record a verify may leave stale on purpose: the post-deploy probe re-runs it, so
|
|
601
|
+
* the pre-deploy record must survive the gate that schedules the deploy. */
|
|
602
|
+
const healthRerunsAfterDeploy = (cfg: Config) => !!cfg.commands.dev && !!healthProbe(cfg);
|
|
603
|
+
|
|
604
|
+
/** Fingerprint of the working-tree state the checks ran against: paths (`status --porcelain`),
|
|
605
|
+
* tracked content (a hash of the uncommitted diff) and HEAD. Null when git cannot answer — a
|
|
606
|
+
* measurement failure must never mark a green record stale (see freshenChecks). */
|
|
607
|
+
async function worktreeFingerprint(cwd: string): Promise<string | null> {
|
|
608
|
+
const st = await sh("git status --porcelain", cwd);
|
|
609
|
+
if (!st.ok) return null;
|
|
610
|
+
const diff = await sh("git diff HEAD --no-color | git hash-object --stdin", cwd);
|
|
611
|
+
const head = await sh("git rev-parse HEAD", cwd);
|
|
612
|
+
if (!diff.ok || !head.ok) return null;
|
|
613
|
+
return checkFingerprint(`${st.out}\n${diff.out}`, head.out);
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/** Stamp freshly recorded checks with the tree they ran against — taken AFTER the run, so a check
|
|
617
|
+
* that rewrites tracked files (a formatter, codegen) does not mark itself stale the moment it passes. */
|
|
618
|
+
async function stampChecks(root: string, state: FlowState, names: string[]): Promise<void> {
|
|
619
|
+
const fp = await worktreeFingerprint(gateCwd(root, state));
|
|
620
|
+
if (!fp) return;
|
|
621
|
+
for (const n of names) if (state.checks[n]) state.checks[n].wt = fp;
|
|
622
|
+
}
|
|
623
|
+
|
|
582
624
|
/** Commits the feature branch holds over its merge base with the default branch, plus how many
|
|
583
625
|
* paths sit uncommitted: verify's proof that there is a committed state behind the operator's
|
|
584
626
|
* question. Local refs only — same offline-safe stance as the changelog proof — and an
|
|
@@ -827,7 +869,7 @@ ${mdDigest(draftRefresh)}`))
|
|
|
827
869
|
const notes: string[] = [];
|
|
828
870
|
const disk = checkoutBuild(root);
|
|
829
871
|
const behind = sessionRunsOlderBuild(loadedVersion(), disk.version);
|
|
830
|
-
if (behind) notes.push(`warning: this session runs dev-flow ${behind}, ${disk.label} ships ${disk.version} — /reload
|
|
872
|
+
if (behind) notes.push(`warning: this session runs dev-flow ${behind}, ${disk.label} ships ${disk.version} — /reload rebinds session state; only restarting the host swaps the code it runs`);
|
|
831
873
|
const dupStart = copyWarning();
|
|
832
874
|
if (dupStart) notes.push(dupStart);
|
|
833
875
|
if (flag("check-upstream")) {
|
|
@@ -883,7 +925,7 @@ ${mdDigest(draftRefresh)}`))
|
|
|
883
925
|
// gate proof printed since the drift began belongs to the older code.
|
|
884
926
|
const disk = checkoutBuild(root);
|
|
885
927
|
const staleBuild = sessionRunsOlderBuild(loadedVersion(), disk.version);
|
|
886
|
-
const warn = [...(findings.length ? [`⚠ doctor: ${findings.length} finding(s) — run flow doctor`] : []), ...(staleBuild ? [`⚠ this session runs dev-flow ${staleBuild}, ${disk.label} ships ${disk.version} — /reload`] : []), ...(copyWarning() ? [copyWarning()!] : [])];
|
|
928
|
+
const warn = [...(findings.length ? [`⚠ doctor: ${findings.length} finding(s) — run flow doctor`] : []), ...(staleBuild ? [`⚠ this session runs dev-flow ${staleBuild}, ${disk.label} ships ${disk.version} — /reload rebinds; restart swaps code`] : []), ...(copyWarning() ? [copyWarning()!] : [])];
|
|
887
929
|
// the backlog nudge belongs to the no-features answer too — that is when a pick is most useful
|
|
888
930
|
const rmap = roadmapOpenCount(readRoadmap(root));
|
|
889
931
|
const rmapLine = rmap ? [`◇ ${rmap} roadmap item(s) open — flow roadmap`] : [];
|
|
@@ -1001,7 +1043,7 @@ ${mdDigest(draftRefresh)}`))
|
|
|
1001
1043
|
const newest = pub.ok ? pub.out.trim().split("\n").pop() : "";
|
|
1002
1044
|
return { text: newest ? `${head} — published: ${newest}${self.version && newest !== self.version ? " (update available)" : ""}` : `${head} — could not read the published version (offline?)` };
|
|
1003
1045
|
}
|
|
1004
|
-
return { text: `${behind ? `${head} — but this session runs ${behind}${from}; /reload to run ${self.version}` : head}${dupNote ? `\n${dupNote}` : ""}` };
|
|
1046
|
+
return { text: `${behind ? `${head} — but this session runs ${behind}${from}; /reload to run ${self.version} \u2014 in a shared-process host (pi-web) reload cannot swap loaded code: only a host restart does` : head}${dupNote ? `\n${dupNote}` : ""}` };
|
|
1005
1047
|
}
|
|
1006
1048
|
|
|
1007
1049
|
case "approve": {
|
|
@@ -1054,6 +1096,7 @@ ${mdDigest(draftRefresh)}`))
|
|
|
1054
1096
|
if (!cfg.commands.test) return { text: "no commands.test configured — add `test = <command>` under ## implement in .dev-flow/project.md", isError: true };
|
|
1055
1097
|
const res = await sh(cfg.commands.test, gateCwd(root, state!));
|
|
1056
1098
|
state!.checks.test = { ok: res.ok, at: now() };
|
|
1099
|
+
await stampChecks(root, state!, ["test"]);
|
|
1057
1100
|
writeState(root, state!);
|
|
1058
1101
|
return { text: `test: ${res.ok ? "PASS" : "FAIL"} (${cfg.commands.test})\n${tail(res.out)}` };
|
|
1059
1102
|
}
|
|
@@ -1064,8 +1107,11 @@ ${mdDigest(draftRefresh)}`))
|
|
|
1064
1107
|
const items = applicableItems(cfg, state!, "implement");
|
|
1065
1108
|
const branch = await branchState(gateCwd(root, state!), cfg.defaultBranch);
|
|
1066
1109
|
const branchLine = describeBranchState(branch, cfg.defaultBranch);
|
|
1067
|
-
//
|
|
1068
|
-
//
|
|
1110
|
+
// A green record belongs to the tree it ran against. A worktree change made through bash (sed,
|
|
1111
|
+
// a formatter, codegen) fires no edit-tool invalidation — the fingerprint is what notices the
|
|
1112
|
+
// tree moved, and the dropped records become pending so the gate itself reruns them (#84 path).
|
|
1113
|
+
const staleAtGate = freshenChecks(state!, await worktreeFingerprint(gateCwd(root, state!)), (n) => n === "health" && healthRerunsAfterDeploy(cfg));
|
|
1114
|
+
if (staleAtGate.length) writeState(root, state!);
|
|
1069
1115
|
const pending = pendingChecks(state!, cfg);
|
|
1070
1116
|
const gateRun = pending.length ? await runChecks(root, state!, cfg, pending) : null;
|
|
1071
1117
|
if (gateRun?.failed) return { text: `verify gate FAILED — a check run at the gate failed:\n${gateRun.lines.join("\n")}\n${branchLine}`, isError: true };
|
|
@@ -1076,6 +1122,7 @@ ${mdDigest(draftRefresh)}`))
|
|
|
1076
1122
|
// agent tell the operator the dev deploy had never run, right after it recreated a container.
|
|
1077
1123
|
const did: string[] = [];
|
|
1078
1124
|
if (gateRun) did.push(`checks ran at the gate (${pending.map((c) => c.name).join(", ")})`);
|
|
1125
|
+
if (staleAtGate.length) did.push(`stale record(s) rerun after a worktree change: ${staleAtGate.join(", ")}`);
|
|
1079
1126
|
if (state!.docs) {
|
|
1080
1127
|
// docs mode's contract: no tier-1 work happens, so a docs flow neither builds, deploys nor probes (#43 #49)
|
|
1081
1128
|
did.push("docs mode: project commands skipped (build/dev/health)");
|
|
@@ -1109,6 +1156,7 @@ ${mdDigest(draftRefresh)}`))
|
|
|
1109
1156
|
}
|
|
1110
1157
|
const probed = await runHealthProbe(probe, gateCwd(root, state!), cfg.healthWait);
|
|
1111
1158
|
state!.checks.health = { ok: probed.ok, at: now() };
|
|
1159
|
+
await stampChecks(root, state!, ["health"]);
|
|
1112
1160
|
writeState(root, state!);
|
|
1113
1161
|
// a probe that needed the wait budget says so — "it passed on the 9th try" is the operator's business (#42)
|
|
1114
1162
|
const tried = probed.attempts > 1 ? `, ${probed.attempts} attempts` : "";
|
|
@@ -1165,6 +1213,7 @@ ${mdDigest(draftRefresh)}`))
|
|
|
1165
1213
|
}
|
|
1166
1214
|
const res = await runHealthProbe(cfg.commands.health, gateCwd(root, state!), cfg.healthWait);
|
|
1167
1215
|
state!.checks.health = { ok: res.ok, at: now() };
|
|
1216
|
+
await stampChecks(root, state!, ["health"]);
|
|
1168
1217
|
writeState(root, state!);
|
|
1169
1218
|
const tried = res.attempts > 1 ? `, ${res.attempts} attempts` : "";
|
|
1170
1219
|
return { text: `health: ${res.ok ? "PASS" : "FAIL"} (${cfg.commands.health}${tried})\n${tail(res.out)}` };
|
|
@@ -1222,6 +1271,8 @@ ${mdDigest(draftRefresh)}`))
|
|
|
1222
1271
|
}
|
|
1223
1272
|
}
|
|
1224
1273
|
const prep = { manifestVersion: manifestVer, remoteTags, changelog, changelogChanged, changelogBase, noFoldCheck: flag("no-fold-check") };
|
|
1274
|
+
// same freshness rule as verify: a green predating a worktree write may not stand for the tree this gate blesses
|
|
1275
|
+
if (freshenChecks(state!, await worktreeFingerprint(wtCwd)).length) writeState(root, state!);
|
|
1225
1276
|
// tier-2 pre-release confirmation is recorded by this very command, so it is excluded here
|
|
1226
1277
|
const preGate = preReleaseGate({ ...state!, confirmations: { ...state!.confirmations, "pre-release": { hash: checklistHash(items), at: now() } } }, cfg, prep);
|
|
1227
1278
|
if (preGate.length) return { text: `release gate FAILED:\n- ${preGate.join("\n- ")}`, isError: true };
|
|
@@ -1565,6 +1616,10 @@ ${mdDigest(draftRefresh)}`))
|
|
|
1565
1616
|
const target = slugArg ?? sess.slug;
|
|
1566
1617
|
if (!target) return { text: "nothing bound — pass a slug", isError: true };
|
|
1567
1618
|
const st = readState(root, target);
|
|
1619
|
+
// a live claim locks the whole feature, not only its gates: aborting it out from under the session
|
|
1620
|
+
// that works it erases the plan that session is still writing (same rule needState applies)
|
|
1621
|
+
const claim = readClaim(root, target);
|
|
1622
|
+
if (claimBlocks(claim, sess.key)) return { text: `${target} is claimed by another live session (pid ${claim!.pid}) — flow use ${target} takes it over explicitly`, isError: true };
|
|
1568
1623
|
if (sess.slug === target) sess.bind(null);
|
|
1569
1624
|
if (st && !st.worktree) {
|
|
1570
1625
|
// plan-stage abort = drop: no worktree/branch exists, so the state dir would linger
|
|
@@ -1742,23 +1797,32 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
1742
1797
|
|
|
1743
1798
|
// Agent-run gates refresh at turn_end (tool ctx lacks setStatus; turn_end catches them).
|
|
1744
1799
|
pi.on("session_start", async (_event, ctx) => {
|
|
1800
|
+
if (!guardsAreMine()) return;
|
|
1745
1801
|
rebuildSession(ctx);
|
|
1746
1802
|
refreshStatus(ctx);
|
|
1747
1803
|
});
|
|
1748
|
-
pi.on("session_tree", async (_event, ctx) =>
|
|
1804
|
+
pi.on("session_tree", async (_event, ctx) => {
|
|
1805
|
+
if (!guardsAreMine()) return;
|
|
1806
|
+
rebuildSession(ctx);
|
|
1807
|
+
});
|
|
1749
1808
|
// The session, not the process, owns the binding and the claim: pi-web keeps serving other sessions
|
|
1750
1809
|
// after one ends, and a stale claim there is a permanent lock (its pid is the server's, always alive).
|
|
1751
1810
|
pi.on("session_shutdown", async (_event, ctx) => {
|
|
1811
|
+
if (!guardsAreMine()) return;
|
|
1752
1812
|
if (!existsSync(dfDir(ctx.cwd))) return;
|
|
1753
1813
|
releaseSession(ctx.cwd, sessionKey(ctx));
|
|
1754
1814
|
});
|
|
1755
1815
|
pi.on("turn_end", async (_event, ctx) => {
|
|
1816
|
+
if (!guardsAreMine()) return;
|
|
1756
1817
|
refreshStatus(ctx);
|
|
1757
1818
|
// pi checks its compaction threshold between every turn; our safe points must be as frequent.
|
|
1758
1819
|
maybeCompactNow(ctx);
|
|
1759
1820
|
});
|
|
1760
1821
|
// Idle backstop: long between-gate runs compact here instead of letting pi hit the threshold mid-work.
|
|
1761
|
-
pi.on("agent_settled", async (_event, ctx) =>
|
|
1822
|
+
pi.on("agent_settled", async (_event, ctx) => {
|
|
1823
|
+
if (!guardsAreMine()) return;
|
|
1824
|
+
maybeCompactNow(ctx);
|
|
1825
|
+
});
|
|
1762
1826
|
// pi forcing a threshold compaction while a flow is bound means our safe-point pacing missed — rebuild the
|
|
1763
1827
|
// summary here with flow-aware instructions and hand it back through the event's custom-compaction channel.
|
|
1764
1828
|
// Never ctx.compact() from this hook: AgentSession.compact() opens with abort() + waitForIdle(), and the run
|
|
@@ -1766,6 +1830,7 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
1766
1830
|
// reaches the provider). If our summary fails we return undefined and pi's own compaction proceeds.
|
|
1767
1831
|
// overflow is never taken over (cancelling it would drop pi's compact-and-retry); manual is the operator's or ours.
|
|
1768
1832
|
pi.on("session_before_compact", async (event, ctx) => {
|
|
1833
|
+
if (!guardsAreMine()) return undefined;
|
|
1769
1834
|
if (!initiated(ctx.cwd)) return undefined;
|
|
1770
1835
|
const key = sessionKey(ctx);
|
|
1771
1836
|
const st = boundFeature(ctx.cwd, key);
|
|
@@ -1789,6 +1854,7 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
1789
1854
|
});
|
|
1790
1855
|
// pi forcing its own compaction while a flow is bound means the pacing was wrong — park a note for the operator.
|
|
1791
1856
|
pi.on("session_compact", async (event, ctx) => {
|
|
1857
|
+
if (!guardsAreMine()) return;
|
|
1792
1858
|
if (!initiated(ctx.cwd)) return;
|
|
1793
1859
|
// Whatever the reason, the summary replaced the transcript — the core the first run injected is
|
|
1794
1860
|
// gone from context, so the next run pays it once more (manual compactions included: our own
|
|
@@ -1807,6 +1873,7 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
1807
1873
|
});
|
|
1808
1874
|
|
|
1809
1875
|
pi.on("tool_call", async (event, ctx) => {
|
|
1876
|
+
if (!guardsAreMine()) return undefined; // election: only the newest loaded copy judges
|
|
1810
1877
|
// pi kills a shell call only when a timeout was passed, and the model omits it in ~75% of
|
|
1811
1878
|
// calls (observed hangs: hours). Deterministic class defaults, clamped ceilings — runs for
|
|
1812
1879
|
// every session that loads this package, flow-bound or not.
|
|
@@ -1935,6 +2002,7 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
1935
2002
|
});
|
|
1936
2003
|
|
|
1937
2004
|
pi.on("before_agent_start", async (_event, ctx) => {
|
|
2005
|
+
if (!guardsAreMine()) return undefined;
|
|
1938
2006
|
// One [dev-flow] line per run, whatever number of copies of this package are installed.
|
|
1939
2007
|
// The same package reaches one runtime twice all the time (a project pin beside the npm install,
|
|
1940
2008
|
// or this checkout's .pi/extensions pointer beside it) and pi dedupes extensions by file path
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-dev-flow",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.61.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": [
|
package/src/core.ts
CHANGED
|
@@ -16,6 +16,11 @@ export interface Check {
|
|
|
16
16
|
ok: boolean;
|
|
17
17
|
at: string;
|
|
18
18
|
note?: string;
|
|
19
|
+
/** The worktree state this check actually ran against (see checkFingerprint). A record whose
|
|
20
|
+
* fingerprint differs from the current tree at gate time was measured against code that no
|
|
21
|
+
* longer exists — green is not enough when the tree moved under it. Absent = recorded by an
|
|
22
|
+
* older build, or git could not be asked: never proven stale, never dropped. */
|
|
23
|
+
wt?: string;
|
|
19
24
|
}
|
|
20
25
|
|
|
21
26
|
export interface StageCheck {
|
|
@@ -175,38 +180,6 @@ export function stageReference(stage: Stage): string | null {
|
|
|
175
180
|
return STAGE_REFERENCE[stage] ?? null;
|
|
176
181
|
}
|
|
177
182
|
|
|
178
|
-
/** Build a Config from DEFAULTS + a partial overrides object (tests, drafts — the persisted
|
|
179
|
-
* source is project.md alone; the legacy project.json loader is gone). */
|
|
180
|
-
export function buildConfig(raw: unknown): Config {
|
|
181
|
-
const c: Config = structuredClone(DEFAULTS);
|
|
182
|
-
if (!raw || typeof raw !== "object") return c;
|
|
183
|
-
const r = raw as Record<string, unknown>;
|
|
184
|
-
for (const key of ["defaultBranch", "branchPattern", "worktreeDir", "mainHook", "forge"] as const) {
|
|
185
|
-
if (typeof r[key] === "string" || typeof r[key] === "boolean") (c[key] as never) = r[key] as never;
|
|
186
|
-
}
|
|
187
|
-
if (Array.isArray(r.mockupGlobs)) c.mockupGlobs = r.mockupGlobs.map(String);
|
|
188
|
-
if (r.commands && typeof r.commands === "object")
|
|
189
|
-
for (const [k, v] of Object.entries(r.commands as Record<string, unknown>)) if (typeof v === "string") (c.commands as Record<string, string>)[k] = v;
|
|
190
|
-
if (r.release && typeof r.release === "object") Object.assign(c.release, r.release);
|
|
191
|
-
if (r.healthWait !== undefined) c.healthWait = toSeconds(r.healthWait) ?? c.healthWait;
|
|
192
|
-
if (r.versioning && typeof r.versioning === "object") {
|
|
193
|
-
const v = r.versioning as Record<string, unknown>;
|
|
194
|
-
if (typeof v.file === "string") c.versioning.file = v.file;
|
|
195
|
-
if (typeof v.pattern === "string") c.versioning.pattern = v.pattern;
|
|
196
|
-
}
|
|
197
|
-
if (r.guard && typeof r.guard === "object") {
|
|
198
|
-
const g = r.guard as Record<string, unknown>;
|
|
199
|
-
for (const verb of ["deny", "confirm", "protect", "forbid"] as const)
|
|
200
|
-
if (Array.isArray(g[verb])) c.guard[verb] = normalizeGuardRules(g[verb]);
|
|
201
|
-
}
|
|
202
|
-
// tier-1 checks from plain commands so legacy project.json keeps the same teeth as project.md
|
|
203
|
-
c.checkList = [
|
|
204
|
-
...(c.commands.test ? [{ name: "test", cmd: c.commands.test }] : []),
|
|
205
|
-
...(c.commands.health ? [{ name: "health", cmd: c.commands.health }] : []),
|
|
206
|
-
];
|
|
207
|
-
return c;
|
|
208
|
-
}
|
|
209
|
-
|
|
210
183
|
/** The project's own "running and healthy" probe — `commands.health` or a flow-check block named
|
|
211
184
|
* health. The plugin runs it, the project says what healthy means (readiness, served build stamp). */
|
|
212
185
|
export function healthProbe(c: Config): string | undefined {
|
|
@@ -457,6 +430,36 @@ export function checklistHash(items: ChecklistItem[]): string {
|
|
|
457
430
|
.slice(0, 12);
|
|
458
431
|
}
|
|
459
432
|
|
|
433
|
+
/** Fingerprint of the worktree state a tier-1 check ran against: the caller composes the working
|
|
434
|
+
* tree's `git status --porcelain`, the hash of its uncommitted `git diff HEAD` (path presence and
|
|
435
|
+
* tracked content move it), and `git rev-parse HEAD`. Deterministic and cheap; the sha is only
|
|
436
|
+
* ever compared against itself, never decoded.
|
|
437
|
+
* shortcut: a content-only change to an UNTRACKED file stays invisible — git does not look at
|
|
438
|
+
* those contents, and untracked worktree content is normally build output, not code under test. */
|
|
439
|
+
export function checkFingerprint(treeState: string, head: string): string {
|
|
440
|
+
return createHash("sha1").update(`${treeState}\n${head}`).digest("hex").slice(0, 12);
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* Drop every check record that carries a fingerprint differing from the tree as it is now — those
|
|
445
|
+
* greens describe code that no longer exists, and a gate must not advance on them. The caller
|
|
446
|
+
* re-runs what is missing (verify re-runs at the gate; the release gate asks for `flow check`).
|
|
447
|
+
* `fp === null` means git could not be asked: a gate must not refuse on its own measurement
|
|
448
|
+
* failure — same rule as BranchState.commitsAhead. Records without a fingerprint (older builds)
|
|
449
|
+
* are never proven stale.
|
|
450
|
+
*/
|
|
451
|
+
export function freshenChecks(state: FlowState, fp: string | null, keep: (name: string) => boolean = () => false): string[] {
|
|
452
|
+
if (!fp) return [];
|
|
453
|
+
const stale: string[] = [];
|
|
454
|
+
for (const [name, rec] of Object.entries(state.checks)) {
|
|
455
|
+
if (rec.wt && rec.wt !== fp && !keep(name)) {
|
|
456
|
+
delete state.checks[name];
|
|
457
|
+
stale.push(name);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
return stale;
|
|
461
|
+
}
|
|
462
|
+
|
|
460
463
|
/** Items that apply to this feature — "(ui)" items only when the UI flag is set. */
|
|
461
464
|
export function applicableItems(cfg: Config, state: FlowState, stage: string): ChecklistItem[] {
|
|
462
465
|
return (cfg.checklist[stage] ?? []).filter((i) => !i.uiOnly || state.ui);
|
|
@@ -762,11 +765,12 @@ export function expandHome(p: string): string {
|
|
|
762
765
|
|
|
763
766
|
/** git usage in a bash command, parsed per shell segment (split on ; | & newline):
|
|
764
767
|
* the git subcommands invoked — empty when git is not a command, so paths like
|
|
765
|
-
* .git/hooks or words like pre-commit never trigger the guard — and the
|
|
766
|
-
*
|
|
768
|
+
* .git/hooks or words like pre-commit never trigger the guard — and the per-segment
|
|
769
|
+
* entries the guard judges, each carrying the directory that segment runs in
|
|
770
|
+
* (last preceding `cd` target or `git -C` target; null = session cwd).
|
|
767
771
|
* shortcut: naive segment split, subshells/backticks not tracked; the pre-commit
|
|
768
772
|
* hook still covers what slips past this advisory guard. */
|
|
769
|
-
export function gitInvocation(command: string): { subs: string[];
|
|
773
|
+
export function gitInvocation(command: string): { subs: string[]; pushes: string[][]; gitSegs: { seg: string; dir: string | null }[] } {
|
|
770
774
|
const subs: string[] = [];
|
|
771
775
|
const pushes: string[][] = [];
|
|
772
776
|
const gitSegs: { seg: string; dir: string | null }[] = [];
|
|
@@ -811,7 +815,7 @@ export function gitInvocation(command: string): { subs: string[]; dir: string |
|
|
|
811
815
|
}
|
|
812
816
|
gitSegs.push({ seg: seg.trim(), dir }); // after -C parsing so the entry carries its own effective dir
|
|
813
817
|
}
|
|
814
|
-
return { subs,
|
|
818
|
+
return { subs, pushes, gitSegs };
|
|
815
819
|
}
|
|
816
820
|
|
|
817
821
|
export type PushRef = { kind: "tag" | "branch" | "current"; name: string };
|
|
@@ -850,16 +854,18 @@ export function parsePushRefs(pushes: string[][]): PushRef[] {
|
|
|
850
854
|
return out;
|
|
851
855
|
}
|
|
852
856
|
|
|
853
|
-
/** Flow
|
|
854
|
-
* (that is how `cd .dev-flow/<slug> && mv state.json …` reaches it).
|
|
855
|
-
|
|
856
|
-
const
|
|
857
|
+
/** Flow control files by full path — state.json and claim.json — or a bare name when the command
|
|
858
|
+
* also touches `.dev-flow` (that is how `cd .dev-flow/<slug> && mv state.json …` reaches it).
|
|
859
|
+
* The claim is the live-session lock: deleting it is as much theft as forging a stage. */
|
|
860
|
+
const STATE_PATH = /(^|[\s'"\/])(?:state|claim)\.json$/;
|
|
861
|
+
const STATE_PATH_ABS = /\.dev-flow\/[\w./-]*(?:state|claim)\.json$/;
|
|
857
862
|
const PLAYBOOK_PATH = /\.dev-flow\/[\w./-]*project\.md/;
|
|
858
863
|
const DF_ANYWHERE = /\.dev-flow\b/;
|
|
859
864
|
/** The `.dev-flow/` folder itself or one feature directory under it — deleting either destroys the flow
|
|
860
865
|
* state and its plan for good. The advisory files the agent owns, and anything deeper (a worktree, a
|
|
861
|
-
* plan/mockups path), are not "the folder".
|
|
862
|
-
|
|
866
|
+
* plan/mockups path), are not "the folder". The leading boundary takes `/` too: an absolute path names
|
|
867
|
+
* the same folder, and absolute paths are the shape the harness hands the agent. */
|
|
868
|
+
const DF_FOLDER = /(?:^|[\s'"/])\.dev-flow(?:\/(?!project\.md$|roadmap\.md$|reflections\.md$|\.gitignore$)[\w.-]+)?(?=$|[\s'"])/;
|
|
863
869
|
// write tools that can overwrite a file. A bare `>` is deliberately absent: the redirect target is
|
|
864
870
|
// checked on its own, and testing for any `>` here refused every segment that merely mentioned an
|
|
865
871
|
// owned path while redirecting elsewhere (`gh pr create … 2>&1`).
|
|
@@ -1015,19 +1021,6 @@ export interface GuardRules {
|
|
|
1015
1021
|
forbid: GuardRule[];
|
|
1016
1022
|
}
|
|
1017
1023
|
|
|
1018
|
-
/** project.json may spell a rule as a bare pattern string. */
|
|
1019
|
-
function normalizeGuardRules(raw: unknown[]): GuardRule[] {
|
|
1020
|
-
const out: GuardRule[] = [];
|
|
1021
|
-
for (const e of raw) {
|
|
1022
|
-
if (typeof e === "string" && e.trim()) out.push({ pattern: e, why: "" });
|
|
1023
|
-
else if (e && typeof e === "object") {
|
|
1024
|
-
const o = e as Record<string, unknown>;
|
|
1025
|
-
if (typeof o.pattern === "string" && o.pattern.trim()) out.push({ pattern: o.pattern, why: typeof o.why === "string" ? o.why : "" });
|
|
1026
|
-
}
|
|
1027
|
-
}
|
|
1028
|
-
return out;
|
|
1029
|
-
}
|
|
1030
|
-
|
|
1031
1024
|
/** Heads that execute their argument: inside these, quoted text is code, not prose. */
|
|
1032
1025
|
export const REEXEC_HEADS = new Set(["sh", "bash", "zsh", "dash", "ksh", "node", "nodejs", "python", "python2", "python3", "perl", "ruby", "php", "env", "xargs", "sudo", "time", "nice", "nohup", "watch"]);
|
|
1033
1026
|
|
|
@@ -1203,30 +1196,36 @@ export function inScratchDir(abs: string, repoRoot?: string | null): boolean {
|
|
|
1203
1196
|
* Returns a reason or null (allowed).
|
|
1204
1197
|
*/
|
|
1205
1198
|
export function writeGuard(o: { abs: string; dfDir: string; features: FeatureRef[]; boundSlug: string | null; repoRoot?: string | null }): string | null {
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1199
|
+
// Judge where the bytes land, not where the path pretends: a symlink inside the worktree pointing
|
|
1200
|
+
// out of it is the same write as the target path (realAbs walks the deepest existing ancestor, so
|
|
1201
|
+
// a brand-new file under a real directory resolves right, and a never-existing one is stable).
|
|
1202
|
+
const abs = realAbs(o.abs);
|
|
1203
|
+
const dfDir = realAbs(o.dfDir);
|
|
1204
|
+
if (abs === path.join(dfDir, "project.json")) return ".dev-flow/project.json is legacy — it is no longer read; fold its values into project.md and delete it";
|
|
1205
|
+
if (abs === path.join(dfDir, "project.md")) return "project.md is the operator playbook — change it with flow init --write (setup) or inside a docs/patch flow's worktree";
|
|
1206
|
+
if (abs.endsWith("state.json") && abs.includes(dfDir + path.sep)) return "state.json is dev-flow-owned — advance stages with the flow tool only";
|
|
1207
|
+
if (abs.endsWith("claim.json") && abs.includes(dfDir + path.sep)) return "claim.json is dev-flow-owned — the live-session lock is not an edit target; take a feature over with flow use <slug>";
|
|
1209
1208
|
// Owner attribution BEFORE the .dev-flow allow: with the default worktreeDir inside .dev-flow,
|
|
1210
1209
|
// a worktree must still be judged by its owning feature's stage, not treated as free plan space.
|
|
1211
|
-
const owner = o.features.find((f) => within(
|
|
1210
|
+
const owner = o.features.find((f) => within(abs, f.worktreeAbs ? realAbs(f.worktreeAbs) : null));
|
|
1212
1211
|
if (owner) {
|
|
1213
1212
|
if (owner.state.stage === "plan") return `feature ${owner.state.slug} is in plan — code is read-only until its plan is approved`;
|
|
1214
1213
|
if (owner.state.stage === "done") return `feature ${owner.state.slug} is done`;
|
|
1215
1214
|
// the playbook copy inside a worktree: only operator-granted lightweight modes may change it
|
|
1216
|
-
if (path.basename(
|
|
1215
|
+
if (path.basename(abs) === "project.md" && abs.includes(path.join(".dev-flow", "project.md")) && !owner.state.docs && !owner.state.patch)
|
|
1217
1216
|
return `project.md changes belong to a docs or patch flow — ${owner.state.slug} is a normal feature (flow start <slug> --docs --confirmed)`;
|
|
1218
1217
|
return null; // implement/pre-release/release: own worktree is the working area
|
|
1219
1218
|
}
|
|
1220
1219
|
// Scratch outside the checkout is not a repo write: every stage (and an unbound session) may use it. It
|
|
1221
1220
|
// sits after the dev-flow-owned refusals and after owner attribution, so no path shape — a symlink, or a
|
|
1222
1221
|
// worktreeDir an operator parked in the temp dir — reaches those rules through the temp dir.
|
|
1223
|
-
if (inScratchDir(
|
|
1222
|
+
if (inScratchDir(abs, o.repoRoot)) return null;
|
|
1224
1223
|
const bound = o.boundSlug ? o.features.find((f) => f.state.slug === o.boundSlug) : undefined;
|
|
1225
1224
|
// A plan-stage session may only write its own feature directory: otherwise one session edits another
|
|
1226
1225
|
// feature's plan and that feature's approval gate then rubber-stamps text it never wrote.
|
|
1227
|
-
if (bound?.state.stage === "plan" && !within(
|
|
1226
|
+
if (bound?.state.stage === "plan" && !within(abs, path.join(dfDir, bound.state.slug)))
|
|
1228
1227
|
return `bound feature ${bound.state.slug} is in plan — write only inside its own .dev-flow/${bound.state.slug}/`;
|
|
1229
|
-
if (within(
|
|
1228
|
+
if (within(abs, dfDir)) return null;
|
|
1230
1229
|
if (bound) {
|
|
1231
1230
|
if (bound.state.stage === "implement" || bound.state.stage === "pre-release")
|
|
1232
1231
|
return `bound feature ${o.boundSlug} is at ${bound.state.stage} — edit its worktree (${bound.state.worktree}), not the main checkout; a throwaway script goes outside the repo (under $TMPDIR)`;
|
|
@@ -1582,7 +1581,7 @@ export function nextHint(state: FlowState, cfg: Config): string {
|
|
|
1582
1581
|
case "plan":
|
|
1583
1582
|
if (state.patch) return `patch: describe the change to the operator in one line, then ask them Approve? in chat and run flow approve --confirmed when they answer — no plan file needed (all gates still apply)`;
|
|
1584
1583
|
if (state.docs) return `docs: describe the change to the operator in one line, then ask them Approve? in chat and run flow approve --confirmed when they answer — no plan file and no tier-1 checks (worktree and release stay intact)`;
|
|
1585
|
-
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
|
|
1584
|
+
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`;
|
|
1586
1585
|
case "implement":
|
|
1587
1586
|
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`;
|
|
1588
1587
|
return `implement in the worktree ${state.worktree}, add tests, run flow check (tier-1 checks, incl. health with seeded data); tick the tier-2 checklist with the operator, then ask them Verified? in chat and run flow verify --confirmed when they answer`;
|
|
@@ -1656,15 +1655,6 @@ export function gateHelpJson(gateHelp: string, version: string | null): string {
|
|
|
1656
1655
|
);
|
|
1657
1656
|
}
|
|
1658
1657
|
|
|
1659
|
-
export function getPath(obj: Record<string, unknown>, key: string): unknown {
|
|
1660
|
-
let cur: unknown = obj;
|
|
1661
|
-
for (const seg of key.split(".")) {
|
|
1662
|
-
if (typeof cur !== "object" || cur === null) return undefined;
|
|
1663
|
-
cur = (cur as Record<string, unknown>)[seg];
|
|
1664
|
-
}
|
|
1665
|
-
return cur;
|
|
1666
|
-
}
|
|
1667
|
-
|
|
1668
1658
|
/** Write (or delete, on null) a dot-path value in a partial project.json object. */
|
|
1669
1659
|
export function applyAnswer(partial: Record<string, unknown>, key: string, value: string | boolean | null): void {
|
|
1670
1660
|
const segs = key.split(".");
|