@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,381 @@
1
+ // AIDEV-NOTE: PMR-H1GA (PMR-6E6T 2.1 split) — the v2 emission/live-wait
2
+ // guard, extracted verbatim from flow/loop.ts: the guarded state machine
3
+ // (lastEmittedV2 dedup, lastV2At recency watermark, the reason-aware +
4
+ // lease-bound live-wait flag/deadline) and the v2 emission trio
5
+ // (emitStateChange with the two-dimension master rationale — its SINGLE
6
+ // authoritative home — emitStep, emitV2). Module contract: dependency-light
7
+ // and daemon-safe by construction — value imports are ONLY ./vocabulary.ts
8
+ // and ./live-wait.ts; ../run-state.ts is type-only. No loop state and no
9
+ // deps object: the two clocks/seams arrive through the constructor. The
10
+ // leaseClock closure drives LEASE ARITHMETIC ONLY (loop.ts reads deps.now
11
+ // AT CALL TIME through it — tests mutate h.deps.now after createFlowLoop);
12
+ // event `at` stamps always use this module's real now(). journalV2 is the
13
+ // raw optional seam; emitV2 wraps it so a throwing/absent seam NEVER
14
+ // propagates (ISC-A-5). FlowLoopImpl keeps the public FlowLoop methods as
15
+ // thin stubs owning the IDLE/REF run-lifecycle guards and delegates here.
16
+ // AIDEV-TODO: adding this file to CLOSURE_ROOTS in
17
+ // test/cost-rows-node-only.test.ts would lock the purity contract above,
18
+ // but that is a test modification — deliberately deferred (PMR-H1GA
19
+ // constraint: zero test-file changes). The same constraint leaves the stale
20
+ // pointer at test/loop-state-change.test.ts:1181 ("The full rule lives at
21
+ // the skip predicate's note in flow/loop.ts") unfixed — the rule now lives
22
+ // HERE; a future test-touching ticket should repoint it.
23
+ import type { FlowPhase, FlowRunEvent } from '../run-state.ts'
24
+ import { addSecondsIso, LIVE_WAIT_LEASE_SECONDS } from './live-wait.ts'
25
+ import type { FlowReason, FlowState } from './vocabulary.ts'
26
+ import { FLOW_STATES, reasonOwnsExternalClose } from './vocabulary.ts'
27
+
28
+ // AIDEV-NOTE: PMR-422Q — the REAL wall clock, for event `at` stamps ONLY.
29
+ // Lease arithmetic goes through the injected leaseClock (deps.now-aware);
30
+ // event stamps must stay on the real clock so the existing real-clock
31
+ // recency tests (external observations dated via atOffset) stay untouched.
32
+ function now(): string {
33
+ return new Date().toISOString()
34
+ }
35
+
36
+ export class V2EmissionGuard {
37
+ // AIDEV-NOTE: PMR-ZV9Y 2.1 — guarded v2 emission: the last state-machine
38
+ // state this run emitted. emitStateChange skips when the new state equals
39
+ // this, so running->running re-snapshots never spam the journal (plan
40
+ // "no running→running duplicates"). Seeded on start()/resume from the
41
+ // journal tail (last state-change, else derived via the phase-1 fold).
42
+ private lastEmittedV2: FlowState | null = null
43
+ // AIDEV-NOTE: PMR-ZV9Y fix-round-2 (P2a) — recency watermark for the external
44
+ // observer. The ISO-8601 `at` of the last v2 observation applied to
45
+ // lastEmittedV2, set by BOTH emitStateChange and noteExternalV2State. Fixed-
46
+ // width UTC-`Z` format everywhere, so string compare == chronological compare.
47
+ // null = nothing applied yet (the first external observation always wins).
48
+ private lastV2At: string | null = null
49
+ // AIDEV-NOTE: PMR-0NRH 3.1, reason-aware per PMR-422Q (review blocker 2) —
50
+ // LIVE-WAIT flag (ISC-4). True ONLY while a newer-than-watermark EXTERNAL
51
+ // `state-change` observed a `waiting_human` whose reason closes itself (see
52
+ // SELF_CLOSING_HUMAN_WAITS in flow/vocabulary.ts), i.e. a live tool-journaled
53
+ // human wait with a guaranteed release: an open mid-turn ask_user_question
54
+ // (the ask emitter) or an open code_review gate — and since PMR-422Q that
55
+ // guarantee is DELIVERED BY THE LEASE, not only by the seam's own close. Four
56
+ // semantics, each load-bearing:
57
+ // * EXTERNAL-ONLY (ONE EXCEPTION): written in noteExternalV2State and,
58
+ // as a release, cleared by the loop's OWN successful `running` emission
59
+ // in emitStateChange (the post-expiry self-heal — see the skip rule's note
60
+ // for why this single exception is unambiguous). Apart from that release it
61
+ // is never written in emitStateChange: the loop's own emissions cannot ARM
62
+ // it either way, because their echo through the observer carries
63
+ // `at === lastV2At`
64
+ // (emitStateChange stamps the watermark BEFORE the write) so the
65
+ // pre-existing P2a recency guard skips it before this field is touched.
66
+ // Without that ordering the loop would clear its own hold and the guard
67
+ // would be a no-op.
68
+ // * REASON-GATED (PMR-422Q): arming used to key on `state === 'waiting_human'`
69
+ // alone, which latched the hold on `escalation` — run_attempt escalates and
70
+ // NEVER journals the running return, and the loop's own snapshot('running')
71
+ // that unsticks such a journal is recency-skipped by this method, so
72
+ // nothing could ever clear the flag until start(). Every later
73
+ // loop-emitted waiting_machine / waiting_human / spec-approval pause was
74
+ // silently dropped for the rest of the process's run. Only a reason whose
75
+ // owning seam journals its own close may arm the hold; an absent reason
76
+ // (a three-argument call) never arms, it only clears.
77
+ // * LEASE-BOUND + RENEWED-BY-HEARTBEAT (PMR-422Q): while armed, the hold is
78
+ // only live while `leaseNow() < leaseExpiresAt` — a DEAD-MAN'S SWITCH, not
79
+ // an unbounded flag. Arming stamps the initial lease from the observation
80
+ // `at` (so the hold is live BEFORE the first heartbeat, ISC-3); the owning
81
+ // seam heartbeats it through renewLiveWaitLease while the wait is
82
+ // genuinely open, and a wait nothing renews expires after
83
+ // LIVE_WAIT_LEASE_SECONDS (flow/live-wait.ts) so a broken close can never
84
+ // strand the journal. Release legs, any of: the next newer external
85
+ // observation — for an armed wait that observation IS the ask's own
86
+ // `state-change{running}` close — the loop's own successful `running`
87
+ // emission (the exception above), or plain lease expiry. While the lease
88
+ // is alive emitStateChange holds EVERY non-terminal emission (`running`
89
+ // included, PMR-422Q: a settle that advances during a live ask must not
90
+ // mask a blocked run as working) and releases terminal ones (`halted` /
91
+ // `done` / `stale`) always. Width and release rationale live at the skip
92
+ // rule (see the note in emitStateChange).
93
+ // * RESET-ON-START: in-process state (flag AND lease), so a process that
94
+ // died mid-ask loses both; a stale `waiting_human` journal tail must
95
+ // never pin a restarted run (ISC-10) — the seeded guard +
96
+ // snapshot('running') unstick the journal exactly as today.
97
+ private externalHumanWaitOpen = false
98
+ // AIDEV-NOTE: PMR-422Q — the live-wait LEASE DEADLINE (fixed-width UTC ISO,
99
+ // so a plain string compare against leaseNow() is chronological), sitting
100
+ // beside the flag it bounds. Non-null ONLY while externalHumanWaitOpen is
101
+ // armed: noteExternalV2State stamps it on arming and nulls it on every
102
+ // non-arming apply; the clear-on-running release and the start() reset null
103
+ // it with the flag. renewLiveWaitLease extends it monotonically (max) — a
104
+ // beat can never shorten an already-granted window. Tunables and the
105
+ // window/beat invariant live in flow/live-wait.ts; the lease is NEVER
106
+ // journaled (in-process ping only).
107
+ private leaseExpiresAt: string | null = null
108
+ // AIDEV-NOTE: explicit field declarations + constructor assignment (NOT
109
+ // parameter properties) — node --test runs these suites in strip-only
110
+ // TypeScript mode, which rejects parameter-property syntax.
111
+ private readonly leaseClock: () => string
112
+ private readonly journalV2: (event: FlowRunEvent) => void
113
+
114
+ constructor(
115
+ leaseClock: () => string,
116
+ journalV2: (event: FlowRunEvent) => void,
117
+ ) {
118
+ this.leaseClock = leaseClock
119
+ this.journalV2 = journalV2
120
+ }
121
+
122
+ // AIDEV-NOTE: PMR-ZV9Y 2.1 — start() seeding/reset (PMR-H1GA: moved here
123
+ // from the loop's start()). Seeds the guarded v2 state from the journal
124
+ // tail (index.ts derives it via resumeV2StateFromEvents). When
125
+ // resumeState is absent the guard starts from null so the first
126
+ // snapshot('running') after start() emits; an explicit 'running' seed
127
+ // suppresses the re-emit. (The plan.spec-approval pairing flag is seeded
128
+ // separately in loop.ts's start() — it is run state, not guard state.)
129
+ seed(resumeState: FlowState | undefined): void {
130
+ if (resumeState !== undefined) {
131
+ this.lastEmittedV2 = resumeState
132
+ } else {
133
+ this.lastEmittedV2 = null
134
+ }
135
+ // PMR-ZV9Y fix-round-2 (P2a): a fresh/superseding start resets the recency
136
+ // watermark so a stale `at` from the previous run can never recency-block the
137
+ // new run's external observations. The seed's own timestamp is unknown here
138
+ // (only the state is threaded through resumeState), so null = the first
139
+ // observation (the loop's own emit after start() or a tool write) always
140
+ // applies.
141
+ this.lastV2At = null
142
+ // PMR-0NRH 3.1 (ISC-10): likewise drop the live-wait flag. It is in-process
143
+ // state, so a run restarted after a mid-ask process death must not stay
144
+ // pinned by a stale `waiting_human` journal tail — the seeded guard plus the
145
+ // snapshot('running') after start() unstick the journal exactly as today.
146
+ // PMR-422Q: the LEASE goes with the flag — a restarted run is never pinned
147
+ // and never silently protected by a deadline from the dead process.
148
+ this.externalHumanWaitOpen = false
149
+ this.leaseExpiresAt = null
150
+ }
151
+
152
+ // AIDEV-NOTE: PMR-ZV9Y fix round (P1 blocker) + fix-round-2 (P2a) — see the
153
+ // FlowLoop.noteExternalV2State method doc (flow/loop.ts). Invalidates the
154
+ // guarded v2 emission when a state-change for the ACTIVE run is journaled
155
+ // through the shared fan-out observer by a tool seam (not the loop's own
156
+ // emitStateChange path). The `state` is re-written into lastEmittedV2 so the
157
+ // loop's next DIFFERING emission is not suppressed. Ref-guarded by the
158
+ // CALLER (the loop's noteExternalV2State stub owns the IDLE/REF
159
+ // run-lifecycle guards — a foreign run never moves this run's guard);
160
+ // vocabulary-guarded and MONOTONIC on `at` HERE: an observation
161
+ // older-or-equal than the last applied one is ignored, so a late-routed
162
+ // loop echo cannot revert the guard to a stale state (a tool write bypasses
163
+ // journalSerial and can route after the loop's queued running event). The
164
+ // loop's own emissions also pass the observer: writing the just-emitted
165
+ // state back is a harmless idempotent no-op — and the echo's `at` equals
166
+ // lastV2At so it is recency-skipped, never a re-pin.
167
+ noteExternal(state: FlowState, at: string, reason?: FlowReason | ''): void {
168
+ if (!FLOW_STATES.includes(state)) return
169
+ if (this.lastV2At !== null && at <= this.lastV2At) return
170
+ this.lastEmittedV2 = state
171
+ this.lastV2At = at
172
+ // PMR-0NRH 3.1, reason-aware per PMR-422Q — the live-wait flag follows the
173
+ // SAME observations the guard does, AFTER every existing guard passed (ref,
174
+ // vocabulary, recency) so the loop's own echo can neither arm nor clear it.
175
+ // It ARMS only for a waiting_human whose reason owns its external close
176
+ // (ask emitter / code-review gate) and CLEARS on every other newer external
177
+ // observation, including an absent reason — the ask's `state-change{running}`
178
+ // close is exactly such an observation, which is why a self-closing reason
179
+ // cannot strand the hold, while escalation (no running return) must never
180
+ // arm it.
181
+ let armsLiveWait = false
182
+ if (state === 'waiting_human' && reason !== undefined) {
183
+ armsLiveWait = reasonOwnsExternalClose(reason)
184
+ }
185
+ this.externalHumanWaitOpen = armsLiveWait
186
+ // PMR-422Q: the lease rides the flag — arming stamps the initial window
187
+ // from the observation `at` (the wait's open time, so the hold is live
188
+ // before the first heartbeat), and EVERY non-arming apply nulls it. The
189
+ // ask's `state-change{running}` close is exactly such an apply, so the
190
+ // normal release clears both fields in one step.
191
+ if (armsLiveWait) {
192
+ this.leaseExpiresAt = addSecondsIso(at, LIVE_WAIT_LEASE_SECONDS)
193
+ } else {
194
+ this.leaseExpiresAt = null
195
+ }
196
+ }
197
+
198
+ // AIDEV-NOTE: PMR-422Q — heartbeat entry point (see the FlowLoop method
199
+ // note for the guards; IDLE/REF live on the loop's renewLiveWaitLease
200
+ // stub, the ARMED guard is the early return here). Callers: the ask
201
+ // emitter's in-process beat timer (index.ts wiring, via the loop stub).
202
+ // Nothing else may touch the lease.
203
+ renewLease(): void {
204
+ if (!this.externalHumanWaitOpen) return
205
+ const renewed = addSecondsIso(this.leaseNow(), LIVE_WAIT_LEASE_SECONDS)
206
+ if (this.leaseExpiresAt === null || renewed > this.leaseExpiresAt) {
207
+ this.leaseExpiresAt = renewed
208
+ }
209
+ }
210
+
211
+ // AIDEV-NOTE: PMR-422Q — the LEASE clock: the leaseClock closure injected
212
+ // by loop.ts, which reads deps.now AT CALL TIME when injected (tests)
213
+ // and otherwise returns the module now(). Lease arithmetic ONLY — event
214
+ // stamps keep this module's now() so the existing real-clock recency
215
+ // tests stay untouched.
216
+ private leaseNow(): string {
217
+ return this.leaseClock()
218
+ }
219
+
220
+ /** True while an armed hold still has lease left (dead-man's switch). */
221
+ private leaseAlive(): boolean {
222
+ if (this.leaseExpiresAt === null) return false
223
+ return this.leaseNow() < this.leaseExpiresAt
224
+ }
225
+
226
+ // AIDEV-NOTE: PMR-ZV9Y 2.1 — guarded v2 state-change emission. Skips when the
227
+ // new state equals the last one this instance emitted (seeded from the
228
+ // journal tail), so the repeated snapshot('running') at every phase prompt
229
+ // never spams running->running and a resume does not re-emit its seeded
230
+ // state. `reason` is dropped when the state carries none. The journalV2 seam
231
+ // is optional and wrapped, so a throwing/absent seam NEVER propagates
232
+ // (ISC-A-5) — the loop always proceeds. PMR-H1GA: `ref` is a parameter now
233
+ // (the caller threads its run ref); null = no run in flight, the old
234
+ // `this.state === null` guard.
235
+ emitStateChange(
236
+ ref: string | null,
237
+ state: FlowState,
238
+ reason?: FlowReason,
239
+ ): void {
240
+ if (ref === null) return
241
+ if (this.lastEmittedV2 === state) return
242
+ // AIDEV-NOTE: PMR-0NRH, REASON-AWARE + LEASE-BOUND WIDTH per PMR-422Q — the
243
+ // live-wait guard has two INDEPENDENT dimensions, both load-bearing; do not
244
+ // collapse them.
245
+ // ARMING is REASON-RESTRICTED: the externalHumanWaitOpen flag is set ONLY
246
+ // for a `waiting_human` whose reason is in SELF_CLOSING_HUMAN_WAITS
247
+ // (flow/vocabulary.ts: human_ask_pending, code_review_pending — seams that
248
+ // journal their own `running` close). WHY: a reason-blind flag latched on
249
+ // `escalation` — a `waiting_human` that journals a wait but NEVER a running
250
+ // return — and the loop's own snapshot('running') that would unstick such a
251
+ // journal is recency-skipped in noteExternalV2State, so nothing could ever
252
+ // clear the flag until start(); every later loop-emitted wait was then
253
+ // silently dropped for the rest of the process's run (that latch was review
254
+ // blocker 2). `deviation_gate_rerun` is NEITHER an arming case NOR a WIDTH
255
+ // case: the gate journals `waiting_machine` (tools/deviation.ts, WAIT_KIND
256
+ // machine) STRAIGHT to the fan-out writer (index.ts:
257
+ // registerDeviationReviewTool), so it never reaches this emitStateChange
258
+ // hold at all — neither the narrow predicate nor the reverted wide one
259
+ // could suppress it. It is the PMR-ZV9Y P1 invalidation case noted on
260
+ // noteExternalV2State above. Its observation CLEARS the flag (and the
261
+ // lease with it, PMR-422Q), decided on the STATE dimension: the observed
262
+ // state is `waiting_machine`, so the `state === 'waiting_human'` guard
263
+ // short-circuits and the reason is never consulted (PMR-FM0F — the
264
+ // non-self-closing reason is a secondary note, not the operative
265
+ // mechanism).
266
+ // Absent reason (a three-argument call) never arms, it only clears — which
267
+ // keeps the five protected PMR-ZV9Y tests green UNMODIFIED (they drive the
268
+ // observer without a reason).
269
+ // WIDTH is NON-TERMINAL-while-lease-alive (PMR-422Q): while the flag is
270
+ // armed AND its lease is alive, emitStateChange holds EVERY non-terminal
271
+ // emission — `waiting_machine`, `waiting_human` AND `running` — and only
272
+ // releases the terminal trio (`halted` / `done` / `stale`, which end the
273
+ // run and make the open wait moot). WHY THE RUNNING INCLUSION IS SAFE NOW:
274
+ // the ORIGINAL wide non-terminal hold (bf1d592) stranded every skip path
275
+ // whose close never landed — a fail-closed ask read (flow/ask-emitter.ts)
276
+ // or an unclear code_review answer that skips closeReviewGate
277
+ // (tools/code-review.ts) — at waiting_human for the REST OF THE PROCESS,
278
+ // because nothing could ever release an unbounded flag. The lease is what
279
+ // makes the width safe: a wait nothing heartbeats stops holding after
280
+ // LIVE_WAIT_LEASE_SECONDS (flow/live-wait.ts), and the loop's next
281
+ // non-terminal emission then self-heals the journal.
282
+ // RELEASE has THREE legs, any of which suffices: (1) the next newer external
283
+ // observation — for an armed wait that is the ask's own
284
+ // `state-change{running}` close, which is why arming only self-closing
285
+ // reasons cannot strand the hold; (2) LEASE EXPIRY — a broken wait stops
286
+ // renewing, the deadline passes, and the next emission proceeds (and a
287
+ // proceeding `running` clears flag + lease via leg 3); (3) clear-on-running
288
+ // below: the loop's own SUCCESSFUL `running` emission additionally clears
289
+ // the flag and the lease. Leg 3 is a deliberate, documented EXCEPTION to
290
+ // "the flag is written only in noteExternalV2State": that rule exists
291
+ // because the loop's own ECHO is indistinguishable from an external
292
+ // observation (recency-skipped, so it can neither arm nor clear the flag);
293
+ // this is NOT the echo path, it is the loop's own emission completing,
294
+ // which is unambiguous. Once the loop journals `running` the journal no
295
+ // longer shows the human wait, so holding is moot — and an armed flag over
296
+ // a `running` journal would otherwise suppress every later genuine wait
297
+ // (waiting_machine{subagent_in_flight}, waiting_human{subagent_ask_pending})
298
+ // for the rest of the process, the original bug class this feature removes.
299
+ // WHAT REMAINS (bounded, PMR-422Q): the board is either right or wrong for
300
+ // at most the lease window — never wrong forever. A LIVE wait (heartbeats
301
+ // arriving) holds indefinitely, no matter how long the human takes; a
302
+ // BROKEN wait (close never landed, beats stopped) holds at most
303
+ // LIVE_WAIT_LEASE_SECONDS past the last beat, and the journal self-heals
304
+ // at the loop's NEXT emission opportunity after that — bounded by the
305
+ // current phase turn, never open-ended. Pinned in test/loop-state-change.
306
+ // test.ts by the inverted live-ask hold plus the lease expiry/renewal
307
+ // cases.
308
+ // The early return MUST precede every mutation: recording the state or
309
+ // advancing the watermark on the held path would desync the guard (the next
310
+ // real emission wrongly suppressed) and recency-skip the ask's own close,
311
+ // pinning the journal at waiting_human forever. The clear-on-running release
312
+ // sits AFTER this return for exactly that reason — a HELD running must not
313
+ // clear the flag, only a run that actually journalled running may.
314
+ if (
315
+ this.externalHumanWaitOpen &&
316
+ this.leaseAlive() &&
317
+ state !== 'halted' &&
318
+ state !== 'done' &&
319
+ state !== 'stale'
320
+ ) {
321
+ return
322
+ }
323
+ this.lastEmittedV2 = state
324
+ // PMR-0NRH review blocker 3 + PMR-422Q: the loop's own successful `running`
325
+ // emission is the post-expiry self-heal for a wait whose external close
326
+ // never landed — it clears the flag AND the lease. See the RELEASE
327
+ // paragraph above for why this single exception is safe and where it sits
328
+ // relative to the held path.
329
+ if (state === 'running') {
330
+ this.externalHumanWaitOpen = false
331
+ this.leaseExpiresAt = null
332
+ }
333
+ const event: FlowRunEvent = {
334
+ kind: 'state-change',
335
+ at: now(),
336
+ ref,
337
+ state,
338
+ }
339
+ // PMR-ZV9Y fix-round-2 (P2a): the loop's OWN emission advances the recency
340
+ // watermark unconditionally (no comparison) — so a future-dated stale external
341
+ // write can never lock the loop out of emitting. The echo of this same event
342
+ // back through noteExternalV2State carries at === lastV2At, so it is
343
+ // recency-skipped (older-or-equal): the idempotent no-op holds.
344
+ this.lastV2At = event.at
345
+ if (reason !== undefined) {
346
+ event.reason = reason
347
+ }
348
+ this.emitV2(event)
349
+ }
350
+
351
+ // AIDEV-NOTE: PMR-ZV9Y 2.1 — journal-only v2 step boundary. step-start and
352
+ // step-stop are NOT state-guarded (they are paired evidence, not a
353
+ // last-wins state); they still route through the same never-throw seam.
354
+ // PMR-H1GA: `ref` is a parameter now; null = no run in flight.
355
+ emitStep(
356
+ kind: 'step-start' | 'step-stop',
357
+ ref: string | null,
358
+ phase: FlowPhase,
359
+ step: string,
360
+ ): void {
361
+ if (ref === null) return
362
+ this.emitV2({
363
+ kind,
364
+ at: now(),
365
+ ref,
366
+ phase,
367
+ step,
368
+ })
369
+ }
370
+
371
+ // AIDEV-NOTE: PMR-ZV9Y 2.1 — the single best-effort v2 write. journalV2 is
372
+ // optional (older harnesses/consumers omit it → no-op) and wrapped so a
373
+ // throwing seam is swallowed; the loop must NEVER halt on a telemetry write.
374
+ private emitV2(event: FlowRunEvent): void {
375
+ try {
376
+ this.journalV2(event)
377
+ } catch {
378
+ // best-effort — never-throw (ISC-A-5)
379
+ }
380
+ }
381
+ }
@@ -0,0 +1,100 @@
1
+ // AIDEV-NOTE: PMR-XVKZ 1.1 (PMR-H1GA split) — the pure v2 resume/seed
2
+ // helpers, extracted verbatim from flow/loop.ts. Module contract: pure
3
+ // functions over the run-event list — no loop state, no deps, no clock, no
4
+ // side effects. The one VALUE import (`projectRunState` from
5
+ // ../run-state.ts) keeps this module session-side, NOT daemon-pure, by
6
+ // design: it reads the same phase-1 projection the loop resumes from.
7
+ // loop.ts re-exports the two public functions so index.ts and the
8
+ // loop-state-change suite keep resolving them from flow/loop.ts, and
9
+ // imports v2StateForStatus back for its snapshot choke point.
10
+ import type { FlowRunEvent, LoopRunStatus } from '../run-state.ts'
11
+ import { projectRunState } from '../run-state.ts'
12
+ import type { FlowState } from './vocabulary.ts'
13
+ import { FLOW_STATES } from './vocabulary.ts'
14
+
15
+ // AIDEV-NOTE: PMR-ZV9Y 2.1 — the v1 `LoopRunStatus` → v2 `FlowState` map (the
16
+ // snapshot choke point's status is v1; the state-change it emits is v2).
17
+ // running→running, paused→waiting_human, halted→halted, done→done. waiting_
18
+ // machine is never reached through this map (only the subagent-in-flight
19
+ // branch emits it, and that site has no snapshot — see onSettled).
20
+ export function v2StateForStatus(status: LoopRunStatus): FlowState {
21
+ if (status === 'running') {
22
+ return 'running'
23
+ }
24
+ if (status === 'paused') {
25
+ return 'waiting_human'
26
+ }
27
+ if (status === 'halted') {
28
+ return 'halted'
29
+ }
30
+ return 'done'
31
+ }
32
+
33
+ /**
34
+ * AIDEV-NOTE: PMR-ZV9Y 2.1 — seed the loop's guarded v2 emission state from
35
+ * the journal tail: the LAST `state-change` event wins (validated against the
36
+ * closed enum — journals parse leniently, same posture as applyEvent), else
37
+ * derived from the projected v1 loop status via the phase-1 fold + the
38
+ * v1→v2 map. `undefined` = nothing seeded (fresh run / no journal), so the
39
+ * first snapshot('running') emits.
40
+ */
41
+ export function resumeV2StateFromEvents(
42
+ events: readonly FlowRunEvent[] | null,
43
+ ): FlowState | undefined {
44
+ if (events === null) {
45
+ return undefined
46
+ }
47
+ let last: FlowState | undefined
48
+ for (const event of events) {
49
+ if (event.kind !== 'state-change') {
50
+ continue
51
+ }
52
+ if (!FLOW_STATES.includes(event.state)) {
53
+ continue
54
+ }
55
+ last = event.state
56
+ }
57
+ if (last !== undefined) {
58
+ return last
59
+ }
60
+ const projected = projectRunState(events)
61
+ if (projected !== null && projected.loop !== undefined) {
62
+ return v2StateForStatus(projected.loop.status)
63
+ }
64
+ return undefined
65
+ }
66
+
67
+ /**
68
+ * AIDEV-NOTE: PMR-ZV9Y 2.1 — is a plan.spec-approval step open on resume? A
69
+ * restart after the spec-approval pause must still emit the matching
70
+ * step-stop; this flag (seeded here from the raw step events) drives the
71
+ * restart close in closeSpecApprovalStepIfOpen (flow/loop-settle.ts, called
72
+ * from start()) so only a real, unresolved start yields a stop. PMR-F79K:
73
+ * that restart close is the ONLY plan.spec-approval close — the old
74
+ * advanceAfter pairing-guard stop was removed as unreachable. The step
75
+ * boundary is journaled-only evidence, so the scan is over the raw event
76
+ * list, not the projection.
77
+ */
78
+ export function resumePlanApprovalOpenFromEvents(
79
+ events: readonly FlowRunEvent[] | null,
80
+ ): boolean {
81
+ if (events === null) {
82
+ return false
83
+ }
84
+ let open = false
85
+ for (const event of events) {
86
+ if (event.kind !== 'step-start' && event.kind !== 'step-stop') {
87
+ continue
88
+ }
89
+ if (event.phase !== 'plan' || event.step !== 'plan.spec-approval') {
90
+ continue
91
+ }
92
+ if (event.kind === 'step-start') {
93
+ open = true
94
+ }
95
+ if (event.kind === 'step-stop') {
96
+ open = false
97
+ }
98
+ }
99
+ return open
100
+ }