pi-dev-flow 0.77.3 → 0.78.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 +25 -0
- package/README.md +6 -3
- package/docs/playbook.md +51 -9
- package/extensions/dev-flow.ts +170 -42
- package/package.json +1 -1
- package/skills/dev-flow/references/start.md +13 -13
- package/src/detect.ts +219 -18
- package/src/projectmd.ts +138 -4
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,31 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
|
|
|
4
4
|
|
|
5
5
|
## [Unreleased]
|
|
6
6
|
|
|
7
|
+
## [0.78.0] - 2026-11-03
|
|
8
|
+
|
|
9
|
+
**`flow init` asks better questions and writes your answers itself.**
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
- 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.
|
|
13
|
+
- The draft no longer invents `versionFile = package.json` when no version file exists (doctor flagged it on day one).
|
|
14
|
+
- The "app runs locally; visual pass" checklist item is now `(ui)`-only, so libraries and CLIs aren't asked about screens.
|
|
15
|
+
- With a UI, the draft dialog no longer appears before the setup questions are shown.
|
|
16
|
+
- 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.
|
|
17
|
+
|
|
18
|
+
### Added
|
|
19
|
+
- `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.
|
|
20
|
+
- Setup questions carry `detected:` / `accept:` / `why:` lines. The interactive first init accepts every detected value in one dialog, then offers the commit.
|
|
21
|
+
- Detection reads:
|
|
22
|
+
- lint/typecheck/format scripts (and clippy, `go vet`, ruff/mypy) → `flow-check` blocks
|
|
23
|
+
- Makefile/justfile/Taskfile targets
|
|
24
|
+
- CI workflow commands and publish steps → a suggested `artifact` check
|
|
25
|
+
- Dockerfile/compose → suggested `preflight`/`dev`
|
|
26
|
+
- `.env`/`secrets/` on disk → drafted `protect`/`forbid` guard rules
|
|
27
|
+
- existing tags → `versionTag`
|
|
28
|
+
- the changelog file, monorepo workspaces, and CLAUDE.md/AGENTS.md/CONTRIBUTING.md
|
|
29
|
+
- The summary shown in the init dialog lists safety rules, and says when no version file is set.
|
|
30
|
+
- `docs/playbook.md` opens with a Quickstart and four typical playbooks.
|
|
31
|
+
|
|
7
32
|
## [0.77.3] - 2026-11-03
|
|
8
33
|
|
|
9
34
|
### 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/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
|
@@ -138,10 +138,10 @@ import {
|
|
|
138
138
|
type PushRef,
|
|
139
139
|
type SessionClaim,
|
|
140
140
|
} from "../src/core.ts";
|
|
141
|
-
import { buildDraft, doctorFindings, ghostFeatureDirs, loadProject, mdDigest, parseProjectMd, setPlaybookKey } from "../src/projectmd.ts";
|
|
141
|
+
import { applyAnswers, buildDraft, doctorFindings, ghostFeatureDirs, lineDiff, loadProject, mdDigest, parseAnswers, parseProjectMd, setPlaybookKey } from "../src/projectmd.ts";
|
|
142
142
|
import { dedupeReflections, linkedTag, parseGhIssues, similarNote, type FoldResult, type GhIssue } from "../src/fold.ts";
|
|
143
143
|
import { bashTimeout, requireTimeout } from "../src/timeouts.ts";
|
|
144
|
-
import { detectProject } from "../src/detect.ts";
|
|
144
|
+
import { detectProject, type Detection } from "../src/detect.ts";
|
|
145
145
|
|
|
146
146
|
const execAsync = promisify(exec);
|
|
147
147
|
|
|
@@ -367,7 +367,7 @@ async function releaseTags(root: string): Promise<string[] | null> {
|
|
|
367
367
|
}
|
|
368
368
|
|
|
369
369
|
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)";
|
|
370
|
+
"help [--json] | init [--force|--draft|--write <text>|--write-file <path>|--answers key=value…|--answers-file <path>] [--confirmed] [--track] | reflect [<note>|list|tidy|move <n> --playbook|--code] | roadmap [add <text>|pick <n> <slug>|done <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui|--patch|--docs --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | approve [--yolo] | verify [--yolo] | release [--yolo|--no-version|--no-fold-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [slug] | abort [slug] | version [--check-upstream] — state gates take [slug] and --confirmed (the operator already answered in chat); without it they ask in a dialog, or refuse with NEEDS-OPERATOR when no UI is present — --ui/--patch/--docs and --merge=<style> on start are operator-granted (--confirmed); start refuses until the playbook has a merge policy and writes the answer into project.md — --yolo (with --confirmed) answers that checkpoint and pre-confirms every later one; checks and guardrails stay — release --no-version ships merge + changelog only (no bump, tag or forge release); --no-fold-check skips the changelog fold line proofs on the operator's word — release names a session running an older dev-flow build than the disk ships and asks update (/reload) or proceed — recorded, never a block — reflect <note> queues a project suggestion in reflections.md (--playbook = docs-flow fix, --code = patch-flow fix); --plugin never writes — dev-flow feedback goes upstream and it prints the GitHub issue recipe; bare reflect prints the session-reflection protocol (bound: run flow_stage op reflect); list numbers open items, move <n> re-files one, tidy drops closed ones — roadmap manages .dev-flow/roadmap.md: pick <n> <slug> stamps an item for flow start, finish checks it off — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — version prints the build the disk ships and any other dev-flow copies in this process (--check-upstream asks the registry)";
|
|
371
371
|
const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
|
|
372
372
|
const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
|
|
373
373
|
const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
|
|
@@ -736,20 +736,74 @@ function isSelfRepo(root: string): boolean {
|
|
|
736
736
|
}
|
|
737
737
|
}
|
|
738
738
|
|
|
739
|
-
/**
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
739
|
+
/** Which tag convention the repo already uses — read off its newest tags, like the merge style is read off
|
|
740
|
+
* its history. null = no version-like tags yet (the v{version} default stands, and is asked about). */
|
|
741
|
+
async function tagPatternEvidence(root: string): Promise<{ pattern: string; note: string } | null> {
|
|
742
|
+
const r = await sh("git tag --list --sort=-creatordate", root, 10_000);
|
|
743
|
+
if (!r.ok) return null;
|
|
744
|
+
const tags = r.out.split("\n").map((t) => t.trim()).filter((t) => /\d+\.\d+\.\d+/.test(t)).slice(0, 20);
|
|
745
|
+
if (!tags.length) return null;
|
|
746
|
+
const prefix = (t: string) => t.slice(0, t.search(/\d+\.\d+\.\d+/));
|
|
747
|
+
const counts = new Map<string, number>();
|
|
748
|
+
for (const t of tags) counts.set(prefix(t), (counts.get(prefix(t)) ?? 0) + 1);
|
|
749
|
+
const [top] = [...counts.entries()].sort((x, y) => y[1] - x[1]);
|
|
750
|
+
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(", ")})` : ""}` };
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
/** One setup question: what to ask, what detection found, why it matters, and the answer that accepts it. */
|
|
754
|
+
export interface SetupQuestion {
|
|
755
|
+
key: string;
|
|
756
|
+
ask: string;
|
|
757
|
+
detected?: string;
|
|
758
|
+
/** `flow init --answers` token(s) that accept the detected/suggested value */
|
|
759
|
+
accept?: string;
|
|
760
|
+
why: string;
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
/** The questions `flow init` asks before writing a playbook — detection fills what it can, the operator
|
|
764
|
+
* answers the rest (the agent relays them). Every question says why it matters and what skipping costs,
|
|
765
|
+
* so it is answerable without reading docs/playbook.md first. */
|
|
766
|
+
function setupQuestions(det: Detection, ev: { merge?: { note: string; recent: string | null } | null; tag?: { pattern: string; note: string } | null }): SetupQuestion[] {
|
|
767
|
+
const sug = (k: string) => det.suggestions.filter((x) => x.key === k);
|
|
768
|
+
const q: SetupQuestion[] = [];
|
|
769
|
+
const forge = det.partial.forge;
|
|
770
|
+
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" });
|
|
771
|
+
const vf = det.partial.versioning?.file;
|
|
772
|
+
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)" });
|
|
773
|
+
const tag = ev.tag?.pattern ?? "v{version}";
|
|
774
|
+
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" });
|
|
775
|
+
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" });
|
|
776
|
+
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" });
|
|
777
|
+
const art = sug("artifact");
|
|
778
|
+
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" });
|
|
779
|
+
const pre = sug("preflight");
|
|
780
|
+
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" });
|
|
781
|
+
const checks = det.partial.checks ?? {};
|
|
782
|
+
q.push({
|
|
783
|
+
key: "check.<name>",
|
|
784
|
+
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)?`,
|
|
785
|
+
detected: Object.entries(det.partial.commands).filter(([k]) => k !== "setup").map(([k, v]) => `${k}: ${v}`).join(" · ") || undefined,
|
|
786
|
+
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)",
|
|
787
|
+
});
|
|
788
|
+
const dev = sug("dev");
|
|
789
|
+
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" });
|
|
790
|
+
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" });
|
|
791
|
+
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)" });
|
|
792
|
+
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
793
|
return q;
|
|
751
794
|
}
|
|
752
795
|
|
|
796
|
+
function renderQuestions(qs: SetupQuestion[]): string[] {
|
|
797
|
+
const out: string[] = [];
|
|
798
|
+
qs.forEach((x, i) => {
|
|
799
|
+
out.push(` ${i + 1}. [${x.key}] ${x.ask}`);
|
|
800
|
+
if (x.detected) out.push(` detected: ${x.detected}`);
|
|
801
|
+
if (x.accept) out.push(` accept: ${x.accept}`);
|
|
802
|
+
out.push(` why: ${x.why}`);
|
|
803
|
+
});
|
|
804
|
+
return out;
|
|
805
|
+
}
|
|
806
|
+
|
|
753
807
|
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
808
|
|
|
755
809
|
/** The dev-flow repo plugin notes are filed against: the manifest's repository field; the dev-flow
|
|
@@ -1472,6 +1526,19 @@ async function gateFinish(o: GateCtx): Promise<RunResult> {
|
|
|
1472
1526
|
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
1527
|
}
|
|
1474
1528
|
|
|
1529
|
+
/** The main-branch guard as a hook body — installed into .git/hooks, or printed for a hook manager to carry. */
|
|
1530
|
+
const mainHookBody = (branch: string) =>
|
|
1531
|
+
`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`;
|
|
1532
|
+
|
|
1533
|
+
/** Value tokens of a multi-value flag: everything after `--name` up to the next `--flag`. */
|
|
1534
|
+
function flagValues(rest: string[], name: string): string[] {
|
|
1535
|
+
const i = rest.indexOf(`--${name}`);
|
|
1536
|
+
if (i === -1) return [];
|
|
1537
|
+
const out: string[] = [];
|
|
1538
|
+
for (let j = i + 1; j < rest.length && !rest[j].startsWith("--"); j++) out.push(rest[j]);
|
|
1539
|
+
return out;
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1475
1542
|
async function gateInit(o: GateCtx): Promise<RunResult> {
|
|
1476
1543
|
const { root, ui, rest, flag } = o;
|
|
1477
1544
|
// a recursive mkdir is silent about whether it created anything, and `flow init --write` is the
|
|
@@ -1490,8 +1557,15 @@ async function gateInit(o: GateCtx): Promise<RunResult> {
|
|
|
1490
1557
|
const det = detectProject(root, branch);
|
|
1491
1558
|
const origin = await originUrl(root);
|
|
1492
1559
|
det.partial.forge = origin ? detectForge(origin) : undefined; // confirmed or corrected by the operator during setup; absent = no origin to detect from
|
|
1493
|
-
|
|
1560
|
+
const mergeEv = await mergeHistoryEvidence(root, branch); // "what do you actually do when a PR merges", read off the log
|
|
1561
|
+
det.partial.merge = mergeEv?.note;
|
|
1562
|
+
const tagEv = await tagPatternEvidence(root);
|
|
1563
|
+
if (tagEv) {
|
|
1564
|
+
det.partial.versionTag = tagEv.pattern;
|
|
1565
|
+
det.report.push(`tags: ${tagEv.note} → versionTag = ${tagEv.pattern}`);
|
|
1566
|
+
}
|
|
1494
1567
|
const draftFresh = buildDraft(det);
|
|
1568
|
+
const questions = setupQuestions(det, { merge: mergeEv, tag: tagEv });
|
|
1495
1569
|
if (flag("draft")) return { text: existsSync(mdFile) ? readFileSync(mdFile, "utf8") : draftFresh }; // read path: prints content, writes nothing (and offers no deletions)
|
|
1496
1570
|
// ghosts: feature dirs whose state.json is gone — inert, invisible to status and guards, and only findable by eye
|
|
1497
1571
|
const ghosts = ghostFeatureDirs(root);
|
|
@@ -1502,6 +1576,7 @@ async function gateInit(o: GateCtx): Promise<RunResult> {
|
|
|
1502
1576
|
notes.push(`removed ${ghosts.length} ghost feature dir(s): ${ghosts.map((g) => g.slice(".dev-flow/".length)).join(", ")}`);
|
|
1503
1577
|
} else notes.push(`kept ${ghosts.length} ghost feature dir(s) — inert, remove them whenever you like`);
|
|
1504
1578
|
}
|
|
1579
|
+
const current = existsSync(mdFile) ? readFileSync(mdFile, "utf8") : null;
|
|
1505
1580
|
/** Validate, back up what was there (the operator's rules are not regenerable), write. */
|
|
1506
1581
|
const writeMd = (text: string): { rej: RunResult } | { warn: string[] } => {
|
|
1507
1582
|
const parsed = parseProjectMd(text);
|
|
@@ -1510,34 +1585,82 @@ async function gateInit(o: GateCtx): Promise<RunResult> {
|
|
|
1510
1585
|
writeFileSync(mdFile, text.endsWith("\n") ? text : `${text}\n`);
|
|
1511
1586
|
return { warn: parsed.warn };
|
|
1512
1587
|
};
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1588
|
+
/** After a write: the playbook belongs in git — commit it on the operator's word, else say how. */
|
|
1589
|
+
const afterWrite = async (w: { warn: string[] }, before: string | null, after: string, offer = false): Promise<void> => {
|
|
1590
|
+
notes.push(`changes:\n${lineDiff(before ?? "", after)}`);
|
|
1591
|
+
if (w.warn.length) notes.push("warnings:", ...w.warn.map((x) => ` ${x}`));
|
|
1592
|
+
// the dialog belongs to the human-driven first init only: an agent write (--write/--answers) follows a chat
|
|
1593
|
+
// confirmation and must not open a second question — it commits on --track
|
|
1594
|
+
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)?")));
|
|
1595
|
+
if (!track) {
|
|
1596
|
+
notes.push(GIT_TRACK_NOTE, "(or re-run the same call with --track on the operator's word)");
|
|
1597
|
+
return;
|
|
1598
|
+
}
|
|
1599
|
+
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);
|
|
1600
|
+
notes.push(c.ok ? "project.md committed (git add -f + playbook chore)" : `commit failed — ${c.out.split("\n").find(Boolean) ?? "?"}; ${GIT_TRACK_NOTE}`);
|
|
1601
|
+
};
|
|
1602
|
+
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 ?? ""}>`]; })() : [])];
|
|
1603
|
+
if (flag("answers") || flag("answers-file")) {
|
|
1604
|
+
// the operator's answers, applied as targeted edits onto the draft (first init) or the current file —
|
|
1605
|
+
// hand-written lines survive; the result is previewed until the operator's word anchors the write
|
|
1606
|
+
const parsed = parseAnswers(answerToks);
|
|
1607
|
+
if (parsed.errors.length) return { text: `answers REJECTED:\n- ${parsed.errors.join("\n- ")}`, isError: true };
|
|
1608
|
+
if (!parsed.answers.length) return { text: "usage: flow init --answers key=value [key=value …] | --answers-file <path> (one key=value per line)", isError: true };
|
|
1609
|
+
const base = current ?? draftFresh;
|
|
1610
|
+
const applied = applyAnswers(base, parsed.answers);
|
|
1611
|
+
const lint = parseProjectMd(applied.text);
|
|
1612
|
+
if (lint.hard.length) return { text: `project.md REJECTED:\n- ${lint.hard.join("\n- ")}`, isError: true };
|
|
1613
|
+
const preview = [`${current ? "playbook" : "draft"} with ${parsed.answers.length} answer(s):`, ...applied.changes.map((c) => ` ${c}`), "", mdDigest(applied.text)];
|
|
1614
|
+
const ok = flag("confirmed") || (ui.hasUI && (await ui.confirm("Write project.md?", preview.join("\n"))));
|
|
1615
|
+
if (!ok) {
|
|
1616
|
+
const open = questions.filter((x) => !parsed.answers.some(([k]) => k === x.key || (x.key === "check.<name>" && (k.startsWith("check.") || ["test", "build", "run"].includes(k)))));
|
|
1617
|
+
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") };
|
|
1618
|
+
}
|
|
1619
|
+
const w = writeMd(applied.text);
|
|
1620
|
+
if ("rej" in w) return w.rej;
|
|
1621
|
+
notes.push(`project.md written with ${parsed.answers.length} answer(s)`);
|
|
1622
|
+
await afterWrite(w, current, applied.text);
|
|
1623
|
+
} else if (flag("write") || flag("write-file")) {
|
|
1624
|
+
let content: string | undefined;
|
|
1625
|
+
if (flag("write-file")) {
|
|
1626
|
+
const f = flagValues(rest, "write-file")[0];
|
|
1627
|
+
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 };
|
|
1628
|
+
content = readFileSync(path.resolve(root, f), "utf8");
|
|
1629
|
+
} else {
|
|
1630
|
+
content = rest[rest.indexOf("--write") + 1];
|
|
1631
|
+
if (!content || content.startsWith("--")) return { text: 'usage: flow init --write "<full project.md content>" (or --write-file <path>)', isError: true };
|
|
1632
|
+
}
|
|
1516
1633
|
const w = writeMd(content);
|
|
1517
1634
|
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.
|
|
1635
|
+
notes.push("project.md written (operator-owned playbook)");
|
|
1636
|
+
await afterWrite(w, current, content);
|
|
1637
|
+
} else if (!current) {
|
|
1638
|
+
// first init: never write silently. The questions come first — a dialog that offered the bare detection
|
|
1639
|
+
// draft before them wrote a playbook with the merge style, forge and versioning still unanswered.
|
|
1524
1640
|
const brief = [
|
|
1525
1641
|
"setup — project.md not written yet; nothing is drafted to disk until the operator confirms.",
|
|
1642
|
+
"detected:",
|
|
1526
1643
|
...det.report.map((r) => ` ${r}`),
|
|
1527
|
-
"questions for the operator (
|
|
1528
|
-
...
|
|
1529
|
-
"agent: ask these in chat
|
|
1530
|
-
GIT_TRACK_NOTE,
|
|
1644
|
+
"questions for the operator (detected value shown; `accept` is the answer that keeps it):",
|
|
1645
|
+
...renderQuestions(questions),
|
|
1646
|
+
"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
1647
|
];
|
|
1648
|
+
let wrote = false;
|
|
1532
1649
|
if (ui.hasUI) {
|
|
1533
|
-
const
|
|
1650
|
+
const accepts = questions.filter((x) => x.accept).map((x) => x.accept!);
|
|
1651
|
+
const withAccepts = applyAnswers(draftFresh, parseAnswers(accepts).answers).text;
|
|
1652
|
+
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
1653
|
if (ok) {
|
|
1535
|
-
const w = writeMd(
|
|
1654
|
+
const w = writeMd(withAccepts);
|
|
1536
1655
|
if ("rej" in w) return w.rej;
|
|
1537
|
-
|
|
1538
|
-
|
|
1656
|
+
wrote = true;
|
|
1657
|
+
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}`));
|
|
1658
|
+
const open = questions.filter((x) => !x.accept);
|
|
1659
|
+
if (open.length) notes.push("still open (answer any time):", ...renderQuestions(open));
|
|
1660
|
+
await afterWrite(w, null, withAccepts, true);
|
|
1661
|
+
}
|
|
1539
1662
|
}
|
|
1540
|
-
notes.push(...brief);
|
|
1663
|
+
if (!wrote) notes.push(...brief);
|
|
1541
1664
|
} else if (flag("force")) {
|
|
1542
1665
|
// a destructive reset of the operator's own file needs their word: --confirmed for an agent, one dialog for a human
|
|
1543
1666
|
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 +1673,26 @@ async function gateInit(o: GateCtx): Promise<RunResult> {
|
|
|
1550
1673
|
// a draft cannot reproduce hand-written prose, items and keys. Edit the file, or flow init --write.
|
|
1551
1674
|
const loaded = loadProject(dfDir(root));
|
|
1552
1675
|
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}`));
|
|
1676
|
+
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
1677
|
}
|
|
1555
1678
|
const initCfg = loadProject(dfDir(root)).cfg;
|
|
1556
1679
|
if (initCfg.mainHook) {
|
|
1680
|
+
// a hook manager (husky, lefthook…) points core.hooksPath elsewhere: git never runs .git/hooks then,
|
|
1681
|
+
// so a hook installed there would guard nothing — print the lines for the manager's own hook instead
|
|
1682
|
+
const hp = await sh("git config --get core.hooksPath", root, 10_000);
|
|
1683
|
+
const hooksPath = hp.ok ? hp.out.trim() : ""; // unset exits 1, and sh() then carries the error text
|
|
1557
1684
|
const hookDir = path.join(root, ".git", "hooks");
|
|
1558
1685
|
const hook = path.join(hookDir, "pre-commit");
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1686
|
+
const body = mainHookBody(initCfg.defaultBranch);
|
|
1687
|
+
if (hooksPath && path.resolve(root, hooksPath) !== hookDir) {
|
|
1688
|
+
const theirs = path.join(hooksPath, "pre-commit");
|
|
1689
|
+
const has = existsSync(path.resolve(root, theirs)) && readFileSync(path.resolve(root, theirs), "utf8").includes("DEV_FLOW_ALLOW_MAIN");
|
|
1690
|
+
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}`);
|
|
1691
|
+
} else if (existsSync(hookDir) && !existsSync(hook)) {
|
|
1692
|
+
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
1693
|
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(
|
|
1694
|
+
} else if (existsSync(hook) && !readFileSync(hook, "utf8").includes("installed by dev-flow") && !readFileSync(hook, "utf8").includes("DEV_FLOW_ALLOW_MAIN")) {
|
|
1695
|
+
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
1696
|
}
|
|
1569
1697
|
}
|
|
1570
1698
|
return { text: notes.join("\n") };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-dev-flow",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.78.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": [
|
|
@@ -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/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";
|