@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/config.ts ADDED
@@ -0,0 +1,577 @@
1
+ // AIDEV-NOTE: viewerPlacement mirrors VIEWER_PLACEMENTS / ViewerPlacement in
2
+ // herdr/viewer.ts — duplicate literal union by design (config stays standalone);
3
+ // keep the two in sync (PMR-YD1P).
4
+ // AIDEV-NOTE: pi-flow config boundary (PMR-T22H) — TypeBox schema is the
5
+ // source of truth for config shape; config.schema.json (checked in) mirrors
6
+ // it. Malformed config throws a clear error — never silent defaults
7
+ // (AGENTS.md rule). resolveMode is the pi-bound mode resolver; the pure
8
+ // modeForToplevel decision lives in work-mode.ts.
9
+
10
+ import { execFile } from 'node:child_process'
11
+ import { promises as fs } from 'node:fs'
12
+ import path from 'node:path'
13
+ import { promisify } from 'node:util'
14
+ import {
15
+ CONFIG_DIR_NAME,
16
+ type ExtensionAPI,
17
+ getAgentDir,
18
+ } from '@earendil-works/pi-coding-agent'
19
+ import { type Static, Type } from 'typebox'
20
+ import { Value } from 'typebox/value'
21
+ import { modeForToplevel, type WorkMode } from './work-mode.ts'
22
+
23
+ const PiFlowConfigSchema = Type.Object({
24
+ workRoots: Type.Array(
25
+ Type.String({ description: 'Absolute path prefix of a work repo root' }),
26
+ {
27
+ description: 'Git toplevels under any prefix are "work" mode',
28
+ minItems: 0,
29
+ },
30
+ ),
31
+ avenWorkspace: Type.Optional(
32
+ Type.String({
33
+ description:
34
+ 'Aven workspace name or key forced on every aven call pi-flow makes (skips cwd inference and search fallback)',
35
+ }),
36
+ ),
37
+ yolo: Type.Optional(
38
+ Type.Boolean({
39
+ description:
40
+ 'Run /flow phases without confirmation gates (personal mode only — work-mode runs refuse yolo at loop start). Only applies when the --yolo flag is absent on the /flow invocation — an explicit flag wins over config',
41
+ }),
42
+ ),
43
+ viewerPlacement: Type.Optional(
44
+ Type.Union(
45
+ [
46
+ Type.Literal('right'),
47
+ Type.Literal('below'),
48
+ Type.Literal('left'),
49
+ Type.Literal('above'),
50
+ Type.Literal('tab'),
51
+ ],
52
+ {
53
+ description:
54
+ 'Default Herdr pane placement for /flow-view when no placement argument is given',
55
+ },
56
+ ),
57
+ ),
58
+ landTestCommand: Type.Optional(
59
+ Type.Array(Type.String(), {
60
+ description:
61
+ 'Argv of the test command flow_land runs before authorizing a landing (default ["bun","run","test"]). PMR-05HX: the landing gate never trusts a claimed-green suite.',
62
+ minItems: 1,
63
+ }),
64
+ ),
65
+ telemetry: Type.Optional(
66
+ Type.Object(
67
+ {
68
+ enabled: Type.Boolean({
69
+ description:
70
+ 'Master switch — telemetry subscribes to nothing when false/absent (PMR-R8AG)',
71
+ }),
72
+ // AIDEV-NOTE: PMR-VSST — `otlpEndpoint` is schema-OPTIONAL so a
73
+ // loki-only config (telemetry.enabled false + telemetry.loki.enabled
74
+ // true) parses without an OTLP base. The surviving coupling —
75
+ // enabled true REQUIRES the endpoint — is an explicit check at the
76
+ // readConfigFile boundary below (a TypeBox union could express it
77
+ // but wrecks the error messages and the checked-in JSON mirror).
78
+ otlpEndpoint: Type.Optional(
79
+ Type.String({
80
+ description:
81
+ 'OTLP/HTTP base URL (e.g. https://host:4478); spans POST to <endpoint>/v1/traces. Required when telemetry.enabled is true (PMR-VSST); omit for a loki-only setup',
82
+ }),
83
+ ),
84
+ headers: Type.Optional(
85
+ Type.Record(Type.String(), Type.String(), {
86
+ description:
87
+ 'Static extra headers for OTLP export. Secrets belong in env (PI_FLOW_OTLP_TOKEN), not config',
88
+ }),
89
+ ),
90
+ captureContent: Type.Optional(
91
+ Type.Union(
92
+ [
93
+ Type.Literal('off'),
94
+ Type.Literal('text'),
95
+ Type.Literal('tools'),
96
+ Type.Literal('all'),
97
+ ],
98
+ {
99
+ description:
100
+ 'Content captured on spans (cumulative): off = metadata only (default), text = assistant text, tools = + tool calls the model made and tool input/output, all = + model reasoning. Captured content can contain secrets and lands in the trace backend',
101
+ },
102
+ ),
103
+ ),
104
+ jiraBaseUrl: Type.Optional(
105
+ Type.String({
106
+ description:
107
+ 'Base URL for Jira issue links, e.g. https://example.atlassian.net/browse/ — work-mode spans then carry flow.url = <base><jira key> so dashboards can link tickets. Absent = no links',
108
+ }),
109
+ ),
110
+ maxContentChars: Type.Optional(
111
+ Type.Integer({
112
+ minimum: 100,
113
+ maximum: 100000,
114
+ description:
115
+ 'Max characters per captured content attribute (default 2000). Tempo truncates attribute values beyond max_attribute_bytes (default 2048) silently — raise both together',
116
+ }),
117
+ ),
118
+ // AIDEV-NOTE: PMR-ZV9Y (4.2) — `telemetry.loki` gates the Loki
119
+ // transition-event stream (telemetry/loki.ts). SINGLE STRICT READER,
120
+ // session-side ONLY (do not add a tolerant daemon half): unlike
121
+ // `reconcile`/`liveness` (TWO READERS, ONE FILE), the daemon never
122
+ // pushes Loki — only the live session fan-out (subtask 4.3) does, so
123
+ // there is exactly one reader here (this schema, via readConfigFile,
124
+ // which throws on a malformed shape — AGENTS.md: never silent
125
+ // defaults). `enabled` defaults to false: absent/disabled = ZERO Loki
126
+ // network calls. `endpoint` stores the base URL only (user-provided,
127
+ // e.g. http://loki.example.com:3100); the pusher appends
128
+ // /loki/api/v1/push (D2). `headers` are static extra headers (Bearer
129
+ // token belongs in env, never config). Free text (note/halt prose) is
130
+ // NEVER a label — it rides the JSON line (ISC-A-1).
131
+ loki: Type.Optional(
132
+ Type.Object(
133
+ {
134
+ enabled: Type.Optional(
135
+ Type.Boolean({
136
+ description:
137
+ 'Push flow transition-event streams to Loki. Default false (disabled — zero network calls)',
138
+ default: false,
139
+ }),
140
+ ),
141
+ endpoint: Type.Optional(
142
+ Type.String({
143
+ description:
144
+ 'Loki base URL (user-provided, e.g. http://loki.example.com:3100); events POST to <endpoint>/loki/api/v1/push. Required with telemetry.loki.enabled',
145
+ }),
146
+ ),
147
+ headers: Type.Optional(
148
+ Type.Record(Type.String(), Type.String(), {
149
+ description:
150
+ 'Static extra headers for the Loki push. Secrets belong in env, not config',
151
+ }),
152
+ ),
153
+ },
154
+ {
155
+ description:
156
+ 'Optional Loki transition-event stream, session-side only (PMR-ZV9Y 4.2)',
157
+ },
158
+ ),
159
+ ),
160
+ },
161
+ { description: 'Optional OTLP telemetry export (PMR-R8AG)' },
162
+ ),
163
+ ),
164
+ // AIDEV-NOTE: PMR-ZV9Y (5.2) — `notify` gates the flow-side DESKTOP
165
+ // notification channel (telemetry/dispatch.ts createNotifySink). SINGLE
166
+ // STRICT READER, session-side ONLY (same posture as `telemetry.loki`, unlike
167
+ // the TWO-READER `reconcile`/`liveness` blocks): the daemon has no notify
168
+ // path, only the live session fan-out pages, so exactly one reader exists
169
+ // (this schema via readConfigFile, which throws on a malformed shape).
170
+ // DEFAULT TRUE — the channel is opt-OUT, so a fresh install pages on a
171
+ // waiting_human run instead of silently notifying nobody. pi-flow's switch
172
+ // gates the FLOW-side page only; the user's own channel toggles
173
+ // (desktop/herdr/ntfy) keep living in the desktop-notify module's own
174
+ // config (rifle-batteries: ~/.pi/agent/pi-rifle-batteries/desktop-notify/),
175
+ // and Grafana alerting is the independent second channel with its own
176
+ // pause/mute (PMR-ZV9Y D3).
177
+ notify: Type.Optional(
178
+ Type.Object(
179
+ {
180
+ desktop: Type.Optional(
181
+ Type.Object(
182
+ {
183
+ enabled: Type.Optional(
184
+ Type.Boolean({
185
+ description:
186
+ 'Send a desktop notification on waiting_human / halted flow transitions through the desktop-notify extension (rifle-batteries). Default true (opt-out)',
187
+ default: true,
188
+ }),
189
+ ),
190
+ },
191
+ {
192
+ description:
193
+ 'Desktop channel via @gtheys/rifle-batteries/notify (optional dependency)',
194
+ },
195
+ ),
196
+ ),
197
+ },
198
+ { description: 'Flow-state notifications (PMR-ZV9Y 5.2)' },
199
+ ),
200
+ ),
201
+ runServer: Type.Optional(
202
+ Type.Object(
203
+ {
204
+ enabled: Type.Optional(
205
+ Type.Boolean({
206
+ description:
207
+ 'Kill switch for the durable run server (PMR-XTQQ). false = never spawn the daemon and journal writers permanently use today\u2019s full in-session path. Default true',
208
+ }),
209
+ ),
210
+ },
211
+ { description: 'Durable run server (daemon) settings' },
212
+ ),
213
+ ),
214
+ // AIDEV-NOTE: PMR-MSDJ (2.1, plan PMR-V36Y decision 4) — `reconcile` is the
215
+ // pushgateway liveness-retire switch. TWO READERS, ONE FILE, DELIBERATE
216
+ // SPLIT (do not "unify" them):
217
+ // • extension side (this schema + resolveReconcileSettings): strict —
218
+ // an invalid shape throws at the readConfigFile boundary (AGENTS.md:
219
+ // never silent defaults).
220
+ // • daemon side (flow/reconcile.ts parseReconcileSettings): tolerant —
221
+ // server/daemon.ts must stay node-only (no pi-coding-agent import), so
222
+ // it reads the GLOBAL file as raw text and falls back to the same
223
+ // defaults with a warning instead of throwing.
224
+ // Both agree on enabled=true / intervalMinutes=360; the split only changes
225
+ // what happens on a MALFORMED file (extension: loud throw, daemon: defaults
226
+ // + warning). The daemon has no session cwd, so it never sees project
227
+ // overrides — the manual /flow-reconcile-push command is the escape hatch.
228
+ // Unknown keys are NOT rejected by either reader (Value.Check does not
229
+ // enforce additionalProperties — true for the whole schema), so a stray key
230
+ // is silently ignored on both paths.
231
+ reconcile: Type.Optional(
232
+ Type.Object(
233
+ {
234
+ enabled: Type.Optional(
235
+ Type.Boolean({
236
+ description:
237
+ 'Reconcile stale run-liveness metrics (tombstone the v2 pi_flow_state series whose aven ticket is not live (neither active nor todo): state halted/waiting_human/waiting_machine becomes stale). Default true',
238
+ }),
239
+ ),
240
+ intervalMinutes: Type.Optional(
241
+ Type.Integer({
242
+ minimum: 1,
243
+ description:
244
+ 'Daemon reconcile interval in minutes. Default 360 (6h)',
245
+ }),
246
+ ),
247
+ },
248
+ { description: 'Pushgateway liveness reconcile (PMR-V36Y)' },
249
+ ),
250
+ ),
251
+ // AIDEV-NOTE: PMR-8MQH (4.1) — `liveness` is the running-flow liveness-push
252
+ // switch. Same TWO READERS, ONE FILE, DELIBERATE SPLIT as `reconcile` above
253
+ // (do not "unify" them):
254
+ // • extension side (this schema + resolveLivenessSettings): strict — an
255
+ // invalid shape throws at the readConfigFile boundary (AGENTS.md: never
256
+ // silent defaults).
257
+ // • daemon side (flow/liveness.ts parseLivenessSettings): tolerant —
258
+ // server/daemon.ts must stay node-only (no pi-coding-agent import), so
259
+ // it reads the GLOBAL file as raw text and falls back to the same
260
+ // defaults with a warning instead of throwing.
261
+ // Both agree on enabled=true / intervalMinutes=5; the defaults are pinned
262
+ // equal in test/config.test.ts against DEFAULT_LIVENESS_SETTINGS so the two
263
+ // readers cannot drift. The daemon has no session cwd, so it sees only the
264
+ // GLOBAL config — project overrides are invisible to it by design.
265
+ // Unknown keys are NOT rejected by either reader (Value.Check does not
266
+ // enforce additionalProperties — true for the whole schema), so a stray key
267
+ // is silently ignored on both paths.
268
+ liveness: Type.Optional(
269
+ Type.Object(
270
+ {
271
+ enabled: Type.Optional(
272
+ Type.Boolean({
273
+ description:
274
+ 'Push run-liveness metrics for flows in flight. Default true',
275
+ }),
276
+ ),
277
+ intervalMinutes: Type.Optional(
278
+ Type.Integer({
279
+ minimum: 1,
280
+ description: 'Daemon liveness push interval in minutes. Default 5',
281
+ }),
282
+ ),
283
+ },
284
+ {
285
+ description: 'Run-liveness pushes while flows are in flight (PMR-8MQH)',
286
+ },
287
+ ),
288
+ ),
289
+ })
290
+
291
+ export type PiFlowConfig = Static<typeof PiFlowConfigSchema>
292
+
293
+ // AIDEV-NOTE: PMR-JP37 (3.3) — persists viewerPlacement to the GLOBAL config
294
+ // (<agentDir>/pi-flow/config.json). Best-effort by contract: the /flow-view
295
+ // handler warns and still opens the pane if this throws. A present-but-
296
+ // malformed existing file throws via the same Value.Check contract as
297
+ // readConfigFile so a bad config is never clobbered; a valid file that merely
298
+ // lacks viewerPlacement is merged in-place, preserving all other keys
299
+ // (including unknown ones — the merged object is NOT re-validated).
300
+ export async function saveViewerPlacement(
301
+ agentDir: string,
302
+ placement: 'right' | 'below' | 'left' | 'above' | 'tab',
303
+ ): Promise<string> {
304
+ const file = path.join(agentDir, 'pi-flow', 'config.json')
305
+ const existing = await readConfigFile(file)
306
+ const merged: Record<string, unknown> = { ...existing }
307
+ // workRoots is required by PiFlowConfigSchema — a fresh config must carry the
308
+ // empty default so the file is valid on the next read.
309
+ if (merged.workRoots === undefined) merged.workRoots = []
310
+ merged.viewerPlacement = placement
311
+ await fs.mkdir(path.dirname(file), { recursive: true })
312
+ await fs.writeFile(file, `${JSON.stringify(merged, null, 2)}\n`, 'utf8')
313
+ return file
314
+ }
315
+
316
+ export async function readConfigFile(
317
+ file: string,
318
+ ): Promise<Partial<PiFlowConfig>> {
319
+ let raw: string
320
+ try {
321
+ raw = await fs.readFile(file, 'utf8')
322
+ } catch (error: unknown) {
323
+ if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') return {}
324
+ const msg = error instanceof Error ? error.message : String(error)
325
+ throw new Error(`Failed to read pi-flow config ${file}: ${msg}`)
326
+ }
327
+ let parsed: unknown
328
+ try {
329
+ parsed = JSON.parse(raw)
330
+ } catch (error: unknown) {
331
+ const msg = error instanceof Error ? error.message : String(error)
332
+ throw new Error(`pi-flow config ${file} is not valid JSON: ${msg}`)
333
+ }
334
+ if (!Value.Check(PiFlowConfigSchema, parsed)) {
335
+ const errors = Value.Errors(PiFlowConfigSchema, parsed)
336
+ // AIDEV-NOTE: include the property path so enum/shape errors name the
337
+ // offending key (e.g. viewerPlacement) instead of bare "equal to constant".
338
+ .map((e) => {
339
+ let text = e.message
340
+ if (e.instancePath !== '/') text = `${e.instancePath}: ${text}`
341
+ return text
342
+ })
343
+ .join('; ')
344
+ throw new Error(`pi-flow config ${file} is invalid: ${errors}`)
345
+ }
346
+ // AIDEV-NOTE: PMR-VSST — the surviving OTLP coupling, enforced at the same
347
+ // strict boundary as the schema check above (never silent defaults):
348
+ // telemetry.enabled true without otlpEndpoint is invalid. Kept out of the
349
+ // schema so a loki-only config (enabled false + telemetry.loki) parses —
350
+ // see the AIDEV-NOTE on the otlpEndpoint property.
351
+ if (
352
+ parsed.telemetry?.enabled === true &&
353
+ parsed.telemetry.otlpEndpoint === undefined
354
+ ) {
355
+ throw new Error(
356
+ `pi-flow config ${file} is invalid: telemetry.otlpEndpoint is required when telemetry.enabled is true`,
357
+ )
358
+ }
359
+ return parsed
360
+ }
361
+
362
+ // AIDEV-NOTE: Global getAgentDir()/pi-flow/config.json, then project override
363
+ // ctx.cwd/CONFIG_DIR_NAME/pi-flow/config.json wins. Missing files = empty
364
+ // merge; present-but-invalid = throw.
365
+ //
366
+ // PMR-BF8W: herdr worktree bootstrap copies only .env*, so a linked git
367
+ // worktree has no .pi/pi-flow/config.json and a stale global landTestCommand
368
+ // (e.g. ["cargo","test"] left over for another project) silently won the
369
+ // flow_land gate. When cwd sits in a LINKED worktree (git rev-parse
370
+ // --git-common-dir points outside the worktree's own .git), the main
371
+ // checkout's project config is consulted as a middle layer:
372
+ // global < main checkout project < worktree-local project (nearest wins)
373
+ // Main-checkout behavior is unchanged (project wins over global). The git
374
+ // lookup is best-effort: outside a repo or on git failure the layer is simply
375
+ // absent. Present-but-invalid config files still throw via readConfigFile —
376
+ // never silent defaults (AGENTS.md rule).
377
+ const execFileAsync = promisify(execFile)
378
+
379
+ // Absolute path of the main checkout that owns the linked worktree containing
380
+ // cwd, or undefined when cwd is not inside a linked worktree (plain checkout,
381
+ // non-git dir, git unavailable/failed).
382
+ async function mainCheckoutRoot(cwd: string): Promise<string | undefined> {
383
+ try {
384
+ const toplevel = (
385
+ await execFileAsync('git', ['rev-parse', '--show-toplevel'], { cwd })
386
+ ).stdout.trim()
387
+ const commonDir = (
388
+ await execFileAsync('git', ['rev-parse', '--git-common-dir'], { cwd })
389
+ ).stdout.trim()
390
+ // Resolve both against cwd (git prints relative paths when cwd is the
391
+ // repo root) so the comparison is stable for any nesting depth.
392
+ const resolvedCommon = path.resolve(cwd, commonDir)
393
+ const ownGitDir = path.resolve(toplevel, '.git')
394
+ if (resolvedCommon === ownGitDir) return undefined
395
+ return path.dirname(resolvedCommon)
396
+ } catch {
397
+ return undefined
398
+ }
399
+ }
400
+
401
+ /**
402
+ * AIDEV-NOTE: PMR-XTQQ — the runServer.enabled kill-switch contract (plan
403
+ * decision 9): absent/true → durable run server enabled; explicit false →
404
+ * the probe reports absent, ensureDaemon never spawns, and the pending
405
+ * consumer stays off — from extension init (session_start sync) through
406
+ * every /flow start. Pure so the derivation is pinned by tests.
407
+ */
408
+ export function resolveRunServerEnabled(config: PiFlowConfig): boolean {
409
+ return config.runServer?.enabled !== false
410
+ }
411
+
412
+ /**
413
+ * AIDEV-NOTE: PMR-MSDJ (2.1) — typed read of the `reconcile` block with the
414
+ * SAME defaults as `flow/reconcile.ts` parseReconcileSettings (enabled=true,
415
+ * intervalMinutes=360). Keep the two in sync; the defaults are pinned by
416
+ * test/config.test.ts. Malformedness cannot reach here on the extension path
417
+ * (readConfigFile throws first); on the daemon path parseReconcileSettings
418
+ * handles it. Takes Partial so readConfigFile's return type plugs straight in.
419
+ */
420
+ export function resolveReconcileSettings(config: Partial<PiFlowConfig>): {
421
+ enabled: boolean
422
+ intervalMinutes: number
423
+ } {
424
+ const settings = {
425
+ enabled: true,
426
+ intervalMinutes: 360,
427
+ }
428
+ if (config.reconcile?.enabled !== undefined) {
429
+ settings.enabled = config.reconcile.enabled
430
+ }
431
+ if (config.reconcile?.intervalMinutes !== undefined) {
432
+ settings.intervalMinutes = config.reconcile.intervalMinutes
433
+ }
434
+ return settings
435
+ }
436
+
437
+ /**
438
+ * AIDEV-NOTE: PMR-8MQH (4.1) — typed read of the `liveness` block with the
439
+ * SAME defaults as `flow/liveness.ts` DEFAULT_LIVENESS_SETTINGS /
440
+ * parseLivenessSettings (enabled=true, intervalMinutes=5). Keep the two in
441
+ * sync; the equality is pinned by test/config.test.ts. Malformedness cannot
442
+ * reach here on the extension path (readConfigFile throws first); on the
443
+ * daemon path parseLivenessSettings handles it. Takes Partial so
444
+ * readConfigFile's return type plugs straight in.
445
+ */
446
+ export function resolveLivenessSettings(config: Partial<PiFlowConfig>): {
447
+ enabled: boolean
448
+ intervalMinutes: number
449
+ } {
450
+ const settings = {
451
+ enabled: true,
452
+ intervalMinutes: 5,
453
+ }
454
+ if (config.liveness?.enabled !== undefined) {
455
+ settings.enabled = config.liveness.enabled
456
+ }
457
+ if (config.liveness?.intervalMinutes !== undefined) {
458
+ settings.intervalMinutes = config.liveness.intervalMinutes
459
+ }
460
+ return settings
461
+ }
462
+
463
+ /**
464
+ * AIDEV-NOTE: PMR-ZV9Y (4.2) — typed read of the session-side `telemetry.loki`
465
+ * block. SINGLE STRICT READER (no daemon/tolerant half — the daemon never
466
+ * pushes Loki, see the AIDEV-NOTE on the schema block): an invalid shape
467
+ * throws at the readConfigFile boundary before this is ever reached.
468
+ * Defaults: disabled (`enabled` absent/false → resolveLokiSettings.enabled
469
+ * false = ZERO Loki network calls), empty endpoint, empty headers. The
470
+ * `LokiSettings` this returns plugs straight into telemetry/loki.ts
471
+ * pushLokiEvent. Takes Partial so readConfigFile's return type plugs in.
472
+ */
473
+ export function resolveLokiSettings(config: Partial<PiFlowConfig>): {
474
+ enabled: boolean
475
+ endpoint: string
476
+ headers: Record<string, string>
477
+ } {
478
+ const loki = config.telemetry?.loki
479
+ const settings = {
480
+ enabled: false,
481
+ endpoint: '',
482
+ headers: {} as Record<string, string>,
483
+ }
484
+ if (loki?.enabled !== undefined) settings.enabled = loki.enabled
485
+ if (loki?.endpoint !== undefined) settings.endpoint = loki.endpoint
486
+ if (loki?.headers !== undefined) settings.headers = { ...loki.headers }
487
+ return settings
488
+ }
489
+
490
+ /**
491
+ * AIDEV-NOTE: PMR-ZV9Y (5.2) — typed read of the session-side `notify`
492
+ * block. SINGLE STRICT READER, no daemon/tolerant half (the daemon has no
493
+ * notify path — see the AIDEV-NOTE on the schema block): a malformed shape
494
+ * throws at the readConfigFile boundary before this is ever reached.
495
+ * DEFAULT: `desktop.enabled` ABSENT resolves TRUE — the flow-side desktop
496
+ * channel is opt-OUT (the opposite of `telemetry.loki`, which is opt-IN), so a
497
+ * fresh install pages on a waiting_human/halted transition. Takes Partial so
498
+ * readConfigFile's return type plugs straight in; the returned object is
499
+ * freshly built, never aliased to the config.
500
+ */
501
+ export function resolveNotifySettings(config: Partial<PiFlowConfig>): {
502
+ desktop: { enabled: boolean }
503
+ } {
504
+ const settings = { desktop: { enabled: true } }
505
+ const enabled = config.notify?.desktop?.enabled
506
+ if (enabled !== undefined) settings.desktop.enabled = enabled
507
+ return settings
508
+ }
509
+
510
+ /**
511
+ * AIDEV-NOTE: PMR-1QKY — provenance-preserving loadConfig variant: records
512
+ * which config layer (global / main checkout project / project) LAST supplied
513
+ * each merged key, so flow_land can name the winning file in the land-test
514
+ * source label. Merge order and semantics are identical to loadConfig (see
515
+ * the PMR-BF8W note below); the layer strings double as the label fragments
516
+ * shown to the user, so keep them human-readable.
517
+ */
518
+ export type ConfigOrigin = 'global' | 'main checkout project' | 'project'
519
+
520
+ export interface LoadedConfig {
521
+ config: PiFlowConfig
522
+ /** Layer that last supplied each key (Object.assign last-writer-wins). */
523
+ origins: Partial<Record<keyof PiFlowConfig, ConfigOrigin>>
524
+ }
525
+
526
+ /** One Object.assign layer of the loadConfig merge, with provenance. */
527
+ function mergeLayer(
528
+ merged: PiFlowConfig,
529
+ origins: LoadedConfig['origins'],
530
+ origin: ConfigOrigin,
531
+ layer: Partial<PiFlowConfig>,
532
+ ): void {
533
+ Object.assign(merged, layer)
534
+ for (const key of Object.keys(layer) as Array<keyof PiFlowConfig>) {
535
+ origins[key] = origin
536
+ }
537
+ }
538
+
539
+ export async function loadConfigWithOrigins(
540
+ cwd: string,
541
+ ): Promise<LoadedConfig> {
542
+ const globalPath = path.join(getAgentDir(), 'pi-flow', 'config.json')
543
+ const projectPath = path.join(cwd, CONFIG_DIR_NAME, 'pi-flow', 'config.json')
544
+ const mainRoot = await mainCheckoutRoot(cwd)
545
+ let mainPath: string | undefined
546
+ if (mainRoot === undefined) mainPath = undefined
547
+ else mainPath = path.join(mainRoot, CONFIG_DIR_NAME, 'pi-flow', 'config.json')
548
+ const merged: PiFlowConfig = { workRoots: [] }
549
+ const origins: LoadedConfig['origins'] = {}
550
+ mergeLayer(merged, origins, 'global', await readConfigFile(globalPath))
551
+ if (mainPath !== undefined) {
552
+ mergeLayer(
553
+ merged,
554
+ origins,
555
+ 'main checkout project',
556
+ await readConfigFile(mainPath),
557
+ )
558
+ }
559
+ mergeLayer(merged, origins, 'project', await readConfigFile(projectPath))
560
+ return { config: merged, origins }
561
+ }
562
+
563
+ export async function loadConfig(cwd: string): Promise<PiFlowConfig> {
564
+ return (await loadConfigWithOrigins(cwd)).config
565
+ }
566
+
567
+ export async function resolveMode(
568
+ pi: ExtensionAPI,
569
+ cwd?: string,
570
+ ): Promise<WorkMode> {
571
+ const { stdout } = await pi.exec('git', ['rev-parse', '--show-toplevel'], {})
572
+ const toplevel = stdout.trim()
573
+ // AIDEV-NOTE: session cwd, not process.cwd() — see avenOverrideArg note in
574
+ // aven/client.ts.
575
+ const config = await loadConfig(cwd ?? process.cwd())
576
+ return modeForToplevel(toplevel, config.workRoots)
577
+ }
@@ -0,0 +1,21 @@
1
+ // AIDEV-NOTE: Pure /feedback arg parsing — mirrors validate/args.ts exactly
2
+ // (single ref, Jira-style or aven).
3
+
4
+ import { parseRefKind } from '../flow/ref-kind.ts'
5
+
6
+ export type FeedbackArgs =
7
+ | { kind: 'jira'; jiraId: string }
8
+ | { kind: 'aven'; ref: string }
9
+ | { kind: 'help' }
10
+
11
+ export function parseFeedbackArgs(raw: string): FeedbackArgs {
12
+ const trimmed = raw.trim()
13
+ if (trimmed === '') return { kind: 'help' }
14
+ const parts = trimmed.split(/\s+/)
15
+ if (parts.length !== 1) return { kind: 'help' }
16
+ const parsed = parseRefKind(parts[0] ?? '')
17
+ if (parsed.kind === 'jira') {
18
+ return { kind: 'jira', jiraId: parsed.jiraId }
19
+ }
20
+ return { kind: 'aven', ref: parsed.ref }
21
+ }