Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/cli/src/__tests__/generate.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ describe('generate pipeline — integration', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(fetchPullRequests).mockResolvedValue(mockPRs)
vi.mocked(analyzePullRequests).mockResolvedValue({ changes: mockChanges })
vi.mocked(analyzePullRequests).mockResolvedValue({ changes: mockChanges, prefilteredCount: 0 })
})

it('fetches PRs with correct repo and range', async () => {
Expand Down Expand Up @@ -189,7 +189,7 @@ describe('generate pipeline — integration', () => {

it('handles all-internal changes gracefully', async () => {
const allInternal: AnalyzedChange[] = mockChanges.map(c => ({ ...c, visible: false, category: 'internal' }))
vi.mocked(analyzePullRequests).mockResolvedValue({ changes: allInternal })
vi.mocked(analyzePullRequests).mockResolvedValue({ changes: allInternal, prefilteredCount: 0 })

const prs = await vi.mocked(fetchPullRequests)({ owner: 'testuser', name: 'testrepo' }, 'v1.0.0', 'v1.1.0')
const { changes } = await vi.mocked(analyzePullRequests)(prs)
Expand Down
69 changes: 69 additions & 0 deletions packages/cli/src/__tests__/prefilter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { describe, it, expect } from 'vitest'
import { prefilterPRs } from '../lib/prefilter.js'
import type { PullRequest } from '../lib/github.js'

function pr(title: string, labels: string[] = []): PullRequest {
return { number: 1, title, body: null, labels, author: 'a', merged_at: '', url: '', linked_issues: [] }
}

describe('prefilterPRs', () => {
it('passes user-facing PRs through to toAnalyze', () => {
const { toAnalyze, prefiltered } = prefilterPRs([pr('Add dark mode support')])
expect(toAnalyze).toHaveLength(1)
expect(prefiltered).toHaveLength(0)
})

it('pre-filters conventional commit chore prefix', () => {
const { toAnalyze, prefiltered } = prefilterPRs([pr('chore: update eslint config')])
expect(toAnalyze).toHaveLength(0)
expect(prefiltered[0].category).toBe('internal')
})

it('pre-filters ci prefix', () => {
const { prefiltered } = prefilterPRs([pr('ci: add node 20 to matrix')])
expect(prefiltered).toHaveLength(1)
})

it('pre-filters bump commits', () => {
const { prefiltered } = prefilterPRs([pr('bump lodash from 4.17.20 to 4.17.21')])
expect(prefiltered).toHaveLength(1)
})

it('pre-filters dependabot PRs', () => {
const { prefiltered } = prefilterPRs([pr('Bump axios from 1.0.0 to 1.1.0', ['dependabot'])])
expect(prefiltered).toHaveLength(1)
})

it('pre-filters by dependencies label', () => {
const { prefiltered } = prefilterPRs([pr('Update packages', ['dependencies'])])
expect(prefiltered).toHaveLength(1)
})

it('pre-filtered items have visible: false', () => {
const { prefiltered } = prefilterPRs([pr('chore: cleanup')])
expect(prefiltered[0].visible).toBe(false)
expect(prefiltered[0].confidence).toBe(1)
})

it('pre-filters refactor prefix', () => {
const { prefiltered } = prefilterPRs([pr('refactor: extract auth middleware')])
expect(prefiltered).toHaveLength(1)
})

it('does not pre-filter a real feature even with chore-like words', () => {
const { toAnalyze } = prefilterPRs([pr('Add CI status badge to README')])
expect(toAnalyze).toHaveLength(1)
})

it('handles mixed batch correctly', () => {
const prs = [
pr('Add search functionality'),
pr('chore: bump node version'),
pr('Fix login timeout bug'),
pr('ci: update GitHub Actions workflow'),
]
const { toAnalyze, prefiltered } = prefilterPRs(prs)
expect(toAnalyze).toHaveLength(2)
expect(prefiltered).toHaveLength(2)
})
})
11 changes: 6 additions & 5 deletions packages/cli/src/commands/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { analyzePullRequests } from '../lib/ai.js'
import { getActiveAIKey, getActiveProvider, AI_PROVIDER_LABELS } from '../lib/config.js'
import { handleError, AuthError } from '../lib/errors.js'
import { formatOutput } from '../lib/formatters.js'
import { estimateCost, formatCostEstimate } from '../lib/cost.js'
import { estimateCostForPRs, formatCostEstimate } from '../lib/cost.js'

export interface GenerateOptions {
from: string
Expand Down Expand Up @@ -92,7 +92,7 @@ ${chalk.bold('Examples:')}
log(` ${chalk.dim(`${i + 1}.`)} ${pr.title}${labelStr}`)
})
log('')
const estimate = estimateCost(prs.length, getActiveProvider())
const estimate = estimateCostForPRs(prs, getActiveProvider())
log(chalk.dim(` ${prs.length} PRs → ${formatCostEstimate(estimate)}`))
log(chalk.dim(' Remove --dry-run to generate release notes.'))
log('')
Expand All @@ -101,16 +101,17 @@ ${chalk.bold('Examples:')}

// 5. Show cost estimate before AI call (--show-cost flag)
if (options.showCost) {
const estimate = estimateCost(prs.length, getActiveProvider())
const estimate = estimateCostForPRs(prs, getActiveProvider())
log(chalk.dim(` cost est. : ${formatCostEstimate(estimate)}`))
log('')
}

const aiSpinner = ora({ text: 'Analyzing with AI...', isSilent: options.quiet }).start()
const { changes } = await analyzePullRequests(prs)
const { changes, prefilteredCount } = await analyzePullRequests(prs)
const visible = changes.filter(c => c.visible)
const hidden = changes.filter(c => !c.visible)
aiSpinner.succeed(`Analyzed — ${chalk.bold(visible.length)} user-facing, ${chalk.dim(`${hidden.length} hidden`)}`)
const prefilteredNote = prefilteredCount > 0 ? chalk.dim(`, ${prefilteredCount} pre-filtered`) : ''
aiSpinner.succeed(`Analyzed — ${chalk.bold(visible.length)} user-facing, ${chalk.dim(`${hidden.length} hidden`)}${prefilteredNote}`)

if (visible.length === 0) {
log('')
Expand Down
24 changes: 15 additions & 9 deletions packages/cli/src/lib/ai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import OpenAI from 'openai'
import { GoogleGenerativeAI } from '@google/generative-ai'
import { getActiveProvider, getActiveAIKey } from './config.js'
import { AuthError, ApiError } from './errors.js'
import { prefilterPRs } from './prefilter.js'
import type { PullRequest } from './github.js'

// ─── Types ────────────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -182,21 +183,26 @@ async function analyzeWithGemini(prs: PullRequest[]): Promise<AnalyzedChange[]>

// ─── Public API ───────────────────────────────────────────────────────────────

export async function analyzePullRequests(prs: PullRequest[]): Promise<AnalysisResult> {
export async function analyzePullRequests(prs: PullRequest[]): Promise<AnalysisResult & { prefilteredCount: number }> {
const { toAnalyze, prefiltered } = prefilterPRs(prs)
const provider = getActiveProvider()
let changes: AnalyzedChange[]

switch (provider) {
case 'anthropic': changes = await analyzeWithAnthropic(prs); break
case 'openai': changes = await analyzeWithOpenAI(prs); break
case 'gemini': changes = await analyzeWithGemini(prs); break
default: throw new ApiError(`Unsupported AI provider: ${provider}`)
let aiChanges: AnalyzedChange[] = []

if (toAnalyze.length > 0) {
switch (provider) {
case 'anthropic': aiChanges = await analyzeWithAnthropic(toAnalyze); break
case 'openai': aiChanges = await analyzeWithOpenAI(toAnalyze); break
case 'gemini': aiChanges = await analyzeWithGemini(toAnalyze); break
default: throw new ApiError(`Unsupported AI provider: ${provider}`)
}
}

const changes = [...aiChanges, ...prefiltered]

const order: Record<ChangeCategory, number> = {
breaking: 0, feature: 1, improvement: 2, bugfix: 3, internal: 4,
}
changes.sort((a, b) => (order[a.category] ?? 5) - (order[b.category] ?? 5))

return { changes }
return { changes, prefilteredCount: prefiltered.length }
}
7 changes: 7 additions & 0 deletions packages/cli/src/lib/cost.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type { AIProvider } from './config.js'
import type { PullRequest } from './github.js'
import { prefilterPRs } from './prefilter.js'

// Approximate token counts based on real prompt structure
const SYSTEM_PROMPT_TOKENS = 350
Expand All @@ -20,6 +22,11 @@ export interface CostEstimate {
model: string
}

export function estimateCostForPRs(prs: PullRequest[], provider: AIProvider): CostEstimate {
const { toAnalyze } = prefilterPRs(prs)
return estimateCost(toAnalyze.length, provider)
}

export function estimateCost(prCount: number, provider: AIProvider): CostEstimate {
const inputTokens = SYSTEM_PROMPT_TOKENS + INPUT_TOKENS_PER_PR * prCount
const outputTokens = OUTPUT_TOKENS_PER_PR * prCount
Expand Down
45 changes: 45 additions & 0 deletions packages/cli/src/lib/prefilter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import type { PullRequest } from './github.js'
import type { AnalyzedChange } from './ai.js'

// Patterns that are always internal - no need to send to AI
const INTERNAL_PATTERNS = [
/^(chore|ci|build|test|tests|refactor|style|perf)(\(.+\))?:/i,
/^bump\s/i,
/^update\s.*(dep|dependencies|dependency|package)/i,
/\bdependabot\b/i,
/^merge\s(branch|pull\srequest)/i,
/^(release|version)\s*v?\d/i,
/\b(renovate|snyk)\b/i,
]

const INTERNAL_LABELS = ['dependencies', 'ci', 'chore', 'internal', 'skip-changelog']

export interface PrefilterResult {
toAnalyze: PullRequest[]
prefiltered: AnalyzedChange[]
}

export function prefilterPRs(prs: PullRequest[]): PrefilterResult {
const toAnalyze: PullRequest[] = []
const prefiltered: AnalyzedChange[] = []

for (const pr of prs) {
const isInternalByTitle = INTERNAL_PATTERNS.some(p => p.test(pr.title))
const isInternalByLabel = pr.labels.some(l => INTERNAL_LABELS.includes(l.toLowerCase()))

if (isInternalByTitle || isInternalByLabel) {
prefiltered.push({
original_title: pr.title,
rewritten_title: pr.title,
category: 'internal',
visible: false,
confidence: 1,
reasoning: 'Pre-filtered: matched internal pattern',
})
} else {
toAnalyze.push(pr)
}
}

return { toAnalyze, prefiltered }
}
Loading