@gtheys/pi-flow 0.0.0-stage → 0.2.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.
Files changed (164) hide show
  1. package/README.md +833 -2
  2. package/adhoc/tracker.ts +360 -0
  3. package/aven/client.ts +996 -0
  4. package/aven/status.ts +395 -0
  5. package/brainstorm/args.ts +24 -0
  6. package/brainstorm/artifact.ts +67 -0
  7. package/brainstorm/paths.ts +43 -0
  8. package/brainstorm/prompt.ts +172 -0
  9. package/brainstorm/refs.ts +41 -0
  10. package/config.schema.json +161 -0
  11. package/config.ts +577 -0
  12. package/feedback/args.ts +21 -0
  13. package/feedback/prompt.ts +177 -0
  14. package/feedback/triage.ts +88 -0
  15. package/flow/agent-role.ts +46 -0
  16. package/flow/answer-wake.ts +212 -0
  17. package/flow/answer.ts +183 -0
  18. package/flow/args.ts +48 -0
  19. package/flow/ask-emitter.ts +331 -0
  20. package/flow/attribution.ts +145 -0
  21. package/flow/aven-resolve-exec.ts +95 -0
  22. package/flow/aven-resolve.ts +80 -0
  23. package/flow/awaiting-approval.ts +32 -0
  24. package/flow/binding-heal.ts +68 -0
  25. package/flow/cost-autopush.ts +162 -0
  26. package/flow/cost-command.ts +122 -0
  27. package/flow/cost-rows-journal.ts +296 -0
  28. package/flow/cost-rows-push.ts +112 -0
  29. package/flow/cost-rows-rows.ts +209 -0
  30. package/flow/cost-rows.ts +228 -0
  31. package/flow/cost.ts +173 -0
  32. package/flow/durable-refs.ts +287 -0
  33. package/flow/effect-gate.ts +137 -0
  34. package/flow/ensure-labels.ts +44 -0
  35. package/flow/frame.ts +172 -0
  36. package/flow/gates.ts +211 -0
  37. package/flow/jira-ref.ts +212 -0
  38. package/flow/label-gate.ts +149 -0
  39. package/flow/land-gate.ts +98 -0
  40. package/flow/lifecycle-policy.ts +162 -0
  41. package/flow/live-wait.ts +52 -0
  42. package/flow/liveness.ts +408 -0
  43. package/flow/loop-deps.ts +210 -0
  44. package/flow/loop-settle.ts +531 -0
  45. package/flow/loop.ts +437 -0
  46. package/flow/orchestrate.ts +45 -0
  47. package/flow/phase-command.ts +287 -0
  48. package/flow/phase-emoji.ts +13 -0
  49. package/flow/phase-prompts.ts +251 -0
  50. package/flow/picker.ts +307 -0
  51. package/flow/push.ts +475 -0
  52. package/flow/reconcile-command.ts +253 -0
  53. package/flow/reconcile-deps.ts +329 -0
  54. package/flow/reconcile.ts +738 -0
  55. package/flow/ref-kind.ts +80 -0
  56. package/flow/resume-picker.ts +222 -0
  57. package/flow/resume.ts +116 -0
  58. package/flow/run-health.ts +252 -0
  59. package/flow/run-liveness.ts +33 -0
  60. package/flow/state-metrics.ts +559 -0
  61. package/flow/status.ts +105 -0
  62. package/flow/step-output.ts +416 -0
  63. package/flow/steps.ts +73 -0
  64. package/flow/terminal-purge.ts +281 -0
  65. package/flow/turn-generation.ts +19 -0
  66. package/flow/v2-emission.ts +381 -0
  67. package/flow/v2-resume.ts +100 -0
  68. package/flow/vocabulary.ts +261 -0
  69. package/flow/widget.ts +448 -0
  70. package/flow/worktree-context.ts +136 -0
  71. package/flow-diagram/assemble.ts +27 -0
  72. package/flow-diagram/command.ts +252 -0
  73. package/flow-diagram/translate.ts +862 -0
  74. package/flow-diagram/vendor/harness-profiler/LICENSE +21 -0
  75. package/flow-diagram/vendor/harness-profiler/PIN.md +64 -0
  76. package/flow-diagram/vendor/harness-profiler/hp.js +960 -0
  77. package/flow-diagram/vendor/harness-profiler/load.ts +66 -0
  78. package/flow-diagram/vendor/harness-profiler/view.html +436 -0
  79. package/gates.ts +20 -0
  80. package/herdr/sync.ts +355 -0
  81. package/herdr/viewer.ts +432 -0
  82. package/implement/args.ts +21 -0
  83. package/implement/prompt.ts +98 -0
  84. package/implement/retry.ts +57 -0
  85. package/implement/routing.ts +31 -0
  86. package/index.ts +3206 -0
  87. package/mode-profile.ts +56 -0
  88. package/package.json +205 -4
  89. package/phase-state.ts +18 -0
  90. package/plan/args.ts +20 -0
  91. package/plan/prompt.ts +251 -0
  92. package/plan/size-check.ts +46 -0
  93. package/plan-tools/helpers.ts +177 -0
  94. package/plan-tools/jira-branch-tool.ts +54 -0
  95. package/plan-tools/jira-branch.ts +109 -0
  96. package/plan-tools/jira-issue.ts +85 -0
  97. package/plan-tools/resolve-feature-path.ts +30 -0
  98. package/plan-tools/resolve-notes-path.ts +37 -0
  99. package/plan-tools/resolve-spec-path.ts +31 -0
  100. package/pr-quality/index.ts +908 -0
  101. package/review/LICENSE +19 -0
  102. package/review/deviation.ts +252 -0
  103. package/review/review.ts +3053 -0
  104. package/review/sem-guidance.d.mts +8 -0
  105. package/review/sem-guidance.mjs +89 -0
  106. package/review/verdict.ts +13 -0
  107. package/run-state.ts +2046 -0
  108. package/run-title.ts +91 -0
  109. package/server/consumer.ts +146 -0
  110. package/server/daemon.ts +1094 -0
  111. package/server/lifecycle.ts +679 -0
  112. package/server/pending.ts +267 -0
  113. package/server/staleness.ts +320 -0
  114. package/server/writer.ts +86 -0
  115. package/shared/diff-base.ts +138 -0
  116. package/shared/flow-base.ts +210 -0
  117. package/shared/sonarqube-utils.ts +415 -0
  118. package/shared/stable-range.ts +102 -0
  119. package/slugify.ts +13 -0
  120. package/sonarqube/sonarqube.ts +821 -0
  121. package/spec-review/approve.ts +91 -0
  122. package/spec-review/args.ts +21 -0
  123. package/spec-review/aven-spec.ts +142 -0
  124. package/spec-review/commands.ts +336 -0
  125. package/spec-review/escape-regexp.ts +7 -0
  126. package/spec-review/open-in-pane.ts +166 -0
  127. package/spec-review/picker.ts +74 -0
  128. package/spec-review/prompt.ts +72 -0
  129. package/spec-review/publish-args.ts +33 -0
  130. package/spec-review/publish.ts +210 -0
  131. package/telemetry/attributes.ts +118 -0
  132. package/telemetry/content.ts +140 -0
  133. package/telemetry/dispatch.ts +521 -0
  134. package/telemetry/exporter.ts +124 -0
  135. package/telemetry/index.ts +776 -0
  136. package/telemetry/loki.ts +224 -0
  137. package/tools/code-review-parse.ts +518 -0
  138. package/tools/code-review.ts +312 -0
  139. package/tools/deviation.ts +737 -0
  140. package/tools/flow-submit.ts +302 -0
  141. package/tools/land.ts +608 -0
  142. package/tools/phase-complete.ts +476 -0
  143. package/tools/result.ts +18 -0
  144. package/tools/review-deps.ts +44 -0
  145. package/tools/run-attempt.ts +312 -0
  146. package/tools/spec-approve.ts +265 -0
  147. package/validate/args.ts +22 -0
  148. package/validate/deviation-gate.ts +229 -0
  149. package/validate/gate-target.ts +371 -0
  150. package/validate/gate.ts +79 -0
  151. package/validate/paths.ts +20 -0
  152. package/validate/personal.ts +104 -0
  153. package/validate/prompt.ts +525 -0
  154. package/validate/review-gate.ts +134 -0
  155. package/validate/subtask-range.ts +113 -0
  156. package/work-mode.ts +19 -0
  157. package/worktree/bootstrap.ts +243 -0
  158. package/worktree/branch.ts +168 -0
  159. package/worktree/herdr.ts +447 -0
  160. package/worktree/index.ts +1447 -0
  161. package/worktree/orphan.ts +384 -0
  162. package/worktree/remove-guards.ts +99 -0
  163. package/worktree/residue.ts +216 -0
  164. package/worktree/sweep.ts +526 -0
package/README.md CHANGED
@@ -1,3 +1,834 @@
1
- # Temporary Holding Version
1
+ # pi-flow
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ PIV flow extension — `/brainstorm /plan /implement /validate /feedback`
4
+ phase commands plus the `/flow` orchestrator, routed over
5
+ pi-interactive-subagents (pi-planning, pi-review and pi-worktree were
6
+ absorbed into this package — plan-tools, jira_create_branch, `/review`,
7
+ `/sonarqube`, `/pr-quality`, `/pr-watch`, the `worktree` tool and their
8
+ agent tools now live here).
9
+ Canonical flow documentation: [`docs/piv-flow.md`](../../docs/piv-flow.md).
10
+
11
+ ## Dependencies
12
+
13
+ Runtime:
14
+
15
+ | Package | Why | Used by |
16
+ |---|---|---|
17
+ | `@gtheys/pi-interactive-subagents` (pinned `0.2.0`, lockstep-bumped each release) | Spawn-and-watch substrate: launches agent sessions into herdr panes, keeps durable assignment records, steers results back | `review/review.ts` (reviewer spawn), `spec-review/publish.ts` (publish worker), `index.ts` (`hasLiveAssignmentForParent` + `hasPendingAskForParent` for the flow loop) |
18
+
19
+ Peers: `@earendil-works/pi-coding-agent` (host API), `@earendil-works/pi-tui`
20
+ (review UI), `typebox` (config schema validation).
21
+
22
+ Failure behavior:
23
+
24
+ - **Package not installed** — the imports are static ESM, so pi-flow fails to
25
+ load at startup with a visible error. No partial registration, no silent
26
+ fallback. Fix: install the package (declared dependency, automatic) and
27
+ restart pi.
28
+ - **No mux** (herdr binary missing or server down) — graceful per call site:
29
+ `/review` falls back to the in-session review path, `/spec-publish` prints
30
+ the manual git recipe, the flow loop reads on-disk assignment records and
31
+ is unaffected.
32
+ - **Spawn fails with a mux present** — the failure steers back as a visible
33
+ `review_result` message; PR worktree cleanup is refcounted so a crashed
34
+ reviewer cannot tear down a shared worktree.
35
+
36
+ ## Commands
37
+
38
+ | Command | What it does |
39
+ | --- | --- |
40
+ | `/brainstorm <topic \| ID=<jira-id> \| --debug <symptom>>` | Standalone (not a lifecycle phase): question loop + scouts → artifact in `notes/brainstorm/` → ticket-creation gate (explicit confirm; work: Jira, personal: aven). `ID=<jira-id>` (or a bare jira-shaped topic in work mode) brainstorms the existing ticket instead: aven local epic first (`jira-ref` metadata), `acli jira workitem view` fallback; no creation gate; the brainstorm artifact path is stored on the ticket as `research-path` metadata. `--debug <symptom>` routes through the user's `debug` skill to a root cause. |
41
+ | `/plan <ref>` | Work: `feature-plan-aven` skill (epic tree, plan-state approval). Personal: size check → human-confirmed oneshot vs plan split; plan.md + epic/subtasks for plans. Ends with status `todo` + `planned` label — work mode: only after the approval-gated tree stage (premature `planned` would misroute `/implement`). |
42
+ | `/implement <ref>` | Gate: `planned` required. Routes bug / plan / oneshot. Worktree isolation, per-task implement→test→commit, retry budget 3 then blocked + escalate. |
43
+ | `/validate <ref>` | Work: ordered cluster gate (minikube → connectivity → queues → deploy → manual tests → Jira evidence comment). Personal: human runs the test. Then the review-tool gate (`/review` → `blockers_count` artifact) → `deviation_review`; 0 → `flow_phase_complete(validate)` (work lands right here via `flow_land`; personal gates end there — feedback owns the PR delivery, `validate/prompt.ts`), >0 → back to `/implement`. |
44
+ | `/feedback <ref>` | Work: `/sonarqube` + `/pr-quality` triage (mechanical fixes committed, behavioral findings become new tasks). Personal: the PR-delivery phase (`personalPrDeliverySection`, `feedback/prompt.ts` — ONE section for yolo and non-yolo): `flow_land` (final integrity gate) → ONE `git push` → ONE `gh pr create` (TL;DR body, `PERSONAL_PR_BODY_SPEC`) → verify → prUrl journaled via `flow_submit` → outcome summary note + review-feedback backlog tickets → `done` at delivery. Worktree removed at delivery; the branch survives until the human merges on GitHub. |
45
+ | `/spec-review [--workspace <name>]` | Lists every spec at `plan-state=review` (aven metadata query), batch-picks them, opens each plan.md in a herdr nvim pane, and injects a review prompt: the session fixes spec issues in place; transitions to approved only via explicit "approve <REF>" (pins `plan` label, plan-state=approved, status todo). |
46
+ | `/spec-publish <ref>` | Launches a worker subagent that publishes the approved plan.md to the ticket's notes repo (plan-state gate). |
47
+ | `/review-spec <path>` | Opens a plan/spec in a herdr nvim `spec-review` pane (absorbed from pi-planning). |
48
+ | `/review [target]` | Code review via a fresh-context `reviewer` subagent — PR / branch / commit / uncommitted / folder / custom; optional ocr second opinion; emits a machine-readable `blockers_count: <N>` verdict the `/validate` review gate consumes (absorbed from pi-review). |
49
+ | `/sonarqube [pr]` | SonarCloud coverage gaps + quality issues for a PR, analysis-only (absorbed from pi-review). Requires `SONARQUBE_TOKEN`. |
50
+ | `/pr-quality [pr]` | Unresolved GitHub review threads + SonarCloud issues in one triage pass (absorbed from pi-review). |
51
+ | `/pr-watch` | Background-polls PR checks; auto-triggers `/pr-quality` when they complete (absorbed from pi-review). |
52
+ | `/flow-cost <ref> [--push]` | Per-ticket cost rollup: replays the run journal, attributes each spawned session's token usage and tool calls to agent/subtask, prints the table. `--push` additionally exports the rollup as Prometheus metrics to a Pushgateway (env-gated, see below); failures warn and never fail the command. Reruns any time — it replays the journal, so it doubles as the backfill path. The rollup also prints a per-phase step outputs section (advisory, never blocking) summarizing the `flow_submit` step-output submissions per phase.
53
+ | `/flow-reconcile-push [--dry-run]` | Runs the stale-liveness reconcile NOW instead of waiting for the daemon timer: tombstones the `pi_flow_state` liveness series of runs whose aven ticket is neither active nor todo (the stored `state="halted"`/`"waiting_human"`/`"waiting_machine"` become `state="stale"`), so halted/waiting alerts stop firing on tickets that closed weeks ago. Takes **no ref** — one pass covers every run journal. `--dry-run` decides without pushing. Output is one summary line plus one line per stale ref (`PMR-X (ticket done) journal=halted → tombstoned`); gateway and aven failures come out as warnings. Details under [Reconcile](#reconcile-stale-run-tombstoning). |
54
+ | `/herdr-sync` | Links this repo as a Herdr plugin (idempotent, explicit-only). |
55
+ | `/flow-view <ref> [placement]` | Opens/focuses a Herdr pane rendering the run-state journal for a ref. |
56
+ | `/flow-diagram <ref> [run]` | Renders the per-ticket flow timeline as a self-contained HTML sequence diagram (one lane per subagent + orchestrator, phase markers, tool arrows with dashed returns, per-lane token totals). Writes to `pi-flow/diagrams/<ref>.run<k>.<stamp>.html` and best-effort opens it; the file path is always the deliverable. |
57
+ | `/flow <ref>` | Extension-owned loop: injects one phase prompt at a time (same builders the phase commands use, gates intact), then advances when the phase turn settles and its completion label has landed; missing label → halt note + stop. Resume = first phase whose completion label is missing. Work mode + Jira ID: find-or-create the local epic (`jira-ref` metadata, dep-linked to the synced ticket) and run on the epic ref. |
58
+ | `/flow` (bare) | Same gate picker as `/flow <ref>`, plus an extra "Start a flow on a ready ticket…" row; picking it opens the cwd-project's ready tickets from `aven list --ready` and Enter starts the flow exactly like `/flow <ref>`. Zero open gates skips the menu and goes straight to the ticket list. Esc cancels silently. |
59
+
60
+ Lifecycle labels on the aven ticket are the run state:
61
+ `planned → active → review-passed → done`; type labels
62
+ `bug` / `oneshot` / `plan` route `/implement`.
63
+
64
+ ## Tools
65
+
66
+ Agent-callable tools registered by pi-flow:
67
+
68
+ | Tool | What it does |
69
+ | --- | --- |
70
+ | `flow_phase_complete` | The ONLY way to write lifecycle labels — re-checks the phase gates before exec'ing aven; direct `aven edit --label` mutations are blocked at the bash tool_call boundary. |
71
+ | `flow_land` | Gates landing behind the `review-passed` label (+ optional `blockers_count` artifact); authorizes `git push` / `gh pr create` for the ref, which are otherwise blocked while a flow is active. Also declares the run's side effects (see [Effect contracts](#effect-contracts) below). |
72
+ | `flow_run_attempt` | Owns the implement-phase retry budget: 3 total attempts, the 3rd failure escalates and further attempts are refused. |
73
+ | `flow_submit` | Advisory step-output journal: reports step evidence (plan written, test run, PR/gate check, PR outcome) per phase. Never gates completion — sole exception (PMR-AYMZ): an ok=true `plan.route-confirmed` row plus the live `oneshot` label satisfies the plan receipt gate. A warned submission never blocks a phase. |
74
+ | `spec_approve` | Only path from plan-state `review` → `approved` (pins the `plan` label, moves the ticket to todo). |
75
+ | `resolve_spec_path` / `resolve_feature_path` / `resolve_notes_path` | Canonical flow-document path resolution — spec/plan.md for a Jira ticket or personal feature, and generic notes paths via `resolve_notes_path` (`subdir` allowlist: `""` root, `prs`, `specs`, `research`, `tickets`). The single contract for every document path — never hand-roll (absorbed from pi-planning). |
76
+ | `open_in_pane` | Opens a file with nvim in a herdr pane for review (absorbed from pi-planning). Call it only after the file write returned; it polls ~1s for the file. Called from a subagent, it opens a durable `spec-review` tab instead so the pane survives subagent cleanup. |
77
+ | `jira_create_branch` | Derives and creates a git branch from a Jira issue (absorbed from pi-planning). Requires `acli` + `git-town`. |
78
+ | `review` | Starts a code review of uncommitted changes / branch / commit / PR / folder / custom instructions (absorbed from pi-review). |
79
+ | `sonarqube` | Fetches SonarCloud coverage gaps + quality issues for a PR as an actionable report (absorbed from pi-review). |
80
+ | `pr_quality` | Gathers unresolved PR review threads + SonarCloud issues into a triage prompt (absorbed from pi-review). |
81
+ | `worktree` | Creates, lists, and removes Herdr-managed git worktree workspaces (absorbed from pi-worktree). |
82
+
83
+ ### Automatic worktree cleanup
84
+
85
+ Flow-created worktrees are cleaned up automatically at three trigger points:
86
+ loop-driven flows clean up via the done handler, a `/flow` rerun of a
87
+ harness-completed flow cleans up its bound worktree, and session start or
88
+ flow start sweeps run-journal refs whose flow is done. Deletion keys off PR
89
+ state in BOTH modes (`ghPrState`, `worktree/remove-guards.ts`): an OPEN PR →
90
+ worktree removed at delivery, branch kept until the human merges on GitHub;
91
+ a MERGED PR (or `force`) → worktree and branch both go. CLOSED PR, no PR,
92
+ or a missing `gh` keep the branch (re-delivery survives). Untracked
93
+ `.pi/plans/` residue that is byte-identical to the main checkout's mirror is
94
+ auto-removed so cleanup can proceed, and a worktree whose herdr record is
95
+ gone while its directory remains is cleaned up by a guarded orphan path.
96
+ User dirt and in-flight agents are never deleted — they defer with an aven
97
+ note naming the exact blocker and a recovery action (one note per unchanged
98
+ state) and are retried by a later sweep.
99
+
100
+ ## Effect contracts
101
+
102
+ Before a risky action runs, the agent declares it in the run journal. Five
103
+ actions are declared (`EffectKind`, `run-state.ts`): `git-push`,
104
+ `gh-pr-create`, `worktree-create`, `worktree-remove`, and `workspace-close`
105
+ (the `worktree` prune action, which only ever closes a workspace proven
106
+ dangling — checkout gone, no agents). Each declaration carries a
107
+ plain-language undo recipe. Legacy journals that still carry the retired
108
+ `merge-main` / `rebase-flow` kinds parse fine; replay drops their
109
+ declarations (PMR-V31Z 6.1).
110
+
111
+ How it holds:
112
+
113
+ - **Fail-closed**: if the journal write fails, the action is refused. No
114
+ journal, no effect.
115
+ - **Worktree gating**: the create/remove actions are gated inside the
116
+ `worktree` tool itself — the command must match exactly, not via regex.
117
+ - **Honest limit**: bash detection (push, PR create, merge) catches literal
118
+ commands at command position only. Aliases, `sh -c '...'`, and
119
+ variable-built commands are **not** detected. This is a guardrail against
120
+ accidental effects, not a privilege boundary. Humans typing in their own
121
+ terminal are out of scope.
122
+
123
+ ## Lifecycle close-out policy
124
+
125
+ Completing the feedback phase (the `done` transition) is gated on one
126
+ close-out evidence contract for EVERY mode, decided by one pure policy
127
+ module (`flow/lifecycle-policy.ts`, PMR-VE27) consulted at every
128
+ authoritative sink — the `flow_phase_complete` tool (fresh AND
129
+ already-recorded), the loop's feedback settle, and the `/flow` all-labels
130
+ re-entry:
131
+
132
+ - **Every mode (work, personal ordinary, personal yolo)**: a
133
+ `gh-pr-create` effect journaled by `flow_land <ref>` — `checkCloseout`
134
+ reads only `proofs.prEffect` (`flow/lifecycle-policy.ts`; the
135
+ `CloseoutProofs` shape has no other field). Missing vs unreadable
136
+ journal are distinct, fail-closed refusals. Personal delivers via PR
137
+ and is unmerged BY DESIGN at close-out (PMR-V31Z superseded the fresh
138
+ ancestry probe: there is no merge-main landing to recover to).
139
+ - **Mode provenance** is per-seam (PMR-Y8AD) and describes only what each
140
+ seam READS — `checkCloseout`'s mode/yolo inputs no longer dispatch.
141
+ The `flow_phase_complete` tool reads the run journal (`readRunMode` +
142
+ `isYoloRun`, fail-closed): an unreadable mode refuses close-out. The
143
+ settle gate reads in-memory loop state (`runState.promptInput`); the
144
+ `/flow` terminal re-entry reads the handler-resolved `resolveMode`.
145
+ `flow_land` reads no mode at all — the route parameter and the
146
+ `merge-main` leg are gone (PMR-V31Z: PR delivery is the only story).
147
+ - **Terminal re-entry**: `/flow <ref>` with all labels present re-verifies
148
+ the same prEffect evidence before the terminal treatment: verified →
149
+ terminal cleanup; refused → abort with a warning + return — nothing is
150
+ destroyed (the landing-continuation re-mapping and its journal-receipt
151
+ fallback leg are superseded, PMR-V31Z). Unverified evidence at the live
152
+ settle halts with the `closeout_check_failed` reason (machine wait;
153
+ recovery is gathering the missing evidence — the gh-pr-create effect
154
+ declared by `flow_land <ref>` — and rerunning `/flow <ref>`).
155
+ - **Deliberate boundaries**: the standalone `/plan` `/implement`
156
+ `/validate` `/feedback` commands stay human-attested escape hatches;
157
+ plan/implement/validate completion stays agent-attested; the bash label
158
+ interceptors (now covering aven global-option forms) are defense in
159
+ depth — labels are claims that the gates above reconcile. The full
160
+ entrypoint × mode matrix with classifications lives in
161
+ [`docs/piv-flow-lifecycle-matrix.md`](../../docs/piv-flow-lifecycle-matrix.md).
162
+
163
+ ## Configuration
164
+
165
+ Global config lives at `~/.pi/agent/pi-flow/config.json` (schema:
166
+ [`config.schema.json`](config.schema.json)). A project-local
167
+ `<repo>/.pi/pi-flow/config.json` is merged on top (project wins per key) —
168
+ handy for enabling telemetry per checkout, or for pinning a per-repo
169
+ `landTestCommand` (e.g. `"landTestCommand": ["cargo", "test"]` in a rust
170
+ checkout) instead of machine-wide.
171
+
172
+ | Option | Type | Default | Description |
173
+ | --- | --- | --- | --- |
174
+ | `workRoots` | `string[]` | `[]` | Absolute path prefixes; a git toplevel under any prefix is `work` mode |
175
+ | `avenWorkspace` | `string` | unset | Aven workspace name or key forced on every aven call pi-flow makes (skips cwd inference and the search fallback) |
176
+ | `yolo` | `boolean` | `false` | Run `/flow` phases without confirmation gates. Only applies when the `--yolo` flag is absent on the invocation — an explicit flag wins over config |
177
+ | `landTestCommand` | `string[]` | detected, else `["bun","run","test"]` | Argv of the test command `flow_land` runs itself before authorizing a landing — the gate never trusts a claimed-green suite. When unset, the command is detected from repo signals in a fixed order: `bun.lock`/`bunfig.toml` → `bun run test`, `Cargo.toml` → `cargo test`, `package-lock.json` → `npm test`, `pnpm-lock.yaml` → `pnpm test`. The summary of every run names the command and its source (config / detection / default) |
178
+ | `telemetry.enabled` | `boolean` | `false` | Master switch for OTLP telemetry. `false` or a missing `telemetry` block = the session probe subscribes to nothing, allocates nothing, makes no network calls |
179
+ | `telemetry.otlpEndpoint` | `string` | unset (required when `telemetry.enabled` is `true`) | OTLP/HTTP base URL (e.g. `https://host:4478`); spans POST to `<endpoint>/v1/traces`. May be omitted when OTLP export is off — a Loki-only setup (`telemetry.enabled: false` + `telemetry.loki.enabled: true`) needs no OTLP base |
180
+ | `telemetry.headers` | `record<string, string>` | `{}` | Static extra headers for OTLP export. Secrets belong in env (`PI_FLOW_OTLP_TOKEN`), not config |
181
+ | `telemetry.captureContent` | `"off" \| "text" \| "tools" \| "all"` | `"off"` | Content layers added to spans (cumulative): `off` metadata only, `text` assistant text, `tools` + tool calls and tool input/output, `all` + model reasoning. See [Capturing content](#capturing-content-in-spans) |
182
+ | `telemetry.jiraBaseUrl` | `string` | unset | Base URL for Jira issue links, e.g. `https://example.atlassian.net/browse/`. Work-mode spans then carry `flow.url` = base + Jira key, so dashboards can link tickets to Jira. Unset = no links |
183
+ | `telemetry.maxContentChars` | `integer` (100–100000) | `2000` | Max characters per captured content attribute; longer values end with `…[truncated N chars]`. Tempo drops anything past its `max_attribute_bytes` (default 2048) silently, so raise both together |
184
+ | `telemetry.loki.enabled` | `boolean` | `false` | Push flow **transition-event** streams (`state-change` / `step-start` / `step-stop`) to Loki from the live session (PMR-ZV9Y 4.2). `false` or a missing `loki` block = zero Loki network calls. Session-side only — the daemon never pushes Loki. See [Loki transition events](#loki-transition-events) |
185
+ | `telemetry.loki.endpoint` | `string` | unset (required with `telemetry.loki.enabled`) | Loki **base** URL you provide yourself (e.g. `http://loki.example.com:3100`); events POST to `<endpoint>/loki/api/v1/push` (the push path is appended for you) |
186
+ | `telemetry.loki.headers` | `record<string, string>` | `{}` | Static extra headers for the Loki push (e.g. a Bearer token in front of a reverse proxy). Secrets belong in env, not config |
187
+ | `notify.desktop.enabled` | `boolean` | `true` | Send a desktop notification on `waiting_human` / `halted` flow transitions through the [desktop-notify extension](../rifle-batteries/README.md) (PMR-ZV9Y 5.2). `false` turns the **flow-side page** off — the user's own channel toggles (desktop / herdr / ntfy) still live in the desktop-notify module's own config (`pi-rifle-batteries/desktop-notify/`), and Grafana alerting is unaffected (independent channel). See [Notifications](#notifications) |
188
+ | `runServer.enabled` | `boolean` | `true` | Kill switch for the durable run server (PMR-XTQQ). `false` = never spawn the daemon; journal writers permanently use the full in-session path (runs don't survive a session exit) |
189
+ | `reconcile.enabled` | `boolean` | `true` | Reconcile stale run-liveness metrics — tombstone the v2 `pi_flow_state` series whose aven ticket is neither active nor todo (`state="halted"`/`"waiting_human"`/`"waiting_machine"` → `state="stale"`), so the alerts only ever fire on runs that still need you. Setting it on a RUNNING daemon takes effect on the next tick: a `false` → `true` flip needs no restart, because a disabled tick skips the pass but stays armed and re-reads the config. Only a daemon that STARTED with `enabled: false` needs a restart — no timer was armed at startup, so nothing re-reads — or a one-off `/flow-reconcile-push` for an immediate pass. See [Reconcile](#reconcile-stale-run-tombstoning) |
190
+ | `reconcile.intervalMinutes` | `integer` (≥ 1) | `360` | Daemon reconcile interval in minutes (6 h by default). An interval change applies on the next cycle — no daemon restart needed |
191
+ | `liveness.enabled` | `boolean` | `true` | Push full run bodies — the v2 `pi_flow_state{state="running"}` gauge refresh — to the Pushgateway while runs are in flight, so the board shows running flows. See [Liveness](#liveness-running-flow-visibility) |
192
+ | `liveness.intervalMinutes` | `integer` (≥ 1) | `5` | Daemon liveness push interval in minutes (5 min by default). An interval change applies on the next cycle — no daemon restart needed |
193
+
194
+ ```json
195
+ {
196
+ "$schema": "https://raw.githubusercontent.com/gtheys/pi-my-rifle-ext/main/packages/pi-flow/config.schema.json",
197
+ "workRoots": [
198
+ "/home/dev/Code/salaryhero"
199
+ ],
200
+ "avenWorkspace": "personal",
201
+ "yolo": false,
202
+ "landTestCommand": ["bun", "run", "test"],
203
+ "telemetry": {
204
+ "enabled": false,
205
+ "otlpEndpoint": "https://tempo.example.com:4478",
206
+ "headers": {},
207
+ "captureContent": "off",
208
+ "maxContentChars": 2000,
209
+ "loki": {
210
+ "enabled": false,
211
+ "endpoint": "",
212
+ "headers": {}
213
+ }
214
+ },
215
+ "notify": {
216
+ "desktop": {
217
+ "enabled": true
218
+ }
219
+ },
220
+ "runServer": {
221
+ "enabled": true
222
+ },
223
+ "reconcile": {
224
+ "enabled": true,
225
+ "intervalMinutes": 360
226
+ },
227
+ "liveness": {
228
+ "enabled": true,
229
+ "intervalMinutes": 5
230
+ }
231
+ }
232
+ ```
233
+
234
+ ### Durable run server
235
+
236
+ Since PMR-XTQQ, a small detached daemon (plain node, own event loop) makes
237
+ `/flow` runs survive a session exit. The extension ensures it is alive at
238
+ `/flow` start only (pidfile + liveness + protocol-version probe at
239
+ `<agentDir>/pi-flow/server.pid`; mismatch → kill + respawn). Reopening a
240
+ session does not spawn it — only the pending-record consumer runs then; a
241
+ dead daemon is respawned by the next `/flow`.
242
+
243
+ **Stale-code warning**: since PMR-7B8M the daemon records the git SHA of the
244
+ checkout it was spawned from in `server.pid`. Sessions compare that SHA against
245
+ the **main checkout's** HEAD — resolved from any worktree via `git worktree list
246
+ --porcelain` — and flag a mismatch (main moved on, or the daemon came from an
247
+ unmerged branch) or a pidfile with no SHA at all (an older daemon). Since
248
+ PMR-5563 that verdict auto-restarts an **idle** daemon — killed and respawned
249
+ with an info note, no manual step — at session start and at `/flow` start.
250
+ A busy daemon (any live flow run on disk needs it) or a failed restart keeps
251
+ the manual `kill <pid>` warning; after killing it yourself the daemon is
252
+ re-ensured at the next `/flow` start. A worktree's own commits never move
253
+ main HEAD, so they never trigger this. The check is silent when the daemon
254
+ was spawned from a different repository — the daemon is global and serves
255
+ every repo's runs, so its recorded SHA says nothing about yours. The
256
+ protocol-version pin is unchanged and remains the other condition that
257
+ kills + respawns.
258
+
259
+ What it does: the daemon is the ONLY projection writer while alive — journal
260
+ writers route journal-only through `server/writer.ts` (per-write liveness
261
+ probe) and the daemon reprojects. Parked runs (awaiting an outcome at a phase
262
+ or human gate) are recorded in `pending/<ref>.json`; when a session with a
263
+ restored flow binding for that ref reopens, the record is consumed exactly
264
+ once (atomic rename) and `/flow <ref>` is re-presented automatically.
265
+ Loop state (blocker retries, validate cutoff) and the attempt ledger are
266
+ journaled and re-seeded on resume.
267
+
268
+ **Resume consent**: a parked run is never silently taken over by a different
269
+ session. A clean session that starts in a repo with live flow runs *asks*
270
+ first — one `Resume <ref> — <phase>, <status>, updated <age>` row per run
271
+ plus `None — leave this session clean` (a run whose owner session still looks
272
+ alive is labelled as such) — and only the run you pick is restored, healed
273
+ and re-presented. Declining (or Esc) leaves the session completely clean: no
274
+ binding, nothing injected, just one line naming the recovery command. A run
275
+ that parked *after* startup is caught by the same prompt on the next settle,
276
+ at most once per process. A session with no UI is never prompted at all — it
277
+ lists `recover with /flow <ref>` per parked run and stays clean. The session
278
+ that already owns the run (its binding came back with the session history)
279
+ still resumes automatically, no question asked.
280
+
281
+ On-disk layout under `<agentDir>/pi-flow/`: `server.pid`, `server.log`,
282
+ `pending/`, `runs/`.
283
+
284
+ **Restarting the daemon (after pi-flow code changes)**: a running daemon keeps
285
+ the code it loaded at startup — there is no hot-reload. The `/flow`-start probe
286
+ only kills + respawns on a `SERVER_PROTOCOL_VERSION` mismatch, so ordinary
287
+ changes to the daemon's closure (`server/`, `flow/liveness.ts`,
288
+ `flow/reconcile.ts`, the `flow/cost-rows*.ts` family (`cost-rows.ts` +
289
+ `cost-rows-journal.ts`, `cost-rows-rows.ts`, `cost-rows-push.ts`),
290
+ `run-state.ts`, `flow/push.ts`) need
291
+ a manual restart to take effect (a stale daemon silently missed the whole
292
+ PMR-8MQH liveness engine once — PMR-7B8M tracks a drift warning). Restarting
293
+ mid-run is safe: the daemon only reads journals, writes projections, and
294
+ pushes; while it is down, journal writers fall back to the in-session path.
295
+
296
+ 1. Easiest — kill it and let the next `/flow` respawn it with fresh code:
297
+
298
+ ```sh
299
+ kill $(jq -r .pid ~/.pi/agent/pi-flow/server.pid)
300
+ ```
301
+
302
+ 2. Immediate restart (when no `/flow` start is coming soon) — mirror what
303
+ `ensureDaemon` spawns. The daemon inherits the launching shell's env, so
304
+ `PI_FLOW_PUSHGATEWAY_URL` / `PI_FLOW_PUSHGATEWAY_TOKEN` must be set there
305
+ for the liveness/reconcile pushes to arm:
306
+
307
+ ```sh
308
+ cd packages/pi-flow
309
+ PI_FLOW_AGENT_DIR=~/.pi/agent nohup node server/daemon.ts \
310
+ >> ~/.pi/agent/pi-flow/server.log 2>&1 &
311
+ ```
312
+
313
+ 3. Verify: `server.pid` shows the new pid, `server.log` gains a
314
+ `daemon started pid=…` line, and ~60 s later the first pass summaries
315
+ (`liveness pass: scanned=… pushed=…`, `reconcile pass: …`) appear — the
316
+ first pass runs 60 s after startup, then every `liveness.intervalMinutes` /
317
+ `reconcile.intervalMinutes`.
318
+
319
+ - **Disable**: set `"runServer": { "enabled": false }` — the daemon is never
320
+ spawned and writers permanently use the in-session full path.
321
+ - **Degrade**: daemon absent or dead = today's pre-PMR-XTQQ behavior. The
322
+ journal stays the authority; the projection and pending records are
323
+ rebuildable caches. Known limits: the projection lags ≤~1s while the daemon
324
+ owns it (only `/flow-view` reads it — receipts and gates read the journal
325
+ and aven directly), and a brand-new session in the same worktree without a
326
+ restored binding is never auto-bound — it only gets the resume prompt above
327
+ (or the `recover with /flow <ref>` lines when there is no UI).
328
+
329
+ **Binding self-heal after resume**: when a resumed session has no replayable
330
+ flow binding (cross-session resume, fork), the flow gate tools
331
+ (`code_review`, `deviation_review`, `flow_land`, `worktree` bind) re-derive
332
+ the worktree binding from durable state (aven `worktree:` note, herdr
333
+ worktree list, pending-run records) and re-arm it themselves — no manual
334
+ `/flow <ref>` re-arm needed. When derivation fails, every refusal names the
335
+ exact recovery command (`/flow <ref>`) for that ref.
336
+
337
+ ### Telemetry (OTLP traces)
338
+
339
+ Optional and **disabled by default**. When enabled, every Pi session (the main session and each spawned worker, joined via the flow env stamps) exports spans to any OTLP/HTTP receiver (metadata only unless you opt in to content capture below) — Tempo, Alloy, the OTel collector, whatever speaks `/v1/traces`.
340
+
341
+ Enable it in the config file (no secrets in here):
342
+
343
+ ```json
344
+ {
345
+ "telemetry": {
346
+ "enabled": true,
347
+ "otlpEndpoint": "https://tempo.example.com:4478"
348
+ }
349
+ }
350
+ ```
351
+
352
+ Set the bearer token in the shell that starts Pi, never in config:
353
+
354
+ ```sh
355
+ export PI_FLOW_OTLP_TOKEN=<token> # sent as "Authorization: Bearer <token>"
356
+ ```
357
+
358
+ **Disabling again**: set `"enabled": false`, or delete the `telemetry` block entirely. Either way the session probe subscribes to nothing and allocates nothing — telemetry leaves zero footprint until the next Pi restart, which fully forgets the settings.
359
+
360
+ Semantics (test-gated, see `telemetry/index.ts`):
361
+
362
+ - **Metadata only by default**: spans carry `flow.ref` / `phase` / `agent.name` / `subtask` and GenAI convention attributes (`gen_ai.usage.input_tokens`, `gen_ai.request.model`, ...). Prompt and completion bodies only appear when you set `telemetry.captureContent` (below).
363
+ - **Trace joining**: spans attach to the run's W3C trace via `PI_FLOW_TRACEPARENT`, so one `/flow` run is one trace in the backend. Find it in Tempo with TraceQL `{ .flow.ref = "<REF>" }`.
364
+ - **No-backend safety**: export is fire-and-forget with a 2.5s timeout. Failures write at most ONE journal note per process and then stay silent — no retry queue, no buffer growth, never a rejected promise into the host. Flows run identically with no receiver at all.
365
+
366
+ #### Work mode vs personal mode
367
+
368
+ Every run is tracked by a **tracking ref**: in **personal mode** the aven ref (as before); in **work mode** the **Jira key** — taken from the Jira ID you typed (`/flow DP-236`), else from the local epic's `jira-ref` metadata when you pass the aven epic, else the aven ref. The aven ref still drives the run journal and every aven operation; only telemetry and metrics are keyed by the tracking ref.
369
+
370
+ - Spans carry `flow.ref` (tracking ref), `flow.aven_ref` (when different), `flow.mode` (`work` | `personal`) and, with `telemetry.jiraBaseUrl` set, `flow.url` (work mode only).
371
+ - Cost metrics use the tracking ref as their `ref` label. Work-mode pushes go to a `mode="work"` Pushgateway group; personal pushes keep their original group (no mode label), so existing history is untouched.
372
+ - The Grafana dashboards have a **mode** switch (Personal / Work / All) and show an "Open in Jira ↗" link for work tickets.
373
+
374
+ #### Capturing content in spans
375
+
376
+ By default spans never carry what the model said or what the tools did. `telemetry.captureContent` opts in, in three **cumulative** layers — each level includes everything below it:
377
+
378
+ | Level | Adds | Span attributes |
379
+ | --- | --- | --- |
380
+ | `off` (default) | nothing — metadata only | — |
381
+ | `text` | what the model answered | `gen_ai.completion` on `gen <model>` spans |
382
+ | `tools` | + the tool calls the model made, + what each tool received and returned | `gen_ai.tool_calls` (JSON `[{name, arguments}]`) on gen spans; `tool.input` (JSON args) and `tool.output` (text result) on `tool <name>` spans |
383
+ | `all` | + the model's reasoning | `gen_ai.reasoning` on gen spans (redacted thinking is skipped) |
384
+
385
+ ```json
386
+ {
387
+ "telemetry": {
388
+ "enabled": true,
389
+ "otlpEndpoint": "https://tempo.example.com:4478",
390
+ "captureContent": "tools",
391
+ "maxContentChars": 2000
392
+ }
393
+ }
394
+ ```
395
+
396
+ Find the content in Grafana by opening a trace and clicking a span (Span attributes), or search it with TraceQL, e.g. `{ .gen_ai.completion =~ ".*migration.*" }` or `{ .tool.output =~ ".*ENOENT.*" }`.
397
+
398
+ Things to know before turning it on:
399
+
400
+ - **It can leak secrets.** Tool inputs/outputs and reasoning contain file contents, env dumps, tokens and personal data, and they land in the trace backend (Tempo keeps 14 days on the homelab) and everyone who can open Grafana can read them. There is **no redaction** — the level is the control. Start with `text`, and use `tools`/`all` only on a backend you trust.
401
+ - **Per-attribute cap.** Each value is cut at `maxContentChars` (default 2000) and ends with `…[truncated N chars]`. Tempo truncates attribute values beyond its `max_attribute_bytes` (default 2048) **silently**, so a larger `maxContentChars` only helps if you raise Tempo's limit too (Tempo exposes `tempo_distributor_attributes_truncated_total` to see it happening).
402
+ - **Per span, not per run.** Content is on the individual gen/tool spans. Phase, root and worker-session spans stay metadata-only.
403
+ - **Applies to every process.** Workers read the same config, so a worker's gen and tool spans carry content at the same level.
404
+ - **Restart Pi** after changing the setting; the config is read once per session.
405
+
406
+ #### Loki transition events
407
+
408
+ Alongside OTLP traces, pi-flow can push the **v2 state-machine transitions**
409
+ (`state-change`, `step-start`, `step-stop`) it journals to a Loki log stream,
410
+ so Grafana can show a per-run timeline and the Waiting-on-me queue can read
411
+ *what is waiting on me* straight from the events. This is a separate, opt-in
412
+ transport nested under the same `telemetry` block; it has its own
413
+ `loki.enabled` switch and ships **disabled by default**, so turning Loki on or
414
+ off is independent of whether OTLP traces export.
415
+
416
+ ```json
417
+ {
418
+ "telemetry": {
419
+ "enabled": true,
420
+ "otlpEndpoint": "https://tempo.example.com:4478",
421
+ "loki": {
422
+ "enabled": true,
423
+ "endpoint": "http://loki.example.com:3100",
424
+ "headers": {}
425
+ }
426
+ }
427
+ }
428
+ ```
429
+
430
+ You expose the Loki endpoint yourself (PMR-ZV9Y D2 — no bundled collector);
431
+ `telemetry.loki.endpoint` stores the **base** URL only and the pusher appends
432
+ `/loki/api/v1/push`, so the example above POSTs to
433
+ `http://loki.example.com:3100/loki/api/v1/push`. A Bearer token in front of a
434
+ reverse proxy belongs in `telemetry.loki.headers` (or better, env), not baked
435
+ into a committed config.
436
+
437
+ Loki does not need OTLP (PMR-VSST): with `telemetry.enabled: false` the
438
+ `otlpEndpoint` may be omitted entirely, so a Loki-only config is just
439
+
440
+ ```json
441
+ {
442
+ "telemetry": {
443
+ "enabled": false,
444
+ "loki": {
445
+ "enabled": true,
446
+ "endpoint": "http://loki.example.com:3100"
447
+ }
448
+ }
449
+ }
450
+ ```
451
+
452
+ The one surviving coupling: `telemetry.enabled: true` still **requires**
453
+ `otlpEndpoint` — the config is rejected at load otherwise.
454
+
455
+ Semantics (test-gated, see `telemetry/loki.ts`):
456
+
457
+ - **Closed labels only.** A stream carries `job="pi-flow"` plus the closed v2
458
+ enum set — `flow_ref`, `mode`, `phase`, `state`, `reason`, `wait_kind`,
459
+ `kind` — and nothing else. Free text (the halt `note` prose, deviation
460
+ reasons) rides the JSON **line**, never a label, so Loki cardinality stays
461
+ bounded. Query the whole family with `{job="pi-flow"}` and slice by `state`
462
+ or `flow_ref`.
463
+ - **Session-side only.** The live session's journal-writer fan-out pushes
464
+ each event as it is recorded; the durable daemon never pushes Loki (it has
465
+ no live event stream). One strict config reader, no daemon mirror.
466
+ - **Fail-silent.** Fire-and-forget with a 2.5 s timeout. An unreachable or
467
+ unconfigured endpoint writes **at most ONE** journal note per process and
468
+ then stays silent — no retry queue, never a rejected promise into the flow
469
+ loop. Runs proceed identically with no Loki backend at all. The unit tests
470
+ mock `fetch`, so nothing here depends on the endpoint being live.
471
+ - **Restart Pi** after changing the setting; the config is read once per session.
472
+
473
+ ### Notifications
474
+
475
+ When a flow stops and needs someone, pi-flow can surface it two ways. They are
476
+ **independent channels with independent off-switches** (PMR-ZV9Y D3): turn
477
+ either one off and the other keeps working, and neither affects the run itself.
478
+
479
+ | Channel | What it does | Off-switch |
480
+ | --- | --- | --- |
481
+ | **Desktop** | Pages you on a `waiting_human` or `halted` transition, through the [desktop-notify extension](../rifle-batteries/README.md) (notify-send / herdr / ntfy) | `notify.desktop.enabled` in pi-flow config (default `true`) — and the channel toggles in the desktop-notify module's own config |
482
+ | **Grafana alerting** | Fires the `pi-flow-runs` alert rules (`piflow-waiting-on-human`, `piflow-run-halted`, …) on the Prometheus/Loki series | Grafana itself: pause or mute the rule / alert group. pi-flow has no switch for it and never will — the alerting backend is not this extension's business |
483
+
484
+ **Desktop channel.** Only two v2 states page: `waiting_human` (a human unblocks
485
+ it) and `halted` (a human must). `waiting_machine` — a retry budget, a
486
+ subagent still working, a deviation gate re-run — is a Grafana/Loki concern,
487
+ never a notification, and `running` / `done` are silent. A subagent that is in
488
+ flight **but parked on an `ask_owner` question** is the exception that used to
489
+ be mislabelled: it pages as `waiting_human` / `subagent_ask_pending`, because
490
+ nothing moves until you answer it. The message is the journal event, nothing
491
+ else:
492
+
493
+ ```
494
+ pi-flow PMR-ZV9Y: waiting_human
495
+ /flow answer PMR-ZV9Y approve — reason: spec_approval_pending
496
+ ```
497
+
498
+ ```
499
+ pi-flow PMR-ZV9Y: waiting_human
500
+ answer the code_review ask (pass/fail in this session) — reason: code_review_pending
501
+ ```
502
+
503
+ ```
504
+ pi-flow PMR-ZV9Y: halted
505
+ reason: label_miss — recover with /flow PMR-ZV9Y
506
+ ```
507
+
508
+ ```
509
+ pi-flow PMR-ZV9Y: waiting_human
510
+ answer the subagent (its pane or answer_subagent) — reason: subagent_ask_pending
511
+ ```
512
+
513
+ The first line of the body is the **expected action** — the exact command from
514
+ the same `expectedAction` map the Waiting-on-me board renders, so what you type
515
+ is what the board already advertised. `subagent_ask_pending` is the one human
516
+ wait with no command to type: its action is prose pointing at the child's pane
517
+ (or the parent's `answer_subagent` tool). Only the closed reason enum is quoted;
518
+ free-text halt prose never enters a notification.
519
+
520
+ Semantics (test-gated, see `telemetry/dispatch.ts` and `test/notify-hook.test.ts`):
521
+
522
+ - **Opt-out.** `notify.desktop.enabled` defaults to `true`: a fresh install
523
+ pages. Set it to `false` (global or per-project config) for silence, no Pi
524
+ restart needed beyond the next config read (`session_start` / `/flow` start).
525
+ - **One page per event, not per state.** The loop already suppresses
526
+ same-state repeats inside a process, so a duplicate only happens when a gate
527
+ genuinely re-asks (you declined a review, the run re-parked) — that earns a
528
+ second page. A resumed run in another session re-notifies the same wait:
529
+ accepted, because the journal is the audit record and the notification mirrors it.
530
+ - **Fail-silent, optional dependency.** `@gtheys/rifle-batteries` (the
531
+ desktop-notify carrier since PMR-8YDK 5.2) is an
532
+ *optional* dependency, loaded by dynamic import on the first paging event.
533
+ Not installed, or its config malformed, or the notify backend dead → **one**
534
+ journal note (`desktop notify unavailable: … (channel off, further failures
535
+ silent)`) and the channel switches off for the session. It is fire-and-forget:
536
+ it never delays a journal write and never throws into the flow loop. Grafana
537
+ alerting is unaffected either way.
538
+
539
+ ```json
540
+ {
541
+ "notify": {
542
+ "desktop": {
543
+ "enabled": false
544
+ }
545
+ }
546
+ }
547
+ ```
548
+
549
+ ### Cost rollup push (`/flow-cost --push`)
550
+
551
+ The offline `/flow-cost <ref>` table needs nothing but the local journal. The optional `--push` export to a Prometheus Pushgateway is env-gated:
552
+
553
+ ```sh
554
+ export PI_FLOW_PUSHGATEWAY_URL=https://pushgateway.example.com:4479
555
+ export PI_FLOW_PUSHGATEWAY_TOKEN=<token>
556
+ ```
557
+
558
+ Push failures print a warning and never fail the command; rerun `/flow-cost <ref> --push` any time to re-export or backfill.
559
+
560
+ **Automatic push**: with `PI_FLOW_PUSHGATEWAY_URL` set, the same rollup is pushed for you whenever a `/flow` run ends — completed, halted, or paused for spec approval. A one-line notice confirms it (`flow-cost <ref>: cost metrics pushed to the pushgateway.`); a failure shows a warning with the retry command. With the URL unset nothing happens. Pushing is idempotent (same-identity series are overwritten in place — official Pushgateway replaces the whole group, the homelab build was verified to merge on write, PMR-WBC2), so a resumed flow just refreshes the numbers. The rollup covers spawned workers and, for runs started after the `main-session` journal event existed, the main session split across plan / implement / validate. It also includes a per-phase **step outputs** section summarizing `flow_submit` submissions (advisory evidence, never blocking). While a run is still in flight the daemon refreshes the same body on its own timer — see [Liveness](#liveness-running-flow-visibility).
561
+
562
+ **Terminal purge (done/stale publications).** `pi_flow_phase` means "the phase the run is in right now", so the render path stops emitting it once a run derives `done` or `stale` (PMR-2EGV — a halted run is still in its phase and keeps the line). But the homelab gateway merges on write, so an omitted line is never deleted: the phase series stored while the run was active would be served forever. The automatic push therefore precedes the terminal POST with a **guarded purge** (`flow/terminal-purge.ts`): read the stored group back, and DELETE the group only when the fresh terminal body provably still contains every stored series except the purge targets — the two in-flight gauges the render path already suppresses on terminal runs, `pi_flow_phase` and the open-step `pi_flow_step` — then POST the terminal body as usual, recreating the group without the residue. Halted and paused publications keep the plain POST. Every failure mode degrades to a warning plus the plain POST — the purge never blocks the push: a guard skip (a stored non-target series missing from the fresh body) leaves the residue in place and names the manual runbook (DELETE the pushgateway group, then `/flow-cost <ref> --push`); a failed read or DELETE warns the same way and pushes without cleanup. Three skip cases are known and intentional — the guard is fail-closed by design, so it never deletes past a stored-only series: (1) a rotated session file lost a cost row the stored group still has; (2) an **old-title residual** — a resumed run whose ticket was renamed leaves the previous `pi_flow_run_title_info` title variant stored alongside the current one on the merge-on-write gateway, and the fresh body carries only the current title (see Run title info below); (3) **stored v1 residue** — groups written before the v1 state-vocabulary retirement (PMR-ZV9Y) still serve `pi_flow_run_status` / `pi_flow_run_halt_reason` / `pi_flow_human_wait_seconds` / `pi_flow_gate_wait_seconds`, which no fresh body ever contains. In all three the phase/step residue simply stays served until the manual runbook above is run; the cost and history series are never at risk. A POST failure keeps the existing `/flow-cost <ref> --push` restore warning. The manual `/flow-cost <ref> --push` itself stays a plain, non-destructive POST — it never deletes a group.
563
+
564
+ **Run title info (`pi_flow_run_title_info{ref,title} 1`).** One extra line per run carries the ticket title so the boards can show `PMR-9DZ0 — Show the ticket title next to every ref` instead of a bare ref. It is an **info series** (value always `1`, one series per `ref`, labels `ref` and `title`) and it is **journal-derived**: the title is resolved once at run-start (aven's ticket title in personal mode, the Jira summary in work mode, sanitized to a single ≤120-char line) and journaled on the `run-start` event, and every push body re-renders it from that journal — never from a live ticket lookup at push time. That is what lets the daemon-side liveness push (see [Liveness](#liveness-running-flow-visibility)) carry it too: both push paths render the same body through `buildPushBody(trackRef, rows, durations, events)`. The render rule is **last title wins** — a resume that re-journals `run-start` with a new title supersedes the old one, while a resume whose lookup failed journals no title and therefore keeps the earlier one — and a run with no title anywhere in its journal emits **no line at all**, never an empty one. `filterGroupLines` (`flow/push.ts`) **keeps** the family in every fetched group body (PMR-2EGV, superseding the PMR-9DZ0/PMR-2CPZ prune). Terminal publication — the done purge and the stale tombstone — DELETEs the group and re-POSTs the stored body on this merge-on-write gateway, so the title must ride that re-post to survive: dropping it would delete run-title history, because the stored group is rebuilt from exactly what is sent. Keeping it cannot resurrect a stale title in the render: every fresh push re-renders the current title from the journal, and a terminal re-post carries forward whatever the last fresh push stored. One merge-on-write residual to know (PMR-3W5K): only an **unchanged** title is overwritten in place. When a resumed run's ticket was renamed, the new title is a different series (the `title` label differs), so the fresh push stores it **alongside** the old-title variant — the gateway never deletes the old one. That stored old-title variant then makes the terminal purge guard skip fail-closed (see Terminal purge above), leaving the phase/step residue served until the manual runbook (DELETE the pushgateway group, then `/flow-cost <ref> --push`) cleans the group. Consumers query it as `... * on (ref) group_left (title) pi_flow_run_title_info`, with an `or ... unless on (ref)` fallback arm so title-less runs (including every run journaling before this landed) stay visible; the label `ref` is preserved, so `ref=~"$ref"` filtering keeps working. Runs started before the title was journaled pick it up on their next start or resume.
565
+
566
+ ### Reconcile (stale run tombstoning)
567
+
568
+ Pushgateway groups never expire on their own: a `/flow` run that halted or
569
+ parked on a gate keeps exporting `pi_flow_state{state="halted"}` (or
570
+ `state="waiting_human"`/`state="waiting_machine"`) forever, so the halted and
571
+ waiting-on-human alerts go on firing for tickets that closed weeks ago
572
+ (PMR-V36Y started as exactly that — four alerts on four dead runs). Reconcile
573
+ retires those series by **tombstoning** them. (Before PMR-ZV9Y this flipped the
574
+ v1 `pi_flow_run_status` value and dropped `pi_flow_run_halt_reason`; those
575
+ v1 state-vocabulary lines are retired — the surgery is now on the v2 state
576
+ lines.)
577
+
578
+ **What counts as stale.** A journal run whose projected loop status is
579
+ `halted` or `paused` AND whose aven ticket status is neither `active` nor
580
+ `todo` (backlog, inbox, done, canceled, or the ticket is gone). `todo` counts
581
+ as live because gate-waiting runs park there (the flow loop moves tickets to
582
+ `active` later); backlog stays stale — an abandoned run parked in backlog
583
+ must not page. A live ticket keeps its series; a running journal is never
584
+ touched.
585
+
586
+ **A gap in the ticket listing never tombstones a live run.** Liveness is read
587
+ from `aven list`, and `aven list` is workspace-routed, so its answer can be
588
+ valid yet incomplete (a configured `avenWorkspace` other than the two
589
+ workspaces pi-flow pins). Because "missing from that listing" would then be
590
+ wrong evidence, every candidate the listing does not know gets a BOUNDED
591
+ direct question first — `aven show <ref> --json`, asked of the same workspaces
592
+ the listing covered plus aven's own cwd-inferred workspace, stopping at the
593
+ first one that knows the ref — so the direct lookups a pass can make stay
594
+ proportional to its candidate count. Three answers: aven says the ticket is
595
+ `active`/`todo` → the run is LIVE and is skipped as
596
+ `ticket live on direct lookup` (nothing is read from or written to the
597
+ gateway for it); aven says none of those universes has such a ticket →
598
+ genuinely gone, so it is tombstoned; aven cannot be asked at all (unreachable,
599
+ timeout, malformed output, or a ref that only matches by prefix) → the ref is
600
+ skipped as `aven lookup inconclusive` with one warning. That last case fails
601
+ closed PER REF: one bad shell-out costs one tombstone, not the whole pass, and
602
+ the question can only ever cancel a tombstone — it is asked solely for refs
603
+ the listing already lacked.
604
+
605
+ **What a tombstone does.** The run's Pushgateway group is deleted and
606
+ re-pushed from its stored body, with these changes and nothing else:
607
+
608
+ - `pi_flow_state{…}` and `pi_flow_state_start_seconds{…}` whose
609
+ `state="halted"|"waiting_human"|"waiting_machine"` become `state="stale"` —
610
+ a new state **value**; metric names and label keys stay frozen, so the alerts
611
+ and the Waiting-on-me board's value mappings simply stop matching a closed
612
+ run. The label-value flip lands even though the homelab gateway MERGES on
613
+ write rather than applying official Pushgateway replace semantics
614
+ (PMR-WBC2, verified live 2026-11-24): same-identity series are overwritten in
615
+ place, so `state="stale"` replaces the old value.
616
+ - the transient `pi_flow_step{…} 1` **open-step gauge and the
617
+ `pi_flow_phase{…} 1` current-phase gauge are dropped** from the re-POSTed
618
+ body. Both are in-flight evidence ("a step is in flight right now", "the run
619
+ is currently in this phase") that is definitively false for a retired run,
620
+ so neither can be value-flipped to `stale` — dropping them is the only lever.
621
+ The drops fire only when a state line was actually flipped (never for a live
622
+ run), match the exact `pi_flow_step{` / `pi_flow_phase{` prefixes and not
623
+ the cumulative `pi_flow_step_seconds{` / `pi_flow_wait_seconds{` siblings,
624
+ and are the belt-and-braces half of the anti-phantom fix: the **primary**
625
+ lever is render-side suppression in `flow/state-metrics.ts` (a
626
+ halted/done/stale run emits no open-step line; a done/stale run emits no
627
+ phase line), so these drops also clean an ALREADY-STORED phantom. Because
628
+ the homelab gateway merges on write, the pass DELETEs the group before
629
+ re-POSTing, so the drops take effect there too.
630
+ - the `pi_flow_run_title_info{…}` title series **stays in the fetched body**
631
+ and is re-posted with it (`filterGroupLines` in `flow/push.ts`, PMR-2EGV
632
+ superseding the PMR-9DZ0 prune). Terminal publication re-posts the full
633
+ stored body after the group delete, so the title must ride that re-post to
634
+ survive: dropping it would delete run-title history. Every fresh push
635
+ re-renders the current title from the journal, so keeping it cannot
636
+ resurrect a stale one (see the **Run title info** paragraph above).
637
+
638
+ Every other line (cost, tokens, tool calls, durations, gate decisions, retry
639
+ and blocker counters, worktree sweep, run start, `pi_flow_run_role_info`, the
640
+ `pi_flow_run_title_info` title series, and the remaining non-state v2 families
641
+ `pi_flow_wait_seconds`/`pi_flow_step_seconds`) is re-emitted byte-identical, so
642
+ done-run cost history on the runs board is untouched. The pass DELETEs the
643
+ group and then re-POSTs the transformed body — on this merge-on-write gateway
644
+ that is what makes the phase/step drops effective, and it is safe by
645
+ construction: the re-posted body is a transform of the group read seconds
646
+ earlier, so every non-target family is rebuilt wholesale. No non-target family
647
+ is intended to be lost. A DELETE failure skips with no re-POST at all (the
648
+ group stays untouched); a POST failure after a successful DELETE gets one
649
+ bounded in-process retry, and if that fails too the warning names
650
+ `/flow-cost <ref> --push` as the restore path (the body is deterministic from
651
+ the journal and session files). The one accepted residual: a process crash in
652
+ the narrow DELETE→POST window leaves the group gone until that same manual
653
+ restore is run.
654
+
655
+ One consequence of cutting over to v2 (matches the 6.5 cutover): a group
656
+ **stored before the v2 render landed** carries only v1 lines and no
657
+ `pi_flow_state*` to flip, so `tombstoneBody` reads it as `already clean` and
658
+ never re-posts it. That is harmless — every alert rule and board was cut to the
659
+ v2 vocabulary, so a stale v1-only body drives nothing anymore; re-push the
660
+ run's group (a terminal `/flow-cost <aven-ref> --push`, or let the next run
661
+ re-render) to give it v2 series.
662
+
663
+ **Where it runs.** Two places, same engine:
664
+
665
+ - The daemon timer: first pass ~60 s after the daemon starts, then every
666
+ `reconcile.intervalMinutes` (default 360 = 6 h). One summary line lands in
667
+ `<agentDir>/pi-flow/server.log` per pass.
668
+ - `/flow-reconcile-push` for an immediate pass, with `--dry-run` to list what
669
+ would be tombstoned without pushing anything.
670
+
671
+ Both are gated on `PI_FLOW_PUSHGATEWAY_URL`: the daemon timer is never armed
672
+ without it, and a REAL `/flow-reconcile-push` run refuses with an error rather
673
+ than silently doing nothing. A `--dry-run` is the documented exception — it
674
+ still answers "which runs would be retired?" without a gateway, from the run
675
+ journals + aven alone, and labels its output `candidates only, groups not
676
+ inspected` so nobody mistakes an unverified body for a verified one.
677
+
678
+ ```
679
+ DRY RUN — nothing pushed
680
+ PI_FLOW_PUSHGATEWAY_URL unset — candidates only, groups not inspected
681
+ reconcile pass: scanned=123 candidates=4 stale=4 tombstoned=0 skipped=0 dry-run
682
+ PMR-C0WG (ticket backlog) journal=halted → would tombstone
683
+ PMR-ESPA (ticket done) journal=halted → would tombstone
684
+ PMR-HHS8 (ticket done) journal=halted → would tombstone
685
+ PMR-XXXX (ticket todo) journal=halted → would tombstone
686
+ ```
687
+
688
+ With the URL set, the `groups not inspected` header disappears (the groups ARE
689
+ read) and the arrow shows what actually happened: `→ tombstoned`,
690
+ `→ skipped: already clean`, `→ skipped: pushgateway responded 500 …` — the
691
+ same pass above, run against a real gateway, reported
692
+ `skipped=1 … → skipped: already clean` for a ref whose stored body held no
693
+ liveness series to retire, a fact only the gateway can tell you. A
694
+ `ticket missing` status is the ordinary case for a deleted or never-filed
695
+ ticket — a missing ticket is stale, once the direct question above agrees.
696
+ Refs that stayed live are not listed; the `candidates=N` count covers them.
697
+
698
+ **Known limitation: only journals name the candidates.** Because candidacy
699
+ comes from the run journals, Reconcile can never retire a Pushgateway group
700
+ that no journal names any more. A work group exporting
701
+ `ref="DP-253",mode="work"` at `state="waiting_human"` whose run re-tracked to a
702
+ different journal ref (say `AA-SG9T`) stays exported, and a waiting-on-human
703
+ alert rule can still fire on it; likewise a resumed run keeps its stored wait
704
+ state until the next terminal transition re-pushes it. Sweeping the gateway dump
705
+ instead (retire every halted/waiting group whose ticket is closed) is
706
+ deliberately out of scope: a stored group carries no identity beyond its
707
+ `ref` label, so a sweep means guessing which journal that ref belongs to, and
708
+ a sweep that ignores `ref` entirely would reach adhoc runs and other jobs'
709
+ groups. If this bites, `/flow-reconcile-push` cannot help either — snapshot the
710
+ full `/metrics` dump, DELETE only the affected group, then re-push its retained
711
+ body (omitting the v2 state line is not enough on the merge-on-write gateway),
712
+ or let the `piflow-waiting-on-human` rule page and close the loop.
713
+
714
+ **Fail-closed on aven errors.** If `aven list` fails, times out, or returns
715
+ something unexpected, the pass tombstones **nothing** and logs exactly one
716
+ warning. An empty universe counts as such a failure: every workspace
717
+ answering zero tickets on a host that holds hundreds is aven breaking in a way
718
+ that still parses, and reading it as a real "no tickets" answer would retire
719
+ every halted run at once, so it fails closed too. Worst case the alerts keep
720
+ firing on stale runs until aven recovers — status quo, visible, honest. A
721
+ malformed config likewise falls back to the defaults with a warning instead of
722
+ silently switching retires off.
723
+
724
+ **Only the global file counts for the timer.** The daemon has no session
725
+ directory, so the interval comes from `~/.pi/agent/pi-flow/config.json` only —
726
+ per-checkout config does not affect it. `/flow-reconcile-push` is the escape
727
+ hatch when you need a pass now, or for one checkout.
728
+
729
+ **Mode is not part of the decision.** The candidate filter asks only whether a
730
+ JOURNAL projects a halted/paused loop state (the v1 loop status — candidacy
731
+ stayed journal-keyed through the v2 cutover, so retiring the `pi_flow_run_status`
732
+ series did not change which refs are stale); liveness then comes from the aven
733
+ ticket map, where a missing entry is stale. In practice `TP-*` personal runs
734
+ carry no loop-state journal, so they never become candidates — but a
735
+ personal-mode ref that DOES have a halted/paused journal and no aven ticket
736
+ tombstones under the same rule. `mode` only picks the group URL suffix
737
+ (`/mode/work`), so the tombstone replaces the RIGHT group instead of creating
738
+ a duplicate personal one.
739
+
740
+ On the Grafana side, the `piflow-runs` board maps the `state="stale"` value to a
741
+ gray **stale (ticket closed)** and the needs-attention rows gate on the v2 state
742
+ value (`state="waiting_human"`, `state="halted"`, `state="running"`, …), so
743
+ tombstoned runs drop out of them while their cost history stays browsable.
744
+
745
+ ### Liveness (running-flow visibility)
746
+
747
+ Reconcile retires series for runs that are over. Liveness is the other half
748
+ of that story: until PMR-8MQH the group was only ever pushed at a TERMINAL loop
749
+ transition (`onRunEnd` → done/halt/pause, plus the manual
750
+ `/flow-cost <ref> --push`), so a flow that was still running exported
751
+ **nothing** — DP-253 ran 14:21–14:37 and the board stayed empty until the
752
+ pause autopush landed at 14:37:05. The daemon now periodically re-pushes each
753
+ run that is in flight, so the v2 `pi_flow_state{state="running"}` gauge has a
754
+ producer and the board's running/needs-attention mappings actually light up.
755
+
756
+ **What it pushes.** Not a status-only patch — the FULL group body: cost, token,
757
+ tool-call and duration lines plus the run-health lines, rendered through the
758
+ SAME path the terminal autopush uses (`buildPushBody(trackRef, rows, durations,
759
+ events)`). That is a requirement, not a style choice: on official Pushgateway
760
+ semantics a POST replaces the entire group, so a partial body would drop the
761
+ cost series the terminal push owns. (The homelab gateway was verified to MERGE
762
+ on write instead — PMR-WBC2, 2026-11-24 — but the full-body rule stays: it is
763
+ correct under either semantics and does not depend on which build answers.) It
764
+ also means the two pushes of one run differ only in the state-vocabulary lines
765
+ (the v2 `pi_flow_state` / `pi_flow_state_start_seconds` / step and wait gauges
766
+ that the journal fold re-renders). Reading the stored group back with
767
+ `fetchGroupBody` is deliberately NOT used here — that round-trip stays reserved
768
+ for the tombstone reconcile above.
769
+
770
+ **Terminal push stays the last writer.** The pass re-reads and re-gates the
771
+ journal immediately before the POST, so a run that went terminal while the
772
+ rollup was being computed is skipped rather than stamped over the terminal
773
+ body. (A millisecond-scale window remains — the re-gate passes, the session
774
+ dies, and the terminal push lands before the POST does. When it hits, the
775
+ group sticks at `state="running"`: liveness never revisits the ref (the
776
+ journal no longer projects running) and the tombstone reconcile only
777
+ covers halted/paused journals, so nothing self-heals until the group is
778
+ replaced — a restart under the same ref, or manual cleanup. Rare, accepted,
779
+ documented rather than silent.) Refs projecting
780
+ anything other than `running` — paused, halted, done, no projection — are
781
+ never touched by liveness.
782
+
783
+ **Where it runs.** The daemon timer only: first pass ~60 s after the daemon
784
+ starts, then every `liveness.intervalMinutes` (default 5). A run too fresh to
785
+ have any cost rows yet still gets a body pushed (the run-health and duration
786
+ lines, no cost lines), so it appears on the board at the first tick instead of
787
+ waiting for its first cost-bearing push — but only for runs whose trackRef is
788
+ the journal ref (personal runs, and work runs with no Jira key): a work-mode
789
+ fresh run tracked by the shared Jira key would erase the previous run's cost
790
+ series with a zero-cost body, so such refs wait for their first cost-bearing
791
+ pass. One summary line lands in `<agentDir>/pi-flow/server.log` per pass; a
792
+ broken journal or a failed POST costs one warning and a `failed` count, never
793
+ the pass.
794
+
795
+ ```
796
+ liveness pass: scanned=42 pushed=2 skipped=40 failed=0
797
+ ```
798
+
799
+ Like reconcile, the timer is gated on `PI_FLOW_PUSHGATEWAY_URL` — unset
800
+ means no timer at all (one log line, no journal reads for liveness), and
801
+ `liveness.enabled = false` arms nothing. There is no `/flow-liveness-push`
802
+ command: the exported `runLivenessPassOnce` is the manual escape hatch for
803
+ verification.
804
+
805
+ **Only the global file counts for the timer.** Same dual-reader rule as
806
+ `reconcile`: the session side reads the `liveness` block through `config.ts`
807
+ (typed, throws on a malformed value), the daemon reads the raw global JSON
808
+ tolerantly and falls back to the defaults with a warning. The daemon has no
809
+ session directory, so a per-checkout `liveness` override does not affect it —
810
+ only `~/.pi/agent/pi-flow/config.json` does.
811
+
812
+ **Known limitation: a crashed run stays `running`.** Liveness only stamps
813
+ what the journal projects, and a session that died mid-run never wrote a
814
+ terminal loop state, so its series keeps refreshing (or, if the daemon died
815
+ with it, simply stays) as `running` until either a terminal push happens for
816
+ that ref or its group is cleaned up. Detecting crashed-running flows is out
817
+ of scope for this feature — reconcile tombstones halted/paused only.
818
+
819
+ ### Aven ref resolution
820
+
821
+ Aven resolves refs against the workspace inferred from the current
822
+ directory via project path mappings. On a checkout without such a mapping,
823
+ pi-flow falls back automatically: `aven show <ref> --json` first, then an
824
+ exact-ref `aven search` in the active workspace, then a sweep of every
825
+ workspace from `aven workspace list`; the resolved workspace is pinned for
826
+ all later calls on that ref. If nothing matches, the failure names the
827
+ fix. Two one-time remedies:
828
+
829
+ ```sh
830
+ # map this checkout to its aven project (recommended)
831
+ aven project path add pi-my-rifle-ext /path/to/this/checkout
832
+
833
+ # or pin the workspace explicitly in pi-flow config.json (see avenWorkspace)
834
+ ```