Repository navigation
Expand file tree
/
Copy pathapi.ts
More file actions
370 lines (349 loc) · 17.3 KB
/
Copy pathapi.ts
File metadata and controls
370 lines (349 loc) · 17.3 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
import type { Result } from './data/model/result';
import type { AgentConfiguration } from './domain/agent';
import type { FindingsQueryPort } from './application/ports/agent_findings_ports';
import type { BugbotScmPorts } from './application/ports/bugbot_scm_ports';
import type { BugbotTelemetryPort } from './application/ports/bugbot_telemetry_ports';
import type { BugbotReviewConfiguration } from './domain/bugbot/review_configuration';
import { DetectPotentialProblemsUseCase } from './application/usecases/steps/commit/detect_potential_problems_use_case';
import { ApplicationError, toApplicationError } from './application/errors/application_error';
import { runAtApplicationErrorBoundary } from './application/errors/application_error_context';
import { normalizeBugbotReviewConfiguration } from './domain/bugbot/review_configuration';
import type { BugbotReviewOperationContext } from './application/usecases/steps/commit/bugbot/bugbot_review_operation_context';
import type { MessageCatalogResolutionPort } from './application/ports/message_catalog_ports';
import { resolveLocaleProfile } from './domain/locale';
export type { MessageCatalogResolutionPort } from './application/ports/message_catalog_ports';
/** Already-bound SCM authority for exactly one repository. */
export interface BugbotScmGateway extends BugbotScmPorts {
readonly repository: {
readonly owner: string;
readonly name: string;
};
readonly telemetry?: BugbotTelemetryPort;
}
export type BugbotMinimumSeverity = 'info' | 'low' | 'medium' | 'high';
export type BugbotReviewTarget =
| {
readonly kind: 'pull-request';
readonly number: number;
readonly head: string;
readonly base?: string;
readonly linkedIssueNumber?: number;
readonly action?: 'opened' | 'reopened' | 'synchronize';
readonly expectedHeadSha?: string;
readonly before?: string;
readonly draft?: boolean;
}
| {
readonly kind: 'branch';
readonly branch: string;
readonly base?: string;
readonly issueNumber?: number;
readonly before?: string;
readonly after?: string;
};
/** Sole supported request for the programmatic Bugbot review entry point. */
export interface BugbotReviewRequest {
readonly target: BugbotReviewTarget;
readonly agent: AgentConfiguration;
readonly configuration?: Partial<BugbotReviewConfiguration>;
readonly ignoreFiles?: readonly string[];
readonly minimumSeverity?: BugbotMinimumSeverity;
readonly commentLimit?: number;
readonly authenticatedUser?: string;
readonly locale?: {
readonly issue?: string;
readonly pullRequest?: string;
};
}
/** Provider-neutral programmatic entry point. Consumers supply agent and SCM adapters. */
export class BugbotReviewService {
private readonly useCase: DetectPotentialProblemsUseCase;
private readonly repository: BugbotScmGateway['repository'];
constructor(
agent: FindingsQueryPort,
scm: BugbotScmGateway,
catalogResolver?: MessageCatalogResolutionPort,
) {
this.repository = snapshotRepositoryBinding(scm);
this.useCase = new DetectPotentialProblemsUseCase(
agent,
scm,
scm.telemetry,
catalogResolver,
);
}
async review(request: BugbotReviewRequest): Promise<readonly Result[]> {
return runAtApplicationErrorBoundary(async () => {
try {
return await this.useCase.invoke(
buildReviewOperationContext(request, this.repository),
);
} catch (cause) {
throw toApplicationError(cause, 'unexpected', 'Bugbot review failed.');
}
});
}
}
function snapshotRepositoryBinding(scm: BugbotScmGateway): BugbotScmGateway['repository'] {
return Object.freeze({
owner: requireText(scm?.repository?.owner, 'Bound repository owner', 100),
name: requireText(scm?.repository?.name, 'Bound repository name', 100),
});
}
function buildReviewOperationContext(
request: BugbotReviewRequest,
binding: BugbotScmGateway['repository'],
): BugbotReviewOperationContext {
if (!request || typeof request !== 'object') {
throw new ApplicationError('validation.invalid-input', 'Bugbot review request is missing or invalid.');
}
const owner = requireText(binding?.owner, 'Bound repository owner', 100);
const repository = requireText(binding?.name, 'Bound repository name', 100);
const commentLimit = request.commentLimit ?? 20;
if (!Number.isSafeInteger(commentLimit) || commentLimit < 1 || commentLimit > 100) {
throw new ApplicationError('configuration.invalid', 'Bugbot comment limit must be an integer between 1 and 100.');
}
if (!['opencode', 'codex', 'cursor'].includes(request.agent?.provider)) {
throw new ApplicationError('configuration.unsupported', 'The requested agent provider is not supported.');
}
validateAgentConfiguration(request.agent);
const target = normalizeTarget(request.target);
const agent = { ...request.agent };
const ignoreFiles = normalizeIgnoreFiles(request.ignoreFiles);
const configuration = validateReviewConfiguration(request.configuration);
const minimumSeverity = request.minimumSeverity ?? 'low';
if (!['info', 'low', 'medium', 'high'].includes(minimumSeverity)) {
throw new ApplicationError('configuration.invalid', 'Bugbot minimum severity is invalid.');
}
const normalizedConfiguration = normalizeBugbotReviewConfiguration(configuration);
const { organizationRules, ...reviewConfiguration } = normalizedConfiguration;
const isPullRequest = target.kind === 'pull-request';
const issueNumber = isPullRequest ? target.linkedIssueNumber ?? -1 : target.issueNumber ?? -1;
const branch = isPullRequest ? target.head : target.branch;
const eventName = isPullRequest ? 'pull_request' : 'push';
const action = isPullRequest ? target.action ?? 'synchronize' : '';
const authenticatedUser = optionalText(request.authenticatedUser, 'Authenticated user', 255);
const locale = normalizeReviewLocale(request.locale);
return Object.freeze({
repository: Object.freeze({ owner, name: repository }),
target: Object.freeze({
issueNumber,
isPullRequest,
pullRequestNumber: isPullRequest ? target.number : -1,
headBranch: branch,
commitBranch: branch,
baseBranch: target.base ?? 'develop',
pullRequestAction: action,
draft: isPullRequest ? target.draft ?? false : false,
}),
trigger: Object.freeze({
kind: eventName,
...(target.before ? { before: target.before } : {}),
...(!isPullRequest && target.after ? { after: target.after } : {}),
...(isPullRequest && target.expectedHeadSha
? { expectedHeadSha: target.expectedHeadSha.toLowerCase() }
: {}),
headOwner: owner,
}),
...(authenticatedUser ? { trustedAuthorLogin: authenticatedUser } : {}),
ignorePatterns: Object.freeze(ignoreFiles),
organizationRules: Object.freeze([...organizationRules]),
locale,
analysis: Object.freeze({
agentConfiguration: Object.freeze(agent),
minimumSeverity,
commentLimit,
reviewConfiguration: Object.freeze(reviewConfiguration),
}),
});
}
function normalizeReviewLocale(
value: BugbotReviewRequest['locale'],
): BugbotReviewOperationContext['locale'] {
if (value !== undefined && (value === null || typeof value !== 'object' || Array.isArray(value)
|| Object.keys(value).some(key => !['issue', 'pullRequest'].includes(key)))) {
throw new ApplicationError(
'configuration.invalid',
'Bugbot locale configuration must contain only issue and pullRequest BCP-47 tags.',
);
}
try {
const locale = resolveLocaleProfile('en-US', value?.issue, value?.pullRequest);
return Object.freeze({ issue: locale.issue, pullRequest: locale.pullRequest });
} catch {
throw new ApplicationError(
'configuration.invalid',
'Bugbot locale configuration contains an invalid BCP-47 tag.',
);
}
}
function normalizeTarget(target: BugbotReviewTarget): BugbotReviewTarget {
if (!target || !['pull-request', 'branch'].includes(target.kind)) {
throw new ApplicationError('validation.invalid-input', 'Bugbot review target must be a branch or pull request.');
}
if (target.kind === 'pull-request') {
if (!Number.isSafeInteger(target.number) || target.number < 1) {
throw new ApplicationError('validation.invalid-input', 'Pull request number must be a positive integer.');
}
validateOptionalPositiveInteger(target.linkedIssueNumber, 'Linked issue number');
if (target.action !== undefined && !['opened', 'reopened', 'synchronize'].includes(target.action)) {
throw new ApplicationError('validation.invalid-input', 'Pull request action is invalid.');
}
if (target.draft !== undefined && typeof target.draft !== 'boolean') {
throw new ApplicationError('validation.invalid-input', 'Pull request draft state is invalid.');
}
return {
...target,
head: requireText(target.head, 'Pull request head branch', 255),
base: optionalText(target.base, 'Pull request base branch', 255),
expectedHeadSha: optionalObjectId(target.expectedHeadSha, 'Expected pull request head SHA'),
before: optionalObjectId(target.before, 'Pull request before SHA'),
};
}
validateOptionalPositiveInteger(target.issueNumber, 'Issue number');
return {
...target,
branch: requireText(target.branch, 'Review branch', 255),
base: optionalText(target.base, 'Review base branch', 255),
before: optionalObjectId(target.before, 'Branch before SHA'),
after: optionalObjectId(target.after, 'Branch after SHA'),
};
}
function validateAgentConfiguration(agent: AgentConfiguration): void {
const allowedKeys = new Set(['provider', 'modelProvider', 'model', 'effort', 'executable']);
if (!agent || typeof agent !== 'object'
|| Object.keys(agent).some(key => !allowedKeys.has(key))
|| !['codex', 'opencode', 'cursor'].includes(agent.provider)
|| typeof agent.model !== 'string'
|| (agent.executable !== undefined && typeof agent.executable !== 'string')
|| (agent.modelProvider !== undefined && typeof agent.modelProvider !== 'string')
|| (agent.effort !== undefined && typeof agent.effort !== 'string')) {
throw new ApplicationError('configuration.invalid', 'Agent configuration is invalid.');
}
if (agent.model.length > 500 || (agent.executable?.length ?? 0) > 4_096
|| (agent.modelProvider?.length ?? 0) > 100 || (agent.effort?.length ?? 0) > 100) {
throw new ApplicationError('configuration.invalid', 'Agent configuration exceeds the supported limits.');
}
}
function normalizeIgnoreFiles(value: readonly string[] | undefined): string[] {
if (value === undefined) return [];
if (!Array.isArray(value) || value.length > 1_000
|| value.some(item => typeof item !== 'string' || item.length > 1_024 || /[\r\n\0]/u.test(item))) {
throw new ApplicationError('configuration.invalid', 'Bugbot ignored file patterns are invalid.');
}
return [...value];
}
function validateReviewConfiguration(
value: Partial<BugbotReviewConfiguration> | undefined,
): Partial<BugbotReviewConfiguration> | undefined {
if (value === undefined) return undefined;
if (!value || typeof value !== 'object' || Array.isArray(value)) {
throw new ApplicationError('configuration.invalid', 'Bugbot review configuration is invalid.');
}
const allowedKeys = new Set<keyof BugbotReviewConfiguration>([
'publicationMode', 'effort', 'reviewDrafts', 'traceRules', 'suggestedChanges',
'telemetry', 'failOnUnresolved', 'organizationRules',
]);
if (Object.keys(value).some(key => !allowedKeys.has(key as keyof BugbotReviewConfiguration))) {
throw new ApplicationError('configuration.invalid', 'Bugbot review configuration contains an unsupported field.');
}
if (value.publicationMode !== undefined && !['publish', 'dry-run'].includes(value.publicationMode)) {
throw new ApplicationError('configuration.invalid', 'Bugbot publication mode is invalid.');
}
if (value.effort !== undefined && !['low', 'default', 'high', 'smart'].includes(value.effort)) {
throw new ApplicationError('configuration.invalid', 'Bugbot review effort is invalid.');
}
const booleanKeys: readonly (keyof BugbotReviewConfiguration)[] = [
'reviewDrafts', 'traceRules', 'suggestedChanges', 'telemetry', 'failOnUnresolved',
];
if (booleanKeys.some(key => value[key] !== undefined && typeof value[key] !== 'boolean')) {
throw new ApplicationError('configuration.invalid', 'Bugbot review flags must be boolean values.');
}
if (value.organizationRules !== undefined
&& (!Array.isArray(value.organizationRules)
|| value.organizationRules.length > 100
|| value.organizationRules.some(rule => typeof rule !== 'string' || rule.length > 2_000))) {
throw new ApplicationError('configuration.invalid', 'Bugbot organization rules are invalid.');
}
return {
...value,
organizationRules: value.organizationRules ? [...value.organizationRules] : undefined,
};
}
function validateOptionalPositiveInteger(value: number | undefined, field: string): void {
if (value !== undefined && (!Number.isSafeInteger(value) || value < 1)) {
throw new ApplicationError('validation.invalid-input', `${field} must be a positive integer.`);
}
}
function optionalObjectId(value: string | undefined, field: string): string | undefined {
const normalized = optionalText(value, field, 64);
if (normalized !== undefined && !/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/u.test(normalized)) {
throw new ApplicationError('validation.invalid-input', `${field} is invalid.`);
}
return normalized;
}
function optionalText(value: string | undefined, field: string, maximum: number): string | undefined {
return value === undefined ? undefined : requireText(value, field, maximum);
}
function requireText(
value: unknown,
field: string,
maximum: number,
): string {
const normalized = typeof value === 'string' ? value.trim() : '';
if (!normalized || normalized.length > maximum || /[\r\n\0]/u.test(normalized)) {
throw new ApplicationError('validation.invalid-input', `${field} is missing or invalid.`);
}
return normalized;
}
export { evaluateBugbotFindings, evaluateBugbotQualityGate } from './tooling/bugbot_quality_eval';
export { evaluateBugbotBenchmark, loadBugbotBenchmark, loadBugbotPredictions } from './tooling/bugbot_benchmark';
export { buildBugbotAnalytics, parseBugbotTelemetry } from './tooling/bugbot_analytics';
export { buildSemanticFindingFingerprint, buildFindingFingerprint } from './domain/bugbot/finding_identity';
export { normalizeBugbotReviewConfiguration, resolveBugbotReviewEffort } from './domain/bugbot/review_configuration';
export {
BUGBOT_FINDING_STATES,
classifyBugbotFindingState,
countActionableBugbotFindings,
countBugbotFindingStates,
isBugbotActionableState,
isBugbotCleanState,
} from './domain/bugbot/review_state';
export { buildBugbotReviewProjection } from './domain/bugbot/review_projection';
export { ApplicationError } from './application/errors/application_error';
export type {
ApplicationErrorCode,
ApplicationErrorKind,
ApplicationErrorPublicRecord,
} from './application/errors/application_error';
export type { AgentConfiguration } from './domain/agent';
export type { FindingsQueryPort } from './application/ports/agent_findings_ports';
export type { BugbotContextPorts } from './application/ports/bugbot_context_ports';
export type { BugbotFindingPublicationPorts } from './application/ports/bugbot_finding_publication_ports';
export type { BugbotFindingResolutionPorts } from './application/ports/bugbot_finding_resolution_ports';
export type { BugbotScmPorts } from './application/ports/bugbot_scm_ports';
export type {
BugbotPresentationMutationPorts,
BugbotReconciliationSnapshotPorts,
} from './application/ports/bugbot_reconciliation_ports';
export type { BugbotTelemetryPort } from './application/ports/bugbot_telemetry_ports';
export type { BugbotReviewNavigation } from './application/ports/bugbot_review_navigation_ports';
export type { Result } from './data/model/result';
export type { BugbotFinding } from './domain/bugbot/finding';
export type { BugbotReviewConfiguration } from './domain/bugbot/review_configuration';
export type { BugbotReviewTelemetrySnapshot } from './application/ports/bugbot_telemetry_ports';
export type {
BugbotFindingState,
BugbotFindingStateCounts,
BugbotFindingEvidence,
BugbotResolvedFindingState,
} from './domain/bugbot/review_state';
export type {
BugbotProjectedFinding,
BugbotProjectionOutcome,
BugbotReviewProjection,
} from './domain/bugbot/review_projection';
export type {
PullRequestReviewReference,
PullRequestReviewSummary,
} from './application/ports/pull_request_review_comment_ports';