@weareikko/code-review 0.10.3 → 0.11.1
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/README.md +12 -37
- package/dist/{cli-CIKr0_zd.js → cli-BFqDzUM6.js} +409 -2606
- package/dist/cli-BFqDzUM6.js.map +1 -0
- package/dist/cli.d.ts +1 -19
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +2 -2
- package/dist/config.d.ts +7 -10
- package/dist/config.d.ts.map +1 -1
- package/dist/gitlab-review.d.ts +9 -23
- package/dist/gitlab-review.d.ts.map +1 -1
- package/dist/mcp.d.ts +4 -6
- package/dist/mcp.d.ts.map +1 -1
- package/dist/product.d.ts +12 -0
- package/dist/product.d.ts.map +1 -1
- package/dist/review.d.ts +5 -7
- package/dist/review.d.ts.map +1 -1
- package/dist/review.js +3 -2
- package/package.json +8 -29
- package/dist/cli-CIKr0_zd.js.map +0 -1
- package/dist/marketplaces.d.ts +0 -100
- package/dist/marketplaces.d.ts.map +0 -1
- package/dist/mcp-config.d.ts +0 -90
- package/dist/mcp-config.d.ts.map +0 -1
- package/dist/mcp-parse.d.ts +0 -146
- package/dist/mcp-parse.d.ts.map +0 -1
- package/dist/skill-links.d.ts +0 -62
- package/dist/skill-links.d.ts.map +0 -1
- package/dist/skill-usage.d.ts +0 -67
- package/dist/skill-usage.d.ts.map +0 -1
- package/dist/skills.d.ts +0 -156
- package/dist/skills.d.ts.map +0 -1
|
@@ -1,15 +1,14 @@
|
|
|
1
|
-
import { mkdir, readFile,
|
|
2
|
-
import { dirname,
|
|
1
|
+
import { mkdir, readFile, rm, unlink, writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, join, resolve } from "node:path";
|
|
3
3
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
4
|
-
import
|
|
4
|
+
import { AgentContextError, CONVENTION_FILES, GitRevisionProjectConfigReader, MCP_DISCOVERY_MODES, WorkingTreeProjectConfigReader, buildMarketplaceRegistry, createSkillReadCounter, findGitRoot, formatMcpFooter, formatReviewUsageSummary, formatSkillsFooter, isReadOnlyMcpTool, loadSkills, parseMarketplaceEntry, pickMcpEnvVars, redactUrl, resolveMcpServers, resolveSkillCacheDir, walkUpContextFiles } from "@weareikko/agent-context";
|
|
5
|
+
import nodeFs, { readFileSync } from "node:fs";
|
|
5
6
|
import { getEnvApiKey, streamSimple } from "@earendil-works/pi-ai/compat";
|
|
6
7
|
import { createHash, randomUUID } from "node:crypto";
|
|
7
|
-
import { homedir } from "node:os";
|
|
8
|
-
import { parse } from "yaml";
|
|
9
|
-
import { execFile } from "node:child_process";
|
|
10
|
-
import { promisify } from "node:util";
|
|
11
8
|
import { tracingChannel } from "node:diagnostics_channel";
|
|
12
9
|
import { performance } from "node:perf_hooks";
|
|
10
|
+
import { execFile } from "node:child_process";
|
|
11
|
+
import { promisify } from "node:util";
|
|
13
12
|
import { Agent } from "@earendil-works/pi-agent-core";
|
|
14
13
|
import { getBuiltinModel } from "@earendil-works/pi-ai/providers/all";
|
|
15
14
|
import { createReadOnlyTools } from "@earendil-works/pi-coding-agent";
|
|
@@ -17,6 +16,7 @@ import { createTwoFilesPatch } from "diff";
|
|
|
17
16
|
import * as git from "isomorphic-git";
|
|
18
17
|
import { Type } from "typebox";
|
|
19
18
|
import { McpClient, StdioTransport, StreamableHttpTransport } from "@earendil-works/pi-mcp";
|
|
19
|
+
import { jsonrepair } from "jsonrepair";
|
|
20
20
|
import { SpanKind, SpanStatusCode, context, metrics, trace } from "@opentelemetry/api";
|
|
21
21
|
import { SeverityNumber, logs } from "@opentelemetry/api-logs";
|
|
22
22
|
//#region src/errors.ts
|
|
@@ -363,1219 +363,40 @@ var GitHubClient = class {
|
|
|
363
363
|
* Return the database IDs of review comments that belong to a **settled**
|
|
364
364
|
* review thread — one that is either resolved or outdated. GitHub's REST
|
|
365
365
|
* comment endpoints omit both states; they are only exposed via GraphQL
|
|
366
|
-
* `reviewThreads.isResolved` / `isOutdated`. Callers use this set to mark
|
|
367
|
-
* normalized notes resolved so settled threads are excluded from summary
|
|
368
|
-
* carry-over and prior-thread context. Paginates over threads.
|
|
369
|
-
*
|
|
370
|
-
* Outdated counts as settled because GitHub, unlike GitLab, does not
|
|
371
|
-
* auto-resolve a thread when the line it anchors to changes: fixing a finding
|
|
372
|
-
* flips the thread to outdated but leaves `isResolved` false until someone
|
|
373
|
-
* manually resolves it. Treating outdated as settled mirrors GitLab's
|
|
374
|
-
* "automatically resolve outdated diff discussions" behaviour, so a fixed
|
|
375
|
-
* finding stops being re-listed under "Still open from earlier reviews" (#133).
|
|
376
|
-
*/
|
|
377
|
-
async listSettledReviewCommentIds(owner, repo, pull) {
|
|
378
|
-
const settled = /* @__PURE__ */ new Set();
|
|
379
|
-
let cursor = null;
|
|
380
|
-
let hasNext = true;
|
|
381
|
-
while (hasNext) {
|
|
382
|
-
const threads = (await this.graphql(REVIEW_THREADS_QUERY, {
|
|
383
|
-
owner,
|
|
384
|
-
repo,
|
|
385
|
-
pull,
|
|
386
|
-
cursor
|
|
387
|
-
})).repository?.pullRequest?.reviewThreads;
|
|
388
|
-
if (!threads) break;
|
|
389
|
-
for (const thread of threads.nodes ?? []) {
|
|
390
|
-
if (!thread.isResolved && !thread.isOutdated) continue;
|
|
391
|
-
for (const comment of thread.comments?.nodes ?? []) if (typeof comment.databaseId === "number") settled.add(comment.databaseId);
|
|
392
|
-
}
|
|
393
|
-
hasNext = threads.pageInfo?.hasNextPage ?? false;
|
|
394
|
-
cursor = threads.pageInfo?.endCursor ?? null;
|
|
395
|
-
if (!cursor) hasNext = false;
|
|
396
|
-
}
|
|
397
|
-
return settled;
|
|
398
|
-
}
|
|
399
|
-
};
|
|
400
|
-
//#endregion
|
|
401
|
-
//#region src/mcp-parse.ts
|
|
402
|
-
var KNOWN_TYPES = /* @__PURE__ */ new Set([
|
|
403
|
-
"stdio",
|
|
404
|
-
"http",
|
|
405
|
-
"sse",
|
|
406
|
-
"ws"
|
|
407
|
-
]);
|
|
408
|
-
var TEMPLATE_PATTERN = /\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g;
|
|
409
|
-
/**
|
|
410
|
-
* Upper bound on a server-declared `timeout`. A server definition governs its
|
|
411
|
-
* own per-call timeout, but it must not be able to stall the review for hours:
|
|
412
|
-
* connect and `tools/list` run before the agent loop, outside the review
|
|
413
|
-
* timeout, so an unclamped value there is a one-line denial of service.
|
|
414
|
-
*/
|
|
415
|
-
var MAX_MCP_TIMEOUT_MS = 12e4;
|
|
416
|
-
function isRecord$1(value) {
|
|
417
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
418
|
-
}
|
|
419
|
-
/**
|
|
420
|
-
* The subset of `env` an operator opted into exposing to `${VAR}` expansion.
|
|
421
|
-
*
|
|
422
|
-
* Server definitions can come from the repository under review or from a
|
|
423
|
-
* marketplace plugin whose upstream ref moves, so expanding from the whole
|
|
424
|
-
* process environment would let a definition read any secret the reviewer holds
|
|
425
|
-
* (`CODE_REVIEW_GITLAB_TOKEN`, `ANTHROPIC_API_KEY`, …) and ship it out in argv,
|
|
426
|
-
* a header, or a URL query string. Only names listed in `allowlist` are
|
|
427
|
-
* readable; everything else expands as unset, which skips the server with a
|
|
428
|
-
* warning that names the variable and never a value.
|
|
429
|
-
*/
|
|
430
|
-
function pickMcpEnvVars(env, allowlist) {
|
|
431
|
-
const picked = {};
|
|
432
|
-
for (const name of allowlist) if (env[name] !== void 0) picked[name] = env[name];
|
|
433
|
-
return picked;
|
|
434
|
-
}
|
|
435
|
-
/**
|
|
436
|
-
* Expand `${VAR}` and `${VAR:-default}` references in `value`. Missing
|
|
437
|
-
* variables (unset, with no default) are left untouched and reported by name in
|
|
438
|
-
* `missing` so callers can skip the server without ever logging a value.
|
|
439
|
-
*
|
|
440
|
-
* `${VAR:-default}` follows POSIX: the default applies when `VAR` is unset *or*
|
|
441
|
-
* empty. Bare `${VAR}` expands to an empty string when `VAR` is set but empty.
|
|
442
|
-
*/
|
|
443
|
-
function expandMcpTemplate(value, vars) {
|
|
444
|
-
const missing = [];
|
|
445
|
-
return {
|
|
446
|
-
value: value.replace(TEMPLATE_PATTERN, (match, name, fallback) => {
|
|
447
|
-
const current = vars[name];
|
|
448
|
-
if (fallback !== void 0) return current !== void 0 && current !== "" ? current : fallback;
|
|
449
|
-
if (current !== void 0) return current;
|
|
450
|
-
if (!missing.includes(name)) missing.push(name);
|
|
451
|
-
return match;
|
|
452
|
-
}),
|
|
453
|
-
missing
|
|
454
|
-
};
|
|
455
|
-
}
|
|
456
|
-
/**
|
|
457
|
-
* Extract the server map from a parsed `.mcp.json`-style document. Two shapes
|
|
458
|
-
* are accepted:
|
|
459
|
-
*
|
|
460
|
-
* - Claude Code project shape: `{ "mcpServers": { name: server } }`
|
|
461
|
-
* - Plugin shape: `{ name: server }` (servers at the top level)
|
|
462
|
-
*
|
|
463
|
-
* The project shape is detected by a top-level `mcpServers` object. Returns
|
|
464
|
-
* `null` when the document is not an object at all.
|
|
465
|
-
*/
|
|
466
|
-
function extractMcpServerMap(raw) {
|
|
467
|
-
if (!isRecord$1(raw)) return null;
|
|
468
|
-
if (isRecord$1(raw.mcpServers)) return raw.mcpServers;
|
|
469
|
-
return raw;
|
|
470
|
-
}
|
|
471
|
-
function stringList(value) {
|
|
472
|
-
return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
|
|
473
|
-
}
|
|
474
|
-
function stringMap(value) {
|
|
475
|
-
if (!isRecord$1(value)) return {};
|
|
476
|
-
const out = {};
|
|
477
|
-
for (const [key, entry] of Object.entries(value)) if (typeof entry === "string") out[key] = entry;
|
|
478
|
-
return out;
|
|
479
|
-
}
|
|
480
|
-
/**
|
|
481
|
-
* Drop headers whose value is empty or whitespace-only.
|
|
482
|
-
*
|
|
483
|
-
* A header value is routinely a `${VAR}` or `${VAR:-}` reference to a
|
|
484
|
-
* credential that is simply absent — an optional API key, or a token only set
|
|
485
|
-
* in CI. Sending `Authorization:` with no value is worse than not sending it:
|
|
486
|
-
* some servers reject the malformed header outright where they would have
|
|
487
|
-
* served the request anonymously. So an empty expansion means "no header",
|
|
488
|
-
* not "empty header". `env` for stdio servers is deliberately left alone: an
|
|
489
|
-
* empty environment variable is a meaningful, distinct value there.
|
|
490
|
-
*/
|
|
491
|
-
function dropEmptyHeaders(headers) {
|
|
492
|
-
return Object.fromEntries(Object.entries(headers).filter(([, value]) => value.trim() !== ""));
|
|
493
|
-
}
|
|
494
|
-
/** Read the MCP disable lists from a parsed `.claude/settings.json` document. */
|
|
495
|
-
function parseMcpDisableFilters(raw) {
|
|
496
|
-
if (!isRecord$1(raw)) return {
|
|
497
|
-
disabledMcpjsonServers: [],
|
|
498
|
-
disabledMcpServers: []
|
|
499
|
-
};
|
|
500
|
-
return {
|
|
501
|
-
disabledMcpjsonServers: stringList(raw.disabledMcpjsonServers),
|
|
502
|
-
disabledMcpServers: stringList(raw.disabledMcpServers)
|
|
503
|
-
};
|
|
504
|
-
}
|
|
505
|
-
function createExpander(vars) {
|
|
506
|
-
const missing = /* @__PURE__ */ new Set();
|
|
507
|
-
return {
|
|
508
|
-
missing,
|
|
509
|
-
expand(value) {
|
|
510
|
-
const result = expandMcpTemplate(value, vars);
|
|
511
|
-
for (const name of result.missing) missing.add(name);
|
|
512
|
-
return result.value;
|
|
513
|
-
}
|
|
514
|
-
};
|
|
515
|
-
}
|
|
516
|
-
function describeSource(source) {
|
|
517
|
-
return source.kind === "marketplace" ? `${source.marketplace}:${source.plugin}` : source.path;
|
|
518
|
-
}
|
|
519
|
-
/**
|
|
520
|
-
* Normalise one raw server entry. Returns `null` (after warning) when the
|
|
521
|
-
* server is unsupported or incomplete:
|
|
522
|
-
*
|
|
523
|
-
* - `type: sse` or `ws`, or any `oauth` / `headersHelper` field — unsupported
|
|
524
|
-
* transports and auth flows
|
|
525
|
-
* - no `command` for stdio, no `url` for http, before or after expansion
|
|
526
|
-
* - a `${VAR}` reference with no value and no default (the warning names the
|
|
527
|
-
* variable, never a value)
|
|
528
|
-
*
|
|
529
|
-
* `type` defaults to `stdio` when `command` is present and `http` when `url`
|
|
530
|
-
* is present. A server-declared `timeout` is clamped to `MAX_MCP_TIMEOUT_MS`.
|
|
531
|
-
*/
|
|
532
|
-
function normalizeMcpServer(name, raw, source, options = {}) {
|
|
533
|
-
const warn = options.warn ?? (() => {});
|
|
534
|
-
const where = describeSource(source);
|
|
535
|
-
if (!isRecord$1(raw)) {
|
|
536
|
-
warn(`MCP server "${name}" in ${where} is not an object — skipped.`);
|
|
537
|
-
return null;
|
|
538
|
-
}
|
|
539
|
-
if (raw.oauth !== void 0 || raw.headersHelper !== void 0) {
|
|
540
|
-
warn(`MCP server "${name}" in ${where} uses "${raw.oauth !== void 0 ? "oauth" : "headersHelper"}", which is not supported — skipped.`);
|
|
541
|
-
return null;
|
|
542
|
-
}
|
|
543
|
-
const hasCommand = typeof raw.command === "string" && raw.command.length > 0;
|
|
544
|
-
const hasUrl = typeof raw.url === "string" && raw.url.length > 0;
|
|
545
|
-
let type;
|
|
546
|
-
if (typeof raw.type === "string") {
|
|
547
|
-
type = raw.type;
|
|
548
|
-
if (!KNOWN_TYPES.has(type)) {
|
|
549
|
-
warn(`MCP server "${name}" in ${where} has unknown type "${type}" — skipped.`);
|
|
550
|
-
return null;
|
|
551
|
-
}
|
|
552
|
-
} else if (hasCommand) type = "stdio";
|
|
553
|
-
else if (hasUrl) type = "http";
|
|
554
|
-
else {
|
|
555
|
-
warn(`MCP server "${name}" in ${where} has neither "command" nor "url" — skipped.`);
|
|
556
|
-
return null;
|
|
557
|
-
}
|
|
558
|
-
if (type === "sse" || type === "ws") {
|
|
559
|
-
warn(`MCP server "${name}" in ${where} uses the ${type} transport, which is not supported — skipped.`);
|
|
560
|
-
return null;
|
|
561
|
-
}
|
|
562
|
-
if (type === "stdio" && !hasCommand) {
|
|
563
|
-
warn(`MCP server "${name}" in ${where} is stdio but has no "command" — skipped.`);
|
|
564
|
-
return null;
|
|
565
|
-
}
|
|
566
|
-
if (type !== "stdio" && !hasUrl) {
|
|
567
|
-
warn(`MCP server "${name}" in ${where} is ${type} but has no "url" — skipped.`);
|
|
568
|
-
return null;
|
|
569
|
-
}
|
|
570
|
-
const expander = createExpander({
|
|
571
|
-
...options.vars,
|
|
572
|
-
...options.pluginRoot === void 0 ? {} : { CLAUDE_PLUGIN_ROOT: options.pluginRoot }
|
|
573
|
-
});
|
|
574
|
-
const expandMap = (map) => Object.fromEntries(Object.entries(map).map(([k, v]) => [k, expander.expand(v)]));
|
|
575
|
-
const config = {
|
|
576
|
-
name,
|
|
577
|
-
type,
|
|
578
|
-
args: [],
|
|
579
|
-
env: {},
|
|
580
|
-
headers: {},
|
|
581
|
-
source
|
|
582
|
-
};
|
|
583
|
-
if (type === "stdio") {
|
|
584
|
-
config.command = expander.expand(raw.command);
|
|
585
|
-
config.args = stringList(raw.args).map((arg) => expander.expand(arg));
|
|
586
|
-
config.env = expandMap(stringMap(raw.env));
|
|
587
|
-
} else {
|
|
588
|
-
config.url = expander.expand(raw.url);
|
|
589
|
-
config.headers = dropEmptyHeaders(expandMap(stringMap(raw.headers)));
|
|
590
|
-
}
|
|
591
|
-
if (typeof raw.timeout === "number" && Number.isFinite(raw.timeout) && raw.timeout > 0) config.timeoutMs = Math.min(raw.timeout, MAX_MCP_TIMEOUT_MS);
|
|
592
|
-
if (expander.missing.size > 0) {
|
|
593
|
-
warn(`MCP server "${name}" in ${where} references unset environment variable(s) ${[...expander.missing].map((v) => `\${${v}}`).join(", ")} — skipped. Set them or add a default with \${VAR:-default}, and allow them with --mcp-env / CODE_REVIEW_MCP_ENV.`);
|
|
594
|
-
return null;
|
|
595
|
-
}
|
|
596
|
-
if (type === "stdio" && !config.command) {
|
|
597
|
-
warn(`MCP server "${name}" in ${where} expands to an empty "command" — skipped.`);
|
|
598
|
-
return null;
|
|
599
|
-
}
|
|
600
|
-
if (type !== "stdio" && !config.url) {
|
|
601
|
-
warn(`MCP server "${name}" in ${where} expands to an empty "url" — skipped.`);
|
|
602
|
-
return null;
|
|
603
|
-
}
|
|
604
|
-
return config;
|
|
605
|
-
}
|
|
606
|
-
/**
|
|
607
|
-
* Parse a whole `.mcp.json`-style document (either shape) into normalised
|
|
608
|
-
* server configs. Invalid entries are skipped with a warning.
|
|
609
|
-
*/
|
|
610
|
-
function parseMcpServers(raw, source, options = {}) {
|
|
611
|
-
const map = extractMcpServerMap(raw);
|
|
612
|
-
if (!map) {
|
|
613
|
-
options.warn?.(`MCP config in ${describeSource(source)} is not a JSON object — skipped.`);
|
|
614
|
-
return [];
|
|
615
|
-
}
|
|
616
|
-
const servers = [];
|
|
617
|
-
for (const [name, entry] of Object.entries(map)) {
|
|
618
|
-
const server = normalizeMcpServer(name, entry, source, options);
|
|
619
|
-
if (server) servers.push(server);
|
|
620
|
-
}
|
|
621
|
-
return servers;
|
|
622
|
-
}
|
|
623
|
-
/** Drop servers named in either disable list. */
|
|
624
|
-
function applyMcpDisableFilters(servers, filters) {
|
|
625
|
-
const disabled = /* @__PURE__ */ new Set([...filters.disabledMcpjsonServers, ...filters.disabledMcpServers]);
|
|
626
|
-
return servers.filter((server) => !disabled.has(server.name));
|
|
627
|
-
}
|
|
628
|
-
//#endregion
|
|
629
|
-
//#region src/git.ts
|
|
630
|
-
var exec$1 = promisify(execFile);
|
|
631
|
-
var DEFAULT_DIFF_CONTEXT = 20;
|
|
632
|
-
var DEFAULT_CODEQUALITY_ARTIFACTS = [
|
|
633
|
-
"gl-code-quality-report.json",
|
|
634
|
-
"codequality.json",
|
|
635
|
-
"codeclimate.json",
|
|
636
|
-
"code-quality-report.json"
|
|
637
|
-
];
|
|
638
|
-
function gitErrorMessage(error) {
|
|
639
|
-
const err = error;
|
|
640
|
-
return [
|
|
641
|
-
err.message,
|
|
642
|
-
err.stderr,
|
|
643
|
-
err.stdout
|
|
644
|
-
].filter(Boolean).join("\n").trim();
|
|
645
|
-
}
|
|
646
|
-
async function git$1(args, options = {}) {
|
|
647
|
-
try {
|
|
648
|
-
const { stdout } = await exec$1("git", args, {
|
|
649
|
-
cwd: options.cwd,
|
|
650
|
-
maxBuffer: 52428800
|
|
651
|
-
});
|
|
652
|
-
return stdout;
|
|
653
|
-
} catch (error) {
|
|
654
|
-
throw new GitError(`git ${args.join(" ")} failed.`, {
|
|
655
|
-
cause: error,
|
|
656
|
-
hint: gitErrorMessage(error)
|
|
657
|
-
});
|
|
658
|
-
}
|
|
659
|
-
}
|
|
660
|
-
function remoteRef(remote, branch) {
|
|
661
|
-
return `refs/remotes/${remote}/${branch}`;
|
|
662
|
-
}
|
|
663
|
-
/**
|
|
664
|
-
* Diff the target branch with the MR head commit, not `HEAD`: CI checks out a
|
|
665
|
-
* merge commit (GitHub `refs/pull/N/merge`, GitLab merged results) whose base
|
|
666
|
-
* can be stale, and then `HEAD` carries commits the MR does not change.
|
|
667
|
-
*/
|
|
668
|
-
function getMergeDiffArguments(targetBranch, headSha, options = {}) {
|
|
669
|
-
const remote = options.remote ?? "origin";
|
|
670
|
-
const context = options.context ?? DEFAULT_DIFF_CONTEXT;
|
|
671
|
-
return [
|
|
672
|
-
`${remoteRef(remote, targetBranch)}...${headSha}`,
|
|
673
|
-
`--unified=${context}`,
|
|
674
|
-
"--"
|
|
675
|
-
];
|
|
676
|
-
}
|
|
677
|
-
/**
|
|
678
|
-
* Full git argv for the merge diff. `-c core.quotepath=false` keeps non-ASCII
|
|
679
|
-
* paths literal instead of git's default octal-escaped + double-quoted form
|
|
680
|
-
* (`"a/caf\303\251.ts"`), which the comment-position parser cannot match —
|
|
681
|
-
* leaving such comments with invalid one-sided positions that 500 on
|
|
682
|
-
* `bulk_publish`. Diffing literally also gives the reviewer readable paths.
|
|
683
|
-
*/
|
|
684
|
-
function getMergeDiffCommand(targetBranch, headSha, options = {}) {
|
|
685
|
-
return [
|
|
686
|
-
"-c",
|
|
687
|
-
"core.quotepath=false",
|
|
688
|
-
"diff",
|
|
689
|
-
...getMergeDiffArguments(targetBranch, headSha, options)
|
|
690
|
-
];
|
|
691
|
-
}
|
|
692
|
-
async function fetchBranch(remote, branch, options) {
|
|
693
|
-
await git$1([
|
|
694
|
-
"fetch",
|
|
695
|
-
"--no-tags",
|
|
696
|
-
remote,
|
|
697
|
-
`+refs/heads/${branch}:${remoteRef(remote, branch)}`
|
|
698
|
-
], options);
|
|
699
|
-
}
|
|
700
|
-
async function isTracked(path, options) {
|
|
701
|
-
try {
|
|
702
|
-
await git$1([
|
|
703
|
-
"ls-files",
|
|
704
|
-
"--error-unmatch",
|
|
705
|
-
"--",
|
|
706
|
-
path
|
|
707
|
-
], options);
|
|
708
|
-
return true;
|
|
709
|
-
} catch {
|
|
710
|
-
return false;
|
|
711
|
-
}
|
|
712
|
-
}
|
|
713
|
-
async function removeGeneratedCodeQualityArtifacts(paths = DEFAULT_CODEQUALITY_ARTIFACTS, options = {}) {
|
|
714
|
-
const removed = [];
|
|
715
|
-
for (const path of paths) {
|
|
716
|
-
if (await isTracked(path, options)) continue;
|
|
717
|
-
try {
|
|
718
|
-
await unlink(options.cwd ? join(options.cwd, path) : path);
|
|
719
|
-
removed.push(path);
|
|
720
|
-
} catch (error) {
|
|
721
|
-
if (error.code !== "ENOENT") throw error;
|
|
722
|
-
}
|
|
723
|
-
}
|
|
724
|
-
return removed;
|
|
725
|
-
}
|
|
726
|
-
async function prepareGitHistory(sourceBranch, targetBranch, headSha, options = {}) {
|
|
727
|
-
const remote = options.remote ?? "origin";
|
|
728
|
-
await removeGeneratedCodeQualityArtifacts(options.codeQualityArtifacts, options);
|
|
729
|
-
await git$1([
|
|
730
|
-
"fetch",
|
|
731
|
-
"--unshallow",
|
|
732
|
-
"--no-tags",
|
|
733
|
-
remote
|
|
734
|
-
], options).catch(() => void 0);
|
|
735
|
-
const fetchErrors = [];
|
|
736
|
-
for (const branch of [targetBranch, sourceBranch]) try {
|
|
737
|
-
await fetchBranch(remote, branch, options);
|
|
738
|
-
} catch (error) {
|
|
739
|
-
fetchErrors.push(`${branch}: ${gitErrorMessage(error)}`);
|
|
740
|
-
}
|
|
741
|
-
if (fetchErrors.length === 2) throw new GitError(`Unable to fetch MR source/target branches from ${remote}.`, { hint: fetchErrors.join("\n") });
|
|
742
|
-
try {
|
|
743
|
-
await git$1([
|
|
744
|
-
"merge-base",
|
|
745
|
-
remoteRef(remote, targetBranch),
|
|
746
|
-
headSha
|
|
747
|
-
], options);
|
|
748
|
-
} catch (error) {
|
|
749
|
-
const fetchDetail = fetchErrors.length > 0 ? `\nFetch warnings:\n${fetchErrors.join("\n")}` : "";
|
|
750
|
-
throw new GitError(`Unable to prepare Git history for MR review: merge-base ${remoteRef(remote, targetBranch)} ${headSha} failed.`, {
|
|
751
|
-
cause: error,
|
|
752
|
-
hint: `Set GIT_DEPTH: 0 or ensure ${remote}/${targetBranch} and ${remote}/${sourceBranch} are fetchable.${fetchDetail}\n${gitErrorMessage(error)}`
|
|
753
|
-
});
|
|
754
|
-
}
|
|
755
|
-
}
|
|
756
|
-
async function getMergeDiff(targetBranch, headSha, options = {}) {
|
|
757
|
-
return git$1(getMergeDiffCommand(targetBranch, headSha, options), options);
|
|
758
|
-
}
|
|
759
|
-
function getMergeCommitLogArguments(targetBranch, headSha, options = {}) {
|
|
760
|
-
return [
|
|
761
|
-
`${remoteRef(options.remote ?? "origin", targetBranch)}...${headSha}`,
|
|
762
|
-
"--pretty=tformat:commit %h%nAuthor: %an%nDate: %as%n%n%s%n%n%b",
|
|
763
|
-
"--reverse",
|
|
764
|
-
"--no-merges"
|
|
765
|
-
];
|
|
766
|
-
}
|
|
767
|
-
async function getMergeCommitLog(targetBranch, headSha, options = {}) {
|
|
768
|
-
return git$1(["log", ...getMergeCommitLogArguments(targetBranch, headSha, options)], options);
|
|
769
|
-
}
|
|
770
|
-
/**
|
|
771
|
-
* Summarize a unified diff into file/line counts for telemetry. Counts one file
|
|
772
|
-
* per `diff --git` header and counts `+`/`-` lines only inside a hunk (after a
|
|
773
|
-
* `@@` header), so the `--- a/file` / `+++ b/file` header lines are excluded and
|
|
774
|
-
* a genuine content line whose text starts with `++`/`--` is still counted. Pure
|
|
775
|
-
* and allocation-light so it can run on the full merge diff without an extra git
|
|
776
|
-
* invocation.
|
|
777
|
-
*/
|
|
778
|
-
function summarizeDiff(diff) {
|
|
779
|
-
let filesChanged = 0;
|
|
780
|
-
let linesAdded = 0;
|
|
781
|
-
let linesRemoved = 0;
|
|
782
|
-
let inHunk = false;
|
|
783
|
-
for (const line of diff.split("\n")) if (line.startsWith("diff --git ")) {
|
|
784
|
-
filesChanged += 1;
|
|
785
|
-
inHunk = false;
|
|
786
|
-
} else if (line.startsWith("@@ ")) inHunk = true;
|
|
787
|
-
else if (inHunk && line.startsWith("+")) linesAdded += 1;
|
|
788
|
-
else if (inHunk && line.startsWith("-")) linesRemoved += 1;
|
|
789
|
-
return {
|
|
790
|
-
filesChanged,
|
|
791
|
-
linesAdded,
|
|
792
|
-
linesRemoved
|
|
793
|
-
};
|
|
794
|
-
}
|
|
795
|
-
//#endregion
|
|
796
|
-
//#region src/skills.ts
|
|
797
|
-
/** Normalize a filesystem-relative path to the POSIX form used in URLs. */
|
|
798
|
-
function toPosixPath(path) {
|
|
799
|
-
return sep === "/" ? path : path.split(sep).join("/");
|
|
800
|
-
}
|
|
801
|
-
var SKILL_DIRS = [".agents/skills", ".claude/skills"];
|
|
802
|
-
var RESOURCE_DIRS = ["references"];
|
|
803
|
-
function parseFrontmatter(content) {
|
|
804
|
-
const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
|
|
805
|
-
if (!match) return null;
|
|
806
|
-
let data;
|
|
807
|
-
try {
|
|
808
|
-
data = parse(match[1]);
|
|
809
|
-
} catch {
|
|
810
|
-
return null;
|
|
811
|
-
}
|
|
812
|
-
if (!data || typeof data !== "object") return null;
|
|
813
|
-
const { name, description } = data;
|
|
814
|
-
if (typeof name !== "string" || typeof description !== "string") return null;
|
|
815
|
-
const trimmedName = name.trim();
|
|
816
|
-
const trimmedDescription = description.trim();
|
|
817
|
-
if (!trimmedName || !trimmedDescription) return null;
|
|
818
|
-
return {
|
|
819
|
-
name: trimmedName,
|
|
820
|
-
description: trimmedDescription
|
|
821
|
-
};
|
|
822
|
-
}
|
|
823
|
-
async function loadSkillFromDir(dirPath, origin) {
|
|
824
|
-
const skillMdPath = join(dirPath, "SKILL.md");
|
|
825
|
-
let content;
|
|
826
|
-
try {
|
|
827
|
-
content = await readFile(skillMdPath, "utf8");
|
|
828
|
-
} catch {
|
|
829
|
-
return null;
|
|
830
|
-
}
|
|
831
|
-
const parsed = parseFrontmatter(content);
|
|
832
|
-
if (!parsed) return null;
|
|
833
|
-
const resourceDirs = RESOURCE_DIRS.filter((d) => existsSync(join(dirPath, d)));
|
|
834
|
-
return {
|
|
835
|
-
name: parsed.name,
|
|
836
|
-
description: parsed.description,
|
|
837
|
-
filePath: skillMdPath,
|
|
838
|
-
rootDir: dirPath,
|
|
839
|
-
resourceDirs,
|
|
840
|
-
origin
|
|
841
|
-
};
|
|
842
|
-
}
|
|
843
|
-
function resolveBuiltinSkillsDir() {
|
|
844
|
-
return join(dirname(fileURLToPath(import.meta.url)), "..", "skills");
|
|
845
|
-
}
|
|
846
|
-
async function loadBuiltinSkill(name) {
|
|
847
|
-
return loadSkillFromDir(join(resolveBuiltinSkillsDir(), name), {
|
|
848
|
-
kind: "builtin",
|
|
849
|
-
name
|
|
850
|
-
});
|
|
851
|
-
}
|
|
852
|
-
async function loadAutoDiscoveredSkills(cwd, gitRoot, warn) {
|
|
853
|
-
const dirs = [];
|
|
854
|
-
let current = cwd;
|
|
855
|
-
while (true) {
|
|
856
|
-
dirs.unshift(current);
|
|
857
|
-
if (current === gitRoot) break;
|
|
858
|
-
const parent = dirname(current);
|
|
859
|
-
if (parent === current) break;
|
|
860
|
-
current = parent;
|
|
861
|
-
}
|
|
862
|
-
const found = /* @__PURE__ */ new Map();
|
|
863
|
-
for (const dir of dirs) for (const skillDir of SKILL_DIRS) {
|
|
864
|
-
const skillsPath = join(dir, skillDir);
|
|
865
|
-
let entries;
|
|
866
|
-
try {
|
|
867
|
-
entries = await readdir(skillsPath);
|
|
868
|
-
} catch {
|
|
869
|
-
continue;
|
|
870
|
-
}
|
|
871
|
-
for (const entry of entries) {
|
|
872
|
-
const entryPath = join(skillsPath, entry);
|
|
873
|
-
const skill = await loadSkillFromDir(entryPath, {
|
|
874
|
-
kind: "project",
|
|
875
|
-
path: toPosixPath(relative(gitRoot, entryPath))
|
|
876
|
-
});
|
|
877
|
-
if (skill) found.set(skill.name, skill);
|
|
878
|
-
else if (warn && existsSync(join(entryPath, "SKILL.md"))) warn(`Skill at ${entryPath} has a SKILL.md but is missing required frontmatter fields (name, description) — skill not loaded.`);
|
|
879
|
-
}
|
|
880
|
-
}
|
|
881
|
-
return [...found.values()];
|
|
882
|
-
}
|
|
883
|
-
/**
|
|
884
|
-
* Parse a skill spec string into a typed `SkillSpec` descriptor.
|
|
885
|
-
*
|
|
886
|
-
* Supported spec formats:
|
|
887
|
-
*
|
|
888
|
-
* | Input | Result |
|
|
889
|
-
* |------------------------------------|---------------------------------------------------|
|
|
890
|
-
* | `code-review` | `{ protocol: 'builtin', name: 'code-review' }` |
|
|
891
|
-
* | `npm:my-skill` | `{ protocol: 'npm', packageName: 'my-skill', ... }`|
|
|
892
|
-
* | `npm:@scope/pkg` | `{ protocol: 'npm', packageName: '@scope/pkg', ... }`|
|
|
893
|
-
* | `npm:@scope/bundle/security` | `{ protocol: 'npm', packageName: '@scope/bundle', subpath: 'security' }`|
|
|
894
|
-
* | `npm:bundle/security` | `{ protocol: 'npm', packageName: 'bundle', subpath: 'security' }`|
|
|
895
|
-
* | `file:./path/to/skill` | `{ protocol: 'file', path: './path/to/skill' }` |
|
|
896
|
-
* | `file:/absolute/path` | `{ protocol: 'file', path: '/absolute/path' }` |
|
|
897
|
-
* | `git:https://host/org/s.git` | `{ protocol: 'git', url: 'https://host/org/s.git', ref: '', subpath: '' }` |
|
|
898
|
-
* | `git:https://host/org/b.git#v1/sec`| `{ protocol: 'git', url: 'https://host/org/b.git', ref: 'v1', subpath: 'sec' }` |
|
|
899
|
-
* | `git+ssh://git@host/org/s.git` | `{ protocol: 'git', url: 'ssh://git@host/org/s.git', ref: '', subpath: '' }` |
|
|
900
|
-
* | `acme:dev/aria-apg` (acme known) | `{ protocol: 'marketplace', marketplace: 'acme', plugin: 'dev', skill: 'aria-apg' }` |
|
|
901
|
-
*
|
|
902
|
-
* A spec whose portion before the first `:` matches a registered marketplace
|
|
903
|
-
* name (from `knownMarketplaces`) is parsed as a `marketplace` reference. The
|
|
904
|
-
* remainder must be `<plugin>/<skill>` — an explicit skill is always required.
|
|
905
|
-
*/
|
|
906
|
-
function parseSkillSpec(spec, knownMarketplaces = /* @__PURE__ */ new Set()) {
|
|
907
|
-
if (spec.startsWith("file:")) return {
|
|
908
|
-
protocol: "file",
|
|
909
|
-
path: spec.slice(5)
|
|
910
|
-
};
|
|
911
|
-
if (spec.startsWith("npm:")) {
|
|
912
|
-
const rest = spec.slice(4);
|
|
913
|
-
if (rest.startsWith("@")) {
|
|
914
|
-
const parts = rest.split("/");
|
|
915
|
-
if (parts.length < 2) return {
|
|
916
|
-
protocol: "npm",
|
|
917
|
-
packageName: rest,
|
|
918
|
-
subpath: ""
|
|
919
|
-
};
|
|
920
|
-
return {
|
|
921
|
-
protocol: "npm",
|
|
922
|
-
packageName: `${parts[0]}/${parts[1]}`,
|
|
923
|
-
subpath: parts.slice(2).join("/")
|
|
924
|
-
};
|
|
925
|
-
}
|
|
926
|
-
const slashIdx = rest.indexOf("/");
|
|
927
|
-
if (slashIdx === -1) return {
|
|
928
|
-
protocol: "npm",
|
|
929
|
-
packageName: rest,
|
|
930
|
-
subpath: ""
|
|
931
|
-
};
|
|
932
|
-
return {
|
|
933
|
-
protocol: "npm",
|
|
934
|
-
packageName: rest.slice(0, slashIdx),
|
|
935
|
-
subpath: rest.slice(slashIdx + 1)
|
|
936
|
-
};
|
|
937
|
-
}
|
|
938
|
-
if (spec.startsWith("git+") || spec.startsWith("git:")) return parseGitSpec(spec);
|
|
939
|
-
const colonIdx = spec.indexOf(":");
|
|
940
|
-
if (colonIdx > 0 && knownMarketplaces.has(spec.slice(0, colonIdx))) return parseMarketplaceSkillSpec(spec, colonIdx);
|
|
941
|
-
return {
|
|
942
|
-
protocol: "builtin",
|
|
943
|
-
name: spec
|
|
944
|
-
};
|
|
945
|
-
}
|
|
946
|
-
/**
|
|
947
|
-
* Parse the `<marketplace>:<plugin>/<skill>` selector into its parts. The
|
|
948
|
-
* marketplace name has already been matched against the registry by the caller;
|
|
949
|
-
* `colonIdx` is the index of the separating `:`. Throws a `ConfigError` when the
|
|
950
|
-
* `<plugin>/<skill>` remainder is malformed (a skill name is always required).
|
|
951
|
-
*/
|
|
952
|
-
function parseMarketplaceSkillSpec(spec, colonIdx) {
|
|
953
|
-
const marketplace = spec.slice(0, colonIdx);
|
|
954
|
-
const rest = spec.slice(colonIdx + 1);
|
|
955
|
-
const slashIdx = rest.indexOf("/");
|
|
956
|
-
const plugin = slashIdx === -1 ? rest : rest.slice(0, slashIdx);
|
|
957
|
-
const skill = slashIdx === -1 ? "" : rest.slice(slashIdx + 1);
|
|
958
|
-
if (!plugin || !skill || skill.includes("/")) throw new ConfigError(`Cannot load skill: "${spec}"`, { hint: `Marketplace skills use the form "<marketplace>:<plugin>/<skill>", e.g. "${marketplace}:dev/aria-apg".` });
|
|
959
|
-
return {
|
|
960
|
-
protocol: "marketplace",
|
|
961
|
-
marketplace,
|
|
962
|
-
plugin,
|
|
963
|
-
skill
|
|
964
|
-
};
|
|
965
|
-
}
|
|
966
|
-
/**
|
|
967
|
-
* Parse a `git:` / `git+ssh:` skill spec into its URL, pinned ref, and subpath.
|
|
968
|
-
*
|
|
969
|
-
* - `git:<url>` strips the `git:` marker; what follows is the clone URL
|
|
970
|
-
* (e.g. `git:https://host/org/repo.git`).
|
|
971
|
-
* - `git+<transport>://…` strips the leading `git+`, leaving a URL git
|
|
972
|
-
* understands directly (`git+ssh://git@host/…` → `ssh://git@host/…`), matching
|
|
973
|
-
* npm's `package.json` git-dependency convention.
|
|
974
|
-
*
|
|
975
|
-
* An optional `#<ref>[/<subpath>]` fragment pins the ref (tag, branch, or
|
|
976
|
-
* commit) and, after the first `/`, points at a skill directory inside the repo.
|
|
977
|
-
*/
|
|
978
|
-
function parseGitSpec(spec) {
|
|
979
|
-
const raw = spec.startsWith("git+") ? spec.slice(4) : spec.slice(4);
|
|
980
|
-
let parsed;
|
|
981
|
-
try {
|
|
982
|
-
parsed = new URL(raw);
|
|
983
|
-
} catch {
|
|
984
|
-
return {
|
|
985
|
-
protocol: "git",
|
|
986
|
-
url: raw,
|
|
987
|
-
ref: "",
|
|
988
|
-
subpath: ""
|
|
989
|
-
};
|
|
990
|
-
}
|
|
991
|
-
const fragment = parsed.hash ? parsed.hash.slice(1) : "";
|
|
992
|
-
parsed.hash = "";
|
|
993
|
-
const url = parsed.toString();
|
|
994
|
-
const slashIdx = fragment.indexOf("/");
|
|
995
|
-
if (slashIdx === -1) return {
|
|
996
|
-
protocol: "git",
|
|
997
|
-
url,
|
|
998
|
-
ref: fragment,
|
|
999
|
-
subpath: ""
|
|
1000
|
-
};
|
|
1001
|
-
return {
|
|
1002
|
-
protocol: "git",
|
|
1003
|
-
url,
|
|
1004
|
-
ref: fragment.slice(0, slashIdx),
|
|
1005
|
-
subpath: fragment.slice(slashIdx + 1)
|
|
1006
|
-
};
|
|
1007
|
-
}
|
|
1008
|
-
/**
|
|
1009
|
-
* Resolve the directory for an npm-installed skill by walking `node_modules`
|
|
1010
|
-
* upward from `cwd` (supports monorepo hoisting). Returns the resolved path
|
|
1011
|
-
* or `null` if the package / subpath cannot be found.
|
|
1012
|
-
*/
|
|
1013
|
-
async function resolveNpmSkillDir(packageName, subpath, cwd) {
|
|
1014
|
-
let current = cwd;
|
|
1015
|
-
while (true) {
|
|
1016
|
-
const candidate = subpath ? join(current, "node_modules", packageName, subpath) : join(current, "node_modules", packageName);
|
|
1017
|
-
if (existsSync(candidate)) return candidate;
|
|
1018
|
-
const parent = dirname(current);
|
|
1019
|
-
if (parent === current) break;
|
|
1020
|
-
current = parent;
|
|
1021
|
-
}
|
|
1022
|
-
return null;
|
|
1023
|
-
}
|
|
1024
|
-
/** Strip a leading `git+` transport marker (`git+ssh://…` → `ssh://…`). */
|
|
1025
|
-
function normalizeGitUrl(raw) {
|
|
1026
|
-
return raw.startsWith("git+") ? raw.slice(4) : raw;
|
|
1027
|
-
}
|
|
1028
|
-
/**
|
|
1029
|
-
* Remove embedded credentials from a URL so it is safe to show in logs, hints,
|
|
1030
|
-
* and errors. `https://user:token@host/path` becomes `https://***@host/path`.
|
|
1031
|
-
* Non-URL strings are returned with a best-effort `//user@` → `//***@` scrub.
|
|
1032
|
-
*/
|
|
1033
|
-
function redactUrl(url) {
|
|
1034
|
-
try {
|
|
1035
|
-
const parsed = new URL(url);
|
|
1036
|
-
if (parsed.username || parsed.password) {
|
|
1037
|
-
parsed.username = "***";
|
|
1038
|
-
parsed.password = "";
|
|
1039
|
-
}
|
|
1040
|
-
return parsed.toString();
|
|
1041
|
-
} catch {
|
|
1042
|
-
return url.replace(/\/\/[^/@]+@/, "//***@");
|
|
1043
|
-
}
|
|
1044
|
-
}
|
|
1045
|
-
/** Base directory for cached git-skill clones (honours `XDG_CACHE_HOME`). */
|
|
1046
|
-
function resolveSkillCacheDir() {
|
|
1047
|
-
const base = process.env.XDG_CACHE_HOME?.trim() || join(homedir(), ".cache");
|
|
1048
|
-
return join(base, "code-review", "skills");
|
|
1049
|
-
}
|
|
1050
|
-
/**
|
|
1051
|
-
* Stable cache-directory name for a git skill. Keyed on the clone URL plus the
|
|
1052
|
-
* pinned ref so that two refs of the same repo never share a cache entry.
|
|
1053
|
-
*/
|
|
1054
|
-
function gitSkillCacheKey(url, ref) {
|
|
1055
|
-
return createHash("sha256").update(`${url}#${ref}`).digest("hex").slice(0, 16);
|
|
1056
|
-
}
|
|
1057
|
-
/**
|
|
1058
|
-
* Shallow-clone `url` at `ref` into `dir`. Using init + a single-ref fetch +
|
|
1059
|
-
* `checkout FETCH_HEAD` (rather than `clone --branch`) means a branch, tag, or
|
|
1060
|
-
* commit SHA all resolve through the same path; an empty `ref` fetches the
|
|
1061
|
-
* remote's default branch via `HEAD`.
|
|
1062
|
-
*/
|
|
1063
|
-
async function gitShallowClone(url, ref, dir) {
|
|
1064
|
-
await git$1([
|
|
1065
|
-
"init",
|
|
1066
|
-
"--quiet",
|
|
1067
|
-
dir
|
|
1068
|
-
]);
|
|
1069
|
-
await git$1([
|
|
1070
|
-
"remote",
|
|
1071
|
-
"add",
|
|
1072
|
-
"origin",
|
|
1073
|
-
url
|
|
1074
|
-
], { cwd: dir });
|
|
1075
|
-
await git$1([
|
|
1076
|
-
"fetch",
|
|
1077
|
-
"--depth",
|
|
1078
|
-
"1",
|
|
1079
|
-
"--quiet",
|
|
1080
|
-
"origin",
|
|
1081
|
-
ref || "HEAD"
|
|
1082
|
-
], { cwd: dir });
|
|
1083
|
-
await git$1([
|
|
1084
|
-
"checkout",
|
|
1085
|
-
"--quiet",
|
|
1086
|
-
"FETCH_HEAD"
|
|
1087
|
-
], { cwd: dir });
|
|
1088
|
-
}
|
|
1089
|
-
/** Monotonic counter making each clone's temp dir unique within the process. */
|
|
1090
|
-
var cloneSeq = 0;
|
|
1091
|
-
/**
|
|
1092
|
-
* Resolve a git URL + ref to a local clone directory, reusing the on-disk cache
|
|
1093
|
-
* when possible. The clone lands in a temp sibling first and is renamed into
|
|
1094
|
-
* place atomically, so a crashed or concurrent clone never leaves a half-written
|
|
1095
|
-
* cache entry. With `refresh`, any cached copy is discarded first. Shared by
|
|
1096
|
-
* `git:` skills and Claude-plugin marketplaces (see `marketplaces.ts`).
|
|
1097
|
-
*/
|
|
1098
|
-
async function cloneGitRepo(url, ref, options) {
|
|
1099
|
-
const repoDir = join(options.cacheDir, gitSkillCacheKey(url, ref));
|
|
1100
|
-
if (options.refresh) await rm(repoDir, {
|
|
1101
|
-
recursive: true,
|
|
1102
|
-
force: true
|
|
1103
|
-
});
|
|
1104
|
-
else if (existsSync(join(repoDir, ".git"))) return repoDir;
|
|
1105
|
-
else if (existsSync(repoDir)) await rm(repoDir, {
|
|
1106
|
-
recursive: true,
|
|
1107
|
-
force: true
|
|
1108
|
-
});
|
|
1109
|
-
await mkdir(options.cacheDir, { recursive: true });
|
|
1110
|
-
const tmpDir = `${repoDir}.tmp-${process.pid}-${cloneSeq += 1}`;
|
|
1111
|
-
await rm(tmpDir, {
|
|
1112
|
-
recursive: true,
|
|
1113
|
-
force: true
|
|
1114
|
-
});
|
|
1115
|
-
try {
|
|
1116
|
-
await gitShallowClone(url, ref, tmpDir);
|
|
1117
|
-
try {
|
|
1118
|
-
await rename(tmpDir, repoDir);
|
|
1119
|
-
} catch (error) {
|
|
1120
|
-
if (existsSync(join(repoDir, ".git"))) {
|
|
1121
|
-
await rm(tmpDir, {
|
|
1122
|
-
recursive: true,
|
|
1123
|
-
force: true
|
|
1124
|
-
});
|
|
1125
|
-
return repoDir;
|
|
1126
|
-
}
|
|
1127
|
-
throw error;
|
|
1128
|
-
}
|
|
1129
|
-
} catch (error) {
|
|
1130
|
-
await rm(tmpDir, {
|
|
1131
|
-
recursive: true,
|
|
1132
|
-
force: true
|
|
1133
|
-
});
|
|
1134
|
-
throw error;
|
|
1135
|
-
}
|
|
1136
|
-
return repoDir;
|
|
1137
|
-
}
|
|
1138
|
-
/**
|
|
1139
|
-
* Load a skill by its spec string (`code-review`, `npm:@scope/pkg`, `file:./path`,
|
|
1140
|
-
* `git:https://…`, …).
|
|
1141
|
-
*
|
|
1142
|
-
* Resolution order:
|
|
1143
|
-
* 1. `builtin` — package-bundled `skills/<name>/`
|
|
1144
|
-
* 2. `npm:` — `node_modules/<packageName>[/subpath]` walked up from `cwd`
|
|
1145
|
-
* 3. `file:` — direct filesystem path (relative paths resolved from `cwd`)
|
|
1146
|
-
* 4. `git:` / `git+ssh:` — shallow clone at the pinned ref, cached on disk,
|
|
1147
|
-
* loading `SKILL.md` from the repo root or the `#<ref>/<subpath>` directory
|
|
1148
|
-
*
|
|
1149
|
-
* Throws a `ConfigError` if the spec cannot be resolved or the resolved
|
|
1150
|
-
* directory does not contain a valid `SKILL.md`.
|
|
1151
|
-
*/
|
|
1152
|
-
async function loadNamedSkill(spec, cwd, options = {}) {
|
|
1153
|
-
const parsed = parseSkillSpec(spec);
|
|
1154
|
-
if (parsed.protocol === "builtin") {
|
|
1155
|
-
const skill = await loadBuiltinSkill(parsed.name);
|
|
1156
|
-
if (!skill) throw new ConfigError(`Cannot load skill: "${spec}"`, { hint: `No built-in skill named "${parsed.name}" was found. Check the skill name, or use npm: / file: to reference external skills.` });
|
|
1157
|
-
return skill;
|
|
1158
|
-
}
|
|
1159
|
-
if (parsed.protocol === "npm") {
|
|
1160
|
-
const dir = await resolveNpmSkillDir(parsed.packageName, parsed.subpath, cwd);
|
|
1161
|
-
if (dir === null) {
|
|
1162
|
-
const pkgRef = parsed.subpath ? `${parsed.packageName} (subpath "${parsed.subpath}")` : parsed.packageName;
|
|
1163
|
-
throw new ConfigError(`Cannot load skill: "${spec}"`, { hint: `Package ${pkgRef} was not found in node_modules. Run \`npm install ${parsed.packageName}\` in the project.` });
|
|
1164
|
-
}
|
|
1165
|
-
const skill = await loadSkillFromDir(dir, {
|
|
1166
|
-
kind: "npm",
|
|
1167
|
-
packageName: parsed.packageName,
|
|
1168
|
-
subpath: parsed.subpath
|
|
1169
|
-
});
|
|
1170
|
-
if (!skill) throw new ConfigError(`Cannot load skill: "${spec}"`, { hint: `The package at ${dir} does not contain a valid SKILL.md.` });
|
|
1171
|
-
return skill;
|
|
1172
|
-
}
|
|
1173
|
-
if (parsed.protocol === "file") {
|
|
1174
|
-
const resolvedPath = parsed.path.startsWith("/") ? parsed.path : join(cwd, parsed.path);
|
|
1175
|
-
const skill = await loadSkillFromDir(resolvedPath, {
|
|
1176
|
-
kind: "file",
|
|
1177
|
-
path: resolvedPath
|
|
1178
|
-
});
|
|
1179
|
-
if (!skill) throw new ConfigError(`Cannot load skill: "${spec}"`, { hint: `No valid SKILL.md was found at "${resolvedPath}". Check that the path points to a skill directory.` });
|
|
1180
|
-
return skill;
|
|
1181
|
-
}
|
|
1182
|
-
if (parsed.protocol === "marketplace") throw new ConfigError(`Cannot load skill: "${spec}"`, { hint: "Marketplace skills must be resolved through a registered marketplace, not loaded directly." });
|
|
1183
|
-
let repoDir;
|
|
1184
|
-
try {
|
|
1185
|
-
repoDir = await cloneGitRepo(parsed.url, parsed.ref, {
|
|
1186
|
-
cacheDir: options.cacheDir ?? resolveSkillCacheDir(),
|
|
1187
|
-
refresh: options.refresh ?? false
|
|
1188
|
-
});
|
|
1189
|
-
} catch (error) {
|
|
1190
|
-
const atRef = parsed.ref ? ` at ref "${parsed.ref}"` : "";
|
|
1191
|
-
throw new ConfigError(`Cannot load skill: "${spec}"`, {
|
|
1192
|
-
cause: error,
|
|
1193
|
-
hint: `Failed to clone "${redactUrl(parsed.url)}"${atRef}. Check the URL, the ref, and your git credentials. For GitLab, prefer the SSH form: git+ssh://git@host/group/project.git`
|
|
1194
|
-
});
|
|
1195
|
-
}
|
|
1196
|
-
const skill = await loadSkillFromDir(parsed.subpath ? join(repoDir, parsed.subpath) : repoDir, {
|
|
1197
|
-
kind: "git",
|
|
1198
|
-
url: parsed.url,
|
|
1199
|
-
ref: parsed.ref,
|
|
1200
|
-
path: parsed.subpath
|
|
1201
|
-
});
|
|
1202
|
-
if (!skill) throw new ConfigError(`Cannot load skill: "${spec}"`, { hint: parsed.subpath ? `The cloned repository has no valid SKILL.md at subpath "${parsed.subpath}".` : "The cloned repository has no valid SKILL.md at its root. If the skill lives in a subdirectory, point at it with \"#<ref>/<subpath>\"." });
|
|
1203
|
-
return skill;
|
|
1204
|
-
}
|
|
1205
|
-
//#endregion
|
|
1206
|
-
//#region src/marketplaces.ts
|
|
1207
|
-
/**
|
|
1208
|
-
* Marketplace manifest formats we know how to read. Different vendors ship the
|
|
1209
|
-
* same open SKILL.md standard but package it differently: Claude Code uses a
|
|
1210
|
-
* `.claude-plugin/marketplace.json` catalog (`anthropic`), OpenAI Codex uses a
|
|
1211
|
-
* `.codex-plugin/` layout (a future `codex` format). Only `anthropic` is
|
|
1212
|
-
* implemented today; the type is the extension point for the rest.
|
|
1213
|
-
*/
|
|
1214
|
-
var MARKETPLACE_FORMATS = ["anthropic"];
|
|
1215
|
-
/** The default format assumed when a marketplace declaration omits a prefix. */
|
|
1216
|
-
var DEFAULT_MARKETPLACE_FORMAT = "anthropic";
|
|
1217
|
-
/**
|
|
1218
|
-
* Marketplace names that collide with skill-spec protocol prefixes
|
|
1219
|
-
* (`npm:`, `file:`, `git:`) or the bare-name builtin lookup, and so cannot be
|
|
1220
|
-
* used as a marketplace name — `<name>:<plugin>/<skill>` would be ambiguous.
|
|
1221
|
-
*/
|
|
1222
|
-
var RESERVED_MARKETPLACE_NAMES = /* @__PURE__ */ new Set([
|
|
1223
|
-
"npm",
|
|
1224
|
-
"file",
|
|
1225
|
-
"git",
|
|
1226
|
-
"builtin"
|
|
1227
|
-
]);
|
|
1228
|
-
var NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
1229
|
-
var FORMAT_PREFIX_PATTERN = /^([a-z][a-z0-9-]*):(?!\/\/)/;
|
|
1230
|
-
/**
|
|
1231
|
-
* Parse a single marketplace declaration: `<name>=<[format:]url[#ref]>`.
|
|
1232
|
-
*
|
|
1233
|
-
* - `acme=https://host/group/tools.git#1.0.0` → default `anthropic` format
|
|
1234
|
-
* - `acme=anthropic:https://host/group/tools.git#1.0.0` → explicit format
|
|
1235
|
-
* - `acme=git+ssh://git@host/group/tools.git#main` → SSH transport
|
|
1236
|
-
*
|
|
1237
|
-
* The `#<ref>` fragment is taken whole as the ref (branch names may contain
|
|
1238
|
-
* `/`). Throws a `ConfigError` with an actionable hint on any malformed input.
|
|
1239
|
-
*/
|
|
1240
|
-
function parseMarketplaceEntry(entry) {
|
|
1241
|
-
const eqIdx = entry.indexOf("=");
|
|
1242
|
-
if (eqIdx <= 0) throw new ConfigError(`Invalid marketplace declaration: "${redactUrl(entry)}"`, { hint: "Use <name>=<git-url>[#ref], e.g. acme=https://host/group/tools.git#1.0.0." });
|
|
1243
|
-
const name = entry.slice(0, eqIdx).trim();
|
|
1244
|
-
if (!NAME_PATTERN.test(name)) throw new ConfigError(`Invalid marketplace name: "${name}"`, { hint: "Names must start with a letter or digit and contain only letters, digits, \".\", \"_\", or \"-\"." });
|
|
1245
|
-
if (RESERVED_MARKETPLACE_NAMES.has(name)) throw new ConfigError(`Marketplace name "${name}" is reserved`, { hint: `Choose another name — ${[...RESERVED_MARKETPLACE_NAMES].join(", ")} collide with skill-spec protocols.` });
|
|
1246
|
-
let rhs = entry.slice(eqIdx + 1).trim();
|
|
1247
|
-
let format = DEFAULT_MARKETPLACE_FORMAT;
|
|
1248
|
-
const formatMatch = rhs.match(FORMAT_PREFIX_PATTERN);
|
|
1249
|
-
if (formatMatch) {
|
|
1250
|
-
const token = formatMatch[1];
|
|
1251
|
-
if (!MARKETPLACE_FORMATS.includes(token)) throw new ConfigError(`Unknown marketplace format "${token}" in "${redactUrl(entry)}"`, { hint: `Supported formats: ${MARKETPLACE_FORMATS.join(", ")}. Omit the prefix (e.g. "${name}=https://…") to default to "${DEFAULT_MARKETPLACE_FORMAT}".` });
|
|
1252
|
-
format = token;
|
|
1253
|
-
rhs = rhs.slice(formatMatch[0].length);
|
|
1254
|
-
}
|
|
1255
|
-
let parsed;
|
|
1256
|
-
try {
|
|
1257
|
-
parsed = new URL(normalizeGitUrl(rhs));
|
|
1258
|
-
} catch {
|
|
1259
|
-
throw new ConfigError(`Invalid marketplace URL for "${name}": "${redactUrl(rhs)}"`, { hint: "Expected a git URL like https://host/group/tools.git or git+ssh://git@host/group/tools.git. scp-style (git@host:group/repo.git) is not supported — use the ssh:// form." });
|
|
1260
|
-
}
|
|
1261
|
-
const ref = parsed.hash ? parsed.hash.slice(1) : "";
|
|
1262
|
-
parsed.hash = "";
|
|
1263
|
-
return {
|
|
1264
|
-
name,
|
|
1265
|
-
format,
|
|
1266
|
-
url: parsed.toString(),
|
|
1267
|
-
ref
|
|
1268
|
-
};
|
|
1269
|
-
}
|
|
1270
|
-
/**
|
|
1271
|
-
* Build a name→ref registry from parsed marketplace declarations, rejecting
|
|
1272
|
-
* duplicate names (a later entry silently shadowing an earlier one is a config
|
|
1273
|
-
* bug worth surfacing).
|
|
1274
|
-
*/
|
|
1275
|
-
function buildMarketplaceRegistry(refs) {
|
|
1276
|
-
const registry = /* @__PURE__ */ new Map();
|
|
1277
|
-
for (const ref of refs) {
|
|
1278
|
-
if (registry.has(ref.name)) throw new ConfigError(`Duplicate marketplace name "${ref.name}"`, { hint: "Each marketplace must be declared once. Remove the duplicate declaration." });
|
|
1279
|
-
registry.set(ref.name, ref);
|
|
1280
|
-
}
|
|
1281
|
-
return registry;
|
|
1282
|
-
}
|
|
1283
|
-
/**
|
|
1284
|
-
* Resolve a `<marketplace>:<plugin>/<skill>` reference to a loaded {@link Skill}.
|
|
1285
|
-
*
|
|
1286
|
-
* Clones the marketplace repo (reusing the shared on-disk clone cache), then
|
|
1287
|
-
* dispatches to the format-specific resolver. Throws a `ConfigError` with a
|
|
1288
|
-
* redacted, actionable hint when the marketplace, plugin, or skill cannot be
|
|
1289
|
-
* resolved — the caller treats that as a skip-and-warn, not a fatal error.
|
|
1290
|
-
*/
|
|
1291
|
-
async function loadMarketplaceSkill(spec, registry, options = {}) {
|
|
1292
|
-
const ref = `${spec.marketplace}:${spec.plugin}/${spec.skill}`;
|
|
1293
|
-
const mp = registry.get(spec.marketplace);
|
|
1294
|
-
if (!mp) throw new ConfigError(`Cannot load skill: "${ref}"`, { hint: `No marketplace named "${spec.marketplace}" is registered. Declare it with CODE_REVIEW_MARKETPLACES or --marketplace.` });
|
|
1295
|
-
let repoDir;
|
|
1296
|
-
try {
|
|
1297
|
-
repoDir = await cloneGitRepo(mp.url, mp.ref, {
|
|
1298
|
-
cacheDir: options.cacheDir ?? resolveSkillCacheDir(),
|
|
1299
|
-
refresh: options.refresh ?? false
|
|
1300
|
-
});
|
|
1301
|
-
} catch (error) {
|
|
1302
|
-
const atRef = mp.ref ? ` at ref "${mp.ref}"` : "";
|
|
1303
|
-
throw new ConfigError(`Cannot load marketplace "${mp.name}"`, {
|
|
1304
|
-
cause: error,
|
|
1305
|
-
hint: `Failed to clone "${redactUrl(mp.url)}"${atRef}. Check the URL, the ref, and your git credentials. For private GitLab, prefer git+ssh://git@host/group/project.git.`
|
|
1306
|
-
});
|
|
1307
|
-
}
|
|
1308
|
-
switch (mp.format) {
|
|
1309
|
-
case "anthropic": return resolveAnthropicSkill(repoDir, mp, spec);
|
|
1310
|
-
default: {
|
|
1311
|
-
const exhaustive = mp.format;
|
|
1312
|
-
throw new ConfigError(`Unsupported marketplace format: "${String(exhaustive)}"`, { hint: `Supported formats: ${MARKETPLACE_FORMATS.join(", ")}.` });
|
|
1313
|
-
}
|
|
1314
|
-
}
|
|
1315
|
-
}
|
|
1316
|
-
/**
|
|
1317
|
-
* Resolve a `<marketplace>:<plugin>` or `<marketplace>:<plugin>/<server>`
|
|
1318
|
-
* reference to its normalised {@link McpServerConfig}s.
|
|
1319
|
-
*
|
|
1320
|
-
* Clones the marketplace repo (reusing the shared on-disk clone cache), then
|
|
1321
|
-
* reads two independent, additive sources for the plugin's servers: a
|
|
1322
|
-
* `.mcp.json` colocated with the plugin (either the project or the plugin
|
|
1323
|
-
* shape), and the `mcpServers` field of the plugin's own
|
|
1324
|
-
* `.claude-plugin/plugin.json` (subject to the same `strict` gating as its
|
|
1325
|
-
* `skills` field). A server declared in both is taken from `plugin.json`,
|
|
1326
|
-
* since it is the more specific, authored-by-the-plugin declaration.
|
|
1327
|
-
* `${CLAUDE_PLUGIN_ROOT}` expands to the plugin's directory in both.
|
|
1328
|
-
*
|
|
1329
|
-
* With `spec.server` set, only that server is returned. Throws a
|
|
1330
|
-
* `ConfigError` with a redacted, actionable hint when the marketplace,
|
|
1331
|
-
* plugin, or named server cannot be resolved — the caller treats that as a
|
|
1332
|
-
* skip-and-warn, not a fatal error, matching `loadMarketplaceSkill`.
|
|
1333
|
-
*/
|
|
1334
|
-
async function loadMarketplaceMcpServers(spec, registry, options = {}) {
|
|
1335
|
-
const ref = spec.server ? `${spec.marketplace}:${spec.plugin}/${spec.server}` : `${spec.marketplace}:${spec.plugin}`;
|
|
1336
|
-
const mp = registry.get(spec.marketplace);
|
|
1337
|
-
if (!mp) throw new ConfigError(`Cannot load MCP servers: "${ref}"`, { hint: `No marketplace named "${spec.marketplace}" is registered. Declare it with CODE_REVIEW_MARKETPLACES or --marketplace.` });
|
|
1338
|
-
let repoDir;
|
|
1339
|
-
try {
|
|
1340
|
-
repoDir = await cloneGitRepo(mp.url, mp.ref, {
|
|
1341
|
-
cacheDir: options.cacheDir ?? resolveSkillCacheDir(),
|
|
1342
|
-
refresh: options.refresh ?? false
|
|
1343
|
-
});
|
|
1344
|
-
} catch (error) {
|
|
1345
|
-
const atRef = mp.ref ? ` at ref "${mp.ref}"` : "";
|
|
1346
|
-
throw new ConfigError(`Cannot load marketplace "${mp.name}"`, {
|
|
1347
|
-
cause: error,
|
|
1348
|
-
hint: `Failed to clone "${redactUrl(mp.url)}"${atRef}. Check the URL, the ref, and your git credentials. For private GitLab, prefer git+ssh://git@host/group/project.git.`
|
|
1349
|
-
});
|
|
1350
|
-
}
|
|
1351
|
-
const realRoot = await realpath(repoDir);
|
|
1352
|
-
const { pluginDir, pluginManifest } = await resolvePluginEntry(repoDir, realRoot, mp, spec.plugin, ref);
|
|
1353
|
-
const source = {
|
|
1354
|
-
kind: "marketplace",
|
|
1355
|
-
marketplace: mp.name,
|
|
1356
|
-
plugin: spec.plugin,
|
|
1357
|
-
url: mp.url,
|
|
1358
|
-
ref: mp.ref,
|
|
1359
|
-
path: toPosixPath(relative(repoDir, pluginDir))
|
|
1360
|
-
};
|
|
1361
|
-
const normalizeOptions = {
|
|
1362
|
-
vars: options.vars,
|
|
1363
|
-
pluginRoot: pluginDir,
|
|
1364
|
-
warn: options.warn
|
|
1365
|
-
};
|
|
1366
|
-
const servers = /* @__PURE__ */ new Map();
|
|
1367
|
-
const mcpJsonRaw = await readTextInside(realRoot, join(pluginDir, ".mcp.json"), ref);
|
|
1368
|
-
if (mcpJsonRaw !== null) {
|
|
1369
|
-
let raw;
|
|
1370
|
-
try {
|
|
1371
|
-
raw = JSON.parse(mcpJsonRaw);
|
|
1372
|
-
} catch (error) {
|
|
1373
|
-
throw new ConfigError(`Plugin "${spec.plugin}" in marketplace "${mp.name}" is invalid`, {
|
|
1374
|
-
cause: error,
|
|
1375
|
-
hint: `Its .mcp.json is not valid JSON.`
|
|
1376
|
-
});
|
|
1377
|
-
}
|
|
1378
|
-
for (const server of parseMcpServers(raw, source, normalizeOptions)) servers.set(server.name, server);
|
|
1379
|
-
}
|
|
1380
|
-
const manifestServers = pluginManifest?.mcpServers;
|
|
1381
|
-
if (manifestServers !== void 0) for (const server of parseMcpServers(manifestServers, source, normalizeOptions)) servers.set(server.name, server);
|
|
1382
|
-
if (!spec.server) return [...servers.values()];
|
|
1383
|
-
const one = servers.get(spec.server);
|
|
1384
|
-
if (!one) throw new ConfigError(`Cannot load MCP servers: "${ref}"`, { hint: `No server "${spec.server}" found in plugin "${spec.plugin}". Available: ${[...servers.keys()].join(", ") || "(none)"}.` });
|
|
1385
|
-
return [one];
|
|
1386
|
-
}
|
|
1387
|
-
/**
|
|
1388
|
-
* Resolve a named plugin inside a cloned marketplace repo: read
|
|
1389
|
-
* `.claude-plugin/marketplace.json`, find the plugin's entry, resolve its
|
|
1390
|
-
* `source` to a directory, and (unless `strict: false`) read its own
|
|
1391
|
-
* `.claude-plugin/plugin.json`. Shared by skill and MCP-server resolution —
|
|
1392
|
-
* both need the same plugin lookup before reading their own manifest field.
|
|
1393
|
-
*/
|
|
1394
|
-
async function resolvePluginEntry(repoDir, realRoot, mp, pluginName, ref) {
|
|
1395
|
-
const manifestRaw = await readTextInside(realRoot, join(repoDir, ".claude-plugin", "marketplace.json"), ref);
|
|
1396
|
-
if (manifestRaw === null) throw new ConfigError(`Marketplace "${mp.name}" is not a valid Anthropic plugin marketplace`, { hint: `Expected a readable .claude-plugin/marketplace.json at "${redactUrl(mp.url)}"${mp.ref ? ` (ref "${mp.ref}")` : ""}.` });
|
|
1397
|
-
let manifest;
|
|
1398
|
-
try {
|
|
1399
|
-
manifest = JSON.parse(manifestRaw);
|
|
1400
|
-
} catch (error) {
|
|
1401
|
-
throw new ConfigError(`Marketplace "${mp.name}" is not a valid Anthropic plugin marketplace`, {
|
|
1402
|
-
cause: error,
|
|
1403
|
-
hint: `.claude-plugin/marketplace.json at "${redactUrl(mp.url)}" is not valid JSON.`
|
|
1404
|
-
});
|
|
1405
|
-
}
|
|
1406
|
-
const plugins = Array.isArray(manifest.plugins) ? manifest.plugins : [];
|
|
1407
|
-
const entry = plugins.find((p) => p && p.name === pluginName);
|
|
1408
|
-
if (!entry) {
|
|
1409
|
-
const available = plugins.map((p) => typeof p?.name === "string" ? p.name : null).filter((n) => Boolean(n));
|
|
1410
|
-
throw new ConfigError(`Plugin "${pluginName}" not found in marketplace "${mp.name}"`, { hint: available.length ? `Available plugins: ${available.join(", ")}.` : "The marketplace lists no plugins." });
|
|
1411
|
-
}
|
|
1412
|
-
const pluginDir = resolvePluginDir(repoDir, manifest, entry.source, mp, ref);
|
|
1413
|
-
const realPluginDir = await resolveInside(realRoot, pluginDir, ref);
|
|
1414
|
-
return {
|
|
1415
|
-
pluginDir,
|
|
1416
|
-
realPluginDir,
|
|
1417
|
-
pluginManifest: entry.strict !== false && realPluginDir ? await readPluginManifest(realRoot, realPluginDir, ref) : null,
|
|
1418
|
-
entry
|
|
1419
|
-
};
|
|
1420
|
-
}
|
|
1421
|
-
/** Resolve a skill inside a Claude Code (`anthropic`) plugin marketplace. */
|
|
1422
|
-
async function resolveAnthropicSkill(repoDir, mp, spec) {
|
|
1423
|
-
const ref = `${mp.name}:${spec.plugin}/${spec.skill}`;
|
|
1424
|
-
const realRoot = await realpath(repoDir);
|
|
1425
|
-
const { pluginDir, pluginManifest, entry } = await resolvePluginEntry(repoDir, realRoot, mp, spec.plugin, ref);
|
|
1426
|
-
const bases = computeSkillBases(repoDir, pluginDir, entry, pluginManifest, ref);
|
|
1427
|
-
const skill = await findSkillInBases(realRoot, bases, pluginDir, spec, ref, mp);
|
|
1428
|
-
if (!skill) throw new ConfigError(`Cannot load skill: "${ref}"`, { hint: `No skill "${spec.skill}" found in plugin "${spec.plugin}". Looked under the default skills/ directory${bases.length > 1 ? " and the plugin's custom \"skills\" paths" : ""}. Check the skill name against the marketplace.` });
|
|
1429
|
-
return skill;
|
|
1430
|
-
}
|
|
1431
|
-
/**
|
|
1432
|
-
* Read a plugin's optional `.claude-plugin/plugin.json`. A missing file returns
|
|
1433
|
-
* `null` (the manifest is optional), but a malformed one throws a `ConfigError`
|
|
1434
|
-
* rather than being silently ignored — otherwise a typo would quietly drop the
|
|
1435
|
-
* plugin's declared `skills` paths.
|
|
1436
|
-
*/
|
|
1437
|
-
async function readPluginManifest(realRoot, pluginDir, ref) {
|
|
1438
|
-
const raw = await readTextInside(realRoot, join(pluginDir, ".claude-plugin", "plugin.json"), ref);
|
|
1439
|
-
if (raw === null) return null;
|
|
1440
|
-
try {
|
|
1441
|
-
return JSON.parse(raw);
|
|
1442
|
-
} catch (error) {
|
|
1443
|
-
throw new ConfigError(`Malformed plugin.json for "${ref}"`, {
|
|
1444
|
-
cause: error,
|
|
1445
|
-
hint: "The plugin's .claude-plugin/plugin.json is not valid JSON. Fix it in the marketplace repository."
|
|
1446
|
-
});
|
|
1447
|
-
}
|
|
1448
|
-
}
|
|
1449
|
-
/** Normalize a `skills`/`commands` manifest field (string | string[]) to a path list. */
|
|
1450
|
-
function toPathArray(value) {
|
|
1451
|
-
return (typeof value === "string" ? [value] : Array.isArray(value) ? value : []).filter((v) => typeof v === "string").map((v) => v.trim()).filter(Boolean);
|
|
1452
|
-
}
|
|
1453
|
-
/**
|
|
1454
|
-
* Compute the directories to search for a named skill, per the plugin schema:
|
|
1455
|
-
* the default `<plugin>/skills/` scan plus any directories declared in the
|
|
1456
|
-
* `skills` field of the marketplace entry and (unless `strict: false`) the
|
|
1457
|
-
* plugin's own `plugin.json`. When the plugin source resolves to the marketplace
|
|
1458
|
-
* root and the entry lists specific `skills` subdirectories, those replace the
|
|
1459
|
-
* default scan rather than adding to it.
|
|
1460
|
-
*/
|
|
1461
|
-
function computeSkillBases(repoDir, pluginDir, entry, pluginManifest, ref) {
|
|
1462
|
-
const strict = entry.strict !== false;
|
|
1463
|
-
const entrySkills = toPathArray(entry.skills);
|
|
1464
|
-
const custom = (strict ? [...entrySkills, ...toPathArray(pluginManifest?.skills)] : entrySkills).map((p) => resolveUnderPlugin(repoDir, pluginDir, p, ref));
|
|
1465
|
-
const bases = resolve(pluginDir) === resolve(repoDir) && entrySkills.length > 0 ? custom : [join(pluginDir, "skills"), ...custom];
|
|
1466
|
-
return [...new Set(bases)];
|
|
1467
|
-
}
|
|
1468
|
-
/** Resolve a plugin-relative `skills` path to an absolute dir, guarding escapes. */
|
|
1469
|
-
function resolveUnderPlugin(repoDir, pluginDir, rel, ref) {
|
|
1470
|
-
let p = rel.trim();
|
|
1471
|
-
if (p === "." || p === "./") p = "";
|
|
1472
|
-
else if (p.startsWith("./")) p = p.slice(2);
|
|
1473
|
-
const dir = join(pluginDir, p);
|
|
1474
|
-
ensureInside(repoDir, dir, ref);
|
|
1475
|
-
return dir;
|
|
1476
|
-
}
|
|
1477
|
-
/**
|
|
1478
|
-
* Find `skillName` across the candidate base directories. Each base is either a
|
|
1479
|
-
* container of skill sub-directories (`<base>/<skill>/SKILL.md`) or a single
|
|
1480
|
-
* skill directory (`<base>/SKILL.md`, matched by its frontmatter `name`). Falls
|
|
1481
|
-
* back to a single `SKILL.md` at the plugin root (single-skill plugins).
|
|
1482
|
-
*
|
|
1483
|
-
* Every candidate is verified with {@link loadSkillIfInside} to resolve through
|
|
1484
|
-
* symlinks and reject any directory that escapes the cloned marketplace before a
|
|
1485
|
-
* file is read.
|
|
1486
|
-
*/
|
|
1487
|
-
async function findSkillInBases(realRoot, bases, pluginDir, spec, ref, mp) {
|
|
1488
|
-
const skillName = spec.skill;
|
|
1489
|
-
for (const base of bases) {
|
|
1490
|
-
const container = await loadSkillIfInside(realRoot, join(base, skillName), ref, mp, spec);
|
|
1491
|
-
if (container) return container;
|
|
1492
|
-
const single = await loadSkillIfInside(realRoot, base, ref, mp, spec);
|
|
1493
|
-
if (single && single.name === skillName) return single;
|
|
1494
|
-
}
|
|
1495
|
-
const root = await loadSkillIfInside(realRoot, pluginDir, ref, mp, spec);
|
|
1496
|
-
return root && root.name === skillName ? root : null;
|
|
1497
|
-
}
|
|
1498
|
-
/**
|
|
1499
|
-
* Resolve `dir` through symlinks and confirm it stays within `realRoot`. Returns
|
|
1500
|
-
* the real path, or `null` when the directory does not exist (nothing to read).
|
|
1501
|
-
* A directory that resolves — via `..` or a symlink — outside the marketplace
|
|
1502
|
-
* throws a `ConfigError`, so a malicious manifest cannot reach outside the clone.
|
|
1503
|
-
*/
|
|
1504
|
-
async function resolveInside(realRoot, dir, ref) {
|
|
1505
|
-
let real;
|
|
1506
|
-
try {
|
|
1507
|
-
real = await realpath(dir);
|
|
1508
|
-
} catch {
|
|
1509
|
-
return null;
|
|
1510
|
-
}
|
|
1511
|
-
assertInside(realRoot, real, ref);
|
|
1512
|
-
return real;
|
|
1513
|
-
}
|
|
1514
|
-
/** Throw if `real` (an already-resolved real path) is not within `realRoot`. */
|
|
1515
|
-
function assertInside(realRoot, real, ref) {
|
|
1516
|
-
if (real !== realRoot && !real.startsWith(realRoot + sep)) throw new ConfigError(`Refusing to load "${ref}": path escapes the marketplace repository`, { hint: "A plugin \"source\", manifest, or skill path resolved (via \"..\" or a symlink) outside the cloned marketplace." });
|
|
1517
|
-
}
|
|
1518
|
-
/**
|
|
1519
|
-
* Read a file only if its real path (following any symlink on the file itself,
|
|
1520
|
-
* not just its parent directory) stays within `realRoot`. Returns `null` when
|
|
1521
|
-
* the file does not exist; throws a `ConfigError` when it resolves outside the
|
|
1522
|
-
* marketplace, so a symlinked `SKILL.md` / manifest cannot exfiltrate an outside
|
|
1523
|
-
* file's contents.
|
|
1524
|
-
*/
|
|
1525
|
-
async function readTextInside(realRoot, filePath, ref) {
|
|
1526
|
-
let real;
|
|
1527
|
-
try {
|
|
1528
|
-
real = await realpath(filePath);
|
|
1529
|
-
} catch {
|
|
1530
|
-
return null;
|
|
1531
|
-
}
|
|
1532
|
-
assertInside(realRoot, real, ref);
|
|
1533
|
-
return readFile(real, "utf8");
|
|
1534
|
-
}
|
|
1535
|
-
/**
|
|
1536
|
-
* Load a skill from `dir` only if both the directory AND its `SKILL.md` file
|
|
1537
|
-
* resolve within `realRoot`. Guarding the file (not just the directory) closes
|
|
1538
|
-
* the case where a legitimate in-repo dir holds a `SKILL.md` symlinked outside.
|
|
1539
|
-
*/
|
|
1540
|
-
async function loadSkillIfInside(realRoot, dir, ref, mp, spec) {
|
|
1541
|
-
const real = await resolveInside(realRoot, dir, ref);
|
|
1542
|
-
if (!real) return null;
|
|
1543
|
-
if (await readTextInside(realRoot, join(real, "SKILL.md"), ref) === null) return null;
|
|
1544
|
-
return loadSkillFromDir(real, {
|
|
1545
|
-
kind: "marketplace",
|
|
1546
|
-
marketplace: mp.name,
|
|
1547
|
-
plugin: spec.plugin,
|
|
1548
|
-
url: mp.url,
|
|
1549
|
-
ref: mp.ref,
|
|
1550
|
-
path: toPosixPath(relative(realRoot, real))
|
|
1551
|
-
});
|
|
1552
|
-
}
|
|
1553
|
-
/**
|
|
1554
|
-
* Resolve a plugin entry's `source` to an absolute directory inside the cloned
|
|
1555
|
-
* marketplace. Honors `metadata.pluginRoot` for bare (non-`./`) sources, per the
|
|
1556
|
-
* marketplace schema. Remote sources (github/url/git-subdir/npm) are rejected —
|
|
1557
|
-
* we only resolve plugins that live in the marketplace repository itself.
|
|
1558
|
-
*/
|
|
1559
|
-
function resolvePluginDir(repoDir, manifest, source, mp, ref) {
|
|
1560
|
-
if (typeof source !== "string" || !source.trim()) throw new ConfigError(`Plugin in marketplace "${mp.name}" has no local source`, { hint: "Only plugins whose \"source\" is a relative path within the marketplace repo are supported. Remote plugin sources (github/url/git-subdir/npm) are not fetched." });
|
|
1561
|
-
let rel = source.trim();
|
|
1562
|
-
if (rel === "." || rel === "./") rel = "";
|
|
1563
|
-
else if (rel.startsWith("./")) rel = rel.slice(2);
|
|
1564
|
-
else {
|
|
1565
|
-
const pluginRoot = typeof manifest.metadata?.pluginRoot === "string" ? manifest.metadata.pluginRoot.trim() : "";
|
|
1566
|
-
const root = pluginRoot.startsWith("./") ? pluginRoot.slice(2) : pluginRoot;
|
|
1567
|
-
rel = root ? `${root.replace(/\/+$/, "")}/${rel}` : rel;
|
|
366
|
+
* `reviewThreads.isResolved` / `isOutdated`. Callers use this set to mark
|
|
367
|
+
* normalized notes resolved so settled threads are excluded from summary
|
|
368
|
+
* carry-over and prior-thread context. Paginates over threads.
|
|
369
|
+
*
|
|
370
|
+
* Outdated counts as settled because GitHub, unlike GitLab, does not
|
|
371
|
+
* auto-resolve a thread when the line it anchors to changes: fixing a finding
|
|
372
|
+
* flips the thread to outdated but leaves `isResolved` false until someone
|
|
373
|
+
* manually resolves it. Treating outdated as settled mirrors GitLab's
|
|
374
|
+
* "automatically resolve outdated diff discussions" behaviour, so a fixed
|
|
375
|
+
* finding stops being re-listed under "Still open from earlier reviews" (#133).
|
|
376
|
+
*/
|
|
377
|
+
async listSettledReviewCommentIds(owner, repo, pull) {
|
|
378
|
+
const settled = /* @__PURE__ */ new Set();
|
|
379
|
+
let cursor = null;
|
|
380
|
+
let hasNext = true;
|
|
381
|
+
while (hasNext) {
|
|
382
|
+
const threads = (await this.graphql(REVIEW_THREADS_QUERY, {
|
|
383
|
+
owner,
|
|
384
|
+
repo,
|
|
385
|
+
pull,
|
|
386
|
+
cursor
|
|
387
|
+
})).repository?.pullRequest?.reviewThreads;
|
|
388
|
+
if (!threads) break;
|
|
389
|
+
for (const thread of threads.nodes ?? []) {
|
|
390
|
+
if (!thread.isResolved && !thread.isOutdated) continue;
|
|
391
|
+
for (const comment of thread.comments?.nodes ?? []) if (typeof comment.databaseId === "number") settled.add(comment.databaseId);
|
|
392
|
+
}
|
|
393
|
+
hasNext = threads.pageInfo?.hasNextPage ?? false;
|
|
394
|
+
cursor = threads.pageInfo?.endCursor ?? null;
|
|
395
|
+
if (!cursor) hasNext = false;
|
|
396
|
+
}
|
|
397
|
+
return settled;
|
|
1568
398
|
}
|
|
1569
|
-
|
|
1570
|
-
ensureInside(repoDir, dir, ref);
|
|
1571
|
-
return dir;
|
|
1572
|
-
}
|
|
1573
|
-
/** Guard against `..`/symlink escapes: `target` must stay within `root`. */
|
|
1574
|
-
function ensureInside(root, target, ref) {
|
|
1575
|
-
const rootResolved = resolve(root);
|
|
1576
|
-
const targetResolved = resolve(target);
|
|
1577
|
-
if (targetResolved !== rootResolved && !targetResolved.startsWith(rootResolved + sep)) throw new ConfigError(`Refusing to load "${ref}": path escapes the marketplace repository`, { hint: "A plugin \"source\" or skill path resolved outside the cloned marketplace. Check the marketplace manifest." });
|
|
1578
|
-
}
|
|
399
|
+
};
|
|
1579
400
|
//#endregion
|
|
1580
401
|
//#region src/fingerprints.ts
|
|
1581
402
|
/**
|
|
@@ -1692,6 +513,21 @@ var PRODUCT_URL = "https://github.com/weareikko/code-review";
|
|
|
1692
513
|
* footer format, which is guarded by a migration test.
|
|
1693
514
|
*/
|
|
1694
515
|
var PRODUCT_LINK = `[${PRODUCT_NAME}](${PRODUCT_URL})`;
|
|
516
|
+
/** The tool's name for its cache directory: `<cache>/code-review/skills`. */
|
|
517
|
+
var PRODUCT_SLUG = "code-review";
|
|
518
|
+
/** Prefix of every environment variable this tool reads, named in configuration hints. */
|
|
519
|
+
var ENV_PREFIX = "CODE_REVIEW_";
|
|
520
|
+
/** The skills bundled in the package's `skills/` directory, which bare skill names resolve against. */
|
|
521
|
+
var BUILTIN_SKILLS_DIR = join(dirname(fileURLToPath(import.meta.url)), "..", "skills");
|
|
522
|
+
/**
|
|
523
|
+
* Where the bundled skills are published, so a footer links the exact version
|
|
524
|
+
* that ran: the package's `skills/` directory in the monorepo, at the version tag.
|
|
525
|
+
*/
|
|
526
|
+
var BUILTIN_SKILLS = {
|
|
527
|
+
repoWebUrl: PRODUCT_URL,
|
|
528
|
+
ref: "0.11.1",
|
|
529
|
+
path: "packages/code-review/skills"
|
|
530
|
+
};
|
|
1695
531
|
//#endregion
|
|
1696
532
|
//#region src/posting.ts
|
|
1697
533
|
var SUMMARY_MARKER = "<!-- code-review:summary -->";
|
|
@@ -1772,7 +608,7 @@ function buildSummaryBody(summary, costFooter, options = {}) {
|
|
|
1772
608
|
return `${withFooter}\n\n${buildSummaryHistoryBlock(historyEntries)}`;
|
|
1773
609
|
}
|
|
1774
610
|
function buildReviewedCommitFooter(commitSha) {
|
|
1775
|
-
return `Reviewed by ${PRODUCT_LINK} v0.
|
|
611
|
+
return `Reviewed by ${PRODUCT_LINK} v0.11.1 for commit ${commitSha}.`;
|
|
1776
612
|
}
|
|
1777
613
|
function extractReviewedCommitSha(body) {
|
|
1778
614
|
return REVIEWED_COMMIT_FOOTER_PATTERN.exec(body)?.[1] ?? null;
|
|
@@ -2083,17 +919,7 @@ function splitModel(model) {
|
|
|
2083
919
|
//#region src/config.ts
|
|
2084
920
|
/** Source-control backends the reviewer can target. */
|
|
2085
921
|
var PLATFORMS = ["gitlab", "github"];
|
|
2086
|
-
|
|
2087
|
-
* The single source of truth for the tool's own `CODE_REVIEW_*` settings.
|
|
2088
|
-
*
|
|
2089
|
-
* Each entry is the suffix after the `CODE_REVIEW_` prefix (e.g. `MODEL` for
|
|
2090
|
-
* `CODE_REVIEW_MODEL`). These are read directly across `config.ts`/`otel.ts`
|
|
2091
|
-
* and must NEVER be de-prefixed by {@link applyCodeReviewEnvPrefix}.
|
|
2092
|
-
*
|
|
2093
|
-
* Note: `API_KEY` is reserved. `CODE_REVIEW_API_KEY` was intentionally retired
|
|
2094
|
-
* as the AI provider key and must not be revived as one.
|
|
2095
|
-
*/
|
|
2096
|
-
var RESERVED_ENV_SUFFIXES = [
|
|
922
|
+
var RESERVED_ENV_SUFFIX_SET = /* @__PURE__ */ new Set([
|
|
2097
923
|
"API_KEY",
|
|
2098
924
|
"BASE_URL",
|
|
2099
925
|
"DECOMPOSE_HINT_LINES",
|
|
@@ -2119,9 +945,7 @@ var RESERVED_ENV_SUFFIXES = [
|
|
|
2119
945
|
"MCP_DISCOVERY",
|
|
2120
946
|
"LABELS_ON_FINDINGS",
|
|
2121
947
|
"LABELS_ON_CLEAN"
|
|
2122
|
-
];
|
|
2123
|
-
var CODE_REVIEW_PREFIX = "CODE_REVIEW_";
|
|
2124
|
-
var RESERVED_ENV_SUFFIX_SET = new Set(RESERVED_ENV_SUFFIXES);
|
|
948
|
+
]);
|
|
2125
949
|
/**
|
|
2126
950
|
* Optional namespacing shim for provider/infra environment variables.
|
|
2127
951
|
*
|
|
@@ -2149,9 +973,9 @@ var RESERVED_ENV_SUFFIX_SET = new Set(RESERVED_ENV_SUFFIXES);
|
|
|
2149
973
|
*/
|
|
2150
974
|
function applyCodeReviewEnvPrefix(env = process.env) {
|
|
2151
975
|
for (const key of Object.keys(env)) {
|
|
2152
|
-
if (!key.startsWith(
|
|
2153
|
-
const suffix = key.slice(
|
|
2154
|
-
if (!suffix || RESERVED_ENV_SUFFIX_SET.has(suffix) || suffix.startsWith(
|
|
976
|
+
if (!key.startsWith("CODE_REVIEW_")) continue;
|
|
977
|
+
const suffix = key.slice(ENV_PREFIX.length);
|
|
978
|
+
if (!suffix || RESERVED_ENV_SUFFIX_SET.has(suffix) || suffix.startsWith("CODE_REVIEW_")) continue;
|
|
2155
979
|
const value = env[key];
|
|
2156
980
|
if (typeof value !== "string" || value.length === 0) continue;
|
|
2157
981
|
env[suffix] = value;
|
|
@@ -2182,7 +1006,6 @@ var BOOLEAN_FLAGS = /* @__PURE__ */ new Set([
|
|
|
2182
1006
|
"retrieve-skipped",
|
|
2183
1007
|
"no-retrieve-skipped",
|
|
2184
1008
|
"verbose",
|
|
2185
|
-
"mcp-discovery",
|
|
2186
1009
|
"help",
|
|
2187
1010
|
"version"
|
|
2188
1011
|
]);
|
|
@@ -2314,7 +1137,7 @@ function resolveSkills(args, env) {
|
|
|
2314
1137
|
/**
|
|
2315
1138
|
* Resolve `--mcp` (repeatable, preferred) or the comma-separated
|
|
2316
1139
|
* `CODE_REVIEW_MCP` into a list of raw spec strings. Parsing (`parseMcpSpec`)
|
|
2317
|
-
* and resolution happen later, in `
|
|
1140
|
+
* and resolution happen later, in `resolveMcpServers` from `@weareikko/agent-context`.
|
|
2318
1141
|
*/
|
|
2319
1142
|
function resolveMcp(args, env) {
|
|
2320
1143
|
const argMcp = args.mcp;
|
|
@@ -2349,22 +1172,15 @@ function resolveMcpEnv(args, env) {
|
|
|
2349
1172
|
if (envVal) return envVal.split(",").map((s) => s.trim()).filter(Boolean);
|
|
2350
1173
|
return [];
|
|
2351
1174
|
}
|
|
2352
|
-
/**
|
|
2353
|
-
* Resolve whether repo `.mcp.json` auto-discovery runs. Off by default because
|
|
2354
|
-
* those files belong to the repository under review; `--mcp-discovery` always
|
|
2355
|
-
* wins, otherwise `CODE_REVIEW_MCP_DISCOVERY` truthy values (`1`, `true`, `yes`,
|
|
2356
|
-
* `on`) turn it on.
|
|
2357
|
-
*/
|
|
1175
|
+
/** Resolve the repository-controlled MCP configuration source. */
|
|
2358
1176
|
function resolveMcpDiscovery(args, env) {
|
|
2359
|
-
|
|
2360
|
-
const
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
].includes(raw.trim().toLowerCase());
|
|
2367
|
-
return false;
|
|
1177
|
+
const fromFlag = args.mcpDiscovery;
|
|
1178
|
+
const hasFlag = fromFlag !== void 0;
|
|
1179
|
+
const fromEnv = env.CODE_REVIEW_MCP_DISCOVERY;
|
|
1180
|
+
if (!hasFlag && !(fromEnv !== void 0)) return "off";
|
|
1181
|
+
const raw = hasFlag ? fromFlag : fromEnv;
|
|
1182
|
+
if (MCP_DISCOVERY_MODES.includes(raw)) return raw;
|
|
1183
|
+
throw new ConfigError(raw ? `Unknown MCP discovery mode "${String(raw)}".` : "Missing MCP discovery mode.", { hint: `--mcp-discovery (or CODE_REVIEW_MCP_DISCOVERY) must be one of: ${MCP_DISCOVERY_MODES.join(", ")}.` });
|
|
2368
1184
|
}
|
|
2369
1185
|
/**
|
|
2370
1186
|
* Resolve marketplace declarations from `--marketplace` (repeatable, preferred)
|
|
@@ -2374,7 +1190,17 @@ function resolveMcpDiscovery(args, env) {
|
|
|
2374
1190
|
*/
|
|
2375
1191
|
function resolveMarketplaces(args, env) {
|
|
2376
1192
|
const argMarketplace = args.marketplace;
|
|
2377
|
-
return (Array.isArray(argMarketplace) ? argMarketplace : typeof argMarketplace === "string" && argMarketplace.length > 0 ? [argMarketplace] : (env.CODE_REVIEW_MARKETPLACES ?? "").split(",")).map((entry) => entry.trim()).filter(Boolean).map((entry) =>
|
|
1193
|
+
return (Array.isArray(argMarketplace) ? argMarketplace : typeof argMarketplace === "string" && argMarketplace.length > 0 ? [argMarketplace] : (env.CODE_REVIEW_MARKETPLACES ?? "").split(",")).map((entry) => entry.trim()).filter(Boolean).map((entry) => {
|
|
1194
|
+
try {
|
|
1195
|
+
return parseMarketplaceEntry(entry);
|
|
1196
|
+
} catch (error) {
|
|
1197
|
+
if (error instanceof AgentContextError) throw new ConfigError(error.message, {
|
|
1198
|
+
hint: error.hint,
|
|
1199
|
+
cause: error
|
|
1200
|
+
});
|
|
1201
|
+
throw error;
|
|
1202
|
+
}
|
|
1203
|
+
});
|
|
2378
1204
|
}
|
|
2379
1205
|
/**
|
|
2380
1206
|
* Resolve the model pool from `--model-pool` (preferred) or
|
|
@@ -2608,6 +1434,7 @@ function validateConfig(config) {
|
|
|
2608
1434
|
if (!REVIEW_DEPTHS.includes(config.reviewDepth)) throw new ConfigError(`--review-depth must be one of: ${REVIEW_DEPTHS.join(", ")}`);
|
|
2609
1435
|
if (config.inputMode !== void 0 && !REVIEW_INPUT_MODES.includes(config.inputMode)) throw new ConfigError(`--input-mode must be one of: ${REVIEW_INPUT_MODES.join(", ")}`);
|
|
2610
1436
|
if (!POSTING_MODES.includes(config.postingMode)) throw new ConfigError(`--posting-mode must be one of: ${POSTING_MODES.join(", ")}`);
|
|
1437
|
+
if (!MCP_DISCOVERY_MODES.includes(config.mcpDiscovery)) throw new ConfigError(`--mcp-discovery must be one of: ${MCP_DISCOVERY_MODES.join(", ")}`);
|
|
2611
1438
|
const clean = new Set(config.labelsOnClean ?? []);
|
|
2612
1439
|
const overlap = (config.labelsOnFindings ?? []).filter((label) => clean.has(label));
|
|
2613
1440
|
if (overlap.length > 0) throw new ConfigError(`--labels-on-findings and --labels-on-clean share label(s): ${overlap.join(", ")}.`, { hint: "Each review outcome adds its own labels and removes the other set, so a label cannot belong to both." });
|
|
@@ -2707,74 +1534,241 @@ async function traceDiagnostic(channel, context, operation, secretValues = []) {
|
|
|
2707
1534
|
}
|
|
2708
1535
|
}, context);
|
|
2709
1536
|
}
|
|
2710
|
-
function traceDiagnosticPhase(phase, config, runId, operation, overrides = {}) {
|
|
2711
|
-
const context = createDiagnosticContext(phase, config, runId, overrides);
|
|
2712
|
-
return traceDiagnostic(tracingChannel(`${DIAGNOSTIC_CHANNEL_PREFIX}:${phase}`), context, operation, collectSecrets(config));
|
|
1537
|
+
function traceDiagnosticPhase(phase, config, runId, operation, overrides = {}) {
|
|
1538
|
+
const context = createDiagnosticContext(phase, config, runId, overrides);
|
|
1539
|
+
return traceDiagnostic(tracingChannel(`${DIAGNOSTIC_CHANNEL_PREFIX}:${phase}`), context, operation, collectSecrets(config));
|
|
1540
|
+
}
|
|
1541
|
+
var MCP_DIAGNOSTIC_CHANNEL_KEYS = {
|
|
1542
|
+
"mcp.connect": "connect",
|
|
1543
|
+
"mcp.tools": "tools",
|
|
1544
|
+
"mcp.call": "call"
|
|
1545
|
+
};
|
|
1546
|
+
var MCP_DIAGNOSTIC_CHANNEL_NAMES = {
|
|
1547
|
+
connect: `${DIAGNOSTIC_CHANNEL_PREFIX}:mcp.connect`,
|
|
1548
|
+
tools: `${DIAGNOSTIC_CHANNEL_PREFIX}:mcp.tools`,
|
|
1549
|
+
call: `${DIAGNOSTIC_CHANNEL_PREFIX}:mcp.call`
|
|
1550
|
+
};
|
|
1551
|
+
var mcpDiagnosticChannels = Object.fromEntries(Object.entries(MCP_DIAGNOSTIC_CHANNEL_NAMES).map(([key, name]) => [key, tracingChannel(name)]));
|
|
1552
|
+
/**
|
|
1553
|
+
* Traces one MCP bridge operation on its own `mcp.connect` / `mcp.tools` /
|
|
1554
|
+
* `mcp.call` channel. Mirrors {@link traceDiagnosticPhase} (context built,
|
|
1555
|
+
* `tracePromise`d, `durationMs`/`completedAt` stamped, errors sanitized) but
|
|
1556
|
+
* is keyed by `runId` + server name instead of a `Config`, since the MCP
|
|
1557
|
+
* bridge (`src/mcp.ts`) has no `Config` of its own.
|
|
1558
|
+
*
|
|
1559
|
+
* Node's `tracingChannel.tracePromise` assigns the traced function's return
|
|
1560
|
+
* value onto the published context as `.result` — fine for the phase channels
|
|
1561
|
+
* above (their payloads are small counts/flags), but `mcp.call`'s return value
|
|
1562
|
+
* is the MCP tool's arguments/result content, which must never reach a
|
|
1563
|
+
* diagnostics payload. The traced function here always resolves to
|
|
1564
|
+
* `undefined`; the operation's real result is captured in a closure and
|
|
1565
|
+
* returned to the caller separately, after tracing completes.
|
|
1566
|
+
*/
|
|
1567
|
+
function traceMcpDiagnostic(op, runId, server, operation, overrides = {}) {
|
|
1568
|
+
const context = {
|
|
1569
|
+
version: 1,
|
|
1570
|
+
runId,
|
|
1571
|
+
op,
|
|
1572
|
+
server,
|
|
1573
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1574
|
+
...overrides
|
|
1575
|
+
};
|
|
1576
|
+
const started = performance.now();
|
|
1577
|
+
const channel = mcpDiagnosticChannels[MCP_DIAGNOSTIC_CHANNEL_KEYS[op]];
|
|
1578
|
+
let result;
|
|
1579
|
+
return channel.tracePromise(async () => {
|
|
1580
|
+
try {
|
|
1581
|
+
result = await operation(context);
|
|
1582
|
+
} catch (error) {
|
|
1583
|
+
context.errorInfo = toDiagnosticError(error);
|
|
1584
|
+
throw error;
|
|
1585
|
+
} finally {
|
|
1586
|
+
context.completedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1587
|
+
context.durationMs = Number((performance.now() - started).toFixed(3));
|
|
1588
|
+
}
|
|
1589
|
+
}, context).then(() => result);
|
|
1590
|
+
}
|
|
1591
|
+
function toDiagnosticError(error, secretValues = []) {
|
|
1592
|
+
if (error instanceof Error) {
|
|
1593
|
+
const code = "code" in error && typeof error.code === "string" ? error.code : void 0;
|
|
1594
|
+
const timeout = "timeout" in error && error.timeout === true ? true : void 0;
|
|
1595
|
+
const status = "status" in error && typeof error.status === "number" ? error.status : void 0;
|
|
1596
|
+
return {
|
|
1597
|
+
name: error.name,
|
|
1598
|
+
message: scrubSecrets(error.message, secretValues),
|
|
1599
|
+
code,
|
|
1600
|
+
timeout,
|
|
1601
|
+
status
|
|
1602
|
+
};
|
|
1603
|
+
}
|
|
1604
|
+
return { message: scrubSecrets(String(error), secretValues) };
|
|
1605
|
+
}
|
|
1606
|
+
//#endregion
|
|
1607
|
+
//#region src/git.ts
|
|
1608
|
+
var exec = promisify(execFile);
|
|
1609
|
+
var DEFAULT_DIFF_CONTEXT = 20;
|
|
1610
|
+
var DEFAULT_CODEQUALITY_ARTIFACTS = [
|
|
1611
|
+
"gl-code-quality-report.json",
|
|
1612
|
+
"codequality.json",
|
|
1613
|
+
"codeclimate.json",
|
|
1614
|
+
"code-quality-report.json"
|
|
1615
|
+
];
|
|
1616
|
+
function gitErrorMessage(error) {
|
|
1617
|
+
const err = error;
|
|
1618
|
+
return [
|
|
1619
|
+
err.message,
|
|
1620
|
+
err.stderr,
|
|
1621
|
+
err.stdout
|
|
1622
|
+
].filter(Boolean).join("\n").trim();
|
|
1623
|
+
}
|
|
1624
|
+
async function git$1(args, options = {}) {
|
|
1625
|
+
try {
|
|
1626
|
+
const { stdout } = await exec("git", args, {
|
|
1627
|
+
cwd: options.cwd,
|
|
1628
|
+
maxBuffer: 52428800
|
|
1629
|
+
});
|
|
1630
|
+
return stdout;
|
|
1631
|
+
} catch (error) {
|
|
1632
|
+
throw new GitError(`git ${args.join(" ")} failed.`, {
|
|
1633
|
+
cause: error,
|
|
1634
|
+
hint: gitErrorMessage(error)
|
|
1635
|
+
});
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
function remoteRef(remote, branch) {
|
|
1639
|
+
return `refs/remotes/${remote}/${branch}`;
|
|
1640
|
+
}
|
|
1641
|
+
/**
|
|
1642
|
+
* Diff the target branch with the MR head commit, not `HEAD`: CI checks out a
|
|
1643
|
+
* merge commit (GitHub `refs/pull/N/merge`, GitLab merged results) whose base
|
|
1644
|
+
* can be stale, and then `HEAD` carries commits the MR does not change.
|
|
1645
|
+
*/
|
|
1646
|
+
function getMergeDiffArguments(targetBranch, headSha, options = {}) {
|
|
1647
|
+
const remote = options.remote ?? "origin";
|
|
1648
|
+
const context = options.context ?? DEFAULT_DIFF_CONTEXT;
|
|
1649
|
+
return [
|
|
1650
|
+
`${remoteRef(remote, targetBranch)}...${headSha}`,
|
|
1651
|
+
`--unified=${context}`,
|
|
1652
|
+
"--"
|
|
1653
|
+
];
|
|
1654
|
+
}
|
|
1655
|
+
/**
|
|
1656
|
+
* Full git argv for the merge diff. `-c core.quotepath=false` keeps non-ASCII
|
|
1657
|
+
* paths literal instead of git's default octal-escaped + double-quoted form
|
|
1658
|
+
* (`"a/caf\303\251.ts"`), which the comment-position parser cannot match —
|
|
1659
|
+
* leaving such comments with invalid one-sided positions that 500 on
|
|
1660
|
+
* `bulk_publish`. Diffing literally also gives the reviewer readable paths.
|
|
1661
|
+
*/
|
|
1662
|
+
function getMergeDiffCommand(targetBranch, headSha, options = {}) {
|
|
1663
|
+
return [
|
|
1664
|
+
"-c",
|
|
1665
|
+
"core.quotepath=false",
|
|
1666
|
+
"diff",
|
|
1667
|
+
...getMergeDiffArguments(targetBranch, headSha, options)
|
|
1668
|
+
];
|
|
1669
|
+
}
|
|
1670
|
+
async function fetchBranch(remote, branch, options) {
|
|
1671
|
+
await git$1([
|
|
1672
|
+
"fetch",
|
|
1673
|
+
"--no-tags",
|
|
1674
|
+
remote,
|
|
1675
|
+
`+refs/heads/${branch}:${remoteRef(remote, branch)}`
|
|
1676
|
+
], options);
|
|
1677
|
+
}
|
|
1678
|
+
async function isTracked(path, options) {
|
|
1679
|
+
try {
|
|
1680
|
+
await git$1([
|
|
1681
|
+
"ls-files",
|
|
1682
|
+
"--error-unmatch",
|
|
1683
|
+
"--",
|
|
1684
|
+
path
|
|
1685
|
+
], options);
|
|
1686
|
+
return true;
|
|
1687
|
+
} catch {
|
|
1688
|
+
return false;
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
async function removeGeneratedCodeQualityArtifacts(paths = DEFAULT_CODEQUALITY_ARTIFACTS, options = {}) {
|
|
1692
|
+
const removed = [];
|
|
1693
|
+
for (const path of paths) {
|
|
1694
|
+
if (await isTracked(path, options)) continue;
|
|
1695
|
+
try {
|
|
1696
|
+
await unlink(options.cwd ? join(options.cwd, path) : path);
|
|
1697
|
+
removed.push(path);
|
|
1698
|
+
} catch (error) {
|
|
1699
|
+
if (error.code !== "ENOENT") throw error;
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
return removed;
|
|
1703
|
+
}
|
|
1704
|
+
async function prepareGitHistory(sourceBranch, targetBranch, headSha, options = {}) {
|
|
1705
|
+
const remote = options.remote ?? "origin";
|
|
1706
|
+
await removeGeneratedCodeQualityArtifacts(options.codeQualityArtifacts, options);
|
|
1707
|
+
await git$1([
|
|
1708
|
+
"fetch",
|
|
1709
|
+
"--unshallow",
|
|
1710
|
+
"--no-tags",
|
|
1711
|
+
remote
|
|
1712
|
+
], options).catch(() => void 0);
|
|
1713
|
+
const fetchErrors = [];
|
|
1714
|
+
for (const branch of [targetBranch, sourceBranch]) try {
|
|
1715
|
+
await fetchBranch(remote, branch, options);
|
|
1716
|
+
} catch (error) {
|
|
1717
|
+
fetchErrors.push(`${branch}: ${gitErrorMessage(error)}`);
|
|
1718
|
+
}
|
|
1719
|
+
if (fetchErrors.length === 2) throw new GitError(`Unable to fetch MR source/target branches from ${remote}.`, { hint: fetchErrors.join("\n") });
|
|
1720
|
+
try {
|
|
1721
|
+
await git$1([
|
|
1722
|
+
"merge-base",
|
|
1723
|
+
remoteRef(remote, targetBranch),
|
|
1724
|
+
headSha
|
|
1725
|
+
], options);
|
|
1726
|
+
} catch (error) {
|
|
1727
|
+
const fetchDetail = fetchErrors.length > 0 ? `\nFetch warnings:\n${fetchErrors.join("\n")}` : "";
|
|
1728
|
+
throw new GitError(`Unable to prepare Git history for MR review: merge-base ${remoteRef(remote, targetBranch)} ${headSha} failed.`, {
|
|
1729
|
+
cause: error,
|
|
1730
|
+
hint: `Set GIT_DEPTH: 0 or ensure ${remote}/${targetBranch} and ${remote}/${sourceBranch} are fetchable.${fetchDetail}\n${gitErrorMessage(error)}`
|
|
1731
|
+
});
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
async function getMergeDiff(targetBranch, headSha, options = {}) {
|
|
1735
|
+
return git$1(getMergeDiffCommand(targetBranch, headSha, options), options);
|
|
1736
|
+
}
|
|
1737
|
+
function getMergeCommitLogArguments(targetBranch, headSha, options = {}) {
|
|
1738
|
+
return [
|
|
1739
|
+
`${remoteRef(options.remote ?? "origin", targetBranch)}...${headSha}`,
|
|
1740
|
+
"--pretty=tformat:commit %h%nAuthor: %an%nDate: %as%n%n%s%n%n%b",
|
|
1741
|
+
"--reverse",
|
|
1742
|
+
"--no-merges"
|
|
1743
|
+
];
|
|
1744
|
+
}
|
|
1745
|
+
async function getMergeCommitLog(targetBranch, headSha, options = {}) {
|
|
1746
|
+
return git$1(["log", ...getMergeCommitLogArguments(targetBranch, headSha, options)], options);
|
|
2713
1747
|
}
|
|
2714
|
-
var MCP_DIAGNOSTIC_CHANNEL_KEYS = {
|
|
2715
|
-
"mcp.connect": "connect",
|
|
2716
|
-
"mcp.tools": "tools",
|
|
2717
|
-
"mcp.call": "call"
|
|
2718
|
-
};
|
|
2719
|
-
var MCP_DIAGNOSTIC_CHANNEL_NAMES = {
|
|
2720
|
-
connect: `${DIAGNOSTIC_CHANNEL_PREFIX}:mcp.connect`,
|
|
2721
|
-
tools: `${DIAGNOSTIC_CHANNEL_PREFIX}:mcp.tools`,
|
|
2722
|
-
call: `${DIAGNOSTIC_CHANNEL_PREFIX}:mcp.call`
|
|
2723
|
-
};
|
|
2724
|
-
var mcpDiagnosticChannels = Object.fromEntries(Object.entries(MCP_DIAGNOSTIC_CHANNEL_NAMES).map(([key, name]) => [key, tracingChannel(name)]));
|
|
2725
1748
|
/**
|
|
2726
|
-
*
|
|
2727
|
-
* `
|
|
2728
|
-
*
|
|
2729
|
-
*
|
|
2730
|
-
*
|
|
2731
|
-
*
|
|
2732
|
-
* Node's `tracingChannel.tracePromise` assigns the traced function's return
|
|
2733
|
-
* value onto the published context as `.result` — fine for the phase channels
|
|
2734
|
-
* above (their payloads are small counts/flags), but `mcp.call`'s return value
|
|
2735
|
-
* is the MCP tool's arguments/result content, which must never reach a
|
|
2736
|
-
* diagnostics payload. The traced function here always resolves to
|
|
2737
|
-
* `undefined`; the operation's real result is captured in a closure and
|
|
2738
|
-
* returned to the caller separately, after tracing completes.
|
|
1749
|
+
* Summarize a unified diff into file/line counts for telemetry. Counts one file
|
|
1750
|
+
* per `diff --git` header and counts `+`/`-` lines only inside a hunk (after a
|
|
1751
|
+
* `@@` header), so the `--- a/file` / `+++ b/file` header lines are excluded and
|
|
1752
|
+
* a genuine content line whose text starts with `++`/`--` is still counted. Pure
|
|
1753
|
+
* and allocation-light so it can run on the full merge diff without an extra git
|
|
1754
|
+
* invocation.
|
|
2739
1755
|
*/
|
|
2740
|
-
function
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
1756
|
+
function summarizeDiff(diff) {
|
|
1757
|
+
let filesChanged = 0;
|
|
1758
|
+
let linesAdded = 0;
|
|
1759
|
+
let linesRemoved = 0;
|
|
1760
|
+
let inHunk = false;
|
|
1761
|
+
for (const line of diff.split("\n")) if (line.startsWith("diff --git ")) {
|
|
1762
|
+
filesChanged += 1;
|
|
1763
|
+
inHunk = false;
|
|
1764
|
+
} else if (line.startsWith("@@ ")) inHunk = true;
|
|
1765
|
+
else if (inHunk && line.startsWith("+")) linesAdded += 1;
|
|
1766
|
+
else if (inHunk && line.startsWith("-")) linesRemoved += 1;
|
|
1767
|
+
return {
|
|
1768
|
+
filesChanged,
|
|
1769
|
+
linesAdded,
|
|
1770
|
+
linesRemoved
|
|
2748
1771
|
};
|
|
2749
|
-
const started = performance.now();
|
|
2750
|
-
const channel = mcpDiagnosticChannels[MCP_DIAGNOSTIC_CHANNEL_KEYS[op]];
|
|
2751
|
-
let result;
|
|
2752
|
-
return channel.tracePromise(async () => {
|
|
2753
|
-
try {
|
|
2754
|
-
result = await operation(context);
|
|
2755
|
-
} catch (error) {
|
|
2756
|
-
context.errorInfo = toDiagnosticError(error);
|
|
2757
|
-
throw error;
|
|
2758
|
-
} finally {
|
|
2759
|
-
context.completedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2760
|
-
context.durationMs = Number((performance.now() - started).toFixed(3));
|
|
2761
|
-
}
|
|
2762
|
-
}, context).then(() => result);
|
|
2763
|
-
}
|
|
2764
|
-
function toDiagnosticError(error, secretValues = []) {
|
|
2765
|
-
if (error instanceof Error) {
|
|
2766
|
-
const code = "code" in error && typeof error.code === "string" ? error.code : void 0;
|
|
2767
|
-
const timeout = "timeout" in error && error.timeout === true ? true : void 0;
|
|
2768
|
-
const status = "status" in error && typeof error.status === "number" ? error.status : void 0;
|
|
2769
|
-
return {
|
|
2770
|
-
name: error.name,
|
|
2771
|
-
message: scrubSecrets(error.message, secretValues),
|
|
2772
|
-
code,
|
|
2773
|
-
timeout,
|
|
2774
|
-
status
|
|
2775
|
-
};
|
|
2776
|
-
}
|
|
2777
|
-
return { message: scrubSecrets(String(error), secretValues) };
|
|
2778
1772
|
}
|
|
2779
1773
|
//#endregion
|
|
2780
1774
|
//#region src/git-tool.ts
|
|
@@ -2997,195 +1991,12 @@ var noopLogger = {
|
|
|
2997
1991
|
warn: () => {},
|
|
2998
1992
|
error: () => {}
|
|
2999
1993
|
};
|
|
3000
|
-
//#endregion
|
|
3001
|
-
//#region src/mcp-config.ts
|
|
3002
|
-
/** Directories from `gitRoot` down to `cwd`, inclusive, root first. */
|
|
3003
|
-
function walkDirs(cwd, gitRoot) {
|
|
3004
|
-
const dirs = [];
|
|
3005
|
-
let current = cwd;
|
|
3006
|
-
while (true) {
|
|
3007
|
-
dirs.unshift(current);
|
|
3008
|
-
if (current === gitRoot) break;
|
|
3009
|
-
const parent = dirname(current);
|
|
3010
|
-
if (parent === current) break;
|
|
3011
|
-
current = parent;
|
|
3012
|
-
}
|
|
3013
|
-
return dirs;
|
|
3014
|
-
}
|
|
3015
|
-
async function readJsonFile(path) {
|
|
3016
|
-
let content;
|
|
3017
|
-
try {
|
|
3018
|
-
content = await readFile(path, "utf8");
|
|
3019
|
-
} catch {
|
|
3020
|
-
return { error: "missing" };
|
|
3021
|
-
}
|
|
3022
|
-
try {
|
|
3023
|
-
return { raw: JSON.parse(content) };
|
|
3024
|
-
} catch {
|
|
3025
|
-
return { error: "invalid" };
|
|
3026
|
-
}
|
|
3027
|
-
}
|
|
3028
|
-
/**
|
|
3029
|
-
* Collect the MCP disable lists declared in the repository: `.claude/settings.json`
|
|
3030
|
-
* and the gitignored project-local `.claude/settings.local.json` — where Claude
|
|
3031
|
-
* Code persists `disabledMcpjsonServers` when a developer declines a server —
|
|
3032
|
-
* in every directory from `gitRoot` down to `cwd`. Lists from every level and
|
|
3033
|
-
* both files are unioned. Enable keys are ignored: this tool never re-enables a
|
|
3034
|
-
* server another config disabled.
|
|
3035
|
-
*/
|
|
3036
|
-
async function loadMcpDisableFilters(cwd, gitRoot, warn) {
|
|
3037
|
-
const filters = {
|
|
3038
|
-
disabledMcpjsonServers: [],
|
|
3039
|
-
disabledMcpServers: []
|
|
3040
|
-
};
|
|
3041
|
-
for (const dir of walkDirs(cwd, gitRoot)) for (const file of ["settings.json", "settings.local.json"]) {
|
|
3042
|
-
const settingsPath = join(dir, ".claude", file);
|
|
3043
|
-
const settingsFile = await readJsonFile(settingsPath);
|
|
3044
|
-
if ("raw" in settingsFile) {
|
|
3045
|
-
const parsed = parseMcpDisableFilters(settingsFile.raw);
|
|
3046
|
-
filters.disabledMcpjsonServers.push(...parsed.disabledMcpjsonServers);
|
|
3047
|
-
filters.disabledMcpServers.push(...parsed.disabledMcpServers);
|
|
3048
|
-
} else if (settingsFile.error === "invalid") warn?.(`${settingsPath} is not valid JSON — MCP disable lists from this file ignored.`);
|
|
3049
|
-
}
|
|
3050
|
-
return filters;
|
|
3051
|
-
}
|
|
3052
|
-
/**
|
|
3053
|
-
* Discover MCP servers declared in the repository, mirroring
|
|
3054
|
-
* `loadAutoDiscoveredSkills`: `.mcp.json` in every directory from `gitRoot` down
|
|
3055
|
-
* to `cwd`, the closest directory winning per server name.
|
|
3056
|
-
*
|
|
3057
|
-
* `disabledMcpjsonServers` is scoped to these project-declared servers and
|
|
3058
|
-
* applied here. `disabledMcpServers` is *not* scoped to them — it names a server
|
|
3059
|
-
* whatever its source — so `resolveMcpServers` applies it once at the end, over
|
|
3060
|
-
* marketplace and `file:` servers too.
|
|
3061
|
-
*/
|
|
3062
|
-
async function loadAutoDiscoveredMcpServers(cwd, gitRoot, warn, options = {}) {
|
|
3063
|
-
const found = /* @__PURE__ */ new Map();
|
|
3064
|
-
const filters = options.filters ?? await loadMcpDisableFilters(cwd, gitRoot, warn);
|
|
3065
|
-
for (const dir of walkDirs(cwd, gitRoot)) {
|
|
3066
|
-
const mcpPath = join(dir, ".mcp.json");
|
|
3067
|
-
const mcpFile = await readJsonFile(mcpPath);
|
|
3068
|
-
if ("raw" in mcpFile) {
|
|
3069
|
-
const source = {
|
|
3070
|
-
kind: "project",
|
|
3071
|
-
path: toPosixPath(relative(gitRoot, mcpPath))
|
|
3072
|
-
};
|
|
3073
|
-
for (const server of parseMcpServers(mcpFile.raw, source, {
|
|
3074
|
-
vars: options.vars,
|
|
3075
|
-
warn
|
|
3076
|
-
})) found.set(server.name, server);
|
|
3077
|
-
} else if (mcpFile.error === "invalid") warn?.(`${mcpPath} is not valid JSON — MCP servers from this file not loaded.`);
|
|
3078
|
-
}
|
|
3079
|
-
return applyMcpDisableFilters([...found.values()], filters);
|
|
3080
|
-
}
|
|
3081
|
-
/**
|
|
3082
|
-
* Parse a `--mcp` / `CODE_REVIEW_MCP` spec string, mirroring `parseSkillSpec`'s
|
|
3083
|
-
* conventions:
|
|
3084
|
-
*
|
|
3085
|
-
* | Input | Result |
|
|
3086
|
-
* |---------------------------------|------------------------------------------------------------------|
|
|
3087
|
-
* | `file:./extra-servers.json` | `{ protocol: 'file', path: './extra-servers.json' }` |
|
|
3088
|
-
* | `acme:dev` | `{ protocol: 'marketplace', marketplace: 'acme', plugin: 'dev', server: '' }` |
|
|
3089
|
-
* | `acme:dev/context7` | `{ protocol: 'marketplace', marketplace: 'acme', plugin: 'dev', server: 'context7' }` |
|
|
3090
|
-
*
|
|
3091
|
-
* An empty `server` means "every server the plugin exposes". Throws a
|
|
3092
|
-
* `ConfigError` with an actionable hint on any malformed input.
|
|
3093
|
-
*/
|
|
3094
|
-
function parseMcpSpec(spec) {
|
|
3095
|
-
if (spec.startsWith("file:")) {
|
|
3096
|
-
const path = spec.slice(5);
|
|
3097
|
-
if (!path) throw new ConfigError(`Invalid --mcp spec: "${spec}"`, { hint: "A file: spec needs a path, e.g. file:./mcp-extra.json." });
|
|
3098
|
-
return {
|
|
3099
|
-
protocol: "file",
|
|
3100
|
-
path
|
|
3101
|
-
};
|
|
3102
|
-
}
|
|
3103
|
-
const colonIdx = spec.indexOf(":");
|
|
3104
|
-
if (colonIdx <= 0) throw new ConfigError(`Invalid --mcp spec: "${spec}"`, { hint: "Use file:<path>, <marketplace>:<plugin>, or <marketplace>:<plugin>/<server>." });
|
|
3105
|
-
const marketplace = spec.slice(0, colonIdx);
|
|
3106
|
-
const rest = spec.slice(colonIdx + 1);
|
|
3107
|
-
const slashIdx = rest.indexOf("/");
|
|
3108
|
-
const plugin = slashIdx === -1 ? rest : rest.slice(0, slashIdx);
|
|
3109
|
-
const server = slashIdx === -1 ? "" : rest.slice(slashIdx + 1);
|
|
3110
|
-
if (!plugin || server.includes("/")) throw new ConfigError(`Invalid --mcp spec: "${spec}"`, { hint: `Marketplace MCP servers use "<marketplace>:<plugin>" or "<marketplace>:<plugin>/<server>", e.g. "${marketplace || "acme"}:dev/context7".` });
|
|
3111
|
-
return {
|
|
3112
|
-
protocol: "marketplace",
|
|
3113
|
-
marketplace,
|
|
3114
|
-
plugin,
|
|
3115
|
-
server
|
|
3116
|
-
};
|
|
3117
|
-
}
|
|
3118
|
-
/** Load a `file:` MCP spec — a standalone `.mcp.json`-style document anywhere on disk. */
|
|
3119
|
-
async function loadFileMcpServers(path, vars, warn) {
|
|
3120
|
-
const source = {
|
|
3121
|
-
kind: "file",
|
|
3122
|
-
path
|
|
3123
|
-
};
|
|
3124
|
-
const file = await readJsonFile(path);
|
|
3125
|
-
if ("error" in file) {
|
|
3126
|
-
warn(file.error === "missing" ? `MCP file "${path}" does not exist — skipped.` : `MCP file "${path}" is not valid JSON — skipped.`);
|
|
3127
|
-
return [];
|
|
3128
|
-
}
|
|
3129
|
-
return parseMcpServers(file.raw, source, {
|
|
3130
|
-
vars,
|
|
3131
|
-
warn
|
|
3132
|
-
});
|
|
3133
|
-
}
|
|
3134
|
-
/**
|
|
3135
|
-
* Resolve every MCP server for a review, merging sources in the approved order:
|
|
3136
|
-
*
|
|
3137
|
-
* 1. Repo auto-discovery (`.mcp.json` walked from `gitRoot` to `cwd`, closest
|
|
3138
|
-
* wins, `disabledMcpjsonServers` applied) — only when `config.mcpDiscovery`
|
|
3139
|
-
* is `true`, which is opt-in: `.mcp.json` is content of the repository under
|
|
3140
|
-
* review, so a merge request could otherwise make the reviewer spawn a
|
|
3141
|
-
* process of its choosing on the CI runner.
|
|
3142
|
-
* 2. Every `--mcp` / `CODE_REVIEW_MCP` spec, in the order given: a `file:` spec
|
|
3143
|
-
* loads a standalone document, a `<marketplace>:<plugin>[/<server>]` spec
|
|
3144
|
-
* loads from the registered marketplace. A later spec's server overrides an
|
|
3145
|
-
* earlier one (from any source) of the same name.
|
|
3146
|
-
* 3. `disabledMcpServers` from `.claude/settings.json` (and `settings.local.json`)
|
|
3147
|
-
* plus `config.disableMcp` (`--disable-mcp` / `CODE_REVIEW_DISABLE_MCP`),
|
|
3148
|
-
* applied last over every source above — a name disabled there stays dropped
|
|
3149
|
-
* even when a `--mcp` spec redeclares it.
|
|
3150
|
-
*
|
|
3151
|
-
* A spec that fails to resolve (bad file, unregistered marketplace, unknown
|
|
3152
|
-
* plugin/server) is skipped with a warning — one broken `--mcp` entry must not
|
|
3153
|
-
* abort the whole review.
|
|
3154
|
-
*/
|
|
3155
|
-
async function resolveMcpServers(config, cwd, gitRoot, registry, logger, options = {}) {
|
|
3156
|
-
const warn = (msg) => logger?.warn(msg);
|
|
3157
|
-
const filters = await loadMcpDisableFilters(cwd, gitRoot, warn);
|
|
3158
|
-
const found = /* @__PURE__ */ new Map();
|
|
3159
|
-
if (config.mcpDiscovery) for (const server of await loadAutoDiscoveredMcpServers(cwd, gitRoot, warn, {
|
|
3160
|
-
vars: options.vars,
|
|
3161
|
-
filters
|
|
3162
|
-
})) found.set(server.name, server);
|
|
3163
|
-
for (const raw of config.mcp) try {
|
|
3164
|
-
const spec = parseMcpSpec(raw);
|
|
3165
|
-
const servers = spec.protocol === "file" ? await loadFileMcpServers(spec.path, options.vars, warn) : await loadMarketplaceMcpServers(spec, registry, {
|
|
3166
|
-
vars: options.vars,
|
|
3167
|
-
refresh: options.refresh,
|
|
3168
|
-
warn
|
|
3169
|
-
});
|
|
3170
|
-
for (const server of servers) found.set(server.name, server);
|
|
3171
|
-
} catch (error) {
|
|
3172
|
-
warn(`Skipping --mcp "${raw}": ${error instanceof Error ? error.message : String(error)}`);
|
|
3173
|
-
}
|
|
3174
|
-
return applyMcpDisableFilters([...found.values()], {
|
|
3175
|
-
disabledMcpjsonServers: [],
|
|
3176
|
-
disabledMcpServers: [...filters.disabledMcpServers, ...config.disableMcp]
|
|
3177
|
-
});
|
|
3178
|
-
}
|
|
3179
1994
|
/**
|
|
3180
1995
|
* Timeout for connect and `tools/list`. Deliberately not overridable by a server
|
|
3181
1996
|
* definition: both run before the agent loop starts, so they are outside the
|
|
3182
1997
|
* review timeout and a large per-server `timeout` must not stall the pipeline.
|
|
3183
1998
|
*/
|
|
3184
1999
|
var MCP_CONNECT_TIMEOUT_MS = 3e4;
|
|
3185
|
-
/** Only tools that declare themselves read-only and non-destructive are exposed. */
|
|
3186
|
-
function isReadOnlyMcpTool(tool) {
|
|
3187
|
-
return tool.annotations?.readOnlyHint === true && tool.annotations?.destructiveHint !== true;
|
|
3188
|
-
}
|
|
3189
2000
|
function safeSegment(value) {
|
|
3190
2001
|
return value.replace(/[^A-Za-z0-9_-]/g, "_");
|
|
3191
2002
|
}
|
|
@@ -3251,7 +2062,8 @@ function createMcpTransport(config) {
|
|
|
3251
2062
|
}
|
|
3252
2063
|
}
|
|
3253
2064
|
function errorMessage(error) {
|
|
3254
|
-
|
|
2065
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2066
|
+
return redactUrl(message);
|
|
3255
2067
|
}
|
|
3256
2068
|
/**
|
|
3257
2069
|
* Runs `operation` traced on the given MCP diagnostics channel when `runId` is
|
|
@@ -3387,7 +2199,7 @@ async function connectOne(config, options) {
|
|
|
3387
2199
|
};
|
|
3388
2200
|
const client = new McpClient({
|
|
3389
2201
|
name: PRODUCT_NAME,
|
|
3390
|
-
version: "0.
|
|
2202
|
+
version: "0.11.1",
|
|
3391
2203
|
requestTimeoutMs: MCP_CONNECT_TIMEOUT_MS
|
|
3392
2204
|
});
|
|
3393
2205
|
try {
|
|
@@ -3413,804 +2225,63 @@ async function connectOne(config, options) {
|
|
|
3413
2225
|
client,
|
|
3414
2226
|
status,
|
|
3415
2227
|
budget,
|
|
3416
|
-
timeoutMs,
|
|
3417
|
-
maxResultChars,
|
|
3418
|
-
runId
|
|
3419
|
-
}))
|
|
3420
|
-
};
|
|
3421
|
-
} catch (error) {
|
|
3422
|
-
logger.warn(`MCP server "${config.name}" unavailable: ${errorMessage(error)}`);
|
|
3423
|
-
await client.close().catch(() => {});
|
|
3424
|
-
return {
|
|
3425
|
-
client,
|
|
3426
|
-
status,
|
|
3427
|
-
tools: []
|
|
3428
|
-
};
|
|
3429
|
-
}
|
|
3430
|
-
}
|
|
3431
|
-
/**
|
|
3432
|
-
* Connect every configured server, list its tools, and bridge the read-only
|
|
3433
|
-
* ones. Never throws for a server failure: the server is reported as
|
|
3434
|
-
* `unavailable` and the review continues with the others.
|
|
3435
|
-
*/
|
|
3436
|
-
async function connectMcpServers(configs, options = {}) {
|
|
3437
|
-
const total = options.callBudget ?? 40;
|
|
3438
|
-
const resolved = {
|
|
3439
|
-
logger: options.logger ?? noopLogger,
|
|
3440
|
-
timeoutMs: options.timeoutMs ?? 3e4,
|
|
3441
|
-
callBudget: total,
|
|
3442
|
-
maxResultChars: options.maxResultChars ?? 2e5,
|
|
3443
|
-
createTransport: options.createTransport ?? createMcpTransport,
|
|
3444
|
-
budget: {
|
|
3445
|
-
remaining: total,
|
|
3446
|
-
total
|
|
3447
|
-
},
|
|
3448
|
-
runId: options.runId
|
|
3449
|
-
};
|
|
3450
|
-
const connected = await Promise.all(configs.map((config) => connectOne(config, resolved)));
|
|
3451
|
-
const emitted = /* @__PURE__ */ new Set();
|
|
3452
|
-
const tools = [];
|
|
3453
|
-
for (const server of connected) for (const tool of server.tools) {
|
|
3454
|
-
if (emitted.has(tool.name)) {
|
|
3455
|
-
resolved.logger.warn(`MCP server "${server.status.name}": tool "${tool.name}" collides with an already-bridged tool name — dropped.`);
|
|
3456
|
-
const index = server.status.tools.findIndex((name) => mcpToolName(server.status.name, name) === tool.name);
|
|
3457
|
-
if (index !== -1) server.status.tools.splice(index, 1);
|
|
3458
|
-
continue;
|
|
3459
|
-
}
|
|
3460
|
-
emitted.add(tool.name);
|
|
3461
|
-
tools.push(tool);
|
|
3462
|
-
}
|
|
3463
|
-
let closed = false;
|
|
3464
|
-
return {
|
|
3465
|
-
tools,
|
|
3466
|
-
servers: connected.map((server) => server.status),
|
|
3467
|
-
async close() {
|
|
3468
|
-
if (closed) return;
|
|
3469
|
-
closed = true;
|
|
3470
|
-
await Promise.all(connected.filter((server) => server.status.status === "connected").map((server) => server.client.close().catch(() => {})));
|
|
3471
|
-
}
|
|
3472
|
-
};
|
|
3473
|
-
}
|
|
3474
|
-
//#endregion
|
|
3475
|
-
//#region node_modules/jsonrepair/lib/esm/utils/JSONRepairError.js
|
|
3476
|
-
var JSONRepairError = class extends Error {
|
|
3477
|
-
constructor(message, position) {
|
|
3478
|
-
super(`${message} at position ${position}`);
|
|
3479
|
-
this.position = position;
|
|
3480
|
-
}
|
|
3481
|
-
};
|
|
3482
|
-
//#endregion
|
|
3483
|
-
//#region node_modules/jsonrepair/lib/esm/utils/stringUtils.js
|
|
3484
|
-
var codeSpace = 32;
|
|
3485
|
-
var codeNewline = 10;
|
|
3486
|
-
var codeTab = 9;
|
|
3487
|
-
var codeReturn = 13;
|
|
3488
|
-
var codeNonBreakingSpace = 160;
|
|
3489
|
-
var codeMongolianVowelSeparator = 6158;
|
|
3490
|
-
var codeEnQuad = 8192;
|
|
3491
|
-
var codeZeroWidthSpace = 8203;
|
|
3492
|
-
var codeNarrowNoBreakSpace = 8239;
|
|
3493
|
-
var codeMediumMathematicalSpace = 8287;
|
|
3494
|
-
var codeIdeographicSpace = 12288;
|
|
3495
|
-
var codeZeroWidthNoBreakSpace = 65279;
|
|
3496
|
-
function isHex(char) {
|
|
3497
|
-
return /^[0-9A-Fa-f]$/.test(char);
|
|
3498
|
-
}
|
|
3499
|
-
function isDigit(char) {
|
|
3500
|
-
return char >= "0" && char <= "9";
|
|
3501
|
-
}
|
|
3502
|
-
function isValidStringCharacter(char) {
|
|
3503
|
-
return char >= " ";
|
|
3504
|
-
}
|
|
3505
|
-
function isDelimiter(char) {
|
|
3506
|
-
return ",:[]/{}()\n+".includes(char);
|
|
3507
|
-
}
|
|
3508
|
-
function isFunctionNameCharStart(char) {
|
|
3509
|
-
return char >= "a" && char <= "z" || char >= "A" && char <= "Z" || char === "_" || char === "$";
|
|
3510
|
-
}
|
|
3511
|
-
function isFunctionNameChar(char) {
|
|
3512
|
-
return char >= "a" && char <= "z" || char >= "A" && char <= "Z" || char === "_" || char === "$" || char >= "0" && char <= "9";
|
|
3513
|
-
}
|
|
3514
|
-
var regexUrlStart = /^(http|https|ftp|mailto|file|data|irc):\/\/$/;
|
|
3515
|
-
var regexUrlChar = /^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;
|
|
3516
|
-
function isUnquotedStringDelimiter(char) {
|
|
3517
|
-
return ",[]/{}\n+".includes(char);
|
|
3518
|
-
}
|
|
3519
|
-
function isStartOfValue(char) {
|
|
3520
|
-
return isQuote(char) || regexStartOfValue.test(char);
|
|
3521
|
-
}
|
|
3522
|
-
var regexStartOfValue = /^[[{\w-]$/;
|
|
3523
|
-
function isControlCharacter(char) {
|
|
3524
|
-
return char === "\n" || char === "\r" || char === " " || char === "\b" || char === "\f";
|
|
3525
|
-
}
|
|
3526
|
-
/**
|
|
3527
|
-
* Check if the given character is a whitespace character like space, tab, or
|
|
3528
|
-
* newline
|
|
3529
|
-
*/
|
|
3530
|
-
function isWhitespace(text, index) {
|
|
3531
|
-
const code = text.charCodeAt(index);
|
|
3532
|
-
return code === codeSpace || code === codeNewline || code === codeTab || code === codeReturn;
|
|
3533
|
-
}
|
|
3534
|
-
/**
|
|
3535
|
-
* Check if the given character is a whitespace character like space or tab,
|
|
3536
|
-
* but NOT a newline
|
|
3537
|
-
*/
|
|
3538
|
-
function isWhitespaceExceptNewline(text, index) {
|
|
3539
|
-
const code = text.charCodeAt(index);
|
|
3540
|
-
return code === codeSpace || code === codeTab || code === codeReturn;
|
|
3541
|
-
}
|
|
3542
|
-
/**
|
|
3543
|
-
* Check if the given character is a special whitespace character, some
|
|
3544
|
-
* unicode variant
|
|
3545
|
-
*/
|
|
3546
|
-
function isSpecialWhitespace(text, index) {
|
|
3547
|
-
const code = text.charCodeAt(index);
|
|
3548
|
-
return code === codeNonBreakingSpace || code === codeMongolianVowelSeparator || code >= codeEnQuad && code <= codeZeroWidthSpace || code === codeNarrowNoBreakSpace || code === codeMediumMathematicalSpace || code === codeIdeographicSpace || code === codeZeroWidthNoBreakSpace;
|
|
3549
|
-
}
|
|
3550
|
-
/**
|
|
3551
|
-
* Test whether the given character is a quote or double quote character.
|
|
3552
|
-
* Also tests for special variants of quotes.
|
|
3553
|
-
*/
|
|
3554
|
-
function isQuote(char) {
|
|
3555
|
-
return isDoubleQuoteLike(char) || isSingleQuoteLike(char);
|
|
3556
|
-
}
|
|
3557
|
-
/**
|
|
3558
|
-
* Test whether the given character is a double quote character.
|
|
3559
|
-
* Also tests for special variants of double quotes.
|
|
3560
|
-
*/
|
|
3561
|
-
function isDoubleQuoteLike(char) {
|
|
3562
|
-
return char === "\"" || char === "“" || char === "”";
|
|
3563
|
-
}
|
|
3564
|
-
/**
|
|
3565
|
-
* Test whether the given character is a double quote character.
|
|
3566
|
-
* Does NOT test for special variants of double quotes.
|
|
3567
|
-
*/
|
|
3568
|
-
function isDoubleQuote(char) {
|
|
3569
|
-
return char === "\"";
|
|
3570
|
-
}
|
|
3571
|
-
/**
|
|
3572
|
-
* Test whether the given character is a single quote character.
|
|
3573
|
-
* Also tests for special variants of single quotes.
|
|
3574
|
-
*/
|
|
3575
|
-
function isSingleQuoteLike(char) {
|
|
3576
|
-
return char === "'" || char === "‘" || char === "’" || char === "`" || char === "´";
|
|
3577
|
-
}
|
|
3578
|
-
/**
|
|
3579
|
-
* Test whether the given character is a single quote character.
|
|
3580
|
-
* Does NOT test for special variants of single quotes.
|
|
3581
|
-
*/
|
|
3582
|
-
function isSingleQuote(char) {
|
|
3583
|
-
return char === "'";
|
|
3584
|
-
}
|
|
3585
|
-
/**
|
|
3586
|
-
* Strip last occurrence of textToStrip from text
|
|
3587
|
-
*/
|
|
3588
|
-
function stripLastOccurrence(text, textToStrip) {
|
|
3589
|
-
let stripRemainingText = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
|
|
3590
|
-
const index = text.lastIndexOf(textToStrip);
|
|
3591
|
-
return index !== -1 ? text.substring(0, index) + (stripRemainingText ? "" : text.substring(index + 1)) : text;
|
|
3592
|
-
}
|
|
3593
|
-
function insertBeforeLastWhitespace(text, textToInsert) {
|
|
3594
|
-
let index = text.length;
|
|
3595
|
-
if (!isWhitespace(text, index - 1)) return text + textToInsert;
|
|
3596
|
-
while (isWhitespace(text, index - 1)) index--;
|
|
3597
|
-
return text.substring(0, index) + textToInsert + text.substring(index);
|
|
3598
|
-
}
|
|
3599
|
-
function removeAtIndex(text, start, count) {
|
|
3600
|
-
return text.substring(0, start) + text.substring(start + count);
|
|
3601
|
-
}
|
|
3602
|
-
/**
|
|
3603
|
-
* Test whether a string ends with a newline or comma character and optional whitespace
|
|
3604
|
-
*/
|
|
3605
|
-
function endsWithCommaOrNewline(text) {
|
|
3606
|
-
return /[,\n][ \t\r]*$/.test(text);
|
|
3607
|
-
}
|
|
3608
|
-
var namedHtmlEntities = {
|
|
3609
|
-
""": "\"",
|
|
3610
|
-
"&": "&",
|
|
3611
|
-
"<": "<",
|
|
3612
|
-
">": ">",
|
|
3613
|
-
"'": "'"
|
|
3614
|
-
};
|
|
3615
|
-
/**
|
|
3616
|
-
* Try to match an HTML entity at the start of the given fragment. The fragment
|
|
3617
|
-
* is a small slice of text that begins exactly at the candidate '&'. Returns the
|
|
3618
|
-
* decoded character and the number of characters consumed, or null when there
|
|
3619
|
-
* is no complete, valid entity (for example a truncated """ without ';').
|
|
3620
|
-
*/
|
|
3621
|
-
function matchHtmlEntity(fragment) {
|
|
3622
|
-
if (fragment.charAt(0) !== "&") return null;
|
|
3623
|
-
const semicolon = fragment.indexOf(";");
|
|
3624
|
-
if (semicolon === -1) return null;
|
|
3625
|
-
const entity = fragment.substring(0, semicolon + 1);
|
|
3626
|
-
const named = namedHtmlEntities[entity];
|
|
3627
|
-
if (named !== void 0) return {
|
|
3628
|
-
char: named,
|
|
3629
|
-
length: entity.length
|
|
3630
|
-
};
|
|
3631
|
-
if (fragment.charAt(1) === "#") {
|
|
3632
|
-
const body = fragment.substring(2, semicolon);
|
|
3633
|
-
const hex = body.charAt(0) === "x" || body.charAt(0) === "X";
|
|
3634
|
-
const digits = hex ? body.substring(1) : body;
|
|
3635
|
-
if (digits.length > 0) {
|
|
3636
|
-
const code = Number.parseInt(digits, hex ? 16 : 10);
|
|
3637
|
-
if (!Number.isNaN(code) && code >= 0 && code <= 1114111) return {
|
|
3638
|
-
char: String.fromCodePoint(code),
|
|
3639
|
-
length: entity.length
|
|
3640
|
-
};
|
|
3641
|
-
}
|
|
3642
|
-
}
|
|
3643
|
-
return null;
|
|
3644
|
-
}
|
|
3645
|
-
/**
|
|
3646
|
-
* Test whether a matched HTML entity decodes to a double quote character
|
|
3647
|
-
*/
|
|
3648
|
-
function isDoubleQuoteEntity(match) {
|
|
3649
|
-
return match !== null && match.char === "\"";
|
|
3650
|
-
}
|
|
3651
|
-
/**
|
|
3652
|
-
* Test whether a matched HTML entity decodes to a single quote character
|
|
3653
|
-
*/
|
|
3654
|
-
function isSingleQuoteEntity(match) {
|
|
3655
|
-
return match !== null && match.char === "'";
|
|
3656
|
-
}
|
|
3657
|
-
/**
|
|
3658
|
-
* Count the number of occurrences of a single character in a string
|
|
3659
|
-
*/
|
|
3660
|
-
function countOccurrences(text, char) {
|
|
3661
|
-
let count = 0;
|
|
3662
|
-
for (let i = 0; i < text.length; i++) if (text.charAt(i) === char) count++;
|
|
3663
|
-
return count;
|
|
3664
|
-
}
|
|
3665
|
-
/**
|
|
3666
|
-
* Test whether `closeChar` is a closing bracket and `text` still contains an
|
|
3667
|
-
* unmatched opening bracket of the same kind. This indicates that the end of
|
|
3668
|
-
* `text` is located inside the brackets, for example the quote in
|
|
3669
|
-
* `"a (b") c"` is followed by `)` while `(` is still unclosed.
|
|
3670
|
-
*
|
|
3671
|
-
* Note that the (potentially expensive) counting is only performed when
|
|
3672
|
-
* `closeChar` actually is a closing bracket.
|
|
3673
|
-
*/
|
|
3674
|
-
function isInsideUnclosedBracket(text, closeChar) {
|
|
3675
|
-
switch (closeChar) {
|
|
3676
|
-
case ")": return countOccurrences(text, "(") > countOccurrences(text, ")");
|
|
3677
|
-
case "]": return countOccurrences(text, "[") > countOccurrences(text, "]");
|
|
3678
|
-
case "}": return countOccurrences(text, "{") > countOccurrences(text, "}");
|
|
3679
|
-
default: return false;
|
|
2228
|
+
timeoutMs,
|
|
2229
|
+
maxResultChars,
|
|
2230
|
+
runId
|
|
2231
|
+
}))
|
|
2232
|
+
};
|
|
2233
|
+
} catch (error) {
|
|
2234
|
+
logger.warn(`MCP server "${config.name}" unavailable: ${errorMessage(error)}`);
|
|
2235
|
+
await client.close().catch(() => {});
|
|
2236
|
+
return {
|
|
2237
|
+
client,
|
|
2238
|
+
status,
|
|
2239
|
+
tools: []
|
|
2240
|
+
};
|
|
3680
2241
|
}
|
|
3681
2242
|
}
|
|
3682
|
-
//#endregion
|
|
3683
|
-
//#region node_modules/jsonrepair/lib/esm/regular/jsonrepair.js
|
|
3684
|
-
var controlCharacters = {
|
|
3685
|
-
"\b": "\\b",
|
|
3686
|
-
"\f": "\\f",
|
|
3687
|
-
"\n": "\\n",
|
|
3688
|
-
"\r": "\\r",
|
|
3689
|
-
" ": "\\t"
|
|
3690
|
-
};
|
|
3691
|
-
var escapeCharacters = {
|
|
3692
|
-
"\"": "\"",
|
|
3693
|
-
"\\": "\\",
|
|
3694
|
-
"/": "/",
|
|
3695
|
-
b: "\b",
|
|
3696
|
-
f: "\f",
|
|
3697
|
-
n: "\n",
|
|
3698
|
-
r: "\r",
|
|
3699
|
-
t: " "
|
|
3700
|
-
};
|
|
3701
2243
|
/**
|
|
3702
|
-
*
|
|
3703
|
-
*
|
|
3704
|
-
*
|
|
3705
|
-
* Example:
|
|
3706
|
-
*
|
|
3707
|
-
* try {
|
|
3708
|
-
* const json = "{name: 'John'}"
|
|
3709
|
-
* const repaired = jsonrepair(json)
|
|
3710
|
-
* console.log(repaired)
|
|
3711
|
-
* // '{"name": "John"}'
|
|
3712
|
-
* } catch (err) {
|
|
3713
|
-
* console.error(err)
|
|
3714
|
-
* }
|
|
3715
|
-
*
|
|
2244
|
+
* Connect every configured server, list its tools, and bridge the read-only
|
|
2245
|
+
* ones. Never throws for a server failure: the server is reported as
|
|
2246
|
+
* `unavailable` and the review continues with the others.
|
|
3716
2247
|
*/
|
|
3717
|
-
function
|
|
3718
|
-
|
|
3719
|
-
|
|
3720
|
-
|
|
3721
|
-
|
|
3722
|
-
|
|
3723
|
-
|
|
3724
|
-
|
|
3725
|
-
|
|
3726
|
-
|
|
3727
|
-
|
|
3728
|
-
|
|
3729
|
-
|
|
3730
|
-
|
|
3731
|
-
const
|
|
3732
|
-
|
|
3733
|
-
|
|
3734
|
-
|
|
3735
|
-
|
|
3736
|
-
|
|
3737
|
-
|
|
3738
|
-
|
|
3739
|
-
|
|
3740
|
-
}
|
|
3741
|
-
if (i >= text.length) return output;
|
|
3742
|
-
throwUnexpectedCharacter();
|
|
3743
|
-
function parseValue() {
|
|
3744
|
-
parseWhitespaceAndSkipComments();
|
|
3745
|
-
const processed = parseObject() || parseArray() || parseString() || parseNumber() || parseKeywords() || parseUnquotedString(false) || parseRegex();
|
|
3746
|
-
parseWhitespaceAndSkipComments();
|
|
3747
|
-
return processed;
|
|
3748
|
-
}
|
|
3749
|
-
function parseWhitespaceAndSkipComments() {
|
|
3750
|
-
let skipNewline = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
|
|
3751
|
-
const start = i;
|
|
3752
|
-
let changed = parseWhitespace(skipNewline);
|
|
3753
|
-
do {
|
|
3754
|
-
changed = parseComment();
|
|
3755
|
-
if (changed) changed = parseWhitespace(skipNewline);
|
|
3756
|
-
} while (changed);
|
|
3757
|
-
return i > start;
|
|
3758
|
-
}
|
|
3759
|
-
function parseWhitespace(skipNewline) {
|
|
3760
|
-
const _isWhiteSpace = skipNewline ? isWhitespace : isWhitespaceExceptNewline;
|
|
3761
|
-
let whitespace = "";
|
|
3762
|
-
while (true) if (_isWhiteSpace(text, i)) {
|
|
3763
|
-
whitespace += text[i];
|
|
3764
|
-
i++;
|
|
3765
|
-
} else if (isSpecialWhitespace(text, i)) {
|
|
3766
|
-
whitespace += " ";
|
|
3767
|
-
i++;
|
|
3768
|
-
} else break;
|
|
3769
|
-
if (whitespace.length > 0) {
|
|
3770
|
-
output += whitespace;
|
|
3771
|
-
return true;
|
|
3772
|
-
}
|
|
3773
|
-
return false;
|
|
3774
|
-
}
|
|
3775
|
-
function parseComment() {
|
|
3776
|
-
if (text[i] === "/" && text[i + 1] === "*") {
|
|
3777
|
-
while (i < text.length && !atEndOfBlockComment(text, i)) i++;
|
|
3778
|
-
i += 2;
|
|
3779
|
-
return true;
|
|
3780
|
-
}
|
|
3781
|
-
if (text[i] === "/" && text[i + 1] === "/") {
|
|
3782
|
-
while (i < text.length && text[i] !== "\n") i++;
|
|
3783
|
-
return true;
|
|
3784
|
-
}
|
|
3785
|
-
return false;
|
|
3786
|
-
}
|
|
3787
|
-
function parseMarkdownCodeBlock(blocks) {
|
|
3788
|
-
if (skipMarkdownCodeBlock(blocks)) {
|
|
3789
|
-
if (isFunctionNameCharStart(text[i])) while (i < text.length && isFunctionNameChar(text[i])) i++;
|
|
3790
|
-
parseWhitespaceAndSkipComments();
|
|
3791
|
-
return true;
|
|
3792
|
-
}
|
|
3793
|
-
return false;
|
|
3794
|
-
}
|
|
3795
|
-
function skipMarkdownCodeBlock(blocks) {
|
|
3796
|
-
parseWhitespace(true);
|
|
3797
|
-
for (const block of blocks) {
|
|
3798
|
-
const end = i + block.length;
|
|
3799
|
-
if (text.slice(i, end) === block) {
|
|
3800
|
-
i = end;
|
|
3801
|
-
return true;
|
|
3802
|
-
}
|
|
3803
|
-
}
|
|
3804
|
-
return false;
|
|
3805
|
-
}
|
|
3806
|
-
function parseCharacter(char) {
|
|
3807
|
-
if (text[i] === char) {
|
|
3808
|
-
output += text[i];
|
|
3809
|
-
i++;
|
|
3810
|
-
return true;
|
|
3811
|
-
}
|
|
3812
|
-
return false;
|
|
3813
|
-
}
|
|
3814
|
-
function skipCharacter(char) {
|
|
3815
|
-
if (text[i] === char) {
|
|
3816
|
-
i++;
|
|
3817
|
-
return true;
|
|
3818
|
-
}
|
|
3819
|
-
return false;
|
|
3820
|
-
}
|
|
3821
|
-
function skipEscapeCharacter() {
|
|
3822
|
-
return skipCharacter("\\");
|
|
3823
|
-
}
|
|
3824
|
-
/**
|
|
3825
|
-
* Skip ellipsis like "[1,2,3,...]" or "[1,2,3,...,9]" or "[...,7,8,9]"
|
|
3826
|
-
* or a similar construct in objects.
|
|
3827
|
-
*/
|
|
3828
|
-
function skipEllipsis() {
|
|
3829
|
-
parseWhitespaceAndSkipComments();
|
|
3830
|
-
if (text[i] === "." && text[i + 1] === "." && text[i + 2] === ".") {
|
|
3831
|
-
i += 3;
|
|
3832
|
-
parseWhitespaceAndSkipComments();
|
|
3833
|
-
skipCharacter(",");
|
|
3834
|
-
return true;
|
|
3835
|
-
}
|
|
3836
|
-
return false;
|
|
3837
|
-
}
|
|
3838
|
-
/**
|
|
3839
|
-
* Parse an object like '{"key": "value"}'
|
|
3840
|
-
*/
|
|
3841
|
-
function parseObject() {
|
|
3842
|
-
if (text[i] === "{") {
|
|
3843
|
-
output += "{";
|
|
3844
|
-
i++;
|
|
3845
|
-
parseWhitespaceAndSkipComments();
|
|
3846
|
-
if (skipCharacter(",")) parseWhitespaceAndSkipComments();
|
|
3847
|
-
let initial = true;
|
|
3848
|
-
while (i < text.length && text[i] !== "}") {
|
|
3849
|
-
let processedComma;
|
|
3850
|
-
if (!initial) {
|
|
3851
|
-
processedComma = parseCharacter(",");
|
|
3852
|
-
if (!processedComma) output = insertBeforeLastWhitespace(output, ",");
|
|
3853
|
-
parseWhitespaceAndSkipComments();
|
|
3854
|
-
} else processedComma = true;
|
|
3855
|
-
skipEllipsis();
|
|
3856
|
-
if (!(parseString() || parseUnquotedString(true))) {
|
|
3857
|
-
if (text[i] === "}" || text[i] === "{" || text[i] === "]" || text[i] === "[" || text[i] === void 0) {
|
|
3858
|
-
if (!initial) output = stripLastOccurrence(output, ",");
|
|
3859
|
-
} else throwObjectKeyExpected();
|
|
3860
|
-
break;
|
|
3861
|
-
}
|
|
3862
|
-
parseWhitespaceAndSkipComments();
|
|
3863
|
-
const processedColon = parseCharacter(":");
|
|
3864
|
-
const truncatedText = i >= text.length;
|
|
3865
|
-
if (!processedColon) {
|
|
3866
|
-
if (isStartOfValue(text[i]) || truncatedText) output = insertBeforeLastWhitespace(output, ":");
|
|
3867
|
-
else throwColonExpected();
|
|
3868
|
-
}
|
|
3869
|
-
if (!parseValue()) {
|
|
3870
|
-
if (processedColon || truncatedText) output += "null";
|
|
3871
|
-
else throwColonExpected();
|
|
3872
|
-
}
|
|
3873
|
-
initial = false;
|
|
3874
|
-
}
|
|
3875
|
-
if (text[i] === "}") {
|
|
3876
|
-
output += "}";
|
|
3877
|
-
i++;
|
|
3878
|
-
} else output = insertBeforeLastWhitespace(output, "}");
|
|
3879
|
-
return true;
|
|
3880
|
-
}
|
|
3881
|
-
return false;
|
|
3882
|
-
}
|
|
3883
|
-
/**
|
|
3884
|
-
* Parse an array like '["item1", "item2", ...]'
|
|
3885
|
-
*/
|
|
3886
|
-
function parseArray() {
|
|
3887
|
-
if (text[i] === "[") {
|
|
3888
|
-
output += "[";
|
|
3889
|
-
i++;
|
|
3890
|
-
parseWhitespaceAndSkipComments();
|
|
3891
|
-
if (skipCharacter(",")) parseWhitespaceAndSkipComments();
|
|
3892
|
-
let initial = true;
|
|
3893
|
-
while (i < text.length && text[i] !== "]") {
|
|
3894
|
-
if (!initial) {
|
|
3895
|
-
if (!parseCharacter(",")) output = insertBeforeLastWhitespace(output, ",");
|
|
3896
|
-
}
|
|
3897
|
-
skipEllipsis();
|
|
3898
|
-
if (!parseValue()) {
|
|
3899
|
-
if (!initial) output = stripLastOccurrence(output, ",");
|
|
3900
|
-
break;
|
|
3901
|
-
}
|
|
3902
|
-
initial = false;
|
|
3903
|
-
}
|
|
3904
|
-
if (text[i] === "]") {
|
|
3905
|
-
output += "]";
|
|
3906
|
-
i++;
|
|
3907
|
-
} else output = insertBeforeLastWhitespace(output, "]");
|
|
3908
|
-
return true;
|
|
3909
|
-
}
|
|
3910
|
-
return false;
|
|
3911
|
-
}
|
|
3912
|
-
/**
|
|
3913
|
-
* Parse and repair Newline Delimited JSON (NDJSON):
|
|
3914
|
-
* multiple JSON objects separated by a newline character
|
|
3915
|
-
*/
|
|
3916
|
-
function parseNewlineDelimitedJSON() {
|
|
3917
|
-
let initial = true;
|
|
3918
|
-
let processedValue = true;
|
|
3919
|
-
while (processedValue) {
|
|
3920
|
-
if (!initial) {
|
|
3921
|
-
if (!parseCharacter(",")) output = insertBeforeLastWhitespace(output, ",");
|
|
3922
|
-
} else initial = false;
|
|
3923
|
-
processedValue = parseValue();
|
|
3924
|
-
}
|
|
3925
|
-
if (!processedValue) output = stripLastOccurrence(output, ",");
|
|
3926
|
-
output = `[\n${output}\n]`;
|
|
3927
|
-
}
|
|
3928
|
-
/**
|
|
3929
|
-
* Parse a string enclosed by double quotes "...". Can contain escaped quotes
|
|
3930
|
-
* Repair strings enclosed in single quotes or special quotes
|
|
3931
|
-
* Repair an escaped string
|
|
3932
|
-
*
|
|
3933
|
-
* The function can run in two stages:
|
|
3934
|
-
* - First, it assumes the string has a valid end quote
|
|
3935
|
-
* - If it turns out that the string does not have a valid end quote followed
|
|
3936
|
-
* by a delimiter (which should be the case), the function runs again in a
|
|
3937
|
-
* more conservative way, stopping the string at the first next delimiter
|
|
3938
|
-
* and fixing the string by inserting a quote there, or stopping at a
|
|
3939
|
-
* stop index detected in the first iteration.
|
|
3940
|
-
*/
|
|
3941
|
-
function parseString() {
|
|
3942
|
-
let stopAtDelimiter = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false;
|
|
3943
|
-
let stopAtIndex = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : -1;
|
|
3944
|
-
const skipEscapeChars = text[i] === "\\";
|
|
3945
|
-
if (skipEscapeChars) {
|
|
3946
|
-
i++;
|
|
3947
|
-
if (!isQuote(text[i])) throwUnexpectedCharacter();
|
|
3948
|
-
}
|
|
3949
|
-
const openEntity = text[i] === "&" ? matchHtmlEntity(text.slice(i, i + 12)) : null;
|
|
3950
|
-
const openedByEntity = isDoubleQuoteEntity(openEntity) || isSingleQuoteEntity(openEntity);
|
|
3951
|
-
if (isQuote(text[i]) || openedByEntity) {
|
|
3952
|
-
const isEndQuote = isDoubleQuote(text[i]) ? isDoubleQuote : isSingleQuote(text[i]) ? isSingleQuote : isSingleQuoteLike(text[i]) ? isSingleQuoteLike : isDoubleQuoteLike;
|
|
3953
|
-
const iBefore = i;
|
|
3954
|
-
const oBefore = output.length;
|
|
3955
|
-
let str = "\"";
|
|
3956
|
-
i += openedByEntity && openEntity ? openEntity.length : 1;
|
|
3957
|
-
while (true) {
|
|
3958
|
-
if (i >= text.length) {
|
|
3959
|
-
const iPrev = prevNonWhitespaceIndex(i - 1);
|
|
3960
|
-
if (!stopAtDelimiter && isDelimiter(text.charAt(iPrev))) {
|
|
3961
|
-
i = iBefore;
|
|
3962
|
-
output = output.substring(0, oBefore);
|
|
3963
|
-
return parseString(true);
|
|
3964
|
-
}
|
|
3965
|
-
str = insertBeforeLastWhitespace(str, "\"");
|
|
3966
|
-
output += str;
|
|
3967
|
-
return true;
|
|
3968
|
-
}
|
|
3969
|
-
if (i === stopAtIndex) {
|
|
3970
|
-
str = insertBeforeLastWhitespace(str, "\"");
|
|
3971
|
-
output += str;
|
|
3972
|
-
return true;
|
|
3973
|
-
}
|
|
3974
|
-
const entity = openedByEntity && text[i] === "&" ? matchHtmlEntity(text.slice(i, i + 12)) : null;
|
|
3975
|
-
if (entity && openEntity ? entity.char === openEntity.char : isEndQuote(text[i])) {
|
|
3976
|
-
const iQuote = i;
|
|
3977
|
-
const oQuote = str.length;
|
|
3978
|
-
str += "\"";
|
|
3979
|
-
i += entity ? entity.length : 1;
|
|
3980
|
-
output += str;
|
|
3981
|
-
parseWhitespaceAndSkipComments(false);
|
|
3982
|
-
if (stopAtDelimiter || i >= text.length || isDelimiter(text[i]) && !isInsideUnclosedBracket(str, text[i]) || isQuote(text[i]) && !nextQuoteIsEndQuote(i) || isDigit(text[i])) {
|
|
3983
|
-
parseConcatenatedString();
|
|
3984
|
-
return true;
|
|
3985
|
-
}
|
|
3986
|
-
if (text[i] === "\\") throwUnexpectedCharacter();
|
|
3987
|
-
const iPrevChar = prevNonWhitespaceIndex(iQuote - 1);
|
|
3988
|
-
const prevChar = text.charAt(iPrevChar);
|
|
3989
|
-
if (prevChar === ",") {
|
|
3990
|
-
i = iBefore;
|
|
3991
|
-
output = output.substring(0, oBefore);
|
|
3992
|
-
return parseString(false, iPrevChar);
|
|
3993
|
-
}
|
|
3994
|
-
if (isDelimiter(prevChar)) {
|
|
3995
|
-
i = iBefore;
|
|
3996
|
-
output = output.substring(0, oBefore);
|
|
3997
|
-
return parseString(true);
|
|
3998
|
-
}
|
|
3999
|
-
output = output.substring(0, oBefore);
|
|
4000
|
-
i = iQuote + (entity ? entity.length : 1);
|
|
4001
|
-
str = `${str.substring(0, oQuote)}\\${str.substring(oQuote)}`;
|
|
4002
|
-
} else if (stopAtDelimiter && isUnquotedStringDelimiter(text[i])) {
|
|
4003
|
-
if (text[i - 1] === ":" && regexUrlStart.test(text.substring(iBefore + 1, i + 2))) while (i < text.length && regexUrlChar.test(text[i])) {
|
|
4004
|
-
str += text[i];
|
|
4005
|
-
i++;
|
|
4006
|
-
}
|
|
4007
|
-
str = insertBeforeLastWhitespace(str, "\"");
|
|
4008
|
-
output += str;
|
|
4009
|
-
parseConcatenatedString();
|
|
4010
|
-
return true;
|
|
4011
|
-
} else if (entity) {
|
|
4012
|
-
const char = entity.char;
|
|
4013
|
-
if (char === "\"") str += "\\\"";
|
|
4014
|
-
else if (isControlCharacter(char)) str += controlCharacters[char];
|
|
4015
|
-
else str += char;
|
|
4016
|
-
i += entity.length;
|
|
4017
|
-
} else if (text[i] === "\\") {
|
|
4018
|
-
const char = text.charAt(i + 1);
|
|
4019
|
-
if (escapeCharacters[char] !== void 0) {
|
|
4020
|
-
str += text.slice(i, i + 2);
|
|
4021
|
-
i += 2;
|
|
4022
|
-
} else if (char === "u") {
|
|
4023
|
-
let j = 2;
|
|
4024
|
-
while (j < 6 && isHex(text[i + j])) j++;
|
|
4025
|
-
if (j === 6) {
|
|
4026
|
-
str += text.slice(i, i + 6);
|
|
4027
|
-
i += 6;
|
|
4028
|
-
} else if (i + j >= text.length) i = text.length;
|
|
4029
|
-
else throwInvalidUnicodeCharacter();
|
|
4030
|
-
} else if (char === "\n") {
|
|
4031
|
-
str += "\\n";
|
|
4032
|
-
i += 2;
|
|
4033
|
-
} else {
|
|
4034
|
-
str += char;
|
|
4035
|
-
i += 2;
|
|
4036
|
-
}
|
|
4037
|
-
} else {
|
|
4038
|
-
const char = text.charAt(i);
|
|
4039
|
-
if (char === "\"" && text[i - 1] !== "\\") {
|
|
4040
|
-
str += `\\${char}`;
|
|
4041
|
-
i++;
|
|
4042
|
-
} else if (isControlCharacter(char)) {
|
|
4043
|
-
str += controlCharacters[char];
|
|
4044
|
-
i++;
|
|
4045
|
-
} else {
|
|
4046
|
-
if (!isValidStringCharacter(char)) throwInvalidCharacter(char);
|
|
4047
|
-
str += char;
|
|
4048
|
-
i++;
|
|
4049
|
-
}
|
|
4050
|
-
}
|
|
4051
|
-
if (skipEscapeChars) skipEscapeCharacter();
|
|
4052
|
-
}
|
|
4053
|
-
}
|
|
4054
|
-
return false;
|
|
4055
|
-
}
|
|
4056
|
-
/**
|
|
4057
|
-
* Repair concatenated strings like "hello" + "world", change this into "helloworld"
|
|
4058
|
-
*/
|
|
4059
|
-
function parseConcatenatedString() {
|
|
4060
|
-
let processed = false;
|
|
4061
|
-
parseWhitespaceAndSkipComments();
|
|
4062
|
-
while (text[i] === "+") {
|
|
4063
|
-
processed = true;
|
|
4064
|
-
i++;
|
|
4065
|
-
parseWhitespaceAndSkipComments();
|
|
4066
|
-
output = stripLastOccurrence(output, "\"", true);
|
|
4067
|
-
const start = output.length;
|
|
4068
|
-
if (parseString()) output = removeAtIndex(output, start, 1);
|
|
4069
|
-
else output = insertBeforeLastWhitespace(output, "\"");
|
|
4070
|
-
}
|
|
4071
|
-
return processed;
|
|
4072
|
-
}
|
|
4073
|
-
/**
|
|
4074
|
-
* Parse a number like 2.4 or 2.4e6
|
|
4075
|
-
*/
|
|
4076
|
-
function parseNumber() {
|
|
4077
|
-
const start = i;
|
|
4078
|
-
let num = "";
|
|
4079
|
-
let invalid = false;
|
|
4080
|
-
if (text[i] === "-") {
|
|
4081
|
-
num += text[i];
|
|
4082
|
-
i++;
|
|
4083
|
-
if (!isDigit(text[i]) && atEndOfNumber()) num += "0";
|
|
4084
|
-
}
|
|
4085
|
-
if (text[i] === "0" && isDigit(text[i + 1])) invalid = true;
|
|
4086
|
-
while (isDigit(text[i])) {
|
|
4087
|
-
num += text[i];
|
|
4088
|
-
i++;
|
|
4089
|
-
}
|
|
4090
|
-
if (text[i] === ".") {
|
|
4091
|
-
if (num === "" || num === "-") num += "0";
|
|
4092
|
-
num += text[i];
|
|
4093
|
-
i++;
|
|
4094
|
-
if (!isDigit(text[i])) num += "0";
|
|
4095
|
-
while (isDigit(text[i])) {
|
|
4096
|
-
num += text[i];
|
|
4097
|
-
i++;
|
|
4098
|
-
}
|
|
4099
|
-
}
|
|
4100
|
-
if (i > start) {
|
|
4101
|
-
if (text[i] === "e" || text[i] === "E") {
|
|
4102
|
-
if (num === "-") invalid = true;
|
|
4103
|
-
num += text[i];
|
|
4104
|
-
i++;
|
|
4105
|
-
if (text[i] === "-" || text[i] === "+") {
|
|
4106
|
-
num += text[i];
|
|
4107
|
-
i++;
|
|
4108
|
-
}
|
|
4109
|
-
if (!isDigit(text[i])) num += "0";
|
|
4110
|
-
while (isDigit(text[i])) {
|
|
4111
|
-
num += text[i];
|
|
4112
|
-
i++;
|
|
4113
|
-
}
|
|
4114
|
-
}
|
|
4115
|
-
if (!atEndOfNumber()) {
|
|
4116
|
-
i = start;
|
|
4117
|
-
return false;
|
|
4118
|
-
}
|
|
4119
|
-
output += invalid ? `"${text.substring(start, i)}"` : num;
|
|
4120
|
-
return true;
|
|
4121
|
-
}
|
|
4122
|
-
return false;
|
|
4123
|
-
}
|
|
4124
|
-
/**
|
|
4125
|
-
* Parse keywords true, false, null
|
|
4126
|
-
* Repair Python keywords True, False, None
|
|
4127
|
-
*/
|
|
4128
|
-
function parseKeywords() {
|
|
4129
|
-
return parseKeyword("true", "true") || parseKeyword("false", "false") || parseKeyword("null", "null") || parseKeyword("True", "true") || parseKeyword("False", "false") || parseKeyword("None", "null");
|
|
4130
|
-
}
|
|
4131
|
-
function parseKeyword(name, value) {
|
|
4132
|
-
if (text.slice(i, i + name.length) === name && !isFunctionNameChar(text[i + name.length])) {
|
|
4133
|
-
output += value;
|
|
4134
|
-
i += name.length;
|
|
4135
|
-
return true;
|
|
4136
|
-
}
|
|
4137
|
-
return false;
|
|
4138
|
-
}
|
|
4139
|
-
/**
|
|
4140
|
-
* Repair an unquoted string by adding quotes around it
|
|
4141
|
-
* Repair a MongoDB function call like NumberLong("2")
|
|
4142
|
-
* Repair a JSONP function call like callback({...});
|
|
4143
|
-
*/
|
|
4144
|
-
function parseUnquotedString(isKey) {
|
|
4145
|
-
const start = i;
|
|
4146
|
-
if (isFunctionNameCharStart(text[i])) {
|
|
4147
|
-
while (i < text.length && isFunctionNameChar(text[i])) i++;
|
|
4148
|
-
let j = i;
|
|
4149
|
-
while (isWhitespace(text, j)) j++;
|
|
4150
|
-
if (text[j] === "(") {
|
|
4151
|
-
i = j + 1;
|
|
4152
|
-
parseValue();
|
|
4153
|
-
if (text[i] === ")") {
|
|
4154
|
-
i++;
|
|
4155
|
-
if (text[i] === ";") i++;
|
|
4156
|
-
}
|
|
4157
|
-
return true;
|
|
4158
|
-
}
|
|
4159
|
-
}
|
|
4160
|
-
while (i < text.length && !isUnquotedStringDelimiter(text[i]) && !isQuote(text[i]) && (!isKey || text[i] !== ":")) i++;
|
|
4161
|
-
if (text[i - 1] === ":" && regexUrlStart.test(text.substring(start, i + 2))) while (i < text.length && regexUrlChar.test(text[i])) i++;
|
|
4162
|
-
if (i > start) {
|
|
4163
|
-
while (isWhitespace(text, i - 1) && i > 0) i--;
|
|
4164
|
-
const symbol = text.slice(start, i);
|
|
4165
|
-
output += symbol === "undefined" ? "null" : JSON.stringify(symbol);
|
|
4166
|
-
if (text[i] === "\"") i++;
|
|
4167
|
-
return true;
|
|
2248
|
+
async function connectMcpServers(configs, options = {}) {
|
|
2249
|
+
const total = options.callBudget ?? 40;
|
|
2250
|
+
const resolved = {
|
|
2251
|
+
logger: options.logger ?? noopLogger,
|
|
2252
|
+
timeoutMs: options.timeoutMs ?? 3e4,
|
|
2253
|
+
callBudget: total,
|
|
2254
|
+
maxResultChars: options.maxResultChars ?? 2e5,
|
|
2255
|
+
createTransport: options.createTransport ?? createMcpTransport,
|
|
2256
|
+
budget: {
|
|
2257
|
+
remaining: total,
|
|
2258
|
+
total
|
|
2259
|
+
},
|
|
2260
|
+
runId: options.runId
|
|
2261
|
+
};
|
|
2262
|
+
const connected = await Promise.all(configs.map((config) => connectOne(config, resolved)));
|
|
2263
|
+
const emitted = /* @__PURE__ */ new Set();
|
|
2264
|
+
const tools = [];
|
|
2265
|
+
for (const server of connected) for (const tool of server.tools) {
|
|
2266
|
+
if (emitted.has(tool.name)) {
|
|
2267
|
+
resolved.logger.warn(`MCP server "${server.status.name}": tool "${tool.name}" collides with an already-bridged tool name — dropped.`);
|
|
2268
|
+
const index = server.status.tools.findIndex((name) => mcpToolName(server.status.name, name) === tool.name);
|
|
2269
|
+
if (index !== -1) server.status.tools.splice(index, 1);
|
|
2270
|
+
continue;
|
|
4168
2271
|
}
|
|
2272
|
+
emitted.add(tool.name);
|
|
2273
|
+
tools.push(tool);
|
|
4169
2274
|
}
|
|
4170
|
-
|
|
4171
|
-
|
|
4172
|
-
|
|
4173
|
-
|
|
4174
|
-
|
|
4175
|
-
|
|
4176
|
-
|
|
4177
|
-
|
|
2275
|
+
let closed = false;
|
|
2276
|
+
return {
|
|
2277
|
+
tools,
|
|
2278
|
+
servers: connected.map((server) => server.status),
|
|
2279
|
+
async close() {
|
|
2280
|
+
if (closed) return;
|
|
2281
|
+
closed = true;
|
|
2282
|
+
await Promise.all(connected.filter((server) => server.status.status === "connected").map((server) => server.client.close().catch(() => {})));
|
|
4178
2283
|
}
|
|
4179
|
-
}
|
|
4180
|
-
function prevNonWhitespaceIndex(start) {
|
|
4181
|
-
let prev = start;
|
|
4182
|
-
while (prev > 0 && isWhitespace(text, prev)) prev--;
|
|
4183
|
-
return prev;
|
|
4184
|
-
}
|
|
4185
|
-
function nextQuoteIsEndQuote(index) {
|
|
4186
|
-
let next = index + 1;
|
|
4187
|
-
while (next < text.length && isWhitespace(text, next)) next++;
|
|
4188
|
-
return next >= text.length || isDelimiter(text[next]);
|
|
4189
|
-
}
|
|
4190
|
-
function atEndOfNumber() {
|
|
4191
|
-
return i >= text.length || isDelimiter(text[i]) || isWhitespace(text, i);
|
|
4192
|
-
}
|
|
4193
|
-
function throwInvalidCharacter(char) {
|
|
4194
|
-
throw new JSONRepairError(`Invalid character ${JSON.stringify(char)}`, i);
|
|
4195
|
-
}
|
|
4196
|
-
function throwUnexpectedCharacter() {
|
|
4197
|
-
throw new JSONRepairError(`Unexpected character ${JSON.stringify(text[i])}`, i);
|
|
4198
|
-
}
|
|
4199
|
-
function throwUnexpectedEnd() {
|
|
4200
|
-
throw new JSONRepairError("Unexpected end of json string", text.length);
|
|
4201
|
-
}
|
|
4202
|
-
function throwObjectKeyExpected() {
|
|
4203
|
-
throw new JSONRepairError("Object key expected", i);
|
|
4204
|
-
}
|
|
4205
|
-
function throwColonExpected() {
|
|
4206
|
-
throw new JSONRepairError("Colon expected", i);
|
|
4207
|
-
}
|
|
4208
|
-
function throwInvalidUnicodeCharacter() {
|
|
4209
|
-
throw new JSONRepairError(`Invalid unicode character "${text.slice(i, i + 6)}"`, i);
|
|
4210
|
-
}
|
|
4211
|
-
}
|
|
4212
|
-
function atEndOfBlockComment(text, i) {
|
|
4213
|
-
return text[i] === "*" && text[i + 1] === "/";
|
|
2284
|
+
};
|
|
4214
2285
|
}
|
|
4215
2286
|
//#endregion
|
|
4216
2287
|
//#region src/verify.ts
|
|
@@ -4867,88 +2938,6 @@ function escapeXml(text) {
|
|
|
4867
2938
|
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
4868
2939
|
}
|
|
4869
2940
|
//#endregion
|
|
4870
|
-
//#region src/skill-usage.ts
|
|
4871
|
-
/**
|
|
4872
|
-
* The path a built-in read tool call targets, or `undefined` for any other tool
|
|
4873
|
-
* or a call with no usable `path`. The parameter name is `path`, matching the
|
|
4874
|
-
* `read` tool from `createReadOnlyTools` that the reviewer is actually handed.
|
|
4875
|
-
* Only the built-in read tool is considered: a skill is loaded by reading its
|
|
4876
|
-
* `SKILL.md`, and every other tool (grep, git, MCP) says nothing about whether
|
|
4877
|
-
* the reviewer read the skill.
|
|
4878
|
-
*/
|
|
4879
|
-
function readToolPath(toolName, args) {
|
|
4880
|
-
if (toolName !== "Read" && toolName !== "read") return void 0;
|
|
4881
|
-
if (!args || typeof args !== "object") return void 0;
|
|
4882
|
-
const filePath = args.path;
|
|
4883
|
-
return typeof filePath === "string" && filePath.length > 0 ? filePath : void 0;
|
|
4884
|
-
}
|
|
4885
|
-
/**
|
|
4886
|
-
* The skill whose directory contains `path`, or `undefined` when the read
|
|
4887
|
-
* targeted something else. Any file under the skill root counts — a reference
|
|
4888
|
-
* file the `SKILL.md` points at is as much a skill read as the `SKILL.md`
|
|
4889
|
-
* itself. Relative paths resolve against `cwd` — the review working directory
|
|
4890
|
-
* the reviewer's read tool resolves them against, which `--cwd` can move away
|
|
4891
|
-
* from the process working directory.
|
|
4892
|
-
*/
|
|
4893
|
-
function findSkillForPath(skills, path, cwd) {
|
|
4894
|
-
const target = resolve(cwd, path);
|
|
4895
|
-
return skills.find((skill) => {
|
|
4896
|
-
const rel = relative(resolve(skill.rootDir), target);
|
|
4897
|
-
return rel.length > 0 && !rel.startsWith("..") && !isAbsolute(rel);
|
|
4898
|
-
});
|
|
4899
|
-
}
|
|
4900
|
-
/**
|
|
4901
|
-
* Build a counter shared by every review stage — Find and Verify run different
|
|
4902
|
-
* agents over the same tool list, so a skill read in either stage counts.
|
|
4903
|
-
*/
|
|
4904
|
-
function createSkillReadCounter(skills, cwd) {
|
|
4905
|
-
const counts = /* @__PURE__ */ new Map();
|
|
4906
|
-
return {
|
|
4907
|
-
record(toolName, args) {
|
|
4908
|
-
const path = readToolPath(toolName, args);
|
|
4909
|
-
if (!path) return;
|
|
4910
|
-
const skill = findSkillForPath(skills, path, cwd);
|
|
4911
|
-
if (!skill) return;
|
|
4912
|
-
counts.set(skill.rootDir, (counts.get(skill.rootDir) ?? 0) + 1);
|
|
4913
|
-
},
|
|
4914
|
-
countFor(skill) {
|
|
4915
|
-
return counts.get(skill.rootDir) ?? 0;
|
|
4916
|
-
}
|
|
4917
|
-
};
|
|
4918
|
-
}
|
|
4919
|
-
/** Whether a skill was read, as shown in the footer and the usage log line. */
|
|
4920
|
-
function formatSkillUsageState(skill) {
|
|
4921
|
-
return skill.reads > 0 ? "read" : "not read";
|
|
4922
|
-
}
|
|
4923
|
-
/**
|
|
4924
|
-
* How much a server was used, as shown in the footer and the usage log line:
|
|
4925
|
-
* a pluralised call count, `unused` for a server that connected but was never
|
|
4926
|
-
* called, and `unavailable` for one that failed to connect.
|
|
4927
|
-
*/
|
|
4928
|
-
function formatMcpUsageState(server) {
|
|
4929
|
-
if (server.status !== "connected") return "unavailable";
|
|
4930
|
-
if (server.calls <= 0) return "unused";
|
|
4931
|
-
return `${server.calls} call${server.calls === 1 ? "" : "s"}`;
|
|
4932
|
-
}
|
|
4933
|
-
/**
|
|
4934
|
-
* The end-of-review usage log line, e.g.
|
|
4935
|
-
* `Usage: skills code-review (read); MCP github (1 call), docs (unused)`.
|
|
4936
|
-
* Each half is omitted when nothing of that kind was configured, and the whole
|
|
4937
|
-
* line is `undefined` when neither was.
|
|
4938
|
-
*/
|
|
4939
|
-
function formatReviewUsageSummary(usage) {
|
|
4940
|
-
const parts = [];
|
|
4941
|
-
if (usage.skills.length > 0) {
|
|
4942
|
-
const skills = usage.skills.map((s) => `${s.name} (${formatSkillUsageState(s)})`).join(", ");
|
|
4943
|
-
parts.push(`skills ${skills}`);
|
|
4944
|
-
}
|
|
4945
|
-
if (usage.mcp.length > 0) {
|
|
4946
|
-
const servers = usage.mcp.map((s) => `${s.name} (${formatMcpUsageState(s)})`).join(", ");
|
|
4947
|
-
parts.push(`MCP ${servers}`);
|
|
4948
|
-
}
|
|
4949
|
-
return parts.length > 0 ? `Usage: ${parts.join("; ")}` : void 0;
|
|
4950
|
-
}
|
|
4951
|
-
//#endregion
|
|
4952
2941
|
//#region src/skipped-retrieval.ts
|
|
4953
2942
|
/** Directory (relative to cwd) where dropped-file diffs are staged for retrieval. */
|
|
4954
2943
|
var SKIPPED_DIFF_DIR = ".code-review-skipped";
|
|
@@ -5162,13 +3151,7 @@ function triageFindings(groups) {
|
|
|
5162
3151
|
//#region src/gitlab-review.ts
|
|
5163
3152
|
var DEFAULT_REVIEW_TIMEOUT_MS = 6e5;
|
|
5164
3153
|
var DEFAULT_MAX_DIFF_CHARS = 1e5;
|
|
5165
|
-
var CONVENTION_FILES = ["AGENTS.md", "CLAUDE.md"];
|
|
5166
3154
|
var REVIEW_RULE_FILES = ["REVIEW.md"];
|
|
5167
|
-
var CONFIG_DIRS = [
|
|
5168
|
-
".pi",
|
|
5169
|
-
".claude",
|
|
5170
|
-
".agents"
|
|
5171
|
-
];
|
|
5172
3155
|
var NOISE_PATH_PATTERNS = [
|
|
5173
3156
|
/^gitlab-review\.md$/,
|
|
5174
3157
|
/(^|\/)\.yarn\//,
|
|
@@ -5213,7 +3196,6 @@ var SEVERITY_RULE = {
|
|
|
5213
3196
|
WARN: "- Only report CRITICAL and WARN issues — skip INFO",
|
|
5214
3197
|
CRITICAL: "- Only report CRITICAL issues — skip WARN and INFO"
|
|
5215
3198
|
};
|
|
5216
|
-
var exec = promisify(execFile);
|
|
5217
3199
|
/**
|
|
5218
3200
|
* Stream function for the reviewer agent.
|
|
5219
3201
|
*
|
|
@@ -5245,82 +3227,20 @@ function defaultCreateAgent(params) {
|
|
|
5245
3227
|
streamFn: createReviewStreamFn()
|
|
5246
3228
|
});
|
|
5247
3229
|
}
|
|
5248
|
-
async function findGitRoot(cwd) {
|
|
5249
|
-
try {
|
|
5250
|
-
const { stdout } = await exec("git", ["rev-parse", "--show-toplevel"], { cwd });
|
|
5251
|
-
return stdout.trim() || cwd;
|
|
5252
|
-
} catch {
|
|
5253
|
-
return cwd;
|
|
5254
|
-
}
|
|
5255
|
-
}
|
|
5256
|
-
async function readFirstMatch(dir, filenames) {
|
|
5257
|
-
for (const candidate of [dir, ...CONFIG_DIRS.map((d) => join(dir, d))]) {
|
|
5258
|
-
let entries;
|
|
5259
|
-
try {
|
|
5260
|
-
entries = await readdir(candidate);
|
|
5261
|
-
} catch {
|
|
5262
|
-
continue;
|
|
5263
|
-
}
|
|
5264
|
-
const wanted = new Set(filenames.map((f) => f.toLowerCase()));
|
|
5265
|
-
const match = entries.find((entry) => wanted.has(entry.toLowerCase()));
|
|
5266
|
-
if (!match) continue;
|
|
5267
|
-
const fullPath = join(candidate, match);
|
|
5268
|
-
try {
|
|
5269
|
-
return {
|
|
5270
|
-
path: fullPath,
|
|
5271
|
-
content: await readFile(fullPath, "utf8")
|
|
5272
|
-
};
|
|
5273
|
-
} catch {
|
|
5274
|
-
continue;
|
|
5275
|
-
}
|
|
5276
|
-
}
|
|
5277
|
-
return null;
|
|
5278
|
-
}
|
|
5279
|
-
async function walkUpContextFiles(cwd, filenames, gitRoot) {
|
|
5280
|
-
const dirs = [];
|
|
5281
|
-
let current = cwd;
|
|
5282
|
-
while (true) {
|
|
5283
|
-
dirs.unshift(current);
|
|
5284
|
-
if (current === gitRoot) break;
|
|
5285
|
-
const parent = dirname(current);
|
|
5286
|
-
if (parent === current) break;
|
|
5287
|
-
current = parent;
|
|
5288
|
-
}
|
|
5289
|
-
const result = [];
|
|
5290
|
-
const seen = /* @__PURE__ */ new Set();
|
|
5291
|
-
for (const dir of dirs) {
|
|
5292
|
-
const file = await readFirstMatch(dir, filenames);
|
|
5293
|
-
if (!file || seen.has(file.path)) continue;
|
|
5294
|
-
seen.add(file.path);
|
|
5295
|
-
result.push({
|
|
5296
|
-
path: relative(cwd, file.path) || file.path,
|
|
5297
|
-
content: file.content
|
|
5298
|
-
});
|
|
5299
|
-
}
|
|
5300
|
-
return result;
|
|
5301
|
-
}
|
|
5302
3230
|
async function loadReviewContext(cwd, skillNames = [], warn, options = {}) {
|
|
5303
3231
|
const gitRoot = await findGitRoot(cwd);
|
|
5304
|
-
const [conventions, reviewRules,
|
|
3232
|
+
const [conventions, reviewRules, skills] = await Promise.all([
|
|
5305
3233
|
walkUpContextFiles(cwd, CONVENTION_FILES, gitRoot),
|
|
5306
3234
|
walkUpContextFiles(cwd, REVIEW_RULE_FILES, gitRoot),
|
|
5307
|
-
|
|
3235
|
+
loadSkills(cwd, gitRoot, skillNames, {
|
|
3236
|
+
cacheDir: resolveSkillCacheDir(PRODUCT_SLUG),
|
|
3237
|
+
refresh: options.refreshGitSkills,
|
|
3238
|
+
marketplaces: options.marketplaces,
|
|
3239
|
+
builtinSkillsDir: BUILTIN_SKILLS_DIR,
|
|
3240
|
+
envPrefix: ENV_PREFIX,
|
|
3241
|
+
warn
|
|
3242
|
+
})
|
|
5308
3243
|
]);
|
|
5309
|
-
const registry = buildMarketplaceRegistry(options.marketplaces ?? []);
|
|
5310
|
-
const knownMarketplaces = new Set(registry.keys());
|
|
5311
|
-
const skills = [...discovered];
|
|
5312
|
-
const discoveredNames = new Set(discovered.map((s) => s.name));
|
|
5313
|
-
const named = await Promise.all(skillNames.filter((n) => !discoveredNames.has(n)).map(async (n) => {
|
|
5314
|
-
try {
|
|
5315
|
-
const spec = parseSkillSpec(n, knownMarketplaces);
|
|
5316
|
-
if (spec.protocol === "marketplace") return await loadMarketplaceSkill(spec, registry, { refresh: options.refreshGitSkills });
|
|
5317
|
-
return await loadNamedSkill(n, cwd, { refresh: options.refreshGitSkills });
|
|
5318
|
-
} catch (error) {
|
|
5319
|
-
warn?.(`Skipping skill "${n}": ${formatError(error)}`);
|
|
5320
|
-
return null;
|
|
5321
|
-
}
|
|
5322
|
-
}));
|
|
5323
|
-
skills.push(...named.filter((s) => s !== null));
|
|
5324
3244
|
return {
|
|
5325
3245
|
conventions,
|
|
5326
3246
|
reviewRules,
|
|
@@ -5963,13 +3883,31 @@ async function runReview(config, options) {
|
|
|
5963
3883
|
marketplaces: config.marketplaces
|
|
5964
3884
|
});
|
|
5965
3885
|
const gitRoot = await findGitRoot(cwd);
|
|
3886
|
+
const mcpDiscovery = config.mcpDiscovery ?? "off";
|
|
3887
|
+
let projectConfigReader;
|
|
3888
|
+
if (mcpDiscovery === "worktree") projectConfigReader = new WorkingTreeProjectConfigReader(gitRoot);
|
|
3889
|
+
else if (mcpDiscovery === "target") {
|
|
3890
|
+
if (!options.targetSha) throw new ConfigError("Target MCP discovery requires the immutable review target SHA.", { hint: "Pass RunReviewOptions.targetSha from DiffRefs.base_sha, or select mcpDiscovery \"off\" or \"worktree\"." });
|
|
3891
|
+
try {
|
|
3892
|
+
projectConfigReader = await GitRevisionProjectConfigReader.create(gitRoot, options.targetSha);
|
|
3893
|
+
} catch (error) {
|
|
3894
|
+
throw new ConfigError(`Unable to load MCP configuration from target commit ${options.targetSha}.`, {
|
|
3895
|
+
hint: "Ensure the immutable target commit is available in the local Git history, or select mcpDiscovery \"off\" or \"worktree\".",
|
|
3896
|
+
cause: error
|
|
3897
|
+
});
|
|
3898
|
+
}
|
|
3899
|
+
}
|
|
5966
3900
|
const mcpConfigs = await resolveMcpServers({
|
|
5967
3901
|
mcp: config.mcp ?? [],
|
|
5968
3902
|
disableMcp: config.disableMcp ?? [],
|
|
5969
|
-
mcpDiscovery
|
|
5970
|
-
}, cwd, gitRoot, buildMarketplaceRegistry(config.marketplaces ?? []),
|
|
3903
|
+
mcpDiscovery
|
|
3904
|
+
}, cwd, gitRoot, buildMarketplaceRegistry(config.marketplaces ?? []), {
|
|
3905
|
+
cacheDir: resolveSkillCacheDir(PRODUCT_SLUG),
|
|
5971
3906
|
vars: pickMcpEnvVars(process.env, config.mcpEnv ?? []),
|
|
5972
|
-
refresh: config.refreshGitSkills
|
|
3907
|
+
refresh: config.refreshGitSkills,
|
|
3908
|
+
envPrefix: ENV_PREFIX,
|
|
3909
|
+
projectConfigReader,
|
|
3910
|
+
warn: (msg) => logger.warn(msg)
|
|
5973
3911
|
});
|
|
5974
3912
|
const mcpConnection = await (options.connectMcp ?? connectMcpServers)(mcpConfigs, {
|
|
5975
3913
|
logger,
|
|
@@ -7061,7 +4999,7 @@ async function loadDefaultRuntime() {
|
|
|
7061
4999
|
const [sdkNode, resources, semconv] = modules;
|
|
7062
5000
|
const serviceResource = resources.resourceFromAttributes({
|
|
7063
5001
|
[semconv.ATTR_SERVICE_NAME ?? "service.name"]: SERVICE_NAME,
|
|
7064
|
-
[semconv.ATTR_SERVICE_VERSION ?? "service.version"]: "0.
|
|
5002
|
+
[semconv.ATTR_SERVICE_VERSION ?? "service.version"]: "0.11.1"
|
|
7065
5003
|
});
|
|
7066
5004
|
applyOtelExporterDefaults(process.env);
|
|
7067
5005
|
const sdk = new sdkNode.NodeSDK({ resource: resources.defaultResource().merge(serviceResource) });
|
|
@@ -7574,7 +5512,7 @@ function boldCommentTitle(body) {
|
|
|
7574
5512
|
*/
|
|
7575
5513
|
function buildCommentBody(body, commitSha, confidence) {
|
|
7576
5514
|
const confidenceLine = `_Confidence: ${confidence}._`;
|
|
7577
|
-
const footer = `<sub>Reviewed by ${PRODUCT_LINK} v0.
|
|
5515
|
+
const footer = `<sub>Reviewed by ${PRODUCT_LINK} v0.11.1 for commit ${commitSha}.</sub>`;
|
|
7578
5516
|
return `${boldCommentTitle(body.trim())}\n\n${confidenceLine}\n\n---\n\n${footer}`;
|
|
7579
5517
|
}
|
|
7580
5518
|
function buildPayload(comment, body, refs, resolved) {
|
|
@@ -8168,120 +6106,6 @@ function createPlatform(config) {
|
|
|
8168
6106
|
return new GitLabPlatform(config);
|
|
8169
6107
|
}
|
|
8170
6108
|
//#endregion
|
|
8171
|
-
//#region src/skill-links.ts
|
|
8172
|
-
/**
|
|
8173
|
-
* Hosts that serve blobs at `/<repo>/blob/<ref>/<path>`. Everything else is
|
|
8174
|
-
* assumed to be GitLab (`/<repo>/-/blob/<ref>/<path>`), which covers both
|
|
8175
|
-
* gitlab.com and the self-hosted instances this tool mostly runs against.
|
|
8176
|
-
*/
|
|
8177
|
-
var GITHUB_HOSTS = /* @__PURE__ */ new Set(["github.com", "www.github.com"]);
|
|
8178
|
-
/** Percent-encode each path segment while keeping the `/` separators intact. */
|
|
8179
|
-
function encodePath(path) {
|
|
8180
|
-
return path.split("/").filter(Boolean).map((segment) => encodeURIComponent(segment)).join("/");
|
|
8181
|
-
}
|
|
8182
|
-
/**
|
|
8183
|
-
* Build a blob (file) or tree (directory) URL for `path` at `ref` inside the
|
|
8184
|
-
* repository served at `repoWebUrl`. An empty ref resolves to `HEAD`, which both
|
|
8185
|
-
* GitHub and GitLab accept, so a skill or MCP server pinned to a remote's
|
|
8186
|
-
* default branch still links.
|
|
8187
|
-
*/
|
|
8188
|
-
function blobUrl(repoWebUrl, ref, path, kind = "blob") {
|
|
8189
|
-
let parsed;
|
|
8190
|
-
try {
|
|
8191
|
-
parsed = new URL(repoWebUrl);
|
|
8192
|
-
} catch {
|
|
8193
|
-
return;
|
|
8194
|
-
}
|
|
8195
|
-
return `${`${parsed.origin}${parsed.pathname.replace(/\/+$/, "")}`}/${GITHUB_HOSTS.has(parsed.host) ? kind : `-/${kind}`}/${encodeURIComponent(ref || "HEAD")}/${encodePath(path)}`;
|
|
8196
|
-
}
|
|
8197
|
-
/**
|
|
8198
|
-
* Convert a git clone URL to the repository's web URL: drop any transport
|
|
8199
|
-
* marker, embedded credentials, and the `.git` suffix, and serve it over HTTPS.
|
|
8200
|
-
* Accepts `https://`, `ssh://`, `git+<transport>://`, and scp-style
|
|
8201
|
-
* (`git@host:group/repo.git`) forms. Returns `undefined` for anything it cannot
|
|
8202
|
-
* parse, so an exotic remote simply yields an unlinked skill.
|
|
8203
|
-
*/
|
|
8204
|
-
function gitRepoWebUrl(cloneUrl) {
|
|
8205
|
-
let raw = cloneUrl.trim();
|
|
8206
|
-
if (!raw) return void 0;
|
|
8207
|
-
if (raw.startsWith("git+")) raw = raw.slice(4);
|
|
8208
|
-
const scp = /^(?:[^@/]+@)?([^/:]+):(?!\/)(.+)$/.exec(raw);
|
|
8209
|
-
if (scp) raw = `ssh://${scp[1]}/${scp[2]}`;
|
|
8210
|
-
let parsed;
|
|
8211
|
-
try {
|
|
8212
|
-
parsed = new URL(raw);
|
|
8213
|
-
} catch {
|
|
8214
|
-
return;
|
|
8215
|
-
}
|
|
8216
|
-
if (!parsed.host) return void 0;
|
|
8217
|
-
const path = parsed.pathname.replace(/\.git\/?$/, "").replace(/\/+$/, "");
|
|
8218
|
-
if (!path || path === "/") return void 0;
|
|
8219
|
-
return `https://${parsed.host}${path}`;
|
|
8220
|
-
}
|
|
8221
|
-
/**
|
|
8222
|
-
* Resolve a link to a skill's `SKILL.md`, or `undefined` when the source is not
|
|
8223
|
-
* reachable from a browser (a `file:` path, or an in-repo skill on a run with no
|
|
8224
|
-
* CI project URL). Built-in skills link to the published tag of this package, so
|
|
8225
|
-
* the link always shows the skill exactly as the run used it.
|
|
8226
|
-
*/
|
|
8227
|
-
function skillSourceUrl(origin, context = {}) {
|
|
8228
|
-
switch (origin.kind) {
|
|
8229
|
-
case "builtin": return blobUrl(PRODUCT_URL, "0.10.3", `skills/${origin.name}/SKILL.md`);
|
|
8230
|
-
case "project":
|
|
8231
|
-
if (!context.projectWebUrl || !context.commitSha) return void 0;
|
|
8232
|
-
return blobUrl(context.projectWebUrl, context.commitSha, `${origin.path}/SKILL.md`);
|
|
8233
|
-
case "npm": return `https://www.npmjs.com/package/${origin.packageName}`;
|
|
8234
|
-
case "file": return;
|
|
8235
|
-
case "git":
|
|
8236
|
-
case "marketplace": {
|
|
8237
|
-
const repoWebUrl = gitRepoWebUrl(origin.url);
|
|
8238
|
-
if (!repoWebUrl) return void 0;
|
|
8239
|
-
const path = origin.path ? `${origin.path}/SKILL.md` : "SKILL.md";
|
|
8240
|
-
return blobUrl(repoWebUrl, origin.ref, path);
|
|
8241
|
-
}
|
|
8242
|
-
}
|
|
8243
|
-
}
|
|
8244
|
-
/**
|
|
8245
|
-
* Resolve a link to an MCP server's source, or `undefined` when it is not
|
|
8246
|
-
* reachable from a browser (a `file:` spec, or a repo `.mcp.json` on a run with
|
|
8247
|
-
* no CI project URL). A `project` source links to the `.mcp.json` file it was
|
|
8248
|
-
* declared in; a `marketplace` source links to the plugin's directory in the
|
|
8249
|
-
* marketplace repository.
|
|
8250
|
-
*/
|
|
8251
|
-
function mcpSourceUrl(source, context = {}) {
|
|
8252
|
-
switch (source.kind) {
|
|
8253
|
-
case "project":
|
|
8254
|
-
if (!context.projectWebUrl || !context.commitSha) return void 0;
|
|
8255
|
-
return blobUrl(context.projectWebUrl, context.commitSha, source.path);
|
|
8256
|
-
case "file": return;
|
|
8257
|
-
case "marketplace": {
|
|
8258
|
-
const repoWebUrl = gitRepoWebUrl(source.url);
|
|
8259
|
-
if (!repoWebUrl) return void 0;
|
|
8260
|
-
return blobUrl(repoWebUrl, source.ref, source.path, "tree");
|
|
8261
|
-
}
|
|
8262
|
-
}
|
|
8263
|
-
}
|
|
8264
|
-
/**
|
|
8265
|
-
* The name a skill is shown under in the footer. Marketplace skills carry their
|
|
8266
|
-
* full selector (`<marketplace>:<plugin>/<skill>`) because a bare skill name says
|
|
8267
|
-
* nothing about which marketplace and plugin it came from — and that selector is
|
|
8268
|
-
* exactly what a developer would put in `CODE_REVIEW_SKILLS` to use it. Every
|
|
8269
|
-
* other source shows the skill's own name.
|
|
8270
|
-
*/
|
|
8271
|
-
function skillDisplayName(skill) {
|
|
8272
|
-
return skill.origin.kind === "marketplace" ? `${skill.origin.marketplace}:${skill.origin.plugin}/${skill.name}` : skill.name;
|
|
8273
|
-
}
|
|
8274
|
-
/**
|
|
8275
|
-
* Render one skill for the summary footer: a link to its source when one can be
|
|
8276
|
-
* resolved, otherwise the bare name. The name keeps its code span either way so
|
|
8277
|
-
* linked and unlinked skills read the same.
|
|
8278
|
-
*/
|
|
8279
|
-
function formatSkillLink(skill, context = {}) {
|
|
8280
|
-
const name = skillDisplayName(skill);
|
|
8281
|
-
const url = skillSourceUrl(skill.origin, context);
|
|
8282
|
-
return url ? `[\`${name}\`](${url})` : `\`${name}\``;
|
|
8283
|
-
}
|
|
8284
|
-
//#endregion
|
|
8285
6109
|
//#region src/summary-carryover.ts
|
|
8286
6110
|
var FINGERPRINT_MARKER_GLOBAL_RE = new RegExp(FINGERPRINT_MARKER_PATTERN, "gi");
|
|
8287
6111
|
var RISK_RANK = {
|
|
@@ -8466,6 +6290,9 @@ Options:
|
|
|
8466
6290
|
Comma-separated labels added to the MR/PR when the review posts no
|
|
8467
6291
|
new comment; the --labels-on-findings set is removed.
|
|
8468
6292
|
(env: CODE_REVIEW_LABELS_ON_CLEAN)
|
|
6293
|
+
--mcp-discovery <mode> Repository MCP discovery: off, worktree, or target. target reads
|
|
6294
|
+
.mcp.json and .claude/settings*.json from the immutable review target
|
|
6295
|
+
commit. (default: off; env: CODE_REVIEW_MCP_DISCOVERY)
|
|
8469
6296
|
--review-file <path> Raw code-review output file (default: code-review.md)
|
|
8470
6297
|
--output <path> Generated payload artifact (default: review-comments.json)
|
|
8471
6298
|
--cwd <path> Working directory (default: process.cwd())
|
|
@@ -8574,7 +6401,8 @@ async function run(config, bridges) {
|
|
|
8574
6401
|
onUsage: (u) => {
|
|
8575
6402
|
partialUsage = u;
|
|
8576
6403
|
},
|
|
8577
|
-
sinceRef: config.inputMode === "commits" && reviewedCommitSha && reviewedCommitSha !== refs.head_sha ? reviewedCommitSha : void 0
|
|
6404
|
+
sinceRef: config.inputMode === "commits" && reviewedCommitSha && reviewedCommitSha !== refs.head_sha ? reviewedCommitSha : void 0,
|
|
6405
|
+
targetSha: refs.base_sha
|
|
8578
6406
|
});
|
|
8579
6407
|
context.usage = result;
|
|
8580
6408
|
return result;
|
|
@@ -8694,7 +6522,8 @@ async function run(config, bridges) {
|
|
|
8694
6522
|
costFooter: [formatUsageLine(usage), formatPerModelUsage(usage)].filter(Boolean).join("\n\n"),
|
|
8695
6523
|
skillsFooter: formatSkillsFooter(usage.skills, {
|
|
8696
6524
|
projectWebUrl: config.projectWebUrl,
|
|
8697
|
-
commitSha: refs.head_sha
|
|
6525
|
+
commitSha: refs.head_sha,
|
|
6526
|
+
builtinSkills: BUILTIN_SKILLS
|
|
8698
6527
|
}),
|
|
8699
6528
|
mcpFooter: formatMcpFooter(usage.mcp, {
|
|
8700
6529
|
projectWebUrl: config.projectWebUrl,
|
|
@@ -8780,32 +6609,6 @@ function zeroReviewUsage(model, thinkingLevel) {
|
|
|
8780
6609
|
sizeNotice: { sizeSkippedFiles: [] }
|
|
8781
6610
|
};
|
|
8782
6611
|
}
|
|
8783
|
-
/**
|
|
8784
|
-
* The summary footer's skills line. Each skill links to its `SKILL.md` source so
|
|
8785
|
-
* a developer reading the review can check what the reviewer was told; skills
|
|
8786
|
-
* with no reachable source (a `file:` path, or an in-repo skill on a run without
|
|
8787
|
-
* CI project coordinates) stay as plain names.
|
|
8788
|
-
*/
|
|
8789
|
-
function formatSkillsFooter(skills, context = {}) {
|
|
8790
|
-
if (skills.length === 0) return void 0;
|
|
8791
|
-
return `Skills: ${skills.map((skill) => `${formatSkillLink(skill, context)} (${formatSkillUsageState(skill)})`).join(", ")}`;
|
|
8792
|
-
}
|
|
8793
|
-
/**
|
|
8794
|
-
* The summary footer's MCP line, e.g. `MCP: jira (2 calls), docs (unused),
|
|
8795
|
-
* context7 (unavailable)`. A connected server reports how many tool calls the
|
|
8796
|
-
* reviewer actually made against it; an unavailable one is flagged as such. The
|
|
8797
|
-
* exposed tool list stays in the usage artifact — the footer answers what was
|
|
8798
|
-
* used, not what was offered. Each server name links to its source (the repo
|
|
8799
|
-
* `.mcp.json` or the marketplace plugin) when one is reachable, the same way
|
|
8800
|
-
* `formatSkillsFooter` links skills.
|
|
8801
|
-
*/
|
|
8802
|
-
function formatMcpFooter(servers, context = {}) {
|
|
8803
|
-
if (servers.length === 0) return void 0;
|
|
8804
|
-
return `MCP: ${servers.map((server) => {
|
|
8805
|
-
const url = mcpSourceUrl(server.source, context);
|
|
8806
|
-
return `${url ? `[${server.name}](${url})` : server.name} (${formatMcpUsageState(server)})`;
|
|
8807
|
-
}).join(", ")}`;
|
|
8808
|
-
}
|
|
8809
6612
|
function formatUsageLine(usage) {
|
|
8810
6613
|
const formatter = new Intl.NumberFormat("en-US");
|
|
8811
6614
|
const billableInput = usage.tokens.input + usage.tokens.cacheRead + usage.tokens.cacheWrite;
|
|
@@ -8894,10 +6697,10 @@ async function main(argv = process.argv.slice(2)) {
|
|
|
8894
6697
|
return;
|
|
8895
6698
|
}
|
|
8896
6699
|
if (argv.includes("--version") || argv.includes("-v")) {
|
|
8897
|
-
console.log("0.
|
|
6700
|
+
console.log("0.11.1");
|
|
8898
6701
|
return;
|
|
8899
6702
|
}
|
|
8900
|
-
process.stderr.write(`[code-review] @weareikko/code-review v0.
|
|
6703
|
+
process.stderr.write(`[code-review] @weareikko/code-review v0.11.1\n`);
|
|
8901
6704
|
assertNodeVersion();
|
|
8902
6705
|
applyCodeReviewEnvPrefix();
|
|
8903
6706
|
applyDefaultCacheRetention();
|
|
@@ -8918,6 +6721,6 @@ if (isDirectRun()) main().catch((error) => {
|
|
|
8918
6721
|
process.exitCode = 1;
|
|
8919
6722
|
});
|
|
8920
6723
|
//#endregion
|
|
8921
|
-
export {
|
|
6724
|
+
export { fingerprints as $, toGitLabReviewSeverity as A, buildSummaryBody as B, diagnosticChannels as C, traceMcpDiagnostic as D, traceDiagnosticPhase as E, SUMMARY_HISTORY_START as F, findExistingSummaryNote as G, extractReviewedCommitSha as H, SUMMARY_MARKER as I, stripSummaryMarker as J, findExistingSummaryNoteId as K, buildArchivedSummaryEntry as L, SUMMARY_HISTORY_ENTRY_END as M, SUMMARY_HISTORY_ENTRY_START as N, MCP_DISCOVERY_MODES as O, SUMMARY_HISTORY_LIMIT as P, extractExistingFingerprints as Q, buildReviewedCommitFooter as R, createDiagnosticRunId as S, traceDiagnostic as T, extractSummaryHistoryEntries as U, buildSummaryHistoryEntries as V, findExistingReviewedCommitSha as W, appendFingerprintMarkers as X, upsertSummaryNote as Y, extractDiffHunkContext as Z, connectMcpServers as _, main as a, MCP_DIAGNOSTIC_CHANNEL_NAMES as b, withHttpStamping as c, isOtelEnabled as d, normalizeBody as et, startOtelBridge as f, parseReviewMarkdownWithWarnings as g, parseReviewMarkdown as h, formatUsageLine as i, SUMMARY_HISTORY_END as j, normalizeSeverity as k, buildGeneratedComments as l, runReview as m, formatLabelChange as n, resolveLabelChange as o, filterDiff as p, stripSummaryHistory as q, formatPerModelUsage as r, run as s, countPostedBySeverity as t, sha256 as tt, buildPayload as u, DIAGNOSTIC_CHANNEL_NAMES as v, mcpDiagnosticChannels as w, createDiagnosticContext as x, DIAGNOSTIC_CHANNEL_PREFIX as y, buildSizeNoticeBlock as z };
|
|
8922
6725
|
|
|
8923
|
-
//# sourceMappingURL=cli-
|
|
6726
|
+
//# sourceMappingURL=cli-BFqDzUM6.js.map
|