From 1632d28fe5cd326acbe01de442195eeca889f714 Mon Sep 17 00:00:00 2001 From: Daniel Roe Date: Mon, 23 Jun 2025 13:28:26 +0100 Subject: [PATCH] feat: add enhanced context evaluation for better issue labeling decisions (#182) Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: danielroe <28706372+danielroe@users.noreply.github.com> Co-authored-by: Daniel Roe --- server/api/webhook.post.ts | 129 ++++++++++++++++++++++++++---- server/utils/context.ts | 158 +++++++++++++++++++++++++++++++++++++ server/utils/schema.ts | 20 +++++ test/utils.spec.ts | 156 +++++++++++++++++++++++++++++++++++- 4 files changed, 446 insertions(+), 17 deletions(-) create mode 100644 server/utils/context.ts diff --git a/server/api/webhook.post.ts b/server/api/webhook.post.ts index d9b8297..1ed0073 100644 --- a/server/api/webhook.post.ts +++ b/server/api/webhook.post.ts @@ -4,8 +4,10 @@ import type { H3Event } from 'h3' import type { IssuesEvent, IssueCommentEvent } from '@octokit/webhooks-types' import { toXML } from '../utils/xml' -import { aiResponseSchema, analyzedIssueSchema, commentAnalysisResponseSchema, commentAnalysisSchema, IssueLabel, IssueType, responseSchema, translationResponseSchema } from '../utils/schema' +import { aiResponseSchema, analyzedIssueSchema, commentAnalysisResponseSchema, commentAnalysisSchema, enhancedAnalysisResponseSchema, enhancedAnalysisSchema, IssueLabel, IssueType, responseSchema, translationResponseSchema } from '../utils/schema' import { isCollaboratorOrHigher } from '../utils/author-role' +import type { EnhancedContext } from '../utils/context' +import { gatherEnhancedContext, wasClosedAsNotPlanned, wasClosedAsDuplicate, wasClosedAsCompleted, buildEnhancedPromptContent } from '../utils/context' import { transferIssueToSpam } from '../utils/issue-transfer' export default defineEventHandler(async (event) => { @@ -32,6 +34,10 @@ export default defineEventHandler(async (event) => { return handleNewIssue(event, webhookPayload) } + if (action === 'closed') { + return + } + if (action === 'labeled') { return handleIssueLabeled(event, webhookPayload) } @@ -44,6 +50,55 @@ type CommentAnalysisResult = { possibleRegression?: boolean } +type EnhancedAnalysisResult = { + reproductionProvided?: boolean + possibleRegression?: boolean + shouldReopen?: boolean + isDifferentFromDuplicate?: boolean + confidence?: 'low' | 'medium' | 'high' +} + +async function analyzeClosedIssueComment( + event: H3Event, + issue: IssueCommentEvent['issue'], + repository: IssueCommentEvent['repository'], + issueLabels: string[], +): Promise<{ result: EnhancedAnalysisResult, context: EnhancedContext }> { + const enhancedContext = await gatherEnhancedContext(event, issue, repository, { + includeComments: true, + maxComments: 5, + includeTimeline: true, + }) + + const promptContent = buildEnhancedPromptContent(enhancedContext, true) + + // Determine analysis strategy based on how the issue was closed + let systemPrompt = `You are analyzing a closed issue in an open source project to determine if it should be reopened based on new evidence. ` + + if (wasClosedAsNotPlanned(enhancedContext)) { + systemPrompt += `This issue was closed as 'not planned'. Consider if new evidence in comments suggests it should be reconsidered. Pay attention to issue history - if it has been closed and reopened multiple times, be more conservative about reopening. ` + } + else if (wasClosedAsDuplicate(enhancedContext, issueLabels)) { + systemPrompt += `This issue was closed as 'duplicate'. Only suggest reopening if there's clear evidence this is a different issue than the original. ` + } + else if (wasClosedAsCompleted(enhancedContext)) { + systemPrompt += `This issue was closed as completed. Only suggest reopening if there's evidence the issue has reappeared (possible regression). ` + } + + systemPrompt += `Do not answer with anything else other than valid JSON. Here's the JSON schema you must adhere to:\n${toXML(enhancedAnalysisSchema)}\n` + + const res = await hubAI().run('@hf/nousresearch/hermes-2-pro-mistral-7b', { + messages: [ + { role: 'system', content: systemPrompt }, + { role: 'user', content: promptContent }, + ], + }) + + setHeader(event, 'x-enhanced-comment-analysis', JSON.stringify(res)) + const result = 'response' in res ? enhancedAnalysisResponseSchema.parse(JSON.parse(res.response || '{}')) : {} + return { result, context: enhancedContext } +} + async function handleIssueComment(event: H3Event, { comment, issue, repository }: IssueCommentEvent) { if (comment.user?.type === 'Bot') { return @@ -69,20 +124,32 @@ async function handleIssueComment(event: H3Event, { comment, issue, repository } const promises: Array> = [] try { - const res = await hubAI().run('@hf/nousresearch/hermes-2-pro-mistral-7b', { - messages: [ - { - role: 'system', - content: `You categorise issues in an open source project. Reported bugs must have enough information to reproduce them, either a full code example or a link to GitHub, StackBlitz or CodeSandbox. Do not answer with anything else other than valid JSON. Here's the json schema you must adhere to:\n${toXML(commentAnalysisSchema)}\n`, - }, - { role: 'user', content: JSON.stringify({ body: getNormalizedIssueContent(comment.body) }) }, - ], - }) - - setHeader(event, 'x-comment-analysis', JSON.stringify(res)) + let analysisResult: CommentAnalysisResult | EnhancedAnalysisResult + let enhancedContext: EnhancedContext | null = null + + // For closed issues, use enhanced context analysis + if (issue.state === 'closed') { + const analysis = await analyzeClosedIssueComment(event, issue, repository, issueLabels) + analysisResult = analysis.result + enhancedContext = analysis.context + } + else { + // Use original analysis for open issues + const res = await hubAI().run('@hf/nousresearch/hermes-2-pro-mistral-7b', { + messages: [ + { + role: 'system', + content: `You categorise issues in an open source project. Reported bugs must have enough information to reproduce them, either a full code example or a link to GitHub, StackBlitz or CodeSandbox. Do not answer with anything else other than valid JSON. Here's the json schema you must adhere to:\n${toXML(commentAnalysisSchema)}\n`, + }, + { role: 'user', content: JSON.stringify({ body: getNormalizedIssueContent(comment.body) }) }, + ], + }) - const analysisResult: CommentAnalysisResult = 'response' in res ? commentAnalysisResponseSchema.parse(JSON.parse(res.response || '{}')) : {} + setHeader(event, 'x-comment-analysis', JSON.stringify(res)) + analysisResult = 'response' in res ? commentAnalysisResponseSchema.parse(JSON.parse(res.response || '{}')) : {} + } + // Handle analysis results // 1. if a comment adds a reproduction if (hasNeedsReproductionLabel && analysisResult.reproductionProvided) { // we can go ahead and remove the 'needs reproduction' label @@ -106,8 +173,33 @@ async function handleIssueComment(event: H3Event, { comment, issue, repository } ) } } - // 2. if a resolved issue reappears + // 2. if a resolved issue reappears (with enhanced logic for closed issues) else if (issue.state === 'closed' && analysisResult.possibleRegression) { + // For closed issues, we have enhanced analysis results available + const enhancedResult = analysisResult as EnhancedAnalysisResult + + // Check if we should reopen based on enhanced analysis + const shouldReopen = enhancedResult.shouldReopen || analysisResult.possibleRegression + + if (!shouldReopen) { + return Promise.resolve([]) + } + + // For duplicate issues, only reopen if clearly different + if (wasClosedAsDuplicate(enhancedContext!, issueLabels) && !enhancedResult.isDifferentFromDuplicate) { + return Promise.resolve([]) + } + + // Collaborators and above can explicitly reopen if needed + if (isCollaboratorOrHigher(comment.author_association)) { + return Promise.resolve([]) + } + + // Check confidence level for automated reopening + if (enhancedResult.confidence !== 'high' && !analysisResult.possibleRegression) { + return Promise.resolve([]) + } + // then reopen the issue promises.push( github.issues.update({ @@ -118,13 +210,18 @@ async function handleIssueComment(event: H3Event, { comment, issue, repository } }), ) - // ... and add 'pending triage' and 'possible regression' labels + // ... and add appropriate labels + const labelsToAdd = [IssueLabel.PendingTriage] + if (analysisResult.possibleRegression) { + labelsToAdd.push(IssueLabel.PossibleRegression) + } + promises.push( github.issues.addLabels({ owner: repository.owner.login, repo: repository.name, issue_number: issue.number, - labels: [IssueLabel.PendingTriage, IssueLabel.PossibleRegression], + labels: labelsToAdd, }), ) } diff --git a/server/utils/context.ts b/server/utils/context.ts new file mode 100644 index 0000000..a8117dc --- /dev/null +++ b/server/utils/context.ts @@ -0,0 +1,158 @@ +import type { H3Event } from 'h3' +import type { Issue } from '@octokit/webhooks-types' +import { getNormalizedIssueContent } from './normalization' + +export interface EnhancedContext { + issueBody: string + recentComments: Array<{ + body: string + author: string + createdAt: string + authorAssociation: string + }> + issueState: string + issueStateReason: string | null | undefined + timelineEvents: Array<{ + event: string + createdAt?: string + actor?: string + }> +} + +/** + * Gather enhanced context for better issue analysis based on issue status + */ +export async function gatherEnhancedContext( + event: H3Event, + issue: Issue, + repository: { owner: { login: string }, name: string }, + options: { + includeComments?: boolean + maxComments?: number + includeTimeline?: boolean + } = {}, +): Promise { + const github = useGitHubAPI(event) + const { includeComments = true, maxComments = 5, includeTimeline = true } = options + + const context: EnhancedContext = { + issueBody: getNormalizedIssueContent(issue.body || ''), + recentComments: [], + issueState: issue.state || 'open', + issueStateReason: issue.state_reason, + timelineEvents: [], + } + + // Gather recent comments if needed + if (includeComments) { + try { + const commentsResponse = await github.issues.listComments({ + owner: repository.owner.login, + repo: repository.name, + issue_number: issue.number, + per_page: maxComments, + sort: 'created', + direction: 'desc', + }) + + context.recentComments = commentsResponse.data.map(comment => ({ + body: getNormalizedIssueContent(comment.body || ''), + author: comment.user?.login || 'unknown', + createdAt: comment.created_at, + authorAssociation: comment.author_association, + })) + } + catch (error) { + console.error('Error fetching issue comments:', error) + } + } + + // Gather timeline events if needed (for issue status history) + if (includeTimeline) { + try { + const timelineResponse = await github.issues.listEventsForTimeline({ + owner: repository.owner.login, + repo: repository.name, + issue_number: issue.number, + per_page: 20, + }) + + for (const event of timelineResponse.data) { + if (event.event === 'closed' || event.event === 'reopened' || event.event === 'labeled' || event.event === 'unlabeled') { + context.timelineEvents.push({ + event: event.event, + createdAt: 'created_at' in event ? event.created_at : undefined, + actor: 'actor' in event ? event.actor?.login : undefined, + }) + } + } + } + catch (error) { + console.error('Error fetching issue timeline:', error) + } + } + + return context +} + +/** + * Determine if an issue was closed as 'not planned' based on timeline events + */ +export function wasClosedAsNotPlanned(context: EnhancedContext): boolean { + return context.issueState === 'closed' && context.issueStateReason === 'not_planned' +} + +/** + * Determine if an issue was closed as 'duplicate' based on labels or comments + */ +export function wasClosedAsDuplicate(context: EnhancedContext, issueLabels: string[]): boolean { + return context.issueState === 'closed' + && (issueLabels.includes('duplicate') + || context.recentComments.some(comment => + comment.body.toLowerCase().includes('duplicate') + || comment.body.toLowerCase().includes('duplicates'), + )) +} + +/** + * Determine if an issue was closed as 'completed' + */ +export function wasClosedAsCompleted(context: EnhancedContext): boolean { + return context.issueState === 'closed' && context.issueStateReason === 'completed' +} + +/** + * Check if an issue has been reopened multiple times (indicating potential instability) + */ +export function hasBeenReopenedMultipleTimes(context: EnhancedContext): boolean { + const reopenCount = context.timelineEvents.filter(event => event.event === 'reopened').length + return reopenCount >= 2 +} + +/** + * Build enhanced prompt content with additional context + */ +export function buildEnhancedPromptContent(context: EnhancedContext, includeTimeline: boolean = false): string { + let content = `Issue Body:\n${context.issueBody}\n` + + if (context.recentComments.length > 0) { + content += `\nRecent Comments:\n` + context.recentComments.forEach((comment, index) => { + content += `Comment ${index + 1} (by ${comment.author}, ${comment.authorAssociation}):\n${comment.body}\n\n` + }) + } + + if (includeTimeline && context.timelineEvents.length > 0) { + content += `\nIssue Status History:\n` + context.timelineEvents.forEach((event) => { + content += `- ${event.event} on ${event.createdAt} by ${event.actor || 'unknown'}\n` + }) + } + + content += `\nCurrent Issue State: ${context.issueState}` + if (context.issueStateReason) { + content += ` (${context.issueStateReason})` + } + + return content +} diff --git a/server/utils/schema.ts b/server/utils/schema.ts index 07421f7..336715d 100644 --- a/server/utils/schema.ts +++ b/server/utils/schema.ts @@ -27,11 +27,31 @@ export const commentAnalysisSchema = { }, } +export const enhancedAnalysisSchema = { + title: 'Enhanced Issue Analysis', + type: 'object', + properties: { + reproductionProvided: { type: 'boolean' }, + possibleRegression: { type: 'boolean', comment: 'If the issue reported is a bug and the bug has reappeared on upgrade to a new version of Nuxt, it is a possible regression.' }, + shouldReopen: { type: 'boolean', comment: 'Whether a closed issue should be reopened based on new evidence or context.' }, + isDifferentFromDuplicate: { type: 'boolean', comment: 'For issues marked as duplicate, whether the evidence suggests this is actually a different issue.' }, + confidence: { type: 'string', enum: ['low', 'medium', 'high'], comment: 'Confidence level in the analysis based on available context.' }, + }, +} + export const commentAnalysisResponseSchema = z.object({ reproductionProvided: z.boolean().optional(), possibleRegression: z.boolean().optional(), }) +export const enhancedAnalysisResponseSchema = z.object({ + reproductionProvided: z.boolean().optional(), + possibleRegression: z.boolean().optional(), + shouldReopen: z.boolean().optional(), + isDifferentFromDuplicate: z.boolean().optional(), + confidence: z.enum(['low', 'medium', 'high']).optional(), +}) + export enum IssueLabel { NeedsReproduction = 'needs reproduction', PossibleRegression = 'possible regression', diff --git a/test/utils.spec.ts b/test/utils.spec.ts index c34ad3a..09fa48e 100644 --- a/test/utils.spec.ts +++ b/test/utils.spec.ts @@ -1,7 +1,9 @@ import { describe, it, expect, vi } from 'vitest' import { toXML } from '../server/utils/xml' -import { responseSchema, commentAnalysisSchema } from '../server/utils/schema' +import { responseSchema, commentAnalysisSchema, enhancedAnalysisSchema } from '../server/utils/schema' import { getLoggerProxy } from '../server/utils/proxy' +import { wasClosedAsNotPlanned, wasClosedAsDuplicate, wasClosedAsCompleted, hasBeenReopenedMultipleTimes, buildEnhancedPromptContent } from '../server/utils/context' +import type { EnhancedContext } from '../server/utils/context' describe('toXML', () => { it('should convert the comment analysis schema to XML', () => { @@ -13,6 +15,11 @@ describe('toXML', () => { const xml = toXML(responseSchema) expect(xml).toMatchInlineSnapshot(`"Issue Categorisationobjectstring<0>bug<1>feature<2>documentation<3>chore<4>help-wanted<5>spambooleanstringThe language of the title in ISO 639-1 format. Do not include country codes, only language code.booleanIf the issue is reported on upgrade to a new version of Nuxt, it is a possible regression.booleanIf the issue is reported only in relation to a single deployment provider, it is possibly a Nitro issue."`) }) + + it('should convert the enhanced analysis schema to XML', () => { + const xml = toXML(enhancedAnalysisSchema) + expect(xml).toMatchInlineSnapshot(`"Enhanced Issue AnalysisobjectbooleanbooleanIf the issue reported is a bug and the bug has reappeared on upgrade to a new version of Nuxt, it is a possible regression.booleanWhether a closed issue should be reopened based on new evidence or context.booleanFor issues marked as duplicate, whether the evidence suggests this is actually a different issue.string<0>low<1>medium<2>highConfidence level in the analysis based on available context."`) + }) }) describe('getLoggerProxy', () => { @@ -30,3 +37,150 @@ describe('getLoggerProxy', () => { expect(console.log).toHaveBeenCalledTimes(5) }) }) + +describe('Enhanced Context Analysis', () => { + const createMockContext = (overrides: Partial = {}): EnhancedContext => ({ + issueBody: 'Sample issue body', + recentComments: [], + issueState: 'open', + issueStateReason: null, + timelineEvents: [], + ...overrides, + }) + + describe('wasClosedAsNotPlanned', () => { + it('should return true for closed issues with not_planned reason', () => { + const context = createMockContext({ + issueState: 'closed', + issueStateReason: 'not_planned', + }) + expect(wasClosedAsNotPlanned(context)).toBe(true) + }) + + it('should return false for open issues', () => { + const context = createMockContext({ + issueState: 'open', + issueStateReason: null, + }) + expect(wasClosedAsNotPlanned(context)).toBe(false) + }) + + it('should return false for closed issues with other reasons', () => { + const context = createMockContext({ + issueState: 'closed', + issueStateReason: 'completed', + }) + expect(wasClosedAsNotPlanned(context)).toBe(false) + }) + }) + + describe('wasClosedAsDuplicate', () => { + it('should return true when duplicate label is present', () => { + const context = createMockContext({ + issueState: 'closed', + }) + expect(wasClosedAsDuplicate(context, ['duplicate'])).toBe(true) + }) + + it('should return true when duplicate is mentioned in comments', () => { + const context = createMockContext({ + issueState: 'closed', + recentComments: [ + { + body: 'This is a duplicate of issue #123', + author: 'maintainer', + createdAt: '2024-01-01T00:00:00Z', + authorAssociation: 'MEMBER', + }, + ], + }) + expect(wasClosedAsDuplicate(context, [])).toBe(true) + }) + + it('should return false for open issues without duplicate indicators', () => { + const context = createMockContext({ + issueState: 'open', + }) + expect(wasClosedAsDuplicate(context, [])).toBe(false) + }) + }) + + describe('wasClosedAsCompleted', () => { + it('should return true for closed issues with completed reason', () => { + const context = createMockContext({ + issueState: 'closed', + issueStateReason: 'completed', + }) + expect(wasClosedAsCompleted(context)).toBe(true) + }) + + it('should return false for other closed reasons', () => { + const context = createMockContext({ + issueState: 'closed', + issueStateReason: 'not_planned', + }) + expect(wasClosedAsCompleted(context)).toBe(false) + }) + }) + + describe('hasBeenReopenedMultipleTimes', () => { + it('should return true when issue has been reopened multiple times', () => { + const context = createMockContext({ + timelineEvents: [ + { event: 'closed', createdAt: '2024-01-01T00:00:00Z', actor: 'user1' }, + { event: 'reopened', createdAt: '2024-01-02T00:00:00Z', actor: 'user2' }, + { event: 'closed', createdAt: '2024-01-03T00:00:00Z', actor: 'user3' }, + { event: 'reopened', createdAt: '2024-01-04T00:00:00Z', actor: 'user4' }, + ], + }) + expect(hasBeenReopenedMultipleTimes(context)).toBe(true) + }) + + it('should return false when issue has been reopened only once', () => { + const context = createMockContext({ + timelineEvents: [ + { event: 'closed', createdAt: '2024-01-01T00:00:00Z', actor: 'user1' }, + { event: 'reopened', createdAt: '2024-01-02T00:00:00Z', actor: 'user2' }, + ], + }) + expect(hasBeenReopenedMultipleTimes(context)).toBe(false) + }) + }) + + describe('buildEnhancedPromptContent', () => { + it('should build prompt content with issue body and comments', () => { + const context = createMockContext({ + issueBody: 'This is the issue description', + recentComments: [ + { + body: 'This might be related to the recent update', + author: 'contributor', + createdAt: '2024-01-01T00:00:00Z', + authorAssociation: 'CONTRIBUTOR', + }, + ], + issueState: 'closed', + issueStateReason: 'not_planned', + }) + + const content = buildEnhancedPromptContent(context) + expect(content).toContain('Issue Body:') + expect(content).toContain('This is the issue description') + expect(content).toContain('Recent Comments:') + expect(content).toContain('This might be related to the recent update') + expect(content).toContain('Current Issue State: closed (not_planned)') + }) + + it('should include timeline when requested', () => { + const context = createMockContext({ + timelineEvents: [ + { event: 'closed', createdAt: '2024-01-01T00:00:00Z', actor: 'maintainer' }, + ], + }) + + const content = buildEnhancedPromptContent(context, true) + expect(content).toContain('Issue Status History:') + expect(content).toContain('closed on 2024-01-01T00:00:00Z by maintainer') + }) + }) +}) -- knotmirror 0.0.1