diff --git a/packages/cli/src/__tests__/generate.integration.test.ts b/packages/cli/src/__tests__/generate.integration.test.ts index 12c47b9..8b2abbf 100644 --- a/packages/cli/src/__tests__/generate.integration.test.ts +++ b/packages/cli/src/__tests__/generate.integration.test.ts @@ -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 () => { @@ -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) diff --git a/packages/cli/src/__tests__/prefilter.test.ts b/packages/cli/src/__tests__/prefilter.test.ts new file mode 100644 index 0000000..7f86ef7 --- /dev/null +++ b/packages/cli/src/__tests__/prefilter.test.ts @@ -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) + }) +}) diff --git a/packages/cli/src/commands/generate.ts b/packages/cli/src/commands/generate.ts index 318f395..d290f0c 100644 --- a/packages/cli/src/commands/generate.ts +++ b/packages/cli/src/commands/generate.ts @@ -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 @@ -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('') @@ -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('') diff --git a/packages/cli/src/lib/ai.ts b/packages/cli/src/lib/ai.ts index 9ffcf77..24e6830 100644 --- a/packages/cli/src/lib/ai.ts +++ b/packages/cli/src/lib/ai.ts @@ -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 ──────────────────────────────────────────────────────────────────── @@ -182,21 +183,26 @@ async function analyzeWithGemini(prs: PullRequest[]): Promise // ─── Public API ─────────────────────────────────────────────────────────────── -export async function analyzePullRequests(prs: PullRequest[]): Promise { +export async function analyzePullRequests(prs: PullRequest[]): Promise { + 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 = { 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 } } diff --git a/packages/cli/src/lib/cost.ts b/packages/cli/src/lib/cost.ts index eff2dad..9f7c134 100644 --- a/packages/cli/src/lib/cost.ts +++ b/packages/cli/src/lib/cost.ts @@ -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 @@ -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 diff --git a/packages/cli/src/lib/prefilter.ts b/packages/cli/src/lib/prefilter.ts new file mode 100644 index 0000000..3d7da76 --- /dev/null +++ b/packages/cli/src/lib/prefilter.ts @@ -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 } +}