Repository navigation
Expand file tree
/
Copy pathdetect_potential_problems_workflow.ts
More file actions
443 lines (428 loc) · 21.1 KB
/
Copy pathdetect_potential_problems_workflow.ts
File metadata and controls
443 lines (428 loc) · 21.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
import { BugbotReviewCompletenessError } from '../../../../domain/bugbot/framed_review';
import { isAgentConfigurationReady } from '../../../../data/model/agent';
import { Result } from '../../../../data/model/result';
import type { FindingsQueryPort } from '../../../ports/agent_findings_ports';
import { getTaskEmoji } from '../../../../utils/task_emoji';
import { logDebugInfo, logError, logInfo } from '../../../ports/logging_ports';
import type { BugbotScmPorts } from '../../../ports/bugbot_scm_ports';
import { PullRequestReviewOperationError } from '../../../ports/pull_request_review_errors';
import {
loadBugbotContext,
preflightBugbotContext,
} from './bugbot/load_bugbot_context_use_case';
import {
projectBugbotContextRequest,
type LoadBugbotContextOptions,
} from './bugbot/bugbot_context_request';
import { applyDetectedFindings } from './bugbot/apply_detected_findings';
import type { PreparedBugbotFindings } from './bugbot/prepare_bugbot_findings';
import { projectBugbotFindingStatuses } from '../../../policies/bugbot_finding_status_policy';
import type { BugbotContext } from './bugbot/types';
import type { BugbotReviewOutcome, BugbotTelemetryPort } from '../../../ports/bugbot_telemetry_ports';
import { BugbotReviewTelemetry } from './bugbot/bugbot_review_telemetry';
import { analyzeBugbotRevision } from './bugbot/analyze_bugbot_revision_use_case';
import { hasNewerBugbotRevision, isLoadedBugbotRevisionSuperseded } from './bugbot/bugbot_review_freshness';
import {
reconcileBugbotReviewState,
type BugbotPresentationReport,
} from './bugbot/reconcile_bugbot_review_state_use_case';
import type { BugbotFinding } from '../../../../domain/bugbot/finding';
import { ApplicationError, toApplicationError } from '../../../errors/application_error';
import {
type BugbotReviewOperationContext,
} from './bugbot/bugbot_review_operation_context';
import { selectPullRequestOwnerForPushReview } from '../../../policies/bugbot_event_ownership_policy';
import type { MessageCatalogResolutionPort } from '../../../ports/message_catalog_ports';
import {
resolveBugbotCatalog,
type BugbotMessageCatalog,
} from '../../../policies/bugbot_message_catalog';
import { formatBugbotPartitionCompletion } from '../../../policies/bugbot_partition_completion_policy';
export interface DetectPotentialProblemsWorkflowDependencies {
aiRepository: FindingsQueryPort;
scm: BugbotScmPorts;
telemetryPort?: BugbotTelemetryPort;
catalogResolver?: MessageCatalogResolutionPort;
}
const TASK_ID = 'DetectPotentialProblemsUseCase';
/** Coordinates Bugbot context, analysis and finding publication behind application ports. */
export async function runDetectPotentialProblemsWorkflow(
reviewContext: BugbotReviewOperationContext,
dependencies: DetectPotentialProblemsWorkflowDependencies,
): Promise<Result[]> {
const workflowStartedAt = Date.now();
const telemetry = new BugbotReviewTelemetry(reviewContext);
const publishTelemetry = async (outcome: BugbotReviewOutcome, category?: string) => {
const snapshot = telemetry.snapshot(outcome, category);
if (reviewContext.analysis.reviewConfiguration.telemetry) {
try {
await dependencies.telemetryPort?.publish(snapshot);
} catch {
logInfo('Bugbot telemetry publication failed without affecting the review.');
}
}
return snapshot;
};
const complete = async (result: Result, outcome: BugbotReviewOutcome): Promise<Result[]> => {
const snapshot = await publishTelemetry(outcome);
const payload = result.payload && typeof result.payload === 'object' && !Array.isArray(result.payload)
? result.payload as Record<string, unknown>
: {};
result.payload = { ...payload, bugbotTelemetry: snapshot };
return [result];
};
logInfo(`${getTaskEmoji(TASK_ID)} Executing ${TASK_ID}.`);
try {
if (shouldSkipDetection(reviewContext)) {
await publishTelemetry('skipped', 'admission');
return [];
}
const contextOptions = resolveContextOptions(reviewContext);
if (contextOptions === null) {
logDebugInfo('No branch or pull request target available for potential-problems detection.');
await publishTelemetry('skipped', 'missing_context');
return [];
}
const contextRequest = projectBugbotContextRequest(reviewContext, contextOptions);
const preflight = await telemetry.measure('context-preflight', () =>
preflightBugbotContext(contextRequest, dependencies.scm.context));
telemetry.observePreflight(preflight);
const owningPullRequest = selectPullRequestOwnerForPushReview({
triggerKind: reviewContext.trigger.kind,
eventTargetsPullRequest: reviewContext.target.isPullRequest,
selectionReason: preflight.selectionReason,
canonicalPullRequest: preflight.canonicalPullRequest,
});
if (owningPullRequest) {
logInfo(
`Skipping push Bugbot analysis because pull request #${owningPullRequest.number} owns review for this head.`,
);
await publishTelemetry('skipped', 'pull_request_ownership');
return [];
}
// Comment events omit draft state, and delayed PR events may carry an
// obsolete value. The already verified provider identity is authoritative.
if (preflight.canonicalPullRequest?.draft
&& !reviewContext.analysis.reviewConfiguration.reviewDrafts) {
return await complete(skippedDraftResult(), 'skipped');
}
const context = await telemetry.measure('context', () =>
loadBugbotContext(contextRequest, dependencies.scm.context, preflight, dependencies.scm.reviewSource));
const eventHeadSha = reviewContext.trigger.expectedHeadSha;
if (isLoadedBugbotRevisionSuperseded(context, eventHeadSha)) {
return await complete(supersededResult(context.prContext?.prHeadSha, eventHeadSha), 'superseded');
}
const prepared = await analyzeBugbotRevision(reviewContext, context, { agent: dependencies.aiRepository, telemetry, isSourceCurrent: async () => !await hasNewerBugbotRevision(context, dependencies.scm.context) });
if (prepared === undefined) {
const analysisError = new ApplicationError('agent.failed', 'The configured agent returned no potential-problem analysis.');
const catalog = reviewContext.analysis.reviewConfiguration.publicationMode === 'publish'
&& context.prContext && context.canonicalPullRequest
? await resolvePublicationCatalog(reviewContext, dependencies, true)
: undefined;
const presentation = reviewContext.analysis.reviewConfiguration.publicationMode === 'publish'
? await telemetry.measure('projection', () => reconcileReviewState({
operation: reviewContext,
loadedContext: context,
activeFindings: [],
mutationErrors: [analysisError],
dependencies,
catalog,
}))
: undefined;
if (presentation) telemetry.observeProjection(presentation.projection);
return await complete(noAnalysisResult(presentation), 'failed');
}
telemetry.observePrepared(prepared);
if (await telemetry.measure('freshness', () =>
hasNewerBugbotRevision(context, dependencies.scm.context))) {
return await complete(supersededResult(context.prContext?.prHeadSha), 'superseded');
}
if (reviewContext.analysis.reviewConfiguration.publicationMode === 'dry-run') {
return await complete(dryRunResult(prepared, context), 'dry-run');
}
// A pull request still publishes its canonical status card when there are no finding mutations.
const presentsPullRequestStatus = Boolean(context.prContext && context.canonicalPullRequest);
const mutatesFindingComments = prepared.toPublish.length > 0
|| prepared.resolvedFindingIds.size > 0;
const catalog = presentsPullRequestStatus || mutatesFindingComments
? await resolvePublicationCatalog(reviewContext, dependencies, presentsPullRequestStatus)
: undefined;
// Catalog localization may await a provider. Recheck after it, directly before SCM mutation.
if (context.reviewFramedSource && await hasNewerBugbotRevision(context, dependencies.scm.context)) {
return await complete(supersededResult(context.prContext?.prHeadSha), 'superseded');
}
const resolutionErrors = await telemetry.measure('publication', () => applyDetectedFindings(
reviewContext,
context,
prepared,
dependencies.scm.publication,
dependencies.scm.resolution,
catalog,
));
if (await telemetry.measure('post-publication-freshness', () =>
hasNewerBugbotRevision(context, dependencies.scm.context, 'after-publication'))) {
return await complete(supersededResult(context.prContext?.prHeadSha), 'superseded');
}
const presentation = await telemetry.measure('projection', () =>
reconcileReviewState({
operation: reviewContext,
loadedContext: context,
activeFindings: prepared.activeFindings ?? prepared.toPublish,
expectedPublishedFindings: prepared.toPublish,
mutationErrors: resolutionErrors,
dependencies,
catalog,
}));
if (presentation) telemetry.observeProjection(presentation.projection);
logInfo(`Bugbot workflow completed in ${Date.now() - workflowStartedAt}ms.`);
const finalErrors = presentation?.errors ?? resolutionErrors;
const hasChanges = prepared.toPublish.length > 0 || prepared.resolvedFindingIds.size > 0;
return await complete(
detectionResult(prepared, context, finalErrors, presentation),
finalErrors.length > 0
? 'failed'
: context.coverage.status === 'partial'
? 'partial'
: hasChanges ? 'completed' : 'no-findings',
);
} catch (error) {
const resultError = toApplicationError(
error instanceof BugbotReviewCompletenessError
? new ApplicationError('validation.evidence-unavailable', 'Bugbot could not verify a complete source-bound review.', { retryable: false, recovery: { id: 'bugbot-review-incomplete', variables: error.facts } })
: error,
'provider.unavailable',
`Error in ${TASK_ID}: Unable to detect potential problems.`,
);
logError(resultError);
const result = new Result({
id: TASK_ID,
success: false,
executed: true,
errors: [resultError],
});
const snapshot = await publishTelemetry('failed', error instanceof Error ? error.name : 'unknown');
result.payload = { bugbotTelemetry: snapshot };
return [result];
}
}
function skippedDraftResult(): Result {
return new Result({
id: TASK_ID,
success: true,
executed: false,
steps: ['Draft pull request review skipped by configuration.'],
payload: { skipped: 'draft' },
});
}
function dryRunResult(prepared: PreparedBugbotFindings, context: BugbotContext): Result {
const acceptedCount = prepared.activeFindings?.length ?? 0;
const partitionCompletion = formatBugbotPartitionCompletion(context);
const statuses = projectBugbotFindingStatuses(
context.existingByFindingId,
prepared.activeFindings ?? prepared.toPublish,
prepared.resolvedFindingIds,
prepared.resolvedFindingResolutions,
);
return new Result({
id: TASK_ID,
success: true,
executed: true,
steps: [`Bugbot dry-run completed${partitionCompletion.dryRunSuffix} with ${acceptedCount} accepted ${acceptedCount === 1 ? 'finding' : 'findings'}; no SCM mutations performed.`],
payload: {
dryRun: true,
findings: prepared.activeFindings ?? prepared.toPublish,
overflowCount: prepared.overflowCount,
resolvedFindingIds: [...prepared.resolvedFindingIds],
findingStates: statuses.counts,
ruleSources: context.reviewRuleSources ?? [],
contextCoverage: context.coverage,
},
});
}
function supersededResult(loadedHeadSha?: string, expectedHeadSha?: string): Result {
logInfo('Bugbot analysis was superseded by a newer pull-request revision; publication skipped.');
return new Result({
id: TASK_ID,
success: true,
executed: true,
steps: ['Potential problems detection superseded by a newer pull-request revision; no findings were published or resolved.'],
payload: {
superseded: true,
...(loadedHeadSha ? { analyzedHeadSha: loadedHeadSha } : {}),
...(expectedHeadSha ? { expectedHeadSha } : {}),
},
});
}
function resolveContextOptions(param: BugbotReviewOperationContext): LoadBugbotContextOptions | undefined | null {
if (param.target.isPullRequest) {
return {
branchOverride: param.target.headBranch,
issueNumberOverride: param.target.issueNumber,
pullRequestNumberOverride: param.target.pullRequestNumber,
};
}
if (param.target.commitBranch) return undefined;
if (['issues', 'issue_comment'].includes(param.trigger.kind) && param.target.issueNumber > 0) {
return undefined;
}
return null;
}
function shouldSkipDetection(param: BugbotReviewOperationContext): boolean {
if (!isAgentConfigurationReady(param.analysis.agentConfiguration)) {
logDebugInfo('Agent not configured; skipping potential problems detection.');
return true;
}
if (param.target.issueNumber === -1
&& (!param.target.isPullRequest || param.target.pullRequestNumber <= 0)) {
logDebugInfo('No issue or pull request number for this execution; skipping potential problems detection.');
return true;
}
return false;
}
function noAnalysisResult(presentation?: BugbotPresentationReport): Result {
logDebugInfo('DetectPotentialProblems: No response from configured agent.');
const errors = presentation?.errors.length
? [...presentation.errors]
: [new ApplicationError('agent.failed', 'The configured agent returned no potential-problem analysis.')];
return new Result({
id: TASK_ID,
success: false,
executed: true,
...(presentation ? {
steps: [`Bugbot analysis failed; the verified PR status was reconciled (${formatStateCounts(presentation.projection.counts)}).`],
} : {}),
errors: errors.map(error => presentation
? toBugbotPresentationError(error)
: toBugbotApplicationError(error, 'Bugbot review reconciliation failed.')),
...(presentation ? {
payload: {
findingStates: presentation.projection.counts,
reviewProjection: presentation.projection,
statusCardOperation: presentation.statusCardOperation,
reviewUpdates: presentation.reviewUpdates,
pendingReviewUpdates: presentation.pendingReviewUpdates,
},
} : {}),
});
}
function detectionResult(
prepared: PreparedBugbotFindings,
context: BugbotContext,
resolutionErrors: readonly Error[],
presentation?: BugbotPresentationReport,
): Result {
const hasFindingChanges = prepared.toPublish.length > 0 || prepared.resolvedFindingIds.size > 0;
const stepParts = hasFindingChanges
? [`${prepared.toPublish.length} new/current ${prepared.toPublish.length === 1 ? 'finding' : 'findings'} from configured agent`]
: ['no new findings, no resolved'];
if (prepared.overflowCount > 0) stepParts.push(`${prepared.overflowCount} more not published (see summary comment)`);
if (prepared.resolvedFindingIds.size > 0) stepParts.push(`${prepared.resolvedFindingIds.size} marked as resolved by configured agent`);
if (context.coverage.status === 'partial') {
stepParts.push('partial context coverage; this run does not declare the complete target clean');
}
const partitionCompletion = formatBugbotPartitionCompletion(context);
if (partitionCompletion.resultStep) stepParts.push(partitionCompletion.resultStep);
const statusSummary = presentation?.projection ?? projectBugbotFindingStatuses(
context.existingByFindingId,
prepared.activeFindings ?? prepared.toPublish,
prepared.resolvedFindingIds,
prepared.resolvedFindingResolutions,
);
stepParts.push(`states: ${formatStateCounts(statusSummary.counts)}`);
if (presentation) {
stepParts.push(`status card: ${presentation.statusCardOperation}`);
stepParts.push(`review status blocks updated: ${presentation.reviewUpdates}`);
if (presentation.pendingReviewUpdates > 0) {
stepParts.push(`review status blocks pending: ${presentation.pendingReviewUpdates}`);
}
}
return new Result({
id: TASK_ID,
success: resolutionErrors.length === 0,
executed: true,
steps: [`Potential problems detection completed. ${stepParts.join('; ')}.`],
errors: resolutionErrors.map(error => presentation
? toBugbotPresentationError(error)
: toBugbotApplicationError(
error,
'Bugbot finding publication or reconciliation failed.',
)),
payload: {
findingStates: statusSummary.counts,
contextCoverage: context.coverage,
...(presentation ? {
reviewProjection: presentation.projection,
statusCardOperation: presentation.statusCardOperation,
reviewUpdates: presentation.reviewUpdates,
pendingReviewUpdates: presentation.pendingReviewUpdates,
} : {}),
},
});
}
function formatStateCounts(counts: Readonly<Record<string, number>>): string {
return Object.entries(counts)
.filter(([, count]) => count > 0)
.map(([state, count]) => `${state}=${count}`)
.join(', ') || 'none';
}
function toBugbotApplicationError(error: unknown, fallbackMessage: string): ApplicationError {
if (error instanceof ApplicationError) return error;
const message = error instanceof PullRequestReviewOperationError ? error.message : fallbackMessage;
return new ApplicationError('provider.unavailable', message, { cause: error });
}
function toBugbotPresentationError(error: Error): ApplicationError {
if (error instanceof ApplicationError) return error;
const message = error instanceof PullRequestReviewOperationError
? error.message
: 'Bugbot finding presentation failed.';
return new ApplicationError('provider.unavailable', message, { cause: error });
}
async function reconcileReviewState(input: {
readonly operation: BugbotReviewOperationContext;
readonly loadedContext: BugbotContext;
readonly activeFindings: readonly BugbotFinding[];
readonly expectedPublishedFindings?: readonly BugbotFinding[];
readonly mutationErrors?: readonly Error[];
readonly dependencies: DetectPotentialProblemsWorkflowDependencies;
readonly catalog?: BugbotMessageCatalog;
}): Promise<BugbotPresentationReport | undefined> {
const pullRequestNumber = input.loadedContext.canonicalPullRequest?.number;
const analyzedHeadSha = input.loadedContext.prContext?.prHeadSha;
if (!pullRequestNumber || !analyzedHeadSha) return undefined;
return reconcileBugbotReviewState({
target: {
pullRequestNumber,
...(input.operation.target.issueNumber > 0
? { linkedIssueNumber: input.operation.target.issueNumber }
: {}),
analyzedHeadSha,
...(input.operation.trustedAuthorLogin
? { trustedAuthorLogin: input.operation.trustedAuthorLogin }
: {}),
locale: input.operation.locale.pullRequest,
},
loadedContext: input.loadedContext,
activeFindings: input.activeFindings,
...(input.expectedPublishedFindings
? { expectedPublishedFindings: input.expectedPublishedFindings }
: {}),
...(input.mutationErrors ? { mutationErrors: input.mutationErrors } : {}),
snapshotPorts: input.dependencies.scm.reconciliation.snapshot,
presentationPorts: input.dependencies.scm.reconciliation.presentation,
catalog: input.catalog,
});
}
function resolvePublicationCatalog(
operation: BugbotReviewOperationContext,
dependencies: DetectPotentialProblemsWorkflowDependencies,
publishesToPullRequest: boolean,
): Promise<BugbotMessageCatalog> {
const locale = publishesToPullRequest
? operation.locale.pullRequest
: operation.locale.issue ?? operation.locale.pullRequest;
return resolveBugbotCatalog(
locale,
operation.analysis.agentConfiguration,
dependencies.catalogResolver,
);
}