pi-dev-flow 0.97.0 → 0.98.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,26 @@ Format: newest first. `Unreleased` collects what's merged but not yet tagged.
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.98.0] - 2026-11-29
8
+
9
+ **A `confirm` or `protect` rule asks in chat instead of a dialog that held the call for hours. Also: `flow guard` tests a playbook rule, a release call the operator never named is shown before it counts, a hand rebase keeps the Verified? word, and five smaller fixes to workers, briefs and cleanup.**
10
+
11
+ ### Changed
12
+ - **A `confirm` or `protect` rule never opens a dialog inside the agent's call** (fixes #289). The dialog held the call before the command ran, outside its own timeout: 2h53m, 14h43m and about 10 hours in three sessions while nobody was there, with nothing in the transcript to say why. A yes in it also never reached the agent, so one session asked the same question 12 times. Now the call is refused at once as `NEEDS-OPERATOR Run it?` with the rule's reason, and the agent asks you in chat. On your yes it re-runs the same command prefixed with `DEV_FLOW_CONFIRMED=1`, or repeats the same edit. The yes counts only once you have replied since the refusal, and only for that exact command or path. A worker is never granted one. Every rule a call trips is one question. A force push and a merge with no style flag are asked in chat the same way.
13
+
14
+ ### Added
15
+ - **`flow guard "<command>"` and `flow guard --path <file>`** name the playbook `flow-guard` rule a command or an edit would trip, through the same matcher the hooks use, and run nothing. A playbook no longer hand-imports `guardBash` from `src/core.ts` to test its own rules (gh#287).
16
+
17
+ ### Fixed
18
+ - **A release call you never named is shown to you before it counts.** When your Approve? answer names no kind (a bare "approve") and the agent passed `--version=<kind>` from its own proposal, the gate records it as the agent's proposal, says so, and shows it with Verified? to keep or change. Your answer there, or `flow bump <kind> --confirmed`, settles it. If a yolo skips Verified?, the pre-release hint says to ask the kind before cutting the release prep (gh#299).
19
+ - **A hand rebase no longer re-asks Release?** A rebase replays the verified commits under new ids, and the gate listed them as "landed after Verified?". It now compares diffs (`git patch-id`, with the changelog and version file left out): a replayed commit with the patch you verified rides under your Verified?, and a commit whose content changed still asks (gh#298).
20
+ - **Resuming a stopped publish no longer asks for a word already given.** The red-CI "publish stopped" message mentions "the operator's word" (for a real failure's way forward), and that wording re-armed the rule that refuses an unanswered `--confirmed`. After a flaky job was re-run green, the resume was refused and Release? asked again. A stopped or waiting publish now never counts as a question (gh#283).
21
+ - **Release? over changed code asks one question.** When code landed after Verified?, the Release? refusal now tells the agent to ask one thing: re-verify and ask Verified? if behaviour changed, since Release? then answers itself, or else ask Release? with the commits named. Asking Release? first and then re-verifying spent the answer (gh#288).
22
+ - **`flow_stage` with no `op` says what to pass.** It was refused with pi's bare `op: missing`. The schema now lets the call through, so the refusal names the field and the three ops (gh#286).
23
+ - **A worker brief gives its scratch dir as a real path.** It said `$TMPDIR`, which a worker's shell does not set, so `mkdir "$TMPDIR/x"` tried `/x`. The brief now names the feature's tmp dir and says the project playbook's scratch rule wins (gh#281).
24
+ - **A review worker no longer re-runs checks the driver already ran green.** A check that passed against the exact tree under review is marked green in the brief, with "do not re-run it". A read-only reviewer is no longer handed the health probe, since the driver owns the deploy (gh#285).
25
+ - **Empty feature folders are found and cleaned up.** A `.dev-flow/<slug>/` with no file anywhere inside was neither a feature nor a ghost, so nothing named it. `flow doctor` now lists it, and `flow init` removes it without asking once it is ten minutes old. A `plan/` with no file in it counts as empty, not as a ghost (gh#282).
26
+
7
27
  ## [0.97.0] - 2026-11-23
8
28
 
9
29
  **A standard flow asks two questions, Approve? and Verified?, and runs the rest to done. Release? answers itself over docs and test commits and a stale build. Finish files the closing reflection's own fold/drop recommendations and does release-stage items as work. Dev port? is asked only while another flow's deploy is under review.**
package/docs/gates.md CHANGED
@@ -67,7 +67,9 @@ the question also asks: *patch, minor or major release, or merge unreleased?* Yo
67
67
  with `--version=<kind>` or `--no-version`; an Approve? answer without it is refused and nothing is
68
68
  kept. Only the kind of step is recorded, never a number: the number is counted from the newest tag
69
69
  when the release runs, so a flow that released first moves yours along instead of colliding with it.
70
- No later gate asks the call again. You can change it at any point until the tag is cut: say so,
70
+ No later gate asks the call again. When your Approve? answer names no kind (a bare "approve") and the
71
+ agent passed one anyway, the gate records it as the agent's proposal: the output says so, Verified?
72
+ shows it to you to keep or change, and your answer there settles it. You can change it at any point until the tag is cut: say so,
71
73
  and the agent runs `flow bump <patch|minor|major|none> --confirmed`, or passes
72
74
  `--version=<kind>` / `--no-version` on a confirmed `verify` or `release` call. A fold flow — one started with `--reflections`, as `flow reflect plan` prints it — is never asked the call: on a versioned project it always merges unreleased, and `--version=<kind>` or `flow bump <kind>` is refused. A flow approved by an
73
75
  older dev-flow, with no call on record, is asked at Verified? instead.
@@ -150,7 +152,9 @@ Proves the branch is ready to ship:
150
152
  **Release? usually answers itself** (`ask = on-change`, the default): your Verified? is the release
151
153
  word. That happens when your call is on record and only release prep (bump, changelog), docs
152
154
  (`docs/`, README, CHANGELOG) or tests changed since Verified?; the output names any docs/test commit
153
- that rode under it. A `--confirmed` given before the gate asked doesn't count where a question carries news you haven't
155
+ that rode under it. A hand rebase replays the verified commits under new ids: a commit whose diff
156
+ (changelog and version file left out) matches one you verified rides under your Verified? too, while
157
+ a commit whose content changed still asks. A `--confirmed` given before the gate asked doesn't count where a question carries news you haven't
154
158
  seen (commits after Verified? on a yolo flow, or a stale build): the gate asks first. A yolo held back
155
159
  only by `yolo = until-release` is asked like any flow, so your chat answer stands on the first call.
156
160
 
@@ -255,8 +259,11 @@ To drop an unreleased feature, use `flow abort` instead.
255
259
  manages `.dev-flow/roadmap.md`. `pick` stamps an item for `flow start <slug>`, and `finish` checks
256
260
  it off when the feature ships.
257
261
  - `flow doctor ["<note>"]` is a read-only health report: playbook drift, dead commands, ghost
258
- folders, orphan worktrees and branches, and a review of every open reflection. It writes nothing,
259
- so it's safe at any stage and in CI.
262
+ folders, empty feature folders, orphan worktrees and branches, and a review of every open
263
+ reflection. It writes nothing, so it's safe at any stage and in CI. `flow init` removes an empty
264
+ feature folder (no file anywhere inside) without asking, once it is ten minutes old.
265
+ - `flow guard "<command>"` / `flow guard --path <file>` names the playbook `flow-guard` rule a
266
+ command or an edit would trip, or says none does. It reads only.
260
267
 
261
268
  ## status, abort, help, version
262
269
 
@@ -52,10 +52,18 @@ playbook, dev-flow stays silent.
52
52
 
53
53
  **Your own rules.** The `deny` / `confirm` / `protect` / `forbid` rules in your playbook's
54
54
  `flow-guard` block run on every bash command and every edit, at every stage, before dev-flow's own
55
- checks. A block always shows the reason you wrote. See the [playbook](playbook.md).
56
-
57
- **Force pushes ask you.** `git push --force` / `-f` / `--force-with-lease` needs your OK. The
58
- refusal prints the prefix that marks it as approved: `DEV_FLOW_ALLOW_REWRITE=1`.
55
+ checks. A block always shows the reason you wrote. See the [playbook](playbook.md). To test a rule
56
+ before an agent meets it, `flow guard "<command>"` (or `flow guard --path <file>`) names the rule that
57
+ fires, with the same matcher the hooks use, and runs nothing.
58
+
59
+ **Rules that ask you never wait on a dialog.** A `confirm` or `protect` rule refuses the call at
60
+ once with your reason, and the agent asks you in chat. On your yes it re-runs the command prefixed
61
+ with `DEV_FLOW_CONFIRMED=1` (or repeats the edit). The prefix counts only after you replied, and only
62
+ for the command it was asked about. A dialog used to hold the call, outside its own timeout, for
63
+ hours while nobody was there, and a yes in it never reached the agent, so it asked again.
64
+
65
+ **Force pushes ask you.** `git push --force` / `-f` / `--force-with-lease` needs your OK, asked in
66
+ chat. The refusal prints the prefix that marks it as approved: `DEV_FLOW_ALLOW_REWRITE=1`.
59
67
 
60
68
  **Shell calls can't hang.** The model often omits a timeout, so a `gh` waiting on a prompt could
61
69
  freeze a session for hours. A shell call without a timeout gets a default for its kind:
package/docs/playbook.md CHANGED
@@ -141,12 +141,17 @@ forbid docker/secrets :: secret storage
141
141
  | Verb | Applies to | What happens |
142
142
  |---|---|---|
143
143
  | `deny` | a bash command (regex) | blocked |
144
- | `confirm` | a bash command (regex) | asks you; blocked when there's no UI to ask |
145
- | `protect` | an edit/write path | asks you; blocked when there's no UI |
144
+ | `confirm` | a bash command (regex) | refused with your reason; the agent asks you in chat, and on your yes re-runs it prefixed with `DEV_FLOW_CONFIRMED=1` |
145
+ | `protect` | an edit/write path | refused with your reason; the agent asks you in chat, and on your yes repeats the edit |
146
146
  | `forbid` | an edit/write path | blocked |
147
147
 
148
148
  Tips:
149
- - Text after ` :: ` is the reason, shown when the rule fires.
149
+ - Text after ` :: ` is the reason, shown when the rule fires. Name the safe form in it (`scope it with
150
+ --no-deps`): the agent reads it on every refusal, so it can use that form instead of asking you.
151
+ - A `confirm` or `protect` never opens a dialog. The yes counts only after you reply in chat, and it
152
+ covers that exact command or path. When a safe form always exists, prefer `deny` with the safe form
153
+ in the reason: the agent fixes the command itself and you are never asked.
154
+ - `flow guard "<command>"` or `flow guard --path <file>` shows which rule fires, without running anything.
150
155
  - `flow_stage` workers get these rules in their brief. A worker has no one to ask, so `confirm` and
151
156
  `protect` are refusals for it, and the reason you write is what it reads.
152
157
  - An invalid regex makes the playbook invalid, and `flow init` refuses it.
@@ -24,17 +24,17 @@ 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, 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, workerSteerAt, recoverReflectRows, assistantTexts, 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, worktreeWorkGuard, flowArgsShapeError, type WorkerOp, type FlowState, type PushRef } from "../src/core.ts";
27
+ import { ALLOW_REWRITE, OPERATOR_CONFIRMED, confirmedPrefix, guardConfirmVerdict, type GuardAsk, 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, workerSteerAt, recoverReflectRows, assistantTexts, 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, worktreeWorkGuard, flowArgsShapeError, 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";
31
31
  import { Text } from "@earendil-works/pi-tui";
32
32
  import { CONTEXT_EMITTED, COPIES, GATE_HELP, SELF_BUILD, SKILL_DIR, type Ui, WEB_CHIP_KEYS, LEGACY_CHIP_KEYS, nextChipKeys, baseSeams, bindings, boundFeature, claimBlocker, claimFile, compacting, compactionTakeover, coreInjected, coreStale, currentBranch, dfDir, featDir, featureRefs, flowCompactInstructions, flowRoot, guardsAreMine, initiated, lastContext, loadedVersion, maybeCompactNow, noteFriction, now, readClaim, readReflections, readReflectionsText, readRoadmap, readState, registerCopy, releaseSession, sessionKey, sh, skillCore, unfinishedStates, worktreeAbs, writeClaim, writeState } from "../src/runtime/base.ts";
33
- import { type Session, presentRun } from "../src/runtime/checks.ts";
33
+ import { type Session, presentRun, worktreeFingerprint } from "../src/runtime/checks.ts";
34
34
  import { isSelfRepo } from "../src/runtime/setup.ts";
35
35
  import { foldView, pluginUpstream } from "../src/runtime/reflect.ts";
36
36
  import { type FlowHooks, runFlow } from "../src/runtime/gates.ts";
37
- import { grantCheck, grantRecord, isFriction, newGrantLedger, operatorMessageCount, type RefusalStreak } from "../src/runtime/grants.ts";
37
+ import { grantCheck, grantRecord, isFriction, lastOperatorText, newGrantLedger, operatorMessageCount, type RefusalStreak } from "../src/runtime/grants.ts";
38
38
  import { PIWEB_SUBAGENT, WORKER_TOOLS, piwebLiveClaim, piwebStamp, piwebWorkerMeta, reflectSeams, sessionHeaders, stageWorkerSpawn, workerName, workerSessions, workerTiming, writeTranscriptDigests } from "../src/runtime/workers.ts";
39
39
  export { compactionTakeover } from "../src/runtime/base.ts";
40
40
  export { reflectSeams, stageWorkerSpawn, workerTiming } from "../src/runtime/workers.ts";
@@ -86,12 +86,6 @@ function refreshStatus(ctx: ExtensionContext, root: string): void {
86
86
  }
87
87
 
88
88
 
89
- /** A project confirm rule with no operator present is a block — a hidden confirmation is not a confirmation. */
90
- async function askOperator(ctx: ExtensionContext, what: string, why: string): Promise<string | null> {
91
- if (!ctx.hasUI) return needsOperator(`${why}: this needs an operator confirmation and no UI is available — ask them, or run it yourself outside Pi`);
92
- const ok = await ctx.ui.confirm("dev-flow project rule", `${what}\n\n${why}\n\nProceed?`);
93
- return ok ? null : `operator declined — ${why}`;
94
- }
95
89
 
96
90
  /** What a kill by dev-flow's own timeout tells the agent (and the operator reading the transcript). */
97
91
  export function timeoutKillNote(armed: { s: number; cls: string }): string {
@@ -126,6 +120,7 @@ export default function devFlow(pi: ExtensionAPI) {
126
120
  key,
127
121
  slug: bindings.get(key) ?? null,
128
122
  operatorMessages: operatorMessageCount((() => { try { return ctx.sessionManager?.getBranch(); } catch { return null; } })()),
123
+ operatorText: lastOperatorText((() => { try { return ctx.sessionManager?.getBranch(); } catch { return null; } })()),
129
124
  bind: (slug) => {
130
125
  const prev = bindings.get(key);
131
126
  bindings.set(key, slug);
@@ -148,6 +143,22 @@ export default function devFlow(pi: ExtensionAPI) {
148
143
 
149
144
  /** Which gate asked for the operator's word, and when features started — per session (gh#190). */
150
145
  const grantLedger = newGrantLedger();
146
+ /** Per session: the last guard confirm refused, so the operator's answer can be matched to it (gh#289). */
147
+ const guardAsks = new Map<string, GuardAsk>();
148
+ /** A call that trips confirm rule(s): never a dialog — run on the operator's chat answer, else refuse with the reason. */
149
+ const askOperator = (ctx: ExtensionContext, key: string, o: { target: string; what: string; whys: string[]; prefixed: boolean; edit: boolean }): string | null => {
150
+ const users = (() => {
151
+ try {
152
+ return operatorMessageCount(ctx.sessionManager?.getBranch());
153
+ } catch {
154
+ return null;
155
+ }
156
+ })();
157
+ const v = guardConfirmVerdict({ ...o, users, prev: guardAsks.get(key), worker: isWorkerSession(ctx) });
158
+ if (v.allow) return null;
159
+ if (v.record) guardAsks.set(key, v.record);
160
+ return v.reason;
161
+ };
151
162
  /** Gates that refused in a row, per session — what turns a failing check into friction (see isFriction). */
152
163
  const refusalStreak: RefusalStreak = new Map();
153
164
 
@@ -362,7 +373,14 @@ export default function devFlow(pi: ExtensionAPI) {
362
373
  defaultBranch: cfg.defaultBranch,
363
374
  commits: await git(`git log --oneline ${sq(cfg.defaultBranch)}..HEAD`),
364
375
  status: await git("git status --short"),
365
- checks: st.docs ? [] : cfg.checkList.map((c) => ({ name: c.name, command: c.cmd })),
376
+ checks: st.docs
377
+ ? []
378
+ : await (async () => {
379
+ // green only when proven against this tree: a record with no fingerprint is not proof (gh#285)
380
+ const fp = wop === "review" ? await worktreeFingerprint(work) : null;
381
+ return cfg.checkList.map((c) => ({ name: c.name, command: c.cmd, green: !!fp && !!st.checks[c.name]?.ok && st.checks[c.name]?.wt === fp }));
382
+ })(),
383
+ scratchDir: ((d) => (mkdirSync(d, { recursive: true }), d))(featureTmpDir(dfDir(root), st.slug)),
366
384
  preamble: cfg.workerPreamble,
367
385
  docs: !!st.docs,
368
386
  guard: cfg.guard,
@@ -555,7 +573,9 @@ export default function devFlow(pi: ExtensionAPI) {
555
573
  'Optional: hand a slice of work to a fresh pi session so this conversation stays lean. op "implement" (stage implement) — the worker edits and commits a slice on the feature branch; op "review" (implement or pre-release) — a fresh read-only reviewer that returns findings and a PASS/FAIL verdict (the verdict is advisory; that a review ran is recorded — run it in implement once flow check is green: flow verify requires a review on record before it asks Verified?); op "reflect" (any stage; flow finish runs it itself before cleanup) — a fresh read-only reviewer of this session\'s transcript and every worker transcript that returns classified reflection findings (docs / code / plugin) with a fold-or-drop recommendation each, for the operator to decide. The plan path, branch, commits so far and the project checks are added to the brief automatically — `note` is just the slice: what to do, operator answers and decisions the worker cannot see. The worker holds no flow tool; gates and checkpoints stay with you. Delegate an implement slice when it is in the plan, provable by flow check, needs no operator input mid-slice and is big enough (≈4+ files or heavy reading) to crowd this context; small work, small fixes, mid-debug work, operator-judged work and final integration stay inline (criteria: references/implement.md). In pi-web the worker appears in the session\'s Agents menu as a subagent (running while it works, then its final status); the opened transcript holds its report.',
556
574
  promptSnippet: 'flow_stage(op: "implement"|"review"|"reflect", note, label?) — optional fresh-session worker for a big implement slice, an independent review, or a reflection (flow finish runs the closing one itself); gates stay with you; in pi-web workers show up as subagents in the Agents menu',
557
575
  parameters: Type.Object({
558
- op: Type.String({ description: '"implement" (a worker edits + commits a slice), "review" (read-only reviewer, findings + verdict) or "reflect" (read-only reviewer of the session transcripts, reflection findings + fold/drop recommendations)' }),
576
+ // required in practice, optional in the schema: a missing op then reaches workerOpError, which says what to
577
+ // pass, instead of pi's bare "op: missing" refusal (gh#286)
578
+ op: Type.Optional(Type.String({ description: 'Required. "implement" (a worker edits + commits a slice), "review" (read-only reviewer, findings + verdict) or "reflect" (read-only reviewer of the session transcripts, reflection findings + fold/drop recommendations)' })),
559
579
  note: Type.String({ description: "The slice: what to do and anything from this conversation the worker must know (operator answers, decisions). Facts (plan path, commits, checks) are added for you." }),
560
580
  label: Type.Optional(Type.String({ description: "A few words naming this delegation, shown in the worker's session name." })),
561
581
  budgetMin: Type.Optional(Type.Number({ description: "Wall-clock budget in minutes (5-180). Default 60 implement; 30 review, +10 per 500 changed lines past 500 (up to 90); 20 reflect, +5 per 250 KB of transcript past 250 KB (up to 60). Past it the worker is interrupted." })),
@@ -730,7 +750,8 @@ export default function devFlow(pi: ExtensionAPI) {
730
750
  const pv = guardPath(abs, ctx.cwd, cfg.guard);
731
751
  if (pv.block) return { block: true, reason: pv.block };
732
752
  if (pv.confirm) {
733
- const why = await askOperator(ctx, `Editing ${path.relative(ctx.cwd, abs) || abs}`, pv.confirm);
753
+ const rel = path.relative(ctx.cwd, abs) || abs;
754
+ const why = askOperator(ctx, key, { target: `edit:${abs}`, what: `Editing ${rel}`, whys: [pv.confirm], prefixed: false, edit: true });
734
755
  if (why) return { block: true, reason: why };
735
756
  }
736
757
  // only an unbound session's main-checkout write ever reads it — ask git just then (gh#175)
@@ -748,8 +769,17 @@ export default function devFlow(pi: ExtensionAPI) {
748
769
  // and the operator's deny outranks dev-flow's own stage verdicts
749
770
  const gv = guardBash(command, cfg.guard);
750
771
  if (gv.block) return { block: true, reason: gv.block };
751
- for (const r of gv.confirms) {
752
- const why = await askOperator(ctx, command, r.why || `project rule ${r.pattern}`);
772
+ // the playbook's merge style is enforced where the decision is actually made: gh/glab merging the PR.
773
+ // An explicit contradiction is a hard block, a merge with no style flag (the forge default decides)
774
+ // is a confirmation. No policy in the playbook → no new verdicts at all.
775
+ const mv = mergeStyleInvocation(command, cfg.release.merge);
776
+ if (mv.block) return { block: true, reason: mv.block };
777
+ // every confirm this call trips is one question to the operator, not one per rule (gh#289)
778
+ const whys = [...gv.confirms.map((r) => r.why || `project rule ${r.pattern}`), ...(mv.confirm ? [mv.confirm] : [])];
779
+ if (whys.length) {
780
+ const cp = confirmedPrefix(command);
781
+ const short = cp.target.length > 160 ? `${cp.target.slice(0, 160)}…` : cp.target;
782
+ const why = askOperator(ctx, key, { target: cp.target, what: `\`${short}\``, whys, prefixed: cp.prefixed, edit: false });
753
783
  if (why) return { block: true, reason: why };
754
784
  }
755
785
  // `flow` in a shell is a 127 with no pointer, so the mistake repeated — name the call that works
@@ -758,19 +788,9 @@ export default function devFlow(pi: ExtensionAPI) {
758
788
  if (mustStateTimeout) return { block: true, reason: requireTimeout(command)! };
759
789
  // a forced push rewrites history CI and other sessions already have. dev-flow asks the operator
760
790
  // itself so a project never needs a blunt `--force` deny of its own (#82, #83)
761
- if (forcePushInvocation(command)) {
762
- const why = await askOperator(ctx, command, `a forced push rewrites a pushed branch — CI and other sessions lose these commits (with the operator's word, prefix the push with ${ALLOW_REWRITE})`);
763
- if (why) return { block: true, reason: why };
764
- }
765
- // the playbook's merge style is enforced where the decision is actually made: gh/glab merging the PR.
766
- // An explicit contradiction is a hard block, a merge with no style flag (the forge default decides)
767
- // is a confirmation. No policy in the playbook → no new verdicts at all.
768
- const mv = mergeStyleInvocation(command, cfg.release.merge);
769
- if (mv.block) return { block: true, reason: mv.block };
770
- if (mv.confirm) {
771
- const why = await askOperator(ctx, command, mv.confirm);
772
- if (why) return { block: true, reason: why };
773
- }
791
+ // no dialog here either (gh#289): the refusal names the prefix that carries the operator's word
792
+ if (forcePushInvocation(command))
793
+ return { block: true, reason: needsOperator("a forced push rewrites a pushed branch — CI and other sessions lose these commits", "Force-push?", `ask the operator in chat; on their yes, prefix the push with ${ALLOW_REWRITE}`) };
774
794
  // shipping on the forge (PR merge, release page) is release-stage work for a bound feature
775
795
  if (/\b(?:gh|glab)\b/.test(command)) {
776
796
  const ro = releaseOrderInvocation(command, boundFeature(guardRoot, key)?.stage ?? null);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dev-flow",
3
- "version": "0.97.0",
3
+ "version": "0.98.0",
4
4
  "description": "Enforced feature workflow for Pi: plan → implement → pre-release → release, gated checkpoints, self-improvement reflections, one git worktree per feature, changelog + publish as part of the release",
5
5
  "type": "module",
6
6
  "keywords": [
package/src/core.ts CHANGED
@@ -56,6 +56,9 @@ export interface FlowState {
56
56
  /** when flow verify at pre-release asked Verified? over review fixes; cleared by the answer — flow release refuses while it is set */
57
57
  reverifyAsked?: string;
58
58
  releaseOnly?: boolean; // verify found nothing on the branch but unreleased work on main: this flow only cuts the version (#161)
59
+ /** gh#299: the release call came from the agent's --version on a confirmed Approve? whose operator answer named
60
+ * no kind — a proposal, not the operator's word. Shown with Verified?, cleared by their answer or flow bump. */
61
+ versionProposed?: boolean;
59
62
  versionChoice?: string; // the operator's release call, recorded with Approve?: patch | minor | major (a decision, never a number: counted from the newest tag at release, so a parallel flow taking the number moves it), "next" (playbook version = versioned: any bump past the last tag) or "unreleased"; any gate call before the tag can change it
60
63
  versionFrom?: string; // the manifest version when the call was recorded — only for the hint's "as things stand" number; the gate counts from the newest tag
61
64
  /** the session and its operator-message count when Verified? moved this flow to pre-release (gh#254): under
@@ -1361,6 +1364,51 @@ export function localDefaultAhead(o: { defaultBranch: string; checkoutBranch: st
1361
1364
  * DEV_FLOW_ALLOW_MAIN: the guard prints it, the operator grants it, the agent types it. (#83) */
1362
1365
  export const ALLOW_REWRITE = "DEV_FLOW_ALLOW_REWRITE=1";
1363
1366
 
1367
+ /** The operator's yes to a playbook `confirm` rule, spelled on the retried command (gh#289). A guard confirm
1368
+ * never opens a dialog inside the agent's tool call — that held calls silently for hours, past their own
1369
+ * timeout — and a dialog's yes never reached the agent, so it repeated the same command. The guard refuses at
1370
+ * once with the reason; the agent asks in chat; the prefix counts only once an operator message followed. */
1371
+ export const OPERATOR_CONFIRMED = "DEV_FLOW_CONFIRMED=1";
1372
+
1373
+ /** A command carrying the prefix as its leading assignment, and the command it judges (prefix removed). */
1374
+ export function confirmedPrefix(command: string): { prefixed: boolean; target: string } {
1375
+ const t = command.trim();
1376
+ const m = t.match(/^DEV_FLOW_CONFIRMED=1\s+/);
1377
+ return m ? { prefixed: true, target: t.slice(m[0].length).trim() } : { prefixed: false, target: t };
1378
+ }
1379
+
1380
+ /** The last confirm a session was refused: what it was for, and the operator-message count then. */
1381
+ export interface GuardAsk {
1382
+ target: string;
1383
+ users: number | null;
1384
+ }
1385
+
1386
+ /** The verdict on a call that trips confirm rule(s): run (the operator answered this exact call), or a refusal
1387
+ * telling the agent to ask in chat, with the ask to record. `edit`: an edit has no command to prefix — a repeat
1388
+ * of the same edit after an operator message is the answer. A worker has no operator: never granted. */
1389
+ export function guardConfirmVerdict(o: { target: string; what: string; whys: string[]; prefixed: boolean; edit: boolean; users: number | null; prev: GuardAsk | undefined; worker: boolean }): { allow: true } | { allow: false; reason: string; record: GuardAsk | null } {
1390
+ const why = o.whys.join("; ");
1391
+ if (o.worker) return { allow: false, reason: `project rule: ${why} — it needs the operator's yes, and a worker has no operator: do not run it or work around it; name it under \`checks not run:\` in the REPORT`, record: null };
1392
+ const claims = o.edit || o.prefixed;
1393
+ const same = !!o.prev && o.prev.target === o.target;
1394
+ // no transcript to count (users null): a typed prefix is the agent's explicit claim and is taken, as --confirmed is
1395
+ // (grantCheck); a repeated edit claims nothing out loud, so it needs a counted operator reply
1396
+ const counted = o.users !== null && o.prev?.users !== null && o.prev !== undefined && o.users > o.prev.users;
1397
+ const answered = same && (counted || (!o.edit && (o.users === null || o.prev!.users === null)));
1398
+ if (claims && answered) return { allow: true };
1399
+ const retry = o.edit ? "repeat the same edit" : `re-run the same command prefixed with ${OPERATOR_CONFIRMED}`;
1400
+ const early = claims && same ? ` The operator has said nothing since the guard asked — ${o.edit ? "the repeat" : "the prefix"} counts only after their reply.` : o.prefixed ? ` ${OPERATOR_CONFIRMED} answers a refusal of this exact command; there was none, so this is the ask.` : "";
1401
+ return {
1402
+ allow: false,
1403
+ record: { target: o.target, users: o.users },
1404
+ reason: needsOperator(
1405
+ `${o.what} trips a project rule: ${why}.${early}`,
1406
+ o.edit ? "Edit it?" : "Run it?",
1407
+ `ask the operator in chat: name the ${o.edit ? "file" : "command"} and the rule's reason, and offer a form that avoids the rule if there is one. On their yes, ${retry}. A form that avoids the rule runs without asking.`,
1408
+ ),
1409
+ };
1410
+ }
1411
+
1364
1412
  /** True when a segment force-pushes: `git push` carrying a force flag (`--force`, `--force-with-lease…`,
1365
1413
  * `-f`, `-uf`). Decided on the verb per segment, not on a flag anywhere after `git` — `filter-branch
1366
1414
  * --force` rewrites a local copy and `git show -f` lists files, and a blunt flag-only deny blocks both,
@@ -2697,6 +2745,8 @@ function stageHint(state: FlowState, cfg: Config): string {
2697
2745
  if (vc === "unreleased")
2698
2746
  return `${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)` : ""}; show the PR summary, then run flow release${gateAsks}`;
2699
2747
  const prep = [cfg.release.changelog ? `prepare ${cfg.release.changelog} (fold Unreleased lines verbatim)` : "", cfg.versioning.file ? `bump version in ${cfg.versioning.file}${isBumpKind(vc) ? ` one ${vc} step past the newest tag (${bumpVersion(state.versionFrom, vc) ?? `the next ${vc}`} as of approval — a flow that released since moves it; flow release names the number)` : ""}` : ""].filter(Boolean).join(" and ");
2748
+ // gh#299: a proposal the operator never saw (a yolo skipped Verified?) is confirmed before the prep is cut
2749
+ if (vc && prep && state.versionProposed) return `${review}fix must/should, update docs; the release call ${vc} is the agent's proposal, not the operator's word — ask them the kind (patch, minor or major; flow bump <kind> --confirmed on a change) before you ${prep}; show the PR summary, version and changelog, then run flow release${gateAsks}`;
2700
2750
  if (vc && prep) return `${review}fix must/should${state.docs ? "" : " (a fix that changes behaviour: flow verify redeploys and re-asks Verified? over it)"}, update docs, ${prep}; show the PR summary, version and changelog, then run flow release${gateAsks}`;
2701
2751
  if (state.docs && prep) return `${review}fix must/should; a docs flow usually ships unversioned — ask the operator (flow release --no-version on their word); versioned instead: ${prep}; then run flow release${gateAsks}`;
2702
2752
  return `${review}fix must/should${state.docs ? "" : " (a fix that changes behaviour: flow verify redeploys and re-asks Verified? over it)"}, update docs${prep ? `, ${prep}` : ""}; show the PR summary, version and changelog, then run flow release${gateAsks}`;
@@ -2864,6 +2914,7 @@ export function defaultBudgetMin(op: WorkerOp, size: WorkerSize = {}): number {
2864
2914
 
2865
2915
  /** Why an op is not legal for a feature at this stage, or null. */
2866
2916
  export function workerOpError(op: string, stage: Stage): string | null {
2917
+ if (!op) return `op is missing — pass it as its own field beside note: flow_stage({ op: "implement" | "review" | "reflect", note: "…" }). implement: a worker edits and commits a slice; review: a fresh read-only reviewer; reflect: a fresh reviewer of this session's transcripts`;
2867
2918
  if (op !== "implement" && op !== "review" && op !== "reflect") return `unknown op "${op}" — flow_stage ops: implement (a worker edits and commits a slice), review (a fresh read-only reviewer), reflect (a fresh reviewer of this session's transcripts)`;
2868
2919
  const ok = WORKER_OP_STAGES[op];
2869
2920
  return ok.includes(stage) ? null : `op "${op}" runs at ${ok.join(" or ")} — the feature is at ${stage}`;
@@ -2878,7 +2929,11 @@ export interface WorkerBriefInput {
2878
2929
  defaultBranch: string;
2879
2930
  commits: string; // `git log --oneline <base>..HEAD`
2880
2931
  status: string; // `git status --short`
2881
- checks: { name: string; command: string }[];
2932
+ /** `green`: the driver's own flow check passed against this exact tree (fingerprint match) — a reviewer reads
2933
+ * that record instead of re-running the suite (gh#285) */
2934
+ checks: { name: string; command: string; green?: boolean }[];
2935
+ /** the feature's tmp dir as a literal path: a worker shell has no TMPDIR of its own (gh#281) */
2936
+ scratchDir?: string;
2882
2937
  /** the playbook's `flow-worker` lines (gh#201): setup a worker needs before any project check can run */
2883
2938
  preamble?: string[];
2884
2939
  /** a --docs flow: the gates skip every project command, and no setup ran in the worktree — the brief hands out none (gh#211) */
@@ -2910,7 +2965,18 @@ function workerGuardLines(guard: GuardRules | undefined): string[] {
2910
2965
  /** The facts every worker needs, so the driver's note can be just the slice. The plan path is absolute:
2911
2966
  * it lives in the MAIN checkout's gitignored .dev-flow/, never inside the worktree. */
2912
2967
  export function buildWorkerBrief(o: WorkerBriefInput): string {
2913
- const checks = o.checks.length ? o.checks.map((c) => `- ${c.name}: \`${c.command}\``).join("\n") : "- (the playbook defines no tier-1 commands)";
2968
+ // a read-only reviewer does not own the stack: the health probe answers a question it was told not to touch (gh#285)
2969
+ const listed = o.op === "review" ? o.checks.filter((c) => c.name !== "health") : o.checks;
2970
+ const checks = listed.length
2971
+ ? listed.map((c) => `- ${c.name}: \`${c.command}\`${o.op === "review" && c.green ? " — green at this tree per the driver's flow check: do not re-run it" : ""}`).join("\n")
2972
+ : "- (the playbook defines no tier-1 commands)";
2973
+ const allGreen = o.op === "review" && listed.length > 0 && listed.every((c) => c.green);
2974
+ const checksHead =
2975
+ o.op === "review"
2976
+ ? allGreen
2977
+ ? "- Project checks (all green at this tree per the driver's flow check — do not re-run the suite; reproduce a specific claim with a targeted test instead):"
2978
+ : `- Project checks (run only the ones not marked green${o.preamble?.length ? ", in a shell that ran the setup below first" : ""}; a green one ran against this exact tree):`
2979
+ : `- Project checks (run them before you report${o.preamble?.length ? ", in a shell that ran the setup below first" : ""}):`;
2914
2980
  const head = [
2915
2981
  `You are a ${o.op === "implement" ? "stage worker implementing a slice" : "fresh, independent reviewer"} for dev-flow feature \`${o.slug}\`.`,
2916
2982
  "",
@@ -2924,9 +2990,11 @@ export function buildWorkerBrief(o: WorkerBriefInput): string {
2924
2990
  `- Uncommitted now: ${o.status.trim() ? `\n${o.status.trim().split("\n").map((l) => ` ${l}`).join("\n")}` : "clean"}`,
2925
2991
  o.docs
2926
2992
  ? "- Project checks: none — this is a docs flow. The gates skip the project's commands and no setup ran in this worktree (no installed dependencies): do not install, build or run the test suite; check the docs against the code by reading."
2927
- : `- Project checks (run them before you report${o.preamble?.length ? ", in a shell that ran the setup below first" : ""}):\n${checks}`,
2993
+ : `${checksHead}\n${checks}`,
2928
2994
  "- You hold no flow tool: gates, checkpoints and the operator stay with the driving session.",
2929
- "- Scratch goes in $TMPDIR (the feature's tmp dir); remove what you create there — `d=$(mktemp -d) && …; rm -rf \"$d\"`.",
2995
+ // gh#281: TMPDIR is not set in a worker's shell, so "$TMPDIR/x" became "/x"; and a playbook may require
2996
+ // scratch elsewhere (inside the worktree, so the toolchain resolves from it) — its rule wins
2997
+ `- Scratch: ${o.scratchDir ? `\`${o.scratchDir}\` (the feature's tmp dir — use this path; $TMPDIR is not set in your shell)` : "a `mktemp -d` dir"}; remove what you create. When the project's playbook names another scratch location, the playbook wins.`,
2930
2998
  "",
2931
2999
  ...workerGuardLines(o.guard),
2932
3000
  ...(o.preamble?.length && !o.docs
@@ -2951,7 +3019,7 @@ export function buildWorkerBrief(o: WorkerBriefInput): string {
2951
3019
  ]
2952
3020
  : [
2953
3021
  "## Contract",
2954
- `- 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.`,
3022
+ `- Check, don't fix: read ${o.planFile ? "the plan" : "the task"}, the diff (\`git diff ${o.defaultBranch}...HEAD\`) and the code; run the checks not already green and any probe that proves a claim. Change no files, make no commits.`,
2955
3023
  "- Look for correctness bugs, claims in docs/changelog the code does not back, missing tests for risky paths, and plan items not delivered.",
2956
3024
  "- 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.",
2957
3025
  "- 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).",
package/src/projectmd.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  * tier 3: every other line — prose injected to the agent when its stage begins
6
6
  * Parsing is pure and never fatal: unknown stages/keys and odd syntax become warnings.
7
7
  */
8
- import { existsSync, readdirSync, readFileSync } from "node:fs";
8
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
9
9
  import path from "node:path";
10
10
  import { applyAnswer, type ChecklistItem, type Config, DEFAULTS, healthProbe, parseMergeStyle, parseVersion, parseSize, toSeconds, type GuardRules, type StageCheck } from "./core.ts";
11
11
 
@@ -520,7 +520,28 @@ export function ghostFeatureDirs(root: string): string[] {
520
520
  const df = path.join(root, ".dev-flow");
521
521
  if (!existsSync(df)) return [];
522
522
  return readdirSync(df, { withFileTypes: true })
523
- .filter((d) => d.isDirectory() && existsSync(path.join(df, d.name, "plan")) && !existsSync(path.join(df, d.name, "state.json")))
523
+ // a plan/ holding no file has nothing to recover: that dir is an empty one (emptyFeatureDirs), swept without a question
524
+ .filter((d) => d.isDirectory() && existsSync(path.join(df, d.name, "plan")) && !existsSync(path.join(df, d.name, "state.json")) && !holdsNoFile(path.join(df, d.name)))
525
+ .map((d) => `.dev-flow/${d.name}`);
526
+ }
527
+
528
+ /** True when a directory holds no file anywhere beneath it — only (nested) empty directories. */
529
+ function holdsNoFile(dir: string): boolean {
530
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
531
+ if (!e.isDirectory()) return false;
532
+ if (!holdsNoFile(path.join(dir, e.name))) return false;
533
+ }
534
+ return true;
535
+ }
536
+
537
+ /** Feature dirs emptied by a hand cleanup that stopped at the directory (gh#282): no file anywhere inside, so
538
+ * neither a feature (no state.json) nor a plan ghost (no plan/*.md). They hold nothing, so removing them loses
539
+ * nothing. `minAgeMs` keeps a dir a `flow start` is creating this very moment out of the sweep. */
540
+ export function emptyFeatureDirs(root: string, minAgeMs = 0, nowMs = Date.now()): string[] {
541
+ const df = path.join(root, ".dev-flow");
542
+ if (!existsSync(df)) return [];
543
+ return readdirSync(df, { withFileTypes: true })
544
+ .filter((d) => d.isDirectory() && holdsNoFile(path.join(df, d.name)) && nowMs - statSync(path.join(df, d.name)).mtimeMs >= minAgeMs)
524
545
  .map((d) => `.dev-flow/${d.name}`);
525
546
  }
526
547
 
@@ -592,6 +613,7 @@ export function doctorFindings(root: string, cfg: Config, md: ParsedMd | null):
592
613
  if (cfg.commands.run && !cfg.checkList.some((c) => c.name === "health")) f.push('run command configured but no tier-1 health check — add commands.health or a flow-check so "running and healthy" is enforced');
593
614
  if (cfg.commands.dev && !healthProbe(cfg)) f.push("dev deploy configured but no health check — flow verify cannot prove the deploy came back serving this build: add commands.health or a flow-check health block");
594
615
  if (!cfg.checkList.length) f.push("implement tier-1 gates nothing — no test, no health, no flow-check block: 'flow check' would pass vacuously");
616
+ for (const g of emptyFeatureDirs(root)) f.push(`${g} is an empty feature dir — no state.json, no plan/, no file at all (a hand cleanup that stopped at the directory); flow init removes it`);
595
617
  for (const g of ghostFeatureDirs(root)) f.push(`${g} has a plan/ but no state.json — ghost of a closed, aborted or hand-made feature (flow start <slug> --confirmed adopts it as a new feature; flow init offers to remove it)`);
596
618
  return f;
597
619
  }
@@ -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> [--evidence=<file:line>]|list|plan|tidy|move <id> --playbook|--code|done <id>[,<id>…] [<what>]|reopen <id> [<why>]|defer <id> <why>|--same <id> [<evidence>]] | roadmap [add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>[,<n>…]|drop <n>[,<n>…]|tidy] | doctor [<issue note>] | status [slug] [--json] | start <slug> [--ui|--patch|--docs] [--reflections=r<id>,…] [--no-ui --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | review [done <verdict>|--skip] | approve [--yolo] [--version=patch|minor|major|--no-version] | bump <patch|minor|major|none> [slug] | verify [--yolo] [--port=<n>|--replace] [--version=<kind>|--no-version] | release [--yolo|--version=<kind>|--no-version|--no-fold-check|--no-marker-check] | finish [--yolo] [--no-reflect] [--note=<text>] [--no-artifact-check|--no-release-create] [slug] | abort [slug] [--purge] | 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 on start is the agent's call whenever screens change (it only adds the mockup gate); --patch/--docs are proposed at start and granted by the Approve? answer; --no-ui (clearing ui on a plan-stage feature) and --merge=<style> 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 — approve --confirmed carries the operator's release call on a versioned project: --version=patch|minor|major (the kind of step — the number is counted from the newest tag when the release runs) or --no-version (merge unreleased), asked with Approve?; it is never asked again, and the operator changes it on any later gate call (verify/release take the same flags) or with bump <kind> --confirmed, until the tag is cut — on GitHub release then publishes itself (push, PR, CI wait, merge in the playbook style, annotated tag) and records the release; a 'publish stopped' or 'publish waiting' result is resumed by re-running flow release; publish = manual in the playbook (or another forge) leaves those steps to the agent, and finish records the release (--no-artifact-check / --no-release-create skip a proof on the operator's word) — 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 prints open items by id (r<n>: never renumbered), plan groups them into flows with the start command, move <id> re-files one, done <id> checks a fixed one off, reopen <id> brings back one closed by mistake (from the archive too), --same <id> counts a recurrence on its row, defer <id> <why> leaves a row linked to the bound flow open, tidy moves closed ones to reflections-archive.md — start --reflections=<ids> links rows to the flow and finish closes them as fixed by it — 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); <n> is the row number list prints — done leaves the others in place, drop and tidy renumber — 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 — review records the review flow verify requires before it asks Verified? (and flow release before it ships): done <verdict> after the playbook's review step ran inline (a flow_stage review worker records itself); --skip (--confirmed, the operator's Skip review? answer) ships without one; bare review shows what is on record — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — abort unbinds and keeps the worktree; abort --purge (--confirmed, the operator's Purge? answer) removes the worktree, branch and feature folder of a dropped feature, never anything on origin — 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> [--evidence=<file:line>]|list|plan|tidy|move <id> --playbook|--code|done <id>[,<id>…] [<what>]|reopen <id> [<why>]|defer <id> <why>|--same <id> [<evidence>]] | roadmap [add <text> [--slug=<slug>] [--brief=<notes>|--brief-file=<path>]|pick <n> <slug>|done <n>[,<n>…]|drop <n>[,<n>…]|tidy] | doctor [<issue note>] | guard <command>|--path <file> | status [slug] [--json] | start <slug> [--ui|--patch|--docs] [--reflections=r<id>,…] [--no-ui --confirmed] [--force] [--merge=squash|merge|rebase|any] [--check-upstream] | use <slug> | test | check | health | review [done <verdict>|--skip] | approve [--yolo] [--version=patch|minor|major|--no-version] | bump <patch|minor|major|none> [slug] | verify [--yolo] [--port=<n>|--replace] [--version=<kind>|--no-version] | release [--yolo|--version=<kind>|--no-version|--no-fold-check|--no-marker-check] | finish [--yolo] [--no-reflect] [--note=<text>] [--no-artifact-check|--no-release-create] [slug] | abort [slug] [--purge] | 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 on start is the agent's call whenever screens change (it only adds the mockup gate); --patch/--docs are proposed at start and granted by the Approve? answer; --no-ui (clearing ui on a plan-stage feature) and --merge=<style> 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 — approve --confirmed carries the operator's release call on a versioned project: --version=patch|minor|major (the kind of step — the number is counted from the newest tag when the release runs) or --no-version (merge unreleased), asked with Approve?; it is never asked again, and the operator changes it on any later gate call (verify/release take the same flags) or with bump <kind> --confirmed, until the tag is cut — on GitHub release then publishes itself (push, PR, CI wait, merge in the playbook style, annotated tag) and records the release; a 'publish stopped' or 'publish waiting' result is resumed by re-running flow release; publish = manual in the playbook (or another forge) leaves those steps to the agent, and finish records the release (--no-artifact-check / --no-release-create skip a proof on the operator's word) — 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 prints open items by id (r<n>: never renumbered), plan groups them into flows with the start command, move <id> re-files one, done <id> checks a fixed one off, reopen <id> brings back one closed by mistake (from the archive too), --same <id> counts a recurrence on its row, defer <id> <why> leaves a row linked to the bound flow open, tidy moves closed ones to reflections-archive.md — start --reflections=<ids> links rows to the flow and finish closes them as fixed by it — 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); <n> is the row number list prints — done leaves the others in place, drop and tidy renumber — 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 — review records the review flow verify requires before it asks Verified? (and flow release before it ships): done <verdict> after the playbook's review step ran inline (a flow_stage review worker records itself); --skip (--confirmed, the operator's Skip review? answer) ships without one; bare review shows what is on record — doctor reviews structure, git consistency and open reflections (never writes); doctor <note> prints an investigation brief — abort unbinds and keeps the worktree; abort --purge (--confirmed, the operator's Purge? answer) removes the worktree, branch and feature folder of a dropped feature, never anything on origin — 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");
@@ -482,4 +482,6 @@ export interface Session {
482
482
  /** Operator messages in this session's branch so far, or null/undefined when it cannot be read — a gate
483
483
  * compares it with the count it recorded earlier to know whether the operator spoke since (gh#254). */
484
484
  operatorMessages?: number | null;
485
+ /** The operator's newest message text, or null/undefined when it cannot be read (gh#299). */
486
+ operatorText?: string | null;
485
487
  }
@@ -1,9 +1,10 @@
1
1
  /** dev-flow runtime — The gate runner and the gates that do not ship anything. Moved out of extensions/dev-flow.ts as is (exports added). */
2
2
  import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
3
  import path from "node:path";
4
- import { type ReflectFinding, type ReflectOpenCheck, foldCallError, skipsChecks, approveGate, versionArg, playbookVersionChoice, releaseCallQuestion, describeVersionChoice, applicableItems, appendRoadmapItem, checklistHash, claimBlocks, doneItemCount, detectForge, gateHelpJson, healthProbe, parseMergeStyle, investigationBrief, pluginVersion, reflectProtocol, reflectUnfiledCount, reflectionNudges, reflectionRoutes, listFiles, needsOperator, newState, nextHint, openChecklistItems, releaseGate, roadmapDone, roadmapDrop, roadmapOpenCount, roadmapOpenRows, roadmapBriefFor, roadmapPick, roadmapTidy, statusJson, subst, sq, featureTmpDir, foreignWorktreeLinks, validSlug, verifyGate, STAGE_EMOJI, type ReflectTarget, type Config, type FlowState, parseRowIds, DF_GITIGNORE } from "../core.ts";
5
- import { applyAnswers, buildDraft, doctorFindings, ghostFeatureDirs, ghostInfo, lineDiff, loadProject, mdDigest, parseAnswers, parseProjectMd } from "../projectmd.ts";
4
+ import { type ReflectFinding, type ReflectOpenCheck, ALLOW_REWRITE, forcePushInvocation, guardBash, guardPath, foldCallError, skipsChecks, approveGate, versionArg, playbookVersionChoice, releaseCallQuestion, describeVersionChoice, applicableItems, appendRoadmapItem, checklistHash, claimBlocks, doneItemCount, detectForge, gateHelpJson, healthProbe, parseMergeStyle, investigationBrief, pluginVersion, reflectProtocol, reflectUnfiledCount, reflectionNudges, reflectionRoutes, listFiles, needsOperator, newState, nextHint, openChecklistItems, releaseGate, roadmapDone, roadmapDrop, roadmapOpenCount, roadmapOpenRows, roadmapBriefFor, roadmapPick, roadmapTidy, statusJson, subst, sq, featureTmpDir, foreignWorktreeLinks, validSlug, verifyGate, STAGE_EMOJI, type ReflectTarget, type Config, type FlowState, parseRowIds, DF_GITIGNORE } from "../core.ts";
5
+ import { applyAnswers, buildDraft, doctorFindings, emptyFeatureDirs, ghostFeatureDirs, ghostInfo, lineDiff, loadProject, mdDigest, parseAnswers, parseProjectMd } from "../projectmd.ts";
6
6
  import { linkedTag } from "../fold.ts";
7
+ import { namesReleaseCall } from "./grants.ts";
7
8
  import { detectProject } from "../detect.ts";
8
9
  import { AGENT_MARK } from "../present.ts";
9
10
  import { GATE_HELP, SELF_BUILD, refreshDocsCode, type Ui, manifestAt, recordReleaseCall, buildSkew, copyWarning, currentBranch, dfDir, featDir, featureEnv, flagValue, gateCwd, gitConsistency, initiated, loadedVersion, mergeHistoryEvidence, needState, now, originUrl, publishedVersion, readClaim, readReflections, readReflectionsText, readRoadmap, readState, roadmapFile, sh, stateFile, tail, unfinishedStates, writePlaybookMergePolicy, writeState } from "./base.ts";
@@ -75,6 +76,9 @@ export async function runFlow(args: string[], root: string, ui: Ui, sess: Sessio
75
76
  case "doctor":
76
77
  return gateDoctor(o);
77
78
 
79
+ case "guard":
80
+ return gateGuard(o, rest);
81
+
78
82
  case "version":
79
83
  return gateVersion(o);
80
84
 
@@ -169,6 +173,13 @@ export async function gateInit(o: GateCtx): Promise<RunResult> {
169
173
  const draftFresh = buildDraft(det);
170
174
  const questions = setupQuestions(det, { merge: mergeEv, tag: tagEv });
171
175
  if (flag("draft")) return { text: existsSync(mdFile) ? readFileSync(mdFile, "utf8") : draftFresh }; // read path: prints content, writes nothing (and offers no deletions)
176
+ // empty feature dirs hold nothing to lose: removed with a note, no question (gh#282). Ten minutes old at
177
+ // least, so a dir a parallel flow start has only just created is not swept before its state.json lands.
178
+ const empties = emptyFeatureDirs(root, 10 * 60_000);
179
+ if (empties.length) {
180
+ for (const g of empties) rmSync(path.join(root, g), { recursive: true, force: true });
181
+ notes.push(`removed ${empties.length} empty feature dir(s) — no state.json, no plan/, no file: ${empties.map((g) => g.slice(".dev-flow/".length)).join(", ")}`);
182
+ }
172
183
  // ghosts: feature dirs whose state.json is gone — inert, invisible to status and guards, and only findable by eye
173
184
  const ghosts = ghostFeatureDirs(root);
174
185
  if (ghosts.length) {
@@ -517,9 +528,14 @@ export async function gateApprove(o: GateCtx): Promise<RunResult> {
517
528
  state!.stage = "implement";
518
529
  state!.approvals.plan = now();
519
530
  if (call) recordReleaseCall(root, state!, cfg, call);
531
+ // gh#299: an operator answer that names no kind accepts the plan, not the agent's proposed call — kept, marked
532
+ const proposed = flag("confirmed") && !!relArg.choice && !namesReleaseCall(sess.operatorText ?? null, relArg.choice);
533
+ if (proposed) state!.versionProposed = true;
534
+ else if (relArg.choice) delete state!.versionProposed;
520
535
  delete state!.pendingAsk;
521
536
  writeState(root, state!);
522
- return { text: `plan approved${audit}${state!.yolo ? " — yolo: later gate questions pre-confirmed" : ""}; worktree ${wtRel} on branch ${branch}.${call ? `\nrelease call: ${describeVersionChoice(call, state!.versionFrom)} — the number is counted from the newest tag at release; the operator can change the call on any gate call (or flow bump <kind>) until the tag` : ""}${setupNote}\n${AGENT_MARK}next: ${nextHint(state!, cfg)}` };
537
+ const proposedNote = proposed ? ` — recorded as YOUR PROPOSAL: the operator's answer named no kind, so the call is not theirs yet. Verified? shows it to them; their answer, or flow bump <kind> --confirmed, settles it` : "";
538
+ return { text: `plan approved${audit}${state!.yolo ? " — yolo: later gate questions pre-confirmed" : ""}; worktree ${wtRel} on branch ${branch}.${call ? `\nrelease call: ${describeVersionChoice(call, state!.versionFrom)}${proposedNote} — the number is counted from the newest tag at release; the operator can change the call on any gate call (or flow bump <kind>) until the tag` : ""}${setupNote}\n${AGENT_MARK}next: ${nextHint(state!, cfg)}` };
523
539
  }
524
540
 
525
541
  /** `flow bump <patch|minor|major|none> [slug]`: the operator changes the release call at any stage before the tag.
@@ -540,9 +556,10 @@ export async function gateBump(o: GateCtx): Promise<RunResult> {
540
556
  if (!cfg.versioning.file && choice !== "unreleased") return { text: "bump FAILED:\n- the playbook sets no version file (versionFile under ## release), so there is nothing to bump — set one first", isError: true };
541
557
  if (state!.publish?.tag || state!.approvals.release) return { text: `bump FAILED:\n- ${state!.publish?.tag ?? "the release"} is already ${state!.publish?.tag ? "tagged" : "recorded"} — the call cannot change after the tag`, isError: true };
542
558
  const was = state!.versionChoice;
543
- if (was === choice) return { text: `release call unchanged: ${describeVersionChoice(choice, state!.versionFrom)}` };
559
+ if (was === choice && !(state!.versionProposed && flag("confirmed"))) return { text: `release call unchanged: ${describeVersionChoice(choice, state!.versionFrom)}${state!.versionProposed ? " — still the agent's proposal; flow bump <kind> --confirmed on the operator's word settles it" : ""}` };
544
560
  if (!flag("confirmed")) return { text: needsOperator(`change the release call from ${was ? describeVersionChoice(was) : "none"} to ${describeVersionChoice(choice)}`, "Release call?", `this is the operator's word — on it, re-run flow bump ${kind}${slug ? ` ${slug}` : ""} --confirmed`), isError: true };
545
561
  recordReleaseCall(root, state!, cfg, choice);
562
+ delete state!.versionProposed; // the operator's own word now (gh#299)
546
563
  writeState(root, state!);
547
564
  const prep = state!.stage === "pre-release" || state!.stage === "release" ? ` — redo the release prep to match (${choice === "unreleased" ? "revert any bump; the entry goes under Unreleased" : "the version file and its changelog heading"}); flow release names the number` : "";
548
565
  return { text: `release call changed (confirmed by operator instruction): ${was ? describeVersionChoice(was) : "none"} → ${describeVersionChoice(choice, state!.versionFrom)}${prep}` };
@@ -718,6 +735,31 @@ export async function gateRoadmap(o: GateCtx): Promise<RunResult> {
718
735
  }
719
736
  }
720
737
 
738
+ /** `flow guard "<command>"` / `flow guard --path <file>`: which of the playbook's own flow-guard rules a command
739
+ * or a path trips, through the same matcher the hooks use (gh#287). Reads only; runs nothing. */
740
+ export async function gateGuard(o: GateCtx, rest: string[]): Promise<RunResult> {
741
+ const { root, cfg } = o;
742
+ const g = cfg.guard;
743
+ const nRules = g.deny.length + g.confirm.length + g.protect.length + g.forbid.length;
744
+ const usage = 'usage: flow guard "<command>" (which playbook rule a shell command trips) or flow guard --path <file> (which rule an edit of that path trips)';
745
+ if (rest[0] === "--path") {
746
+ const file = rest.slice(1).join(" ").trim();
747
+ if (!file) return { text: usage, isError: true };
748
+ const v = guardPath(path.resolve(root, file), root, g);
749
+ const verdict = v.block ? `blocked — ${v.block}` : v.confirm ? `asks the operator — ${v.confirm}` : "no playbook rule matches this path";
750
+ return { text: `flow guard --path ${file}: ${verdict}\n(${nRules} playbook rule(s); stage guards — worktree, main-checkout and flow-state rules — are judged separately at the call)` };
751
+ }
752
+ const command = rest.join(" ").trim();
753
+ if (!command) return { text: usage, isError: true };
754
+ const v = guardBash(command, g);
755
+ const lines: string[] = [];
756
+ if (v.block) lines.push(`blocked — ${v.block} (the command never runs)`);
757
+ for (const r of v.confirms) lines.push(`asks the operator — \`${r.pattern}\`${r.why ? ` :: ${r.why}` : ""}`);
758
+ if (forcePushInvocation(command)) lines.push(`asks the operator — dev-flow's own force-push rule (the operator's word is the ${ALLOW_REWRITE} prefix)`);
759
+ if (!lines.length) lines.push("no playbook rule matches — runs as far as the playbook is concerned");
760
+ return { text: `flow guard: \`${command.length > 200 ? `${command.slice(0, 200)}…` : command}\`\n${lines.map((l) => `- ${l}`).join("\n")}\n(${nRules} playbook rule(s); read-only segments such as cat or grep are skipped, as at the call; stage guards are judged separately)` };
761
+ }
762
+
721
763
  export async function gateDoctor(o: GateCtx): Promise<RunResult> {
722
764
  const { root, rest } = o;
723
765
  // read-only findings on demand — never writes, never asks, safe for agents and CI at any stage
@@ -29,6 +29,30 @@ export function operatorMessageCount(entries: readonly unknown[] | null | undefi
29
29
  return n;
30
30
  }
31
31
 
32
+ /** The text of the operator's newest message in the branch, or null when it cannot be read. */
33
+ export function lastOperatorText(entries: readonly unknown[] | null | undefined): string | null {
34
+ if (!Array.isArray(entries)) return null;
35
+ for (let i = entries.length - 1; i >= 0; i--) {
36
+ // SAFETY: narrow structural view of the SessionEntry union; only a user message's text is read
37
+ const m = entries[i] as { type?: string; message?: { role?: string; content?: unknown } };
38
+ if (m.type !== "message" || m.message?.role !== "user") continue;
39
+ const c = m.message.content;
40
+ if (typeof c === "string") return c;
41
+ if (Array.isArray(c)) return c.map((p) => (p && typeof p === "object" && (p as { type?: string }).type === "text" ? String((p as { text?: unknown }).text ?? "") : "")).join(" ");
42
+ return "";
43
+ }
44
+ return null;
45
+ }
46
+
47
+ /** Whether the operator's words name this release call (gh#299): `minor` for minor, `unreleased` / `no version`
48
+ * / `don't release` for unreleased. Null words (unreadable) are taken as naming it — nothing to check against. */
49
+ export function namesReleaseCall(words: string | null, choice: string): boolean {
50
+ if (words === null) return true;
51
+ const w = words.toLowerCase();
52
+ if (choice === "unreleased") return /\bunreleased\b|\bno[- ]?version\b|\bdon'?t (?:release|version|bump)\b|\bwithout (?:a )?(?:release|version|bump)\b|\bno (?:release|bump)\b/.test(w);
53
+ return new RegExp(`\\b${choice}\\b`).test(w);
54
+ }
55
+
32
56
  export interface GrantLedger {
33
57
  /** per session: the gate that last asked for the operator's word, and the operator-message count then */
34
58
  asked: Map<string, { sub: string; users: number }>;
@@ -69,7 +93,10 @@ export function grantCheck(args: readonly string[], key: string, users: number |
69
93
  export function grantRecord(args: readonly string[], key: string, users: number | null, res: { text: string; isError?: boolean }, ledger: GrantLedger): void {
70
94
  if (users === null) return;
71
95
  const sub = args[0] ?? "";
72
- if (res.isError && (res.text.startsWith(NEEDS_OPERATOR) || ASKS_FOR_WORD.test(res.text))) {
96
+ // gh#283: a stopped or waiting publish resumes on a re-run and asks nobody — its prose may still mention the
97
+ // operator's word (a real failure's way forward), which must not turn the resume into a question
98
+ const resumable = /(?:^|\n)publish (?:stopped|waiting) —/.test(res.text);
99
+ if (res.isError && !resumable && (res.text.startsWith(NEEDS_OPERATOR) || ASKS_FOR_WORD.test(res.text))) {
73
100
  ledger.asked.set(key, { sub, users });
74
101
  return;
75
102
  }
@@ -13,6 +13,9 @@ import { gatePublishes, prBodyOwed, publishRelease } from "./publish.ts";
13
13
  /** The release call, asked with Verified? only for a flow approved before Approve? carried it — null when the
14
14
  * playbook decides, the flow has no manifest to version, or the call is on record (the usual case). */
15
15
  function versionQuestion(root: string, state: FlowState, cfg: Config): { ask: string; flags: string } | null {
16
+ // gh#299: a call the agent proposed at Approve? is shown here, where the operator answers anyway
17
+ if (state.versionChoice && state.versionProposed)
18
+ return { ask: `the release call is ${describeVersionChoice(state.versionChoice, state.versionFrom)} — the agent's proposal at Approve?, not your word: keep it, or say patch, minor or major (or merge unreleased)`, flags: "--version=patch|minor|major or --no-version to change it" };
16
19
  if (!cfg.versioning.file || playbookVersionChoice(cfg) || state.versionChoice) return null;
17
20
  return releaseCallQuestion(manifestAt(gateCwd(root, state), cfg.versioning.file), cfg.versioning.file, state.docs);
18
21
  }
@@ -194,6 +197,8 @@ export async function gateVerify(o: GateCtx): Promise<RunResult> {
194
197
  const was = state!.versionChoice;
195
198
  const choice = verArg.choice ?? state!.versionChoice ?? playbookVersionChoice(cfg);
196
199
  if (choice) recordReleaseCall(root, state!, cfg, choice);
200
+ // the operator answered a Verified? that showed the proposed call (or changed it): it is their word now (gh#299)
201
+ if (askPending || flag("confirmed")) delete state!.versionProposed;
197
202
  const choiceNote = choice ? `\nrelease call: ${describeVersionChoice(choice, state!.versionFrom)}${was && was !== choice ? ` (changed from ${describeVersionChoice(was)})` : ""}` : "";
198
203
  const before = state!.stage;
199
204
  state!.stage = "pre-release";
@@ -393,22 +398,38 @@ export async function gateRelease(o: GateCtx): Promise<RunResult> {
393
398
  const upstream = (await sh(`git rev-parse --verify -q ${sq(`refs/remotes/origin/${d}`)}`, wtCwd)).ok ? `origin/${d}` : (await sh(`git rev-parse --verify -q ${sq(`refs/heads/${d}`)}`, wtCwd)).ok ? d : "";
394
399
  const range = `${sq(state!.verifiedHead)}..HEAD${upstream ? ` --not ${sq(upstream)}` : ""}`;
395
400
  // one record per commit: "<sha> <subject>" then the files it touched (\x1e starts a record)
396
- const since = await sh(`git log --no-decorate --name-only --format=%x1e%h%x20%s ${upstream ? "--no-merges " : ""}${range}`, wtCwd);
397
- const commits = since.ok
398
- ? since.out.split("\x1e").map((rec) => rec.split("\n").map((l) => l.trim()).filter(Boolean)).filter((r) => r.length).map(([line, ...files]) => ({ line, files }))
401
+ const since = await sh(`git log --no-decorate --name-only --format=%x1e%H%x20%h%x20%s ${upstream ? "--no-merges " : ""}${range}`, wtCwd);
402
+ const listed = since.ok
403
+ ? since.out.split("\x1e").map((rec) => rec.split("\n").map((l) => l.trim()).filter(Boolean)).filter((r) => r.length).map(([head, ...files]) => ({ full: head.split(" ")[0], line: head.split(" ").slice(1).join(" "), files }))
399
404
  : [];
400
405
  const all = upstream ? await sh(`git rev-list --count ${sq(state!.verifiedHead)}..HEAD`, wtCwd) : null;
401
- const mergedIn = all?.ok ? Math.max(0, Number.parseInt(all.out.trim(), 10) - commits.length) : 0;
406
+ const mergedIn = all?.ok ? Math.max(0, Number.parseInt(all.out.trim(), 10) - listed.length) : 0;
402
407
  // gh#187: the release-prep commit (the bump, the changelog entry, whatever else the bump rewrites — an
403
408
  // image tag in a compose file) lands after Verified? by design and no container verdict could cover
404
409
  // it. It is the commit that touches the version file, or one that touches nothing but prep files.
405
410
  const prepSet = prepFiles(cfg);
411
+ // gh#298: a rebase replays the verified commits under new ids — same content, so not news. When the verified
412
+ // head is no longer an ancestor, a commit whose patch (prep files left out, where a rebase conflict usually
413
+ // lands) matches one the operator verified rides under the word; changed content still asks.
414
+ const rewritten = upstream && !(await sh(`git merge-base --is-ancestor ${sq(state!.verifiedHead)} HEAD`, wtCwd)).ok;
415
+ const replayed = new Set<string>();
416
+ if (rewritten) {
417
+ const notPrep = [...prepSet].map((f) => sq(`:(exclude)${f}`)).join(" ");
418
+ const pids = async (r: string) => {
419
+ const out = await sh(`git log -p --no-merges --format='commit %H' ${r} -- . ${notPrep} | git patch-id --stable`, wtCwd);
420
+ return out.ok ? out.out.split("\n").map((l) => l.trim().split(/\s+/)).filter((x) => x.length === 2) : [];
421
+ };
422
+ const seen = new Set((await pids(`${sq(state!.verifiedHead)} --not ${sq(upstream)}`)).map(([pid]) => pid));
423
+ for (const [pid, sha] of await pids(range)) if (seen.has(pid)) replayed.add(sha);
424
+ }
425
+ const commits = listed.filter((c) => !replayed.has(c.full));
426
+ const replayNote = replayed.size ? `${replayed.size} commit(s) a rebase replayed with the patch the operator verified ride under it` : "";
406
427
  const isPrep = (c: { files: string[] }) => (!!cfg.versioning.file && c.files.includes(cfg.versioning.file)) || (c.files.length > 0 && c.files.every((f) => prepSet.has(f)));
407
428
  const prep = commits.filter(isPrep);
408
429
  // docs and tests ship no behaviour the operator's look could have caught: they ride under the verdict, named
409
430
  const quiet = commits.filter((c) => !isPrep(c) && c.files.length > 0 && c.files.every(nonBehaviourPath));
410
431
  const changed = commits.filter((c) => !isPrep(c) && !quiet.includes(c));
411
- if (quiet.length) quietAfterVerify = `${quiet.length} docs/test-only commit(s) after Verified? (${quiet.map((c) => c.line.split(" ")[0]).join(", ")}) ride under it`;
432
+ quietAfterVerify = [quiet.length ? `${quiet.length} docs/test-only commit(s) after Verified? (${quiet.map((c) => c.line.split(" ")[0]).join(", ")}) ride under it` : "", replayNote].filter(Boolean).join("; ");
412
433
  // changed code shipping under an earlier word is friction the closing reflection should look at
413
434
  unverifiedChange = changed.length > 0;
414
435
  if (changed.length)
@@ -467,7 +488,11 @@ export async function gateRelease(o: GateCtx): Promise<RunResult> {
467
488
  markPendingAsk(root, state!, "Release?");
468
489
  if (!ui.hasUI) {
469
490
  const callAsk = cfg.versioning.file && !choice ? " — also ask the release call: a patch, minor or major release, or merge unreleased (no bump, no tag)?" : "";
470
- return { text: needsOperator(`ready to publish${yoloHeld ? ` (${yoloHeld})` : ""}${askWhy ? ` (asked: ${askWhy})` : ""}${postVerify ? ` — ${postVerify}` : ""}${callAsk}`, "Release?", `re-run with --confirmed once the operator answered 'Release?' in chat${callAsk ? " (add --version=patch|minor|major or --no-version for their release call)" : ""}`), isError: true };
491
+ // gh#288: changed code after Verified? is one question, not two — a re-verify after a Release? answer spent it
492
+ const oneQuestion = unverifiedChange && cfg.release.ask !== "always" && !callAsk
493
+ ? "ask ONE question, not both: if these commits change behaviour, run flow verify now and ask Verified? over the new deploy — Release? then answers itself (release.ask = on-change); only if they do not, ask 'Release?' with them named and "
494
+ : "";
495
+ return { text: needsOperator(`ready to publish${yoloHeld ? ` (${yoloHeld})` : ""}${askWhy ? ` (asked: ${askWhy})` : ""}${postVerify ? ` — ${postVerify}` : ""}${callAsk}`, "Release?", `${oneQuestion}re-run with --confirmed once the operator answered 'Release?' in chat${callAsk ? " (add --version=patch|minor|major or --no-version for their release call)" : ""}`), isError: true };
471
496
  }
472
497
  const ok = await ui.confirm("Enter release", `Release ${state!.slug}${manifestVer ? ` v${manifestVer}` : ""}${noVersion ? " (unversioned — merge + changelog entry only: no bump, no tag for this flow)" : ""}? Publishing starts: PR, merge${noVersion ? "" : ", tag"} — release-done afterwards needs no further answer.${staleNote ? `\n\n${staleNote}` : ""}${postVerify ? `\n\n${postVerify}` : ""}${yoloHeld ? `\n\n(${yoloHeld})` : ""}`);
473
498
  if (!ok) {