@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,267 @@
1
+ // AIDEV-NOTE: PMR-XTQQ — pi-flow pending protocol module (durable run
2
+ // server, phase 3). A pending record is the daemon's durable "this run is
3
+ // parked mid-loop and should be re-injected when a session reopens" marker,
4
+ // written to <agentDir>/pi-flow/pending/<ref>.json (sibling of runs/ — the
5
+ // runs dir is ref-keyed journal/projection files, never pending markers).
6
+ //
7
+ // RENAME-FIRST CONTRACT (the no-duplicates guarantee): consumePending
8
+ // renames <ref>.json → <ref>.consumed.json before returning success, and the
9
+ // caller (index.ts, subtask 3.3) only injects `/flow <ref>` after a
10
+ // `{consumed: true}` result. POSIX rename is atomic, so two concurrent
11
+ // consumers race on one rename — exactly one wins, the loser gets ENOENT and
12
+ // returns {consumed:false}. If the post-rename injection throws, consumption
13
+ // already happened: catch + notify the manual `/flow` fallback is correct
14
+ // (a lost injection beats a duplicate loop).
15
+ //
16
+ // "PARKED" DEFINITION: the latest journal `loop-state` snapshot has
17
+ // awaitingOutcome=true AND status='running'. Paused snapshots carry
18
+ // awaitingOutcome=false and are NOT parked (see flow/loop-settle.ts
19
+ // journaling).
20
+ // A stale leftover record (daemon died, run later paused/finished) fails
21
+ // verify and is renamed away with dropped:true — it can never be injected.
22
+ //
23
+ // This module never imports the loop or pi internals: the consumer passes a
24
+ // `verify` closure that reads the journal and answers "is this ref still
25
+ // parked?". writePending/clearPending/sweepConsumed are standalone functions
26
+ // the daemon (subtask 3.2) calls from its serial scan queue.
27
+
28
+ import { promises as fsp } from 'node:fs'
29
+ import path from 'node:path'
30
+ import { type LoopStateRecord, runFileName } from '../run-state.ts'
31
+
32
+ export const PENDING_SCHEMA = 'gtheys.pi-flow.pending.v1'
33
+
34
+ export type PendingPhase = 'plan' | 'implement' | 'validate' | 'feedback'
35
+
36
+ export interface PendingRecord {
37
+ schema: typeof PENDING_SCHEMA
38
+ ref: string
39
+ phase: PendingPhase
40
+ createdAt: string
41
+ sourceAt: string
42
+ }
43
+
44
+ const PENDING_PHASES: readonly PendingPhase[] = [
45
+ 'plan',
46
+ 'implement',
47
+ 'validate',
48
+ 'feedback',
49
+ ]
50
+
51
+ function isRecordObject(value: unknown): value is Record<string, unknown> {
52
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
53
+ }
54
+
55
+ /** Strict string-field check for the record shape. Pure. */
56
+ function hasStringFields(
57
+ obj: Record<string, unknown>,
58
+ keys: readonly string[],
59
+ ): boolean {
60
+ for (const key of keys) {
61
+ if (typeof obj[key] !== 'string') return false
62
+ }
63
+ return true
64
+ }
65
+
66
+ /**
67
+ * Parse a pending record from raw file contents. Strict: the exact schema
68
+ * id, a filename-safe ref, a known phase, ISO-ish strings for both
69
+ * timestamps, and no extra keys. Returns null on any garbage — never throws.
70
+ * Pure.
71
+ */
72
+ export function parsePendingRecord(raw: string): PendingRecord | null {
73
+ let parsed: unknown
74
+ try {
75
+ parsed = JSON.parse(raw)
76
+ } catch {
77
+ return null
78
+ }
79
+ if (!isRecordObject(parsed)) return null
80
+ const keys = Object.keys(parsed)
81
+ if (keys.length !== 5) return null
82
+ if (parsed.schema !== PENDING_SCHEMA) return null
83
+ if (!hasStringFields(parsed, ['ref', 'phase', 'createdAt', 'sourceAt'])) {
84
+ return null
85
+ }
86
+ const ref = parsed.ref as string
87
+ const phase = parsed.phase as string
88
+ // Reuse runFileName's charset rule so a parsed ref can never escape the
89
+ // pending dir even before it hits a path join.
90
+ if (runFileName(ref) === null) return null
91
+ if (!PENDING_PHASES.includes(phase as PendingPhase)) return null
92
+ return {
93
+ schema: PENDING_SCHEMA,
94
+ ref,
95
+ phase: phase as PendingPhase,
96
+ createdAt: parsed.createdAt as string,
97
+ sourceAt: parsed.sourceAt as string,
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Parked check over a loop-state snapshot: awaitingOutcome=true AND
103
+ * status='running'. Paused snapshots are awaitingOutcome=false and do NOT
104
+ * count. Pure. Undefined (no snapshot yet) is not parked.
105
+ */
106
+ export function isParkedLoop(loop: LoopStateRecord | undefined): boolean {
107
+ if (loop === undefined) return false
108
+ return loop.awaitingOutcome === true && loop.status === 'running'
109
+ }
110
+
111
+ export interface PendingPathGuard {
112
+ /** Path components derived from the ref; null on a charset-violating ref. */
113
+ pendingPath: string | null
114
+ consumedPath: string | null
115
+ }
116
+
117
+ /** Derive <ref>.json / <ref>.consumed.json paths under pendingDir. Pure. */
118
+ export function pendingPaths(
119
+ pendingDir: string,
120
+ ref: string,
121
+ ): PendingPathGuard {
122
+ const name = runFileName(ref)
123
+ if (name === null) {
124
+ return { pendingPath: null, consumedPath: null }
125
+ }
126
+ const base = name.slice(0, -'.json'.length)
127
+ return {
128
+ pendingPath: path.join(pendingDir, name),
129
+ consumedPath: path.join(pendingDir, `${base}.consumed.json`),
130
+ }
131
+ }
132
+
133
+ export type ConsumePendingResult =
134
+ | { consumed: true }
135
+ | { consumed: false }
136
+ | { consumed: false; dropped: true }
137
+
138
+ // AIDEV-NOTE: io seam for injectable fs in tests; the exactly-once race test
139
+ // uses the real fs (default io), not fakes.
140
+ export interface PendingIo {
141
+ readFile: (p: string) => Promise<string>
142
+ writeFile: (p: string, data: string) => Promise<void>
143
+ rename: (from: string, to: string) => Promise<void>
144
+ unlink: (p: string) => Promise<void>
145
+ readdir: (p: string) => Promise<string[]>
146
+ mkdir: (dir: string, recursive: true) => Promise<void>
147
+ }
148
+
149
+ export const defaultPendingIo: PendingIo = {
150
+ readFile: (p) => fsp.readFile(p, 'utf8'),
151
+ writeFile: (p, data) => fsp.writeFile(p, data, 'utf8'),
152
+ rename: async (from, to) => {
153
+ await fsp.rename(from, to)
154
+ },
155
+ unlink: (p) => fsp.unlink(p),
156
+ readdir: (p) => fsp.readdir(p),
157
+ mkdir: async (dir, recursive) => {
158
+ await fsp.mkdir(dir, { recursive })
159
+ },
160
+ }
161
+
162
+ /**
163
+ * Consume a pending record for a ref. Ordering:
164
+ * 1. Guard the ref charset (invalid → {consumed:false}, fs untouched).
165
+ * 2. RENAME <ref>.json → <ref>.consumed.json (atomic exactly-once gate;
166
+ * ENOENT → {consumed:false} — someone else won or nothing pending).
167
+ * 3. Read + parse the consumed file; malformed → dropped.
168
+ * 4. `verify(record)` (the caller's journal-closure answering "still
169
+ * parked?") — verify-fail → dropped. Either way the file stays renamed
170
+ * away so a stale record can never be re-injected.
171
+ */
172
+ export async function consumePending(
173
+ pendingDir: string,
174
+ ref: string,
175
+ verify: (record: PendingRecord) => Promise<boolean> | boolean,
176
+ io: PendingIo = defaultPendingIo,
177
+ ): Promise<ConsumePendingResult> {
178
+ const paths = pendingPaths(pendingDir, ref)
179
+ if (paths.pendingPath === null || paths.consumedPath === null) {
180
+ return { consumed: false }
181
+ }
182
+ try {
183
+ await io.rename(paths.pendingPath, paths.consumedPath)
184
+ } catch (err) {
185
+ const code = (err as NodeJS.ErrnoException).code
186
+ if (code === 'ENOENT') return { consumed: false }
187
+ throw err
188
+ }
189
+ let record: PendingRecord | null
190
+ try {
191
+ const raw = await io.readFile(paths.consumedPath)
192
+ record = parsePendingRecord(raw)
193
+ } catch {
194
+ record = null
195
+ }
196
+ if (record === null) {
197
+ return { consumed: false, dropped: true }
198
+ }
199
+ const stillValid = await verify(record)
200
+ if (!stillValid) {
201
+ return { consumed: false, dropped: true }
202
+ }
203
+ return { consumed: true }
204
+ }
205
+
206
+ /**
207
+ * Daemon-side: write a pending record for a ref (idempotent overwrite).
208
+ * Writes to a temp name then renames so a concurrent consumer never reads a
209
+ * torn file. Invalid ref → no-op.
210
+ */
211
+ export async function writePending(
212
+ pendingDir: string,
213
+ record: PendingRecord,
214
+ io: PendingIo = defaultPendingIo,
215
+ ): Promise<void> {
216
+ const paths = pendingPaths(pendingDir, record.ref)
217
+ if (paths.pendingPath === null) return
218
+ await io.mkdir(pendingDir, true)
219
+ const tmpPath = `${paths.pendingPath}.tmp-${process.pid}`
220
+ await io.writeFile(tmpPath, `${JSON.stringify(record, null, 2)}\n`)
221
+ await io.rename(tmpPath, paths.pendingPath)
222
+ }
223
+
224
+ /** Daemon-side: remove a pending marker for a ref (absence is fine). */
225
+ export async function clearPending(
226
+ pendingDir: string,
227
+ ref: string,
228
+ io: PendingIo = defaultPendingIo,
229
+ ): Promise<void> {
230
+ const paths = pendingPaths(pendingDir, ref)
231
+ if (paths.pendingPath === null) return
232
+ try {
233
+ await io.unlink(paths.pendingPath)
234
+ } catch (err) {
235
+ const code = (err as NodeJS.ErrnoException).code
236
+ if (code === 'ENOENT') return
237
+ throw err
238
+ }
239
+ }
240
+
241
+ /**
242
+ * Daemon-side: sweep consumed markers during runs-dir scans. Returns the
243
+ * number of files removed; individual unlink failures (racing consumer, etc.)
244
+ * are skipped, not thrown.
245
+ */
246
+ export async function sweepConsumed(
247
+ pendingDir: string,
248
+ io: PendingIo = defaultPendingIo,
249
+ ): Promise<number> {
250
+ let names: string[]
251
+ try {
252
+ names = await io.readdir(pendingDir)
253
+ } catch {
254
+ return 0
255
+ }
256
+ let swept = 0
257
+ for (const name of names) {
258
+ if (!name.endsWith('.consumed.json')) continue
259
+ try {
260
+ await io.unlink(path.join(pendingDir, name))
261
+ swept += 1
262
+ } catch {
263
+ // raced or vanished — next sweep catches it
264
+ }
265
+ }
266
+ return swept
267
+ }
@@ -0,0 +1,320 @@
1
+ // AIDEV-NOTE: PMR-7B8M rev 1 — session-side daemon staleness check. The daemon
2
+ // records its spawner checkout's SHA in the pidfile; a later session compares
3
+ // that SHA against the MAIN-CHECKOUT HEAD (resolved from any worktree via
4
+ // `git worktree list --porcelain`) with plain string equality:
5
+ // equal → fresh (silent) | different → STALE (warn + restart command)
6
+ // main HEAD unresolvable → unchecked/no-repo, SILENT (nothing to compare).
7
+ // Ancestry (`git merge-base --is-ancestor`) was REMOVED here: the 1.5 smoke
8
+ // proved it inverted — when main moves FORWARD (the Nov 26 incident: daemon at
9
+ // the Nov 21 SHA, HEAD at a descendant Nov 24 SHA) the daemon SHA stays an
10
+ // ancestor → "fresh" → silent. Equality against main HEAD catches exactly that.
11
+ // A pidfile without gitSha (daemon predates PMR-7B8M) is unknown + WARN
12
+ // "restart recommended". Staleness itself never spawns a daemon — the check
13
+ // stays a read-only verdict. Since PMR-5563, handleDaemonStaleness auto-
14
+ // restarts an actionable verdict (stale / no-gitsha) through the injected
15
+ // restart seam (restartDaemon in lifecycle.ts) — but ONLY when the idle gate
16
+ // passes (no active flow run); a busy daemon or a failed restart keeps
17
+ // today's warning. The protocol-version pin is unchanged
18
+ // (EXPECTED_SERVER_PROTOCOL_VERSION stays untouched).
19
+ // AIDEV-NOTE: PMR-5563 — contract change from PMR-7B8M's "Staleness NEVER
20
+ // respawns": the restart lives ONLY in handleDaemonStaleness, behind the
21
+ // injectable `restart` closure, gated on idle; checkDaemonStaleness and
22
+ // daemonStalenessMessage remain read-only and byte-identical.
23
+ //
24
+ // AIDEV-NOTE: PMR-7B8M rev 2 — the daemon is ONE GLOBAL process (a single
25
+ // ~/.pi/agent/pi-flow/server.pid serves every repo: the live runs dir holds
26
+ // work-mode AA-*/HML-* runs next to personal PMR-* ones). A bare SHA therefore
27
+ // says nothing about THIS repo: a /flow start in repo A + any later session in
28
+ // repo B was a permanent false "daemon is running stale code — kill <pid>"
29
+ // warning for a healthy daemon (validate review P1, the rev-1 blocker). Rev 0
30
+ // guarded this by accident (merge-base exits 128 for an object absent from the
31
+ // repo → unknown/git-error → silent); rev 1's plain equality dropped it.
32
+ // The pidfile now carries a second advisory field, gitRoot — the MAIN-worktree
33
+ // path of the spawning repo — surfaced on ProbeResult as `mainWorktree` (PMR-8620:
34
+ // the on-disk key keeps its name for upgrade compatibility, but it is NOT the
35
+ // journal run-input gitRoot, which is the session's own worktree root).
36
+ // path of the spawning repo — and the verdict checks repo identity BEFORE the
37
+ // SHA verdict (see checkDaemonStaleness).
38
+ //
39
+ // Session-side ONLY: git runs exclusively through the injected StalenessExec
40
+ // seam (pi.exec), so this module imports no child_process and the daemon never
41
+ // loads it. Every seam is never-throws (null on failure), like
42
+ // resolveSessionRepoRoot in herdr/sync.ts.
43
+ import {
44
+ type ProbeResult,
45
+ probeDaemon,
46
+ type RestartDaemonResult,
47
+ } from './lifecycle.ts'
48
+
49
+ /** The MAIN worktree of a repo: its path plus the HEAD commit recorded there.
50
+ * Both halves come from one `git worktree list --porcelain` call, so the path
51
+ * is comparable across sessions by plain string equality. */
52
+ export interface MainCheckout {
53
+ path: string
54
+ headSha: string
55
+ }
56
+
57
+ export type DaemonStaleness =
58
+ | { kind: 'fresh' }
59
+ | { kind: 'stale'; pid: number; daemonSha: string; mainHeadSha: string }
60
+ | { kind: 'unknown'; pid: number; reason: 'no-gitsha' }
61
+ | {
62
+ kind: 'unchecked'
63
+ reason:
64
+ | 'daemon-not-running'
65
+ | 'no-repo'
66
+ /** pidfile has a SHA but no repo identity (intermediate build) */
67
+ | 'no-gitroot'
68
+ /** the global daemon was spawned from a different repo */
69
+ | 'other-repo'
70
+ }
71
+
72
+ /** Narrow structural slice of pi.exec (ExecResult.code carries the exit
73
+ * status; pi.exec does not throw on non-zero exit but may throw on spawn
74
+ * failure — every seam below wraps that). */
75
+ export type StalenessExec = (
76
+ command: string,
77
+ args: string[],
78
+ options?: { cwd?: string },
79
+ ) => Promise<{ stdout: string; code: number }>
80
+
81
+ export interface StalenessDeps {
82
+ probe: () => Promise<ProbeResult>
83
+ mainCheckout: () => Promise<MainCheckout | null>
84
+ }
85
+
86
+ /**
87
+ * Verdict for the current session against the running daemon. Order matters
88
+ * and is pinned by test/server-staleness.test.ts:
89
+ *
90
+ * 1. main checkout unresolvable → unchecked/no-repo (silent)
91
+ * 2. daemon not alive → unchecked/daemon-not-running (silent)
92
+ * 3. pidfile has no usable gitSha → unknown/no-gitsha (**warns**)
93
+ * 4. pidfile has no usable gitRoot (probe.mainWorktree) → unchecked/no-gitroot (silent)
94
+ * 5. probe.mainWorktree ≠ this main worktree → unchecked/other-repo (silent)
95
+ * 6. gitSha === main.headSha → fresh, else stale
96
+ *
97
+ * AIDEV-NOTE: PMR-7B8M rev 2 — repo identity is checked BEFORE the SHA verdict
98
+ * because the SHA alone is meaningless for a global daemon (review P1).
99
+ *
100
+ * AIDEV-NOTE: PMR-7B8M rev 2 — why no-gitsha WARNS but no-gitroot stays
101
+ * SILENT: a pidfile with neither field is the known migration case (a daemon
102
+ * started by a build that predates this feature, on this machine) and telling
103
+ * the user to restart it is actionable. A pidfile with a SHA but NO repo
104
+ * identity was written by an intermediate build (rev 1 shipped gitSha without
105
+ * gitRoot); its SHA could belong to ANY repo, so warning would re-create the
106
+ * exact cross-repo false positive this revision fixes. Never guess.
107
+ */
108
+ export async function checkDaemonStaleness(
109
+ deps: StalenessDeps,
110
+ ): Promise<DaemonStaleness> {
111
+ const main = await deps.mainCheckout()
112
+ if (main === null) return { kind: 'unchecked', reason: 'no-repo' }
113
+ const probe = await deps.probe()
114
+ if (!probe.alive) return { kind: 'unchecked', reason: 'daemon-not-running' }
115
+ // AIDEV-NOTE: PMR-7B8M — empty string counts as absent: parsePidfile keeps
116
+ // any string, and an empty SHA could never equal a real main HEAD, so it is
117
+ // the same "no provenance" case. An unusable SHA is the actionable warning,
118
+ // never a silent one.
119
+ if (probe.gitSha === undefined || probe.gitSha === '') {
120
+ return { kind: 'unknown', pid: probe.pid, reason: 'no-gitsha' }
121
+ }
122
+ // Rev 2: same "empty counts as absent" posture for the repo identity, but
123
+ // the verdict is silent (see the AIDEV-NOTE above). PMR-8620: the probe field
124
+ // is `mainWorktree` — the MAIN worktree of the spawning repo, which is what
125
+ // `main.path` is too; a session's own worktree root would never match.
126
+ if (probe.mainWorktree === undefined || probe.mainWorktree === '') {
127
+ return { kind: 'unchecked', reason: 'no-gitroot' }
128
+ }
129
+ // Rev 2: plain string equality on paths is enough — both sides come from the
130
+ // same git plumbing (`worktree list` prints absolute, un-normalised paths),
131
+ // so a symlinked or trailing-slash variant would have to differ in git's own
132
+ // output, not ours.
133
+ if (probe.mainWorktree !== main.path) {
134
+ return { kind: 'unchecked', reason: 'other-repo' }
135
+ }
136
+ // Rev 1: string equality, not ancestry. A worktree session stays quiet while
137
+ // main is unchanged (its own commits never move main HEAD); a daemon spawned
138
+ // from an unmerged branch warns until merged or restarted — accepted, the
139
+ // daemon really does run unmerged code.
140
+ if (probe.gitSha === main.headSha) return { kind: 'fresh' }
141
+ return {
142
+ kind: 'stale',
143
+ pid: probe.pid,
144
+ daemonSha: probe.gitSha,
145
+ mainHeadSha: main.headSha,
146
+ }
147
+ }
148
+
149
+ /**
150
+ * Warning text (no prefix — callers add `pi-flow: `), or null when there is
151
+ * nothing to act on. Single source for ALL three surfaces (session_start,
152
+ * /flow start, /flow-reconcile-push) so they cannot drift.
153
+ * AIDEV-NOTE: PMR-7B8M rev 2 — unchanged: every new silent verdict is an
154
+ * 'unchecked' kind, which already maps to null here.
155
+ */
156
+ export function daemonStalenessMessage(st: DaemonStaleness): string | null {
157
+ if (st.kind === 'stale') {
158
+ return `daemon is running stale code — started from ${st.daemonSha.slice(0, 7)}, the main checkout is at ${st.mainHeadSha.slice(0, 7)}. Restart: kill ${st.pid} — the daemon is re-ensured at the next /flow start.`
159
+ }
160
+ if (st.kind === 'unknown' && st.reason === 'no-gitsha') {
161
+ return `daemon predates staleness tracking (pidfile has no git SHA) — restart recommended: kill ${st.pid} — the daemon is re-ensured at the next /flow start.`
162
+ }
163
+ return null
164
+ }
165
+
166
+ export interface HandleStalenessDeps extends StalenessDeps {
167
+ /** Busy gate — false means a live flow run needs the daemon: warn, never restart. */
168
+ isIdle: () => Promise<boolean>
169
+ /** Injectable restart seam (PMR-5563): SIGTERM + re-ensure. Unit tests stub this. */
170
+ restart: (pid: number) => Promise<RestartDaemonResult>
171
+ }
172
+
173
+ // AIDEV-NOTE: PMR-5563 — the staleness orchestrator: verdict → idle gate →
174
+ // restart-or-warn, EXACTLY ONE notify per invocation. The check itself stays
175
+ // read-only (never spawns); the restart happens only here, behind the
176
+ // injectable `restart` seam (restartDaemon in server/lifecycle.ts). Every
177
+ // seam failure (isIdle throws, restart throws, restart-failed) and a busy
178
+ // daemon degrade to the PMR-7B8M manual-kill warning — the warn-only probe's
179
+ // never-throws posture carries over. Call sites: index.ts session_start and
180
+ // /flow start already-running.
181
+ export async function handleDaemonStaleness(
182
+ deps: HandleStalenessDeps,
183
+ notify: (message: string, level: 'info' | 'warning') => void,
184
+ ): Promise<void> {
185
+ const staleness = await checkDaemonStaleness(deps)
186
+ const warnText = daemonStalenessMessage(staleness)
187
+ if (warnText === null) return // fresh + unchecked stay silent (order semantics unchanged)
188
+ if (staleness.kind !== 'stale' && staleness.kind !== 'unknown') {
189
+ // Unreachable today: a non-null warnText only comes from stale /
190
+ // unknown(no-gitsha), and both carry a pid. Explicit kind check (no cast)
191
+ // narrows `staleness.pid`; if the message mapping ever drifts, the
192
+ // warning still fires and the restart is skipped — never silent.
193
+ notify(`pi-flow: ${warnText}`, 'warning')
194
+ return
195
+ }
196
+ let idle = false
197
+ try {
198
+ idle = await deps.isIdle()
199
+ } catch {
200
+ idle = false // never-throws posture: a throwing seam degrades to the warning
201
+ }
202
+ if (!idle) {
203
+ notify(`pi-flow: ${warnText}`, 'warning')
204
+ return
205
+ }
206
+ let result: RestartDaemonResult
207
+ try {
208
+ result = await deps.restart(staleness.pid)
209
+ } catch {
210
+ notify(`pi-flow: ${warnText}`, 'warning')
211
+ return
212
+ }
213
+ if (result.status === 'restarted') {
214
+ notify(`pi-flow: ${daemonRestartedMessage(staleness, result.pid)}`, 'info')
215
+ return
216
+ }
217
+ notify(`pi-flow: ${warnText}`, 'warning')
218
+ }
219
+
220
+ /** Info note after a successful auto-restart (no prefix — callers add
221
+ * `pi-flow: `). Total over every kind: only stale / unknown(no-gitsha) are
222
+ * reachable from the orchestrator; other kinds fall through to the
223
+ * pre-tracking text so the function can never return undefined. */
224
+ export function daemonRestartedMessage(
225
+ st: DaemonStaleness,
226
+ newPid: number,
227
+ ): string {
228
+ if (st.kind === 'stale') {
229
+ return `daemon was running stale code — started from ${st.daemonSha.slice(0, 7)}, the main checkout is at ${st.mainHeadSha.slice(0, 7)}. No active flow runs — restarted automatically (pid ${newPid}).`
230
+ }
231
+ return `daemon predates staleness tracking (pidfile has no git SHA) — no active flow runs — restarted automatically (pid ${newPid}).`
232
+ }
233
+
234
+ /**
235
+ * The session's own checkout HEAD as 40-hex, or null (not a repo, git
236
+ * broken/missing, unexpected output). Never throws.
237
+ * AIDEV-NOTE: PMR-7B8M — kept for the SPAWN-side provenance only (index.ts
238
+ * /flow start records the spawning session's own HEAD in the pidfile); the
239
+ * staleness verdict itself compares against the main checkout, see
240
+ * resolveMainCheckout. */
241
+ export async function resolveHeadSha(
242
+ exec: StalenessExec,
243
+ cwd?: string,
244
+ ): Promise<string | null> {
245
+ const options: { cwd?: string } = {}
246
+ if (cwd !== undefined) options.cwd = cwd
247
+ try {
248
+ const result = await exec('git', ['rev-parse', 'HEAD'], options)
249
+ const sha = result.stdout.trim()
250
+ if (!/^[0-9a-f]{40}$/.test(sha)) return null
251
+ return sha
252
+ } catch {
253
+ return null
254
+ }
255
+ }
256
+
257
+ /**
258
+ * The MAIN worktree of the repo containing `cwd`: its path and HEAD sha, or
259
+ * null. Never throws.
260
+ *
261
+ * AIDEV-NOTE: PMR-7B8M rev 1 — `git worktree list --porcelain` always lists
262
+ * the main worktree FIRST (git-worktree docs); blocks are separated by blank
263
+ * lines and each starts with a `worktree <path>` line followed by its
264
+ * `HEAD <sha>` line. So the answer is the first `worktree`/`HEAD` pair before
265
+ * the first blank line — ONE call yields both halves (rev 2), which is what
266
+ * makes the path comparison sound: the recorded gitRoot and the compared
267
+ * main.path are produced by identical plumbing.
268
+ * AIDEV-NOTE: PMR-7B8M rev 2 — an unborn HEAD (fresh repo, no commits) prints
269
+ * no `HEAD` line at all → null → the verdict is unchecked/no-repo, silent. Same
270
+ * for a non-repo, a broken git, an empty path, or a non-hex SHA — we never
271
+ * guess, never false-positive.
272
+ */
273
+ export async function resolveMainCheckout(
274
+ exec: StalenessExec,
275
+ cwd?: string,
276
+ ): Promise<MainCheckout | null> {
277
+ const options: { cwd?: string } = {}
278
+ if (cwd !== undefined) options.cwd = cwd
279
+ try {
280
+ const result = await exec(
281
+ 'git',
282
+ ['worktree', 'list', '--porcelain'],
283
+ options,
284
+ )
285
+ if (result.code !== 0) return null
286
+ let mainPath: string | null = null
287
+ let headSha: string | null = null
288
+ for (const line of result.stdout.split('\n')) {
289
+ // Blank line ends the first (main) block.
290
+ if (line === '') break
291
+ if (mainPath === null && line.startsWith('worktree ')) {
292
+ mainPath = line.slice('worktree '.length).trim()
293
+ continue
294
+ }
295
+ if (headSha === null && line.startsWith('HEAD ')) {
296
+ headSha = line.slice('HEAD '.length).trim()
297
+ }
298
+ }
299
+ if (mainPath === null || mainPath === '') return null
300
+ if (headSha === null || !/^[0-9a-f]{40}$/.test(headSha)) return null
301
+ return { path: mainPath, headSha }
302
+ } catch {
303
+ return null
304
+ }
305
+ }
306
+
307
+ /** Session wiring: deps from a pi.exec-shaped seam. `cwd` is the SESSION cwd —
308
+ * AIDEV-NOTE: PMR-7B8M rev 2 (review P2) — callers must pass it explicitly;
309
+ * omitting it lets pi.exec fall back to pi's load-time cwd, which judges a
310
+ * different repo than the session is actually in. */
311
+ export function sessionStalenessDeps(
312
+ exec: StalenessExec,
313
+ agentDir: string,
314
+ cwd?: string,
315
+ ): StalenessDeps {
316
+ return {
317
+ probe: () => probeDaemon(agentDir),
318
+ mainCheckout: () => resolveMainCheckout(exec, cwd),
319
+ }
320
+ }
@@ -0,0 +1,86 @@
1
+ // AIDEV-NOTE: PMR-XTQQ — the single seam every journal writer routes through.
2
+ // record() probes daemon liveness PER WRITE (plan decision 3: writes are
3
+ // phase-transition-frequency, never hot — no caching to invalidate) and hands
4
+ // projection ownership to the daemon by routing journal-only while it is
5
+ // alive; when absent (or runServer.enabled = false, plan decision 9) it falls
6
+ // back to today's full recordRunEvent path. Every write stays best-effort
7
+ // (the journal()/journalOnly() convention in index.ts): journal failures must
8
+ // never break a flow phase — aven labels remain the gate source of truth.
9
+ // Both methods report append success so callers such as the answer-time review
10
+ // stamp can warn immediately; fire-and-forget callers may keep ignoring it.
11
+ import {
12
+ type FlowRunEvent,
13
+ recordRunEvent,
14
+ recordRunEventJournalOnly,
15
+ } from '../run-state.ts'
16
+ import { probeDaemon } from './lifecycle.ts'
17
+
18
+ /** Per-write liveness check. Throwing probes count as "daemon absent". */
19
+ export type DaemonAliveProbe = () => Promise<boolean>
20
+
21
+ export interface EventWriter {
22
+ /** Route by liveness: journal-only while the daemon owns the projection.
23
+ * Returns true when the event reached the journal file, false when the
24
+ * write failed (best-effort: NEVER throws). flow_submit surfaces the
25
+ * boolean as `journaled`, so the journaled:false contract holds in
26
+ * production, not just for test fakes. */
27
+ record(event: FlowRunEvent): Promise<boolean>
28
+ /** Always journal-only (nested spawns, non-main processes). Returns false
29
+ * when the append failed; callers that use the void context may ignore it. */
30
+ recordJournalOnly(event: FlowRunEvent): Promise<boolean>
31
+ }
32
+
33
+ /**
34
+ * Real probe over probeDaemon: pidfile liveness + version match, gated by the
35
+ * runServer.enabled kill switch (disabled = always absent → full-writer
36
+ * fallback permanently, and ensureDaemon never spawns).
37
+ */
38
+ export function createDaemonAliveProbe(
39
+ agentDir: string,
40
+ isEnabled: () => boolean = () => true,
41
+ ): DaemonAliveProbe {
42
+ return async () => {
43
+ if (!isEnabled()) return false
44
+ const probe = await probeDaemon(agentDir)
45
+ return probe.alive
46
+ }
47
+ }
48
+
49
+ export function createEventWriter(
50
+ agentDir: string,
51
+ isDaemonAlive: DaemonAliveProbe,
52
+ ): EventWriter {
53
+ const journalOnlyWrite = async (event: FlowRunEvent): Promise<boolean> => {
54
+ try {
55
+ await recordRunEventJournalOnly(agentDir, event)
56
+ return true
57
+ } catch {
58
+ // best-effort by design — but the outcome is REPORTED, so callers can
59
+ // surface journaled:false (production-reachable contract).
60
+ return false
61
+ }
62
+ }
63
+ return {
64
+ record: async (event) => {
65
+ let alive: boolean
66
+ try {
67
+ alive = await isDaemonAlive()
68
+ } catch {
69
+ alive = false
70
+ }
71
+ if (alive) {
72
+ return journalOnlyWrite(event)
73
+ }
74
+ try {
75
+ await recordRunEvent(agentDir, event)
76
+ return true
77
+ } catch {
78
+ // best-effort by design — never break the phase, but report failure.
79
+ return false
80
+ }
81
+ },
82
+ recordJournalOnly: (event) => {
83
+ return journalOnlyWrite(event)
84
+ },
85
+ }
86
+ }