@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/herdr/sync.ts ADDED
@@ -0,0 +1,355 @@
1
+ // AIDEV-NOTE: Explicit herdr plugin sync (simplified from pi-workflows'
2
+ // src/herdr/setup.ts). `herdr plugin link <repo root>` is run ONLY by the
3
+ // /herdr-sync command — never during session start. Preflight validates the
4
+ // manifest against the package version before touching herdr, and the result
5
+ // is re-verified by listing after the mutation. Herdr absent = graceful skip.
6
+ import { type SpawnSyncReturns, spawnSync } from 'node:child_process'
7
+ import { promises as fs } from 'node:fs'
8
+ import path from 'node:path'
9
+ import { fileURLToPath } from 'node:url'
10
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
11
+ import { escapeRegExp } from '../spec-review/escape-regexp.ts'
12
+
13
+ export const HERDR_PLUGIN_ID = 'gtheys.pi-my-rifle-ext'
14
+
15
+ const MANIFEST_NAME = 'herdr-plugin.toml'
16
+ const VIEWER_PATH = 'plugins/herdr/flow-viewer.mjs'
17
+ const RESULT_SCHEMA = 'gtheys.pi-my-rifle-ext.herdr-sync.v1'
18
+ const MAX_COMMAND_OUTPUT_BYTES = 1024 * 1024
19
+
20
+ // AIDEV-NOTE: Keep in sync with HERDR_MIN_VERSION in
21
+ // packages/pi-interactive-subagents/pi-extension/subagents/herdr.ts — no
22
+ // cross-package runtime dependency by AGENTS.md convention; bump both together.
23
+ export const EXPECTED_MIN_HERDR_VERSION = '0.9.1'
24
+
25
+ // AIDEV-NOTE: Single source for the /herdr-sync handler's repo root since
26
+ // PMR-SWBX — keep this derivation authoritative over any inline copies.
27
+ // sync.ts lives one level deeper (herdr/) than index.ts, so this climbs one
28
+ // more '..' to reach the same repo root.
29
+ export function resolveRepoRoot(): string {
30
+ return path.resolve(
31
+ path.dirname(fileURLToPath(import.meta.url)),
32
+ '..',
33
+ '..',
34
+ '..',
35
+ )
36
+ }
37
+
38
+ // AIDEV-NOTE: PMR-YG2N fix round — deliberate contrast with resolveRepoRoot()
39
+ // above. resolveRepoRoot() resolves from import.meta.url: the EXTENSION
40
+ // INSTALL root, session-independent — correct for version/preflight callers
41
+ // only. resolveSessionRepoRoot() runs `git rev-parse --show-toplevel` from
42
+ // the session's cwd (process cwd when omitted), mirroring commandPhaseInput's
43
+ // journal gitRoot semantics. Never throws: null on failure/empty output, so
44
+ // callers can fail closed.
45
+ export async function resolveSessionRepoRoot(
46
+ pi: ExtensionAPI,
47
+ cwd?: string,
48
+ ): Promise<string | null> {
49
+ const options: { cwd?: string } = {}
50
+ if (cwd !== undefined) {
51
+ options.cwd = cwd
52
+ }
53
+ try {
54
+ const result = await pi.exec(
55
+ 'git',
56
+ ['rev-parse', '--show-toplevel'],
57
+ options,
58
+ )
59
+ const root = result.stdout.trim()
60
+ if (root === '') {
61
+ return null
62
+ }
63
+ return root
64
+ } catch {
65
+ return null
66
+ }
67
+ }
68
+
69
+ export type HerdrSyncStatus =
70
+ | 'linked'
71
+ | 'relinked'
72
+ | 'enabled'
73
+ | 'unchanged'
74
+ | 'unavailable'
75
+
76
+ export type HerdrSyncResult = {
77
+ schema: typeof RESULT_SCHEMA
78
+ status: HerdrSyncStatus
79
+ changed: boolean
80
+ pluginId: string
81
+ expectedVersion: string
82
+ effectiveVersion: string | null
83
+ enabled: boolean | null
84
+ runningPiProcessesNeedReload: true
85
+ message: string
86
+ }
87
+
88
+ type Spawn = (
89
+ command: string,
90
+ args: readonly string[],
91
+ ) => SpawnSyncReturns<string>
92
+
93
+ type InstalledPlugin = {
94
+ root: string
95
+ version: string
96
+ enabled: boolean
97
+ }
98
+
99
+ /** Minimal TOML string reader for the keys preflight checks (port of pi-workflows). */
100
+ export function tomlString(text: string, key: string): string | undefined {
101
+ const match = new RegExp(
102
+ String.raw`^\s*${escapeRegExp(key)}\s*=\s*"((?:[^"\\]|\\.)*)"\s*(?:#.*)?$`,
103
+ 'mu',
104
+ ).exec(text)
105
+ return match?.[1]
106
+ }
107
+
108
+ /** Validate the manifest + launcher against the repo root. Throws on any mismatch. */
109
+ export async function preflightRepo(
110
+ repoRoot: string,
111
+ ): Promise<{ root: string; version: string }> {
112
+ const root = path.resolve(repoRoot)
113
+ const packageJson: unknown = JSON.parse(
114
+ await fs.readFile(path.join(root, 'package.json'), 'utf8'),
115
+ )
116
+ const version = (packageJson as { version?: unknown }).version
117
+ if (typeof version !== 'string' || version.length === 0) {
118
+ throw new Error(`package.json at ${root} has no version.`)
119
+ }
120
+ const manifest = await fs.readFile(path.join(root, MANIFEST_NAME), 'utf8')
121
+ const id = tomlString(manifest, 'id')
122
+ if (id !== HERDR_PLUGIN_ID) {
123
+ throw new Error(`${MANIFEST_NAME} id must be ${HERDR_PLUGIN_ID}.`)
124
+ }
125
+ const manifestVersion = tomlString(manifest, 'version')
126
+ if (manifestVersion !== version) {
127
+ throw new Error(
128
+ `${MANIFEST_NAME} version ${manifestVersion ?? '(missing)'} does not match package version ${version}. Bump both together.`,
129
+ )
130
+ }
131
+ const platformsRaw =
132
+ /platforms\s*=\s*\[([^\]]*)\]/mu.exec(manifest)?.[1] ?? ''
133
+ const platform = process.platform === 'darwin' ? 'macos' : process.platform
134
+ if (!platformsRaw.includes(`"${platform}"`)) {
135
+ throw new Error(`${MANIFEST_NAME} does not support platform ${platform}.`)
136
+ }
137
+ const command = /command\s*=\s*\[([^\]]*)\]/mu.exec(manifest)?.[1] ?? ''
138
+ if (!command.includes('"node"') || !command.includes(`"${VIEWER_PATH}"`)) {
139
+ throw new Error(
140
+ `${MANIFEST_NAME} command must be ["node", "${VIEWER_PATH}"].`,
141
+ )
142
+ }
143
+ const minHerdrVersion = tomlString(manifest, 'min_herdr_version')
144
+ if (minHerdrVersion !== EXPECTED_MIN_HERDR_VERSION) {
145
+ throw new Error(
146
+ `${MANIFEST_NAME} min_herdr_version "${minHerdrVersion ?? '(missing)'}" != expected "${EXPECTED_MIN_HERDR_VERSION}" (HERDR_MIN_VERSION gate in pi-interactive-subagents) — bump both together.`,
147
+ )
148
+ }
149
+ let viewerStat: import('node:fs').Stats
150
+ try {
151
+ viewerStat = await fs.stat(path.join(root, VIEWER_PATH))
152
+ } catch {
153
+ throw new Error(`${VIEWER_PATH} is missing from the repo root.`)
154
+ }
155
+ if (!viewerStat.isFile()) {
156
+ throw new Error(`${VIEWER_PATH} is missing from the repo root.`)
157
+ }
158
+ return { root, version }
159
+ }
160
+
161
+ export function parseInstalledPlugin(
162
+ stdout: string,
163
+ ): InstalledPlugin | undefined {
164
+ let value: unknown
165
+ try {
166
+ value = JSON.parse(stdout)
167
+ } catch {
168
+ throw new Error('Herdr returned invalid plugin JSON.')
169
+ }
170
+ const result = (value as Record<string, unknown>).result
171
+ if (!isRecord(result) || !Array.isArray(result.plugins)) {
172
+ throw new Error('Herdr returned an invalid plugin list.')
173
+ }
174
+ const candidates = result.plugins.filter(
175
+ (plugin) => isRecord(plugin) && plugin.plugin_id === HERDR_PLUGIN_ID,
176
+ )
177
+ const candidate = candidates[0]
178
+ if (candidate === undefined) return undefined
179
+ if (
180
+ !isRecord(candidate) ||
181
+ typeof candidate.plugin_root !== 'string' ||
182
+ typeof candidate.version !== 'string' ||
183
+ typeof candidate.enabled !== 'boolean'
184
+ ) {
185
+ throw new Error(
186
+ `Herdr returned an incomplete record for ${HERDR_PLUGIN_ID}.`,
187
+ )
188
+ }
189
+ return {
190
+ root: candidate.plugin_root,
191
+ version: candidate.version,
192
+ enabled: candidate.enabled,
193
+ }
194
+ }
195
+
196
+ function matchesExpected(
197
+ installed: InstalledPlugin,
198
+ expected: { root: string; version: string },
199
+ requireEnabled: boolean,
200
+ ): boolean {
201
+ return (
202
+ path.resolve(installed.root) === path.resolve(expected.root) &&
203
+ installed.version === expected.version &&
204
+ (!requireEnabled || installed.enabled)
205
+ )
206
+ }
207
+
208
+ export async function syncHerdrPlugin(
209
+ repoRoot: string,
210
+ spawn: Spawn = runCommand,
211
+ ): Promise<HerdrSyncResult> {
212
+ const expected = await preflightRepo(repoRoot)
213
+ const initial = inspectHerdr(spawn, true)
214
+ if (initial.available !== true) {
215
+ return result('unavailable', false, expected.version, undefined)
216
+ }
217
+
218
+ const installed = initial.plugin
219
+ if (installed === undefined) {
220
+ await mutateOrThrow(spawn, 'link', [expected.root])
221
+ const adopted = inspectHerdr(spawn, false)
222
+ if (
223
+ adopted.available === true &&
224
+ adopted.plugin !== undefined &&
225
+ matchesExpected(adopted.plugin, expected, true)
226
+ ) {
227
+ return result('linked', true, expected.version, adopted.plugin)
228
+ }
229
+ throw new Error('Could not link the Herdr plugin — verification failed.')
230
+ }
231
+
232
+ if (matchesExpected(installed, expected, true)) {
233
+ return result('unchanged', false, expected.version, installed)
234
+ }
235
+
236
+ if (matchesExpected(installed, expected, false) && !installed.enabled) {
237
+ await mutateOrThrow(spawn, 'enable', [HERDR_PLUGIN_ID])
238
+ const adopted = inspectHerdr(spawn, false)
239
+ if (
240
+ adopted.available === true &&
241
+ adopted.plugin !== undefined &&
242
+ matchesExpected(adopted.plugin, expected, true)
243
+ ) {
244
+ return result('enabled', true, expected.version, adopted.plugin)
245
+ }
246
+ throw new Error('Could not enable the Herdr plugin — verification failed.')
247
+ }
248
+
249
+ await mutateOrThrow(spawn, 'unlink', [HERDR_PLUGIN_ID])
250
+ await mutateOrThrow(spawn, 'link', [expected.root])
251
+ const adopted = inspectHerdr(spawn, false)
252
+ if (
253
+ adopted.available === true &&
254
+ adopted.plugin !== undefined &&
255
+ matchesExpected(adopted.plugin, expected, true)
256
+ ) {
257
+ return result('relinked', true, expected.version, adopted.plugin)
258
+ }
259
+ throw new Error('Could not relink the Herdr plugin — verification failed.')
260
+ }
261
+
262
+ type Inspection =
263
+ | { available: true; plugin: InstalledPlugin | undefined }
264
+ | { available: false }
265
+
266
+ function inspectHerdr(spawn: Spawn, allowUnavailable: boolean): Inspection {
267
+ const listed = spawn('herdr', [
268
+ 'plugin',
269
+ 'list',
270
+ '--plugin',
271
+ HERDR_PLUGIN_ID,
272
+ '--json',
273
+ ])
274
+ if (listed.error !== undefined && listed.error !== null) {
275
+ if (
276
+ allowUnavailable &&
277
+ (listed.error as NodeJS.ErrnoException).code === 'ENOENT'
278
+ ) {
279
+ return { available: false }
280
+ }
281
+ throw new Error(`Could not run herdr: ${listed.error.message}`)
282
+ }
283
+ if (listed.status !== 0) {
284
+ throw new Error(
285
+ `Could not inspect Herdr plugins: ${bounded(listed.stderr || listed.stdout)}`,
286
+ )
287
+ }
288
+ return { available: true, plugin: parseInstalledPlugin(listed.stdout) }
289
+ }
290
+
291
+ async function mutateOrThrow(
292
+ spawn: Spawn,
293
+ action: 'link' | 'unlink' | 'enable',
294
+ args: readonly string[],
295
+ ): Promise<void> {
296
+ const changed = spawn('herdr', ['plugin', action, ...args])
297
+ if (changed.error !== undefined && changed.error !== null) {
298
+ throw new Error(`herdr plugin ${action} failed: ${changed.error.message}`)
299
+ }
300
+ if (changed.status !== 0) {
301
+ throw new Error(
302
+ `herdr plugin ${action} failed: ${bounded(changed.stderr || changed.stdout)}`,
303
+ )
304
+ }
305
+ }
306
+
307
+ function result(
308
+ status: HerdrSyncStatus,
309
+ changed: boolean,
310
+ expectedVersion: string,
311
+ effective: InstalledPlugin | undefined,
312
+ ): HerdrSyncResult {
313
+ const messages: Record<HerdrSyncStatus, string> = {
314
+ linked: `Linked Herdr plugin ${HERDR_PLUGIN_ID}.`,
315
+ relinked: `Repaired Herdr plugin ${HERDR_PLUGIN_ID}.`,
316
+ enabled: `Enabled Herdr plugin ${HERDR_PLUGIN_ID}.`,
317
+ unchanged: `Herdr plugin ${HERDR_PLUGIN_ID} is current.`,
318
+ unavailable: 'Herdr is not installed; plugin synchronization was skipped.',
319
+ }
320
+ return {
321
+ schema: RESULT_SCHEMA,
322
+ status,
323
+ changed,
324
+ pluginId: HERDR_PLUGIN_ID,
325
+ expectedVersion,
326
+ effectiveVersion: effective?.version ?? null,
327
+ enabled: effective?.enabled ?? null,
328
+ runningPiProcessesNeedReload: true,
329
+ message: messages[status],
330
+ }
331
+ }
332
+
333
+ function runCommand(
334
+ command: string,
335
+ args: readonly string[],
336
+ ): SpawnSyncReturns<string> {
337
+ return spawnSync(command, [...args], {
338
+ encoding: 'utf8',
339
+ stdio: ['ignore', 'pipe', 'pipe'],
340
+ maxBuffer: MAX_COMMAND_OUTPUT_BYTES,
341
+ shell: false,
342
+ })
343
+ }
344
+
345
+ function bounded(value: string): string {
346
+ const compact = value
347
+ .replace(/[\r\n\t]+/gu, ' ')
348
+ .replace(/ +/gu, ' ')
349
+ .trim()
350
+ return compact.length <= 300 ? compact : `${compact.slice(0, 299)}…`
351
+ }
352
+
353
+ function isRecord(value: unknown): value is Record<string, unknown> {
354
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
355
+ }