@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,1094 @@
1
+ // AIDEV-NOTE: PMR-XTQQ — pi-flow durable run server daemon. Own process, own
2
+ // event loop (this is what makes fs.watch sanctioned here — see
3
+ // plugins/herdr/flow-viewer.mjs and the subagent-done.ts scar tissue; NEVER
4
+ // put a watcher inside pi's extension process). The journal is authoritative
5
+ // and written by sessions via O_APPEND; this daemon is the ONLY projection
6
+ // writer, reprojecting per ref from journal events.
7
+ //
8
+ // DEPENDENCY CONTRACT (corrected in PMR-MSDJ 2.2 — the PMR-XTQQ wording here
9
+ // was stale): run-state.ts runtime-imports `@earendil-works/pi-coding-agent`
10
+ // (run-state.ts:10, getAgentDir) and has since before this feature, so the
11
+ // daemon transitively loads pi-coding-agent TODAY — "dependency-free beyond
12
+ // node built-ins" was never literally true. The ENFORCEABLE contract is: every
13
+ // module the daemon imports adds NO NEW runtime dependency beyond
14
+ // run-state.ts + flow/reconcile.ts + flow/reconcile-deps.ts + flow/push.ts +
15
+ // flow/liveness.ts + flow/cost-rows.ts and its cost-rows-* submodules +
16
+ // flow/run-health.ts +
17
+ // flow/state-metrics.ts + flow/vocabulary.ts + aven/status.ts (all node
18
+ // built-ins apart from that pre-existing one). flow/liveness.ts and
19
+ // flow/cost-rows.ts with its cost-rows-* submodules (PMR-8MQH 3.2, PMR-45VS)
20
+ // are sanctioned because they import ONLY the
21
+ // node-only `@gtheys/pi-interactive-subagents` SUBPATH exports (`/usage`,
22
+ // `/assignments`) — never the package root — and, like run-state.ts,
23
+ // `assignments` transitively module-loads pi-coding-agent through
24
+ // `subagents/dataroot.ts`. That is the SAME documented pre-existing acceptance
25
+ // class as run-state.ts (a module-load, not a new dependency edge, and both
26
+ // only ever call `getAgentDir()` at their own call sites the daemon never
27
+ // reaches), so they add no NEW runtime dependency either.
28
+ // AIDEV-NOTE (PMR-ZV9Y 3.2): flow/run-health.ts, flow/state-metrics.ts and
29
+ // flow/vocabulary.ts join the sanctioned list because the v2 gauges MUST render
30
+ // inside the daemon's liveness body — liveness re-pushes run-health bodies
31
+ // through buildPushBody, so a session-side derivation would leave running flows
32
+ // without v2 series. They add no edge beyond the ones already here:
33
+ // state-metrics.ts imports only run-state.ts + ./vocabulary.ts + ./cost-rows.ts
34
+ // (`labelString`), vocabulary.ts is zero-import, and run-health.ts gains only
35
+ // the state-metrics edge. Locked textually, per root, by
36
+ // test/cost-rows-node-only.test.ts.
37
+ // Never
38
+ // add `config.ts` (its readConfigFile THROWS on a malformed file — the daemon
39
+ // is best-effort io), `flow/cost.ts` (runtime dep on
40
+ // @gtheys/pi-interactive-subagents) or `aven/client.ts` (imports config.ts).
41
+ // The agent dir arrives via PI_FLOW_AGENT_DIR from the spawner
42
+ // (server/lifecycle.ts), never from getAgentDir().
43
+ // The spawn-side git provenance arrives the same way via PI_FLOW_DAEMON_GIT_SHA
44
+ // and PI_FLOW_DAEMON_GIT_ROOT (PMR-7B8M): the SHA is validated as 40-hex
45
+ // lowercase and the root as a non-empty absolute path, anything else is
46
+ // dropped, and both are ADVISORY-ONLY — they are recorded in the pidfile so
47
+ // sessions can judge staleness (and stay silent for a daemon spawned from
48
+ // another repo, rev 2); they never affect liveness, respawn, or any daemon
49
+ // decision.
50
+ //
51
+ // KEEPALIVE RULE (PMR-XTQQ review fix): the 1s poll interval is the daemon's
52
+ // LIVENESS BACKSTOP and must NEVER be unref'd — fs.watch(runsDir) can fail at
53
+ // startup (ENOENT: runs/ is only created by the first journal write, and
54
+ // ensureDaemon runs before that), and when it does the poll alone must keep
55
+ // the event loop alive. Watcher failures degrade silently to the poll
56
+ // (close the watcher, never retry fs.watch in a hot loop).
57
+ //
58
+ // BUMP TOGETHER: SERVER_PROTOCOL_VERSION must be kept in sync with
59
+ // server/lifecycle.ts (written in subtask 1.2) — a long-lived daemon can
60
+ // outlive a package upgrade, so the pidfile pins the version and a mismatch
61
+ // means kill + respawn.
62
+ //
63
+ // PENDING MAINTENANCE (subtask 3.2): after each per-ref reproject the same
64
+ // journal read also drives pending-record maintenance — parked loop-state
65
+ // (awaitingOutcome=true, status='running') → writePending (idempotent,
66
+ // skipped when the existing record already matches), otherwise → clearPending
67
+ // (terminal/paused/halted/done or no run); <ref>.consumed.json files are
68
+ // swept once per scan. Pending records are NOT journal events (they live in
69
+ // pending/), so writing them does NOT violate the daemon-never-appends-
70
+ // journal-events invariant above.
71
+
72
+ import { promises as fsp, watch } from 'node:fs'
73
+ import path from 'node:path'
74
+ import { fileURLToPath } from 'node:url'
75
+ import {
76
+ createLivenessDeps,
77
+ type LivenessReport,
78
+ type LivenessSettings,
79
+ livenessSummaryLine,
80
+ parseLivenessSettings,
81
+ runLivenessPassOnce,
82
+ } from '../flow/liveness.ts'
83
+ import type { ReconcileReport } from '../flow/reconcile.ts'
84
+ import {
85
+ globalConfigPath,
86
+ journalRefsFromEntries,
87
+ pushgatewayEnv,
88
+ type ReconcileSettings,
89
+ readReconcileSettings,
90
+ reconcileSummaryLine,
91
+ runReconcilePassOnce,
92
+ } from '../flow/reconcile-deps.ts'
93
+ import {
94
+ type FlowRunEvent,
95
+ type FlowRunState,
96
+ isFlowRunState,
97
+ projectRunState,
98
+ readRunEvents,
99
+ runStatePath,
100
+ runsDir,
101
+ writeFileAtomic,
102
+ } from '../run-state.ts'
103
+ import {
104
+ clearPending,
105
+ defaultPendingIo,
106
+ isParkedLoop,
107
+ PENDING_SCHEMA,
108
+ type PendingIo,
109
+ type PendingPhase,
110
+ type PendingRecord,
111
+ parsePendingRecord,
112
+ sweepConsumed,
113
+ writePending,
114
+ } from './pending.ts'
115
+
116
+ export const SERVER_PROTOCOL_VERSION = '1'
117
+
118
+ const PID_FILE_NAME = 'server.pid'
119
+ const LOG_FILE_NAME = 'server.log'
120
+ const POLL_INTERVAL_MS = 1_000
121
+ const DEBOUNCE_MS = 150
122
+
123
+ // --- pure helpers (exported for unit tests, recordRunEvent io-seam style) ---
124
+
125
+ /** Reproject decision: has the projection's serialized JSON changed? Pure. */
126
+ export function projectionChanged(
127
+ currentRaw: string | null,
128
+ next: NonNullable<ReturnType<typeof projectRunState>>,
129
+ ): boolean {
130
+ if (currentRaw === null) return true
131
+ const serialized = `${JSON.stringify(next, null, 2)}\n`
132
+ return currentRaw !== serialized
133
+ }
134
+
135
+ export type ReprojectResult = 'written' | 'unchanged' | 'no-journal'
136
+
137
+ const defaultReprojectIo = {
138
+ readFile: (p: string) => fsp.readFile(p, 'utf8'),
139
+ // PMR-VHEY 2.1 (class C1): atomic temp+rename — same seam as
140
+ // recordRunEvent's default io; see writeFileAtomic in run-state.ts.
141
+ writeFile: async (p: string, data: string) => {
142
+ await writeFileAtomic(p, data)
143
+ },
144
+ }
145
+
146
+ interface ReprojectIo {
147
+ readFile: (p: string) => Promise<string>
148
+ writeFile: (p: string, data: string) => Promise<void>
149
+ }
150
+
151
+ export interface ReprojectOutcome {
152
+ result: ReprojectResult
153
+ /** Reprojected state; null when there is no readable journal/projection. */
154
+ state: FlowRunState | null
155
+ }
156
+
157
+ /**
158
+ * AIDEV-NOTE: PMR-7B8M — the spawner's checkout HEAD arrives via env (like
159
+ * PI_FLOW_AGENT_DIR); validated 40-hex lowercase, anything else is dropped
160
+ * because gitSha is an advisory pidfile field the daemon must never trust.
161
+ * Pure (reads only the passed env) so it is unit-testable without a spawn.
162
+ */
163
+ export function gitShaFromEnv(env: NodeJS.ProcessEnv): string | undefined {
164
+ const raw = env.PI_FLOW_DAEMON_GIT_SHA
165
+ if (typeof raw !== 'string') return undefined
166
+ if (!/^[0-9a-f]{40}$/.test(raw)) return undefined
167
+ return raw
168
+ }
169
+
170
+ /**
171
+ * AIDEV-NOTE: PMR-7B8M rev 2 — repo identity for the staleness verdict. The
172
+ * daemon is ONE GLOBAL process shared by every repo, so a bare SHA cannot say
173
+ * whether it describes THIS repo (validate review P1: cross-repo false
174
+ * positives at every session start). The spawner therefore records the main
175
+ * worktree path next to the SHA and sessions go silent when it differs. Same
176
+ * advisory posture as gitShaFromEnv: a non-empty absolute path or nothing — a
177
+ * relative path, an empty string, or a non-string is dropped rather than
178
+ * failing the write. Pure, so it is unit-testable without a spawn.
179
+ */
180
+ export function gitRootFromEnv(env: NodeJS.ProcessEnv): string | undefined {
181
+ const raw = env.PI_FLOW_DAEMON_GIT_ROOT
182
+ if (typeof raw !== 'string') return undefined
183
+ if (raw === '') return undefined
184
+ if (!path.isAbsolute(raw)) return undefined
185
+ return raw
186
+ }
187
+
188
+ /**
189
+ * PMR-7B8M: serialize the pidfile line. gitSha is included only when present
190
+ * so pidfiles written outside a repo keep the pre-feature shape exactly
191
+ * (lifecycle.ts treats an absent gitSha as "predates staleness tracking").
192
+ * PMR-7B8M rev 2 adds the same optional treatment for gitRoot (the spawning
193
+ * repo's main-worktree path — absent means "repo identity unverifiable").
194
+ */
195
+ export function pidfileLine(fields: {
196
+ pid: number
197
+ version: string
198
+ startedAt: string
199
+ agentDir: string
200
+ gitSha?: string
201
+ gitRoot?: string
202
+ }): string {
203
+ const payload: Record<string, unknown> = {
204
+ pid: fields.pid,
205
+ version: fields.version,
206
+ startedAt: fields.startedAt,
207
+ agentDir: fields.agentDir,
208
+ }
209
+ if (fields.gitSha !== undefined) payload.gitSha = fields.gitSha
210
+ if (fields.gitRoot !== undefined) payload.gitRoot = fields.gitRoot
211
+ return `${JSON.stringify(payload)}\n`
212
+ }
213
+
214
+ /** AIDEV-NOTE: pending/ lives next to runs/ under <agentDir>/pi-flow/. */
215
+ export function pendingDirPath(agentDir: string): string {
216
+ return path.join(agentDir, 'pi-flow', 'pending')
217
+ }
218
+
219
+ /**
220
+ * Pending decision from one journal read: parked loop → 'write', anything
221
+ * else (terminal/paused/halted/done or no run at all) → 'clear'. Pure.
222
+ */
223
+ export function decidePending(state: FlowRunState | null): 'write' | 'clear' {
224
+ if (state === null) return 'clear'
225
+ if (isParkedLoop(state.loop)) return 'write'
226
+ return 'clear'
227
+ }
228
+
229
+ function recordsEqual(a: PendingRecord, b: PendingRecord): boolean {
230
+ return (
231
+ a.schema === b.schema &&
232
+ a.ref === b.ref &&
233
+ a.phase === b.phase &&
234
+ a.createdAt === b.createdAt &&
235
+ a.sourceAt === b.sourceAt
236
+ )
237
+ }
238
+
239
+ /**
240
+ * Pending maintenance for one ref, derived from the SAME journal read as the
241
+ * reproject (no second readRunEvents). Parked → idempotent writePending,
242
+ * keeping the original createdAt when only sourceAt advanced, and skipping
243
+ * the write entirely when the on-disk record already matches (the daemon
244
+ * writes on every 1s scan while parked — keep it cheap). Non-parked or
245
+ * no-run → clearPending. Best-effort: failures are logged by the scan task,
246
+ * never thrown into the queue tail.
247
+ */
248
+ export async function maintainPending(
249
+ pendingDir: string,
250
+ ref: string,
251
+ state: FlowRunState | null,
252
+ io: PendingIo = defaultPendingIo,
253
+ ): Promise<void> {
254
+ let existing: PendingRecord | null = null
255
+ const decision = decidePending(state)
256
+ if (decision === 'write') {
257
+ try {
258
+ existing = parsePendingRecord(
259
+ await io.readFile(path.join(pendingDir, `${ref}.json`)),
260
+ )
261
+ } catch {
262
+ existing = null
263
+ }
264
+ const loop = state?.loop
265
+ if (loop === undefined) return
266
+ const phase: PendingPhase = loop.phase
267
+ let createdAt = new Date().toISOString()
268
+ if (
269
+ existing !== null &&
270
+ existing.phase === phase &&
271
+ existing.schema === PENDING_SCHEMA &&
272
+ existing.ref === ref
273
+ ) {
274
+ createdAt = existing.createdAt
275
+ }
276
+ let sourceAt = createdAt
277
+ if (state !== null) {
278
+ sourceAt = state.updatedAt
279
+ }
280
+ const record: PendingRecord = {
281
+ schema: PENDING_SCHEMA,
282
+ ref,
283
+ phase,
284
+ createdAt,
285
+ sourceAt,
286
+ }
287
+ if (existing !== null && recordsEqual(existing, record)) return
288
+ await writePending(pendingDir, record, io)
289
+ return
290
+ }
291
+ await clearPending(pendingDir, ref, io)
292
+ }
293
+
294
+ /**
295
+ * Reproject one run from its journal: read events (torn tails skipped),
296
+ * project, and write the projection atomically-in-process ONLY when the
297
+ * serialized state actually changed. The daemon never appends journal events
298
+ * itself, so the "unchanged = skip" shortcut here is safe (unlike the
299
+ * recordRunEvent main-session bug at run-state.ts:531-537 — see that
300
+ * AIDEV-NOTE).
301
+ */
302
+ export async function reprojectRun(
303
+ agentDir: string,
304
+ ref: string,
305
+ io: ReprojectIo = defaultReprojectIo,
306
+ ): Promise<ReprojectResult> {
307
+ const outcome = await reprojectRunDetailed(agentDir, ref, io)
308
+ return outcome.result
309
+ }
310
+
311
+ /**
312
+ * Same read path as reprojectRun but also returns the reprojected state so
313
+ * the scan's pending-maintenance step needs no second journal read.
314
+ */
315
+ export async function reprojectRunDetailed(
316
+ agentDir: string,
317
+ ref: string,
318
+ io: ReprojectIo = defaultReprojectIo,
319
+ ): Promise<ReprojectOutcome> {
320
+ const events = await readRunEvents(agentDir, ref, { readFile: io.readFile })
321
+ if (events === null) return { result: 'no-journal', state: null }
322
+ const state = projectRunState(events)
323
+ if (state === null) return { result: 'no-journal', state: null }
324
+ const statePath = runStatePath(agentDir, ref)
325
+ if (statePath === null) return { result: 'no-journal', state: null }
326
+ let currentRaw: string | null = null
327
+ try {
328
+ currentRaw = await io.readFile(statePath)
329
+ } catch {
330
+ // missing projection — rebuild below
331
+ }
332
+ if (currentRaw !== null) {
333
+ try {
334
+ const parsed: unknown = JSON.parse(currentRaw)
335
+ if (!isFlowRunState(parsed)) currentRaw = null
336
+ } catch {
337
+ currentRaw = null
338
+ }
339
+ }
340
+ if (!projectionChanged(currentRaw, state)) {
341
+ return { result: 'unchanged', state }
342
+ }
343
+ await io.writeFile(statePath, `${JSON.stringify(state, null, 2)}\n`)
344
+ return { result: 'written', state }
345
+ }
346
+
347
+ /**
348
+ * One serial async queue: every reproject and pending-maintenance task goes
349
+ * through here so the daemon never does concurrent read-modify-writes (there
350
+ * are no lock utilities; single-writer serialization is the concurrency
351
+ * story). Pure scheduling — no io, fully unit-testable.
352
+ */
353
+ export interface SerialQueue {
354
+ push(task: () => Promise<void>): Promise<void>
355
+ drain(): Promise<void>
356
+ }
357
+
358
+ export function createSerialQueue(): SerialQueue {
359
+ let tail: Promise<void> = Promise.resolve()
360
+ return {
361
+ push(task: () => Promise<void>): Promise<void> {
362
+ const run = tail.then(task, task)
363
+ // AIDEV-NOTE: the queue must survive task rejections (a failed
364
+ // reproject must not poison subsequent scans); callers of push still
365
+ // get the rejection surfaced through their own awaited promise.
366
+ tail = run.then(
367
+ () => undefined,
368
+ () => undefined,
369
+ )
370
+ return run
371
+ },
372
+ async drain(): Promise<void> {
373
+ // AIDEV-NOTE: awaiting the tail chain covers every task enqueued
374
+ // before the drain call. The previous implementation also kept every
375
+ // settled task promise in a `tracked` array forever — with ~100 tasks
376
+ // per 1s scan that is an unbounded memory leak that OOM-killed the
377
+ // daemon after ~38h (4.9GB heap). Do not reintroduce it.
378
+ await tail
379
+ },
380
+ }
381
+ }
382
+
383
+ /**
384
+ * fs.watch event filter for the runs/ dir: only journal appends are external
385
+ * input worth reacting to. The daemon's own .json projection writes land in
386
+ * the watched dir on every productive scan — rescan-on-own-write turned the
387
+ * watcher into a self-triggering loop amplifier (see the scan model note in
388
+ * main()). A null filename (some platforms never report one) conservatively
389
+ * triggers a rescan — the 1s poll is the correctness backstop either way.
390
+ */
391
+ export function isJournalWatchEvent(filename: string | null): boolean {
392
+ if (filename === null) return true
393
+ return filename.endsWith('.journal.jsonl')
394
+ }
395
+
396
+ /** Change signature for one ref's journal: `${size}:${mtimeMs}`. Pure data. */
397
+ export interface ScanCacheEntry {
398
+ sig: string
399
+ state: FlowRunState
400
+ }
401
+
402
+ /**
403
+ * Per-ref journal change signatures so the 1s poll skips re-reading and
404
+ * re-parsing journals that have not been appended to since the last scan
405
+ * (~800KB across ~100 refs in practice, every second, forever). When the
406
+ * signature matches, pending maintenance still runs — derived from the
407
+ * cached projection, which is provably identical to a fresh reproject
408
+ * (same journal bytes → same projected state). Entries are dropped on
409
+ * error/no-journal so a deleted-then-recreated journal can never serve a
410
+ * stale cached state.
411
+ */
412
+ export interface ScanCache {
413
+ get(ref: string): ScanCacheEntry | undefined
414
+ set(ref: string, sig: string, state: FlowRunState): void
415
+ delete(ref: string): void
416
+ }
417
+
418
+ export function createScanCache(): ScanCache {
419
+ const byRef = new Map<string, ScanCacheEntry>()
420
+ return {
421
+ get(ref: string): ScanCacheEntry | undefined {
422
+ return byRef.get(ref)
423
+ },
424
+ set(ref: string, sig: string, state: FlowRunState): void {
425
+ byRef.set(ref, { sig, state })
426
+ },
427
+ delete(ref: string): void {
428
+ byRef.delete(ref)
429
+ },
430
+ }
431
+ }
432
+
433
+ /**
434
+ * Stat-based change signature for one ref's journal; null when the journal
435
+ * is missing/unreadable (treated as "changed" — the task path handles the
436
+ * no-journal case and clears pending).
437
+ */
438
+ async function journalSignature(
439
+ agentDir: string,
440
+ ref: string,
441
+ ): Promise<string | null> {
442
+ try {
443
+ const st = await fsp.stat(
444
+ path.join(runsDir(agentDir), `${ref}.journal.jsonl`),
445
+ )
446
+ return `${st.size}:${st.mtimeMs}`
447
+ } catch {
448
+ return null
449
+ }
450
+ }
451
+
452
+ // --- daemon process ---
453
+
454
+ function log(agentDir: string, message: string): void {
455
+ // Best-effort append-only lifecycle/error log; failures are swallowed —
456
+ // the daemon must never crash because logging failed.
457
+ const line = `${new Date().toISOString()} ${message}\n`
458
+ fsp
459
+ .appendFile(path.join(agentDir, 'pi-flow', LOG_FILE_NAME), line, 'utf8')
460
+ .catch(() => undefined)
461
+ }
462
+
463
+ /** Scan the runs dir; per ref, reproject + maintain pending from one read,
464
+ * and sweep consumed markers once per scan. Journals whose size+mtime
465
+ * signature matches the previous scan skip the re-read entirely; pending
466
+ * maintenance still runs from the cached projection. */
467
+ async function scanRuns(
468
+ agentDir: string,
469
+ queue: SerialQueue,
470
+ cache: ScanCache,
471
+ ): Promise<void> {
472
+ const dir = runsDir(agentDir)
473
+ let entries: string[]
474
+ try {
475
+ entries = await fsp.readdir(dir)
476
+ } catch {
477
+ return // runs dir does not exist yet — nothing to scan
478
+ }
479
+ const refs = journalRefsFromEntries(entries)
480
+ const pendingDir = pendingDirPath(agentDir)
481
+ for (const ref of refs) {
482
+ const sig = await journalSignature(agentDir, ref)
483
+ let cached: ScanCacheEntry | undefined
484
+ if (sig !== null) {
485
+ cached = cache.get(ref)
486
+ }
487
+ if (sig !== null && cached !== undefined && cached.sig === sig) {
488
+ // AIDEV-NOTE: unchanged journal — skip the full re-read/parse and
489
+ // maintain pending from the cached projection (identical state →
490
+ // identical decision). Cache is dropped on failure so the next scan
491
+ // falls back to the full task path.
492
+ queue.push(async () => {
493
+ try {
494
+ await maintainPending(pendingDir, ref, cached.state)
495
+ } catch (err) {
496
+ cache.delete(ref)
497
+ log(agentDir, `scan maintenance failed for ${ref}: ${String(err)}`)
498
+ }
499
+ })
500
+ continue
501
+ }
502
+ queue.push(async () => {
503
+ try {
504
+ const outcome = await reprojectRunDetailed(agentDir, ref)
505
+ // Same journal read drives the pending decision (subtask 3.2).
506
+ await maintainPending(pendingDir, ref, outcome.state)
507
+ // AIDEV-NOTE: PMR-VHEY 2.7 — cache the PRE-READ signature (the outer
508
+ // `sig`, sampled at scan time BEFORE this task's journal read), never
509
+ // a signature sampled after the read. Proven poisoning mechanism
510
+ // (PMR-VHEY 2.5, openwiki/workflows/testing.md "Mechanism 2 — daemon:
511
+ // scan-cache signature poisoning", in-vivo trace dprobe-r2-5.log): a
512
+ // post-read signature stat observes journal appends the read missed,
513
+ // caching the POST-append sig beside the PRE-append state — every
514
+ // later poll then sig-matches and skips the re-read, permanently
515
+ // stalling the projection while the daemon stays healthy. A pre-read
516
+ // sig can only be STALE (an append between sampling and reading
517
+ // forces one extra re-read on the next poll), never falsely fresh:
518
+ // any mid-task append leaves on-disk sig ≠ cached sig, so the next
519
+ // poll re-reads. Pinned by the poison-regression test in
520
+ // test/run-server-integration.test.mjs.
521
+ if (outcome.state !== null && sig !== null) {
522
+ cache.set(ref, sig, outcome.state)
523
+ } else {
524
+ cache.delete(ref)
525
+ }
526
+ } catch (err) {
527
+ cache.delete(ref)
528
+ log(agentDir, `scan maintenance failed for ${ref}: ${String(err)}`)
529
+ }
530
+ })
531
+ }
532
+ if (refs.length > 0) {
533
+ queue.push(async () => {
534
+ await sweepConsumed(pendingDir)
535
+ })
536
+ }
537
+ }
538
+
539
+ // --- periodic pass timer (PMR-8MQH 3.1) ---
540
+ // AIDEV-NOTE: PMR-8MQH 3.1 — the reconcile timer's loop generalized. The gate
541
+ // check, the settings re-read, the re-arm-before-the-pass cadence, the
542
+ // disabled skip, the in-flight guard and the error logging are ONE
543
+ // implementation here so a second timer (liveness, subtask 3.2) cannot drift
544
+ // from them. Byte-identical behavior to the pre-extraction
545
+ // `startReconcileTimer`: the only difference in shape is that the log lines
546
+ // are built from `label` + a message body, so an adapter with
547
+ // `label: 'reconcile'` emits exactly the strings the tests assert.
548
+ // `gateClosedMessage` exists because the startup-gate reason is adapter
549
+ // knowledge (which env var / which config key), not the loop's.
550
+
551
+ /** One minute in ms — the unit `intervalMinutes` is expressed in. Also the
552
+ * fallback delay after a failed settings read: a read that failed once is
553
+ * retried in a minute rather than at the configured (possibly 6-hour)
554
+ * cadence. */
555
+ const PERIODIC_MINUTE_MS = 60_000
556
+ /** Default delay before the FIRST pass after daemon start (an adapter may
557
+ * override it via `firstPassDelayMs`). */
558
+ const PERIODIC_FIRST_PASS_DELAY_MS = 60_000
559
+
560
+ /** One armed timer. `hasRef` exists so the keepalive posture is assertable —
561
+ * production handles are real `setTimeout`s, which are ref'd until cleared. */
562
+ export interface ReconcileTimerHandle {
563
+ cancel(): void
564
+ hasRef(): boolean
565
+ }
566
+
567
+ export interface ReconcileTimer extends ReconcileTimerHandle {}
568
+
569
+ /** The settings a periodic pass re-reads on every tick. */
570
+ export interface PeriodicPassSettings {
571
+ enabled: boolean
572
+ intervalMinutes: number
573
+ /** a non-fatal problem reading the settings source; logged once per pass,
574
+ * never fatal (defaults are still applied) */
575
+ warning?: string
576
+ }
577
+
578
+ export interface PeriodicPassTimerOptions<TReport> {
579
+ /** prefix for every log line this timer emits (`'reconcile'`,
580
+ * `'liveness'`). Summary lines from `formatSummary` are logged verbatim —
581
+ * they carry their own prefix. */
582
+ label: string
583
+ agentDir: string
584
+ /** the daemon's log channel (`<agentDir>/pi-flow/server.log`) */
585
+ log: (message: string) => void
586
+ readSettings: (agentDir: string) => Promise<PeriodicPassSettings>
587
+ /** the pass itself. `null` means "nothing to report" — no summary line. */
588
+ runPass: () => Promise<TReport | null>
589
+ formatSummary: (report: TReport) => string
590
+ /** startup-only gate, evaluated once. False ⇒ one log line, no timer at all
591
+ * (a gate the daemon's fixed env/config can never satisfy later is not
592
+ * worth an armed chain). */
593
+ gateOpen: () => boolean
594
+ /** body of the gate-failure log line (after `label: `) */
595
+ gateClosedMessage?: string
596
+ /** seam: defaults to `setTimeout` — a REF'D handle (keepalive) */
597
+ schedule?: (fn: () => void, ms: number) => ReconcileTimerHandle
598
+ firstPassDelayMs?: number
599
+ }
600
+
601
+ /**
602
+ * A startup-gated loop whose next delay comes from a settings read on EVERY
603
+ * tick, so `intervalMinutes` changes and a flip back to `enabled: true` take
604
+ * effect WITHOUT restarting the daemon — PROVIDED a timer exists: a flip
605
+ * BEFORE startup (disabled at startup) never arms one, see the gate-2 cost
606
+ * note on `startReconcileTimer` below. A tick that reads `enabled: false`
607
+ * skips the pass but stays armed (plan behavior: "Each pass: settings
608
+ * disabled ⇒ skip").
609
+ *
610
+ * AIDEV-NOTE: KEEPALIVE — the armed handle is intentionally NOT unref'd,
611
+ * mirroring the pollTimer rule above (`hasRef` is exposed so a test pins it).
612
+ * AIDEV-NOTE: THE PASS NEVER TOUCHES THE SCAN QUEUE. It runs on its own async
613
+ * chain: a gateway round-trip (or a hung fetch) must not delay the 1s journal
614
+ * scan by even one tick. The flip side is that ticks do not wait for each
615
+ * other, so `inFlight` keeps a slow pass from stacking a second one behind it
616
+ * — a skipped tick re-arms and says so once.
617
+ */
618
+ export function startPeriodicPassTimer<TReport>(
619
+ options: PeriodicPassTimerOptions<TReport>,
620
+ ): ReconcileTimer {
621
+ const schedule = options.schedule ?? schedulePeriodicPassTimer
622
+ const firstPassDelayMs =
623
+ options.firstPassDelayMs ?? PERIODIC_FIRST_PASS_DELAY_MS
624
+
625
+ let handle: ReconcileTimerHandle | null = null
626
+ let cancelled = false
627
+ let inFlight = false
628
+ // Dedupe the disabled notice so a 1-minute interval cannot spam.
629
+ let disabledNoticed = false
630
+
631
+ const info = (message: string): void => {
632
+ options.log(`${options.label}: ${message}`)
633
+ }
634
+
635
+ const arm = (delayMs: number): void => {
636
+ if (cancelled) return
637
+ handle = schedule(() => {
638
+ void tick()
639
+ }, delayMs)
640
+ }
641
+
642
+ /** Reads the settings, logging the failure (and any source warning) in the
643
+ * same order the pre-extraction timer did. `null` means the read failed. */
644
+ const readSettings = async (): Promise<PeriodicPassSettings | null> => {
645
+ try {
646
+ return await options.readSettings(options.agentDir)
647
+ } catch (err) {
648
+ info(`settings read failed: ${String(err)}`)
649
+ return null
650
+ }
651
+ }
652
+
653
+ const logWarning = (settings: PeriodicPassSettings): void => {
654
+ if (settings.warning !== undefined) {
655
+ info(settings.warning)
656
+ }
657
+ }
658
+
659
+ const tick = async (): Promise<void> => {
660
+ handle = null
661
+ if (cancelled) return
662
+ const settings = await readSettings()
663
+ if (settings === null) {
664
+ arm(PERIODIC_MINUTE_MS)
665
+ return
666
+ }
667
+ if (cancelled) return
668
+ logWarning(settings)
669
+ const delayMs = Math.max(1, settings.intervalMinutes) * PERIODIC_MINUTE_MS
670
+ // Re-arm BEFORE the pass: the cadence must survive a slow or hung pass.
671
+ arm(delayMs)
672
+ if (!settings.enabled) {
673
+ if (!disabledNoticed) {
674
+ disabledNoticed = true
675
+ info('disabled in config — passes skipped')
676
+ }
677
+ return
678
+ }
679
+ disabledNoticed = false
680
+ if (inFlight) {
681
+ info('previous pass still running — pass skipped')
682
+ return
683
+ }
684
+ inFlight = true
685
+ try {
686
+ const report = await options.runPass()
687
+ if (report !== null) {
688
+ options.log(options.formatSummary(report))
689
+ }
690
+ } catch (err) {
691
+ info(`pass failed: ${String(err)}`)
692
+ } finally {
693
+ inFlight = false
694
+ }
695
+ }
696
+
697
+ const startup = async (): Promise<void> => {
698
+ if (!options.gateOpen()) {
699
+ info(
700
+ options.gateClosedMessage ?? 'startup gate closed — timer not started',
701
+ )
702
+ return
703
+ }
704
+ const settings = await readSettings()
705
+ if (settings === null) return
706
+ if (cancelled) return
707
+ logWarning(settings)
708
+ if (!settings.enabled) {
709
+ info('disabled in config — timer not started')
710
+ return
711
+ }
712
+ disabledNoticed = false
713
+ arm(firstPassDelayMs)
714
+ }
715
+ void startup()
716
+
717
+ return {
718
+ cancel(): void {
719
+ cancelled = true
720
+ if (handle !== null) {
721
+ handle.cancel()
722
+ handle = null
723
+ }
724
+ },
725
+ hasRef(): boolean {
726
+ if (handle === null) return false
727
+ return handle.hasRef()
728
+ },
729
+ }
730
+ }
731
+
732
+ /** Production scheduler: a real `setTimeout`, deliberately NOT unref'd. */
733
+ function schedulePeriodicPassTimer(
734
+ fn: () => void,
735
+ ms: number,
736
+ ): ReconcileTimerHandle {
737
+ const timer = setTimeout(fn, ms)
738
+ return {
739
+ cancel: () => {
740
+ clearTimeout(timer)
741
+ },
742
+ hasRef: () => timer.hasRef(),
743
+ }
744
+ }
745
+
746
+ // --- reconcile timer (PMR-MSDJ 2.2, plan PMR-V36Y decision 4a) ---
747
+
748
+ /** Delay before the FIRST pass after daemon start: long enough that a spawn
749
+ * storm (session start → ensureDaemon → reconcile) cannot reach the gateway
750
+ * before the projections exist, short enough that an operator who just ran
751
+ * `/flow-reconcile-push` sees the timer take over within a minute. */
752
+ export const RECONCILE_FIRST_PASS_DELAY_MS = PERIODIC_FIRST_PASS_DELAY_MS
753
+ /** `intervalMinutes` → ms. Exported so the tests assert the re-read contract
754
+ * without a live daemon. */
755
+ export const RECONCILE_MINUTE_MS = PERIODIC_MINUTE_MS
756
+
757
+ export interface ReconcileTimerOptions {
758
+ agentDir: string
759
+ /** the daemon's log channel (`<agentDir>/pi-flow/server.log`) — also where
760
+ * engine warnings go, via `runReconcilePassOnce`'s `warn` */
761
+ log: (message: string) => void
762
+ env?: NodeJS.ProcessEnv
763
+ /** seam: defaults to reading `<agentDir>/pi-flow/config.json` as raw text */
764
+ readSettings?: (agentDir: string) => Promise<ReconcileSettings>
765
+ /** seam: defaults to the wired engine pass (never dry) */
766
+ runPass?: () => Promise<ReconcileReport | null>
767
+ /** seam: defaults to `setTimeout` — a REF'D handle (keepalive) */
768
+ schedule?: (fn: () => void, ms: number) => ReconcileTimerHandle
769
+ firstPassDelayMs?: number
770
+ }
771
+
772
+ /**
773
+ * The daemon's stale-liveness reconcile loop — the reconcile wiring of
774
+ * `startPeriodicPassTimer`. Gates, in order, evaluated at startup:
775
+ * 1. `PI_FLOW_PUSHGATEWAY_URL` unset → log once, NO timer at all (the
776
+ * autopush gate: no endpoint means there is nothing to reconcile, and the
777
+ * daemon's env is fixed at spawn so a later check could never succeed);
778
+ * 2. `reconcile.enabled === false` → log once, NO timer at all.
779
+ * Then on every tick the reconcile settings are re-read (see the factory for
780
+ * the rest of the loop contract).
781
+ *
782
+ * AIDEV-NOTE (PMR-MSDJ review P2-3 — what gate 2 really costs): a flip BACK
783
+ * to `enabled: true` does NOT take effect unless the timer was armed at
784
+ * startup. A daemon that STARTED with `enabled=false` has no timer left to
785
+ * re-read settings (pinned by test/server-reconcile-timer.test.ts: "disabled
786
+ * at startup creates no timer at all"), and `server/lifecycle.ts` respawns
787
+ * only a DEAD daemon or a version mismatch — so disable, wait, re-enable
788
+ * yields silence with no log line until the daemon restarts (kill it and the
789
+ * next session's `ensureDaemon` re-spawns, or run `/flow-reconcile-push` for
790
+ * one pass now). Arming unconditionally and letting the per-tick check skip
791
+ * would close the gap; the startup gate is pinned behaviour, so this round
792
+ * documents it instead of changing it. The liveness timer inherits the same
793
+ * posture by design.
794
+ */
795
+ export function startReconcileTimer(
796
+ options: ReconcileTimerOptions,
797
+ ): ReconcileTimer {
798
+ const runPass =
799
+ options.runPass ??
800
+ (() =>
801
+ runReconcilePassOnce({
802
+ agentDir: options.agentDir,
803
+ env: options.env,
804
+ warn: options.log,
805
+ }))
806
+ return startPeriodicPassTimer<ReconcileReport>({
807
+ label: 'reconcile',
808
+ agentDir: options.agentDir,
809
+ log: options.log,
810
+ readSettings: options.readSettings ?? readReconcileSettings,
811
+ runPass,
812
+ formatSummary: reconcileSummaryLine,
813
+ gateOpen: () => pushgatewayEnv(options.env) !== null,
814
+ gateClosedMessage: 'PI_FLOW_PUSHGATEWAY_URL is not set — timer not started',
815
+ schedule: options.schedule,
816
+ firstPassDelayMs: options.firstPassDelayMs,
817
+ })
818
+ }
819
+
820
+ // --- liveness timer (PMR-8MQH 3.2) ---
821
+
822
+ /** Delay before the FIRST liveness pass and the unit `intervalMinutes` is
823
+ * expressed in — both reuse the factory's shared `PERIODIC_*` values (3.1),
824
+ * which are byte-identical here. Named per the plan's liveness contract and
825
+ * exported so the timer test asserts the re-read policy without a live
826
+ * daemon. */
827
+ export const LIVENESS_FIRST_PASS_DELAY_MS = PERIODIC_FIRST_PASS_DELAY_MS
828
+ export const LIVENESS_MINUTE_MS = PERIODIC_MINUTE_MS
829
+
830
+ /**
831
+ * AIDEV-NOTE: PMR-8MQH 3.2 — the liveness half of the two-reader split over
832
+ * `<agentDir>/pi-flow/config.json` (see flow/liveness.ts's `parseLivenessSettings`
833
+ * note). Mirrors `readReconcileSettings` (flow/reconcile-deps.ts) exactly:
834
+ * read the raw global-config text, hand it to the liveness parser, and degrade
835
+ * a non-ENOENT read failure to defaults + a warning — NEVER throw out of the
836
+ * tick (the daemon is best-effort io; `config.ts`'s throwing reader is
837
+ * deliberately off the allowlist). ENOENT is the normal "no config yet" answer
838
+ * (defaults, no warning).
839
+ */
840
+ async function readLivenessSettings(
841
+ agentDir: string,
842
+ readFile: (file: string) => Promise<string> = (file) =>
843
+ fsp.readFile(file, 'utf8'),
844
+ ): Promise<LivenessSettings> {
845
+ const file = globalConfigPath(agentDir)
846
+ let raw: string | null = null
847
+ let warning: string | undefined
848
+ try {
849
+ raw = await readFile(file)
850
+ } catch (err) {
851
+ const code = (err as NodeJS.ErrnoException).code
852
+ if (code !== 'ENOENT') {
853
+ let reason = `${err}`
854
+ if (err instanceof Error) {
855
+ reason = err.message
856
+ }
857
+ warning = `could not read ${file}: ${reason}`
858
+ }
859
+ raw = null
860
+ }
861
+ const settings = parseLivenessSettings(raw)
862
+ if (warning !== undefined) return { ...settings, warning }
863
+ return settings
864
+ }
865
+
866
+ export interface LivenessTimerOptions {
867
+ agentDir: string
868
+ /** the daemon's log channel (`<agentDir>/pi-flow/server.log`) — also where
869
+ * engine warnings land, via `createLivenessDeps`'s `warn` */
870
+ log: (message: string) => void
871
+ env?: NodeJS.ProcessEnv
872
+ /** seam: defaults to reading `<agentDir>/pi-flow/config.json` as raw text */
873
+ readSettings?: (agentDir: string) => Promise<LivenessSettings>
874
+ /** seam: defaults to the wired engine pass (a null from
875
+ * `createLivenessDeps` — the gate closed late — means "no pass") */
876
+ runPass?: () => Promise<LivenessReport | null>
877
+ /** seam: defaults to `setTimeout` — a REF'D handle (keepalive) */
878
+ schedule?: (fn: () => void, ms: number) => ReconcileTimerHandle
879
+ firstPassDelayMs?: number
880
+ }
881
+
882
+ /**
883
+ * The daemon's liveness pass — the liveness wiring of
884
+ * `startPeriodicPassTimer`. Gates, in order, evaluated at startup:
885
+ * 1. `PI_FLOW_PUSHGATEWAY_URL` unset → log once, NO timer at all (the same
886
+ * endpoint gate the reconcile timer uses — with no gateway there is
887
+ * nothing to keep alive on the dashboard, and the daemon's env is fixed at
888
+ * spawn so a later check could never succeed);
889
+ * 2. `liveness.enabled === false` → log once, NO timer at all.
890
+ * Then on every tick the liveness settings are re-read (see the factory for
891
+ * the rest of the loop contract). `runPass` builds deps via
892
+ * `createLivenessDeps`; a null return (gate closed late) is reported as "no
893
+ * pass" so the factory logs no summary line (2.2 handoff).
894
+ */
895
+ export function startLivenessTimer(
896
+ options: LivenessTimerOptions,
897
+ ): ReconcileTimer {
898
+ const runPass =
899
+ options.runPass ??
900
+ (async () => {
901
+ const deps = createLivenessDeps({
902
+ agentDir: options.agentDir,
903
+ warn: options.log,
904
+ env: options.env,
905
+ })
906
+ if (deps === null) return null
907
+ return runLivenessPassOnce(deps)
908
+ })
909
+ return startPeriodicPassTimer<LivenessReport>({
910
+ label: 'liveness',
911
+ agentDir: options.agentDir,
912
+ log: options.log,
913
+ readSettings: options.readSettings ?? readLivenessSettings,
914
+ runPass,
915
+ formatSummary: livenessSummaryLine,
916
+ gateOpen: () => pushgatewayEnv(options.env) !== null,
917
+ gateClosedMessage: 'PI_FLOW_PUSHGATEWAY_URL is not set — timer not started',
918
+ schedule: options.schedule,
919
+ firstPassDelayMs: options.firstPassDelayMs,
920
+ })
921
+ }
922
+
923
+ function main(): void {
924
+ const agentDir = process.env.PI_FLOW_AGENT_DIR ?? ''
925
+ if (!path.isAbsolute(agentDir)) {
926
+ process.stderr.write('PI_FLOW_AGENT_DIR must be set to an absolute path\n')
927
+ process.exitCode = 1
928
+ return
929
+ }
930
+
931
+ const queue = createSerialQueue()
932
+ const scanCache = createScanCache()
933
+
934
+ // Pidfile: the extension's lifecycle module (subtask 1.2) uses pid +
935
+ // version + startedAt + agentDir for liveness and version-mismatch respawn.
936
+ // PMR-7B8M adds the ADVISORY gitSha — the spawning checkout's HEAD, dropped
937
+ // unless it validates as 40-hex — and (rev 2) the ADVISORY gitRoot — the
938
+ // spawning repo's main-worktree path, dropped unless it is a non-empty
939
+ // absolute path. Later sessions compare both against their own repo before
940
+ // acting on staleness (PMR-5563: manual-kill warning when busy, auto-restart
941
+ // when idle); a daemon spawned from another repo is never judged (the
942
+ // daemon is global). Neither field influences this daemon's behavior.
943
+ const pidPath = path.join(agentDir, 'pi-flow', PID_FILE_NAME)
944
+ const gitSha = gitShaFromEnv(process.env)
945
+ const gitRoot = gitRootFromEnv(process.env)
946
+ fsp
947
+ .mkdir(path.dirname(pidPath), { recursive: true })
948
+ .then(() =>
949
+ fsp.writeFile(
950
+ pidPath,
951
+ pidfileLine({
952
+ pid: process.pid,
953
+ version: SERVER_PROTOCOL_VERSION,
954
+ startedAt: new Date().toISOString(),
955
+ agentDir,
956
+ gitSha,
957
+ gitRoot,
958
+ }),
959
+ 'utf8',
960
+ ),
961
+ )
962
+ .catch((err: unknown) => {
963
+ log(agentDir, `failed to write pidfile: ${String(err)}`)
964
+ })
965
+
966
+ // AIDEV-NOTE: PMR-XTQQ phase 1 — pending/ is created harmlessly at startup
967
+ // (spec acceptance): the on-disk layout exists before the first parked run
968
+ // and the consumer never needs to mkdir (consumePending only renames).
969
+ // Best-effort: an unwritable agent dir degrades exactly like every other
970
+ // daemon io failure (the journal stays authoritative).
971
+ fsp
972
+ .mkdir(pendingDirPath(agentDir), { recursive: true })
973
+ .catch((err: unknown) => {
974
+ log(agentDir, `failed to create pending dir: ${String(err)}`)
975
+ })
976
+
977
+ log(
978
+ agentDir,
979
+ `daemon started pid=${process.pid} version=${SERVER_PROTOCOL_VERSION}`,
980
+ )
981
+
982
+ // AIDEV-NOTE: scan model (plan decision 8) — 1s stat-poll full scan is the
983
+ // PERMANENT fallback and the correctness backstop (dir-watch does not
984
+ // reliably report appends into existing files); fs.watch only buys latency
985
+ // for new journals (filtered to *.journal.jsonl — see isJournalWatchEvent),
986
+ // and its failure degrades silently to poll. The per-ref size+mtime scan
987
+ // cache (createScanCache) keeps an idle poll from re-reading every journal
988
+ // every second; a cache hit still runs pending maintenance from the cached
989
+ // projection. Hot-loop history: legacy out-of-vocabulary journals made
990
+ // projections fail the daemon's own guard, so every scan rewrote identical
991
+ // bytes inside the watched dir — CPU burn + watch churn + unbounded queue
992
+ // growth (see applyEvent's AIDEV-NOTE in run-state.ts and the drain note
993
+ // in createSerialQueue).
994
+ // AIDEV-NOTE: KEEPALIVE — pollTimer is intentionally NOT unref'd. It is the
995
+ // only guaranteed event-loop handle when fs.watch(runsDir) fails (runs/ may
996
+ // not exist at startup); unref'ing it let the daemon exit milliseconds after
997
+ // writing its pidfile (PMR-XTQQ review blocker). If you add another handle,
998
+ // this interval must remain ref'd or the daemon must gain an explicit
999
+ // keepalive handle.
1000
+ const schedule = createDebouncedScheduler(() => {
1001
+ void scanRuns(agentDir, queue, scanCache)
1002
+ }, DEBOUNCE_MS)
1003
+ const pollTimer = setInterval(() => {
1004
+ void scanRuns(agentDir, queue, scanCache)
1005
+ }, POLL_INTERVAL_MS)
1006
+ // AIDEV-NOTE: PMR-MSDJ 2.2 — reconcile timer (plan PMR-V36Y decision 4a).
1007
+ // Runs on its OWN async chain, never through `queue`, so a Pushgateway
1008
+ // round-trip cannot delay a 1s scan; its handle is ref'd like pollTimer
1009
+ // (keepalive), and `cancel()` on shutdown stops it from re-arming behind an
1010
+ // in-flight pass. Startup gates (no endpoint / disabled) mean no timer is
1011
+ // created at all; per-pass the config is re-read so interval and enable
1012
+ // changes apply without restarting the daemon. Best-effort io: every failure
1013
+ // is one log line.
1014
+ const reconcile = startReconcileTimer({
1015
+ agentDir,
1016
+ log: (message) => {
1017
+ log(agentDir, message)
1018
+ },
1019
+ })
1020
+ // AIDEV-NOTE: PMR-8MQH 3.2 — liveness timer, the same gated periodic-pass
1021
+ // loop as reconcile but pushing the FULL running body for still-running
1022
+ // runs (so they never fade from the dashboard between phase pushes). Own
1023
+ // async chain, ref'd handle (keepalive), `cancel()` on shutdown; the
1024
+ // settings (`liveness` block) are re-read per tick. Gates identically: no
1025
+ // endpoint / disabled at startup ⇒ no timer.
1026
+ const liveness = startLivenessTimer({
1027
+ agentDir,
1028
+ log: (message) => {
1029
+ log(agentDir, message)
1030
+ },
1031
+ env: process.env,
1032
+ })
1033
+ try {
1034
+ const watcher = watch(runsDir(agentDir), (_event, filename) => {
1035
+ if (isJournalWatchEvent(filename)) schedule()
1036
+ })
1037
+ watcher.on('error', () => {
1038
+ // Degrade silently to the poll scan.
1039
+ watcher.close()
1040
+ })
1041
+ } catch {
1042
+ // runs dir may not exist yet; the poll scan covers everything
1043
+ }
1044
+
1045
+ const shutdown = (): void => {
1046
+ clearInterval(pollTimer)
1047
+ reconcile.cancel()
1048
+ liveness.cancel()
1049
+ log(agentDir, 'daemon stopping')
1050
+ // AIDEV-NOTE: best-effort pidfile unlink on clean shutdown (SIGTERM/SIGINT)
1051
+ // so a drained daemon doesn't leave a stale server.pid behind. A SIGKILL
1052
+ // still leaves one — acceptable: probeDaemon's pid-liveness check is the
1053
+ // source of truth, and lifecycle.ts treats a fresh dead-pid pidfile as
1054
+ // spawn-in-progress rather than trusting it.
1055
+ fsp.unlink(pidPath).catch(() => undefined)
1056
+ void queue
1057
+ .drain()
1058
+ .catch(() => undefined)
1059
+ .then(() => {
1060
+ process.exit(0)
1061
+ })
1062
+ }
1063
+ process.on('SIGTERM', shutdown)
1064
+ process.on('SIGINT', shutdown)
1065
+
1066
+ void scanRuns(agentDir, queue, scanCache)
1067
+ }
1068
+
1069
+ // AIDEV-NOTE: extracted so schedule() is constructible without io; same
1070
+ // debounce shape as flow-viewer.mjs's createDebouncedRender.
1071
+ function createDebouncedScheduler(fn: () => void, ms: number): () => void {
1072
+ let timer: NodeJS.Timeout | null = null
1073
+ return () => {
1074
+ if (timer !== null) clearTimeout(timer)
1075
+ timer = setTimeout(() => {
1076
+ timer = null
1077
+ fn()
1078
+ }, ms)
1079
+ timer.unref()
1080
+ }
1081
+ }
1082
+
1083
+ // ── main-module guard (flow-viewer.mjs pattern) ──
1084
+ // AIDEV-NOTE: only the daemon process (spawned with PI_FLOW_AGENT_DIR set)
1085
+ // runs the execution prelude below; importing this module from tests must
1086
+ // execute nothing. Pure helpers (reprojectRun, projectionChanged,
1087
+ // createSerialQueue, SERVER_PROTOCOL_VERSION) are exported for unit tests.
1088
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
1089
+ main()
1090
+ }
1091
+
1092
+ // FlowRunEvent is re-exported only as a type so test/daemon consumers can
1093
+ // build journal events without importing from two modules.
1094
+ export type { FlowRunEvent }