@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/status.ts ADDED
@@ -0,0 +1,395 @@
1
+ // AIDEV-NOTE (PMR-MSDJ 1.4, plan PMR-V36Y decision 2): daemon-safe aven
2
+ // ticket STATUS map — the liveness rule for the pushgateway reconcile. A
3
+ // halted/paused journal run counts as LIVE only while its aven ticket status
4
+ // is `active`; everything else (inbox/backlog/todo/done/canceled, or the ref
5
+ // missing from the map) is stale and gets tombstoned.
6
+ //
7
+ // This file deliberately MIRROWS aven/client.ts's conventions (the
8
+ // `AvenRunner` contract, `avenExec`'s execFile + 5s timeout, and the
9
+ // fail-closed classify discipline of classifyListHead/classifyOpenTicketRefs
10
+ // — ISC-13) WITHOUT importing it: client.ts imports config.ts, which
11
+ // runtime-imports `@earendil-works/pi-coding-agent`. server/daemon.ts's
12
+ // header contract forbids that on the daemon path, so everything reachable
13
+ // from the reconcile engine stays node-built-ins-only. `AvenRunner` is
14
+ // re-declared here (structurally identical to client.ts's, so session-side
15
+ // callers can pass `avenExec` straight in); spec-review/aven-spec.ts is also
16
+ // NOT reused for the same reason — the `/^(Error:|error\s)/` text check is
17
+ // duplicated instead.
18
+ //
19
+ // Fail-closed semantics (same as classifyOpenTicketRefs, PMR-384R): aven
20
+ // exits 0 on its own errors, so NOTHING here trusts the exit code. ANY
21
+ // anomaly — error text on stdout or stderr, non-JSON, non-array schema drift,
22
+ // or an entry lacking a usable `ref`/`status` — returns null, never a partial
23
+ // Map. A partial Map would be read as "this ticket is gone" and wrongly
24
+ // tombstone a live run's metrics, which is the exact failure mode decision 2
25
+ // guards against. An empty Map at the PARSE level comes only from a
26
+ // successfully parsed empty array, but an empty MERGED universe is treated as
27
+ // an anomaly (null) — see the P2-2 guard in listTicketStatuses. null carries
28
+ // no reason string: the engine warns once per pass on null (see
29
+ // flow/reconcile.ts), so no client.ts-style recordAvenFailure store is
30
+ // mirrored here.
31
+ //
32
+ // Consumer: flow/reconcile.ts runReconcilePass — ONE listTicketStatuses()
33
+ // call per pass (which is TWO aven shell-outs), injected as
34
+ // ReconcileDeps.listTicketStatuses, PLUS one bounded ticketStatusOf() probe
35
+ // per candidate the listing does not know (see P2-1 below).
36
+ //
37
+ // Pinned against the real CLI (aven 0.1.54, output captured 2026-11-24):
38
+ // `aven list --all-projects … --json` prints a JSON ARRAY of ticket objects
39
+ // whose fields are `ref` (string, e.g. "PMR-62EN") and `status` (string,
40
+ // one of inbox|backlog|todo|active|done|canceled). DONE AND CANCELED TICKETS
41
+ // DO APPEAR in the listing (live measurement: 809 entries — 702 done, 27
42
+ // canceled, 59 backlog, 15 inbox, 4 todo, 2 active), so the map carries
43
+ // closed statuses and computeStaleRefs reads them directly. Active tickets
44
+ // always appear (verified). A ref the listing omits is only a STALE candidate
45
+ // — `ticketStatusOf` below is what turns that evidence into a decision.
46
+ //
47
+ // AIDEV-NOTE (PMR-MSDJ 1.4, workspace pinning — the fix for the cwd-routing
48
+ // hazard first measured here): `aven list` is WORKSPACE-ROUTE DEPENDENT even
49
+ // with
50
+ // `--all-projects`, because aven resolves the workspace from process.cwd()
51
+ // through ~/.config/aven/config.yaml `workspace.routes`. Measured live: cwd
52
+ // `<home>/Code/personal` → workspace "projects" (809 tickets), but a herdr
53
+ // worktree under `~/.herdr/worktrees` is UNROUTED and falls back to the
54
+ // "default" workspace (1 ticket). The unrouted listing is perfectly valid
55
+ // JSON, so fail-closed null CANNOT catch it — every real ref would read as
56
+ // "missing ⇒ stale" and the reconcile would tombstone LIVE runs, the one
57
+ // thing decision 2 forbids. A daemon's cwd is wherever pi happened to start,
58
+ // so this module never relies on cwd routing: it pins `--workspace` and
59
+ // shells out ONCE PER KNOWN WORKSPACE (see AVEN_TICKET_WORKSPACES), merging
60
+ // the results. Flow refs live in both: PMR-* personal tickets in "projects",
61
+ // Jira-pulled local epics in "salaryhero".
62
+ //
63
+ // Consequences of the pin, all deliberate:
64
+ // • TWO shell-outs per pass, so the worst-case stall is 2 x timeout
65
+ // (10s at 5s each) — irrelevant for a 6h timer and a manual command;
66
+ // • ANY failure in EITHER call fails the WHOLE map closed to null (no
67
+ // partial merge — a half universe produces exactly the false-stale the
68
+ // pin exists to prevent);
69
+ // • therefore a machine that lacks one of these workspaces tombstones
70
+ // nothing and warns once per pass: `aven list --workspace nosuchws` exits
71
+ // 1 with `Error: … unknown-workspace …` on stderr, which rejects
72
+ // execFileAsync ⇒ null. That is the safe direction, but it DOES mean the
73
+ // workspace list below is host-assumed — adjust the const (or have 2.2/2.3
74
+ // pass a configured list) rather than adding a cwd fallback.
75
+ //
76
+ // AIDEV-NOTE (PMR-MSDJ fix round, P2-1 — the hole this closes): an
77
+ // `avenWorkspace` config override to a THIRD workspace does NOT reject: both
78
+ // pinned listings succeed, the merge is a valid Map that simply lacks the
79
+ // run's ref, and the old "missing ⇒ stale" rule tombstoned a LIVE run. That
80
+ // is why the engine no longer treats a missing entry as sufficient evidence:
81
+ // `ticketStatusOf` below is a bounded, per-candidate confirmation with VETO
82
+ // authority only (it is consulted for refs the map already lacks, so it can
83
+ // remove a tombstone, never add one — verified against the real CLI: a live
84
+ // `todo` ticket in `projects` reads back as `ticket`, an absent ref as
85
+ // `missing`, a prefix-matched one as inconclusive null). It is
86
+ // workspace-EXPLICIT for the SAME reason the listing is: measured here, an
87
+ // un-pinned `aven show PMR-MSDJ --json` from a herdr worktree answers
88
+ // `unknown-ref` on a LIVE ticket (the cwd falls back to the 1-ticket
89
+ // `default` workspace), so one un-pinned shell-out would have made the veto a
90
+ // silent no-op. RESIDUAL: a workspace that is neither pinned nor reachable
91
+ // from the daemon's cwd stays invisible to BOTH calls, so such a ref still
92
+ // reads as missing — the structural fix is threading the configured
93
+ // `avenWorkspace` into AVEN_TICKET_WORKSPACES, which needs a session-side
94
+ // `loadConfig` read that the node-only daemon contract forbids (see
95
+ // flow/reconcile-deps.ts's P2-1 note).
96
+ import { execFile } from 'node:child_process'
97
+ import { promisify } from 'node:util'
98
+
99
+ const execFileAsync = promisify(execFile)
100
+
101
+ /** Same ceiling as aven/client.ts's AVEN_TIMEOUT_MS (client.ts:20). */
102
+ const AVEN_TIMEOUT_MS = 5_000
103
+
104
+ // AIDEV-NOTE: 16 MiB execFile buffer, not the 1 MiB default. The full
105
+ // `--all-projects --json` dump measured 698 KB / 809 tickets on 2026-11-24;
106
+ // at the default ceiling the list would soon start failing with ENOBUFS,
107
+ // which classifies as null and silently disables tombstoning forever.
108
+ const AVEN_LIST_MAX_BUFFER = 16 * 1024 * 1024
109
+
110
+ // AIDEV-NOTE: the workspaces that can hold a flow ref, in merge order (LAST
111
+ // WINS on a ref collision — see listTicketStatuses). Measured 2026-11-24 the
112
+ // two universes are disjoint (809 `projects` refs, 88 `salaryhero` refs, 0
113
+ // shared), so the tie-break is defensive only; `salaryhero` comes last so a
114
+ // collision resolves to the WORK-mode status, which is what a work-mode run's
115
+ // liveness must key on.
116
+ const AVEN_TICKET_WORKSPACES = ['projects', 'salaryhero']
117
+
118
+ /**
119
+ * Local mirror of aven/client.ts's `AvenRunner` contract (client.ts:22-24),
120
+ * re-declared so the daemon path stays node-only. Structurally identical:
121
+ * `avenExec` from client.ts satisfies it.
122
+ */
123
+ export type AvenRunner = (
124
+ args: readonly string[],
125
+ ) => Promise<{ stdout: string; stderr: string }>
126
+
127
+ /** The production runner: one `aven <args>` shell-out, used by both the
128
+ * pinned `list` calls and the single-ref `show` probe. */
129
+ export const avenListExec: AvenRunner = async (args) => {
130
+ const { stdout, stderr } = await execFileAsync('aven', [...args], {
131
+ timeout: AVEN_TIMEOUT_MS,
132
+ maxBuffer: AVEN_LIST_MAX_BUFFER,
133
+ })
134
+ return { stdout, stderr }
135
+ }
136
+
137
+ /** aven's unknown-ref marker (flow/aven-resolve.ts isUnknownRef): seen on
138
+ * stderr as `error unknown-ref input=<ref>`, exit 1 — and, like every aven
139
+ * error, sometimes with exit 0. */
140
+ const UNKNOWN_REF_MARKER = 'unknown-ref'
141
+
142
+ /**
143
+ * Classify one `aven list … --json` output as a ref → status map. Returns
144
+ * null on ANY anomaly (see the file header for the fail-closed contract);
145
+ * an empty Map means aven really has no tickets in that workspace.
146
+ */
147
+ export function classifyTicketStatuses(
148
+ stdout: string,
149
+ stderr: string,
150
+ ): Map<string, string> | null {
151
+ // avenErrorText pattern (spec-review/aven-spec.ts:37-44), inlined: aven
152
+ // prints domain errors WITH EXIT 0, so classify by text on either stream.
153
+ const lines = [...stdout.split('\n'), ...stderr.split('\n')]
154
+ if (lines.some((line) => /^(Error:|error\s)/.test(line.trim()))) {
155
+ return null
156
+ }
157
+ // aven's own CLI errors print lowercase `error: …` on stderr, which the
158
+ // pattern above does not match (`error` + `:`). Trim first (PMR-NPFR): an
159
+ // indented error line evaded both checks once and silently passed through.
160
+ if (stderr.split('\n').some((line) => /^error\b/.test(line.trim()))) {
161
+ return null
162
+ }
163
+ let parsed: unknown
164
+ try {
165
+ parsed = JSON.parse(stdout)
166
+ } catch {
167
+ return null
168
+ }
169
+ if (!Array.isArray(parsed)) return null
170
+ const statuses = new Map<string, string>()
171
+ for (const entry of parsed) {
172
+ // Unlike extractListRefs (client.ts:493-501), which SKIPS entries with no
173
+ // usable ref, every anomaly here fails the WHOLE map closed: a dropped
174
+ // entry looks exactly like a closed ticket to computeStaleRefs, and that
175
+ // guess would tombstone a live run.
176
+ if (typeof entry !== 'object' || entry === null) return null
177
+ const { ref, status } = entry as { ref?: unknown; status?: unknown }
178
+ if (typeof ref !== 'string' || ref.length === 0) return null
179
+ if (typeof status !== 'string' || status.length === 0) return null
180
+ statuses.set(ref, status)
181
+ }
182
+ return statuses
183
+ }
184
+
185
+ /**
186
+ * One workspace's ref → status map, or null when that workspace could not be
187
+ * listed or its output is anomalous.
188
+ */
189
+ async function listWorkspaceTicketStatuses(
190
+ runner: AvenRunner,
191
+ workspace: string,
192
+ ): Promise<Map<string, string> | null> {
193
+ try {
194
+ const out = await runner([
195
+ 'list',
196
+ '--all-projects',
197
+ '--workspace',
198
+ workspace,
199
+ '--json',
200
+ ])
201
+ return classifyTicketStatuses(out.stdout, out.stderr)
202
+ } catch {
203
+ // execFileAsync rejects on spawn failure, non-zero exit (an unknown
204
+ // workspace exits 1 with `Error: … unknown-workspace …`), and timeout —
205
+ // all the same answer: the status universe is unverifiable.
206
+ return null
207
+ }
208
+ }
209
+
210
+ /**
211
+ * Ref → aven ticket status over EVERY workspace a flow ref can live in, or
212
+ * null when aven is unreachable / anomalous in any of them (fail-closed —
213
+ * the reconcile tombstones nothing on a null and warns once per pass).
214
+ * Workspace-EXPLICIT by design: `--all-projects` alone still routes by
215
+ * process.cwd(), which a daemon cannot trust (see the header AIDEV-NOTE).
216
+ * Two shell-outs per call; neither is merged until both succeed.
217
+ *
218
+ * @param runner injectable for tests; defaults to {@link avenListExec}.
219
+ */
220
+ export async function listTicketStatuses(
221
+ runner: AvenRunner = avenListExec,
222
+ ): Promise<Map<string, string> | null> {
223
+ const listings: Map<string, string>[] = []
224
+ for (const workspace of AVEN_TICKET_WORKSPACES) {
225
+ const listing = await listWorkspaceTicketStatuses(runner, workspace)
226
+ if (listing === null) return null
227
+ listings.push(listing)
228
+ }
229
+ const merged = new Map<string, string>()
230
+ for (const listing of listings) {
231
+ for (const [ref, status] of listing) merged.set(ref, status)
232
+ }
233
+ // AIDEV-NOTE (PMR-MSDJ fix round, P2-2 — mass false-stale guard): every
234
+ // workspace answering ZERO tickets is not a real "no tickets" answer on a
235
+ // host that holds ~900 — it is aven failing in a way that still parses
236
+ // (this file's own threat model is "aven exits 0 on its own errors"). An
237
+ // empty Map reads to computeStaleRefs as "every ticket is gone", so one
238
+ // such pass would tombstone EVERY halted/paused run at once. Fail closed
239
+ // instead: null ⇒ the engine tombstones nothing and warns once.
240
+ // One EMPTY workspace alongside a populated one stays a real answer.
241
+ if (merged.size === 0) return null
242
+ return merged
243
+ }
244
+
245
+ /**
246
+ * Outcome of the bounded single-ref confirmation (P2-1): either aven knows
247
+ * the ticket (`ticket`, with its status) or it definitively does not
248
+ * (`missing`, aven's own `unknown-ref`). `null` is NOT an answer — it is an
249
+ * inconclusive lookup (spawn/timeout/other error text, non-JSON, schema
250
+ * drift, or a prefix-matched ref that belongs to a DIFFERENT ticket), and the
251
+ * engine must not tombstone on it.
252
+ */
253
+ export type TicketProbe =
254
+ | { readonly kind: 'ticket'; readonly status: string }
255
+ | { readonly kind: 'missing' }
256
+
257
+ /** Text of an execFile rejection: aven's error rides on stderr (or the
258
+ * message, which promisify prefixes with the command plus both streams). */
259
+ function rejectionText(error: unknown): string {
260
+ const stderr = (error as { stderr?: unknown })?.stderr
261
+ if (typeof stderr === 'string' && stderr.length > 0) return stderr
262
+ return error instanceof Error ? error.message : `${error}`
263
+ }
264
+
265
+ /**
266
+ * Ask aven DIRECTLY about one ref: `aven show <ref> --json`, workspace-EXPLICIT
267
+ * like {@link listTicketStatuses} and for the same measured reason — an
268
+ * unpinned `show` is cwd-route dependent, and the probe was verified against
269
+ * the real CLI to answer `unknown-ref` for LIVE tickets from an unrouted cwd
270
+ * (a herdr worktree falls back to the 1-ticket `default` workspace). Since
271
+ * "missing" is the answer that costs a tombstone, the probe consults the same
272
+ * universes the listing does PLUS aven's own cwd-routed default (which is how
273
+ * an `avenWorkspace` override reaches its tickets), and only calls a ref
274
+ * `missing` when EVERY universe answered `unknown-ref`. First exact hit wins,
275
+ * so a normally-placed ref costs ONE shell-out; the worst case is
276
+ * `AVEN_TICKET_WORKSPACES.length + 1` per missing candidate, still bounded by
277
+ * the candidate count and irrelevant for a 6 h timer or a manual pass.
278
+ *
279
+ * This exists to VETO false stales, never to create them: it is consulted
280
+ * only for refs the merged map already lacks, so every answer is at worst the
281
+ * pre-P2-1 behaviour and at best a live run keeps its metrics.
282
+ *
283
+ * Fail-closed discipline, identical to classifyTicketStatuses: only a parsed
284
+ * ticket whose ref matches the request EXACTLY (case-insensitively; PMR-F8HB:
285
+ * aven prefix-matches, so `aven show PMR-TPN` happily returns `PMR-TPN7`, and
286
+ * another ticket's status is not an answer about this one) with a non-empty
287
+ * string `status` counts as an answer, and only aven's own `unknown-ref`
288
+ * marker counts as `missing`. EVERYTHING else — spawn/timeout, other error
289
+ * text, non-JSON, schema drift, a fuzzy-matched ref — returns null, and a
290
+ * null on ANY universe makes the whole probe inconclusive rather than
291
+ * silently narrowing the evidence.
292
+ *
293
+ * @param runner injectable for tests; defaults to {@link avenListExec}.
294
+ */
295
+ export async function ticketStatusOf(
296
+ ref: string,
297
+ runner: AvenRunner = avenListExec,
298
+ ): Promise<TicketProbe | null> {
299
+ const universes: (string | undefined)[] = [...AVEN_TICKET_WORKSPACES]
300
+ // The cwd-routed default LAST: it is the only universe that can see an
301
+ // `avenWorkspace` override, and a hit anywhere else already answers.
302
+ universes.push(undefined)
303
+ let sawUnknownRef = false
304
+ for (const workspace of universes) {
305
+ const probe = await showTicketStatus(runner, ref, workspace)
306
+ if (probe === null) return null
307
+ if (probe.kind === 'ticket') return probe
308
+ sawUnknownRef = true
309
+ }
310
+ return sawUnknownRef ? { kind: 'missing' } : null
311
+ }
312
+
313
+ /** One `aven show <ref> --json` against one workspace universe (undefined =
314
+ * let aven resolve it from cwd). */
315
+ async function showTicketStatus(
316
+ runner: AvenRunner,
317
+ ref: string,
318
+ workspace: string | undefined,
319
+ ): Promise<TicketProbe | null> {
320
+ const args = ['show', ref, '--json']
321
+ if (workspace !== undefined) args.push('--workspace', workspace)
322
+ let stdout = ''
323
+ let stderr = ''
324
+ try {
325
+ const out = await runner(args)
326
+ stdout = out.stdout
327
+ stderr = out.stderr
328
+ } catch (error) {
329
+ // execFileAsync rejects on spawn failure, timeout and aven's exit 1.
330
+ // Only the unknown-ref marker is a real "there is no such ticket" answer.
331
+ return rejectionText(error).includes(UNKNOWN_REF_MARKER)
332
+ ? { kind: 'missing' }
333
+ : null
334
+ }
335
+ // aven prints errors with exit 0, so classify the TEXT before trusting the
336
+ // payload (ISC-13): unknown-ref => missing, any other error text => null.
337
+ if (
338
+ stderr.includes(UNKNOWN_REF_MARKER) ||
339
+ stdout.includes(UNKNOWN_REF_MARKER)
340
+ ) {
341
+ return { kind: 'missing' }
342
+ }
343
+ if (avenErrorText(stdout, stderr)) return null
344
+ let parsed: unknown
345
+ try {
346
+ parsed = JSON.parse(stdout)
347
+ } catch {
348
+ return null
349
+ }
350
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
351
+ return null
352
+ }
353
+ const record = parsed as { ref?: unknown; status?: unknown }
354
+ if (typeof record.ref !== 'string' || record.ref.length === 0) return null
355
+ if (record.ref.toUpperCase() !== ref.toUpperCase()) return null
356
+ if (typeof record.status !== 'string' || record.status.length === 0) {
357
+ return null
358
+ }
359
+ return { kind: 'ticket', status: record.status }
360
+ }
361
+
362
+ // AIDEV-NOTE (PMR-STDK): avenErrorText and classifyTicketStatuses each carry
363
+ // the fail-closed error-text rule, and they are DELIBERATELY not the same
364
+ // predicate. Do NOT consolidate them into one shared helper: it is
365
+ // correctness/security-critical (a missed error line reads as a live ticket
366
+ // and skips a tombstone, or the inverse), and unifying two slightly different
367
+ // strictness levels is riskier than keeping two local copies.
368
+ //
369
+ // HOW the in-file copy differs from classifyTicketStatuses's inline rule:
370
+ // • classifyTicketStatuses checks `^(Error:|error\s)` across BOTH streams but
371
+ // the `^error\b` anchor on STDERR ONLY (stdout is the JSON payload, so a
372
+ // bare `error:` token there is tolerated until the JSON.parse fails closed).
373
+ // • avenErrorText applies `^(Error:|error\s)` AND `^error\b` to BOTH streams,
374
+ // so it is the STRICTER superset — a stdout line like `error: ...` trips it
375
+ // but not classifyTicketStatuses. Its caller (showTicketStatus, line ~343)
376
+ // reads a single-ticket show payload where the error can ride on either
377
+ // stream, hence the wider net.
378
+ // WHAT MUST STAY IN SYNC: the two core `^(Error:|error\s)` patterns and the
379
+ // "any error text on either stream => fail closed, never trust the exit code"
380
+ // contract (aven exits 0 on its own errors). If one caller's `Error:` /
381
+ // `error ` shape changes, audit the other in the same edit; the `^error\b`
382
+ // stream scope is the ONLY intended divergence.
383
+ /** The aven error-text rule (`Error:` / `error ` / indented `error:`) that
384
+ * classifyTicketStatuses applies inline, in one pass: returns the offending
385
+ * line, or null when neither stream carries one. NOT shared with
386
+ * spec-review/aven-spec.ts for the reason the file header gives — that
387
+ * module imports aven/client.ts, which runtime-imports pi-coding-agent. */
388
+ function avenErrorText(stdout: string, stderr: string): string | null {
389
+ for (const line of [...stdout.split('\n'), ...stderr.split('\n')]) {
390
+ const trimmed = line.trim()
391
+ if (/^(Error:|error\s)/.test(trimmed)) return trimmed
392
+ if (/^error\b/.test(trimmed)) return trimmed
393
+ }
394
+ return null
395
+ }
@@ -0,0 +1,24 @@
1
+ // AIDEV-NOTE: Pure /brainstorm arg parsing — unit-testable without pi.
2
+ // `ID=<jira-id>` marks the topic as a known Jira ID (forceRef): the target
3
+ // classifier (brainstorm/refs.ts) then takes the ticket path in any mode.
4
+
5
+ export type BrainstormArgs =
6
+ | { kind: 'feature'; topic: string; forceRef?: boolean }
7
+ | { kind: 'debug'; symptom: string }
8
+ | { kind: 'help' }
9
+
10
+ export function parseBrainstormArgs(raw: string): BrainstormArgs {
11
+ const trimmed = raw.trim()
12
+ if (trimmed === '') return { kind: 'help' }
13
+ if (trimmed.startsWith('--debug')) {
14
+ const symptom = trimmed.slice('--debug'.length).trim()
15
+ if (symptom === '') return { kind: 'help' }
16
+ return { kind: 'debug', symptom }
17
+ }
18
+ if (trimmed.startsWith('ID=')) {
19
+ const topic = trimmed.slice('ID='.length).trim()
20
+ if (topic === '') return { kind: 'help' }
21
+ return { kind: 'feature', topic, forceRef: true }
22
+ }
23
+ return { kind: 'feature', topic: trimmed }
24
+ }
@@ -0,0 +1,67 @@
1
+ // AIDEV-NOTE: Artifact renderer for the /brainstorm phase. Both flows share
2
+ // the skeleton; flow 1 gets "Ticket implications", flow 2 gets "Hypothesis
3
+ // chain" + "Evidence". Diagrams/flows are embedded as mermaid code fences.
4
+ // AIDEV-NOTE (PMR-85RV): the former findBrainstormArtifact + its
5
+ // "> brainstormed by pi-flow" marker are gone. The /flow pull-in caller was
6
+ // removed in PMR-Z2K7, so the rediscovery contract had no production reader
7
+ // left; the prompt no longer promises discovery nothing implements.
8
+
9
+ export interface ArtifactInput {
10
+ kind: 'feature' | 'debug'
11
+ title: string
12
+ date: string
13
+ mode: string
14
+ questions: readonly string[]
15
+ findings: readonly string[]
16
+ diagrams: readonly string[]
17
+ ticketImplications?: readonly string[]
18
+ hypothesisChain?: readonly string[]
19
+ evidence?: readonly string[]
20
+ }
21
+
22
+ function bullets(items: readonly string[]): string {
23
+ if (items.length === 0) return '_None yet_'
24
+ return items.map((item) => `- ${item}`).join('\n')
25
+ }
26
+
27
+ export function renderArtifact(input: ArtifactInput): string {
28
+ const lines: string[] = []
29
+ lines.push(`# Brainstorm: ${input.title}`)
30
+ lines.push('')
31
+ lines.push(`- Date: ${input.date}`)
32
+ lines.push(`- Flow: ${input.kind}`)
33
+ lines.push(`- Mode: ${input.mode}`)
34
+ lines.push('')
35
+ lines.push('## Questions')
36
+ lines.push('')
37
+ lines.push(bullets(input.questions))
38
+ lines.push('')
39
+ lines.push('## Findings')
40
+ lines.push('')
41
+ lines.push(bullets(input.findings))
42
+ lines.push('')
43
+ if (input.diagrams.length > 0) {
44
+ lines.push('## Diagrams')
45
+ lines.push('')
46
+ for (const diagram of input.diagrams) {
47
+ lines.push(diagram)
48
+ lines.push('')
49
+ }
50
+ }
51
+ if (input.kind === 'feature') {
52
+ lines.push('## Ticket implications')
53
+ lines.push('')
54
+ lines.push(bullets(input.ticketImplications ?? []))
55
+ lines.push('')
56
+ } else {
57
+ lines.push('## Hypothesis chain')
58
+ lines.push('')
59
+ lines.push(bullets(input.hypothesisChain ?? []))
60
+ lines.push('')
61
+ lines.push('## Evidence')
62
+ lines.push('')
63
+ lines.push(bullets(input.evidence ?? []))
64
+ lines.push('')
65
+ }
66
+ return lines.join('\n')
67
+ }
@@ -0,0 +1,43 @@
1
+ import { join } from 'node:path'
2
+ import { MODE_PROFILE } from '../mode-profile.ts'
3
+ import { slugify } from '../slugify.ts'
4
+ import type { WorkMode } from '../work-mode.ts'
5
+
6
+ // AIDEV-NOTE: PMR-XCA9 — mirrors plan-tools/helpers.ts resolveSpecPath's
7
+ // env-fallback contract (same package since the pi-planning absorption;
8
+ // pure here, exec-based there). Work mode: $LLM_NOTES_ROOT/<repo>/notes/brainstorm/
9
+ // when set. Personal mode: $PERSONAL_FEATURES/<repo>/notes/brainstorm/ when set
10
+ // ($PERSONAL_FEATURES is the personal counterpart of $LLM_NOTES_ROOT —
11
+ // PMR-MSGE: personal brainstorm artifacts must never land under the work
12
+ // notes root). Both modes fall back to <git-toplevel>/notes/brainstorm/.
13
+ // PMR-H7RW: dir renamed notes/research -> notes/brainstorm; no production
14
+ // reader of the old dir remained (findResearchedArtifact's /flow caller
15
+ // was removed with PMR-Z2K7), so the rename is a clean break.
16
+ export function resolveBrainstormDir(
17
+ mode: WorkMode,
18
+ notesRoot: string | undefined,
19
+ personalFeatures: string | undefined,
20
+ repoName: string,
21
+ gitToplevel: string,
22
+ ): string {
23
+ // AIDEV-NOTE: which env root applies is data (mode-profile.ts); the
24
+ // params still carry both values so the caller shape is unchanged.
25
+ let root: string | undefined
26
+ if (MODE_PROFILE[mode].artifactRootEnv === 'LLM_NOTES_ROOT') {
27
+ root = notesRoot
28
+ } else {
29
+ root = personalFeatures
30
+ }
31
+ if (root) {
32
+ return join(root, repoName, 'notes', 'brainstorm')
33
+ }
34
+ return join(gitToplevel, 'notes', 'brainstorm')
35
+ }
36
+
37
+ export function brainstormArtifactPath(
38
+ dir: string,
39
+ title: string,
40
+ date: string,
41
+ ): string {
42
+ return join(dir, `${date}-${slugify(title)}.md`)
43
+ }