pi-dev-flow 0.94.2 → 0.95.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/core.ts CHANGED
@@ -61,6 +61,12 @@ export interface FlowState {
61
61
  /** the session and its operator-message count when Verified? moved this flow to pre-release (gh#254): under
62
62
  * yolo = until-release, a message after it is the operator's own Release? word, not a replayed plan-stage yolo */
63
63
  verifiedAtMessage?: { key: string; users: number };
64
+ /** a docs flow's changed paths that are not documentation (its branch vs the default branch, plus uncommitted):
65
+ * any at all and the tier-1 checks apply to it as to any flow — docs mode skips them for docs, not for code */
66
+ docsCode?: string[];
67
+ /** reflection rows this flow set out to fix (`flow start --reflections=r3,r7`): finish closes each as fixed by
68
+ * this flow, unless `flow reflect defer <id> "<why>"` left it open with a reason */
69
+ reflections?: { id: number; body: string; deferred?: string }[];
64
70
  verifiedHead?: string; // HEAD the operator's Verified? was given over — release names commits after it, so the word is not recorded as the verdict for a tree nobody looked at (#162)
65
71
  reflectedAt?: string; // a reflect worker reported for this flow — finish runs one first while this is unset (only --no-reflect --confirmed skips it)
66
72
  devPort?: number; // the port the operator chose for this flow's dev deploy when the default was held by another flow — finish stops it (devDown)
@@ -415,7 +421,7 @@ export function verifyGate(state: FlowState, cfg: Config, branch?: BranchState |
415
421
  ? `nothing committed on the feature branch, and ${branch.unreleased.since ? `nothing landed on the default branch since ${branch.unreleased.since}` : "the default branch has nothing to release"} — there is nothing to verify or release`
416
422
  : "nothing committed on the feature branch yet — commit as you go, verify proves a committed state",
417
423
  );
418
- 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`);
424
+ if (!skipsChecks(state)) for (const c of cfg.checkList) if (!state.checks[c.name]?.ok) errs.push(`check "${c.name}" has not passed — run flow check${state.docs ? ` (a docs flow whose diff reaches code: ${state.docsCode!.slice(0, 4).join(", ")}${state.docsCode!.length > 4 ? ` +${state.docsCode!.length - 4}` : ""})` : ""}`);
419
425
  const pend = openItemsNote(cfg, state, "implement");
420
426
  if (pend) errs.push(`tier-2 checklist not confirmed — ${pend}; confirm them with the operator, then run flow verify`);
421
427
  return errs;
@@ -594,7 +600,7 @@ export function reviewOwed(state: FlowState, cfg: Config): string | null {
594
600
  export function preReleaseGate(state: FlowState, cfg: Config, prep: ReleasePrep): string[] {
595
601
  const errs: string[] = [];
596
602
  if (state.stage !== "pre-release") errs.push(`stage is "${state.stage}", the release gate only applies to "pre-release"`);
597
- 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`);
603
+ if (!skipsChecks(state)) for (const c of cfg.checkList) if (!state.checks[c.name]?.ok) errs.push(`check "${c.name}" has not passed — run flow check${state.docs ? ` (a docs flow whose diff reaches code: ${state.docsCode!.slice(0, 4).join(", ")}${state.docsCode!.length > 4 ? ` +${state.docsCode!.length - 4}` : ""})` : ""}`);
598
604
  const pend = openItemsNote(cfg, state, "pre-release");
599
605
  if (pend) errs.push(`tier-2 checklist not confirmed — ${pend}; confirm them with the operator, then run flow release`);
600
606
  if (prep.conflictMarkers?.length && !prep.noMarkerCheck)
@@ -627,7 +633,7 @@ export function preReleaseGate(state: FlowState, cfg: Config, prep: ReleasePrep)
627
633
  if (cfg.versioning.file) {
628
634
  if (!prep.manifestVersion) errs.push(`versioning.file "${cfg.versioning.file}" has no parsable version — bump it to the version you will release`);
629
635
  else if (prep.remoteTags.includes(cfg.versioning.pattern.replace("{version}", prep.manifestVersion)))
630
- errs.push(`version ${prep.manifestVersion} is already tagged — bump the manifest to the next version`);
636
+ errs.push(`version ${prep.manifestVersion} is already tagged — bump the manifest to the next version${unversionedAlt(state)}`);
631
637
  }
632
638
  if (cfg.release.changelog) {
633
639
  if (!prep.changelog) errs.push(`release.changelog "${cfg.release.changelog}" does not exist — prepare the changelog (a project that keeps none: set changelog = "" under ## release)`);
@@ -646,13 +652,30 @@ export function preReleaseGate(state: FlowState, cfg: Config, prep: ReleasePrep)
646
652
  errs.push(`${prep.changelog.file} drops ${dropped.length} Unreleased entr${dropped.length === 1 ? "y" : "ies"} from the ${base.source} under the ${prep.manifestVersion ?? "new"} heading — folding means moving them in as they are (reword afterwards, or skip with --no-fold-check):\n ${dropped.slice(0, 5).join("\n ")}${dropped.length > 5 ? `\n …(${dropped.length - 5} more)` : ""}`);
647
653
  }
648
654
  if (unreleasedPending(prep.changelog.content))
649
- errs.push(`${prep.changelog.file} still has entries under Unreleased — fold them under the v${prep.manifestVersion ?? "new"} heading before releasing (they were left by --no-version flows)`);
655
+ errs.push(`${prep.changelog.file} still has entries under Unreleased — fold them under the ${prep.manifestVersion ?? "new"} heading before releasing (they were left by --no-version flows)${unversionedAlt(state)}`);
650
656
  }
651
657
  }
652
658
  }
653
659
  return errs;
654
660
  }
655
661
 
662
+ /** A path a docs flow may change without the project's checks: prose, the playbook, skills' markdown. A script
663
+ * under `.agents/` or `scripts/` is code, whatever the flow is called. */
664
+ export function isDocPath(p: string): boolean {
665
+ const f = p.replace(/^"|"$/g, "");
666
+ return /\.(md|mdx|markdown|txt|rst|adoc)$/i.test(f) || /^(?:LICENSE|NOTICE|AUTHORS|CODEOWNERS)(?:\.\w+)?$/i.test(path.basename(f)) || /\.(png|jpe?g|gif|svg|webp)$/i.test(f);
667
+ }
668
+
669
+ /** Does this flow skip the project's tier-1 checks? A docs flow does — unless its diff reaches code (a docs flow
670
+ * that also edited scripts/harness.ts and scripts/verify.ts shipped with no gate at all). */
671
+ export const skipsChecks = (state: FlowState): boolean => !!state.docs && !state.docsCode?.length;
672
+
673
+ /** The other way out of a versioned-release refusal, for a flow whose release call is not on record or is a docs
674
+ * flow: those usually ship unversioned, and a refusal naming only the versioned repair sent the agent to cut a
675
+ * tag a parallel flow already held. */
676
+ const unversionedAlt = (state: FlowState): string =>
677
+ state.docs || !state.versionChoice ? ` — or, if it ships unversioned${state.docs ? " (a docs flow usually does)" : ""}: ask the operator, and on their word run flow release --no-version` : "";
678
+
656
679
  /** True when the changelog's Unreleased section still holds entries — --no-version flows park
657
680
  * their lines there and a versioned release must fold them under its own heading. Matches
658
681
  * `## Unreleased` / `## [Unreleased]`; deeper `###` sub-headings stay inside the section, the
@@ -1136,6 +1159,8 @@ export function parsePushRefs(pushes: string[][]): PushRef[] {
1136
1159
  const STATE_PATH = /(^|[\s'"\/])(?:state|claim)\.json$/;
1137
1160
  const STATE_PATH_ABS = /\.dev-flow\/[\w./-]*(?:state|claim)\.json$/;
1138
1161
  const PLAYBOOK_PATH = /\.dev-flow\/[\w./-]*project\.md/;
1162
+ /** A file the playbook chore may carry: the playbook, or the folder's own ignore file tracked beside it. */
1163
+ const isPlaybookFile = (p: string): boolean => PLAYBOOK_PATH.test(p) || p === ".dev-flow/.gitignore";
1139
1164
  const DF_ANYWHERE = /\.dev-flow\b/;
1140
1165
  /** The `.dev-flow/` folder itself or one feature directory under it — deleting either destroys the flow
1141
1166
  * state and its plan for good. The advisory files the agent owns, and anything deeper (a worktree, a
@@ -1223,7 +1248,27 @@ export function playbookTamper(command: string): boolean {
1223
1248
  * and no command parsing to fool. shortcut: a guard rail against accidents, not a sandbox. */
1224
1249
  export function playbookOnlyChange(porcelain: string): boolean {
1225
1250
  const paths = porcelain.split("\n").map((l) => l.slice(3).trim()).filter(Boolean);
1226
- return paths.length === 1 && PLAYBOOK_PATH.test(paths[0]);
1251
+ // the playbook, and the folder's own ignore file (tracked so a clone carries it — see DF_GITIGNORE); it ignores
1252
+ // itself, so it shows here only once staged: `git add -f` it in one call, commit in the next
1253
+ return paths.length > 0 && paths.every(isPlaybookFile);
1254
+ }
1255
+
1256
+ /** `.dev-flow/.gitignore`: the folder ignores everything but the playbook. Untracked, it ignores itself too — a
1257
+ * fresh clone brought project.md back without it, every feature dir then showed as untracked work, and flow
1258
+ * finish refused on "uncommitted changes" that were two flows' own state (ollamaMQ, 2026-11-20). */
1259
+ export const DF_GITIGNORE = "*\n!project.md\n";
1260
+
1261
+ /** `git status --porcelain` lines that are the operator's work: dev-flow's own folder is never that — the
1262
+ * playbook excepted, which is tracked and edited by hand. */
1263
+ export function operatorDirt(porcelain: string): string {
1264
+ return porcelain
1265
+ .split("\n")
1266
+ .filter((l) => {
1267
+ const p = l.slice(3).trim().replace(/^"|"$/g, "");
1268
+ if (!p) return false;
1269
+ return !(p === ".dev-flow/" || (p.startsWith(".dev-flow/") && p !== ".dev-flow/project.md"));
1270
+ })
1271
+ .join("\n");
1227
1272
  }
1228
1273
 
1229
1274
  /** gh#234, gh#228: what `flow finish` says about commits on the local default branch that origin does not have.
@@ -1237,7 +1282,7 @@ export function localDefaultAhead(o: { defaultBranch: string; checkoutBranch: st
1237
1282
  if (!commits.length) return null;
1238
1283
  const list = `${commits.slice(0, 5).map((c) => c.line).join(" | ")}${commits.length > 5 ? ` …(${commits.length - 5} more)` : ""}`;
1239
1284
  const where = cur && cur !== d ? ` (the main checkout is on ${cur}, not ${d} — this is the local ${d} branch)` : "";
1240
- if (commits.every((c) => c.files.length > 0 && c.files.every((f) => PLAYBOOK_PATH.test(f))))
1285
+ if (commits.every((c) => c.files.length > 0 && c.files.every(isPlaybookFile)))
1241
1286
  return { block: null, note: ` local ${d} carries ${commits.length} playbook commit(s) origin/${d} does not have (${list})${where} — playbook tracking from flow init --track; they reach origin through a docs flow, never a direct push to ${d}. To line local ${d} up with origin meanwhile: git -C <main checkout> rebase origin/${d} ${d}.` };
1242
1287
  return { block: `local ${d} has ${commits.length} commit(s) origin/${d} does not have${where}: ${list} — finish removes the flow state, so nothing may stay local-only. If these are release chores, push them (git push origin ${d}); if they are work that belongs in a flow, move them onto a branch and ship them through one; then re-run flow finish`, note: "" };
1243
1288
  }
@@ -1873,17 +1918,157 @@ export function reflectionsTidy(text: string): string {
1873
1918
  }
1874
1919
 
1875
1920
  /** Shared wording for every surface that notices closed items piling up, so all hints read alike. */
1876
- export const reflectionsTidyHint = (closed: number) => `↻ ${closed} closed reflection(s) — flow reflect tidy drops them`;
1921
+ export const reflectionsTidyHint = (closed: number) => `↻ ${closed} closed reflection(s) — flow reflect tidy moves them to the archive`;
1877
1922
 
1878
1923
  /** The note text of an item, without the checkbox and without the trailing ` — <attribution>`: what
1879
1924
  * two reflects are compared on, so the same note at another date is still the same note.
1880
1925
  * shortcut: split on the last em dash — matches what the tool writes; a hand-written item ending in
1881
1926
  * an em-dash clause compares wider than intended. */
1882
- const reflectionBody = (l: string) => l.trim().replace(/^-\s*\[[ xX]\]\s*/, "").replace(/\s*—.*$/, "").trim();
1927
+ const reflectionBody = (l: string) => l.trim().replace(/^-\s*\[[ xX]\]\s*/, "").replace(REFLECT_ID, "").replace(/\s*—.*$/, "").trim();
1928
+
1929
+ /** One reflections.md item line — with no flow bound the slug is left out; `— - <date>` read as a broken slug.
1930
+ * The evidence the reflect worker named (a transcript file:line) rides on the row, so whoever fixes it can
1931
+ * re-check the claim instead of writing a rule from a paraphrase (a fold flow's review failed on exactly that). */
1932
+ export function reflectionLine(note: string, slug: string | null, date: string, evidence = ""): string {
1933
+ return `- [ ] ${note.trim()} — ${slug ? `${slug} ` : ""}${date}${evidence.trim() ? ` · evidence: ${evidence.trim()}` : ""}`;
1934
+ }
1935
+
1936
+ /** A row's stable id (`[r42]` after the checkbox): assigned once, never reused — `tidy` archives closed rows with
1937
+ * theirs — so a number read off one list names the same row after any tidy, move or parallel session (gh#263,
1938
+ * where positional numbers shifted under a batch and closed seven wrong rows). */
1939
+ const REFLECT_ID = /^\[r(\d+)\]\s*/;
1940
+ const ROW_HEAD = /^(\s*-\s*\[[ xX]\]\s*)/;
1941
+ export function rowId(line: string): number | null {
1942
+ const m = REFLECT_ID.exec(line.trim().replace(ROW_HEAD, ""));
1943
+ return m ? Number(m[1]) : null;
1944
+ }
1945
+ const maxRowId = (text: string): number => Math.max(0, ...text.split("\n").map((l) => (isOpenItem(l) || isDoneItem(l) ? (rowId(l) ?? 0) : 0)));
1946
+
1947
+ /** Give every checklist row without an id the next free one (counted over the archive too, so an id is never
1948
+ * reused). Idempotent; unchanged text comes back as is. */
1949
+ export function ensureReflectIds(text: string, archive = ""): string {
1950
+ let next = Math.max(maxRowId(text), maxRowId(archive));
1951
+ let changed = false;
1952
+ const out = text.split("\n").map((l) => {
1953
+ if ((!isOpenItem(l) && !isDoneItem(l)) || rowId(l) !== null) return l;
1954
+ changed = true;
1955
+ return l.replace(ROW_HEAD, `$1[r${++next}] `);
1956
+ });
1957
+ return changed ? out.join("\n") : text;
1958
+ }
1959
+
1960
+ /** Parse `r42`, `42`, `r3,r7` into ids; NaN marks a token that is not one. */
1961
+ export const parseRowIds = (arg: string): number[] => [...new Set(String(arg ?? "").split(",").map((p) => p.trim()).filter(Boolean).map((p) => (/^r?\d+$/i.test(p) ? Number(p.replace(/^r/i, "")) : Number.NaN)))];
1962
+
1963
+ /** How many times a row was reported: the filing, plus each `· seen again` a recurrence appended. */
1964
+ export const rowOccurrences = (line: string): number => 1 + (line.match(/ · seen again /g)?.length ?? 0);
1965
+
1966
+ /** A recurrence: append ` · seen again <stamp>[: evidence]` to open row `id` — the count, not a new row, ranks it.
1967
+ * null when no open row has that id. */
1968
+ export function reflectSame(text: string, id: number, stamp: string, evidence = ""): string | null {
1969
+ const row = reflectRow(text, id);
1970
+ if (!row?.open) return null;
1971
+ const lines = text.split("\n");
1972
+ lines[row.index] = `${lines[row.index].trimEnd()} · seen again ${stamp}${evidence.trim() ? `: ${evidence.trim()}` : ""}`;
1973
+ return lines.join("\n");
1974
+ }
1975
+
1976
+ /** Reopen closed row `id` in place: ` — fixed: X` becomes ` · reopened <stamp>: <why> (was fixed: X)`, so the
1977
+ * history stays on the row. null when no closed row has that id here. */
1978
+ export function reflectReopen(text: string, id: number, stamp: string, why: string): string | null {
1979
+ const row = reflectRow(text, id);
1980
+ if (!row || row.open) return null;
1981
+ const lines = text.split("\n");
1982
+ const l = lines[row.index].replace(/^(\s*)-\s*\[[xX]\]\s*/, "$1- [ ] ");
1983
+ const at = l.lastIndexOf(" — fixed: ");
1984
+ const was = at >= 0 ? l.slice(at + " — fixed: ".length) : "";
1985
+ lines[row.index] = `${at >= 0 ? l.slice(0, at) : l.trimEnd()} · reopened ${stamp}${why.trim() ? `: ${why.trim()}` : ""}${was ? ` (was fixed: ${was})` : ""}`;
1986
+ return lines.join("\n");
1987
+ }
1988
+
1989
+ /** What ties rows together for a fix plan: the files and code names a note mentions. */
1990
+ function rowTokens(body: string): Set<string> {
1991
+ const out = new Set<string>();
1992
+ for (const m of body.matchAll(/`([^`]{3,60})`/g)) out.add(m[1].toLowerCase().replace(/[()]+$/, ""));
1993
+ for (const m of body.matchAll(/\b[\w.-]*[\w-]\/[\w./-]*\w|\b[\w-][\w.-]*\.(?:ts|tsx|js|mjs|cjs|md|sh|yml|yaml|json|toml|rs|py)\b/g)) out.add(m[0].toLowerCase());
1994
+ return out;
1995
+ }
1996
+
1997
+ export interface FixGroup { section: string; ids: number[]; hits: number; topic: string; bodies: string[] }
1998
+
1999
+ /** "33 code items → a patch flow" left the grouping to the agent. Rows of a section that share a
2000
+ * file or code name (one no more than half the section shares) form a group — one flow each, ranked by how often
2001
+ * their rows were hit. Playbook rows are one group: a single docs flow takes them all. */
2002
+ export function reflectFixPlan(items: readonly ReflectItem[]): { groups: FixGroup[]; singles: FixGroup[] } {
2003
+ const groups: FixGroup[] = [];
2004
+ const singles: FixGroup[] = [];
2005
+ const slugPart = (t: string) => (t.split("/").filter(Boolean).pop() ?? t).replace(/\.[a-z]+$/i, "").replace(/[^a-z0-9]+/gi, "-").replace(/^-|-$/g, "").toLowerCase().slice(0, 24) || "misc";
2006
+ const docs = items.filter((i) => i.section === "playbook" || i.section === "unfiled");
2007
+ if (docs.length) groups.push({ section: "playbook", ids: docs.map((i) => i.n), hits: docs.reduce((n, i) => n + (i.hits ?? 1), 0), topic: "playbook", bodies: docs.map((i) => i.body) });
2008
+ const code = items.filter((i) => i.section === "code");
2009
+ const toks = code.map((i) => rowTokens(i.body));
2010
+ const df = new Map<string, number>();
2011
+ for (const t of toks) for (const k of t) df.set(k, (df.get(k) ?? 0) + 1);
2012
+ const parent = code.map((_, i) => i);
2013
+ const find = (i: number): number => (parent[i] === i ? i : (parent[i] = find(parent[i])));
2014
+ const owner = new Map<string, number>();
2015
+ toks.forEach((t, i) => {
2016
+ for (const k of t) {
2017
+ const n = df.get(k) ?? 0;
2018
+ if (n < 2 || n > Math.max(2, code.length / 2)) continue;
2019
+ const o = owner.get(k);
2020
+ if (o === undefined) owner.set(k, i);
2021
+ else parent[find(i)] = find(o);
2022
+ }
2023
+ });
2024
+ const byRoot = new Map<number, number[]>();
2025
+ code.forEach((_, i) => byRoot.set(find(i), [...(byRoot.get(find(i)) ?? []), i]));
2026
+ for (const members of byRoot.values()) {
2027
+ const shared = new Map<string, number>();
2028
+ for (const i of members) for (const k of toks[i]) if ((df.get(k) ?? 0) >= 2) shared.set(k, (shared.get(k) ?? 0) + 1);
2029
+ const topic = [...shared].sort((a, b) => b[1] - a[1] || a[0].length - b[0].length)[0]?.[0] ?? "";
2030
+ const g: FixGroup = { section: "code", ids: members.map((i) => code[i].n), hits: members.reduce((n, i) => n + (code[i].hits ?? 1), 0), topic: slugPart(topic || code[members[0]].body.split(/\s+/).slice(0, 3).join("-")), bodies: members.map((i) => code[i].body) };
2031
+ (members.length > 1 ? groups : singles).push(g);
2032
+ }
2033
+ groups.sort((a, b) => (a.section === "playbook" ? -1 : b.section === "playbook" ? 1 : b.hits - a.hits || b.ids.length - a.ids.length));
2034
+ singles.sort((a, b) => b.hits - a.hits);
2035
+ return { groups, singles };
2036
+ }
2037
+
2038
+ /** The closed rows of a ledger with the section each sits under — what `tidy` moves to the archive. */
2039
+ export function closedRowsBySection(text: string): { section: string; line: string }[] {
2040
+ const out: { section: string; line: string }[] = [];
2041
+ let section = "unfiled";
2042
+ for (const raw of text.split("\n")) {
2043
+ const l = raw.trim();
2044
+ if (ANY_HEADING.test(l)) { section = REFLECT_HEADING.exec(l)?.[1].toLowerCase() ?? "unfiled"; continue; }
2045
+ if (isDoneItem(l)) out.push({ section, line: l });
2046
+ }
2047
+ return out;
2048
+ }
2049
+
2050
+ /** Archive text with closed rows appended under their headings (`## section` blocks, appended per tidy). */
2051
+ export function archiveAppend(archive: string, rows: { section: string; line: string }[], stamp: string): string {
2052
+ if (!rows.length) return archive;
2053
+ const head = archive.trim() ? archive.trimEnd() : "# dev-flow reflections archive\n\n<!-- Closed reflections, moved here by flow reflect tidy. Ids are never reused; flow reflect reopen <id> brings one back. -->";
2054
+ const bySection = new Map<string, string[]>();
2055
+ for (const r of rows) bySection.set(r.section, [...(bySection.get(r.section) ?? []), r.line]);
2056
+ return `${head}\n\n<!-- tidy ${stamp} -->\n${[...bySection].map(([s, ls]) => `## ${s}\n\n${ls.join("\n")}`).join("\n\n")}\n`;
2057
+ }
1883
2058
 
1884
- /** One reflections.md item line — with no flow bound the slug is left out; `— - <date>` read as a broken slug. */
1885
- export function reflectionLine(note: string, slug: string | null, date: string): string {
1886
- return `- [ ] ${note.trim()} — ${slug ? `${slug} ` : ""}${date}`;
2059
+ /** Remove closed row `id` from archive text — the row comes back through reopen. */
2060
+ export function archiveTake(archive: string, id: number): { archive: string; row: { section: string; line: string } } | null {
2061
+ const lines = archive.split("\n");
2062
+ let section = "unfiled";
2063
+ for (let i = 0; i < lines.length; i++) {
2064
+ const l = lines[i].trim();
2065
+ if (ANY_HEADING.test(l)) { section = REFLECT_HEADING.exec(l)?.[1].toLowerCase() ?? "unfiled"; continue; }
2066
+ if (isDoneItem(l) && rowId(l) === id) {
2067
+ lines.splice(i, 1);
2068
+ return { archive: lines.join("\n"), row: { section, line: l } };
2069
+ }
2070
+ }
2071
+ return null;
1887
2072
  }
1888
2073
 
1889
2074
  export const REFLECT_HEADER =
@@ -1917,8 +2102,11 @@ export interface ReflectItem {
1917
2102
  body: string;
1918
2103
  /** gh#197: the row's stable number — its position among every checklist row of the file, open or closed. Checking
1919
2104
  * an item off leaves every other number where it was, so a batch of `done <n>` read off one list stays paired;
1920
- * only `tidy` (drops closed rows) and `move` (relocates one) renumber. */
2105
+ * only `tidy` (drops closed rows) and `move` (relocates one) renumber. gh#263: once rows carry ids (`[r42]`)
2106
+ * this is the id, which nothing renumbers. */
1921
2107
  n: number;
2108
+ /** how many times it was reported (the filing plus each `· seen again`) */
2109
+ hits?: number;
1922
2110
  }
1923
2111
 
1924
2112
  /** Open items of reflections.md, each carrying the heading that owns it. Items above every known
@@ -1937,7 +2125,9 @@ export function reflectItems(text: string): ReflectItem[] {
1937
2125
  }
1938
2126
  if (isDoneItem(l)) row++;
1939
2127
  if (!isOpenItem(l)) continue;
1940
- out.push({ section, line: l, body: reflectionBody(l), n: ++row });
2128
+ // the row's id once it has one; a ledger not yet given ids keeps the old position numbering
2129
+ row++;
2130
+ out.push({ section, line: l, body: reflectionBody(l), n: rowId(l) ?? row, hits: rowOccurrences(l) });
1941
2131
  }
1942
2132
  return out;
1943
2133
  }
@@ -1945,11 +2135,14 @@ export function reflectItems(text: string): ReflectItem[] {
1945
2135
  /** Row `n` of reflections.md (the stable numbering, gh#197): its line index and whether it is still open; null when no such row. */
1946
2136
  export function reflectRow(text: string, n: number): { index: number; open: boolean; line: string } | null {
1947
2137
  const lines = text.split("\n");
2138
+ // gh#263: a ledger with ids is addressed by id only — a position never stands in for one
2139
+ const byId = lines.some((l) => (isOpenItem(l) || isDoneItem(l)) && rowId(l) !== null);
1948
2140
  let row = 0;
1949
2141
  for (let i = 0; i < lines.length; i++) {
1950
2142
  const open = isOpenItem(lines[i]);
1951
2143
  if (!open && !isDoneItem(lines[i])) continue;
1952
- if (++row === n) return { index: i, open, line: lines[i].trim() };
2144
+ row++;
2145
+ if (byId ? rowId(lines[i]) === n : row === n) return { index: i, open, line: lines[i].trim() };
1953
2146
  }
1954
2147
  return null;
1955
2148
  }
@@ -2039,7 +2232,7 @@ const CODE_ROUTE = "patch flow (flow start fix-<topic> --patch), normal flow whe
2039
2232
 
2040
2233
  export function reflectionRoutes(items: ReflectItem[], selfRepo: boolean): ReflectionRoute[] {
2041
2234
  return items.map((it) => {
2042
- const text = it.line.replace(/^-\s*\[[ xX]\]\s*/, "").trim();
2235
+ const text = it.line.replace(/^-\s*\[[ xX]\]\s*/, "").replace(/^\[r\d+\]\s*/, "").trim();
2043
2236
  const sections = [it.section];
2044
2237
  if (it.section === "code") return { text, sections, mode: "code" as const, route: CODE_ROUTE };
2045
2238
  if (it.section === "plugin")
@@ -2207,7 +2400,7 @@ export function reflectionNudges(text: string, today: string, opts: { recurred?:
2207
2400
  let fix: string | null = null;
2208
2401
  if (open.length && why.length) {
2209
2402
  const split = [docs ? `${docs} playbook item(s) → one docs flow (flow start fold-<topic> --docs)` : "", code ? `${code} code item(s) → patch flow (flow start fix-<topic> --patch)` : ""].filter(Boolean).join("; ");
2210
- fix = `⚑ fix the open reflections now? (${why.join(", ")}) — ${split}`;
2403
+ fix = `⚑ fix the open reflections now? (${why.join(", ")}) — ${split}; flow reflect plan groups them into flows`;
2211
2404
  }
2212
2405
  const closedLines = text.split("\n").filter(isDoneItem);
2213
2406
  const closed = closedLines.length;
@@ -2397,6 +2590,14 @@ export function compactionStateBlock(state: FlowState, cfg: Config): string {
2397
2590
  * holds the how; this carries only what the gate knows and the file cannot: paths, the playbook's
2398
2591
  * merge command, which versioning steps apply. */
2399
2592
  export function nextHint(state: FlowState, cfg: Config): string {
2593
+ const base = stageHint(state, cfg);
2594
+ // the linked reflection rows ride every hint until finish closes them: fixed by this branch, or deferred with a reason
2595
+ const open = (state.reflections ?? []).filter((r) => !r.deferred);
2596
+ if (!open.length || state.stage === "release") return base;
2597
+ return `${base} — linked reflections ${open.map((r) => `r${r.id}`).join(", ")}: fix each on this branch (finish closes them as fixed), or flow reflect defer <id> "<why>" for one it will not fix`;
2598
+ }
2599
+
2600
+ function stageHint(state: FlowState, cfg: Config): string {
2400
2601
  switch (state.stage) {
2401
2602
  case "plan":
2402
2603
  if (state.patch || state.docs) return `${state.patch ? "patch" : "docs"} (proposed — the Approve? answer grants the mode): describe the change in one line, ask Approve? in chat naming the mode, then flow approve --confirmed — no plan file${state.docs ? ", no tier-1 checks" : ""}`;
@@ -2567,11 +2768,26 @@ export const WORKER_BUDGET_MIN: Record<WorkerOp, number> = { implement: 60, revi
2567
2768
  /** Times a worker that stopped without its REPORT is told to keep going before the run gives up. */
2568
2769
  export const WORKER_NUDGES = 2;
2569
2770
 
2570
- export const clampBudgetMin = (n: unknown, op: WorkerOp): number => {
2571
- const v = typeof n === "number" && Number.isFinite(n) ? n : WORKER_BUDGET_MIN[op];
2771
+ export const clampBudgetMin = (n: unknown, op: WorkerOp, size?: WorkerSize): number => {
2772
+ const v = typeof n === "number" && Number.isFinite(n) ? n : defaultBudgetMin(op, size);
2572
2773
  return Math.min(180, Math.max(5, Math.round(v)));
2573
2774
  };
2574
2775
 
2776
+ /** How much a worker has to read: the transcripts a reflection reviews, the diff a review reads. */
2777
+ export interface WorkerSize { transcriptBytes?: number; diffLines?: number }
2778
+
2779
+ /** The default budget, grown with the work (gh#252). One default for every flow cut a long flow's reflection off
2780
+ * at 20 min three times in a day — it returned nothing and finish removed nothing — and a 1,600-line review ran
2781
+ * its whole 30. A reflection gets 5 min per 250 KB of transcript past the first 250 KB (up to 60); a review
2782
+ * 10 min per 500 changed lines past the first 500 (up to 90). An explicit budgetMin always wins. */
2783
+ export function defaultBudgetMin(op: WorkerOp, size: WorkerSize = {}): number {
2784
+ const base = WORKER_BUDGET_MIN[op];
2785
+ const steps = (amount: number | undefined, free: number, per: number) => Math.max(0, Math.ceil(((amount ?? 0) - free) / per));
2786
+ if (op === "reflect") return Math.min(60, base + 5 * steps(size.transcriptBytes, 250_000, 250_000));
2787
+ if (op === "review") return Math.min(90, base + 10 * steps(size.diffLines, 500, 500));
2788
+ return base;
2789
+ }
2790
+
2575
2791
  /** Why an op is not legal for a feature at this stage, or null. */
2576
2792
  export function workerOpError(op: string, stage: Stage): string | null {
2577
2793
  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)`;
@@ -2720,20 +2936,51 @@ export const WORKER_NUDGE = "You stopped before finishing and without the REPORT
2720
2936
  /** The nudge a read-only worker (review, reflect) gets — it has nothing to commit. */
2721
2937
  export const WORKER_NUDGE_READONLY = "You stopped before finishing and without the REPORT section. Continue the task now (keep using tools; change no files). When it is done — or you are truly blocked — end with the `REPORT` section the contract asks for.";
2722
2938
 
2723
- /** Share of the budget at which a worker is steered to wrap up (gh#142's grace, restored for every op). */
2939
+ /** Share of the budget at which a worker is steered to wrap up (gh#142's grace, restored for every op). A steer
2940
+ * is delivered between turns, and a read-only worker on a thinking model spends minutes in one turn — the 75%
2941
+ * steer reached the 20-min reflection after the cut (gh#252) — so review and reflect are steered at 60%. */
2724
2942
  export const WORKER_STEER_AT = 0.75;
2943
+ export const workerSteerAt = (op: WorkerOp): number => (op === "implement" ? WORKER_STEER_AT : 0.6);
2725
2944
 
2726
2945
  /** Grace after the hard cut: one REPORT-only prompt, so an interrupted worker hands back what it found. */
2727
2946
  export const WORKER_SALVAGE_MS = 3 * 60_000;
2728
2947
 
2729
2948
  /** The steer a worker gets at WORKER_STEER_AT of its budget — wrap up while there is time to. */
2730
2949
  export function workerSteer(op: WorkerOp, budgetMin: number): string {
2731
- const left = Math.max(1, Math.round(budgetMin * (1 - WORKER_STEER_AT)));
2950
+ const left = Math.max(1, Math.round(budgetMin * (1 - workerSteerAt(op))));
2732
2951
  return op === "implement"
2733
2952
  ? `Time check: about ${left} min of your ${budgetMin}-min budget are left. Finish the edit in hand, commit what works, and end with the REPORT section now (done, commits, open items, risks) — an honest partial report beats being cut off.`
2734
2953
  : `Time check: about ${left} min of your ${budgetMin}-min budget are left. Stop probing and write the REPORT section now with what you have — rows you could not fully prove say so in their evidence. Being cut off loses every finding.`;
2735
2954
  }
2736
2955
 
2956
+ /** The visible text of every assistant message, in order (thinking excluded: rows are written, not mused). */
2957
+ export function assistantTexts(messages: readonly unknown[]): string[] {
2958
+ const out: string[] = [];
2959
+ for (const m of messages) {
2960
+ const msg = m as { role?: string; content?: unknown };
2961
+ if (msg?.role !== "assistant") continue;
2962
+ if (typeof msg.content === "string") out.push(msg.content);
2963
+ else if (Array.isArray(msg.content)) for (const c of msg.content as { type?: string; text?: string }[]) if (c?.type === "text" && c.text) out.push(c.text);
2964
+ }
2965
+ return out;
2966
+ }
2967
+
2968
+ /** The finding rows a reflection already wrote in any of its messages, as a REPORT body — the last fallback when
2969
+ * the salvage turn returned nothing (gh#252): rows written before the cut are findings, not lost work. A later
2970
+ * row for the same F<n>/O<n> replaces an earlier one. Null when there are none. */
2971
+ export function recoverReflectRows(texts: readonly string[]): string | null {
2972
+ const rows = new Map<string, string>();
2973
+ for (const t of texts)
2974
+ for (const raw of (t ?? "").split("\n")) {
2975
+ const m = /^[\s>*`-]*([FO]\d+)\s*\|/i.exec(raw);
2976
+ if (m) rows.set(m[1].toUpperCase(), raw.trim());
2977
+ }
2978
+ if (!rows.size) return null;
2979
+ const body = [...rows.values()].join("\n");
2980
+ const parsed = parseReflectReport(body);
2981
+ return parsed.findings.length || parsed.open.length ? body : null;
2982
+ }
2983
+
2737
2984
  /** The prompt an interrupted worker gets once after the hard cut — report only, no more tools. */
2738
2985
  export const WORKER_SALVAGE = "Your time budget is spent and your last turn was interrupted. Do not call any more tools. Reply now with only the REPORT section the contract asks for, from what you already found (mark anything unfinished or unproven as such).";
2739
2986
 
@@ -2878,7 +3125,7 @@ export interface ReflectBriefInput {
2878
3125
  * the operator decides fold or drop per finding in the driving session. */
2879
3126
  export function buildReflectBrief(o: ReflectBriefInput): string {
2880
3127
  const up = o.upstream || "(unknown — say so in the REPORT)";
2881
- const open = o.items.length ? o.items.map((it) => ` ${it.n}. [${it.section}] ${it.line.replace(/^- \[ \] /, "")}`).join("\n") : " (none)";
3128
+ const open = o.items.length ? o.items.map((it) => ` r${it.n}. [${it.section}] ${it.line.replace(/^- \[ \] /, "").replace(/^\[r\d+\]\s*/, "")}`).join("\n") : " (none)";
2882
3129
  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)";
2883
3130
  const digests = o.digests?.length ? o.digests.map((d) => ` - ${d.digest} (of ${path.basename(d.transcript)})`).join("\n") : "";
2884
3131
  const upIssues = o.upstreamIssues ? (o.upstreamIssues.length ? o.upstreamIssues.map((i) => ` gh#${i.number} [${i.state.toLowerCase()}] ${i.title}`).join("\n") : " (none)") : "";
@@ -2917,8 +3164,8 @@ export function buildReflectBrief(o: ReflectBriefInput): string {
2917
3164
  "## Contract",
2918
3165
  "- Check, don't fix: read and run read-only probes only. Change no files, make no commits, file nothing.",
2919
3166
  "- Finish with a final message whose last section starts with a line `REPORT`, then one row per line, pipe-separated, nothing else in the section:",
2920
- " F<n> | fold|drop | docs|code|plugin | <one-line note, written as the reflection itself> | dup: none|#<open item>|gh#<N> | why: <reason> | evidence: <transcript file:line or a short quote>",
2921
- " O<n> | still-open|fixed|recurred | <reason, with evidence>",
3167
+ " F<n> | fold|drop | docs|code|plugin | <one-line note, written as the reflection itself> | dup: none|r<open item id>|gh#<N> | why: <reason> | evidence: <transcript file:line or a short quote>",
3168
+ " O<id> | still-open|fixed|recurred | <reason, with evidence> (<id> is the open item's r<n> above, digits only)",
2922
3169
  " (no findings → a single line `F0 | none`; no open items → no O rows)",
2923
3170
  ].join("\n");
2924
3171
  }
@@ -2965,23 +3212,57 @@ export function parseReflectReport(body: string): { findings: ReflectFinding[];
2965
3212
  return { findings, open };
2966
3213
  }
2967
3214
 
2968
- /** The numbered list the driver shows the operator: one row per finding with its route, then the
2969
- * open-item re-check. Routes follow where the fix lives — plugin is always an upstream issue
2970
- * (code in the dev-flow repo itself), never a local row. */
3215
+ /** A finding as one short operator-facing line: clipped at a word boundary, with any dev-flow command text
3216
+ * spelled as plain words. The view drops a line that names a flow command, so a finding that merely quoted
3217
+ * one (`flow finish` removed nothing) vanished from the list the operator was answering about. */
3218
+ export function shortFindingNote(note: string, max = 110): string {
3219
+ const plain = note
3220
+ .replace(/`([^`]*)`/g, "$1")
3221
+ .replace(/(^|[\s'"(*_])\/?flow (?=[a-z])/g, "$1")
3222
+ .replace(/(^|\s)--(?=[a-z])/g, "$1")
3223
+ .replace(/\bflow_stage\b/g, "worker")
3224
+ .replace(/\s+/g, " ")
3225
+ .trim();
3226
+ if (plain.length <= max) return plain;
3227
+ const cut = plain.slice(0, max);
3228
+ const at = cut.lastIndexOf(" ");
3229
+ return `${(at > max * 0.6 ? cut.slice(0, at) : cut).replace(/[\s,;:—-]+$/, "")}…`;
3230
+ }
3231
+
3232
+ /** The fold/drop list the operator answers (gh#260): a short line per finding, the suggested folds first —
3233
+ * grouped by where the fix lives (plugin, playbook, code) — then the suggested drops, so "fold 2" names
3234
+ * something they can read. The full rows (route, dup, why) follow for the agent only. Routes follow where
3235
+ * the fix lives — plugin is always an upstream issue (code in the dev-flow repo itself), never a local row. */
2971
3236
  export function renderReflectFindings(r: { findings: ReflectFinding[]; open: ReflectOpenCheck[] }, selfRepo: boolean): string[] {
3237
+ const kindOf = (f: ReflectFinding): ReflectKind => (f.kind === "plugin" && selfRepo ? "code" : f.kind);
2972
3238
  const route = (k: ReflectKind) =>
2973
- k === "docs" ? "docs flow · record: flow reflect --playbook" : k === "code" || selfRepo ? "patch flow · record: flow reflect --code" : "upstream GitHub issue · flow reflect --plugin prints the recipe (never a local row)";
3239
+ k === "docs" ? "docs flow · record: flow reflect --playbook" : k === "code" ? "patch flow · record: flow reflect --code" : "upstream GitHub issue · flow reflect --plugin prints the recipe (never a local row)";
3240
+ const KIND_LABEL: Record<ReflectKind, string> = { plugin: "plugin (an upstream dev-flow issue)", docs: "playbook (a docs flow)", code: "code (a patch flow)" };
2974
3241
  const out: string[] = [];
2975
3242
  if (r.findings.length) {
2976
- out.push(`findings (${r.findings.length}) — recommendation · kind → route:`);
3243
+ const folds = r.findings.filter((f) => f.rec === "fold");
3244
+ const drops = r.findings.filter((f) => f.rec === "drop");
3245
+ const nums = (fs: ReflectFinding[]) => fs.map((f) => f.n).join(",");
3246
+ out.push(`findings (${r.findings.length}) — suggested: ${[folds.length ? `fold ${nums(folds)}` : "", drops.length ? `drop ${nums(drops)}` : ""].filter(Boolean).join(" · ")}`);
3247
+ for (const k of ["plugin", "docs", "code"] as const) {
3248
+ const group = folds.filter((f) => kindOf(f) === k);
3249
+ if (!group.length) continue;
3250
+ out.push(`fold — ${KIND_LABEL[k]}:`);
3251
+ for (const f of group) out.push(` ${f.n}. ${shortFindingNote(f.note)}`);
3252
+ }
3253
+ if (drops.length) {
3254
+ out.push("drop:");
3255
+ for (const f of drops) out.push(` ${f.n}. ${shortFindingNote(f.note)} (${kindOf(f) === "docs" ? "playbook" : kindOf(f)})`);
3256
+ }
3257
+ out.push(`${AGENT_MARK}finding detail — recommendation · kind → route:`);
2977
3258
  for (const f of r.findings) {
2978
- out.push(` ${f.n}. [${f.rec}] ${f.kind}: ${f.note}`);
2979
- out.push(` → ${route(f.kind === "plugin" && selfRepo ? "code" : f.kind)}${f.dup && f.dup !== "none" ? ` · dup: ${f.dup}` : ""}${f.why ? ` · ${f.why}` : ""}`);
3259
+ out.push(`${AGENT_MARK}${f.n}. [${f.rec}] ${f.kind}: ${f.note}`);
3260
+ out.push(`${AGENT_MARK} → ${route(kindOf(f))}${f.dup && f.dup !== "none" ? ` · dup: ${f.dup}` : ""}${f.why ? ` · ${f.why}` : ""}`);
2980
3261
  }
2981
3262
  } else out.push("findings: none");
2982
3263
  if (r.open.length) {
2983
3264
  out.push("open items re-checked:");
2984
- for (const o of r.open) out.push(` #${o.n} ${o.status}${o.reason ? ` — ${o.reason}` : ""}${o.status === "fixed" ? " → propose the check-off" : o.status === "recurred" ? " → recommend fixing it now" : ""}`);
3265
+ for (const o of r.open) out.push(` r${o.n} ${o.status}${o.reason ? ` — ${o.reason}` : ""}${o.status === "fixed" ? " → propose the check-off" : o.status === "recurred" ? " → recommend fixing it now" : ""}`);
2985
3266
  }
2986
3267
  return out;
2987
3268
  }