@auracheck-ai/cli 0.2.11 → 0.3.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +6 -0
- package/README.md +9 -0
- package/dist/bin.js +3502 -213
- package/dist/mcp/server.js +19 -2
- package/package.json +18 -13
- package/schema/auracheck.schema.json +295 -0
package/dist/bin.js
CHANGED
|
@@ -1,9 +1,308 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __esm = (fn, res, err) => function __init() {
|
|
5
|
+
if (err) throw err[0];
|
|
6
|
+
try {
|
|
7
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
8
|
+
} catch (e) {
|
|
9
|
+
throw err = [e], e;
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
var __export = (target, all) => {
|
|
13
|
+
for (var name in all)
|
|
14
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// src/review/config.ts
|
|
18
|
+
var config_exports = {};
|
|
19
|
+
__export(config_exports, {
|
|
20
|
+
CONFIG_FILENAMES: () => CONFIG_FILENAMES,
|
|
21
|
+
DEFAULT_GUIDELINE_PATTERNS: () => DEFAULT_GUIDELINE_PATTERNS,
|
|
22
|
+
auraCheckConfigSchema: () => auraCheckConfigSchema,
|
|
23
|
+
defaultConfig: () => defaultConfig,
|
|
24
|
+
isIndonesian: () => isIndonesian,
|
|
25
|
+
loadReviewConfig: () => loadReviewConfig,
|
|
26
|
+
parseConfigObject: () => parseConfigObject,
|
|
27
|
+
toServerConfig: () => toServerConfig
|
|
28
|
+
});
|
|
29
|
+
import { promises as fs4 } from "fs";
|
|
30
|
+
import path3 from "path";
|
|
31
|
+
import { parse as parseYaml } from "yaml";
|
|
32
|
+
import { z as z18 } from "zod";
|
|
33
|
+
function defaultConfig() {
|
|
34
|
+
return auraCheckConfigSchema.parse({});
|
|
35
|
+
}
|
|
36
|
+
function isCodeRabbitKey(dotted) {
|
|
37
|
+
if (/^reviews\.tools\.[^.]+$/.test(dotted)) return true;
|
|
38
|
+
if (dotted.startsWith("reviews.tools.") && dotted.split(".").length > 3) {
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
for (const k of CODERABBIT_KEYS) {
|
|
42
|
+
if (dotted === k || dotted.startsWith(`${k}.`)) return true;
|
|
43
|
+
}
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
function unwrap(schema) {
|
|
47
|
+
let s = schema;
|
|
48
|
+
for (; ; ) {
|
|
49
|
+
const t = s?._def?.typeName;
|
|
50
|
+
if (t === "ZodDefault" || t === "ZodOptional" || t === "ZodNullable") {
|
|
51
|
+
s = s._def.innerType;
|
|
52
|
+
} else if (t === "ZodEffects") {
|
|
53
|
+
s = s._def.schema;
|
|
54
|
+
} else {
|
|
55
|
+
return s;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function collectUnknownKeys(raw, schema, prefix, out) {
|
|
60
|
+
const s = unwrap(schema);
|
|
61
|
+
if (s?._def?.typeName !== "ZodObject") return;
|
|
62
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return;
|
|
63
|
+
const shape = s.shape;
|
|
64
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
65
|
+
const dotted = prefix ? `${prefix}.${key}` : key;
|
|
66
|
+
if (key in shape) {
|
|
67
|
+
collectUnknownKeys(value, shape[key], dotted, out);
|
|
68
|
+
} else if (!isCodeRabbitKey(dotted)) {
|
|
69
|
+
out.push(dotted);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function deletePath(obj, p) {
|
|
74
|
+
if (p.length === 0) return false;
|
|
75
|
+
let cur = obj;
|
|
76
|
+
for (const seg of p.slice(0, -1)) {
|
|
77
|
+
if (cur == null || typeof cur !== "object") return false;
|
|
78
|
+
cur = cur[seg];
|
|
79
|
+
}
|
|
80
|
+
if (cur == null || typeof cur !== "object") return false;
|
|
81
|
+
const last = p[p.length - 1];
|
|
82
|
+
if (Array.isArray(cur) && typeof last === "number") {
|
|
83
|
+
cur.splice(last, 1);
|
|
84
|
+
} else {
|
|
85
|
+
delete cur[last];
|
|
86
|
+
}
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
function normalizeRaw(raw) {
|
|
90
|
+
const cg = raw?.knowledge_base?.code_guidelines;
|
|
91
|
+
if (cg && typeof cg === "object" && cg.filePatterns && !cg.file_patterns) {
|
|
92
|
+
cg.file_patterns = cg.filePatterns;
|
|
93
|
+
}
|
|
94
|
+
return raw;
|
|
95
|
+
}
|
|
96
|
+
function parseConfigObject(raw) {
|
|
97
|
+
const warnings = [];
|
|
98
|
+
if (raw == null) return { config: defaultConfig(), warnings };
|
|
99
|
+
if (typeof raw !== "object" || Array.isArray(raw)) {
|
|
100
|
+
warnings.push("config is not a YAML mapping; using defaults");
|
|
101
|
+
return { config: defaultConfig(), warnings };
|
|
102
|
+
}
|
|
103
|
+
const doc = normalizeRaw(structuredClone(raw));
|
|
104
|
+
const unknown = [];
|
|
105
|
+
collectUnknownKeys(doc, auraCheckConfigSchema, "", unknown);
|
|
106
|
+
for (const k of unknown) warnings.push(`unknown key "${k}" ignored`);
|
|
107
|
+
for (let attempt = 0; attempt < 20; attempt++) {
|
|
108
|
+
const res = auraCheckConfigSchema.safeParse(doc);
|
|
109
|
+
if (res.success) return { config: res.data, warnings };
|
|
110
|
+
let removed = false;
|
|
111
|
+
for (const issue of res.error.issues) {
|
|
112
|
+
warnings.push(
|
|
113
|
+
`invalid value at "${issue.path.join(".")}": ${issue.message}; using the default`
|
|
114
|
+
);
|
|
115
|
+
removed = deletePath(doc, issue.path) || removed;
|
|
116
|
+
}
|
|
117
|
+
if (!removed) break;
|
|
118
|
+
}
|
|
119
|
+
warnings.push("config could not be validated; using defaults");
|
|
120
|
+
return { config: defaultConfig(), warnings };
|
|
121
|
+
}
|
|
122
|
+
async function loadReviewConfig(projectDir) {
|
|
123
|
+
for (const name of CONFIG_FILENAMES) {
|
|
124
|
+
const file = path3.join(projectDir, name);
|
|
125
|
+
let text;
|
|
126
|
+
try {
|
|
127
|
+
text = await fs4.readFile(file, "utf8");
|
|
128
|
+
} catch {
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
let raw;
|
|
132
|
+
try {
|
|
133
|
+
raw = parseYaml(text);
|
|
134
|
+
} catch (err) {
|
|
135
|
+
return {
|
|
136
|
+
config: defaultConfig(),
|
|
137
|
+
warnings: [
|
|
138
|
+
`${name} is not valid YAML (${err.message}); using defaults`
|
|
139
|
+
],
|
|
140
|
+
source: `${name} (invalid, defaults used)`
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
const parsed = parseConfigObject(raw);
|
|
144
|
+
return {
|
|
145
|
+
...parsed,
|
|
146
|
+
warnings: parsed.warnings.map((w) => `${name}: ${w}`),
|
|
147
|
+
source: name
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
return { config: defaultConfig(), warnings: [], source: "defaults" };
|
|
151
|
+
}
|
|
152
|
+
function isIndonesian(config) {
|
|
153
|
+
return config.language.toLowerCase().startsWith("id");
|
|
154
|
+
}
|
|
155
|
+
function toServerConfig(config) {
|
|
156
|
+
const r = config.reviews;
|
|
157
|
+
return {
|
|
158
|
+
profile: r.profile,
|
|
159
|
+
language: config.language,
|
|
160
|
+
toneInstructions: config.tone_instructions,
|
|
161
|
+
pathInstructions: r.path_instructions.map((p) => ({
|
|
162
|
+
path: p.path,
|
|
163
|
+
instructions: p.instructions
|
|
164
|
+
})),
|
|
165
|
+
mergeRiskInstructions: r.merge_risk_instructions,
|
|
166
|
+
securityRiskInstructions: r.security_risk_instructions,
|
|
167
|
+
maxInlineComments: r.max_inline_comments,
|
|
168
|
+
promptForAiAgents: r.enable_prompt_for_ai_agents,
|
|
169
|
+
optOut: config.knowledge_base.opt_out
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
var CONFIG_FILENAMES, DEFAULT_GUIDELINE_PATTERNS, checkMode, toolToggle, auraCheckConfigSchema, CODERABBIT_KEYS;
|
|
173
|
+
var init_config = __esm({
|
|
174
|
+
"src/review/config.ts"() {
|
|
175
|
+
"use strict";
|
|
176
|
+
CONFIG_FILENAMES = [".auracheck.yaml", ".auracheck.yml"];
|
|
177
|
+
DEFAULT_GUIDELINE_PATTERNS = [
|
|
178
|
+
"AGENTS.md",
|
|
179
|
+
"CLAUDE.md",
|
|
180
|
+
"CONTRIBUTING.md",
|
|
181
|
+
".cursorrules",
|
|
182
|
+
".github/copilot-instructions.md"
|
|
183
|
+
];
|
|
184
|
+
checkMode = z18.preprocess(
|
|
185
|
+
(v) => v === false ? "off" : v === true ? "warning" : v,
|
|
186
|
+
z18.enum(["off", "warning", "error"])
|
|
187
|
+
);
|
|
188
|
+
toolToggle = z18.object({ enabled: z18.boolean().default(true) }).default({});
|
|
189
|
+
auraCheckConfigSchema = z18.object({
|
|
190
|
+
language: z18.string().default("en").describe('Language of the review prose, e.g. "en" or "id".'),
|
|
191
|
+
tone_instructions: z18.string().max(250).optional().describe("Extra instructions for the tone of the review comments."),
|
|
192
|
+
reviews: z18.object({
|
|
193
|
+
profile: z18.enum(["quiet", "chill", "assertive"]).default("chill").describe(
|
|
194
|
+
"quiet: only likely bugs and security; chill: balanced; assertive: also nitpicks."
|
|
195
|
+
),
|
|
196
|
+
high_level_summary: z18.boolean().default(true).describe(
|
|
197
|
+
'Write the "what this MR changes" summary into the MR description in place of the placeholder.'
|
|
198
|
+
),
|
|
199
|
+
high_level_summary_placeholder: z18.string().default("@auracheck summary").describe(
|
|
200
|
+
"Text in the MR description that the summary replaces (once; later runs update the block)."
|
|
201
|
+
),
|
|
202
|
+
changed_files_summary: z18.boolean().default(true),
|
|
203
|
+
estimate_code_review_effort: z18.boolean().default(true),
|
|
204
|
+
assess_linked_issues: z18.boolean().default(true),
|
|
205
|
+
collapse_walkthrough: z18.boolean().default(false),
|
|
206
|
+
commit_status: z18.boolean().default(true).describe('Set an "AuraCheck review" commit status on the MR head.'),
|
|
207
|
+
fail_commit_status: z18.boolean().default(false).describe("Mark that commit status failed when the review errors."),
|
|
208
|
+
enable_prompt_for_ai_agents: z18.boolean().default(true),
|
|
209
|
+
max_inline_comments: z18.number().int().min(0).max(50).default(8).describe("At most this many inline discussions per run."),
|
|
210
|
+
path_filters: z18.array(z18.string()).default([]).describe(
|
|
211
|
+
'Globs. "!glob" excludes matching files; plain globs keep only matching files.'
|
|
212
|
+
),
|
|
213
|
+
path_instructions: z18.array(z18.object({ path: z18.string(), instructions: z18.string() })).default([]),
|
|
214
|
+
merge_risk_instructions: z18.string().optional(),
|
|
215
|
+
security_risk_instructions: z18.string().optional(),
|
|
216
|
+
auto_review: z18.object({
|
|
217
|
+
enabled: z18.boolean().default(true),
|
|
218
|
+
auto_incremental_review: z18.boolean().default(true).describe(
|
|
219
|
+
"Review only the files changed since the last reviewed commit."
|
|
220
|
+
),
|
|
221
|
+
drafts: z18.boolean().default(false),
|
|
222
|
+
base_branches: z18.array(z18.string()).default([]).describe(
|
|
223
|
+
"Regexes of target branches to review besides the default branch."
|
|
224
|
+
),
|
|
225
|
+
ignore_title_keywords: z18.array(z18.string()).default(["[skip review]"]),
|
|
226
|
+
labels: z18.array(z18.string()).default([]).describe(
|
|
227
|
+
'"!label" skips MRs with that label; plain entries review only MRs with one of them.'
|
|
228
|
+
),
|
|
229
|
+
ignore_usernames: z18.array(z18.string()).default([])
|
|
230
|
+
}).default({}),
|
|
231
|
+
pre_merge_checks: z18.object({
|
|
232
|
+
title: z18.object({
|
|
233
|
+
mode: checkMode.default("warning"),
|
|
234
|
+
requirements: z18.string().optional().describe(
|
|
235
|
+
"A regex the title must match, written as /pattern/flags or starting with ^."
|
|
236
|
+
)
|
|
237
|
+
}).default({}),
|
|
238
|
+
description: z18.object({ mode: checkMode.default("warning") }).default({}),
|
|
239
|
+
issue_assessment: z18.object({ mode: checkMode.default("warning") }).default({})
|
|
240
|
+
}).default({}),
|
|
241
|
+
tools: z18.object({
|
|
242
|
+
biome: toolToggle,
|
|
243
|
+
eslint: toolToggle,
|
|
244
|
+
gitleaks: toolToggle,
|
|
245
|
+
osv: toolToggle
|
|
246
|
+
}).default({})
|
|
247
|
+
}).default({}),
|
|
248
|
+
knowledge_base: z18.object({
|
|
249
|
+
opt_out: z18.boolean().default(false).describe("Keep nothing beyond usage counters on the server."),
|
|
250
|
+
code_guidelines: z18.object({
|
|
251
|
+
enabled: z18.boolean().default(true),
|
|
252
|
+
file_patterns: z18.array(z18.string()).default(DEFAULT_GUIDELINE_PATTERNS)
|
|
253
|
+
}).default({})
|
|
254
|
+
}).default({})
|
|
255
|
+
}).describe("AuraCheck PR review configuration (.auracheck.yaml)");
|
|
256
|
+
CODERABBIT_KEYS = /* @__PURE__ */ new Set([
|
|
257
|
+
"$schema",
|
|
258
|
+
"early_access",
|
|
259
|
+
"enable_free_tier",
|
|
260
|
+
"inheritance",
|
|
261
|
+
"chat",
|
|
262
|
+
"code_generation",
|
|
263
|
+
"issue_enrichment",
|
|
264
|
+
"reviews.poem",
|
|
265
|
+
"reviews.review_status",
|
|
266
|
+
"reviews.review_details",
|
|
267
|
+
"reviews.request_changes_workflow",
|
|
268
|
+
"reviews.high_level_summary_in_walkthrough",
|
|
269
|
+
"reviews.high_level_summary_instructions",
|
|
270
|
+
"reviews.auto_title_placeholder",
|
|
271
|
+
"reviews.auto_title_instructions",
|
|
272
|
+
"reviews.sequence_diagrams",
|
|
273
|
+
"reviews.related_issues",
|
|
274
|
+
"reviews.related_prs",
|
|
275
|
+
"reviews.suggested_labels",
|
|
276
|
+
"reviews.labeling_instructions",
|
|
277
|
+
"reviews.auto_apply_labels",
|
|
278
|
+
"reviews.suggested_reviewers",
|
|
279
|
+
"reviews.auto_assign_reviewers",
|
|
280
|
+
"reviews.in_progress_fortune",
|
|
281
|
+
"reviews.abort_on_close",
|
|
282
|
+
"reviews.disable_cache",
|
|
283
|
+
"reviews.slop_detection",
|
|
284
|
+
"reviews.finishing_touches",
|
|
285
|
+
"reviews.auto_review.description_keyword",
|
|
286
|
+
"reviews.auto_review.auto_pause_after_reviewed_commits",
|
|
287
|
+
"reviews.pre_merge_checks.docstrings",
|
|
288
|
+
"reviews.pre_merge_checks.custom_checks",
|
|
289
|
+
"reviews.pre_merge_checks.override_requested_reviewers_only",
|
|
290
|
+
"knowledge_base.web_search",
|
|
291
|
+
"knowledge_base.learnings",
|
|
292
|
+
"knowledge_base.issues",
|
|
293
|
+
"knowledge_base.jira",
|
|
294
|
+
"knowledge_base.linear",
|
|
295
|
+
"knowledge_base.pull_requests",
|
|
296
|
+
"knowledge_base.mcp",
|
|
297
|
+
"knowledge_base.code_guidelines.filePatterns"
|
|
298
|
+
]);
|
|
299
|
+
}
|
|
300
|
+
});
|
|
2
301
|
|
|
3
302
|
// src/bin.ts
|
|
4
|
-
import
|
|
303
|
+
import path9 from "path";
|
|
5
304
|
import { Command } from "commander";
|
|
6
|
-
import
|
|
305
|
+
import pc7 from "picocolors";
|
|
7
306
|
|
|
8
307
|
// src/commands/doctor.ts
|
|
9
308
|
import pc from "picocolors";
|
|
@@ -74,8 +373,8 @@ var AuraCheckApi = class {
|
|
|
74
373
|
dispatcherInit() {
|
|
75
374
|
return this.dispatcher ? { dispatcher: this.dispatcher } : {};
|
|
76
375
|
}
|
|
77
|
-
async request(method,
|
|
78
|
-
const url = `${this.baseUrl}${
|
|
376
|
+
async request(method, path10, body) {
|
|
377
|
+
const url = `${this.baseUrl}${path10}`;
|
|
79
378
|
const headers = {
|
|
80
379
|
Authorization: `Bearer ${this.token}`,
|
|
81
380
|
Accept: "application/json",
|
|
@@ -104,7 +403,7 @@ var AuraCheckApi = class {
|
|
|
104
403
|
}
|
|
105
404
|
const text = await res.text();
|
|
106
405
|
if (!res.ok) {
|
|
107
|
-
let msg = `${method} ${
|
|
406
|
+
let msg = `${method} ${path10} -> ${res.status}`;
|
|
108
407
|
let serverError = "";
|
|
109
408
|
try {
|
|
110
409
|
const parsed = JSON.parse(text);
|
|
@@ -345,8 +644,8 @@ var AuraCheckApi = class {
|
|
|
345
644
|
* which finds/creates the project's external-results container.
|
|
346
645
|
*/
|
|
347
646
|
async recordResults(input) {
|
|
348
|
-
const
|
|
349
|
-
const { success, data } = await this.request("POST",
|
|
647
|
+
const path10 = input.runId ? `/api/runs/${input.runId}/results` : `/api/projects/${input.projectId}/results`;
|
|
648
|
+
const { success, data } = await this.request("POST", path10, input);
|
|
350
649
|
if (!success)
|
|
351
650
|
throw new ApiError(500, "", "record_result failed");
|
|
352
651
|
return data;
|
|
@@ -490,6 +789,20 @@ function requireProjectId(ctx, explicit) {
|
|
|
490
789
|
}
|
|
491
790
|
|
|
492
791
|
// ../mcp-core/dist/errors.js
|
|
792
|
+
function resetClause(resetsAt) {
|
|
793
|
+
if (!resetsAt)
|
|
794
|
+
return "";
|
|
795
|
+
const d = new Date(resetsAt);
|
|
796
|
+
if (Number.isNaN(d.getTime()))
|
|
797
|
+
return "";
|
|
798
|
+
const day = new Intl.DateTimeFormat("en-GB", {
|
|
799
|
+
day: "numeric",
|
|
800
|
+
month: "short",
|
|
801
|
+
year: "numeric",
|
|
802
|
+
timeZone: "Asia/Jakarta"
|
|
803
|
+
}).format(d);
|
|
804
|
+
return ` It resets on ${day}.`;
|
|
805
|
+
}
|
|
493
806
|
function parseBody(bodyText) {
|
|
494
807
|
try {
|
|
495
808
|
return JSON.parse(bodyText);
|
|
@@ -525,7 +838,7 @@ function mapApiError(err, ctx, requiresCapability) {
|
|
|
525
838
|
const actionClause = isAdmin ? `Upgrade your plan or buy an AI-run top-up: ${ctx.renewalUrl}` : contact2 ? `Ask ${contactName(contact2)} to upgrade or buy a top-up.` : "Ask your admin to upgrade or buy a top-up.";
|
|
526
839
|
return {
|
|
527
840
|
blocked: true,
|
|
528
|
-
message: `
|
|
841
|
+
message: `The AI test run quota for this period (${body.limit} per month) is used up.${resetClause(body.resetsAt)} You can still run this case manually. ${actionClause}`
|
|
529
842
|
};
|
|
530
843
|
}
|
|
531
844
|
if (body.isCompanyAdmin ?? isCompanyAdminRole(account)) {
|
|
@@ -1167,6 +1480,9 @@ function stripSecrets(value, depth = 0) {
|
|
|
1167
1480
|
if (depth > MAX_DEPTH || value === null || value === void 0) {
|
|
1168
1481
|
return value;
|
|
1169
1482
|
}
|
|
1483
|
+
if (value instanceof Uint8Array) {
|
|
1484
|
+
return value;
|
|
1485
|
+
}
|
|
1170
1486
|
if (Array.isArray(value)) {
|
|
1171
1487
|
return value.map((v) => stripSecrets(v, depth + 1));
|
|
1172
1488
|
}
|
|
@@ -2045,7 +2361,7 @@ function tokenize(source) {
|
|
|
2045
2361
|
function parseTableRow(text) {
|
|
2046
2362
|
const trimmed = text.trim();
|
|
2047
2363
|
const inner = trimmed.replace(/^\|/, "").replace(/\|$/, "");
|
|
2048
|
-
return inner.split("|").map((
|
|
2364
|
+
return inner.split("|").map((cell2) => cell2.trim());
|
|
2049
2365
|
}
|
|
2050
2366
|
function parseTags(line) {
|
|
2051
2367
|
const out = [];
|
|
@@ -5547,157 +5863,3103 @@ async function authStatusCommand(opts) {
|
|
|
5547
5863
|
}
|
|
5548
5864
|
}
|
|
5549
5865
|
|
|
5550
|
-
// src/commands/
|
|
5551
|
-
import { spawn as spawn2, spawnSync } from "child_process";
|
|
5552
|
-
import { promises as fs3 } from "fs";
|
|
5553
|
-
import path3 from "path";
|
|
5866
|
+
// src/commands/review.ts
|
|
5554
5867
|
import pc4 from "picocolors";
|
|
5555
|
-
|
|
5556
|
-
|
|
5557
|
-
|
|
5558
|
-
|
|
5559
|
-
}
|
|
5560
|
-
return r.status === 0;
|
|
5868
|
+
|
|
5869
|
+
// src/review/client.ts
|
|
5870
|
+
var REVIEW_TIMEOUT_MS = 24e4;
|
|
5871
|
+
function reviewEndpoint(baseUrl) {
|
|
5872
|
+
return `${baseUrl.replace(/\/+$/, "")}/api/code-review/review`;
|
|
5561
5873
|
}
|
|
5562
|
-
function
|
|
5563
|
-
|
|
5564
|
-
|
|
5874
|
+
function looksLikeResponse(x) {
|
|
5875
|
+
return x && typeof x === "object" && Array.isArray(x.findings) && x.summary && typeof x.summary === "object" && x.stats && x.coverage && x.usage;
|
|
5876
|
+
}
|
|
5877
|
+
function createReviewServer(opts) {
|
|
5878
|
+
const fetchImpl = opts.fetch ?? globalThis.fetch;
|
|
5879
|
+
return async (req) => {
|
|
5880
|
+
let res;
|
|
5881
|
+
try {
|
|
5882
|
+
res = await fetchImpl(reviewEndpoint(opts.baseUrl), {
|
|
5883
|
+
method: "POST",
|
|
5884
|
+
headers: {
|
|
5885
|
+
authorization: `Bearer ${opts.token}`,
|
|
5886
|
+
"content-type": "application/json",
|
|
5887
|
+
accept: "application/json",
|
|
5888
|
+
"user-agent": opts.userAgent ?? "auracheck-cli"
|
|
5889
|
+
},
|
|
5890
|
+
body: JSON.stringify(req),
|
|
5891
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? REVIEW_TIMEOUT_MS)
|
|
5892
|
+
});
|
|
5893
|
+
} catch (err) {
|
|
5894
|
+
const timedOut = err?.name === "TimeoutError" || err?.name === "AbortError";
|
|
5895
|
+
return {
|
|
5896
|
+
kind: "error",
|
|
5897
|
+
message: timedOut ? `the AuraCheck server did not answer within ${Math.round((opts.timeoutMs ?? REVIEW_TIMEOUT_MS) / 1e3)} s` : `cannot reach AuraCheck (${err?.cause?.code ?? err?.message ?? "network error"})`
|
|
5898
|
+
};
|
|
5899
|
+
}
|
|
5900
|
+
const text = await res.text().catch(() => "");
|
|
5901
|
+
let body = null;
|
|
5902
|
+
try {
|
|
5903
|
+
body = text ? JSON.parse(text) : null;
|
|
5904
|
+
} catch {
|
|
5905
|
+
body = null;
|
|
5906
|
+
}
|
|
5907
|
+
if (res.status === 429 && body && typeof body.limit === "number") {
|
|
5908
|
+
return { kind: "limit", error: body };
|
|
5909
|
+
}
|
|
5910
|
+
if (res.status === 401 || res.status === 403) {
|
|
5911
|
+
return {
|
|
5912
|
+
kind: "error",
|
|
5913
|
+
status: res.status,
|
|
5914
|
+
message: `AuraCheck rejected the token (${res.status}); check the AURACHECK_TOKEN CI variable`
|
|
5915
|
+
};
|
|
5916
|
+
}
|
|
5917
|
+
if (!res.ok) {
|
|
5918
|
+
const detail = body && (body.message || body.error) || text.slice(0, 200) || "";
|
|
5919
|
+
return {
|
|
5920
|
+
kind: "error",
|
|
5921
|
+
status: res.status,
|
|
5922
|
+
message: `AuraCheck returned ${res.status}${detail ? ` (${String(detail).slice(0, 200)})` : ""}`
|
|
5923
|
+
};
|
|
5924
|
+
}
|
|
5925
|
+
if (!looksLikeResponse(body)) {
|
|
5926
|
+
return {
|
|
5927
|
+
kind: "error",
|
|
5928
|
+
status: res.status,
|
|
5929
|
+
message: "AuraCheck sent a response this CLI version cannot read; update @auracheck-ai/cli"
|
|
5930
|
+
};
|
|
5931
|
+
}
|
|
5932
|
+
return { kind: "ok", response: body };
|
|
5933
|
+
};
|
|
5934
|
+
}
|
|
5935
|
+
|
|
5936
|
+
// src/review/gitlab.ts
|
|
5937
|
+
var GitLabError = class extends Error {
|
|
5938
|
+
constructor(status, message) {
|
|
5939
|
+
super(message);
|
|
5940
|
+
this.status = status;
|
|
5941
|
+
this.name = "GitLabError";
|
|
5565
5942
|
}
|
|
5566
|
-
|
|
5943
|
+
status;
|
|
5944
|
+
};
|
|
5945
|
+
var MAX_PAGES = 50;
|
|
5946
|
+
var ISSUE_TEXT_CAP = 1500;
|
|
5947
|
+
var MAX_LINKED_ISSUES = 5;
|
|
5948
|
+
function parseIssueRefs(description) {
|
|
5949
|
+
const out = [];
|
|
5950
|
+
const text = description.replace(/```[\s\S]*?```/g, " ").replace(/`[^`\n]*`/g, " ");
|
|
5951
|
+
const re = /(?:^|[\s(\[,;:])#(\d{1,7})\b/g;
|
|
5952
|
+
for (const m of text.matchAll(re)) {
|
|
5953
|
+
const n = Number(m[1]);
|
|
5954
|
+
if (n > 0 && !out.includes(n)) out.push(n);
|
|
5955
|
+
}
|
|
5956
|
+
return out;
|
|
5957
|
+
}
|
|
5958
|
+
function truncate2(s, n) {
|
|
5959
|
+
return s.length > n ? `${s.slice(0, n)}\u2026` : s;
|
|
5960
|
+
}
|
|
5961
|
+
function toNote(n) {
|
|
5567
5962
|
return {
|
|
5568
|
-
|
|
5569
|
-
|
|
5570
|
-
|
|
5963
|
+
id: n.id,
|
|
5964
|
+
body: n.body ?? "",
|
|
5965
|
+
authorId: n.author?.id ?? -1,
|
|
5966
|
+
authorUsername: n.author?.username ?? "",
|
|
5967
|
+
createdAt: n.created_at ?? "",
|
|
5968
|
+
system: !!n.system
|
|
5571
5969
|
};
|
|
5572
5970
|
}
|
|
5573
|
-
|
|
5574
|
-
|
|
5575
|
-
|
|
5576
|
-
|
|
5577
|
-
|
|
5578
|
-
|
|
5579
|
-
|
|
5580
|
-
|
|
5971
|
+
var GitLabProvider = class _GitLabProvider {
|
|
5972
|
+
kind = "gitlab";
|
|
5973
|
+
apiUrl;
|
|
5974
|
+
project;
|
|
5975
|
+
projectIdRaw;
|
|
5976
|
+
token;
|
|
5977
|
+
fetchImpl;
|
|
5978
|
+
delays;
|
|
5979
|
+
warn;
|
|
5980
|
+
constructor(opts) {
|
|
5981
|
+
this.apiUrl = opts.apiUrl.replace(/\/+$/, "");
|
|
5982
|
+
this.project = encodeURIComponent(opts.projectId);
|
|
5983
|
+
this.projectIdRaw = opts.projectId;
|
|
5984
|
+
this.token = opts.token;
|
|
5985
|
+
this.fetchImpl = opts.fetch ?? globalThis.fetch;
|
|
5986
|
+
this.delays = opts.retryDelaysMs ?? [1e3, 3e3];
|
|
5987
|
+
this.warn = opts.warn ?? (() => {
|
|
5988
|
+
});
|
|
5581
5989
|
}
|
|
5582
|
-
|
|
5583
|
-
const
|
|
5584
|
-
|
|
5585
|
-
|
|
5586
|
-
|
|
5587
|
-
);
|
|
5588
|
-
child.on("exit", (code) => resolve(code === 0));
|
|
5589
|
-
child.on("error", () => resolve(false));
|
|
5590
|
-
});
|
|
5591
|
-
}
|
|
5592
|
-
function printManualSnippets(target, invocation) {
|
|
5593
|
-
const argsJson = JSON.stringify(invocation.args);
|
|
5594
|
-
if (target === "cursor") {
|
|
5595
|
-
process.stdout.write(
|
|
5596
|
-
`
|
|
5597
|
-
${pc4.bold("Add to")} ${pc4.cyan(".cursor/mcp.json")}:
|
|
5598
|
-
`
|
|
5599
|
-
);
|
|
5600
|
-
process.stdout.write(
|
|
5601
|
-
`${pc4.dim(
|
|
5602
|
-
JSON.stringify(
|
|
5603
|
-
{
|
|
5604
|
-
mcpServers: {
|
|
5605
|
-
auracheck: { command: invocation.command, args: invocation.args }
|
|
5606
|
-
}
|
|
5607
|
-
},
|
|
5608
|
-
null,
|
|
5609
|
-
2
|
|
5610
|
-
)
|
|
5611
|
-
)}
|
|
5612
|
-
`
|
|
5990
|
+
url(p, query) {
|
|
5991
|
+
const base = p.startsWith("/user") ? `${this.apiUrl}${p}` : `${this.apiUrl}/projects/${this.project}${p}`;
|
|
5992
|
+
if (!query) return base;
|
|
5993
|
+
const qs = new URLSearchParams(
|
|
5994
|
+
Object.entries(query).map(([k, v]) => [k, String(v)])
|
|
5613
5995
|
);
|
|
5614
|
-
return
|
|
5996
|
+
return `${base}?${qs}`;
|
|
5615
5997
|
}
|
|
5616
|
-
|
|
5617
|
-
|
|
5618
|
-
|
|
5619
|
-
|
|
5620
|
-
|
|
5621
|
-
|
|
5622
|
-
|
|
5623
|
-
|
|
5624
|
-
|
|
5625
|
-
|
|
5626
|
-
|
|
5627
|
-
|
|
5628
|
-
}
|
|
5998
|
+
async request(method, p, opts = {}) {
|
|
5999
|
+
const idempotent = method !== "POST";
|
|
6000
|
+
const url = this.url(p, opts.query);
|
|
6001
|
+
for (let attempt = 0; ; attempt++) {
|
|
6002
|
+
let res;
|
|
6003
|
+
try {
|
|
6004
|
+
res = await this.fetchImpl(url, {
|
|
6005
|
+
method,
|
|
6006
|
+
headers: {
|
|
6007
|
+
"PRIVATE-TOKEN": this.token,
|
|
6008
|
+
accept: "application/json",
|
|
6009
|
+
...opts.body !== void 0 ? { "content-type": "application/json" } : {}
|
|
5629
6010
|
},
|
|
5630
|
-
|
|
5631
|
-
|
|
5632
|
-
|
|
5633
|
-
|
|
5634
|
-
|
|
5635
|
-
|
|
5636
|
-
|
|
6011
|
+
body: opts.body !== void 0 ? JSON.stringify(opts.body) : void 0
|
|
6012
|
+
});
|
|
6013
|
+
} catch (err) {
|
|
6014
|
+
if (idempotent && attempt < this.delays.length) {
|
|
6015
|
+
await sleep(this.delays[attempt]);
|
|
6016
|
+
continue;
|
|
6017
|
+
}
|
|
6018
|
+
throw new GitLabError(
|
|
6019
|
+
0,
|
|
6020
|
+
`GitLab ${method} ${p}: ${err?.message ?? err}`
|
|
6021
|
+
);
|
|
6022
|
+
}
|
|
6023
|
+
const retryable = res.status === 429 || idempotent && res.status >= 500;
|
|
6024
|
+
if (retryable && attempt < this.delays.length) {
|
|
6025
|
+
const retryAfter = Number(res.headers.get("retry-after"));
|
|
6026
|
+
const wait = Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter * 1e3, 1e4) : this.delays[attempt];
|
|
6027
|
+
await sleep(wait);
|
|
6028
|
+
continue;
|
|
6029
|
+
}
|
|
6030
|
+
const text = await res.text();
|
|
6031
|
+
let data = null;
|
|
6032
|
+
try {
|
|
6033
|
+
data = text ? JSON.parse(text) : null;
|
|
6034
|
+
} catch {
|
|
6035
|
+
data = text;
|
|
6036
|
+
}
|
|
6037
|
+
if (!res.ok) {
|
|
6038
|
+
const detail = typeof data === "object" && data ? JSON.stringify(data.message ?? data.error ?? data) : String(data ?? "").slice(0, 200);
|
|
6039
|
+
throw new GitLabError(
|
|
6040
|
+
res.status,
|
|
6041
|
+
`GitLab ${method} ${p} \u2192 ${res.status}: ${truncate2(detail, 300)}`
|
|
6042
|
+
);
|
|
6043
|
+
}
|
|
6044
|
+
return { status: res.status, data, headers: res.headers };
|
|
6045
|
+
}
|
|
5637
6046
|
}
|
|
5638
|
-
}
|
|
5639
|
-
|
|
5640
|
-
|
|
5641
|
-
|
|
5642
|
-
|
|
5643
|
-
|
|
5644
|
-
|
|
5645
|
-
|
|
5646
|
-
|
|
5647
|
-
|
|
5648
|
-
|
|
5649
|
-
message: "AuraCheck platform URL (not your app)",
|
|
5650
|
-
initial: "https://space.auracheck.ai.id",
|
|
5651
|
-
validate: (v) => /^https?:\/\//.test(v) ? true : "must start with http(s)://"
|
|
5652
|
-
});
|
|
5653
|
-
baseUrl = ans.baseUrl;
|
|
6047
|
+
async paginate(p, query = {}) {
|
|
6048
|
+
const out = [];
|
|
6049
|
+
let page = "1";
|
|
6050
|
+
for (let i = 0; page && i < MAX_PAGES; i++) {
|
|
6051
|
+
const res = await this.request("GET", p, {
|
|
6052
|
+
query: { ...query, per_page: 100, page }
|
|
6053
|
+
});
|
|
6054
|
+
if (Array.isArray(res.data)) out.push(...res.data);
|
|
6055
|
+
page = res.headers.get("x-next-page") || null;
|
|
6056
|
+
}
|
|
6057
|
+
return out;
|
|
5654
6058
|
}
|
|
5655
|
-
|
|
5656
|
-
|
|
5657
|
-
|
|
5658
|
-
|
|
6059
|
+
async getCurrentUser() {
|
|
6060
|
+
const { data } = await this.request("GET", "/user");
|
|
6061
|
+
return { id: data.id, username: data.username };
|
|
6062
|
+
}
|
|
6063
|
+
async getMergeRequest(iid) {
|
|
6064
|
+
const { data: mr } = await this.request("GET", `/merge_requests/${iid}`);
|
|
6065
|
+
const refs = mr.diff_refs;
|
|
6066
|
+
return {
|
|
6067
|
+
iid: mr.iid,
|
|
6068
|
+
title: mr.title ?? "",
|
|
6069
|
+
description: mr.description ?? "",
|
|
6070
|
+
sourceBranch: mr.source_branch,
|
|
6071
|
+
targetBranch: mr.target_branch,
|
|
6072
|
+
author: mr.author?.username ?? "",
|
|
6073
|
+
labels: Array.isArray(mr.labels) ? mr.labels.map((l) => typeof l === "string" ? l : l.name) : [],
|
|
6074
|
+
draft: !!(mr.draft ?? mr.work_in_progress),
|
|
6075
|
+
state: mr.state ?? "opened",
|
|
6076
|
+
webUrl: mr.web_url ?? "",
|
|
6077
|
+
sha: mr.sha ?? refs?.head_sha ?? "",
|
|
6078
|
+
diffRefs: refs?.base_sha && refs?.head_sha ? {
|
|
6079
|
+
baseSha: refs.base_sha,
|
|
6080
|
+
startSha: refs.start_sha ?? refs.base_sha,
|
|
6081
|
+
headSha: refs.head_sha
|
|
6082
|
+
} : null
|
|
6083
|
+
};
|
|
6084
|
+
}
|
|
6085
|
+
async listMrDiffs(iid) {
|
|
6086
|
+
let raw;
|
|
5659
6087
|
try {
|
|
5660
|
-
|
|
5661
|
-
|
|
5662
|
-
|
|
5663
|
-
|
|
5664
|
-
|
|
5665
|
-
`
|
|
5666
|
-
)
|
|
6088
|
+
raw = await this.paginate(`/merge_requests/${iid}/diffs`);
|
|
6089
|
+
} catch (err) {
|
|
6090
|
+
if (!(err instanceof GitLabError) || err.status !== 404) throw err;
|
|
6091
|
+
const { data } = await this.request(
|
|
6092
|
+
"GET",
|
|
6093
|
+
`/merge_requests/${iid}/changes`
|
|
5667
6094
|
);
|
|
5668
|
-
|
|
5669
|
-
}
|
|
5670
|
-
|
|
5671
|
-
|
|
5672
|
-
|
|
5673
|
-
|
|
5674
|
-
|
|
6095
|
+
raw = data?.changes ?? [];
|
|
6096
|
+
}
|
|
6097
|
+
return raw.map((d) => ({
|
|
6098
|
+
oldPath: d.old_path,
|
|
6099
|
+
newPath: d.new_path,
|
|
6100
|
+
diff: d.diff ?? "",
|
|
6101
|
+
newFile: !!d.new_file,
|
|
6102
|
+
deletedFile: !!d.deleted_file,
|
|
6103
|
+
renamedFile: !!d.renamed_file,
|
|
6104
|
+
tooLarge: !!(d.too_large || d.collapsed)
|
|
6105
|
+
}));
|
|
6106
|
+
}
|
|
6107
|
+
async compareCommits(from, to) {
|
|
6108
|
+
try {
|
|
6109
|
+
const { data } = await this.request("GET", "/repository/compare", {
|
|
6110
|
+
query: { from, to, straight: "false" }
|
|
6111
|
+
});
|
|
6112
|
+
if (!data || data.compare_timeout || !Array.isArray(data.diffs)) {
|
|
6113
|
+
return null;
|
|
6114
|
+
}
|
|
6115
|
+
const paths = /* @__PURE__ */ new Set();
|
|
6116
|
+
for (const d of data.diffs) {
|
|
6117
|
+
if (d.new_path) paths.add(d.new_path);
|
|
6118
|
+
if (d.old_path) paths.add(d.old_path);
|
|
6119
|
+
}
|
|
6120
|
+
return [...paths];
|
|
6121
|
+
} catch (err) {
|
|
6122
|
+
this.warn(
|
|
6123
|
+
`compare ${from.slice(0, 8)}..${to.slice(0, 8)} failed: ${err.message}`
|
|
5675
6124
|
);
|
|
6125
|
+
return null;
|
|
5676
6126
|
}
|
|
5677
6127
|
}
|
|
5678
|
-
|
|
5679
|
-
|
|
5680
|
-
|
|
5681
|
-
|
|
5682
|
-
|
|
5683
|
-
|
|
6128
|
+
async listCommits(iid) {
|
|
6129
|
+
const raw = await this.paginate(`/merge_requests/${iid}/commits`);
|
|
6130
|
+
return raw.map((c) => ({
|
|
6131
|
+
sha: c.id,
|
|
6132
|
+
title: c.title ?? "",
|
|
6133
|
+
message: c.message ?? c.title ?? ""
|
|
6134
|
+
}));
|
|
6135
|
+
}
|
|
6136
|
+
async listNotes(iid) {
|
|
6137
|
+
const raw = await this.paginate(`/merge_requests/${iid}/notes`, {
|
|
6138
|
+
sort: "asc",
|
|
6139
|
+
order_by: "created_at"
|
|
5684
6140
|
});
|
|
6141
|
+
return raw.map(toNote);
|
|
5685
6142
|
}
|
|
5686
|
-
|
|
5687
|
-
|
|
5688
|
-
|
|
5689
|
-
|
|
5690
|
-
|
|
5691
|
-
|
|
5692
|
-
|
|
5693
|
-
`
|
|
5694
|
-
)
|
|
6143
|
+
async createNote(iid, body) {
|
|
6144
|
+
const { data } = await this.request(
|
|
6145
|
+
"POST",
|
|
6146
|
+
`/merge_requests/${iid}/notes`,
|
|
6147
|
+
{
|
|
6148
|
+
body: { body }
|
|
6149
|
+
}
|
|
5695
6150
|
);
|
|
5696
|
-
|
|
5697
|
-
|
|
5698
|
-
|
|
5699
|
-
|
|
5700
|
-
|
|
6151
|
+
return toNote(data);
|
|
6152
|
+
}
|
|
6153
|
+
async updateNote(iid, noteId, body) {
|
|
6154
|
+
await this.request("PUT", `/merge_requests/${iid}/notes/${noteId}`, {
|
|
6155
|
+
body: { body }
|
|
6156
|
+
});
|
|
6157
|
+
}
|
|
6158
|
+
async deleteNote(iid, noteId) {
|
|
6159
|
+
await this.request("DELETE", `/merge_requests/${iid}/notes/${noteId}`);
|
|
6160
|
+
}
|
|
6161
|
+
async listDiscussions(iid) {
|
|
6162
|
+
const raw = await this.paginate(`/merge_requests/${iid}/discussions`);
|
|
6163
|
+
return raw.map((d) => ({
|
|
6164
|
+
id: d.id,
|
|
6165
|
+
notes: (d.notes ?? []).map(toNote)
|
|
6166
|
+
}));
|
|
6167
|
+
}
|
|
6168
|
+
/** The `position` object GitLab expects for a line comment. */
|
|
6169
|
+
static linePosition(pos) {
|
|
6170
|
+
const out = {
|
|
6171
|
+
position_type: "text",
|
|
6172
|
+
base_sha: pos.baseSha,
|
|
6173
|
+
start_sha: pos.startSha,
|
|
6174
|
+
head_sha: pos.headSha,
|
|
6175
|
+
old_path: pos.oldPath,
|
|
6176
|
+
new_path: pos.newPath,
|
|
6177
|
+
new_line: pos.newLine
|
|
6178
|
+
};
|
|
6179
|
+
if (pos.oldLine != null) out.old_line = pos.oldLine;
|
|
6180
|
+
return out;
|
|
6181
|
+
}
|
|
6182
|
+
async createDiscussion(iid, body, pos) {
|
|
6183
|
+
const p = `/merge_requests/${iid}/discussions`;
|
|
6184
|
+
try {
|
|
6185
|
+
const { data } = await this.request("POST", p, {
|
|
6186
|
+
body: { body, position: _GitLabProvider.linePosition(pos) }
|
|
6187
|
+
});
|
|
6188
|
+
return { id: data.id, noteId: data.notes?.[0]?.id ?? 0, level: "line" };
|
|
6189
|
+
} catch (err) {
|
|
6190
|
+
const status = err instanceof GitLabError ? err.status : 0;
|
|
6191
|
+
if (status !== 400 && status !== 422) {
|
|
6192
|
+
this.warn(
|
|
6193
|
+
`inline comment on ${pos.newPath}:${pos.newLine} failed: ${err.message}`
|
|
6194
|
+
);
|
|
6195
|
+
return null;
|
|
6196
|
+
}
|
|
6197
|
+
this.warn(
|
|
6198
|
+
`GitLab refused the line position ${pos.newPath}:${pos.newLine}; posting on the file instead`
|
|
6199
|
+
);
|
|
6200
|
+
}
|
|
6201
|
+
try {
|
|
6202
|
+
const { data } = await this.request("POST", p, {
|
|
6203
|
+
body: {
|
|
6204
|
+
body,
|
|
6205
|
+
position: {
|
|
6206
|
+
position_type: "file",
|
|
6207
|
+
base_sha: pos.baseSha,
|
|
6208
|
+
start_sha: pos.startSha,
|
|
6209
|
+
head_sha: pos.headSha,
|
|
6210
|
+
old_path: pos.oldPath,
|
|
6211
|
+
new_path: pos.newPath
|
|
6212
|
+
}
|
|
6213
|
+
}
|
|
6214
|
+
});
|
|
6215
|
+
return { id: data.id, noteId: data.notes?.[0]?.id ?? 0, level: "file" };
|
|
6216
|
+
} catch (err) {
|
|
6217
|
+
this.warn(
|
|
6218
|
+
`file-level comment on ${pos.newPath} failed too (${err.message}); keeping it in the summary note`
|
|
6219
|
+
);
|
|
6220
|
+
return null;
|
|
6221
|
+
}
|
|
6222
|
+
}
|
|
6223
|
+
async replyToNote(iid, noteId, body) {
|
|
6224
|
+
try {
|
|
6225
|
+
const discussions = await this.listDiscussions(iid);
|
|
6226
|
+
const d = discussions.find((x) => x.notes.some((n) => n.id === noteId));
|
|
6227
|
+
if (d) {
|
|
6228
|
+
await this.request(
|
|
6229
|
+
"POST",
|
|
6230
|
+
`/merge_requests/${iid}/discussions/${d.id}/notes`,
|
|
6231
|
+
{ body: { body } }
|
|
6232
|
+
);
|
|
6233
|
+
return;
|
|
6234
|
+
}
|
|
6235
|
+
} catch (err) {
|
|
6236
|
+
this.warn(`reply in thread failed (${err.message}); posting a new note`);
|
|
6237
|
+
}
|
|
6238
|
+
await this.createNote(iid, body);
|
|
6239
|
+
}
|
|
6240
|
+
async listAwardEmoji(iid, noteId) {
|
|
6241
|
+
const raw = await this.paginate(
|
|
6242
|
+
`/merge_requests/${iid}/notes/${noteId}/award_emoji`
|
|
6243
|
+
);
|
|
6244
|
+
return raw.map((a) => ({ name: a.name, userId: a.user?.id ?? -1 }));
|
|
6245
|
+
}
|
|
6246
|
+
async awardEmoji(iid, noteId, name) {
|
|
6247
|
+
try {
|
|
6248
|
+
await this.request(
|
|
6249
|
+
"POST",
|
|
6250
|
+
`/merge_requests/${iid}/notes/${noteId}/award_emoji`,
|
|
6251
|
+
{ body: { name } }
|
|
6252
|
+
);
|
|
6253
|
+
} catch (err) {
|
|
6254
|
+
if (err instanceof GitLabError && [404, 409].includes(err.status)) return;
|
|
6255
|
+
throw err;
|
|
6256
|
+
}
|
|
6257
|
+
}
|
|
6258
|
+
async setCommitStatus(sha, s) {
|
|
6259
|
+
await this.request("POST", `/statuses/${sha}`, {
|
|
6260
|
+
body: {
|
|
6261
|
+
state: s.state,
|
|
6262
|
+
name: s.name,
|
|
6263
|
+
...s.description ? { description: truncate2(s.description, 250) } : {},
|
|
6264
|
+
...s.targetUrl ? { target_url: s.targetUrl } : {},
|
|
6265
|
+
...s.pipelineId ? { pipeline_id: s.pipelineId } : {}
|
|
6266
|
+
}
|
|
6267
|
+
});
|
|
6268
|
+
}
|
|
6269
|
+
async listCommitStatuses(sha, name) {
|
|
6270
|
+
const raw = await this.paginate(`/repository/commits/${sha}/statuses`, {
|
|
6271
|
+
name
|
|
6272
|
+
});
|
|
6273
|
+
return raw.map((s) => ({ name: s.name, status: s.status }));
|
|
6274
|
+
}
|
|
6275
|
+
async updateMrDescription(iid, description) {
|
|
6276
|
+
await this.request("PUT", `/merge_requests/${iid}`, {
|
|
6277
|
+
body: { description }
|
|
6278
|
+
});
|
|
6279
|
+
}
|
|
6280
|
+
async getLinkedIssues(iid, description) {
|
|
6281
|
+
const out = [];
|
|
6282
|
+
const seen = /* @__PURE__ */ new Set();
|
|
6283
|
+
const push = (ref, title, desc) => {
|
|
6284
|
+
if (seen.has(ref) || out.length >= MAX_LINKED_ISSUES) return;
|
|
6285
|
+
seen.add(ref);
|
|
6286
|
+
out.push({
|
|
6287
|
+
ref,
|
|
6288
|
+
title: truncate2(title ?? "", 200),
|
|
6289
|
+
description: truncate2(desc ?? "", ISSUE_TEXT_CAP)
|
|
6290
|
+
});
|
|
6291
|
+
};
|
|
6292
|
+
try {
|
|
6293
|
+
const closing = await this.paginate(
|
|
6294
|
+
`/merge_requests/${iid}/closes_issues`
|
|
6295
|
+
);
|
|
6296
|
+
for (const issue of closing) {
|
|
6297
|
+
const sameProject = issue.project_id == null || String(issue.project_id) === this.projectIdRaw;
|
|
6298
|
+
const ref = sameProject ? `#${issue.iid}` : issue.references?.full ?? `#${issue.iid}`;
|
|
6299
|
+
push(ref, issue.title, issue.description);
|
|
6300
|
+
}
|
|
6301
|
+
} catch (err) {
|
|
6302
|
+
this.warn(`closing issues lookup failed: ${err.message}`);
|
|
6303
|
+
}
|
|
6304
|
+
for (const n of parseIssueRefs(description)) {
|
|
6305
|
+
if (out.length >= MAX_LINKED_ISSUES) break;
|
|
6306
|
+
if (seen.has(`#${n}`)) continue;
|
|
6307
|
+
try {
|
|
6308
|
+
const { data } = await this.request("GET", `/issues/${n}`);
|
|
6309
|
+
push(`#${n}`, data.title, data.description);
|
|
6310
|
+
} catch {
|
|
6311
|
+
}
|
|
6312
|
+
}
|
|
6313
|
+
return out;
|
|
6314
|
+
}
|
|
6315
|
+
};
|
|
6316
|
+
function sleep(ms) {
|
|
6317
|
+
return ms > 0 ? new Promise((r) => setTimeout(r, ms)) : Promise.resolve();
|
|
6318
|
+
}
|
|
6319
|
+
|
|
6320
|
+
// src/review/run.ts
|
|
6321
|
+
import { readFile as readFileFs } from "fs/promises";
|
|
6322
|
+
|
|
6323
|
+
// src/review/commands.ts
|
|
6324
|
+
import { promises as fs3 } from "fs";
|
|
6325
|
+
var ACK_START = "eyes";
|
|
6326
|
+
var ACK_DONE = "white_check_mark";
|
|
6327
|
+
var MAX_ACK_LOOKUPS = 10;
|
|
6328
|
+
var COMMAND_RE = /^[ \t]*@auracheck[ \t]+(full[ \t]+review|review|help)\b/im;
|
|
6329
|
+
function parseCommand(body) {
|
|
6330
|
+
const m = COMMAND_RE.exec(body ?? "");
|
|
6331
|
+
if (!m) return null;
|
|
6332
|
+
const word = m[1].toLowerCase().replace(/\s+/g, " ");
|
|
6333
|
+
if (word === "full review") return "full_review";
|
|
6334
|
+
return word === "help" ? "help" : "review";
|
|
6335
|
+
}
|
|
6336
|
+
function commandFromEnv(value) {
|
|
6337
|
+
const v = (value ?? "").trim().toLowerCase().replace(/[\s-]+/g, "_");
|
|
6338
|
+
if (v === "review" || v === "full_review" || v === "help") return v;
|
|
6339
|
+
return null;
|
|
6340
|
+
}
|
|
6341
|
+
function isBotUsername(username, botUsername) {
|
|
6342
|
+
if (botUsername && username === botUsername) return true;
|
|
6343
|
+
return /^(?:project|group)_\d+_bot(?:_|$)/.test(username);
|
|
6344
|
+
}
|
|
6345
|
+
function decideTrigger(payload) {
|
|
6346
|
+
if (payload?.object_kind !== "note") {
|
|
6347
|
+
return {
|
|
6348
|
+
kind: "ignore",
|
|
6349
|
+
reason: `trigger payload is a ${payload?.object_kind ?? "unknown"} event, not a comment`
|
|
6350
|
+
};
|
|
6351
|
+
}
|
|
6352
|
+
const attrs = payload.object_attributes ?? {};
|
|
6353
|
+
if (attrs.noteable_type !== "MergeRequest") {
|
|
6354
|
+
return { kind: "ignore", reason: "comment is not on a merge request" };
|
|
6355
|
+
}
|
|
6356
|
+
const command = parseCommand(String(attrs.note ?? ""));
|
|
6357
|
+
if (!command)
|
|
6358
|
+
return { kind: "ignore", reason: "comment is not an @auracheck command" };
|
|
6359
|
+
const author = String(payload.user?.username ?? "");
|
|
6360
|
+
if (isBotUsername(author)) {
|
|
6361
|
+
return { kind: "ignore", reason: `comment is by a bot (${author})` };
|
|
6362
|
+
}
|
|
6363
|
+
const mr = payload.merge_request ?? {};
|
|
6364
|
+
if (mr.state && mr.state !== "opened") {
|
|
6365
|
+
return { kind: "ignore", reason: `merge request is ${mr.state}` };
|
|
6366
|
+
}
|
|
6367
|
+
const iid = Number(mr.iid);
|
|
6368
|
+
const noteId = Number(attrs.id);
|
|
6369
|
+
if (!Number.isInteger(iid) || iid <= 0 || !Number.isInteger(noteId)) {
|
|
6370
|
+
return {
|
|
6371
|
+
kind: "ignore",
|
|
6372
|
+
reason: "trigger payload has no merge request iid or note id"
|
|
6373
|
+
};
|
|
6374
|
+
}
|
|
6375
|
+
return { kind: "command", iid, command, noteId, author };
|
|
6376
|
+
}
|
|
6377
|
+
async function readTriggerPayload(env, readFile = (p) => fs3.readFile(p, "utf8")) {
|
|
6378
|
+
const ref = env.TRIGGER_PAYLOAD;
|
|
6379
|
+
if (!ref) return null;
|
|
6380
|
+
let text;
|
|
6381
|
+
try {
|
|
6382
|
+
text = ref.trim().startsWith("{") ? ref : await readFile(ref);
|
|
6383
|
+
} catch (err) {
|
|
6384
|
+
return {
|
|
6385
|
+
kind: "ignore",
|
|
6386
|
+
reason: `cannot read TRIGGER_PAYLOAD (${err?.code ?? err?.message})`
|
|
6387
|
+
};
|
|
6388
|
+
}
|
|
6389
|
+
try {
|
|
6390
|
+
return decideTrigger(JSON.parse(text));
|
|
6391
|
+
} catch {
|
|
6392
|
+
return { kind: "ignore", reason: "TRIGGER_PAYLOAD is not JSON" };
|
|
6393
|
+
}
|
|
6394
|
+
}
|
|
6395
|
+
function commandNotes(discussions, botUser) {
|
|
6396
|
+
const out = [];
|
|
6397
|
+
for (const d of discussions) {
|
|
6398
|
+
for (const n of d.notes) {
|
|
6399
|
+
if (n.system) continue;
|
|
6400
|
+
if (botUser && n.authorId === botUser.id) continue;
|
|
6401
|
+
if (isBotUsername(n.authorUsername, botUser?.username)) continue;
|
|
6402
|
+
const kind = parseCommand(n.body);
|
|
6403
|
+
if (kind) out.push({ note: n, kind });
|
|
6404
|
+
}
|
|
6405
|
+
}
|
|
6406
|
+
return out.sort(
|
|
6407
|
+
(a, b) => a.note.createdAt === b.note.createdAt ? b.note.id - a.note.id : a.note.createdAt < b.note.createdAt ? 1 : -1
|
|
6408
|
+
);
|
|
6409
|
+
}
|
|
6410
|
+
async function findUnacknowledgedCommand(provider, iid, discussions, botUser) {
|
|
6411
|
+
const candidates = commandNotes(discussions, botUser).slice(
|
|
6412
|
+
0,
|
|
6413
|
+
MAX_ACK_LOOKUPS
|
|
6414
|
+
);
|
|
6415
|
+
for (const { note, kind } of candidates) {
|
|
6416
|
+
let awards = [];
|
|
6417
|
+
try {
|
|
6418
|
+
awards = await provider.listAwardEmoji(iid, note.id);
|
|
6419
|
+
} catch {
|
|
6420
|
+
return null;
|
|
6421
|
+
}
|
|
6422
|
+
const acked = awards.some(
|
|
6423
|
+
(a) => (a.name === ACK_START || a.name === ACK_DONE) && (botUser ? a.userId === botUser.id : true)
|
|
6424
|
+
);
|
|
6425
|
+
if (acked) return null;
|
|
6426
|
+
return { kind, noteId: note.id, source: "scan" };
|
|
6427
|
+
}
|
|
6428
|
+
return null;
|
|
6429
|
+
}
|
|
6430
|
+
async function acknowledge(provider, iid, cmd, name, warn2) {
|
|
6431
|
+
if (!cmd?.noteId) return;
|
|
6432
|
+
try {
|
|
6433
|
+
await provider.awardEmoji(iid, cmd.noteId, name);
|
|
6434
|
+
} catch (err) {
|
|
6435
|
+
warn2(`could not add :${name}: to the command comment: ${err.message}`);
|
|
6436
|
+
}
|
|
6437
|
+
}
|
|
6438
|
+
|
|
6439
|
+
// src/review/run.ts
|
|
6440
|
+
init_config();
|
|
6441
|
+
|
|
6442
|
+
// src/review/contract.ts
|
|
6443
|
+
var REVIEW_CONTRACT_VERSION = 1;
|
|
6444
|
+
var FINDING_CATEGORIES = [
|
|
6445
|
+
"bug",
|
|
6446
|
+
"security",
|
|
6447
|
+
"not-needed",
|
|
6448
|
+
"adds-weight",
|
|
6449
|
+
"inefficient",
|
|
6450
|
+
"maintainability"
|
|
6451
|
+
];
|
|
6452
|
+
var SEVERITIES = [
|
|
6453
|
+
"critical",
|
|
6454
|
+
"high",
|
|
6455
|
+
"medium",
|
|
6456
|
+
"low"
|
|
6457
|
+
];
|
|
6458
|
+
|
|
6459
|
+
// src/review/dedup.ts
|
|
6460
|
+
var FP_MARKER_RE = /<!-- auracheck-fp:([A-Za-z0-9_-]{1,64}) -->/g;
|
|
6461
|
+
function sanitizeFingerprint(fp) {
|
|
6462
|
+
return fp.replace(/[^A-Za-z0-9_-]/g, "").slice(0, 64);
|
|
6463
|
+
}
|
|
6464
|
+
function fingerprintMarker(fp) {
|
|
6465
|
+
return `<!-- auracheck-fp:${sanitizeFingerprint(fp)} -->`;
|
|
6466
|
+
}
|
|
6467
|
+
function fingerprintsInDiscussions(discussions) {
|
|
6468
|
+
const out = /* @__PURE__ */ new Set();
|
|
6469
|
+
for (const d of discussions) {
|
|
6470
|
+
for (const n of d.notes) {
|
|
6471
|
+
for (const m of n.body.matchAll(FP_MARKER_RE)) out.add(m[1]);
|
|
6472
|
+
}
|
|
6473
|
+
}
|
|
6474
|
+
return out;
|
|
6475
|
+
}
|
|
6476
|
+
function knownFingerprints(state, inDiscussions) {
|
|
6477
|
+
return [.../* @__PURE__ */ new Set([...Object.keys(state.posted), ...inDiscussions])];
|
|
6478
|
+
}
|
|
6479
|
+
function isKnown(finding, state, inDiscussions) {
|
|
6480
|
+
const fp = sanitizeFingerprint(finding.fingerprint);
|
|
6481
|
+
return fp in state.posted || inDiscussions.has(fp);
|
|
6482
|
+
}
|
|
6483
|
+
function selectInline(findings, state, inDiscussions, cap) {
|
|
6484
|
+
const toPost = [];
|
|
6485
|
+
const duplicates = [];
|
|
6486
|
+
const noteOnly = [];
|
|
6487
|
+
const seenThisRun = /* @__PURE__ */ new Set();
|
|
6488
|
+
for (const f of findings) {
|
|
6489
|
+
const fp = sanitizeFingerprint(f.fingerprint);
|
|
6490
|
+
if (isKnown(f, state, inDiscussions) || seenThisRun.has(fp)) {
|
|
6491
|
+
duplicates.push(f);
|
|
6492
|
+
continue;
|
|
6493
|
+
}
|
|
6494
|
+
seenThisRun.add(fp);
|
|
6495
|
+
if (f.inline && f.anchor && toPost.length < cap) toPost.push(f);
|
|
6496
|
+
else noteOnly.push(f);
|
|
6497
|
+
}
|
|
6498
|
+
return { toPost, duplicates, noteOnly };
|
|
6499
|
+
}
|
|
6500
|
+
|
|
6501
|
+
// src/review/glob.ts
|
|
6502
|
+
var cache = /* @__PURE__ */ new Map();
|
|
6503
|
+
function globToRegExp(glob) {
|
|
6504
|
+
const cached = cache.get(glob);
|
|
6505
|
+
if (cached) return cached;
|
|
6506
|
+
let g = glob.trim().replace(/^\.\//, "").replace(/^\//, "");
|
|
6507
|
+
if (g.endsWith("/")) g = `${g}**`;
|
|
6508
|
+
let re = "";
|
|
6509
|
+
let braceDepth = 0;
|
|
6510
|
+
for (let i = 0; i < g.length; i++) {
|
|
6511
|
+
const c = g[i];
|
|
6512
|
+
if (c === "*") {
|
|
6513
|
+
if (g[i + 1] === "*") {
|
|
6514
|
+
const atSegStart = i === 0 || g[i - 1] === "/";
|
|
6515
|
+
if (g[i + 2] === "/" && atSegStart) {
|
|
6516
|
+
re += "(?:.*/)?";
|
|
6517
|
+
i += 2;
|
|
6518
|
+
} else {
|
|
6519
|
+
re += ".*";
|
|
6520
|
+
i += 1;
|
|
6521
|
+
}
|
|
6522
|
+
} else {
|
|
6523
|
+
re += "[^/]*";
|
|
6524
|
+
}
|
|
6525
|
+
} else if (c === "?") {
|
|
6526
|
+
re += "[^/]";
|
|
6527
|
+
} else if (c === "{") {
|
|
6528
|
+
braceDepth++;
|
|
6529
|
+
re += "(?:";
|
|
6530
|
+
} else if (c === "}" && braceDepth > 0) {
|
|
6531
|
+
braceDepth--;
|
|
6532
|
+
re += ")";
|
|
6533
|
+
} else if (c === "," && braceDepth > 0) {
|
|
6534
|
+
re += "|";
|
|
6535
|
+
} else if (c === "[") {
|
|
6536
|
+
const end = g.indexOf("]", i + 1);
|
|
6537
|
+
if (end === -1) {
|
|
6538
|
+
re += "\\[";
|
|
6539
|
+
} else {
|
|
6540
|
+
let cls = g.slice(i + 1, end).replace(/\\/g, "\\\\");
|
|
6541
|
+
if (cls.startsWith("!")) cls = `^${cls.slice(1)}`;
|
|
6542
|
+
re += `[${cls}]`;
|
|
6543
|
+
i = end;
|
|
6544
|
+
}
|
|
6545
|
+
} else if ("\\^$.|+()".includes(c)) {
|
|
6546
|
+
re += `\\${c}`;
|
|
6547
|
+
} else {
|
|
6548
|
+
re += c;
|
|
6549
|
+
}
|
|
6550
|
+
}
|
|
6551
|
+
const out = new RegExp(`^${re}$`);
|
|
6552
|
+
cache.set(glob, out);
|
|
6553
|
+
return out;
|
|
6554
|
+
}
|
|
6555
|
+
function matchGlob(filePath, glob) {
|
|
6556
|
+
const p = filePath.replace(/^\.\//, "");
|
|
6557
|
+
const g = glob.trim();
|
|
6558
|
+
if (!g) return false;
|
|
6559
|
+
if (globToRegExp(g).test(p)) return true;
|
|
6560
|
+
const body = g.replace(/\/$/, "");
|
|
6561
|
+
if (!body.includes("/")) {
|
|
6562
|
+
const base = p.slice(p.lastIndexOf("/") + 1);
|
|
6563
|
+
if (globToRegExp(body).test(base)) return true;
|
|
6564
|
+
if (g.endsWith("/")) return p.split("/").slice(0, -1).includes(body);
|
|
6565
|
+
}
|
|
6566
|
+
return false;
|
|
6567
|
+
}
|
|
6568
|
+
function matchAny(filePath, globs) {
|
|
6569
|
+
return globs.some((g) => matchGlob(filePath, g));
|
|
6570
|
+
}
|
|
6571
|
+
|
|
6572
|
+
// src/review/filters.ts
|
|
6573
|
+
var LOCKFILES = [
|
|
6574
|
+
"pnpm-lock.yaml",
|
|
6575
|
+
"package-lock.json",
|
|
6576
|
+
"npm-shrinkwrap.json",
|
|
6577
|
+
"yarn.lock",
|
|
6578
|
+
"bun.lockb",
|
|
6579
|
+
"bun.lock",
|
|
6580
|
+
"Cargo.lock",
|
|
6581
|
+
"poetry.lock",
|
|
6582
|
+
"Pipfile.lock",
|
|
6583
|
+
"uv.lock",
|
|
6584
|
+
"Gemfile.lock",
|
|
6585
|
+
"composer.lock",
|
|
6586
|
+
"go.sum",
|
|
6587
|
+
"packages.lock.json",
|
|
6588
|
+
"pubspec.lock",
|
|
6589
|
+
"Podfile.lock"
|
|
6590
|
+
];
|
|
6591
|
+
var BUILD_OUTPUT = [
|
|
6592
|
+
"**/dist/**",
|
|
6593
|
+
"**/build/**",
|
|
6594
|
+
"**/.next/**",
|
|
6595
|
+
"**/.nuxt/**",
|
|
6596
|
+
"**/.svelte-kit/**",
|
|
6597
|
+
"**/coverage/**",
|
|
6598
|
+
"**/node_modules/**",
|
|
6599
|
+
"**/__snapshots__/**"
|
|
6600
|
+
];
|
|
6601
|
+
var MINIFIED_OR_MAPS = [
|
|
6602
|
+
"*.min.js",
|
|
6603
|
+
"*.min.css",
|
|
6604
|
+
"*.min.mjs",
|
|
6605
|
+
"*.map",
|
|
6606
|
+
"*.snap"
|
|
6607
|
+
];
|
|
6608
|
+
var GENERATED = [
|
|
6609
|
+
"*.generated.*",
|
|
6610
|
+
"*.gen.go",
|
|
6611
|
+
"*.pb.go",
|
|
6612
|
+
"*_pb2.py",
|
|
6613
|
+
"*_pb2_grpc.py",
|
|
6614
|
+
"*.pb.ts",
|
|
6615
|
+
"**/generated/**",
|
|
6616
|
+
"**/__generated__/**"
|
|
6617
|
+
];
|
|
6618
|
+
var BINARY_EXT = new Set(
|
|
6619
|
+
"png jpg jpeg gif webp avif ico bmp tif tiff psd heic svg woff woff2 ttf otf eot mp3 mp4 m4a wav ogg webm mov avi mkv flac zip gz tgz tar bz2 xz 7z rar jar war ear apk aab ipa dmg iso pdf doc docx xls xlsx ppt pptx odt exe dll so dylib bin o a lib class pyc pyo wasm node sqlite db parquet avro pkl pt onnx h5".split(" ")
|
|
6620
|
+
);
|
|
6621
|
+
var MAX_FILE_DIFF_CHARS = 15e4;
|
|
6622
|
+
var MAX_FILES = 300;
|
|
6623
|
+
function defaultExcludeReason(file) {
|
|
6624
|
+
const p = file.newPath || file.oldPath;
|
|
6625
|
+
const base = p.slice(p.lastIndexOf("/") + 1);
|
|
6626
|
+
if (LOCKFILES.includes(base)) return "lockfile";
|
|
6627
|
+
const ext = base.includes(".") ? base.slice(base.lastIndexOf(".") + 1) : "";
|
|
6628
|
+
if (BINARY_EXT.has(ext.toLowerCase())) return "binary or media file";
|
|
6629
|
+
if (matchAny(p, MINIFIED_OR_MAPS)) return "minified, source map or snapshot";
|
|
6630
|
+
if (matchAny(p, BUILD_OUTPUT)) return "build output or vendored";
|
|
6631
|
+
if (matchAny(p, GENERATED)) return "generated file";
|
|
6632
|
+
if (file.tooLarge) return "diff too large for the git host";
|
|
6633
|
+
if (!file.deletedFile && file.diff.trim() === "" && !file.renamedFile) {
|
|
6634
|
+
return "binary or empty diff";
|
|
6635
|
+
}
|
|
6636
|
+
if (file.diff.length > MAX_FILE_DIFF_CHARS) return "diff too large";
|
|
6637
|
+
return null;
|
|
6638
|
+
}
|
|
6639
|
+
function pathFilterReason(filePath, pathFilters) {
|
|
6640
|
+
const excludes = pathFilters.filter((f) => f.trim().startsWith("!")).map((f) => f.trim().slice(1));
|
|
6641
|
+
const includes = pathFilters.map((f) => f.trim()).filter((f) => f && !f.startsWith("!"));
|
|
6642
|
+
const hit = excludes.find((g) => matchGlob(filePath, g));
|
|
6643
|
+
if (hit) return `path_filters: !${hit}`;
|
|
6644
|
+
if (includes.length && !matchAny(filePath, includes)) {
|
|
6645
|
+
return "path_filters: not in the include list";
|
|
6646
|
+
}
|
|
6647
|
+
return null;
|
|
6648
|
+
}
|
|
6649
|
+
function filterFiles(files, pathFilters) {
|
|
6650
|
+
const kept = [];
|
|
6651
|
+
const skippedFiles = [];
|
|
6652
|
+
for (const f of files) {
|
|
6653
|
+
const p = f.newPath || f.oldPath;
|
|
6654
|
+
const reason = defaultExcludeReason(f) ?? pathFilterReason(p, pathFilters) ?? null;
|
|
6655
|
+
if (reason) {
|
|
6656
|
+
skippedFiles.push({ path: p, reason });
|
|
6657
|
+
} else if (kept.length >= MAX_FILES) {
|
|
6658
|
+
skippedFiles.push({ path: p, reason: `over the ${MAX_FILES}-file cap` });
|
|
6659
|
+
} else {
|
|
6660
|
+
kept.push(f);
|
|
6661
|
+
}
|
|
6662
|
+
}
|
|
6663
|
+
return { files: kept, skippedFiles };
|
|
6664
|
+
}
|
|
6665
|
+
|
|
6666
|
+
// src/review/guidelines.ts
|
|
6667
|
+
import { promises as fs5 } from "fs";
|
|
6668
|
+
import path4 from "path";
|
|
6669
|
+
var GUIDELINES_CHAR_CAP = 6e3;
|
|
6670
|
+
var WALK_SKIP = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", "build", "vendor"]);
|
|
6671
|
+
var WALK_MAX_ENTRIES = 3e3;
|
|
6672
|
+
var WALK_MAX_DEPTH = 4;
|
|
6673
|
+
async function walk(root) {
|
|
6674
|
+
const out = [];
|
|
6675
|
+
const queue = [{ dir: "", depth: 0 }];
|
|
6676
|
+
let seen = 0;
|
|
6677
|
+
while (queue.length && seen < WALK_MAX_ENTRIES) {
|
|
6678
|
+
const { dir, depth } = queue.shift();
|
|
6679
|
+
let entries;
|
|
6680
|
+
try {
|
|
6681
|
+
entries = await fs5.readdir(path4.join(root, dir), { withFileTypes: true });
|
|
6682
|
+
} catch {
|
|
6683
|
+
continue;
|
|
6684
|
+
}
|
|
6685
|
+
for (const e of entries) {
|
|
6686
|
+
if (++seen > WALK_MAX_ENTRIES) break;
|
|
6687
|
+
const rel = dir ? `${dir}/${e.name}` : e.name;
|
|
6688
|
+
if (e.isDirectory()) {
|
|
6689
|
+
if (!WALK_SKIP.has(e.name) && depth < WALK_MAX_DEPTH) {
|
|
6690
|
+
queue.push({ dir: rel, depth: depth + 1 });
|
|
6691
|
+
}
|
|
6692
|
+
} else if (e.isFile()) {
|
|
6693
|
+
out.push(rel);
|
|
6694
|
+
}
|
|
6695
|
+
}
|
|
6696
|
+
}
|
|
6697
|
+
return out;
|
|
6698
|
+
}
|
|
6699
|
+
async function readGuidelines(projectDir, config, cap = GUIDELINES_CHAR_CAP) {
|
|
6700
|
+
const cg = config.knowledge_base.code_guidelines;
|
|
6701
|
+
if (!projectDir || !cg.enabled) return [];
|
|
6702
|
+
const paths = [];
|
|
6703
|
+
let tree = null;
|
|
6704
|
+
for (const pattern of cg.file_patterns) {
|
|
6705
|
+
if (/[*?[{]/.test(pattern)) {
|
|
6706
|
+
tree ??= await walk(projectDir);
|
|
6707
|
+
for (const p of tree) {
|
|
6708
|
+
if (matchGlob(p, pattern) && !paths.includes(p)) paths.push(p);
|
|
6709
|
+
}
|
|
6710
|
+
} else {
|
|
6711
|
+
const p = pattern.replace(/^\.\//, "");
|
|
6712
|
+
if (!paths.includes(p)) paths.push(p);
|
|
6713
|
+
}
|
|
6714
|
+
}
|
|
6715
|
+
const out = [];
|
|
6716
|
+
let left = cap;
|
|
6717
|
+
for (const p of paths) {
|
|
6718
|
+
if (left <= 0) break;
|
|
6719
|
+
let content;
|
|
6720
|
+
try {
|
|
6721
|
+
content = await fs5.readFile(path4.join(projectDir, p), "utf8");
|
|
6722
|
+
} catch {
|
|
6723
|
+
continue;
|
|
6724
|
+
}
|
|
6725
|
+
content = content.trim();
|
|
6726
|
+
if (!content) continue;
|
|
6727
|
+
if (content.length > left)
|
|
6728
|
+
content = `${content.slice(0, left)}
|
|
6729
|
+
\u2026(truncated)`;
|
|
6730
|
+
left -= content.length;
|
|
6731
|
+
out.push({ path: p, content });
|
|
6732
|
+
}
|
|
6733
|
+
return out;
|
|
6734
|
+
}
|
|
6735
|
+
|
|
6736
|
+
// src/review/i18n.ts
|
|
6737
|
+
var CATEGORY_EN = {
|
|
6738
|
+
bug: "Bugs and logic",
|
|
6739
|
+
security: "Security",
|
|
6740
|
+
"not-needed": "Not needed",
|
|
6741
|
+
"adds-weight": "Adds weight",
|
|
6742
|
+
inefficient: "Inefficient",
|
|
6743
|
+
maintainability: "Maintainability"
|
|
6744
|
+
};
|
|
6745
|
+
var CATEGORY_ID = {
|
|
6746
|
+
bug: "Bug dan logika",
|
|
6747
|
+
security: "Keamanan",
|
|
6748
|
+
"not-needed": "Tidak diperlukan",
|
|
6749
|
+
"adds-weight": "Menambah beban",
|
|
6750
|
+
inefficient: "Tidak efisien",
|
|
6751
|
+
maintainability: "Maintainability"
|
|
6752
|
+
};
|
|
6753
|
+
var COMMANDS = "Commands: `@auracheck review`, `@auracheck full review`, `@auracheck help`";
|
|
6754
|
+
var DOCS_URL = "https://www.auracheck.ai.id/docs/pr-agent";
|
|
6755
|
+
var EN = {
|
|
6756
|
+
title: "AuraCheck review",
|
|
6757
|
+
status: "Status",
|
|
6758
|
+
statusReviewed: (sha, mode) => `\u2705 Reviewed ${sha} (${mode})`,
|
|
6759
|
+
statusNoChanges: (sha) => `\u2705 No reviewable changes since ${sha}; the previous review still applies`,
|
|
6760
|
+
statusSkipped: (reason) => `\u23ED\uFE0F Skipped: ${reason}`,
|
|
6761
|
+
statusLimit: (used, limit, resetsAt) => `\u23F8\uFE0F Review limit reached (${used}/${limit} used, resets ${resetsAt})`,
|
|
6762
|
+
statusFailed: (reason) => `\u26A0\uFE0F Review failed: ${reason}`,
|
|
6763
|
+
statusRunning: (sha) => `\u23F3 Reviewing ${sha}\u2026`,
|
|
6764
|
+
findingsLine: (total, inline) => `${total} finding${total === 1 ? "" : "s"}, ${inline} posted inline`,
|
|
6765
|
+
modeFull: "full review",
|
|
6766
|
+
modeIncremental: (since) => `incremental since ${since}`,
|
|
6767
|
+
whatChanges: "What this MR changes",
|
|
6768
|
+
walkthrough: "Walkthrough",
|
|
6769
|
+
risk: "Risk",
|
|
6770
|
+
mergeRisk: "Merge risk",
|
|
6771
|
+
securityRisk: "Security risk",
|
|
6772
|
+
level: "Level",
|
|
6773
|
+
why: "Why",
|
|
6774
|
+
riskLevel: { low: "\u{1F7E2} Low", medium: "\u{1F7E1} Medium", high: "\u{1F534} High" },
|
|
6775
|
+
effort: "Review effort",
|
|
6776
|
+
findings: "Findings",
|
|
6777
|
+
category: "Category",
|
|
6778
|
+
severity: "Severity",
|
|
6779
|
+
count: "Count",
|
|
6780
|
+
categoryLabel: CATEGORY_EN,
|
|
6781
|
+
severityLabel: {
|
|
6782
|
+
critical: "Critical",
|
|
6783
|
+
high: "High",
|
|
6784
|
+
medium: "Medium",
|
|
6785
|
+
low: "Low"
|
|
6786
|
+
},
|
|
6787
|
+
coverage: "Coverage",
|
|
6788
|
+
coverageDiffOnly: "diff only",
|
|
6789
|
+
coverageFullFiles: (files) => `diff plus full context of ${files}`,
|
|
6790
|
+
skippedBudget: "Skipped (token budget)",
|
|
6791
|
+
skippedFilters: "Skipped (filters)",
|
|
6792
|
+
reviewedCommit: "Reviewed commit",
|
|
6793
|
+
mode: "Mode",
|
|
6794
|
+
linkedIssues: "Linked issues",
|
|
6795
|
+
issueStatus: {
|
|
6796
|
+
addressed: "\u2705 addressed",
|
|
6797
|
+
"partly-addressed": "\u{1F7E1} partly addressed",
|
|
6798
|
+
"not-addressed": "\u274C not addressed",
|
|
6799
|
+
unclear: "\u2754 unclear"
|
|
6800
|
+
},
|
|
6801
|
+
preMerge: "Pre-merge checks",
|
|
6802
|
+
check: "Check",
|
|
6803
|
+
result: "Result",
|
|
6804
|
+
detail: "Detail",
|
|
6805
|
+
changedFiles: (n) => `Changed files (${n})`,
|
|
6806
|
+
file: "File",
|
|
6807
|
+
summary: "Summary",
|
|
6808
|
+
notInline: (n) => `Findings not posted inline (${n})`,
|
|
6809
|
+
details: "Review details",
|
|
6810
|
+
configSource: "Config",
|
|
6811
|
+
profile: "Profile",
|
|
6812
|
+
models: "Model(s)",
|
|
6813
|
+
tokens: "Tokens (prompt / completion)",
|
|
6814
|
+
latency: "Latency",
|
|
6815
|
+
reviewedCommits: "Reviewed commits",
|
|
6816
|
+
suppressed: "Suppressed (low confidence, total)",
|
|
6817
|
+
unanchored: "Not anchored to a diff line",
|
|
6818
|
+
skippedDuplicates: "Skipped duplicates (posted before)",
|
|
6819
|
+
toolWarnings: "Tool warnings",
|
|
6820
|
+
commands: COMMANDS,
|
|
6821
|
+
evidence: "Evidence",
|
|
6822
|
+
fix: "Fix",
|
|
6823
|
+
exploitability: "Exploitability",
|
|
6824
|
+
promptForAgents: "\u{1F916} Prompt for AI agents",
|
|
6825
|
+
helpReply: `AuraCheck PR review commands (write them at the start of a comment):
|
|
6826
|
+
|
|
6827
|
+
- \`@auracheck review\`: review the new commits now, even if this MR would be skipped automatically (draft, label, title keyword).
|
|
6828
|
+
- \`@auracheck full review\`: review every file of the MR again, not only what changed since the last review. Findings posted before are not repeated.
|
|
6829
|
+
- \`@auracheck help\`: show this list.
|
|
6830
|
+
|
|
6831
|
+
Settings live in \`.auracheck.yaml\` at the repo root: ${DOCS_URL}`,
|
|
6832
|
+
limitRetry: "The next push after the reset is reviewed as usual.",
|
|
6833
|
+
failedRetry: "It will retry on the next push, or comment `@auracheck review`."
|
|
6834
|
+
};
|
|
6835
|
+
var ID = {
|
|
6836
|
+
...EN,
|
|
6837
|
+
title: "AuraCheck review",
|
|
6838
|
+
statusReviewed: (sha, mode) => `\u2705 Sudah direview ${sha} (${mode})`,
|
|
6839
|
+
statusNoChanges: (sha) => `\u2705 Tidak ada perubahan yang perlu direview sejak ${sha}; review sebelumnya masih berlaku`,
|
|
6840
|
+
statusSkipped: (reason) => `\u23ED\uFE0F Dilewati: ${reason}`,
|
|
6841
|
+
statusLimit: (used, limit, resetsAt) => `\u23F8\uFE0F Batas review tercapai (${used}/${limit} terpakai, reset ${resetsAt})`,
|
|
6842
|
+
statusFailed: (reason) => `\u26A0\uFE0F Review gagal: ${reason}`,
|
|
6843
|
+
statusRunning: (sha) => `\u23F3 Sedang mereview ${sha}\u2026`,
|
|
6844
|
+
findingsLine: (total, inline) => `${total} temuan, ${inline} diposting inline`,
|
|
6845
|
+
modeFull: "review penuh",
|
|
6846
|
+
modeIncremental: (since) => `inkremental sejak ${since}`,
|
|
6847
|
+
whatChanges: "Yang diubah MR ini",
|
|
6848
|
+
walkthrough: "Ringkasan",
|
|
6849
|
+
risk: "Risiko",
|
|
6850
|
+
mergeRisk: "Risiko merge",
|
|
6851
|
+
securityRisk: "Risiko keamanan",
|
|
6852
|
+
level: "Level",
|
|
6853
|
+
why: "Alasan",
|
|
6854
|
+
riskLevel: { low: "\u{1F7E2} Rendah", medium: "\u{1F7E1} Sedang", high: "\u{1F534} Tinggi" },
|
|
6855
|
+
effort: "Usaha review",
|
|
6856
|
+
findings: "Temuan",
|
|
6857
|
+
category: "Kategori",
|
|
6858
|
+
severity: "Tingkat",
|
|
6859
|
+
count: "Jumlah",
|
|
6860
|
+
categoryLabel: CATEGORY_ID,
|
|
6861
|
+
severityLabel: {
|
|
6862
|
+
critical: "Kritis",
|
|
6863
|
+
high: "Tinggi",
|
|
6864
|
+
medium: "Sedang",
|
|
6865
|
+
low: "Rendah"
|
|
6866
|
+
},
|
|
6867
|
+
coverage: "Cakupan",
|
|
6868
|
+
coverageDiffOnly: "hanya diff",
|
|
6869
|
+
coverageFullFiles: (files) => `diff plus konteks penuh dari ${files}`,
|
|
6870
|
+
skippedBudget: "Dilewati (batas token)",
|
|
6871
|
+
skippedFilters: "Dilewati (filter)",
|
|
6872
|
+
reviewedCommit: "Commit yang direview",
|
|
6873
|
+
mode: "Mode",
|
|
6874
|
+
linkedIssues: "Issue terkait",
|
|
6875
|
+
issueStatus: {
|
|
6876
|
+
addressed: "\u2705 terpenuhi",
|
|
6877
|
+
"partly-addressed": "\u{1F7E1} sebagian",
|
|
6878
|
+
"not-addressed": "\u274C belum",
|
|
6879
|
+
unclear: "\u2754 belum jelas"
|
|
6880
|
+
},
|
|
6881
|
+
preMerge: "Cek sebelum merge",
|
|
6882
|
+
check: "Cek",
|
|
6883
|
+
result: "Hasil",
|
|
6884
|
+
detail: "Detail",
|
|
6885
|
+
changedFiles: (n) => `File yang berubah (${n})`,
|
|
6886
|
+
file: "File",
|
|
6887
|
+
summary: "Ringkasan",
|
|
6888
|
+
notInline: (n) => `Temuan yang tidak diposting inline (${n})`,
|
|
6889
|
+
details: "Detail review",
|
|
6890
|
+
configSource: "Konfigurasi",
|
|
6891
|
+
profile: "Profil",
|
|
6892
|
+
models: "Model",
|
|
6893
|
+
tokens: "Token (prompt / completion)",
|
|
6894
|
+
latency: "Latensi",
|
|
6895
|
+
reviewedCommits: "Commit yang direview",
|
|
6896
|
+
suppressed: "Disaring (keyakinan rendah, total)",
|
|
6897
|
+
unanchored: "Tidak menempel ke baris diff",
|
|
6898
|
+
skippedDuplicates: "Duplikat dilewati (sudah diposting)",
|
|
6899
|
+
toolWarnings: "Peringatan tool",
|
|
6900
|
+
evidence: "Bukti",
|
|
6901
|
+
fix: "Perbaikan",
|
|
6902
|
+
exploitability: "Cara dieksploitasi",
|
|
6903
|
+
promptForAgents: "\u{1F916} Prompt untuk AI agent",
|
|
6904
|
+
helpReply: `Perintah AuraCheck PR review (tulis di awal komentar):
|
|
6905
|
+
|
|
6906
|
+
- \`@auracheck review\`: review commit baru sekarang, walaupun MR ini biasanya dilewati otomatis (draft, label, kata kunci judul).
|
|
6907
|
+
- \`@auracheck full review\`: review ulang semua file MR, bukan hanya yang berubah sejak review terakhir. Temuan yang sudah diposting tidak diulang.
|
|
6908
|
+
- \`@auracheck help\`: tampilkan daftar ini.
|
|
6909
|
+
|
|
6910
|
+
Pengaturan ada di \`.auracheck.yaml\` di root repo: ${DOCS_URL}`,
|
|
6911
|
+
limitRetry: "Push berikutnya setelah reset akan direview seperti biasa.",
|
|
6912
|
+
failedRetry: "Akan dicoba lagi di push berikutnya, atau komentari `@auracheck review`."
|
|
6913
|
+
};
|
|
6914
|
+
function strings(language) {
|
|
6915
|
+
return language.toLowerCase().startsWith("id") ? ID : EN;
|
|
6916
|
+
}
|
|
6917
|
+
|
|
6918
|
+
// src/review/inline.ts
|
|
6919
|
+
function fenceFor(content) {
|
|
6920
|
+
let longest = 0;
|
|
6921
|
+
for (const m of content.matchAll(/`+/g)) {
|
|
6922
|
+
longest = Math.max(longest, m[0].length);
|
|
6923
|
+
}
|
|
6924
|
+
return "`".repeat(Math.max(3, longest + 1));
|
|
6925
|
+
}
|
|
6926
|
+
function codeBlock(content, info = "") {
|
|
6927
|
+
const fence = fenceFor(content);
|
|
6928
|
+
const body = content.replace(/\n+$/, "");
|
|
6929
|
+
if (body === "") return `${fence}${info}
|
|
6930
|
+
${fence}`;
|
|
6931
|
+
return `${fence}${info}
|
|
6932
|
+
${body}
|
|
6933
|
+
${fence}`;
|
|
6934
|
+
}
|
|
6935
|
+
function suggestionSpan(f) {
|
|
6936
|
+
const anchorLine = f.anchor?.newLine ?? f.startLine;
|
|
6937
|
+
return Math.max(0, f.endLine - anchorLine);
|
|
6938
|
+
}
|
|
6939
|
+
function renderInlineBody(f, language) {
|
|
6940
|
+
const t = strings(language);
|
|
6941
|
+
const parts = [];
|
|
6942
|
+
parts.push(`**[${f.severity}] ${f.category}: ${f.title.trim()}**`);
|
|
6943
|
+
if (f.body.trim()) parts.push(f.body.trim());
|
|
6944
|
+
if (f.evidence.trim()) {
|
|
6945
|
+
parts.push(`**${t.evidence}**
|
|
6946
|
+
|
|
6947
|
+
${codeBlock(f.evidence)}`);
|
|
6948
|
+
}
|
|
6949
|
+
if (f.suggestedFix.trim()) {
|
|
6950
|
+
parts.push(`**${t.fix}:** ${f.suggestedFix.trim()}`);
|
|
6951
|
+
}
|
|
6952
|
+
if (f.category === "security" && f.exploitability?.trim()) {
|
|
6953
|
+
parts.push(`**${t.exploitability}:** ${f.exploitability.trim()}`);
|
|
6954
|
+
}
|
|
6955
|
+
if (f.suggestionCode != null) {
|
|
6956
|
+
parts.push(
|
|
6957
|
+
codeBlock(f.suggestionCode, `suggestion:-0+${suggestionSpan(f)}`)
|
|
6958
|
+
);
|
|
6959
|
+
}
|
|
6960
|
+
if (f.aiAgentPrompt?.trim()) {
|
|
6961
|
+
parts.push(
|
|
6962
|
+
`<details>
|
|
6963
|
+
<summary>${t.promptForAgents}</summary>
|
|
6964
|
+
|
|
6965
|
+
${codeBlock(f.aiAgentPrompt.trim())}
|
|
6966
|
+
|
|
6967
|
+
</details>`
|
|
6968
|
+
);
|
|
6969
|
+
}
|
|
6970
|
+
parts.push(fingerprintMarker(f.fingerprint));
|
|
6971
|
+
return parts.join("\n\n");
|
|
6972
|
+
}
|
|
6973
|
+
|
|
6974
|
+
// src/review/state.ts
|
|
6975
|
+
var NOTE_MARKER = "<!-- auracheck-review:v1 -->";
|
|
6976
|
+
var STATE_MARKER_PREFIX = "<!-- auracheck-review-state:v1 ";
|
|
6977
|
+
var STATUS_START = "<!-- auracheck-status-start -->";
|
|
6978
|
+
var STATUS_END = "<!-- auracheck-status-end -->";
|
|
6979
|
+
var MAX_REVIEWED_SHAS = 20;
|
|
6980
|
+
var MAX_HISTORY = 15;
|
|
6981
|
+
function emptyState() {
|
|
6982
|
+
return {
|
|
6983
|
+
lastReviewedSha: null,
|
|
6984
|
+
reviewedShas: [],
|
|
6985
|
+
posted: {},
|
|
6986
|
+
suppressedTotal: 0,
|
|
6987
|
+
history: []
|
|
6988
|
+
};
|
|
6989
|
+
}
|
|
6990
|
+
function serializeState(state) {
|
|
6991
|
+
const json = JSON.stringify(state).replace(/</g, "\\u003c").replace(/>/g, "\\u003e");
|
|
6992
|
+
return `${STATE_MARKER_PREFIX}${json} -->`;
|
|
6993
|
+
}
|
|
6994
|
+
function parseState(body) {
|
|
6995
|
+
if (!body) return emptyState();
|
|
6996
|
+
const start = body.indexOf(STATE_MARKER_PREFIX);
|
|
6997
|
+
if (start === -1) return emptyState();
|
|
6998
|
+
const from = start + STATE_MARKER_PREFIX.length;
|
|
6999
|
+
const end = body.indexOf(" -->", from);
|
|
7000
|
+
if (end === -1) return emptyState();
|
|
7001
|
+
try {
|
|
7002
|
+
const raw = JSON.parse(body.slice(from, end));
|
|
7003
|
+
const s = emptyState();
|
|
7004
|
+
if (typeof raw.lastReviewedSha === "string") {
|
|
7005
|
+
s.lastReviewedSha = raw.lastReviewedSha;
|
|
7006
|
+
}
|
|
7007
|
+
if (Array.isArray(raw.reviewedShas)) {
|
|
7008
|
+
s.reviewedShas = raw.reviewedShas.filter(
|
|
7009
|
+
(x) => typeof x === "string"
|
|
7010
|
+
);
|
|
7011
|
+
}
|
|
7012
|
+
if (raw.posted && typeof raw.posted === "object") s.posted = raw.posted;
|
|
7013
|
+
if (typeof raw.suppressedTotal === "number") {
|
|
7014
|
+
s.suppressedTotal = raw.suppressedTotal;
|
|
7015
|
+
}
|
|
7016
|
+
if (Array.isArray(raw.history)) s.history = raw.history;
|
|
7017
|
+
return s;
|
|
7018
|
+
} catch {
|
|
7019
|
+
return emptyState();
|
|
7020
|
+
}
|
|
7021
|
+
}
|
|
7022
|
+
function recordReviewed(state, entry) {
|
|
7023
|
+
const reviewedShas = [
|
|
7024
|
+
...state.reviewedShas.filter((s) => s !== entry.sha),
|
|
7025
|
+
entry.sha
|
|
7026
|
+
].slice(-MAX_REVIEWED_SHAS);
|
|
7027
|
+
return {
|
|
7028
|
+
...state,
|
|
7029
|
+
lastReviewedSha: entry.sha,
|
|
7030
|
+
reviewedShas,
|
|
7031
|
+
history: [...state.history, entry].slice(-MAX_HISTORY)
|
|
7032
|
+
};
|
|
7033
|
+
}
|
|
7034
|
+
function recordAttempt(state, entry) {
|
|
7035
|
+
return { ...state, history: [...state.history, entry].slice(-MAX_HISTORY) };
|
|
7036
|
+
}
|
|
7037
|
+
function isStickyNote(note, botUserId) {
|
|
7038
|
+
if (note.system || !note.body.includes(NOTE_MARKER)) return false;
|
|
7039
|
+
return botUserId == null || note.authorId === botUserId;
|
|
7040
|
+
}
|
|
7041
|
+
function findStickyNotes(notes, botUserId) {
|
|
7042
|
+
const mine = notes.filter((n) => isStickyNote(n, botUserId)).sort(
|
|
7043
|
+
(a, b) => a.createdAt === b.createdAt ? a.id - b.id : a.createdAt < b.createdAt ? -1 : 1
|
|
7044
|
+
);
|
|
7045
|
+
return { note: mine[0] ?? null, duplicates: mine.slice(1) };
|
|
7046
|
+
}
|
|
7047
|
+
function replaceStatusBlock(body, statusMarkdown) {
|
|
7048
|
+
const s = body.indexOf(STATUS_START);
|
|
7049
|
+
const e = body.indexOf(STATUS_END);
|
|
7050
|
+
if (s === -1 || e === -1 || e < s) return body;
|
|
7051
|
+
return `${body.slice(0, s + STATUS_START.length)}
|
|
7052
|
+
${statusMarkdown}
|
|
7053
|
+
${body.slice(e)}`;
|
|
7054
|
+
}
|
|
7055
|
+
function replaceStateMarker(body, state) {
|
|
7056
|
+
const start = body.indexOf(STATE_MARKER_PREFIX);
|
|
7057
|
+
if (start === -1) return `${body}
|
|
7058
|
+
|
|
7059
|
+
${serializeState(state)}`;
|
|
7060
|
+
const end = body.indexOf(" -->", start + STATE_MARKER_PREFIX.length);
|
|
7061
|
+
if (end === -1) return `${body}
|
|
7062
|
+
|
|
7063
|
+
${serializeState(state)}`;
|
|
7064
|
+
return `${body.slice(0, start)}${serializeState(state)}${body.slice(end + 4)}`;
|
|
7065
|
+
}
|
|
7066
|
+
var StickyNote = class _StickyNote {
|
|
7067
|
+
constructor(provider, iid, existing, warn2 = () => {
|
|
7068
|
+
}) {
|
|
7069
|
+
this.provider = provider;
|
|
7070
|
+
this.iid = iid;
|
|
7071
|
+
this.warn = warn2;
|
|
7072
|
+
this.noteId = existing?.id ?? null;
|
|
7073
|
+
this.body = existing?.body ?? null;
|
|
7074
|
+
}
|
|
7075
|
+
provider;
|
|
7076
|
+
iid;
|
|
7077
|
+
warn;
|
|
7078
|
+
noteId;
|
|
7079
|
+
body;
|
|
7080
|
+
get id() {
|
|
7081
|
+
return this.noteId;
|
|
7082
|
+
}
|
|
7083
|
+
/**
|
|
7084
|
+
* Load the note (collapsing duplicates a race may have left: the oldest
|
|
7085
|
+
* wins and the rest are deleted).
|
|
7086
|
+
*/
|
|
7087
|
+
static async load(provider, iid, botUserId, warn2 = () => {
|
|
7088
|
+
}, collapseDuplicates = true) {
|
|
7089
|
+
const notes = await provider.listNotes(iid);
|
|
7090
|
+
const { note, duplicates } = findStickyNotes(notes, botUserId);
|
|
7091
|
+
for (const d of collapseDuplicates ? duplicates : []) {
|
|
7092
|
+
try {
|
|
7093
|
+
await provider.deleteNote(iid, d.id);
|
|
7094
|
+
} catch (err) {
|
|
7095
|
+
warn2(`could not delete duplicate summary note ${d.id}: ${err.message}`);
|
|
7096
|
+
}
|
|
7097
|
+
}
|
|
7098
|
+
return new _StickyNote(provider, iid, note, warn2);
|
|
7099
|
+
}
|
|
7100
|
+
/** Update in place when the note exists; create it only otherwise. */
|
|
7101
|
+
async save(body) {
|
|
7102
|
+
if (this.noteId != null && body === this.body) return this.noteId;
|
|
7103
|
+
if (this.noteId != null) {
|
|
7104
|
+
await this.provider.updateNote(this.iid, this.noteId, body);
|
|
7105
|
+
} else {
|
|
7106
|
+
const created = await this.provider.createNote(this.iid, body);
|
|
7107
|
+
this.noteId = created.id;
|
|
7108
|
+
}
|
|
7109
|
+
this.body = body;
|
|
7110
|
+
return this.noteId;
|
|
7111
|
+
}
|
|
7112
|
+
};
|
|
7113
|
+
|
|
7114
|
+
// src/review/note.ts
|
|
7115
|
+
function shortSha(sha) {
|
|
7116
|
+
return (sha ?? "").slice(0, 8);
|
|
7117
|
+
}
|
|
7118
|
+
function shaLink(ctx, sha) {
|
|
7119
|
+
const url = ctx.commitUrl(sha);
|
|
7120
|
+
return url ? `[\`${shortSha(sha)}\`](${url})` : `\`${shortSha(sha)}\``;
|
|
7121
|
+
}
|
|
7122
|
+
function cell(text) {
|
|
7123
|
+
return text.replace(/\r?\n+/g, " ").replace(/\|/g, "\\|").trim();
|
|
7124
|
+
}
|
|
7125
|
+
function modeText(t, ctx) {
|
|
7126
|
+
return ctx.mode === "incremental" && ctx.sinceSha ? t.modeIncremental(`\`${shortSha(ctx.sinceSha)}\``) : t.modeFull;
|
|
7127
|
+
}
|
|
7128
|
+
function renderStatus(ctx, status, counts) {
|
|
7129
|
+
const t = strings(ctx.language);
|
|
7130
|
+
let line;
|
|
7131
|
+
switch (status.kind) {
|
|
7132
|
+
case "reviewed":
|
|
7133
|
+
line = t.statusReviewed(shaLink(ctx, ctx.headSha), modeText(t, ctx));
|
|
7134
|
+
if (counts) line += ` \xB7 ${t.findingsLine(counts.total, counts.inline)}`;
|
|
7135
|
+
break;
|
|
7136
|
+
case "no-changes":
|
|
7137
|
+
line = t.statusNoChanges(shaLink(ctx, ctx.headSha));
|
|
7138
|
+
break;
|
|
7139
|
+
case "skipped":
|
|
7140
|
+
line = t.statusSkipped(status.reason ?? "");
|
|
7141
|
+
break;
|
|
7142
|
+
case "limit": {
|
|
7143
|
+
const l = status.limit;
|
|
7144
|
+
line = l ? `${t.statusLimit(l.used, l.limit, l.resetsAt)}. ${t.limitRetry}` : t.statusFailed(status.reason ?? "limit reached");
|
|
7145
|
+
break;
|
|
7146
|
+
}
|
|
7147
|
+
case "failed":
|
|
7148
|
+
line = `${t.statusFailed(status.reason ?? "unknown error")}. ${t.failedRetry}`;
|
|
7149
|
+
break;
|
|
7150
|
+
case "running":
|
|
7151
|
+
line = t.statusRunning(shaLink(ctx, ctx.headSha));
|
|
7152
|
+
break;
|
|
7153
|
+
}
|
|
7154
|
+
return `**${t.status}:** ${line}`;
|
|
7155
|
+
}
|
|
7156
|
+
function countBy(keys, findings, pick, fromStats) {
|
|
7157
|
+
const out = {};
|
|
7158
|
+
for (const k of keys) out[k] = 0;
|
|
7159
|
+
if (fromStats) {
|
|
7160
|
+
for (const k of keys) out[k] = Number(fromStats[k] ?? 0);
|
|
7161
|
+
return out;
|
|
7162
|
+
}
|
|
7163
|
+
for (const f of findings) out[pick(f)] = (out[pick(f)] ?? 0) + 1;
|
|
7164
|
+
return out;
|
|
7165
|
+
}
|
|
7166
|
+
var CHECK_NAMES = {
|
|
7167
|
+
en: { title: "Title", description: "Description", issue: "Linked issue" },
|
|
7168
|
+
id: { title: "Judul", description: "Deskripsi", issue: "Issue terkait" }
|
|
7169
|
+
};
|
|
7170
|
+
function details(summary, body) {
|
|
7171
|
+
return `<details>
|
|
7172
|
+
<summary>${summary}</summary>
|
|
7173
|
+
|
|
7174
|
+
${body}
|
|
7175
|
+
|
|
7176
|
+
</details>`;
|
|
7177
|
+
}
|
|
7178
|
+
function listFiles(files, max = 15) {
|
|
7179
|
+
const shown = files.slice(0, max).map((f) => `\`${f}\``);
|
|
7180
|
+
const more = files.length > max ? ` +${files.length - max}` : "";
|
|
7181
|
+
return `${shown.join(", ")}${more}`;
|
|
7182
|
+
}
|
|
7183
|
+
function renderWalkthrough(input, t) {
|
|
7184
|
+
const r = input.response;
|
|
7185
|
+
if (!r) return [];
|
|
7186
|
+
const cfg = input.config.reviews;
|
|
7187
|
+
const out = [];
|
|
7188
|
+
const s = r.summary;
|
|
7189
|
+
if (s.describe?.trim())
|
|
7190
|
+
out.push(`### ${t.whatChanges}
|
|
7191
|
+
|
|
7192
|
+
${s.describe.trim()}`);
|
|
7193
|
+
const reasons = (xs) => cell(xs.join("; ")) || "-";
|
|
7194
|
+
out.push(
|
|
7195
|
+
[
|
|
7196
|
+
`### ${t.risk}`,
|
|
7197
|
+
"",
|
|
7198
|
+
`| | ${t.level} | ${t.why} |`,
|
|
7199
|
+
"|---|---|---|",
|
|
7200
|
+
`| ${t.mergeRisk} | ${t.riskLevel[s.mergeRisk.level]} | ${reasons(s.mergeRisk.reasons)} |`,
|
|
7201
|
+
`| ${t.securityRisk} | ${t.riskLevel[s.securityRisk.level]} | ${reasons(s.securityRisk.reasons)} |`
|
|
7202
|
+
].join("\n")
|
|
7203
|
+
);
|
|
7204
|
+
if (cfg.estimate_code_review_effort && s.effort) {
|
|
7205
|
+
out.push(
|
|
7206
|
+
`**${t.effort}:** ${s.effort.score}/5 \xB7 ${s.effort.reason.trim()}`
|
|
7207
|
+
);
|
|
7208
|
+
}
|
|
7209
|
+
const byCat = countBy(
|
|
7210
|
+
FINDING_CATEGORIES,
|
|
7211
|
+
r.findings,
|
|
7212
|
+
(f) => f.category,
|
|
7213
|
+
r.stats?.byCategory
|
|
7214
|
+
);
|
|
7215
|
+
const bySev = countBy(
|
|
7216
|
+
SEVERITIES,
|
|
7217
|
+
r.findings,
|
|
7218
|
+
(f) => f.severity,
|
|
7219
|
+
r.stats?.bySeverity
|
|
7220
|
+
);
|
|
7221
|
+
out.push(
|
|
7222
|
+
[
|
|
7223
|
+
`### ${t.findings}`,
|
|
7224
|
+
"",
|
|
7225
|
+
`| ${t.category} | ${t.count} |`,
|
|
7226
|
+
"|---|---|",
|
|
7227
|
+
...FINDING_CATEGORIES.map(
|
|
7228
|
+
(c) => `| ${t.categoryLabel[c]} | ${byCat[c]} |`
|
|
7229
|
+
),
|
|
7230
|
+
"",
|
|
7231
|
+
`| ${t.severity} | ${t.count} |`,
|
|
7232
|
+
"|---|---|",
|
|
7233
|
+
...SEVERITIES.map((v) => `| ${t.severityLabel[v]} | ${bySev[v]} |`)
|
|
7234
|
+
].join("\n")
|
|
7235
|
+
);
|
|
7236
|
+
if (cfg.changed_files_summary && s.changedFiles?.length) {
|
|
7237
|
+
const rows = s.changedFiles.map(
|
|
7238
|
+
(f) => `| \`${cell(f.file)}\` | ${cell(f.summary)} |`
|
|
7239
|
+
);
|
|
7240
|
+
out.push(
|
|
7241
|
+
details(
|
|
7242
|
+
t.changedFiles(s.changedFiles.length),
|
|
7243
|
+
[`| ${t.file} | ${t.summary} |`, "|---|---|", ...rows].join("\n")
|
|
7244
|
+
)
|
|
7245
|
+
);
|
|
7246
|
+
}
|
|
7247
|
+
return out;
|
|
7248
|
+
}
|
|
7249
|
+
function renderNote(input) {
|
|
7250
|
+
const t = strings(input.language);
|
|
7251
|
+
const r = input.response;
|
|
7252
|
+
const cfg = input.config.reviews;
|
|
7253
|
+
const parts = [NOTE_MARKER, `## ${t.title}`];
|
|
7254
|
+
const counts = r ? { total: r.findings.length, inline: input.postedInline } : void 0;
|
|
7255
|
+
parts.push(
|
|
7256
|
+
`${STATUS_START}
|
|
7257
|
+
${renderStatus(input, input.status, counts)}
|
|
7258
|
+
${STATUS_END}`
|
|
7259
|
+
);
|
|
7260
|
+
const walkthrough = renderWalkthrough(input, t);
|
|
7261
|
+
if (walkthrough.length) {
|
|
7262
|
+
parts.push(
|
|
7263
|
+
cfg.collapse_walkthrough ? details(t.walkthrough, walkthrough.join("\n\n")) : walkthrough.join("\n\n")
|
|
7264
|
+
);
|
|
7265
|
+
}
|
|
7266
|
+
if (r) {
|
|
7267
|
+
const cov = r.coverage;
|
|
7268
|
+
const lines = [];
|
|
7269
|
+
lines.push(
|
|
7270
|
+
`**${t.coverage}:** ${cov.kind === "diff+full-files" && cov.fullContextFiles.length ? t.coverageFullFiles(listFiles(cov.fullContextFiles)) : t.coverageDiffOnly}`
|
|
7271
|
+
);
|
|
7272
|
+
if (cov.budgetSkippedFiles.length) {
|
|
7273
|
+
lines.push(
|
|
7274
|
+
`**${t.skippedBudget}:** ${listFiles(cov.budgetSkippedFiles)}`
|
|
7275
|
+
);
|
|
7276
|
+
}
|
|
7277
|
+
if (input.skippedFiles.length) {
|
|
7278
|
+
const shown = input.skippedFiles.slice(0, 10).map((f) => `\`${f.path}\` (${f.reason})`).join(", ");
|
|
7279
|
+
const more = input.skippedFiles.length > 10 ? ` +${input.skippedFiles.length - 10}` : "";
|
|
7280
|
+
lines.push(`**${t.skippedFilters}:** ${shown}${more}`);
|
|
7281
|
+
}
|
|
7282
|
+
lines.push(
|
|
7283
|
+
`**${t.reviewedCommit}:** ${shaLink(input, input.headSha)} \xB7 **${t.mode}:** ${modeText(t, input)}`
|
|
7284
|
+
);
|
|
7285
|
+
parts.push(lines.join(" \n"));
|
|
7286
|
+
if (cfg.assess_linked_issues && r.summary.linkedIssues?.length) {
|
|
7287
|
+
parts.push(
|
|
7288
|
+
[
|
|
7289
|
+
`### ${t.linkedIssues}`,
|
|
7290
|
+
"",
|
|
7291
|
+
...r.summary.linkedIssues.map(
|
|
7292
|
+
(i) => `- ${i.ref}: ${t.issueStatus[i.status] ?? i.status} \xB7 ${i.reason.trim()}`
|
|
7293
|
+
)
|
|
7294
|
+
].join("\n")
|
|
7295
|
+
);
|
|
7296
|
+
}
|
|
7297
|
+
}
|
|
7298
|
+
if (input.preMerge.length) {
|
|
7299
|
+
const names = input.language.toLowerCase().startsWith("id") ? CHECK_NAMES.id : CHECK_NAMES.en;
|
|
7300
|
+
parts.push(
|
|
7301
|
+
[
|
|
7302
|
+
`### ${t.preMerge}`,
|
|
7303
|
+
"",
|
|
7304
|
+
`| ${t.check} | ${t.result} | ${t.detail} |`,
|
|
7305
|
+
"|---|---|---|",
|
|
7306
|
+
...input.preMerge.map(
|
|
7307
|
+
(c) => `| ${names[c.id]} | ${c.passed ? "\u2705" : c.mode === "error" ? "\u274C" : "\u26A0\uFE0F"} | ${cell(c.detail)} |`
|
|
7308
|
+
)
|
|
7309
|
+
].join("\n")
|
|
7310
|
+
);
|
|
7311
|
+
}
|
|
7312
|
+
if (input.notInline.length) {
|
|
7313
|
+
const items = input.notInline.map(
|
|
7314
|
+
(f) => `- \`${f.file}:${f.startLine}\` **${f.severity}** ${f.category}: ${cell(f.title)}`
|
|
7315
|
+
);
|
|
7316
|
+
parts.push(details(t.notInline(input.notInline.length), items.join("\n")));
|
|
7317
|
+
}
|
|
7318
|
+
if (r) {
|
|
7319
|
+
const u = r.usage;
|
|
7320
|
+
const rows = [
|
|
7321
|
+
[t.configSource, `\`${input.configSource}\``],
|
|
7322
|
+
[t.profile, cfg.profile],
|
|
7323
|
+
[
|
|
7324
|
+
t.models,
|
|
7325
|
+
u.models.length ? u.models.map((m) => `\`${m}\``).join(", ") : "-"
|
|
7326
|
+
],
|
|
7327
|
+
[t.tokens, `${u.promptTokens} / ${u.completionTokens}`],
|
|
7328
|
+
[t.latency, `${(u.latencyMs / 1e3).toFixed(1)} s`],
|
|
7329
|
+
[t.reviewedCommits, String(input.reviewedCommits)],
|
|
7330
|
+
[t.suppressed, `${r.stats.suppressed} (${input.state.suppressedTotal})`],
|
|
7331
|
+
[t.unanchored, String(r.stats.unanchored)],
|
|
7332
|
+
[t.skippedDuplicates, String(input.skippedDuplicates)]
|
|
7333
|
+
];
|
|
7334
|
+
if (input.toolWarnings.length) {
|
|
7335
|
+
rows.push([t.toolWarnings, cell(input.toolWarnings.join("; "))]);
|
|
7336
|
+
}
|
|
7337
|
+
parts.push(
|
|
7338
|
+
details(
|
|
7339
|
+
t.details,
|
|
7340
|
+
["| | |", "|---|---|", ...rows.map(([k, v]) => `| ${k} | ${v} |`)].join(
|
|
7341
|
+
"\n"
|
|
7342
|
+
)
|
|
7343
|
+
)
|
|
7344
|
+
);
|
|
7345
|
+
}
|
|
7346
|
+
parts.push(`---
|
|
7347
|
+
<sub>${t.commands}</sub>`);
|
|
7348
|
+
parts.push(serializeState(input.state));
|
|
7349
|
+
return parts.join("\n\n");
|
|
7350
|
+
}
|
|
7351
|
+
|
|
7352
|
+
// src/review/summary-block.ts
|
|
7353
|
+
var SUMMARY_START = "<!-- auracheck-summary-start -->";
|
|
7354
|
+
var SUMMARY_END = "<!-- auracheck-summary-end -->";
|
|
7355
|
+
function applySummaryBlock(description, placeholder, summary) {
|
|
7356
|
+
const block = `${SUMMARY_START}
|
|
7357
|
+
${summary.trim()}
|
|
7358
|
+
${SUMMARY_END}`;
|
|
7359
|
+
const s = description.indexOf(SUMMARY_START);
|
|
7360
|
+
const e = description.indexOf(SUMMARY_END);
|
|
7361
|
+
let next = null;
|
|
7362
|
+
if (s !== -1 && e > s) {
|
|
7363
|
+
next = description.slice(0, s) + block + description.slice(e + SUMMARY_END.length);
|
|
7364
|
+
} else if (placeholder && description.includes(placeholder)) {
|
|
7365
|
+
next = description.replace(placeholder, block);
|
|
7366
|
+
}
|
|
7367
|
+
return next !== null && next !== description ? next : null;
|
|
7368
|
+
}
|
|
7369
|
+
|
|
7370
|
+
// src/review/premerge.ts
|
|
7371
|
+
var DRAFT_WORDS = /\b(?:wip|draft|tmp|temp|todo|fixup|test|update|changes?|fix(?:es)?|stuff|misc)\b/gi;
|
|
7372
|
+
var DRAFT_PREFIX = /^\s*(?:\[(?:draft|wip)\]|\(draft\)|draft:|wip:)\s*/i;
|
|
7373
|
+
function requirementRegex(req) {
|
|
7374
|
+
if (!req) return null;
|
|
7375
|
+
const t = req.trim();
|
|
7376
|
+
const slashed = /^\/(.+)\/([gimsuy]*)$/s.exec(t);
|
|
7377
|
+
try {
|
|
7378
|
+
if (slashed) return new RegExp(slashed[1], slashed[2].replace("g", ""));
|
|
7379
|
+
if (t.startsWith("^")) return new RegExp(t);
|
|
7380
|
+
} catch {
|
|
7381
|
+
return null;
|
|
7382
|
+
}
|
|
7383
|
+
return null;
|
|
7384
|
+
}
|
|
7385
|
+
function checkTitle(title, requirements) {
|
|
7386
|
+
const bare = title.replace(DRAFT_PREFIX, "").trim();
|
|
7387
|
+
if (!bare) return { passed: false, detail: "title is empty" };
|
|
7388
|
+
if (bare.replace(DRAFT_WORDS, "").replace(/[\s\p{P}]/gu, "") === "") {
|
|
7389
|
+
return {
|
|
7390
|
+
passed: false,
|
|
7391
|
+
detail: "title only says WIP/draft/fix; say what changes"
|
|
7392
|
+
};
|
|
7393
|
+
}
|
|
7394
|
+
if (bare.length < 10) {
|
|
7395
|
+
return {
|
|
7396
|
+
passed: false,
|
|
7397
|
+
detail: `title is ${bare.length} characters; use at least 10`
|
|
7398
|
+
};
|
|
7399
|
+
}
|
|
7400
|
+
const re = requirementRegex(requirements);
|
|
7401
|
+
if (re && !re.test(bare)) {
|
|
7402
|
+
return { passed: false, detail: `title does not match ${re}` };
|
|
7403
|
+
}
|
|
7404
|
+
if (requirements && !re) {
|
|
7405
|
+
return {
|
|
7406
|
+
passed: true,
|
|
7407
|
+
detail: `requirement (not machine-checked): ${requirements}`
|
|
7408
|
+
};
|
|
7409
|
+
}
|
|
7410
|
+
return { passed: true, detail: "ok" };
|
|
7411
|
+
}
|
|
7412
|
+
function meaningfulDescription(description) {
|
|
7413
|
+
let d = description;
|
|
7414
|
+
const s = d.indexOf(SUMMARY_START);
|
|
7415
|
+
const e = d.indexOf(SUMMARY_END);
|
|
7416
|
+
if (s !== -1 && e > s) d = d.slice(0, s) + d.slice(e + SUMMARY_END.length);
|
|
7417
|
+
return d.replace(/<!--[\s\S]*?-->/g, " ").split("\n").filter((l) => !/^\s*#{1,6}\s/.test(l)).map((l) => l.replace(/^\s*[-*]\s*\[[ xX]\]\s*/, "")).join("\n").replace(/@auracheck summary/gi, " ").replace(/\s+/g, " ").trim();
|
|
7418
|
+
}
|
|
7419
|
+
function checkDescription(description) {
|
|
7420
|
+
const text = meaningfulDescription(description);
|
|
7421
|
+
if (text.length >= 30) return { passed: true, detail: "ok" };
|
|
7422
|
+
return {
|
|
7423
|
+
passed: false,
|
|
7424
|
+
detail: text.length === 0 ? "description is empty (or only the template)" : `description has ${text.length} characters of its own text; write at least 30`
|
|
7425
|
+
};
|
|
7426
|
+
}
|
|
7427
|
+
function runPreMergeChecks(input) {
|
|
7428
|
+
const c = input.config.reviews.pre_merge_checks;
|
|
7429
|
+
const out = [];
|
|
7430
|
+
if (c.title.mode !== "off") {
|
|
7431
|
+
out.push({
|
|
7432
|
+
id: "title",
|
|
7433
|
+
mode: c.title.mode,
|
|
7434
|
+
...checkTitle(input.title, c.title.requirements)
|
|
7435
|
+
});
|
|
7436
|
+
}
|
|
7437
|
+
if (c.description.mode !== "off") {
|
|
7438
|
+
out.push({
|
|
7439
|
+
id: "description",
|
|
7440
|
+
mode: c.description.mode,
|
|
7441
|
+
...checkDescription(input.description)
|
|
7442
|
+
});
|
|
7443
|
+
}
|
|
7444
|
+
if (c.issue_assessment.mode !== "off") {
|
|
7445
|
+
const n = input.linkedIssueCount;
|
|
7446
|
+
out.push({
|
|
7447
|
+
id: "issue",
|
|
7448
|
+
mode: c.issue_assessment.mode,
|
|
7449
|
+
passed: n > 0,
|
|
7450
|
+
detail: n > 0 ? `${n} linked issue${n === 1 ? "" : "s"}` : "no linked or closing issue (write `Closes #123`)"
|
|
7451
|
+
});
|
|
7452
|
+
}
|
|
7453
|
+
return out;
|
|
7454
|
+
}
|
|
7455
|
+
function failedErrorChecks(results) {
|
|
7456
|
+
return results.filter((r) => !r.passed && r.mode === "error");
|
|
7457
|
+
}
|
|
7458
|
+
|
|
7459
|
+
// src/review/tools/lint.ts
|
|
7460
|
+
import { execFile } from "child_process";
|
|
7461
|
+
import { promises as fs6, existsSync } from "fs";
|
|
7462
|
+
import path5 from "path";
|
|
7463
|
+
|
|
7464
|
+
// src/review/diff.ts
|
|
7465
|
+
var HUNK_RE = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;
|
|
7466
|
+
function parseDiff(diff) {
|
|
7467
|
+
const out = [];
|
|
7468
|
+
let oldLine = 0;
|
|
7469
|
+
let newLine = 0;
|
|
7470
|
+
let inHunk = false;
|
|
7471
|
+
for (const raw of diff.split("\n")) {
|
|
7472
|
+
const hunk = HUNK_RE.exec(raw);
|
|
7473
|
+
if (hunk) {
|
|
7474
|
+
oldLine = Number(hunk[1]);
|
|
7475
|
+
newLine = Number(hunk[2]);
|
|
7476
|
+
inHunk = true;
|
|
7477
|
+
continue;
|
|
7478
|
+
}
|
|
7479
|
+
if (!inHunk) continue;
|
|
7480
|
+
if (raw.startsWith("\\")) continue;
|
|
7481
|
+
const sign = raw[0];
|
|
7482
|
+
const text = raw.slice(1);
|
|
7483
|
+
if (sign === "+") {
|
|
7484
|
+
out.push({ kind: "add", text, newLine, oldLine: null });
|
|
7485
|
+
newLine++;
|
|
7486
|
+
} else if (sign === "-") {
|
|
7487
|
+
out.push({ kind: "del", text, newLine: null, oldLine });
|
|
7488
|
+
oldLine++;
|
|
7489
|
+
} else if (sign === " ") {
|
|
7490
|
+
out.push({ kind: "ctx", text, newLine, oldLine });
|
|
7491
|
+
newLine++;
|
|
7492
|
+
oldLine++;
|
|
7493
|
+
}
|
|
7494
|
+
}
|
|
7495
|
+
return out;
|
|
7496
|
+
}
|
|
7497
|
+
function addedLines(diff) {
|
|
7498
|
+
const map = /* @__PURE__ */ new Map();
|
|
7499
|
+
for (const l of parseDiff(diff)) {
|
|
7500
|
+
if (l.kind === "add" && l.newLine !== null) map.set(l.newLine, l.text);
|
|
7501
|
+
}
|
|
7502
|
+
return map;
|
|
7503
|
+
}
|
|
7504
|
+
|
|
7505
|
+
// src/review/tools/lint.ts
|
|
7506
|
+
var defaultExec = (cmd, args, opts) => new Promise((resolve) => {
|
|
7507
|
+
execFile(
|
|
7508
|
+
cmd,
|
|
7509
|
+
args,
|
|
7510
|
+
{
|
|
7511
|
+
cwd: opts.cwd,
|
|
7512
|
+
timeout: opts.timeoutMs,
|
|
7513
|
+
maxBuffer: 32 * 1024 * 1024,
|
|
7514
|
+
env: { ...process.env, NO_COLOR: "1" }
|
|
7515
|
+
},
|
|
7516
|
+
(err, stdout, stderr) => {
|
|
7517
|
+
const timedOut = err?.killed || err?.signal === "SIGTERM";
|
|
7518
|
+
resolve({
|
|
7519
|
+
stdout: String(stdout ?? ""),
|
|
7520
|
+
stderr: String(stderr ?? ""),
|
|
7521
|
+
code: typeof err?.code === "number" ? err.code : err ? null : 0,
|
|
7522
|
+
error: timedOut ? "timed out" : err && typeof err.code !== "number" ? String(err.message ?? err) : void 0
|
|
7523
|
+
});
|
|
7524
|
+
}
|
|
7525
|
+
);
|
|
7526
|
+
});
|
|
7527
|
+
var LINT_TIMEOUT_MS = 9e4;
|
|
7528
|
+
var MAX_PER_TOOL = 60;
|
|
7529
|
+
var JS_FILE_RE = /\.(?:[cm]?[jt]s|[jt]sx)$/;
|
|
7530
|
+
var ESLINT_CONFIGS = [
|
|
7531
|
+
"eslint.config.js",
|
|
7532
|
+
"eslint.config.mjs",
|
|
7533
|
+
"eslint.config.cjs",
|
|
7534
|
+
"eslint.config.ts",
|
|
7535
|
+
"eslint.config.mts",
|
|
7536
|
+
"eslint.config.cts"
|
|
7537
|
+
];
|
|
7538
|
+
function lintableFiles(projectDir, files) {
|
|
7539
|
+
return files.filter(
|
|
7540
|
+
(f) => !f.deletedFile && JS_FILE_RE.test(f.newPath) && existsSync(path5.join(projectDir, f.newPath))
|
|
7541
|
+
);
|
|
7542
|
+
}
|
|
7543
|
+
async function biomeVersion(projectDir) {
|
|
7544
|
+
try {
|
|
7545
|
+
const pkg = JSON.parse(
|
|
7546
|
+
await fs6.readFile(path5.join(projectDir, "package.json"), "utf8")
|
|
7547
|
+
);
|
|
7548
|
+
const v = pkg?.devDependencies?.["@biomejs/biome"] ?? pkg?.dependencies?.["@biomejs/biome"];
|
|
7549
|
+
const m = typeof v === "string" ? /(\d+\.\d+\.\d+[\w.-]*)/.exec(v) : null;
|
|
7550
|
+
if (m) return m[1];
|
|
7551
|
+
} catch {
|
|
7552
|
+
}
|
|
7553
|
+
return "latest";
|
|
7554
|
+
}
|
|
7555
|
+
function biomeCategory(rule) {
|
|
7556
|
+
if (/\/security\//.test(rule)) return "security";
|
|
7557
|
+
if (/noUnused/.test(rule)) return "not-needed";
|
|
7558
|
+
if (/\/performance\//.test(rule)) return "inefficient";
|
|
7559
|
+
if (/\/(correctness|suspicious)\//.test(rule)) return "bug";
|
|
7560
|
+
return "maintainability";
|
|
7561
|
+
}
|
|
7562
|
+
function eslintCategory(rule) {
|
|
7563
|
+
if (/security|no-eval|no-implied-eval|no-new-func/.test(rule)) {
|
|
7564
|
+
return "security";
|
|
7565
|
+
}
|
|
7566
|
+
if (/no-unused|unused-imports/.test(rule)) return "not-needed";
|
|
7567
|
+
if (/no-undef|no-unreachable|no-dupe|no-cond-assign|no-fallthrough|no-self-compare|use-isnan|valid-typeof|no-floating-promises|no-misused-promises|rules-of-hooks|exhaustive-deps/.test(
|
|
7568
|
+
rule
|
|
7569
|
+
)) {
|
|
7570
|
+
return "bug";
|
|
7571
|
+
}
|
|
7572
|
+
if (/no-await-in-loop/.test(rule)) return "inefficient";
|
|
7573
|
+
return "maintainability";
|
|
7574
|
+
}
|
|
7575
|
+
function offsetToLine(content, offset) {
|
|
7576
|
+
let line = 1;
|
|
7577
|
+
for (let i = 0; i < offset && i < content.length; i++) {
|
|
7578
|
+
if (content[i] === 10) line++;
|
|
7579
|
+
}
|
|
7580
|
+
return line;
|
|
7581
|
+
}
|
|
7582
|
+
function messageText(msg) {
|
|
7583
|
+
if (typeof msg === "string") return msg;
|
|
7584
|
+
if (Array.isArray(msg)) {
|
|
7585
|
+
return msg.map((m) => m?.content ?? m ?? "").join("");
|
|
7586
|
+
}
|
|
7587
|
+
return "";
|
|
7588
|
+
}
|
|
7589
|
+
async function parseBiomeJson(stdout, projectDir) {
|
|
7590
|
+
const start = stdout.indexOf("{");
|
|
7591
|
+
if (start === -1) return [];
|
|
7592
|
+
const json = JSON.parse(stdout.slice(start));
|
|
7593
|
+
const out = [];
|
|
7594
|
+
const contents = /* @__PURE__ */ new Map();
|
|
7595
|
+
for (const d of json?.diagnostics ?? []) {
|
|
7596
|
+
const rule = String(d?.category ?? "");
|
|
7597
|
+
if (!rule.startsWith("lint/")) continue;
|
|
7598
|
+
const sev = String(d?.severity ?? "");
|
|
7599
|
+
if (sev !== "error" && sev !== "warning") continue;
|
|
7600
|
+
const file = String(
|
|
7601
|
+
d?.location?.path?.file ?? d?.location?.path ?? ""
|
|
7602
|
+
).replace(/^\.\//, "");
|
|
7603
|
+
if (!file) continue;
|
|
7604
|
+
let line = d?.location?.start?.line ?? null;
|
|
7605
|
+
const span = d?.location?.span;
|
|
7606
|
+
if (line == null && Array.isArray(span)) {
|
|
7607
|
+
if (!contents.has(file)) {
|
|
7608
|
+
contents.set(
|
|
7609
|
+
file,
|
|
7610
|
+
await fs6.readFile(path5.join(projectDir, file)).catch(() => Buffer.alloc(0))
|
|
7611
|
+
);
|
|
7612
|
+
}
|
|
7613
|
+
line = offsetToLine(contents.get(file) ?? Buffer.alloc(0), span[0]);
|
|
7614
|
+
}
|
|
7615
|
+
if (line == null) continue;
|
|
7616
|
+
out.push({
|
|
7617
|
+
tool: "biome",
|
|
7618
|
+
ruleId: rule.replace(/^lint\//, ""),
|
|
7619
|
+
file,
|
|
7620
|
+
line,
|
|
7621
|
+
severity: sev === "error" ? "medium" : "low",
|
|
7622
|
+
category: biomeCategory(rule),
|
|
7623
|
+
message: messageText(d?.description) || messageText(d?.message) || rule
|
|
7624
|
+
});
|
|
7625
|
+
}
|
|
7626
|
+
return out;
|
|
7627
|
+
}
|
|
7628
|
+
function parseEslintJson(stdout, projectDir) {
|
|
7629
|
+
const start = stdout.indexOf("[");
|
|
7630
|
+
if (start === -1) return [];
|
|
7631
|
+
const json = JSON.parse(stdout.slice(start));
|
|
7632
|
+
const out = [];
|
|
7633
|
+
for (const r of json ?? []) {
|
|
7634
|
+
const file = path5.relative(projectDir, String(r?.filePath ?? "")).split(path5.sep).join("/");
|
|
7635
|
+
for (const m of r?.messages ?? []) {
|
|
7636
|
+
if (!m?.ruleId || typeof m.line !== "number") continue;
|
|
7637
|
+
out.push({
|
|
7638
|
+
tool: "eslint",
|
|
7639
|
+
ruleId: m.ruleId,
|
|
7640
|
+
file,
|
|
7641
|
+
line: m.line,
|
|
7642
|
+
...m.endLine ? { endLine: m.endLine } : {},
|
|
7643
|
+
severity: m.severity === 2 ? "medium" : "low",
|
|
7644
|
+
category: eslintCategory(m.ruleId),
|
|
7645
|
+
message: String(m.message ?? m.ruleId)
|
|
7646
|
+
});
|
|
7647
|
+
}
|
|
7648
|
+
}
|
|
7649
|
+
return out;
|
|
7650
|
+
}
|
|
7651
|
+
function onAddedLines(findings, files) {
|
|
7652
|
+
const added = new Map(files.map((f) => [f.newPath, addedLines(f.diff)]));
|
|
7653
|
+
const counts = /* @__PURE__ */ new Map();
|
|
7654
|
+
return findings.filter((f) => {
|
|
7655
|
+
if (!added.get(f.file)?.has(f.line)) return false;
|
|
7656
|
+
const n = (counts.get(f.tool) ?? 0) + 1;
|
|
7657
|
+
counts.set(f.tool, n);
|
|
7658
|
+
return n <= MAX_PER_TOOL;
|
|
7659
|
+
});
|
|
7660
|
+
}
|
|
7661
|
+
async function runLinters(opts) {
|
|
7662
|
+
const exec = opts.exec ?? defaultExec;
|
|
7663
|
+
const warnings = [];
|
|
7664
|
+
const findings = [];
|
|
7665
|
+
const targets = lintableFiles(opts.projectDir, opts.files);
|
|
7666
|
+
if (targets.length === 0) return { findings, warnings };
|
|
7667
|
+
const paths = targets.map((f) => f.newPath);
|
|
7668
|
+
const hasBiome = ["biome.json", "biome.jsonc"].some(
|
|
7669
|
+
(f) => existsSync(path5.join(opts.projectDir, f))
|
|
7670
|
+
);
|
|
7671
|
+
if (opts.biome && hasBiome) {
|
|
7672
|
+
const version2 = await biomeVersion(opts.projectDir);
|
|
7673
|
+
const res = await exec(
|
|
7674
|
+
"npx",
|
|
7675
|
+
[
|
|
7676
|
+
"--yes",
|
|
7677
|
+
`@biomejs/biome@${version2}`,
|
|
7678
|
+
"lint",
|
|
7679
|
+
"--reporter=json",
|
|
7680
|
+
...paths
|
|
7681
|
+
],
|
|
7682
|
+
{ cwd: opts.projectDir, timeoutMs: LINT_TIMEOUT_MS }
|
|
7683
|
+
);
|
|
7684
|
+
if (res.error) {
|
|
7685
|
+
warnings.push(`biome: ${res.error}; skipped`);
|
|
7686
|
+
} else {
|
|
7687
|
+
try {
|
|
7688
|
+
findings.push(...await parseBiomeJson(res.stdout, opts.projectDir));
|
|
7689
|
+
} catch {
|
|
7690
|
+
warnings.push(
|
|
7691
|
+
`biome: could not read its JSON output (exit ${res.code}); skipped`
|
|
7692
|
+
);
|
|
7693
|
+
}
|
|
7694
|
+
}
|
|
7695
|
+
}
|
|
7696
|
+
const eslintBin = path5.join(
|
|
7697
|
+
opts.projectDir,
|
|
7698
|
+
"node_modules",
|
|
7699
|
+
".bin",
|
|
7700
|
+
"eslint"
|
|
7701
|
+
);
|
|
7702
|
+
const hasEslintConfig = ESLINT_CONFIGS.some(
|
|
7703
|
+
(f) => existsSync(path5.join(opts.projectDir, f))
|
|
7704
|
+
);
|
|
7705
|
+
if (opts.eslint && hasEslintConfig && existsSync(eslintBin)) {
|
|
7706
|
+
const res = await exec(eslintBin, ["-f", "json", ...paths], {
|
|
7707
|
+
cwd: opts.projectDir,
|
|
7708
|
+
timeoutMs: LINT_TIMEOUT_MS
|
|
7709
|
+
});
|
|
7710
|
+
if (res.error) {
|
|
7711
|
+
warnings.push(`eslint: ${res.error}; skipped`);
|
|
7712
|
+
} else {
|
|
7713
|
+
try {
|
|
7714
|
+
findings.push(...parseEslintJson(res.stdout, opts.projectDir));
|
|
7715
|
+
} catch {
|
|
7716
|
+
warnings.push(
|
|
7717
|
+
`eslint: could not read its JSON output (exit ${res.code}); skipped`
|
|
7718
|
+
);
|
|
7719
|
+
}
|
|
7720
|
+
}
|
|
7721
|
+
}
|
|
7722
|
+
return { findings: onAddedLines(findings, targets), warnings };
|
|
7723
|
+
}
|
|
7724
|
+
|
|
7725
|
+
// src/review/tools/osv.ts
|
|
7726
|
+
import { promises as fs7 } from "fs";
|
|
7727
|
+
import path6 from "path";
|
|
7728
|
+
var OSV_BATCH_URL = "https://api.osv.dev/v1/querybatch";
|
|
7729
|
+
var OSV_VULN_URL = "https://api.osv.dev/v1/vulns/";
|
|
7730
|
+
var TIMEOUT_MS = 8e3;
|
|
7731
|
+
var MAX_QUERIES = 100;
|
|
7732
|
+
var MAX_DETAILS = 25;
|
|
7733
|
+
var DEP_SECTIONS = [
|
|
7734
|
+
"dependencies",
|
|
7735
|
+
"devDependencies",
|
|
7736
|
+
"optionalDependencies",
|
|
7737
|
+
"peerDependencies"
|
|
7738
|
+
];
|
|
7739
|
+
function minVersion(range) {
|
|
7740
|
+
const r = range.trim();
|
|
7741
|
+
if (/^(workspace|file|link|git|git\+|github|http|https|npm|portal|patch):/.test(
|
|
7742
|
+
r
|
|
7743
|
+
)) {
|
|
7744
|
+
return null;
|
|
7745
|
+
}
|
|
7746
|
+
const first = r.split("||")[0].trim();
|
|
7747
|
+
const m = /^(?:[\^~]|>=|=|v)?\s*v?(\d+)(?:\.(\d+|x|\*))?(?:\.(\d+|x|\*))?(-[0-9A-Za-z.-]+)?/.exec(
|
|
7748
|
+
first
|
|
7749
|
+
);
|
|
7750
|
+
if (!m) return null;
|
|
7751
|
+
const num = (s) => s && /^\d+$/.test(s) ? s : "0";
|
|
7752
|
+
return `${m[1]}.${num(m[2])}.${num(m[3])}${m[4] ?? ""}`;
|
|
7753
|
+
}
|
|
7754
|
+
async function findAddedDependencies(files, projectDir) {
|
|
7755
|
+
const out = [];
|
|
7756
|
+
for (const f of files) {
|
|
7757
|
+
if (f.deletedFile || !/(^|\/)package\.json$/.test(f.newPath)) continue;
|
|
7758
|
+
let declared = null;
|
|
7759
|
+
if (projectDir) {
|
|
7760
|
+
try {
|
|
7761
|
+
const json = JSON.parse(
|
|
7762
|
+
await fs7.readFile(path6.join(projectDir, f.newPath), "utf8")
|
|
7763
|
+
);
|
|
7764
|
+
declared = /* @__PURE__ */ new Map();
|
|
7765
|
+
for (const s of DEP_SECTIONS) {
|
|
7766
|
+
for (const [n, v] of Object.entries(json?.[s] ?? {})) {
|
|
7767
|
+
if (typeof v === "string") declared.set(n, v);
|
|
7768
|
+
}
|
|
7769
|
+
}
|
|
7770
|
+
} catch {
|
|
7771
|
+
declared = null;
|
|
7772
|
+
}
|
|
7773
|
+
}
|
|
7774
|
+
for (const [line, text] of addedLines(f.diff)) {
|
|
7775
|
+
const m = /^\s*"((?:@[\w.-]+\/)?[\w.-]+)"\s*:\s*"([^"]+)"/.exec(text);
|
|
7776
|
+
if (!m) continue;
|
|
7777
|
+
const [, name, range] = m;
|
|
7778
|
+
if (declared) {
|
|
7779
|
+
if (declared.get(name) !== range) continue;
|
|
7780
|
+
} else if (["version", "node", "npm", "pnpm", "yarn", "name", "main"].includes(
|
|
7781
|
+
name
|
|
7782
|
+
)) {
|
|
7783
|
+
continue;
|
|
7784
|
+
}
|
|
7785
|
+
const version2 = minVersion(range);
|
|
7786
|
+
if (!version2) continue;
|
|
7787
|
+
out.push({ file: f.newPath, line, name, range, version: version2 });
|
|
7788
|
+
}
|
|
7789
|
+
}
|
|
7790
|
+
return out;
|
|
7791
|
+
}
|
|
7792
|
+
function mapSeverity(vuln) {
|
|
7793
|
+
const s = String(
|
|
7794
|
+
vuln?.database_specific?.severity ?? vuln?.affected?.[0]?.ecosystem_specific?.severity ?? ""
|
|
7795
|
+
).toUpperCase();
|
|
7796
|
+
if (s === "CRITICAL") return "critical";
|
|
7797
|
+
if (s === "HIGH") return "high";
|
|
7798
|
+
if (s === "LOW") return "low";
|
|
7799
|
+
return "medium";
|
|
7800
|
+
}
|
|
7801
|
+
function fixedVersion(vuln, name) {
|
|
7802
|
+
for (const a of vuln?.affected ?? []) {
|
|
7803
|
+
if (a?.package?.name !== name) continue;
|
|
7804
|
+
for (const r of a.ranges ?? []) {
|
|
7805
|
+
for (const e of r.events ?? []) if (e.fixed) return e.fixed;
|
|
7806
|
+
}
|
|
7807
|
+
}
|
|
7808
|
+
return null;
|
|
7809
|
+
}
|
|
7810
|
+
async function checkOsv(files, projectDir, fetchImpl = globalThis.fetch) {
|
|
7811
|
+
const warnings = [];
|
|
7812
|
+
const deps = (await findAddedDependencies(files, projectDir)).slice(
|
|
7813
|
+
0,
|
|
7814
|
+
MAX_QUERIES
|
|
7815
|
+
);
|
|
7816
|
+
if (deps.length === 0) return { findings: [], warnings };
|
|
7817
|
+
const signal = AbortSignal.timeout(TIMEOUT_MS);
|
|
7818
|
+
try {
|
|
7819
|
+
const res = await fetchImpl(OSV_BATCH_URL, {
|
|
7820
|
+
method: "POST",
|
|
7821
|
+
headers: { "content-type": "application/json" },
|
|
7822
|
+
body: JSON.stringify({
|
|
7823
|
+
queries: deps.map((d) => ({
|
|
7824
|
+
package: { name: d.name, ecosystem: "npm" },
|
|
7825
|
+
version: d.version
|
|
7826
|
+
}))
|
|
7827
|
+
}),
|
|
7828
|
+
signal
|
|
7829
|
+
});
|
|
7830
|
+
if (!res.ok) {
|
|
7831
|
+
warnings.push(`osv: querybatch returned ${res.status}; skipped`);
|
|
7832
|
+
return { findings: [], warnings };
|
|
7833
|
+
}
|
|
7834
|
+
const body = await res.json();
|
|
7835
|
+
const hits = [];
|
|
7836
|
+
(body?.results ?? []).forEach((r, i) => {
|
|
7837
|
+
for (const v of r?.vulns ?? []) {
|
|
7838
|
+
if (deps[i] && v?.id) hits.push({ dep: deps[i], id: v.id });
|
|
7839
|
+
}
|
|
7840
|
+
});
|
|
7841
|
+
if (hits.length === 0) return { findings: [], warnings };
|
|
7842
|
+
const ids = [...new Set(hits.map((h) => h.id))].slice(0, MAX_DETAILS);
|
|
7843
|
+
const details2 = /* @__PURE__ */ new Map();
|
|
7844
|
+
await Promise.all(
|
|
7845
|
+
ids.map(async (id) => {
|
|
7846
|
+
try {
|
|
7847
|
+
const r = await fetchImpl(
|
|
7848
|
+
`${OSV_VULN_URL}${encodeURIComponent(id)}`,
|
|
7849
|
+
{
|
|
7850
|
+
signal
|
|
7851
|
+
}
|
|
7852
|
+
);
|
|
7853
|
+
if (r.ok) details2.set(id, await r.json());
|
|
7854
|
+
} catch {
|
|
7855
|
+
}
|
|
7856
|
+
})
|
|
7857
|
+
);
|
|
7858
|
+
const findings = [];
|
|
7859
|
+
for (const { dep, id } of hits) {
|
|
7860
|
+
const v = details2.get(id);
|
|
7861
|
+
const aliases = (v?.aliases ?? []).filter(
|
|
7862
|
+
(a) => a.startsWith("CVE-")
|
|
7863
|
+
);
|
|
7864
|
+
const fixed = v ? fixedVersion(v, dep.name) : null;
|
|
7865
|
+
const summary = v?.summary ? `: ${v.summary}` : "";
|
|
7866
|
+
findings.push({
|
|
7867
|
+
tool: "osv",
|
|
7868
|
+
ruleId: id,
|
|
7869
|
+
file: dep.file,
|
|
7870
|
+
line: dep.line,
|
|
7871
|
+
severity: v ? mapSeverity(v) : "medium",
|
|
7872
|
+
category: "security",
|
|
7873
|
+
message: `${dep.name}@${dep.version} (from "${dep.range}") has a known vulnerability ${id}${aliases.length ? ` (${aliases.join(", ")})` : ""}${summary}.${fixed ? ` Fixed in ${fixed}.` : ""}`
|
|
7874
|
+
});
|
|
7875
|
+
}
|
|
7876
|
+
return { findings, warnings };
|
|
7877
|
+
} catch (err) {
|
|
7878
|
+
warnings.push(
|
|
7879
|
+
`osv: ${err?.name === "TimeoutError" || err?.name === "AbortError" ? "timed out" : err?.message ?? "network error"}; skipped`
|
|
7880
|
+
);
|
|
7881
|
+
return { findings: [], warnings };
|
|
7882
|
+
}
|
|
7883
|
+
}
|
|
7884
|
+
|
|
7885
|
+
// src/review/tools/secrets.ts
|
|
7886
|
+
function shannonEntropy(s) {
|
|
7887
|
+
if (!s) return 0;
|
|
7888
|
+
const freq = /* @__PURE__ */ new Map();
|
|
7889
|
+
for (const c of s) freq.set(c, (freq.get(c) ?? 0) + 1);
|
|
7890
|
+
let h = 0;
|
|
7891
|
+
for (const n of freq.values()) {
|
|
7892
|
+
const p = n / s.length;
|
|
7893
|
+
h -= p * Math.log2(p);
|
|
7894
|
+
}
|
|
7895
|
+
return h;
|
|
7896
|
+
}
|
|
7897
|
+
var PLACEHOLDER_RE = /example|sample|dummy|placeholder|changeme|change_me|your[_-]|xxxx|\*\*\*\*|<[^>]*>|\$\{|\{\{|process\.env|os\.environ|getenv|redacted|test(ing)?[_-]?(key|token|secret|password)|^(password|secret|token)$/i;
|
|
7898
|
+
function looksReal(value) {
|
|
7899
|
+
if (PLACEHOLDER_RE.test(value)) return false;
|
|
7900
|
+
if (/^(.)\1+$/.test(value)) return false;
|
|
7901
|
+
return shannonEntropy(value) >= 3;
|
|
7902
|
+
}
|
|
7903
|
+
var SECRET_RULES = [
|
|
7904
|
+
{
|
|
7905
|
+
id: "private-key",
|
|
7906
|
+
label: "private key",
|
|
7907
|
+
re: /-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----/,
|
|
7908
|
+
severity: "critical"
|
|
7909
|
+
},
|
|
7910
|
+
{
|
|
7911
|
+
id: "aws-access-token",
|
|
7912
|
+
label: "AWS access key id",
|
|
7913
|
+
re: /\b((?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z2-7]{16})\b/,
|
|
7914
|
+
severity: "critical",
|
|
7915
|
+
group: 1
|
|
7916
|
+
},
|
|
7917
|
+
{
|
|
7918
|
+
id: "github-pat",
|
|
7919
|
+
label: "GitHub token",
|
|
7920
|
+
re: /\b(gh[pousr]_[0-9a-zA-Z]{36})\b/,
|
|
7921
|
+
severity: "critical",
|
|
7922
|
+
group: 1
|
|
7923
|
+
},
|
|
7924
|
+
{
|
|
7925
|
+
id: "github-fine-grained-pat",
|
|
7926
|
+
label: "GitHub fine-grained token",
|
|
7927
|
+
re: /\b(github_pat_\w{82})\b/,
|
|
7928
|
+
severity: "critical",
|
|
7929
|
+
group: 1
|
|
7930
|
+
},
|
|
7931
|
+
{
|
|
7932
|
+
id: "gitlab-pat",
|
|
7933
|
+
label: "GitLab token",
|
|
7934
|
+
re: /\b(gl(?:pat|ptt|rt|dt|cbt|oas|imt|ft|soat|agent)-[0-9a-zA-Z_-]{20,})/,
|
|
7935
|
+
severity: "critical",
|
|
7936
|
+
group: 1
|
|
7937
|
+
},
|
|
7938
|
+
{
|
|
7939
|
+
id: "slack-token",
|
|
7940
|
+
label: "Slack token",
|
|
7941
|
+
re: /\b(xox[baprs]-[0-9a-zA-Z-]{10,250})/,
|
|
7942
|
+
severity: "high",
|
|
7943
|
+
group: 1
|
|
7944
|
+
},
|
|
7945
|
+
{
|
|
7946
|
+
id: "slack-webhook-url",
|
|
7947
|
+
label: "Slack webhook URL",
|
|
7948
|
+
re: /(hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9+/]{43,56})/,
|
|
7949
|
+
severity: "high",
|
|
7950
|
+
group: 1
|
|
7951
|
+
},
|
|
7952
|
+
{
|
|
7953
|
+
id: "stripe-access-token",
|
|
7954
|
+
label: "Stripe live key",
|
|
7955
|
+
re: /\b((?:sk|rk)_live_[0-9a-zA-Z]{10,99})\b/,
|
|
7956
|
+
severity: "critical",
|
|
7957
|
+
group: 1
|
|
7958
|
+
},
|
|
7959
|
+
{
|
|
7960
|
+
id: "anthropic-api-key",
|
|
7961
|
+
label: "Anthropic API key",
|
|
7962
|
+
re: /\b(sk-ant-(?:api03|admin01)-[\w-]{80,})/,
|
|
7963
|
+
severity: "critical",
|
|
7964
|
+
group: 1
|
|
7965
|
+
},
|
|
7966
|
+
{
|
|
7967
|
+
id: "openai-api-key",
|
|
7968
|
+
label: "OpenAI API key",
|
|
7969
|
+
re: /\b(sk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}T3BlbkFJ[A-Za-z0-9_-]{20,})/,
|
|
7970
|
+
severity: "critical",
|
|
7971
|
+
group: 1
|
|
7972
|
+
},
|
|
7973
|
+
{
|
|
7974
|
+
id: "gcp-api-key",
|
|
7975
|
+
label: "Google API key",
|
|
7976
|
+
re: /\b(AIza[\w-]{35})\b/,
|
|
7977
|
+
severity: "high",
|
|
7978
|
+
group: 1
|
|
7979
|
+
},
|
|
7980
|
+
{
|
|
7981
|
+
id: "auracheck-ci-token",
|
|
7982
|
+
label: "AuraCheck CI token",
|
|
7983
|
+
re: /\b(67ci_[A-Za-z0-9_-]{16,})/,
|
|
7984
|
+
severity: "critical",
|
|
7985
|
+
group: 1
|
|
7986
|
+
},
|
|
7987
|
+
{
|
|
7988
|
+
id: "jwt",
|
|
7989
|
+
label: "JSON Web Token",
|
|
7990
|
+
re: /\b(ey[A-Za-z0-9]{17,}\.ey[A-Za-z0-9/_-]{17,}\.[A-Za-z0-9/_-]{10,}={0,2})/,
|
|
7991
|
+
severity: "high",
|
|
7992
|
+
group: 1
|
|
7993
|
+
},
|
|
7994
|
+
{
|
|
7995
|
+
id: "generic-api-key",
|
|
7996
|
+
label: "hardcoded credential",
|
|
7997
|
+
// key name containing a credential word, `=`/`:`/`:=`/`=>`, then a QUOTED
|
|
7998
|
+
// literal: `password = process.env.X` has no quotes, so it never matches.
|
|
7999
|
+
re: /([A-Za-z0-9_.-]*(?:password|passwd|pwd|secret|api[_-]?key|apikey|access[_-]?key|access[_-]?token|auth[_-]?token|private[_-]?key|client[_-]?secret|token)[A-Za-z0-9_.-]*)["']?\s*(?::=|=>|[:=])\s*["'`]([^"'`\s]{8,200})["'`]/i,
|
|
8000
|
+
severity: "high",
|
|
8001
|
+
group: 2,
|
|
8002
|
+
check: looksReal
|
|
8003
|
+
}
|
|
8004
|
+
];
|
|
8005
|
+
function redact(value) {
|
|
8006
|
+
return `${value.slice(0, 4)}\u2026`;
|
|
8007
|
+
}
|
|
8008
|
+
var ALLOW_COMMENT_RE = /gitleaks:allow|auracheck:allow/;
|
|
8009
|
+
function scanSecrets(files) {
|
|
8010
|
+
const out = [];
|
|
8011
|
+
for (const f of files) {
|
|
8012
|
+
if (f.deletedFile) continue;
|
|
8013
|
+
for (const [line, text] of addedLines(f.diff)) {
|
|
8014
|
+
if (ALLOW_COMMENT_RE.test(text)) continue;
|
|
8015
|
+
for (const rule of SECRET_RULES) {
|
|
8016
|
+
const m = rule.re.exec(text);
|
|
8017
|
+
if (!m) continue;
|
|
8018
|
+
const value = m[rule.group ?? 0] ?? m[0];
|
|
8019
|
+
if (rule.check && !rule.check(value)) continue;
|
|
8020
|
+
out.push({
|
|
8021
|
+
tool: "secrets",
|
|
8022
|
+
ruleId: rule.id,
|
|
8023
|
+
file: f.newPath,
|
|
8024
|
+
line,
|
|
8025
|
+
severity: rule.severity,
|
|
8026
|
+
category: "security",
|
|
8027
|
+
message: `Possible ${rule.label} committed (${redact(value)}). Move it to a CI/CD variable or secret manager and rotate it: it is in the git history now.`
|
|
8028
|
+
});
|
|
8029
|
+
break;
|
|
8030
|
+
}
|
|
8031
|
+
}
|
|
8032
|
+
}
|
|
8033
|
+
return out;
|
|
8034
|
+
}
|
|
8035
|
+
|
|
8036
|
+
// src/review/tools/index.ts
|
|
8037
|
+
async function runTools(input) {
|
|
8038
|
+
const t = input.config.reviews.tools;
|
|
8039
|
+
const findings = [];
|
|
8040
|
+
const warnings = [];
|
|
8041
|
+
const ran = [];
|
|
8042
|
+
if (t.gitleaks.enabled) {
|
|
8043
|
+
try {
|
|
8044
|
+
findings.push(...scanSecrets(input.files));
|
|
8045
|
+
ran.push("secrets");
|
|
8046
|
+
} catch (err) {
|
|
8047
|
+
warnings.push(`secrets: ${err?.message ?? err}; skipped`);
|
|
8048
|
+
}
|
|
8049
|
+
}
|
|
8050
|
+
const atHead = input.checkoutAtHead !== false && !!input.projectDir;
|
|
8051
|
+
if (t.osv.enabled) {
|
|
8052
|
+
const res = await checkOsv(
|
|
8053
|
+
input.files,
|
|
8054
|
+
atHead ? input.projectDir : null,
|
|
8055
|
+
input.fetch
|
|
8056
|
+
);
|
|
8057
|
+
findings.push(...res.findings);
|
|
8058
|
+
warnings.push(...res.warnings);
|
|
8059
|
+
ran.push("osv");
|
|
8060
|
+
}
|
|
8061
|
+
const wantLint = t.biome.enabled || t.eslint.enabled;
|
|
8062
|
+
if (wantLint && input.projectDir && !atHead) {
|
|
8063
|
+
warnings.push("lint: the checkout is not the MR head; linters skipped");
|
|
8064
|
+
} else if (wantLint && input.projectDir) {
|
|
8065
|
+
try {
|
|
8066
|
+
const res = await runLinters({
|
|
8067
|
+
projectDir: input.projectDir,
|
|
8068
|
+
files: input.files,
|
|
8069
|
+
biome: t.biome.enabled,
|
|
8070
|
+
eslint: t.eslint.enabled,
|
|
8071
|
+
exec: input.exec
|
|
8072
|
+
});
|
|
8073
|
+
findings.push(...res.findings);
|
|
8074
|
+
warnings.push(...res.warnings);
|
|
8075
|
+
ran.push("lint");
|
|
8076
|
+
} catch (err) {
|
|
8077
|
+
warnings.push(`lint: ${err?.message ?? err}; skipped`);
|
|
8078
|
+
}
|
|
8079
|
+
}
|
|
8080
|
+
return { findings, warnings, ran };
|
|
8081
|
+
}
|
|
8082
|
+
|
|
8083
|
+
// src/review/run.ts
|
|
8084
|
+
var COMMIT_STATUS_NAME = "AuraCheck review";
|
|
8085
|
+
var MAX_COMMIT_MESSAGES = 50;
|
|
8086
|
+
var CONTEXT_MAX_FILES = 15;
|
|
8087
|
+
var CONTEXT_MAX_FILE_CHARS = 4e4;
|
|
8088
|
+
var CONTEXT_MAX_FILE_LINES = 400;
|
|
8089
|
+
var CONTEXT_MAX_TOTAL_CHARS = 15e4;
|
|
8090
|
+
async function readHeadContents(files, projectDir, read) {
|
|
8091
|
+
const out = /* @__PURE__ */ new Map();
|
|
8092
|
+
let total = 0;
|
|
8093
|
+
for (const f of files) {
|
|
8094
|
+
if (out.size >= CONTEXT_MAX_FILES) break;
|
|
8095
|
+
if (f.deletedFile || f.newPath.includes("..")) continue;
|
|
8096
|
+
const text = await read(`${projectDir}/${f.newPath}`).catch(() => null);
|
|
8097
|
+
if (text === null || text.includes("\0")) continue;
|
|
8098
|
+
if (text.length > CONTEXT_MAX_FILE_CHARS) continue;
|
|
8099
|
+
if (text.split("\n").length > CONTEXT_MAX_FILE_LINES) continue;
|
|
8100
|
+
if (total + text.length > CONTEXT_MAX_TOTAL_CHARS) break;
|
|
8101
|
+
total += text.length;
|
|
8102
|
+
out.set(f.newPath, text);
|
|
8103
|
+
}
|
|
8104
|
+
return out;
|
|
8105
|
+
}
|
|
8106
|
+
function int(v) {
|
|
8107
|
+
const n = Number(v);
|
|
8108
|
+
return v && Number.isInteger(n) && n > 0 ? n : null;
|
|
8109
|
+
}
|
|
8110
|
+
function resolveReviewEnv(env, opts = {}) {
|
|
8111
|
+
const rawBase = normalizeBaseUrl2(
|
|
8112
|
+
opts.baseUrl || env.AURACHECK_BASE_URL || env.SIXSEVEN_BASE_URL || DEFAULT_BASE_URL
|
|
8113
|
+
);
|
|
8114
|
+
const apiUrl = env.CI_API_V4_URL ? env.CI_API_V4_URL.replace(/\/+$/, "") : env.CI_SERVER_URL ? `${env.CI_SERVER_URL.replace(/\/+$/, "")}/api/v4` : null;
|
|
8115
|
+
return {
|
|
8116
|
+
baseUrl: migrateLegacyBaseUrl(rawBase),
|
|
8117
|
+
token: env.AURACHECK_TOKEN?.trim() || env.SIXSEVEN_TOKEN?.trim() || null,
|
|
8118
|
+
gitlabToken: env.AURACHECK_GITLAB_TOKEN?.trim() || null,
|
|
8119
|
+
apiUrl,
|
|
8120
|
+
projectId: env.CI_PROJECT_ID || env.CI_PROJECT_PATH || null,
|
|
8121
|
+
projectPath: env.CI_PROJECT_PATH || null,
|
|
8122
|
+
projectUrl: env.CI_PROJECT_URL || null,
|
|
8123
|
+
projectDir: env.CI_PROJECT_DIR || null,
|
|
8124
|
+
mrIid: opts.mrIid ?? int(env.AURACHECK_MR_IID) ?? int(env.CI_MERGE_REQUEST_IID),
|
|
8125
|
+
jobUrl: env.CI_JOB_URL || null,
|
|
8126
|
+
commitSha: env.CI_COMMIT_SHA || null,
|
|
8127
|
+
sourceBranchSha: env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA || null,
|
|
8128
|
+
pipelineId: int(env.CI_PIPELINE_ID),
|
|
8129
|
+
defaultBranch: env.CI_DEFAULT_BRANCH || null,
|
|
8130
|
+
command: commandFromEnv(env.AURACHECK_COMMAND),
|
|
8131
|
+
commandNoteId: int(env.AURACHECK_COMMAND_NOTE_ID)
|
|
8132
|
+
};
|
|
8133
|
+
}
|
|
8134
|
+
function autoReviewSkip(mr, config, defaultBranch) {
|
|
8135
|
+
const ar = config.reviews.auto_review;
|
|
8136
|
+
if (!ar.enabled) {
|
|
8137
|
+
return {
|
|
8138
|
+
reason: "automatic review is off (`reviews.auto_review.enabled: false`); comment `@auracheck review`",
|
|
8139
|
+
announce: false
|
|
8140
|
+
};
|
|
8141
|
+
}
|
|
8142
|
+
if (mr.state !== "opened") {
|
|
8143
|
+
return { reason: `the MR is ${mr.state}`, announce: false };
|
|
8144
|
+
}
|
|
8145
|
+
if (ar.ignore_usernames.some((u) => u.toLowerCase() === mr.author.toLowerCase())) {
|
|
8146
|
+
return {
|
|
8147
|
+
reason: `author ${mr.author} is in \`reviews.auto_review.ignore_usernames\``,
|
|
8148
|
+
announce: false
|
|
8149
|
+
};
|
|
8150
|
+
}
|
|
8151
|
+
if (mr.draft && !ar.drafts) {
|
|
8152
|
+
return {
|
|
8153
|
+
reason: "draft MR; mark it ready or comment `@auracheck review`",
|
|
8154
|
+
announce: true
|
|
8155
|
+
};
|
|
8156
|
+
}
|
|
8157
|
+
const title = mr.title.toLowerCase();
|
|
8158
|
+
const kw = ar.ignore_title_keywords.find(
|
|
8159
|
+
(k) => k.trim() && title.includes(k.trim().toLowerCase())
|
|
8160
|
+
);
|
|
8161
|
+
if (kw) {
|
|
8162
|
+
return { reason: `the title contains "${kw}"`, announce: true };
|
|
8163
|
+
}
|
|
8164
|
+
const labels = mr.labels.map((l) => l.toLowerCase());
|
|
8165
|
+
const excluded = ar.labels.filter((l) => l.startsWith("!")).map((l) => l.slice(1).trim().toLowerCase());
|
|
8166
|
+
const hit = excluded.find((l) => labels.includes(l));
|
|
8167
|
+
if (hit) return { reason: `the MR has the label "${hit}"`, announce: true };
|
|
8168
|
+
const required = ar.labels.filter((l) => !l.startsWith("!") && l.trim()).map((l) => l.trim().toLowerCase());
|
|
8169
|
+
if (required.length && !required.some((l) => labels.includes(l))) {
|
|
8170
|
+
return {
|
|
8171
|
+
reason: `the MR has none of the labels ${required.map((l) => `"${l}"`).join(", ")}`,
|
|
8172
|
+
announce: true
|
|
8173
|
+
};
|
|
8174
|
+
}
|
|
8175
|
+
if (defaultBranch && mr.targetBranch !== defaultBranch) {
|
|
8176
|
+
const allowed = ar.base_branches.some((re) => {
|
|
8177
|
+
try {
|
|
8178
|
+
return new RegExp(`^(?:${re})$`).test(mr.targetBranch);
|
|
8179
|
+
} catch {
|
|
8180
|
+
return re === mr.targetBranch;
|
|
8181
|
+
}
|
|
8182
|
+
});
|
|
8183
|
+
if (!allowed) {
|
|
8184
|
+
return {
|
|
8185
|
+
reason: `target branch \`${mr.targetBranch}\` is not the default branch; add it to \`reviews.auto_review.base_branches\``,
|
|
8186
|
+
announce: true
|
|
8187
|
+
};
|
|
8188
|
+
}
|
|
8189
|
+
}
|
|
8190
|
+
return null;
|
|
8191
|
+
}
|
|
8192
|
+
function projectWebUrl(env, mr) {
|
|
8193
|
+
if (env.projectUrl) return env.projectUrl.replace(/\/+$/, "");
|
|
8194
|
+
const m = /^(.*)\/-\/merge_requests\/\d+/.exec(mr.webUrl);
|
|
8195
|
+
return m ? m[1] : null;
|
|
8196
|
+
}
|
|
8197
|
+
async function loadConfigDefault(dir) {
|
|
8198
|
+
if (!dir) {
|
|
8199
|
+
const { defaultConfig: defaultConfig2 } = await Promise.resolve().then(() => (init_config(), config_exports));
|
|
8200
|
+
return { config: defaultConfig2(), warnings: [], source: "defaults" };
|
|
8201
|
+
}
|
|
8202
|
+
return loadReviewConfig(dir);
|
|
8203
|
+
}
|
|
8204
|
+
async function runReview(deps, opts = {}) {
|
|
8205
|
+
const log = deps.log ?? ((m) => process.stdout.write(`${m}
|
|
8206
|
+
`));
|
|
8207
|
+
const warn2 = deps.warn ?? ((m) => process.stderr.write(`warning: ${m}
|
|
8208
|
+
`));
|
|
8209
|
+
const print = deps.print ?? ((t2) => process.stdout.write(`${t2}
|
|
8210
|
+
`));
|
|
8211
|
+
const now = deps.now ?? (() => /* @__PURE__ */ new Date());
|
|
8212
|
+
const env = resolveReviewEnv(deps.env, opts);
|
|
8213
|
+
const p = deps.provider;
|
|
8214
|
+
const dryRun = !!opts.dryRun;
|
|
8215
|
+
const result = {
|
|
8216
|
+
exitCode: 0,
|
|
8217
|
+
outcome: "reviewed",
|
|
8218
|
+
noteId: null,
|
|
8219
|
+
posted: []
|
|
8220
|
+
};
|
|
8221
|
+
const done = (outcome, exitCode = 0) => {
|
|
8222
|
+
result.outcome = outcome;
|
|
8223
|
+
result.exitCode = exitCode;
|
|
8224
|
+
return result;
|
|
8225
|
+
};
|
|
8226
|
+
let iid = env.mrIid;
|
|
8227
|
+
let command = null;
|
|
8228
|
+
const trigger = await readTriggerPayload(deps.env, deps.readFile);
|
|
8229
|
+
let triggerAuthor = null;
|
|
8230
|
+
if (trigger) {
|
|
8231
|
+
if (trigger.kind === "ignore") {
|
|
8232
|
+
log(`AuraCheck review: ${trigger.reason}; nothing to do.`);
|
|
8233
|
+
return done("ignored");
|
|
8234
|
+
}
|
|
8235
|
+
iid = trigger.iid;
|
|
8236
|
+
triggerAuthor = trigger.author;
|
|
8237
|
+
command = {
|
|
8238
|
+
kind: trigger.command,
|
|
8239
|
+
noteId: trigger.noteId,
|
|
8240
|
+
source: "trigger"
|
|
8241
|
+
};
|
|
8242
|
+
} else if (env.command) {
|
|
8243
|
+
command = {
|
|
8244
|
+
kind: env.command,
|
|
8245
|
+
noteId: env.commandNoteId,
|
|
8246
|
+
source: "webhook"
|
|
8247
|
+
};
|
|
8248
|
+
}
|
|
8249
|
+
if (!command && opts.full) {
|
|
8250
|
+
command = { kind: "full_review", noteId: null, source: "cli" };
|
|
8251
|
+
}
|
|
8252
|
+
if (!iid) {
|
|
8253
|
+
log(
|
|
8254
|
+
"AuraCheck review: not a merge request pipeline (no CI_MERGE_REQUEST_IID or AURACHECK_MR_IID); nothing to do."
|
|
8255
|
+
);
|
|
8256
|
+
return done("not-mr");
|
|
8257
|
+
}
|
|
8258
|
+
let bot = null;
|
|
8259
|
+
try {
|
|
8260
|
+
bot = await p.getCurrentUser();
|
|
8261
|
+
} catch (err) {
|
|
8262
|
+
warn2(
|
|
8263
|
+
`cannot read the bot user (${err.message}); matching the summary note by marker only`
|
|
8264
|
+
);
|
|
8265
|
+
}
|
|
8266
|
+
if (trigger && bot && triggerAuthor === bot.username) {
|
|
8267
|
+
log("AuraCheck review: the comment is from the bot itself; nothing to do.");
|
|
8268
|
+
return done("ignored");
|
|
8269
|
+
}
|
|
8270
|
+
const mr = await p.getMergeRequest(iid);
|
|
8271
|
+
if (trigger && mr.state !== "opened") {
|
|
8272
|
+
log(`AuraCheck review: MR !${iid} is ${mr.state}; nothing to do.`);
|
|
8273
|
+
return done("ignored");
|
|
8274
|
+
}
|
|
8275
|
+
log(`AuraCheck review: MR !${mr.iid} ${mr.webUrl}`);
|
|
8276
|
+
const loaded = await (deps.loadConfig ?? loadConfigDefault)(env.projectDir);
|
|
8277
|
+
for (const w of loaded.warnings) warn2(w);
|
|
8278
|
+
const config = loaded.config;
|
|
8279
|
+
const t = strings(config.language);
|
|
8280
|
+
const headSha = mr.diffRefs?.headSha ?? mr.sha;
|
|
8281
|
+
const webBase = projectWebUrl(env, mr);
|
|
8282
|
+
const ctx = {
|
|
8283
|
+
language: config.language,
|
|
8284
|
+
headSha,
|
|
8285
|
+
commitUrl: (sha) => webBase ? `${webBase}/-/commit/${sha}` : null,
|
|
8286
|
+
mode: "full",
|
|
8287
|
+
sinceSha: null
|
|
8288
|
+
};
|
|
8289
|
+
let discussions = [];
|
|
8290
|
+
try {
|
|
8291
|
+
discussions = await p.listDiscussions(iid);
|
|
8292
|
+
} catch (err) {
|
|
8293
|
+
warn2(
|
|
8294
|
+
`cannot list discussions (${err.message}); dedup relies on the note state only`
|
|
8295
|
+
);
|
|
8296
|
+
}
|
|
8297
|
+
if (!command && !trigger) {
|
|
8298
|
+
command = await findUnacknowledgedCommand(p, iid, discussions, bot);
|
|
8299
|
+
if (command)
|
|
8300
|
+
log(
|
|
8301
|
+
`AuraCheck review: handling the "${command.kind}" comment (note ${command.noteId}).`
|
|
8302
|
+
);
|
|
8303
|
+
}
|
|
8304
|
+
const sticky = await StickyNote.load(p, iid, bot?.id ?? null, warn2, !dryRun);
|
|
8305
|
+
result.noteId = sticky.id;
|
|
8306
|
+
let state = parseState(sticky.body);
|
|
8307
|
+
const noteUrl = () => sticky.id != null ? `${mr.webUrl}#note_${sticky.id}` : "";
|
|
8308
|
+
const writeStatus = async (status, next) => {
|
|
8309
|
+
if (dryRun) {
|
|
8310
|
+
print(renderStatus(ctx, status));
|
|
8311
|
+
return;
|
|
8312
|
+
}
|
|
8313
|
+
let body;
|
|
8314
|
+
if (sticky.body?.includes(STATUS_START)) {
|
|
8315
|
+
body = replaceStateMarker(
|
|
8316
|
+
replaceStatusBlock(sticky.body, renderStatus(ctx, status)),
|
|
8317
|
+
next
|
|
8318
|
+
);
|
|
8319
|
+
} else {
|
|
8320
|
+
body = renderNote(baseNoteInput(status, next));
|
|
8321
|
+
}
|
|
8322
|
+
result.noteId = await sticky.save(body);
|
|
8323
|
+
log(`AuraCheck review: summary note ${noteUrl()}`);
|
|
8324
|
+
};
|
|
8325
|
+
const baseNoteInput = (status, next) => ({
|
|
8326
|
+
...ctx,
|
|
8327
|
+
config,
|
|
8328
|
+
configSource: loaded.source,
|
|
8329
|
+
status,
|
|
8330
|
+
response: null,
|
|
8331
|
+
postedInline: 0,
|
|
8332
|
+
notInline: [],
|
|
8333
|
+
skippedDuplicates: 0,
|
|
8334
|
+
skippedFiles: [],
|
|
8335
|
+
preMerge: [],
|
|
8336
|
+
reviewedCommits: 0,
|
|
8337
|
+
toolWarnings: [],
|
|
8338
|
+
state: next
|
|
8339
|
+
});
|
|
8340
|
+
if (command?.kind === "help") {
|
|
8341
|
+
if (dryRun) {
|
|
8342
|
+
print(t.helpReply);
|
|
8343
|
+
return done("help");
|
|
8344
|
+
}
|
|
8345
|
+
await acknowledge(p, iid, command, ACK_START, warn2);
|
|
8346
|
+
if (command.noteId) await p.replyToNote(iid, command.noteId, t.helpReply);
|
|
8347
|
+
else await p.createNote(iid, t.helpReply);
|
|
8348
|
+
await acknowledge(p, iid, command, ACK_DONE, warn2);
|
|
8349
|
+
log("AuraCheck review: answered @auracheck help.");
|
|
8350
|
+
return done("help");
|
|
8351
|
+
}
|
|
8352
|
+
if (!command) {
|
|
8353
|
+
const skip = autoReviewSkip(mr, config, env.defaultBranch);
|
|
8354
|
+
if (skip) {
|
|
8355
|
+
log(`AuraCheck review: skipped, ${skip.reason}.`);
|
|
8356
|
+
if (sticky.id != null || skip.announce) {
|
|
8357
|
+
await writeStatus({ kind: "skipped", reason: skip.reason }, state);
|
|
8358
|
+
}
|
|
8359
|
+
return done("skipped");
|
|
8360
|
+
}
|
|
8361
|
+
if (state.lastReviewedSha === headSha) {
|
|
8362
|
+
log(
|
|
8363
|
+
`AuraCheck review: ${shortSha(headSha)} was already reviewed; nothing to do.`
|
|
8364
|
+
);
|
|
8365
|
+
return done("no-changes");
|
|
8366
|
+
}
|
|
8367
|
+
}
|
|
8368
|
+
const statusOn = config.reviews.commit_status && !dryRun;
|
|
8369
|
+
let statusState = "success";
|
|
8370
|
+
let statusDescription = "Review done";
|
|
8371
|
+
const setStatus = async (state2, description) => {
|
|
8372
|
+
if (!statusOn || !headSha) return;
|
|
8373
|
+
try {
|
|
8374
|
+
await p.setCommitStatus(headSha, {
|
|
8375
|
+
state: state2,
|
|
8376
|
+
name: COMMIT_STATUS_NAME,
|
|
8377
|
+
description,
|
|
8378
|
+
targetUrl: env.jobUrl ?? void 0,
|
|
8379
|
+
pipelineId: env.pipelineId && env.commitSha === headSha ? env.pipelineId : void 0
|
|
8380
|
+
});
|
|
8381
|
+
} catch (err) {
|
|
8382
|
+
warn2(`commit status "${state2}" not set: ${err.message}`);
|
|
8383
|
+
}
|
|
8384
|
+
};
|
|
8385
|
+
if (!dryRun) await acknowledge(p, iid, command, ACK_START, warn2);
|
|
8386
|
+
await setStatus("running", "AuraCheck is reviewing this commit");
|
|
8387
|
+
let reviewErrored = false;
|
|
8388
|
+
try {
|
|
8389
|
+
return await reviewFlow();
|
|
8390
|
+
} catch (err) {
|
|
8391
|
+
reviewErrored = true;
|
|
8392
|
+
const reason = String(err?.message ?? err).slice(0, 300);
|
|
8393
|
+
warn2(`review failed: ${reason}`);
|
|
8394
|
+
statusDescription = "Review failed; see the job log";
|
|
8395
|
+
try {
|
|
8396
|
+
await writeStatus(
|
|
8397
|
+
{ kind: "failed", reason },
|
|
8398
|
+
recordAttempt(state, {
|
|
8399
|
+
sha: headSha,
|
|
8400
|
+
at: now().toISOString(),
|
|
8401
|
+
mode: ctx.mode,
|
|
8402
|
+
status: "failed"
|
|
8403
|
+
})
|
|
8404
|
+
);
|
|
8405
|
+
} catch (e) {
|
|
8406
|
+
warn2(`could not write the failure into the summary note: ${e.message}`);
|
|
8407
|
+
}
|
|
8408
|
+
return done("failed", 1);
|
|
8409
|
+
} finally {
|
|
8410
|
+
if (reviewErrored && config.reviews.fail_commit_status)
|
|
8411
|
+
statusState = "failed";
|
|
8412
|
+
await setStatus(statusState, statusDescription);
|
|
8413
|
+
if (!dryRun && !reviewErrored)
|
|
8414
|
+
await acknowledge(p, iid, command, ACK_DONE, warn2);
|
|
8415
|
+
}
|
|
8416
|
+
async function reviewFlow() {
|
|
8417
|
+
const forceFull = command?.kind === "full_review";
|
|
8418
|
+
const allDiffs = await p.listMrDiffs(iid);
|
|
8419
|
+
let candidates = allDiffs;
|
|
8420
|
+
const last = state.lastReviewedSha;
|
|
8421
|
+
if (!forceFull && config.reviews.auto_review.auto_incremental_review && last && last !== headSha) {
|
|
8422
|
+
const changed = await p.compareCommits(last, headSha);
|
|
8423
|
+
if (changed) {
|
|
8424
|
+
const set = new Set(changed);
|
|
8425
|
+
candidates = allDiffs.filter(
|
|
8426
|
+
(f) => set.has(f.newPath) || set.has(f.oldPath)
|
|
8427
|
+
);
|
|
8428
|
+
ctx.mode = "incremental";
|
|
8429
|
+
ctx.sinceSha = last;
|
|
8430
|
+
} else {
|
|
8431
|
+
log(
|
|
8432
|
+
"AuraCheck review: cannot compare with the last reviewed commit (force-push?); reviewing the whole MR."
|
|
8433
|
+
);
|
|
8434
|
+
}
|
|
8435
|
+
}
|
|
8436
|
+
const { files, skippedFiles } = filterFiles(
|
|
8437
|
+
candidates,
|
|
8438
|
+
config.reviews.path_filters
|
|
8439
|
+
);
|
|
8440
|
+
const at = now().toISOString();
|
|
8441
|
+
if (files.length === 0) {
|
|
8442
|
+
if (ctx.mode === "incremental") {
|
|
8443
|
+
state = recordReviewed(state, {
|
|
8444
|
+
sha: headSha,
|
|
8445
|
+
at,
|
|
8446
|
+
mode: ctx.mode,
|
|
8447
|
+
status: "no-changes"
|
|
8448
|
+
});
|
|
8449
|
+
await writeStatus({ kind: "no-changes" }, state);
|
|
8450
|
+
log("AuraCheck review: no reviewable changes since the last review.");
|
|
8451
|
+
return done("no-changes");
|
|
8452
|
+
}
|
|
8453
|
+
const reason = allDiffs.length === 0 ? "the MR has no changes" : `no reviewable files (${skippedFiles.length} filtered out)`;
|
|
8454
|
+
state = recordReviewed(state, {
|
|
8455
|
+
sha: headSha,
|
|
8456
|
+
at,
|
|
8457
|
+
mode: ctx.mode,
|
|
8458
|
+
status: "skipped"
|
|
8459
|
+
});
|
|
8460
|
+
await writeStatus({ kind: "skipped", reason }, state);
|
|
8461
|
+
statusDescription = `Skipped: ${reason}`;
|
|
8462
|
+
return done("skipped");
|
|
8463
|
+
}
|
|
8464
|
+
const checkoutAtHead = !!env.projectDir && (!env.commitSha || env.commitSha === headSha || env.sourceBranchSha === headSha);
|
|
8465
|
+
const wantIssues = config.reviews.assess_linked_issues || config.reviews.pre_merge_checks.issue_assessment.mode !== "off";
|
|
8466
|
+
const [tools, guidelines, linkedIssues, commits] = await Promise.all([
|
|
8467
|
+
(deps.runTools ?? runTools)({
|
|
8468
|
+
files,
|
|
8469
|
+
projectDir: env.projectDir,
|
|
8470
|
+
checkoutAtHead,
|
|
8471
|
+
config
|
|
8472
|
+
}).catch(
|
|
8473
|
+
(err) => ({
|
|
8474
|
+
findings: [],
|
|
8475
|
+
warnings: [`tools: ${err.message}`],
|
|
8476
|
+
ran: []
|
|
8477
|
+
})
|
|
8478
|
+
),
|
|
8479
|
+
(deps.readGuidelines ?? readGuidelines)(env.projectDir, config).catch(
|
|
8480
|
+
() => []
|
|
8481
|
+
),
|
|
8482
|
+
wantIssues ? p.getLinkedIssues(iid, mr.description).catch((err) => {
|
|
8483
|
+
warn2(`linked issues: ${err.message}`);
|
|
8484
|
+
return [];
|
|
8485
|
+
}) : Promise.resolve([]),
|
|
8486
|
+
p.listCommits(iid).catch((err) => {
|
|
8487
|
+
warn2(`commits: ${err.message}`);
|
|
8488
|
+
return [];
|
|
8489
|
+
})
|
|
8490
|
+
]);
|
|
8491
|
+
for (const w of tools.warnings) warn2(w);
|
|
8492
|
+
const headContents = checkoutAtHead && env.projectDir ? await readHeadContents(
|
|
8493
|
+
files,
|
|
8494
|
+
env.projectDir,
|
|
8495
|
+
deps.readFile ?? ((path10) => readFileFs(path10, "utf8"))
|
|
8496
|
+
).catch(() => /* @__PURE__ */ new Map()) : /* @__PURE__ */ new Map();
|
|
8497
|
+
const preMerge = runPreMergeChecks({
|
|
8498
|
+
title: mr.title,
|
|
8499
|
+
description: mr.description,
|
|
8500
|
+
linkedIssueCount: linkedIssues.length,
|
|
8501
|
+
config
|
|
8502
|
+
});
|
|
8503
|
+
const inDiscussions = fingerprintsInDiscussions(discussions);
|
|
8504
|
+
const request = {
|
|
8505
|
+
contractVersion: REVIEW_CONTRACT_VERSION,
|
|
8506
|
+
provider: p.kind,
|
|
8507
|
+
repo: env.projectPath ?? env.projectId ?? "",
|
|
8508
|
+
mr: {
|
|
8509
|
+
iid: mr.iid,
|
|
8510
|
+
title: mr.title,
|
|
8511
|
+
description: mr.description,
|
|
8512
|
+
sourceBranch: mr.sourceBranch,
|
|
8513
|
+
targetBranch: mr.targetBranch,
|
|
8514
|
+
author: mr.author,
|
|
8515
|
+
labels: mr.labels,
|
|
8516
|
+
draft: mr.draft,
|
|
8517
|
+
webUrl: mr.webUrl
|
|
8518
|
+
},
|
|
8519
|
+
baseSha: mr.diffRefs?.baseSha ?? "",
|
|
8520
|
+
headSha,
|
|
8521
|
+
mode: ctx.mode,
|
|
8522
|
+
...ctx.mode === "incremental" && ctx.sinceSha ? { sinceSha: ctx.sinceSha } : {},
|
|
8523
|
+
files: files.map((f) => ({
|
|
8524
|
+
oldPath: f.oldPath,
|
|
8525
|
+
newPath: f.newPath,
|
|
8526
|
+
// A deleted file's removed lines cost tokens and can't get comments.
|
|
8527
|
+
diff: f.deletedFile ? "" : f.diff,
|
|
8528
|
+
newFile: f.newFile,
|
|
8529
|
+
deletedFile: f.deletedFile,
|
|
8530
|
+
renamedFile: f.renamedFile,
|
|
8531
|
+
...headContents.has(f.newPath) ? { headContent: headContents.get(f.newPath) } : {}
|
|
8532
|
+
})),
|
|
8533
|
+
skippedFiles,
|
|
8534
|
+
commitMessages: commits.slice(-MAX_COMMIT_MESSAGES).map((c) => c.message.slice(0, 500)),
|
|
8535
|
+
linkedIssues: config.reviews.assess_linked_issues ? linkedIssues : [],
|
|
8536
|
+
guidelines,
|
|
8537
|
+
toolFindings: tools.findings,
|
|
8538
|
+
knownFingerprints: knownFingerprints(state, inDiscussions),
|
|
8539
|
+
config: toServerConfig(config)
|
|
8540
|
+
};
|
|
8541
|
+
result.request = request;
|
|
8542
|
+
log(
|
|
8543
|
+
`AuraCheck review: ${ctx.mode} review of ${files.length} file(s) at ${shortSha(headSha)}${ctx.sinceSha ? ` since ${shortSha(ctx.sinceSha)}` : ""}; ${skippedFiles.length} skipped, ${tools.findings.length} tool finding(s), ${linkedIssues.length} linked issue(s).`
|
|
8544
|
+
);
|
|
8545
|
+
if (dryRun) {
|
|
8546
|
+
print(
|
|
8547
|
+
[
|
|
8548
|
+
"--- request summary ---",
|
|
8549
|
+
`endpoint: ${env.baseUrl}/api/code-review/review`,
|
|
8550
|
+
`mr: !${mr.iid} ${mr.title}`,
|
|
8551
|
+
`mode: ${ctx.mode}${ctx.sinceSha ? ` since ${shortSha(ctx.sinceSha)}` : ""}`,
|
|
8552
|
+
`files: ${files.map((f) => f.newPath).join(", ")}`,
|
|
8553
|
+
`skipped: ${skippedFiles.map((s) => `${s.path} (${s.reason})`).join(", ") || "-"}`,
|
|
8554
|
+
`tools: ${tools.findings.map((f) => `${f.tool}:${f.ruleId} ${f.file}:${f.line}`).join(", ") || "-"}`,
|
|
8555
|
+
`guidelines: ${guidelines.map((g) => g.path).join(", ") || "-"}`,
|
|
8556
|
+
`issues: ${linkedIssues.map((i) => i.ref).join(", ") || "-"}`,
|
|
8557
|
+
`known fps: ${request.knownFingerprints.length}`,
|
|
8558
|
+
`config: ${loaded.source} (profile ${config.reviews.profile}, language ${config.language})`
|
|
8559
|
+
].join("\n")
|
|
8560
|
+
);
|
|
8561
|
+
if (!deps.server) {
|
|
8562
|
+
print("(no AURACHECK_TOKEN: the server was not called)");
|
|
8563
|
+
return done("dry-run");
|
|
8564
|
+
}
|
|
8565
|
+
}
|
|
8566
|
+
if (!deps.server) {
|
|
8567
|
+
throw new Error(
|
|
8568
|
+
"AURACHECK_TOKEN is not set; add the AuraCheck project CI token as a masked CI/CD variable"
|
|
8569
|
+
);
|
|
8570
|
+
}
|
|
8571
|
+
const res = await deps.server(request);
|
|
8572
|
+
if (res.kind === "limit") {
|
|
8573
|
+
log(`AuraCheck review: ${res.error.message}`);
|
|
8574
|
+
statusDescription = "Review limit reached";
|
|
8575
|
+
await writeStatus(
|
|
8576
|
+
{ kind: "limit", limit: res.error },
|
|
8577
|
+
recordAttempt(state, {
|
|
8578
|
+
sha: headSha,
|
|
8579
|
+
at,
|
|
8580
|
+
mode: ctx.mode,
|
|
8581
|
+
status: "limit"
|
|
8582
|
+
})
|
|
8583
|
+
);
|
|
8584
|
+
return done("limit");
|
|
8585
|
+
}
|
|
8586
|
+
if (res.kind === "error") {
|
|
8587
|
+
throw new Error(res.message);
|
|
8588
|
+
}
|
|
8589
|
+
const response = res.response;
|
|
8590
|
+
const sel = selectInline(
|
|
8591
|
+
response.findings,
|
|
8592
|
+
state,
|
|
8593
|
+
inDiscussions,
|
|
8594
|
+
config.reviews.max_inline_comments
|
|
8595
|
+
);
|
|
8596
|
+
const notInline = [...sel.noteOnly];
|
|
8597
|
+
const posted = { ...state.posted };
|
|
8598
|
+
let postedInline = 0;
|
|
8599
|
+
for (const f of sel.toPost) {
|
|
8600
|
+
const file = files.find((x) => x.newPath === f.file) ?? allDiffs.find((x) => x.newPath === f.file);
|
|
8601
|
+
if (dryRun || !mr.diffRefs || !file || !f.anchor) {
|
|
8602
|
+
notInline.push(f);
|
|
8603
|
+
continue;
|
|
8604
|
+
}
|
|
8605
|
+
const created = await p.createDiscussion(
|
|
8606
|
+
iid,
|
|
8607
|
+
renderInlineBody(
|
|
8608
|
+
config.reviews.enable_prompt_for_ai_agents ? f : { ...f, aiAgentPrompt: void 0 },
|
|
8609
|
+
config.language
|
|
8610
|
+
),
|
|
8611
|
+
{
|
|
8612
|
+
baseSha: mr.diffRefs.baseSha,
|
|
8613
|
+
startSha: mr.diffRefs.startSha,
|
|
8614
|
+
headSha: mr.diffRefs.headSha,
|
|
8615
|
+
oldPath: file.oldPath,
|
|
8616
|
+
newPath: file.newPath,
|
|
8617
|
+
newLine: f.anchor.newLine,
|
|
8618
|
+
oldLine: f.anchor.oldLine
|
|
8619
|
+
}
|
|
8620
|
+
);
|
|
8621
|
+
if (!created) {
|
|
8622
|
+
notInline.push(f);
|
|
8623
|
+
continue;
|
|
8624
|
+
}
|
|
8625
|
+
postedInline++;
|
|
8626
|
+
const fp = sanitizeFingerprint(f.fingerprint);
|
|
8627
|
+
posted[fp] = {
|
|
8628
|
+
discussionId: created.id,
|
|
8629
|
+
file: f.file,
|
|
8630
|
+
line: f.anchor.newLine,
|
|
8631
|
+
title: f.title.slice(0, 120)
|
|
8632
|
+
};
|
|
8633
|
+
result.posted.push({
|
|
8634
|
+
fingerprint: fp,
|
|
8635
|
+
discussionId: created.id,
|
|
8636
|
+
level: created.level
|
|
8637
|
+
});
|
|
8638
|
+
log(
|
|
8639
|
+
`AuraCheck review: ${created.level === "line" ? "inline" : "file-level"} comment ${f.file}:${f.anchor.newLine} ${mr.webUrl}#note_${created.noteId}`
|
|
8640
|
+
);
|
|
8641
|
+
}
|
|
8642
|
+
state = recordReviewed(
|
|
8643
|
+
{
|
|
8644
|
+
...state,
|
|
8645
|
+
posted,
|
|
8646
|
+
suppressedTotal: state.suppressedTotal + (response.stats?.suppressed ?? 0)
|
|
8647
|
+
},
|
|
8648
|
+
{
|
|
8649
|
+
sha: headSha,
|
|
8650
|
+
at,
|
|
8651
|
+
mode: ctx.mode,
|
|
8652
|
+
status: "reviewed",
|
|
8653
|
+
findings: response.findings.length,
|
|
8654
|
+
inline: postedInline
|
|
8655
|
+
}
|
|
8656
|
+
);
|
|
8657
|
+
const body = renderNote({
|
|
8658
|
+
...ctx,
|
|
8659
|
+
config,
|
|
8660
|
+
configSource: loaded.source,
|
|
8661
|
+
status: { kind: "reviewed" },
|
|
8662
|
+
response,
|
|
8663
|
+
postedInline,
|
|
8664
|
+
notInline,
|
|
8665
|
+
skippedDuplicates: sel.duplicates.length,
|
|
8666
|
+
skippedFiles,
|
|
8667
|
+
preMerge,
|
|
8668
|
+
reviewedCommits: commits.length,
|
|
8669
|
+
toolWarnings: tools.warnings,
|
|
8670
|
+
state
|
|
8671
|
+
});
|
|
8672
|
+
if (dryRun) {
|
|
8673
|
+
print("--- summary note ---");
|
|
8674
|
+
print(body);
|
|
8675
|
+
return done("dry-run");
|
|
8676
|
+
}
|
|
8677
|
+
result.noteId = await sticky.save(body);
|
|
8678
|
+
log(`AuraCheck review: summary note ${noteUrl()}`);
|
|
8679
|
+
if (config.reviews.high_level_summary && response.summary.describe?.trim()) {
|
|
8680
|
+
const next = applySummaryBlock(
|
|
8681
|
+
mr.description,
|
|
8682
|
+
config.reviews.high_level_summary_placeholder,
|
|
8683
|
+
response.summary.describe
|
|
8684
|
+
);
|
|
8685
|
+
if (next !== null) {
|
|
8686
|
+
try {
|
|
8687
|
+
await p.updateMrDescription(iid, next);
|
|
8688
|
+
log("AuraCheck review: summary written into the MR description.");
|
|
8689
|
+
} catch (err) {
|
|
8690
|
+
warn2(`could not update the MR description: ${err.message}`);
|
|
8691
|
+
}
|
|
8692
|
+
}
|
|
8693
|
+
}
|
|
8694
|
+
const sev = response.stats?.bySeverity;
|
|
8695
|
+
const serious = sev ? (sev.critical ?? 0) + (sev.high ?? 0) : 0;
|
|
8696
|
+
const failedChecks = failedErrorChecks(preMerge);
|
|
8697
|
+
const checkNote = failedChecks.length ? `; pre-merge check failed: ${failedChecks.map((c) => c.id).join(", ")}` : "";
|
|
8698
|
+
statusDescription = `${response.findings.length} finding(s), ${serious} high or critical${checkNote}`;
|
|
8699
|
+
log(
|
|
8700
|
+
`AuraCheck review: done. ${response.findings.length} finding(s), ${postedInline} posted inline, ${sel.duplicates.length} duplicate(s) skipped, ${notInline.length} in the note only.`
|
|
8701
|
+
);
|
|
8702
|
+
return done("reviewed");
|
|
8703
|
+
}
|
|
8704
|
+
}
|
|
8705
|
+
async function finalizeStatus(deps) {
|
|
8706
|
+
const log = deps.log ?? ((m) => process.stdout.write(`${m}
|
|
8707
|
+
`));
|
|
8708
|
+
const env = resolveReviewEnv(deps.env);
|
|
8709
|
+
let sha = env.commitSha;
|
|
8710
|
+
const trigger = await readTriggerPayload(deps.env).catch(() => null);
|
|
8711
|
+
const iid = trigger?.kind === "command" ? trigger.iid : env.mrIid;
|
|
8712
|
+
if (trigger?.kind === "ignore") return 0;
|
|
8713
|
+
if (iid) {
|
|
8714
|
+
try {
|
|
8715
|
+
const mr = await deps.provider.getMergeRequest(iid);
|
|
8716
|
+
sha = mr.diffRefs?.headSha ?? mr.sha ?? sha;
|
|
8717
|
+
} catch {
|
|
8718
|
+
}
|
|
8719
|
+
}
|
|
8720
|
+
if (!sha) {
|
|
8721
|
+
log("AuraCheck review: no commit to finalize.");
|
|
8722
|
+
return 0;
|
|
8723
|
+
}
|
|
8724
|
+
try {
|
|
8725
|
+
const statuses = await deps.provider.listCommitStatuses(
|
|
8726
|
+
sha,
|
|
8727
|
+
COMMIT_STATUS_NAME
|
|
8728
|
+
);
|
|
8729
|
+
const mine = statuses.filter((s) => s.name === COMMIT_STATUS_NAME);
|
|
8730
|
+
const open = mine.some(
|
|
8731
|
+
(s) => s.status === "pending" || s.status === "running"
|
|
8732
|
+
);
|
|
8733
|
+
if (!open) {
|
|
8734
|
+
log("AuraCheck review: commit status already settled.");
|
|
8735
|
+
return 0;
|
|
8736
|
+
}
|
|
8737
|
+
await deps.provider.setCommitStatus(sha, {
|
|
8738
|
+
state: "success",
|
|
8739
|
+
name: COMMIT_STATUS_NAME,
|
|
8740
|
+
description: "Review did not finish; see the job log",
|
|
8741
|
+
targetUrl: env.jobUrl ?? void 0
|
|
8742
|
+
});
|
|
8743
|
+
log("AuraCheck review: commit status closed (review did not finish).");
|
|
8744
|
+
} catch (err) {
|
|
8745
|
+
log(
|
|
8746
|
+
`AuraCheck review: could not finalize the commit status: ${err.message}`
|
|
8747
|
+
);
|
|
8748
|
+
}
|
|
8749
|
+
return 0;
|
|
8750
|
+
}
|
|
8751
|
+
|
|
8752
|
+
// src/commands/review.ts
|
|
8753
|
+
async function reviewCommand(opts) {
|
|
8754
|
+
const env = process.env;
|
|
8755
|
+
const mrIid = opts.mr ? Number(opts.mr) : void 0;
|
|
8756
|
+
if (opts.mr && (!Number.isInteger(mrIid) || (mrIid ?? 0) <= 0)) {
|
|
8757
|
+
throw new Error(`--mr expects a merge request number, got "${opts.mr}"`);
|
|
8758
|
+
}
|
|
8759
|
+
const resolved = resolveReviewEnv(env, { baseUrl: opts.baseUrl, mrIid });
|
|
8760
|
+
const missing = [];
|
|
8761
|
+
if (!resolved.gitlabToken) missing.push("AURACHECK_GITLAB_TOKEN");
|
|
8762
|
+
if (!resolved.apiUrl) missing.push("CI_SERVER_URL (or CI_API_V4_URL)");
|
|
8763
|
+
if (!resolved.projectId) missing.push("CI_PROJECT_ID");
|
|
8764
|
+
const warn2 = (m) => process.stderr.write(pc4.yellow(`warning: ${m}
|
|
8765
|
+
`));
|
|
8766
|
+
if (missing.length) {
|
|
8767
|
+
if (opts.finalizeStatus) return;
|
|
8768
|
+
process.stderr.write(
|
|
8769
|
+
pc4.red(
|
|
8770
|
+
`AuraCheck review: missing ${missing.join(", ")}. AURACHECK_GITLAB_TOKEN is a project access token (scope api) added as a masked CI/CD variable; the CI_* variables come from GitLab CI.
|
|
8771
|
+
`
|
|
8772
|
+
)
|
|
8773
|
+
);
|
|
8774
|
+
process.exitCode = 1;
|
|
8775
|
+
return;
|
|
8776
|
+
}
|
|
8777
|
+
const provider = new GitLabProvider({
|
|
8778
|
+
apiUrl: resolved.apiUrl,
|
|
8779
|
+
projectId: resolved.projectId,
|
|
8780
|
+
token: resolved.gitlabToken,
|
|
8781
|
+
warn: warn2
|
|
8782
|
+
});
|
|
8783
|
+
if (opts.finalizeStatus) {
|
|
8784
|
+
process.exitCode = await finalizeStatus({ env, provider });
|
|
8785
|
+
return;
|
|
8786
|
+
}
|
|
8787
|
+
const server = resolved.token ? createReviewServer({
|
|
8788
|
+
baseUrl: resolved.baseUrl,
|
|
8789
|
+
token: resolved.token,
|
|
8790
|
+
userAgent: `auracheck-cli/${opts.version}`
|
|
8791
|
+
}) : null;
|
|
8792
|
+
if (!server && !opts.dryRun) {
|
|
8793
|
+
warn2(
|
|
8794
|
+
"AURACHECK_TOKEN is not set; the review will report the failure in the MR note"
|
|
8795
|
+
);
|
|
8796
|
+
}
|
|
8797
|
+
try {
|
|
8798
|
+
const result = await runReview(
|
|
8799
|
+
{ env, provider, server, warn: warn2 },
|
|
8800
|
+
{ dryRun: opts.dryRun, mrIid, full: opts.full, baseUrl: opts.baseUrl }
|
|
8801
|
+
);
|
|
8802
|
+
process.exitCode = result.exitCode;
|
|
8803
|
+
} catch (err) {
|
|
8804
|
+
process.stderr.write(
|
|
8805
|
+
pc4.red(`AuraCheck review failed: ${err?.message ?? err}
|
|
8806
|
+
`)
|
|
8807
|
+
);
|
|
8808
|
+
process.exitCode = 1;
|
|
8809
|
+
}
|
|
8810
|
+
}
|
|
8811
|
+
|
|
8812
|
+
// src/commands/setup.ts
|
|
8813
|
+
import { spawn as spawn2, spawnSync } from "child_process";
|
|
8814
|
+
import { promises as fs8 } from "fs";
|
|
8815
|
+
import path7 from "path";
|
|
8816
|
+
import pc5 from "picocolors";
|
|
8817
|
+
import prompts3 from "prompts";
|
|
8818
|
+
function hasBinaryOnPath(bin) {
|
|
8819
|
+
const r = spawnSync(process.platform === "win32" ? "where" : "which", [bin], {
|
|
8820
|
+
stdio: "ignore"
|
|
8821
|
+
});
|
|
8822
|
+
return r.status === 0;
|
|
8823
|
+
}
|
|
8824
|
+
function resolveMcpInvocation() {
|
|
8825
|
+
if (hasBinaryOnPath("auracheck")) {
|
|
8826
|
+
return { command: "auracheck", args: ["mcp"], display: "auracheck mcp" };
|
|
8827
|
+
}
|
|
8828
|
+
const entry = process.argv[1];
|
|
8829
|
+
return {
|
|
8830
|
+
command: process.execPath,
|
|
8831
|
+
args: [entry, "mcp"],
|
|
8832
|
+
display: `node ${entry} mcp`
|
|
8833
|
+
};
|
|
8834
|
+
}
|
|
8835
|
+
async function registerWithClaudeCode(invocation) {
|
|
8836
|
+
if (!hasBinaryOnPath("claude")) {
|
|
8837
|
+
process.stdout.write(
|
|
8838
|
+
pc5.yellow(
|
|
8839
|
+
"! `claude` CLI not found on PATH \u2014 skipping auto-registration.\n"
|
|
8840
|
+
)
|
|
8841
|
+
);
|
|
8842
|
+
return false;
|
|
8843
|
+
}
|
|
8844
|
+
return await new Promise((resolve) => {
|
|
8845
|
+
const child = spawn2(
|
|
8846
|
+
"claude",
|
|
8847
|
+
["mcp", "add", "auracheck", "--", invocation.command, ...invocation.args],
|
|
8848
|
+
{ stdio: "inherit" }
|
|
8849
|
+
);
|
|
8850
|
+
child.on("exit", (code) => resolve(code === 0));
|
|
8851
|
+
child.on("error", () => resolve(false));
|
|
8852
|
+
});
|
|
8853
|
+
}
|
|
8854
|
+
function printManualSnippets(target, invocation) {
|
|
8855
|
+
const argsJson = JSON.stringify(invocation.args);
|
|
8856
|
+
if (target === "cursor") {
|
|
8857
|
+
process.stdout.write(
|
|
8858
|
+
`
|
|
8859
|
+
${pc5.bold("Add to")} ${pc5.cyan(".cursor/mcp.json")}:
|
|
8860
|
+
`
|
|
8861
|
+
);
|
|
8862
|
+
process.stdout.write(
|
|
8863
|
+
`${pc5.dim(
|
|
8864
|
+
JSON.stringify(
|
|
8865
|
+
{
|
|
8866
|
+
mcpServers: {
|
|
8867
|
+
auracheck: { command: invocation.command, args: invocation.args }
|
|
8868
|
+
}
|
|
8869
|
+
},
|
|
8870
|
+
null,
|
|
8871
|
+
2
|
|
8872
|
+
)
|
|
8873
|
+
)}
|
|
8874
|
+
`
|
|
8875
|
+
);
|
|
8876
|
+
return;
|
|
8877
|
+
}
|
|
8878
|
+
if (target === "claude-desktop") {
|
|
8879
|
+
process.stdout.write(
|
|
8880
|
+
`
|
|
8881
|
+
${pc5.bold("Add to Claude Desktop config")} (${pc5.cyan("~/Library/Application Support/Claude/claude_desktop_config.json")} on macOS):
|
|
8882
|
+
`
|
|
8883
|
+
);
|
|
8884
|
+
process.stdout.write(
|
|
8885
|
+
`${pc5.dim(
|
|
8886
|
+
JSON.stringify(
|
|
8887
|
+
{
|
|
8888
|
+
mcpServers: {
|
|
8889
|
+
auracheck: { command: invocation.command, args: invocation.args }
|
|
8890
|
+
}
|
|
8891
|
+
},
|
|
8892
|
+
null,
|
|
8893
|
+
2
|
|
8894
|
+
)
|
|
8895
|
+
)}
|
|
8896
|
+
`
|
|
8897
|
+
);
|
|
8898
|
+
void argsJson;
|
|
8899
|
+
}
|
|
8900
|
+
}
|
|
8901
|
+
async function setupCommand(opts) {
|
|
8902
|
+
const cwd = process.cwd();
|
|
8903
|
+
process.stdout.write(
|
|
8904
|
+
pc5.bold("AuraCheck setup\n") + pc5.dim("Walks through: login \u2192 bind project \u2192 register MCP.\n\n")
|
|
8905
|
+
);
|
|
8906
|
+
let baseUrl = opts.baseUrl;
|
|
8907
|
+
if (!baseUrl && !opts.nonInteractive) {
|
|
8908
|
+
const ans = await prompts3({
|
|
8909
|
+
type: "text",
|
|
8910
|
+
name: "baseUrl",
|
|
8911
|
+
message: "AuraCheck platform URL (not your app)",
|
|
8912
|
+
initial: "https://space.auracheck.ai.id",
|
|
8913
|
+
validate: (v) => /^https?:\/\//.test(v) ? true : "must start with http(s)://"
|
|
8914
|
+
});
|
|
8915
|
+
baseUrl = ans.baseUrl;
|
|
8916
|
+
}
|
|
8917
|
+
if (!baseUrl) throw new Error("Aborted (no base URL).");
|
|
8918
|
+
const existingToken = await getToken(baseUrl);
|
|
8919
|
+
let tokenValid = false;
|
|
8920
|
+
if (existingToken) {
|
|
8921
|
+
try {
|
|
8922
|
+
const api = new AuraCheckApi({ baseUrl, token: existingToken });
|
|
8923
|
+
const user = await api.me();
|
|
8924
|
+
process.stdout.write(
|
|
8925
|
+
pc5.green(
|
|
8926
|
+
`\u2713 Token already saved for ${normalizeBaseUrl2(baseUrl)} (${user.email}). Skipping login.
|
|
8927
|
+
`
|
|
8928
|
+
)
|
|
8929
|
+
);
|
|
8930
|
+
tokenValid = true;
|
|
8931
|
+
} catch {
|
|
8932
|
+
process.stdout.write(
|
|
8933
|
+
pc5.yellow(
|
|
8934
|
+
`! Saved token for ${normalizeBaseUrl2(baseUrl)} is invalid \u2014 re-login required.
|
|
8935
|
+
`
|
|
8936
|
+
)
|
|
8937
|
+
);
|
|
8938
|
+
}
|
|
8939
|
+
}
|
|
8940
|
+
if (!tokenValid) {
|
|
8941
|
+
process.stdout.write(pc5.bold("\n[1/3] Login\n"));
|
|
8942
|
+
await loginCommand({
|
|
8943
|
+
baseUrl,
|
|
8944
|
+
token: opts.token,
|
|
8945
|
+
nonInteractive: !!opts.nonInteractive
|
|
8946
|
+
});
|
|
8947
|
+
}
|
|
8948
|
+
process.stdout.write(pc5.bold("\n[2/3] Bind project\n"));
|
|
8949
|
+
const existing = await readProjectConfig(cwd).catch(() => null);
|
|
8950
|
+
let shouldInit = true;
|
|
8951
|
+
if (existing) {
|
|
8952
|
+
process.stdout.write(
|
|
8953
|
+
pc5.dim(
|
|
8954
|
+
` Found existing .sixseven/config.json \u2192 projectId ${existing.projectId} on ${existing.baseUrl}
|
|
8955
|
+
`
|
|
8956
|
+
)
|
|
8957
|
+
);
|
|
8958
|
+
if (opts.nonInteractive) {
|
|
8959
|
+
shouldInit = false;
|
|
8960
|
+
} else {
|
|
8961
|
+
const ans = await prompts3({
|
|
8962
|
+
type: "confirm",
|
|
5701
8963
|
name: "rebind",
|
|
5702
8964
|
message: "Re-bind this repo to a different project?",
|
|
5703
8965
|
initial: false
|
|
@@ -5712,16 +8974,16 @@ async function setupCommand(opts) {
|
|
|
5712
8974
|
nonInteractive: !!opts.nonInteractive
|
|
5713
8975
|
});
|
|
5714
8976
|
} else {
|
|
5715
|
-
process.stdout.write(
|
|
8977
|
+
process.stdout.write(pc5.dim(" Keeping existing binding.\n"));
|
|
5716
8978
|
}
|
|
5717
|
-
process.stdout.write(
|
|
8979
|
+
process.stdout.write(pc5.bold("\n[3/3] Register MCP server\n"));
|
|
5718
8980
|
if (opts.skipMcp) {
|
|
5719
|
-
process.stdout.write(
|
|
8981
|
+
process.stdout.write(pc5.dim(" --skip-mcp set, skipping.\n"));
|
|
5720
8982
|
return;
|
|
5721
8983
|
}
|
|
5722
8984
|
const invocation = resolveMcpInvocation();
|
|
5723
8985
|
process.stdout.write(
|
|
5724
|
-
|
|
8986
|
+
pc5.dim(` MCP launch command: ${invocation.display}
|
|
5725
8987
|
|
|
5726
8988
|
`)
|
|
5727
8989
|
);
|
|
@@ -5753,13 +9015,13 @@ async function setupCommand(opts) {
|
|
|
5753
9015
|
const ok2 = await registerWithClaudeCode(invocation);
|
|
5754
9016
|
if (ok2) {
|
|
5755
9017
|
process.stdout.write(
|
|
5756
|
-
|
|
9018
|
+
pc5.green(
|
|
5757
9019
|
'\n\u2713 Registered as MCP server "auracheck" with Claude Code.\n'
|
|
5758
9020
|
)
|
|
5759
9021
|
);
|
|
5760
9022
|
} else {
|
|
5761
9023
|
process.stdout.write(
|
|
5762
|
-
|
|
9024
|
+
pc5.yellow("\n! Auto-registration failed. Run manually:\n") + pc5.cyan(
|
|
5763
9025
|
` claude mcp add auracheck -- ${invocation.command} ${invocation.args.join(" ")}
|
|
5764
9026
|
`
|
|
5765
9027
|
)
|
|
@@ -5767,7 +9029,7 @@ async function setupCommand(opts) {
|
|
|
5767
9029
|
}
|
|
5768
9030
|
} else if (target === "skip") {
|
|
5769
9031
|
process.stdout.write(
|
|
5770
|
-
|
|
9032
|
+
pc5.dim(" Manual command:\n") + pc5.cyan(
|
|
5771
9033
|
` claude mcp add auracheck -- ${invocation.command} ${invocation.args.join(" ")}
|
|
5772
9034
|
`
|
|
5773
9035
|
)
|
|
@@ -5775,27 +9037,27 @@ async function setupCommand(opts) {
|
|
|
5775
9037
|
} else {
|
|
5776
9038
|
printManualSnippets(target, invocation);
|
|
5777
9039
|
}
|
|
5778
|
-
const cfgPath =
|
|
5779
|
-
const cfgExists = await
|
|
9040
|
+
const cfgPath = path7.join(cwd, ".sixseven", "config.json");
|
|
9041
|
+
const cfgExists = await fs8.stat(cfgPath).then(() => true).catch(() => false);
|
|
5780
9042
|
process.stdout.write(
|
|
5781
9043
|
`
|
|
5782
|
-
${
|
|
5783
|
-
${
|
|
9044
|
+
${pc5.bold("Done.")} ${pc5.dim("Next:")}
|
|
9045
|
+
${pc5.dim(
|
|
5784
9046
|
` \u2022 auracheck status \u2014 verify binding (${cfgExists ? "config OK" : "no config"})
|
|
5785
9047
|
`
|
|
5786
|
-
)}${
|
|
9048
|
+
)}${pc5.dim(" \u2022 auracheck doctor \u2014 full diagnostics\n")}${pc5.dim(' \u2022 Open Claude Code and ask: "list auracheck features"\n')}`
|
|
5787
9049
|
);
|
|
5788
9050
|
}
|
|
5789
9051
|
|
|
5790
9052
|
// src/commands/status.ts
|
|
5791
|
-
import
|
|
9053
|
+
import pc6 from "picocolors";
|
|
5792
9054
|
async function statusCommand() {
|
|
5793
9055
|
const ctx = await loadContext(process.cwd());
|
|
5794
9056
|
const api = new AuraCheckApi({
|
|
5795
9057
|
baseUrl: ctx.config.baseUrl,
|
|
5796
9058
|
token: ctx.token
|
|
5797
9059
|
});
|
|
5798
|
-
process.stdout.write(
|
|
9060
|
+
process.stdout.write(pc6.bold("AuraCheck CLI status\n"));
|
|
5799
9061
|
process.stdout.write(` config: ${ctx.configPath}
|
|
5800
9062
|
`);
|
|
5801
9063
|
process.stdout.write(` repoRoot: ${ctx.repoRoot}
|
|
@@ -5811,13 +9073,13 @@ async function statusCommand() {
|
|
|
5811
9073
|
try {
|
|
5812
9074
|
const user = await api.me();
|
|
5813
9075
|
process.stdout.write(
|
|
5814
|
-
|
|
9076
|
+
pc6.green(
|
|
5815
9077
|
` token: \u2713 valid (user: ${user.email}, role: ${user.role})
|
|
5816
9078
|
`
|
|
5817
9079
|
)
|
|
5818
9080
|
);
|
|
5819
9081
|
} catch (err) {
|
|
5820
|
-
process.stdout.write(
|
|
9082
|
+
process.stdout.write(pc6.red(` token: \u2717 ${err.message}
|
|
5821
9083
|
`));
|
|
5822
9084
|
process.exitCode = 1;
|
|
5823
9085
|
return;
|
|
@@ -5830,7 +9092,7 @@ async function statusCommand() {
|
|
|
5830
9092
|
process.stdout.write(` testcases: ${tcs.length}
|
|
5831
9093
|
`);
|
|
5832
9094
|
} catch (err) {
|
|
5833
|
-
process.stdout.write(
|
|
9095
|
+
process.stdout.write(pc6.yellow(` warn: ${err.message}
|
|
5834
9096
|
`));
|
|
5835
9097
|
}
|
|
5836
9098
|
}
|
|
@@ -5926,11 +9188,11 @@ function registerKnowledgeResources(server) {
|
|
|
5926
9188
|
// src/mcp/server.ts
|
|
5927
9189
|
import { McpServer } from "@modelcontextprotocol/server";
|
|
5928
9190
|
import { serveStdio } from "@modelcontextprotocol/server/stdio";
|
|
5929
|
-
import { z as
|
|
9191
|
+
import { z as z19 } from "zod";
|
|
5930
9192
|
|
|
5931
9193
|
// src/source-reader.ts
|
|
5932
|
-
import { promises as
|
|
5933
|
-
import
|
|
9194
|
+
import { promises as fs9 } from "fs";
|
|
9195
|
+
import path8 from "path";
|
|
5934
9196
|
var DEFAULT_MAX_FILE_BYTES = 2e5;
|
|
5935
9197
|
var DEFAULT_MAX_SEARCH_RESULTS = 200;
|
|
5936
9198
|
var TEXT_EXT = /* @__PURE__ */ new Set([
|
|
@@ -5973,8 +9235,8 @@ var SourceReader = class {
|
|
|
5973
9235
|
excludeGlobs;
|
|
5974
9236
|
maxFileBytes;
|
|
5975
9237
|
constructor(opts) {
|
|
5976
|
-
this.repoRoot =
|
|
5977
|
-
this.roots = (opts.config.codeRoots.length ? opts.config.codeRoots : ["."]).map((r) =>
|
|
9238
|
+
this.repoRoot = path8.resolve(opts.repoRoot);
|
|
9239
|
+
this.roots = (opts.config.codeRoots.length ? opts.config.codeRoots : ["."]).map((r) => path8.resolve(this.repoRoot, r));
|
|
5978
9240
|
const excludeNames = /* @__PURE__ */ new Set();
|
|
5979
9241
|
const excludeGlobs = [];
|
|
5980
9242
|
for (const e of opts.config.exclude) {
|
|
@@ -5991,16 +9253,16 @@ var SourceReader = class {
|
|
|
5991
9253
|
*/
|
|
5992
9254
|
resolveSafe(relPath) {
|
|
5993
9255
|
const cleaned = relPath.replace(/^[./\\]+/, "").replace(/\\/g, "/");
|
|
5994
|
-
const abs =
|
|
5995
|
-
const repoRel =
|
|
5996
|
-
if (repoRel.startsWith("..") ||
|
|
9256
|
+
const abs = path8.resolve(this.repoRoot, cleaned);
|
|
9257
|
+
const repoRel = path8.relative(this.repoRoot, abs);
|
|
9258
|
+
if (repoRel.startsWith("..") || path8.isAbsolute(repoRel)) {
|
|
5997
9259
|
throw new Error(`Path escapes repo root: ${relPath}`);
|
|
5998
9260
|
}
|
|
5999
9261
|
if (!this.roots.some(
|
|
6000
|
-
(root) => abs === root || abs.startsWith(root +
|
|
9262
|
+
(root) => abs === root || abs.startsWith(root + path8.sep)
|
|
6001
9263
|
)) {
|
|
6002
9264
|
throw new Error(
|
|
6003
|
-
`Path is outside configured codeRoots (${this.roots.map((r) =>
|
|
9265
|
+
`Path is outside configured codeRoots (${this.roots.map((r) => path8.relative(this.repoRoot, r)).join(", ")}): ${relPath}`
|
|
6004
9266
|
);
|
|
6005
9267
|
}
|
|
6006
9268
|
if (this.isExcluded(abs)) {
|
|
@@ -6009,8 +9271,8 @@ var SourceReader = class {
|
|
|
6009
9271
|
return abs;
|
|
6010
9272
|
}
|
|
6011
9273
|
isExcluded(absPath) {
|
|
6012
|
-
const rel =
|
|
6013
|
-
const parts = rel.split(
|
|
9274
|
+
const rel = path8.relative(this.repoRoot, absPath);
|
|
9275
|
+
const parts = rel.split(path8.sep);
|
|
6014
9276
|
if (parts.some((p) => this.excludeNames.has(p))) return true;
|
|
6015
9277
|
for (const g of this.excludeGlobs) {
|
|
6016
9278
|
if (rel.includes(g.replace(/\*/g, ""))) return true;
|
|
@@ -6019,19 +9281,19 @@ var SourceReader = class {
|
|
|
6019
9281
|
}
|
|
6020
9282
|
async readFile(relPath) {
|
|
6021
9283
|
const abs = this.resolveSafe(relPath);
|
|
6022
|
-
const stat = await
|
|
9284
|
+
const stat = await fs9.stat(abs);
|
|
6023
9285
|
if (!stat.isFile()) throw new Error(`Not a file: ${relPath}`);
|
|
6024
|
-
const ext =
|
|
9286
|
+
const ext = path8.extname(abs).toLowerCase();
|
|
6025
9287
|
if (ext && !TEXT_EXT.has(ext)) {
|
|
6026
9288
|
throw new Error(
|
|
6027
9289
|
`Refusing to read non-text file: ${relPath} (extension ${ext})`
|
|
6028
9290
|
);
|
|
6029
9291
|
}
|
|
6030
|
-
const buf = await
|
|
9292
|
+
const buf = await fs9.readFile(abs);
|
|
6031
9293
|
const truncated = buf.byteLength > this.maxFileBytes;
|
|
6032
9294
|
const sliced = truncated ? buf.subarray(0, this.maxFileBytes) : buf;
|
|
6033
9295
|
return {
|
|
6034
|
-
path:
|
|
9296
|
+
path: path8.relative(this.repoRoot, abs),
|
|
6035
9297
|
bytes: stat.size,
|
|
6036
9298
|
content: sliced.toString("utf8"),
|
|
6037
9299
|
truncated
|
|
@@ -6039,16 +9301,16 @@ var SourceReader = class {
|
|
|
6039
9301
|
}
|
|
6040
9302
|
async listDir(relPath) {
|
|
6041
9303
|
const abs = this.resolveSafe(relPath || ".");
|
|
6042
|
-
const stat = await
|
|
9304
|
+
const stat = await fs9.stat(abs);
|
|
6043
9305
|
if (!stat.isDirectory()) throw new Error(`Not a directory: ${relPath}`);
|
|
6044
|
-
const dirents = await
|
|
6045
|
-
const entries = dirents.filter((d) => !this.isExcluded(
|
|
9306
|
+
const dirents = await fs9.readdir(abs, { withFileTypes: true });
|
|
9307
|
+
const entries = dirents.filter((d) => !this.isExcluded(path8.join(abs, d.name))).map((d) => ({
|
|
6046
9308
|
name: d.name,
|
|
6047
9309
|
type: d.isDirectory() ? "dir" : "file"
|
|
6048
9310
|
})).sort(
|
|
6049
9311
|
(a, b) => a.type === b.type ? a.name.localeCompare(b.name) : a.type === "dir" ? -1 : 1
|
|
6050
9312
|
);
|
|
6051
|
-
return { path:
|
|
9313
|
+
return { path: path8.relative(this.repoRoot, abs), entries };
|
|
6052
9314
|
}
|
|
6053
9315
|
/**
|
|
6054
9316
|
* Substring/regex search across configured codeRoots. Returns up to
|
|
@@ -6060,26 +9322,26 @@ var SourceReader = class {
|
|
|
6060
9322
|
const flags = opts.caseSensitive ? "g" : "gi";
|
|
6061
9323
|
const re = opts.regex ? new RegExp(query, flags) : new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), flags);
|
|
6062
9324
|
const results = [];
|
|
6063
|
-
const
|
|
9325
|
+
const walk2 = async (dir) => {
|
|
6064
9326
|
if (results.length >= maxResults) return;
|
|
6065
9327
|
let dirents;
|
|
6066
9328
|
try {
|
|
6067
|
-
dirents = await
|
|
9329
|
+
dirents = await fs9.readdir(dir, { withFileTypes: true });
|
|
6068
9330
|
} catch {
|
|
6069
9331
|
return;
|
|
6070
9332
|
}
|
|
6071
9333
|
for (const d of dirents) {
|
|
6072
9334
|
if (results.length >= maxResults) return;
|
|
6073
|
-
const abs =
|
|
9335
|
+
const abs = path8.join(dir, d.name);
|
|
6074
9336
|
if (this.isExcluded(abs)) continue;
|
|
6075
9337
|
if (d.isDirectory()) {
|
|
6076
|
-
await
|
|
9338
|
+
await walk2(abs);
|
|
6077
9339
|
} else if (d.isFile()) {
|
|
6078
|
-
const ext =
|
|
9340
|
+
const ext = path8.extname(d.name).toLowerCase();
|
|
6079
9341
|
if (ext && !TEXT_EXT.has(ext)) continue;
|
|
6080
9342
|
let content;
|
|
6081
9343
|
try {
|
|
6082
|
-
const buf = await
|
|
9344
|
+
const buf = await fs9.readFile(abs);
|
|
6083
9345
|
if (buf.byteLength > this.maxFileBytes) continue;
|
|
6084
9346
|
content = buf.toString("utf8");
|
|
6085
9347
|
} catch {
|
|
@@ -6090,7 +9352,7 @@ var SourceReader = class {
|
|
|
6090
9352
|
const line = lines[i];
|
|
6091
9353
|
if (re.test(line)) {
|
|
6092
9354
|
results.push({
|
|
6093
|
-
file:
|
|
9355
|
+
file: path8.relative(this.repoRoot, abs),
|
|
6094
9356
|
line: i + 1,
|
|
6095
9357
|
preview: line.length > 240 ? `${line.slice(0, 240)}\u2026` : line
|
|
6096
9358
|
});
|
|
@@ -6102,7 +9364,7 @@ var SourceReader = class {
|
|
|
6102
9364
|
}
|
|
6103
9365
|
};
|
|
6104
9366
|
for (const root of this.roots) {
|
|
6105
|
-
await
|
|
9367
|
+
await walk2(root);
|
|
6106
9368
|
if (results.length >= maxResults) break;
|
|
6107
9369
|
}
|
|
6108
9370
|
return results;
|
|
@@ -6110,7 +9372,7 @@ var SourceReader = class {
|
|
|
6110
9372
|
};
|
|
6111
9373
|
|
|
6112
9374
|
// src/mcp/server.ts
|
|
6113
|
-
var CLI_VERSION = "0.
|
|
9375
|
+
var CLI_VERSION = "0.3.0-next.0";
|
|
6114
9376
|
var LOCAL_ALL_CAPABILITIES = [
|
|
6115
9377
|
"viewProject",
|
|
6116
9378
|
"viewReports",
|
|
@@ -6164,23 +9426,23 @@ var LOCAL_TOOLS = [
|
|
|
6164
9426
|
{
|
|
6165
9427
|
name: "auracheck.read_code",
|
|
6166
9428
|
description: "Read a text file from the developer repo. Path is relative to repo root and must fall within configured codeRoots. Use to understand routes, components, validators, and fixtures before generating a testcase.",
|
|
6167
|
-
zod:
|
|
6168
|
-
handler: async ({ path:
|
|
9429
|
+
zod: z19.object({ path: z19.string().min(1) }),
|
|
9430
|
+
handler: async ({ path: path10 }, { reader }) => reader.readFile(path10)
|
|
6169
9431
|
},
|
|
6170
9432
|
{
|
|
6171
9433
|
name: "auracheck.list_dir",
|
|
6172
9434
|
description: "List entries of a directory inside the developer repo. Path is relative to repo root.",
|
|
6173
|
-
zod:
|
|
6174
|
-
handler: async ({ path:
|
|
9435
|
+
zod: z19.object({ path: z19.string().default(".") }),
|
|
9436
|
+
handler: async ({ path: path10 }, { reader }) => reader.listDir(path10)
|
|
6175
9437
|
},
|
|
6176
9438
|
{
|
|
6177
9439
|
name: "auracheck.search_code",
|
|
6178
9440
|
description: "Search developer repo (within codeRoots) for a substring or regex. Returns up to 200 matches with file + line + preview. Use to locate routes, handlers, components by name.",
|
|
6179
|
-
zod:
|
|
6180
|
-
query:
|
|
6181
|
-
regex:
|
|
6182
|
-
caseSensitive:
|
|
6183
|
-
maxResults:
|
|
9441
|
+
zod: z19.object({
|
|
9442
|
+
query: z19.string().min(1),
|
|
9443
|
+
regex: z19.boolean().optional(),
|
|
9444
|
+
caseSensitive: z19.boolean().optional(),
|
|
9445
|
+
maxResults: z19.number().int().positive().max(1e3).optional()
|
|
6184
9446
|
}),
|
|
6185
9447
|
handler: async (args, { reader }) => reader.search(args.query, args)
|
|
6186
9448
|
},
|
|
@@ -6188,7 +9450,7 @@ var LOCAL_TOOLS = [
|
|
|
6188
9450
|
{
|
|
6189
9451
|
name: "auracheck.whoami",
|
|
6190
9452
|
description: "Report sign-in status, the base URL, and the project this MCP session is bound to, plus a nextStep hint for what to do next (sign in, bind a project, or nothing \u2014 already set up). Safe to call first, before signing in.",
|
|
6191
|
-
zod:
|
|
9453
|
+
zod: z19.object({}).passthrough(),
|
|
6192
9454
|
handler: async (_args, { api, signedIn, baseUrl, tokenSource }) => {
|
|
6193
9455
|
const boundProjectId = await currentDefaultProjectId();
|
|
6194
9456
|
if (!signedIn) {
|
|
@@ -6219,9 +9481,9 @@ var LOCAL_TOOLS = [
|
|
|
6219
9481
|
{
|
|
6220
9482
|
name: "auracheck.login",
|
|
6221
9483
|
description: "Sign in to AuraCheck through the browser (same OAuth/PKCE flow as `auracheck login` in a terminal) \u2014 no terminal needed. Opens the system browser and waits up to ~90s for the person to click Allow. If it times out before that, it returns the sign-in url and 'Not finished \u2014 call auracheck.login again to resume.'; calling it again starts a fresh attempt (no duplicate tokens are saved \u2014 a new sign-in simply replaces the old one for this baseUrl). On success the token is saved exactly like the CLI command, and tool calls that needed auracheck.login now work.",
|
|
6222
|
-
zod:
|
|
6223
|
-
baseUrl:
|
|
6224
|
-
timeoutSec:
|
|
9484
|
+
zod: z19.object({
|
|
9485
|
+
baseUrl: z19.string().url().optional(),
|
|
9486
|
+
timeoutSec: z19.number().int().positive().max(600).optional()
|
|
6225
9487
|
}),
|
|
6226
9488
|
handler: async (args, { baseUrl: ctxBaseUrl }) => {
|
|
6227
9489
|
const baseUrl = normalizeBaseUrl2(args.baseUrl ?? ctxBaseUrl);
|
|
@@ -6259,7 +9521,7 @@ var LOCAL_TOOLS = [
|
|
|
6259
9521
|
{
|
|
6260
9522
|
name: "auracheck.logout",
|
|
6261
9523
|
description: "Forget the locally saved sign-in for this baseUrl. Local only \u2014 does not revoke the token on the server (do that from Profile \u2192 Active devices if needed).",
|
|
6262
|
-
zod:
|
|
9524
|
+
zod: z19.object({ baseUrl: z19.string().url().optional() }),
|
|
6263
9525
|
handler: async (args, { baseUrl: ctxBaseUrl }) => {
|
|
6264
9526
|
const baseUrl = normalizeBaseUrl2(args.baseUrl ?? ctxBaseUrl);
|
|
6265
9527
|
const removed = await removeToken(baseUrl);
|
|
@@ -6269,7 +9531,7 @@ var LOCAL_TOOLS = [
|
|
|
6269
9531
|
{
|
|
6270
9532
|
name: "auracheck.bind_project",
|
|
6271
9533
|
description: "Set the default AuraCheck project for this repo (if a .sixseven/config.json binding exists or can be created in the current working directory) or, otherwise, as this machine-wide default \u2014 the same fallback project tools use when no projectId is passed. Verifies the id against auracheck.list_projects when signed in. Onboarding order: auracheck.login \u2192 auracheck.list_projects \u2192 ask the person which one \u2192 auracheck.bind_project.",
|
|
6272
|
-
zod:
|
|
9534
|
+
zod: z19.object({ projectId: z19.string().min(1) }),
|
|
6273
9535
|
handler: async ({ projectId }, { api, signedIn, repoRoot, config }) => {
|
|
6274
9536
|
if (signedIn) {
|
|
6275
9537
|
const projects = await api.listProjects().catch(() => null);
|
|
@@ -6280,11 +9542,11 @@ var LOCAL_TOOLS = [
|
|
|
6280
9542
|
}
|
|
6281
9543
|
}
|
|
6282
9544
|
if (config) {
|
|
6283
|
-
const
|
|
9545
|
+
const path10 = await writeProjectConfig(repoRoot, {
|
|
6284
9546
|
...config,
|
|
6285
9547
|
projectId
|
|
6286
9548
|
});
|
|
6287
|
-
return { ok: true, scope: "repo", projectId, configPath:
|
|
9549
|
+
return { ok: true, scope: "repo", projectId, configPath: path10 };
|
|
6288
9550
|
}
|
|
6289
9551
|
await setDefaultProjectId(projectId);
|
|
6290
9552
|
return { ok: true, scope: "global", projectId };
|
|
@@ -6294,22 +9556,22 @@ var LOCAL_TOOLS = [
|
|
|
6294
9556
|
{
|
|
6295
9557
|
name: "auracheck.get_screenshot",
|
|
6296
9558
|
description: "Download a run screenshot (or any authenticated blob) to a local file and return its path, so it can then be opened and looked at. Pass a `screenshotUrl` straight from auracheck.get_evidence \u2014 those are bare paths that cannot be fetched without the bound base URL and CI token, so this is the only way to actually SEE a step's screenshot. Reach for it whenever a failure's cause is visual: 'the page froze' is often disproved by two consecutive screenshots being identical, or by the page rendering fine with a control merely disabled.",
|
|
6297
|
-
zod:
|
|
6298
|
-
url:
|
|
9559
|
+
zod: z19.object({
|
|
9560
|
+
url: z19.string().min(1).describe(
|
|
6299
9561
|
"screenshotUrl from get_evidence, e.g. '/api/blob/screenshots/<runId>/<caseId>-step14.png'. An absolute URL is accepted only on the bound host."
|
|
6300
9562
|
),
|
|
6301
|
-
outPath:
|
|
9563
|
+
outPath: z19.string().optional().describe(
|
|
6302
9564
|
"Where to write it. Defaults to a temp file named after the blob."
|
|
6303
9565
|
)
|
|
6304
9566
|
}),
|
|
6305
9567
|
handler: async (args, { api }) => {
|
|
6306
9568
|
const { tmpdir } = await import("os");
|
|
6307
|
-
const
|
|
9569
|
+
const path10 = await import("path");
|
|
6308
9570
|
const { mkdir, writeFile } = await import("fs/promises");
|
|
6309
9571
|
const { bytes, contentType } = await api.downloadBlob(args.url);
|
|
6310
|
-
const base =
|
|
6311
|
-
const dest = args.outPath ??
|
|
6312
|
-
await mkdir(
|
|
9572
|
+
const base = path10.basename(args.url.split("?")[0] || "").replace(/[^\w.-]/g, "_") || "screenshot.png";
|
|
9573
|
+
const dest = args.outPath ?? path10.join(tmpdir(), `auracheck-${Date.now()}-${base}`);
|
|
9574
|
+
await mkdir(path10.dirname(dest), { recursive: true });
|
|
6313
9575
|
await writeFile(dest, bytes);
|
|
6314
9576
|
return {
|
|
6315
9577
|
path: dest,
|
|
@@ -6553,10 +9815,10 @@ async function runMcpServer(overrides = {}) {
|
|
|
6553
9815
|
}
|
|
6554
9816
|
|
|
6555
9817
|
// src/bin.ts
|
|
6556
|
-
var version = "0.
|
|
9818
|
+
var version = "0.3.0-next.0";
|
|
6557
9819
|
function invokedCommandName() {
|
|
6558
9820
|
const argv1 = process.argv[1] ?? "";
|
|
6559
|
-
const base =
|
|
9821
|
+
const base = path9.basename(argv1).replace(/\.(c|m)?js$/, "");
|
|
6560
9822
|
return base === "sixseven" ? "sixseven" : "auracheck";
|
|
6561
9823
|
}
|
|
6562
9824
|
async function main() {
|
|
@@ -6641,6 +9903,33 @@ async function main() {
|
|
|
6641
9903
|
).action(async () => {
|
|
6642
9904
|
await doctorCommand();
|
|
6643
9905
|
});
|
|
9906
|
+
program.command("review").description(
|
|
9907
|
+
"Review the current GitLab merge request (run in the MR pipeline): one summary note, inline comments on the top findings"
|
|
9908
|
+
).option(
|
|
9909
|
+
"--dry-run",
|
|
9910
|
+
"print the request summary and the note instead of posting"
|
|
9911
|
+
).option(
|
|
9912
|
+
"--mr <iid>",
|
|
9913
|
+
"merge request number (default: CI_MERGE_REQUEST_IID or AURACHECK_MR_IID)"
|
|
9914
|
+
).option(
|
|
9915
|
+
"--full",
|
|
9916
|
+
"review every file of the MR, not only what changed since the last review"
|
|
9917
|
+
).option(
|
|
9918
|
+
"--base-url <url>",
|
|
9919
|
+
"AuraCheck base URL (default: AURACHECK_BASE_URL, else https://space.auracheck.ai.id)"
|
|
9920
|
+
).option(
|
|
9921
|
+
"--finalize-status",
|
|
9922
|
+
"after_script: close a commit status left running by a killed job"
|
|
9923
|
+
).action(async (opts) => {
|
|
9924
|
+
await reviewCommand({
|
|
9925
|
+
dryRun: !!opts.dryRun,
|
|
9926
|
+
mr: opts.mr,
|
|
9927
|
+
full: !!opts.full,
|
|
9928
|
+
baseUrl: opts.baseUrl,
|
|
9929
|
+
finalizeStatus: !!opts.finalizeStatus,
|
|
9930
|
+
version
|
|
9931
|
+
});
|
|
9932
|
+
});
|
|
6644
9933
|
program.command("mcp").description(
|
|
6645
9934
|
"Start the AuraCheck MCP server on stdio (spawned by Claude Code)"
|
|
6646
9935
|
).option(
|
|
@@ -6652,7 +9941,7 @@ async function main() {
|
|
|
6652
9941
|
await program.parseAsync(process.argv);
|
|
6653
9942
|
}
|
|
6654
9943
|
main().catch((err) => {
|
|
6655
|
-
process.stderr.write(
|
|
9944
|
+
process.stderr.write(pc7.red(`
|
|
6656
9945
|
error: ${err?.message ?? err}
|
|
6657
9946
|
`));
|
|
6658
9947
|
if (process.env.AURACHECK_DEBUG || process.env.SIXSEVEN_DEBUG) {
|