@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,821 @@
1
+ /**
2
+ * SonarQube Analysis Extension
3
+ *
4
+ * Provides a `/sonarqube` command that fetches SonarCloud coverage gaps and
5
+ * quality issues for a PR, then generates an actionable report.
6
+ *
7
+ * Rewrite of salaryhero/opencode/bin/sonar-* scripts as a pi extension.
8
+ * Analysis-only — no code changes.
9
+ *
10
+ * Usage:
11
+ * /sonarqube — auto-detect PR from current branch + config from sonar-project.properties
12
+ * /sonarqube 283 — explicit PR number
13
+ * /sonarqube 283 --severity=BLOCKER,CRITICAL
14
+ * /sonarqube 283 --types=BUG,VULNERABILITY
15
+ */
16
+
17
+ import { promises as fs } from 'node:fs'
18
+ import path from 'node:path'
19
+ import type {
20
+ AgentToolResult,
21
+ ExtensionAPI,
22
+ ExtensionToolContext,
23
+ } from '@earendil-works/pi-coding-agent'
24
+ import { Type } from 'typebox'
25
+ import {
26
+ analyzeCoverage,
27
+ analyzeIssues,
28
+ type CoverageAnalysis,
29
+ type CoverageMeasure,
30
+ type CoverageResponse,
31
+ detectPrNumber,
32
+ detectSonarConfig,
33
+ type FilterOptions,
34
+ fetchAllIssues,
35
+ type IssuesAnalysis,
36
+ type SonarConfig,
37
+ type SonarIssue,
38
+ sonarFetch,
39
+ TYPE_SYMBOLS,
40
+ } from '../shared/sonarqube-utils.ts'
41
+
42
+ // ── Duplication types ────────────────────────────────────────────────────────
43
+
44
+ interface DuplicationBlock {
45
+ from: number
46
+ size: number
47
+ _ref: string
48
+ }
49
+
50
+ interface DuplicationEntry {
51
+ blocks: DuplicationBlock[]
52
+ }
53
+
54
+ interface DuplicationFile {
55
+ key: string
56
+ name: string
57
+ projectName?: string
58
+ }
59
+
60
+ interface DuplicationsShowResponse {
61
+ duplications: DuplicationEntry[]
62
+ files: Record<string, DuplicationFile>
63
+ }
64
+
65
+ interface ComponentMeasure {
66
+ key: string
67
+ name: string
68
+ qualifier: string
69
+ measures: Array<{ metric: string; value?: string }>
70
+ }
71
+
72
+ interface ComponentTreeResponse {
73
+ components: ComponentMeasure[]
74
+ paging: { pageIndex: number; pageSize: number; total: number }
75
+ }
76
+
77
+ interface DuplicatedFileDetail {
78
+ file: string
79
+ key: string
80
+ density: number
81
+ blocks: number
82
+ duplicatedLines: number
83
+ duplicationGroups?: Array<{
84
+ blocks: Array<{ from: number; size: number; file: string }>
85
+ }>
86
+ }
87
+
88
+ interface DuplicationAnalysis {
89
+ density: number
90
+ duplicatedLines: number
91
+ duplicatedBlocks: number
92
+ duplicatedFiles: number
93
+ status: string
94
+ icon: string
95
+ topFiles: DuplicatedFileDetail[]
96
+ }
97
+
98
+ // ── Duplication fetching & analysis ─────────────────────────────────────────
99
+
100
+ // AIDEV-NOTE: component_tree supports the `pullRequest` param so we scope results
101
+ // to the PR diff. Falls back gracefully if the API returns no duplication data.
102
+ async function fetchDuplicatedFiles(
103
+ baseUrl: string,
104
+ token: string,
105
+ projectKey: string,
106
+ prNumber: string,
107
+ signal?: AbortSignal,
108
+ ): Promise<DuplicatedFileDetail[]> {
109
+ const data = (await sonarFetch(
110
+ baseUrl,
111
+ token,
112
+ 'measures/component_tree',
113
+ {
114
+ component: projectKey,
115
+ pullRequest: prNumber,
116
+ metricKeys: 'duplicated_lines_density,duplicated_blocks,duplicated_lines',
117
+ qualifiers: 'FIL',
118
+ s: 'metric',
119
+ metricSort: 'duplicated_lines_density',
120
+ asc: 'false',
121
+ ps: '20',
122
+ },
123
+ signal,
124
+ )) as ComponentTreeResponse
125
+
126
+ return (data.components ?? [])
127
+ .map((c) => {
128
+ const getMeasure = (metric: string) =>
129
+ parseFloat(c.measures.find((m) => m.metric === metric)?.value ?? '0') ||
130
+ 0
131
+ return {
132
+ file: c.key.split(':')[1] || c.key,
133
+ key: c.key,
134
+ density: getMeasure('duplicated_lines_density'),
135
+ blocks: getMeasure('duplicated_blocks'),
136
+ duplicatedLines: getMeasure('duplicated_lines'),
137
+ }
138
+ })
139
+ .filter((f) => f.density > 0)
140
+ }
141
+
142
+ async function fetchDuplicationDetails(
143
+ baseUrl: string,
144
+ token: string,
145
+ fileKey: string,
146
+ prNumber: string,
147
+ signal?: AbortSignal,
148
+ ): Promise<DuplicationsShowResponse | null> {
149
+ try {
150
+ return (await sonarFetch(
151
+ baseUrl,
152
+ token,
153
+ 'duplications/show',
154
+ { key: fileKey, pullRequest: prNumber },
155
+ signal,
156
+ )) as DuplicationsShowResponse
157
+ } catch {
158
+ // Per-file detail is best-effort — don't fail the whole report
159
+ return null
160
+ }
161
+ }
162
+
163
+ function analyzeDuplications(
164
+ coverageMeasures: CoverageMeasure[],
165
+ topFiles: DuplicatedFileDetail[],
166
+ ): DuplicationAnalysis {
167
+ const getMetric = (metric: string): number => {
168
+ const m = coverageMeasures.find((m) => m.metric === metric)
169
+ if (!m) return 0
170
+ if (m.periods && m.periods.length > 0)
171
+ return parseFloat(m.periods[0].value) || 0
172
+ return parseFloat(m.value ?? '0') || 0
173
+ }
174
+
175
+ const density = getMetric('duplicated_lines_density')
176
+ const duplicatedLines = Math.round(getMetric('duplicated_lines'))
177
+ const duplicatedBlocks = Math.round(getMetric('duplicated_blocks'))
178
+ const duplicatedFiles = Math.round(getMetric('duplicated_files'))
179
+
180
+ let status: 'PASS' | 'WARN' | 'FAIL'
181
+ let icon: string
182
+ if (density <= 3) {
183
+ status = 'PASS'
184
+ icon = '✅'
185
+ } else if (density <= 10) {
186
+ status = 'WARN'
187
+ icon = '⚠️'
188
+ } else {
189
+ status = 'FAIL'
190
+ icon = '❌'
191
+ }
192
+
193
+ return {
194
+ density,
195
+ duplicatedLines,
196
+ duplicatedBlocks,
197
+ duplicatedFiles,
198
+ status,
199
+ icon,
200
+ topFiles,
201
+ }
202
+ }
203
+
204
+ // ── Arg parsing ───────────────────────────────────────────────────────────────
205
+
206
+ function parseArgs(args: string): {
207
+ prNumber?: string
208
+ filter?: FilterOptions
209
+ } {
210
+ if (!args.trim()) return {}
211
+
212
+ const parts = args.trim().split(/\s+/)
213
+ let prNumber: string | undefined
214
+ const filter: FilterOptions = {}
215
+
216
+ for (const part of parts) {
217
+ if (/^\d+$/.test(part)) {
218
+ prNumber = part
219
+ } else if (part.startsWith('--severity=')) {
220
+ filter.severity = part.split('=')[1].split(',')
221
+ } else if (part.startsWith('--types=')) {
222
+ filter.types = part.split('=')[1].split(',')
223
+ } else if (part.startsWith('--files=')) {
224
+ filter.files = part.split('=')[1]
225
+ }
226
+ }
227
+
228
+ let filterArg: typeof filter | undefined
229
+ if (Object.keys(filter).length > 0) {
230
+ filterArg = filter
231
+ } else {
232
+ filterArg = undefined
233
+ }
234
+ return {
235
+ prNumber,
236
+ filter: filterArg,
237
+ }
238
+ }
239
+
240
+ // ── Report generation ─────────────────────────────────────────────────────────
241
+
242
+ function generateDuplicationSection(dup: DuplicationAnalysis): string[] {
243
+ const lines: string[] = []
244
+ const sep = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'
245
+
246
+ lines.push(sep)
247
+ lines.push('🔁 CODE DUPLICATION REPORT')
248
+ lines.push(sep)
249
+ lines.push('')
250
+ lines.push(`Duplication Density: ${dup.density.toFixed(1)}% ${dup.icon}`)
251
+ lines.push(`Duplicated Lines: ${dup.duplicatedLines}`)
252
+ lines.push(`Duplicated Blocks: ${dup.duplicatedBlocks}`)
253
+ lines.push(`Duplicated Files: ${dup.duplicatedFiles}`)
254
+ lines.push('')
255
+ lines.push('Threshold: ≤3% PASS | ≤10% WARN | >10% FAIL')
256
+ lines.push('')
257
+
258
+ if (dup.topFiles.length > 0) {
259
+ lines.push('📂 Most Duplicated Files:')
260
+ lines.push('')
261
+ dup.topFiles.slice(0, 10).forEach((f, i) => {
262
+ lines.push(`${i + 1}. ${f.file}`)
263
+ lines.push(
264
+ ` Density: ${f.density.toFixed(1)}% Blocks: ${f.blocks} Lines: ${f.duplicatedLines}`,
265
+ )
266
+ if (f.duplicationGroups && f.duplicationGroups.length > 0) {
267
+ f.duplicationGroups.slice(0, 3).forEach((g, gi) => {
268
+ lines.push(` Group ${gi + 1}:`)
269
+ g.blocks.forEach((b) => {
270
+ let location: string
271
+ if (b.file !== f.file) {
272
+ location = ` (in ${b.file})`
273
+ } else {
274
+ location = ''
275
+ }
276
+ lines.push(
277
+ ` • Lines ${b.from}–${b.from + b.size - 1} [${b.size} lines]${location}`,
278
+ )
279
+ })
280
+ })
281
+ }
282
+ lines.push('')
283
+ })
284
+ } else {
285
+ lines.push('No duplicated files detected in this PR. ✅')
286
+ lines.push('')
287
+ }
288
+
289
+ return lines
290
+ }
291
+
292
+ function generateReport(
293
+ prNumber: string,
294
+ config: SonarConfig,
295
+ coverage: CoverageAnalysis,
296
+ issues: IssuesAnalysis,
297
+ duplication?: DuplicationAnalysis,
298
+ ): string {
299
+ const lines: string[] = []
300
+ const sep = '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'
301
+
302
+ // Header
303
+ lines.push(`📊 SonarCloud Analysis — PR #${prNumber}`)
304
+ lines.push('')
305
+ lines.push(sep)
306
+ lines.push('📈 COVERAGE REPORT')
307
+ lines.push(sep)
308
+ lines.push('')
309
+
310
+ // Coverage metrics
311
+ lines.push(
312
+ `Overall Line Coverage: ${coverage.overallCoverage}% ${coverage.icons.overall}`,
313
+ )
314
+ lines.push(
315
+ `New Code Coverage: ${coverage.newCoverage}% ${coverage.icons.newCode}`,
316
+ )
317
+ lines.push(
318
+ `Branch Coverage: ${coverage.branchCoverage}% ${coverage.icons.branch}`,
319
+ )
320
+ lines.push(
321
+ `New Branch Coverage: ${coverage.newBranchCoverage}% ${coverage.icons.newBranch}`,
322
+ )
323
+ lines.push('')
324
+ lines.push(
325
+ `Uncovered Lines: ${coverage.uncoveredLines} / ${coverage.linesToCover}`,
326
+ )
327
+ lines.push('')
328
+ lines.push('Coverage Thresholds (80% minimum):')
329
+ const fmtGap = (gap: number): string => {
330
+ if (gap > 0) {
331
+ return `${gap}% to target`
332
+ }
333
+ return 'meets threshold'
334
+ }
335
+ lines.push(
336
+ `${coverage.icons.overall} Overall: ${fmtGap(coverage.gaps.overall)}`,
337
+ )
338
+ lines.push(
339
+ `${coverage.icons.newCode} New Code: ${fmtGap(coverage.gaps.newCode)}`,
340
+ )
341
+ lines.push(`${coverage.icons.branch} Branch: ${fmtGap(coverage.gaps.branch)}`)
342
+ lines.push(
343
+ `${coverage.icons.newBranch} New Branch: ${fmtGap(coverage.gaps.newBranch)}`,
344
+ )
345
+ lines.push('')
346
+
347
+ // Duplication section (after coverage metrics)
348
+ if (duplication) {
349
+ lines.push(...generateDuplicationSection(duplication))
350
+ }
351
+
352
+ // Low-coverage files from issues
353
+ const lowCoverageFiles = issues.byFile.slice(0, 5)
354
+ if (lowCoverageFiles.length > 0) {
355
+ lines.push(sep)
356
+ lines.push('🔴 FILES NEEDING ATTENTION')
357
+ lines.push(sep)
358
+ lines.push('')
359
+ lowCoverageFiles.forEach((f, i) => {
360
+ lines.push(`${i + 1}. ${f.file} — ${f.count} issues`)
361
+ })
362
+ lines.push('')
363
+ }
364
+
365
+ // Quality issues summary
366
+ lines.push(sep)
367
+ lines.push('⚠️ QUALITY ISSUES SUMMARY')
368
+ lines.push(sep)
369
+ lines.push('')
370
+
371
+ lines.push(`Total Issues: ${issues.total}`)
372
+ lines.push('')
373
+
374
+ // By severity
375
+ lines.push('By Severity:')
376
+ const blockCrit =
377
+ (issues.bySeverity.BLOCKER || 0) + (issues.bySeverity.CRITICAL || 0)
378
+ const major = issues.bySeverity.MAJOR || 0
379
+ const minorInfo =
380
+ (issues.bySeverity.MINOR || 0) + (issues.bySeverity.INFO || 0)
381
+ lines.push(`🔴 Blocker/Critical: ${blockCrit}`)
382
+ lines.push(`🟡 Major: ${major}`)
383
+ lines.push(`🔵 Minor/Info: ${minorInfo}`)
384
+ lines.push('')
385
+
386
+ // By type
387
+ lines.push('By Type:')
388
+ for (const [type, count] of Object.entries(issues.byType)) {
389
+ lines.push(`${TYPE_SYMBOLS[type] || '❓'} ${type}: ${count}`)
390
+ }
391
+ lines.push('')
392
+
393
+ // Top files
394
+ if (issues.byFile.length > 0) {
395
+ lines.push(sep)
396
+ lines.push('📂 TOP FILES WITH ISSUES')
397
+ lines.push(sep)
398
+ lines.push('')
399
+ issues.byFile.slice(0, 10).forEach((f, i) => {
400
+ lines.push(`${i + 1}. ${f.file} — ${f.count} issues`)
401
+ })
402
+ lines.push('')
403
+ }
404
+
405
+ // Top rules
406
+ if (issues.byRule.length > 0) {
407
+ lines.push(sep)
408
+ lines.push('⚠️ TOP VIOLATED RULES')
409
+ lines.push(sep)
410
+ lines.push('')
411
+ issues.byRule.forEach((r, i) => {
412
+ lines.push(`${i + 1}. ${r.rule} (${r.severity}) — ${r.count} occurrences`)
413
+ lines.push(` "${r.message}"`)
414
+ lines.push('')
415
+ })
416
+ }
417
+
418
+ // Action plan
419
+ lines.push(sep)
420
+ lines.push('✅ ACTION PLAN')
421
+ lines.push(sep)
422
+ lines.push('')
423
+
424
+ if (coverage.gaps.overall > 0 || coverage.gaps.newCode > 0) {
425
+ const lowCovFiles = issues.byFile
426
+ .slice(0, 5)
427
+ .map((f) => f.file)
428
+ .join(', ')
429
+ lines.push('Priority 0 — COVERAGE GAPS:')
430
+ if (lowCovFiles)
431
+ lines.push(` • Add tests for low-coverage files: ${lowCovFiles}`)
432
+ lines.push(' • Minimum 80% coverage required before merge')
433
+ lines.push('')
434
+ }
435
+
436
+ if (blockCrit > 0) {
437
+ const topFiles = issues.byFile
438
+ .slice(0, 3)
439
+ .map((f) => f.file)
440
+ .join(', ')
441
+ lines.push(`Priority 1 — CRITICAL/BLOCKER (${blockCrit} issues):`)
442
+ lines.push(' • Fix immediately before merge')
443
+ if (topFiles) lines.push(` • Focus on: ${topFiles}`)
444
+ lines.push('')
445
+ }
446
+
447
+ if (major > 0) {
448
+ lines.push(`Priority 2 — MAJOR (${major} issues):`)
449
+ lines.push(' • Address in this PR if possible')
450
+ lines.push(' • Consider tech debt ticket if extensive')
451
+ lines.push('')
452
+ }
453
+
454
+ if (minorInfo > 0) {
455
+ lines.push(`Priority 3 — MINOR/INFO (${minorInfo} issues):`)
456
+ lines.push(' • Can be addressed in follow-up PR')
457
+ lines.push(' • Add to backlog for refactoring sprint')
458
+ lines.push('')
459
+ }
460
+
461
+ // Links
462
+ lines.push(sep)
463
+ lines.push('🔗 LINKS')
464
+ lines.push(sep)
465
+ lines.push('')
466
+ lines.push('View in SonarCloud:')
467
+ lines.push(
468
+ `https://sonarcloud.io/project/pull_requests_list?id=${config.projectKey}&pullRequest=${prNumber}`,
469
+ )
470
+
471
+ return lines.join('\n')
472
+ }
473
+
474
+ // ── Shared analysis core ──────────────────────────────────────────────────────
475
+
476
+ export type SonarAnalysisErrorKind =
477
+ | 'token'
478
+ | 'config'
479
+ | 'pr'
480
+ | 'coverage'
481
+ | 'issues'
482
+
483
+ // AIDEV-NOTE: Classified failure so the /sonarqube command and the sonarqube
484
+ // tool can map the same error to their own surfaces (notify vs isError result).
485
+ export class SonarAnalysisError extends Error {
486
+ kind: SonarAnalysisErrorKind
487
+ cause?: Error
488
+
489
+ constructor(kind: SonarAnalysisErrorKind, message: string, cause?: Error) {
490
+ super(message)
491
+ this.kind = kind
492
+ this.cause = cause
493
+ }
494
+ }
495
+
496
+ export interface SonarAnalysisOptions {
497
+ cwd: string
498
+ prNumber?: string
499
+ filter?: FilterOptions
500
+ signal?: AbortSignal
501
+ // AIDEV-NOTE: progress feed so the command keeps its original notify
502
+ // updates; the tool leaves it unset.
503
+ onProgress?: (message: string) => void
504
+ }
505
+
506
+ // Structured summary for the tool's `details` field — report text stays the
507
+ // single source of truth for humans.
508
+ export interface SonarAnalysisDetails {
509
+ prNumber: string
510
+ projectKey: string
511
+ organization: string
512
+ coverageOverall: number
513
+ coverageNewCode: number
514
+ issuesTotal: number
515
+ duplicationDensity?: number
516
+ duplicationStatus?: string
517
+ }
518
+
519
+ export interface SonarAnalysisResult {
520
+ report: string
521
+ prNumber: string
522
+ config: SonarConfig
523
+ coverage: CoverageAnalysis
524
+ issues: IssuesAnalysis
525
+ duplication?: DuplicationAnalysis
526
+ details: SonarAnalysisDetails
527
+ }
528
+
529
+ // AIDEV-NOTE: Shared core extracted from the /sonarqube command handler. Does
530
+ // NOT write sonarqube-report.md — the command caller keeps that behavior; the
531
+ // sonarqube tool returns content + details instead. Errors are classified via
532
+ // SonarAnalysisError.kind so each caller maps them to its own surface.
533
+ export async function runSonarAnalysis(
534
+ options: SonarAnalysisOptions,
535
+ ): Promise<SonarAnalysisResult> {
536
+ const { cwd, filter, signal, onProgress } = options
537
+ const token = process.env.SONARQUBE_TOKEN
538
+ if (!token) {
539
+ throw new SonarAnalysisError(
540
+ 'token',
541
+ 'SONARQUBE_TOKEN not set. Run: export SONARQUBE_TOKEN=your_token',
542
+ )
543
+ }
544
+
545
+ let config: SonarConfig
546
+ try {
547
+ config = await detectSonarConfig(cwd)
548
+ } catch (err) {
549
+ throw new SonarAnalysisError('config', String((err as Error).message))
550
+ }
551
+
552
+ let prNumber: string
553
+ if (options.prNumber) {
554
+ prNumber = options.prNumber
555
+ } else {
556
+ try {
557
+ prNumber = await detectPrNumber('/sonarqube')
558
+ } catch (err) {
559
+ throw new SonarAnalysisError(
560
+ 'pr',
561
+ String((err as Error).message),
562
+ err as Error,
563
+ )
564
+ }
565
+ }
566
+
567
+ if (onProgress) {
568
+ onProgress(`Analyzing PR #${prNumber}...`)
569
+ }
570
+
571
+ let coverageData: CoverageResponse
572
+ try {
573
+ coverageData = (await sonarFetch(
574
+ config.baseUrl,
575
+ token,
576
+ 'measures/component',
577
+ {
578
+ component: config.projectKey,
579
+ pullRequest: prNumber,
580
+ metricKeys:
581
+ 'coverage,new_coverage,new_line_coverage,uncovered_lines,lines_to_cover,branch_coverage,new_branch_coverage,new_lines_to_cover',
582
+ },
583
+ signal,
584
+ )) as CoverageResponse
585
+ } catch (err) {
586
+ throw new SonarAnalysisError(
587
+ 'coverage',
588
+ `Coverage fetch failed: ${(err as Error).message}`,
589
+ )
590
+ }
591
+
592
+ let allIssues: SonarIssue[]
593
+ let total: number
594
+ try {
595
+ ;({ issues: allIssues, total } = await fetchAllIssues(
596
+ config.baseUrl,
597
+ token,
598
+ config.projectKey,
599
+ prNumber,
600
+ signal,
601
+ ))
602
+ } catch (err) {
603
+ throw new SonarAnalysisError(
604
+ 'issues',
605
+ `Issues fetch failed: ${(err as Error).message}`,
606
+ )
607
+ }
608
+
609
+ const coverage = analyzeCoverage(coverageData)
610
+ const issues = analyzeIssues({ total, issues: allIssues }, filter)
611
+
612
+ let duplication: DuplicationAnalysis | undefined
613
+ if (onProgress) {
614
+ onProgress('Fetching duplication data...')
615
+ }
616
+ try {
617
+ const dupMeasuresData = (await sonarFetch(
618
+ config.baseUrl,
619
+ token,
620
+ 'measures/component',
621
+ {
622
+ component: config.projectKey,
623
+ pullRequest: prNumber,
624
+ metricKeys:
625
+ 'duplicated_lines_density,duplicated_lines,duplicated_blocks,duplicated_files',
626
+ },
627
+ signal,
628
+ )) as CoverageResponse
629
+
630
+ const topFiles = await fetchDuplicatedFiles(
631
+ config.baseUrl,
632
+ token,
633
+ config.projectKey,
634
+ prNumber,
635
+ signal,
636
+ )
637
+
638
+ const TOP_N = 5
639
+ for (const fileDetail of topFiles.slice(0, TOP_N)) {
640
+ const details = await fetchDuplicationDetails(
641
+ config.baseUrl,
642
+ token,
643
+ fileDetail.key,
644
+ prNumber,
645
+ signal,
646
+ )
647
+ if (details) {
648
+ fileDetail.duplicationGroups = details.duplications.map((d) => ({
649
+ blocks: d.blocks.map((b) => ({
650
+ from: b.from,
651
+ size: b.size,
652
+ file:
653
+ details.files[b._ref]?.key.split(':')[1] ||
654
+ details.files[b._ref]?.key ||
655
+ fileDetail.file,
656
+ })),
657
+ }))
658
+ }
659
+ }
660
+
661
+ duplication = analyzeDuplications(
662
+ dupMeasuresData.component?.measures ?? [],
663
+ topFiles,
664
+ )
665
+ } catch (err) {
666
+ // AIDEV-NOTE: Duplication fetch is non-fatal — report still generated
667
+ // without it. The command's "Duplication fetch skipped" info notify is
668
+ // preserved via onProgress so the human surface matches main.
669
+ if (onProgress) {
670
+ onProgress(`Duplication fetch skipped: ${(err as Error).message}`)
671
+ }
672
+ }
673
+
674
+ const report = generateReport(prNumber, config, coverage, issues, duplication)
675
+
676
+ let analysisDetails: SonarAnalysisDetails = {
677
+ prNumber,
678
+ projectKey: config.projectKey,
679
+ organization: config.organization,
680
+ coverageOverall: coverage.overallCoverage,
681
+ coverageNewCode: coverage.newCoverage,
682
+ issuesTotal: issues.total,
683
+ }
684
+ if (duplication) {
685
+ analysisDetails = {
686
+ ...analysisDetails,
687
+ duplicationDensity: duplication.density,
688
+ duplicationStatus: duplication.status,
689
+ }
690
+ }
691
+
692
+ return {
693
+ report,
694
+ prNumber,
695
+ config,
696
+ coverage,
697
+ issues,
698
+ duplication,
699
+ details: analysisDetails,
700
+ }
701
+ }
702
+
703
+ // ── Extension ─────────────────────────────────────────────────────────────────
704
+
705
+ // AIDEV-NOTE: Human surface (/sonarqube command) — keeps the original behavior:
706
+ // notify progress, write sonarqube-report.md to cwd, send report as user message.
707
+ export default function sonarqube(pi: ExtensionAPI) {
708
+ pi.registerCommand('sonarqube', {
709
+ description: 'Analyze SonarCloud coverage gaps and quality issues for a PR',
710
+ handler: async (args, ctx) => {
711
+ const parsed = parseArgs(args)
712
+
713
+ let result: SonarAnalysisResult
714
+ try {
715
+ result = await runSonarAnalysis({
716
+ cwd: ctx.cwd,
717
+ prNumber: parsed.prNumber,
718
+ filter: parsed.filter,
719
+ signal: ctx.signal,
720
+ onProgress: (message) => {
721
+ ctx.ui.notify(message, 'info')
722
+ },
723
+ })
724
+ } catch (err) {
725
+ ctx.ui.notify(String((err as Error).message), 'error')
726
+ return
727
+ }
728
+
729
+ const reportPath = path.join(ctx.cwd, 'sonarqube-report.md')
730
+ await fs.writeFile(reportPath, result.report, 'utf8')
731
+
732
+ ctx.ui.notify(
733
+ `Analysis complete: ${result.issues.total} issues, coverage ${result.coverage.overallCoverage}%. Report: ${reportPath}`,
734
+ 'info',
735
+ )
736
+
737
+ pi.sendUserMessage(result.report)
738
+ },
739
+ })
740
+
741
+ // AIDEV-NOTE: Agent-callable surface — never writes sonarqube-report.md;
742
+ // report text comes back in content, structured numbers in details. Shares
743
+ // runSonarAnalysis with the command so there is one implementation.
744
+ pi.registerTool({
745
+ name: 'sonarqube',
746
+ label: 'sonarqube analysis',
747
+ description:
748
+ 'Fetch SonarCloud coverage gaps and quality issues for a PR and return an actionable report. Does not write any files.',
749
+ promptSnippet:
750
+ 'SonarCloud coverage/issue analysis for a PR; returns the full report text and structured numbers.',
751
+ parameters: Type.Object({
752
+ pr_number: Type.Optional(
753
+ Type.String({
754
+ description:
755
+ 'PR number to analyze. Omit to auto-detect from the current branch via gh.',
756
+ }),
757
+ ),
758
+ severity: Type.Optional(
759
+ Type.Array(Type.String(), {
760
+ description:
761
+ 'Filter issues by severity, e.g. ["BLOCKER", "CRITICAL", "MAJOR", "MINOR", "INFO"]',
762
+ }),
763
+ ),
764
+ types: Type.Optional(
765
+ Type.Array(Type.String(), {
766
+ description:
767
+ 'Filter issues by type, e.g. ["BUG", "VULNERABILITY", "CODE_SMELL"]',
768
+ }),
769
+ ),
770
+ files: Type.Optional(
771
+ Type.String({ description: 'Filter issues by file path pattern' }),
772
+ ),
773
+ }),
774
+ async execute(
775
+ _toolCallId: string,
776
+ params: {
777
+ pr_number?: string
778
+ severity?: string[]
779
+ types?: string[]
780
+ files?: string
781
+ },
782
+ signal: AbortSignal,
783
+ _onUpdate: unknown,
784
+ ctx: ExtensionToolContext,
785
+ ): Promise<AgentToolResult<SonarAnalysisDetails | undefined>> {
786
+ let filter: FilterOptions | undefined
787
+ if (params.severity || params.types || params.files) {
788
+ filter = {
789
+ severity: params.severity,
790
+ types: params.types,
791
+ files: params.files,
792
+ }
793
+ }
794
+
795
+ try {
796
+ const result = await runSonarAnalysis({
797
+ cwd: ctx.cwd,
798
+ prNumber: params.pr_number,
799
+ filter,
800
+ signal,
801
+ })
802
+ return {
803
+ content: [{ type: 'text', text: result.report }],
804
+ details: result.details,
805
+ }
806
+ } catch (err) {
807
+ // AIDEV-NOTE: isError results omit details — see pr-quality/index.ts.
808
+ return {
809
+ content: [
810
+ {
811
+ type: 'text',
812
+ text: `sonarqube analysis failed: ${(err as Error).message}`,
813
+ },
814
+ ],
815
+ details: undefined,
816
+ isError: true,
817
+ }
818
+ }
819
+ },
820
+ })
821
+ }