@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/aven/client.ts ADDED
@@ -0,0 +1,996 @@
1
+ // AIDEV-NOTE: PMR-T22H — single aven boundary for pi-flow. Every shell-out
2
+ // to the aven CLI lives behind this module: the AvenRunner contract (the one
3
+ // definition — flow/jira-ref.ts and flow/aven-resolve-exec.ts re-export it),
4
+ // the avenExec runner, workspace resolution (per-ref memoized and
5
+ // config-override), and the label/note/plan-state/epic helpers. Consumers
6
+ // that take an AvenRunner param keep doing so (tests inject fakes); index.ts
7
+ // wires avenExec.
8
+ import { execFile } from 'node:child_process'
9
+ import { readFile } from 'node:fs/promises'
10
+ import { promisify } from 'node:util'
11
+ import { loadConfig } from '../config.ts'
12
+ import { resolveAvenRef } from '../flow/aven-resolve-exec.ts'
13
+ import { classifyLabelFailure } from '../flow/ensure-labels.ts'
14
+ import { ALL_LABELS } from '../phase-state.ts'
15
+ import { approveSpec } from '../spec-review/approve.ts'
16
+ import { avenErrorText, parseMetadataBlock } from '../spec-review/aven-spec.ts'
17
+ import { escapeRegExp } from '../spec-review/escape-regexp.ts'
18
+ import { sha256Hex } from '../validate/gate-target.ts'
19
+
20
+ const execFileAsync = promisify(execFile)
21
+ const AVEN_TIMEOUT_MS = 5_000
22
+
23
+ export type AvenRunner = (
24
+ args: readonly string[],
25
+ ) => Promise<{ stdout: string; stderr: string }>
26
+
27
+ // AIDEV-NOTE: PMR-5900 — aven ref resolution must not depend on implicit
28
+ // cwd inference. The first ref-scoped aven call per ref resolves the
29
+ // workspace (see flow/aven-resolve-exec.ts) and memoizes it; later calls
30
+ // for the same ref reuse it. `avenWorkspace` config overrides everything.
31
+ // PMR-28BR — lifetime: the memo lives for the whole process and is never
32
+ // invalidated. A ticket moved between workspaces mid-session keeps the stale
33
+ // --workspace flag (fail-closed: confusing aven errors, not corruption);
34
+ // restart the session after moving a ticket.
35
+ const resolvedRefWorkspaces = new Map<string, string | undefined>()
36
+ // AIDEV-NOTE: PMR-8JZA — session cwd for every aven call. Set once from
37
+ // session_start (ctx.cwd); command handlers and the flow loop all share it,
38
+ // so the project-level avenWorkspace resolves from the session cwd even when
39
+ // process.cwd() differs (worktree sessions, --cwd launches). Memoized per
40
+ // resolved cwd, so two sessions in one process with different cwds each
41
+ // load their own project config.
42
+ // PMR-7ZEE — avenSessionCwd is process-global, last-writer-wins: with two
43
+ // sessions of different cwds in one process, in-flight aven calls of the
44
+ // earlier session switch to the newer session's cwd. Same limit as the
45
+ // notifyUser holder; Pi sessions rarely coexist in one process. Key this
46
+ // per session if multi-session-per-process ever becomes real.
47
+ let avenSessionCwd: string | undefined
48
+ const avenWorkspaceOverrideByCwd = new Map<string, string | undefined>()
49
+ let lastAvenFailure: string | undefined
50
+
51
+ export function lastAvenResolutionFailure(): string | undefined {
52
+ return lastAvenFailure
53
+ }
54
+
55
+ function recordAvenFailure(error: unknown): void {
56
+ lastAvenFailure = error instanceof Error ? error.message : String(error)
57
+ }
58
+
59
+ // AIDEV-NOTE: cwd resolution: avenSessionCwd (set by session_start) wins;
60
+ // process.cwd() is only the fallback for direct library use before any
61
+ // session starts. Previously this memoized once on the first caller's cwd
62
+ // (ensureLabels at session_start), silently pinning process.cwd() for the
63
+ // whole process (PMR-8JZA).
64
+ export async function avenOverrideArg(): Promise<string[]> {
65
+ const cwd = avenSessionCwd ?? process.cwd()
66
+ if (!avenWorkspaceOverrideByCwd.has(cwd)) {
67
+ const config = await loadConfig(cwd)
68
+ avenWorkspaceOverrideByCwd.set(cwd, config.avenWorkspace)
69
+ }
70
+ const avenWorkspaceOverride = avenWorkspaceOverrideByCwd.get(cwd)
71
+ if (avenWorkspaceOverride !== undefined) {
72
+ return ['--workspace', avenWorkspaceOverride]
73
+ }
74
+ return []
75
+ }
76
+
77
+ async function avenArgsWithWorkspace(
78
+ args: string[],
79
+ ref: string,
80
+ ): Promise<string[]> {
81
+ const override = await avenOverrideArg()
82
+ if (override.length > 0) return [...args, ...override]
83
+ if (!resolvedRefWorkspaces.has(ref)) {
84
+ const resolved = await resolveAvenRef(ref, avenExec)
85
+ if (!resolved.ok) throw new Error(resolved.reason)
86
+ resolvedRefWorkspaces.set(ref, resolved.workspace)
87
+ }
88
+ const workspace = resolvedRefWorkspaces.get(ref)
89
+ if (workspace !== undefined) {
90
+ return [...args, '--workspace', workspace]
91
+ }
92
+ return args
93
+ }
94
+
95
+ // AIDEV-NOTE: workspace resolution for the spec commands (/spec-review,
96
+ // /spec-publish) and the spec_approve tool (PMR-MR36 fix round). Priority:
97
+ // explicit --workspace flag > project-config avenWorkspace override (the
98
+ // SAME avenOverrideArg path the flow loop uses — no second config mechanism)
99
+ // > per-ref resolution via resolveAvenRef, memoized in
100
+ // resolvedRefWorkspaces like avenArgsWithWorkspace. Throws on failed
101
+ // per-ref resolution — callers show the reason and stop; never fall back to
102
+ // the cwd-inferred workspace silently (that was the original bug).
103
+ export async function resolveSpecWorkspace(
104
+ explicit: string | undefined,
105
+ ref: string,
106
+ ): Promise<string | undefined> {
107
+ if (explicit !== undefined) return explicit
108
+ const override = await avenOverrideArg()
109
+ if (override.length > 0) return override[1]
110
+ if (!resolvedRefWorkspaces.has(ref)) {
111
+ const resolved = await resolveAvenRef(ref, avenExec)
112
+ if (!resolved.ok) throw new Error(resolved.reason)
113
+ resolvedRefWorkspaces.set(ref, resolved.workspace)
114
+ }
115
+ return resolvedRefWorkspaces.get(ref)
116
+ }
117
+
118
+ // AIDEV-NOTE: aven runner for the Jira-ID resolver (flow/jira-ref.ts) and
119
+ // the spec modules — execFileAsync throws on spawn failure / non-zero exit;
120
+ // aven's own errors (exit 0, text on stdout) are classified inside the
121
+ // resolvers.
122
+ export const avenExec: AvenRunner = async (args) => {
123
+ const { stdout, stderr } = await execFileAsync('aven', [...args], {
124
+ timeout: AVEN_TIMEOUT_MS,
125
+ })
126
+ return { stdout, stderr }
127
+ }
128
+
129
+ // AIDEV-NOTE: spec_approve tool body (PMR-MR36 fix round). approveSpec was
130
+ // dead code and the injected review prompt made the model run a raw
131
+ // `aven edit` — no loud failure, no workspace pin. The spec_approve tool in
132
+ // tools/spec-approve.ts is a thin wrapper mapping this result to tool output.
133
+ export async function specApprove(params: {
134
+ ref: string
135
+ workspace?: string
136
+ }): Promise<{ ok: boolean; text: string }> {
137
+ let workspace: string | undefined
138
+ try {
139
+ workspace = await resolveSpecWorkspace(params.workspace, params.ref)
140
+ } catch (error) {
141
+ const msg = error instanceof Error ? error.message : String(error)
142
+ return { ok: false, text: `spec_approve: ${msg}` }
143
+ }
144
+ const result = await approveSpec(avenExec, params.ref, { workspace })
145
+ if (result.kind === 'error') {
146
+ return { ok: false, text: `spec_approve: ${result.reason}` }
147
+ }
148
+ return {
149
+ ok: true,
150
+ text: `spec_approve: ${params.ref} approved (plan-state=approved, label=plan, status=todo) — now call the spec_publish tool for ${params.ref}`,
151
+ }
152
+ }
153
+
154
+ // AIDEV-NOTE: Shared aven helpers (labels are the run state, notes are the
155
+ // halt record). Used by the /implement and /flow command handlers and by the
156
+ // flow loop deps — one parsing path, fail-closed (null/[] on any failure).
157
+ //
158
+ // AIDEV-NOTE: PMR-9DZ0 1.1 — readAvenLabels was split so the run-start
159
+ // journal (subtask 1.4) can reuse the SAME `aven show --json` read for the
160
+ // ticket title without a second shell-out. readAvenSnapshot does the work
161
+ // that readAvenLabels did verbatim before (avenArgsWithWorkspace routing,
162
+ // AVEN_TIMEOUT_MS, identical recordAvenFailure messages) and hands back the
163
+ // full AvenTicketSnapshot; readAvenLabels is now a thin wrapper that keeps
164
+ // its EXACT contract for every existing caller — null on any failure
165
+ // (exec throw OR a fuzzy-match/bad-json snapshot), the labels array on ok.
166
+ // This is a behaviour-preserving refactor: the failure wording and the
167
+ // recordAvenFailure calls are unchanged, only relocated.
168
+ export async function readAvenSnapshot(
169
+ ref: string,
170
+ workspace?: string,
171
+ ): Promise<AvenTicketSnapshot | null> {
172
+ try {
173
+ // PMR-3VWM: an explicit workspace threads into the read exactly like the
174
+ // receipt read (showFullGuarded) and approveSpec's readLabels — explicit
175
+ // wins over config/per-ref resolution (the resolveSpecWorkspace
176
+ // priority), so the spec_approve oneshot exemption cannot resolve a
177
+ // DIFFERENT ticket than the gate answer and edit when the explicit
178
+ // workspace diverges from config/per-ref resolution. Omitted = the
179
+ // unchanged config/per-ref path.
180
+ let args: string[]
181
+ if (workspace !== undefined) {
182
+ args = ['show', ref, '--json', '--workspace', workspace]
183
+ } else {
184
+ args = await avenArgsWithWorkspace(['show', ref, '--json'], ref)
185
+ }
186
+ const { stdout } = await execFileAsync('aven', args, {
187
+ timeout: AVEN_TIMEOUT_MS,
188
+ })
189
+ const snapshot = ticketSnapshotFor(JSON.parse(stdout), ref)
190
+ if (snapshot.ok) {
191
+ return snapshot
192
+ }
193
+ // PMR-F8HB: aven prefix-matches refs (`aven show PMR-TPN` happily
194
+ // returns PMR-TPN7), so a truncated or typo'd ref would silently read
195
+ // (and later write) the WRONG ticket's labels. Fail closed instead.
196
+ let message: string
197
+ if (snapshot.kind === 'fuzzy-match') {
198
+ message = `aven matched ${ref} to ${snapshot.resolvedRef} — not an exact ticket ref; use the full ref`
199
+ } else {
200
+ message = 'aven show returned a ticket without a labels array'
201
+ }
202
+ recordAvenFailure(message)
203
+ return snapshot
204
+ } catch (error: unknown) {
205
+ recordAvenFailure(error)
206
+ return null
207
+ }
208
+ }
209
+
210
+ export async function readAvenLabels(
211
+ ref: string,
212
+ workspace?: string,
213
+ ): Promise<string[] | null> {
214
+ const snapshot = await readAvenSnapshot(ref, workspace)
215
+ if (snapshot === null) return null
216
+ if (snapshot.ok) return snapshot.labels
217
+ return null
218
+ }
219
+
220
+ // AIDEV-NOTE: PMR-YG2N — durable-binding read for the worktree cleanup sweep
221
+ // (`aven show <ref> --full`, same --full shape tools/code-review-parse.ts
222
+ // parses). Workspace routing mirrors readAvenLabels via avenArgsWithWorkspace;
223
+ // fail-closed: returns null on any failure, never throws.
224
+ export async function avenShowFull(ref: string): Promise<string | null> {
225
+ try {
226
+ const args = await avenArgsWithWorkspace(['show', ref, '--full'], ref)
227
+ const result = await execFileAsync('aven', args, {
228
+ timeout: AVEN_TIMEOUT_MS,
229
+ })
230
+ if (result.stdout.length === 0) {
231
+ return null
232
+ }
233
+ return result.stdout
234
+ } catch (error: unknown) {
235
+ recordAvenFailure(error)
236
+ return null
237
+ }
238
+ }
239
+
240
+ /**
241
+ * PMR-F8HB — pure classification of an `aven show --json` result against
242
+ * the ref that was asked for. `fuzzy-match` means aven resolved the ref to
243
+ * a DIFFERENT ticket (prefix match); every caller must treat that as a
244
+ * failure, never as data about the requested ticket.
245
+ *
246
+ * AIDEV-NOTE: PMR-9DZ0 1.1 — the ok-variant now carries `title?: string`,
247
+ * parsed additively from the `aven show --json` record so the run-start
248
+ * journal (subtask 1.4) can show "REF — title" without a second aven call.
249
+ * WHY additive-only: readAvenLabels must keep its exact fail-closed contract
250
+ * for every existing caller, so a missing / non-string / empty title can
251
+ * NEVER turn an otherwise-ok snapshot into a failure — it is `undefined`
252
+ * instead. The title is metadata, not identity, so it is not part of the
253
+ * fuzzy-match / bad-json guards below.
254
+ */
255
+ export type AvenTicketSnapshot =
256
+ | { ok: true; labels: string[]; resolvedRef: string; title?: string }
257
+ | {
258
+ ok: false
259
+ kind: 'bad-json' | 'fuzzy-match'
260
+ resolvedRef: string | null
261
+ }
262
+
263
+ export function ticketSnapshotFor(
264
+ raw: unknown,
265
+ requestedRef: string,
266
+ ): AvenTicketSnapshot {
267
+ if (typeof raw !== 'object' || raw === null) {
268
+ return { ok: false, kind: 'bad-json', resolvedRef: null }
269
+ }
270
+ const record = raw as {
271
+ labels?: unknown
272
+ ref?: unknown
273
+ title?: unknown
274
+ }
275
+ if (!Array.isArray(record.labels)) {
276
+ return { ok: false, kind: 'bad-json', resolvedRef: null }
277
+ }
278
+ const labels = record.labels.filter((l): l is string => typeof l === 'string')
279
+ const resolvedRef =
280
+ typeof record.ref === 'string' && record.ref !== '' ? record.ref : null
281
+ // A ticket without a ref field cannot be identity-verified: fail closed
282
+ // (bad-json) rather than trusting an unverifiable identity.
283
+ if (resolvedRef === null) {
284
+ return { ok: false, kind: 'bad-json', resolvedRef: null }
285
+ }
286
+ // Case-insensitive compare: a case variant of the same ref is the same
287
+ // ticket; anything else (PMR-TPN vs PMR-TPN7) is a different ticket.
288
+ if (resolvedRef.toUpperCase() === requestedRef.toUpperCase()) {
289
+ // PMR-9DZ0 — additive title parse: only a non-empty string is a title;
290
+ // anything else stays undefined and never blocks the ok result.
291
+ let title: string | undefined
292
+ if (typeof record.title === 'string' && record.title !== '') {
293
+ title = record.title
294
+ }
295
+ return { ok: true, labels, resolvedRef, title }
296
+ }
297
+ return { ok: false, kind: 'fuzzy-match', resolvedRef }
298
+ }
299
+
300
+ /**
301
+ * AIDEV-NOTE: PMR-TE7Q — false is a confirmed non-delivery signal, not a
302
+ * successful best-effort call. Worktree cleanup wrappers return this boolean
303
+ * unchanged so a transient failure cannot become a permanent dedupe key.
304
+ */
305
+ export async function writeAvenNote(
306
+ ref: string,
307
+ text: string,
308
+ ): Promise<boolean> {
309
+ try {
310
+ const args = await avenArgsWithWorkspace(['note', ref, text], ref)
311
+ await execFileAsync('aven', args, {
312
+ timeout: AVEN_TIMEOUT_MS,
313
+ })
314
+ return true
315
+ } catch (error: unknown) {
316
+ recordAvenFailure(error)
317
+ return false
318
+ }
319
+ }
320
+
321
+ // AIDEV-NOTE: yolo 5.1 — best-effort `error` type-label application for
322
+ // halted yolo runs. `error` is deliberately OUTSIDE lifecycleLabelMutation
323
+ // (label-gate) — it marks the run's outcome type, not its lifecycle stage, so
324
+ // the bash interceptor does not conflict. Bootstrap: `aven label create
325
+ // error` first (an 'already exists' failure is fine to ignore), then `aven
326
+ // edit <ref> --label error`. Never throws; false = the label was not applied.
327
+ export async function applyAvenErrorLabel(ref: string): Promise<boolean> {
328
+ try {
329
+ const createArgs = await avenArgsWithWorkspace(
330
+ ['label', 'create', 'error'],
331
+ ref,
332
+ )
333
+ await execFileAsync('aven', createArgs, {
334
+ timeout: AVEN_TIMEOUT_MS,
335
+ })
336
+ } catch {
337
+ // already exists (or aven unavailable) — the edit below decides success
338
+ }
339
+ try {
340
+ const editArgs = await avenArgsWithWorkspace(
341
+ ['edit', ref, '--label', 'error'],
342
+ ref,
343
+ )
344
+ await execFileAsync('aven', editArgs, {
345
+ timeout: AVEN_TIMEOUT_MS,
346
+ })
347
+ } catch (error: unknown) {
348
+ recordAvenFailure(error)
349
+ return false
350
+ }
351
+ // AIDEV-NOTE: PMR-VE27 (plan decision 11) — the loop's error-label path
352
+ // gets the same write-verification reread as writeAvenLabel: exit 0 is
353
+ // not proof the label landed. Best-effort callers (the loop's avenLabel
354
+ // dep, run-attempt) already treat false as not-applied, so the stricter
355
+ // semantics are transparent to them.
356
+ const applied = await readAvenLabels(ref)
357
+ if (applied === null || !applied.includes('error')) {
358
+ recordAvenFailure(
359
+ new Error(
360
+ `error-label write verification failed: "error" is absent (or the reread failed) on ${ref} after the edit`,
361
+ ),
362
+ )
363
+ return false
364
+ }
365
+ return true
366
+ }
367
+
368
+ // AIDEV-NOTE: Structural input for the implement routing guard — an open
369
+ // epic tree is plan-route work regardless of type labels. Fail-open on aven
370
+ // errors (label-based routing stays the primary contract).
371
+ export async function epicHasOpenChildren(ref: string): Promise<boolean> {
372
+ try {
373
+ const args = await avenArgsWithWorkspace(
374
+ ['epic', 'list', ref, '--json'],
375
+ ref,
376
+ )
377
+ const { stdout } = await execFileAsync('aven', args, {
378
+ timeout: AVEN_TIMEOUT_MS,
379
+ })
380
+ const parsed: unknown = JSON.parse(stdout)
381
+ if (
382
+ typeof parsed === 'object' &&
383
+ parsed !== null &&
384
+ Array.isArray((parsed as { children?: unknown }).children)
385
+ )
386
+ return (parsed as { children: { open?: unknown }[] }).children.some(
387
+ (c) => c.open === true,
388
+ )
389
+ return false
390
+ } catch (error: unknown) {
391
+ recordAvenFailure(error)
392
+ return false
393
+ }
394
+ }
395
+
396
+ // AIDEV-NOTE: PMR-R5VB — exact-ref-guarded gate-answer read/write (the
397
+ // protected-decision answers the human records on the aven ticket). aven
398
+ // prefix-matches refs (PMR-F8HB), so BOTH the read and the write go through
399
+ // `showFullGuarded` first: a case-insensitive first-line ref mismatch means
400
+ // the operation targets the WRONG ticket and fails closed. aven exits 0 on
401
+ // errors — never trust exit codes, only output text (stderr for reads,
402
+ // `updated <ref>` stdout for writes).
403
+ // AIDEV-NOTE: PMR-V31Z 7.1 — the review gate is deleted: AnswerGate is
404
+ // 'spec' only, AnswerChoice is approve/reject only, and the old
405
+ // `review: 'review-answer'` metadata mapping is gone. The spec gate stays —
406
+ // its spec-answer receipt is what spec_approve accepts.
407
+ export type AnswerGate = 'spec'
408
+ export type AnswerChoice = 'approve' | 'reject'
409
+ export const ANSWER_METADATA_KEY: Record<AnswerGate, string> = {
410
+ spec: 'spec-answer',
411
+ }
412
+
413
+ /**
414
+ * PMR-R5VB — pure extraction of the resolved ticket ref from
415
+ * `aven show <ref> --full` output (the --full analog of ticketSnapshotFor):
416
+ * the first token of the first line (`<ref> status=...`).
417
+ */
418
+ export function resolveShowFullRef(stdout: string): string | null {
419
+ const firstLine = stdout.split('\n')[0] ?? ''
420
+ const match = /^(\S+) status=/.exec(firstLine)
421
+ if (match === null) return null
422
+ return match[1] ?? null
423
+ }
424
+
425
+ export type ShowFullResult = { ok: true; stdout: string } | { ok: false }
426
+
427
+ async function showFullGuarded(
428
+ ref: string,
429
+ workspace?: string,
430
+ ): Promise<ShowFullResult> {
431
+ try {
432
+ let args: string[]
433
+ if (workspace !== undefined) {
434
+ args = ['show', ref, '--full', '--workspace', workspace]
435
+ } else {
436
+ args = await avenArgsWithWorkspace(['show', ref, '--full'], ref)
437
+ }
438
+ const { stdout, stderr } = await execFileAsync('aven', args, {
439
+ timeout: AVEN_TIMEOUT_MS,
440
+ })
441
+ // AIDEV-NOTE: PMR-69V8 — stderr only; note bodies quote "Error:".
442
+ if (avenErrorText('', stderr) !== null) return { ok: false }
443
+ const resolvedRef = resolveShowFullRef(stdout)
444
+ if (resolvedRef === null) return { ok: false }
445
+ // Case-insensitive compare like ticketSnapshotFor: a case variant is
446
+ // the same ticket; anything else is a different (wrong) ticket.
447
+ if (resolvedRef.toUpperCase() !== ref.toUpperCase()) return { ok: false }
448
+ return { ok: true, stdout }
449
+ } catch {
450
+ return { ok: false }
451
+ }
452
+ }
453
+
454
+ /**
455
+ * PMR-R5VB — best-effort gate-answer read: null on any aven failure or
456
+ * when the metadata field is absent / holds an unknown value (the
457
+ * readPlanState fail-closed precedent).
458
+ */
459
+ export async function readGateAnswer(
460
+ ref: string,
461
+ gate: AnswerGate,
462
+ workspace?: string,
463
+ ): Promise<AnswerChoice | null> {
464
+ const guarded = await showFullGuarded(ref, workspace)
465
+ if (!guarded.ok) return null
466
+ const value = parseMetadataBlock(guarded.stdout, ANSWER_METADATA_KEY[gate])
467
+ if (value === 'approve' || value === 'reject') {
468
+ return value
469
+ }
470
+ return null
471
+ }
472
+
473
+ // AIDEV-NOTE: PMR-N0D5 — the plan-revision token for the spec-answer
474
+ // binding: sha256 of the plan file's CONTENT at the ticket's plan-path
475
+ // (content hash over mtime — mtime is not stable across checkouts and
476
+ // restores). Best-effort like every read here:
477
+ // null on aven failure, absent plan-path metadata, or an unreadable plan
478
+ // file, and the consumer (specAnswerBindingRefusal) fails closed on null.
479
+ // The workspace threads through showFullGuarded exactly like
480
+ // readGateAnswer, so the binding and the gate answer always resolve the
481
+ // SAME ticket.
482
+ export async function readPlanRevision(
483
+ ref: string,
484
+ workspace?: string,
485
+ ): Promise<string | null> {
486
+ const guarded = await showFullGuarded(ref, workspace)
487
+ if (!guarded.ok) return null
488
+ const planPath = parseMetadataBlock(guarded.stdout, 'plan-path')
489
+ if (planPath === null) return null
490
+ try {
491
+ const content = await readFile(planPath, 'utf8')
492
+ return sha256Hex(content)
493
+ } catch {
494
+ return null
495
+ }
496
+ }
497
+
498
+ /**
499
+ * PMR-R5VB — guarded gate-answer write (the writeAvenLabel pattern): the
500
+ * exact-ref read must pass first or nothing is written. Success is judged
501
+ * by `updated <ref>` on stdout — aven exits 0 on errors.
502
+ */
503
+ export async function writeGateAnswer(
504
+ ref: string,
505
+ gate: AnswerGate,
506
+ choice: AnswerChoice,
507
+ workspace?: string,
508
+ ): Promise<boolean> {
509
+ const guarded = await showFullGuarded(ref, workspace)
510
+ if (!guarded.ok) return false
511
+ try {
512
+ let args: string[]
513
+ if (workspace !== undefined) {
514
+ args = [
515
+ 'edit',
516
+ ref,
517
+ '--metadata',
518
+ `${ANSWER_METADATA_KEY[gate]}=${choice}`,
519
+ '--workspace',
520
+ workspace,
521
+ ]
522
+ } else {
523
+ args = await avenArgsWithWorkspace(
524
+ ['edit', ref, '--metadata', `${ANSWER_METADATA_KEY[gate]}=${choice}`],
525
+ ref,
526
+ )
527
+ }
528
+ const { stdout } = await execFileAsync('aven', args, {
529
+ timeout: AVEN_TIMEOUT_MS,
530
+ })
531
+ return new RegExp(`^updated ${escapeRegExp(ref)}(\\s|$)`, 'm').test(stdout)
532
+ } catch (error: unknown) {
533
+ recordAvenFailure(error)
534
+ return false
535
+ }
536
+ }
537
+
538
+ // AIDEV-NOTE: PMR-W60H — plan-state reader for the flow loop's
539
+ // awaiting-approval gate. Reads the same `aven show <ref> --full` metadata
540
+ // blocks /spec-review uses, with the same workspace threading as
541
+ // readAvenLabels. null = aven failed OR the field is absent — the loop
542
+ // treats both as "no gate" (the failure-halt path is unchanged); only an
543
+ // explicit plan-state=review triggers the graceful pause.
544
+ export async function readPlanState(ref: string): Promise<string | null> {
545
+ try {
546
+ const args = await avenArgsWithWorkspace(['show', ref, '--full'], ref)
547
+ const { stdout, stderr } = await execFileAsync('aven', args, {
548
+ timeout: AVEN_TIMEOUT_MS,
549
+ })
550
+ // AIDEV-NOTE: PMR-69V8 — stderr only; note bodies may quote "Error:".
551
+ if (avenErrorText('', stderr) !== null) return null
552
+ return parseMetadataBlock(stdout, 'plan-state')
553
+ } catch {
554
+ return null
555
+ }
556
+ }
557
+
558
+ // AIDEV-NOTE (PMR-ZGPY 2.2, D5; PMR-384R): refs of tickets with
559
+ // plan-state=review, across ALL projects (--all-projects required per
560
+ // DP-252 — aven >=0.1.51 scopes a plain `list` to the cwd-inferred
561
+ // project). Aven prints unknown-metadata-field with exit 0 when no ticket
562
+ // in the workspace ever registered plan-state — same as an empty list, NOT
563
+ // a failure. Fail-closed: any spawn/parse problem returns [] so the
564
+ // flow-status widget keeps showing run-derived gates only. Only
565
+ // aven/client.ts shells out to aven (boundary rule); flow/gates.ts
566
+ // consumes this via the GateDeps seam. Generic aven-list ref extractor —
567
+ // the shared tail lives in extractListRefs below.
568
+ export function parsePlanReviewRefs(stdout: string): string[] {
569
+ let parsed: unknown
570
+ try {
571
+ parsed = JSON.parse(stdout)
572
+ } catch {
573
+ return []
574
+ }
575
+ if (!Array.isArray(parsed)) return []
576
+ return extractListRefs(parsed)
577
+ }
578
+
579
+ // Shared tail of the aven-list ref extractors: entries without a string
580
+ // ref are skipped (same rule for both consumers).
581
+ function extractListRefs(parsed: unknown[]): string[] {
582
+ const refs: string[] = []
583
+ for (const entry of parsed) {
584
+ if (typeof entry !== 'object' || entry === null) continue
585
+ const ref = (entry as { ref?: unknown }).ref
586
+ if (typeof ref === 'string' && ref.length > 0) refs.push(ref)
587
+ }
588
+ return refs
589
+ }
590
+
591
+ // AIDEV-NOTE (PMR-KESB): shared fail-closed head of the aven-list
592
+ // classifiers — one contract for both consumers (previously copied
593
+ // verbatim between classifyOpenTicketRefs and classifyReadyTickets, which
594
+ // is exactly why extractListRefs was extracted as the shared tail).
595
+ // Error text on either stream, a lowercase `error:` stderr line, non-JSON
596
+ // stdout, or non-array schema drift all record their reason via
597
+ // recordAvenFailure and return { ok: false }; a successfully parsed array
598
+ // (including an empty one — a real zero answer) returns its entries.
599
+ // `universe` names what becomes unverifiable in the recorded messages, so
600
+ // per-consumer diagnostics still differ. Tails stay per-consumer.
601
+ function classifyListHead(
602
+ stdout: string,
603
+ stderr: string,
604
+ universe: string,
605
+ ): { ok: true; entries: unknown[] } | { ok: false } {
606
+ const errorText = avenErrorText(stdout, stderr)
607
+ if (errorText !== null) {
608
+ // Bound the recorded reason: aven output can be arbitrarily large.
609
+ recordAvenFailure(
610
+ `aven list output contains error text: ${errorText.trim().split('\n')[0]?.slice(0, 200) ?? '(empty)'}`,
611
+ )
612
+ return { ok: false }
613
+ }
614
+ // aven's own CLI errors print lowercase `error: …` on stderr (observed:
615
+ // `error: unexpected argument … found`); avenErrorText's regex only
616
+ // knows `Error:`/`error `. An error line on stderr means the run's
617
+ // status is unverifiable — fail closed to null, never to [] (ISC-13).
618
+ // PMR-NPFR: trim each line before the prefix test — avenErrorText trims
619
+ // but doesn't match `error:`, this check matches `error:` but didn't
620
+ // trim, so an indented line evaded both when stdout was valid JSON.
621
+ const stderrErrorLine = stderr
622
+ .split('\n')
623
+ .find((line) => /^error\b/.test(line.trim()))
624
+ if (stderrErrorLine !== undefined) {
625
+ recordAvenFailure(
626
+ `aven list stderr reported an error: ${stderrErrorLine.trim().slice(0, 200)}`,
627
+ )
628
+ return { ok: false }
629
+ }
630
+ let parsed: unknown
631
+ try {
632
+ parsed = JSON.parse(stdout)
633
+ } catch {
634
+ recordAvenFailure(
635
+ `aven list stdout was not valid JSON — ${universe} unverifiable`,
636
+ )
637
+ return { ok: false }
638
+ }
639
+ if (!Array.isArray(parsed)) {
640
+ recordAvenFailure(
641
+ `aven list stdout JSON is not an array (schema drift) — ${universe} unverifiable`,
642
+ )
643
+ return { ok: false }
644
+ }
645
+ return { ok: true, entries: parsed }
646
+ }
647
+
648
+ // AIDEV-NOTE (PMR-384R fix round, review blocker 1): classifier for
649
+ // `aven list --open` output. aven exits 0 on errors — never trust exit
650
+ // codes, classify by text via avenErrorText (the listPlansAtReviewRefs
651
+ // guard pattern) — so anything unclassifiable (error text on stdout or
652
+ // stderr, non-JSON, non-array schema drift) returns null: ISC-13, gates
653
+ // suppress NOTHING when status cannot be verified. [] is reserved for a
654
+ // successfully parsed empty array (a real zero-open answer). PMR-710A:
655
+ // every null path records its reason via recordAvenFailure, so
656
+ // lastAvenResolutionFailure() can explain why gates were kept after a
657
+ // silent aven-side failure (the spawn catch alone misses classify-level
658
+ // anomalies). PMR-KESB: the fail-closed head is shared via
659
+ // classifyListHead. Exported for tests; listOpenTicketRefs is the
660
+ // production consumer.
661
+ export function classifyOpenTicketRefs(
662
+ stdout: string,
663
+ stderr: string,
664
+ ): string[] | null {
665
+ const head = classifyListHead(stdout, stderr, 'ticket-status universe')
666
+ if (!head.ok) {
667
+ return null
668
+ }
669
+ return extractListRefs(head.entries)
670
+ }
671
+
672
+ // AIDEV-NOTE (PMR-3E1Z): classifier for the ready-ticket picker's
673
+ // `aven list --ready` output. Same fail-closed convention as
674
+ // classifyOpenTicketRefs (PMR-384R): aven exits 0 on errors, so classify
675
+ // by text; any anomaly (error text, stderr error line, non-JSON, non-array
676
+ // schema drift) returns null and records its reason via
677
+ // recordAvenFailure — [] is reserved for a successfully parsed empty
678
+ // array. The tail keeps ref+title pairs and SKIPS entries lacking either
679
+ // non-empty string, mirroring extractListRefs' skip rule.
680
+ export interface ReadyTicket {
681
+ ref: string
682
+ title: string
683
+ }
684
+
685
+ export function classifyReadyTickets(
686
+ stdout: string,
687
+ stderr: string,
688
+ ): ReadyTicket[] | null {
689
+ const head = classifyListHead(stdout, stderr, 'ready-ticket universe')
690
+ if (!head.ok) {
691
+ return null
692
+ }
693
+ const tickets: ReadyTicket[] = []
694
+ for (const entry of head.entries) {
695
+ if (typeof entry !== 'object' || entry === null) continue
696
+ const ref = (entry as { ref?: unknown }).ref
697
+ const title = (entry as { title?: unknown }).title
698
+ if (
699
+ typeof ref === 'string' &&
700
+ ref.length > 0 &&
701
+ typeof title === 'string' &&
702
+ title.length > 0
703
+ ) {
704
+ tickets.push({ ref, title })
705
+ }
706
+ }
707
+ return tickets
708
+ }
709
+
710
+ export async function listPlansAtReviewRefs(): Promise<string[]> {
711
+ try {
712
+ const out = await avenExec([
713
+ 'list',
714
+ '--metadata',
715
+ 'plan-state=review',
716
+ '--all-projects',
717
+ '--json',
718
+ ])
719
+ if (/unknown-metadata-field/.test(out.stdout)) return []
720
+ return parsePlanReviewRefs(out.stdout)
721
+ } catch (error: unknown) {
722
+ recordAvenFailure(error)
723
+ return []
724
+ }
725
+ }
726
+
727
+ /**
728
+ * Refs with a live (nonterminal, non-deleted) aven ticket, across ALL
729
+ * projects (PMR-384R; --all-projects per DP-252 — the shared runsDir holds
730
+ * other projects' flows, so gate refs can belong to any project). One
731
+ * batched `aven list --open --all-projects --json` call. Returns null when
732
+ * aven failed in ANY way — spawn/timeout, or (fix round, review blocker 1)
733
+ * exit-0 domain errors, non-JSON output, or schema drift, per
734
+ * classifyOpenTicketRefs — the ISC-13 signal for gates.ts to suppress
735
+ * NOTHING. [] only from a successfully parsed empty array and DOES
736
+ * suppress. A ref absent from the universe is either terminal (done/
737
+ * canceled — --open excludes it) or has no record at all (deleted tickets
738
+ * are excluded too) — both must suppress: aven ticket status is the truth,
739
+ * a stale journal gate record cannot override it.
740
+ */
741
+ export async function listOpenTicketRefs(): Promise<string[] | null> {
742
+ try {
743
+ const out = await avenExec(['list', '--open', '--all-projects', '--json'])
744
+ return classifyOpenTicketRefs(out.stdout, out.stderr)
745
+ } catch (error: unknown) {
746
+ recordAvenFailure(error)
747
+ return null
748
+ }
749
+ }
750
+
751
+ /**
752
+ * Ref+title pairs of aven tickets ready for pickup, in the session cwd's
753
+ * project scope. One batched `aven list --ready --json` call. Returns null
754
+ * when aven failed in ANY way — spawn/timeout, or (classifyReadyTickets)
755
+ * exit-0 domain errors, non-JSON output, or schema drift. [] only from a
756
+ * successfully parsed empty array.
757
+ */
758
+ // AIDEV-NOTE: PMR-3E1Z — override-only workspace routing. Unlike per-ref
759
+ // avenArgsWithWorkspace calls, a ref-less list cannot resolve a project per
760
+ // ref, so routing relies solely on the session cwd (avenSessionCwd) plus
761
+ // the avenWorkspace config override tail. Like discoverAvenPrefixes, this
762
+ // uses execFileAsync with cwd (not avenExec, which sets no cwd) because the
763
+ // list is cwd-scoped.
764
+ export async function listReadyTickets(): Promise<ReadyTicket[] | null> {
765
+ try {
766
+ const out = await execFileAsync(
767
+ 'aven',
768
+ ['list', '--ready', '--json', ...(await avenOverrideArg())],
769
+ { timeout: AVEN_TIMEOUT_MS, cwd: avenSessionCwd },
770
+ )
771
+ return classifyReadyTickets(out.stdout, out.stderr)
772
+ } catch (error: unknown) {
773
+ recordAvenFailure(error)
774
+ return null
775
+ }
776
+ }
777
+
778
+ /**
779
+ * `jira-ref` metadata of a local aven epic (the Jira key it mirrors), or null
780
+ * when absent/unreadable. Used so work-mode runs started from the aven epic
781
+ * ref are still tracked by their Jira key. Best-effort: never throws.
782
+ */
783
+ export async function readJiraRef(ref: string): Promise<string | null> {
784
+ try {
785
+ const args = await avenArgsWithWorkspace(['show', ref, '--full'], ref)
786
+ const { stdout, stderr } = await execFileAsync('aven', args, {
787
+ timeout: AVEN_TIMEOUT_MS,
788
+ })
789
+ if (avenErrorText('', stderr) !== null) return null
790
+ const value = parseMetadataBlock(stdout, 'jira-ref')
791
+ if (value === null || value.length === 0) return null
792
+ return value
793
+ } catch {
794
+ return null
795
+ }
796
+ }
797
+
798
+ // AIDEV-NOTE: PMR-69V8 — pure parser for the flow loop's blockers signal.
799
+ // `aven show --full` prints notes as `note id=… created=<iso>` followed by a
800
+ // `body<<EOF … EOF` block. A note counts as a review-blockers note when its
801
+ // body carries the "reviewed-at:" marker the validate prompt tells the agent
802
+ // to append. Only notes created at/after sinceIso count, so a blockers note
803
+ // from an earlier round never retriggers a retry.
804
+ export function hasBlockersNoteSince(
805
+ showFullOutput: string,
806
+ sinceIso: string,
807
+ ): boolean {
808
+ const since = Date.parse(sinceIso)
809
+ if (Number.isNaN(since)) return false
810
+ // Anchored heredoc shape (same as parseWorktreeNotes): a pasted
811
+ // "note id=" line inside a body cannot start a new note.
812
+ const re = /^note id=\S+ created=(\S+).*$\n^body<<EOF$\n([\s\S]*?)\n^EOF$/gm
813
+ for (const match of showFullOutput.matchAll(re)) {
814
+ const created = Date.parse(match[1] ?? '')
815
+ if (Number.isNaN(created) || created < since) continue
816
+ if (/^reviewed-at:/m.test(match[2] ?? '')) return true
817
+ }
818
+ return false
819
+ }
820
+
821
+ // Fail-closed: any aven failure -> false (no retry, the loop halts as before).
822
+ export async function readFreshBlockers(
823
+ ref: string,
824
+ sinceIso: string,
825
+ ): Promise<boolean> {
826
+ try {
827
+ const args = await avenArgsWithWorkspace(['show', ref, '--full'], ref)
828
+ const { stdout, stderr } = await execFileAsync('aven', args, {
829
+ timeout: AVEN_TIMEOUT_MS,
830
+ })
831
+ // AIDEV-NOTE: PMR-69V8 — check stderr ONLY: note bodies quote failing
832
+ // tests ("Error: ...") and must not be mistaken for an aven failure.
833
+ if (avenErrorText('', stderr) !== null) return false
834
+ return hasBlockersNoteSince(stdout, sinceIso)
835
+ } catch {
836
+ return false
837
+ }
838
+ }
839
+
840
+ export async function writeAvenLabel(
841
+ ref: string,
842
+ label: string,
843
+ ): Promise<boolean> {
844
+ // PMR-F8HB: `aven edit` prefix-matches like `aven show`, so an inexact
845
+ // ref would write a LIFECYCLE LABEL onto the wrong ticket. Guard the
846
+ // write with the exact-ref read; the fuzzy-match message lands in
847
+ // lastAvenResolutionFailure for the caller to surface.
848
+ const labels = await readAvenLabels(ref)
849
+ if (labels === null) return false
850
+ try {
851
+ const args = await avenArgsWithWorkspace(
852
+ ['edit', ref, '--label', label],
853
+ ref,
854
+ )
855
+ await execFileAsync('aven', args, {
856
+ timeout: AVEN_TIMEOUT_MS,
857
+ })
858
+ } catch (error: unknown) {
859
+ recordAvenFailure(error)
860
+ return false
861
+ }
862
+ // AIDEV-NOTE: PMR-VE27 (ISC-8) — verify success by REREAD, not by the
863
+ // exec's exit code: aven exiting 0 is not proof the label landed (an
864
+ // aven-side silent no-op must never read as a gate transition). The
865
+ // reread reuses the fail-closed readAvenLabels; an absent label (or a
866
+ // failed reread) records the reason and returns false — the lifecycle
867
+ // tool then reports a write failure and journals no phase receipt.
868
+ const after = await readAvenLabels(ref)
869
+ if (after === null) {
870
+ recordAvenFailure(
871
+ new Error(
872
+ `write verification failed: could not reread labels of ${ref} after the edit — "${label}" is unverified`,
873
+ ),
874
+ )
875
+ return false
876
+ }
877
+ if (!after.includes(label)) {
878
+ recordAvenFailure(
879
+ new Error(
880
+ `write verification failed: aven edit exited 0 but "${label}" is absent after rereading ${ref} — the write did not take effect`,
881
+ ),
882
+ )
883
+ return false
884
+ }
885
+ return true
886
+ }
887
+
888
+ // AIDEV-NOTE: PMR-B033 — the removal counterpart of writeAvenLabel. The ONLY
889
+ // caller is the flow loop's blocker route-back (removeAvenLabel dep): when
890
+ // validate routes back to implement for a fix round, the stale 'active' label
891
+ // from the previous round must be cleared so the loop's label-presence check
892
+ // cannot auto-complete the fix round. The agent bash interceptor keeps
893
+ // blocking model-side removals, so lifecycle labels stay extension-governed
894
+ // in BOTH directions. PMR-F8HB exact-ref guard first (an inexact ref must
895
+ // never strip a lifecycle label from the wrong ticket); idempotent: label
896
+ // already absent -> true with no exec (also sidesteps unknown CLI behavior
897
+ // when removing a label the ticket doesn't have).
898
+ export async function removeAvenLabel(
899
+ ref: string,
900
+ label: string,
901
+ ): Promise<boolean> {
902
+ const labels = await readAvenLabels(ref)
903
+ if (labels === null) return false
904
+ if (!labels.includes(label)) return true
905
+ try {
906
+ const args = await avenArgsWithWorkspace(
907
+ ['edit', ref, '--remove-label', label],
908
+ ref,
909
+ )
910
+ await execFileAsync('aven', args, {
911
+ timeout: AVEN_TIMEOUT_MS,
912
+ })
913
+ return true
914
+ } catch (error: unknown) {
915
+ recordAvenFailure(error)
916
+ return false
917
+ }
918
+ }
919
+
920
+ /**
921
+ * PMR-F8HB — best-effort discovery of aven project prefixes (PMR, MNT, …)
922
+ * via `aven project list --json`. Feeds registerAvenPrefixes (flow/ref-kind)
923
+ * so bare Jira-shaped aven refs (PMR-2424) classify as aven. Never throws;
924
+ * an empty result keeps the historical Jira-first heuristic.
925
+ */
926
+ export async function discoverAvenPrefixes(): Promise<string[]> {
927
+ try {
928
+ const { stdout } = await execFileAsync(
929
+ 'aven',
930
+ ['project', 'list', '--json'],
931
+ { timeout: AVEN_TIMEOUT_MS, cwd: avenSessionCwd },
932
+ )
933
+ const parsed: unknown = JSON.parse(stdout)
934
+ if (!Array.isArray(parsed)) return []
935
+ const prefixes: string[] = []
936
+ for (const entry of parsed) {
937
+ const prefix = (entry as { prefix?: unknown })?.prefix
938
+ if (typeof prefix === 'string' && prefix.trim() !== '') {
939
+ prefixes.push(prefix)
940
+ }
941
+ }
942
+ return prefixes
943
+ } catch {
944
+ return []
945
+ }
946
+ }
947
+
948
+ export function setAvenSessionCwd(cwd: string | undefined): void {
949
+ avenSessionCwd = cwd
950
+ }
951
+
952
+ export function getAvenSessionCwd(): string | undefined {
953
+ return avenSessionCwd
954
+ }
955
+
956
+ // AIDEV-NOTE: Best-effort label bootstrap — label creation must never break
957
+ // startup (PMR-SE93). Failures are classified (flow/ensure-labels.ts):
958
+ // aven-missing → one visible warning; already-exists → silent; anything else
959
+ // → surfaced warning with stderr. The override targets the same workspace the
960
+ // ref-resolution path uses when `avenWorkspace` is configured; without it,
961
+ // cwd inference is the only option here (no ref is known at session_start).
962
+ export async function ensureLabels(
963
+ notify?: (message: string, level: 'info' | 'warning' | 'error') => void,
964
+ ): Promise<void> {
965
+ let override: string[]
966
+ try {
967
+ override = await avenOverrideArg()
968
+ } catch {
969
+ override = []
970
+ }
971
+ let avenMissing = false
972
+ const otherFailures: string[] = []
973
+ for (const label of ALL_LABELS) {
974
+ try {
975
+ await execFileAsync('aven', ['label', 'create', label, ...override], {
976
+ timeout: AVEN_TIMEOUT_MS,
977
+ })
978
+ } catch (error: unknown) {
979
+ const failure = classifyLabelFailure(error)
980
+ if (failure.kind === 'aven-missing') {
981
+ avenMissing = true
982
+ } else if (failure.detail !== undefined) {
983
+ otherFailures.push(`aven label create ${label}: ${failure.detail}`)
984
+ }
985
+ }
986
+ }
987
+ if (avenMissing) {
988
+ notify?.(
989
+ 'phase labels unavailable; gates will fail-closed until aven is on PATH',
990
+ 'warning',
991
+ )
992
+ }
993
+ for (const failure of otherFailures) {
994
+ notify?.(failure, 'warning')
995
+ }
996
+ }