pi-dev-flow 0.77.3 → 0.79.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/README.md +6 -3
- package/docs/guardrails.md +1 -1
- package/docs/playbook.md +51 -9
- package/extensions/dev-flow.ts +209 -54
- package/package.json +1 -1
- package/skills/dev-flow/references/finish.md +2 -2
- package/skills/dev-flow/references/implement.md +3 -0
- package/skills/dev-flow/references/start.md +13 -13
- package/src/core.ts +13 -1
- package/src/detect.ts +219 -18
- package/src/projectmd.ts +138 -4
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,38 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
|
|
|
4
4
|
|
|
5
5
|
## [Unreleased]
|
|
6
6
|
|
|
7
|
+
## [0.79.0] - 2026-11-03
|
|
8
|
+
|
|
9
|
+
**Scratch files live in the feature folder and go away at finish.**
|
|
10
|
+
|
|
11
|
+
### Changed
|
|
12
|
+
- **Scratch files now go in the feature folder, not `/tmp`.** A bound session's bash calls, and every project command a gate runs (`flow test`, checks, build, dev, seed, health), now run with `TMPDIR` set to `.dev-flow/<slug>/tmp/`. Throwaway scripts, `mktemp` output and test fixtures created with `os.tmpdir()` (the smoke suite alone makes about 40 per run) land there instead of piling up in the OS temp dir. `flow finish` removes the folder with the feature, and `flow abort` drops it when it unbinds. The prefix goes on after the guards have judged the command, so no guard ever sees it. Unbound sessions are unchanged.
|
|
13
|
+
|
|
14
|
+
## [0.78.0] - 2026-11-03
|
|
15
|
+
|
|
16
|
+
**`flow init` asks better questions and writes your answers itself.**
|
|
17
|
+
|
|
18
|
+
### Fixed
|
|
19
|
+
- npm drafts wrote `build = npm build` / `run = npm dev`, which npm rejects with "Unknown command". Scripts now run as `npm run <script>` (only `test`/`start` keep the shorthand), and bun's test is `bun run test`, because `bun test` is bun's own runner, not your script.
|
|
20
|
+
- The draft no longer invents `versionFile = package.json` when no version file exists (doctor flagged it on day one).
|
|
21
|
+
- The "app runs locally; visual pass" checklist item is now `(ui)`-only, so libraries and CLIs aren't asked about screens.
|
|
22
|
+
- With a UI, the draft dialog no longer appears before the setup questions are shown.
|
|
23
|
+
- With husky or lefthook setting `core.hooksPath`, init no longer installs a hook git never runs. It prints the lines to add to the manager's hook instead.
|
|
24
|
+
|
|
25
|
+
### Added
|
|
26
|
+
- `flow init --answers key=value …` / `--answers-file <path>` apply setup answers as targeted edits (merge, forge, version, artifact, preflight, commands, `check.<name>` blocks). They preview the summary and a diff, and write only with `--confirmed`. `--write-file <path>` writes a whole file. `--track` commits the playbook. Every write prints its diff.
|
|
27
|
+
- Setup questions carry `detected:` / `accept:` / `why:` lines. The interactive first init accepts every detected value in one dialog, then offers the commit.
|
|
28
|
+
- Detection reads:
|
|
29
|
+
- lint/typecheck/format scripts (and clippy, `go vet`, ruff/mypy) → `flow-check` blocks
|
|
30
|
+
- Makefile/justfile/Taskfile targets
|
|
31
|
+
- CI workflow commands and publish steps → a suggested `artifact` check
|
|
32
|
+
- Dockerfile/compose → suggested `preflight`/`dev`
|
|
33
|
+
- `.env`/`secrets/` on disk → drafted `protect`/`forbid` guard rules
|
|
34
|
+
- existing tags → `versionTag`
|
|
35
|
+
- the changelog file, monorepo workspaces, and CLAUDE.md/AGENTS.md/CONTRIBUTING.md
|
|
36
|
+
- The summary shown in the init dialog lists safety rules, and says when no version file is set.
|
|
37
|
+
- `docs/playbook.md` opens with a Quickstart and four typical playbooks.
|
|
38
|
+
|
|
7
39
|
## [0.77.3] - 2026-11-03
|
|
8
40
|
|
|
9
41
|
### Changed
|
package/README.md
CHANGED
|
@@ -71,9 +71,12 @@ Then, once per project repo, `/flow init`. It reads the repo (default branch and
|
|
|
71
71
|
package manager, test/build/run conventions, version manifest) and writes **`.dev-flow/project.md`
|
|
72
72
|
— your playbook**: the commands that count as checks, the manual checklist, the version and tag
|
|
73
73
|
convention, how a merged PR lands (`merge = squash | merge | rebase`), and any hard safety rules of your
|
|
74
|
-
own. It
|
|
75
|
-
|
|
76
|
-
|
|
74
|
+
own. It also reads lint/typecheck scripts, CI workflows, Makefiles, Docker files, secrets on disk and your existing
|
|
75
|
+
tags. Every question shows what was detected and why it matters, so "keep these" answers most of
|
|
76
|
+
them. Your answers land as targeted edits (`flow init --answers key=value …`), previewed as a diff
|
|
77
|
+
before anything is written. It asks about everything detection could not decide (self-hosted forge?
|
|
78
|
+
Docker artifacts? what "healthy" means?) and installs a `pre-commit` hook that blocks direct main
|
|
79
|
+
commits (or prints the lines for husky/lefthook when they own the hooks). Run `/flow init` again later and it becomes a **doctor**: drift in
|
|
77
80
|
your playbook, dead commands, config problems — it never rewrites your hand edits without asking.
|
|
78
81
|
The flow is completely inert in repos with no `.dev-flow/`.
|
|
79
82
|
|
package/docs/guardrails.md
CHANGED
|
@@ -6,7 +6,7 @@ While a feature is active, the extension intercepts every tool call:
|
|
|
6
6
|
|
|
7
7
|
- **Nothing on main, ever** (until release): `git commit` on the default branch is blocked at every stage except `release` — where release chores commit in the main checkout (prefixed `DEV_FLOW_ALLOW_MAIN=1` for the hook) — and except one chore that needs no flow: a commit whose **only** change in the checkout is `.dev-flow/project.md`, because tracking the operator's playbook is setup, not feature work (any other dirty path closes that lane). pushes are judged by the ref they write — only pushing *to* the default branch (or a bare push while on it) requires stage `release`, so tag pushes and feature-branch pushes pass from any stage; `git merge` onto the default branch also requires stage `release`. Plus the standalone pre-commit hook for commits made outside Pi.
|
|
8
8
|
- **No code before an approved plan**: at stage `plan`, edits are confined to `.dev-flow/<slug>/` — the session's **own** feature directory, so one session cannot write another feature's plan and have its gate rubber-stamp what it never wrote.
|
|
9
|
-
- **Work stays in the worktree**: at stages `implement` and `pre-release`, edits are confined to that feature's worktree — judged per-path by the owning feature, so one session can never write into another session's worktree or into the main checkout. A throwaway **outside** the checkout is not feature work and stays free at every stage (the OS temp dir, e.g. a one-off rewrite script): both sides are realpath'd, so a symlink out of the temp dir is still judged as the repo path it writes, and a repository that merely lives under the temp dir (a test repo) keeps the stage rules.
|
|
9
|
+
- **Work stays in the worktree**: at stages `implement` and `pre-release`, edits are confined to that feature's worktree — judged per-path by the owning feature, so one session can never write into another session's worktree or into the main checkout. A throwaway **outside** the checkout is not feature work and stays free at every stage (the OS temp dir, e.g. a one-off rewrite script): both sides are realpath'd, so a symlink out of the temp dir is still judged as the repo path it writes, and a repository that merely lives under the temp dir (a test repo) keeps the stage rules. For a bound feature that scratch lives in the feature itself: every bash call the guards let through, and every project command a gate runs (test, checks, build, dev, seed, health), gets `TMPDIR=.dev-flow/<slug>/tmp/`, so `mktemp`, `os.tmpdir()` and test-suite fixtures land there and `flow finish` (or `flow abort`) removes them. Unbound sessions keep the OS temp dir.
|
|
10
10
|
- **Shipping waits for `flow release`**: while a bound feature is at `plan`, `implement` or `pre-release`, cutting or pushing a tag (`git tag <name>`, `git push --tags`, `refs/tags/…`), merging its PR (`gh pr merge`, `glab mr merge`) and creating a forge release (`gh|glab release create`) are refused with "run flow release first". Shipping by hand first left `flow release` unable to record the release ("already tagged") and the flow unable to close. Reads (`git tag -l`, `gh pr view`) and opening the PR at pre-release are unaffected.
|
|
11
11
|
- **A feature worktree keeps its branch**: creating a branch inside a feature worktree (`git checkout -b`, `git switch -c`) is refused. An unrelated fix is its own flow (`flow start <slug> --patch --confirmed`), not a side branch in someone's worktree. A session whose cwd is a feature worktree is judged by the **main checkout's** `.dev-flow/` state, which is where the features live.
|
|
12
12
|
- **Flow by default**: in a repo with `.dev-flow/`, an unbound session cannot touch source files at all — every request goes through `flow start`/`flow use`; there is no bypass. `flow start` refuses when the main checkout isn't on the default branch, worktrees are always created from the default branch, and the agent cannot check feature branches out in the main checkout.
|
package/docs/playbook.md
CHANGED
|
@@ -2,6 +2,39 @@
|
|
|
2
2
|
|
|
3
3
|
The operator-owned file that says how *your* project is tested, run, versioned and guarded. Written once per repo with `flow init`, edited by you.
|
|
4
4
|
|
|
5
|
+
## Quickstart
|
|
6
|
+
|
|
7
|
+
1. `/flow init`. dev-flow reads the repo and prints what it found, then one numbered question per knob. Each question shows what was detected (`detected:`), the answer that keeps it (`accept: merge=squash`), and why it matters. Nothing is written yet.
|
|
8
|
+
2. Answer in chat. Saying "keep these" is enough for every question that has an `accept` line.
|
|
9
|
+
3. The agent applies all your answers in one call, `flow init --answers merge=squash versionFile=VERSION check.lint="npm run lint" …`. That shows a summary and a diff and writes nothing.
|
|
10
|
+
4. You confirm. The agent re-runs the same call with `--confirmed --track`, which validates and writes the playbook, then commits it.
|
|
11
|
+
5. Anything detection can't know goes in later through `flow init --write-file <path>` with the whole file: checklist items, standing guidance, guard rules. You can also run `flow init --answers key=value` for a single knob at any time.
|
|
12
|
+
|
|
13
|
+
In a TUI, one dialog shows the summary with every detected value already accepted ("Accept the detected setup?"), followed by a commit offer. Decline it to answer the questions in chat first.
|
|
14
|
+
|
|
15
|
+
**What detection reads** (deterministic, files and git only, never runs your commands):
|
|
16
|
+
- the language manifest (package.json, Cargo.toml, go.mod, pyproject/requirements), the package manager and its scripts (`npm run build`, never `npm build`)
|
|
17
|
+
- lint, typecheck and format scripts, ruff and mypy config → extra `flow-check` blocks
|
|
18
|
+
- Makefile, justfile and Taskfile targets when no manifest decides
|
|
19
|
+
- CI workflows (the commands they run, which your checks should match) and publish steps (npm, crates, container image) → a suggested `artifact` check
|
|
20
|
+
- Dockerfile and compose files → suggested `preflight` and `dev`
|
|
21
|
+
- `.env` and `secrets/` on disk → drafted `protect`/`forbid` guard rules; an `.env.example` → a reminder that `setup` must copy it
|
|
22
|
+
- the version manifest, existing tags (the `versionTag` convention), the changelog, the merge style seen in history, monorepo workspaces
|
|
23
|
+
- CLAUDE.md, AGENTS.md and CONTRIBUTING.md (named, so their rules can be proposed as guidance; never copied silently)
|
|
24
|
+
|
|
25
|
+
Anything detection can't find is left out and asked about, never invented. No health check, no version file, no merge style is ever guessed.
|
|
26
|
+
|
|
27
|
+
**Typical playbooks.** These are minimal; add to them as the project teaches you:
|
|
28
|
+
|
|
29
|
+
| Project | `## implement` | `## pre-release` / `## release` |
|
|
30
|
+
|---|---|---|
|
|
31
|
+
| library (npm) | `test`, `build`, `flow-check lint` / `typecheck` | `versionFile = package.json`, `artifact = npm view --prefer-online <name>@{version} version`, `merge = …` |
|
|
32
|
+
| CLI (go/rust) | `test`, `build`, `flow-check vet` / `clippy` | `versionFile = VERSION`, `releases = true`, `merge = …` |
|
|
33
|
+
| web service | `setup` (install + copy `.env`), `test`, `run`, `flow-check health`, `(ui)` checklist items | `versionFile`, `merge = …` |
|
|
34
|
+
| Docker app | `dev = docker compose up -d --build`, `flow-check health` | `preflight = docker build .`, `artifact = docker buildx imagetools inspect <image>:{version}` |
|
|
35
|
+
|
|
36
|
+
The rest of this page is the reference.
|
|
37
|
+
|
|
5
38
|
`.dev-flow/` ignores itself — its own `.dev-flow/.gitignore` is `*` with the single exception
|
|
6
39
|
`!project.md`, so no state, plan or worktree path is ever tracked by accident. Tracking the playbook
|
|
7
40
|
in a repo that ignores the folder is a deliberate one-off:
|
|
@@ -154,15 +187,24 @@ needs to know which one the release contains. Three things read the key:
|
|
|
154
187
|
What it cannot do is bind a human clicking the merge button in the Web UI: only the forge's own
|
|
155
188
|
require-a-merge-strategy setting does that, and setting it stays your step in the forge, not dev-flow's.
|
|
156
189
|
|
|
157
|
-
`flow init` is the dialogue around this file
|
|
158
|
-
|
|
159
|
-
the
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
190
|
+
`flow init` is the dialogue around this file (see the Quickstart above).
|
|
191
|
+
|
|
192
|
+
On a **fresh repo** it prints the setup brief: the detection report, plus one question per knob, each with `detected:` / `accept:` / `why:` lines. It writes nothing.
|
|
193
|
+
|
|
194
|
+
`--answers key=value …` (or `--answers-file <path>`, one pair per line, `#` for comments) applies answers as targeted edits onto the fresh draft, or onto the current file if one exists:
|
|
195
|
+
- Keys: `forge`, `defaultBranch`, `setup`/`test`/`build`/`run`/`dev`/`health`, `versionFile`/`versionTag`/`changelog`, `releases`/`artifact`/`preflight`/`merge`, and `check.<name>` for a `flow-check` block. An empty value removes a check.
|
|
196
|
+
- Hand-written lines survive, and a key already written under one release section stays there.
|
|
197
|
+
- It previews the summary and the diff, and writes only with `--confirmed` (or on a dialog yes).
|
|
198
|
+
|
|
199
|
+
`--write "<content>"` / `--write-file <path>` replace the whole file. The content is hard-validated, and the result shows the diff.
|
|
200
|
+
|
|
201
|
+
`--track` commits the playbook as a playbook chore (`git add -f` + the main-hook prefix). `--draft` prints the draft, or the current file, without writing.
|
|
202
|
+
|
|
203
|
+
On an **existing file** init is doctor mode. It reports drift, dead commands and scripts, an unparseable manifest, dual configs, and **ghost feature dirs** (a `.dev-flow/<slug>/` whose `state.json` is gone). It offers to delete ghost dirs on your confirm, and says so instead when no UI is present. It never runs your commands.
|
|
204
|
+
|
|
205
|
+
When a hook manager sets `core.hooksPath` (husky, lefthook…), git ignores `.git/hooks`, so init prints the main-branch guard lines for you to add to that hook instead of installing one that would never run. An existing foreign `pre-commit` gets the same printout.
|
|
206
|
+
|
|
207
|
+
Init prints its findings and never regenerates your file: a draft cannot reproduce your prose, checklist items and hand-set keys. `--force` is the deliberate overwrite — with your word (`--confirmed`, or one
|
|
166
208
|
confirm dialog) and a `project.md.bak` of what was there. At any time
|
|
167
209
|
you can just edit `.dev-flow/project.md` yourself — the next `flow init` (doctor) validates and
|
|
168
210
|
flags problems, and `flow doctor` runs the same probes on demand without offering to change
|
package/extensions/dev-flow.ts
CHANGED
|
@@ -25,7 +25,7 @@ import path from "node:path";
|
|
|
25
25
|
import { promisify } from "node:util";
|
|
26
26
|
import { Type } from "@earendil-works/pi-ai";
|
|
27
27
|
import { compact, createAgentSession, DefaultResourceLoader, defineTool, getAgentDir, isToolCallEventType, SessionManager, SettingsManager, type AgentSession, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
28
|
-
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
28
|
+
import type { ExtensionAPI, ToolCallEvent, ToolCallEventResult } from "@earendil-works/pi-coding-agent";
|
|
29
29
|
import {
|
|
30
30
|
ALLOW_REWRITE,
|
|
31
31
|
approveGate,
|
|
@@ -114,6 +114,8 @@ import {
|
|
|
114
114
|
statusJson,
|
|
115
115
|
subst,
|
|
116
116
|
sq,
|
|
117
|
+
featureTmpDir,
|
|
118
|
+
withTmpDir,
|
|
117
119
|
tagNotesCommand,
|
|
118
120
|
validSlug,
|
|
119
121
|
verifyGate,
|
|
@@ -138,10 +140,10 @@ import {
|
|
|
138
140
|
type PushRef,
|
|
139
141
|
type SessionClaim,
|
|
140
142
|
} from "../src/core.ts";
|
|
141
|
-
import { buildDraft, doctorFindings, ghostFeatureDirs, loadProject, mdDigest, parseProjectMd, setPlaybookKey } from "../src/projectmd.ts";
|
|
143
|
+
import { applyAnswers, buildDraft, doctorFindings, ghostFeatureDirs, lineDiff, loadProject, mdDigest, parseAnswers, parseProjectMd, setPlaybookKey } from "../src/projectmd.ts";
|
|
142
144
|
import { dedupeReflections, linkedTag, parseGhIssues, similarNote, type FoldResult, type GhIssue } from "../src/fold.ts";
|
|
143
145
|
import { bashTimeout, requireTimeout } from "../src/timeouts.ts";
|
|
144
|
-
import { detectProject } from "../src/detect.ts";
|
|
146
|
+
import { detectProject, type Detection } from "../src/detect.ts";
|
|
145
147
|
|
|
146
148
|
const execAsync = promisify(exec);
|
|
147
149
|
|
|
@@ -228,9 +230,9 @@ const now = () => new Date().toISOString();
|
|
|
228
230
|
|
|
229
231
|
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
230
232
|
|
|
231
|
-
async function sh(command: string, cwd: string, timeoutMs = 15 * 60_000): Promise<{ ok: boolean; out: string }> {
|
|
233
|
+
async function sh(command: string, cwd: string, timeoutMs = 15 * 60_000, env?: Record<string, string>): Promise<{ ok: boolean; out: string }> {
|
|
232
234
|
try {
|
|
233
|
-
const { stdout, stderr } = await execAsync(command, { cwd, timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024 });
|
|
235
|
+
const { stdout, stderr } = await execAsync(command, { cwd, timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024, ...(env ? { env: { ...process.env, ...env } } : {}) });
|
|
234
236
|
return { ok: true, out: `${stdout}\n${stderr}`.trim() };
|
|
235
237
|
} catch (e) {
|
|
236
238
|
const err = e as { stdout?: string; stderr?: string; message?: string };
|
|
@@ -345,12 +347,12 @@ async function writePlaybookMergePolicy(root: string, style: string): Promise<{
|
|
|
345
347
|
* container start can never pass a single shot, and hand-writing a poll loop into every playbook was
|
|
346
348
|
* the workaround; the gate waits and says how long it tried. Attempts/schedule: core.healthRetry.
|
|
347
349
|
*/
|
|
348
|
-
async function runHealthProbe(cmd: string, cwd: string, waitSec: number): Promise<{ ok: boolean; out: string; attempts: number }> {
|
|
350
|
+
async function runHealthProbe(cmd: string, cwd: string, waitSec: number, env?: Record<string, string>): Promise<{ ok: boolean; out: string; attempts: number }> {
|
|
349
351
|
const { attempts, delayMs } = healthRetry(waitSec);
|
|
350
352
|
const deadline = Date.now() + waitSec * 1000; // the budget is wall time: a slow probe must not multiply it by its own duration
|
|
351
353
|
let res = { ok: false, out: "" };
|
|
352
354
|
for (let i = 1; ; i++) {
|
|
353
|
-
res = await sh(cmd, cwd);
|
|
355
|
+
res = await sh(cmd, cwd, undefined, env);
|
|
354
356
|
if (res.ok || i >= attempts || Date.now() >= deadline) return { ...res, attempts: i };
|
|
355
357
|
await sleep(delayMs);
|
|
356
358
|
}
|
|
@@ -367,7 +369,7 @@ async function releaseTags(root: string): Promise<string[] | null> {
|
|
|
367
369
|
}
|
|
368
370
|
|
|
369
371
|
const GATE_HELP =
|
|
370
|
-
"help [--json] | init [--force|--draft|--write <text>] | reflect [<note>|list|tidy|move <n> --playbook|--code] | roadmap [add <text>|pick <n> <slug>|done <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui|--patch|--docs --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | approve [--yolo] | verify [--yolo] | release [--yolo|--no-version|--no-fold-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [slug] | abort [slug] | version [--check-upstream] — state gates take [slug] and --confirmed (the operator already answered in chat); without it they ask in a dialog, or refuse with NEEDS-OPERATOR when no UI is present — --ui/--patch/--docs and --merge=<style> on start are operator-granted (--confirmed); start refuses until the playbook has a merge policy and writes the answer into project.md — --yolo (with --confirmed) answers that checkpoint and pre-confirms every later one; checks and guardrails stay — release --no-version ships merge + changelog only (no bump, tag or forge release); --no-fold-check skips the changelog fold line proofs on the operator's word — release names a session running an older dev-flow build than the disk ships and asks update (/reload) or proceed — recorded, never a block — reflect <note> queues a project suggestion in reflections.md (--playbook = docs-flow fix, --code = patch-flow fix); --plugin never writes — dev-flow feedback goes upstream and it prints the GitHub issue recipe; bare reflect prints the session-reflection protocol (bound: run flow_stage op reflect); list numbers open items, move <n> re-files one, tidy drops closed ones — roadmap manages .dev-flow/roadmap.md: pick <n> <slug> stamps an item for flow start, finish checks it off — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — version prints the build the disk ships and any other dev-flow copies in this process (--check-upstream asks the registry)";
|
|
372
|
+
"help [--json] | init [--force|--draft|--write <text>|--write-file <path>|--answers key=value…|--answers-file <path>] [--confirmed] [--track] | reflect [<note>|list|tidy|move <n> --playbook|--code] | roadmap [add <text>|pick <n> <slug>|done <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui|--patch|--docs --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | approve [--yolo] | verify [--yolo] | release [--yolo|--no-version|--no-fold-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [slug] | abort [slug] | version [--check-upstream] — state gates take [slug] and --confirmed (the operator already answered in chat); without it they ask in a dialog, or refuse with NEEDS-OPERATOR when no UI is present — --ui/--patch/--docs and --merge=<style> on start are operator-granted (--confirmed); start refuses until the playbook has a merge policy and writes the answer into project.md — --yolo (with --confirmed) answers that checkpoint and pre-confirms every later one; checks and guardrails stay — release --no-version ships merge + changelog only (no bump, tag or forge release); --no-fold-check skips the changelog fold line proofs on the operator's word — release names a session running an older dev-flow build than the disk ships and asks update (/reload) or proceed — recorded, never a block — reflect <note> queues a project suggestion in reflections.md (--playbook = docs-flow fix, --code = patch-flow fix); --plugin never writes — dev-flow feedback goes upstream and it prints the GitHub issue recipe; bare reflect prints the session-reflection protocol (bound: run flow_stage op reflect); list numbers open items, move <n> re-files one, tidy drops closed ones — roadmap manages .dev-flow/roadmap.md: pick <n> <slug> stamps an item for flow start, finish checks it off — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — version prints the build the disk ships and any other dev-flow copies in this process (--check-upstream asks the registry)";
|
|
371
373
|
const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
|
|
372
374
|
const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
|
|
373
375
|
const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
|
|
@@ -603,6 +605,14 @@ function gateCwd(root: string, state: FlowState): string {
|
|
|
603
605
|
return wt && existsSync(wt) ? wt : root;
|
|
604
606
|
}
|
|
605
607
|
|
|
608
|
+
/** TMPDIR for the project commands a gate runs: the feature's own scratch dir, removed at finish —
|
|
609
|
+
* a test suite's mkdtemp fixtures no longer pile up in the OS temp dir. */
|
|
610
|
+
function featureEnv(root: string, state: FlowState): Record<string, string> {
|
|
611
|
+
const dir = featureTmpDir(dfDir(root), state.slug);
|
|
612
|
+
mkdirSync(dir, { recursive: true });
|
|
613
|
+
return { TMPDIR: dir };
|
|
614
|
+
}
|
|
615
|
+
|
|
606
616
|
/** Tier-1 checks the gate still has to see green. Entering a stage — and every edit of the worktree —
|
|
607
617
|
* clears the records, so "run flow check first" cost three round trips to say what one could (#84).
|
|
608
618
|
* `health` is left to the post-deploy probe when there is a deploy to prove: probing twice only waits twice. */
|
|
@@ -618,7 +628,7 @@ async function runChecks(root: string, state: FlowState, cfg: Config, checks: St
|
|
|
618
628
|
const ran: string[] = [];
|
|
619
629
|
for (const c of checks) {
|
|
620
630
|
// health is the same probe `flow health` runs: seeded first, retried within healthWait
|
|
621
|
-
const res = c.name === "health" ? await seededProbe(root, state, cfg, c.cmd) : await sh(c.cmd, gateCwd(root, state));
|
|
631
|
+
const res = c.name === "health" ? await seededProbe(root, state, cfg, c.cmd) : await sh(c.cmd, gateCwd(root, state), undefined, featureEnv(root, state));
|
|
622
632
|
if ("seedFail" in res) {
|
|
623
633
|
lines.push(res.seedFail.text);
|
|
624
634
|
failed = true;
|
|
@@ -643,7 +653,7 @@ const healthRerunsAfterDeploy = (cfg: Config) => !!cfg.commands.dev && !!healthP
|
|
|
643
653
|
* deploy probe both do this). Returns an error result on failure, null when seeded or not configured. */
|
|
644
654
|
async function seedStep(root: string, state: FlowState, cfg: Config): Promise<{ text: string; isError: true } | null> {
|
|
645
655
|
if (!cfg.commands.seedData) return null;
|
|
646
|
-
const seed = await sh(cfg.commands.seedData, gateCwd(root, state));
|
|
656
|
+
const seed = await sh(cfg.commands.seedData, gateCwd(root, state), undefined, featureEnv(root, state));
|
|
647
657
|
state.checks.seedData = { ok: seed.ok, at: now() };
|
|
648
658
|
writeState(root, state);
|
|
649
659
|
return seed.ok ? null : { text: `seedData FAILED (${cfg.commands.seedData}):\n${tail(seed.out)}`, isError: true };
|
|
@@ -654,7 +664,7 @@ type HealthRun = { ok: boolean; out: string; attempts: number } | { seedFail: Ru
|
|
|
654
664
|
/** Seed (when configured), then run the health probe within the playbook's wait budget. */
|
|
655
665
|
async function seededProbe(root: string, state: FlowState, cfg: Config, probe: string): Promise<HealthRun> {
|
|
656
666
|
const seedFail = await seedStep(root, state, cfg);
|
|
657
|
-
return seedFail ? { seedFail } : runHealthProbe(probe, gateCwd(root, state), cfg.healthWait);
|
|
667
|
+
return seedFail ? { seedFail } : runHealthProbe(probe, gateCwd(root, state), cfg.healthWait, featureEnv(root, state));
|
|
658
668
|
}
|
|
659
669
|
|
|
660
670
|
/** seededProbe, recorded and stamped as the `health` check — `flow health` and both verify probes. */
|
|
@@ -736,20 +746,74 @@ function isSelfRepo(root: string): boolean {
|
|
|
736
746
|
}
|
|
737
747
|
}
|
|
738
748
|
|
|
739
|
-
/**
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
749
|
+
/** Which tag convention the repo already uses — read off its newest tags, like the merge style is read off
|
|
750
|
+
* its history. null = no version-like tags yet (the v{version} default stands, and is asked about). */
|
|
751
|
+
async function tagPatternEvidence(root: string): Promise<{ pattern: string; note: string } | null> {
|
|
752
|
+
const r = await sh("git tag --list --sort=-creatordate", root, 10_000);
|
|
753
|
+
if (!r.ok) return null;
|
|
754
|
+
const tags = r.out.split("\n").map((t) => t.trim()).filter((t) => /\d+\.\d+\.\d+/.test(t)).slice(0, 20);
|
|
755
|
+
if (!tags.length) return null;
|
|
756
|
+
const prefix = (t: string) => t.slice(0, t.search(/\d+\.\d+\.\d+/));
|
|
757
|
+
const counts = new Map<string, number>();
|
|
758
|
+
for (const t of tags) counts.set(prefix(t), (counts.get(prefix(t)) ?? 0) + 1);
|
|
759
|
+
const [top] = [...counts.entries()].sort((x, y) => y[1] - x[1]);
|
|
760
|
+
return { pattern: `${top[0]}{version}`, note: `${tags.length} version tag(s), newest ${tags[0]}${counts.size > 1 ? ` (mixed prefixes: ${[...counts.keys()].map((k) => k || "none").join(", ")})` : ""}` };
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
/** One setup question: what to ask, what detection found, why it matters, and the answer that accepts it. */
|
|
764
|
+
export interface SetupQuestion {
|
|
765
|
+
key: string;
|
|
766
|
+
ask: string;
|
|
767
|
+
detected?: string;
|
|
768
|
+
/** `flow init --answers` token(s) that accept the detected/suggested value */
|
|
769
|
+
accept?: string;
|
|
770
|
+
why: string;
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
/** The questions `flow init` asks before writing a playbook — detection fills what it can, the operator
|
|
774
|
+
* answers the rest (the agent relays them). Every question says why it matters and what skipping costs,
|
|
775
|
+
* so it is answerable without reading docs/playbook.md first. */
|
|
776
|
+
function setupQuestions(det: Detection, ev: { merge?: { note: string; recent: string | null } | null; tag?: { pattern: string; note: string } | null }): SetupQuestion[] {
|
|
777
|
+
const sug = (k: string) => det.suggestions.filter((x) => x.key === k);
|
|
778
|
+
const q: SetupQuestion[] = [];
|
|
779
|
+
const forge = det.partial.forge;
|
|
780
|
+
q.push({ key: "forge", ask: "Where is the repo hosted: github, gitlab or self (plain git)?", detected: forge ? `${forge} (from the origin URL)` : "no origin remote", accept: forge ? `forge=${forge}` : undefined, why: "decides who creates the release and how dev-flow proves a PR really merged (gh/glab); self = git only, no automatic releases" });
|
|
781
|
+
const vf = det.partial.versioning?.file;
|
|
782
|
+
q.push({ key: "versionFile", ask: vf ? `Version lives in ${vf} — keep it?` : "Which file holds the version? (VERSION recommended for non-package repos; or answer that releases carry no version)", detected: vf, accept: vf ? `versionFile=${vf}` : undefined, why: "a release bumps this file and the tag must match it; without one, every release is merge-only (no bump, no tag)" });
|
|
783
|
+
const tag = ev.tag?.pattern ?? "v{version}";
|
|
784
|
+
q.push({ key: "versionTag", ask: `Tag pattern: ${tag}?`, detected: ev.tag ? `${ev.tag.note}` : "no version tags yet — default v{version}", accept: `versionTag=${tag}`, why: "release tags and the manifest are checked against each other; a pattern that differs from your existing tags breaks the last-release lookup" });
|
|
785
|
+
q.push({ key: "merge", ask: "How should a merged PR land on the default branch: squash, merge (a merge commit), rebase, or any (no policy)?", detected: ev.merge?.note ?? "no history to read a style from", accept: ev.merge?.recent ? `merge=${ev.merge.recent}` : undefined, why: "the guard blocks a PR merge in a different style and release-done proves what landed; flow start refuses until this is answered" });
|
|
786
|
+
q.push({ key: "releases", ask: "Should release-done create the forge release automatically (gh/glab release from the changelog entry)?", detected: forge === "self" ? "forge = self: no CLI to create one" : undefined, accept: forge === "self" ? "releases=false" : "releases=true", why: "off = the tag is pushed and publishing the release page stays your manual step" });
|
|
787
|
+
const art = sug("artifact");
|
|
788
|
+
q.push({ key: "artifact", ask: art.length ? "Verify the published artifact after release with this command?" : "Do you publish anything to a registry (npm, crates.io, a container image)? If so, which command proves the version is out?", detected: art.map((a) => a.why).join("; ") || undefined, accept: art[0] ? `artifact=${art[0].value}` : undefined, why: "release-done refuses to finish until the artifact is really there — catches a CI publish that silently failed; none = no check" });
|
|
789
|
+
const pre = sug("preflight");
|
|
790
|
+
if (pre.length) q.push({ key: "preflight", ask: `Run \`${pre[0].value}\` before anything ships?`, detected: pre[0].why, accept: `preflight=${pre[0].value}`, why: "flow release runs it in the worktree first — a build the tag would trigger, proven before the tag exists" });
|
|
791
|
+
const checks = det.partial.checks ?? {};
|
|
792
|
+
q.push({
|
|
793
|
+
key: "check.<name>",
|
|
794
|
+
ask: `Tier-1 checks: ${det.missing.length ? `not detected: ${det.missing.join(", ")}` : "test/build/run detected"}${Object.keys(checks).length ? `; drafted extra checks: ${Object.keys(checks).join(", ")}` : ""}. Correct? Anything CI runs that is missing (lint, typecheck, e2e)?`,
|
|
795
|
+
detected: Object.entries(det.partial.commands).filter(([k]) => k !== "setup").map(([k, v]) => `${k}: ${v}`).join(" · ") || undefined,
|
|
796
|
+
why: "flow check runs every one of these and the gates refuse while any fails — a check missing here is a failure only CI will see; answer test=… / build=… / check.<name>=<cmd> (empty value removes)",
|
|
797
|
+
});
|
|
798
|
+
const dev = sug("dev");
|
|
799
|
+
q.push({ key: "health", ask: `Does the app expose a health probe (e.g. curl -fs localhost:PORT/healthz)?${dev.length ? ` And use \`${dev[0].value}\` as the dev deploy reviewed before verify?` : " Is there a dev deploy reviewed before verify?"}`, detected: dev[0]?.why, accept: dev[0] ? `dev=${dev[0].value}` : undefined, why: "verify proves the running build is healthy only with a probe; none is fine for libraries and CLIs" });
|
|
800
|
+
if (det.partial.changelog === "") q.push({ key: "changelog", ask: "No changelog found — create CHANGELOG.md, or run without one?", accept: "changelog=", why: "the release gates fold the branch's entry into the version heading; empty = no changelog checks at all" });
|
|
801
|
+
q.push({ key: "guard", ask: `Any commands the agent must never run, or files it must never touch?${det.partial.guards?.length ? ` (drafted from disk: ${det.partial.guards.map((g) => g.split(" :: ")[0].replace(/\s+/g, " ")).join(", ")})` : ""}`, why: "flow-guard rules are hard blocks or operator confirmations on every shell call and edit; added with flow init --write-file (free text)" });
|
|
802
|
+
q.push({ key: "checklist", ask: "Anything you want to tick off by hand per stage (e.g. 'migration tested on a prod copy'), or standing guidance the agent should read at a stage?", why: "checklist items are confirmed as a set at the gate; prose is injected when the stage begins — both are free text: flow init --write-file" });
|
|
750
803
|
return q;
|
|
751
804
|
}
|
|
752
805
|
|
|
806
|
+
function renderQuestions(qs: SetupQuestion[]): string[] {
|
|
807
|
+
const out: string[] = [];
|
|
808
|
+
qs.forEach((x, i) => {
|
|
809
|
+
out.push(` ${i + 1}. [${x.key}] ${x.ask}`);
|
|
810
|
+
if (x.detected) out.push(` detected: ${x.detected}`);
|
|
811
|
+
if (x.accept) out.push(` accept: ${x.accept}`);
|
|
812
|
+
out.push(` why: ${x.why}`);
|
|
813
|
+
});
|
|
814
|
+
return out;
|
|
815
|
+
}
|
|
816
|
+
|
|
753
817
|
const GIT_TRACK_NOTE = 'the playbook belongs in git: git add -f .dev-flow/project.md && DEV_FLOW_ALLOW_MAIN=1 git commit -m "track project.md" (force-add: a root .gitignore may exclude .dev-flow/ entirely — tracked once, the ignore stops mattering; the env prefix is for the pre-commit hook, dev-flow itself lets a main commit whose only change is the playbook)';
|
|
754
818
|
|
|
755
819
|
/** The dev-flow repo plugin notes are filed against: the manifest's repository field; the dev-flow
|
|
@@ -1001,7 +1065,7 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
|
|
|
1001
1065
|
did.push("docs mode: project commands skipped (build/dev/health)");
|
|
1002
1066
|
} else {
|
|
1003
1067
|
if (cfg.commands.build) {
|
|
1004
|
-
const res = await sh(cfg.commands.build, gateCwd(root, state!));
|
|
1068
|
+
const res = await sh(cfg.commands.build, gateCwd(root, state!), undefined, featureEnv(root, state!));
|
|
1005
1069
|
state!.checks.build = { ok: res.ok, at: now() };
|
|
1006
1070
|
writeState(root, state!);
|
|
1007
1071
|
if (!res.ok) return { text: `build FAILED (${cfg.commands.build}):\n${tail(res.out)}`, isError: true };
|
|
@@ -1010,7 +1074,7 @@ async function gateVerify(o: GateCtx): Promise<RunResult> {
|
|
|
1010
1074
|
// deploy to dev before asking — the operator reviews the running dev app, not a promise
|
|
1011
1075
|
const probe = healthProbe(cfg);
|
|
1012
1076
|
if (cfg.commands.dev) {
|
|
1013
|
-
const res = await sh(cfg.commands.dev, gateCwd(root, state!));
|
|
1077
|
+
const res = await sh(cfg.commands.dev, gateCwd(root, state!), undefined, featureEnv(root, state!));
|
|
1014
1078
|
state!.checks.dev = { ok: res.ok, at: now() };
|
|
1015
1079
|
writeState(root, state!);
|
|
1016
1080
|
if (!res.ok) return { text: `dev deploy FAILED (${cfg.commands.dev}):\n${tail(res.out)}`, isError: true };
|
|
@@ -1472,6 +1536,19 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
|
|
|
1472
1536
|
return { text: `feature ${state!.slug} done — ${closeNote}${remoteNote}; .dev-flow/${state!.slug}/ removed.${roadmapNote}${forgeSkipNote}${syncNote}${nudgeNote} Re-read flow status before reporting open flows — a sibling feature may have finished while this session ran.` };
|
|
1473
1537
|
}
|
|
1474
1538
|
|
|
1539
|
+
/** The main-branch guard as a hook body — installed into .git/hooks, or printed for a hook manager to carry. */
|
|
1540
|
+
const mainHookBody = (branch: string) =>
|
|
1541
|
+
`branch=$(git rev-parse --abbrev-ref HEAD)\nif [ "$branch" = "${branch}" ] && [ -z "$DEV_FLOW_ALLOW_MAIN" ]; then\n echo "dev-flow: direct commits to ${branch} are forbidden — use a feature worktree and a PR" >&2\n exit 1\nfi\n`;
|
|
1542
|
+
|
|
1543
|
+
/** Value tokens of a multi-value flag: everything after `--name` up to the next `--flag`. */
|
|
1544
|
+
function flagValues(rest: string[], name: string): string[] {
|
|
1545
|
+
const i = rest.indexOf(`--${name}`);
|
|
1546
|
+
if (i === -1) return [];
|
|
1547
|
+
const out: string[] = [];
|
|
1548
|
+
for (let j = i + 1; j < rest.length && !rest[j].startsWith("--"); j++) out.push(rest[j]);
|
|
1549
|
+
return out;
|
|
1550
|
+
}
|
|
1551
|
+
|
|
1475
1552
|
async function gateInit(o: GateCtx): Promise<RunResult> {
|
|
1476
1553
|
const { root, ui, rest, flag } = o;
|
|
1477
1554
|
// a recursive mkdir is silent about whether it created anything, and `flow init --write` is the
|
|
@@ -1490,8 +1567,15 @@ async function gateInit(o: GateCtx): Promise<RunResult> {
|
|
|
1490
1567
|
const det = detectProject(root, branch);
|
|
1491
1568
|
const origin = await originUrl(root);
|
|
1492
1569
|
det.partial.forge = origin ? detectForge(origin) : undefined; // confirmed or corrected by the operator during setup; absent = no origin to detect from
|
|
1493
|
-
|
|
1570
|
+
const mergeEv = await mergeHistoryEvidence(root, branch); // "what do you actually do when a PR merges", read off the log
|
|
1571
|
+
det.partial.merge = mergeEv?.note;
|
|
1572
|
+
const tagEv = await tagPatternEvidence(root);
|
|
1573
|
+
if (tagEv) {
|
|
1574
|
+
det.partial.versionTag = tagEv.pattern;
|
|
1575
|
+
det.report.push(`tags: ${tagEv.note} → versionTag = ${tagEv.pattern}`);
|
|
1576
|
+
}
|
|
1494
1577
|
const draftFresh = buildDraft(det);
|
|
1578
|
+
const questions = setupQuestions(det, { merge: mergeEv, tag: tagEv });
|
|
1495
1579
|
if (flag("draft")) return { text: existsSync(mdFile) ? readFileSync(mdFile, "utf8") : draftFresh }; // read path: prints content, writes nothing (and offers no deletions)
|
|
1496
1580
|
// ghosts: feature dirs whose state.json is gone — inert, invisible to status and guards, and only findable by eye
|
|
1497
1581
|
const ghosts = ghostFeatureDirs(root);
|
|
@@ -1502,6 +1586,7 @@ async function gateInit(o: GateCtx): Promise<RunResult> {
|
|
|
1502
1586
|
notes.push(`removed ${ghosts.length} ghost feature dir(s): ${ghosts.map((g) => g.slice(".dev-flow/".length)).join(", ")}`);
|
|
1503
1587
|
} else notes.push(`kept ${ghosts.length} ghost feature dir(s) — inert, remove them whenever you like`);
|
|
1504
1588
|
}
|
|
1589
|
+
const current = existsSync(mdFile) ? readFileSync(mdFile, "utf8") : null;
|
|
1505
1590
|
/** Validate, back up what was there (the operator's rules are not regenerable), write. */
|
|
1506
1591
|
const writeMd = (text: string): { rej: RunResult } | { warn: string[] } => {
|
|
1507
1592
|
const parsed = parseProjectMd(text);
|
|
@@ -1510,34 +1595,82 @@ async function gateInit(o: GateCtx): Promise<RunResult> {
|
|
|
1510
1595
|
writeFileSync(mdFile, text.endsWith("\n") ? text : `${text}\n`);
|
|
1511
1596
|
return { warn: parsed.warn };
|
|
1512
1597
|
};
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1598
|
+
/** After a write: the playbook belongs in git — commit it on the operator's word, else say how. */
|
|
1599
|
+
const afterWrite = async (w: { warn: string[] }, before: string | null, after: string, offer = false): Promise<void> => {
|
|
1600
|
+
notes.push(`changes:\n${lineDiff(before ?? "", after)}`);
|
|
1601
|
+
if (w.warn.length) notes.push("warnings:", ...w.warn.map((x) => ` ${x}`));
|
|
1602
|
+
// the dialog belongs to the human-driven first init only: an agent write (--write/--answers) follows a chat
|
|
1603
|
+
// confirmation and must not open a second question — it commits on --track
|
|
1604
|
+
const track = flag("track") || (offer && ui.hasUI && (await ui.confirm("Commit project.md?", "The playbook belongs in git. Commit .dev-flow/project.md now (only that file, as a playbook chore)?")));
|
|
1605
|
+
if (!track) {
|
|
1606
|
+
notes.push(GIT_TRACK_NOTE, "(or re-run the same call with --track on the operator's word)");
|
|
1607
|
+
return;
|
|
1608
|
+
}
|
|
1609
|
+
const c = await sh(`git add -f .dev-flow/project.md && DEV_FLOW_ALLOW_MAIN=1 git commit -q -m ${sq(before ? "chore: update dev-flow playbook" : "chore: add dev-flow playbook")} -- .dev-flow/project.md`, root, 60_000);
|
|
1610
|
+
notes.push(c.ok ? "project.md committed (git add -f + playbook chore)" : `commit failed — ${c.out.split("\n").find(Boolean) ?? "?"}; ${GIT_TRACK_NOTE}`);
|
|
1611
|
+
};
|
|
1612
|
+
const answerToks = [...flagValues(rest, "answers"), ...(flag("answers-file") ? (() => { const f = flagValues(rest, "answers-file")[0]; return f && existsSync(path.resolve(root, f)) ? readFileSync(path.resolve(root, f), "utf8").split("\n") : [`<missing answers file ${f ?? ""}>`]; })() : [])];
|
|
1613
|
+
if (flag("answers") || flag("answers-file")) {
|
|
1614
|
+
// the operator's answers, applied as targeted edits onto the draft (first init) or the current file —
|
|
1615
|
+
// hand-written lines survive; the result is previewed until the operator's word anchors the write
|
|
1616
|
+
const parsed = parseAnswers(answerToks);
|
|
1617
|
+
if (parsed.errors.length) return { text: `answers REJECTED:\n- ${parsed.errors.join("\n- ")}`, isError: true };
|
|
1618
|
+
if (!parsed.answers.length) return { text: "usage: flow init --answers key=value [key=value …] | --answers-file <path> (one key=value per line)", isError: true };
|
|
1619
|
+
const base = current ?? draftFresh;
|
|
1620
|
+
const applied = applyAnswers(base, parsed.answers);
|
|
1621
|
+
const lint = parseProjectMd(applied.text);
|
|
1622
|
+
if (lint.hard.length) return { text: `project.md REJECTED:\n- ${lint.hard.join("\n- ")}`, isError: true };
|
|
1623
|
+
const preview = [`${current ? "playbook" : "draft"} with ${parsed.answers.length} answer(s):`, ...applied.changes.map((c) => ` ${c}`), "", mdDigest(applied.text)];
|
|
1624
|
+
const ok = flag("confirmed") || (ui.hasUI && (await ui.confirm("Write project.md?", preview.join("\n"))));
|
|
1625
|
+
if (!ok) {
|
|
1626
|
+
const open = questions.filter((x) => !parsed.answers.some(([k]) => k === x.key || (x.key === "check.<name>" && (k.startsWith("check.") || ["test", "build", "run"].includes(k)))));
|
|
1627
|
+
return { text: [...preview, "", `changes:\n${lineDiff(base, applied.text)}`, "", "not written — present this to the operator; on their confirmation re-run the same call with --confirmed", ...(open.length ? ["still unanswered:", ...renderQuestions(open)] : [])].join("\n") };
|
|
1628
|
+
}
|
|
1629
|
+
const w = writeMd(applied.text);
|
|
1630
|
+
if ("rej" in w) return w.rej;
|
|
1631
|
+
notes.push(`project.md written with ${parsed.answers.length} answer(s)`);
|
|
1632
|
+
await afterWrite(w, current, applied.text);
|
|
1633
|
+
} else if (flag("write") || flag("write-file")) {
|
|
1634
|
+
let content: string | undefined;
|
|
1635
|
+
if (flag("write-file")) {
|
|
1636
|
+
const f = flagValues(rest, "write-file")[0];
|
|
1637
|
+
if (!f || !existsSync(path.resolve(root, f))) return { text: `usage: flow init --write-file <path> — ${f ? `${f} does not exist` : "no path given"}`, isError: true };
|
|
1638
|
+
content = readFileSync(path.resolve(root, f), "utf8");
|
|
1639
|
+
} else {
|
|
1640
|
+
content = rest[rest.indexOf("--write") + 1];
|
|
1641
|
+
if (!content || content.startsWith("--")) return { text: 'usage: flow init --write "<full project.md content>" (or --write-file <path>)', isError: true };
|
|
1642
|
+
}
|
|
1516
1643
|
const w = writeMd(content);
|
|
1517
1644
|
if ("rej" in w) return w.rej;
|
|
1518
|
-
notes.push("project.md written (operator-owned playbook)"
|
|
1519
|
-
|
|
1520
|
-
} else if (!
|
|
1521
|
-
// first init: never write silently. The
|
|
1522
|
-
//
|
|
1523
|
-
// (validated) after presenting the digest; an interactive init may confirm the draft right here.
|
|
1645
|
+
notes.push("project.md written (operator-owned playbook)");
|
|
1646
|
+
await afterWrite(w, current, content);
|
|
1647
|
+
} else if (!current) {
|
|
1648
|
+
// first init: never write silently. The questions come first — a dialog that offered the bare detection
|
|
1649
|
+
// draft before them wrote a playbook with the merge style, forge and versioning still unanswered.
|
|
1524
1650
|
const brief = [
|
|
1525
1651
|
"setup — project.md not written yet; nothing is drafted to disk until the operator confirms.",
|
|
1652
|
+
"detected:",
|
|
1526
1653
|
...det.report.map((r) => ` ${r}`),
|
|
1527
|
-
"questions for the operator (
|
|
1528
|
-
...
|
|
1529
|
-
"agent: ask these in chat
|
|
1530
|
-
GIT_TRACK_NOTE,
|
|
1654
|
+
"questions for the operator (detected value shown; `accept` is the answer that keeps it):",
|
|
1655
|
+
...renderQuestions(questions),
|
|
1656
|
+
"agent: ask these in chat — group the ones with an `accept` line as \"keep these?\", explain the rest in a line each. Then apply every answer in one call: flow init --answers key=value … (previews the digest and diff, writes nothing); on the operator's confirmation re-run it with --confirmed (add --track to commit the playbook). Free-text additions — checklist items, prose, flow-guard rules — go in through flow init --write-file <path> with the full file (flow init --draft prints the current draft).",
|
|
1531
1657
|
];
|
|
1658
|
+
let wrote = false;
|
|
1532
1659
|
if (ui.hasUI) {
|
|
1533
|
-
const
|
|
1660
|
+
const accepts = questions.filter((x) => x.accept).map((x) => x.accept!);
|
|
1661
|
+
const withAccepts = applyAnswers(draftFresh, parseAnswers(accepts).answers).text;
|
|
1662
|
+
const ok = await ui.confirm("Accept the detected setup?", `${mdDigest(withAccepts)}\n\nWrite this now, keeping every detected value? ${questions.length - accepts.length} question(s) have no detected answer (${questions.filter((x) => !x.accept).map((x) => x.key).join(", ")}) — decline to answer them in chat first.`);
|
|
1534
1663
|
if (ok) {
|
|
1535
|
-
const w = writeMd(
|
|
1664
|
+
const w = writeMd(withAccepts);
|
|
1536
1665
|
if ("rej" in w) return w.rej;
|
|
1537
|
-
|
|
1538
|
-
|
|
1666
|
+
wrote = true;
|
|
1667
|
+
notes.push("wrote .dev-flow/project.md from detection with the detected values accepted — change any of them with flow init --answers key=value", ...det.report.map((r) => ` ${r}`));
|
|
1668
|
+
const open = questions.filter((x) => !x.accept);
|
|
1669
|
+
if (open.length) notes.push("still open (answer any time):", ...renderQuestions(open));
|
|
1670
|
+
await afterWrite(w, null, withAccepts, true);
|
|
1671
|
+
}
|
|
1539
1672
|
}
|
|
1540
|
-
notes.push(...brief);
|
|
1673
|
+
if (!wrote) notes.push(...brief);
|
|
1541
1674
|
} else if (flag("force")) {
|
|
1542
1675
|
// a destructive reset of the operator's own file needs their word: --confirmed for an agent, one dialog for a human
|
|
1543
1676
|
const ok = flag("confirmed") || (ui.hasUI && (await ui.confirm("Overwrite project.md?", `flow init --force replaces the operator playbook with a fresh detection draft. Hand-written rules, checklist items and guidance are lost (a copy is kept as project.md.bak).`)));
|
|
@@ -1550,21 +1683,26 @@ async function gateInit(o: GateCtx): Promise<RunResult> {
|
|
|
1550
1683
|
// a draft cannot reproduce hand-written prose, items and keys. Edit the file, or flow init --write.
|
|
1551
1684
|
const loaded = loadProject(dfDir(root));
|
|
1552
1685
|
const findings = doctorFindings(root, loaded.cfg, loaded.md);
|
|
1553
|
-
notes.push("project.md already exists — kept (edit it directly, flow init --write to replace it, --force to redraft)", findings.length ? `doctor: ${findings.length} finding(s):` : "doctor: no findings", ...findings.map((x) => ` ${x}`));
|
|
1686
|
+
notes.push("project.md already exists — kept (edit it directly, flow init --answers key=value for one knob, --write-file to replace it, --force to redraft)", findings.length ? `doctor: ${findings.length} finding(s):` : "doctor: no findings", ...findings.map((x) => ` ${x}`));
|
|
1554
1687
|
}
|
|
1555
1688
|
const initCfg = loadProject(dfDir(root)).cfg;
|
|
1556
1689
|
if (initCfg.mainHook) {
|
|
1690
|
+
// a hook manager (husky, lefthook…) points core.hooksPath elsewhere: git never runs .git/hooks then,
|
|
1691
|
+
// so a hook installed there would guard nothing — print the lines for the manager's own hook instead
|
|
1692
|
+
const hp = await sh("git config --get core.hooksPath", root, 10_000);
|
|
1693
|
+
const hooksPath = hp.ok ? hp.out.trim() : ""; // unset exits 1, and sh() then carries the error text
|
|
1557
1694
|
const hookDir = path.join(root, ".git", "hooks");
|
|
1558
1695
|
const hook = path.join(hookDir, "pre-commit");
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1696
|
+
const body = mainHookBody(initCfg.defaultBranch);
|
|
1697
|
+
if (hooksPath && path.resolve(root, hooksPath) !== hookDir) {
|
|
1698
|
+
const theirs = path.join(hooksPath, "pre-commit");
|
|
1699
|
+
const has = existsSync(path.resolve(root, theirs)) && readFileSync(path.resolve(root, theirs), "utf8").includes("DEV_FLOW_ALLOW_MAIN");
|
|
1700
|
+
if (!has) notes.push(`core.hooksPath = ${hooksPath} — git runs hooks from there, not .git/hooks, so dev-flow installed none; to block main commits outside Pi, add to ${theirs}:\n${body}`);
|
|
1701
|
+
} else if (existsSync(hookDir) && !existsSync(hook)) {
|
|
1702
|
+
writeFileSync(hook, `#!/bin/sh\n# installed by dev-flow: direct commits to ${initCfg.defaultBranch} are forbidden (override: DEV_FLOW_ALLOW_MAIN=1)\n${body}`, { mode: 0o755 });
|
|
1565
1703
|
notes.push("pre-commit hook installed (blocks commits on main)");
|
|
1566
|
-
} else if (existsSync(hook) && !readFileSync(hook, "utf8").includes("installed by dev-flow")) {
|
|
1567
|
-
notes.push(
|
|
1704
|
+
} else if (existsSync(hook) && !readFileSync(hook, "utf8").includes("installed by dev-flow") && !readFileSync(hook, "utf8").includes("DEV_FLOW_ALLOW_MAIN")) {
|
|
1705
|
+
notes.push(`existing pre-commit hook found — dev-flow did not replace it; main commits outside Pi stay unguarded until you add to .git/hooks/pre-commit:\n${body}`);
|
|
1568
1706
|
}
|
|
1569
1707
|
}
|
|
1570
1708
|
return { text: notes.join("\n") };
|
|
@@ -1864,7 +2002,7 @@ async function gateTest(o: GateCtx): Promise<RunResult> {
|
|
|
1864
2002
|
const { state, err } = needState(root, sess, slugArg);
|
|
1865
2003
|
if (err) return err;
|
|
1866
2004
|
if (!cfg.commands.test) return { text: "no commands.test configured — add `test = <command>` under ## implement in .dev-flow/project.md", isError: true };
|
|
1867
|
-
const res = await sh(cfg.commands.test, gateCwd(root, state!));
|
|
2005
|
+
const res = await sh(cfg.commands.test, gateCwd(root, state!), undefined, featureEnv(root, state!));
|
|
1868
2006
|
state!.checks.test = { ok: res.ok, at: now() };
|
|
1869
2007
|
await stampChecks(root, state!, ["test"]);
|
|
1870
2008
|
writeState(root, state!);
|
|
@@ -1940,6 +2078,8 @@ async function gateAbort(o: GateCtx): Promise<RunResult> {
|
|
|
1940
2078
|
return { text: `aborted ${target} — feature removed (nothing approved, nothing to recover)` };
|
|
1941
2079
|
}
|
|
1942
2080
|
if (sess.slug === target) sess.bind(null);
|
|
2081
|
+
// the scratch dir is the bound session's working junk — it does not outlive the binding
|
|
2082
|
+
rmSync(featureTmpDir(dfDir(root), target), { recursive: true, force: true });
|
|
1943
2083
|
if (st?.worktree) { st.aborted = now(); writeState(root, st); } // the doctor skips the removed worktree for stamped states (gh#138)
|
|
1944
2084
|
return { text: `session unbound from ${target}; state stays at .dev-flow/${target}/` + (st?.aborted ? " (marked aborted — the doctor leaves it alone once you clean the worktree up)" : "") + (st?.worktree ? `\nto remove the worktree and branch:\n git worktree remove ${st.worktree}\n git branch -D ${st.branch}` : "") };
|
|
1945
2085
|
}
|
|
@@ -2528,7 +2668,22 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2528
2668
|
pi.appendEntry("dev-flow-skill", { core: true, stale: true });
|
|
2529
2669
|
});
|
|
2530
2670
|
|
|
2671
|
+
// A bash call every guard let through runs with TMPDIR in its bound feature's scratch dir
|
|
2672
|
+
// (.dev-flow/<slug>/tmp/): mktemp, os.tmpdir() and test fixtures land there and flow finish removes
|
|
2673
|
+
// them. Prefixed only after the verdict, so no guard ever judges the prefix.
|
|
2531
2674
|
pi.on("tool_call", async (event, ctx) => {
|
|
2675
|
+
const verdict = await guardToolCall(event, ctx);
|
|
2676
|
+
if (verdict || !isToolCallEventType("bash", event) || !guardsAreMine() || !initiated(ctx.cwd)) return verdict;
|
|
2677
|
+
const root = await flowRoot(ctx.cwd);
|
|
2678
|
+
const bound = boundFeature(root, sessionKey(ctx));
|
|
2679
|
+
if (!bound) return undefined;
|
|
2680
|
+
const dir = featureTmpDir(dfDir(root), bound.slug);
|
|
2681
|
+
mkdirSync(dir, { recursive: true });
|
|
2682
|
+
event.input.command = withTmpDir(String(event.input.command ?? ""), dir);
|
|
2683
|
+
return undefined;
|
|
2684
|
+
});
|
|
2685
|
+
|
|
2686
|
+
async function guardToolCall(event: ToolCallEvent, ctx: ExtensionContext): Promise<ToolCallEventResult | undefined> {
|
|
2532
2687
|
if (!guardsAreMine()) return undefined; // election: only the newest loaded copy judges
|
|
2533
2688
|
// pi kills a shell call only when a timeout was passed, and the model omits it in ~75% of
|
|
2534
2689
|
// calls (observed hangs: hours). Deterministic class defaults, clamped ceilings — runs for
|
|
@@ -2658,7 +2813,7 @@ export default function devFlow(pi: ExtensionAPI) {
|
|
|
2658
2813
|
}
|
|
2659
2814
|
}
|
|
2660
2815
|
return undefined;
|
|
2661
|
-
}
|
|
2816
|
+
}
|
|
2662
2817
|
|
|
2663
2818
|
pi.on("before_agent_start", async (_event, ctx) => {
|
|
2664
2819
|
if (!guardsAreMine()) return undefined;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-dev-flow",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.79.0",
|
|
4
4
|
"description": "Enforced feature workflow for Pi: plan → implement → pre-release → release, gated checkpoints, self-improvement reflections, one git worktree per feature, changelog + publish as part of the release",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
@@ -43,8 +43,8 @@ unmerged. `flow finish [slug]`:
|
|
|
43
43
|
through `flow abort` instead;
|
|
44
44
|
- requires the main checkout **clean and pushed** — an uncommitted changelog or
|
|
45
45
|
a local-only release commit is exactly what it protects against;
|
|
46
|
-
- removes the worktree and branch, then deletes `.dev-flow/<slug>/`
|
|
47
|
-
unbinds the session. A feature branch still on `origin` is deleted **only on
|
|
46
|
+
- removes the worktree and branch, then deletes `.dev-flow/<slug>/` (its
|
|
47
|
+
`tmp/` scratch dir included) and unbinds the session. A feature branch still on `origin` is deleted **only on
|
|
48
48
|
proof it was merged** — ancestor of `origin/<default>`, or a merged PR via gh
|
|
49
49
|
or glab (what a squash leaves behind); otherwise kept with a note. Uncommitted worktree edits block
|
|
50
50
|
finish; commits that never reached the default branch are read against the playbook's `merge` policy —
|
|
@@ -22,6 +22,9 @@ feature).
|
|
|
22
22
|
never block verify, they are what the operator sees they are approving.
|
|
23
23
|
2. Write tests as you go (project framework: the `test` key / `flow-check`
|
|
24
24
|
blocks).
|
|
25
|
+
Throwaway scripts and scratch output go in `$TMPDIR` (or `mktemp`), not a
|
|
26
|
+
hard-coded `/tmp/...`: in a bound session, and in every command a gate runs,
|
|
27
|
+
it is `.dev-flow/<slug>/tmp/`, and finish removes it with the feature.
|
|
25
28
|
3. `flow check` runs every tier-1 check (test, health, named `flow-check`
|
|
26
29
|
blocks) and records each against a fingerprint of the worktree; any later
|
|
27
30
|
worktree change makes them stale — verify reruns stale checks itself.
|
|
@@ -5,19 +5,19 @@
|
|
|
5
5
|
## Start
|
|
6
6
|
|
|
7
7
|
**No `.dev-flow/`?** `flow init` analyzes the repo and prints a **setup
|
|
8
|
-
brief**: what was detected plus one question per knob
|
|
9
|
-
(
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
`
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
8
|
+
brief**: what was detected plus one numbered question per knob, each with
|
|
9
|
+
`detected:` (what was found), `accept:` (the answer that keeps it) and `why:`.
|
|
10
|
+
Relay them: group the ones with an `accept` line as one "keep these?", and
|
|
11
|
+
explain the rest in a line each. Apply **every** answer in one call:
|
|
12
|
+
`flow init --answers key=value …` (targeted edits onto the draft; unknown
|
|
13
|
+
keys are refused). It **previews** the summary and diff and writes nothing.
|
|
14
|
+
Present that, and only after the operator confirms, re-run the same call with
|
|
15
|
+
`--confirmed --track` (validated write + the playbook commit). Free-text
|
|
16
|
+
additions (checklist items, prose, `flow-guard` rules) go through
|
|
17
|
+
`flow init --write-file <path>` with the full file (`flow init --draft` prints
|
|
18
|
+
it). Never hand-edit, and never write project.md before the confirmation.
|
|
19
|
+
Detection names CLAUDE.md / AGENTS.md / CONTRIBUTING.md when present: propose
|
|
20
|
+
their stage rules as prose, never copy them unasked. **With existing config** `flow init` is a **doctor**: discuss
|
|
21
21
|
findings, fix via the same write path, never overwrite hand edits without
|
|
22
22
|
confirming; ghost feature dirs (a `plan/` whose `state.json` is gone) come
|
|
23
23
|
with a delete offer — surface the dialog, never delete on your own.
|
package/src/core.ts
CHANGED
|
@@ -1325,6 +1325,18 @@ export function mainCheckoutRoot(cwd: string, commonDir: string | null): string
|
|
|
1325
1325
|
return main === path.resolve(cwd) ? null : main;
|
|
1326
1326
|
}
|
|
1327
1327
|
|
|
1328
|
+
/** A bound feature's scratch dir: every process the flow runs for it gets this as TMPDIR, so throwaways
|
|
1329
|
+
* and test fixtures land inside `.dev-flow/<slug>/` and `flow finish` removes them with the feature. */
|
|
1330
|
+
export function featureTmpDir(dfDir: string, slug: string): string {
|
|
1331
|
+
return path.join(dfDir, slug, "tmp");
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
/** The agent's shell command with TMPDIR pointed at the feature's scratch dir (newline-prefixed, the
|
|
1335
|
+
* shape pi's own commandPrefix uses — the command itself stays byte-for-byte what the guards judged). */
|
|
1336
|
+
export function withTmpDir(command: string, dir: string): string {
|
|
1337
|
+
return `export TMPDIR=${sq(dir)}\n${command}`;
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1328
1340
|
export function inScratchDir(abs: string, repoRoot?: string | null): boolean {
|
|
1329
1341
|
const real = realAbs(abs);
|
|
1330
1342
|
if (repoRoot) {
|
|
@@ -1382,7 +1394,7 @@ export function writeGuard(o: { abs: string; dfDir: string; features: FeatureRef
|
|
|
1382
1394
|
}
|
|
1383
1395
|
if (bound) {
|
|
1384
1396
|
if (bound.state.stage === "implement" || bound.state.stage === "pre-release")
|
|
1385
|
-
return `bound feature ${o.boundSlug} is at ${bound.state.stage} — edit its worktree (${bound.state.worktree}), not the main checkout; a throwaway script goes
|
|
1397
|
+
return `bound feature ${o.boundSlug} is at ${bound.state.stage} — edit its worktree (${bound.state.worktree}), not the main checkout; a throwaway script goes in $TMPDIR (.dev-flow/${o.boundSlug}/tmp/, removed at finish)`;
|
|
1386
1398
|
return null; // release: release chores may touch the main checkout
|
|
1387
1399
|
}
|
|
1388
1400
|
if (!o.features.length) return "no active flow — every request goes through flow: flow start <slug> for new work, flow use <slug> for an unfinished feature";
|
package/src/detect.ts
CHANGED
|
@@ -4,16 +4,41 @@
|
|
|
4
4
|
* Produces a *partial* config (merged over DEFAULTS by the caller) plus
|
|
5
5
|
* human-readable report lines. No LLM, no guessing beyond strong evidence —
|
|
6
6
|
* anything not confidently detected is left empty and reported as missing.
|
|
7
|
+
*
|
|
8
|
+
* Two kinds of output: `partial` is drafted into project.md (strong evidence only), `suggestions` are
|
|
9
|
+
* ready-made answers to setup questions (plausible, but a command that reaches a network or a registry
|
|
10
|
+
* is the operator's call, so it is offered — never drafted).
|
|
7
11
|
*/
|
|
8
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
12
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
9
13
|
import path from "node:path";
|
|
10
14
|
import { parseVersion } from "./core.ts";
|
|
11
15
|
|
|
16
|
+
/** A ready-made answer to one setup question: `flow init --answers <key>=<value>` applies it. */
|
|
17
|
+
export interface Suggestion {
|
|
18
|
+
key: string;
|
|
19
|
+
value: string;
|
|
20
|
+
why: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
12
23
|
export interface Detection {
|
|
13
|
-
/** `merge`
|
|
14
|
-
partial: {
|
|
24
|
+
/** `merge`/`versionTag` are not detected here (detection is fs-only): the caller fills them from git history. */
|
|
25
|
+
partial: {
|
|
26
|
+
defaultBranch: string;
|
|
27
|
+
commands: Record<string, string>;
|
|
28
|
+
versioning?: { file: string };
|
|
29
|
+
forge?: string;
|
|
30
|
+
merge?: string;
|
|
31
|
+
versionTag?: string;
|
|
32
|
+
/** a changelog file other than the default CHANGELOG.md; "" = none found (the release would expect one) */
|
|
33
|
+
changelog?: string;
|
|
34
|
+
/** extra tier-1 checks (lint, typecheck…) drafted as flow-check blocks under ## implement */
|
|
35
|
+
checks?: Record<string, string>;
|
|
36
|
+
/** flow-guard lines drafted under ## global (protect/forbid of secrets that exist on disk) */
|
|
37
|
+
guards?: string[];
|
|
38
|
+
};
|
|
15
39
|
report: string[]; // human lines: what was detected
|
|
16
40
|
missing: string[]; // command keys left empty (excluding setup)
|
|
41
|
+
suggestions: Suggestion[];
|
|
17
42
|
}
|
|
18
43
|
|
|
19
44
|
const read = (p: string): string | null => {
|
|
@@ -24,6 +49,8 @@ const read = (p: string): string | null => {
|
|
|
24
49
|
}
|
|
25
50
|
};
|
|
26
51
|
|
|
52
|
+
const firstExisting = (root: string, names: string[]): string | undefined => names.find((n) => existsSync(path.join(root, n)));
|
|
53
|
+
|
|
27
54
|
function pkgManager(root: string, field?: string): string {
|
|
28
55
|
const m = field?.match(/^(npm|pnpm|yarn|bun)@/);
|
|
29
56
|
if (m) return m[1];
|
|
@@ -33,17 +60,47 @@ function pkgManager(root: string, field?: string): string {
|
|
|
33
60
|
return "npm";
|
|
34
61
|
}
|
|
35
62
|
|
|
63
|
+
/** How a package manager runs a package.json script. `npm build` / `npm dev` are "Unknown command" —
|
|
64
|
+
* only test/start have npm shorthands — and `bun test` is bun's own runner, not the script. */
|
|
65
|
+
export function scriptCmd(pm: string, script: string): string {
|
|
66
|
+
if (pm === "npm" && (script === "test" || script === "start")) return `npm ${script}`;
|
|
67
|
+
return `${pm} run ${script}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
36
70
|
export function detectProject(root: string, defaultBranch: string): Detection {
|
|
37
71
|
const commands: Record<string, string> = {};
|
|
72
|
+
const checks: Record<string, string> = {};
|
|
73
|
+
const suggestions: Suggestion[] = [];
|
|
38
74
|
const report: string[] = [];
|
|
39
75
|
const guessed = /^(main|master|develop|trunk)$/.test(defaultBranch);
|
|
40
76
|
report.push(guessed ? `default branch: ${defaultBranch} (guessed from git)` : `default branch: "${defaultBranch}" looks like a working branch — confirm or correct it below`);
|
|
41
|
-
const detected = detectCommands(root, commands, report);
|
|
42
|
-
if (!detected) report.push("no supported manifest found — fill in commands yourself (see
|
|
77
|
+
const detected = detectCommands(root, commands, checks, report) || detectTaskRunner(root, commands, checks, report);
|
|
78
|
+
if (!detected) report.push("no supported manifest or task runner found — fill in commands yourself (see docs/playbook.md)");
|
|
43
79
|
if (Object.keys(commands).length) report.push(`commands: ${Object.entries(commands).map(([k, v]) => `${k}="${v}"`).join(", ")}`);
|
|
80
|
+
if (Object.keys(checks).length) report.push(`extra checks (drafted as flow-check blocks): ${Object.entries(checks).map(([k, v]) => `${k}="${v}"`).join(", ")}`);
|
|
44
81
|
const missing = ["test", "build", "run"].filter((k) => !commands[k]);
|
|
45
82
|
const versioning = detectVersioning(root, report);
|
|
46
|
-
|
|
83
|
+
detectWorkspaces(root, report);
|
|
84
|
+
const ci = detectCi(root, report);
|
|
85
|
+
detectDocker(root, report, suggestions);
|
|
86
|
+
const guards = detectSecrets(root, report);
|
|
87
|
+
const changelog = detectChangelog(root, report);
|
|
88
|
+
detectPublish(root, ci, report, suggestions);
|
|
89
|
+
const agentDocs = ["CLAUDE.md", "AGENTS.md", "CONTRIBUTING.md"].filter((f) => existsSync(path.join(root, f)));
|
|
90
|
+
if (agentDocs.length) report.push(`project docs: ${agentDocs.join(", ")} — read them for stage guidance and release rules worth moving into the playbook (proposed to the operator, never copied silently)`);
|
|
91
|
+
return {
|
|
92
|
+
partial: {
|
|
93
|
+
defaultBranch,
|
|
94
|
+
commands,
|
|
95
|
+
...(versioning ? { versioning } : {}),
|
|
96
|
+
...(changelog !== undefined ? { changelog } : {}),
|
|
97
|
+
...(Object.keys(checks).length ? { checks } : {}),
|
|
98
|
+
...(guards.length ? { guards } : {}),
|
|
99
|
+
},
|
|
100
|
+
report,
|
|
101
|
+
missing,
|
|
102
|
+
suggestions,
|
|
103
|
+
};
|
|
47
104
|
}
|
|
48
105
|
|
|
49
106
|
/** Version manifest probe: first of VERSION / package.json / Cargo.toml / pyproject.toml holding a version. */
|
|
@@ -58,23 +115,29 @@ function detectVersioning(root: string, report: string[]): { file: string } | nu
|
|
|
58
115
|
return { file };
|
|
59
116
|
}
|
|
60
117
|
}
|
|
61
|
-
report.push("versioning: none found — ask the operator to pick/create a version manifest (VERSION recommended), then set
|
|
118
|
+
report.push("versioning: none found — ask the operator to pick/create a version manifest (VERSION recommended), then set versionFile");
|
|
62
119
|
return null;
|
|
63
120
|
}
|
|
64
121
|
|
|
65
|
-
function detectCommands(root: string, c: Record<string, string>, report: string[]): boolean {
|
|
122
|
+
function detectCommands(root: string, c: Record<string, string>, checks: Record<string, string>, report: string[]): boolean {
|
|
66
123
|
// node — first match wins; other ecosystems below are realistically exclusive here
|
|
67
124
|
const pkgRaw = read(path.join(root, "package.json"));
|
|
68
125
|
if (pkgRaw) {
|
|
69
126
|
try {
|
|
70
127
|
const pkg = JSON.parse(pkgRaw) as { packageManager?: string; scripts?: Record<string, string> };
|
|
71
128
|
const pm = pkgManager(root, pkg.packageManager);
|
|
129
|
+
const s = pkg.scripts ?? {};
|
|
72
130
|
report.push(`node project detected (package manager: ${pm})`);
|
|
73
131
|
c.setup = `${pm} install`;
|
|
74
|
-
if (
|
|
75
|
-
if (
|
|
76
|
-
if (
|
|
77
|
-
else if (
|
|
132
|
+
if (s.test) c.test = scriptCmd(pm, "test");
|
|
133
|
+
if (s.build) c.build = scriptCmd(pm, "build");
|
|
134
|
+
if (s.dev) c.run = scriptCmd(pm, "dev");
|
|
135
|
+
else if (s.start) c.run = scriptCmd(pm, "start");
|
|
136
|
+
if (s.lint) checks.lint = scriptCmd(pm, "lint");
|
|
137
|
+
const tc = ["typecheck", "type-check", "check-types", "tsc"].find((k) => s[k]);
|
|
138
|
+
if (tc) checks.typecheck = scriptCmd(pm, tc);
|
|
139
|
+
const fmt = ["format:check", "fmt:check", "prettier:check"].find((k) => s[k]);
|
|
140
|
+
if (fmt) checks.format = scriptCmd(pm, fmt);
|
|
78
141
|
return true;
|
|
79
142
|
} catch {
|
|
80
143
|
report.push("package.json exists but is not valid JSON — ignored");
|
|
@@ -83,22 +146,160 @@ function detectCommands(root: string, c: Record<string, string>, report: string[
|
|
|
83
146
|
if (existsSync(path.join(root, "Cargo.toml"))) {
|
|
84
147
|
report.push("rust project detected (Cargo.toml)");
|
|
85
148
|
Object.assign(c, { test: "cargo test", build: "cargo build --release", run: "cargo run" });
|
|
149
|
+
Object.assign(checks, { clippy: "cargo clippy --all-targets -- -D warnings", format: "cargo fmt --check" });
|
|
86
150
|
return true;
|
|
87
151
|
}
|
|
88
152
|
if (existsSync(path.join(root, "go.mod"))) {
|
|
89
153
|
report.push("go project detected (go.mod)");
|
|
90
154
|
Object.assign(c, { test: "go test ./...", build: "go build ./..." });
|
|
155
|
+
checks.vet = "go vet ./...";
|
|
91
156
|
return true;
|
|
92
157
|
}
|
|
93
158
|
if (existsSync(path.join(root, "pyproject.toml")) || existsSync(path.join(root, "requirements.txt"))) {
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
}
|
|
159
|
+
const py = read(path.join(root, "pyproject.toml")) ?? "";
|
|
160
|
+
const runner = existsSync(path.join(root, "uv.lock")) ? "uv run " : existsSync(path.join(root, "poetry.lock")) ? "poetry run " : "";
|
|
161
|
+
if (runner === "uv run ") c.setup = "uv sync";
|
|
162
|
+
else if (runner === "poetry run ") c.setup = "poetry install";
|
|
163
|
+
else if (existsSync(path.join(root, "requirements.txt"))) c.setup = "pip install -r requirements.txt";
|
|
164
|
+
c.test = `${runner}pytest`;
|
|
165
|
+
// a tool configured in pyproject is strong evidence the project runs it
|
|
166
|
+
if (/^\[tool\.ruff\b/m.test(py)) checks.lint = `${runner}ruff check .`;
|
|
167
|
+
if (/^\[tool\.mypy\b/m.test(py)) checks.typecheck = `${runner}mypy .`;
|
|
100
168
|
report.push("python project detected");
|
|
101
169
|
return true;
|
|
102
170
|
}
|
|
103
171
|
return false;
|
|
104
172
|
}
|
|
173
|
+
|
|
174
|
+
/** Makefile / justfile / Taskfile targets — the fallback when no language manifest decided the commands. */
|
|
175
|
+
function detectTaskRunner(root: string, c: Record<string, string>, checks: Record<string, string>, report: string[]): boolean {
|
|
176
|
+
const runners: [string, string, RegExp][] = [
|
|
177
|
+
["Makefile", "make", /^([A-Za-z][\w-]*)\s*:(?!=)/gm],
|
|
178
|
+
["justfile", "just", /^([A-Za-z][\w-]*)(?:\s+[^:\n=]*)?:(?!=)/gm],
|
|
179
|
+
["Taskfile.yml", "task", /^ {2}([A-Za-z][\w-]*):\s*$/gm],
|
|
180
|
+
];
|
|
181
|
+
for (const [file, bin, re] of runners) {
|
|
182
|
+
const raw = read(path.join(root, file)) ?? (file === "justfile" ? read(path.join(root, "Justfile")) : null);
|
|
183
|
+
if (!raw) continue;
|
|
184
|
+
const targets = new Set([...raw.matchAll(re)].map((m) => m[1]));
|
|
185
|
+
const pick = (...names: string[]) => names.find((n) => targets.has(n));
|
|
186
|
+
const t = pick("test", "tests", "check");
|
|
187
|
+
const b = pick("build");
|
|
188
|
+
const r = pick("run", "dev", "serve", "start");
|
|
189
|
+
const l = pick("lint");
|
|
190
|
+
if (!t && !b && !r && !l) continue;
|
|
191
|
+
if (t) c.test = `${bin} ${t}`;
|
|
192
|
+
if (b) c.build = `${bin} ${b}`;
|
|
193
|
+
if (r) c.run = `${bin} ${r}`;
|
|
194
|
+
if (l) checks.lint = `${bin} ${l}`;
|
|
195
|
+
report.push(`${file} targets detected (${[...targets].slice(0, 12).join(", ")})`);
|
|
196
|
+
return true;
|
|
197
|
+
}
|
|
198
|
+
return false;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function detectWorkspaces(root: string, report: string[]): void {
|
|
202
|
+
const pkg = read(path.join(root, "package.json")) ?? "";
|
|
203
|
+
const cargo = read(path.join(root, "Cargo.toml")) ?? "";
|
|
204
|
+
const kinds = [
|
|
205
|
+
/"workspaces"\s*:/.test(pkg) && "npm/yarn workspaces",
|
|
206
|
+
existsSync(path.join(root, "pnpm-workspace.yaml")) && "pnpm workspace",
|
|
207
|
+
/^\[workspace\]/m.test(cargo) && "cargo workspace",
|
|
208
|
+
existsSync(path.join(root, "go.work")) && "go workspace",
|
|
209
|
+
].filter(Boolean);
|
|
210
|
+
if (kinds.length) report.push(`monorepo: ${kinds.join(", ")} — the root commands run every package; ask whether some checks or the version manifest are per package`);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** CI is where the project already states what "green" means: its `run:` lines are the check commands
|
|
214
|
+
* the operator trusts, and a tool only CI has is a check the local gate cannot run (gh#134). */
|
|
215
|
+
function detectCi(root: string, report: string[]): string {
|
|
216
|
+
const files: string[] = [];
|
|
217
|
+
const wf = path.join(root, ".github", "workflows");
|
|
218
|
+
if (existsSync(wf)) {
|
|
219
|
+
try {
|
|
220
|
+
for (const f of readdirSync(wf)) if (/\.ya?ml$/.test(f)) files.push(path.join(".github", "workflows", f));
|
|
221
|
+
} catch {
|
|
222
|
+
/* unreadable dir: nothing to report */
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
for (const f of [".gitlab-ci.yml", ".circleci/config.yml", "azure-pipelines.yml", "bitbucket-pipelines.yml"]) if (existsSync(path.join(root, f))) files.push(f);
|
|
226
|
+
if (!files.length) return "";
|
|
227
|
+
const all = files.map((f) => read(path.join(root, f)) ?? "").join("\n");
|
|
228
|
+
const runs = [...new Set([...all.matchAll(/^\s*(?:-\s*)?(?:run|script):\s*(?!\||>)(.+?)\s*$/gm)].map((m) => m[1].replace(/^["']|["']$/g, "")).filter((r) => !/^\$\{\{/.test(r)))];
|
|
229
|
+
report.push(`CI: ${files.join(", ")}${runs.length ? ` — runs: ${runs.slice(0, 8).map((r) => `\`${r}\``).join(", ")}${runs.length > 8 ? ` (+${runs.length - 8})` : ""}` : ""} — the tier-1 checks should match what CI enforces`);
|
|
230
|
+
return all;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function detectDocker(root: string, report: string[], suggestions: Suggestion[]): void {
|
|
234
|
+
const dockerfile = firstExisting(root, ["Dockerfile", "docker/Dockerfile"]);
|
|
235
|
+
const compose = firstExisting(root, ["compose.yaml", "compose.yml", "docker-compose.yml", "docker-compose.yaml", "docker/compose.yaml", "docker/docker-compose.yml"]);
|
|
236
|
+
if (dockerfile) {
|
|
237
|
+
const ctx = path.dirname(dockerfile) === "." ? "." : `-f ${dockerfile} .`;
|
|
238
|
+
report.push(`docker: ${dockerfile}`);
|
|
239
|
+
suggestions.push({ key: "preflight", value: `docker build ${ctx}`, why: `${dockerfile} exists — prove the image builds before the tag triggers the real build` });
|
|
240
|
+
}
|
|
241
|
+
if (compose) {
|
|
242
|
+
const raw = read(path.join(root, compose)) ?? "";
|
|
243
|
+
const hc = /^\s+healthcheck:/m.test(raw);
|
|
244
|
+
report.push(`compose: ${compose}${hc ? " (declares a healthcheck)" : ""}`);
|
|
245
|
+
suggestions.push({ key: "dev", value: `docker compose -f ${compose} up -d --build`, why: `${compose} exists — the dev deploy the operator reviews before verify (must background and exit)` });
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Secrets that exist on disk get a drafted guard: the agent must never rewrite live credentials, and a
|
|
250
|
+
* backup copied beside them is the same secret (hence the basename glob). Templates are not secrets. */
|
|
251
|
+
function detectSecrets(root: string, report: string[]): string[] {
|
|
252
|
+
const guards: string[] = [];
|
|
253
|
+
let entries: string[] = [];
|
|
254
|
+
try {
|
|
255
|
+
entries = readdirSync(root);
|
|
256
|
+
} catch {
|
|
257
|
+
return guards;
|
|
258
|
+
}
|
|
259
|
+
const envs = entries.filter((f) => /^\.env(\.|$)/.test(f) && !/\.(example|sample|template|dist)$/.test(f));
|
|
260
|
+
if (envs.length) guards.push("protect .env* :: live secrets — and any backup copied beside them");
|
|
261
|
+
for (const d of ["secrets", ".secrets"]) if (existsSync(path.join(root, d))) guards.push(`forbid ${d} :: secret storage`);
|
|
262
|
+
const tmpl = entries.find((f) => /^\.env\.(example|sample|template|dist)$/.test(f));
|
|
263
|
+
if (envs.length || guards.length) report.push(`secrets on disk: ${[...envs, ...guards.filter((g) => g.startsWith("forbid")).map((g) => g.split(/\s+/)[1])].join(", ")} — drafted as flow-guard rules`);
|
|
264
|
+
if (tmpl) report.push(`env template: ${tmpl} — a fresh worktree needs its own .env: put the copy into setup (e.g. cp <main checkout>/.env .env)`);
|
|
265
|
+
return guards;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** undefined = CHANGELOG.md is there (the default holds); a name = a different file; "" = none found. */
|
|
269
|
+
function detectChangelog(root: string, report: string[]): string | undefined {
|
|
270
|
+
if (existsSync(path.join(root, "CHANGELOG.md"))) return undefined;
|
|
271
|
+
const other = firstExisting(root, ["CHANGES.md", "HISTORY.md", "CHANGELOG", "NEWS.md", "docs/CHANGELOG.md"]);
|
|
272
|
+
if (other) {
|
|
273
|
+
report.push(`changelog: ${other}`);
|
|
274
|
+
return other;
|
|
275
|
+
}
|
|
276
|
+
report.push("changelog: none found — the release gates expect CHANGELOG.md: create one, or answer changelog= (empty) to opt out");
|
|
277
|
+
return "";
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** A release CI that publishes is the strongest hint of what release-done should verify. */
|
|
281
|
+
function detectPublish(root: string, ci: string, report: string[], suggestions: Suggestion[]): void {
|
|
282
|
+
const pkg = (() => {
|
|
283
|
+
try {
|
|
284
|
+
return JSON.parse(read(path.join(root, "package.json")) ?? "null") as { name?: string; private?: boolean } | null;
|
|
285
|
+
} catch {
|
|
286
|
+
return null;
|
|
287
|
+
}
|
|
288
|
+
})();
|
|
289
|
+
if (pkg?.name && !pkg.private && /\bnpm publish\b|\bpnpm publish\b|\byarn npm publish\b/.test(ci)) {
|
|
290
|
+
report.push(`publish: CI runs npm publish for ${pkg.name}`);
|
|
291
|
+
suggestions.push({ key: "artifact", value: `npm view --prefer-online ${pkg.name}@{version} version`, why: "CI publishes to npm — release-done proves the version is really out (--prefer-online skips npm's cached 404)" });
|
|
292
|
+
}
|
|
293
|
+
if (/\bcargo publish\b/.test(ci)) {
|
|
294
|
+
const name = (read(path.join(root, "Cargo.toml")) ?? "").match(/^\s*name\s*=\s*"([^"]+)"/m)?.[1];
|
|
295
|
+
if (name) {
|
|
296
|
+
report.push(`publish: CI runs cargo publish for ${name}`);
|
|
297
|
+
suggestions.push({ key: "artifact", value: `cargo search ${name} --limit 1 | grep -q '"{version}"'`, why: "CI publishes the crate — release-done proves the version is on crates.io" });
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
const image = ci.match(/\b(?:docker\/build-push-action|docker push|buildx[^\n]*--push)\b[\s\S]{0,400}?tags:\s*([\w./-]+\/[\w.-]+):/)?.[1] ?? ci.match(/docker push\s+([\w./-]+\/[\w.-]+)(?::|\s)/)?.[1];
|
|
301
|
+
if (image && !image.includes("$")) {
|
|
302
|
+
report.push(`publish: CI pushes the image ${image}`);
|
|
303
|
+
suggestions.push({ key: "artifact", value: `docker buildx imagetools inspect ${image}:{version}`, why: "CI pushes a container image — release-done proves the tag reached the registry" });
|
|
304
|
+
}
|
|
305
|
+
}
|
package/src/projectmd.ts
CHANGED
|
@@ -283,6 +283,121 @@ export function setPlaybookKey(text: string, stage: MdStage, key: string, value:
|
|
|
283
283
|
return { text: lines.join("\n"), where: `## ${stage} — opened a flow block for it` };
|
|
284
284
|
}
|
|
285
285
|
|
|
286
|
+
/** Set one ` ```flow-check <name>` block under ## implement: replaces the body of an existing block of that
|
|
287
|
+
* name, else inserts a new block right after the section's last fence (or under the heading). An empty
|
|
288
|
+
* command removes the block — the operator's "no, we don't lint". */
|
|
289
|
+
export function setPlaybookCheck(text: string, name: string, cmd: string): { text: string; where: string } {
|
|
290
|
+
const lines = text.split("\n");
|
|
291
|
+
let head = lines.findIndex((l) => /^##\s+implement\s*$/i.test(l));
|
|
292
|
+
if (head === -1) {
|
|
293
|
+
if (!cmd) return { text, where: `no flow-check ${name} to remove` };
|
|
294
|
+
const tail = `\n## implement\n\n` + "```flow-check " + name + "\n" + cmd + "\n```\n";
|
|
295
|
+
return { text: (text.endsWith("\n") ? text : text + "\n") + tail, where: "## implement — the section was created for it" };
|
|
296
|
+
}
|
|
297
|
+
let end = lines.length;
|
|
298
|
+
for (let i = head + 1; i < lines.length; i++) if (/^##\s/.test(lines[i])) { end = i; break; }
|
|
299
|
+
let lastClose = -1;
|
|
300
|
+
for (let i = head + 1; i < end; i++) {
|
|
301
|
+
if (!/^```/.test(lines[i]) || lines[i].trim() === "```") continue;
|
|
302
|
+
let close = end - 1;
|
|
303
|
+
for (let j = i + 1; j < end; j++) if (lines[j].trim() === "```") { close = j; break; }
|
|
304
|
+
if (lines[i].trim() === "```flow-check " + name) {
|
|
305
|
+
if (!cmd) {
|
|
306
|
+
lines.splice(i, close - i + 1 + (lines[close + 1] === "" ? 1 : 0));
|
|
307
|
+
return { text: lines.join("\n"), where: `## implement flow-check ${name} (removed)` };
|
|
308
|
+
}
|
|
309
|
+
lines.splice(i + 1, close - i - 1, cmd);
|
|
310
|
+
return { text: lines.join("\n"), where: `## implement flow-check ${name} (replaced its command)` };
|
|
311
|
+
}
|
|
312
|
+
lastClose = close;
|
|
313
|
+
i = close;
|
|
314
|
+
}
|
|
315
|
+
if (!cmd) return { text, where: `no flow-check ${name} to remove` };
|
|
316
|
+
const at = lastClose === -1 ? head + 1 : lastClose + 1;
|
|
317
|
+
lines.splice(at, 0, "", "```flow-check " + name, cmd, "```");
|
|
318
|
+
return { text: lines.join("\n"), where: `## implement flow-check ${name}` };
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** Where each setup answer lives. `check.<name>` is a flow-check block; everything else a flow key. */
|
|
322
|
+
const ANSWER_STAGE: Record<string, MdStage> = {
|
|
323
|
+
defaultBranch: "global", forge: "global", worktreeDir: "global", branchPattern: "global", mainHook: "global", mockupGlobs: "global", bashTimeout: "global",
|
|
324
|
+
setup: "implement", test: "implement", build: "implement", run: "implement", seedData: "implement", health: "implement", dev: "implement", healthWait: "implement",
|
|
325
|
+
versionFile: "pre-release", versionTag: "pre-release", changelog: "pre-release", review: "pre-release",
|
|
326
|
+
releases: "release", artifact: "release", preflight: "release", merge: "release",
|
|
327
|
+
};
|
|
328
|
+
/** The draft's placeholder comment per key (buildDraft) — stale once the key has an answer. */
|
|
329
|
+
const DRAFT_HINTS: Record<string, RegExp> = { versionFile: /<!-- versionFile = /, merge: /<!-- merge = /, changelog: /<!-- no changelog found/ };
|
|
330
|
+
export const ANSWER_KEYS = [...Object.keys(ANSWER_STAGE), "check.<name>"];
|
|
331
|
+
|
|
332
|
+
/** Parse `key=value` answer tokens (CLI args, or the lines of an answers file; `#` lines are comments). */
|
|
333
|
+
export function parseAnswers(tokens: string[]): { answers: [string, string][]; errors: string[] } {
|
|
334
|
+
const answers: [string, string][] = [];
|
|
335
|
+
const errors: string[] = [];
|
|
336
|
+
for (const raw of tokens) {
|
|
337
|
+
const t = raw.trim();
|
|
338
|
+
if (!t || t.startsWith("#")) continue;
|
|
339
|
+
const m = t.match(/^([\w.-]+)\s*=\s*(.*)$/);
|
|
340
|
+
if (!m) { errors.push(`"${t}" is not key=value`); continue; }
|
|
341
|
+
const [, key, value] = m;
|
|
342
|
+
if (!(key in ANSWER_STAGE) && !/^check\.[\w-]+$/.test(key)) { errors.push(`unknown answer key "${key}" — known: ${ANSWER_KEYS.join(", ")}`); continue; }
|
|
343
|
+
answers.push([key, value.trim()]);
|
|
344
|
+
}
|
|
345
|
+
return { answers, errors };
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** Apply setup answers onto a playbook text — each a single targeted insert/replace, so hand-written lines
|
|
349
|
+
* survive. The section a key is already written under wins (a versionFile under ## release stays there). */
|
|
350
|
+
export function applyAnswers(text: string, answers: [string, string][]): { text: string; changes: string[] } {
|
|
351
|
+
let cur = text;
|
|
352
|
+
const changes: string[] = [];
|
|
353
|
+
for (const [key, value] of answers) {
|
|
354
|
+
if (key.startsWith("check.")) {
|
|
355
|
+
const r = setPlaybookCheck(cur, key.slice("check.".length), value);
|
|
356
|
+
cur = r.text;
|
|
357
|
+
changes.push(`${key} → ${r.where}`);
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
let stage = ANSWER_STAGE[key];
|
|
361
|
+
const parsed = parseProjectMd(cur);
|
|
362
|
+
const holder = MD_STAGES.find((s) => Object.keys(parsed.flow[s]).some((dot) => KEYMAP[s]?.[key] === dot));
|
|
363
|
+
if (holder && holder !== stage && (stage === "pre-release" || stage === "release") && (holder === "pre-release" || holder === "release")) stage = holder;
|
|
364
|
+
const r = setPlaybookKey(cur, stage, key, value);
|
|
365
|
+
if ("error" in r) { changes.push(`${key}: ${r.error}`); continue; }
|
|
366
|
+
cur = r.text;
|
|
367
|
+
// the draft's "not decided yet" hint for this key is now wrong: drop it (and the blank line after it)
|
|
368
|
+
const hint = DRAFT_HINTS[key];
|
|
369
|
+
if (hint) cur = cur.replace(new RegExp(`^${hint.source}.*\\n\\n?`, "m"), "");
|
|
370
|
+
changes.push(`${key} = ${value} → ${r.where}`);
|
|
371
|
+
}
|
|
372
|
+
return { text: cur, changes };
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** Minimal line diff (LCS) for showing the operator what a write changes — playbooks are small. */
|
|
376
|
+
export function lineDiff(before: string, after: string, context = 1): string {
|
|
377
|
+
const a = before.split("\n");
|
|
378
|
+
const b = after.split("\n");
|
|
379
|
+
const n = a.length;
|
|
380
|
+
const m = b.length;
|
|
381
|
+
const dp: number[][] = Array.from({ length: n + 1 }, () => new Array<number>(m + 1).fill(0));
|
|
382
|
+
for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
|
|
383
|
+
const ops: { t: " " | "-" | "+"; l: string }[] = [];
|
|
384
|
+
let i = 0;
|
|
385
|
+
let j = 0;
|
|
386
|
+
while (i < n || j < m) {
|
|
387
|
+
if (i < n && j < m && a[i] === b[j]) { ops.push({ t: " ", l: a[i] }); i++; j++; }
|
|
388
|
+
else if (i < n && (j >= m || dp[i + 1][j] >= dp[i][j + 1])) ops.push({ t: "-", l: a[i++] });
|
|
389
|
+
else ops.push({ t: "+", l: b[j++] });
|
|
390
|
+
}
|
|
391
|
+
const keep = ops.map((o, k) => o.t !== " " || ops.slice(Math.max(0, k - context), k + context + 1).some((x) => x.t !== " "));
|
|
392
|
+
const out: string[] = [];
|
|
393
|
+
let gap = false;
|
|
394
|
+
ops.forEach((o, k) => {
|
|
395
|
+
if (keep[k]) { out.push(`${o.t} ${o.l}`); gap = false; }
|
|
396
|
+
else if (!gap) { out.push(" …"); gap = true; }
|
|
397
|
+
});
|
|
398
|
+
return ops.some((o) => o.t !== " ") ? out.join("\n") : "(no changes)";
|
|
399
|
+
}
|
|
400
|
+
|
|
286
401
|
/** Load the project config: project.md is the only source. */
|
|
287
402
|
export function loadProject(dfDir: string): { cfg: Config; md: ParsedMd | null } {
|
|
288
403
|
const mdFile = path.join(dfDir, "project.md");
|
|
@@ -382,11 +497,16 @@ export function mdDigest(text: string): string {
|
|
|
382
497
|
bits.push(DIGEST_CMDS[k] ? `${DIGEST_CMDS[k]}: ${JSON.stringify(v)}` : `${DIGEST_WORDS[k] ?? k}: ${v}`);
|
|
383
498
|
}
|
|
384
499
|
if (s === "implement" && p.checks.length) bits.push(`named checks: ${p.checks.map((c) => c.name).join(", ")}`);
|
|
500
|
+
if (s === "global") {
|
|
501
|
+
const rules = (["deny", "confirm", "protect", "forbid"] as const).flatMap((v) => p.guard[v].map((r) => `${v} ${r.pattern}`));
|
|
502
|
+
if (rules.length) bits.push(`safety rules: ${rules.join(" · ")}`);
|
|
503
|
+
}
|
|
385
504
|
if (relStage && keys.file) {
|
|
386
505
|
bits.push(`version in ${keys.file} → tag ${keys.pattern ?? "v{version}"}`);
|
|
387
506
|
bits.push(keys.releases === "false" || keys.releases === "no" ? "forge release: off" : "forge release: created automatically (gh/glab)");
|
|
388
507
|
bits.push(`artifact check: ${keys.artifact ?? "none set"}`);
|
|
389
508
|
}
|
|
509
|
+
if (s === "pre-release" && !keys.file && !p.flow.release["versioning.file"]) bits.push("version: no version file set — releases cannot bump or tag");
|
|
390
510
|
const items = p.checklist[s] ?? [];
|
|
391
511
|
if (items.length) bits.push(`manual check: ${items.map((i) => `${i.uiOnly ? "(UI only) " : ""}\"${i.text}\"`).join(" · ")}`);
|
|
392
512
|
if (p.prose[s]) bits.push(`guidance: "${p.prose[s].replace(/\s+/g, " ").trim()}"`);
|
|
@@ -397,23 +517,37 @@ export function mdDigest(text: string): string {
|
|
|
397
517
|
|
|
398
518
|
/** Draft project.md from detection (first init, --force). Never a regeneration of an existing playbook:
|
|
399
519
|
* a draft cannot reproduce hand-written prose, checklist items and keys. */
|
|
400
|
-
export function buildDraft(det: {
|
|
520
|
+
export function buildDraft(det: {
|
|
521
|
+
report: string[];
|
|
522
|
+
partial: { defaultBranch: string; commands: Record<string, string>; versioning?: { file: string }; forge?: string; versionTag?: string; changelog?: string; checks?: Record<string, string>; guards?: string[] };
|
|
523
|
+
}): string {
|
|
401
524
|
const cmd = (k: string) => det.partial.commands[k];
|
|
402
525
|
const L: string[] = [];
|
|
403
526
|
L.push("# dev-flow", "", "<!-- Operator-owned playbook. Regenerate with: flow init --draft -->", "");
|
|
404
527
|
L.push("## global", "", "```flow", `defaultBranch = ${det.partial.defaultBranch}`);
|
|
405
528
|
if (det.partial.forge) L.push(`forge = ${det.partial.forge}`); // from the origin URL — confirm or correct
|
|
406
529
|
L.push("```", "");
|
|
530
|
+
// only secrets that exist on disk: a guard on a path the repo does not have guards nothing and reads as noise
|
|
531
|
+
if (det.partial.guards?.length) L.push("```flow-guard", ...det.partial.guards, "```", "");
|
|
407
532
|
L.push("## plan", "", "- [ ] (ui) rendered mockups attached for every changed screen", "", "<!-- what the plan must contain, UI expectations -->", "");
|
|
408
533
|
L.push("## implement", "", "```flow");
|
|
409
534
|
for (const k of ["setup", "test", "build", "run", "seedData", "dev"]) if (cmd(k)) L.push(`${k} = ${cmd(k)}`);
|
|
410
535
|
L.push("```", "");
|
|
536
|
+
for (const [name, c] of Object.entries(det.partial.checks ?? {})) L.push("```flow-check " + name, c, "```", "");
|
|
411
537
|
// never invent a health check: a placeholder that can't pass blocks verify forever (dogfooded: curl localhost:3000 in a library repo)
|
|
412
538
|
if (cmd("health")) L.push("```flow-check health", cmd("health"), "```", "");
|
|
413
539
|
else L.push("<!-- optional tier-1: add a flow-check 'health' block once the app exposes a health endpoint -->", "");
|
|
414
|
-
|
|
415
|
-
L.push("
|
|
416
|
-
|
|
540
|
+
// (ui): a library or CLI has no screen to give a visual pass — the item would ask on every feature
|
|
541
|
+
L.push("- [ ] (ui) app runs locally with real data; visual pass: no overflows or stray scrollbars", "", "<!-- tier-3: standing guidance for this stage -->", "");
|
|
542
|
+
L.push("## pre-release", "", "<!-- e.g. review policy, docs expectations, who picks the version -->", "");
|
|
543
|
+
// never invent a manifest either: a versionFile naming a file the repo lacks is a doctor finding on day one
|
|
544
|
+
const rel: string[] = [];
|
|
545
|
+
if (det.partial.versioning?.file) rel.push(`versionFile = ${det.partial.versioning.file}`, `versionTag = ${det.partial.versionTag ?? "v{version}"}`);
|
|
546
|
+
if (det.partial.changelog) rel.push(`changelog = ${det.partial.changelog}`);
|
|
547
|
+
if (rel.length) L.push("```flow", ...rel, "```", "");
|
|
548
|
+
if (!det.partial.versioning?.file) L.push("<!-- versionFile = <the file that holds the version> — none was detected; flow init asks -->", "");
|
|
549
|
+
if (det.partial.changelog === "") L.push("<!-- no changelog found: create CHANGELOG.md, or set changelog = (empty) to opt out -->", "");
|
|
550
|
+
// the merge policy is never invented by detection: flow init / flow start ask and write it
|
|
417
551
|
L.push("## release", "", "<!-- merge = squash | merge | rebase — how a merged PR lands on the default branch (`any` = no policy). flow start also asks and writes it. -->", "");
|
|
418
552
|
L.push("<!-- e.g. tag policy, who publishes artifacts -->", "");
|
|
419
553
|
return L.join("\n") + "\n";
|