@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,679 @@
1
+ // AIDEV-NOTE: PMR-XTQQ — extension-side lifecycle for the pi-flow durable run
2
+ // server (server/daemon.ts). Owns the pidfile liveness probe and the
3
+ // spawn/respawn decision. NEVER throws: every failure mode (missing/garbage
4
+ // pidfile, dead pid, version mismatch, spawn failure, spawn timeout) degrades
5
+ // to a typed status — journal writes fall back to the full writer path
6
+ // (server/writer.ts) and a flow phase must never break because the daemon
7
+ // could not start.
8
+ //
9
+ // BUMP TOGETHER: EXPECTED_SERVER_PROTOCOL_VERSION pins the pidfile version the
10
+ // daemon writes (SERVER_PROTOCOL_VERSION in server/daemon.ts). Two-sided pin
11
+ // per plan decision 7 (pattern: HERDR_MIN_VERSION in pi-interactive-subagents
12
+ // herdr.ts ↔ EXPECTED_MIN_HERDR_VERSION in herdr/sync.ts): a long-lived daemon
13
+ // can outlive a package upgrade, so a mismatch means kill + respawn. The
14
+ // value is imported from daemon.ts (same package, single literal) — when
15
+ // bumping, update the constant in daemon.ts and this note together.
16
+
17
+ import { spawn as nodeSpawn } from 'node:child_process'
18
+ import { closeSync, promises as fsp, openSync } from 'node:fs'
19
+ import path from 'node:path'
20
+ import { fileURLToPath } from 'node:url'
21
+ import { SERVER_PROTOCOL_VERSION } from './daemon.ts'
22
+
23
+ /** Pidfile version pin — see BUMP TOGETHER note above. */
24
+ export const EXPECTED_SERVER_PROTOCOL_VERSION = SERVER_PROTOCOL_VERSION
25
+
26
+ const PID_FILE_NAME = 'server.pid'
27
+ const SPAWN_LOCK_NAME = 'server.spawn-lock'
28
+ const LOG_FILE_NAME = 'server.log'
29
+ const POLL_INTERVAL_MS = 50
30
+ const SPAWN_READY_BUDGET_MS = 2_000
31
+ // AIDEV-NOTE: spawn-in-progress window — a pidfile with a DEAD pid whose
32
+ // mtime is younger than this is treated as a spawn racing/just-crashed, not
33
+ // as an immediate respawn trigger (prevents trusting a recycled pid and
34
+ // prevents two rapid /flow starts from double-spawning). The pidfile is
35
+ // written by the daemon child right after startup, so "fresh but dead" means
36
+ // either the child died within milliseconds or another ensureDaemon's spawn
37
+ // is in flight; either way we wait briefly, re-probe, and only report a
38
+ // typed status — never spawn a duplicate ourselves in that window.
39
+ const SPAWN_IN_PROGRESS_MAX_AGE_MS = 5_000
40
+ const SPAWN_IN_PROGRESS_WAIT_MS = 1_500
41
+ // AIDEV-NOTE: PMR-5563 — bounded death budget for restartDaemon: after
42
+ // SIGTERMing the stale daemon, poll its liveness for at most this long
43
+ // before declaring 'old daemon survived SIGTERM'. Same bounded-wait shape as
44
+ // contendedStatus below (deadline from io.now, POLL_INTERVAL_MS steps).
45
+ export const RESTART_DEATH_WAIT_MS = 1_500
46
+
47
+ export function pidFilePath(agentDir: string): string {
48
+ return path.join(agentDir, 'pi-flow', PID_FILE_NAME)
49
+ }
50
+
51
+ export function spawnLockPath(agentDir: string): string {
52
+ return path.join(agentDir, 'pi-flow', SPAWN_LOCK_NAME)
53
+ }
54
+
55
+ export function logFilePath(agentDir: string): string {
56
+ return path.join(agentDir, 'pi-flow', LOG_FILE_NAME)
57
+ }
58
+
59
+ /** Daemon entry module, derived from this file's location so it works both
60
+ * from the repo and an installed package layout. */
61
+ export function daemonEntryPath(): string {
62
+ return path.resolve(path.dirname(fileURLToPath(import.meta.url)), 'daemon.ts')
63
+ }
64
+
65
+ export interface SpawnedProcess {
66
+ pid: number
67
+ unref(): void
68
+ }
69
+
70
+ export type SpawnFn = (
71
+ cmd: string,
72
+ args: string[],
73
+ opts: {
74
+ detached: boolean
75
+ stdio: ['ignore', number, number]
76
+ env: NodeJS.ProcessEnv
77
+ },
78
+ ) => SpawnedProcess
79
+
80
+ export interface LifecycleIo {
81
+ /** Pidfile contents, or null when missing/unreadable. */
82
+ readFile: (p: string) => Promise<string | null>
83
+ /** Liveness check — real impl is `process.kill(pid, 0)` in a try/catch. */
84
+ isProcessAlive: (pid: number) => boolean
85
+ /** Best-effort SIGTERM; real impl swallows errors (incl. ESRCH). */
86
+ kill: (pid: number, signal: 'SIGTERM') => void
87
+ spawn: SpawnFn
88
+ mkdir: (p: string) => Promise<void>
89
+ openLogFd: (p: string) => number
90
+ closeFd: (fd: number) => void
91
+ sleep: (ms: number) => Promise<void>
92
+ /** Pidfile mtime in ms, or null when missing/unreadable (injectable clock
93
+ * pairs with `now`). */
94
+ statMtimeMs: (p: string) => Promise<number | null>
95
+ /** Wall clock in ms (injectable so the spawn-in-progress wait costs
96
+ * nothing in tests even with instant sleeps). */
97
+ now: () => number
98
+ // AIDEV-NOTE: PMR-HRGJ — cross-process spawn-claim seam. These are REQUIRED
99
+ // members (no optional/legacy fallback) so a degraded implementation fails
100
+ // loudly instead of silently losing the single-daemon guarantee.
101
+ /** Exclusive create: write `content` at `p` only if it does not exist
102
+ * (real impl: fs open 'wx'). Returns false on EEXIST or any failure. */
103
+ tryCreateExclusive: (p: string, content: string) => Promise<boolean>
104
+ /** Atomic rename of `from` over `to`; false when the rename fails. */
105
+ renameOver: (from: string, to: string) => Promise<boolean>
106
+ /** Best-effort unlink; real impl swallows errors (incl. ENOENT). */
107
+ unlinkFile: (p: string) => Promise<void>
108
+ }
109
+
110
+ /**
111
+ * PMR-5563: the single real liveness implementation — `realIo.isProcessAlive`
112
+ * uses it, and it is exported so callers outside this module (e.g. the
113
+ * flow/run-liveness.ts idle gate) share one probe instead of re-rolling
114
+ * process.kill(pid, 0) try/catch blocks. Never throws.
115
+ */
116
+ export function realPidAlive(pid: number): boolean {
117
+ try {
118
+ process.kill(pid, 0)
119
+ return true
120
+ } catch {
121
+ return false
122
+ }
123
+ }
124
+
125
+ const realIo: LifecycleIo = {
126
+ readFile: async (p) => {
127
+ try {
128
+ return await fsp.readFile(p, 'utf8')
129
+ } catch {
130
+ return null
131
+ }
132
+ },
133
+ isProcessAlive: realPidAlive,
134
+ kill: (pid, signal) => {
135
+ try {
136
+ process.kill(pid, signal)
137
+ } catch {
138
+ // Already dead (ESRCH) or permissions — respawn decision stands either way.
139
+ }
140
+ },
141
+ spawn: (cmd, args, opts) => {
142
+ const child = nodeSpawn(cmd, args, opts)
143
+ return { pid: child.pid ?? -1, unref: () => child.unref() }
144
+ },
145
+ mkdir: async (p) => {
146
+ await fsp.mkdir(p, { recursive: true })
147
+ },
148
+ openLogFd: (p) => openSync(p, 'a'),
149
+ closeFd: (fd) => {
150
+ closeSync(fd)
151
+ },
152
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
153
+ statMtimeMs: async (p) => {
154
+ try {
155
+ const st = await fsp.stat(p)
156
+ return st.mtimeMs
157
+ } catch {
158
+ return null
159
+ }
160
+ },
161
+ now: () => Date.now(),
162
+ // AIDEV-NOTE: PMR-HRGJ — real claim primitives. 'wx' flag = fail if the
163
+ // path exists (the O_EXCL lockfile pattern); any error counts as "lost".
164
+ tryCreateExclusive: async (p, content) => {
165
+ try {
166
+ const fh = await fsp.open(p, 'wx')
167
+ try {
168
+ await fh.writeFile(content, 'utf8')
169
+ } finally {
170
+ await fh.close()
171
+ }
172
+ return true
173
+ } catch {
174
+ return false
175
+ }
176
+ },
177
+ renameOver: async (from, to) => {
178
+ try {
179
+ await fsp.rename(from, to)
180
+ return true
181
+ } catch {
182
+ return false
183
+ }
184
+ },
185
+ unlinkFile: async (p) => {
186
+ try {
187
+ await fsp.unlink(p)
188
+ } catch {
189
+ // Missing/unlinkable lock — nothing to release.
190
+ }
191
+ },
192
+ }
193
+
194
+ export type ProbeResult =
195
+ | {
196
+ alive: true
197
+ pid: number
198
+ /**
199
+ * PMR-7B8M: git SHA of the spawning checkout, from the pidfile; absent
200
+ * on pre-feature pidfiles. Used only for session-side staleness
201
+ * warnings, never by the liveness/respawn decision.
202
+ */
203
+ gitSha?: string
204
+ /**
205
+ * PMR-7B8M rev 2: MAIN-worktree path of the repo the daemon was spawned
206
+ * from — repo identity. The daemon is one global process serving every
207
+ * repo, so a SHA alone cannot say whether it describes this repo; this
208
+ * path is what lets a session stay silent about another repo's daemon.
209
+ * Never consulted by the liveness/respawn decision.
210
+ *
211
+ * AIDEV-NOTE: PMR-8620 — this is the MAIN worktree, NOT the session's own
212
+ * root: do not compare it against `resolveSessionRepoRoot()` or a journaled
213
+ * run-input `gitRoot`, which are the session's own (worktree) path for any
214
+ * herdr worktree session — the check would mismatch on every worktree and
215
+ * go permanently silent. `server/staleness.ts` compares it only against
216
+ * `MainCheckout.path` (also the main worktree). Read from the pidfile's
217
+ * `gitRoot` key; that on-disk name is unchanged so pidfiles written by
218
+ * already-running daemons stay readable after an upgrade.
219
+ */
220
+ mainWorktree?: string
221
+ }
222
+ | {
223
+ alive: false
224
+ reason:
225
+ | 'no-pidfile'
226
+ | 'malformed-pidfile'
227
+ | 'dead-process'
228
+ | 'version-mismatch'
229
+ /** Surfaced when the pidfile parsed, so callers can SIGTERM without re-reading. */
230
+ pid?: number
231
+ }
232
+
233
+ interface ParsedPidfile {
234
+ pid: number
235
+ version: string
236
+ /** PMR-7B8M: advisory git SHA of the spawner's checkout. Absent on older
237
+ * pidfiles. NEVER affects the malformed verdict — a wrong type degrades to
238
+ * absent (a bad gitSha must not SIGTERM a healthy daemon). */
239
+ gitSha?: string
240
+ /** PMR-7B8M rev 2: advisory main-worktree path of the spawner's repo, same
241
+ * posture as gitSha — only a string is kept, everything else degrades to
242
+ * absent so the probe stays `alive`. */
243
+ gitRoot?: string
244
+ }
245
+
246
+ function parsePidfile(raw: string): ParsedPidfile | null {
247
+ let parsed: unknown
248
+ try {
249
+ parsed = JSON.parse(raw)
250
+ } catch {
251
+ return null
252
+ }
253
+ if (typeof parsed !== 'object' || parsed === null) return null
254
+ const rec = parsed as {
255
+ pid?: unknown
256
+ version?: unknown
257
+ gitSha?: unknown
258
+ gitRoot?: unknown
259
+ }
260
+ if (typeof rec.pid !== 'number' || !Number.isInteger(rec.pid)) return null
261
+ if (typeof rec.version !== 'string') return null
262
+ const parsedPidfile: ParsedPidfile = { pid: rec.pid, version: rec.version }
263
+ // PMR-7B8M: advisory — only a string is kept, everything else (number,
264
+ // object, null, bool) is dropped so the probe stays `alive`.
265
+ if (typeof rec.gitSha === 'string') parsedPidfile.gitSha = rec.gitSha
266
+ // PMR-7B8M rev 2: same advisory treatment for the repo identity.
267
+ if (typeof rec.gitRoot === 'string') parsedPidfile.gitRoot = rec.gitRoot
268
+ return parsedPidfile
269
+ }
270
+
271
+ /** Liveness probe: never throws, every failure mode a distinct reason. */
272
+ export async function probeDaemon(
273
+ agentDir: string,
274
+ io: LifecycleIo = realIo,
275
+ ): Promise<ProbeResult> {
276
+ let raw: string | null = null
277
+ try {
278
+ raw = await io.readFile(pidFilePath(agentDir))
279
+ } catch {
280
+ raw = null
281
+ }
282
+ if (raw === null) return { alive: false, reason: 'no-pidfile' }
283
+ const parsed = parsePidfile(raw)
284
+ if (parsed === null) return { alive: false, reason: 'malformed-pidfile' }
285
+ if (!io.isProcessAlive(parsed.pid)) {
286
+ return { alive: false, reason: 'dead-process', pid: parsed.pid }
287
+ }
288
+ if (parsed.version !== EXPECTED_SERVER_PROTOCOL_VERSION) {
289
+ return {
290
+ alive: false,
291
+ reason: 'version-mismatch',
292
+ pid: parsed.pid,
293
+ }
294
+ }
295
+ const result: ProbeResult = { alive: true, pid: parsed.pid }
296
+ // PMR-7B8M: assigned conditionally so callers can distinguish "pre-feature
297
+ // pidfile" (key absent) from a present SHA. PMR-7B8M rev 2 does the same for
298
+ // the repo identity, surfaced as `mainWorktree` (PMR-8620: the pidfile key is
299
+ // `gitRoot` but the value is the MAIN worktree, never the session's worktree).
300
+ if (parsed.gitSha !== undefined) result.gitSha = parsed.gitSha
301
+ if (parsed.gitRoot !== undefined) result.mainWorktree = parsed.gitRoot
302
+ return result
303
+ }
304
+
305
+ // AIDEV-NOTE: PMR-HRGJ — spawn claim. Before spawning, ensureDaemon claims
306
+ // `server.spawn-lock` (JSON {pid, at}) via exclusive create. Concurrent
307
+ // ensureDaemons that lose the claim must NOT spawn (or SIGTERM): they wait
308
+ // and re-probe, exactly like the fresh-dead spawnInProgressStatus window.
309
+ // A claim is STALE when its claimant pid is provably dead OR its age exceeds
310
+ // SPAWN_IN_PROGRESS_MAX_AGE_MS (5s); stale/garbage claims are stolen atomically
311
+ // via a temp-then-rename (exclusive temp write, then renameOver onto the lock —
312
+ // losing the rename means someone else claimed first). The winner releases the
313
+ // lock on every spawn exit path EXCEPT spawn-timeout, which deliberately KEEPS
314
+ // the claim (keepClaim, PMR-9NA0) so late writers cannot start a second
315
+ // daemon; the 5s age bound lets a later contender reclaim it.
316
+ interface SpawnClaim {
317
+ pid: number
318
+ at: number
319
+ }
320
+
321
+ function parseSpawnClaim(raw: string): SpawnClaim | null {
322
+ let parsed: unknown
323
+ try {
324
+ parsed = JSON.parse(raw)
325
+ } catch {
326
+ return null
327
+ }
328
+ if (typeof parsed !== 'object' || parsed === null) return null
329
+ const rec = parsed as { pid?: unknown; at?: unknown }
330
+ if (typeof rec.pid !== 'number' || !Number.isInteger(rec.pid)) return null
331
+ if (typeof rec.at !== 'number') return null
332
+ return { pid: rec.pid, at: rec.at }
333
+ }
334
+
335
+ function claimIsStale(claim: SpawnClaim | null, io: LifecycleIo): boolean {
336
+ // Unreadable/garbage claim content → treat as stale so a corrupt lock
337
+ // cannot wedge daemon startup forever.
338
+ if (claim === null) return true
339
+ if (!io.isProcessAlive(claim.pid)) return true
340
+ if (io.now() - claim.at > SPAWN_IN_PROGRESS_MAX_AGE_MS) return true
341
+ return false
342
+ }
343
+
344
+ /**
345
+ * Try to win the spawn claim. Returns `won: true` (with the claim timestamp
346
+ * `at` for ownership-checked release) when the caller may spawn and owns the
347
+ * lock file, including after a stale-claim steal. Never throws.
348
+ */
349
+ async function acquireSpawnClaim(
350
+ agentDir: string,
351
+ io: LifecycleIo,
352
+ ): Promise<{ won: boolean; at: number }> {
353
+ const lockPath = spawnLockPath(agentDir)
354
+ const myAt = io.now()
355
+ const claimJson = JSON.stringify({ pid: process.pid, at: myAt })
356
+ const won = await io.tryCreateExclusive(lockPath, claimJson)
357
+ if (won) return { won: true, at: myAt }
358
+
359
+ // Contended: is the existing claim stale enough to steal?
360
+ let raw: string | null = null
361
+ try {
362
+ raw = await io.readFile(lockPath)
363
+ } catch {
364
+ raw = null
365
+ }
366
+ const existing = parseSpawnClaim(raw ?? '')
367
+ // PMR-HRGJ: young-empty-lock guard — between open('wx') and the content
368
+ // write the lock exists but is EMPTY; parsing it yields null and the old
369
+ // code treated that as "stale", clobbering the winner's fresh claim. If
370
+ // the unparsable/empty lock is YOUNG (mtime within the age bound), a
371
+ // winner is writing it right now → contend, never steal. Old (or
372
+ // unmeasurable) empty/garbage locks stay stale → steal below.
373
+ if (existing === null) {
374
+ let lockMtime: number | null = null
375
+ try {
376
+ lockMtime = await io.statMtimeMs(lockPath)
377
+ } catch {
378
+ lockMtime = null
379
+ }
380
+ if (
381
+ lockMtime !== null &&
382
+ io.now() - lockMtime <= SPAWN_IN_PROGRESS_MAX_AGE_MS
383
+ ) {
384
+ return { won: false, at: myAt }
385
+ }
386
+ }
387
+ if (!claimIsStale(existing, io)) return { won: false, at: myAt }
388
+
389
+ // Atomic steal: exclusive temp claim, then rename over the lock. Losing
390
+ // the rename means another contender claimed/refreshed first.
391
+ const tmpPath = `${lockPath}.${process.pid}.${io.now()}.tmp`
392
+ const tmpCreated = await io.tryCreateExclusive(tmpPath, claimJson)
393
+ if (!tmpCreated) return { won: false, at: myAt }
394
+ const stolen = await io.renameOver(tmpPath, lockPath)
395
+ if (stolen) {
396
+ // PMR-HRGJ — rename replaces UNCONDITIONALLY, so a faster contender's
397
+ // steal can land between our stale-claim read and our rename; both
398
+ // renames then "succeed" but only the last claim on the lock is real.
399
+ // Read the lock back and spawn only if it still holds OUR claim —
400
+ // otherwise we lost the steal race and must contend, never spawn twice.
401
+ const verifyRaw = await io.readFile(lockPath)
402
+ const verified = parseSpawnClaim(verifyRaw ?? '')
403
+ if (
404
+ verified !== null &&
405
+ verified.pid === process.pid &&
406
+ verified.at === myAt
407
+ ) {
408
+ return { won: true, at: myAt }
409
+ }
410
+ return { won: false, at: myAt }
411
+ }
412
+ await io.unlinkFile(tmpPath)
413
+ return { won: false, at: myAt }
414
+ }
415
+
416
+ // PMR-HRGJ: ownership-checked release — the winner may be >5s stalled, by
417
+ // which time a contender has legitimately stolen the aged claim and is
418
+ // spawning under it. A blind unlink would delete the STEALER's fresh claim
419
+ // and re-open the double-spawn window. Only unlink when the lock still holds
420
+ // OUR pid + OUR claim timestamp; otherwise leave it alone.
421
+ async function releaseSpawnClaimIfOwned(
422
+ agentDir: string,
423
+ io: LifecycleIo,
424
+ myAt: number,
425
+ ): Promise<void> {
426
+ const lockPath = spawnLockPath(agentDir)
427
+ let raw: string | null = null
428
+ try {
429
+ raw = await io.readFile(lockPath)
430
+ } catch {
431
+ raw = null
432
+ }
433
+ const claim = parseSpawnClaim(raw ?? '')
434
+ if (claim !== null && claim.pid === process.pid && claim.at === myAt) {
435
+ await io.unlinkFile(lockPath)
436
+ }
437
+ }
438
+
439
+ /**
440
+ * Wait-and-reprobe when another session owns a live spawn claim. Mirrors
441
+ * spawnInProgressStatus's bounded wait (statuses reused, enum unchanged).
442
+ */
443
+ async function contendedStatus(
444
+ agentDir: string,
445
+ io: LifecycleIo,
446
+ ): Promise<EnsureDaemonResult> {
447
+ const deadline = io.now() + SPAWN_IN_PROGRESS_WAIT_MS
448
+ while (io.now() < deadline) {
449
+ await io.sleep(POLL_INTERVAL_MS)
450
+ const check = await probeDaemon(agentDir, io)
451
+ if (check.alive) return { status: 'already-running', pid: check.pid }
452
+ }
453
+ return { status: 'spawn-in-progress' }
454
+ }
455
+
456
+ export type EnsureDaemonResult =
457
+ | { status: 'already-running'; pid: number }
458
+ | { status: 'spawned'; pid: number }
459
+ | { status: 'spawn-timeout' }
460
+ | { status: 'spawn-failed'; reason: string }
461
+ | { status: 'spawn-in-progress' }
462
+
463
+ /**
464
+ * Spawn-in-progress guard: when the pidfile holds a DEAD pid but is FRESH
465
+ * (mtime within SPAWN_IN_PROGRESS_MAX_AGE_MS), another ensureDaemon's spawn
466
+ * may be in flight (or a just-started daemon died instantly). Do not spawn a
467
+ * duplicate: wait up to SPAWN_IN_PROGRESS_WAIT_MS (injectable clock via
468
+ * io.now/io.sleep), re-probing as we go. Daemon came up (or the pidfile was
469
+ * replaced by a live one) → 'already-running'. Still dead after the wait →
470
+ * 'spawn-in-progress' so the caller's journal write degrades to the full
471
+ * writer path without a double-spawn. Old/missing/unreadable pidfile → null
472
+ * (caller falls through to the normal respawn decision). Never throws.
473
+ */
474
+ async function spawnInProgressStatus(
475
+ agentDir: string,
476
+ io: LifecycleIo,
477
+ ): Promise<EnsureDaemonResult | null> {
478
+ let mtimeMs: number | null = null
479
+ try {
480
+ mtimeMs = await io.statMtimeMs(pidFilePath(agentDir))
481
+ } catch {
482
+ mtimeMs = null
483
+ }
484
+ if (mtimeMs === null) return null
485
+ const age = io.now() - mtimeMs
486
+ // Negative age = clock skew / just-written: treat as fresh.
487
+ if (age > SPAWN_IN_PROGRESS_MAX_AGE_MS) return null
488
+ const deadline = io.now() + SPAWN_IN_PROGRESS_WAIT_MS
489
+ let last: ProbeResult = { alive: false, reason: 'dead-process' }
490
+ while (io.now() < deadline) {
491
+ await io.sleep(POLL_INTERVAL_MS)
492
+ last = await probeDaemon(agentDir, io)
493
+ if (last.alive) return { status: 'already-running', pid: last.pid }
494
+ }
495
+ return { status: 'spawn-in-progress' }
496
+ }
497
+
498
+ export interface EnsureDaemonOptions {
499
+ /**
500
+ * PMR-7B8M: git SHA of the spawner's checkout, handed to a fresh daemon via
501
+ * PI_FLOW_DAEMON_GIT_SHA so it records the SHA in its pidfile. Ignored when
502
+ * a daemon is already running; null/absent outside a git repo.
503
+ */
504
+ gitSha?: string | null
505
+ /**
506
+ * PMR-7B8M rev 2: MAIN-worktree path of the spawner's repo, handed to a
507
+ * fresh daemon via PI_FLOW_DAEMON_GIT_ROOT so it records the repo identity
508
+ * next to the SHA. Sessions only judge staleness when this matches their own
509
+ * main checkout (the daemon is global — one process serves every repo).
510
+ */
511
+ gitRoot?: string | null
512
+ }
513
+
514
+ /**
515
+ * Ensure a live, version-matching daemon. Alive+matching → no-op; stale,
516
+ * mismatched or dead → best-effort SIGTERM of the old pid, then spawn
517
+ * detached with stdio → server.log, unref, and poll ≤2s for the fresh
518
+ * pidfile. Never throws — degradation is a status, not an error.
519
+ */
520
+ export async function ensureDaemon(
521
+ agentDir: string,
522
+ io: LifecycleIo = realIo,
523
+ opts: EnsureDaemonOptions = {},
524
+ ): Promise<EnsureDaemonResult> {
525
+ try {
526
+ const probe = await probeDaemon(agentDir, io)
527
+ if (probe.alive) return { status: 'already-running', pid: probe.pid }
528
+
529
+ // Fresh dead pidfile → spawn-in-progress window (see the anchor note on
530
+ // the constants): never spawn a duplicate, just wait + re-probe.
531
+ if (probe.reason === 'dead-process') {
532
+ const inProgress = await spawnInProgressStatus(agentDir, io)
533
+ if (inProgress !== null) return inProgress
534
+ }
535
+
536
+ // PMR-HRGJ: cross-process claim before any SIGTERM/spawn — with NO
537
+ // pidfile the fresh-dead window below cannot fire, so this lock is the
538
+ // only guard against two concurrent ensureDaemons double-spawning.
539
+ const claim = await acquireSpawnClaim(agentDir, io)
540
+ if (!claim.won) return await contendedStatus(agentDir, io)
541
+ // PMR-HRGJ: keepClaim — on spawn-timeout the claim is deliberately KEPT:
542
+ // the child may still be >2s from writing its pidfile, so releasing
543
+ // would let a contender spawn a duplicate while the slow child is
544
+ // starting. The SPAWN_IN_PROGRESS_MAX_AGE_MS (5s) age bound reclaims the
545
+ // claim eventually — a contender steals it once stale, and until then
546
+ // contention resolves via wait-and-reprobe (contendedStatus).
547
+ let keepClaim = false
548
+ try {
549
+ // PMR-HRGJ: post-claim re-probe — the pre-claim probe above is a
550
+ // STALE OBSERVATION once we hold the claim. Two interleavings:
551
+ // (a) a scheduling/GC stall in the probe→claim gap lets a rival
552
+ // complete claim→spawn→pidfile→release; we then win the now-free
553
+ // lock and would spawn over a live daemon;
554
+ // (b) a claimant SIGKILLed after spawning but before release leaves a
555
+ // dead-claimant lock that we steal while the orphan child is still
556
+ // starting.
557
+ // Re-probing here fully closes (a) and shrinks (b) to the sub-window
558
+ // where the orphan's pidfile has not yet landed. Recording the child
559
+ // pid in the claim was considered and deferred — the child pid is
560
+ // unknowable before spawn().
561
+ const reprobe = await probeDaemon(agentDir, io)
562
+ if (reprobe.alive) {
563
+ return { status: 'already-running', pid: reprobe.pid }
564
+ }
565
+
566
+ // Best-effort SIGTERM of a stale/mismatched daemon; the dead-process
567
+ // case carries a pid too but killing it is pointless — kill() swallows
568
+ // ESRCH either way, so a single unguarded call is fine.
569
+ if (probe.pid !== undefined) {
570
+ io.kill(probe.pid, 'SIGTERM')
571
+ }
572
+
573
+ await io.mkdir(path.join(agentDir, 'pi-flow'))
574
+ const logFd = io.openLogFd(logFilePath(agentDir))
575
+ let child: SpawnedProcess
576
+ try {
577
+ // AIDEV-NOTE: PMR-7B8M — the daemon never runs git itself (DEPENDENCY
578
+ // CONTRACT in server/daemon.ts): the session owns the checkout, so the
579
+ // SHA is resolved spawn-side and passed in via the env, mirroring the
580
+ // PI_FLOW_AGENT_DIR precedent. PMR-7B8M rev 2 adds the repo identity
581
+ // (PI_FLOW_DAEMON_GIT_ROOT) with the identical delete-guard so a
582
+ // polluted parent env can never leak either advisory field.
583
+ const env: NodeJS.ProcessEnv = {
584
+ ...process.env,
585
+ PI_FLOW_AGENT_DIR: agentDir,
586
+ }
587
+ if (typeof opts.gitSha === 'string' && opts.gitSha.length > 0) {
588
+ env.PI_FLOW_DAEMON_GIT_SHA = opts.gitSha
589
+ } else {
590
+ // AIDEV-NOTE: PMR-7B8M ISC-9 — delete, not omit: the ...process.env
591
+ // spread above can carry a stale PI_FLOW_DAEMON_GIT_SHA from the
592
+ // parent env, and a spawn without a resolvable SHA must not inherit
593
+ // it (the pidfile would claim a provenance it does not have).
594
+ delete env.PI_FLOW_DAEMON_GIT_SHA
595
+ }
596
+ if (typeof opts.gitRoot === 'string' && opts.gitRoot.length > 0) {
597
+ env.PI_FLOW_DAEMON_GIT_ROOT = opts.gitRoot
598
+ } else {
599
+ // PMR-7B8M rev 2: same inheritance-leak guard as the SHA above.
600
+ delete env.PI_FLOW_DAEMON_GIT_ROOT
601
+ }
602
+ child = io.spawn(process.execPath, [daemonEntryPath()], {
603
+ detached: true,
604
+ stdio: ['ignore', logFd, logFd],
605
+ env,
606
+ })
607
+ } finally {
608
+ io.closeFd(logFd)
609
+ }
610
+ child.unref()
611
+
612
+ // Bounded readiness poll: the real daemon writes its pidfile right after
613
+ // startup; sleep is injectable so this loop costs nothing in tests.
614
+ const maxPolls = SPAWN_READY_BUDGET_MS / POLL_INTERVAL_MS
615
+ for (let i = 0; i < maxPolls; i += 1) {
616
+ await io.sleep(POLL_INTERVAL_MS)
617
+ const check = await probeDaemon(agentDir, io)
618
+ if (check.alive) return { status: 'spawned', pid: check.pid }
619
+ }
620
+ keepClaim = true
621
+ return { status: 'spawn-timeout' }
622
+ } finally {
623
+ // Release in all exit paths EXCEPT spawn-timeout (keepClaim above);
624
+ // the thrown-error case still lands in the outer catch as
625
+ // spawn-failed. Release is ownership-checked: a stealer's fresh claim
626
+ // must survive our stalled finally.
627
+ if (!keepClaim) {
628
+ await releaseSpawnClaimIfOwned(agentDir, io, claim.at)
629
+ }
630
+ }
631
+ } catch (err) {
632
+ return { status: 'spawn-failed', reason: String(err) }
633
+ }
634
+ }
635
+
636
+ export type RestartDaemonResult =
637
+ | { status: 'restarted'; pid: number }
638
+ | { status: 'restart-failed'; reason: string }
639
+
640
+ // AIDEV-NOTE: PMR-5563 — restartDaemon operates at the VERDICT level, not the
641
+ // ensure level: callers (server/staleness.ts orchestrator) invoke it only
642
+ // after checkDaemonStaleness returned an actionable verdict (stale /
643
+ // unknown-no-gitsha) AND the idle gate passed. ensureDaemon itself cannot do
644
+ // this — its already-running fast path returns before any kill and cannot
645
+ // distinguish a SHA-stale daemon from a fresh one — which is why the restart
646
+ // lives here instead of inside ensureDaemon (plan decision D1). Contract:
647
+ // SIGTERM the stale pid, wait a bounded RESTART_DEATH_WAIT_MS for its death,
648
+ // then funnel through ensureDaemon so the existing spawn-claim protocol
649
+ // serializes concurrent restarts (a loser sees already-running — any live,
650
+ // fresh daemon is a success). Every failure mode degrades to a typed
651
+ // 'restart-failed' reason — never throws; the caller falls back to the
652
+ // manual-kill warning. ensureDaemon itself stays untouched by this seam.
653
+ export async function restartDaemon(
654
+ agentDir: string,
655
+ pid: number,
656
+ opts: EnsureDaemonOptions = {},
657
+ io: LifecycleIo = realIo,
658
+ ): Promise<RestartDaemonResult> {
659
+ io.kill(pid, 'SIGTERM') // real impl swallows ESRCH
660
+ const deadline = io.now() + RESTART_DEATH_WAIT_MS
661
+ while (io.isProcessAlive(pid) && io.now() < deadline) {
662
+ await io.sleep(POLL_INTERVAL_MS)
663
+ }
664
+ if (io.isProcessAlive(pid)) {
665
+ return { status: 'restart-failed', reason: 'old daemon survived SIGTERM' }
666
+ }
667
+ const ensured = await ensureDaemon(agentDir, io, opts)
668
+ if (ensured.status === 'spawned')
669
+ return { status: 'restarted', pid: ensured.pid }
670
+ if (ensured.status === 'already-running')
671
+ return { status: 'restarted', pid: ensured.pid }
672
+ if (ensured.status === 'spawn-timeout') {
673
+ return { status: 'restart-failed', reason: 'spawn timeout' }
674
+ }
675
+ if (ensured.status === 'spawn-failed') {
676
+ return { status: 'restart-failed', reason: ensured.reason }
677
+ }
678
+ return { status: 'restart-failed', reason: 'spawn in progress' }
679
+ }