pi-dev-flow 0.89.0 → 0.90.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,73 @@
1
+ # Reflections: the agent's notes to you
2
+
3
+ When something costs the agent a step, it writes the problem down instead of quietly working
4
+ around it. Examples: a playbook command that no longer exists, a guard that blocked the wrong thing,
5
+ or a gate that forced a detour. That is how your playbook stays in sync with your project.
6
+
7
+ Reflections are advisory. They never block a gate, and nothing is fixed without your word.
8
+
9
+ ## Where notes go
10
+
11
+ `.dev-flow/reflections.md` is your project's queue. It has two sections:
12
+
13
+ | Section | The fix lives in | Fixed by |
14
+ |---|---|---|
15
+ | `## playbook` | `.dev-flow/project.md` | a docs flow |
16
+ | `## code` | your project's code | a patch flow |
17
+
18
+ **Feedback about dev-flow itself never goes into your project.** It becomes a GitHub issue on the
19
+ dev-flow repo, filed only when you say so.
20
+
21
+ | Command | Does |
22
+ |---|---|
23
+ | `flow reflect --playbook "<note>"` | adds a playbook note |
24
+ | `flow reflect --code "<note>"` | adds a code note |
25
+ | `flow reflect --plugin "<note>"` | prints how to file a dev-flow issue (search first, then `gh issue create`); writes nothing |
26
+ | `flow reflect "<note>"` | guesses the section from the wording and says why |
27
+ | `flow reflect list` | numbers the open notes |
28
+ | `flow reflect move <n> --code` | moves a note to the other section |
29
+ | `flow reflect done <n> "<what>"` | checks a note off as fixed |
30
+ | `flow reflect tidy` | removes the checked-off notes |
31
+
32
+ `flow status` and `flow doctor` show how many notes are open.
33
+
34
+ ## The closing review at finish
35
+
36
+ Before `flow finish` removes anything, a fresh read-only reviewer reads the whole session: the main
37
+ transcript and every worker's. It checks the findings against the open notes and the upstream
38
+ issues, then gives you a numbered list. Each finding is marked docs, code or plugin, with a
39
+ suggestion to **fold** (keep) or **drop** it.
40
+
41
+ You answer per item, for example `fold 1,3 drop 2`. Folding records a note, or files the issue for a
42
+ plugin finding. Dropping records nothing.
43
+
44
+ The review is skipped when the flow ran into no friction: no gate refusal, no guard block, no code change
45
+ after Verified?, and no `--note`. Set `reflect = always` in the playbook's `## release` section to run it every time. Only
46
+ your explicit `--no-reflect` skips it; *yolo* doesn't.
47
+
48
+ ## Nudges
49
+
50
+ The agent suggests working through the notes only at good moments: at finish, between flows, or in
51
+ `flow doctor`, and never in the middle of a feature.
52
+
53
+ - **"Fix the open reflections now?"** appears when a note came up again this session, a note is 14
54
+ days old, three playbook notes could share one docs flow, or a code note is waiting while you're
55
+ between flows.
56
+ - **"Tidy?"** appears once 5 notes are closed, closed notes outnumber open ones, or a closed note is
57
+ a month old.
58
+
59
+ To fix them, ask the agent to go through them, usually with `flow doctor`. It sends each note to the
60
+ flow that should fix it: playbook notes to a docs flow, code notes to a patch flow.
61
+
62
+ ## GitHub issues alongside
63
+
64
+ If the repo has a GitHub remote, `flow doctor` and `flow reflect list` also show open GitHub issues
65
+ next to your notes:
66
+
67
+ - a note that an open issue already covers is marked `⟷ gh#120`;
68
+ - the other issues are listed below as upstream rows;
69
+ - a possible duplicate is flagged (`~ gh#NNN may duplicate`), never merged automatically.
70
+
71
+ This view is display-only. Issues are closed on GitHub and notes are checked off in the file. If
72
+ `gh` is missing or fails, you get one line saying so. Set `DEV_FLOW_NO_ISSUES=1` to turn the view
73
+ off.
@@ -24,7 +24,7 @@ import path from "node:path";
24
24
  import { Type } from "typebox";
25
25
  import { compact, defineTool, isToolCallEventType, type AgentSession, type ExtensionContext } from "@earendil-works/pi-coding-agent";
26
26
  import { type ExtensionAPI, type ToolCallEvent, type ToolCallEventResult, type TurnEndEvent, type TurnEndEventResult } from "@earendil-works/pi-coding-agent";
27
- import { ALLOW_REWRITE, applicableItems, bashFlowGuard, checklistPending, checkoutInvocation, claimBlocks, featureBranchPrefix, FLOW_SHELL_HINT, flowShellInvocation, forcePushInvocation, freshenChecks, gitInvocation, guardBash, guardPath, mergeStyleInvocation, parsePushRefs, playbookTamper, playbookOnlyChange, pluginVersion, reflectionNudges, buildReflectBrief, parseReflectReport, renderReflectFindings, childSessionFiles, workerSteer, WORKER_STEER_AT, WORKER_SALVAGE, WORKER_SALVAGE_MS, WORKER_NUDGE_READONLY, stageReference, needsOperator, NEEDS_OPERATOR, nextHint, roadmapOpenCount, shouldTakeOverCompaction, stageGuidance, stateTamper, statusFor, sq, featureTmpDir, compactionStateBlock, withTmpDir, widgetLines, chipLabel, writeGuard, buildWorkerBrief, clampBudgetMin, parseWorkerReport, workerTurnError, hollowStop, hollowStopNote, workerOpError, WORKER_NUDGE, WORKER_NUDGES, releaseOrderInvocation, type WorkerOp, type FlowState, type PushRef } from "../src/core.ts";
27
+ import { ALLOW_REWRITE, applicableItems, openItemsNote, bashFlowGuard, checklistPending, checkoutInvocation, claimBlocks, featureBranchPrefix, FLOW_SHELL_HINT, flowShellInvocation, forcePushInvocation, freshenChecks, gitInvocation, guardBash, guardPath, mergeStyleInvocation, parsePushRefs, playbookTamper, playbookOnlyChange, pluginVersion, reflectionNudges, buildReflectBrief, parseReflectReport, renderReflectFindings, childSessionFiles, workerSteer, WORKER_STEER_AT, WORKER_SALVAGE, WORKER_SALVAGE_MS, WORKER_NUDGE_READONLY, stageReference, needsOperator, NEEDS_OPERATOR, nextHint, roadmapOpenCount, shouldTakeOverCompaction, stageGuidance, stateTamper, statusFor, sq, featureTmpDir, compactionStateBlock, withTmpDir, widgetLines, chipLabel, writeGuard, buildWorkerBrief, clampBudgetMin, parseWorkerReport, workerTurnError, hollowStop, hollowStopNote, workerOpError, WORKER_NUDGE, WORKER_NUDGES, releaseOrderInvocation, type WorkerOp, type FlowState, type PushRef } from "../src/core.ts";
28
28
  import { loadProject } from "../src/projectmd.ts";
29
29
  import { bashTimeout, requireTimeout, timeoutClass } from "../src/timeouts.ts";
30
30
  import { AGENT_MARK, operatorCommandAsks, operatorCommandCorrection, viewHeader, askLine, type GateView } from "../src/present.ts";
@@ -341,6 +341,7 @@ export default function devFlow(pi: ExtensionAPI) {
341
341
  commits: await git(`git log --oneline ${sq(cfg.defaultBranch)}..HEAD`),
342
342
  status: await git("git status --short"),
343
343
  checks: cfg.checkList.map((c) => ({ name: c.name, command: c.cmd })),
344
+ preamble: cfg.workerPreamble,
344
345
  note: String(params.note ?? ""),
345
346
  });
346
347
  // pi-web visibility needs both halves of the lineage: the id the Agents menu links the child
@@ -878,7 +879,7 @@ export default function devFlow(pi: ExtensionAPI) {
878
879
  if (prose) guidance.push(`Stage guidance (${prose.source}): ${prose.text}`);
879
880
  guidance.push("Stage reports: open with the stage line the last gate returned, pasted as is; a checkpoint closes with `Done:` / `Next steps:` (see the ground rules).");
880
881
  const pend = checklistPending(cfg, state, state.stage);
881
- if (pend) guidance.push(`Tier-2 checklist NOT yet confirmed (${pend} item(s)): ${applicableItems(cfg, state, state.stage).map((i) => i.text).join(" | ")}${state.stage === "release" ? " — release-stage items close with the operator's Finish? answer; no earlier gate records them" : ""}`);
882
+ if (pend) guidance.push(`Tier-2 checklist NOT yet confirmed — ${openItemsNote(cfg, state, state.stage)}${state.stage === "release" ? " — release-stage items close with the operator's Finish? answer; no earlier gate records them" : ""}`);
882
883
  // mid-feature is the wrong moment to divert into old reflections — they surface at the release
883
884
  // stage (finish runs the reflection), between flows, and in status/doctor
884
885
  if (state.stage === "release") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dev-flow",
3
- "version": "0.89.0",
3
+ "version": "0.90.1",
4
4
  "description": "Enforced feature workflow for Pi: plan → implement → pre-release → release, gated checkpoints, self-improvement reflections, one git worktree per feature, changelog + publish as part of the release",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -28,7 +28,9 @@ note). Other sessions' worktrees are theirs.
28
28
  deploy and the health probe against what it deployed, and returns
29
29
  `NEEDS-OPERATOR Verified?`. It never opens a dialog.
30
30
  - Another flow holds the dev port → `NEEDS-OPERATOR Dev port?` with free
31
- RAM/disk: ask, then re-run with `--port=<n>` or `--replace`.
31
+ RAM/disk: ask, stop, then re-run with `--port=<n>` or `--replace` on
32
+ their answer. "wait" means wait; a later "proceed" about the feature is
33
+ not a yes to replacing another flow's stack.
32
34
  - The health probe retries every 2s up to `healthWait` (default 30s); a
33
35
  service that needs a moment is not a broken deploy.
34
36
  2. Look at the change yourself, **keep the app running**, ask **Verified?**
@@ -19,7 +19,10 @@ friction only, never the same issue twice. `.dev-flow/reflections.md` holds
19
19
  - No flag → the wording decides and the printed line says why.
20
20
  - `flow reflect list` numbers the queue; `flow reflect move <n>
21
21
  --playbook|--code` re-files; `flow reflect done <n> ["<what fixed it>"]`
22
- checks one off; `flow reflect tidy` drops closed items.
22
+ checks one off; `flow reflect tidy` drops closed items. The numbers are
23
+ row numbers: checking items off leaves the others' numbers alone, so a
24
+ batch of `done` calls read off one `list` is safe; after `move` or `tidy`,
25
+ list again.
23
26
  - `flow doctor "<observation>"` prints an investigation brief without queueing.
24
27
  - The end-of-session reflection runs at finish (see [finish.md](finish.md)).
25
28
 
@@ -34,7 +34,10 @@ knobs · merge-policy state.
34
34
  the mode (`normal` default, or `--patch` / `--docs`), `--ui` when screens
35
35
  change, and the merge policy if the playbook has none —
36
36
  `flow start <slug> [--ui] [--patch|--docs] [--merge=<style>] --confirmed`.
37
- Never grant any of them yourself.
37
+ Never grant any of them yourself. When the operator's own request already
38
+ grants one ("start a docs flow"), that is their word: pass `--confirmed` on
39
+ the first call. After a refusal, only a message sent later counts, so a
40
+ `--confirmed` re-run right away is refused too. Ask once.
38
41
  - No merge policy → the gate refuses with `NEEDS-OPERATOR Merge policy?` and a
39
42
  suggestion read off the repo's history. Ask: squash, merge, rebase or any.
40
43
  The answer is written into `## release` once.
package/src/core.ts CHANGED
@@ -58,11 +58,13 @@ export interface FlowState {
58
58
  }
59
59
 
60
60
  /** Tier-2 item: operator prose; uiOnly items ("(ui)" in project.md) apply only to --ui features;
61
- * 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). */
62
63
  export interface ChecklistItem {
63
64
  text: string;
64
65
  uiOnly: boolean;
65
66
  versionedOnly?: boolean;
67
+ docs?: boolean;
66
68
  }
67
69
 
68
70
  export interface Commands {
@@ -128,6 +130,9 @@ export interface Config {
128
130
  bashTimeout: "require" | "inject";
129
131
  /** Operator safety rules from the project.md flow-guard block — stage-independent. */
130
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[];
131
136
  }
132
137
 
133
138
  export const DEFAULTS: Config = {
@@ -384,8 +389,8 @@ export function verifyGate(state: FlowState, cfg: Config, branch?: BranchState |
384
389
  : "nothing committed on the feature branch yet — commit as you go, verify proves a committed state",
385
390
  );
386
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`);
387
- const pend = checklistPending(cfg, state, "implement");
388
- 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`);
389
394
  return errs;
390
395
  }
391
396
 
@@ -555,8 +560,8 @@ export function preReleaseGate(state: FlowState, cfg: Config, prep: ReleasePrep)
555
560
  const errs: string[] = [];
556
561
  if (state.stage !== "pre-release") errs.push(`stage is "${state.stage}", the release gate only applies to "pre-release"`);
557
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`);
558
- const pend = checklistPending(cfg, state, "pre-release");
559
- 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`);
560
565
  if (prep.conflictMarkers?.length && !prep.noMarkerCheck)
561
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)` : ""}`);
562
567
  if (state.noVersion) {
@@ -623,7 +628,7 @@ export function unreleasedPending(content: string): boolean {
623
628
 
624
629
  export function checklistHash(items: ChecklistItem[]): string {
625
630
  return createHash("sha1")
626
- .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"))
627
632
  .digest("hex")
628
633
  .slice(0, 12);
629
634
  }
@@ -658,9 +663,38 @@ export function freshenChecks(state: FlowState, fp: string | null, keep: (name:
658
663
  return stale;
659
664
  }
660
665
 
661
- /** 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). */
662
688
  export function applicableItems(cfg: Config, state: FlowState, stage: string): ChecklistItem[] {
663
- 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(" | ")}`;
664
698
  }
665
699
 
666
700
  /** Items exist for the stage and current confirmation does not match their hash; returns pending count or 0. */
@@ -1763,6 +1797,10 @@ export interface ReflectItem {
1763
1797
  line: string;
1764
1798
  /** the note without checkbox and without the ` — attribution` tail */
1765
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;
1766
1804
  }
1767
1805
 
1768
1806
  /** Open items of reflections.md, each carrying the heading that owns it. Items above every known
@@ -1771,6 +1809,7 @@ export interface ReflectItem {
1771
1809
  export function reflectItems(text: string): ReflectItem[] {
1772
1810
  const out: ReflectItem[] = [];
1773
1811
  let section: KnownSection | "unfiled" = "unfiled";
1812
+ let row = 0;
1774
1813
  for (const raw of text.split("\n")) {
1775
1814
  const l = raw.trim();
1776
1815
  if (ANY_HEADING.test(l)) {
@@ -1778,12 +1817,25 @@ export function reflectItems(text: string): ReflectItem[] {
1778
1817
  section = h ? (h[1].toLowerCase() as KnownSection) : "unfiled";
1779
1818
  continue;
1780
1819
  }
1820
+ if (isDoneItem(l)) row++;
1781
1821
  if (!isOpenItem(l)) continue;
1782
- out.push({ section, line: l, body: reflectionBody(l) });
1822
+ out.push({ section, line: l, body: reflectionBody(l), n: ++row });
1783
1823
  }
1784
1824
  return out;
1785
1825
  }
1786
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
+
1787
1839
  /** Open items the file does not place in a known section — doctor names the count so a note that
1788
1840
  * would once have quietly migrated to `## playbook` on the next write gets moved on purpose. */
1789
1841
  export const reflectUnfiledCount = (text: string) => reflectItems(text).filter((i) => i.section === "unfiled").length;
@@ -1880,37 +1932,25 @@ export function reflectionRoutes(items: ReflectItem[], selfRepo: boolean): Refle
1880
1932
  });
1881
1933
  }
1882
1934
 
1883
- /** Move open item n (1-based over open items — the numbering `flow reflect list` prints) under
1884
- * `## section`. null = out of range; an item already in that section comes back unchanged, so the
1885
- * 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. */
1886
1938
  export function reflectMove(text: string, n: number, section: ReflectSection): string | null {
1939
+ const row = reflectRow(text, n);
1940
+ if (!row?.open) return null;
1887
1941
  const lines = text.split("\n");
1888
- let seen = 0;
1889
- let hit = -1;
1890
- for (let i = 0; i < lines.length; i++) {
1891
- if (!isOpenItem(lines[i])) continue;
1892
- if (++seen === n) {
1893
- hit = i;
1894
- break;
1895
- }
1896
- }
1897
- if (hit < 0) return null;
1898
- const [line] = lines.splice(hit, 1);
1942
+ const [line] = lines.splice(row.index, 1);
1899
1943
  return appendReflection(lines.join("\n"), [section], line.trim());
1900
1944
  }
1901
1945
 
1902
- /** Check open item `n` (the `flow reflect list` numbering) off: `- [x] … — fixed: <note>` — the convention
1903
- * 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`. */
1904
1948
  export function reflectDone(text: string, n: number, note: string): string | null {
1949
+ const row = reflectRow(text, n);
1950
+ if (!row?.open) return null;
1905
1951
  const lines = text.split("\n");
1906
- let seen = 0;
1907
- for (let i = 0; i < lines.length; i++) {
1908
- if (!isOpenItem(lines[i])) continue;
1909
- if (++seen !== n) continue;
1910
- lines[i] = `${lines[i].replace(/^(\s*)- \[ \] /, "$1- [x] ").trimEnd()} — fixed: ${note.trim()}`;
1911
- return lines.join("\n");
1912
- }
1913
- return null;
1952
+ lines[row.index] = `${lines[row.index].replace(/^(\s*)- \[ \] /, "$1- [x] ").trimEnd()} — fixed: ${note.trim()}`;
1953
+ return lines.join("\n");
1914
1954
  }
1915
1955
 
1916
1956
  /** What `flow doctor <note>` prints: the note is an investigation order, not an answer —
@@ -2232,7 +2272,10 @@ export function nextHint(state: FlowState, cfg: Config): string {
2232
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" : ""}`;
2233
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`;
2234
2274
  case "implement":
2235
- 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
+ }
2236
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`;
2237
2280
  case "pre-release": {
2238
2281
  // gh#198: the release call made with Verified? decides which prep this is
@@ -2372,6 +2415,8 @@ export interface WorkerBriefInput {
2372
2415
  commits: string; // `git log --oneline <base>..HEAD`
2373
2416
  status: string; // `git status --short`
2374
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[];
2375
2420
  note: string;
2376
2421
  }
2377
2422
 
@@ -2390,9 +2435,12 @@ export function buildWorkerBrief(o: WorkerBriefInput): string {
2390
2435
  `- Branch base: ${o.defaultBranch}`,
2391
2436
  `- Commits on the branch so far:\n${o.commits.trim() ? o.commits.trim().split("\n").map((l) => ` ${l}`).join("\n") : " (none)"}`,
2392
2437
  `- Uncommitted now: ${o.status.trim() ? `\n${o.status.trim().split("\n").map((l) => ` ${l}`).join("\n")}` : "clean"}`,
2393
- `- 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}`,
2394
2439
  "- You hold no flow tool: gates, checkpoints and the operator stay with the driving session.",
2395
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
+ : []),
2396
2444
  "## Your task",
2397
2445
  o.note.trim() || "(no note — do what the plan's next unfinished step asks)",
2398
2446
  "",
@@ -2414,6 +2462,7 @@ export function buildWorkerBrief(o: WorkerBriefInput): string {
2414
2462
  "## Contract",
2415
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.`,
2416
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.",
2417
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).",
2418
2467
  ];
2419
2468
  return [...head, ...contract].join("\n");
@@ -2626,7 +2675,7 @@ export interface ReflectBriefInput {
2626
2675
  * the operator decides fold or drop per finding in the driving session. */
2627
2676
  export function buildReflectBrief(o: ReflectBriefInput): string {
2628
2677
  const up = o.upstream || "(unknown — say so in the REPORT)";
2629
- 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)";
2630
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)";
2631
2680
  const digests = o.digests?.length ? o.digests.map((d) => ` - ${d.digest} (of ${path.basename(d.transcript)})`).join("\n") : "";
2632
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/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
@@ -123,7 +125,7 @@ function parseGuardRules(entries: { line: string; where: string }[], stage: stri
123
125
  }
124
126
 
125
127
  export function parseProjectMd(text: string): ParsedMd {
126
- 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: [] };
127
129
  let stage: string | null = null;
128
130
  const prose: Record<string, string[]> = {};
129
131
  let inFence: string | null = null; // "flow" | "flow-check" | other lang
@@ -192,6 +194,11 @@ export function parseProjectMd(text: string): ParsedMd {
192
194
  }
193
195
  }
194
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
+ }
195
202
  else if (inFence === "flow-guard") guardBody.push({ line, where });
196
203
  return;
197
204
  }
@@ -204,6 +211,7 @@ export function parseProjectMd(text: string): ParsedMd {
204
211
  inFence = "flow-check";
205
212
  checkName = lang.slice("flow-check".length).trim();
206
213
  } else if (lang === "flow-guard") inFence = "flow-guard";
214
+ else if (lang === "flow-worker") inFence = "flow-worker";
207
215
  else inFence = lang || "code";
208
216
  return;
209
217
  }
@@ -216,16 +224,19 @@ export function parseProjectMd(text: string): ParsedMd {
216
224
  if (!stage || stage === "global" || !MD_STAGES.includes(stage as MdStage)) return; // preamble/unknown → not injected
217
225
  const item = line.match(CHECK_ITEM);
218
226
  if (item) {
219
- // 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)
220
229
  let text = item[1].trim();
221
230
  let uiOnly = false;
222
231
  let versionedOnly = false;
223
- 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)) {
224
234
  if (q[1] === "ui") uiOnly = true;
235
+ else if (q[1] === "docs") docs = true;
225
236
  else versionedOnly = true;
226
237
  text = text.slice(q[0].length);
227
238
  }
228
- (p.checklist[stage] ??= []).push(versionedOnly ? { text, uiOnly, versionedOnly } : { text, uiOnly });
239
+ (p.checklist[stage] ??= []).push({ text, uiOnly, ...(versionedOnly ? { versionedOnly } : {}), ...(docs ? { docs } : {}) });
229
240
  return;
230
241
  }
231
242
  if (/^(#|```|<!--|\s*$)/.test(line) && !line.startsWith("### ")) return; // h1/html comments/blank are not prose
@@ -262,6 +273,7 @@ export function mdToConfig(p: ParsedMd): Config {
262
273
  ];
263
274
  c.checklist = p.checklist;
264
275
  c.prose = p.prose;
276
+ if (p.workerPreamble.length) c.workerPreamble = [...p.workerPreamble];
265
277
  return c;
266
278
  }
267
279
 
@@ -552,6 +564,7 @@ export function mdDigest(text: string): string {
552
564
  if (s === "global") {
553
565
  const rules = (["deny", "confirm", "protect", "forbid"] as const).flatMap((v) => p.guard[v].map((r) => `${v} ${r.pattern}`));
554
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`);
555
568
  }
556
569
  if (relStage && keys.file) {
557
570
  bits.push(`version in ${keys.file} → tag ${keys.pattern ?? "v{version}"}`);
@@ -560,7 +573,7 @@ export function mdDigest(text: string): string {
560
573
  }
561
574
  if (s === "pre-release" && !keys.file && !p.flow.release["versioning.file"]) bits.push("version: no version file set — releases cannot bump or tag");
562
575
  const items = p.checklist[s] ?? [];
563
- 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(" · ")}`);
564
577
  if (p.prose[s]) bits.push(`guidance: "${p.prose[s].replace(/\s+/g, " ").trim()}"`);
565
578
  if (bits.length) rows.push(`${label} — ${bits.join(" · ")}`);
566
579
  }
@@ -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)`;