@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,162 @@
1
+ // AIDEV-NOTE: PMR-VE27 — the ONE shared mode-aware lifecycle policy: the
2
+ // close-out evidence dispatch (checkCloseout) and the /flow all-labels
3
+ // terminal re-entry reconciliation (reconcileTerminalEntry). RE-BASED by
4
+ // PMR-V31Z (rebase resolution, human-approved supersede policy): the
5
+ // ancestry evidence leg and the landing-route eligibility
6
+ // (eligibleLandingRoute — deleted in PMR-V31Z 4.1 with its flow_land
7
+ // consumer) and the phase-entry adapter (checkPhaseEntry — feedback entry is
8
+ // label-ordered now) are superseded, because they guarded the deleted
9
+ // local-merge landing. The surviving close-out evidence is the journaled
10
+ // gh-pr-create effect for EVERY mode: work always landed via PR, and
11
+ // personal now delivers via PR too (feedback journals the prUrl,
12
+ // flow_land declares the effect before authorizing — the PR is the
13
+ // close-out evidence). The full decision contract remains the checked-in
14
+ // docs/piv-flow-lifecycle-matrix.md. PURE by construction — no git/exec/fs
15
+ // imports: proofs arrive as dep-injected types (the PrEffectProbe journal
16
+ // tri-state). Fail-closed by construction: an absent probe dep (null), an
17
+ // unreadable journal never yields verified — every refusal carries a reason
18
+ // (no default-allow). The sinks (tools/phase-complete.ts,
19
+ // flow/loop-settle.ts, index.ts /flow) map these decisions to
20
+ // site-appropriate actions.
21
+
22
+ import type { WorkMode } from '../work-mode.ts'
23
+ import type { NextPhase } from './orchestrate.ts'
24
+
25
+ /**
26
+ * Journal evidence for a sanctioned PR landing: the tri-state result of
27
+ * looking up a `gh-pr-create` effect declaration for the flow ref in the run
28
+ * journal (PMR-VDVJ reuse — `flow_land` declares the effect before
29
+ * authorizing). `missing` = a readable journal with no declaration;
30
+ * `unreadable` = the journal read itself failed. A `null` probe (dep not
31
+ * wired) is refused fail-closed at every consumer.
32
+ */
33
+ export type PrEffectProbe =
34
+ | { kind: 'found' }
35
+ | { kind: 'missing' }
36
+ | { kind: 'unreadable'; reason: string }
37
+
38
+ /**
39
+ * The close-out evidence bundle. PMR-V31Z: every mode reads `prEffect` (the
40
+ * journaled PR-landing effect) — personal delivers via PR and is unmerged by
41
+ * design at close-out, so the ancestry leg is gone. A null member means the
42
+ * probe dep is not wired at the calling sink.
43
+ */
44
+ export interface CloseoutProofs {
45
+ /** journaled gh-pr-create effect for the ref (every mode, PMR-V31Z). */
46
+ prEffect: PrEffectProbe | null
47
+ }
48
+
49
+ export type CloseoutDecision =
50
+ | { kind: 'verified' }
51
+ | { kind: 'refuse'; reason: string }
52
+
53
+ // AIDEV-NOTE: PMR-VE27 — the close-out dispatch, re-based by PMR-V31Z: the
54
+ // mode/yolo inputs stay in the signature for call-site stability but no
55
+ // longer dispatch — every mode verifies the journaled gh-pr-create effect.
56
+ // null dep / unreadable / missing → refuse, found → verified. Fail-closed
57
+ // by construction: there is no evidence leg that can pass on a guess.
58
+ export function checkCloseout(input: {
59
+ mode: WorkMode
60
+ yolo: boolean
61
+ proofs: CloseoutProofs
62
+ }): CloseoutDecision {
63
+ const prEffect = input.proofs.prEffect
64
+ if (prEffect === null) {
65
+ return {
66
+ kind: 'refuse',
67
+ reason:
68
+ 'close-out PR-effect probe unavailable: the prEffect dep is not wired — refusing feedback close-out without a journaled gh-pr-create effect (PMR-VE27 fail-closed)',
69
+ }
70
+ }
71
+ if (prEffect.kind === 'unreadable') {
72
+ return {
73
+ kind: 'refuse',
74
+ reason: `close-out journal unreadable: ${prEffect.reason} — refusing feedback close-out without a readable run journal (PMR-VE27 fail-closed)`,
75
+ }
76
+ }
77
+ if (prEffect.kind === 'missing') {
78
+ return {
79
+ kind: 'refuse',
80
+ reason:
81
+ 'no journaled gh-pr-create effect for this ref — refusing feedback close-out without sanctioned PR-landing evidence (PMR-VE27 fail-closed; PMR-V31Z: personal journals it in feedback via flow_land)',
82
+ }
83
+ }
84
+ return { kind: 'verified' }
85
+ }
86
+
87
+ export type TerminalEntryDecision =
88
+ | { kind: 'terminal' }
89
+ | { kind: 'abort'; reason: string }
90
+
91
+ // AIDEV-NOTE: PMR-VE27 (decisions 5/7) — the done mapping of the /flow
92
+ // all-labels re-entry. This function owns ONLY the done mapping: a non-done
93
+ // label mapping aborts as a misuse rather than deciding (PMR-V31Z: the old
94
+ // landing-continuation re-mapping and its journal-receipt fallback leg are
95
+ // superseded — personal is unmerged by design at close-out, so there is no
96
+ // landing recovery to offer; verified → terminal, refused → abort).
97
+ export function reconcileTerminalEntry(input: {
98
+ next: NextPhase
99
+ mode: WorkMode
100
+ yolo: boolean
101
+ proofs: CloseoutProofs
102
+ }): TerminalEntryDecision {
103
+ if (input.next.kind !== 'done') {
104
+ return {
105
+ kind: 'abort',
106
+ reason:
107
+ 'reconcileTerminalEntry owns only the done mapping — a phase mapping must go through the label-ordered entry instead (PMR-VE27 misuse guard; PMR-V31Z superseded the PMR-5THZ reconcile)',
108
+ }
109
+ }
110
+ const closeout = checkCloseout({
111
+ mode: input.mode,
112
+ yolo: input.yolo,
113
+ proofs: input.proofs,
114
+ })
115
+ if (closeout.kind === 'verified') return { kind: 'terminal' }
116
+ return { kind: 'abort', reason: closeout.reason }
117
+ }
118
+
119
+ async function probePrEffect(
120
+ ref: string,
121
+ prEffectFn?: (ref: string) => Promise<PrEffectProbe>,
122
+ ): Promise<PrEffectProbe | null> {
123
+ if (prEffectFn === undefined) return null
124
+ try {
125
+ return await prEffectFn(ref)
126
+ } catch (error) {
127
+ return { kind: 'unreadable', reason: errorText(error) }
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Run the close-out probe fail-closed; the policy verifies the journaled
133
+ * gh-pr-create effect (PMR-V31Z: the only evidence leg). A THROWN probe maps
134
+ * to the failure leg, never a pass; an ABSENT dep maps to null —
135
+ * checkCloseout refuses fail-closed on a null proof.
136
+ */
137
+ export async function resolveCloseoutProofs(
138
+ ref: string,
139
+ probes: {
140
+ prEffectFn?: (ref: string) => Promise<PrEffectProbe>
141
+ },
142
+ ): Promise<CloseoutProofs> {
143
+ return {
144
+ prEffect: await probePrEffect(ref, probes.prEffectFn),
145
+ }
146
+ }
147
+
148
+ function errorText(error: unknown): string {
149
+ if (error instanceof Error) return error.message
150
+ return String(error)
151
+ }
152
+
153
+ // AIDEV-NOTE: PMR-VE27 (decision 9) — loop-sink halt text, shared by
154
+ // flow/loop-settle.ts so the settle additions stay minimal. The FlowReason
155
+ // is always closeout_check_failed at the sink; this builds the actionable
156
+ // free-text halt record for a non-verified checkCloseout decision.
157
+ export function closeoutHaltReason(
158
+ decision: Exclude<CloseoutDecision, { kind: 'verified' }>,
159
+ ref: string,
160
+ ): string {
161
+ return `close-out check failed: ${decision.reason} — rerun /flow ${ref} once the close-out evidence exists (the gh-pr-create effect journaled by flow_land ${ref} during the feedback PR delivery)`
162
+ }
@@ -0,0 +1,52 @@
1
+ // AIDEV-NOTE: PMR-422Q — the live-wait lease tunables. The lease deadline in
2
+ // flow/v2-emission.ts is that guard's DEAD-MAN'S SWITCH: an armed live-wait hold may
3
+ // only suppress loop emissions while `now < leaseExpiresAt`, so a wait whose
4
+ // owning seam died (process exit, lost tool_result, a settle that closed a
5
+ // different wait) releases itself instead of latching the journal to
6
+ // `waiting_human` for the rest of the run.
7
+ //
8
+ // WINDOW/BEAT INVARIANT: LIVE_WAIT_LEASE_SECONDS must stay >= 2-3x the
9
+ // heartbeat interval (LIVE_WAIT_HEARTBEAT_MS), i.e. the window has to tolerate
10
+ // TWO OR THREE missed beats. A heartbeat that is merely late (an event loop
11
+ // under load, an unref'd timer firing after a long turn) must never be able to
12
+ // expire the lease: the board would flip to a non-waiting state while a human
13
+ // is still being asked, which is the exact wrongness the hold exists to
14
+ // prevent. Lowering the window or raising the interval breaks this;
15
+ // test/live-wait.test.ts pins the ratio.
16
+ //
17
+ // HEARTBEATS ARE IN-PROCESS PINGS — the lease is NEVER JOURNALED. A beat is a
18
+ // direct call (index.ts -> loop.renewLiveWaitLease), not a journal record: the
19
+ // hold flag is reset by start() and the deadline lives only in memory, so
20
+ // journal visibility would buy nothing while costing a write per beat on the
21
+ // single-writer journal and creating a second, competing source of truth for
22
+ // the wait state. Nothing outside this process may read or extend a lease.
23
+
24
+ /** Interval between lease-renewing heartbeat beats (flow/ask-emitter.ts). */
25
+ export const LIVE_WAIT_HEARTBEAT_MS = 60_000
26
+
27
+ /** Lease window in seconds — how long a beat keeps the hold alive. */
28
+ export const LIVE_WAIT_LEASE_SECONDS = 180
29
+
30
+ /**
31
+ * Shift a fixed-width UTC ISO stamp (`2026-11-28T00:00:00.000Z`, 24 chars, as
32
+ * every journal `at` is written) forward by `seconds`, returning the same
33
+ * fixed-width shape so lexicographic comparison against another `at` string
34
+ * stays a valid chronology test.
35
+ *
36
+ * An unparseable `at` yields an Invalid Date and `toISOString()` throws
37
+ * RangeError. That throw only surfaces on DIRECT calls (tests): both
38
+ * production call sites are wrapped in never-throw catches per ISC-A-5, so
39
+ * in production the RangeError is silently swallowed —
40
+ * `noteExternalV2State` runs inside the fan-out observer's try/catch
41
+ * (telemetry/dispatch.ts), and `renewLiveWaitLease` runs inside the ask
42
+ * emitter's heartbeat beat try/catch (flow/ask-emitter.ts). Worse, on the
43
+ * noteExternalV2State path the throw lands MID-MUTATION: lastEmittedV2,
44
+ * lastV2At and externalHumanWaitOpen are already updated while
45
+ * leaseExpiresAt is left stale/null — a partially-applied observation.
46
+ * Reachable only via journal corruption (every real `at` is a fixed-width
47
+ * UTC ISO stamp), so the impact is negligible — but do not rely on the
48
+ * throw being loud in production; it is loud only when called directly.
49
+ */
50
+ export function addSecondsIso(at: string, seconds: number): string {
51
+ return new Date(Date.parse(at) + seconds * 1000).toISOString()
52
+ }
@@ -0,0 +1,408 @@
1
+ // AIDEV-NOTE (PMR-8MQH 2.1 + 2.2, plan PMR-8MQH decision D3): node-only
2
+ // settings reader, io wiring and the pass engine for the running-flow
3
+ // liveness push. This is the daemon's half of the `liveness` config block plus
4
+ // the single place where the daemon's world (agent dir + process env) becomes
5
+ // the engine's injected `LivenessDeps`; only the timer wiring (3.2) is still
6
+ // missing from this module.
7
+ //
8
+ // Home justification: reconcile's equivalent split lived in two files
9
+ // (`flow/reconcile.ts` engine + `flow/reconcile-deps.ts` wiring) because a
10
+ // manual in-session command (`/flow-reconcile-push`) reused the wiring with
11
+ // its own warn sink. Liveness has NO command (plan: "no /flow-liveness-push"),
12
+ // so its engine, tolerant reader and wiring collapse into this one node-only
13
+ // module instead of adding a second file pair. The 2.2 pass goes here too.
14
+ //
15
+ // Dependency contract (mirrors flow/reconcile-deps.ts:1-25 and the node-only
16
+ // module contract in the flow/cost-rows.ts header): node built-ins +
17
+ // ../run-state.ts + ./push.ts + ./reconcile-deps.ts + ./cost-rows.ts and its
18
+ // ./cost-rows-journal.ts / ./cost-rows-push.ts / ./cost-rows-rows.ts siblings
19
+ // + the `@gtheys/pi-interactive-subagents` `assignments`/`usage` SUBPATHS only.
20
+ // Never the package root, never `config.ts` (its `readConfigFile` THROWS on a
21
+ // malformed file and its loader pulls `@earendil-works/pi-coding-agent` — a
22
+ // daemon must degrade to defaults + warning instead), never a pi extension
23
+ // runtime. Locked textually by test/run-liveness.test.ts. Note the accepted
24
+ // pre-existing exception: `../run-state.ts` and the `assignments` subpath each
25
+ // transitively module-load pi-coding-agent (`run-state.ts:10`,
26
+ // `subagents/dataroot.ts`), and both only ever call `getAgentDir()` when their
27
+ // own root/agentDir argument is omitted — every call site here passes an
28
+ // explicit one, so the daemon never resolves a path it was not handed.
29
+ //
30
+ // Two further contracts, both deliberate:
31
+ // - env is always a parameter (`options.env`, defaulted to `process.env`
32
+ // only at the boundary) so tests inject the gate and nothing reads
33
+ // `process.env` deep in the module;
34
+ // - the agent dir comes from `PI_FLOW_AGENT_DIR` (server/lifecycle.ts),
35
+ // NEVER from `getAgentDir()`, and the runs dir is derived from it exactly
36
+ // as `flow/reconcile-deps.ts` does.
37
+
38
+ import { promises as fsp, readFileSync } from 'node:fs'
39
+ import { join } from 'node:path'
40
+ import {
41
+ type AssignmentRecord,
42
+ listAssignments,
43
+ } from '@gtheys/pi-interactive-subagents/assignments'
44
+ import {
45
+ type FlowRunEvent,
46
+ projectRunState,
47
+ readRunEvents,
48
+ runTracking,
49
+ } from '../run-state.ts'
50
+ import {
51
+ buildPushBody,
52
+ computeCostRollup,
53
+ type PhaseDuration,
54
+ phaseDurations,
55
+ type WorkerRow,
56
+ } from './cost-rows.ts'
57
+ import { type PushFetch, type PushResult, pushToGateway } from './push.ts'
58
+ import { listJournalRefs, pushgatewayEnv } from './reconcile-deps.ts'
59
+
60
+ /** Daemon-side `liveness` settings. `warning` is ours, not the engine's: a
61
+ * broken file keeps the timer running on defaults and says why, exactly like
62
+ * `ReconcileSettings` in flow/reconcile-deps.ts. */
63
+ export interface LivenessSettings {
64
+ enabled: boolean
65
+ intervalMinutes: number
66
+ warning?: string
67
+ }
68
+
69
+ // AIDEV-NOTE: PMR-8MQH (2.1) — these defaults are the daemon half of a
70
+ // DELIBERATE two-reader split over the same `<agentDir>/pi-flow/config.json`.
71
+ // `config.ts`'s typed `liveness` reader (subtask 4.1) is the session half and
72
+ // must return the identical `{ enabled: true, intervalMinutes: 5 }` for an
73
+ // absent block. This function stays here, not delegating to config.ts, because
74
+ // the daemon must remain node-only AND must not throw on a broken file — it
75
+ // warns and keeps its retires/cost pushes running instead.
76
+ export const DEFAULT_LIVENESS_SETTINGS: LivenessSettings = {
77
+ enabled: true,
78
+ intervalMinutes: 5,
79
+ }
80
+
81
+ /**
82
+ * Parse the `liveness` block out of RAW config file text
83
+ * (`<agentDir>/pi-flow/config.json`). Mirrors `parseReconcileSettings`
84
+ * (flow/reconcile.ts:217) key for key: null/blank input and an absent section
85
+ * are silent defaults; malformed JSON, a non-object file, a non-object
86
+ * section, a non-boolean `enabled`, or a non-finite/`< 1` `intervalMinutes`
87
+ * all fall back to the defaults AND return a `liveness: …` warning the daemon
88
+ * logs. A broken config must not silently stop running pushes, and must not
89
+ * crash the daemon.
90
+ */
91
+ export function parseLivenessSettings(raw: string | null): LivenessSettings {
92
+ if (raw === null || raw.trim().length === 0) {
93
+ return { ...DEFAULT_LIVENESS_SETTINGS }
94
+ }
95
+ let parsed: unknown
96
+ try {
97
+ parsed = JSON.parse(raw)
98
+ } catch {
99
+ return warned('liveness: config file is not valid JSON')
100
+ }
101
+ if (!isRecord(parsed)) return warned('liveness: config file is not an object')
102
+ if (parsed.liveness === undefined) return { ...DEFAULT_LIVENESS_SETTINGS }
103
+ if (!isRecord(parsed.liveness)) {
104
+ return warned('liveness: "liveness" is not an object')
105
+ }
106
+ const block = parsed.liveness
107
+ const settings: LivenessSettings = { ...DEFAULT_LIVENESS_SETTINGS }
108
+ if (block.enabled !== undefined) {
109
+ if (typeof block.enabled !== 'boolean') {
110
+ return warned('liveness: "enabled" is not a boolean')
111
+ }
112
+ settings.enabled = block.enabled
113
+ }
114
+ if (block.intervalMinutes !== undefined) {
115
+ const minutes = block.intervalMinutes
116
+ if (
117
+ typeof minutes !== 'number' ||
118
+ !Number.isFinite(minutes) ||
119
+ minutes < 1
120
+ ) {
121
+ return warned('liveness: "intervalMinutes" is not a number >= 1')
122
+ }
123
+ settings.intervalMinutes = minutes
124
+ }
125
+ return settings
126
+ }
127
+
128
+ function warned(warning: string): LivenessSettings {
129
+ return { ...DEFAULT_LIVENESS_SETTINGS, warning }
130
+ }
131
+
132
+ function isRecord(value: unknown): value is Record<string, unknown> {
133
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
134
+ }
135
+
136
+ /** Injected IO for one liveness pass. Everything impure lives here so the
137
+ * 2.2 engine stays node-only and testable with fakes. The three reads
138
+ * `readRunEvents` / `listAssignmentRecords` / `readSessionFile` are exactly
139
+ * `CostRollupDeps` (flow/cost-rows.ts), so a `LivenessDeps` value can be
140
+ * handed to `computeCostRollup` unchanged — that is the point, not a
141
+ * coincidence: the liveness body must be the same rollup the terminal autopush
142
+ * renders. */
143
+ export interface LivenessDeps {
144
+ /** Refs (journal basenames) to scan — the daemon readdir's `runsDir`. */
145
+ listJournalRefs: () => Promise<string[]>
146
+ /** Journal events for a ref, or null when the journal is unreadable. */
147
+ readRunEvents: (ref: string) => Promise<FlowRunEvent[] | null>
148
+ /** Durable assignment records (subagents data dir of the agent dir). */
149
+ listAssignmentRecords: () => readonly AssignmentRecord[]
150
+ /** Raw session jsonl body, or null when unreadable (coverage gap). */
151
+ readSessionFile: (file: string) => string | null
152
+ /** Replace a group with the full running body (POST to the group URL). */
153
+ pushBody: (
154
+ trackRef: string,
155
+ mode: 'work' | 'personal',
156
+ body: string,
157
+ ) => Promise<PushResult>
158
+ /** The daemon's log channel (or a test collector). */
159
+ warn: (message: string) => void
160
+ }
161
+
162
+ export interface LivenessDepsOptions {
163
+ /** agent dir from PI_FLOW_AGENT_DIR (the daemon); never getAgentDir() */
164
+ agentDir: string
165
+ /** the daemon's log channel — engine warnings land here */
166
+ warn: (message: string) => void
167
+ env?: NodeJS.ProcessEnv
168
+ /** gateway seam (tests capture POSTs); defaults to global fetch */
169
+ fetchImpl?: PushFetch
170
+ /** runs-dir listing seam for journal enumeration */
171
+ readdir?: (dir: string) => Promise<string[]>
172
+ }
173
+
174
+ /**
175
+ * Wire the engine's io. Returns null when the pushgateway env gate is closed
176
+ * — the caller then skips the pass silently (ISC-4: no journal read, no fetch,
177
+ * no assignment scan happens either, because every read is a lazy closure and
178
+ * this factory performs no io itself).
179
+ */
180
+ export function createLivenessDeps(
181
+ options: LivenessDepsOptions,
182
+ ): LivenessDeps | null {
183
+ const gateway = pushgatewayEnv(options.env ?? process.env)
184
+ if (gateway === null) return null
185
+ const fetchImpl: PushFetch = options.fetchImpl ?? defaultPushFetch
186
+ const readdir = options.readdir ?? defaultReaddir
187
+ const { agentDir, warn } = options
188
+ const assignmentsRoot = join(agentDir, 'pi-subagents')
189
+ return {
190
+ listJournalRefs: () => listJournalRefs(agentDir, readdir),
191
+ readRunEvents: (ref: string) => readRunEvents(agentDir, ref),
192
+ listAssignmentRecords: () => {
193
+ const records: AssignmentRecord[] = []
194
+ for (const view of listAssignments(assignmentsRoot)) {
195
+ if (view.state === 'unknown') continue
196
+ records.push(view.record)
197
+ }
198
+ return records
199
+ },
200
+ readSessionFile: (file: string) => {
201
+ try {
202
+ return readFileSync(file, 'utf8')
203
+ } catch {
204
+ return null
205
+ }
206
+ },
207
+ pushBody: (trackRef: string, mode: 'work' | 'personal', body: string) =>
208
+ pushBodyOrError(gateway, trackRef, mode, body, fetchImpl),
209
+ warn,
210
+ }
211
+ }
212
+
213
+ async function defaultReaddir(dir: string): Promise<string[]> {
214
+ return fsp.readdir(dir)
215
+ }
216
+
217
+ async function defaultPushFetch(
218
+ url: string,
219
+ init: { method: string; headers: Record<string, string>; body: string },
220
+ ): Promise<{
221
+ status: number
222
+ statusText: string
223
+ text: () => Promise<string>
224
+ }> {
225
+ const response = await fetch(url, init)
226
+ // PMR-WBC2: pass text() through so pushToGateway can put a bounded snippet
227
+ // of the gateway's reason body into PushResult.error on non-2xx.
228
+ return {
229
+ status: response.status,
230
+ statusText: response.statusText,
231
+ text: () => response.text(),
232
+ }
233
+ }
234
+
235
+ // AIDEV-NOTE: the `LivenessDeps` contract is `{ok:false,error}` or a
236
+ // PushResult, never a throw — but flow/push.ts only guarantees that for its own
237
+ // io. This wrapper keeps the promise for the whole call (a frozen DNS cache
238
+ // throwing synchronously inside `fetch` must cost one failed ref, not the
239
+ // daemon's pass): unexpected throws become ordinary failure results. Same
240
+ // pattern as reconcile-deps.ts `pushTombstoneOrError`.
241
+ async function pushBodyOrError(
242
+ gateway: { url: string; token: string | undefined },
243
+ trackRef: string,
244
+ mode: 'work' | 'personal',
245
+ body: string,
246
+ fetchImpl: PushFetch,
247
+ ): Promise<PushResult> {
248
+ try {
249
+ return await pushToGateway(
250
+ gateway.url,
251
+ trackRef,
252
+ body,
253
+ fetchImpl,
254
+ gateway.token,
255
+ mode,
256
+ )
257
+ } catch (err) {
258
+ return { ok: false, error: errorText(err) }
259
+ }
260
+ }
261
+
262
+ /** `unknown` from a catch becomes a loggable message, Error first (the one
263
+ * shape every warning in this module uses). */
264
+ function errorText(err: unknown): string {
265
+ if (err instanceof Error) return err.message
266
+ return `${err}`
267
+ }
268
+
269
+ // the pass engine (PMR-8MQH 2.2): the report, its log line, and one pass.
270
+
271
+ type RefOutcome = 'pushed' | 'skipped' | 'failed'
272
+
273
+ /** What one pass did, as counts. `scanned` is every enumerated journal ref,
274
+ * so `scanned === pushed + skipped + failed` always holds. */
275
+ export interface LivenessReport {
276
+ scanned: number
277
+ pushed: number
278
+ skipped: number
279
+ failed: number
280
+ }
281
+
282
+ /** The one log line per pass. The factory (3.1) logs `formatSummary` output
283
+ * VERBATIM (server/daemon.ts:592), so this line is the whole log entry — no
284
+ * label prefix is applied. The exact shape is a contract — homelab log greps
285
+ * key on these names. */
286
+ export function livenessSummaryLine(report: LivenessReport): string {
287
+ return `liveness pass: scanned=${report.scanned} pushed=${report.pushed} skipped=${report.skipped} failed=${report.failed}`
288
+ }
289
+
290
+ /**
291
+ * AIDEV-NOTE (PMR-8MQH 2.2, plan decisions D2/D4): one liveness pass. For
292
+ * every journal ref whose projection says the loop is `running`, re-render
293
+ * the FULL group body and POST it, so a running run never fades from the
294
+ * dashboard between phase pushes. Reading order per ref:
295
+ * read journal -> gate on `running` -> `computeCostRollup` -> render ->
296
+ * RE-READ + re-gate (ISC-8: a run that went terminal during the rollup must
297
+ * not get a `running` body pushed after its terminal push) -> `pushBody`.
298
+ * Two invariants the call sites cannot give up:
299
+ * - the body is `buildPushBody(trackRef, rows, durations, events)` — the
300
+ * SAME render path as the terminal autopush, so the two pushes of one run
301
+ * differ only in the status line (ISC-2, and why the rollup's own `events`
302
+ * are preferred over the gate read when present);
303
+ * - this function NEVER appends a journal event (ISC-A-1) and NEVER reads a
304
+ * group back with `fetchGroupBody` (ISC-A-5): a partial body POST would
305
+ * drop the series the terminal push owns.
306
+ * Never rejects: the enumeration and every ref are wrapped, so a broken runs
307
+ * dir costs one warning, and one broken journal or gateway costs a `failed`
308
+ * count plus one warning — never the pass (ISC-5).
309
+ */
310
+ export async function runLivenessPassOnce(
311
+ deps: LivenessDeps,
312
+ ): Promise<LivenessReport> {
313
+ const report: LivenessReport = {
314
+ scanned: 0,
315
+ pushed: 0,
316
+ skipped: 0,
317
+ failed: 0,
318
+ }
319
+ let refs: string[]
320
+ try {
321
+ refs = await deps.listJournalRefs()
322
+ } catch (err) {
323
+ // The wired deps swallow a readdir failure to an empty list, so this only
324
+ // fires for hand-wired deps; an enumeration error is not a per-ref count.
325
+ deps.warn(`liveness: journal enumeration failed: ${errorText(err)}`)
326
+ return report
327
+ }
328
+ report.scanned = refs.length
329
+ for (const ref of refs) {
330
+ let outcome: RefOutcome
331
+ try {
332
+ outcome = await pushIfRunning(deps, ref)
333
+ } catch (err) {
334
+ outcome = 'failed'
335
+ deps.warn(`liveness ${ref}: pass aborted: ${errorText(err)}`)
336
+ }
337
+ if (outcome === 'pushed') report.pushed += 1
338
+ if (outcome === 'skipped') report.skipped += 1
339
+ if (outcome === 'failed') report.failed += 1
340
+ }
341
+ return report
342
+ }
343
+
344
+ /** The per-ref half of the pass. Skips are silent (a non-running ref is the
345
+ * normal case); only a failed POST warns, because the caller's own throw
346
+ * handling already warns on exceptions. */
347
+ async function pushIfRunning(
348
+ deps: LivenessDeps,
349
+ ref: string,
350
+ ): Promise<RefOutcome> {
351
+ const events = await deps.readRunEvents(ref)
352
+ if (events === null) return 'skipped'
353
+ if (!projectsRunning(events)) return 'skipped'
354
+ const rollup = await computeCostRollup(ref, deps)
355
+ if (rollup.kind === 'no-journal') return 'skipped'
356
+ let trackRef = ref
357
+ let mode: 'work' | 'personal' = 'personal'
358
+ let rows: readonly WorkerRow[] = []
359
+ let durations: readonly PhaseDuration[] = []
360
+ let bodyEvents: readonly FlowRunEvent[] = events
361
+ if (rollup.kind === 'ok') {
362
+ trackRef = rollup.trackRef
363
+ mode = rollup.mode
364
+ rows = rollup.rows
365
+ durations = rollup.durations
366
+ if (rollup.events !== undefined) bodyEvents = rollup.events
367
+ } else {
368
+ // `empty` (plan ISC-10): a fresh run with no spawn notes and no
369
+ // main-session record yet, so there are no cost rows to render. The
370
+ // tracking ref and the phase durations still come straight from the
371
+ // journal — same `runTracking` derivation the terminal autopush uses —
372
+ // which makes the push health-only rather than absent.
373
+ // AIDEV-NOTE (PMR-8MQH review P2): guarded to trackRef === ref. The
374
+ // Pushgateway group is keyed by TRACKREF, and in work mode several runs
375
+ // (across resume/restarts of one Jira issue) share one trackRef — a
376
+ // zero-cost health-only body would REPLACE that group and erase the
377
+ // previous run's cost/token series (measured: 85 series lost, and
378
+ // unrecoverable if the new run dies before its terminal push). An
379
+ // 'ok' rollup may still replace the shared group: it carries the full
380
+ // re-render of everything the current journal knows, matching the
381
+ // terminal autopush exactly. ISC-10 therefore covers personal-mode fresh
382
+ // runs; a work-mode fresh run appears at its first cost-bearing pass.
383
+ const tracking = runTracking(events, ref)
384
+ if (tracking.trackRef !== ref) return 'skipped'
385
+ trackRef = tracking.trackRef
386
+ mode = tracking.mode
387
+ durations = phaseDurations(events)
388
+ }
389
+ const latest = await deps.readRunEvents(ref)
390
+ if (latest === null) return 'skipped'
391
+ if (!projectsRunning(latest)) return 'skipped'
392
+ const body = buildPushBody(trackRef, rows, durations, bodyEvents)
393
+ const result = await deps.pushBody(trackRef, mode, body)
394
+ if (result.ok) return 'pushed'
395
+ deps.warn(
396
+ `liveness ${ref}: push failed: ${result.error ?? 'pushgateway POST failed'}`,
397
+ )
398
+ return 'failed'
399
+ }
400
+
401
+ /** The liveness gate: a journal that projects no state, or a state with no
402
+ * loop record, or a loop that is not `running`, gets no push (ISC-3). Pure. */
403
+ function projectsRunning(events: readonly FlowRunEvent[]): boolean {
404
+ const state = projectRunState(events)
405
+ if (state === null) return false
406
+ if (state.loop === undefined) return false
407
+ return state.loop.status === 'running'
408
+ }