@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/flow/answer.ts ADDED
@@ -0,0 +1,183 @@
1
+ // AIDEV-NOTE: PMR-R5VB — `/flow answer <ref> <choice>` parser + orchestration.
2
+ // HUMAN-ONLY GUARANTEE: this module must NEVER trigger a model turn. It has
3
+ // no pi import, no model-turn API of any kind, and no ctx parameter — the
4
+ // injected AnswerDeps object is the only side-effect surface, so the agent structurally
5
+ // cannot invoke this path on its own behalf (subtask 1.4 wires the /flow
6
+ // handler dispatch on the leading `answer` token BEFORE parseFlowArgs).
7
+ // AIDEV-NOTE: PMR-DMHH — the optional AnswerDeps.onGateAnswered hook is the
8
+ // SOLE wake seam: it fires only after a successful receipt record, and its
9
+ // implementation lives outside this module (dispatcher-owned, wired in
10
+ // index.ts). This module itself never injects a user message.
11
+ // AIDEV-NOTE: PMR-V31Z 7.1 — the review gate (pass/fail answers, the
12
+ // review-answer metadata write, and the PMR-5NZB 2.3 head-stamp seam that
13
+ // pinned review passes as code_review command-receipts) is DELETED: no flow
14
+ // phase calls code_review anymore and flow_land no longer reads humanReview
15
+ // receipts. `/flow answer` now serves ONLY the spec gate (approve/reject,
16
+ // spec-answer receipts) — the receipt source spec_approve accepts.
17
+
18
+ import type { AnswerChoice, AnswerGate } from '../aven/client.ts'
19
+ import { parseRefKind } from './ref-kind.ts'
20
+
21
+ export type FlowAnswerArgs =
22
+ | { kind: 'not-answer' }
23
+ | { kind: 'answer-help' }
24
+ | { kind: 'answer'; ref: string; choice: AnswerChoice }
25
+
26
+ export const answerUsageText =
27
+ 'Usage: /flow answer <aven-ref> <choice>\n' +
28
+ 'Records a protected human decision on the aven ticket.\n' +
29
+ 'Choices — spec gate only: approve | reject\n' +
30
+ 'Example: /flow answer PMR-ZTVG approve'
31
+
32
+ const CHOICE_GATE: Record<AnswerChoice, AnswerGate> = {
33
+ approve: 'spec',
34
+ reject: 'spec',
35
+ }
36
+
37
+ export function parseFlowAnswerArgs(raw: string): FlowAnswerArgs {
38
+ const parts = raw.trim().split(/\s+/).filter(Boolean)
39
+ if (parts[0] !== 'answer') return { kind: 'not-answer' }
40
+ if (parts.length !== 3) return { kind: 'answer-help' }
41
+ const refPart = parts[1] ?? ''
42
+ const choice = parts[2] ?? ''
43
+ const parsed = parseRefKind(refPart)
44
+ if (parsed.kind === 'jira') return { kind: 'answer-help' }
45
+ if (choice !== 'approve' && choice !== 'reject') {
46
+ return { kind: 'answer-help' }
47
+ }
48
+ return { kind: 'answer', ref: parsed.ref, choice }
49
+ }
50
+
51
+ export interface AnswerDeps {
52
+ notify(message: string, level: 'info' | 'warning' | 'error'): void
53
+ /** Guarded aven metadata write; false = failed (metadata is authoritative). */
54
+ writeGateAnswer(
55
+ ref: string,
56
+ gate: AnswerGate,
57
+ choice: AnswerChoice,
58
+ ): Promise<boolean>
59
+ /** Aven note write; false = failed (audit only — the answer still stands). */
60
+ writeAvenNote(ref: string, text: string): Promise<boolean>
61
+ /** Best-effort local journal append; may throw, callers swallow. */
62
+ appendJournal(event: FlowRunEventSubset): Promise<void>
63
+ now(): string
64
+ // AIDEV-NOTE: PMR-DMHH — optional post-record wake hook. Invoked at the END
65
+ // of executeFlowAnswer, only after a successful metadata write (the receipt
66
+ // is durable) and after the final notify; wrapped in a fail-soft try/catch
67
+ // so a wake failure never retro-fails the answer. Dispatcher-owned: the
68
+ // implementation (flow/answer-wake.ts wakeOnGateAnswer plus the pi
69
+ // user-message injection) is wired in index.ts — this module stays pi-free.
70
+ onGateAnswered?(
71
+ ref: string,
72
+ gate: AnswerGate,
73
+ choice: AnswerChoice,
74
+ ): Promise<void> | void
75
+ // AIDEV-NOTE: PMR-N0D5 — optional plan-revision binding hook for spec
76
+ // approve answers. Invoked ONLY for choice 'approve' after
77
+ // the metadata write succeeded; the returned hash (sha256 of the plan
78
+ // file content at the ticket's plan-path, aven/client.ts
79
+ // readPlanRevision) is journaled WITH the gate-answer event so
80
+ // spec_approve / the plan receipt gate can refuse a stale answer after
81
+ // the plan changed. null or a throw is FAIL-SOFT for the answer (the
82
+ // human decision stands): the journal event carries no binding and a
83
+ // warning tells the human the approval is unbindable until a re-answer
84
+ // — the gates refuse fail-closed on an unbound journal answer.
85
+ // Dispatcher-owned (index.ts makeAnswerDeps); this module stays pi-free.
86
+ bindPlanRevision?(ref: string): Promise<string | null>
87
+ }
88
+
89
+ // AIDEV-NOTE: structural subset of run-state.ts's FlowRunEvent 'gate-answer'
90
+ // member — avoids importing run-state (and its transitive graph) into this
91
+ // model-turn-free module. run-state's own member narrows this shape: this
92
+ // module only ever WRITES spec-review answers now (the code-review journal
93
+ // kind lives on in run-state for legacy-journal replay).
94
+ type FlowRunEventSubset = {
95
+ kind: 'gate-answer'
96
+ at: string
97
+ ref: string
98
+ gate: 'spec-review'
99
+ choice: AnswerChoice
100
+ planRevision?: string
101
+ }
102
+
103
+ export async function executeFlowAnswer(
104
+ args: { ref: string; choice: AnswerChoice },
105
+ deps: AnswerDeps,
106
+ ): Promise<void> {
107
+ const { ref, choice } = args
108
+ const gate = CHOICE_GATE[choice]
109
+
110
+ // 1. Metadata write — authoritative. On failure nothing else is attempted.
111
+ const metadataOk = await deps.writeGateAnswer(ref, gate, choice)
112
+ if (!metadataOk) {
113
+ deps.notify(
114
+ `flow answer NOT recorded: ${ref} ${choice} — aven write failed; fix and re-run /flow answer ${ref} ${choice}`,
115
+ 'error',
116
+ )
117
+ return
118
+ }
119
+
120
+ // 2. Audit note (marker-note precedent: hasBlockersNoteSince, aven/client.ts).
121
+ const noteOk = await deps.writeAvenNote(
122
+ ref,
123
+ `flow-answer: ${gate}=${choice}\nanswered-at: ${deps.now()}\nanswered-by: human (/flow answer)`,
124
+ )
125
+ if (!noteOk) {
126
+ deps.notify(
127
+ `flow answer note failed for ${ref} — metadata answer still stands`,
128
+ 'warning',
129
+ )
130
+ }
131
+
132
+ // 3. Local journal projection — best effort. Spec-gate answers journal as
133
+ // 'spec-review'; the 'code-review' journal kind belongs to the deleted
134
+ // review gate (PMR-V31Z 7.1) and is never written from here anymore.
135
+ // AIDEV-NOTE: PMR-N0D5 — a spec approve answer binds to the CURRENT plan
136
+ // revision (content hash at the ticket's plan-path) journaled WITH the
137
+ // answer; the key is omitted (never undefined) when unresolvable so the
138
+ // journal line stays byte-identical to the pre-N0D5 shape. A null or
139
+ // throwing binding hook is SILENT here (notify counts are pinned by
140
+ // flow.test.ts): the answer still stands and journals unbound, and the
141
+ // gates (spec_approve / flow_phase_complete plan) refuse fail-closed on
142
+ // an unbound journaled answer with the exact re-answer recovery.
143
+ const journalEvent: FlowRunEventSubset = {
144
+ kind: 'gate-answer',
145
+ at: deps.now(),
146
+ ref,
147
+ gate: 'spec-review',
148
+ choice,
149
+ }
150
+ if (choice === 'approve') {
151
+ if (deps.bindPlanRevision !== undefined) {
152
+ let bound: string | null = null
153
+ try {
154
+ bound = await deps.bindPlanRevision(ref)
155
+ } catch {
156
+ bound = null
157
+ }
158
+ if (bound !== null) {
159
+ journalEvent.planRevision = bound
160
+ }
161
+ }
162
+ }
163
+ try {
164
+ await deps.appendJournal(journalEvent)
165
+ } catch {
166
+ // Swallowed: journal is a projection, the aven metadata is authoritative.
167
+ }
168
+
169
+ deps.notify(
170
+ `flow answer: ${ref} ${gate}=${choice} recorded (aven metadata + note + journal)`,
171
+ 'info',
172
+ )
173
+
174
+ // AIDEV-NOTE: PMR-DMHH — post-record wake hook (optional, dispatcher-owned).
175
+ // Fail-soft: the receipt is already durable; a wake failure never fails the answer.
176
+ if (deps.onGateAnswered !== undefined) {
177
+ try {
178
+ await deps.onGateAnswered(ref, gate, choice)
179
+ } catch {
180
+ // Swallowed — the dispatcher's implementation notifies on failure.
181
+ }
182
+ }
183
+ }
package/flow/args.ts ADDED
@@ -0,0 +1,48 @@
1
+ // AIDEV-NOTE: Pure /flow arg parsing — ref only (PMR-Z2K7: --skip-research
2
+ // removed with the research phase). Same jira/aven split as implement/args.ts.
3
+ // Yolo mode (PMR yolo plan 1.1): `--yolo` may trail a ref (runs without gates)
4
+ // or stand alone as a picker invocation. It must NEVER fall through to
5
+ // parseRefKind — '--yolo' matches the ref charset and would start a run for a
6
+ // ticket named '--yolo'.
7
+
8
+ import { parseRefKind } from './ref-kind.ts'
9
+
10
+ // AIDEV-NOTE: PMR-N181 — exported so index.ts's usage notify and its test
11
+ // pin one string. Mentions --yolo (personal-mode only, PMR-ZRMQ).
12
+ export const FLOW_USAGE =
13
+ 'Usage: /flow <jira-id | aven-ref | aven:<ref> | jira:<key>> [--yolo] | /flow --yolo. --yolo runs without the receipt gates (personal mode only). Brainstorm topics go through /brainstorm.'
14
+
15
+ export type FlowArgs =
16
+ | { kind: 'jira'; jiraId: string; yolo: boolean }
17
+ | { kind: 'aven'; ref: string; yolo: boolean }
18
+ | { kind: 'picker'; yolo: true }
19
+ | { kind: 'help' }
20
+
21
+ export function parseFlowArgs(raw: string): FlowArgs {
22
+ const parts = raw.trim().split(/\s+/)
23
+ if (parts.length === 0 || parts[0] === '') return { kind: 'help' }
24
+ if (parts.length > 2) return { kind: 'help' }
25
+ const token = parts[0] ?? ''
26
+ // PMR-N0W6: a literal '/flow help' is a usage request, not a run for a
27
+ // ticket named 'help' — reserve the exact token (case-insensitive) in every
28
+ // shape. Similar-but-different tokens ('helpme') still parse as refs.
29
+ if (token.toLowerCase() === 'help') return { kind: 'help' }
30
+ if (parts.length === 1) {
31
+ // Single token: bare '--yolo' is the picker invocation — reserved here so
32
+ // it never reaches parseRefKind ('--yolo' matches the ref charset).
33
+ if (token === '--yolo') return { kind: 'picker', yolo: true }
34
+ return parseRefToken(token, false)
35
+ }
36
+ // Two tokens: '<ref> --yolo' only. Flag-first ('--yolo <ref>') is usage.
37
+ const flag = parts[1] ?? ''
38
+ if (flag !== '--yolo') return { kind: 'help' }
39
+ return parseRefToken(token, true)
40
+ }
41
+
42
+ function parseRefToken(token: string, yolo: boolean): FlowArgs {
43
+ const parsed = parseRefKind(token)
44
+ if (parsed.kind === 'jira') {
45
+ return { kind: 'jira', jiraId: parsed.jiraId, yolo }
46
+ }
47
+ return { kind: 'aven', ref: parsed.ref, yolo }
48
+ }
@@ -0,0 +1,331 @@
1
+ // AIDEV-NOTE: PMR-0NRH 2.1 — generic ask emitter on the tool_call /
2
+ // tool_result(+tool_execution_end) hook pair. A plain ask_user_question
3
+ // issued inside an OPEN agent turn is invisible to settle-based v2 emission
4
+ // (the turn never settles while the ask blocks, so pi_flow_state keeps
5
+ // serving the last emitted value for the whole wait). This hook pair wraps
6
+ // the ask in the SAME open turn: journal state-change{waiting_human,
7
+ // human_ask_pending} on tool_call (Pi awaits the handler before executing the
8
+ // tool, so the line lands BEFORE the ask blocks) and state-change{running}
9
+ // when the call finalizes.
10
+ //
11
+ // TWO-TIER DEDUPE (the critical contract):
12
+ // - PRIMARY: skip the open outright when `parentToolCallId` is set — a nested
13
+ // call is one made by another tool via ctx.executeTool, and such a tool
14
+ // owns and journals its own wait (tools/code-review.ts does exactly this).
15
+ // Nested calls re-fire the tool_call/tool_result handlers and carry
16
+ // parentToolCallId with toolCallId assigned by Pi as `<parent id>/<n>` —
17
+ // docs/extensions.md "Calling Other Tools". This check is deterministic and
18
+ // does no journal I/O. It runs before any CLOSE tracking — heartbeat tracking
19
+ // deliberately covers nested asks (PMR-422Q): a nested ask still blocks the
20
+ // human so it must keep the live-wait lease alive, while its close/journal
21
+ // stays a Map miss on openAsks (the owning tool closes its own wait).
22
+ // - SECONDARY: for a non-nested open, scan the journal tail (lastV2StateRecord,
23
+ // last state-change wins, FLOW_STATES-validated) and skip if it already
24
+ // reads waiting_human — covers a loop-owned wait (e.g.
25
+ // subagent_ask_pending) and a second concurrent ask in this session. A
26
+ // failed/unreadable journal degrades to "no open wait" (fail-open: a
27
+ // possibly-duplicate waiting_human line is still honest evidence).
28
+ //
29
+ // AIDEV-NOTE: PMR-0NRH fix round (review blocker 1) — the dedupe above gates
30
+ // only the JOURNALING of the open, never the TRACKING of the ask, and the
31
+ // close is reference-counted and reason-checked. Why: pi runs the tool calls
32
+ // of one assistant message in PARALLEL by default — tool calls "run in
33
+ // parallel by default" (docs/extensions.md:2305) and sibling calls are
34
+ // "preflighted sequentially, then executed concurrently"
35
+ // (docs/extensions.md:979); ask_user_question declares no executionMode. In
36
+ // executeToolCallsParallel every prepareToolCall — i.e. every tool_call
37
+ // handler — therefore runs in the initial loop BEFORE Promise.all executes
38
+ // any tool. So a batch of N asks fires all N handlers up front: ask #1
39
+ // journals the open, asks #2..N hit the secondary dedupe and journal nothing,
40
+ // then the asks serialize on the shared UI lock. Ungated, ask #1's
41
+ // finalize would journal state-change{running} while ask #2 still blocked the
42
+ // human — the board flips to running, the Waiting-on-me row disappears, no
43
+ // desktop page fires, and human_ask_pending wait-seconds are under-counted.
44
+ // ask_user_question's own promptGuidelines tell the model to "make multiple
45
+ // separate ask_user_question tool calls instead of combining them", so
46
+ // batching is the encouraged shape, not a corner case.
47
+ //
48
+ // THE SEMANTICS NOW:
49
+ // 1. TRACKING (refcount + ref lookup): openAsks maps toolCallId -> ref for
50
+ // EVERY tracked non-nested ask, inserted right after the toolName /
51
+ // parentToolCallId / getActiveRef() / writer checks — i.e. whenever this
52
+ // emitter is responsible for the ask — regardless of whether its open was
53
+ // actually journaled.
54
+ // 2. REFCOUNTED CLOSE: finalize deletes the id and returns WITHOUT writing
55
+ // while openAsks is still non-empty (other asks still block the human).
56
+ // Only the finalize that empties the Map may close the wait.
57
+ // 3. REASON-CHECKED CLOSE: even when the Map is empty, re-read the journal
58
+ // tail with lastV2StateRecord(events) and journal state-change{running} ONLY
59
+ // when that tail is waiting_human with reason human_ask_pending, i.e. our
60
+ // wait is the one still open. Any other reason (notably code_review_pending)
61
+ // or any non-waiting_human tail means another seam owns the wait or it is
62
+ // already closed — write nothing. That is what makes the batched code_review
63
+ // case correct: a plain ask's close must not clear the gate's still-open wait.
64
+ // AIDEV-NOTE: PMR-0NRH fix round 2 (finding P2-a) — BOTH sides now derive the
65
+ // tail from the SAME helper (lastV2StateRecord: a raw FLOW_STATES-validated
66
+ // state-change scan, no run-start precondition). They previously differed: the
67
+ // open used resumeV2StateFromEvents (raw scan, works on a journal whose
68
+ // run-start line is missing) while the close used projectRunState, whose
69
+ // run-start precondition is STRICTLY STRONGER — so a journal the emitter could
70
+ // open it could never close (the reviewer's P2-a proof, pinned by the
71
+ // 'P2-a: a journal with NO run-start' test). Deriving both from one scan
72
+ // removes the asymmetry; it also let this module drop its cross-module import
73
+ // of resumeV2StateFromEvents from ./loop.ts.
74
+ // 4. FAIL CLOSED AT CLOSE: an unreadable/absent tail (readEvents rejects,
75
+ // returns null, or a journal from which no valid state-change can be derived
76
+ // by lastV2StateRecord) means NO running is journaled. This is the opposite of
77
+ // the fail-OPEN rule on the open side, and the asymmetry is intentional: a
78
+ // false `running` is the exact bug being fixed (it destroys the human wait —
79
+ // invisible ask, no page, under-counted seconds) and cannot be undone from
80
+ // here, whereas a stale `waiting_human` is recoverable — the loop's next
81
+ // emitStateChange('running') is NOT a competing wait under the narrow guard
82
+ // predicate (flow/v2-emission.ts), so it still emits and additionally clears the
83
+ // loop's live-wait flag, unsticking the journal. AIDEV-NOTE: PMR-0NRH fix
84
+ // round 2 (review blocker 3) — this self-heal is TRUE AGAIN: bf1d592 briefly
85
+ // widened the loop hold to every non-terminal state, which suppressed the
86
+ // loop's own `running` and made a skipped close strand the journal for the
87
+ // whole process. That widening is reverted to the narrow two-competing-wait
88
+ // hold (and reason-aware arming was what actually fixed the escalate latch),
89
+ // so the recovery this asymmetry relies on holds. See the skip-rule note in
90
+ // flow/v2-emission.ts.
91
+ // AIDEV-NOTE: PMR-422Q 2.1 — the stale-`waiting_human` recovery now has a
92
+ // SECOND, stronger guarantee: the heartbeat stops at finalize. A skipped
93
+ // close still deletes the id from heartbeatAsks (first statement of closeAsk
94
+ // for EVERY finalize, nested or plain), so beats stop, the lease expires
95
+ // within LIVE_WAIT_LEASE_SECONDS, and the loop's next running emission after
96
+ // expiry self-heals the journal — a stale waiting_human is bounded, not
97
+ // permanent.
98
+ //
99
+ // AIDEV-NOTE: PMR-0NRH fix round — MAP-GATED CLOSE, stated ONCE (the older
100
+ // pre-refcount paragraph that sat here next to its own SUPERSEDED correction is
101
+ // folded into this one accurate contract). openAsks (toolCallId -> ref)
102
+ // guarantees a close can NEVER fire for a call this emitter did not TRACK — the
103
+ // Map key is set on tracking, not on a journaled open, which is the wording
104
+ // docs/pi-flow-observability.md uses too (defence in depth for tool-owned
105
+ // nested asks). TRACKING IS UNCONDITIONAL: an
106
+ // id is remembered for every tracked non-nested ask whether or not its open
107
+ // write landed, so the record() boolean does not decide tracking. The close is
108
+ // refcounted (rule 2) and reason-checked (rule 3), so it may write nothing:
109
+ // tool_result-then-tool_execution_end emits AT MOST ONE running record, not
110
+ // exactly one (docs/pi-flow-observability.md already says "at most one"). The
111
+ // property the older wording protected — a failed open must not produce an
112
+ // orphan close — still holds, enforced one level later: the failed write never
113
+ // reached the journal, so at close time the tail does not read our wait and
114
+ // rule 3 writes nothing.
115
+ //
116
+ // NEVER-THROW (ISC-A-5): handler bodies swallow all errors — a journal
117
+ // failure must never fail the ask or the tool call. OPTIONAL WRITER
118
+ // (ISC-A-2): deps.writer undefined = complete no-op, zero events. The
119
+ // emitter never imports or constructs a writer itself — index.ts passes THE
120
+ // single wrapped fan-out writer so onV2StateChangeObserved keeps the loop
121
+ // guard in sync (single-writer seam).
122
+ //
123
+ // AIDEV-NOTE: PMR-422Q 2.1 — HEARTBEAT ORACLE. This emitter is the single
124
+ // source of live-wait heartbeats for the renewing lease in flow/v2-emission.ts. While
125
+ // ANY tracked ask_user_question is in-flight it calls deps.renewLease(ref) on a
126
+ // fixed interval so the loop's externalHumanWait hold stays alive for as long
127
+ // as a human is genuinely being asked; when the LAST tracked ask finalizes the
128
+ // interval stops and the lease is left to expire within LIVE_WAIT_LEASE_SECONDS.
129
+ // A SEPARATE heartbeatAsks map (toolCallId -> ref) tracks BOTH plain and nested
130
+ // asks — a nested ask (e.g. the code-review gate's ask) still blocks the human,
131
+ // so it must keep the lease alive; the journaling/close refcount (openAsks)
132
+ // stays plain-only and untouched. The beat is a direct in-process call, never a
133
+ // journal write (ISC-A-2). The interval is unref'd so it can never hold the
134
+ // process open, and is cleared on the 1->0 transition so it cannot leak. With
135
+ // renewLease unwired (no deps.renewLease) no timer is ever started and this
136
+ // module behaves exactly as before PMR-422Q.
137
+
138
+ import type { FlowRunEvent } from '../run-state.ts'
139
+ import type { EventWriter } from '../server/writer.ts'
140
+ import { LIVE_WAIT_HEARTBEAT_MS } from './live-wait.ts'
141
+ import type { FlowReason, FlowState } from './vocabulary.ts'
142
+ import { FLOW_STATES } from './vocabulary.ts'
143
+
144
+ export interface AskEmitterDeps {
145
+ /** The session's active flow ref (loop.activeRef()); null = no run bound. */
146
+ getActiveRef: () => string | null
147
+ /** THE wrapped fan-out writer (index.ts:537). Optional = no-op (ISC-A-2). */
148
+ writer?: EventWriter
149
+ /** Journal read for the dedupe scan: readRunEvents(getAgentDir(), ref). */
150
+ readEvents: (ref: string) => Promise<readonly FlowRunEvent[] | null>
151
+ now: () => string
152
+ /**
153
+ * PMR-422Q — in-process lease-renewal ping (loop.renewLiveWaitLease). When
154
+ * wired, this emitter is the heartbeat oracle: while ANY tracked ask
155
+ * (plain OR nested) is in-flight it renews each distinct tracked ref on
156
+ * `heartbeatMs`. Optional — absent means no timer, identical to pre-422Q.
157
+ */
158
+ renewLease?: (ref: string) => void
159
+ /** Beat interval, ms. Defaults to LIVE_WAIT_HEARTBEAT_MS. */
160
+ heartbeatMs?: number
161
+ }
162
+
163
+ export interface AskEmitter {
164
+ /** pi.on('tool_call', …) — journals the open before the ask blocks. */
165
+ onToolCall: (event: {
166
+ toolName: string
167
+ toolCallId: string
168
+ /** Present when another tool made this call (docs/extensions.md:2794). */
169
+ parentToolCallId?: string
170
+ }) => Promise<void>
171
+ /** pi.on('tool_result'|'tool_execution_end', …) — journals the close, first-wins. */
172
+ onToolFinalized: (event: { toolCallId: string }) => Promise<void>
173
+ }
174
+
175
+ /**
176
+ * AIDEV-NOTE: PMR-0NRH fix round 2 (finding P2-a) — the SINGLE journal-tail
177
+ * derivation both sides of this module use. The open used to scan raw
178
+ * `state-change` lines via resumeV2StateFromEvents while the close used
179
+ * projectRunState(events)?.currentState, whose `run-start` precondition is
180
+ * strictly STRONGER — so the reviewer proved a journal this emitter can OPEN but
181
+ * never CLOSE (a swallowed run-start write at start(), then a later successful
182
+ * state-change write). Both sides now read the tail the same, more permissive
183
+ * way: the LAST `state-change` line wins, validated against the closed
184
+ * FLOW_STATES vocabulary exactly as resumeV2StateFromEvents does, returning its
185
+ * {state, reason} or undefined (no events / no valid state-change). `null` input
186
+ * (unreadable journal) returns undefined, so the close stays fail-CLOSED. The
187
+ * open decides on `state === 'waiting_human'`; the close on
188
+ * `state === 'waiting_human' && reason === 'human_ask_pending'`. Local to this
189
+ * module because the symmetry is its private concern.
190
+ */
191
+ function lastV2StateRecord(
192
+ events: readonly FlowRunEvent[] | null,
193
+ ): { state: FlowState; reason: FlowReason | '' } | undefined {
194
+ if (events === null) {
195
+ return undefined
196
+ }
197
+ let last: { state: FlowState; reason: FlowReason | '' } | undefined
198
+ for (const event of events) {
199
+ if (event.kind !== 'state-change') {
200
+ continue
201
+ }
202
+ if (!FLOW_STATES.includes(event.state)) {
203
+ continue
204
+ }
205
+ last = { state: event.state, reason: event.reason ?? '' }
206
+ }
207
+ return last
208
+ }
209
+
210
+ /**
211
+ * AIDEV-NOTE: PMR-422Q 2.1 — the heartbeat lifecycle, extracted so createAskEmitter
212
+ * stays readable. Owns the SEPARATE heartbeatAsks map (toolCallId -> ref over
213
+ * ALL tracked asks, plain AND nested) plus its interval. track() starts the
214
+ * unref'd timer only on the 0->1 transition AND only when renewLease is wired;
215
+ * stop() clears it on the 1->0 transition so it never leaks or holds the
216
+ * process open. Each beat renews every DISTINCT tracked ref (Set over values)
217
+ * and never throws (ISC-A-5).
218
+ */
219
+ function createHeartbeat(deps: AskEmitterDeps) {
220
+ const heartbeatAsks = new Map<string, string>()
221
+ let heartbeatTimer: ReturnType<typeof setInterval> | null = null
222
+ const beat = (): void => {
223
+ try {
224
+ for (const ref of new Set(heartbeatAsks.values())) {
225
+ deps.renewLease?.(ref)
226
+ }
227
+ } catch {
228
+ // never-throw (ISC-A-5)
229
+ }
230
+ }
231
+ const track = (id: string, ref: string): void => {
232
+ heartbeatAsks.set(id, ref)
233
+ if (heartbeatTimer === null && deps.renewLease !== undefined) {
234
+ heartbeatTimer = setInterval(
235
+ beat,
236
+ deps.heartbeatMs ?? LIVE_WAIT_HEARTBEAT_MS,
237
+ )
238
+ heartbeatTimer.unref?.()
239
+ }
240
+ }
241
+ const stop = (id: string): void => {
242
+ heartbeatAsks.delete(id)
243
+ if (heartbeatAsks.size === 0 && heartbeatTimer !== null) {
244
+ clearInterval(heartbeatTimer)
245
+ heartbeatTimer = null
246
+ }
247
+ }
248
+ return { track, stop }
249
+ }
250
+
251
+ export function createAskEmitter(deps: AskEmitterDeps): AskEmitter {
252
+ // In-flight asks this emitter is responsible for: toolCallId -> ref. Doubles
253
+ // as the refcount that keeps a parallel batch's close from firing early.
254
+ const openAsks = new Map<string, string>()
255
+ // PMR-422Q — SEPARATE heartbeat oracle over ALL tracked asks (plain AND
256
+ // nested); a nested ask still blocks the human so it keeps the lease alive
257
+ // even though openAsks stays plain-only.
258
+ const heartbeat = createHeartbeat(deps)
259
+ const closeAsk = async (event: { toolCallId: string }): Promise<void> => {
260
+ try {
261
+ // PMR-422Q — first statement for EVERY finalize, nested or plain: stop
262
+ // heartbeating this ask. This is the 1->0 transition that tears the timer
263
+ // down once the LAST tracked ask closes.
264
+ heartbeat.stop(event.toolCallId)
265
+ const ref = openAsks.get(event.toolCallId)
266
+ if (ref === undefined) return // never close a call this emitter did not track
267
+ openAsks.delete(event.toolCallId)
268
+ // REFCOUNT: another ask in the batch is still blocking the human.
269
+ if (openAsks.size > 0) return
270
+ if (deps.writer === undefined) return
271
+ const events = await deps.readEvents(ref)
272
+ // FAIL CLOSED: an unreadable tail (events null) or a journal with no valid
273
+ // state-change line must not buy a false `running`. lastV2StateRecord folds
274
+ // both into `undefined` — the SAME tail the open scans, so a journal this
275
+ // seam opened it can also close (review finding P2-a).
276
+ const tail = lastV2StateRecord(events)
277
+ if (tail === undefined) return
278
+ // REASON CHECK: only close the wait this seam opened.
279
+ if (tail.state !== 'waiting_human') return
280
+ if (tail.reason !== 'human_ask_pending') return
281
+ await deps.writer.record({
282
+ kind: 'state-change',
283
+ at: deps.now(),
284
+ ref,
285
+ state: 'running',
286
+ })
287
+ } catch {
288
+ // never-throw (ISC-A-5)
289
+ }
290
+ }
291
+ return {
292
+ onToolCall: async (event) => {
293
+ try {
294
+ if (event.toolName !== 'ask_user_question') return
295
+ const ref = deps.getActiveRef()
296
+ if (ref === null) return
297
+ // PMR-422Q — heartbeat tracking BEFORE the nested check: a nested ask
298
+ // (e.g. the code-review gate's ask) still blocks the human, so it must
299
+ // keep the lease alive even though its open/close journal stays
300
+ // plain-only. renewLease gates the timer — absent, no timer starts.
301
+ heartbeat.track(event.toolCallId, ref)
302
+ // PRIMARY dedupe: a nested ask is owned by a tool that journals its
303
+ // own wait (code_review does) — deterministic, no journal I/O, and it
304
+ // must happen before CLOSE tracking so such an ask is never counted in
305
+ // openAsks.
306
+ if (event.parentToolCallId !== undefined) return
307
+ if (deps.writer === undefined) return
308
+ // Track every in-flight ask this emitter is responsible for, whether
309
+ // or not the open below is journaled (parallel batches ask #2..N are
310
+ // deduped on the journal yet still block the human).
311
+ openAsks.set(event.toolCallId, ref)
312
+ // SECONDARY dedupe (journaling only): a non-nested open while a
313
+ // waiting_human is already journaled (loop-owned wait, or ask #2..N of
314
+ // a parallel batch whose sibling just opened the wait). Same tail
315
+ // derivation as the close (lastV2StateRecord, review finding P2-a).
316
+ const events = await deps.readEvents(ref)
317
+ if (lastV2StateRecord(events)?.state === 'waiting_human') return
318
+ await deps.writer.record({
319
+ kind: 'state-change',
320
+ at: deps.now(),
321
+ ref,
322
+ state: 'waiting_human',
323
+ reason: 'human_ask_pending',
324
+ })
325
+ } catch {
326
+ // never-throw (ISC-A-5)
327
+ }
328
+ },
329
+ onToolFinalized: closeAsk,
330
+ }
331
+ }