@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
@@ -0,0 +1,447 @@
1
+ /**
2
+ * Exec wrappers around the Herdr CLI (`herdr worktree` / `herdr agent`).
3
+ *
4
+ * AIDEV-NOTE: herdr JSON shapes are defensive-parse territory (plan risk
5
+ * section). Field-name variants observed on herdr 0.8.2 are documented at
6
+ * each pick site; every field is optional during narrowing so a minor
7
+ * herdr release that renames a field degrades to "" instead of crashing.
8
+ */
9
+
10
+ import path from 'node:path'
11
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
12
+
13
+ export interface HerdrWorktree {
14
+ path: string
15
+ branch: string
16
+ label: string
17
+ workspaceId: string
18
+ isLinked: boolean
19
+ }
20
+
21
+ export interface HerdrAgent {
22
+ name: string
23
+ state: string
24
+ pane: string
25
+ workspaceId?: string
26
+ cwd?: string
27
+ }
28
+
29
+ /** Workspace record from `herdr workspace list` (PMR-DMZR). */
30
+ export interface HerdrWorkspace {
31
+ workspaceId: string
32
+ label: string
33
+ agentStatus: string
34
+ // Worktree provenance — '' when the workspace is not worktree-backed.
35
+ checkoutPath: string
36
+ isLinkedWorktree: boolean
37
+ repoKey: string
38
+ repoName: string
39
+ repoRoot: string
40
+ }
41
+
42
+ /** True when candidate is the root itself or a real descendant of root. */
43
+ // AIDEV-NOTE: PMR-8BG5 — containment is path-segment-aware: sibling prefixes
44
+ // such as `/wt/foo2` do not match `/wt/foo`; trailing separators normalize away.
45
+ export function isPathWithin(candidate: string, root: string): boolean {
46
+ const relative = path.relative(root, candidate)
47
+ if (relative === '') {
48
+ return true
49
+ }
50
+ if (relative === '..' || relative.startsWith(`..${path.sep}`)) {
51
+ return false
52
+ }
53
+ return path.isAbsolute(relative) === false
54
+ }
55
+
56
+ /** JSON.parse with a never-throw contract; returns null on non-JSON. */
57
+ export function parseJson(stdout: string): unknown {
58
+ try {
59
+ return JSON.parse(stdout) as unknown
60
+ } catch {
61
+ return null
62
+ }
63
+ }
64
+
65
+ /**
66
+ * First truthy string among candidate keys (optionally nested one level,
67
+ * e.g. "workspace.id"). NO any — obj stays unknown throughout.
68
+ */
69
+ export function pickString(obj: unknown, keys: string[]): string {
70
+ if (typeof obj !== 'object' || obj === null) {
71
+ return ''
72
+ }
73
+ const record = obj as Record<string, unknown>
74
+ for (const key of keys) {
75
+ let value: unknown = record[key]
76
+ if (key.includes('.')) {
77
+ const [outer, inner] = key.split('.')
78
+ const nested = record[outer]
79
+ if (typeof nested !== 'object' || nested === null) {
80
+ continue
81
+ }
82
+ value = (nested as Record<string, unknown>)[inner]
83
+ }
84
+ if (typeof value === 'string' && value !== '') {
85
+ return value
86
+ }
87
+ }
88
+ return ''
89
+ }
90
+
91
+ function isRecord(value: unknown): value is Record<string, unknown> {
92
+ return typeof value === 'object' && value !== null
93
+ }
94
+
95
+ /**
96
+ * AIDEV-NOTE: is_linked_worktree defaults to TRUE when absent — herdr
97
+ * 0.8.2 always emits it, but if a future herdr drops the field the
98
+ * dashboard should still list worktrees (someone created them via this
99
+ * tool) rather than silently hiding everything. Explicit false (the main
100
+ * checkout row) is the only thing filtered out.
101
+ */
102
+ function pickLinked(entry: unknown): boolean {
103
+ if (isRecord(entry) && entry.is_linked_worktree === false) {
104
+ return false
105
+ }
106
+ return true
107
+ }
108
+
109
+ /** Keep only linked worktrees (drops the main checkout row). */
110
+ export function filterLinked(worktrees: HerdrWorktree[]): HerdrWorktree[] {
111
+ return worktrees.filter((wt) => wt.isLinked)
112
+ }
113
+
114
+ /** Extract the `{result: ...}` envelope; the payload itself when absent. */
115
+ export function extractResult(root: unknown): unknown {
116
+ if (isRecord(root) && isRecord(root.result)) {
117
+ return root.result
118
+ }
119
+ return root
120
+ }
121
+
122
+ /** Extract the payload array from `{result: {<key>: [...]}}`-style output. */
123
+ function pickArray(root: unknown, key: string): unknown[] {
124
+ const result = isRecord(root) ? root.result : null
125
+ if (!isRecord(result)) {
126
+ return []
127
+ }
128
+ const arr = result[key]
129
+ if (!Array.isArray(arr)) {
130
+ return []
131
+ }
132
+ return arr
133
+ }
134
+
135
+ // AIDEV-NOTE: PMR-PMPF — distinguishes "herdr reported zero workspaces"
136
+ // (explicit empty array) from "payload has no workspaces array at all"
137
+ // (envelope renamed upstream). pickArray alone conflates the two into [].
138
+ function hasWorkspacesArray(root: unknown): boolean {
139
+ const result = isRecord(root) ? root.result : null
140
+ if (!isRecord(result)) {
141
+ return false
142
+ }
143
+ return Array.isArray(result.workspaces)
144
+ }
145
+
146
+ /**
147
+ * Preflight: `herdr worktree list` exit 0 proves binary exists, socket
148
+ * reachable, and HERDR_ENV guardrail passes. Failure surfaces stderr
149
+ * verbatim (covers missing binary AND outside-Herdr refusal).
150
+ */
151
+ export async function herdrAvailable(
152
+ pi: ExtensionAPI,
153
+ // PMR-YG2N fix round — undefined = process cwd (loop done path).
154
+ cwd: string | undefined,
155
+ ): Promise<{ ok: true } | { ok: false; error: string }> {
156
+ const result = await pi.exec('herdr', ['worktree', 'list'], { cwd })
157
+ if (result.code === 0) {
158
+ return { ok: true }
159
+ }
160
+ const detail = result.stderr || result.stdout || `exit code ${result.code}`
161
+ return { ok: false, error: `herdr preflight failed: ${detail}` }
162
+ }
163
+
164
+ /** Map a parsed `herdr worktree list` payload onto HerdrWorktree[]. */
165
+ export function parseWorktrees(root: unknown): HerdrWorktree[] {
166
+ // AIDEV-NOTE: herdr 0.8.2 emits {result:{worktrees:[{branch,path,label,
167
+ // open_workspace_id,is_linked_worktree,...}]}}. Variants tolerated:
168
+ // workspace_id, id, and nested workspace.id for the workspace key.
169
+ return pickArray(root, 'worktrees').map((entry) => ({
170
+ path: pickString(entry, ['path', 'worktree_path', 'checkout_path']),
171
+ branch: pickString(entry, ['branch', 'head', 'ref']),
172
+ label: pickString(entry, ['label', 'name']),
173
+ workspaceId: pickString(entry, [
174
+ 'open_workspace_id',
175
+ 'workspace_id',
176
+ 'id',
177
+ 'workspace.id',
178
+ ]),
179
+ isLinked: pickLinked(entry),
180
+ }))
181
+ }
182
+
183
+ async function herdrJson(
184
+ pi: ExtensionAPI,
185
+ cwd: string | undefined,
186
+ args: string[],
187
+ operation: string,
188
+ ): Promise<{ parsed: unknown; stdout: string }> {
189
+ const result = await pi.exec('herdr', args, { cwd })
190
+ if (result.code !== 0) {
191
+ throw new Error(
192
+ `herdr ${operation} failed: ${result.stderr || result.stdout}`,
193
+ )
194
+ }
195
+ const parsed = parseJson(result.stdout)
196
+ if (parsed === null) {
197
+ throw new Error(
198
+ `herdr ${operation} returned non-JSON: ${result.stdout.slice(-200)}`,
199
+ )
200
+ }
201
+ return { parsed, stdout: result.stdout }
202
+ }
203
+
204
+ export async function worktreeList(
205
+ pi: ExtensionAPI,
206
+ // PMR-YG2N fix round — undefined = process cwd (loop done path).
207
+ cwd: string | undefined,
208
+ ): Promise<HerdrWorktree[]> {
209
+ const { parsed } = await herdrJson(
210
+ pi,
211
+ cwd,
212
+ ['worktree', 'list'],
213
+ 'worktree list',
214
+ )
215
+ return parseWorktrees(parsed)
216
+ }
217
+
218
+ /** Parse `herdr worktree create` stdout — pure, fixture-tested. */
219
+ export function parseCreateResult(stdout: string): {
220
+ path: string
221
+ workspaceId: string
222
+ } {
223
+ // AIDEV-NOTE: live shape captured on herdr 0.8.2 (smoke test 4.2):
224
+ // {result:{worktree:{path,branch,open_workspace_id,...},workspace:{...}}}.
225
+ // Flat fallback keys kept for tolerance.
226
+ const payload: unknown = extractResult(parseJson(stdout))
227
+ return {
228
+ path: pickString(payload, [
229
+ 'worktree.path',
230
+ 'path',
231
+ 'worktree_path',
232
+ 'checkout_path',
233
+ ]),
234
+ workspaceId: pickString(payload, [
235
+ 'worktree.open_workspace_id',
236
+ 'workspace_id',
237
+ 'open_workspace_id',
238
+ 'id',
239
+ 'workspace.id',
240
+ ]),
241
+ }
242
+ }
243
+
244
+ // AIDEV-NOTE: PMR-R4AP — always pass --base <sha>: without it herdr branches
245
+ // from the HEAD of --cwd, which is NOT necessarily the main checkout's branch
246
+ // (e.g. session running inside another worktree).
247
+ export function worktreeCreateArgs(
248
+ cwd: string,
249
+ branch: string,
250
+ label: string,
251
+ baseSha?: string,
252
+ ): string[] {
253
+ const args = [
254
+ 'worktree',
255
+ 'create',
256
+ '--cwd',
257
+ cwd,
258
+ '--branch',
259
+ branch,
260
+ '--label',
261
+ label,
262
+ ]
263
+ if (baseSha !== undefined) {
264
+ args.push('--base', baseSha)
265
+ }
266
+ return args
267
+ }
268
+
269
+ export async function worktreeCreate(
270
+ pi: ExtensionAPI,
271
+ cwd: string,
272
+ branch: string,
273
+ label: string,
274
+ baseSha?: string,
275
+ ): Promise<{ path: string; workspaceId: string }> {
276
+ const result = await pi.exec(
277
+ 'herdr',
278
+ worktreeCreateArgs(cwd, branch, label, baseSha),
279
+ {
280
+ cwd,
281
+ },
282
+ )
283
+ if (result.code !== 0) {
284
+ throw new Error(
285
+ `herdr worktree create failed: ${result.stderr || result.stdout}`,
286
+ )
287
+ }
288
+ return parseCreateResult(result.stdout)
289
+ }
290
+
291
+ export async function worktreeRemove(
292
+ pi: ExtensionAPI,
293
+ // PMR-YG2N fix round — undefined = process cwd (loop done path).
294
+ cwd: string | undefined,
295
+ workspaceId: string,
296
+ force: boolean,
297
+ ): Promise<void> {
298
+ const args = ['worktree', 'remove', '--workspace', workspaceId]
299
+ if (force) {
300
+ args.push('--force')
301
+ }
302
+ const result = await pi.exec('herdr', args, { cwd })
303
+ if (result.code !== 0) {
304
+ throw new Error(
305
+ `herdr worktree remove failed: ${result.stderr || result.stdout}`,
306
+ )
307
+ }
308
+ }
309
+
310
+ export async function agentList(
311
+ pi: ExtensionAPI,
312
+ // PMR-YG2N fix round — undefined = process cwd (loop done path).
313
+ cwd: string | undefined,
314
+ ): Promise<HerdrAgent[]> {
315
+ const { parsed } = await herdrJson(pi, cwd, ['agent', 'list'], 'agent list')
316
+ // AIDEV-NOTE: herdr 0.8.2 emits {result:{agents:[{agent,agent_status,
317
+ // pane_id,workspace_id,cwd,...}]}}. Variants tolerated: name, state, pane.
318
+ return pickArray(parsed, 'agents')
319
+ .map((entry) => {
320
+ const workspaceId = pickString(entry, ['workspace_id', 'workspace.id'])
321
+ const cwdField = pickString(entry, ['cwd', 'working_dir'])
322
+ const agent: HerdrAgent = {
323
+ name: pickString(entry, ['agent', 'name']),
324
+ state: pickString(entry, ['agent_status', 'state', 'status']),
325
+ pane: pickString(entry, ['pane_id', 'pane']),
326
+ }
327
+ if (workspaceId !== '') {
328
+ agent.workspaceId = workspaceId
329
+ }
330
+ if (cwdField !== '') {
331
+ agent.cwd = cwdField
332
+ }
333
+ return agent
334
+ })
335
+ .filter((agent) => agent.name !== '')
336
+ }
337
+
338
+ // AIDEV-NOTE (PMR-F5HB; extracted PMR-PB3Z 2.2): the flow session's OWN
339
+ // herdr agent must not self-match in-flight guards — when the session runs
340
+ // INSIDE the worktree being cleaned up, its own agent row carries the
341
+ // worktree cwd and would defer cleanup forever. Identify self by pane id:
342
+ // herdr exposes the current pane via HERDR_PANE_ID ('<workspaceId>:<paneId>')
343
+ // and agentList carries pane_id per agent. Shared by cleanupFlowWorktree,
344
+ // pruneFlow, and the orphan cleanup engine (worktree/orphan.ts) so all three
345
+ // guards exclude self identically. '' = unknown self pane (no exclusion).
346
+ export function ownPaneIdFromEnv(): string {
347
+ const herdrPane = process.env.HERDR_PANE_ID?.trim()
348
+ let ownPaneId = ''
349
+ if (herdrPane?.includes(':') === true) {
350
+ ownPaneId = herdrPane.slice(herdrPane.indexOf(':') + 1)
351
+ }
352
+ return ownPaneId
353
+ }
354
+
355
+ /**
356
+ * AIDEV-NOTE: PMR-DMZR — worktree provenance block nested on worktree-backed
357
+ * workspace records (live shape on herdr 0.8.2: worktree.checkout_path,
358
+ * worktree.is_linked_worktree, worktree.repo_key, worktree.repo_name,
359
+ * worktree.repo_root). Variants tolerated: work_tree for the block key.
360
+ * Returns null for plain-directory workspaces — the prune action's
361
+ * provenance check then fails closed (never closes a dir: workspace).
362
+ */
363
+ function pickWorktreeProvenance(
364
+ entry: unknown,
365
+ ): Record<string, unknown> | null {
366
+ if (!isRecord(entry)) {
367
+ return null
368
+ }
369
+ for (const key of ['worktree', 'work_tree']) {
370
+ const nested = entry[key]
371
+ if (isRecord(nested)) {
372
+ return nested
373
+ }
374
+ }
375
+ return null
376
+ }
377
+
378
+ /** Map a parsed `herdr workspace list` payload onto HerdrWorkspace[]. */
379
+ export function parseWorkspaces(root: unknown): HerdrWorkspace[] {
380
+ // AIDEV-NOTE: PMR-DMZR — herdr 0.8.2 emits {result:{type:'workspace_list',
381
+ // workspaces:[{workspace_id,label,agent_status,...,worktree?:{...}}]}}.
382
+ // Variants tolerated: id / workspace.id for the workspace key, name for
383
+ // the label, status/state for the agent status. Without a provenance
384
+ // block, checkoutPath stays '' and isLinkedWorktree stays false.
385
+ return pickArray(root, 'workspaces').map((entry) => {
386
+ const workspace: HerdrWorkspace = {
387
+ workspaceId: pickString(entry, ['workspace_id', 'id', 'workspace.id']),
388
+ label: pickString(entry, ['label', 'name']),
389
+ agentStatus: pickString(entry, ['agent_status', 'status', 'state']),
390
+ checkoutPath: '',
391
+ isLinkedWorktree: false,
392
+ repoKey: '',
393
+ repoName: '',
394
+ repoRoot: '',
395
+ }
396
+ const provenance = pickWorktreeProvenance(entry)
397
+ if (provenance !== null) {
398
+ workspace.checkoutPath = pickString(provenance, ['checkout_path', 'path'])
399
+ workspace.isLinkedWorktree = pickLinked(provenance)
400
+ workspace.repoKey = pickString(provenance, ['repo_key', 'key'])
401
+ workspace.repoName = pickString(provenance, ['repo_name', 'name'])
402
+ workspace.repoRoot = pickString(provenance, ['repo_root', 'root'])
403
+ }
404
+ return workspace
405
+ })
406
+ }
407
+
408
+ export async function workspaceList(
409
+ pi: ExtensionAPI,
410
+ // PMR-YG2N fix round — undefined = process cwd (loop done path).
411
+ cwd: string | undefined,
412
+ ): Promise<HerdrWorkspace[]> {
413
+ const { parsed, stdout } = await herdrJson(
414
+ pi,
415
+ cwd,
416
+ ['workspace', 'list'],
417
+ 'workspace list',
418
+ )
419
+ const workspaces = parseWorkspaces(parsed)
420
+ // AIDEV-NOTE: PMR-PMPF — zero parsed workspaces is only acceptable when
421
+ // the payload carries a recognizable workspaces array (an explicit empty
422
+ // list). If a future herdr renames the result.workspaces envelope, parsing
423
+ // would silently yield [] and prune would report a clean 0-closed/0-skipped
424
+ // no-op, resurrecting the PMR-DMZR silent-dangling bug. Fail loudly.
425
+ if (workspaces.length === 0 && !hasWorkspacesArray(parsed)) {
426
+ throw new Error(
427
+ `herdr workspace list payload has no recognizable workspaces array — refusing to treat it as zero workspaces: ${stdout.slice(-200)}`,
428
+ )
429
+ }
430
+ return workspaces
431
+ }
432
+
433
+ export async function workspaceClose(
434
+ pi: ExtensionAPI,
435
+ // PMR-YG2N fix round — undefined = process cwd (loop done path).
436
+ cwd: string | undefined,
437
+ workspaceId: string,
438
+ ): Promise<void> {
439
+ const result = await pi.exec('herdr', ['workspace', 'close', workspaceId], {
440
+ cwd,
441
+ })
442
+ if (result.code !== 0) {
443
+ throw new Error(
444
+ `herdr workspace close ${workspaceId} failed: ${result.stderr || result.stdout}`,
445
+ )
446
+ }
447
+ }