pi-dev-flow 0.76.1 → 0.77.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
@@ -47,6 +47,7 @@ export interface FlowState {
47
47
  forgeReleaseSkipped?: string; // a gh/glab release create that failed: release-done says so, finish names it so the missing forge release cannot slip past (#63)
48
48
  staleBuild?: string; // release ran under an older dev-flow than the checkout by operator choice ("<loaded> (checkout <disk>)"); release-done repeats the acknowledgement
49
49
  pendingAsk?: string; // the checkpoint word a gate asked for and has not been given ("Approve?", "Verified?", …) — presentation only (💬 in the footer), it never gates
50
+ reflectedAt?: string; // a flow_stage reflect worker reported for this flow — finish names a missing one (advisory, never a block)
50
51
  aborted?: string; // flow abort on a feature whose worktree exists: the state is a deliberate abandoned-feature record (gh#138) — the doctor's git-consistency sweep must never flag its hand-removed worktree as drift
51
52
  }
52
53
 
@@ -1505,15 +1506,21 @@ export function reflectionLine(note: string, slug: string | null, date: string):
1505
1506
  }
1506
1507
 
1507
1508
  export const REFLECT_HEADER =
1508
- "# dev-flow reflections\n\n<!-- Suggestions queued by the agent; the operator decides. Fold playbook items in via flow init --write, file plugin items as issues; check off when handled. -->\n";
1509
+ "# dev-flow reflections\n\n<!-- This project's queue, filed by the agent; the operator decides. ## playbook = fix in project.md (docs flow), ## code = fix in code (patch flow). dev-flow plugin feedback never lands here — it is filed as a GitHub issue upstream. Check off when handled. -->\n";
1509
1510
 
1510
- /** The two reflections.md sections, in document order. */
1511
- export const REFLECT_SECTIONS = ["playbook", "plugin"] as const;
1511
+ /** The sections a note can be written to, in document order: `playbook` — the fix lives only in
1512
+ * project.md (docs flow); `code` — the fix touches project code, maybe the playbook too (patch flow).
1513
+ * Plugin feedback has no section: it is filed as an upstream GitHub issue, never kept locally. */
1514
+ export const REFLECT_SECTIONS = ["playbook", "code"] as const;
1512
1515
  export type ReflectSection = (typeof REFLECT_SECTIONS)[number];
1516
+ /** `## plugin` from before plugin notes went upstream: still read (and flagged), never written to. */
1517
+ const LEGACY_SECTIONS = ["plugin"] as const;
1518
+ type KnownSection = ReflectSection | (typeof LEGACY_SECTIONS)[number];
1519
+ const KNOWN_SECTIONS: readonly KnownSection[] = [...REFLECT_SECTIONS, ...LEGACY_SECTIONS];
1513
1520
 
1514
1521
  /** One matcher for the section headings: the writer, the tidy and the reader share it, so a heading
1515
1522
  * one of them accepts cannot be invisible to another. */
1516
- const REFLECT_HEADING = new RegExp(`^##\\s*(${REFLECT_SECTIONS.join("|")})\\s*$`, "i");
1523
+ const REFLECT_HEADING = new RegExp(`^##\\s*(${KNOWN_SECTIONS.join("|")})\\s*$`, "i");
1517
1524
  /** Any `## …` line claims the items under it — one that names no section leaves them unfiled, so the
1518
1525
  * reader (and doctor) can say so instead of inheriting whichever heading came before. */
1519
1526
  const ANY_HEADING = /^##/;
@@ -1521,8 +1528,8 @@ const ANY_HEADING = /^##/;
1521
1528
  /** An open reflections.md item together with the section that owns it. The heading is the record of
1522
1529
  * where a note was filed; the keyword guess is made once, when the note is queued. */
1523
1530
  export interface ReflectItem {
1524
- /** the `## section` the line sits under; "unfiled" = above every heading or under an unknown one */
1525
- section: ReflectSection | "unfiled";
1531
+ /** the `## section` the line sits under; "plugin" = legacy heading (belongs on GitHub); "unfiled" = above every heading or under an unknown one */
1532
+ section: KnownSection | "unfiled";
1526
1533
  /** the verbatim `- [ ] …` line, trimmed */
1527
1534
  line: string;
1528
1535
  /** the note without checkbox and without the ` — attribution` tail */
@@ -1534,12 +1541,12 @@ export interface ReflectItem {
1534
1541
  * silently inheriting whichever bucket came before them. */
1535
1542
  export function reflectItems(text: string): ReflectItem[] {
1536
1543
  const out: ReflectItem[] = [];
1537
- let section: ReflectSection | "unfiled" = "unfiled";
1544
+ let section: KnownSection | "unfiled" = "unfiled";
1538
1545
  for (const raw of text.split("\n")) {
1539
1546
  const l = raw.trim();
1540
1547
  if (ANY_HEADING.test(l)) {
1541
1548
  const h = REFLECT_HEADING.exec(l);
1542
- section = h ? (h[1].toLowerCase() as ReflectSection) : "unfiled";
1549
+ section = h ? (h[1].toLowerCase() as KnownSection) : "unfiled";
1543
1550
  continue;
1544
1551
  }
1545
1552
  if (!isOpenItem(l)) continue;
@@ -1551,6 +1558,8 @@ export function reflectItems(text: string): ReflectItem[] {
1551
1558
  /** Open items the file does not place in a known section — doctor names the count so a note that
1552
1559
  * would once have quietly migrated to `## playbook` on the next write gets moved on purpose. */
1553
1560
  export const reflectUnfiledCount = (text: string) => reflectItems(text).filter((i) => i.section === "unfiled").length;
1561
+ /** Open items still under the legacy `## plugin` heading — doctor and list ask for each to be filed upstream. */
1562
+ export const reflectLegacyPluginCount = (text: string) => reflectItems(text).filter((i) => i.section === "plugin").length;
1554
1563
 
1555
1564
  // The classifier decides where a note being queued LANDS — nothing re-derives it afterwards.
1556
1565
  // Signals are ranked. A note that names dev-flow's own surface is a plugin issue, and its commands
@@ -1566,15 +1575,18 @@ const PLAYBOOK_STRONG = /project\.md|playbook|checklist|defaultBranch|merge poli
1566
1575
  const PLUGIN_WEAK = /\b(plugin|extension|dev-flow|tool|session|compact\w*|hook|status bar)\b/i;
1567
1576
  const PLAYBOOK_WEAK = /\b(playbook|checklist|versioning|prose|setup|docs?|readme)\b/i;
1568
1577
 
1578
+ /** Where a note belongs: one of this project's sections, or `plugin` — dev-flow itself, filed upstream. */
1579
+ export type ReflectTarget = ReflectSection | "plugin";
1580
+
1569
1581
  export interface ReflectGuess {
1570
- sections: ReflectSection[];
1582
+ target: ReflectTarget;
1571
1583
  /** why the note landed there — printed, so a wrong guess is visible at the moment it is filed */
1572
1584
  why: string;
1573
1585
  }
1574
1586
 
1575
- /** Where a fresh note lands: ONE primary home. Writing a both-shaped note to both sections made the
1576
- * operator check the same issue off twice while only the plugin half ever got a route. A strong
1577
- * plugin signal wins; otherwise the playbook, where the operator reads it and can move it. */
1587
+ /** Where a fresh note lands: ONE home. A strong plugin signal wins (it goes upstream, not into the
1588
+ * file); otherwise the playbook, where the operator reads it and can move it. `code` is never a
1589
+ * guess — the agent states it with --code. */
1578
1590
  export function guessReflectSections(note: string): ReflectGuess {
1579
1591
  // never classify the ` — <slug> <date>` tail: slugs are made of "guard", "release", "versioning"
1580
1592
  const body = reflectionBody(note);
@@ -1584,36 +1596,58 @@ export function guessReflectSections(note: string): ReflectGuess {
1584
1596
  const hits = [...body.matchAll(PLUGIN_STRONG_ALL)]
1585
1597
  .map((m) => m[0].trim())
1586
1598
  .filter((h) => !(qualified && /gates?|guards?/i.test(h)));
1587
- if (hits.length) return { sections: ["plugin"], why: `"${hits[0]}" names dev-flow itself` };
1599
+ if (hits.length) return { target: "plugin", why: `"${hits[0]}" names dev-flow itself` };
1588
1600
  const plug = PLUGIN_WEAK.test(body);
1589
1601
  const playStrong = PLAYBOOK_STRONG.test(body);
1590
1602
  const play = playStrong || PLAYBOOK_WEAK.test(body);
1591
- if (plug && !play) return { sections: ["plugin"], why: "plugin wording" };
1592
- if (play) return { sections: ["playbook"], why: playStrong ? "playbook or project wording" : "playbook wording" };
1593
- return { sections: ["playbook"], why: "nothing plugin-shaped in the note — if it is a dev-flow bug: flow reflect move <n> --plugin" };
1603
+ if (plug && !play) return { target: "plugin", why: "plugin wording" };
1604
+ if (play) return { target: "playbook", why: playStrong ? "playbook or project wording" : "playbook wording" };
1605
+ return { target: "playbook", why: "nothing plugin-shaped in the note — a code fix: flow reflect move <n> --code; a dev-flow bug: file it upstream (flow reflect --plugin)" };
1606
+ }
1607
+
1608
+ /** How a plugin note is filed: never into reflections.md — search the upstream tracker, then open an
1609
+ * issue whose body ends in the `— reflection from` tail the fold matches on. dev-flow runs nothing
1610
+ * itself; the agent runs these on the operator's fold answer. */
1611
+ export function pluginIssueRecipe(note: string, upstream: string, slug: string | null, date: string): string[] {
1612
+ const title = reflectionBody(note).replace(/"/g, "'");
1613
+ const tail = `— reflection from ${slug ? `${slug} ` : ""}${date}`;
1614
+ if (!upstream)
1615
+ return [
1616
+ `plugin note — not written to reflections.md (dev-flow feedback is filed upstream, never kept in a project): "${title}"`,
1617
+ "upstream repo unknown — ask the operator for the dev-flow repo, then file a GitHub issue with a detailed description, session evidence and a suggested fix,",
1618
+ `ending the body with '${tail}'.`,
1619
+ ];
1620
+ return [
1621
+ `plugin note — not written to reflections.md (dev-flow feedback is filed upstream, never kept in a project): "${title}"`,
1622
+ `1. dedupe: gh issue list --repo ${upstream} --state all --search "<keywords>" — an issue the author already answered (fixed in v… / won't-fix) is reported back, never re-filed.`,
1623
+ `2. no match: gh issue create --repo ${upstream} --title "${title}" --body "<what happened, session evidence, suggested fix>\n\n${tail}"`,
1624
+ "3. report the issue URL to the operator. No gh / offline: hand the operator the title and body to file by hand.",
1625
+ ];
1594
1626
  }
1595
1627
 
1596
1628
  /** Where a fix must be implemented: every fix runs through a flow whose gates confirm it —
1597
- * playbook-only change → docs flow; code in the dev-flow repo → patch/normal flow;
1598
- * plugin feedback in someone else's repo → upstream issue (dev-flow files nothing itself). */
1629
+ * playbook-only change → docs flow; code change → patch flow (normal flow when bigger); a legacy
1630
+ * `## plugin` row → upstream issue (or the code route in the dev-flow repo itself). */
1599
1631
  export interface ReflectionRoute {
1600
1632
  text: string;
1601
- sections: ReflectSection[];
1633
+ sections: (KnownSection | "unfiled")[];
1602
1634
  mode: "docs" | "code" | "upstream";
1603
1635
  route: string;
1604
1636
  }
1605
1637
 
1638
+ const DOCS_ROUTE = "docs flow (flow start fold-<topic> --docs --confirmed) — project.md edits only pass its worktree";
1639
+ const CODE_ROUTE = "patch flow (flow start fix-<topic> --patch --confirmed), normal flow when bigger";
1640
+
1606
1641
  export function reflectionRoutes(items: ReflectItem[], selfRepo: boolean): ReflectionRoute[] {
1607
1642
  return items.map((it) => {
1608
1643
  const text = it.line.replace(/^-\s*\[[ xX]\]\s*/, "").trim();
1609
- // the heading the item lives under IS the filing; a both-flagged note sits under both headings
1610
- // and therefore yields one item per section, each with its own route.
1611
- const sections: ReflectSection[] = it.section === "unfiled" ? ["playbook"] : [it.section];
1612
- if (sections.includes("plugin"))
1644
+ const sections = [it.section];
1645
+ if (it.section === "code") return { text, sections, mode: "code" as const, route: CODE_ROUTE };
1646
+ if (it.section === "plugin")
1613
1647
  return selfRepo
1614
- ? { text, sections, mode: "code" as const, route: "patch flow for a small fix (flow start fix-<topic> --patch --confirmed), normal flow when bigger" }
1615
- : { text, sections, mode: "upstream" as const, route: "file an issue against pi-dev-flow upstream (manual — dev-flow files nothing itself); copy the item text there" };
1616
- return { text, sections, mode: "docs", route: "docs flow (flow start fold-<topic> --docs --confirmed) — project.md edits only pass its worktree" };
1648
+ ? { text, sections, mode: "code" as const, route: `${CODE_ROUTE} — legacy ## plugin row: flow reflect move <n> --code files it where it belongs` }
1649
+ : { text, sections, mode: "upstream" as const, route: "legacy ## plugin row — belongs on GitHub, not here: file it upstream (flow reflect --plugin \"<note>\" prints the recipe), then check it off '— filed: gh#NNN'" };
1650
+ return { text, sections, mode: "docs" as const, route: DOCS_ROUTE };
1617
1651
  });
1618
1652
  }
1619
1653
 
@@ -1640,40 +1674,53 @@ export function reflectMove(text: string, n: number, section: ReflectSection): s
1640
1674
  * the plugin has no LLM; the agent investigates, the gates confirm, the flow implements. */
1641
1675
  export function investigationBrief(note: string, selfRepo: boolean): string[] {
1642
1676
  const guess = guessReflectSections(note);
1643
- const [route] = reflectionRoutes([{ section: guess.sections[0], line: `- [ ] ${note.trim()}`, body: note.trim() }], selfRepo);
1677
+ const target = guess.target === "plugin" ? (selfRepo ? "code" : "plugin") : guess.target;
1678
+ const route =
1679
+ target === "plugin"
1680
+ ? "file a GitHub issue upstream (flow reflect --plugin \"<note>\" prints the recipe) — plugin notes never go into reflections.md"
1681
+ : target === "code"
1682
+ ? CODE_ROUTE
1683
+ : DOCS_ROUTE;
1644
1684
  return [
1645
- `investigate: "${route.text}"`,
1685
+ `investigate: "${note.trim()}"`,
1646
1686
  "read first: .dev-flow/project.md, flow doctor findings, and whatever files the note names.",
1647
- `if it is real it belongs in ## ${route.sections[0]} (${guess.why})`,
1648
- `fix routing: ${route.route}`,
1687
+ target === "plugin" ? `if it is real it is dev-flow feedback (${guess.why}) — an upstream issue, not a local row` : `if it is real it belongs in ## ${target} (${guess.why})`,
1688
+ `fix routing: ${route}`,
1649
1689
  "the note is not implemented by doctor — propose the fix to the operator first; only after they confirm, open the routed flow; its gates carry the confirmation.",
1650
1690
  ];
1651
1691
  }
1652
1692
 
1653
- /** Bare `flow reflect`: the full session-reflection protocol for the agent (the plugin has no LLM —
1654
- * the agent reviews the session log, re-checks open items against shipped fixes, dedupes new
1655
- * findings and puts the fix decision to the operator). Writes nothing, runs no network calls. */
1656
- export function reflectProtocol(items: ReflectItem[], selfRepo: boolean, facts: { version: string | null; upstream: string; closed?: number; ghFold?: { repo: string; open: number; similar: number } }): string[] {
1693
+ /** Bare `flow reflect`: the session-reflection protocol for the agent (the plugin has no LLM). Bound to
1694
+ * a flow, the review itself is delegated to a fresh reflect worker (flow_stage op "reflect") that reads
1695
+ * the driver's and every worker's transcript; unbound, the agent runs the review inline. Either way the
1696
+ * operator decides fold or drop per finding. Writes nothing, runs no network calls. */
1697
+ export function reflectProtocol(
1698
+ items: ReflectItem[],
1699
+ selfRepo: boolean,
1700
+ facts: { version: string | null; upstream: string; tidy?: string | null; fix?: string | null; bound?: boolean; ghFold?: { repo: string; open: number; similar: number } },
1701
+ ): string[] {
1657
1702
  const ver = facts.version ? `dev-flow ${facts.version}` : "dev-flow version unknown";
1658
1703
  const up = facts.upstream || "<upstream — ask the operator for the dev-flow repo>";
1659
1704
  const url = facts.upstream ? `https://github.com/${facts.upstream}` : "<upstream-url>";
1705
+ const review = facts.bound
1706
+ ? '1. delegate the review: call flow_stage(op: "reflect", note: "<anything the operator said about friction this session>") — a fresh read-only reviewer reads this session\'s transcript and every flow_stage worker transcript, re-checks the open items below and returns a classified list (docs / code / plugin) with a fold-or-drop recommendation per finding. Only if the worker fails, do the review inline: read the full session log — every message, tool call and result.'
1707
+ : "1. review the current session log in full — every message, tool call and result: friction, wrong turns, repeated failures, guards or gates that misfired, playbook drift, optimization candidates. Classify each finding: docs (fix only in project.md), code (fix in this project's code, maybe the playbook too) or plugin (dev-flow itself).";
1660
1708
  const lines = [
1661
1709
  `flow reflect — session reflection (${ver}, upstream: ${up})`,
1662
1710
  "this output is your work instruction: execute these steps now — do not echo the protocol and do not ask to begin.",
1663
- "queue: .dev-flow/reflections.md — gitignored and yours to edit; check items off as `- [x] … — fixed: <what or where>`; a note filed under the wrong heading is moved with flow reflect move <n> --plugin|--playbook (flow reflect list numbers them).",
1664
- "1. review the current session log in full — every message, tool call and result: friction, wrong turns, repeated failures, guards or gates that misfired, playbook drift, optimization candidates. Decide each one BEFORE queueing — you know what the note is about, so say it: flow reflect --plugin \"<note>\" for a dev-flow bug, --playbook for this project's playbook; a note queued without a flag is filed on a keyword guess and the printed line tells you which.",
1665
- `2. re-check every open item below: already handled by the current playbook (.dev-flow/project.md) or obsolete → check it off with a fixed: note. Possibly fixed in a newer dev-flow: npm view pi-dev-flow version — a newer published version covering the item → recommend the operator update the plugin (pi install npm:pi-dev-flow, then /reload; a git-installed copy updates against its own tags: git ls-remote --tags --sort=-v:refname ${url} | head -1), never update it yourself.`,
1666
- '3. new findings: dedupe against the open items first — never reflect the same issue twice; queue each real one with flow reflect --plugin|--playbook "<one-line note>", then report to the operator structurally: playbook items vs plugin items, each with its route from the list below.',
1667
- "4. ask the operator whether to fix the open issues now. If yes:",
1668
- ` a. plugin items: search upstream first — gh issue list --repo ${up} --state all --search "<keywords>" — an author-addressed match → report the verdict back to the operator (fixed in v… / closed won't-fix + reason), do not re-file; no match → gh issue create --repo ${up} with a detailed description, session evidence and a suggested fix.`,
1669
- " b. playbook items: run flow doctor — it reviews each open item and routes it to the docs flow that implements the fix.",
1711
+ "queue: .dev-flow/reflections.md — this project's queue only (## playbook → docs flow, ## code → patch flow); dev-flow plugin feedback is never written there, it becomes a GitHub issue upstream. Gitignored and yours to edit; check items off as `- [x] … — fixed: <what or where>`.",
1712
+ review,
1713
+ `2. re-check every open item below: handled by the current playbook (.dev-flow/project.md) or code, or obsolete → propose checking it off with a fixed: note. dev-flow behaviour possibly fixed in a newer release: npm view pi-dev-flow version — newer → recommend the operator update (pi install npm:pi-dev-flow, then /reload; a git-installed copy: git ls-remote --tags --sort=-v:refname ${url} | head -1), never update it yourself.`,
1714
+ "3. show the operator the findings as one numbered list — per item: the note, its kind (docs / code / plugin), its route (docs flow / patch flow / upstream issue), a duplicate it matches, and your recommendation (fold or drop, with a one-clause reason). Ask fold or drop per item (one answer like 'fold 1,3 drop 2' is fine) and STOP until the operator answers.",
1715
+ "4. apply the answer: fold docs → flow reflect --playbook \"<note>\"; fold code → flow reflect --code \"<note>\"; fold plugin → flow reflect --plugin \"<note>\" prints the upstream recipe (dedupe search, then gh issue create — the fold answer is the operator's confirmation), report the issue URL; drop → nothing is recorded anywhere.",
1670
1716
  ];
1671
1717
  if (facts.ghFold)
1672
1718
  lines.push(
1673
- `upstream fold: ${facts.ghFold.open} open issue(s) on ${facts.ghFold.repo} ride along in flow doctor and flow reflect list — treat them as already filed: never file a finding an open issue covers, resolve upstream items on GitHub (close there, never in reflections.md)${facts.ghFold.similar ? `; ${facts.ghFold.similar} flagged near-duplicate(s) of local items need your verdict before anything is fixed twice` : ""}. When filing an issue for a local item, end the body with '— reflection from <flow-slug> <date>' so future folds match it, then check the item off with '— filed: gh#NNN'.`,
1719
+ `upstream fold: ${facts.ghFold.open} open issue(s) on ${facts.ghFold.repo} ride along in flow doctor and flow reflect list — treat them as already filed: never file a finding an open issue covers, resolve them on GitHub (close there, never in reflections.md)${facts.ghFold.similar ? `; ${facts.ghFold.similar} flagged near-duplicate(s) of local items need your verdict before anything is fixed twice` : ""}.`,
1674
1720
  );
1675
- if (facts.closed) lines.push(`${reflectionsTidyHint(facts.closed)} — check an item off only when it is handled; tidy once the checked-off pile grows.`);
1676
- if (!items.length) lines.push("open items: none — steps 1 and 3 still apply.");
1721
+ if (facts.fix) lines.push(`${facts.fix} — offer it to the operator after the fold/drop answer.`);
1722
+ if (facts.tidy) lines.push(`${facts.tidy} — offer it to the operator after the fold/drop answer; check an item off only when it is handled.`);
1723
+ if (!items.length) lines.push("open items: none — steps 1, 3 and 4 still apply.");
1677
1724
  else {
1678
1725
  lines.push(`open items (${items.length}):`);
1679
1726
  for (const r of reflectionRoutes(items, selfRepo)) lines.push(` [${r.sections.join("+")}] ${r.text}`, ` → ${r.route}`);
@@ -1686,8 +1733,10 @@ export function reflectProtocol(items: ReflectItem[], selfRepo: boolean, facts:
1686
1733
  * the end of each named section. Everything above the first item (title, comment, operator notes) is
1687
1734
  * kept verbatim. Below the first item a `## section` heading owns the lines under it, so an existing
1688
1735
  * line never changes section; an item under no known heading files under `## playbook` (where the
1689
- * operator reads it — `flow reflect move` re-files it). A note already in a section is not written
1690
- * there again — an all-duplicate call returns the content untouched so the caller can say so.
1736
+ * operator reads it — `flow reflect move` re-files it). Legacy `## plugin` rows are kept verbatim
1737
+ * (last, so they read as the leftover they are) but nothing new is ever written there. A note already
1738
+ * in a section is not written there again — an all-duplicate call returns the content untouched so the
1739
+ * caller can say so.
1691
1740
  */
1692
1741
  export function appendReflection(text: string, sections: ReflectSection[], line: string): string {
1693
1742
  const lines = text.split("\n");
@@ -1699,8 +1748,8 @@ export function appendReflection(text: string, sections: ReflectSection[], line:
1699
1748
  .join("\n")
1700
1749
  .replace(/\n{3,}/g, "\n\n")
1701
1750
  .trim();
1702
- const buckets = Object.fromEntries(REFLECT_SECTIONS.map((s) => [s, [] as string[]])) as Record<ReflectSection, string[]>;
1703
- let section: ReflectSection | null = null;
1751
+ const buckets = Object.fromEntries(KNOWN_SECTIONS.map((s) => [s, [] as string[]])) as Record<KnownSection, string[]>;
1752
+ let section: KnownSection | null = null;
1704
1753
  for (const raw of firstBody < 0 ? [] : lines.slice(firstBody)) {
1705
1754
  const l = raw.trim();
1706
1755
  if (ANY_HEADING.test(l)) {
@@ -1708,7 +1757,7 @@ export function appendReflection(text: string, sections: ReflectSection[], line:
1708
1757
  // a heading is authoritative for the items under it: deriving the bucket from the inline
1709
1758
  // marker instead moved every marker-less `## plugin` line into `## playbook` on the next write.
1710
1759
  // an unknown `## …` heading places nothing (it used to inherit the previous section by accident).
1711
- section = header ? (header[1].toLowerCase() as ReflectSection) : null;
1760
+ section = header ? (header[1].toLowerCase() as KnownSection) : null;
1712
1761
  continue;
1713
1762
  }
1714
1763
  if (!l.startsWith("- [")) continue;
@@ -1718,7 +1767,58 @@ export function appendReflection(text: string, sections: ReflectSection[], line:
1718
1767
  const body = reflectionBody(note);
1719
1768
  // only open items block a duplicate: a checked-off note may be reported again when it comes back.
1720
1769
  for (const s of sections) if (!buckets[s].some((l) => l.trim().startsWith("- [ ]") && reflectionBody(l) === body)) buckets[s].push(note);
1721
- return `${preamble || REFLECT_HEADER.trimEnd()}\n\n` + REFLECT_SECTIONS.filter((s) => buckets[s].length).map((s) => `## ${s}\n\n${buckets[s].join("\n")}\n`).join("\n");
1770
+ return `${preamble || REFLECT_HEADER.trimEnd()}\n\n` + KNOWN_SECTIONS.filter((s) => buckets[s].length).map((s) => `## ${s}\n\n${buckets[s].join("\n")}\n`).join("\n");
1771
+ }
1772
+
1773
+ /** The `YYYY-MM-DD` an item was filed — the first date in its ` — <slug> <date>` tail (a later
1774
+ * ` — fixed: …` clause may carry another date; the note itself is never read). */
1775
+ const itemDate = (line: string): string | null => {
1776
+ const at = line.indexOf(" — ");
1777
+ return at < 0 ? null : (/\b(\d{4}-\d{2}-\d{2})\b/.exec(line.slice(at))?.[1] ?? null);
1778
+ };
1779
+ const daysBetween = (from: string, to: string): number => Math.floor((Date.parse(to) - Date.parse(from)) / 86_400_000);
1780
+
1781
+ /** Thresholds for the two timing nudges. Mid-feature is the wrong moment for either — they surface
1782
+ * at finish, between flows, and in doctor. */
1783
+ export const REFLECT_NUDGE = { staleDays: 14, docsBatch: 3, tidyClosed: 5, tidyMinClosed: 3, tidyAgeDays: 30 } as const;
1784
+
1785
+ /**
1786
+ * When to suggest fixing the open project reflections, and when to suggest the tidy. Pure: the
1787
+ * reflections.md text, today's date, and what the caller knows (`recurred` — open items the reflect
1788
+ * worker saw hit again this session; `between` — no flow bound, the natural moment to start one).
1789
+ * fix fires on: a recurrence (strongest), an item ≥ staleDays old, ≥ docsBatch playbook items (one
1790
+ * docs flow takes them all), or any code item while between flows. tidy fires on: ≥ tidyClosed
1791
+ * closed, closed ≥ open with ≥ tidyMinClosed closed, or a closed item filed ≥ tidyAgeDays ago.
1792
+ */
1793
+ export function reflectionNudges(text: string, today: string, opts: { recurred?: number; between?: boolean } = {}): { fix: string | null; tidy: string | null } {
1794
+ const open = reflectItems(text).filter((i) => i.section !== "plugin");
1795
+ const docs = open.filter((i) => i.section === "playbook" || i.section === "unfiled").length;
1796
+ const code = open.filter((i) => i.section === "code").length;
1797
+ const stale = open.filter((i) => {
1798
+ const d = itemDate(i.line);
1799
+ return d !== null && daysBetween(d, today) >= REFLECT_NUDGE.staleDays;
1800
+ }).length;
1801
+ const why: string[] = [];
1802
+ if (opts.recurred) why.push(`${opts.recurred} recurred this session`);
1803
+ if (stale) why.push(`${stale} open ≥ ${REFLECT_NUDGE.staleDays} days`);
1804
+ if (docs >= REFLECT_NUDGE.docsBatch) why.push(`${docs} playbook items batch into one docs flow`);
1805
+ if (code && opts.between) why.push("between flows");
1806
+ let fix: string | null = null;
1807
+ if (open.length && why.length) {
1808
+ const split = [docs ? `${docs} playbook item(s) → one docs flow (flow start fold-<topic> --docs --confirmed)` : "", code ? `${code} code item(s) → patch flow (flow start fix-<topic> --patch --confirmed)` : ""].filter(Boolean).join("; ");
1809
+ fix = `⚑ fix the open reflections now? (${why.join(", ")}) — ${split}`;
1810
+ }
1811
+ const closedLines = text.split("\n").filter(isDoneItem);
1812
+ const closed = closedLines.length;
1813
+ const oldClosed = closedLines.some((l) => {
1814
+ const d = itemDate(l);
1815
+ return d !== null && daysBetween(d, today) >= REFLECT_NUDGE.tidyAgeDays;
1816
+ });
1817
+ const tidy =
1818
+ closed >= REFLECT_NUDGE.tidyClosed || (closed >= REFLECT_NUDGE.tidyMinClosed && closed >= open.length) || (closed > 0 && oldClosed)
1819
+ ? reflectionsTidyHint(closed)
1820
+ : null;
1821
+ return { fix, tidy };
1722
1822
  }
1723
1823
 
1724
1824
  /** Header of roadmap.md — the backlog of future features (gitignored, agent-editable like reflections.md). */
@@ -1923,14 +2023,15 @@ export function applyAnswer(partial: Record<string, unknown>, key: string, value
1923
2023
 
1924
2024
  // ------------------------------------------------------------- stage worker (flow_stage)
1925
2025
 
1926
- export type WorkerOp = "implement" | "review";
2026
+ export type WorkerOp = "implement" | "review" | "reflect";
1927
2027
 
1928
2028
  /** Stages where each worker op is legal: implement edits only while the flow is at implement; a review
1929
- * (read-only, advisory) is useful before verify and again before release. */
1930
- export const WORKER_OP_STAGES: Record<WorkerOp, Stage[]> = { implement: ["implement"], review: ["implement", "pre-release"] };
2029
+ * (read-only, advisory) is useful before verify and again before release; a reflection (read-only,
2030
+ * reviews the session transcripts) runs whenever the operator asks — finish is its standard moment. */
2031
+ export const WORKER_OP_STAGES: Record<WorkerOp, Stage[]> = { implement: ["implement"], review: ["implement", "pre-release"], reflect: ["plan", "implement", "pre-release", "release"] };
1931
2032
 
1932
2033
  /** Default wall-clock budget per op, in minutes. */
1933
- export const WORKER_BUDGET_MIN: Record<WorkerOp, number> = { implement: 60, review: 30 };
2034
+ export const WORKER_BUDGET_MIN: Record<WorkerOp, number> = { implement: 60, review: 30, reflect: 20 };
1934
2035
 
1935
2036
  /** Times a worker that stopped without its REPORT is told to keep going before the run gives up. */
1936
2037
  export const WORKER_NUDGES = 2;
@@ -1942,13 +2043,13 @@ export const clampBudgetMin = (n: unknown, op: WorkerOp): number => {
1942
2043
 
1943
2044
  /** Why an op is not legal for a feature at this stage, or null. */
1944
2045
  export function workerOpError(op: string, stage: Stage): string | null {
1945
- if (op !== "implement" && op !== "review") return `unknown op "${op}" — flow_stage ops: implement (a worker edits and commits a slice), review (a fresh read-only reviewer)`;
2046
+ 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)`;
1946
2047
  const ok = WORKER_OP_STAGES[op];
1947
2048
  return ok.includes(stage) ? null : `op "${op}" runs at ${ok.join(" or ")} — the feature is at ${stage}`;
1948
2049
  }
1949
2050
 
1950
2051
  export interface WorkerBriefInput {
1951
- op: WorkerOp;
2052
+ op: Exclude<WorkerOp, "reflect">;
1952
2053
  slug: string;
1953
2054
  workDir: string;
1954
2055
  planFile: string;
@@ -2011,3 +2112,155 @@ export function parseWorkerReport(text: string): { found: boolean; body: string;
2011
2112
 
2012
2113
  /** The nudge a worker gets when its turn ended without the REPORT block. */
2013
2114
  export const WORKER_NUDGE = "You stopped before finishing and without the REPORT section. Continue the task now (keep using tools; commit as you go). When it is done — or you are truly blocked — end with the `REPORT` section the contract asks for.";
2115
+
2116
+ /** The nudge a read-only worker (review, reflect) gets — it has nothing to commit. */
2117
+ 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.";
2118
+
2119
+ // ------------------------------------------------------------- reflect worker (flow_stage op "reflect")
2120
+
2121
+ /** A pi session file and the `parentSession` its header names (line 1 of the JSONL). */
2122
+ export interface SessionHeaderInfo {
2123
+ file: string;
2124
+ parentSession?: string;
2125
+ name?: string;
2126
+ }
2127
+
2128
+ /** The sub-agent transcripts of a driver session: every session file whose header names the driver
2129
+ * (flow_stage workers are created with parentSession = the driver's file), and their children in
2130
+ * turn. Ordered as found; cycles and the driver itself are never returned. */
2131
+ export function childSessionFiles(driverFile: string, headers: SessionHeaderInfo[]): SessionHeaderInfo[] {
2132
+ const out: SessionHeaderInfo[] = [];
2133
+ const seen = new Set<string>([path.resolve(driverFile)]);
2134
+ const queue = [path.resolve(driverFile)];
2135
+ while (queue.length) {
2136
+ const parent = queue.shift()!;
2137
+ for (const h of headers) {
2138
+ const f = path.resolve(h.file);
2139
+ if (seen.has(f) || !h.parentSession || path.resolve(h.parentSession) !== parent) continue;
2140
+ seen.add(f);
2141
+ out.push(h);
2142
+ queue.push(f);
2143
+ }
2144
+ }
2145
+ return out;
2146
+ }
2147
+
2148
+ export interface ReflectBriefInput {
2149
+ slug: string;
2150
+ root: string;
2151
+ today: string;
2152
+ driverFile: string | null;
2153
+ children: SessionHeaderInfo[];
2154
+ reflectionsFile: string;
2155
+ items: ReflectItem[];
2156
+ projectMd: string;
2157
+ version: string | null;
2158
+ upstream: string;
2159
+ selfRepo: boolean;
2160
+ /** open issues on this project's own GitHub repo (the read-time fold), when gh could list them */
2161
+ projectIssues?: { repo: string; issues: { number: number; title: string }[] };
2162
+ note: string;
2163
+ }
2164
+
2165
+ /** The brief for the reflect worker: a fresh, read-only reviewer of the session transcripts. It
2166
+ * classifies, dedupes and recommends; it never writes reflections.md and never files an issue —
2167
+ * the operator decides fold or drop per finding in the driving session. */
2168
+ export function buildReflectBrief(o: ReflectBriefInput): string {
2169
+ const up = o.upstream || "(unknown — say so in the REPORT)";
2170
+ const open = o.items.length ? o.items.map((it, i) => ` ${i + 1}. [${it.section}] ${it.line.replace(/^- \[ \] /, "")}`).join("\n") : " (none)";
2171
+ 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)";
2172
+ const issues = o.projectIssues ? (o.projectIssues.issues.length ? o.projectIssues.issues.map((i) => ` gh#${i.number} ${i.title}`).join("\n") : " (none open)") : "";
2173
+ return [
2174
+ `You are a fresh, independent reviewer of the dev-flow session for feature \`${o.slug}\`: find what went wrong or was slow, and say where each fix belongs.`,
2175
+ "",
2176
+ "## Facts",
2177
+ `- Repo (your cwd): ${o.root} — today is ${o.today}`,
2178
+ `- Driver session transcript (read it in full): ${o.driverFile ?? "(unknown — the session is not file-backed; say so and review what you can)"}`,
2179
+ `- Sub-agent (flow_stage worker) transcripts:\n${kids}`,
2180
+ "- Transcripts are pi JSONL, one entry per line (type session / message / custom …; messages carry role, content, tool calls and tool results). Skim with jq or grep — e.g. jq -c 'select(.type==\"message\")' <file> — for tool errors, guard or gate refusals, NEEDS-OPERATOR, retries, repeated commands, operator corrections; then read the surrounding entries.",
2181
+ `- This project's playbook: ${o.projectMd}`,
2182
+ `- This project's reflection queue: ${o.reflectionsFile} — open items:\n${open}`,
2183
+ `- dev-flow ${o.version ?? "(version unknown)"}; upstream repo: ${up}${o.selfRepo ? " — this checkout IS dev-flow, so plugin findings are this project's code findings" : ""}`,
2184
+ ...(o.upstream && !o.selfRepo ? [`- Dedupe plugin findings upstream (read-only): gh issue list --repo ${o.upstream} --state all --search "<keywords>" — cite gh#N when one covers it (fixed / won't-fix / open).`] : []),
2185
+ ...(o.projectIssues ? [`- Open issues on this project's repo ${o.projectIssues.repo}:\n${issues}`] : []),
2186
+ "- You hold no flow tool and write nothing: no file edits, no commits, no gh issue create. The driving session and the operator decide.",
2187
+ "",
2188
+ "## Your task",
2189
+ o.note.trim() ? `Operator context: ${o.note.trim()}` : "(no extra context from the driver)",
2190
+ "1. Review the transcripts for real friction only: wrong turns, repeated failures, misfiring guards or gates, playbook drift, slow paths with an obvious fix. One-off typos, environment hiccups and things already fixed later in the session are not findings.",
2191
+ `2. Classify each finding: docs — the fix lives only in this project's playbook (project.md) → docs flow; code — the fix touches this project's code (maybe the playbook too) → patch flow; plugin — dev-flow's own behaviour or wording → upstream GitHub issue${o.selfRepo ? " (here: report it as code)" : ""}.`,
2192
+ "3. Dedupe each finding against the open items above and the issues; a finding an open item already covers is not new — mark that item recurred instead.",
2193
+ "4. Recommend fold (worth recording / filing) or drop (one-off, environmental, operator choice, already covered) with a one-clause reason.",
2194
+ "5. Re-check every open item: still-open, fixed (cite where — playbook line, commit, newer dev-flow) or recurred (hit again in this session).",
2195
+ "",
2196
+ "## Contract",
2197
+ "- Check, don't fix: read and run read-only probes only. Change no files, make no commits, file nothing.",
2198
+ "- 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:",
2199
+ " 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>",
2200
+ " O<n> | still-open|fixed|recurred | <reason, with evidence>",
2201
+ " (no findings → a single line `F0 | none`; no open items → no O rows)",
2202
+ ].join("\n");
2203
+ }
2204
+
2205
+ export type ReflectKind = "docs" | "code" | "plugin";
2206
+ export interface ReflectFinding {
2207
+ n: number;
2208
+ rec: "fold" | "drop";
2209
+ kind: ReflectKind;
2210
+ note: string;
2211
+ dup: string;
2212
+ why: string;
2213
+ evidence: string;
2214
+ }
2215
+ export interface ReflectOpenCheck {
2216
+ n: number;
2217
+ status: "still-open" | "fixed" | "recurred";
2218
+ reason: string;
2219
+ }
2220
+
2221
+ /** Parse the reflect worker's REPORT rows. Malformed rows are skipped — the caller shows the raw
2222
+ * REPORT when nothing parsed, so a sloppy report is never silently lost. */
2223
+ export function parseReflectReport(body: string): { findings: ReflectFinding[]; open: ReflectOpenCheck[] } {
2224
+ const findings: ReflectFinding[] = [];
2225
+ const open: ReflectOpenCheck[] = [];
2226
+ for (const raw of (body ?? "").split("\n")) {
2227
+ const cells = raw.replace(/^[\s>*`-]+/, "").replace(/`+\s*$/, "").split("|").map((c) => c.trim());
2228
+ const f = /^F(\d+)$/i.exec(cells[0] ?? "");
2229
+ if (f && cells.length >= 4) {
2230
+ const rec = cells[1].toLowerCase();
2231
+ const kind = cells[2].toLowerCase();
2232
+ if ((rec !== "fold" && rec !== "drop") || !["docs", "code", "plugin"].includes(kind) || !cells[3]) continue;
2233
+ const field = (k: string) => cells.slice(4).find((c) => c.toLowerCase().startsWith(`${k}:`))?.slice(k.length + 1).trim() ?? "";
2234
+ findings.push({ n: Number(f[1]), rec, kind: kind as ReflectKind, note: cells[3], dup: field("dup") || "none", why: field("why"), evidence: field("evidence") });
2235
+ continue;
2236
+ }
2237
+ const o = /^O(\d+)$/i.exec(cells[0] ?? "");
2238
+ if (o && cells.length >= 2) {
2239
+ const status = cells[1].toLowerCase();
2240
+ if (status !== "still-open" && status !== "fixed" && status !== "recurred") continue;
2241
+ open.push({ n: Number(o[1]), status, reason: cells.slice(2).join(" | ") });
2242
+ }
2243
+ }
2244
+ return { findings, open };
2245
+ }
2246
+
2247
+ /** The numbered list the driver shows the operator: one row per finding with its route, then the
2248
+ * open-item re-check. Routes follow where the fix lives — plugin is always an upstream issue
2249
+ * (code in the dev-flow repo itself), never a local row. */
2250
+ export function renderReflectFindings(r: { findings: ReflectFinding[]; open: ReflectOpenCheck[] }, selfRepo: boolean): string[] {
2251
+ const route = (k: ReflectKind) =>
2252
+ 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)";
2253
+ const out: string[] = [];
2254
+ if (r.findings.length) {
2255
+ out.push(`findings (${r.findings.length}) — recommendation · kind → route:`);
2256
+ for (const f of r.findings) {
2257
+ out.push(` ${f.n}. [${f.rec}] ${f.kind}: ${f.note}`);
2258
+ out.push(` → ${route(f.kind === "plugin" && selfRepo ? "code" : f.kind)}${f.dup && f.dup !== "none" ? ` · dup: ${f.dup}` : ""}${f.why ? ` · ${f.why}` : ""}`);
2259
+ }
2260
+ } else out.push("findings: none");
2261
+ if (r.open.length) {
2262
+ out.push("open items re-checked:");
2263
+ 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" : ""}`);
2264
+ }
2265
+ return out;
2266
+ }