@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,908 @@
1
+ /**
2
+ * PR Quality Extension
3
+ *
4
+ * Combines GitHub PR unresolved review comments with SonarCloud analysis for
5
+ * the same PR, then sends a unified context message to the LLM so it can:
6
+ * - Triage each review thread (VALID / INVALID)
7
+ * - Auto-resolve INVALID threads via GitHub GraphQL
8
+ * - Cross-reference VALID comments with SonarCloud issues by file
9
+ * - Fix issues immediately — no plan file written
10
+ *
11
+ * Prerequisites:
12
+ * - gh CLI installed and authenticated
13
+ * - SONARQUBE_TOKEN env var set (get from https://sonarcloud.io/account/security)
14
+ * - sonar-project.properties in repo root (or SONAR_PROJECT_KEY + SONAR_ORGANIZATION env vars)
15
+ *
16
+ * Usage:
17
+ * /pr-quality — auto-detect PR from current branch
18
+ * /pr-quality 283 — explicit PR number
19
+ */
20
+
21
+ import type {
22
+ AgentToolResult,
23
+ ExtensionAPI,
24
+ ExtensionToolContext,
25
+ } from '@earendil-works/pi-coding-agent'
26
+ import { Type } from 'typebox'
27
+ import { adhocBeginMain } from '../adhoc/tracker.ts'
28
+ import {
29
+ analyzeCoverage,
30
+ analyzeIssues,
31
+ type CoverageResponse,
32
+ detectPrNumber,
33
+ detectSonarConfig,
34
+ fetchAllIssues,
35
+ type IssuesAnalysis,
36
+ localExec,
37
+ SEVERITY_SYMBOLS,
38
+ type SonarConfig,
39
+ type SonarIssue,
40
+ sonarFetch,
41
+ TYPE_SYMBOLS,
42
+ } from '../shared/sonarqube-utils.ts'
43
+
44
+ // ── GitHub types ──────────────────────────────────────────────────────────────
45
+
46
+ export interface CheckRun {
47
+ name: string
48
+ status: string // "QUEUED" | "IN_PROGRESS" | "COMPLETED"
49
+ conclusion: string | null // "SUCCESS" | "FAILURE" | "CANCELLED" | "SKIPPED" | ...
50
+ workflowName?: string
51
+ }
52
+
53
+ interface GhComment {
54
+ author: string
55
+ body: string
56
+ createdAt: string
57
+ url: string
58
+ }
59
+
60
+ interface GhReviewThread {
61
+ threadId: string
62
+ path: string
63
+ line: number | null
64
+ startLine: number | null
65
+ isOutdated: boolean
66
+ comments: GhComment[]
67
+ }
68
+
69
+ export interface GhPrData {
70
+ pr_title: string
71
+ pr_url: string
72
+ total_review_threads: number
73
+ unresolved_count: number
74
+ unresolved_threads: GhReviewThread[]
75
+ }
76
+
77
+ // ── GH Actions check ────────────────────────────────────────────────────────
78
+
79
+ interface ActionsStatus {
80
+ complete: boolean
81
+ pending: CheckRun[]
82
+ all: CheckRun[]
83
+ }
84
+
85
+ // AIDEV-NOTE: Uses statusCheckRollup from gh pr view — covers both GitHub
86
+ // Actions CheckRuns and external status checks (e.g. SonarCloud gate itself).
87
+ async function checkActionsComplete(
88
+ prNumber: string,
89
+ cwd?: string,
90
+ ): Promise<ActionsStatus> {
91
+ const result = await localExec(
92
+ 'gh',
93
+ ['pr', 'view', prNumber, '--json', 'statusCheckRollup'],
94
+ { timeout: 15000, cwd },
95
+ )
96
+
97
+ if (result.code !== 0) {
98
+ throw new Error(`gh pr view failed: ${result.stderr || result.stdout}`)
99
+ }
100
+
101
+ const data = JSON.parse(result.stdout) as { statusCheckRollup?: CheckRun[] }
102
+ const checks = data.statusCheckRollup ?? []
103
+
104
+ // AIDEV-NOTE: Skip checks with conclusion "SKIPPED" — they never become
105
+ // COMPLETED in the traditional sense but do not block the workflow.
106
+ const relevant = checks.filter((c) => c.conclusion !== 'SKIPPED')
107
+ const pending = relevant.filter((c) => c.status !== 'COMPLETED')
108
+
109
+ return { complete: pending.length === 0, pending, all: checks }
110
+ }
111
+
112
+ // ── Arg parsing ───────────────────────────────────────────────────────────────
113
+
114
+ function parseArgs(args: string): { prNumber?: string } {
115
+ const match = args.trim().match(/^(\d+)/)
116
+ return { prNumber: match?.[1] }
117
+ }
118
+
119
+ // ── GitHub PR comment fetching ────────────────────────────────────────────────
120
+
121
+ // AIDEV-NOTE: Uses inline GraphQL via `gh api graphql` so the extension has no
122
+ // dependency on the fetch_unresolved_comments.sh shell script. Same query as
123
+ // the gh-unresolved-comments skill.
124
+ const REVIEW_THREADS_QUERY = `
125
+ query($owner: String!, $repo: String!, $pr: Int!, $limit: Int!) {
126
+ repository(owner: $owner, name: $repo) {
127
+ pullRequest(number: $pr) {
128
+ title
129
+ url
130
+ reviewThreads(first: $limit) {
131
+ totalCount
132
+ nodes {
133
+ id
134
+ isResolved
135
+ isOutdated
136
+ path
137
+ line
138
+ startLine
139
+ comments(first: 10) {
140
+ nodes {
141
+ body
142
+ author { login }
143
+ createdAt
144
+ url
145
+ }
146
+ }
147
+ }
148
+ }
149
+ }
150
+ }
151
+ }
152
+ `.trim()
153
+
154
+ async function fetchUnresolvedThreads(prNumber: string): Promise<GhPrData> {
155
+ const result = await localExec(
156
+ 'gh',
157
+ [
158
+ 'api',
159
+ 'graphql',
160
+ '-f',
161
+ `query=${REVIEW_THREADS_QUERY}`,
162
+ '-F',
163
+ 'owner={owner}',
164
+ '-F',
165
+ 'repo={repo}',
166
+ '-F',
167
+ `pr=${prNumber}`,
168
+ '-F',
169
+ 'limit=100',
170
+ ],
171
+ { timeout: 30000 },
172
+ )
173
+
174
+ if (result.code !== 0) {
175
+ throw new Error(
176
+ `gh GraphQL query failed: ${result.stderr || result.stdout}`,
177
+ )
178
+ }
179
+
180
+ // AIDEV-NOTE: `gh api graphql` with `-F owner={owner}` uses the repo owner
181
+ // inferred from the current git remote — same behaviour as the skill script.
182
+ const raw = JSON.parse(result.stdout)
183
+ const pr = raw?.data?.repository?.pullRequest
184
+ if (!pr) {
185
+ throw new Error(
186
+ 'GitHub GraphQL returned no pull request data. Check PR number and repo access.',
187
+ )
188
+ }
189
+
190
+ const allThreads = pr.reviewThreads?.nodes ?? []
191
+ const unresolved: GhReviewThread[] = allThreads
192
+ .filter((t: { isResolved: boolean }) => !t.isResolved)
193
+ .map(
194
+ (t: {
195
+ id: string
196
+ path: string
197
+ line: number | null
198
+ startLine: number | null
199
+ isOutdated: boolean
200
+ comments: {
201
+ nodes: Array<{
202
+ body: string
203
+ author: { login: string }
204
+ createdAt: string
205
+ url: string
206
+ }>
207
+ }
208
+ }) => ({
209
+ threadId: t.id,
210
+ path: t.path,
211
+ line: t.line,
212
+ startLine: t.startLine,
213
+ isOutdated: t.isOutdated,
214
+ comments: (t.comments?.nodes ?? []).map((c) => ({
215
+ author: c.author?.login ?? 'unknown',
216
+ body: c.body,
217
+ createdAt: c.createdAt,
218
+ url: c.url,
219
+ })),
220
+ }),
221
+ )
222
+
223
+ return {
224
+ pr_title: pr.title,
225
+ pr_url: pr.url,
226
+ total_review_threads: pr.reviewThreads?.totalCount ?? 0,
227
+ unresolved_count: unresolved.length,
228
+ unresolved_threads: unresolved,
229
+ }
230
+ }
231
+
232
+ // ── Prompt construction ───────────────────────────────────────────────────────
233
+
234
+ // AIDEV-NOTE: The prompt is intentionally verbose and structured so the LLM has
235
+ // clear, step-by-step instructions for both the triage and the SonarQube fix
236
+ // tasks. The file is written to disk so the agent can read it back if it gets
237
+ // compacted mid-task.
238
+ function buildAgentPrompt(
239
+ prNumber: string,
240
+ prData: GhPrData,
241
+ sonarConfig: SonarConfig,
242
+ issues: IssuesAnalysis,
243
+ coverageData: ReturnType<typeof analyzeCoverage>,
244
+ ): string {
245
+ const lines: string[] = []
246
+
247
+ lines.push(`# PR Quality Check — PR #${prNumber}: ${prData.pr_title}`)
248
+ lines.push(`> ${prData.pr_url}`)
249
+ lines.push('')
250
+
251
+ // ── Section 1: instructions ─────────────────────────────────────────────
252
+ lines.push('## Your Tasks')
253
+ lines.push('')
254
+ lines.push(
255
+ 'You have two data sources below. Triage first, then fix immediately. Do NOT write a plan file.',
256
+ )
257
+ lines.push('')
258
+ // AIDEV-NOTE: Success-criteria preamble added from workflow-hygiene review
259
+ // 2026-10 — every /pr-quality session lacked explicit done-when/verification.
260
+ lines.push('### Success criteria (read first)')
261
+ lines.push('')
262
+ lines.push(
263
+ '- **Goal:** every unresolved review thread is fixed or resolved, and all BLOCKER/CRITICAL SonarCloud issues are fixed.',
264
+ )
265
+ lines.push(
266
+ '- **Constraints:** fix only what the two data sources flag — no drive-by refactors. Follow repo lint/style rules. Never resolve a thread as INVALID without a one-line justification.',
267
+ )
268
+ lines.push(
269
+ '- **Done when:** VALID threads fixed, INVALID threads resolved, BLOCKER/CRITICAL issues fixed or explicitly skipped with a reason, tests pass, fixes committed referencing the PR.',
270
+ )
271
+ lines.push(
272
+ '- **Verification:** run the repo test suite (its documented runner) after fixes; `git diff --stat` shows only intended files.',
273
+ )
274
+ lines.push(
275
+ '- **Circuit breaker:** if the same command or API call fails 3 times in a row, stop retrying — report what failed and what remains.',
276
+ )
277
+ lines.push('')
278
+ lines.push('### Task A — Triage & Fix GitHub Review Comments')
279
+ lines.push('')
280
+ lines.push(
281
+ 'For each unresolved thread in **Section 2**, read the referenced file at the given line, then classify the thread:',
282
+ )
283
+ lines.push('')
284
+ lines.push('**VALID** — needs action:')
285
+ lines.push(' - Real bug, security issue, or logic error')
286
+ lines.push(
287
+ ' - Meaningful improvement to quality, readability, or performance',
288
+ )
289
+ lines.push(' - Legitimate architectural / design concern')
290
+ lines.push(' - Missing error handling, edge cases, or tests')
291
+ lines.push('')
292
+ lines.push('**INVALID** — dismiss:')
293
+ lines.push(' - Code already changed or fixed (outdated diff)')
294
+ lines.push(' - Style nitpick with no functional impact')
295
+ lines.push(" - Based on a misunderstanding of the code's intent")
296
+ lines.push(' - Already answered elsewhere in the PR')
297
+ lines.push('')
298
+ lines.push('For every **INVALID** thread, auto-resolve it via:')
299
+ lines.push('```bash')
300
+ lines.push(
301
+ `gh api graphql -f query='mutation { resolveReviewThread(input: {threadId: "<THREAD_ID>"}) { thread { isResolved } } }'`,
302
+ )
303
+ lines.push('```')
304
+ lines.push('(Replace `<THREAD_ID>` with the threadId from Section 2.)')
305
+ lines.push('')
306
+ lines.push('For every **VALID** thread, **fix the issue now**:')
307
+ lines.push(' 1. Read the file at the referenced line.')
308
+ lines.push(' 2. Apply the fix directly using your edit tools.')
309
+ lines.push(' 3. Run tests to confirm nothing is broken.')
310
+ lines.push('')
311
+ lines.push('### Task B — Fix SonarCloud Issues')
312
+ lines.push('')
313
+ lines.push(
314
+ 'Using the SonarCloud data in **Section 3**, fix issues in severity order (BLOCKER → CRITICAL → MAJOR).',
315
+ )
316
+ lines.push(
317
+ 'Prioritise files that also have VALID review comments — fix both at once.',
318
+ )
319
+ lines.push('For each issue: read the file, apply the fix, run tests.')
320
+ lines.push('')
321
+ lines.push('### Task C — Final Summary')
322
+ lines.push('')
323
+ lines.push('After all fixes are applied and tests pass:')
324
+ lines.push(' - Run `git diff --stat` to confirm scope of changes.')
325
+ lines.push(
326
+ ' - Present the final summary in three lists: **Fixed** (item → what changed),',
327
+ )
328
+ lines.push(
329
+ ' **Resolved as INVALID** (thread → one-line justification), **Skipped** (item → why).',
330
+ )
331
+ lines.push(
332
+ ' - Commit the fixes with a clear message referencing the PR number.',
333
+ )
334
+ lines.push('')
335
+
336
+ // ── Section 2: review threads ────────────────────────────────────────────
337
+ lines.push('---')
338
+ lines.push('')
339
+ lines.push(
340
+ `## Section 2 — Unresolved Review Threads (${prData.unresolved_count})`,
341
+ )
342
+ lines.push('')
343
+
344
+ if (prData.unresolved_count === 0) {
345
+ lines.push('_No unresolved threads. Skip Task A._')
346
+ } else {
347
+ for (const [i, thread] of prData.unresolved_threads.entries()) {
348
+ let loc: string
349
+ if (thread.line) {
350
+ loc = `${thread.path}:${thread.line}`
351
+ } else {
352
+ loc = thread.path
353
+ }
354
+ let outdated: string
355
+ if (thread.isOutdated) {
356
+ outdated = ' _(outdated diff)_'
357
+ } else {
358
+ outdated = ''
359
+ }
360
+ lines.push(`### Thread ${i + 1} — \`${loc}\`${outdated}`)
361
+ lines.push(`**threadId:** \`${thread.threadId}\``)
362
+ lines.push('')
363
+ for (const c of thread.comments) {
364
+ lines.push(`**@${c.author}** (${c.createdAt.slice(0, 10)}):`)
365
+ lines.push(`> ${c.body.split('\n').join('\n> ')}`)
366
+ lines.push(`[View on GitHub](${c.url})`)
367
+ lines.push('')
368
+ }
369
+ }
370
+ }
371
+
372
+ // ── Section 3: SonarCloud ────────────────────────────────────────────────
373
+ lines.push('---')
374
+ lines.push('')
375
+ lines.push('## Section 3 — SonarCloud Analysis')
376
+ lines.push('')
377
+ lines.push(`**Project:** \`${sonarConfig.projectKey}\``)
378
+ lines.push('')
379
+
380
+ // Coverage summary
381
+ lines.push('### Coverage')
382
+ lines.push(`| Metric | Value | Status |`)
383
+ lines.push(`|--------|-------|--------|`)
384
+ lines.push(
385
+ `| Overall Line | ${coverageData.overallCoverage}% | ${coverageData.icons.overall} ${coverageData.status.overall} |`,
386
+ )
387
+ lines.push(
388
+ `| New Code | ${coverageData.newCoverage}% | ${coverageData.icons.newCode} ${coverageData.status.newCode} |`,
389
+ )
390
+ lines.push(
391
+ `| Branch | ${coverageData.branchCoverage}% | ${coverageData.icons.branch} ${coverageData.status.branch} |`,
392
+ )
393
+ lines.push(
394
+ `| New Branch | ${coverageData.newBranchCoverage}% | ${coverageData.icons.newBranch} ${coverageData.status.newBranch} |`,
395
+ )
396
+ lines.push(
397
+ `| Uncovered Lines | ${coverageData.uncoveredLines} / ${coverageData.linesToCover} | — |`,
398
+ )
399
+ lines.push('')
400
+
401
+ // Issues summary
402
+ lines.push('### Issues')
403
+ lines.push(`**Total:** ${issues.total}`)
404
+ lines.push('')
405
+
406
+ if (issues.total > 0) {
407
+ lines.push('**By Severity:**')
408
+ for (const [sev, count] of Object.entries(issues.bySeverity)) {
409
+ lines.push(` - ${SEVERITY_SYMBOLS[sev] ?? '❓'} ${sev}: ${count}`)
410
+ }
411
+ lines.push('')
412
+
413
+ lines.push('**By Type:**')
414
+ for (const [type, count] of Object.entries(issues.byType)) {
415
+ lines.push(` - ${TYPE_SYMBOLS[type] ?? '❓'} ${type}: ${count}`)
416
+ }
417
+ lines.push('')
418
+
419
+ // Per-file issues (top 15)
420
+ if (issues.byFile.length > 0) {
421
+ lines.push('### Issues by File (top 15)')
422
+ lines.push('')
423
+ for (const f of issues.byFile.slice(0, 15)) {
424
+ lines.push(`#### \`${f.file}\` — ${f.count} issue(s)`)
425
+ for (const issue of f.issues.slice(0, 20)) {
426
+ let loc: string
427
+ if (issue.line) {
428
+ loc = `:${issue.line}`
429
+ } else {
430
+ loc = ''
431
+ }
432
+ const sym = SEVERITY_SYMBOLS[issue.severity] ?? '❓'
433
+ const typeSym = TYPE_SYMBOLS[issue.type] ?? '❓'
434
+ lines.push(
435
+ `- ${sym} ${typeSym} **${issue.severity}** \`${issue.rule}\`${loc} — ${issue.message}`,
436
+ )
437
+ }
438
+ lines.push('')
439
+ }
440
+ }
441
+
442
+ // Top rules
443
+ if (issues.byRule.length > 0) {
444
+ lines.push('### Top Violated Rules')
445
+ for (const r of issues.byRule) {
446
+ lines.push(
447
+ `- \`${r.rule}\` (${r.severity}) × ${r.count} — "${r.message}"`,
448
+ )
449
+ }
450
+ lines.push('')
451
+ }
452
+ }
453
+
454
+ // SonarCloud link
455
+ lines.push(
456
+ `[View PR in SonarCloud](https://sonarcloud.io/project/pull_requests_list?id=${sonarConfig.projectKey}&pullRequest=${prNumber})`,
457
+ )
458
+
459
+ return lines.join('\n')
460
+ }
461
+
462
+ // ── Shared quality core ───────────────────────────────────────────────────────
463
+
464
+ export type PrQualityErrorKind =
465
+ | 'token'
466
+ | 'pr'
467
+ | 'ci-pending'
468
+ | 'config'
469
+ | 'fetch'
470
+
471
+ // AIDEV-NOTE: Classified failure so the /pr-quality command and the pr_quality
472
+ // tool can map the same error to their own surfaces (notify vs isError result).
473
+ // The 'ci-pending' kind is deliberately NOT a hard failure for the command —
474
+ // it warns and returns — while the tool reports it as an isError result with
475
+ // the pending check names.
476
+ export class PrQualityError extends Error {
477
+ kind: PrQualityErrorKind
478
+ pending: CheckRun[]
479
+ cause?: Error
480
+
481
+ constructor(
482
+ kind: PrQualityErrorKind,
483
+ message: string,
484
+ pending: CheckRun[] = [],
485
+ cause?: Error,
486
+ ) {
487
+ super(message)
488
+ this.kind = kind
489
+ this.pending = pending
490
+ this.cause = cause
491
+ }
492
+ }
493
+
494
+ export interface PrQualityOptions {
495
+ cwd: string
496
+ prNumber?: string
497
+ signal?: AbortSignal
498
+ // AIDEV-NOTE: progress feed so the command keeps its original notify
499
+ // updates; the tool leaves it unset.
500
+ onProgress?: (message: string) => void
501
+ }
502
+
503
+ // Structured summary for the tool's `details` field — prompt text stays the
504
+ // single source of truth for the agent.
505
+ export interface PrQualityDetails {
506
+ prNumber: string
507
+ prTitle: string
508
+ prUrl: string
509
+ unresolvedCount: number
510
+ issuesTotal: number
511
+ issuesBySeverity: Record<string, number>
512
+ projectKey: string
513
+ }
514
+
515
+ export interface PrQualityResult {
516
+ prompt: string
517
+ prNumber: string
518
+ prData: GhPrData
519
+ sonarConfig: SonarConfig
520
+ coverage: ReturnType<typeof analyzeCoverage>
521
+ issues: IssuesAnalysis
522
+ details: PrQualityDetails
523
+ }
524
+
525
+ // AIDEV-NOTE: Shared pending-check formatter so the command's warning notify
526
+ // and the tool's isError text stay identical.
527
+ function describePending(pending: CheckRun[]): string {
528
+ return pending
529
+ .map((c) => {
530
+ let wf: string
531
+ if (c.workflowName) {
532
+ wf = `${c.workflowName} / `
533
+ } else {
534
+ wf = ''
535
+ }
536
+ return `${wf}${c.name} (${c.status.toLowerCase()})`
537
+ })
538
+ .join(', ')
539
+ }
540
+
541
+ // AIDEV-NOTE: Shared core extracted from the /pr-quality command handler.
542
+ // Token guard → PR detect → CI guard → SonarCloud config → parallel fetch →
543
+ // analyze → buildAgentPrompt. The command sends the prompt via
544
+ // sendUserMessage; the pr_quality tool returns it as content. Errors are
545
+ // classified via PrQualityError.kind so each caller maps them to its own
546
+ // surface.
547
+ export async function gatherPrQualityData(
548
+ options: PrQualityOptions,
549
+ ): Promise<PrQualityResult> {
550
+ const { cwd, signal, onProgress } = options
551
+ const token = process.env.SONARQUBE_TOKEN
552
+ if (!token) {
553
+ throw new PrQualityError(
554
+ 'token',
555
+ 'SONARQUBE_TOKEN is not set. Get a token at https://sonarcloud.io/account/security',
556
+ )
557
+ }
558
+
559
+ let prNumber: string
560
+ if (options.prNumber) {
561
+ prNumber = options.prNumber
562
+ } else {
563
+ try {
564
+ prNumber = await detectPrNumber('/pr-quality')
565
+ } catch (err) {
566
+ throw new PrQualityError(
567
+ 'pr',
568
+ String((err as Error).message),
569
+ [],
570
+ err as Error,
571
+ )
572
+ }
573
+ }
574
+
575
+ if (onProgress) {
576
+ onProgress(`PR Quality: analyzing PR #${prNumber}...`)
577
+ }
578
+
579
+ let actionsStatus: ActionsStatus
580
+ try {
581
+ actionsStatus = await checkActionsComplete(prNumber, cwd)
582
+ } catch (err) {
583
+ throw new PrQualityError(
584
+ 'pr',
585
+ `Could not check Actions status: ${(err as Error).message}`,
586
+ [],
587
+ err as Error,
588
+ )
589
+ }
590
+
591
+ if (!actionsStatus.complete) {
592
+ throw new PrQualityError(
593
+ 'ci-pending',
594
+ `PR #${prNumber} CI not done yet — ${actionsStatus.pending.length} check(s) still running: ${describePending(actionsStatus.pending)}`,
595
+ actionsStatus.pending,
596
+ )
597
+ }
598
+
599
+ let sonarConfig: SonarConfig
600
+ try {
601
+ sonarConfig = await detectSonarConfig(cwd)
602
+ } catch (err) {
603
+ throw new PrQualityError(
604
+ 'config',
605
+ String((err as Error).message),
606
+ [],
607
+ err as Error,
608
+ )
609
+ }
610
+
611
+ if (onProgress) {
612
+ onProgress('Fetching GitHub threads + SonarCloud data...')
613
+ }
614
+
615
+ // AIDEV-NOTE: GitHub and SonarCloud calls are independent — run them
616
+ // concurrently to reduce total wall-clock time.
617
+ let prData: GhPrData
618
+ let coverageRaw: CoverageResponse
619
+ let rawIssues: { issues: SonarIssue[]; total: number }
620
+ try {
621
+ ;[prData, coverageRaw, rawIssues] = await Promise.all([
622
+ fetchUnresolvedThreads(prNumber),
623
+ sonarFetch(
624
+ sonarConfig.baseUrl,
625
+ token,
626
+ 'measures/component',
627
+ {
628
+ component: sonarConfig.projectKey,
629
+ pullRequest: prNumber,
630
+ metricKeys:
631
+ 'coverage,new_coverage,new_line_coverage,uncovered_lines,lines_to_cover,branch_coverage,new_branch_coverage,new_lines_to_cover',
632
+ },
633
+ signal,
634
+ ).then((d) => d as CoverageResponse),
635
+ fetchAllIssues(
636
+ sonarConfig.baseUrl,
637
+ token,
638
+ sonarConfig.projectKey,
639
+ prNumber,
640
+ signal,
641
+ ),
642
+ ])
643
+ } catch (err) {
644
+ throw new PrQualityError(
645
+ 'fetch',
646
+ `Fetch failed: ${(err as Error).message}`,
647
+ [],
648
+ err as Error,
649
+ )
650
+ }
651
+
652
+ const coverage = analyzeCoverage(coverageRaw)
653
+ const issues = analyzeIssues(rawIssues)
654
+ const prompt = buildAgentPrompt(
655
+ prNumber,
656
+ prData,
657
+ sonarConfig,
658
+ issues,
659
+ coverage,
660
+ )
661
+
662
+ if (onProgress) {
663
+ onProgress(
664
+ `Fetched ${prData.unresolved_count} unresolved threads, ${issues.total} SonarCloud issues. Starting triage...`,
665
+ )
666
+ }
667
+
668
+ return {
669
+ prompt,
670
+ prNumber,
671
+ prData,
672
+ sonarConfig,
673
+ coverage,
674
+ issues,
675
+ details: {
676
+ prNumber,
677
+ prTitle: prData.pr_title,
678
+ prUrl: prData.pr_url,
679
+ unresolvedCount: prData.unresolved_count,
680
+ issuesTotal: issues.total,
681
+ issuesBySeverity: issues.bySeverity,
682
+ projectKey: sonarConfig.projectKey,
683
+ },
684
+ }
685
+ }
686
+
687
+ // ── Extension ─────────────────────────────────────────────────────────────────
688
+
689
+ // AIDEV-NOTE: Tracks active poll intervals keyed by PR number so we can
690
+ // clear them on session_shutdown and prevent duplicate watchers.
691
+ // Uses setInterval + checkActionsComplete (same gh API call as /pr-quality guard)
692
+ // instead of a detached bash process + sentinel files, which had PATH and
693
+ // fs.watch reliability issues.
694
+ // Since PMR-4B5A the poller also fully stops (interval cleared, poller
695
+ // removed, one error notification) on ANY poll error — it does not retry.
696
+ const activePollers = new Map<string, ReturnType<typeof setInterval>>()
697
+
698
+ export default function prQuality(pi: ExtensionAPI) {
699
+ // ── /pr-watch ────────────────────────────────────────────────────────────
700
+ pi.registerCommand('pr-watch', {
701
+ description:
702
+ 'Watch PR checks in background; triggers /pr-quality when all pass',
703
+ handler: async (args, ctx) => {
704
+ const parsed = parseArgs(args)
705
+ let prNumber: string
706
+ try {
707
+ prNumber = parsed.prNumber ?? (await detectPrNumber('/pr-watch'))
708
+ } catch (err) {
709
+ ctx.ui.notify(String((err as Error).message), 'error')
710
+ return
711
+ }
712
+
713
+ if (activePollers.has(prNumber)) {
714
+ ctx.ui.notify(`Already watching PR #${prNumber}`, 'warning')
715
+ return
716
+ }
717
+
718
+ // Capture cwd now so the poller always runs gh in the right repo
719
+ const cwd = ctx.cwd
720
+
721
+ const poll = async () => {
722
+ try {
723
+ const status = await checkActionsComplete(prNumber, cwd)
724
+ if (status.complete) {
725
+ clearInterval(activePollers.get(prNumber))
726
+ activePollers.delete(prNumber)
727
+ ctx.ui.notify(
728
+ `PR #${prNumber} ✔ all checks passed — triggering /pr-quality`,
729
+ 'info',
730
+ )
731
+ pi.sendUserMessage(`/pr-quality ${prNumber}`)
732
+ } else {
733
+ const failing = status.all.filter(
734
+ (c) =>
735
+ c.conclusion &&
736
+ c.conclusion !== 'SUCCESS' &&
737
+ c.conclusion !== 'SKIPPED',
738
+ )
739
+ if (failing.length > 0) {
740
+ clearInterval(activePollers.get(prNumber))
741
+ activePollers.delete(prNumber)
742
+ const names = failing.map((c) => c.name).join(', ')
743
+ ctx.ui.notify(
744
+ `PR #${prNumber} ✖ check(s) failed: ${names}`,
745
+ 'error',
746
+ )
747
+ }
748
+ // else still pending — keep polling
749
+ }
750
+ } catch (err) {
751
+ // PMR-4B5A: stop polling on ANY error — notify once and wait for
752
+ // the human to re-run /pr-watch. No backoff, no retry by design.
753
+ clearInterval(activePollers.get(prNumber))
754
+ activePollers.delete(prNumber)
755
+ ctx.ui.notify(
756
+ `PR #${prNumber} ✖ watch error — polling stopped: ${
757
+ (err as Error).message
758
+ }`,
759
+ 'error',
760
+ )
761
+ }
762
+ }
763
+
764
+ // Run once immediately, then every 60s
765
+ void poll()
766
+ const interval = setInterval(() => {
767
+ void poll()
768
+ }, 60_000)
769
+ activePollers.set(prNumber, interval)
770
+
771
+ ctx.ui.notify(
772
+ `Watching PR #${prNumber} checks (polling every 60s). Will trigger /pr-quality when all pass.`,
773
+ 'info',
774
+ )
775
+ },
776
+ })
777
+
778
+ // Clean up pollers when session ends
779
+ pi.on('session_shutdown', async () => {
780
+ for (const [pr, interval] of activePollers) {
781
+ clearInterval(interval)
782
+ activePollers.delete(pr)
783
+ }
784
+ })
785
+
786
+ pi.registerCommand('pr-quality', {
787
+ description:
788
+ 'Triage unresolved PR review comments + SonarCloud issues and fix them immediately',
789
+ // AIDEV-NOTE: Human surface — keeps the original behavior (token guard
790
+ // multi-line notify, CI-pending warn+return, setStatus during fetch,
791
+ // sendUserMessage(prompt)) over the shared gatherPrQualityData core.
792
+ handler: async (args, ctx) => {
793
+ const parsed = parseArgs(args)
794
+ ctx.ui.setStatus(
795
+ 'pr-quality',
796
+ 'Fetching GitHub threads + SonarCloud data...',
797
+ )
798
+
799
+ let result: PrQualityResult
800
+ try {
801
+ result = await gatherPrQualityData({
802
+ cwd: ctx.cwd,
803
+ prNumber: parsed.prNumber,
804
+ signal: ctx.signal,
805
+ onProgress: (message) => {
806
+ ctx.ui.notify(message, 'info')
807
+ },
808
+ })
809
+ } catch (err) {
810
+ ctx.ui.setStatus('pr-quality', undefined)
811
+ if (err instanceof PrQualityError && err.kind === 'token') {
812
+ ctx.ui.notify(
813
+ [
814
+ 'SONARQUBE_TOKEN is not set.',
815
+ 'Get a token at https://sonarcloud.io/account/security',
816
+ 'Then run: export SONARQUBE_TOKEN=<your_token>',
817
+ 'Add it to your shell profile (~/.bashrc / ~/.zshrc) to persist it.',
818
+ ].join(' '),
819
+ 'error',
820
+ )
821
+ return
822
+ }
823
+ if (err instanceof PrQualityError && err.kind === 'pr') {
824
+ ctx.ui.notify(String(err.message), 'error')
825
+ return
826
+ }
827
+ // AIDEV-NOTE: CI-pending is not a failure for the human — warn and
828
+ // return, exactly as before the core extraction.
829
+ if (err instanceof PrQualityError && err.kind === 'ci-pending') {
830
+ ctx.ui.notify(String(err.message), 'warning')
831
+ return
832
+ }
833
+ if (err instanceof PrQualityError && err.kind === 'config') {
834
+ ctx.ui.notify(
835
+ [
836
+ String(err.message),
837
+ 'Either create sonar-project.properties with sonar.projectKey and sonar.organization,',
838
+ 'or set SONAR_PROJECT_KEY and SONAR_ORGANIZATION env vars.',
839
+ ].join(' '),
840
+ 'error',
841
+ )
842
+ return
843
+ }
844
+ ctx.ui.notify(String((err as Error).message), 'error')
845
+ return
846
+ }
847
+
848
+ ctx.ui.setStatus('pr-quality', undefined)
849
+ adhocBeginMain('pr-quality', `PR ${result.prNumber}`, true)
850
+ pi.sendUserMessage(result.prompt)
851
+ },
852
+ })
853
+
854
+ // AIDEV-NOTE: Agent-callable surface — prompt text comes back in content,
855
+ // compact structured numbers in details. CI-pending becomes an isError
856
+ // result instead of a notify. Shares gatherPrQualityData with the command
857
+ // so there is one implementation.
858
+ pi.registerTool({
859
+ name: 'pr_quality',
860
+ label: 'PR quality triage',
861
+ description:
862
+ 'Gather unresolved GitHub PR review threads plus SonarCloud coverage/issues for a PR and return a structured triage prompt for the agent to act on.',
863
+ promptSnippet:
864
+ 'PR quality triage data: unresolved review threads, SonarCloud coverage and issues, with a step-by-step triage prompt.',
865
+ parameters: Type.Object({
866
+ pr_number: Type.Optional(
867
+ Type.String({
868
+ description:
869
+ 'PR number to analyze. Omit to auto-detect from the current branch via gh.',
870
+ }),
871
+ ),
872
+ }),
873
+ async execute(
874
+ _toolCallId: string,
875
+ params: { pr_number?: string },
876
+ signal: AbortSignal,
877
+ _onUpdate: unknown,
878
+ ctx: ExtensionToolContext,
879
+ ): Promise<AgentToolResult<PrQualityDetails | undefined>> {
880
+ try {
881
+ const result = await gatherPrQualityData({
882
+ cwd: ctx.cwd,
883
+ prNumber: params.pr_number,
884
+ signal,
885
+ })
886
+ return {
887
+ content: [{ type: 'text', text: result.prompt }],
888
+ details: result.details,
889
+ }
890
+ } catch (err) {
891
+ let text: string
892
+ if (err instanceof PrQualityError && err.kind === 'ci-pending') {
893
+ text = `pr_quality: ${err.message}. Re-run when all checks complete.`
894
+ } else {
895
+ text = `pr_quality failed: ${(err as Error).message}`
896
+ }
897
+ // AIDEV-NOTE: isError results omit details — a zeroed payload would
898
+ // fabricate data the analysis never produced. The error text is
899
+ // authoritative. Same rule in sonarqube.ts and review/review.ts.
900
+ return {
901
+ content: [{ type: 'text', text }],
902
+ details: undefined,
903
+ isError: true,
904
+ }
905
+ }
906
+ },
907
+ })
908
+ }