@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,166 @@
1
+ // AIDEV-NOTE: PMR-XCA9 — single surviving copy. pi-planning's twin
2
+ // (plan-tools/open-in-pane.ts, source of truth until the absorption) was
3
+ // retired with the package; registerOpenInPane moved here with it.
4
+
5
+ import { existsSync } from 'node:fs'
6
+ import { dirname, resolve } from 'node:path'
7
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
8
+ import { Type } from 'typebox'
9
+
10
+ type OpenInPaneResult = {
11
+ content: Array<{ type: 'text'; text: string }>
12
+ details: { ok: boolean; paneId?: string }
13
+ }
14
+
15
+ type WaitOptions = { attempts?: number; delayMs?: number }
16
+
17
+ // AIDEV-NOTE: PMR-R0JD — a plan write can race the open_in_pane call, so
18
+ // poll briefly (default 5 x 200ms) before reporting the file missing.
19
+ async function waitForFile(
20
+ file: string,
21
+ { attempts = 5, delayMs = 200 }: WaitOptions,
22
+ ): Promise<boolean> {
23
+ for (let i = 0; i < attempts; i++) {
24
+ if (existsSync(file)) return true
25
+ await new Promise((r) => setTimeout(r, delayMs))
26
+ }
27
+ return existsSync(file)
28
+ }
29
+
30
+ export async function openFileInPane(
31
+ pi: ExtensionAPI,
32
+ file: string,
33
+ command = 'nvim',
34
+ wait: WaitOptions = {},
35
+ ): Promise<OpenInPaneResult> {
36
+ const absFile = resolve(file)
37
+ // AIDEV-NOTE: shell-quote for herdr pane send-text — the pane's shell
38
+ // parses the text, so single quotes in the path must be escaped
39
+ // (same one-liner as shellEscape in pi-interactive-subagents surface.ts;
40
+ // duplicate on purpose — no cross-package imports).
41
+ const quotedFile = absFile.replace(/'/g, "'\\''")
42
+
43
+ if (!(await waitForFile(absFile, wait))) {
44
+ return {
45
+ content: [{ type: 'text', text: `File not found: ${absFile}` }],
46
+ details: { ok: false },
47
+ }
48
+ }
49
+
50
+ // AIDEV-NOTE: herdr CLI called directly — deliberate: no cross-package
51
+ // dependency on pi-interactive-subagents for 4 exec calls (plan 2026-09-07-open-spec-file-with-glow).
52
+ // AIDEV-NOTE: subagent panes live in ephemeral tabs that
53
+ // pi-interactive-subagents closes (pane + tab) when the subagent exits, so
54
+ // a review pane split from the calling pane dies with that tab. When the
55
+ // subagent spawn env (PI_SUBAGENT_ID) is present, open a dedicated durable
56
+ // tab instead — it outlives the subagent cleanup. Workspace id comes from
57
+ // the inherited herdr env; without it fall back to the legacy split path.
58
+ const workspaceId = process.env.HERDR_WORKSPACE_ID
59
+ const inSubagent =
60
+ process.env.PI_SUBAGENT_ID !== undefined && workspaceId !== undefined
61
+
62
+ try {
63
+ let paneId: string
64
+ if (inSubagent) {
65
+ const created = await pi.exec(
66
+ 'herdr',
67
+ [
68
+ 'tab',
69
+ 'create',
70
+ '--workspace',
71
+ workspaceId,
72
+ '--cwd',
73
+ dirname(absFile),
74
+ '--label',
75
+ 'spec-review',
76
+ '--no-focus',
77
+ ],
78
+ {},
79
+ )
80
+ const parsed: unknown = JSON.parse(created.stdout)
81
+ const result = parsed as {
82
+ result?: { root_pane?: { pane_id?: unknown } }
83
+ }
84
+ const rootPaneId = result.result?.root_pane?.pane_id
85
+ if (typeof rootPaneId !== 'string') {
86
+ throw new Error(
87
+ 'herdr tab create: missing root_pane.pane_id in response',
88
+ )
89
+ }
90
+ paneId = rootPaneId
91
+ } else {
92
+ const split = await pi.exec(
93
+ 'herdr',
94
+ [
95
+ 'pane',
96
+ 'split',
97
+ '--direction',
98
+ 'right',
99
+ '--no-focus',
100
+ '--cwd',
101
+ dirname(absFile),
102
+ '--current',
103
+ ],
104
+ {},
105
+ )
106
+ const parsed: unknown = JSON.parse(split.stdout)
107
+ const result = parsed as {
108
+ result?: { pane?: { pane_id?: unknown } }
109
+ }
110
+ const splitPaneId = result.result?.pane?.pane_id
111
+ if (typeof splitPaneId !== 'string') {
112
+ throw new Error('herdr pane split: missing pane_id in response')
113
+ }
114
+ paneId = splitPaneId
115
+
116
+ try {
117
+ await pi.exec('herdr', ['pane', 'rename', paneId, 'spec-review'], {})
118
+ } catch {
119
+ // cosmetic, non-fatal
120
+ }
121
+ }
122
+
123
+ await pi.exec(
124
+ 'herdr',
125
+ ['pane', 'send-text', paneId, `${command} '${quotedFile}'`],
126
+ {},
127
+ )
128
+ await pi.exec('herdr', ['pane', 'send-keys', paneId, 'return'], {})
129
+
130
+ return {
131
+ content: [{ type: 'text', text: `Opened ${absFile} in pane ${paneId}` }],
132
+ details: { ok: true, paneId },
133
+ }
134
+ } catch {
135
+ return {
136
+ content: [
137
+ {
138
+ type: 'text',
139
+ text: `${absFile}\nherdr unavailable — open manually: nvim ${quotedFile}`,
140
+ },
141
+ ],
142
+ details: { ok: false },
143
+ }
144
+ }
145
+ }
146
+
147
+ // AIDEV-NOTE: PMR-XCA9 — tool registration moved from pi-planning's
148
+ // plan-tools/open-in-pane.ts; registerOpenInPane is a thin wrapper.
149
+ export function registerOpenInPane(pi: ExtensionAPI) {
150
+ pi.registerTool({
151
+ name: 'open_in_pane',
152
+ label: 'Open File in Pane',
153
+ description:
154
+ 'Open a file with nvim in a herdr review pane (from a subagent: a durable spec-review tab that survives subagent cleanup). Non-fatal: returns the path and a manual-open note if herdr is unavailable.',
155
+ promptSnippet: 'Open a spec/plan file with nvim in a herdr review pane',
156
+ parameters: Type.Object({
157
+ file: Type.String({ description: 'Absolute path to the file to open' }),
158
+ command: Type.Optional(
159
+ Type.String({ description: 'Command to run (default: nvim)' }),
160
+ ),
161
+ }),
162
+ async execute(_id, params) {
163
+ return openFileInPane(pi, params.file, params.command ?? 'nvim')
164
+ },
165
+ })
166
+ }
@@ -0,0 +1,74 @@
1
+ // AIDEV-NOTE: pure picker-loop logic for /spec-review (PMR-MR36) — no ctx,
2
+ // no pi, side effects only through the injected callbacks (select,
3
+ // resolvePlanPath, onPicked, onSkipped). ctx.ui.select is modal and blocks
4
+ // the handler, so the loop collects a BATCH: each pick resolves the plan
5
+ // path (missing -> skipped with a notice) and re-presents the remaining
6
+ // entries plus Done; the caller sends one combined review prompt after Done
7
+ // so review prompts never interleave. A cancel (undefined selection)
8
+ // behaves like Done. onPicked may be async (the caller opens the file in a
9
+ // pane, which awaits) and the loop awaits it before the next select; onSkipped
10
+ // stays synchronous. When the last spec is picked the loop ends without
11
+ // requiring a final Done.
12
+
13
+ import type { SpecInReview } from './aven-spec.ts'
14
+
15
+ export interface PickedSpec {
16
+ ref: string
17
+ title: string
18
+ planPath: string
19
+ }
20
+
21
+ export type PlanPathProbe =
22
+ | { ok: true; planPath: string }
23
+ | { ok: false; reason: string }
24
+
25
+ export type PickerOutcome =
26
+ | { kind: 'done'; picked: PickedSpec[] }
27
+ | { kind: 'error'; reason: string }
28
+
29
+ export function pickerOptions(specs: SpecInReview[]): string[] {
30
+ return [...specs.map((s) => `${s.ref} ${s.title}`), 'Done']
31
+ }
32
+
33
+ export async function pickSpecs(opts: {
34
+ specs: SpecInReview[]
35
+ select: (title: string, options: string[]) => Promise<string | undefined>
36
+ resolvePlanPath: (ref: string) => Promise<PlanPathProbe>
37
+ onPicked?: (spec: PickedSpec) => void | Promise<void>
38
+ onSkipped?: (spec: SpecInReview, reason: string) => void
39
+ }): Promise<PickerOutcome> {
40
+ const remaining = [...opts.specs]
41
+ const picked: PickedSpec[] = []
42
+ while (remaining.length > 0) {
43
+ let choice: string | undefined
44
+ try {
45
+ choice = await opts.select(
46
+ 'Specs awaiting review:',
47
+ pickerOptions(remaining),
48
+ )
49
+ } catch (error) {
50
+ const msg = error instanceof Error ? error.message : String(error)
51
+ return { kind: 'error', reason: `picker failed: ${msg}` }
52
+ }
53
+ if (choice === undefined || choice === 'Done') {
54
+ return { kind: 'done', picked }
55
+ }
56
+ const index = remaining.findIndex((s) => `${s.ref} ${s.title}` === choice)
57
+ if (index === -1) continue
58
+ const [spec] = remaining.splice(index, 1)
59
+ if (spec === undefined) continue
60
+ const probe = await opts.resolvePlanPath(spec.ref)
61
+ if (!probe.ok) {
62
+ opts.onSkipped?.(spec, probe.reason)
63
+ continue
64
+ }
65
+ const entry: PickedSpec = {
66
+ ref: spec.ref,
67
+ title: spec.title,
68
+ planPath: probe.planPath,
69
+ }
70
+ picked.push(entry)
71
+ await opts.onPicked?.(entry)
72
+ }
73
+ return { kind: 'done', picked }
74
+ }
@@ -0,0 +1,72 @@
1
+ // AIDEV-NOTE: review-prompt builder for /spec-review (PMR-MR36). Pure
2
+ // module. The injected message makes the SESSION the reviewer: it loads the
3
+ // feature-plan-aven review-stage behavior, reads each plan.md fully, fixes
4
+ // the spec in place in one go.
5
+ // AIDEV-NOTE: PMR-DMHH 4.4 — approval is receipt-gated in pi-flow context:
6
+ // the human records it with "/flow answer <REF> approve" (human-only);
7
+ // the receipt is the approval signal and recording it wakes this session
8
+ // automatically. When the receipt exists — after the wake, or when the
9
+ // user says "approve <REF>" — the agent calls the spec_approve tool
10
+ // (workspace-pinned approveSpec, loud failure) and then /spec-publish.
11
+ // A spoken word without a receipt only means "go check": spec_approve
12
+ // refuses fail-closed without it. Never run raw aven edits for approval.
13
+
14
+ import type { PickedSpec } from './picker.ts'
15
+
16
+ export function buildReviewPrompt(picked: PickedSpec[]): string {
17
+ const lines: string[] = []
18
+ lines.push(
19
+ 'You are the spec reviewer for the following specs awaiting review.',
20
+ )
21
+ lines.push('')
22
+ lines.push(
23
+ 'First, read the review-stage behavior of the feature-plan-aven skill:',
24
+ )
25
+ lines.push('skills/engineering/feature-plan-aven/SKILL.md')
26
+ lines.push('')
27
+ lines.push('Specs to review:')
28
+ for (const spec of picked) {
29
+ lines.push(`- ${spec.ref} — ${spec.title} (plan: ${spec.planPath})`)
30
+ }
31
+ lines.push('')
32
+ lines.push('For each spec above:')
33
+ lines.push(`1. Read its plan.md fully.`)
34
+ lines.push(
35
+ '2. Follow the feature-plan-aven review-stage behavior: verify the spec',
36
+ )
37
+ lines.push(
38
+ ' against the codebase, and fix issues in the spec IN PLACE, all in',
39
+ )
40
+ lines.push(' one go. Do not wait for per-spec approval.')
41
+ lines.push('3. Report what you checked and what you changed.')
42
+ lines.push('')
43
+ lines.push('Approval is receipt-gated in pi-flow context:')
44
+ lines.push(`- The human records approval with "/flow answer <REF> approve"`)
45
+ lines.push(
46
+ ' (human-only; writes the durable approval receipt). The receipt is the',
47
+ )
48
+ lines.push(' approval signal — no spoken "approve" is required or expected.')
49
+ lines.push(
50
+ '- Recording the answer wakes this session automatically; when you are',
51
+ )
52
+ lines.push(' woken, call the spec_approve tool with that ref. A spoken')
53
+ lines.push(
54
+ ` "approve <REF>" (for example "approve ${picked[0]?.ref ?? '<REF>'}")`,
55
+ )
56
+ lines.push(' without a receipt only means "go check": call spec_approve')
57
+ lines.push(
58
+ ' anyway — it refuses fail-closed without the receipt; on refusal tell',
59
+ )
60
+ lines.push(
61
+ ' the human to record the answer with "/flow answer <REF> approve".',
62
+ )
63
+ lines.push(`- Never run the aven edit command yourself — spec_approve owns`)
64
+ lines.push(` the workspace pin and fails loud on error.`)
65
+ lines.push(
66
+ `- After spec_approve returns ok, call the spec_publish tool with that ref.`,
67
+ )
68
+ lines.push(
69
+ '- NEVER approve more than the ref the receipt (or the user) named.',
70
+ )
71
+ return lines.join('\n')
72
+ }
@@ -0,0 +1,33 @@
1
+ // AIDEV-NOTE: argument parser for /spec-publish (PMR-MR36 subtask PMR-2D2X).
2
+ // Pure module — tested without ctx. Exactly one aven ref is required;
3
+ // `--workspace <name>` (any position) is the cross-workspace escape hatch.
4
+
5
+ export type SpecPublishArgs =
6
+ | { kind: 'help' }
7
+ | { kind: 'ok'; ref: string; workspace?: string }
8
+
9
+ export function parseSpecPublishArgs(args: string): SpecPublishArgs {
10
+ const parts = args
11
+ .trim()
12
+ .split(/\s+/)
13
+ .filter((p) => p !== '')
14
+ let workspace: string | undefined
15
+ const rest: string[] = []
16
+ let i = 0
17
+ while (i < parts.length) {
18
+ const part = parts[i] as string
19
+ if (part === '--workspace') {
20
+ const value = parts[i + 1]
21
+ if (value === undefined || value === '--workspace')
22
+ return { kind: 'help' }
23
+ workspace = value
24
+ i += 2
25
+ continue
26
+ }
27
+ rest.push(part)
28
+ i += 1
29
+ }
30
+ if (rest.length !== 1) return { kind: 'help' }
31
+ if (workspace === undefined) return { kind: 'ok', ref: rest[0] as string }
32
+ return { kind: 'ok', ref: rest[0] as string, workspace }
33
+ }
@@ -0,0 +1,210 @@
1
+ // AIDEV-NOTE: publish half of /spec-publish (PMR-MR36 subtask PMR-2D2X).
2
+ // Three pure-ish parts: per-mode root resolution, the worker task text, and
3
+ // the launchSubagent wrapper. planPath comes from the caller (readPlanPath in
4
+ // index.ts) — publish.ts never queries aven itself. Both notes repos carry
5
+ // unrelated dirty state, so the worker must add the plan file ONLY.
6
+ import type { ExtensionContext } from '@earendil-works/pi-coding-agent'
7
+ import { launchSubagent, watchSubagent } from '@gtheys/pi-interactive-subagents'
8
+
9
+ export interface PublishRootInput {
10
+ repo: string
11
+ planPath: string
12
+ // Project git toplevel — only needed for the env-unset fallback.
13
+ toplevel?: string
14
+ env?: NodeJS.ProcessEnv
15
+ }
16
+
17
+ export type PublishRootResult =
18
+ | { kind: 'ok'; root: string; planFile: string; isFallback: boolean }
19
+ | { kind: 'error'; reason: string }
20
+
21
+ // AIDEV-NOTE: PMR-7FEP — the root derives from the planPath prefix, not the
22
+ // repo toplevel mode: local (non-Jira) plans live under PERSONAL_FEATURES or
23
+ // LLM_NOTES_ROOT in ANY mode, so matching on mode git-adds files outside the
24
+ // chosen root. Match on the <root>/<repo>/ boundary (sibling repos with
25
+ // prefix-colliding names must not match). The toplevel fallback covers plans
26
+ // under <toplevel>/.pi/plans/ — ONLY while no notes-root env var is set:
27
+ // with one set but unmatched, the result is a loud error (PMR-AQTF).
28
+ export function resolvePublishRoot(input: PublishRootInput): PublishRootResult {
29
+ const env = input.env ?? process.env
30
+ const candidates = [env.PERSONAL_FEATURES, env.LLM_NOTES_ROOT]
31
+ const setRoots: string[] = []
32
+ for (const notesRoot of candidates) {
33
+ if (notesRoot === undefined || notesRoot === '') continue
34
+ setRoots.push(notesRoot)
35
+ const prefix = `${notesRoot.replace(/\/$/, '')}/${input.repo}/`
36
+ if (input.planPath.startsWith(prefix)) {
37
+ return {
38
+ kind: 'ok',
39
+ root: prefix.slice(0, -1),
40
+ planFile: input.planPath,
41
+ isFallback: false,
42
+ }
43
+ }
44
+ }
45
+ // AIDEV-NOTE: PMR-AQTF — a notes-root env var IS set but no candidate
46
+ // matched (legacy plan-path metadata recorded from a worktree before the
47
+ // origin-name derivation, or a plan under a sibling repo's notes dir):
48
+ // fail with the real mismatch reason. The old silent downgrade told the
49
+ // worker "notes root env var was unset" (a lie) and had it git-add a plan
50
+ // file OUTSIDE the fallback root (exit 128).
51
+ if (setRoots.length > 0) {
52
+ return {
53
+ kind: 'error',
54
+ reason: `plan path ${input.planPath} is not under ${setRoots.join(' or ')} at the <root>/${input.repo}/ boundary (repo segment mismatch) — refusing the project-repo fallback while a notes-root env var is set`,
55
+ }
56
+ }
57
+ if (input.toplevel === undefined || input.toplevel === '') {
58
+ return {
59
+ kind: 'error',
60
+ reason:
61
+ 'plan is under neither PERSONAL_FEATURES nor LLM_NOTES_ROOT and no project toplevel available',
62
+ }
63
+ }
64
+ return {
65
+ kind: 'ok',
66
+ root: input.toplevel,
67
+ planFile: input.planPath,
68
+ isFallback: true,
69
+ }
70
+ }
71
+
72
+ export interface PublishWorkerTaskInput {
73
+ ref: string
74
+ repo: string
75
+ root: string
76
+ planFile: string
77
+ isFallback: boolean
78
+ }
79
+
80
+ // AIDEV-NOTE: pure string builder — the task text is the worker's contract.
81
+ // Fetch+pull must be ff-only with NO conflict resolution; the retry cap (2)
82
+ // bounds a flaky network, not a broken repo state. PMR-Z0C9: a failing
83
+ // pre-push hook (common in project-repo fallback publishes) must surface as a
84
+ // loud local-only failure with the sha, never a silent unreported commit.
85
+ export function buildPublishWorkerTask(input: PublishWorkerTaskInput): string {
86
+ let fallbackNote: string
87
+ if (input.isFallback === true) {
88
+ fallbackNote =
89
+ 'This is a project-repo fallback publish (notes root env var was unset).'
90
+ } else {
91
+ fallbackNote = 'This publishes into a shared notes repo.'
92
+ }
93
+ return [
94
+ `Publish the approved spec plan ${input.ref} to ${input.root}. ${fallbackNote}`,
95
+ "Run these steps IN ORDER from that directory and report each step's outcome:",
96
+ `1. cd ${input.root}`,
97
+ '2. git fetch origin',
98
+ '3. git pull --ff-only — on conflict STOP immediately and report. Never rebase, merge, or force-push.',
99
+ `4. git add ${input.planFile} — add this ONE file only, never stage everything (no -A flag, no "git add .") — the repo has unrelated dirty state you must not touch.`,
100
+ `5. git commit -m "docs(${input.repo}): publish ${input.ref} plan"`,
101
+ '6. git push origin HEAD',
102
+ 'Rules: touch NOTHING except that single file. If a step fails, retry at most 2 times, then STOP and report the failure loudly with the exact error output — do not roll anything back, do not clean the repo, do not stash.',
103
+ 'If step 6 is rejected by a hook (e.g. pre-push running tests), do NOT retry and NEVER use --no-verify. The commit stays local: run "git rev-parse --short HEAD" and also run "git status --short" (read-only) and quote the failing hook lines plus any dirty files outside the plan file, since unrelated dirty state often breaks the hook. Finish with "PUBLISH FAILED: committed locally as <sha>, not pushed — <hook error>".',
104
+ 'Your final message: one line per step (ok/failed + detail), then "PUBLISH OK" if the push succeeded or "PUBLISH FAILED: <reason>" otherwise.',
105
+ ].join('\n')
106
+ }
107
+
108
+ // AIDEV-NOTE: PMR-MR36 fix round - the old inline check required exit-0 AND
109
+ // the absence of failure strings, so any exit-0 worker output counted as
110
+ // success. The worker contract (buildPublishWorkerTask) promises exactly one
111
+ // terminal marker: success is PUBLISH OK, nothing else is.
112
+ export function isPublishSuccess(outcome: string): boolean {
113
+ return outcome.includes('PUBLISH OK')
114
+ }
115
+
116
+ export interface SpawnPublishWorkerInput {
117
+ task: string
118
+ name: string
119
+ cwd: string
120
+ ref: string
121
+ repo: string
122
+ root: string
123
+ planFile: string
124
+ // Caller label, e.g. '/spec-publish' (command) or 'spec_publish' (tool).
125
+ prefix?: string
126
+ // Releases the caller's wait only; the detached worker keeps running.
127
+ signal?: AbortSignal
128
+ }
129
+
130
+ // AIDEV-NOTE: PMR-YB4E — do NOT pass the caller signal into watchSubagent:
131
+ // its abort path closes the worker pane, killing git mid-publish. Race the
132
+ // wait against the signal instead so Esc releases the tool call while the
133
+ // worker finishes on its own.
134
+ export function raceAbort<T>(
135
+ wait: Promise<T>,
136
+ signal: AbortSignal | undefined,
137
+ onAbort: () => T,
138
+ ): Promise<T> {
139
+ if (signal === undefined) return wait
140
+ if (signal.aborted) return Promise.resolve(onAbort())
141
+ return new Promise<T>((resolve, reject) => {
142
+ const abort = () => resolve(onAbort())
143
+ signal.addEventListener('abort', abort, { once: true })
144
+ wait.then(resolve, reject).finally(() => {
145
+ signal.removeEventListener('abort', abort)
146
+ })
147
+ })
148
+ }
149
+
150
+ // AIDEV-NOTE: PMR-XE3W — the manual-publish block is for a human. The tool
151
+ // caller is an agent told never to retry with raw git, so the block is
152
+ // addressed to the user and the agent is told not to run it.
153
+ export function buildSpawnFailureText(
154
+ input: SpawnPublishWorkerInput,
155
+ msg: string,
156
+ ): string {
157
+ const prefix = input.prefix ?? '/spec-publish'
158
+ const isTool = prefix === 'spec_publish'
159
+ let lead = 'Publish manually:'
160
+ if (isTool) {
161
+ lead =
162
+ 'Ask the user to publish manually — do NOT run these commands yourself:'
163
+ }
164
+ return [
165
+ `${prefix}: could not spawn publish worker (${msg}).`,
166
+ lead,
167
+ `cd ${input.root}`,
168
+ 'git fetch origin',
169
+ 'git pull --ff-only',
170
+ `git add ${input.planFile}`,
171
+ `git commit -m "docs(${input.repo}): publish ${input.ref} plan"`,
172
+ 'git push origin HEAD',
173
+ ].join('\n')
174
+ }
175
+
176
+ // AIDEV-NOTE: wraps launchSubagent + watchSubagent. launchSubagent throws
177
+ // when mux is unavailable — the caller then notifies the manual fallback.
178
+ // Never resolves to a rejection: worker failure is a string result too, so
179
+ // the approval is never rolled back either way.
180
+ export async function spawnPublishWorker(
181
+ ctx: ExtensionContext,
182
+ input: SpawnPublishWorkerInput,
183
+ ): Promise<string> {
184
+ let running: Awaited<ReturnType<typeof launchSubagent>>
185
+ try {
186
+ running = await launchSubagent(
187
+ { agent: 'worker', name: input.name, task: input.task, cwd: input.cwd },
188
+ ctx,
189
+ )
190
+ } catch (error) {
191
+ const msg = error instanceof Error ? error.message : String(error)
192
+ return buildSpawnFailureText(input, msg)
193
+ }
194
+ const prefix = input.prefix ?? '/spec-publish'
195
+ const result = await raceAbort(
196
+ watchSubagent(running, new AbortController().signal),
197
+ input.signal,
198
+ () => null,
199
+ )
200
+ if (result === null) {
201
+ return `${prefix}: wait aborted; the publish worker "${input.name}" keeps running in the background — check the notes repo before retrying.`
202
+ }
203
+ const base = `${prefix} worker "${result.name}" exited with code ${result.exitCode}`
204
+ if (result.exitCode === 0 && result.summary !== undefined) {
205
+ return `${base}: ${result.summary}`
206
+ }
207
+ const detail =
208
+ result.errorMessage ?? result.summary ?? 'no worker output captured'
209
+ return `${base}: ${detail}`
210
+ }
@@ -0,0 +1,118 @@
1
+ // AIDEV-NOTE (PMR-R8AG): pure env->attribute mapping for telemetry spans.
2
+ // No I/O, fully unit-tested. Metadata only — never prompt or completion
3
+ // bodies (hard rule from the observability plan: spans describe, they do
4
+ // not leak content).
5
+ export type TelemetryEnv = Record<string, string | undefined>
6
+
7
+ export type SpanAttributes = Record<string, string>
8
+
9
+ /** W3C traceparent: 00-<32 hex traceId>-<16 hex parentId>-<2 hex flags>. */
10
+ export interface TraceContext {
11
+ traceId: string
12
+ parentId: string
13
+ }
14
+
15
+ const TRACEPARENT_RE = /^[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/
16
+
17
+ /** Parse PI_FLOW_TRACEPARENT into trace coordinates; null when absent/invalid. */
18
+ export function parseTraceparent(
19
+ value: string | undefined,
20
+ ): TraceContext | null {
21
+ if (value === undefined) return null
22
+ if (!TRACEPARENT_RE.test(value)) return null
23
+ const parts = value.split('-')
24
+ return { traceId: parts[1], parentId: parts[2] }
25
+ }
26
+
27
+ /** Bytes source for id generation (crypto.randomBytes in wiring, stub in tests). */
28
+ export interface TelemetryRng {
29
+ bytes: (n: number) => Uint8Array
30
+ }
31
+
32
+ function toHex(bytes: Uint8Array): string {
33
+ let out = ''
34
+ for (const byte of bytes) {
35
+ out += byte.toString(16).padStart(2, '0')
36
+ }
37
+ return out
38
+ }
39
+
40
+ export function randomTraceId(rng: TelemetryRng): string {
41
+ return toHex(rng.bytes(16))
42
+ }
43
+
44
+ export function randomSpanId(rng: TelemetryRng): string {
45
+ return toHex(rng.bytes(8))
46
+ }
47
+
48
+ /**
49
+ * Map the attribution env into span attributes. Keys follow the flow /
50
+ * subagent env vars so backend queries read the same names everywhere:
51
+ * flow.ref, phase, agent.name, subtask, parent.session. Empty or missing
52
+ * values are omitted, never forwarded as empty strings.
53
+ */
54
+ export function flowAttributes(env: TelemetryEnv): SpanAttributes {
55
+ const attrs: SpanAttributes = {}
56
+ const mapping: Array<[string, string]> = [
57
+ ['flow.ref', 'PI_FLOW_REF'],
58
+ ['phase', 'PI_FLOW_PHASE'],
59
+ ['agent.name', 'PI_SUBAGENT_NAME'],
60
+ ['agent.type', 'PI_SUBAGENT_AGENT'],
61
+ ['subtask', 'PI_FLOW_SUBTASK'],
62
+ ['parent.session', 'PI_SUBAGENT_PARENT_SESSION'],
63
+ ['flow.mode', 'PI_FLOW_MODE'],
64
+ ]
65
+ for (const [attrKey, envKey] of mapping) {
66
+ const value = env[envKey]
67
+ if (value !== undefined && value.length > 0) {
68
+ attrs[attrKey] = value
69
+ }
70
+ }
71
+ // AIDEV-NOTE: work/personal separation. `flow.ref` is the ref the run is
72
+ // TRACKED by: the Jira key in work mode (PI_FLOW_TRACK_REF), else the aven
73
+ // ref. The aven ref stays available as `flow.aven_ref` when it differs.
74
+ const track = env.PI_FLOW_TRACK_REF
75
+ const aven = env.PI_FLOW_REF
76
+ if (track !== undefined && track.length > 0) {
77
+ attrs['flow.ref'] = track
78
+ if (aven !== undefined && aven.length > 0 && aven !== track) {
79
+ attrs['flow.aven_ref'] = aven
80
+ }
81
+ }
82
+ return attrs
83
+ }
84
+
85
+ export interface ToolSpanInput {
86
+ toolName: string
87
+ isError: boolean
88
+ }
89
+
90
+ /** Attributes for a tool-execution span (gen_ai.tool.* conventions). */
91
+ export function toolSpanAttributes(
92
+ flow: SpanAttributes,
93
+ tool: ToolSpanInput,
94
+ ): SpanAttributes {
95
+ const attrs: SpanAttributes = { ...flow }
96
+ attrs['gen_ai.tool.name'] = tool.toolName
97
+ attrs['tool.error'] = tool.isError ? 'true' : 'false'
98
+ return attrs
99
+ }
100
+
101
+ export interface GenerationSpanInput {
102
+ model: string
103
+ inputTokens: number
104
+ outputTokens: number
105
+ }
106
+
107
+ /** Attributes for a generation span (OTLP GenAI semantic conventions). */
108
+ export function generationSpanAttributes(
109
+ flow: SpanAttributes,
110
+ gen: GenerationSpanInput,
111
+ ): SpanAttributes {
112
+ const attrs: SpanAttributes = { ...flow }
113
+ attrs['gen_ai.operation.name'] = 'generate_content'
114
+ attrs['gen_ai.request.model'] = gen.model
115
+ attrs['gen_ai.usage.input_tokens'] = `${gen.inputTokens}`
116
+ attrs['gen_ai.usage.output_tokens'] = `${gen.outputTokens}`
117
+ return attrs
118
+ }