@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,415 @@
1
+ /**
2
+ * Shared SonarQube/SonarCloud utilities.
3
+ *
4
+ * Used by both the sonarqube and pr-quality extensions.
5
+ * Keep this module pure (no pi API imports, no side effects).
6
+ */
7
+
8
+ import { execFile } from 'node:child_process'
9
+ import { promises as fs } from 'node:fs'
10
+ import path from 'node:path'
11
+ import { promisify } from 'node:util'
12
+
13
+ const execFileAsync = promisify(execFile)
14
+
15
+ // ── Shell exec helper ─────────────────────────────────────────────────────────
16
+
17
+ // AIDEV-NOTE: ExtensionCommandContext does not expose an exec helper, so we
18
+ // use node:child_process directly. Extensions run with full system permissions.
19
+ export async function localExec(
20
+ cmd: string,
21
+ args: string[],
22
+ opts?: { timeout?: number; cwd?: string },
23
+ ): Promise<{ code: number; stdout: string; stderr: string }> {
24
+ try {
25
+ const { stdout, stderr } = await execFileAsync(cmd, args, {
26
+ timeout: opts?.timeout,
27
+ cwd: opts?.cwd,
28
+ maxBuffer: 10 * 1024 * 1024, // 10 MB — GraphQL responses can be large
29
+ })
30
+ return { code: 0, stdout, stderr }
31
+ } catch (err: unknown) {
32
+ const e = err as { code?: number; stdout?: string; stderr?: string }
33
+ return { code: e.code ?? 1, stdout: e.stdout ?? '', stderr: e.stderr ?? '' }
34
+ }
35
+ }
36
+
37
+ // ── Types ─────────────────────────────────────────────────────────────────────
38
+
39
+ export interface CoverageMeasure {
40
+ metric: string
41
+ value?: string
42
+ periods?: Array<{ index: number; value: string }>
43
+ }
44
+
45
+ export interface CoverageResponse {
46
+ component?: {
47
+ measures: CoverageMeasure[]
48
+ }
49
+ }
50
+
51
+ export interface SonarIssue {
52
+ key: string
53
+ rule: string
54
+ severity: string
55
+ type: string
56
+ message: string
57
+ component: string
58
+ line?: number
59
+ textRange?: { startLine: number; endLine: number }
60
+ effort?: string
61
+ debt?: string
62
+ }
63
+
64
+ export interface IssuesResponse {
65
+ total?: number
66
+ issues: SonarIssue[]
67
+ p?: number
68
+ ps?: number
69
+ }
70
+
71
+ export interface CoverageAnalysis {
72
+ overallCoverage: number
73
+ newCoverage: number
74
+ branchCoverage: number
75
+ newBranchCoverage: number
76
+ uncoveredLines: number
77
+ linesToCover: number
78
+ gaps: { overall: number; newCode: number; branch: number; newBranch: number }
79
+ status: {
80
+ overall: string
81
+ newCode: string
82
+ branch: string
83
+ newBranch: string
84
+ }
85
+ icons: { overall: string; newCode: string; branch: string; newBranch: string }
86
+ }
87
+
88
+ export interface IssuesAnalysis {
89
+ total: number
90
+ bySeverity: Record<string, number>
91
+ byType: Record<string, number>
92
+ byFile: Array<{ file: string; count: number; issues: SonarIssue[] }>
93
+ byRule: Array<{
94
+ rule: string
95
+ count: number
96
+ severity: string
97
+ message: string
98
+ }>
99
+ issues: SonarIssue[]
100
+ }
101
+
102
+ export interface FilterOptions {
103
+ severity?: string[]
104
+ types?: string[]
105
+ files?: string
106
+ }
107
+
108
+ export interface SonarConfig {
109
+ projectKey: string
110
+ organization: string
111
+ baseUrl: string
112
+ }
113
+
114
+ // ── Severity helpers ──────────────────────────────────────────────────────────
115
+
116
+ export const SEVERITY_ORDER: Record<string, number> = {
117
+ BLOCKER: 0,
118
+ CRITICAL: 1,
119
+ MAJOR: 2,
120
+ MINOR: 3,
121
+ INFO: 4,
122
+ }
123
+
124
+ // AIDEV-NOTE: Emojis used intentionally here for terminal report readability (severity/type
125
+ // indicators in the generated sonarqube-report.md). Coding-standards "no emojis" rule applies
126
+ // to code comments and logic, not to user-facing report output.
127
+ export const SEVERITY_SYMBOLS: Record<string, string> = {
128
+ BLOCKER: '🔴',
129
+ CRITICAL: '🔴',
130
+ MAJOR: '🟡',
131
+ MINOR: '🔵',
132
+ INFO: '🔵',
133
+ }
134
+
135
+ export const TYPE_SYMBOLS: Record<string, string> = {
136
+ BUG: '🐛',
137
+ VULNERABILITY: '🛡️',
138
+ CODE_SMELL: '🧹',
139
+ SECURITY_HOTSPOT: '🔒',
140
+ }
141
+
142
+ // ── SonarCloud API ────────────────────────────────────────────────────────────
143
+
144
+ export async function sonarFetch(
145
+ baseUrl: string,
146
+ token: string,
147
+ endpoint: string,
148
+ params: Record<string, string>,
149
+ signal?: AbortSignal,
150
+ ): Promise<unknown> {
151
+ let base: string
152
+ if (baseUrl.endsWith('/')) {
153
+ base = baseUrl
154
+ } else {
155
+ base = `${baseUrl}/`
156
+ }
157
+ const url = new URL(endpoint, base)
158
+ for (const [k, v] of Object.entries(params)) {
159
+ url.searchParams.set(k, v)
160
+ }
161
+
162
+ const resp = await fetch(url.toString(), {
163
+ headers: {
164
+ Authorization: `Basic ${Buffer.from(`${token}:`).toString('base64')}`,
165
+ },
166
+ signal,
167
+ })
168
+
169
+ if (!resp.ok) {
170
+ const body = await resp.text().catch(() => '')
171
+ let bodySnippet: string
172
+ if (body) {
173
+ bodySnippet = ` — ${body.slice(0, 200)}`
174
+ } else {
175
+ bodySnippet = ''
176
+ }
177
+ throw new Error(
178
+ `SonarCloud API ${resp.status}: ${resp.statusText}${bodySnippet}`,
179
+ )
180
+ }
181
+
182
+ return resp.json()
183
+ }
184
+
185
+ // ── Coverage analysis ─────────────────────────────────────────────────────────
186
+
187
+ export function statusIcon(val: number, threshold = 80): string {
188
+ if (val >= threshold) return '✅'
189
+ if (val >= threshold - 10) return '⚠️'
190
+ return '❌'
191
+ }
192
+
193
+ export function analyzeCoverage(data: CoverageResponse): CoverageAnalysis {
194
+ const measures = data.component?.measures ?? []
195
+ const metrics: Record<string, number> = {}
196
+
197
+ for (const m of measures) {
198
+ if (m.periods && m.periods.length > 0) {
199
+ metrics[m.metric] = parseFloat(m.periods[0].value) || 0
200
+ } else if (m.value !== undefined) {
201
+ metrics[m.metric] = parseFloat(m.value) || 0
202
+ }
203
+ }
204
+
205
+ const overallCoverage = metrics.coverage || 0
206
+ const newCoverage = metrics.new_coverage || metrics.new_line_coverage || 0
207
+ const branchCoverage = metrics.branch_coverage || 0
208
+ const newBranchCoverage = metrics.new_branch_coverage || 0
209
+ const uncoveredLines = Math.round(metrics.uncovered_lines || 0)
210
+ const linesToCover = Math.round(metrics.lines_to_cover || 0)
211
+
212
+ const passOrFail = (v: number): 'PASS' | 'FAIL' => {
213
+ if (v >= 80) {
214
+ return 'PASS'
215
+ }
216
+ return 'FAIL'
217
+ }
218
+ const overallStatus = passOrFail(overallCoverage)
219
+ const newCodeStatus = passOrFail(newCoverage)
220
+ const branchStatus = passOrFail(branchCoverage)
221
+ const newBranchStatus = passOrFail(newBranchCoverage)
222
+
223
+ return {
224
+ overallCoverage,
225
+ newCoverage,
226
+ branchCoverage,
227
+ newBranchCoverage,
228
+ uncoveredLines,
229
+ linesToCover,
230
+ gaps: {
231
+ overall: Math.max(0, 80 - overallCoverage),
232
+ newCode: Math.max(0, 80 - newCoverage),
233
+ branch: Math.max(0, 80 - branchCoverage),
234
+ newBranch: Math.max(0, 80 - newBranchCoverage),
235
+ },
236
+ status: {
237
+ overall: overallStatus,
238
+ newCode: newCodeStatus,
239
+ branch: branchStatus,
240
+ newBranch: newBranchStatus,
241
+ },
242
+ icons: {
243
+ overall: statusIcon(overallCoverage),
244
+ newCode: statusIcon(newCoverage),
245
+ branch: statusIcon(branchCoverage),
246
+ newBranch: statusIcon(newBranchCoverage),
247
+ },
248
+ }
249
+ }
250
+
251
+ // ── Issues analysis ───────────────────────────────────────────────────────────
252
+
253
+ export function analyzeIssues(
254
+ data: IssuesResponse,
255
+ filter?: FilterOptions,
256
+ ): IssuesAnalysis {
257
+ let issues = data.issues ?? []
258
+
259
+ if (filter?.severity?.length) {
260
+ issues = issues.filter((i) => filter.severity?.includes(i.severity))
261
+ }
262
+ if (filter?.types?.length) {
263
+ issues = issues.filter((i) => filter.types?.includes(i.type))
264
+ }
265
+ if (filter?.files) {
266
+ const pattern = new RegExp(filter.files.replace(/\*/g, '.*'))
267
+ issues = issues.filter((i) => {
268
+ const file = i.component.split(':')[1] || i.component
269
+ return pattern.test(file)
270
+ })
271
+ }
272
+
273
+ const bySeverity: Record<string, number> = {}
274
+ const byType: Record<string, number> = {}
275
+
276
+ for (const i of issues) {
277
+ bySeverity[i.severity] = (bySeverity[i.severity] || 0) + 1
278
+ byType[i.type] = (byType[i.type] || 0) + 1
279
+ }
280
+
281
+ const byFileMap: Record<string, { count: number; issues: SonarIssue[] }> = {}
282
+ for (const i of issues) {
283
+ const file = i.component.split(':')[1] || i.component
284
+ if (!byFileMap[file]) byFileMap[file] = { count: 0, issues: [] }
285
+ byFileMap[file].count++
286
+ byFileMap[file].issues.push(i)
287
+ }
288
+
289
+ const byRuleMap: Record<
290
+ string,
291
+ { count: number; severity: string; message: string }
292
+ > = {}
293
+ for (const i of issues) {
294
+ if (!byRuleMap[i.rule]) {
295
+ byRuleMap[i.rule] = { count: 0, severity: i.severity, message: i.message }
296
+ }
297
+ byRuleMap[i.rule].count++
298
+ }
299
+
300
+ return {
301
+ total: issues.length,
302
+ bySeverity,
303
+ byType,
304
+ byFile: Object.entries(byFileMap)
305
+ .sort(([, a], [, b]) => b.count - a.count)
306
+ .slice(0, 10)
307
+ .map(([file, d]) => ({ file, count: d.count, issues: d.issues })),
308
+ byRule: Object.entries(byRuleMap)
309
+ .map(([rule, d]) => ({ rule, ...d }))
310
+ .sort((a, b) => b.count - a.count)
311
+ .slice(0, 5),
312
+ issues: [...issues].sort(
313
+ (a, b) =>
314
+ (SEVERITY_ORDER[a.severity] ?? 9) - (SEVERITY_ORDER[b.severity] ?? 9),
315
+ ),
316
+ }
317
+ }
318
+
319
+ // ── Config detection ──────────────────────────────────────────────────────────
320
+
321
+ export async function detectSonarConfig(cwd: string): Promise<SonarConfig> {
322
+ const propPath = path.join(cwd, 'sonar-project.properties')
323
+
324
+ try {
325
+ const content = await fs.readFile(propPath, 'utf8')
326
+ const getProp = (key: string): string | undefined => {
327
+ const line = content
328
+ .split('\n')
329
+ .find((l) => l.startsWith(`sonar.${key}=`))
330
+ return line?.split('=').slice(1).join('=').trim()
331
+ }
332
+
333
+ const projectKey = getProp('projectKey')
334
+ const organization = getProp('organization')
335
+
336
+ if (projectKey && organization) {
337
+ return { projectKey, organization, baseUrl: 'https://sonarcloud.io/api' }
338
+ }
339
+ } catch {
340
+ // No properties file — fall through
341
+ }
342
+
343
+ const envProjectKey = process.env.SONAR_PROJECT_KEY
344
+ const envOrg = process.env.SONAR_ORGANIZATION
345
+ if (envProjectKey && envOrg) {
346
+ return {
347
+ projectKey: envProjectKey,
348
+ organization: envOrg,
349
+ baseUrl: process.env.SONAR_BASE_URL || 'https://sonarcloud.io/api',
350
+ }
351
+ }
352
+
353
+ throw new Error(
354
+ 'No SonarCloud config found. Create sonar-project.properties or set SONAR_PROJECT_KEY + SONAR_ORGANIZATION env vars.',
355
+ )
356
+ }
357
+
358
+ // ── PR number detection via gh CLI ────────────────────────────────────────────
359
+
360
+ export async function detectPrNumber(
361
+ fallbackHint = '/pr-quality',
362
+ ): Promise<string> {
363
+ const result = await localExec(
364
+ 'gh',
365
+ ['pr', 'view', '--json', 'number', '-q', '.number'],
366
+ {
367
+ timeout: 10000,
368
+ },
369
+ )
370
+ if (result.code === 0 && result.stdout.trim()) {
371
+ return result.stdout.trim()
372
+ }
373
+ throw new Error(
374
+ `Could not detect PR number. Provide it as argument: ${fallbackHint} <PR_NUMBER>`,
375
+ )
376
+ }
377
+
378
+ // ── Issue pagination ──────────────────────────────────────────────────────────
379
+
380
+ export async function fetchAllIssues(
381
+ baseUrl: string,
382
+ token: string,
383
+ projectKey: string,
384
+ prNumber: string,
385
+ signal?: AbortSignal,
386
+ ): Promise<{ issues: SonarIssue[]; total: number }> {
387
+ let allIssues: SonarIssue[] = []
388
+ let total = 0
389
+ let page = 1
390
+
391
+ while (true) {
392
+ const data = (await sonarFetch(
393
+ baseUrl,
394
+ token,
395
+ 'issues/search',
396
+ {
397
+ componentKeys: projectKey,
398
+ pullRequest: prNumber,
399
+ issueStatuses: 'OPEN,CONFIRMED',
400
+ sinceLeakPeriod: 'true',
401
+ ps: '500',
402
+ p: String(page),
403
+ },
404
+ signal,
405
+ )) as IssuesResponse
406
+
407
+ allIssues = allIssues.concat(data.issues ?? [])
408
+ total = data.total ?? allIssues.length
409
+
410
+ if (allIssues.length >= total || (data.issues ?? []).length < 500) break
411
+ page++
412
+ }
413
+
414
+ return { issues: allIssues, total }
415
+ }
@@ -0,0 +1,102 @@
1
+ // AIDEV-NOTE: PMR-5NZB — ONE shared stable-range resolver for the personal
2
+ // mode gates (review, deviation, tuicr — PMR-R4AP single-resolver rule, so
3
+ // the gates agree by construction). The personal range is pinned to the
4
+ // creation-time flowbasesha recorded at worktree create; the integrity
5
+ // probe merge-base(HEAD, <flowbase branch>) === flowbasesha is deterministic
6
+ // (no reflog): main advancing alone never moves it, any rebase or
7
+ // base-merge does. Fail-closed on divergence — never fall back to a moving
8
+ // base, never consult <base>@{upstream} (PMR-MH1Y/DQ7Z). This module
9
+ // REPLACES the PMR-7N3D gate-time merge-base policy for personal mode; work
10
+ // mode never comes here (MODE_PROFILE[mode].baseResolution gates the call).
11
+ // Keep this module cycle-free: it imports flow-base.ts and diff-base.ts
12
+ // only.
13
+ import { type Exec, type FlowRange, resolveFlowRange } from './diff-base.ts'
14
+ import { readFlowBase, resolveMergeBase } from './flow-base.ts'
15
+
16
+ export type StableRangeRefusalKind =
17
+ | 'no-binding'
18
+ | 'no-sha'
19
+ | 'corrupt-sha'
20
+ | 'diverged'
21
+ | 'range-error'
22
+
23
+ export interface StableRangeRefusal {
24
+ ok: false
25
+ kind: StableRangeRefusalKind
26
+ reason: string
27
+ }
28
+
29
+ export type StableRangeResult =
30
+ | { ok: true; value: FlowRange }
31
+ | StableRangeRefusal
32
+
33
+ /**
34
+ * Resolve the stable review range `<flowbasesha>..HEAD` for a bound personal
35
+ * flow worktree. Every failure is a typed, fail-closed refusal carrying
36
+ * human-routable recovery guidance — there is no fallback base.
37
+ */
38
+ export async function resolveStableRange(
39
+ exec: Exec,
40
+ cwd: string,
41
+ ): Promise<StableRangeResult> {
42
+ const base = await readFlowBase(exec, cwd)
43
+ if (!base.ok) {
44
+ // PMR-182S: the readFlowBase reason already carries the full
45
+ // resume/bind recovery — stableRefusalText passes it through verbatim.
46
+ return { ok: false, kind: 'no-binding', reason: base.reason }
47
+ }
48
+ if (base.value.sha === null) {
49
+ return {
50
+ ok: false,
51
+ kind: 'no-sha',
52
+ reason: `flow base branch '${base.value.branch}' is recorded for this worktree but the creation-time SHA is missing (legacy or damaged worktree) — the stable review range cannot be derived. STOP and ask the human: re-create the flow worktree (/flow <ref> + worktree create) or knowingly re-record branch.<branch>.flowbasesha.`,
53
+ }
54
+ }
55
+ const verified = await exec(
56
+ 'git',
57
+ ['rev-parse', '--verify', `${base.value.sha}^{commit}`],
58
+ { cwd },
59
+ )
60
+ if (verified.code !== 0) {
61
+ return {
62
+ ok: false,
63
+ kind: 'corrupt-sha',
64
+ reason: `recorded flowbasesha '${base.value.sha}' does not resolve in ${cwd} — the flow base metadata is corrupt. STOP and ask the human.`,
65
+ }
66
+ }
67
+ const mb = await resolveMergeBase(exec, cwd, 'HEAD', base.value.branch)
68
+ if (!mb.ok) return { ok: false, kind: 'range-error', reason: mb.reason }
69
+ if (mb.sha !== base.value.sha) {
70
+ return {
71
+ ok: false,
72
+ kind: 'diverged',
73
+ reason: `integrity check failed: merge-base(HEAD, '${base.value.branch}') is ${mb.sha} but the recorded creation-time base is ${base.value.sha} — the flow branch was rebased or the base was merged into it, so a stable range cannot include it. STOP and ask the human (never treat the merge-base as the new base; never include upstream commits). If flow_land's sanctioned integration already ran, do not re-run this gate — proceed to landing.`,
74
+ }
75
+ }
76
+ const range = await resolveFlowRange(
77
+ exec,
78
+ cwd,
79
+ base.value.branch,
80
+ base.value.sha,
81
+ )
82
+ if (!range.ok) return { ok: false, kind: 'range-error', reason: range.reason }
83
+ return { ok: true, value: range.value }
84
+ }
85
+
86
+ /**
87
+ * Gate-agnostic refusal text: the resolver's reasons carry the recovery
88
+ * guidance; the consuming gate names itself here so the agent sees WHICH
89
+ * gate refused. Distinct per refusal kind (the kind tag plus the kind's own
90
+ * reason). `no-binding` returns the existing PMR-182S reason verbatim — it
91
+ * already names the resume/bind recovery and must never suggest hand-setting
92
+ * branch.<branch>.flowbase.
93
+ */
94
+ export function stableRefusalText(
95
+ refusal: StableRangeRefusal,
96
+ gate: string,
97
+ ): string {
98
+ if (refusal.kind === 'no-binding') {
99
+ return refusal.reason
100
+ }
101
+ return `${gate}: stable review range refused (${refusal.kind}) — ${refusal.reason}`
102
+ }
package/slugify.ts ADDED
@@ -0,0 +1,13 @@
1
+ // AIDEV-NOTE: Canonical slug rule — lowercase, strip non-alnum, max 5 words,
2
+ // dashes. Re-homed out of brainstorm/paths.ts (PMR-H7RW); imported by
3
+ // brainstorm/paths.ts and plan-tools/helpers.ts (plan/paths.ts was deleted
4
+ // with the dead resolvePlanDir duplicate, PMR-6RM5).
5
+ export function slugify(summary: string): string {
6
+ return summary
7
+ .toLowerCase()
8
+ .replace(/[^a-z0-9\s-]/g, '')
9
+ .trim()
10
+ .split(/\s+/)
11
+ .slice(0, 5)
12
+ .join('-')
13
+ }