pi-dev-flow 0.88.0 → 0.90.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/src/core.ts CHANGED
@@ -48,6 +48,8 @@ export interface FlowState {
48
48
  staleBuild?: string; // release ran under an older dev-flow than the checkout by operator choice ("<loaded> (checkout <disk>)"); release-done repeats the acknowledgement
49
49
  pendingAsk?: string; // the checkpoint word a gate asked for and has not been given ("Approve?", "Verified?", …) — presentation only (💬 in the footer), it never gates
50
50
  releaseOnly?: boolean; // verify found nothing on the branch but unreleased work on main: this flow only cuts the version (#161)
51
+ versionChoice?: string; // the operator's release call, recorded with Verified? (gh#198): patch | minor | major (counted from the newest tag at release, so a parallel flow taking the number moves it), an exact version, "next" (playbook version = versioned: any bump past the last tag) or "unreleased"
52
+ versionFrom?: string; // the manifest version when the call was recorded — what a patch/minor/major call was counted from at Verified?
51
53
  verifiedHead?: string; // HEAD the operator's Verified? was given over — release names commits after it, so the word is not recorded as the verdict for a tree nobody looked at (#162)
52
54
  reflectedAt?: string; // a reflect worker reported for this flow — finish runs one first while this is unset (only --no-reflect --confirmed skips it)
53
55
  devPort?: number; // the port the operator chose for this flow's dev deploy when the default was held by another flow — finish stops it (devDown)
@@ -56,11 +58,13 @@ export interface FlowState {
56
58
  }
57
59
 
58
60
  /** Tier-2 item: operator prose; uiOnly items ("(ui)" in project.md) apply only to --ui features;
59
- * versionedOnly items ("(versioned)") presuppose a bump/tag and stand down on a --no-version flow (#166). */
61
+ * versionedOnly items ("(versioned)") presuppose a bump/tag and stand down on a --no-version flow (#166);
62
+ * docs items ("(docs)") keep an implement item on a --docs flow, where implement items otherwise stand down (gh#207). */
60
63
  export interface ChecklistItem {
61
64
  text: string;
62
65
  uiOnly: boolean;
63
66
  versionedOnly?: boolean;
67
+ docs?: boolean;
64
68
  }
65
69
 
66
70
  export interface Commands {
@@ -119,13 +123,16 @@ export interface Config {
119
123
  /** Bytes one dev instance needs (playbook `instanceMem` / `instanceDisk`, e.g. 2G) — the side-by-side feasibility check. */
120
124
  instanceMem?: number;
121
125
  instanceDisk?: number;
122
- release: { review: string; changelog?: string; releases?: boolean; artifact?: string; preflight?: string; merge?: MergeStyle | "any"; /** `until-release`: a standing yolo never answers Release? (gh#176) */ yolo?: "all" | "until-release"; /** `always`: finish runs the closing reflection even on a flow with no friction */ reflect?: "always" | "on-friction" };
126
+ release: { review: string; changelog?: string; releases?: boolean; artifact?: string; preflight?: string; merge?: MergeStyle | "any"; /** `until-release`: a standing yolo never answers Release? (gh#176) */ yolo?: "all" | "until-release"; /** `always`: finish runs the closing reflection even on a flow with no friction */ reflect?: "always" | "on-friction"; /** who decides versioned vs unreleased: asked with Verified? (`ask`, default) or fixed by the playbook (gh#198) */ version?: "ask" | "versioned" | "unversioned"; /** `on-change` (default): Release? answers itself when nothing but release prep changed since Verified? and the version choice is on record; `always` asks it every time (gh#198) */ ask?: "always" | "on-change" };
123
127
  mainHook: boolean; // flow init installs a pre-commit hook blocking main commits
124
128
  /** `inject` (default): the class default timeout is armed silently on every shell call.
125
129
  * `require`: a shell call without its own visible timeout is refused (costs a turn per miss). */
126
130
  bashTimeout: "require" | "inject";
127
131
  /** Operator safety rules from the project.md flow-guard block — stage-independent. */
128
132
  guard: GuardRules;
133
+ /** Lines from the ## global `flow-worker` block: every flow_stage brief carries them, so a worker can run the
134
+ * project's checks (e.g. an export of a test password read from a gitignored file) — gh#201. */
135
+ workerPreamble?: string[];
129
136
  }
130
137
 
131
138
  export const DEFAULTS: Config = {
@@ -382,8 +389,8 @@ export function verifyGate(state: FlowState, cfg: Config, branch?: BranchState |
382
389
  : "nothing committed on the feature branch yet — commit as you go, verify proves a committed state",
383
390
  );
384
391
  if (!state.docs) for (const c of cfg.checkList) if (!state.checks[c.name]?.ok) errs.push(`check "${c.name}" has not passed — run flow check`);
385
- const pend = checklistPending(cfg, state, "implement");
386
- if (pend) errs.push(`tier-2 checklist not confirmed (${pend} item(s)) — run flow verify after ticking them off`);
392
+ const pend = openItemsNote(cfg, state, "implement");
393
+ if (pend) errs.push(`tier-2 checklist not confirmed — ${pend}; confirm them with the operator, then run flow verify`);
387
394
  return errs;
388
395
  }
389
396
 
@@ -497,6 +504,49 @@ export function pickReleaseNotes(src: { changelog: string | null; version: strin
497
504
  return { notes: "", source: "none" };
498
505
  }
499
506
 
507
+ /** gh#198 — the operator's release call: a bump kind (`patch|minor|major`, turned into a number at release from
508
+ * the newest tag), an exact version (`1.2.0`, a pre-release suffix allowed), `next` (the playbook says
509
+ * versioned: any bump past the last tag) or `unreleased` (merge + changelog only). */
510
+ export const VERSION_ARG_RE = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
511
+ export type BumpKind = "patch" | "minor" | "major";
512
+ export const isBumpKind = (c: string | null | undefined): c is BumpKind => c === "patch" || c === "minor" || c === "major";
513
+
514
+ /** `from` bumped by one `kind` step (a pre-release suffix is dropped), or null when `from` is not x.y.z. */
515
+ export function bumpVersion(from: string | null | undefined, kind: BumpKind): string | null {
516
+ const m = from?.match(/^(\d+)\.(\d+)\.(\d+)/);
517
+ if (!m) return null;
518
+ const [maj, min, pat] = [Number(m[1]), Number(m[2]), Number(m[3])];
519
+ return kind === "major" ? `${maj + 1}.0.0` : kind === "minor" ? `${maj}.${min + 1}.0` : `${maj}.${min}.${pat + 1}`;
520
+ }
521
+
522
+ /** The call a playbook makes for every flow (`release.version`), or undefined when the operator is asked. */
523
+ export const playbookVersionChoice = (cfg: Config): string | undefined =>
524
+ cfg.release.version === "versioned" ? "next" : cfg.release.version === "unversioned" ? "unreleased" : undefined;
525
+
526
+ /** `to` raises the major version over `from` (1.x → 2.0, and 0.x → 1.0). */
527
+ export function majorBump(from: string, to: string): boolean {
528
+ const maj = (v: string) => Number.parseInt(v.split(".")[0] ?? "", 10);
529
+ return Number.isFinite(maj(from)) && Number.isFinite(maj(to)) && maj(to) > maj(from);
530
+ }
531
+
532
+ /** A recorded call in the operator's words. */
533
+ export const describeVersionChoice = (c: string, from?: string | null): string =>
534
+ c === "unreleased"
535
+ ? "merge unreleased (no bump, no tag)"
536
+ : c === "next"
537
+ ? "a versioned release (playbook: version = versioned)"
538
+ : isBumpKind(c)
539
+ ? `a ${c} release${bumpVersion(from, c) ? ` (${from} → ${bumpVersion(from, c)})` : ""}`
540
+ : `release ${c}`;
541
+
542
+ /** Does the version flag pair on a verify/release call parse? Returns the call it makes, null for none, or an error. */
543
+ export function versionArg(value: string | null, noVersion: boolean): { choice: string | null } | { error: string } {
544
+ if (value !== null && noVersion) return { error: "--version=<v> and --no-version contradict each other — pass the one the operator chose" };
545
+ if (value !== null && !isBumpKind(value.trim()) && !VERSION_ARG_RE.test(value.trim()))
546
+ return { error: `--version=${value} is not a release call — pass what the operator chose: patch, minor, major, or an exact version such as 1.4.0` };
547
+ return { choice: value !== null ? value.trim() : noVersion ? "unreleased" : null };
548
+ }
549
+
500
550
  /**
501
551
  * Gate: pre-release → release ("Release?"). Machine-proves the parts of release prep that can be
502
552
  * proven — checks re-greened after the prep edits, manifest bumped past the last tag, and the
@@ -510,8 +560,8 @@ export function preReleaseGate(state: FlowState, cfg: Config, prep: ReleasePrep)
510
560
  const errs: string[] = [];
511
561
  if (state.stage !== "pre-release") errs.push(`stage is "${state.stage}", the release gate only applies to "pre-release"`);
512
562
  if (!state.docs) for (const c of cfg.checkList) if (!state.checks[c.name]?.ok) errs.push(`check "${c.name}" has not passed — run flow check`);
513
- const pend = checklistPending(cfg, state, "pre-release");
514
- if (pend) errs.push(`tier-2 checklist not confirmed (${pend} item(s)) — run flow release after ticking them off`);
563
+ const pend = openItemsNote(cfg, state, "pre-release");
564
+ if (pend) errs.push(`tier-2 checklist not confirmed — ${pend}; confirm them with the operator, then run flow release`);
515
565
  if (prep.conflictMarkers?.length && !prep.noMarkerCheck)
516
566
  errs.push(`the branch adds ${prep.conflictMarkers.length} merge-conflict marker line(s) — a hand-resolved merge kept them; fix and commit (or, when the lines are meant, re-run with --no-marker-check on the operator's word):\n ${prep.conflictMarkers.slice(0, 5).join("\n ")}${prep.conflictMarkers.length > 5 ? `\n …(${prep.conflictMarkers.length - 5} more)` : ""}`);
517
567
  if (state.noVersion) {
@@ -578,7 +628,7 @@ export function unreleasedPending(content: string): boolean {
578
628
 
579
629
  export function checklistHash(items: ChecklistItem[]): string {
580
630
  return createHash("sha1")
581
- .update(items.map((i) => `${i.uiOnly ? "(ui) " : ""}${i.versionedOnly ? "(versioned) " : ""}${i.text}`).join("\n"))
631
+ .update(items.map((i) => `${i.uiOnly ? "(ui) " : ""}${i.versionedOnly ? "(versioned) " : ""}${i.docs ? "(docs) " : ""}${i.text}`).join("\n"))
582
632
  .digest("hex")
583
633
  .slice(0, 12);
584
634
  }
@@ -613,9 +663,38 @@ export function freshenChecks(state: FlowState, fp: string | null, keep: (name:
613
663
  return stale;
614
664
  }
615
665
 
616
- /** Items that apply to this feature — "(ui)" items only when the UI flag is set. */
666
+ /** gh#204: what a dev command resolved to. The playbook command prints verbatim (`COMPOSE_PROJECT_NAME=app$DEV_FLOW_SUFFIX`),
667
+ * and on the default port `DEV_FLOW_SUFFIX` is "" — the difference between a private stack and the machine's shared
668
+ * one. Names the DEV_FLOW_* values the command reads and the compose project it lands on; "" when it reads none. */
669
+ export function resolvedDevEnv(cmd: string, env: Record<string, string>): string {
670
+ const esc = (k: string) => k.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
671
+ const names = Object.keys(env).filter((k) => k.startsWith("DEV_FLOW_") && new RegExp(`\\$\\{?${esc(k)}(?![A-Za-z0-9_])`).test(cmd));
672
+ let expanded = cmd;
673
+ for (const k of names) {
674
+ const v = env[k];
675
+ expanded = expanded.replace(new RegExp(`\\$\\{${esc(k)}(?::?-[^}]*)?\\}`, "g"), () => v).replace(new RegExp(`\\$${esc(k)}(?![A-Za-z0-9_])`, "g"), () => v);
676
+ }
677
+ const compose = /\bdocker[ -]compose\b/.test(cmd);
678
+ const proj = expanded.match(/\bCOMPOSE_PROJECT_NAME=("[^"]*"|'[^']*'|[^\s;&|]*)/)?.[1] ?? expanded.match(/\bdocker[ -]compose\b[^;&|]*?\s(?:-p|--project-name)[ =]("[^"]*"|'[^']*'|[^\s;&|]+)/)?.[1];
679
+ const parts = names.map((k) => `${k}=${env[k] === "" ? '""' : env[k]}`);
680
+ if (proj !== undefined) parts.push(`compose project ${proj.replace(/^(["'])(.*)\1$/, "$2") || '""'}`);
681
+ else if (compose) parts.push("compose project not set by the command (compose names it after the directory)");
682
+ return parts.length ? `resolved: ${parts.join(", ")}` : "";
683
+ }
684
+
685
+ /** Items that apply to this feature — "(ui)" items only when the UI flag is set. A --docs flow skips build,
686
+ * deploy and health at implement, so the implement items that check the running app stand down there too:
687
+ * only the ones tagged "(docs)" apply (gh#207). */
617
688
  export function applicableItems(cfg: Config, state: FlowState, stage: string): ChecklistItem[] {
618
- return (cfg.checklist[stage] ?? []).filter((i) => (!i.uiOnly || state.ui) && (!i.versionedOnly || !state.noVersion));
689
+ return (cfg.checklist[stage] ?? []).filter((i) => (!i.uiOnly || state.ui) && (!i.versionedOnly || !state.noVersion) && (!state.docs || stage !== "implement" || !!i.docs));
690
+ }
691
+
692
+ /** gh#207: an open tier-2 count names its items and where they live — "tier-2 3 open" alone could not be found
693
+ * in project.md (the word "tier-2" is not in it). "" when nothing is open. */
694
+ export function openItemsNote(cfg: Config, state: FlowState, stage: string): string {
695
+ if (!checklistPending(cfg, state, stage)) return "";
696
+ const items = applicableItems(cfg, state, stage);
697
+ return `${items.length} item(s) under ## ${stage} in .dev-flow/project.md: ${items.map((i) => `"${i.text}"`).join(" | ")}`;
619
698
  }
620
699
 
621
700
  /** Items exist for the stage and current confirmation does not match their hash; returns pending count or 0. */
@@ -1718,6 +1797,10 @@ export interface ReflectItem {
1718
1797
  line: string;
1719
1798
  /** the note without checkbox and without the ` — attribution` tail */
1720
1799
  body: string;
1800
+ /** gh#197: the row's stable number — its position among every checklist row of the file, open or closed. Checking
1801
+ * an item off leaves every other number where it was, so a batch of `done <n>` read off one list stays paired;
1802
+ * only `tidy` (drops closed rows) and `move` (relocates one) renumber. */
1803
+ n: number;
1721
1804
  }
1722
1805
 
1723
1806
  /** Open items of reflections.md, each carrying the heading that owns it. Items above every known
@@ -1726,6 +1809,7 @@ export interface ReflectItem {
1726
1809
  export function reflectItems(text: string): ReflectItem[] {
1727
1810
  const out: ReflectItem[] = [];
1728
1811
  let section: KnownSection | "unfiled" = "unfiled";
1812
+ let row = 0;
1729
1813
  for (const raw of text.split("\n")) {
1730
1814
  const l = raw.trim();
1731
1815
  if (ANY_HEADING.test(l)) {
@@ -1733,12 +1817,25 @@ export function reflectItems(text: string): ReflectItem[] {
1733
1817
  section = h ? (h[1].toLowerCase() as KnownSection) : "unfiled";
1734
1818
  continue;
1735
1819
  }
1820
+ if (isDoneItem(l)) row++;
1736
1821
  if (!isOpenItem(l)) continue;
1737
- out.push({ section, line: l, body: reflectionBody(l) });
1822
+ out.push({ section, line: l, body: reflectionBody(l), n: ++row });
1738
1823
  }
1739
1824
  return out;
1740
1825
  }
1741
1826
 
1827
+ /** Row `n` of reflections.md (the stable numbering, gh#197): its line index and whether it is still open; null when no such row. */
1828
+ export function reflectRow(text: string, n: number): { index: number; open: boolean; line: string } | null {
1829
+ const lines = text.split("\n");
1830
+ let row = 0;
1831
+ for (let i = 0; i < lines.length; i++) {
1832
+ const open = isOpenItem(lines[i]);
1833
+ if (!open && !isDoneItem(lines[i])) continue;
1834
+ if (++row === n) return { index: i, open, line: lines[i].trim() };
1835
+ }
1836
+ return null;
1837
+ }
1838
+
1742
1839
  /** Open items the file does not place in a known section — doctor names the count so a note that
1743
1840
  * would once have quietly migrated to `## playbook` on the next write gets moved on purpose. */
1744
1841
  export const reflectUnfiledCount = (text: string) => reflectItems(text).filter((i) => i.section === "unfiled").length;
@@ -1835,37 +1932,25 @@ export function reflectionRoutes(items: ReflectItem[], selfRepo: boolean): Refle
1835
1932
  });
1836
1933
  }
1837
1934
 
1838
- /** Move open item n (1-based over open items — the numbering `flow reflect list` prints) under
1839
- * `## section`. null = out of range; an item already in that section comes back unchanged, so the
1840
- * caller can say so instead of pretending to relocate it. */
1935
+ /** Move open row n (the stable numbering `flow reflect list` prints, gh#197) under `## section`. null = no open
1936
+ * row n; an item already in that section comes back unchanged, so the caller can say so instead of pretending
1937
+ * to relocate it. */
1841
1938
  export function reflectMove(text: string, n: number, section: ReflectSection): string | null {
1939
+ const row = reflectRow(text, n);
1940
+ if (!row?.open) return null;
1842
1941
  const lines = text.split("\n");
1843
- let seen = 0;
1844
- let hit = -1;
1845
- for (let i = 0; i < lines.length; i++) {
1846
- if (!isOpenItem(lines[i])) continue;
1847
- if (++seen === n) {
1848
- hit = i;
1849
- break;
1850
- }
1851
- }
1852
- if (hit < 0) return null;
1853
- const [line] = lines.splice(hit, 1);
1942
+ const [line] = lines.splice(row.index, 1);
1854
1943
  return appendReflection(lines.join("\n"), [section], line.trim());
1855
1944
  }
1856
1945
 
1857
- /** Check open item `n` (the `flow reflect list` numbering) off: `- [x] … — fixed: <note>` — the convention
1858
- * doctor reads as closed, so a folded item stops re-nagging (#165). null when there is no item `n`. */
1946
+ /** Check open row `n` (the stable `flow reflect list` numbering, gh#197) off: `- [x] … — fixed: <note>` — the
1947
+ * convention doctor reads as closed, so a folded item stops re-nagging (#165). null when there is no open row `n`. */
1859
1948
  export function reflectDone(text: string, n: number, note: string): string | null {
1949
+ const row = reflectRow(text, n);
1950
+ if (!row?.open) return null;
1860
1951
  const lines = text.split("\n");
1861
- let seen = 0;
1862
- for (let i = 0; i < lines.length; i++) {
1863
- if (!isOpenItem(lines[i])) continue;
1864
- if (++seen !== n) continue;
1865
- lines[i] = `${lines[i].replace(/^(\s*)- \[ \] /, "$1- [x] ").trimEnd()} — fixed: ${note.trim()}`;
1866
- return lines.join("\n");
1867
- }
1868
- return null;
1952
+ lines[row.index] = `${lines[row.index].replace(/^(\s*)- \[ \] /, "$1- [x] ").trimEnd()} — fixed: ${note.trim()}`;
1953
+ return lines.join("\n");
1869
1954
  }
1870
1955
 
1871
1956
  /** What `flow doctor <note>` prints: the note is an investigation order, not an answer —
@@ -2187,10 +2272,19 @@ export function nextHint(state: FlowState, cfg: Config): string {
2187
2272
  if (state.patch || state.docs) return `${state.patch ? "patch" : "docs"}: describe the change in one line, ask Approve? in chat, then flow approve --confirmed — no plan file${state.docs ? ", no tier-1 checks" : ""}`;
2188
2273
  return `clarify the direction in chat, write .dev-flow/${state.slug}/plan/plan.md${state.ui ? ` and render mockups to plan/mockups/ (${cfg.mockupGlobs.join(", ")}) with headless chromium, embedded in plan.md` : ""}, then ask Approve? and run flow approve --confirmed on the answer`;
2189
2274
  case "implement":
2190
- if (state.docs) return `edit in ${state.worktree} (docs mode: no project commands), tick the tier-2 checklist with the operator, ask Verified?, then flow verify --confirmed`;
2275
+ if (state.docs) {
2276
+ const open = openItemsNote(cfg, state, "implement");
2277
+ return `edit in ${state.worktree} (docs mode: no project commands)${open ? `, go through the checklist with the operator (${open})` : ""}, ask Verified?, then flow verify --confirmed`;
2278
+ }
2191
2279
  return `build and test in ${state.worktree}, commit as you go, flow check; then flow verify (deploys for review), look yourself, keep the app running, ask Verified? and run flow verify --confirmed on the answer`;
2192
2280
  case "pre-release": {
2193
- const prep = [cfg.release.changelog ? `prepare ${cfg.release.changelog} (fold Unreleased lines verbatim)` : "", cfg.versioning.file ? `bump version in ${cfg.versioning.file}` : ""].filter(Boolean).join(" and ");
2281
+ // gh#198: the release call made with Verified? decides which prep this is
2282
+ const vc = state.versionChoice;
2283
+ const auto = cfg.release.ask !== "always" ? " (release.ask = on-change: it asks Release? only when something beyond the prep changed)" : "";
2284
+ if (vc === "unreleased")
2285
+ return `${cfg.release.review}, fix must/should${state.docs ? "" : " (a fix that changes behaviour: flow verify redeploys and re-asks Verified? over it)"}, update docs${cfg.release.changelog && !state.docs ? `, add this flow's line under Unreleased in ${cfg.release.changelog} (the call is merge unreleased: no bump)` : ""}, flow check; show the PR summary, then run flow release${auto || " and ask Release?"}`;
2286
+ const prep = [cfg.release.changelog ? `prepare ${cfg.release.changelog} (fold Unreleased lines verbatim)` : "", cfg.versioning.file ? `bump version in ${cfg.versioning.file}${isBumpKind(vc) ? ` to ${bumpVersion(state.versionFrom, vc) ?? `the next ${vc}`} (a ${vc} release, the operator's call — the gate counts it from the newest tag, so a flow that released first moves the number)` : vc && vc !== "next" ? ` to ${vc} (the operator's call)` : ""}` : ""].filter(Boolean).join(" and ");
2287
+ if (vc && prep) return `${cfg.release.review}, fix must/should${state.docs ? "" : " (a fix that changes behaviour: flow verify redeploys and re-asks Verified? over it)"}, update docs, ${prep}, flow check; show the PR summary, version and changelog, then run flow release${auto || " and ask Release?"}`;
2194
2288
  if (state.docs && prep) return `${cfg.release.review}, fix must/should; a docs flow usually ships unversioned — ask the operator (flow release --no-version on their word); versioned instead: ${prep}; then ask Release? and run flow release`;
2195
2289
  return `${cfg.release.review}, fix must/should${state.docs ? "" : " (a fix that changes behaviour: flow verify redeploys and re-asks Verified? over it)"}, update docs${prep ? `, ${prep}` : ""}, flow check; show the PR summary, version and changelog, ask Release? and run flow release`;
2196
2290
  }
@@ -2321,6 +2415,8 @@ export interface WorkerBriefInput {
2321
2415
  commits: string; // `git log --oneline <base>..HEAD`
2322
2416
  status: string; // `git status --short`
2323
2417
  checks: { name: string; command: string }[];
2418
+ /** the playbook's `flow-worker` lines (gh#201): setup a worker needs before any project check can run */
2419
+ preamble?: string[];
2324
2420
  note: string;
2325
2421
  }
2326
2422
 
@@ -2339,9 +2435,12 @@ export function buildWorkerBrief(o: WorkerBriefInput): string {
2339
2435
  `- Branch base: ${o.defaultBranch}`,
2340
2436
  `- Commits on the branch so far:\n${o.commits.trim() ? o.commits.trim().split("\n").map((l) => ` ${l}`).join("\n") : " (none)"}`,
2341
2437
  `- Uncommitted now: ${o.status.trim() ? `\n${o.status.trim().split("\n").map((l) => ` ${l}`).join("\n")}` : "clean"}`,
2342
- `- Project checks (run them before you report):\n${checks}`,
2438
+ `- Project checks (run them before you report${o.preamble?.length ? ", in a shell that ran the setup below first" : ""}):\n${checks}`,
2343
2439
  "- You hold no flow tool: gates, checkpoints and the operator stay with the driving session.",
2344
2440
  "",
2441
+ ...(o.preamble?.length
2442
+ ? ["## Setup (from the project's playbook)", "Run these lines in every shell that runs a project check: each bash call is a fresh shell, so prefix the check with them or chain them with `&&`.", "```sh", ...o.preamble, "```", ""]
2443
+ : []),
2345
2444
  "## Your task",
2346
2445
  o.note.trim() || "(no note — do what the plan's next unfinished step asks)",
2347
2446
  "",
@@ -2363,6 +2462,7 @@ export function buildWorkerBrief(o: WorkerBriefInput): string {
2363
2462
  "## Contract",
2364
2463
  `- Check, don't fix: read ${o.planFile ? "the plan" : "the task"}, the diff (\`git diff ${o.defaultBranch}...HEAD\`) and the code; run the checks and any probe that proves a claim. Change no files, make no commits.`,
2365
2464
  "- Look for correctness bugs, claims in docs/changelog the code does not back, missing tests for risky paths, and plan items not delivered.",
2465
+ "- A project check you could not run (a missing variable, file or service) is not a pass: name it and why under `checks not run:` in the REPORT, and say in the verdict line that the review is read-only for it.",
2366
2466
  "- Finish with a final message whose last section starts with a line `REPORT` followed by: `verdict: PASS` or `verdict: FAIL`, then findings (most severe first, each with file:line and how you proved it).",
2367
2467
  ];
2368
2468
  return [...head, ...contract].join("\n");
@@ -2575,7 +2675,7 @@ export interface ReflectBriefInput {
2575
2675
  * the operator decides fold or drop per finding in the driving session. */
2576
2676
  export function buildReflectBrief(o: ReflectBriefInput): string {
2577
2677
  const up = o.upstream || "(unknown — say so in the REPORT)";
2578
- const open = o.items.length ? o.items.map((it, i) => ` ${i + 1}. [${it.section}] ${it.line.replace(/^- \[ \] /, "")}`).join("\n") : " (none)";
2678
+ const open = o.items.length ? o.items.map((it) => ` ${it.n}. [${it.section}] ${it.line.replace(/^- \[ \] /, "")}`).join("\n") : " (none)";
2579
2679
  const kids = o.children.length ? o.children.map((c) => ` - ${c.file}${c.name ? ` (${c.name})` : ""}`).join("\n") : " (none — no flow_stage worker ran in this session)";
2580
2680
  const digests = o.digests?.length ? o.digests.map((d) => ` - ${d.digest} (of ${path.basename(d.transcript)})`).join("\n") : "";
2581
2681
  const upIssues = o.upstreamIssues ? (o.upstreamIssues.length ? o.upstreamIssues.map((i) => ` gh#${i.number} [${i.state.toLowerCase()}] ${i.title}`).join("\n") : " (none)") : "";
package/src/present.ts CHANGED
@@ -117,7 +117,7 @@ export function stageLine(state: FlowState, cfg: Config, f: StageFacts = {}): st
117
117
  else if (items) fields.push("tier-2 `confirmed` ✓");
118
118
  }
119
119
  if (stage === "pre-release" || stage === "release") {
120
- const version = state.noVersion ? "version `no-version` ✓" : state.releaseVersion ? `version \`${state.releaseVersion}\` ✓` : f.manifest ? `version \`${f.manifest}\` ~` : "version `pending` ?";
120
+ const version = state.noVersion ? "version `no-version` ✓" : state.releaseVersion ? `version \`${state.releaseVersion}\` ✓` : state.versionChoice && state.versionChoice !== "next" && state.versionChoice !== "unreleased" ? `version \`${state.versionChoice}\` ✓` : f.manifest ? `version \`${f.manifest}\` ~` : "version `pending` ?";
121
121
  fields.push(version);
122
122
  const merge = cfg.release.merge;
123
123
  fields.push(merge ? `merge \`${merge}\` ✓playbook` : "merge `unset` ?");
@@ -207,7 +207,7 @@ export function agentText(text: string, v: GateView): string {
207
207
 
208
208
  /** Flags only dev-flow's gates take. A generic CLI flag (`docker compose up -d --no-deps`, `gh pr merge --merge`)
209
209
  * in a report of what the agent ran is not a dev-flow command handed to the operator. */
210
- const GATE_FLAGS = "confirmed|ui|patch|docs|yolo|replace|port|no-version|no-fold-check|no-marker-check|no-artifact-check|no-release-create|no-reflect|check-upstream|answers|answers-file|write-file|brief|brief-file|playbook|note";
210
+ const GATE_FLAGS = "version=|confirmed|ui|patch|docs|yolo|replace|port|no-version|no-fold-check|no-marker-check|no-artifact-check|no-release-create|no-reflect|check-upstream|answers|answers-file|write-file|brief|brief-file|playbook|note";
211
211
  const ASK_COMMAND_RE = new RegExp(`(?:^|[\\s\`'"(*_])/?flow (?:${FLOW_VERBS})\\b|(?:^|[\\s\`])--(?:${GATE_FLAGS})\\b|\\bflow_stage\\b|(?:^|[\\s\`])/flow\\b`);
212
212
  /** An imperative addressed to the operator: the verb opens a clause (or follows please/then/just), or a "you can" form. */
213
213
  const ASK_VERB_RE = /(?:^|[:;,.!?(—–]\s*|\b(?:please|then|just|now|simply|and)\s+)(?:run|type|enter|use|try|send|invoke)\b|\byou (?:can|could|may|should|need to|might)\b|\bplease\b/i;
package/src/projectmd.ts CHANGED
@@ -21,6 +21,8 @@ export interface ParsedMd {
21
21
  guard: GuardRules;
22
22
  checklist: Record<string, ChecklistItem[]>;
23
23
  prose: Record<string, string>;
24
+ /** ## global `flow-worker` block lines — the setup every stage worker's brief carries (gh#201) */
25
+ workerPreamble: string[];
24
26
  }
25
27
 
26
28
  // stage → flow-key → config dot-path (aliases); unknown keys warn
@@ -64,6 +66,8 @@ const KEYMAP: Record<string, Record<string, string>> = {
64
66
  merge: "release.merge", // how a merged branch lands: squash | merge | rebase | any
65
67
  yolo: "release.yolo", // how far a standing yolo reaches: all (default) | until-release (gh#176)
66
68
  reflect: "release.reflect", // when finish runs the closing reflection: on-friction (default) | always
69
+ version: "release.version", // who decides versioned vs unreleased: ask (with Verified?, default) | versioned | unversioned (gh#198)
70
+ ask: "release.ask", // when Release? is asked: on-change (default) | always (gh#198)
67
71
  },
68
72
  };
69
73
  // pre-release owns release preparation; the release keys are accepted under both sections so
@@ -121,7 +125,7 @@ function parseGuardRules(entries: { line: string; where: string }[], stage: stri
121
125
  }
122
126
 
123
127
  export function parseProjectMd(text: string): ParsedMd {
124
- const p: ParsedMd = { hard: [], warn: [], global: {}, flow: Object.fromEntries(MD_STAGES.map((s) => [s, {}])) as Record<MdStage, Record<string, string>>, checks: [], guard: structuredClone(DEFAULTS.guard), checklist: {}, prose: {} };
128
+ const p: ParsedMd = { hard: [], warn: [], global: {}, flow: Object.fromEntries(MD_STAGES.map((s) => [s, {}])) as Record<MdStage, Record<string, string>>, checks: [], guard: structuredClone(DEFAULTS.guard), checklist: {}, prose: {}, workerPreamble: [] };
125
129
  let stage: string | null = null;
126
130
  const prose: Record<string, string[]> = {};
127
131
  let inFence: string | null = null; // "flow" | "flow-check" | other lang
@@ -178,10 +182,23 @@ export function parseProjectMd(text: string): ParsedMd {
178
182
  p.warn.push(`${where}: reflect = "${m[2]}" — expected always or on-friction, keeping on-friction`);
179
183
  return;
180
184
  }
185
+ if (mapped === "release.version" && !/^(ask|versioned|unversioned)$/.test(m[2].trim())) {
186
+ p.warn.push(`${where}: version = "${m[2]}" — expected ask, versioned or unversioned, keeping ask`);
187
+ return;
188
+ }
189
+ if (mapped === "release.ask" && !/^(always|on-change)$/.test(m[2].trim())) {
190
+ p.warn.push(`${where}: ask = "${m[2]}" — expected on-change or always, keeping on-change`);
191
+ return;
192
+ }
181
193
  p.flow[stage as MdStage][mapped] = m[2];
182
194
  }
183
195
  }
184
196
  } else if (inFence === "flow-check") checkBody.push(line);
197
+ else if (inFence === "flow-worker") {
198
+ if (stage === "global") {
199
+ if (line.trim()) p.workerPreamble.push(line.trimEnd());
200
+ } else if (line.trim()) p.warn.push(`${where}: flow-worker lines belong to ## global — ignored under ## ${stage ?? "(no stage)"}`);
201
+ }
185
202
  else if (inFence === "flow-guard") guardBody.push({ line, where });
186
203
  return;
187
204
  }
@@ -194,6 +211,7 @@ export function parseProjectMd(text: string): ParsedMd {
194
211
  inFence = "flow-check";
195
212
  checkName = lang.slice("flow-check".length).trim();
196
213
  } else if (lang === "flow-guard") inFence = "flow-guard";
214
+ else if (lang === "flow-worker") inFence = "flow-worker";
197
215
  else inFence = lang || "code";
198
216
  return;
199
217
  }
@@ -206,16 +224,19 @@ export function parseProjectMd(text: string): ParsedMd {
206
224
  if (!stage || stage === "global" || !MD_STAGES.includes(stage as MdStage)) return; // preamble/unknown → not injected
207
225
  const item = line.match(CHECK_ITEM);
208
226
  if (item) {
209
- // qualifiers lead the item in any order: (ui) = --ui features only, (versioned) = not on a --no-version flow
227
+ // qualifiers lead the item in any order: (ui) = --ui features only, (versioned) = not on a --no-version flow,
228
+ // (docs) = an implement item that still applies on a --docs flow (gh#207)
210
229
  let text = item[1].trim();
211
230
  let uiOnly = false;
212
231
  let versionedOnly = false;
213
- for (let q = /^\((ui|versioned)\)\s+/.exec(text); q; q = /^\((ui|versioned)\)\s+/.exec(text)) {
232
+ let docs = false;
233
+ for (let q = /^\((ui|versioned|docs)\)\s+/.exec(text); q; q = /^\((ui|versioned|docs)\)\s+/.exec(text)) {
214
234
  if (q[1] === "ui") uiOnly = true;
235
+ else if (q[1] === "docs") docs = true;
215
236
  else versionedOnly = true;
216
237
  text = text.slice(q[0].length);
217
238
  }
218
- (p.checklist[stage] ??= []).push(versionedOnly ? { text, uiOnly, versionedOnly } : { text, uiOnly });
239
+ (p.checklist[stage] ??= []).push({ text, uiOnly, ...(versionedOnly ? { versionedOnly } : {}), ...(docs ? { docs } : {}) });
219
240
  return;
220
241
  }
221
242
  if (/^(#|```|<!--|\s*$)/.test(line) && !line.startsWith("### ")) return; // h1/html comments/blank are not prose
@@ -252,6 +273,7 @@ export function mdToConfig(p: ParsedMd): Config {
252
273
  ];
253
274
  c.checklist = p.checklist;
254
275
  c.prose = p.prose;
276
+ if (p.workerPreamble.length) c.workerPreamble = [...p.workerPreamble];
255
277
  return c;
256
278
  }
257
279
 
@@ -542,6 +564,7 @@ export function mdDigest(text: string): string {
542
564
  if (s === "global") {
543
565
  const rules = (["deny", "confirm", "protect", "forbid"] as const).flatMap((v) => p.guard[v].map((r) => `${v} ${r.pattern}`));
544
566
  if (rules.length) bits.push(`safety rules: ${rules.join(" · ")}`);
567
+ if (p.workerPreamble.length) bits.push(`stage-worker setup: ${p.workerPreamble.length} line(s) in every flow_stage brief`);
545
568
  }
546
569
  if (relStage && keys.file) {
547
570
  bits.push(`version in ${keys.file} → tag ${keys.pattern ?? "v{version}"}`);
@@ -550,7 +573,7 @@ export function mdDigest(text: string): string {
550
573
  }
551
574
  if (s === "pre-release" && !keys.file && !p.flow.release["versioning.file"]) bits.push("version: no version file set — releases cannot bump or tag");
552
575
  const items = p.checklist[s] ?? [];
553
- if (items.length) bits.push(`manual check: ${items.map((i) => `${i.uiOnly ? "(UI only) " : ""}${i.versionedOnly ? "(versioned only) " : ""}\"${i.text}\"`).join(" · ")}`);
576
+ if (items.length) bits.push(`manual check: ${items.map((i) => `${i.uiOnly ? "(UI only) " : ""}${i.versionedOnly ? "(versioned only) " : ""}${i.docs ? "(docs flows too) " : ""}\"${i.text}\"`).join(" · ")}`);
554
577
  if (p.prose[s]) bits.push(`guidance: "${p.prose[s].replace(/\s+/g, " ").trim()}"`);
555
578
  if (bits.length) rows.push(`${label} — ${bits.join(" · ")}`);
556
579
  }
@@ -236,7 +236,7 @@ export async function releaseTags(root: string): Promise<string[] | null> {
236
236
  }
237
237
 
238
238
  export const GATE_HELP =
239
- "help [--json] | init [--force|--draft|--write <text>|--write-file <path>|--answers key=value…|--answers-file <path>] [--confirmed] [--track] | reflect [<note>|list|tidy|move <n> --playbook|--code|done <n> [<what>]] | roadmap [add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>|drop <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui|--patch|--docs --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | approve [--yolo] | verify [--yolo] [--port=<n>|--replace] | release [--yolo|--no-version|--no-fold-check|--no-marker-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [--no-reflect] [--note=<text>] [slug] | abort [slug] | version [--check-upstream] — state gates take [slug] and --confirmed (the operator already answered in chat); without it the agent's call returns NEEDS-OPERATOR with the question to ask in chat (it never opens a dialog), and the /flow slash command asks in a dialog — verify without --confirmed rebases a branch that is behind the default branch and deploys for review; --port=<n> / --replace answer its Dev port? question when another flow holds the stack — --ui/--patch/--docs and --merge=<style> on start are operator-granted (--confirmed); start refuses until the playbook has a merge policy and writes the answer into project.md — --yolo (with --confirmed) answers that checkpoint and pre-confirms every later one; checks and guardrails stay — release --no-version ships merge + changelog only (no bump, tag or forge release); --no-fold-check skips the changelog fold line proofs on the operator's word; --no-marker-check lets a branch add conflict-marker-shaped lines on purpose — finish runs the closing reflection worker first (before removing anything) and stops for the operator's fold/drop; the re-run with --confirmed cleans up; --no-reflect --confirmed skips it on the operator's explicit word (yolo never does), --note= hands the worker the operator's friction notes — release names a session running an older dev-flow build than the disk ships and asks update (/reload) or proceed — recorded, never a block — reflect <note> queues a project suggestion in reflections.md (--playbook = docs-flow fix, --code = patch-flow fix); --plugin never writes — dev-flow feedback goes upstream and it prints the GitHub issue recipe; bare reflect prints the session-reflection protocol (bound: run flow_stage op reflect); list numbers open items, move <n> re-files one, done <n> checks a fixed one off, tidy drops closed ones — roadmap manages .dev-flow/roadmap.md: pick <n> <slug> (or add --slug=) stamps an item for flow start, which seeds the new plan from its brief; finish checks it off; drop <n> removes an item nobody wants any more (done would record it as shipped) — a new feature asked for mid-flow is parked there, never as a hand-made .dev-flow/<slug>/; start <slug> --confirmed adopts such a ghost dir — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — version prints the build the disk ships and any other dev-flow copies in this process (--check-upstream asks the registry)";
239
+ "help [--json] | init [--force|--draft|--write <text>|--write-file <path>|--answers key=value…|--answers-file <path>] [--confirmed] [--track] | reflect [<note>|list|tidy|move <n> --playbook|--code|done <n> [<what>]] | roadmap [add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>|drop <n>|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui|--patch|--docs --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | approve [--yolo] | verify [--yolo] [--port=<n>|--replace] [--version=<v>|--no-version] | release [--yolo|--version=<v>|--no-version|--no-fold-check|--no-marker-check] | release-done [--no-artifact-check|--no-release-create] | finish [--yolo] [--no-reflect] [--note=<text>] [slug] | abort [slug] | version [--check-upstream] — state gates take [slug] and --confirmed (the operator already answered in chat); without it the agent's call returns NEEDS-OPERATOR with the question to ask in chat (it never opens a dialog), and the /flow slash command asks in a dialog — verify without --confirmed rebases a branch that is behind the default branch and deploys for review; --port=<n> / --replace answer its Dev port? question when another flow holds the stack — --ui/--patch/--docs and --merge=<style> on start are operator-granted (--confirmed); start refuses until the playbook has a merge policy and writes the answer into project.md — --yolo (with --confirmed) answers that checkpoint and pre-confirms every later one; checks and guardrails stay — verify --confirmed carries the operator's release call: --version=<v> (ship that version) or --no-version (merge unreleased), asked with Verified?; release takes the same flags when the call changed — release --no-version ships merge + changelog only (no bump, tag or forge release); --no-fold-check skips the changelog fold line proofs on the operator's word; --no-marker-check lets a branch add conflict-marker-shaped lines on purpose — finish runs the closing reflection worker first (before removing anything) and stops for the operator's fold/drop; the re-run with --confirmed cleans up; --no-reflect --confirmed skips it on the operator's explicit word (yolo never does), --note= hands the worker the operator's friction notes — release names a session running an older dev-flow build than the disk ships and asks update (/reload) or proceed — recorded, never a block — reflect <note> queues a project suggestion in reflections.md (--playbook = docs-flow fix, --code = patch-flow fix); --plugin never writes — dev-flow feedback goes upstream and it prints the GitHub issue recipe; bare reflect prints the session-reflection protocol (bound: run flow_stage op reflect); list numbers open items, move <n> re-files one, done <n> checks a fixed one off, tidy drops closed ones — roadmap manages .dev-flow/roadmap.md: pick <n> <slug> (or add --slug=) stamps an item for flow start, which seeds the new plan from its brief; finish checks it off; drop <n> removes an item nobody wants any more (done would record it as shipped) — a new feature asked for mid-flow is parked there, never as a hand-made .dev-flow/<slug>/; start <slug> --confirmed adopts such a ghost dir — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — version prints the build the disk ships and any other dev-flow copies in this process (--check-upstream asks the registry)";
240
240
  export const featDir = (root: string, slug: string) => path.join(dfDir(root), slug);
241
241
  export const stateFile = (root: string, slug: string) => path.join(featDir(root, slug), "state.json");
242
242
  export const claimFile = (root: string, slug: string) => path.join(featDir(root, slug), "claim.json");
@@ -273,6 +273,12 @@ export async function gateInit(o: GateCtx): Promise<RunResult> {
273
273
  return { text: notes.join("\n") };
274
274
  }
275
275
 
276
+ /** gh#206: an operator-granted refusal states the rule that makes an immediate --confirmed re-run useless
277
+ * (gh#190 binds only a message that postdates the ask), so the agent asks once instead of burning a call
278
+ * to learn it — and says what to do next time the operator's own request carries the grant. */
279
+ export const GRANT_AFTER =
280
+ "ask the operator in chat and stop; re-run with --confirmed once they reply. Only an operator message sent after this refusal counts, so a grant given before it (even in the request that started this) must be asked again, and an immediate re-run is refused. When the operator's own request already grants it, pass --confirmed on the first call";
281
+
276
282
  export async function gateStart(o: GateCtx): Promise<RunResult> {
277
283
  const { root, sess, cfg, rest, flag, slugArg } = o;
278
284
  if (!slugArg || !validSlug(slugArg)) return { text: "usage: flow start <slug> [--ui] [--patch|--docs] [--merge=squash|merge|rebase|any] (slug: lowercase, dashes); --ui/--patch/--docs are operator-granted — ask the operator in chat, then add --confirmed", isError: true };
@@ -299,7 +305,7 @@ export async function gateStart(o: GateCtx): Promise<RunResult> {
299
305
  // proof at approve and every (ui) checklist item (lettuce rail-ui-fixes shipped 20 ungated mockups)
300
306
  const existing = readState(root, slugArg);
301
307
  if (flag("ui") && existing && sess.slug === slugArg) {
302
- if (!flag("confirmed")) return { text: "--ui is operator-granted — it adds a rendered-mockup requirement to the plan gate; ask the operator, then re-run with --confirmed", isError: true };
308
+ if (!flag("confirmed")) return { text: `--ui is operator-granted — it adds a rendered-mockup requirement to the plan gate; ${GRANT_AFTER}`, isError: true };
303
309
  if (existing.ui) return { text: `feature ${slugArg} already has the ui flag` };
304
310
  if (existing.stage !== "plan") return { text: `feature ${slugArg} is at ${existing.stage} — the ui flag can be set only at plan (the mockup gate is approve's); render the screens anyway and say so in the verify report`, isError: true };
305
311
  writeState(root, { ...existing, ui: true });
@@ -313,9 +319,9 @@ export async function gateStart(o: GateCtx): Promise<RunResult> {
313
319
  // every grant start needs goes into one question: a refusal for one names the others still open, so
314
320
  // the operator answers mode, mockups and merge policy in a single message
315
321
  const alsoMerge = !cfg.release.merge && flagValue(rest, "merge") === null ? `\n${AGENT_MARK}the playbook also has no merge policy — put it in the same question (squash | merge | rebase | any) and pass --merge=<style> on the same re-run` : "";
316
- if (mode && !flag("confirmed")) return { text: `${mode} mode is operator-granted — the operator must grant it in chat, then re-run with --confirmed${alsoMerge}`, isError: true };
322
+ if (mode && !flag("confirmed")) return { text: `${mode} mode is operator-granted — ${GRANT_AFTER}${alsoMerge}`, isError: true };
317
323
  // --ui adds the rendered-mockup gate to plan: worth it only when screens change, and the operator says so
318
- if (flag("ui") && !flag("confirmed")) return { text: `--ui is operator-granted — it adds a rendered-mockup requirement to the plan gate, so use it only when the feature changes screens; ask the operator, then re-run with --confirmed${alsoMerge}`, isError: true };
324
+ if (flag("ui") && !flag("confirmed")) return { text: `--ui is operator-granted — it adds a rendered-mockup requirement to the plan gate, so use it only when the feature changes screens; ${GRANT_AFTER}${alsoMerge}`, isError: true };
319
325
  // branch discipline: features branch off the default branch — starting from a stale checkout poisons the base
320
326
  const curBr = await currentBranch(root);
321
327
  if (curBr !== cfg.defaultBranch && !flag("force")) return { text: `main checkout is on ${curBr}, not ${cfg.defaultBranch} — check out ${cfg.defaultBranch} first (git checkout ${cfg.defaultBranch} && git pull) or flow use an unfinished feature; --force to override`, isError: true };
@@ -605,7 +611,7 @@ export async function gateDoctor(o: GateCtx): Promise<RunResult> {
605
611
  findings.push(` [${r.sections.join("+")}] ${r.text}${link ? linkedTag(link.issue) : ""}\n → ${r.route}${link ? ` — already upstream (gh#${link.issue}); check off with — filed: gh#${link.issue} once it lands` : ""}`);
606
612
  });
607
613
  }
608
- findings.push(...foldRows(fold, isSelfRepo(root)));
614
+ findings.push(...foldRows(fold, isSelfRepo(root), refl));
609
615
  const reflText = readReflectionsText(root);
610
616
  const unfiled = reflectUnfiledCount(reflText);
611
617
  if (unfiled) findings.push(` reflections: ${unfiled} open item(s) sit outside ## playbook / ## code — flow reflect list shows them, flow reflect move <n> --playbook|--code files them`);
@@ -8,6 +8,10 @@
8
8
  * B. a feature started in this session gets a mode flag (--ui/--patch/--docs) granted with --confirmed
9
9
  * before any operator message arrived after the start.
10
10
  *
11
+ * --confirmed is not the only answer a gate takes: `Dev port?` is answered with --replace or --port=<n>
12
+ * (gh#203), and those bind the same way — a re-run of the gate that asked, carrying any of them, needs
13
+ * an operator message after the question.
14
+ *
11
15
  * It never decides what the operator meant — one message after the question is all it asks for. A
12
16
  * session it cannot read (no session manager) is not checked. Pure module: no pi imports. */
13
17
  import { NEEDS_OPERATOR } from "../core.ts";
@@ -35,16 +39,22 @@ export const newGrantLedger = (): GrantLedger => ({ asked: new Map(), started: n
35
39
 
36
40
  const ASKS_FOR_WORD = /operator-granted|operator's (?:explicit )?word|the operator must grant/;
37
41
  const MODE_FLAGS = ["--ui", "--patch", "--docs"];
42
+ /** Flags that carry the operator's answer to the question a gate asked — `--confirmed`, and the
43
+ * `Dev port?` answers (gh#203). */
44
+ export function answerFlags(args: readonly string[]): string[] {
45
+ return args.filter((a) => a === "--confirmed" || a === "--replace" || a.startsWith("--port="));
46
+ }
38
47
  const slugOf = (args: readonly string[]) => args.slice(1).find((a) => !a.startsWith("--")) ?? "";
39
48
 
40
49
  /** The refusal for a `--confirmed` no operator message stands behind, or null when the call may run. */
41
50
  export function grantCheck(args: readonly string[], key: string, users: number | null, ledger: GrantLedger): string | null {
42
- if (users === null || !args.includes("--confirmed")) return null;
51
+ const answers = answerFlags(args);
52
+ if (users === null || !answers.length) return null;
43
53
  const sub = args[0] ?? "";
44
54
  const asked = ledger.asked.get(key);
45
55
  if (asked && asked.sub === sub && users <= asked.users)
46
- return `${NEEDS_OPERATOR} no operator message since flow ${sub} asked for their word — --confirmed records the operator's answer in chat, it is not yours to give: ask in chat, stop, and re-run with --confirmed once they reply (gh#190)`;
47
- if (sub === "start" && args.some((a) => MODE_FLAGS.includes(a))) {
56
+ return `${NEEDS_OPERATOR} no operator message since flow ${sub} asked for their word — ${answers.join(" ")} records the operator's answer in chat, it is not yours to give. A word given before the question does not count, so re-running now is refused again: ask in chat, stop, and re-run once they reply (gh#190)`;
57
+ if (sub === "start" && args.includes("--confirmed") && args.some((a) => MODE_FLAGS.includes(a))) {
48
58
  const at = ledger.started.get(`${key}\u0000${slugOf(args)}`);
49
59
  if (at !== undefined && users <= at)
50
60
  return `${NEEDS_OPERATOR} ${args.filter((a) => MODE_FLAGS.includes(a)).join(" ")} on ${slugOf(args)} is operator-granted, and the operator has said nothing since it started — ask them in chat whether to turn it on, stop, and re-run with --confirmed once they reply (gh#190)`;