@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
package/run-state.ts ADDED
@@ -0,0 +1,2046 @@
1
+ // AIDEV-NOTE: Flow run-state journal (PMR follow-up, ported from
2
+ // pi-workflows' "durable run state" idea). Aven labels stay the gate source
3
+ // of truth; this journal is the *evidence record* — append-only JSONL events
4
+ // plus a current-state projection, written under
5
+ // getAgentDir()/pi-flow/runs/<ref>.json (+ .journal.jsonl).
6
+ // The Herdr flow viewer renders the projection WITHOUT touching aven.
7
+
8
+ import { promises as fs } from 'node:fs'
9
+ import path from 'node:path'
10
+ import { getAgentDir } from '@earendil-works/pi-coding-agent'
11
+ import type { AnswerChoice } from './aven/client.ts'
12
+ import type { FlowReason, FlowState } from './flow/vocabulary.ts'
13
+ import { FLOW_REASONS, FLOW_STATES } from './flow/vocabulary.ts'
14
+ import { isFullSha, sha256Hex } from './validate/gate-target.ts'
15
+ import type { WorkMode } from './work-mode.ts'
16
+
17
+ // AIDEV-NOTE: PMR-Z2K7 — 'research' left the flow lifecycle (PIV); old
18
+ // journals containing research phases fail isFlowRunState and are rebuilt
19
+ // from the journal, whose unknown events are simply ignored by projection.
20
+ export type FlowPhase = 'plan' | 'implement' | 'validate' | 'feedback'
21
+
22
+ // AIDEV-NOTE: PMR-6EEW gate integrity — journal event kinds for pinned gate
23
+ // targets and the decisions that cite them. gate-target is recorded when a
24
+ // gate spawns (pin at spawn); gate-decision when its verdict is accepted,
25
+ // rejected or invalidated (echo missing / target mismatch / stale).
26
+ export type GateJournalKind =
27
+ | 'review'
28
+ | 'deviation'
29
+ | 'code-review'
30
+ | 'spec-review'
31
+
32
+ export type GateDecisionStatus =
33
+ | 'pass'
34
+ | 'fail'
35
+ | 'echo-missing'
36
+ | 'target-mismatch'
37
+ | 'stale'
38
+
39
+ // AIDEV-NOTE: PMR-4S6V — command receipts: one per COMMITTED gate
40
+ // transition; duplicates adopt the stored receipt instead of repeating the
41
+ // transition. BEST-EFFORT by design: missing/corrupt/torn receipts degrade
42
+ // to label checks + suite re-run; aven labels stay the gate of record.
43
+ // AIDEV-NOTE: PMR-2HFC/PMR-XTQQ — the flow_run_attempt budget WAS
44
+ // non-durable (PMR-2HFC); it is durable as of PMR-XTQQ 4.2: the loop-level
45
+ // blockerRetries budget is durable since phase 2 (loop-state snapshots +
46
+ // resume seeding) and the attempt ledger is durable since 4.2 —
47
+ // tools/run-attempt.ts reads/journals attempt-record events (the projection
48
+ // half landed in phase 4) through the writer seam.
49
+ // AIDEV-NOTE: PMR-XTQQ 5.1 — 'code_review' joined the receipt commands: the
50
+ // code_review tool recorded a headSha-pinned receipt after a HUMAN pass —
51
+ // the durable twin of the (since-deleted) humanReviewPassed marker.
52
+ // AIDEV-NOTE: PMR-V31Z — 4.1 killed the flow_land reader of both; 7.2
53
+ // deleted the code_review WRITE side and the marker too. 'code_review'
54
+ // STAYS in the union: old run journals legitimately contain code_review
55
+ // receipts and projections must keep validating them (receipts are
56
+ // immutable history). No current writer produces them.
57
+ // AIDEV-NOTE: PMR-CD46 — 'spec_approve' joins the receipt commands: the
58
+ // spec_approve tool records a target='plan' receipt after a successful
59
+ // approval and adopts it on duplicate calls (single-use dedup).
60
+ export type ReceiptCommand =
61
+ | 'flow_land'
62
+ | 'flow_phase_complete'
63
+ | 'code_review'
64
+ | 'spec_approve'
65
+
66
+ const RECEIPT_COMMANDS: readonly ReceiptCommand[] = [
67
+ 'flow_land',
68
+ 'flow_phase_complete',
69
+ 'code_review',
70
+ 'spec_approve',
71
+ ]
72
+
73
+ // AIDEV-NOTE: PMR-VDVJ — kinds of side-effecting actions that must declare
74
+ // themselves in the run journal BEFORE they may run (see effect-declaration).
75
+ // PMR-V31Z 6.1 retired 'merge-main' and 'rebase-flow' with the merge-main
76
+ // landing route and the sanctioned-rebase subsystem: the flow delivers via
77
+ // its GitHub PR (flow_land), so the vocabulary is exactly what flow_land and
78
+ // the worktree tools declare. Old journals carrying retired declarations are
79
+ // tolerated (see the applyEvent effect-declaration guard and the
80
+ // legacy-journal pins in test/run-state.test.ts).
81
+ export type EffectKind =
82
+ | 'git-push'
83
+ | 'gh-pr-create'
84
+ | 'worktree-create'
85
+ | 'worktree-remove'
86
+ | 'workspace-close'
87
+
88
+ // Exported for flow/effect-gate.ts (PMR-VDVJ phase 2) to mirror the union.
89
+ export const EFFECT_KINDS: readonly EffectKind[] = [
90
+ 'git-push',
91
+ 'gh-pr-create',
92
+ 'worktree-create',
93
+ 'worktree-remove',
94
+ 'workspace-close',
95
+ ]
96
+
97
+ export interface CommandReceiptRecord {
98
+ command: ReceiptCommand
99
+ target: string
100
+ headSha?: string
101
+ status: 'ok'
102
+ at: string
103
+ }
104
+
105
+ // AIDEV-NOTE: PMR-VDVJ — one per declared side-effecting action, idempotent
106
+ // by effectId (deterministic hash of ref|effect|command|headSha).
107
+ export interface EffectDeclarationRecord {
108
+ effect: EffectKind
109
+ effectId: string
110
+ command: string
111
+ recipe: string[]
112
+ headSha?: string
113
+ at: string
114
+ }
115
+
116
+ export type FlowRunEvent =
117
+ | {
118
+ kind: 'run-start'
119
+ at: string
120
+ ref: string
121
+ mode: 'work' | 'personal'
122
+ /** Ref the run is tracked by (Jira key in work mode); absent = `ref`. */
123
+ trackRef?: string
124
+ /**
125
+ * AIDEV-NOTE: PMR-9DZ0 — optional, sanitized ticket title (single line,
126
+ * <=120 chars, control chars stripped) journaled at run-start so the
127
+ * Grafana dashboards can show "REF — title" next to every ref. Additive
128
+ * only: runTracking/applyEvent/projectRunState never read it (pinned by
129
+ * test/run-state-tracking.test.ts), so a title-carrying event projects
130
+ * identically to a title-less one. The key is OMITTED (never written as
131
+ * undefined) when no title resolved, so old journals and title-less runs
132
+ * are byte-identical. Resolve with run-title.ts at the index.ts write
133
+ * seam; render is Phase 2 (flow/run-health.ts). */
134
+ title?: string
135
+ /**
136
+ * AIDEV-NOTE: PMR-N0D5 — oneshot-ness of the ticket AT run-start,
137
+ * snapshotted from the aven labels so mid-run label mutation cannot
138
+ * mint the oneshot receipt-gate exemption (journal-first provenance:
139
+ * readOneshotSnapshot). Additive only — the projection ignores it (the
140
+ * applyEvent run-start fold builds its state from fixed fields), and
141
+ * the key is OMITTED when false so non-oneshot run-start lines stay
142
+ * byte-identical to the pre-PMR-N0D5 shape. ABSENT means NOT oneshot
143
+ * at start, for old journals and new non-oneshot runs alike. */
144
+ oneshot?: boolean
145
+ }
146
+ | {
147
+ kind: 'phase-start'
148
+ at: string
149
+ ref: string
150
+ phase: FlowPhase
151
+ }
152
+ | {
153
+ kind: 'phase-complete'
154
+ at: string
155
+ ref: string
156
+ phase: FlowPhase
157
+ label: string
158
+ }
159
+ | {
160
+ kind: 'gate-target'
161
+ at: string
162
+ ref: string
163
+ gate: GateJournalKind
164
+ targetId: string
165
+ baseSha: string
166
+ headSha: string
167
+ diffSha256: string
168
+ }
169
+ | {
170
+ kind: 'gate-decision'
171
+ at: string
172
+ ref: string
173
+ gate: GateJournalKind
174
+ targetId: string
175
+ status: GateDecisionStatus
176
+ }
177
+ | {
178
+ /**
179
+ * AIDEV-NOTE: PMR-4S6V — command receipt: one per COMMITTED gate
180
+ * transition. The flow_run_attempt ledger projection landed in phase 4
181
+ * (attempt-record kind + `attempts` projection); the tool-side durable
182
+ * ledger (tools/run-attempt.ts) landed in PMR-XTQQ 4.2.
183
+ */
184
+ kind: 'command-receipt'
185
+ at: string
186
+ ref: string
187
+ command: ReceiptCommand
188
+ /** Phase name for flow_phase_complete; landing target 'pr' for flow_land. */
189
+ target: string
190
+ /** Worktree HEAD when the transition committed; flow_land adopts only on an exact match. */
191
+ headSha?: string
192
+ status: 'ok'
193
+ }
194
+ | {
195
+ /** AIDEV-NOTE: PMR-6EEW per-subtask ranges — subtask → commits map */
196
+ kind: 'subtask-ranges'
197
+ at: string
198
+ ref: string
199
+ gate: GateJournalKind
200
+ baseSha: string
201
+ headSha: string
202
+ bySubtask: Array<{ subtask: string; commits: string[] }>
203
+ unattributed: string[]
204
+ }
205
+ | {
206
+ /**
207
+ * AIDEV-NOTE: PMR-R5VB — a human's raw gate answer (approve/reject;
208
+ * the deleted review gate also wrote pass/fail) recorded journal-only
209
+ * by index.ts's journalOnly helper. The projection keeps the LATEST
210
+ * answer per gate. Journal kinds the reader doesn't know are ignored
211
+ * by design (PMR-Z2K7): old readers skip 'gate-answer' and new readers
212
+ * replay old journals fine.
213
+ */
214
+ kind: 'gate-answer'
215
+ at: string
216
+ ref: string
217
+ gate: Extract<GateJournalKind, 'spec-review' | 'code-review'>
218
+ choice: JournalAnswerChoice
219
+ /**
220
+ * AIDEV-NOTE: PMR-N0D5 — plan-revision binding for spec approve
221
+ * answers: the sha256 of the plan file at the ticket's plan-path,
222
+ * hashed at answer time and journaled WITH the answer, so spec_approve
223
+ * and the plan receipt gate can refuse a stale answer after the plan
224
+ * changed (recovery: re-run /flow answer). Optional so pre-PMR-N0D5
225
+ * journals stay valid; applyEvent copies it only when it is a
226
+ * non-empty string (lenient-parse drift protection), and review-gate
227
+ * answers never carry it. */
228
+ planRevision?: string
229
+ }
230
+ | {
231
+ /**
232
+ * AIDEV-NOTE: main-session cost attribution — the main pi session file
233
+ * active when a phase started. /flow-cost splits this file's usage
234
+ * across phases by journal timestamps (workers are attributed via
235
+ * their spawn notes; the main session was never counted before).
236
+ */
237
+ kind: 'main-session'
238
+ at: string
239
+ ref: string
240
+ sessionFile: string
241
+ }
242
+ | {
243
+ /**
244
+ * AIDEV-NOTE: PMR-C998 — journal-only spawn evidence. Carries the
245
+ * SpawnRecord fields needed by /flow-cost and the flow viewer to
246
+ * attribute child-worker cost. The field is named `spawnKind` (not
247
+ * `kind`) so it does not clash with the event-kind discriminant.
248
+ * Deliberately NO `phase` field: phase annotation stays read-time
249
+ * (derived from journal timestamps by the single derivation path shared
250
+ * by both sources), never write-time. Journal-only like 'main-session'
251
+ * — see isJournalOnlyEvent.
252
+ */
253
+ kind: 'spawn-record'
254
+ at: string
255
+ ref: string
256
+ childId: string
257
+ name: string
258
+ spawnKind: 'spawn' | 'resume' | 'reattach'
259
+ subtask?: string
260
+ sessionFile?: string
261
+ }
262
+ | {
263
+ /**
264
+ * AIDEV-NOTE: PMR-C998 — journal-only append-only step evidence
265
+ * (submissions), flattened StepOutputEventPayload fields. Never
266
+ * deduped (each submission is evidence) and never projected
267
+ * (advisory-only; old readers ignore unknown kinds — PMR-Z2K7).
268
+ * `headShaVerified` is journaled verification state: surfaced to
269
+ * consumers, never silently accepted as truth.
270
+ */
271
+ kind: 'step-output'
272
+ at: string
273
+ ref: string
274
+ phase: FlowPhase
275
+ step: string
276
+ ok?: boolean
277
+ detail?: string
278
+ planPath?: string
279
+ subtaskRefs?: string[]
280
+ command?: string
281
+ passed?: boolean
282
+ headSha?: string
283
+ headShaVerified?: boolean
284
+ prNumber?: number
285
+ prUrl?: string
286
+ gateTargetIds?: string[]
287
+ prMerged?: boolean
288
+ }
289
+ | {
290
+ /**
291
+ * AIDEV-NOTE: PMR-ZV9Y 1.1 — v2 state-machine transition (PROJECTED).
292
+ * `state`/`reason` are closed-enum values from flow/vocabulary.ts; an
293
+ * out-of-vocabulary value is IGNORED by applyEvent but the journal line
294
+ * is still kept (recordRunEvent never drops a v2 evidence line — see
295
+ * the lenient-parse note above applyEvent). `reason` is absent or ''
296
+ * when the state carries none (running/done/stale); the projection
297
+ * always materialises '' so label math never sees undefined.
298
+ * This does NOT replace LoopRunStatus: 'loop-state' stays the v1
299
+ * resume/pending-protocol record, v2 state is derived alongside it
300
+ * (ISC-A-2 — v2 state is DERIVED, never a rename).
301
+ */
302
+ kind: 'state-change'
303
+ at: string
304
+ ref: string
305
+ state: FlowState
306
+ /** Closed-enum reason; absent or '' when the state carries none. */
307
+ reason?: FlowReason | ''
308
+ }
309
+ | {
310
+ /**
311
+ * AIDEV-NOTE: PMR-ZV9Y 1.1 — v2 step boundary evidence (JOURNAL-ONLY,
312
+ * like 'step-output'). `step` is a registered name from flow/steps.ts and
313
+ * `phase` the phase it belongs to. Journal-only on purpose: the projection
314
+ * models the run, not in-flight steps — phase 3 derives `pi_flow_step`
315
+ * and `pi_flow_step_seconds` by scanning the journal windows.
316
+ */
317
+ kind: 'step-start'
318
+ at: string
319
+ ref: string
320
+ phase: FlowPhase
321
+ step: string
322
+ }
323
+ | {
324
+ /** AIDEV-NOTE: PMR-ZV9Y 1.1 — closes a 'step-start' (journal-only). */
325
+ kind: 'step-stop'
326
+ at: string
327
+ ref: string
328
+ phase: FlowPhase
329
+ step: string
330
+ }
331
+ | {
332
+ kind: 'note'
333
+ at: string
334
+ ref: string
335
+ text: string
336
+ }
337
+ | {
338
+ /**
339
+ * AIDEV-NOTE: PMR-YG2N durable sweep marker — one per worktree removed
340
+ * or skipped by the sweep. `source` records who wrote it ('flow-done'
341
+ * from the flow-done path, 'sweep' from the manual sweep command).
342
+ * Terminal outcomes ('removed'/'noop') let a later sweep skip the ref;
343
+ * 'deferred' is retried later. Fail-closed: sweep runs only
344
+ * when the journal says every merged worktree was already handled.
345
+ * AIDEV-NOTE: PMR-TE7Q — `annotated` is delivery evidence, not outcome
346
+ * state: only true proves the aven note landed and permits dedupe;
347
+ * false makes an identical outcome retry. Absent keeps legacy/no-note
348
+ * markers readable without claiming delivery.
349
+ */
350
+ kind: 'worktree-sweep'
351
+ at: string
352
+ ref: string
353
+ source: 'flow-done' | 'sweep'
354
+ outcome: 'removed' | 'noop' | 'deferred'
355
+ detail?: string
356
+ annotated?: boolean
357
+ }
358
+ | {
359
+ /**
360
+ * AIDEV-NOTE: durable run server — serializable prompt-input subset
361
+ * ({ mode, gitRoot, workRoots }); labels are re-derived live and
362
+ * findTicketRef/epicHasOpenChildren are rebuilt closures, never
363
+ * serialized. Last-wins in the projection.
364
+ */
365
+ kind: 'run-input'
366
+ at: string
367
+ ref: string
368
+ input: RunInputRecord
369
+ }
370
+ | {
371
+ /** AIDEV-NOTE: durable run server — loop snapshot; last-wins. */
372
+ kind: 'loop-state'
373
+ at: string
374
+ ref: string
375
+ loop: LoopStateRecord
376
+ }
377
+ | {
378
+ /**
379
+ * AIDEV-NOTE: PMR-T9ZQ — owner identity of the pi process driving this
380
+ * run: the main session file plus the writer's pid, journaled at run
381
+ * start and refreshed on every phase prompt. PROJECTED (last-wins into
382
+ * `owner`), not journal-only — the parked-run resume picker reads the
383
+ * projection through readRunEvents + projectRunState and journal-only
384
+ * kinds never reach it. `sessionFile` is nullable because a headless /
385
+ * server-driven run may have no session file at all; `pid` is the
386
+ * liveness carrier the picker probes.
387
+ */
388
+ kind: 'owner-session'
389
+ at: string
390
+ ref: string
391
+ sessionFile: string | null
392
+ pid: number
393
+ }
394
+ | {
395
+ /**
396
+ * AIDEV-NOTE: PMR-XTQQ durable attempt ledger — post-transition
397
+ * snapshot of the flow_run_attempt budget; last-wins per ref.
398
+ * `outcome: 'passed'` resets the projection `attempts` to 0;
399
+ * 'retry'/'escalate' carry the post-transition count. Journal-only
400
+ * consumers (e.g. the flow viewer) skip unknown kinds, so this stays
401
+ * forward-compatible.
402
+ */
403
+ kind: 'attempt-record'
404
+ at: string
405
+ ref: string
406
+ tool: 'flow_run_attempt'
407
+ outcome: 'passed' | 'retry' | 'escalate'
408
+ attempts: number
409
+ }
410
+ | {
411
+ /**
412
+ * AIDEV-NOTE: PMR-VDVJ — effect declaration: journaled BEFORE a
413
+ * side-effecting action may run (push / pr create / worktree create /
414
+ * remove / workspace close). Carries the recovery recipe so undo
415
+ * steps are journal-readable. Journal-only + STRICT: unlike receipts,
416
+ * a failed declaration write refuses the effect (fail-closed by
417
+ * design — this gate never degrades to prompt).
418
+ */
419
+ kind: 'effect-declaration'
420
+ at: string
421
+ ref: string
422
+ effect: EffectKind
423
+ effectId: string
424
+ command: string
425
+ recipe: string[]
426
+ headSha?: string
427
+ }
428
+
429
+ /**
430
+ * AIDEV-NOTE: PMR-C998 — event kinds that are journaled but never projected.
431
+ * recordRunEvent appends these without a read-modify-write of the projection
432
+ * (see the shipped 'main-session' drop bug noted there). Extend this union
433
+ * only; isJournalOnlyEvent is the single membership check. 'step-output'
434
+ * joined via PMR-C998 phase 2 (step submissions are append-only evidence).
435
+ * PMR-ZV9Y 1.1: 'step-start'/'step-stop' join for the same reason — they are
436
+ * append-only boundary evidence (phase 3 derives the step gauges by scanning
437
+ * the journal windows, the projection never models in-flight steps). The
438
+ * sibling v2 kind 'state-change' is deliberately NOT here: it is projected
439
+ * last-wins into FlowRunState.currentState. PMR-5NZB: 'integration-receipt'
440
+ * WAS joined for the same reason (the lineage walk read the raw journal
441
+ * directly); the kind retired with the sanctioned-rebase subsystem
442
+ * (PMR-V31Z 5.1) — no writer remains and the membership entry is gone, so
443
+ * an old receipt line hits applyEvent's default (ignored) instead of being
444
+ * modeled. Pinned by the legacy-journal parse test in test/run-state.test.ts.
445
+ */
446
+ type JournalOnlyKind =
447
+ | 'main-session'
448
+ | 'spawn-record'
449
+ | 'step-output'
450
+ | 'step-start'
451
+ | 'step-stop'
452
+
453
+ export function isJournalOnlyEvent(event: FlowRunEvent): boolean {
454
+ const kinds: JournalOnlyKind[] = [
455
+ 'main-session',
456
+ 'spawn-record',
457
+ 'step-output',
458
+ 'step-start',
459
+ 'step-stop',
460
+ ]
461
+ return kinds.some((k) => k === event.kind)
462
+ }
463
+
464
+ // AIDEV-NOTE (PMR-MSDJ 1.2, extracted from flow/cost-command.ts): runTracking
465
+ // is the SINGLE source for a run's Pushgateway tracking ref + mode. The group
466
+ // URL (and therefore which group a push REPLACES) is derived from these two
467
+ // values, and the PMR-05MQ tombstone pushes depend on the work-mode
468
+ // `/mode/work` suffix being preserved exactly — a drifted derivation here
469
+ // would create a duplicate personal group instead of replacing the work one.
470
+ // Semantics (pinned by test/run-state-tracking.test.ts): the LAST run-start
471
+ // event wins; its `mode` FIELD decides work vs personal (NOT the presence of
472
+ // trackRef — a stamped work run without a tracking ref still pushes to the
473
+ // work group under the aven ref); an absent or empty trackRef falls back to
474
+ // the caller's ref; no run-start event at all ⇒ personal + fallback (old
475
+ // journals).
476
+ export function runTracking(
477
+ events: readonly FlowRunEvent[],
478
+ fallbackRef: string,
479
+ ): { trackRef: string; mode: 'work' | 'personal' } {
480
+ let trackRef = fallbackRef
481
+ let mode: 'work' | 'personal' = 'personal'
482
+ for (const event of events) {
483
+ if (event.kind !== 'run-start') continue
484
+ mode = event.mode
485
+ if (event.trackRef !== undefined && event.trackRef.length > 0) {
486
+ trackRef = event.trackRef
487
+ } else {
488
+ trackRef = fallbackRef
489
+ }
490
+ }
491
+ return { trackRef, mode }
492
+ }
493
+
494
+ export interface RunInputRecord {
495
+ mode: 'work' | 'personal'
496
+ gitRoot: string
497
+ workRoots: string[]
498
+ // AIDEV-NOTE: yolo plan 2.2 — optional so pre-yolo journals stay valid;
499
+ // the JOURNALED value wins on resume (see mergeSeedInput in flow/resume.ts):
500
+ // a flag-less re-invocation of a yolo run stays yolo, and a later --yolo
501
+ // cannot upgrade a running non-yolo seed.
502
+ yolo?: boolean
503
+ }
504
+
505
+ export type LoopRunStatus = 'running' | 'paused' | 'halted' | 'done'
506
+
507
+ /**
508
+ * AIDEV-NOTE: PMR-T9ZQ — projected owner identity (see the 'owner-session'
509
+ * event). `sessionFile` null = the writer had no session file; liveness is
510
+ * judged from `pid` alone.
511
+ */
512
+ export interface OwnerRecord {
513
+ sessionFile: string | null
514
+ pid: number
515
+ at: string
516
+ }
517
+
518
+ export interface LoopStateRecord {
519
+ phase: FlowPhase
520
+ awaitingOutcome: boolean
521
+ blockerRetries: number
522
+ validateStartedAt: string
523
+ status: LoopRunStatus
524
+ }
525
+
526
+ /**
527
+ * AIDEV-NOTE: PMR-ZV9Y 1.1 — the projected v2 state (see the 'state-change'
528
+ * event). Last-wins: the journal is the fold, this is its tail. `reason` is
529
+ * '' when the state carries none. Phase 3's Prometheus derivation prefers
530
+ * this projection but re-scans the raw events for the wait windows, so a
531
+ * dropped projection write never loses window math.
532
+ */
533
+ export interface CurrentStateRecord {
534
+ state: FlowState
535
+ reason: FlowReason | ''
536
+ at: string
537
+ }
538
+
539
+ export interface GateTargetRecord {
540
+ targetId: string
541
+ gate: GateJournalKind
542
+ baseSha: string
543
+ headSha: string
544
+ diffSha256: string
545
+ at: string
546
+ }
547
+
548
+ export interface GateDecisionRecord {
549
+ targetId: string
550
+ gate: GateJournalKind
551
+ status: GateDecisionStatus
552
+ at: string
553
+ }
554
+
555
+ export type FlowRunState = {
556
+ schema: 'gtheys.pi-flow.run.v1'
557
+ ref: string
558
+ mode: 'work' | 'personal'
559
+ startedAt: string
560
+ updatedAt: string
561
+ completedPhases: FlowPhase[]
562
+ currentPhase: FlowPhase | null
563
+ notes: { at: string; text: string }[]
564
+ // AIDEV-NOTE: PMR-6EEW — optional so pre-gate-integrity projections (and
565
+ // journals rebuilt without gate events) stay valid.
566
+ gateTargets?: GateTargetRecord[]
567
+ gateDecisions?: GateDecisionRecord[]
568
+ subtaskRanges?: SubtaskRangesRecord[]
569
+ // AIDEV-NOTE: PMR-4S6V — optional so pre-receipt projections (and old
570
+ // journals rebuilt without command-receipt events) stay valid.
571
+ receipts?: CommandReceiptRecord[]
572
+ // AIDEV-NOTE: PMR-VDVJ — optional so pre-effect-declaration projections
573
+ // (and old journals rebuilt without effect-declaration events) stay valid.
574
+ effectDeclarations?: EffectDeclarationRecord[]
575
+ // AIDEV-NOTE: durable run server — optional so pre-input/loop projections
576
+ // (and old journals rebuilt without these events) stay valid.
577
+ input?: RunInputRecord
578
+ loop?: LoopStateRecord
579
+ // AIDEV-NOTE: PMR-T9ZQ — optional so pre-owner projections (and old
580
+ // journals rebuilt without owner-session events) stay valid; validated only
581
+ // when present (old journals).
582
+ owner?: OwnerRecord
583
+ // AIDEV-NOTE: PMR-XTQQ — optional so pre-attempt-ledger projections (and
584
+ // old journals rebuilt without attempt-record events) stay valid.
585
+ attempts?: number
586
+ gateAnswers?: GateAnswerRecord[]
587
+ // AIDEV-NOTE: PMR-ZV9Y 1.1 — optional so pre-v2 projections (and old
588
+ // journals rebuilt without state-change events) stay valid; validated only
589
+ // when present, and only against the closed v2 enums (see isFlowRunState).
590
+ currentState?: CurrentStateRecord
591
+ }
592
+
593
+ export interface GateAnswerRecord {
594
+ gate: GateJournalKind
595
+ choice: JournalAnswerChoice
596
+ at: string
597
+ /** AIDEV-NOTE: PMR-N0D5 — plan content hash bound at answer time. */
598
+ planRevision?: string
599
+ }
600
+
601
+ export interface SubtaskRangesRecord {
602
+ gate: GateJournalKind
603
+ baseSha: string
604
+ headSha: string
605
+ bySubtask: Array<{ subtask: string; commits: string[] }>
606
+ unattributed: string[]
607
+ at: string
608
+ }
609
+
610
+ export function runFileName(ref: string): string | null {
611
+ // Refs are ticket ids (PMR-ABC123 / DP-71). Restrict to a safe filename
612
+ // charset so the ref can never escape the runs dir or add path segments.
613
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(ref)) return null
614
+ return `${ref}.json`
615
+ }
616
+
617
+ export function runsDir(agentDir: string): string {
618
+ return path.join(agentDir, 'pi-flow', 'runs')
619
+ }
620
+
621
+ export function runStatePath(agentDir: string, ref: string): string | null {
622
+ const name = runFileName(ref)
623
+ if (name === null) return null
624
+ return path.join(runsDir(agentDir), name)
625
+ }
626
+
627
+ /** Sibling journal path for a run-state file (PMR-WF74 env plumbing source of truth). */
628
+ export function journalPathFor(statePath: string): string {
629
+ return `${statePath.slice(0, -'.json'.length)}.journal.jsonl`
630
+ }
631
+
632
+ /** Project the current run state from an ordered event list. Pure. */
633
+ export function projectRunState(
634
+ events: readonly FlowRunEvent[],
635
+ ): FlowRunState | null {
636
+ let state: FlowRunState | null = null
637
+ for (const event of events) {
638
+ state = applyEvent(state, event)
639
+ }
640
+ return state
641
+ }
642
+
643
+ /**
644
+ * AIDEV-NOTE: hot-loop scar tissue — journals are parsed leniently
645
+ * (readRunEvents casts JSON.parse output as FlowRunEvent), so event fields
646
+ * can hold values outside the CURRENT type vocabulary, e.g. the dropped
647
+ * 'research' phase in Oct-2026 journals. Projecting those verbatim produced
648
+ * states that failed isFlowRunState, and the durable daemon then judged its
649
+ * own projection "changed" on every 1s scan — rewriting identical bytes
650
+ * forever while every rewrite re-triggered fs.watch inside runs/ (CPU burn
651
+ * + unbounded serial-queue growth). Invariant: applyEvent must only emit
652
+ * guard-valid state; events whose vocabulary the guard constrains are
653
+ * validated HERE and ignored when out-of-vocabulary. The journal remains
654
+ * authoritative (events are never dropped from it). If you add a new event
655
+ * field that isFlowRunState validates, constrain it in this switch too.
656
+ */
657
+ export function applyEvent(
658
+ state: FlowRunState | null,
659
+ event: FlowRunEvent,
660
+ ): FlowRunState {
661
+ switch (event.kind) {
662
+ case 'run-start': {
663
+ return {
664
+ schema: 'gtheys.pi-flow.run.v1',
665
+ ref: event.ref,
666
+ mode: event.mode,
667
+ startedAt: event.at,
668
+ updatedAt: event.at,
669
+ completedPhases: [],
670
+ currentPhase: null,
671
+ notes: [],
672
+ }
673
+ }
674
+ case 'phase-start': {
675
+ if (state === null || state.ref !== event.ref)
676
+ return state as FlowRunState
677
+ if (!PHASES.includes(event.phase)) return state
678
+ if (state.currentPhase === event.phase) return state
679
+ return { ...state, currentPhase: event.phase, updatedAt: event.at }
680
+ }
681
+ case 'phase-complete': {
682
+ if (state === null || state.ref !== event.ref)
683
+ return state as FlowRunState
684
+ if (!PHASES.includes(event.phase)) return state
685
+ const completed = state.completedPhases.includes(event.phase)
686
+ ? state.completedPhases
687
+ : [...state.completedPhases, event.phase]
688
+ const current =
689
+ state.currentPhase === event.phase ? null : state.currentPhase
690
+ return {
691
+ ...state,
692
+ completedPhases: completed,
693
+ currentPhase: current,
694
+ updatedAt: event.at,
695
+ }
696
+ }
697
+ case 'gate-target': {
698
+ if (state === null || state.ref !== event.ref)
699
+ return state as FlowRunState
700
+ const targets = state.gateTargets ?? []
701
+ // idempotent by targetId — the same pin re-recorded is a no-op
702
+ if (targets.some((t) => t.targetId === event.targetId)) return state
703
+ return {
704
+ ...state,
705
+ gateTargets: [
706
+ ...targets,
707
+ {
708
+ targetId: event.targetId,
709
+ gate: event.gate,
710
+ baseSha: event.baseSha,
711
+ headSha: event.headSha,
712
+ diffSha256: event.diffSha256,
713
+ at: event.at,
714
+ },
715
+ ],
716
+ updatedAt: event.at,
717
+ }
718
+ }
719
+ case 'gate-decision': {
720
+ if (state === null || state.ref !== event.ref)
721
+ return state as FlowRunState
722
+ const decisions = state.gateDecisions ?? []
723
+ return {
724
+ ...state,
725
+ gateDecisions: [
726
+ ...decisions,
727
+ {
728
+ targetId: event.targetId,
729
+ gate: event.gate,
730
+ status: event.status,
731
+ at: event.at,
732
+ },
733
+ ],
734
+ updatedAt: event.at,
735
+ }
736
+ }
737
+ case 'subtask-ranges': {
738
+ if (state === null || state.ref !== event.ref)
739
+ return state as FlowRunState
740
+ return {
741
+ ...state,
742
+ subtaskRanges: [
743
+ ...(state.subtaskRanges ?? []),
744
+ {
745
+ gate: event.gate,
746
+ baseSha: event.baseSha,
747
+ headSha: event.headSha,
748
+ bySubtask: event.bySubtask,
749
+ unattributed: event.unattributed,
750
+ at: event.at,
751
+ },
752
+ ],
753
+ updatedAt: event.at,
754
+ }
755
+ }
756
+ case 'command-receipt': {
757
+ if (state === null || state.ref !== event.ref)
758
+ return state as FlowRunState
759
+ const receipts = state.receipts ?? []
760
+ // AIDEV-NOTE: PMR-TX2Y — idempotent by (command, target, headSha). The
761
+ // pre-TX2Y (command, target) key silently DROPPED a fix-round re-pass at a
762
+ // new head: recordRunEvent skips the journal append when this fold returns
763
+ // unchanged state, so the HEAD_B receipt never reached the journal and
764
+ // flow_land's durable-receipt route could not adopt it. undefined ===
765
+ // undefined keeps UNPINNED receipts byte-identical to the old fold.
766
+ // PMR-4S6V established the fold; PMR-TX2Y only widens the key.
767
+ if (
768
+ receipts.some(
769
+ (r) =>
770
+ r.command === event.command &&
771
+ r.target === event.target &&
772
+ r.headSha === event.headSha,
773
+ )
774
+ )
775
+ return state
776
+ return {
777
+ ...state,
778
+ receipts: [
779
+ ...receipts,
780
+ {
781
+ command: event.command,
782
+ target: event.target,
783
+ headSha: event.headSha,
784
+ status: event.status,
785
+ at: event.at,
786
+ },
787
+ ],
788
+ updatedAt: event.at,
789
+ }
790
+ }
791
+ case 'effect-declaration': {
792
+ if (state === null || state.ref !== event.ref)
793
+ return state as FlowRunState
794
+ // AIDEV-NOTE: PMR-V31Z 6.1 — legacy-tolerance guard, mirroring the
795
+ // phase/run-input drift checks above: readRunEvents parses leniently,
796
+ // so pre-shrink journals still carry 'merge-main'/'rebase-flow'
797
+ // declarations even though those kinds left EffectKind. Projecting one
798
+ // verbatim would emit a state isFlowRunState rejects (the daemon
799
+ // rewrite-loop scar tissue this switch exists to prevent), so
800
+ // out-of-vocabulary declarations are dropped here; the journal line
801
+ // itself is never removed (the journal stays authoritative).
802
+ if (!EFFECT_KINDS.includes(event.effect)) return state
803
+ const effectDeclarations = state.effectDeclarations ?? []
804
+ // AIDEV-NOTE: PMR-VDVJ — idempotent by effectId: re-declaring the
805
+ // same effect (same deterministic id) returns the same state.
806
+ if (effectDeclarations.some((d) => d.effectId === event.effectId))
807
+ return state
808
+ return {
809
+ ...state,
810
+ effectDeclarations: [
811
+ ...effectDeclarations,
812
+ {
813
+ effect: event.effect,
814
+ effectId: event.effectId,
815
+ command: event.command,
816
+ recipe: event.recipe,
817
+ headSha: event.headSha,
818
+ at: event.at,
819
+ },
820
+ ],
821
+ updatedAt: event.at,
822
+ }
823
+ }
824
+ case 'main-session': {
825
+ // evidence for /flow-cost only; the projection stays unchanged
826
+ return state as FlowRunState
827
+ }
828
+ case 'run-input': {
829
+ if (state === null || state.ref !== event.ref)
830
+ return state as FlowRunState
831
+ // yolo plan 2.2 — mirror the isFlowRunState constraint: a leniently
832
+ // parsed journal with a non-boolean yolo must not project a state the
833
+ // guard then rejects (see the applyEvent AIDEV-NOTE above).
834
+ const input = event.input
835
+ const inputYoloOk =
836
+ input.yolo === undefined || typeof input.yolo === 'boolean'
837
+ if (!inputYoloOk) return state as FlowRunState
838
+ return {
839
+ ...state,
840
+ input: event.input,
841
+ updatedAt: event.at,
842
+ }
843
+ }
844
+ case 'loop-state': {
845
+ if (state === null || state.ref !== event.ref)
846
+ return state as FlowRunState
847
+ // loop.phase/loop.status are guard-validated — same drift risk as the
848
+ // phase events above (see the applyEvent AIDEV-NOTE).
849
+ if (!PHASES.includes(event.loop.phase)) return state
850
+ if (!LOOP_STATUSES.includes(event.loop.status)) return state
851
+ return {
852
+ ...state,
853
+ loop: event.loop,
854
+ updatedAt: event.at,
855
+ }
856
+ }
857
+ case 'owner-session': {
858
+ if (state === null || state.ref !== event.ref)
859
+ return state as FlowRunState
860
+ // AIDEV-NOTE: PMR-T9ZQ — lenient-parse drift protection (see the
861
+ // applyEvent AIDEV-NOTE): owner values land in the projection, so the
862
+ // guard's vocabulary is enforced HERE and an out-of-vocabulary event is
863
+ // ignored rather than projected. pid must be an integer, sessionFile a
864
+ // string or null (undefined is not accepted — the writer always sends
865
+ // null explicitly), at a string.
866
+ if (!Number.isInteger(event.pid)) return state
867
+ if (event.sessionFile !== null && typeof event.sessionFile !== 'string')
868
+ return state
869
+ if (typeof event.at !== 'string') return state
870
+ // AIDEV-NOTE: PMR-T9ZQ — last-wins, and deliberately NO updatedAt bump:
871
+ // an owner refresh is a liveness stamp, not run activity, so it must not
872
+ // make a parked run look freshly updated to the picker or the widget.
873
+ return {
874
+ ...state,
875
+ owner: {
876
+ sessionFile: event.sessionFile,
877
+ pid: event.pid,
878
+ at: event.at,
879
+ },
880
+ }
881
+ }
882
+ case 'attempt-record': {
883
+ if (state === null || state.ref !== event.ref)
884
+ return state as FlowRunState
885
+ // AIDEV-NOTE: PMR-XTQQ — post-transition snapshot, last-wins. 'passed'
886
+ // resets durably; 'retry'/'escalate' carry the post-transition count.
887
+ let attempts = event.attempts
888
+ if (event.outcome === 'passed') attempts = 0
889
+ return {
890
+ ...state,
891
+ attempts,
892
+ updatedAt: event.at,
893
+ }
894
+ }
895
+ case 'state-change': {
896
+ if (state === null || state.ref !== event.ref)
897
+ return state as FlowRunState
898
+ // AIDEV-NOTE: PMR-ZV9Y 1.1 — the v2 enums land in the projection, so
899
+ // the guard's vocabulary is enforced HERE (see the applyEvent note
900
+ // above): out-of-vocabulary state/reason, or a non-string `at`, means
901
+ // the event is ignored by the fold. recordRunEvent still journals the
902
+ // line (the evidence record stays complete) — projection leniency and
903
+ // journal durability are separate contracts.
904
+ if (!FLOW_STATES.includes(event.state)) return state
905
+ // Absent reason normalizes to '' (the plan's `reason?` shape and the
906
+ // "empty when none" contract are the same thing on the projection). An
907
+ // explicit non-string (null from a corrupt line) is NOT normalized — it
908
+ // is out of vocabulary and the event is ignored.
909
+ const reason = event.reason === undefined ? '' : event.reason
910
+ if (typeof reason !== 'string') return state
911
+ if (reason !== '' && !FLOW_REASONS.includes(reason as FlowReason))
912
+ return state
913
+ if (typeof event.at !== 'string') return state
914
+ // AIDEV-NOTE: PMR-ZV9Y 1.1 — last-wins (duplicate transitions from a
915
+ // re-ask or a re-snapshot simply overwrite; the wait-window scan reads
916
+ // the raw journal, so a re-opened wait still opens a new window).
917
+ return {
918
+ ...state,
919
+ currentState: {
920
+ state: event.state,
921
+ reason: reason as FlowReason | '',
922
+ at: event.at,
923
+ },
924
+ updatedAt: event.at,
925
+ }
926
+ }
927
+ case 'note': {
928
+ if (state === null || state.ref !== event.ref)
929
+ return state as FlowRunState
930
+ return {
931
+ ...state,
932
+ notes: [...state.notes, { at: event.at, text: event.text }],
933
+ updatedAt: event.at,
934
+ }
935
+ }
936
+ case 'worktree-sweep': {
937
+ if (state === null || state.ref !== event.ref)
938
+ return state as FlowRunState
939
+ // AIDEV-NOTE: PMR-YG2N — sweep markers are evidence-only; the
940
+ // projection only keeps updatedAt fresh so replays stay current.
941
+ return {
942
+ ...state,
943
+ updatedAt: event.at,
944
+ }
945
+ }
946
+ case 'gate-answer': {
947
+ if (state === null || state.ref !== event.ref)
948
+ return state as FlowRunState
949
+ // AIDEV-NOTE: PMR-R5VB — latest answer wins per gate: later answers for
950
+ // the same gate replace earlier entries instead of appending.
951
+ const answers = (state.gateAnswers ?? []).filter(
952
+ (a) => a.gate !== event.gate,
953
+ )
954
+ // AIDEV-NOTE: PMR-N0D5 — the plan-revision binding lands in the
955
+ // projection only when it is a non-empty string (lenient-parse drift
956
+ // protection, same invariant as the yolo/owner folds above): a corrupt
957
+ // line must not project a state the guard would reject.
958
+ const record: GateAnswerRecord = {
959
+ gate: event.gate,
960
+ choice: event.choice,
961
+ at: event.at,
962
+ }
963
+ if (
964
+ typeof event.planRevision === 'string' &&
965
+ event.planRevision.length > 0
966
+ ) {
967
+ record.planRevision = event.planRevision
968
+ }
969
+ return {
970
+ ...state,
971
+ gateAnswers: [...answers, record],
972
+ updatedAt: event.at,
973
+ }
974
+ }
975
+ // AIDEV-NOTE: PMR-Z2K7 — journal lines from a NEWER writer (kinds this
976
+ // reader doesn't know) are ignored rather than crashing replay. Without
977
+ // this default an unknown kind would make applyEvent return undefined and
978
+ // poison every later event in the replay.
979
+ default: {
980
+ return state as FlowRunState
981
+ }
982
+ }
983
+ }
984
+
985
+ const SCHEMA = 'gtheys.pi-flow.run.v1'
986
+ const PHASES: readonly FlowPhase[] = [
987
+ 'plan',
988
+ 'implement',
989
+ 'validate',
990
+ 'feedback',
991
+ ]
992
+
993
+ const GATE_KINDS: readonly GateJournalKind[] = [
994
+ 'review',
995
+ 'deviation',
996
+ 'code-review',
997
+ 'spec-review',
998
+ ]
999
+
1000
+ const LOOP_STATUSES: readonly LoopRunStatus[] = [
1001
+ 'running',
1002
+ 'paused',
1003
+ 'halted',
1004
+ 'done',
1005
+ ]
1006
+
1007
+ const GATE_STATUSES: readonly GateDecisionStatus[] = [
1008
+ 'pass',
1009
+ 'fail',
1010
+ 'echo-missing',
1011
+ 'target-mismatch',
1012
+ 'stale',
1013
+ ]
1014
+
1015
+ // AIDEV-NOTE: PMR-V31Z 7.1 — `/flow answer` no longer writes 'pass'/'fail'
1016
+ // (the review gate is deleted; AnswerChoice narrowed to approve/reject), but
1017
+ // journals and projections from the review-gate era still carry them and
1018
+ // MUST keep replaying instead of failing isFlowRunState validation. This
1019
+ // widened union is the journal/projection vocabulary; the write-side answer
1020
+ // command uses the narrowed AnswerChoice.
1021
+ type JournalAnswerChoice = AnswerChoice | 'pass' | 'fail'
1022
+
1023
+ // PMR-MGHQ — runtime mirror of JournalAnswerChoice's members; the annotation
1024
+ // is compile-checked against the type, so the validator cannot drift from it.
1025
+ const ANSWER_CHOICES: readonly JournalAnswerChoice[] = [
1026
+ 'approve',
1027
+ 'reject',
1028
+ 'pass',
1029
+ 'fail',
1030
+ ]
1031
+
1032
+ export function isFlowRunState(value: unknown): value is FlowRunState {
1033
+ if (typeof value !== 'object' || value === null) return false
1034
+ const v = value as Record<string, unknown>
1035
+ if (v.schema !== SCHEMA) return false
1036
+ if (typeof v.ref !== 'string') return false
1037
+ if (v.mode !== 'work' && v.mode !== 'personal') return false
1038
+ if (typeof v.startedAt !== 'string') return false
1039
+ if (typeof v.updatedAt !== 'string') return false
1040
+ if (!Array.isArray(v.completedPhases)) return false
1041
+ if (!v.completedPhases.every((p) => PHASES.includes(p as FlowPhase)))
1042
+ return false
1043
+ const current = v.currentPhase
1044
+ if (current !== null && !PHASES.includes(current as FlowPhase)) return false
1045
+ if (!Array.isArray(v.notes)) return false
1046
+ const notesOk = v.notes.every(
1047
+ (n) =>
1048
+ typeof n === 'object' &&
1049
+ n !== null &&
1050
+ typeof (n as Record<string, unknown>).at === 'string' &&
1051
+ typeof (n as Record<string, unknown>).text === 'string',
1052
+ )
1053
+ if (!notesOk) return false
1054
+ // AIDEV-NOTE: PMR-6EEW — optional arrays validated only when present.
1055
+ if (v.gateTargets !== undefined) {
1056
+ if (!Array.isArray(v.gateTargets)) return false
1057
+ const targetsOk = v.gateTargets.every(
1058
+ (t) =>
1059
+ typeof t === 'object' &&
1060
+ t !== null &&
1061
+ typeof (t as Record<string, unknown>).targetId === 'string' &&
1062
+ GATE_KINDS.includes(
1063
+ (t as Record<string, unknown>).gate as GateJournalKind,
1064
+ ) &&
1065
+ typeof (t as Record<string, unknown>).baseSha === 'string' &&
1066
+ typeof (t as Record<string, unknown>).headSha === 'string' &&
1067
+ typeof (t as Record<string, unknown>).diffSha256 === 'string' &&
1068
+ typeof (t as Record<string, unknown>).at === 'string',
1069
+ )
1070
+ if (!targetsOk) return false
1071
+ }
1072
+ if (v.gateDecisions !== undefined) {
1073
+ if (!Array.isArray(v.gateDecisions)) return false
1074
+ const decisionsOk = v.gateDecisions.every(
1075
+ (d) =>
1076
+ typeof d === 'object' &&
1077
+ d !== null &&
1078
+ typeof (d as Record<string, unknown>).targetId === 'string' &&
1079
+ GATE_KINDS.includes(
1080
+ (d as Record<string, unknown>).gate as GateJournalKind,
1081
+ ) &&
1082
+ GATE_STATUSES.includes(
1083
+ (d as Record<string, unknown>).status as GateDecisionStatus,
1084
+ ) &&
1085
+ typeof (d as Record<string, unknown>).at === 'string',
1086
+ )
1087
+ if (!decisionsOk) return false
1088
+ }
1089
+ // AIDEV-NOTE: PMR-6EEW per-subtask ranges — optional, validated when present.
1090
+ if (v.subtaskRanges !== undefined) {
1091
+ if (!Array.isArray(v.subtaskRanges)) return false
1092
+ const rangesOk = v.subtaskRanges.every(
1093
+ (r) =>
1094
+ typeof r === 'object' &&
1095
+ r !== null &&
1096
+ GATE_KINDS.includes(
1097
+ (r as Record<string, unknown>).gate as GateJournalKind,
1098
+ ) &&
1099
+ typeof (r as Record<string, unknown>).baseSha === 'string' &&
1100
+ typeof (r as Record<string, unknown>).headSha === 'string' &&
1101
+ Array.isArray((r as Record<string, unknown>).bySubtask) &&
1102
+ Array.isArray((r as Record<string, unknown>).unattributed) &&
1103
+ typeof (r as Record<string, unknown>).at === 'string',
1104
+ )
1105
+ if (!rangesOk) return false
1106
+ }
1107
+ // AIDEV-NOTE: PMR-6EEW / PMR-MGHQ — gate answers optional, validated when present.
1108
+ if (v.gateAnswers !== undefined) {
1109
+ if (!Array.isArray(v.gateAnswers)) return false
1110
+ const answersOk = v.gateAnswers.every(
1111
+ (a) =>
1112
+ typeof a === 'object' &&
1113
+ a !== null &&
1114
+ GATE_KINDS.includes(
1115
+ (a as Record<string, unknown>).gate as GateJournalKind,
1116
+ ) &&
1117
+ ANSWER_CHOICES.includes(
1118
+ (a as Record<string, unknown>).choice as JournalAnswerChoice,
1119
+ ) &&
1120
+ typeof (a as Record<string, unknown>).at === 'string' &&
1121
+ // AIDEV-NOTE: PMR-N0D5 — the binding is optional (pre-N0D5 records);
1122
+ // when present it must be a non-empty string.
1123
+ ((a as Record<string, unknown>).planRevision === undefined ||
1124
+ (typeof (a as Record<string, unknown>).planRevision === 'string' &&
1125
+ ((a as Record<string, unknown>).planRevision as string).length >
1126
+ 0)),
1127
+ )
1128
+ if (!answersOk) return false
1129
+ }
1130
+ // AIDEV-NOTE: PMR-4S6V — receipts validated only when present (old journals).
1131
+ if (v.receipts !== undefined) {
1132
+ if (!Array.isArray(v.receipts)) return false
1133
+ const receiptsOk = v.receipts.every(
1134
+ (r) =>
1135
+ typeof r === 'object' &&
1136
+ r !== null &&
1137
+ RECEIPT_COMMANDS.includes(
1138
+ (r as Record<string, unknown>).command as ReceiptCommand,
1139
+ ) &&
1140
+ typeof (r as Record<string, unknown>).target === 'string' &&
1141
+ (r as Record<string, unknown>).status === 'ok' &&
1142
+ typeof (r as Record<string, unknown>).at === 'string' &&
1143
+ ((r as Record<string, unknown>).headSha === undefined ||
1144
+ typeof (r as Record<string, unknown>).headSha === 'string'),
1145
+ )
1146
+ if (!receiptsOk) return false
1147
+ }
1148
+ // AIDEV-NOTE: PMR-VDVJ — effect declarations validated only when present
1149
+ // (old journals). STRICT consumers depend on this block keeping the same
1150
+ // discipline as the receipts block above.
1151
+ if (v.effectDeclarations !== undefined) {
1152
+ if (!Array.isArray(v.effectDeclarations)) return false
1153
+ const declarationsOk = v.effectDeclarations.every(
1154
+ (d) =>
1155
+ typeof d === 'object' &&
1156
+ d !== null &&
1157
+ EFFECT_KINDS.includes(
1158
+ (d as Record<string, unknown>).effect as EffectKind,
1159
+ ) &&
1160
+ typeof (d as Record<string, unknown>).effectId === 'string' &&
1161
+ typeof (d as Record<string, unknown>).command === 'string' &&
1162
+ Array.isArray((d as Record<string, unknown>).recipe) &&
1163
+ ((d as Record<string, unknown>).recipe as unknown[]).length > 0 &&
1164
+ ((d as Record<string, unknown>).recipe as unknown[]).every(
1165
+ (step) => typeof step === 'string' && step.length > 0,
1166
+ ) &&
1167
+ typeof (d as Record<string, unknown>).at === 'string' &&
1168
+ ((d as Record<string, unknown>).headSha === undefined ||
1169
+ typeof (d as Record<string, unknown>).headSha === 'string'),
1170
+ )
1171
+ if (!declarationsOk) return false
1172
+ }
1173
+ // AIDEV-NOTE: durable run server — input/loop validated only when present
1174
+ // (old journals/projections lack them).
1175
+ if (v.input !== undefined) {
1176
+ const input = v.input as Record<string, unknown>
1177
+ const inputOk =
1178
+ typeof input === 'object' &&
1179
+ input !== null &&
1180
+ (input.mode === 'work' || input.mode === 'personal') &&
1181
+ typeof input.gitRoot === 'string' &&
1182
+ Array.isArray(input.workRoots) &&
1183
+ input.workRoots.every((r) => typeof r === 'string') &&
1184
+ (input.yolo === undefined || typeof input.yolo === 'boolean')
1185
+ if (!inputOk) return false
1186
+ }
1187
+ if (v.loop !== undefined) {
1188
+ const loop = v.loop as Record<string, unknown>
1189
+ const loopOk =
1190
+ typeof loop === 'object' &&
1191
+ loop !== null &&
1192
+ PHASES.includes(loop.phase as FlowPhase) &&
1193
+ typeof loop.awaitingOutcome === 'boolean' &&
1194
+ typeof loop.blockerRetries === 'number' &&
1195
+ typeof loop.validateStartedAt === 'string' &&
1196
+ LOOP_STATUSES.includes(loop.status as LoopRunStatus)
1197
+ if (!loopOk) return false
1198
+ }
1199
+ // AIDEV-NOTE: PMR-XTQQ — attempts validated only when present (old journals).
1200
+ if (v.attempts !== undefined) {
1201
+ if (typeof v.attempts !== 'number') return false
1202
+ }
1203
+ // AIDEV-NOTE: PMR-T9ZQ — owner validated only when present (old journals).
1204
+ if (v.owner !== undefined) {
1205
+ const owner = v.owner as Record<string, unknown>
1206
+ const ownerOk =
1207
+ typeof owner === 'object' &&
1208
+ owner !== null &&
1209
+ (owner.sessionFile === null || typeof owner.sessionFile === 'string') &&
1210
+ typeof owner.pid === 'number' &&
1211
+ Number.isInteger(owner.pid) &&
1212
+ typeof owner.at === 'string'
1213
+ if (!ownerOk) return false
1214
+ }
1215
+ // AIDEV-NOTE: PMR-ZV9Y 1.1 — the v2 projected state is validated only when
1216
+ // present (old journals) and ONLY against the closed enums, mirroring the
1217
+ // checks in the applyEvent 'state-change' case. A hand-edited or future-
1218
+ // writer currentState the guard would reject must never reach the fold in
1219
+ // the first place — the hot-loop invariant (see the applyEvent note).
1220
+ if (v.currentState !== undefined) {
1221
+ const current = v.currentState as Record<string, unknown>
1222
+ const currentOk =
1223
+ typeof current === 'object' &&
1224
+ current !== null &&
1225
+ FLOW_STATES.includes(current.state as FlowState) &&
1226
+ (current.reason === '' ||
1227
+ FLOW_REASONS.includes(current.reason as FlowReason)) &&
1228
+ typeof current.at === 'string'
1229
+ if (!currentOk) return false
1230
+ }
1231
+ return true
1232
+ }
1233
+
1234
+ // AIDEV-NOTE: PMR-VHEY 2.1 (class C1, aven PMR-4Y29 / PMR-C9QG) — atomic
1235
+ // file write: unique same-directory temp file + fs.rename. A plain
1236
+ // fs.writeFile truncates then writes in multiple syscalls once the payload
1237
+ // exceeds a single write() chunk, so any concurrent reader (readRunState,
1238
+ // the daemon's reproject read, the widget, tests) could observe a torn
1239
+ // projection — reproduced red 20/20 in the 1.2 probe (see
1240
+ // test/run-state-atomic.test.ts). Same directory ⇒ same filesystem ⇒
1241
+ // POSIX-atomic rename; pid + module counter keep temp names collision-free
1242
+ // for concurrent same-process writers and across processes. Both default
1243
+ // projection-write seams route through this helper: recordRunEvent's
1244
+ // default io below and the daemon's defaultReprojectIo
1245
+ // (server/daemon.ts).
1246
+ let writeFileAtomicCounter = 0
1247
+ export async function writeFileAtomic(p: string, data: string): Promise<void> {
1248
+ writeFileAtomicCounter += 1
1249
+ const tmp = `${p}.tmp-${process.pid}-${writeFileAtomicCounter}`
1250
+ try {
1251
+ await fs.writeFile(tmp, data, 'utf8')
1252
+ await fs.rename(tmp, p)
1253
+ } catch (err) {
1254
+ // Failure cleanup: a temp file must never linger in the runs dir.
1255
+ await fs.rm(tmp, { force: true }).catch(() => {})
1256
+ throw err
1257
+ }
1258
+ }
1259
+
1260
+ /**
1261
+ * Append an event to the journal and rewrite the projection atomically.
1262
+ * Best-effort per repo convention: journal failures must never break a flow
1263
+ * phase — aven labels remain the gate source of truth.
1264
+ */
1265
+ export async function recordRunEvent(
1266
+ agentDir: string,
1267
+ event: FlowRunEvent,
1268
+ io: {
1269
+ readFile: (p: string) => Promise<string>
1270
+ appendFile: (p: string, data: string) => Promise<void>
1271
+ writeFile: (p: string, data: string) => Promise<void>
1272
+ mkdir: (dir: string, recursive: true) => Promise<void>
1273
+ } = {
1274
+ readFile: (p) =>
1275
+ fs.readFile(p, 'utf8').then((text) => {
1276
+ if (text === undefined) throw new Error('unreachable')
1277
+ return text
1278
+ }),
1279
+ appendFile: async (p, data) => {
1280
+ await fs.appendFile(p, data, 'utf8')
1281
+ },
1282
+ writeFile: async (p, data) => {
1283
+ // PMR-VHEY 2.1: atomic temp+rename — see writeFileAtomic above.
1284
+ await writeFileAtomic(p, data)
1285
+ },
1286
+ mkdir: async (dir, recursive) => {
1287
+ await fs.mkdir(dir, { recursive })
1288
+ },
1289
+ },
1290
+ ): Promise<void> {
1291
+ const statePath = runStatePath(agentDir, event.ref)
1292
+ if (statePath === null) return
1293
+ const journalPath = journalPathFor(statePath)
1294
+ const dir = path.dirname(statePath)
1295
+ await io.mkdir(dir, true)
1296
+ let state: FlowRunState | null = null
1297
+ try {
1298
+ const raw = await io.readFile(statePath)
1299
+ const parsed: unknown = JSON.parse(raw)
1300
+ if (isFlowRunState(parsed)) state = parsed
1301
+ } catch {
1302
+ // missing or corrupt projection — rebuild from the journal below
1303
+ }
1304
+ if (state === null) {
1305
+ // Rebuild from the journal so a deleted projection cannot lose history.
1306
+ const events: FlowRunEvent[] = []
1307
+ try {
1308
+ const journal = await io.readFile(journalPath)
1309
+ for (const line of journal.split('\n')) {
1310
+ const trimmed = line.trim()
1311
+ if (trimmed.length === 0) continue
1312
+ try {
1313
+ events.push(JSON.parse(trimmed) as FlowRunEvent)
1314
+ } catch {
1315
+ // torn tail line — skip
1316
+ }
1317
+ }
1318
+ } catch {
1319
+ // no journal yet — start fresh
1320
+ }
1321
+ state = projectRunState(events)
1322
+ }
1323
+ // AIDEV-NOTE: PMR-C998 — journal-only kinds append to the journal without
1324
+ // touching the projection. 'main-session' is journal-only evidence for
1325
+ // /flow-cost — it never changes the projection, so the "unchanged state =
1326
+ // nothing to write" shortcut below would silently DROP it (that bug shipped
1327
+ // once: no run had a main-session event, so no main-session cost was ever
1328
+ // rolled up). Append it to the journal and leave the projection file alone.
1329
+ // 'spawn-record' joined in PMR-C998 for the same reason (worker spawn
1330
+ // evidence; the projection never models child runs). Keep this as a
1331
+ // membership check over JournalOnlyKind — extend the union only.
1332
+ if (isJournalOnlyEvent(event)) {
1333
+ await io.appendFile(journalPath, `${JSON.stringify(event)}\n`)
1334
+ return
1335
+ }
1336
+ const next = applyEvent(state, event)
1337
+ if (next === state) {
1338
+ // AIDEV-NOTE: PMR-ZV9Y 1.1 — a state-change whose enums are out of
1339
+ // vocabulary folds to the SAME state, and this shortcut would silently
1340
+ // drop it (exactly the shipped 'main-session' bug above). The v2 evidence
1341
+ // line must survive: phase 3's wait/step windows scan the journal, so an
1342
+ // ignored projection write may never mean an ignored journal append.
1343
+ if (event.kind === 'state-change') {
1344
+ await io.appendFile(journalPath, `${JSON.stringify(event)}\n`)
1345
+ }
1346
+ return
1347
+ }
1348
+ await io.appendFile(journalPath, `${JSON.stringify(event)}\n`)
1349
+ await io.writeFile(statePath, `${JSON.stringify(next, null, 2)}\n`)
1350
+ }
1351
+
1352
+ /**
1353
+ * Append an event to the run JOURNAL only — no projection rewrite. For
1354
+ * writers that are not the flow's main process (a worker journaling its own
1355
+ * nested spawns): the projection is a read-modify-write file and two
1356
+ * processes rewriting it can clobber each other, while a one-line O_APPEND to
1357
+ * the journal is safe and is all /flow-cost reads. Best-effort like
1358
+ * recordRunEvent.
1359
+ */
1360
+ export async function recordRunEventJournalOnly(
1361
+ agentDir: string,
1362
+ event: FlowRunEvent,
1363
+ ): Promise<void> {
1364
+ const statePath = runStatePath(agentDir, event.ref)
1365
+ if (statePath === null) return
1366
+ const journalPath = journalPathFor(statePath)
1367
+ await fs.mkdir(path.dirname(statePath), { recursive: true })
1368
+ await fs.appendFile(journalPath, `${JSON.stringify(event)}\n`, 'utf8')
1369
+ }
1370
+
1371
+ /** Read a run projection for display. Returns null when no run exists. */
1372
+ export async function readRunState(
1373
+ agentDir: string,
1374
+ ref: string,
1375
+ ): Promise<FlowRunState | null> {
1376
+ const statePath = runStatePath(agentDir, ref)
1377
+ if (statePath === null) return null
1378
+ try {
1379
+ const raw = await fs.readFile(statePath, 'utf8')
1380
+ const parsed: unknown = JSON.parse(raw)
1381
+ return isFlowRunState(parsed) ? parsed : null
1382
+ } catch {
1383
+ return null
1384
+ }
1385
+ }
1386
+
1387
+ /**
1388
+ * AIDEV-NOTE: yolo plan 3.1 — is the run for this ref journaled as yolo?
1389
+ * Reads the restored projection (input.yolo === true). Fail-closed: absent
1390
+ * projection or any read failure returns false. Unlike the agent-writable
1391
+ * oneshot label (PMR-J6TW), the yolo bit is journaled from the human's CLI
1392
+ * invocation, so gate exemptions keyed on it cannot be self-granted.
1393
+ */
1394
+ export async function isYoloRun(ref: string): Promise<boolean> {
1395
+ const state = await readRunState(getAgentDir(), ref)
1396
+ if (state === null) return false
1397
+ return state.input?.yolo === true
1398
+ }
1399
+
1400
+ /**
1401
+ * AIDEV-NOTE: PMR-VE27 — mode provenance for the feedback close-out gate
1402
+ * (tools/phase-complete.ts). Reads the run JOURNAL (not the projection —
1403
+ * the journal is the evidence record and the only thing guaranteed to
1404
+ * exist for standalone tool use) and returns the LAST run-start event's
1405
+ * mode, the runTracking "last wins" semantics. Unlike runTracking there is
1406
+ * NO personal fallback: a close-out gate must fail closed, so an unreadable
1407
+ * journal or one with no run-start event returns null and the consumer
1408
+ * refuses with recovery text instead of guessing a mode (runTracking keeps
1409
+ * its fallback — its callers are telemetry-only).
1410
+ */
1411
+ export async function readRunMode(ref: string): Promise<WorkMode | null> {
1412
+ const events = await readRunEvents(getAgentDir(), ref)
1413
+ if (events === null) return null
1414
+ let mode: WorkMode | null = null
1415
+ for (const event of events) {
1416
+ if (event.kind === 'run-start') mode = event.mode
1417
+ }
1418
+ return mode
1419
+ }
1420
+
1421
+ /**
1422
+ * AIDEV-NOTE: PMR-N0D5 — ISO-timestamp ordering for the epoch rules.
1423
+ * Journal `at` fields are `new Date().toISOString()` output, but journals
1424
+ * parse leniently, so numeric Date.parse comparison is primary and a
1425
+ * lexicographic fallback covers unparseable values. `>=` (not `>`) is the
1426
+ * epoch-open convention: an event stamped in the same millisecond as the
1427
+ * run-start belongs to the new epoch (a receipt can only be journaled once
1428
+ * run state exists, so it can never predate its epoch in practice).
1429
+ */
1430
+ function atOrAfter(eventAt: string, sinceAt: string): boolean {
1431
+ const a = Date.parse(eventAt)
1432
+ const b = Date.parse(sinceAt)
1433
+ if (Number.isNaN(a) || Number.isNaN(b)) return eventAt >= sinceAt
1434
+ return a >= b
1435
+ }
1436
+
1437
+ /**
1438
+ * AIDEV-NOTE: PMR-N0D5 — PURE yolo-exemption currency over journal events.
1439
+ * The journaled yolo bit exempts only when ALL of these hold:
1440
+ * 1. a run-start exists for the ref (no journal / no run-start = no
1441
+ * exemption — standalone calls are never yolo-exempt);
1442
+ * 2. the bit was journaled AT or AFTER the latest run-start (a bit from a
1443
+ * previous run epoch is stale);
1444
+ * 3. the latest loop snapshot in the CURRENT epoch is non-terminal
1445
+ * (running/paused/absent — halted/done runs fail closed).
1446
+ * Each new run-start resets both the bit and the terminal flag, so the
1447
+ * scan is epoch-correct by construction. This is deliberately separate
1448
+ * from isYoloRun: the projection reader also feeds the close-out mode
1449
+ * dispatch and the /flow terminal machinery, whose semantics are pinned
1450
+ * elsewhere (ISC-A-4) and must NOT flip on terminal runs.
1451
+ */
1452
+ export function yoloRunCurrentFromEvents(
1453
+ events: readonly FlowRunEvent[],
1454
+ ref: string,
1455
+ ): boolean {
1456
+ let runStartAt: string | null = null
1457
+ let yoloCurrent = false
1458
+ let terminal = false
1459
+ for (const event of events) {
1460
+ if (event.ref !== ref) continue
1461
+ if (event.kind === 'run-start') {
1462
+ runStartAt = event.at
1463
+ yoloCurrent = false
1464
+ terminal = false
1465
+ continue
1466
+ }
1467
+ if (runStartAt === null) continue
1468
+ if (event.kind === 'run-input') {
1469
+ if (event.input.yolo === true) {
1470
+ yoloCurrent = true
1471
+ }
1472
+ continue
1473
+ }
1474
+ if (event.kind === 'loop-state') {
1475
+ if (event.loop.status === 'halted' || event.loop.status === 'done') {
1476
+ terminal = true
1477
+ }
1478
+ }
1479
+ }
1480
+ if (runStartAt === null) return false
1481
+ if (terminal) return false
1482
+ return yoloCurrent
1483
+ }
1484
+
1485
+ /**
1486
+ * AIDEV-NOTE: PMR-N0D5 — the epoch-aware yolo read for the RECEIPT gates
1487
+ * (spec_approve's exemption and the plan receipt gate in
1488
+ * tools/phase-complete.ts): journaled-after-latest-run-start plus
1489
+ * non-terminal, else no exemption (fail closed). JOURNAL-based like
1490
+ * readRunMode, so it works for standalone tool use even when the daemon
1491
+ * owns the projection.
1492
+ */
1493
+ export async function isYoloRunCurrent(ref: string): Promise<boolean> {
1494
+ const events = await readRunEvents(getAgentDir(), ref)
1495
+ if (events === null) return false
1496
+ return yoloRunCurrentFromEvents(events, ref)
1497
+ }
1498
+
1499
+ /**
1500
+ * AIDEV-NOTE: PMR-N0D5 — PURE oneshot provenance over journal events:
1501
+ * the LAST run-start event's `oneshot` snapshot (the ticket's label state
1502
+ * AT start time). Returns null when the journal has NO run-start for the
1503
+ * ref — the consumer's signal to fall back to the live label read for
1504
+ * truly standalone calls (the sanctioned journal-first/label-fallback
1505
+ * policy). A journal WITH a run-start always answers with the snapshot:
1506
+ * absent/false both mean the exemption was not minted at start, so a
1507
+ * mid-run label add is inert (and old pre-N0D5 journals fail closed to
1508
+ * the human gate rather than trusting a live agent-writable label).
1509
+ */
1510
+ export function oneshotSnapshotFromEvents(
1511
+ events: readonly FlowRunEvent[],
1512
+ ref: string,
1513
+ ): boolean | null {
1514
+ let oneshot: boolean | null = null
1515
+ for (const event of events) {
1516
+ if (event.kind !== 'run-start') continue
1517
+ if (event.ref !== ref) continue
1518
+ oneshot = event.oneshot === true
1519
+ }
1520
+ return oneshot
1521
+ }
1522
+
1523
+ /**
1524
+ * AIDEV-NOTE: PMR-N0D5 — journal-backed oneshot snapshot read (see
1525
+ * oneshotSnapshotFromEvents for the contract). Fail-soft: an unreadable
1526
+ * journal is the same as no journal (null → live-label fallback),
1527
+ * mirroring the ReceiptJournal best-effort boundary.
1528
+ */
1529
+ export async function readOneshotSnapshot(
1530
+ ref: string,
1531
+ ): Promise<boolean | null> {
1532
+ const events = await readRunEvents(getAgentDir(), ref)
1533
+ if (events === null) return null
1534
+ return oneshotSnapshotFromEvents(events, ref)
1535
+ }
1536
+
1537
+ /**
1538
+ * AIDEV-NOTE: PMR-AYMZ — PURE epoch scan for a journaled human route
1539
+ * confirmation: true only when an ok=true `plan.route-confirmed`
1540
+ * step-output exists AFTER the latest run-start for the ref (the
1541
+ * PMR-N0D5 epoch contract: journal lines are append-ordered, every
1542
+ * run-start resets the flag, and events from before the latest
1543
+ * run-start — or from other refs — never count; no run-start for the
1544
+ * ref at all → false, fail-closed for standalone calls). Deliberately
1545
+ * diverges from yoloRunCurrentFromEvents by having NO loop-terminality
1546
+ * check: route-confirmed is a human-decision fact in the current epoch,
1547
+ * not run liveness.
1548
+ */
1549
+ export function routeConfirmedFromEvents(
1550
+ events: readonly FlowRunEvent[],
1551
+ ref: string,
1552
+ ): boolean {
1553
+ let runStartAt: string | null = null
1554
+ let routeConfirmed = false
1555
+ for (const event of events) {
1556
+ if (event.ref !== ref) continue
1557
+ if (event.kind === 'run-start') {
1558
+ runStartAt = event.at
1559
+ routeConfirmed = false
1560
+ continue
1561
+ }
1562
+ if (runStartAt === null) continue
1563
+ if (
1564
+ event.kind === 'step-output' &&
1565
+ event.step === 'plan.route-confirmed' &&
1566
+ event.phase === 'plan' &&
1567
+ event.ok === true
1568
+ ) {
1569
+ routeConfirmed = true
1570
+ }
1571
+ }
1572
+ if (runStartAt === null) return false
1573
+ return routeConfirmed
1574
+ }
1575
+
1576
+ /**
1577
+ * AIDEV-NOTE: PMR-AYMZ — journal-backed route-confirmation read (see
1578
+ * routeConfirmedFromEvents for the contract it inherits from the
1579
+ * PMR-N0D5 epoch rules: only events after the latest run-start count;
1580
+ * no run-start for the ref → false). Fail-soft: an unreadable or absent
1581
+ * journal is the same as no confirmation, mirroring isYoloRunCurrent.
1582
+ */
1583
+ export async function readRouteConfirmedCurrent(ref: string): Promise<boolean> {
1584
+ const events = await readRunEvents(getAgentDir(), ref)
1585
+ if (events === null) return false
1586
+ return routeConfirmedFromEvents(events, ref)
1587
+ }
1588
+
1589
+ /**
1590
+ * AIDEV-NOTE: PMR-N0D5 — the journaled binding of a spec approve answer to
1591
+ * a plan revision. `hasJournal` is true when ANY journal evidence exists
1592
+ * for the ref (a gate-answer is journaled even for standalone answers via
1593
+ * the journal-only route, so standalone approvals are bound too);
1594
+ * `boundRevision` is the planRevision of the LATEST journaled spec-review
1595
+ * approve answer, or null when that latest answer is unbound (pre-N0D5
1596
+ * journal, or answered while the plan-path was unresolvable — both
1597
+ * fail closed at the gates). Consumers: spec_approve and the plan receipt
1598
+ * gate, via specAnswerBindingRefusal.
1599
+ */
1600
+ export interface SpecAnswerBinding {
1601
+ hasJournal: boolean
1602
+ boundRevision: string | null
1603
+ }
1604
+
1605
+ export function specAnswerBindingFromEvents(
1606
+ events: readonly FlowRunEvent[],
1607
+ ref: string,
1608
+ ): SpecAnswerBinding {
1609
+ let boundRevision: string | null = null
1610
+ let sawApproveAnswer = false
1611
+ for (const event of events) {
1612
+ if (event.kind !== 'gate-answer') continue
1613
+ if (event.ref !== ref) continue
1614
+ if (event.gate !== 'spec-review') continue
1615
+ if (event.choice !== 'approve') continue
1616
+ sawApproveAnswer = true
1617
+ if (
1618
+ typeof event.planRevision === 'string' &&
1619
+ event.planRevision.length > 0
1620
+ ) {
1621
+ boundRevision = event.planRevision
1622
+ } else {
1623
+ // The latest approve answer is unbound: it supersedes any older
1624
+ // binding (fail-closed — the human must re-answer to bind).
1625
+ boundRevision = null
1626
+ }
1627
+ }
1628
+ return { hasJournal: sawApproveAnswer || events.length > 0, boundRevision }
1629
+ }
1630
+
1631
+ /**
1632
+ * AIDEV-NOTE: PMR-N0D5 — journal-backed binding read (see
1633
+ * specAnswerBindingFromEvents). An absent/unreadable journal yields
1634
+ * hasJournal:false → the gates skip binding enforcement entirely, which
1635
+ * is exactly the standalone (never-flowed) case.
1636
+ */
1637
+ export async function readSpecAnswerBinding(
1638
+ ref: string,
1639
+ ): Promise<SpecAnswerBinding> {
1640
+ const events = await readRunEvents(getAgentDir(), ref)
1641
+ if (events === null) return { hasJournal: false, boundRevision: null }
1642
+ return specAnswerBindingFromEvents(events, ref)
1643
+ }
1644
+
1645
+ /**
1646
+ * AIDEV-NOTE: PMR-N0D5 — shared refusal classifier for the spec-answer
1647
+ * gates. Returns null when the answer may proceed (no journal → standalone
1648
+ * metadata-only gate, PMR-FA3D; or bound revision === current revision),
1649
+ * else the fail-closed reason WITH the re-answer recovery. A null
1650
+ * `currentRevision` means the plan revision could not be resolved at gate
1651
+ * time (aven failure, absent plan-path metadata, unreadable plan file) —
1652
+ * unbindable → fail closed.
1653
+ */
1654
+ export function specAnswerBindingRefusal(
1655
+ binding: SpecAnswerBinding,
1656
+ currentRevision: string | null,
1657
+ ref: string,
1658
+ ): string | null {
1659
+ if (!binding.hasJournal) return null
1660
+ if (currentRevision === null) {
1661
+ return `the plan revision could not be resolved for ${ref} (no readable plan-path metadata or the plan file is missing) — the approval is unbindable; fix the plan-path metadata or restore the plan file, then re-run /flow answer ${ref} approve`
1662
+ }
1663
+ if (binding.boundRevision === null) {
1664
+ return `no plan-revision-bound approval is journaled for ${ref} (the recorded answer predates revision binding or was recorded without a resolvable plan) — re-run /flow answer ${ref} approve to bind the approval to the current plan`
1665
+ }
1666
+ if (binding.boundRevision !== currentRevision) {
1667
+ return `the plan changed after the approval was recorded for ${ref} (the journaled approval is bound to a different plan revision than the current plan file) — the answer is stale; re-run /flow answer ${ref} approve once the plan is final`
1668
+ }
1669
+ return null
1670
+ }
1671
+
1672
+ /**
1673
+ * Read a run's journal events in order (PMR-EA8X). The journal is the
1674
+ * evidence record — /flow-cost rolls up from these events. Null when the
1675
+ * ref is invalid or no journal exists; torn tail lines are skipped.
1676
+ */
1677
+ export async function readRunEvents(
1678
+ agentDir: string,
1679
+ ref: string,
1680
+ io: {
1681
+ readFile: (p: string) => Promise<string>
1682
+ } = { readFile: (p) => fs.readFile(p, 'utf8') },
1683
+ ): Promise<FlowRunEvent[] | null> {
1684
+ const statePath = runStatePath(agentDir, ref)
1685
+ if (statePath === null) return null
1686
+ const journalPath = journalPathFor(statePath)
1687
+ let raw: string
1688
+ try {
1689
+ raw = await io.readFile(journalPath)
1690
+ } catch {
1691
+ return null
1692
+ }
1693
+ const events: FlowRunEvent[] = []
1694
+ for (const line of raw.split('\n')) {
1695
+ const trimmed = line.trim()
1696
+ if (trimmed.length === 0) continue
1697
+ try {
1698
+ events.push(JSON.parse(trimmed) as FlowRunEvent)
1699
+ } catch {
1700
+ // torn tail line — skip
1701
+ }
1702
+ }
1703
+ return events
1704
+ }
1705
+
1706
+ export interface ReceiptQuery {
1707
+ ref: string
1708
+ command: ReceiptCommand
1709
+ target: string
1710
+ /** When set, adopt only if the receipt's headSha matches exactly. */
1711
+ headSha?: string
1712
+ /**
1713
+ * AIDEV-NOTE: PMR-N0D5 — current-run binding: adopt only receipts minted
1714
+ * AT or AFTER the latest run-start for the ref (same-run idempotent
1715
+ * adoption stays, receipts from a previous run epoch stop deduping).
1716
+ * Deliberately OPT-IN: spec_approve passes it; the other receipt consumers
1717
+ * (flow_land's head-pinned adoption, landing re-verification) keep the
1718
+ * raw-journal lookup — a reviewed-head receipt from a previous epoch is
1719
+ * still valid landing authority, so tightening find() globally would
1720
+ * break sanctioned restarts. No journaled run-start at all → nothing is
1721
+ * current (the PMR-FA3D standalone degradation). */
1722
+ currentRunEpoch?: boolean
1723
+ }
1724
+
1725
+ /**
1726
+ * AIDEV-NOTE: PMR-4S6V — best-effort boundary: find returns null and record
1727
+ * swallows errors, so journal failures never block a gate transition.
1728
+ */
1729
+ export interface ReceiptJournal {
1730
+ find(query: ReceiptQuery): Promise<CommandReceiptRecord | null>
1731
+ record(query: ReceiptQuery): Promise<void>
1732
+ }
1733
+
1734
+ /**
1735
+ * AIDEV-NOTE: PMR-4S6V — best-effort receipt access over the run journal.
1736
+ * `find` reads via readRunEvents and returns null on missing/corrupt
1737
+ * journals; `record` goes through recordRunEvent (projection mutation, not
1738
+ * the journal-only route) and swallows io errors.
1739
+ */
1740
+ export function createReceiptJournal(
1741
+ agentDir: string,
1742
+ io?: {
1743
+ readFile: (p: string) => Promise<string>
1744
+ appendFile: (p: string, data: string) => Promise<void>
1745
+ writeFile: (p: string, data: string) => Promise<void>
1746
+ mkdir: (dir: string, recursive: true) => Promise<void>
1747
+ },
1748
+ // AIDEV-NOTE: PMR-XTQQ — optional mode-aware record fn (server/writer.ts)
1749
+ // threaded through registerLandTool/registerPhaseCompleteTool so receipt
1750
+ // writes route journal-only while the daemon owns the projection. Absent =
1751
+ // today's exact full-writer behavior. Outcome-agnostic: accepts the
1752
+ // EventWriter.record boolean (PMR-HRZE) as well as void writers.
1753
+ record?: (event: FlowRunEvent) => Promise<void> | Promise<boolean>,
1754
+ ): ReceiptJournal {
1755
+ const recordEvent = async (query: ReceiptQuery): Promise<void> => {
1756
+ const event: FlowRunEvent = {
1757
+ kind: 'command-receipt',
1758
+ at: new Date().toISOString(),
1759
+ ref: query.ref,
1760
+ command: query.command,
1761
+ target: query.target,
1762
+ status: 'ok',
1763
+ }
1764
+ if (query.headSha !== undefined) event.headSha = query.headSha
1765
+ if (record !== undefined) {
1766
+ try {
1767
+ await record(event)
1768
+ } catch {
1769
+ // best-effort — journal failures never block a gate transition
1770
+ }
1771
+ return
1772
+ }
1773
+ try {
1774
+ await recordRunEvent(agentDir, event, io)
1775
+ } catch {
1776
+ // best-effort — journal failures never block a gate transition
1777
+ }
1778
+ }
1779
+ const find = async (
1780
+ query: ReceiptQuery,
1781
+ ): Promise<CommandReceiptRecord | null> => {
1782
+ try {
1783
+ const events = await readRunEvents(agentDir, query.ref, io)
1784
+ if (events === null) return null
1785
+ // AIDEV-NOTE: PMR-N0D5 — the epoch rule is evaluated over the raw
1786
+ // journal: the LAST run-start event for the ref opens the current run
1787
+ // epoch, and a receipt only dedupes when it was minted at/after it.
1788
+ // `>=` (not `>`) is deliberate: a receipt can only be journaled once
1789
+ // run state exists, so a same-millisecond receipt belongs to the
1790
+ // current epoch, never to a superseded one.
1791
+ let epochStartAt: string | null = null
1792
+ if (query.currentRunEpoch === true) {
1793
+ for (const event of events) {
1794
+ if (event.kind === 'run-start' && event.ref === query.ref) {
1795
+ epochStartAt = event.at
1796
+ }
1797
+ }
1798
+ if (epochStartAt === null) return null
1799
+ }
1800
+ for (const event of events) {
1801
+ if (event.kind !== 'command-receipt') continue
1802
+ if (event.ref !== query.ref) continue
1803
+ if (event.command !== query.command) continue
1804
+ if (event.target !== query.target) continue
1805
+ if (query.headSha !== undefined && event.headSha !== query.headSha)
1806
+ continue
1807
+ if (
1808
+ query.currentRunEpoch === true &&
1809
+ epochStartAt !== null &&
1810
+ !atOrAfter(event.at, epochStartAt)
1811
+ )
1812
+ continue
1813
+ const receipt: CommandReceiptRecord = {
1814
+ command: event.command,
1815
+ target: event.target,
1816
+ status: event.status,
1817
+ at: event.at,
1818
+ }
1819
+ if (event.headSha !== undefined) receipt.headSha = event.headSha
1820
+ return receipt
1821
+ }
1822
+ return null
1823
+ } catch {
1824
+ return null
1825
+ }
1826
+ }
1827
+ return { find, record: recordEvent }
1828
+ }
1829
+
1830
+ // AIDEV-NOTE: PMR-VDVJ — deterministic effect id: first 12 hex of sha256
1831
+ // over 'ref|effect|command|headSha' (headSha absent = empty segment). Same
1832
+ // input always maps to the same id, which is what makes declare() idempotent.
1833
+ export function effectDeclarationId(input: {
1834
+ ref: string
1835
+ effect: EffectKind
1836
+ command: string
1837
+ headSha?: string
1838
+ }): string {
1839
+ const headSha = input.headSha ?? ''
1840
+ return sha256Hex(
1841
+ `${input.ref}|${input.effect}|${input.command}|${headSha}`,
1842
+ ).slice(0, 12)
1843
+ }
1844
+
1845
+ export interface EffectDeclareInput {
1846
+ ref: string
1847
+ effect: EffectKind
1848
+ command: string
1849
+ recipe: string[]
1850
+ headSha?: string
1851
+ }
1852
+
1853
+ export type EffectDeclarationResult =
1854
+ | { ok: true; record: EffectDeclarationRecord }
1855
+ | { ok: false; reason: string }
1856
+
1857
+ // AIDEV-NOTE: PMR-VDVJ — THE single validation seam for effect declarations.
1858
+ // PMR-5ME4: it now lives next to the journal and createEffectJournal().declare()
1859
+ // runs it on the PRODUCTION write path (it used to be test-only in
1860
+ // flow/effect-gate.ts, which merely re-exports it now). Validates the ref
1861
+ // against the runFileName charset (it lands in the runs dir as a filename),
1862
+ // the effect against the known kinds, command and recipe as non-empty, and
1863
+ // headSha as a full 40-hex SHA (echo-compare requires exact commits). `now`
1864
+ // is injected so tests can pin the timestamp.
1865
+ export function buildEffectDeclaration(
1866
+ input: EffectDeclareInput,
1867
+ now: () => string = () => new Date().toISOString(),
1868
+ ): EffectDeclarationResult {
1869
+ if (runFileName(input.ref) === null) {
1870
+ return {
1871
+ ok: false,
1872
+ reason: `invalid ref "${input.ref}" — must be a safe ticket id (runFileName charset)`,
1873
+ }
1874
+ }
1875
+ if (!EFFECT_KINDS.includes(input.effect)) {
1876
+ return {
1877
+ ok: false,
1878
+ reason: `unknown effect "${String(input.effect)}" — must be one of ${EFFECT_KINDS.join(', ')}`,
1879
+ }
1880
+ }
1881
+ if (input.command.trim().length === 0) {
1882
+ return { ok: false, reason: 'command must be a non-empty string' }
1883
+ }
1884
+ if (!Array.isArray(input.recipe) || input.recipe.length === 0) {
1885
+ return { ok: false, reason: 'recipe must have at least 1 step' }
1886
+ }
1887
+ if (input.recipe.some((step) => step.trim().length === 0)) {
1888
+ return { ok: false, reason: 'recipe steps must all be non-empty' }
1889
+ }
1890
+ if (input.headSha !== undefined && !isFullSha(input.headSha)) {
1891
+ return {
1892
+ ok: false,
1893
+ reason: `headSha "${input.headSha}" must be a full 40-hex SHA`,
1894
+ }
1895
+ }
1896
+ const effectId = effectDeclarationId(input)
1897
+ return {
1898
+ ok: true,
1899
+ record: {
1900
+ effect: input.effect,
1901
+ effectId,
1902
+ command: input.command,
1903
+ recipe: input.recipe,
1904
+ headSha: input.headSha,
1905
+ at: now(),
1906
+ },
1907
+ }
1908
+ }
1909
+
1910
+ /**
1911
+ * AIDEV-NOTE: PMR-VDVJ — STRICT effect journal access, the fail-closed twin
1912
+ * of the best-effort ReceiptJournal. declare() must succeed before a
1913
+ * side-effecting action may run: an invalid ref is rejected (recordRunEvent
1914
+ * JournalOnly would silently no-op, which is fail-open), an append failure is
1915
+ * converted to {ok:false} so the caller refuses the effect, and identical
1916
+ * re-declarations are idempotent (no second journal line). Journal-only on
1917
+ * purpose: O_APPEND is daemon-safe and the projection folds in on the next
1918
+ * full write — readers use the journal.
1919
+ */
1920
+ export interface EffectJournal {
1921
+ declare(
1922
+ input: EffectDeclareInput,
1923
+ ): Promise<{ ok: true; effectId: string } | { ok: false; reason: string }>
1924
+ find(query: {
1925
+ ref: string
1926
+ effect: EffectKind
1927
+ headSha?: string
1928
+ }): Promise<EffectDeclarationRecord | null>
1929
+ }
1930
+
1931
+ export function createEffectJournal(
1932
+ agentDir: string,
1933
+ io?: {
1934
+ readFile: (p: string) => Promise<string>
1935
+ appendFile: (p: string, data: string) => Promise<void>
1936
+ mkdir: (dir: string, recursive: true) => Promise<void>
1937
+ },
1938
+ ): EffectJournal {
1939
+ const readFile = io?.readFile ?? ((p: string) => fs.readFile(p, 'utf8'))
1940
+ const appendFile =
1941
+ io?.appendFile ??
1942
+ (async (p: string, data: string) => {
1943
+ await fs.appendFile(p, data, 'utf8')
1944
+ })
1945
+ const mkdir =
1946
+ io?.mkdir ??
1947
+ (async (dir: string, recursive: true) => {
1948
+ await fs.mkdir(dir, { recursive })
1949
+ })
1950
+
1951
+ const declare = async (
1952
+ input: EffectDeclareInput,
1953
+ ): Promise<
1954
+ { ok: true; effectId: string } | { ok: false; reason: string }
1955
+ > => {
1956
+ // AIDEV-NOTE: PMR-5ME4 — validate through buildEffectDeclaration (the
1957
+ // single seam) BEFORE any journal work: unknown effect, empty command or
1958
+ // recipe, and a non-40-hex headSha are refused here on the production
1959
+ // write path, with no journal line appended.
1960
+ const built = buildEffectDeclaration(input)
1961
+ if (!built.ok) return built
1962
+ const statePath = runStatePath(agentDir, input.ref)
1963
+ // AIDEV-NOTE: PMR-VDVJ — invalid ref must fail here: the journal-only
1964
+ // append would silently no-op and the effect would run undeclared.
1965
+ // buildEffectDeclaration normally rejects the same inputs first; this
1966
+ // check stays as defense-in-depth against a future runStatePath change
1967
+ // silently re-opening that fail-open hole.
1968
+ if (statePath === null) {
1969
+ return {
1970
+ ok: false,
1971
+ reason: `invalid run ref, effect declaration refused (fail-closed): ${input.ref}`,
1972
+ }
1973
+ }
1974
+ const journalPath = journalPathFor(statePath)
1975
+ // AIDEV-NOTE: PMR-VDVJ fix round — mkdir BEFORE the append, same as
1976
+ // recordRunEvent/recordRunEventJournalOnly. Without it a fresh agent dir
1977
+ // (no pi-flow/runs/ yet) fails with ENOENT, the fail-closed conversion
1978
+ // turns that into {ok:false}, and the gate permanently refuses declared
1979
+ // effects until some other writer happens to create the directory.
1980
+ try {
1981
+ await mkdir(path.dirname(journalPath), true)
1982
+ } catch (err) {
1983
+ return {
1984
+ ok: false,
1985
+ reason: `effect declaration could not be recorded in the run journal (fail-closed): ${err instanceof Error ? err.message : String(err)}`,
1986
+ }
1987
+ }
1988
+ const effectId = built.record.effectId
1989
+ // Idempotent: an identical declaration already journaled — do not append.
1990
+ const existing = await find({
1991
+ ref: input.ref,
1992
+ effect: input.effect,
1993
+ headSha: input.headSha,
1994
+ })
1995
+ if (existing !== null && existing.effectId === effectId) {
1996
+ return { ok: true, effectId }
1997
+ }
1998
+ const event: FlowRunEvent = {
1999
+ kind: 'effect-declaration',
2000
+ at: built.record.at,
2001
+ ref: input.ref,
2002
+ effect: input.effect,
2003
+ effectId,
2004
+ command: input.command,
2005
+ recipe: input.recipe,
2006
+ }
2007
+ if (input.headSha !== undefined) event.headSha = input.headSha
2008
+ try {
2009
+ await appendFile(journalPath, `${JSON.stringify(event)}\n`)
2010
+ } catch (err) {
2011
+ return {
2012
+ ok: false,
2013
+ reason: `effect declaration could not be recorded in the run journal (fail-closed): ${err instanceof Error ? err.message : String(err)}`,
2014
+ }
2015
+ }
2016
+ return { ok: true, effectId }
2017
+ }
2018
+
2019
+ const find = async (query: {
2020
+ ref: string
2021
+ effect: EffectKind
2022
+ headSha?: string
2023
+ }): Promise<EffectDeclarationRecord | null> => {
2024
+ const events = await readRunEvents(agentDir, query.ref, { readFile })
2025
+ if (events === null) return null
2026
+ for (const event of events) {
2027
+ if (event.kind !== 'effect-declaration') continue
2028
+ if (event.ref !== query.ref) continue
2029
+ if (event.effect !== query.effect) continue
2030
+ if (query.headSha !== undefined && event.headSha !== query.headSha)
2031
+ continue
2032
+ const record: EffectDeclarationRecord = {
2033
+ effect: event.effect,
2034
+ effectId: event.effectId,
2035
+ command: event.command,
2036
+ recipe: event.recipe,
2037
+ at: event.at,
2038
+ }
2039
+ if (event.headSha !== undefined) record.headSha = event.headSha
2040
+ return record
2041
+ }
2042
+ return null
2043
+ }
2044
+
2045
+ return { declare, find }
2046
+ }