@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
@@ -0,0 +1,738 @@
1
+ // AIDEV-NOTE (PMR-MSDJ 1.3, plan PMR-V36Y): node-only tombstone engine for
2
+ // stale run-liveness metrics. Halted/paused `pi_flow_run_status` series are
3
+ // NEVER deleted — deleting the group would also erase the cost/token rows the
4
+ // `piflow-runs` board needs (true under official Pushgateway replace
5
+ // semantics AND under the merge-on-write behavior verified live on the
6
+ // homelab build, PMR-WBC2).
7
+ // Instead a stale run's group is re-pushed with the liveness series
8
+ // TOMBSTONED. Semantics of a tombstone:
9
+ // • `pi_flow_run_status{…status="halted"|"paused"}` becomes `status="stale"`
10
+ // — a NEW status VALUE, metric names and label KEYS stay frozen, so the
11
+ // dashboard's value mappings (and the alert rules' `status="halted"`)
12
+ // simply stop matching a closed run;
13
+ // • `pi_flow_run_halt_reason{…}` is DROPPED entirely, which is what makes
14
+ // the "needs attention" tables stop listing dead runs (the reason series
15
+ // only ever exists for halted runs). AIDEV-NOTE (PMR-WBC2, verified live
16
+ // 2026-11-24): the homelab gateway MERGES on write — an omitted series
17
+ // KEEPS being served, so this drop removes halt_reason only under
18
+ // official Pushgateway replace semantics; there it survives until
19
+ // overwritten. Tables and alerts still clear: both gate on `status`, and
20
+ // the status flip to `stale` lands (same-identity series are overwritten
21
+ // in place). The drop stays — correct under either semantics;
22
+ // • everything else is re-emitted byte-identical, so
23
+ // `sum(pi_flow_gate_wait_seconds)` / `pi_flow_human_wait_seconds` and all
24
+ // cost accounting are unaffected.
25
+ //
26
+ // AIDEV-NOTE (PMR-ZV9Y 7.1): the three bullets above are the PRE-retirement
27
+ // (PMR-MSDJ/PMR-WBC2) semantics and are kept as history. The v1 state
28
+ // vocabulary they describe (`pi_flow_run_status`, `pi_flow_run_halt_reason`)
29
+ // is no longer rendered by flow/run-health.ts, so `tombstoneBody` now performs
30
+ // the SAME label-VALUE-only surgery on the v2 STATE lines ONLY:
31
+ // `pi_flow_state{…}` and `pi_flow_state_start_seconds{…}` with
32
+ // `state="halted"|"waiting_human"|"waiting_machine"` become `state="stale"`.
33
+ // The candidacy filter is UNCHANGED and stays JOURNAL-keyed (`livenessStatusOf`
34
+ // reads the projected v1 loop status from the run journal, never a metric line),
35
+ // so retiring the v1 status series does not change WHICH refs are stale — only
36
+ // which lines in a fetched body are rewritten.
37
+ // AIDEV-NOTE (PMR-ZV9Y fix round 1, P3a — RETRACTS the "no line is DROPPED any
38
+ // more" sentence this note originally carried): the tombstone is NOT pure value
39
+ // surgery. `tombstoneBody` (1) VALUE-FLIPS `pi_flow_state` and
40
+ // `pi_flow_state_start_seconds` from `halted|waiting_human|waiting_machine` to
41
+ // `stale`, AND (2) DROPS the transient `pi_flow_step{…} 1` gauge entirely from
42
+ // the re-POSTed body. The drop exists because `pi_flow_step` is the only v2
43
+ // family with NO state label whose whole meaning ("a step is in flight right
44
+ // now") is definitively FALSE for a retired run — it cannot be value-flipped to
45
+ // stale, so dropping is the only lever. It fires ONLY when a state line was
46
+ // actually flipped (`rewrites > 0`), so a live run's open step is never touched,
47
+ // and it matches only `pi_flow_step{` (the `{`), never `pi_flow_step_seconds{`.
48
+ // WHY a drop is correct despite this file's own earlier note (P3a): under
49
+ // OFFICIAL Pushgateway REPLACE semantics (the contract the GET-transform-POST
50
+ // round-trip assumes) an omitted series is gone after the re-POST — which is
51
+ // exactly the phantom-in-flight-step cleanup we want for a dead run. On the
52
+ // homelab gateway that MERGES on write (PMR-WBC2) an omission alone degrades
53
+ // to a no-op (the stored series persists until overwritten), just like the
54
+ // retired halt_reason drop — which is exactly why the pass no longer relies
55
+ // on omission: PMR-2EGV DELETEs the whole group and re-POSTs the transformed
56
+ // body (see `runReconcilePass`), so the drop is effective under BOTH
57
+ // semantics. The render-side suppression in flow/state-metrics.ts
58
+ // (`isTerminalState` for the step, `isPhaseRetiredState` for the phase) stays
59
+ // the PRIMARY lever — it stops NEW phantoms from ever being pushed; the
60
+ // delete+re-post tombstone is the half that also cleans an ALREADY-STORED
61
+ // phantom.
62
+ // AIDEV-NOTE (PMR-2EGV 2.3): the drop set is now TWO transient gauges —
63
+ // `pi_flow_step{…}` (P3a) and `pi_flow_phase{…}` (a stale run has no current
64
+ // phase, mirroring the render-side `isPhaseRetiredState` rule). Every OTHER
65
+ // v2 family (`pi_flow_wait_seconds`, `pi_flow_step_seconds`) is re-emitted
66
+ // byte-identical — only the two `{`-suffixed exact prefixes are dropped. The
67
+ // tests in test/reconcile-tombstone-v2.test.ts PIN both drops.
68
+ // (Fix round 3 note: the README and docs/pi-flow-observability.md previously
69
+ // still said "no line is dropped any more" and listed `pi_flow_step` among the
70
+ // byte-identical re-emissions — both were corrected to this contract.)
71
+ // Consequence to accept (matches the 6.5 cutover): a stored group that predates
72
+ // the v2 render carries only v1 lines, so `tombstoneBody` reads it as "already
73
+ // clean" (null) and never re-posts it. That is harmless because every alert
74
+ // rule and board was cut to the v2 vocabulary in 6.2–6.5, so a stale v1-only
75
+ // body drives nothing anymore; the pre-existing P2-4 "stored group the journal
76
+ // no longer describes" limitation already covers this shape.
77
+ //
78
+ // AIDEV-NOTE: because a POST REPLACES THE WHOLE GROUP (official Pushgateway
79
+ // semantics; the homelab build merges on write — PMR-WBC2, see above. The
80
+ // full-body rule holds under both), the body must carry
81
+ // every line that was stored — hence the GET-transform-POST round-trip via
82
+ // `fetchGroupBody`. A body rebuilt from the journal could silently drop
83
+ // worker cost rows (assignment records live only in extension memory), which
84
+ // would permanently destroy done-run cost history. Never rebuild: transform.
85
+ //
86
+ // Dependency contract (server/daemon.ts header, daemon.ts:1-11): this module
87
+ // imports ONLY `../run-state.ts` and types from `./push.ts` and
88
+ // `../aven/status.ts`. The `TicketProbe` import is TYPE-ONLY (erased at
89
+ // runtime), so no new runtime edge is added.
90
+ // No
91
+ // `@earendil-works/pi-coding-agent`, no `@gtheys/pi-interactive-subagents`,
92
+ // no `aven/client.ts` (it imports config.ts → pi-coding-agent at runtime), no
93
+ // `flow/cost.ts` (runtime dep on pi-interactive-subagents), no `config.ts`.
94
+ // NOTE: run-state.ts itself does runtime-import pi-coding-agent today
95
+ // (getAgentDir) — a pre-existing condition found in 1.2. server/daemon.ts's
96
+ // header contract was corrected for this in 2.2: what is enforceable is that
97
+ // the reconcile modules add NO NEW runtime dependency beyond run-state.ts +
98
+ // flow/push.ts + aven/status.ts (which is what this file does).
99
+ import type { TicketProbe } from '../aven/status.ts'
100
+ import {
101
+ type FlowRunEvent,
102
+ type LoopRunStatus,
103
+ projectRunState,
104
+ runTracking,
105
+ } from '../run-state.ts'
106
+ // AIDEV-NOTE: PMR-7B8M — TYPE-ONLY import by design. `ReconcileReport.daemonStaleness`
107
+ // below is an advisory, SESSION-SIDE-ONLY field: the daemon's own reconcile
108
+ // passes can never fill it (a daemon cannot judge its staleness against a
109
+ // session checkout — it does not know one), so it stays undefined on the
110
+ // daemon path and formatReconcileReport renders nothing. flow/reconcile.ts is
111
+ // daemon-reachable and node-only per the daemon DEPENDENCY CONTRACT (file
112
+ // header), so this module must gain NO runtime edge to
113
+ // server/staleness.ts (which value-imports session-side server/lifecycle.ts).
114
+ // test/cost-rows-node-only.test.ts strips type-only edges when it walks the
115
+ // runtime graph, which is exactly why this one is safe.
116
+ import type { DaemonStaleness } from '../server/staleness.ts'
117
+ import type { GroupBodyResult, PushResult } from './push.ts'
118
+
119
+ /** Liveness statuses that a tombstone retires.
120
+ * AIDEV-NOTE: EXPORTED because the gateway-less `--dry-run` half of
121
+ * `/flow-reconcile-push` (flow/reconcile-command.ts) decides with the SAME
122
+ * data this engine does. Keeping it private meant two places to update when a
123
+ * status is ever added, i.e. a dry-run that could disagree with the real
124
+ * pass. `livenessStatusOf` below is the shared projection rule. */
125
+ export const LIVENESS_STATUSES = ['halted', 'paused']
126
+
127
+ /** Ticket statuses that keep a halted/paused run LIVE (see computeStaleRefs
128
+ * docstring for the amendment evidence). */
129
+ export const LIVE_TICKET_STATUSES = ['active', 'todo']
130
+
131
+ /** The ONE aven fail-closed warning, exported for the same reason: both entry
132
+ * points must say the identical thing (the manual test counts it as exactly
133
+ * one user-visible warning). */
134
+ export const AVEN_FAILED_WARNING =
135
+ 'reconcile: aven ticket statuses unavailable — tombstoned nothing this pass (fail-closed)'
136
+
137
+ // AIDEV-NOTE (PMR-MSDJ fix round, P2-1 — bounded confirmation of a MISSING
138
+ // ref): "missing from the merged listing ⇒ stale" is EVIDENCE of a closed
139
+ // ticket, not PROOF of an absent one — `listTicketStatuses` merges only the
140
+ // two host-pinned workspaces, so a valid-but-incomplete universe (an
141
+ // `avenWorkspace` override to a third) reads as "gone" and would tombstone a
142
+ // LIVE run. So `runReconcilePass` asks aven about each unknown candidate
143
+ // DIRECTLY (`ticketStatusOf` in aven/status.ts), which bounds aven cost by the
144
+ // CANDIDATE count, not the run population: one shell-out when the first
145
+ // universe knows the ref, at most `workspaces + 1` when it is really gone. A
146
+ // null probe fails CLOSED PER REF — one bad shell-out costs one tombstone,
147
+ // not the pass. The probe can only ever VETO (it runs solely for refs the map
148
+ // already lacks), so it never widens the stale set. `scanWithoutGateway`
149
+ // (flow/reconcile-command.ts) does NOT probe: it reports unprobed dry-run
150
+ // candidates and never pushes, so its worst case is an over-reported line.
151
+ const INCONCLUSIVE_PROBE_REASON = 'aven lookup inconclusive'
152
+ const LIVE_ON_PROBE_REASON = 'ticket live on direct lookup'
153
+
154
+ /** The tombstone status value (label-VALUE-only addition; frozen labels). */
155
+ const STALE_STATUS = 'stale'
156
+
157
+ // AIDEV-NOTE (PMR-ZV9Y 7.1): the v1 line prefixes this engine used to key on
158
+ // (`pi_flow_run_status{`, `pi_flow_run_halt_reason{`) are gone with the retired
159
+ // v1 state vocabulary, so only the v2 state families below are targets now.
160
+
161
+ // AIDEV-NOTE (PMR-ZV9Y 3.2): the v2 state families get the SAME label-VALUE-only
162
+ // surgery as the v1 status line, for the same reason: renaming a metric or a
163
+ // label KEY would break the rebuilt boards, while flipping a VALUE retires the
164
+ // series because every v2 consumer (the Waiting-on-me queue, the halted rule)
165
+ // gates on `state="…"`. ISC-8. The two prefixes are disjoint by construction —
166
+ // `pi_flow_state_start_seconds{` never matches `pi_flow_state{` because the 12th
167
+ // char is `_`, not `{` — so one family can never shadow the other.
168
+ //
169
+ // The states the retired v1 rewrite used to retire were `halted|paused`. Its v2
170
+ // counterparts are `halted` (same word) plus the two wait states v1 collapsed
171
+ // into `paused`: `waiting_human` and `waiting_machine`. `running` and `done` are
172
+ // deliberately NOT targets, mirroring v1 exactly: v1 never tombstoned
173
+ // `status="running"|"done"`, and candidacy is JOURNAL-keyed
174
+ // (`livenessStatusOf` reads the v1 loop status), so a group whose stored body
175
+ // still shows a state the journal has moved past is reported "already clean"
176
+ // rather than half-retired — the P2-4 known limitation, held identical across
177
+ // both vocabularies on purpose. `stale` is the tombstone value itself, so
178
+ // re-running the pass over an already-tombstoned body stays a no-op.
179
+ const V2_STATE_METRICS = ['pi_flow_state{', 'pi_flow_state_start_seconds{']
180
+ const V2_LIVENESS_STATES = ['halted', 'waiting_human', 'waiting_machine']
181
+
182
+ // AIDEV-NOTE (PMR-RE56): merge-on-write accumulation (PMR-WBC2) leaves OLDER
183
+ // state variants in the stored body — a run that went running → halted holds
184
+ // BOTH `state="running"` and `state="halted"` lines. `running` is not a flip
185
+ // target (V2_LIVENESS_STATES above), so it used to pass the tombstone through
186
+ // and DELETE+re-POST rebuilt a live-looking row for a dead run. Once a
187
+ // tombstone rewrite occurs, these obsolete non-stale current-state variants
188
+ // are DROPPED alongside the transient gauges — they carry no value worth
189
+ // flipping, since the `stale` series already records the run's terminal
190
+ // state. The drop fires ONLY when rewrites > 0, so a genuinely live running
191
+ // run (no halted/waiting variant to flip) still reads "already clean" (null)
192
+ // and is never touched. `done` stays untouched: it is not a live-looking
193
+ // state and was never named a tombstone problem.
194
+ const V2_OBSOLETE_STATES = ['running']
195
+
196
+ /**
197
+ * The liveness status a journal projects, or null when the run is NOT a
198
+ * reconcile candidate: no projection, no loop state, or a status outside
199
+ * `LIVENESS_STATUSES` (a `running` run is never retired; an unprojectable or
200
+ * empty journal is not either).
201
+ *
202
+ * Exported because `/flow-reconcile-push --dry-run` without a gateway runs
203
+ * exactly this filter and nothing else — one rule, two surfaces.
204
+ */
205
+ export function livenessStatusOf(
206
+ events: readonly FlowRunEvent[],
207
+ ): LoopRunStatus | null {
208
+ const status = projectRunState(events)?.loop?.status
209
+ if (status === undefined) return null
210
+ if (!LIVENESS_STATUSES.includes(status)) return null
211
+ return status
212
+ }
213
+
214
+ /**
215
+ * Pure liveness rule (interview decision 2, AMENDED in 2.3 smoke): a
216
+ * halted/paused journal run is LIVE while its aven ticket status is
217
+ * `active` OR `todo`. Anything else — backlog/inbox/done/canceled, or the
218
+ * ticket missing from the listing — makes the ref stale. `ticketStatus ===
219
+ * null` means aven could not be consulted, which fails CLOSED: nothing is
220
+ * tombstoned on a guess.
221
+ *
222
+ * AIDEV-NOTE (amendment evidence, 2026-11-24): the first live dry-run listed
223
+ * PMR-MSDJ's OWN in-flight run as a stale candidate — its journal's last
224
+ * loop state is `paused` (waiting at the plan-approval gate) while its
225
+ * ticket sits in `todo`, because the flow loop never moves the ticket to
226
+ * `active` before implement. Under active-only the daemon would tombstone
227
+ * runs that are merely gate-waiting. The user's original criterion was
228
+ * "done or canceled must not fire" — `todo` is neither, so todo stays live.
229
+ * backlog/inbox stay stale: an abandoned run parked in backlog (the
230
+ * PMR-C0WG incident) must not page.
231
+ *
232
+ * @param journalStates ref → projected `loop.status` (only `halted`/`paused`
233
+ * entries are candidates; any other value is ignored defensively).
234
+ * @returns stale refs in the journal map's iteration order.
235
+ */
236
+ export function computeStaleRefs(
237
+ journalStates: Map<string, string>,
238
+ ticketStatus: Map<string, string> | null,
239
+ ): string[] {
240
+ if (ticketStatus === null) return []
241
+ const stale: string[] = []
242
+ for (const [ref, status] of journalStates) {
243
+ if (!LIVENESS_STATUSES.includes(status)) continue
244
+ if (LIVE_TICKET_STATUSES.includes(ticketStatus.get(ref) ?? '')) continue
245
+ stale.push(ref)
246
+ }
247
+ return stale
248
+ }
249
+
250
+ /**
251
+ * Pure line-wise transform of a group body read back from the gateway: rewrite
252
+ * `state="halted"` / `state="waiting_human"` / `state="waiting_machine"` to
253
+ * `state="stale"` on `pi_flow_state` and `pi_flow_state_start_seconds` lines and
254
+ * keep every other byte. Returns `null` when nothing was rewritten (already
255
+ * clean, already tombstoned, a running/done run, or the group is gone) —
256
+ * callers skip those so a body is never re-posted unchanged.
257
+ *
258
+ * AIDEV-NOTE (PMR-ZV9Y 7.1): used to also rewrite `status="halted"|"paused"` on
259
+ * `pi_flow_run_status` and DROP every `pi_flow_run_halt_reason` line. Both
260
+ * behaviours disappeared with the v1 state vocabulary — the lines are no longer
261
+ * rendered, and a drop is exactly what the merge-on-write homelab gateway could
262
+ * not honour anyway (PMR-WBC2), so removing it loses nothing. `livenessStatusOf`
263
+ * below still decides candidacy from the JOURNAL's v1 loop status, which is
264
+ * untouched by this retirement (LoopStateRecord / LoopRunStatus stay, plan D2).
265
+ *
266
+ * AIDEV-NOTE (PMR-ZV9Y 3.2): since the v2 gauges render into the SAME push
267
+ * body (flow/run-health.ts), the pass flips
268
+ * `state="halted"|"waiting_human"|"waiting_machine"` to `state="stale"` on
269
+ * `pi_flow_state` and `pi_flow_state_start_seconds` lines (ISC-8), so the
270
+ * Waiting-on-me queue and the halted rule retire with a closed run instead of
271
+ * keeping it on the board. AIDEV-NOTE (PMR-ZV9Y fix round 1, P3a — corrected
272
+ * the earlier "every other family is byte-identical" wording, which wrongly
273
+ * listed `pi_flow_step`): beyond the two value flips this pass DROPS the
274
+ * transient `pi_flow_step{…}` open-step gauge (no state label, meaning
275
+ * definitively false for a retired run — see the file header P3a note for the
276
+ * why and the merge-vs-replace posture). AIDEV-NOTE (PMR-2EGV 2.3): the
277
+ * transient `pi_flow_phase{…}` gauge is dropped alongside it — a stale run
278
+ * has no current phase (the render-side twin is `isPhaseRetiredState` in
279
+ * state-metrics.ts), and `runReconcilePass` now DELETEs the group before
280
+ * re-POSTing, so both drops are effective on the merge-on-write homelab
281
+ * gateway too. AIDEV-NOTE (PMR-RE56): obsolete non-stale current-state
282
+ * variants (`state="running"` lines on the two state families, left behind
283
+ * by merge-on-write accumulation) are dropped too — a tombstoned run serves
284
+ * ONLY the `stale` state series. Every OTHER v2 family (`pi_flow_wait_seconds`,
285
+ * `pi_flow_step_seconds`) plus all counters and cost rows is re-emitted
286
+ * byte-identical: label VALUES move on the state lines, the two transient
287
+ * gauges and the obsolete running variants are dropped, and
288
+ * `pi_flow_step_seconds` (the cumulative bucket) stays.
289
+ *
290
+ * The rewrite is minimal substring surgery inside the label section: label
291
+ * ORDER (the gateway emits them alphabetically, e.g.
292
+ * `{job="pi-flow",mode="work",ref="X",state="halted"}`), all sibling labels
293
+ * and the trailing value must survive byte-identical.
294
+ */
295
+ export function tombstoneBody(body: string): string | null {
296
+ const out: string[] = []
297
+ let rewrites = 0
298
+ for (const line of body.split('\n')) {
299
+ if (startsWithAny(line, V2_STATE_METRICS)) {
300
+ const rewritten = swapLabelValue(line, 'state', V2_LIVENESS_STATES)
301
+ if (rewritten !== null) {
302
+ out.push(rewritten)
303
+ rewrites += 1
304
+ continue
305
+ }
306
+ }
307
+ out.push(line)
308
+ }
309
+ if (rewrites === 0) return null
310
+ // AIDEV-NOTE (PMR-ZV9Y fix round, P3a — tombstone-side decision; extended
311
+ // by PMR-2EGV 2.3): a tombstone retires the run to `stale`, so the two
312
+ // transient gauges whose meaning is definitively FALSE for a retired run —
313
+ // the OPEN-step gauge `pi_flow_step{…} 1` ("a step is in flight right now")
314
+ // and the phase gauge `pi_flow_phase{…} 1` ("the run is currently in this
315
+ // phase") — are DROPPED from the re-POSTed body. Neither carries a state
316
+ // label, so they cannot be value-flipped to stale like the state pair;
317
+ // dropping is the only lever, and it runs ONLY here (rewrites > 0
318
+ // guarantees the same body already flips a state line to stale, so the drop
319
+ // never happens without a tombstone). Correct under the official
320
+ // Pushgateway Replace semantics the round-trip assumes; on the
321
+ // merge-on-write homelab gateway (PMR-WBC2) an omission alone would be a
322
+ // no-op, which is why `runReconcilePass` DELETEs the group before
323
+ // re-POSTing — the drop is effective under both semantics. The PRIMARY
324
+ // lever stays the render-side suppression in flow/state-metrics.ts
325
+ // (`isTerminalState` / `isPhaseRetiredState`); this is the half that also
326
+ // cleans an ALREADY-STORED phantom. The `{` is load-bearing: it matches
327
+ // only `pi_flow_step{…}` / `pi_flow_phase{…}`, never
328
+ // `pi_flow_step_seconds{…}` or a hypothetical `pi_flow_phase`-prefixed
329
+ // sibling family, which stay.
330
+ const dropped: string[] = []
331
+ for (const line of out) {
332
+ if (line.startsWith('pi_flow_step{')) continue
333
+ if (line.startsWith('pi_flow_phase{')) continue
334
+ // AIDEV-NOTE (PMR-RE56): drop the obsolete non-stale current-state
335
+ // variants (see V2_OBSOLETE_STATES) — a tombstoned run must serve ONLY
336
+ // the `stale` state series. Keyed on the v2 state metric NAMES (like the
337
+ // flip) and on a proper `state="…"` label token, so a decoy series or an
338
+ // escaped lookalike value inside another label survives.
339
+ if (
340
+ startsWithAny(line, V2_STATE_METRICS) &&
341
+ carriesLabelValue(line, 'state', V2_OBSOLETE_STATES)
342
+ ) {
343
+ continue
344
+ }
345
+ dropped.push(line)
346
+ }
347
+ return dropped.join('\n')
348
+ }
349
+
350
+ function startsWithAny(line: string, prefixes: readonly string[]): boolean {
351
+ for (const prefix of prefixes) {
352
+ if (line.startsWith(prefix)) return true
353
+ }
354
+ return false
355
+ }
356
+
357
+ /** True when the line's label section carries `<key>="<value>"` as a proper
358
+ * label token for one of `values`. Mirrors swapLabelValue's token scan (same
359
+ * boundary rules: token starts at the section start or after a comma, so an
360
+ * escaped `key="…"` inside another label's VALUE never matches). */
361
+ function carriesLabelValue(
362
+ line: string,
363
+ key: string,
364
+ values: readonly string[],
365
+ ): boolean {
366
+ const open = line.indexOf('{')
367
+ const close = line.lastIndexOf('}')
368
+ if (open < 0 || close <= open) return false
369
+ const inner = line.slice(open + 1, close)
370
+ const token = `${key}="`
371
+ let i = 0
372
+ while (i < inner.length) {
373
+ const at = inner.indexOf(token, i)
374
+ if (at < 0) return false
375
+ if (at !== 0 && inner[at - 1] !== ',') {
376
+ i = at + token.length
377
+ continue
378
+ }
379
+ const valueStart = at + token.length
380
+ const valueEnd = inner.indexOf('"', valueStart)
381
+ if (valueEnd < 0) return false
382
+ return values.includes(inner.slice(valueStart, valueEnd))
383
+ }
384
+ return false
385
+ }
386
+
387
+ /** Rewrite one `<key>="<retired>"` label to `<key>="stale"`. Returns null when
388
+ * the line carries no retired value for that key. Only label tokens are
389
+ * touched: a `key="…"`-shaped sequence inside another label's VALUE (the
390
+ * gateway escapes those as `\"`) or a longer label name ending in the same
391
+ * characters is left alone. */
392
+ function swapLabelValue(
393
+ line: string,
394
+ key: string,
395
+ retired: readonly string[],
396
+ ): string | null {
397
+ const open = line.indexOf('{')
398
+ const close = line.lastIndexOf('}')
399
+ if (open < 0 || close <= open) return null
400
+ const inner = line.slice(open + 1, close)
401
+ const token = `${key}="`
402
+ let labels = ''
403
+ let i = 0
404
+ let changed = 0
405
+ while (i < inner.length) {
406
+ const at = inner.indexOf(token, i)
407
+ if (at < 0) {
408
+ labels += inner.slice(i)
409
+ break
410
+ }
411
+ // A label token starts at the beginning of the section or after a comma.
412
+ if (at !== 0 && inner[at - 1] !== ',') {
413
+ labels += inner.slice(i, at + token.length)
414
+ i = at + token.length
415
+ continue
416
+ }
417
+ const valueStart = at + token.length
418
+ const valueEnd = inner.indexOf('"', valueStart)
419
+ if (valueEnd < 0) {
420
+ labels += inner.slice(i)
421
+ break
422
+ }
423
+ const value = inner.slice(valueStart, valueEnd)
424
+ labels += inner.slice(i, at)
425
+ if (retired.includes(value)) {
426
+ labels += `${key}="${STALE_STATUS}"`
427
+ changed += 1
428
+ } else {
429
+ labels += inner.slice(at, valueEnd + 1)
430
+ }
431
+ i = valueEnd + 1
432
+ }
433
+ if (changed === 0) return null
434
+ return `${line.slice(0, open + 1)}${labels}${line.slice(close)}`
435
+ }
436
+
437
+ /** Defaults for a best-effort daemon: reconcile on, every 6 hours. */
438
+ // AIDEV-NOTE: PMR-MSDJ (2.1) — these defaults are the daemon half of a
439
+ // DELIBERATE two-reader split over the same `<agentDir>/pi-flow/config.json`.
440
+ // `config.ts` PiFlowConfigSchema + resolveReconcileSettings are the typed
441
+ // extension half and must return the identical `{ enabled: true,
442
+ // intervalMinutes: 360 }` for an absent block (pinned by test/config.test.ts).
443
+ // This function stays here, not delegating to config.ts, because the daemon
444
+ // must remain node-only AND must not throw on a broken file — it warns and
445
+ // keeps retires running instead.
446
+ const DEFAULT_SETTINGS = { enabled: true, intervalMinutes: 360 }
447
+
448
+ /**
449
+ * Parse the `reconcile` block out of RAW config file text
450
+ * (`<agentDir>/pi-flow/config.json`). The daemon has no session cwd, so it
451
+ * reads the global file only and cannot use `config.ts` (which imports
452
+ * pi-coding-agent); this is the deliberately tolerant, fail-to-defaults
453
+ * version of that boundary. Malformed JSON, wrong shapes or an unusable
454
+ * interval fall back to the defaults AND return a `warning` the daemon logs —
455
+ * a broken config must not silently disable retires, and must not crash the
456
+ * daemon.
457
+ */
458
+ export function parseReconcileSettings(raw: string | null): {
459
+ enabled: boolean
460
+ intervalMinutes: number
461
+ warning?: string
462
+ } {
463
+ if (raw === null || raw.trim().length === 0) {
464
+ return { ...DEFAULT_SETTINGS }
465
+ }
466
+ let parsed: unknown
467
+ try {
468
+ parsed = JSON.parse(raw)
469
+ } catch {
470
+ return warned('reconcile: config file is not valid JSON')
471
+ }
472
+ if (!isRecord(parsed))
473
+ return warned('reconcile: config file is not an object')
474
+ if (parsed.reconcile === undefined) return { ...DEFAULT_SETTINGS }
475
+ if (!isRecord(parsed.reconcile)) {
476
+ return warned('reconcile: "reconcile" is not an object')
477
+ }
478
+ const block = parsed.reconcile
479
+ const settings: { enabled: boolean; intervalMinutes: number } = {
480
+ ...DEFAULT_SETTINGS,
481
+ }
482
+ if (block.enabled !== undefined) {
483
+ if (typeof block.enabled !== 'boolean') {
484
+ return warned('reconcile: "enabled" is not a boolean')
485
+ }
486
+ settings.enabled = block.enabled
487
+ }
488
+ if (block.intervalMinutes !== undefined) {
489
+ const minutes = block.intervalMinutes
490
+ if (
491
+ typeof minutes !== 'number' ||
492
+ !Number.isFinite(minutes) ||
493
+ minutes < 1
494
+ ) {
495
+ return warned('reconcile: "intervalMinutes" is not a number >= 1')
496
+ }
497
+ settings.intervalMinutes = minutes
498
+ }
499
+ return settings
500
+ }
501
+
502
+ function warned(warning: string): {
503
+ enabled: boolean
504
+ intervalMinutes: number
505
+ warning: string
506
+ } {
507
+ return { ...DEFAULT_SETTINGS, warning }
508
+ }
509
+
510
+ function isRecord(value: unknown): value is Record<string, unknown> {
511
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
512
+ }
513
+
514
+ /** Injected IO for one reconcile pass. Everything impure lives here so the
515
+ * engine stays node-only and testable with fakes. */
516
+ export interface ReconcileDeps {
517
+ /** Refs (journal basenames) to scan — the daemon readdir's `runsDir`. */
518
+ listJournalRefs(): Promise<string[]>
519
+ /** Journal events for a ref, or null when the journal is unreadable. */
520
+ readRunEvents(ref: string): Promise<readonly FlowRunEvent[] | null>
521
+ /** ref → aven ticket status, or null when aven is unreachable (fail-closed:
522
+ * the engine then tombstones nothing and warns once). */
523
+ listTicketStatuses(): Promise<Map<string, string> | null>
524
+ /** Direct answer about ONE ref the merged listing does not know (P2-1).
525
+ * Null (aven unreachable/anomalous) fails CLOSED for that ref: skip with
526
+ * 'aven lookup inconclusive' rather than tombstone a ticket we cannot see. */
527
+ ticketStatusOf(ref: string): Promise<TicketProbe | null>
528
+ /** Read one stored Pushgateway group back (full-dump GET + filter). */
529
+ fetchGroupBody(
530
+ trackRef: string,
531
+ mode: 'work' | 'personal',
532
+ ): Promise<GroupBodyResult>
533
+ /** AIDEV-NOTE (PMR-2EGV 2.3): DELETE the whole stored group BEFORE the
534
+ * tombstoned body is re-POSTed. The homelab gateway MERGES on write
535
+ * (PMR-WBC2), so an omitted `pi_flow_phase{`/`pi_flow_step{` line only
536
+ * disappears when the group is replaced wholesale — delete first, then
537
+ * re-POST. A DELETE failure is fail-closed: no re-POST may follow (it
538
+ * would leave the stale series served while reporting success). */
539
+ deleteGroup(trackRef: string, mode: 'work' | 'personal'): Promise<PushResult>
540
+ /** Replace a group with the tombstoned body (POST to the same group URL). */
541
+ pushTombstone(
542
+ trackRef: string,
543
+ mode: 'work' | 'personal',
544
+ body: string,
545
+ ): Promise<PushResult>
546
+ warn(message: string): void
547
+ }
548
+
549
+ export interface ReconcileStaleEntry {
550
+ ref: string
551
+ journalStatus: string
552
+ ticketStatus: string | undefined
553
+ }
554
+
555
+ export interface ReconcileSkipEntry {
556
+ ref: string
557
+ reason: string
558
+ }
559
+
560
+ export interface ReconcileReport {
561
+ /** Journals examined (refs from `listJournalRefs`). */
562
+ scanned: number
563
+ /** Journals projecting a halted/paused loop status. */
564
+ candidates: number
565
+ /** Refs judged stale (ticket not live: neither active nor todo). In dry-run this is the
566
+ * whole answer — `tombstoned` stays empty. */
567
+ stale: ReconcileStaleEntry[]
568
+ /** Refs whose group was replaced with the tombstoned body. */
569
+ tombstoned: string[]
570
+ /** Refs deliberately not tombstoned, with the reason. */
571
+ skipped: ReconcileSkipEntry[]
572
+ /** aven could not be consulted ⇒ zero tombstones this pass. */
573
+ avenFailed: boolean
574
+ /** Echo of the dry-run flag (so callers can render one message shape). */
575
+ dryRun: boolean
576
+ /**
577
+ * Daemon staleness verdict — filled ONLY by the session-side command
578
+ * (`/flow-reconcile-push`, PMR-7B8M), NEVER by `runReconcilePass`: the
579
+ * daemon cannot judge its own staleness (no session checkout to compare
580
+ * against), so on the daemon path this stays undefined and
581
+ * `formatReconcileReport` renders no line. Session-side only — see the
582
+ * type-only import of `DaemonStaleness` at the top of this file.
583
+ */
584
+ daemonStaleness?: DaemonStaleness
585
+ }
586
+
587
+ /**
588
+ * One reconcile pass. IO-free decisions are the exported pure functions
589
+ * above; this orchestrates them and keeps warnings bounded (at most
590
+ * `stale.length + 1` lines plus one per ref whose direct lookup came back
591
+ * inconclusive, and aven failure short-circuits before any gateway call).
592
+ */
593
+ export async function runReconcilePass(
594
+ deps: ReconcileDeps,
595
+ opts?: { dryRun?: boolean },
596
+ ): Promise<ReconcileReport> {
597
+ const dryRun = opts?.dryRun === true
598
+ const report: ReconcileReport = {
599
+ scanned: 0,
600
+ candidates: 0,
601
+ stale: [],
602
+ tombstoned: [],
603
+ skipped: [],
604
+ avenFailed: false,
605
+ dryRun,
606
+ }
607
+ const refs = await deps.listJournalRefs()
608
+ report.scanned = refs.length
609
+ const journalStates = new Map<string, string>()
610
+ const eventsByRef = new Map<string, readonly FlowRunEvent[]>()
611
+ for (const ref of refs) {
612
+ const events = await deps.readRunEvents(ref)
613
+ if (events === null) continue
614
+ const status = livenessStatusOf(events)
615
+ if (status === null) continue
616
+ // AIDEV-NOTE: PMR-MSDJ 2.2 — the candidate filter is deliberately
617
+ // MODE-AGNOSTIC; this closes the TODO 2.1 left for the orchestrator, whose
618
+ // decision is recorded here (do not "fix" it by adding `mode === 'work'`).
619
+ // Plan PMR-V36Y decision 6's OPERATIVE rule is the one 1.3 implemented and
620
+ // the plan text was patched to before approval (interview Q2): a ref is a
621
+ // candidate when ITS JOURNAL projects a halted/paused loop state — in ANY
622
+ // mode — and liveness is then decided solely by the aven ticket map, where
623
+ // a MISSING ticket is stale. Consequences, both user-approved:
624
+ // • TP-* personal runs carry no loop-state journal at all (the loop only
625
+ // snapshots for flow-driven runs), so they never reach this filter and
626
+ // ISC-5 ("personal runs never tombstoned") holds in practice;
627
+ // • a personal-mode run that DOES have a halted/paused journal but no
628
+ // aven ticket tombstones under the missing-ticket rule — that is the
629
+ // approved behaviour, and test/reconcile.test.ts
630
+ // ("personal-mode stale run uses the personal group") pins it
631
+ // deliberately. `mode` plays no part in the decision; `runTracking`
632
+ // below uses it only to pick the group URL suffix (work adds
633
+ // /mode/work), so the tombstone replaces the RIGHT group.
634
+ // AIDEV-NOTE (PMR-MSDJ review P2-4, KNOWN LIMITATION — documented, not
635
+ // fixed): journal-keyed candidacy can NEVER retire a Pushgateway group the
636
+ // journal no longer names — e.g. a work group exporting
637
+ // `ref="DP-253",mode="work"` at status="paused" whose journal now projects
638
+ // `running` under another ref (AA-SG9T), or a resumed run that keeps its
639
+ // `paused` series until the NEXT terminal transition. A gateway-side sweep
640
+ // (decide from the dump's halted/paused groups instead) is out of scope: a
641
+ // stored group carries no journal identity beyond its `ref` label, so
642
+ // sweeping means guessing the journal, and a ref-less sweep reaches adhoc
643
+ // runs and other jobs' groups. README's Reconcile section says the same.
644
+ journalStates.set(ref, status)
645
+ eventsByRef.set(ref, events)
646
+ }
647
+ report.candidates = journalStates.size
648
+ if (report.candidates === 0) return report
649
+
650
+ const ticketStatus = await deps.listTicketStatuses()
651
+ if (ticketStatus === null) {
652
+ deps.warn(AVEN_FAILED_WARNING)
653
+ report.avenFailed = true
654
+ return report
655
+ }
656
+
657
+ for (const ref of computeStaleRefs(journalStates, ticketStatus)) {
658
+ const journalStatus = journalStates.get(ref)
659
+ const events = eventsByRef.get(ref)
660
+ if (journalStatus === undefined || events === undefined) continue
661
+ let ticketStatusOfRef = ticketStatus.get(ref)
662
+ if (ticketStatusOfRef === undefined) {
663
+ // P2-1: one direct question to aven before a listing gap costs a live
664
+ // run its metrics.
665
+ const probe = await deps.ticketStatusOf(ref)
666
+ if (probe === null) {
667
+ report.skipped.push({ ref, reason: INCONCLUSIVE_PROBE_REASON })
668
+ deps.warn(
669
+ `reconcile ${ref}: ${INCONCLUSIVE_PROBE_REASON} — skipped fail-closed`,
670
+ )
671
+ continue
672
+ }
673
+ if (probe.kind === 'ticket') {
674
+ if (LIVE_TICKET_STATUSES.includes(probe.status)) {
675
+ report.skipped.push({ ref, reason: LIVE_ON_PROBE_REASON })
676
+ continue
677
+ }
678
+ ticketStatusOfRef = probe.status
679
+ }
680
+ }
681
+ report.stale.push({ ref, journalStatus, ticketStatus: ticketStatusOfRef })
682
+ // The group identity comes from the journal (same derivation as cost
683
+ // pushes), so the tombstone REPLACES the right group instead of creating
684
+ // a duplicate personal one.
685
+ const tracking = runTracking(events, ref)
686
+ const fetched = await deps.fetchGroupBody(tracking.trackRef, tracking.mode)
687
+ if (fetched.ok === false) {
688
+ report.skipped.push({ ref, reason: fetched.error })
689
+ deps.warn(`reconcile ${ref}: reading the group failed: ${fetched.error}`)
690
+ continue
691
+ }
692
+ const tombstone = tombstoneBody(fetched.body)
693
+ if (tombstone === null) {
694
+ report.skipped.push({ ref, reason: 'already clean' })
695
+ continue
696
+ }
697
+ if (dryRun) continue
698
+ // AIDEV-NOTE (PMR-2EGV 2.3): DELETE the stored group BEFORE re-POSTing
699
+ // the tombstone. The homelab gateway merges on write (PMR-WBC2), so the
700
+ // phase/step drops in `tombstoneBody` only take effect when the group is
701
+ // replaced wholesale. Fail-closed at every step: a DELETE failure skips
702
+ // with NO re-POST (a POST after a failed DELETE would leave the stale
703
+ // series served); a POST failure after a successful DELETE gets ONE
704
+ // bounded in-process retry, and if that fails too the group is gone, so
705
+ // the warning names the manual restore (`/flow-cost <ref> --push`).
706
+ const deleted = await deps.deleteGroup(tracking.trackRef, tracking.mode)
707
+ if (deleted.ok === false) {
708
+ const reason = deleted.error ?? 'pushgateway DELETE failed'
709
+ report.skipped.push({ ref, reason })
710
+ deps.warn(
711
+ `reconcile ${ref}: group delete failed: ${reason} — no re-POST attempted`,
712
+ )
713
+ continue
714
+ }
715
+ let pushed = await deps.pushTombstone(
716
+ tracking.trackRef,
717
+ tracking.mode,
718
+ tombstone,
719
+ )
720
+ if (pushed.ok === false) {
721
+ pushed = await deps.pushTombstone(
722
+ tracking.trackRef,
723
+ tracking.mode,
724
+ tombstone,
725
+ )
726
+ }
727
+ if (pushed.ok === true) {
728
+ report.tombstoned.push(ref)
729
+ continue
730
+ }
731
+ const reason = pushed.error ?? 'pushgateway POST failed'
732
+ report.skipped.push({ ref, reason })
733
+ deps.warn(
734
+ `reconcile ${ref}: tombstone push failed after group delete (retried once): ${reason} — restore with /flow-cost ${ref} --push`,
735
+ )
736
+ }
737
+ return report
738
+ }