@getcodesentinel/codesentinel 1.42.1 → 1.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3856,8 +3856,8 @@ var resolveAutoBaselineRef = async (input) => {
3856
3856
 
3857
3857
  // src/index.ts
3858
3858
  import { readFileSync as readFileSync4 } from "fs";
3859
- import { readFile as readFile11, writeFile as writeFile12 } from "fs/promises";
3860
- import { dirname as dirname4, resolve as resolve12 } from "path";
3859
+ import { readFile as readFile11, writeFile as writeFile13 } from "fs/promises";
3860
+ import { dirname as dirname4, resolve as resolve14 } from "path";
3861
3861
  import { fileURLToPath as fileURLToPath2 } from "url";
3862
3862
 
3863
3863
  // src/application/format-analyze-output.ts
@@ -4538,7 +4538,7 @@ var promptInstall = async (packageName, latestVersion, currentVersion) => {
4538
4538
  );
4539
4539
  return "skip";
4540
4540
  }
4541
- return await new Promise((resolve13) => {
4541
+ return await new Promise((resolve15) => {
4542
4542
  emitKeypressEvents(stdin);
4543
4543
  let selectedIndex = 0;
4544
4544
  const previousRawMode = stdin.isRaw;
@@ -4563,7 +4563,7 @@ var promptInstall = async (packageName, latestVersion, currentVersion) => {
4563
4563
  } else {
4564
4564
  stderr.write("\n");
4565
4565
  }
4566
- resolve13(choice);
4566
+ resolve15(choice);
4567
4567
  };
4568
4568
  const onKeypress = (_str, key) => {
4569
4569
  if (key.ctrl === true && key.name === "c") {
@@ -4757,7 +4757,7 @@ var promptSelection = async (currentVersion, actions) => {
4757
4757
  if (!stdin2.isTTY || !stderr2.isTTY || typeof stdin2.setRawMode !== "function") {
4758
4758
  return "exit";
4759
4759
  }
4760
- return await new Promise((resolve13) => {
4760
+ return await new Promise((resolve15) => {
4761
4761
  emitKeypressEvents2(stdin2);
4762
4762
  let selectedIndex = 0;
4763
4763
  const previousRawMode = stdin2.isRaw;
@@ -4772,7 +4772,7 @@ var promptSelection = async (currentVersion, actions) => {
4772
4772
  stdin2.setRawMode(previousRawMode);
4773
4773
  clearTerminal();
4774
4774
  showCursor2();
4775
- resolve13(selection);
4775
+ resolve15(selection);
4776
4776
  };
4777
4777
  const onKeypress = (_str, key) => {
4778
4778
  if (key.ctrl === true && key.name === "c") {
@@ -4865,7 +4865,7 @@ var waitForReturnToMenu = async () => {
4865
4865
  }
4866
4866
  stderr2.write(`
4867
4867
  ${PROMPT_PADDING}Press enter to return to the menu...`);
4868
- await new Promise((resolve13) => {
4868
+ await new Promise((resolve15) => {
4869
4869
  emitKeypressEvents2(stdin2);
4870
4870
  const previousRawMode = stdin2.isRaw;
4871
4871
  const cleanup = () => {
@@ -4874,7 +4874,7 @@ ${PROMPT_PADDING}Press enter to return to the menu...`);
4874
4874
  stdin2.setRawMode(previousRawMode);
4875
4875
  showCursor2();
4876
4876
  stderr2.write("\n");
4877
- resolve13();
4877
+ resolve15();
4878
4878
  };
4879
4879
  const onKeypress = (_str, key) => {
4880
4880
  if (key.ctrl === true && key.name === "c") {
@@ -4892,7 +4892,7 @@ ${PROMPT_PADDING}Press enter to return to the menu...`);
4892
4892
  });
4893
4893
  };
4894
4894
  var runCliCommand = async (scriptPath2, args) => {
4895
- return await new Promise((resolve13, reject) => {
4895
+ return await new Promise((resolve15, reject) => {
4896
4896
  const child = spawn2(process.execPath, [...process.execArgv, scriptPath2, ...args], {
4897
4897
  stdio: ["inherit", "pipe", "pipe"],
4898
4898
  env: {
@@ -4906,7 +4906,7 @@ var runCliCommand = async (scriptPath2, args) => {
4906
4906
  reject(error);
4907
4907
  });
4908
4908
  child.on("close", (code) => {
4909
- resolve13(code ?? 1);
4909
+ resolve15(code ?? 1);
4910
4910
  });
4911
4911
  });
4912
4912
  };
@@ -10576,15 +10576,15 @@ var openPath = async (targetPath) => {
10576
10576
  if (command === void 0) {
10577
10577
  return false;
10578
10578
  }
10579
- return new Promise((resolve13) => {
10579
+ return new Promise((resolve15) => {
10580
10580
  const child = spawn3(command.command, command.args, {
10581
10581
  detached: true,
10582
10582
  stdio: "ignore"
10583
10583
  });
10584
- child.once("error", () => resolve13(false));
10584
+ child.once("error", () => resolve15(false));
10585
10585
  child.once("spawn", () => {
10586
10586
  child.unref();
10587
- resolve13(true);
10587
+ resolve15(true);
10588
10588
  });
10589
10589
  });
10590
10590
  };
@@ -13400,9 +13400,934 @@ var runInitCommand = async (inputPath, options = {}) => {
13400
13400
  };
13401
13401
  };
13402
13402
 
13403
+ // src/mcp/server.ts
13404
+ import { McpServer } from "@modelcontextprotocol/server";
13405
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
13406
+
13407
+ // src/mcp/analysis-cache.ts
13408
+ var createAnalysisCache = (root, logger) => {
13409
+ let analysisPromise = null;
13410
+ const ownershipPromises = /* @__PURE__ */ new Map();
13411
+ const getAnalysis = () => {
13412
+ if (analysisPromise === null) {
13413
+ analysisPromise = runAnalyzeCommand(root, "likely_merge", {}, logger).catch((error) => {
13414
+ analysisPromise = null;
13415
+ throw error;
13416
+ });
13417
+ }
13418
+ return analysisPromise;
13419
+ };
13420
+ const getOwnershipAudit = (ref) => {
13421
+ const cached = ownershipPromises.get(ref);
13422
+ if (cached !== void 0) {
13423
+ return cached;
13424
+ }
13425
+ const pending = buildOwnershipAudit(root, { ref }, logger).then((result) => result.audit).catch((error) => {
13426
+ ownershipPromises.delete(ref);
13427
+ throw error;
13428
+ });
13429
+ ownershipPromises.set(ref, pending);
13430
+ return pending;
13431
+ };
13432
+ return { getAnalysis, getOwnershipAudit };
13433
+ };
13434
+
13435
+ // src/mcp/context.ts
13436
+ import { existsSync as existsSync7 } from "fs";
13437
+ import { isAbsolute as isAbsolute3, relative as relative5, resolve as resolve12 } from "path";
13438
+
13439
+ // src/mcp/errors.ts
13440
+ var McpToolError = class extends Error {
13441
+ code;
13442
+ constructor(code, message) {
13443
+ super(message);
13444
+ this.name = "McpToolError";
13445
+ this.code = code;
13446
+ }
13447
+ };
13448
+ var REDACTED = "[REDACTED]";
13449
+ var SECRET_PATTERNS = [
13450
+ /\bgithub_pat_[A-Za-z0-9_]{20,}/gi,
13451
+ /\bgh[pous]_[A-Za-z0-9]{20,}/gi,
13452
+ /\bBearer\s+[A-Za-z0-9._~+/=-]+/gi,
13453
+ /\btoken=[^\s&"'<>]+/gi,
13454
+ /\/\/[^/\s:@]+:[^/\s@]+@/g
13455
+ ];
13456
+ var redactSecrets = (text) => {
13457
+ let redacted = text;
13458
+ for (const pattern of SECRET_PATTERNS) {
13459
+ redacted = redacted.replace(pattern, (match) => {
13460
+ if (/^Bearer\s/i.test(match)) {
13461
+ return `Bearer ${REDACTED}`;
13462
+ }
13463
+ if (/^token=/i.test(match)) {
13464
+ return `token=${REDACTED}`;
13465
+ }
13466
+ if (match.startsWith("//")) {
13467
+ return `//${REDACTED}@`;
13468
+ }
13469
+ return REDACTED;
13470
+ });
13471
+ }
13472
+ return redacted;
13473
+ };
13474
+ var toToolErrorResult = (error) => {
13475
+ const code = error instanceof McpToolError ? error.code : "analysis_failed";
13476
+ const rawMessage = error instanceof McpToolError ? error.message : error instanceof Error && error.message.trim().length > 0 ? error.message : "unexpected analysis failure";
13477
+ return {
13478
+ content: [
13479
+ {
13480
+ type: "text",
13481
+ text: JSON.stringify({ error: { code, message: redactSecrets(rawMessage) } })
13482
+ }
13483
+ ],
13484
+ isError: true
13485
+ };
13486
+ };
13487
+
13488
+ // src/mcp/context.ts
13489
+ var resolveMcpRoot = (environment) => resolve12(environment["CODESENTINEL_ROOT"] ?? process.cwd());
13490
+ var isOutsideRoot = (relativePath) => relativePath.startsWith("..") || isAbsolute3(relativePath);
13491
+ var resolveRepositoryPath = (root, input) => {
13492
+ const absolutePath = resolve12(root, input);
13493
+ const relativePath = relative5(root, absolutePath);
13494
+ if (relativePath === "" || isOutsideRoot(relativePath)) {
13495
+ throw new McpToolError(
13496
+ "path_outside_root",
13497
+ `path "${input}" is outside the repository root or is the root itself`
13498
+ );
13499
+ }
13500
+ if (!existsSync7(absolutePath)) {
13501
+ throw new McpToolError("path_not_found", `path "${input}" does not exist in the repository`);
13502
+ }
13503
+ return normalizeRepositoryPath(relativePath);
13504
+ };
13505
+ var assertPathInsideRoot = (root, absolutePath) => {
13506
+ const relativePath = relative5(root, absolutePath);
13507
+ if (isOutsideRoot(relativePath)) {
13508
+ throw new McpToolError(
13509
+ "path_outside_root",
13510
+ `path "${absolutePath}" is outside the repository root`
13511
+ );
13512
+ }
13513
+ return normalizeRepositoryPath(relative5(root, absolutePath));
13514
+ };
13515
+
13516
+ // src/mcp/tools.ts
13517
+ import { spawn as spawn4 } from "child_process";
13518
+ import { mkdir as mkdir5, writeFile as writeFile12 } from "fs/promises";
13519
+ import { isAbsolute as isAbsolute4, join as join15, resolve as resolve13 } from "path";
13520
+ import { z } from "zod";
13521
+
13522
+ // src/mcp/shapes.ts
13523
+ var OWNERSHIP_FINDING_RULES = {
13524
+ "ownership/unowned-critical": "error",
13525
+ "ownership/ghost-owner": "error",
13526
+ "ownership/drift": "warning",
13527
+ "ownership/unknown": "warning"
13528
+ };
13529
+ var RULE_BY_STATUS = {
13530
+ "unowned-critical": "ownership/unowned-critical",
13531
+ ghosted: "ownership/ghost-owner",
13532
+ drifted: "ownership/drift",
13533
+ unknown: "ownership/unknown"
13534
+ };
13535
+ var compareText5 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
13536
+ var severityRank2 = {
13537
+ error: 0,
13538
+ warning: 1
13539
+ };
13540
+ var formatOwners = (owners) => owners.length === 0 ? "no declared owner" : owners.map(declaredOwnerKey).join(", ");
13541
+ var findingMessage = (file) => {
13542
+ const owners = formatOwners(file.declared);
13543
+ switch (file.status) {
13544
+ case "unowned-critical":
13545
+ return `${file.filePath} is a critical file without a declared owner`;
13546
+ case "ghosted":
13547
+ return `${file.filePath} is declared to ${owners} but none of its owners committed in the observation window`;
13548
+ case "drifted":
13549
+ return `${file.filePath} is declared to ${owners} but ${file.observed.topAuthorId ?? "an unknown author"} is the top recent author`;
13550
+ case "unknown":
13551
+ return `${file.filePath} is declared to ${owners} but its ownership cannot be verified offline`;
13552
+ default:
13553
+ return `${file.filePath} has no ownership finding`;
13554
+ }
13555
+ };
13556
+ var toFindings = (audit) => {
13557
+ if (!audit.available) {
13558
+ return [];
13559
+ }
13560
+ const findings = [];
13561
+ for (const file of audit.files) {
13562
+ const rule = RULE_BY_STATUS[file.status];
13563
+ if (rule === void 0) continue;
13564
+ findings.push({
13565
+ rule,
13566
+ severity: OWNERSHIP_FINDING_RULES[rule],
13567
+ status: file.status,
13568
+ path: file.filePath,
13569
+ message: findingMessage(file),
13570
+ matchLine: file.matchLine
13571
+ });
13572
+ }
13573
+ return findings.sort((a, b) => {
13574
+ const bySeverity = severityRank2[a.severity] - severityRank2[b.severity];
13575
+ if (bySeverity !== 0) return bySeverity;
13576
+ const byStatus = ownershipStatusRank(a.status) - ownershipStatusRank(b.status);
13577
+ if (byStatus !== 0) return byStatus;
13578
+ return compareText5(a.path, b.path);
13579
+ });
13580
+ };
13581
+ var normalizePathPrefix = (input) => {
13582
+ let normalized = input.trim().replace(/\\/g, "/");
13583
+ while (normalized.startsWith("./")) normalized = normalized.slice(2);
13584
+ normalized = normalized.replace(/\/+$/, "");
13585
+ return normalized === "." ? "" : normalized;
13586
+ };
13587
+ var filterFindings = (findings, filters) => findings.filter((finding) => {
13588
+ if (filters.severity !== void 0 && finding.severity !== filters.severity) return false;
13589
+ if (filters.rule !== void 0 && finding.rule !== filters.rule) return false;
13590
+ if (filters.status !== void 0 && finding.status !== filters.status) return false;
13591
+ if (filters.path !== void 0) {
13592
+ const path = filters.path;
13593
+ if (finding.path !== path && !finding.path.startsWith(`${path}/`)) return false;
13594
+ }
13595
+ return true;
13596
+ });
13597
+ var encodeCursor = (offset) => Buffer.from(`v1:${offset}`, "utf8").toString("base64url");
13598
+ var decodeCursor = (cursor) => {
13599
+ if (cursor === void 0) return 0;
13600
+ let decoded;
13601
+ try {
13602
+ decoded = Buffer.from(cursor, "base64url").toString("utf8");
13603
+ } catch {
13604
+ throw new McpToolError("invalid_argument", `invalid cursor: "${cursor}"`);
13605
+ }
13606
+ const match = /^v1:(\d+)$/.exec(decoded);
13607
+ const offset = match?.[1] === void 0 ? null : Number.parseInt(match[1], 10);
13608
+ if (offset === null || !Number.isSafeInteger(offset) || offset < 0) {
13609
+ throw new McpToolError("invalid_argument", `invalid cursor: "${cursor}"`);
13610
+ }
13611
+ return offset;
13612
+ };
13613
+ var paginate = (items, offset, limit) => {
13614
+ const page = items.slice(offset, offset + limit);
13615
+ const nextOffset = offset + limit;
13616
+ return {
13617
+ page,
13618
+ nextCursor: nextOffset < items.length ? encodeCursor(nextOffset) : null
13619
+ };
13620
+ };
13621
+ var toOwnerValues = (owners) => owners.map((owner) => ({ kind: owner.kind, value: declaredOwnerKey(owner) }));
13622
+ var toFileOwner = (file, ref, warnings) => {
13623
+ const teams = [
13624
+ ...new Set(
13625
+ file.declared.filter((owner) => owner.kind === "team").map((owner) => `${owner.org}/${owner.slug}`)
13626
+ )
13627
+ ].sort(compareText5);
13628
+ return {
13629
+ path: file.filePath,
13630
+ ref,
13631
+ owners: toOwnerValues(file.declared),
13632
+ teams,
13633
+ status: file.status,
13634
+ matchLine: file.matchLine,
13635
+ topAuthor: file.observed.topAuthorId === null ? null : { id: file.observed.topAuthorId, share: file.observed.topAuthorShare },
13636
+ observed: {
13637
+ commits: file.observed.commits,
13638
+ recentCommits: file.observed.recentCommits,
13639
+ authors: file.observed.authors,
13640
+ dormant: file.observed.dormant,
13641
+ busFactor: file.observed.busFactor,
13642
+ lastCommitUnix: file.observed.lastCommitUnix
13643
+ },
13644
+ criticality: {
13645
+ isCritical: file.criticality.isCritical,
13646
+ isHotspot: file.criticality.isHotspot,
13647
+ fanIn: file.criticality.fanIn,
13648
+ riskScore: file.criticality.riskScore
13649
+ },
13650
+ warnings: [...warnings]
13651
+ };
13652
+ };
13653
+ var toHotspots = (hotspots, offset) => hotspots.map((hotspot, index) => ({
13654
+ rank: offset + index + 1,
13655
+ path: hotspot.file,
13656
+ score: hotspot.score,
13657
+ factors: hotspot.factors
13658
+ }));
13659
+ var toReadingPath = (path) => ({
13660
+ target: path.target,
13661
+ targetKind: path.targetKind,
13662
+ steps: path.steps.map((step) => ({
13663
+ order: step.order,
13664
+ filePath: step.filePath,
13665
+ role: step.role,
13666
+ reason: step.reason,
13667
+ owner: step.owner === null ? null : toOwnerValues(step.owner),
13668
+ observedTopAuthor: step.observedTopAuthor,
13669
+ commits: step.commits,
13670
+ churn: step.churn,
13671
+ fanInInternal: step.fanInInternal,
13672
+ testFiles: [...step.testFiles]
13673
+ })),
13674
+ people: path.people,
13675
+ commands: [...path.commands],
13676
+ warnings: [...path.warnings],
13677
+ truncated: path.truncated
13678
+ });
13679
+ var trendValue = (point, metric) => {
13680
+ switch (metric) {
13681
+ case "riskScore":
13682
+ return point.riskScore;
13683
+ case "healthScore":
13684
+ return point.healthScore;
13685
+ case "unownedCriticalCount":
13686
+ return point.ownership === null ? null : point.ownership.unownedCritical;
13687
+ case "ghostOwnerCount":
13688
+ return point.ownership === null ? null : point.ownership.ghostOwners;
13689
+ case "driftPercent":
13690
+ return point.ownership === null ? null : point.ownership.driftPercent;
13691
+ }
13692
+ };
13693
+ var DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
13694
+ var sinceBoundary = (value) => Date.parse(DATE_ONLY_PATTERN.test(value) ? `${value}T00:00:00.000Z` : value);
13695
+ var untilBoundary = (value) => Date.parse(DATE_ONLY_PATTERN.test(value) ? `${value}T23:59:59.999Z` : value);
13696
+ var filterTrendByIsoDate = (series, filters) => {
13697
+ const since = filters.since === void 0 ? null : sinceBoundary(filters.since);
13698
+ const until = filters.until === void 0 ? null : untilBoundary(filters.until);
13699
+ return series.filter((point) => {
13700
+ const generatedAt = Date.parse(point.generatedAt);
13701
+ if (since !== null && generatedAt < since) return false;
13702
+ if (until !== null && generatedAt > until) return false;
13703
+ return true;
13704
+ });
13705
+ };
13706
+ var normalizePosixPath = (value) => {
13707
+ let normalized = value.replace(/\\/g, "/").trim();
13708
+ while (normalized.startsWith("./")) normalized = normalized.slice(2);
13709
+ return normalized;
13710
+ };
13711
+ var changedFilesFromGitOutput = (stdout2) => {
13712
+ const paths = stdout2.split(/\r?\n/).map(normalizePosixPath).filter((path) => path.length > 0).sort(compareText5);
13713
+ return [...new Set(paths)];
13714
+ };
13715
+ var shortCommit = (commit) => commit === null ? null : commit.slice(0, 7);
13716
+
13717
+ // src/mcp/tools.ts
13718
+ var READ_ONLY_ANNOTATIONS = {
13719
+ readOnlyHint: true,
13720
+ destructiveHint: false,
13721
+ idempotentHint: true,
13722
+ openWorldHint: false
13723
+ };
13724
+ var WRITE_ANNOTATIONS = {
13725
+ readOnlyHint: false,
13726
+ destructiveHint: false,
13727
+ idempotentHint: false,
13728
+ openWorldHint: false
13729
+ };
13730
+ var createGitRunner = (root) => {
13731
+ return async (args) => new Promise((resolvePromise) => {
13732
+ const child = spawn4("git", args, {
13733
+ cwd: root,
13734
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
13735
+ stdio: ["ignore", "pipe", "ignore"]
13736
+ });
13737
+ let stdout2 = "";
13738
+ child.stdout?.setEncoding("utf8");
13739
+ child.stdout?.on("data", (chunk) => {
13740
+ stdout2 += chunk;
13741
+ });
13742
+ child.on("error", () => {
13743
+ resolvePromise({ stdout: stdout2, exitCode: 1 });
13744
+ });
13745
+ child.on("close", (code) => {
13746
+ resolvePromise({ stdout: stdout2, exitCode: code ?? 1 });
13747
+ });
13748
+ });
13749
+ };
13750
+ var jsonResult = (value) => ({
13751
+ content: [{ type: "text", text: JSON.stringify(value, null, 2) }],
13752
+ structuredContent: value
13753
+ });
13754
+ var ownershipStatusEnum = z.enum([
13755
+ "aligned",
13756
+ "drifted",
13757
+ "ghosted",
13758
+ "unowned",
13759
+ "unowned-critical",
13760
+ "insufficient-evidence",
13761
+ "unknown"
13762
+ ]);
13763
+ var findingSeverityEnum = z.enum(["error", "warning"]);
13764
+ var ownershipRuleEnum = z.enum([
13765
+ "ownership/unowned-critical",
13766
+ "ownership/ghost-owner",
13767
+ "ownership/drift",
13768
+ "ownership/unknown"
13769
+ ]);
13770
+ var ownerValueSchema = z.object({
13771
+ kind: z.enum(["user", "team", "email"]),
13772
+ value: z.string()
13773
+ });
13774
+ var ownerValueListSchema = z.array(ownerValueSchema);
13775
+ var fileOwnerOutputSchema = z.object({
13776
+ path: z.string(),
13777
+ ref: z.string(),
13778
+ owners: ownerValueListSchema,
13779
+ teams: z.array(z.string()),
13780
+ status: ownershipStatusEnum,
13781
+ matchLine: z.number().nullable(),
13782
+ topAuthor: z.object({
13783
+ id: z.string(),
13784
+ share: z.number().nullable()
13785
+ }).nullable(),
13786
+ observed: z.object({
13787
+ commits: z.number(),
13788
+ recentCommits: z.number(),
13789
+ authors: z.number(),
13790
+ dormant: z.boolean(),
13791
+ busFactor: z.number().nullable(),
13792
+ lastCommitUnix: z.number().nullable()
13793
+ }),
13794
+ criticality: z.object({
13795
+ isCritical: z.boolean(),
13796
+ isHotspot: z.boolean(),
13797
+ fanIn: z.number().nullable(),
13798
+ riskScore: z.number().nullable()
13799
+ }),
13800
+ warnings: z.array(z.string())
13801
+ });
13802
+ var fileRiskOutputSchema = z.object({
13803
+ path: z.string(),
13804
+ ref: z.string(),
13805
+ score: z.number(),
13806
+ normalizedScore: z.number(),
13807
+ factors: z.object({
13808
+ structural: z.number(),
13809
+ evolution: z.number(),
13810
+ external: z.number()
13811
+ }),
13812
+ hotspotRank: z.number().nullable(),
13813
+ repositoryRiskScore: z.number()
13814
+ });
13815
+ var readingPathOutputSchema = z.object({
13816
+ target: z.string(),
13817
+ targetKind: z.enum(["file", "directory"]),
13818
+ steps: z.array(
13819
+ z.object({
13820
+ order: z.number(),
13821
+ filePath: z.string(),
13822
+ role: z.enum(["entry", "core", "helper", "test"]),
13823
+ reason: z.string(),
13824
+ owner: ownerValueListSchema.nullable(),
13825
+ observedTopAuthor: z.string().nullable(),
13826
+ commits: z.number(),
13827
+ churn: z.number(),
13828
+ fanInInternal: z.number(),
13829
+ testFiles: z.array(z.string())
13830
+ })
13831
+ ),
13832
+ people: z.array(
13833
+ z.object({
13834
+ authorId: z.string(),
13835
+ files: z.array(z.string()),
13836
+ commits: z.number()
13837
+ })
13838
+ ),
13839
+ commands: z.array(z.string()),
13840
+ warnings: z.array(z.string()),
13841
+ truncated: z.boolean()
13842
+ });
13843
+ var trendMetricEnum = z.enum([
13844
+ "riskScore",
13845
+ "healthScore",
13846
+ "unownedCriticalCount",
13847
+ "ghostOwnerCount",
13848
+ "driftPercent"
13849
+ ]);
13850
+ var DAY_WINDOW_PATTERN = /^\d+d$/;
13851
+ var ISO_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}(?:[T ].*)?$/;
13852
+ var isIsoDate = (value) => ISO_DATE_PATTERN.test(value) && !Number.isNaN(Date.parse(value));
13853
+ var isDayWindow = (value) => {
13854
+ if (!DAY_WINDOW_PATTERN.test(value)) return false;
13855
+ const days = Number.parseInt(value.slice(0, -1), 10);
13856
+ return Number.isInteger(days) && days > 0;
13857
+ };
13858
+ var trendSinceSchema = z.string().refine((value) => isIsoDate(value) || isDayWindow(value), {
13859
+ message: "since must be an ISO date or a day window such as 90d"
13860
+ });
13861
+ var trendUntilSchema = z.string().refine((value) => isIsoDate(value), {
13862
+ message: "until must be an ISO date"
13863
+ });
13864
+ var trendOutputSchema = z.object({
13865
+ metric: trendMetricEnum,
13866
+ series: z.array(
13867
+ z.object({
13868
+ file: z.string(),
13869
+ generatedAt: z.string(),
13870
+ commit: z.string().nullable(),
13871
+ value: z.number().nullable()
13872
+ })
13873
+ ),
13874
+ snapshotCount: z.number(),
13875
+ warnings: z.array(z.string())
13876
+ });
13877
+ var hotspotsOutputSchema = z.object({
13878
+ hotspots: z.array(
13879
+ z.object({
13880
+ rank: z.number(),
13881
+ path: z.string(),
13882
+ score: z.number(),
13883
+ factors: z.object({
13884
+ structural: z.number(),
13885
+ evolution: z.number(),
13886
+ external: z.number()
13887
+ })
13888
+ })
13889
+ ),
13890
+ nextCursor: z.string().nullable(),
13891
+ total: z.number()
13892
+ });
13893
+ var runScanOutputSchema = z.object({
13894
+ snapshotPath: z.string(),
13895
+ generatedAt: z.string(),
13896
+ commit: z.string().nullable(),
13897
+ riskScore: z.number(),
13898
+ healthScore: z.number(),
13899
+ hotspotCount: z.number(),
13900
+ scope: z.enum(["repository", "working_tree_changed"]),
13901
+ changedFiles: z.array(z.string()),
13902
+ changedHotspots: z.array(
13903
+ z.object({
13904
+ file: z.string(),
13905
+ score: z.number()
13906
+ })
13907
+ )
13908
+ });
13909
+ var findingsOutputSchema = z.object({
13910
+ findings: z.array(
13911
+ z.object({
13912
+ rule: z.string(),
13913
+ severity: findingSeverityEnum,
13914
+ status: ownershipStatusEnum,
13915
+ path: z.string(),
13916
+ message: z.string(),
13917
+ matchLine: z.number().nullable()
13918
+ })
13919
+ ),
13920
+ nextCursor: z.string().nullable(),
13921
+ total: z.number(),
13922
+ warnings: z.array(z.string())
13923
+ });
13924
+ var getFileOwner = async (context, input) => {
13925
+ const filePath = resolveRepositoryPath(context.root, input.path);
13926
+ const audit = await context.cache.getOwnershipAudit("HEAD");
13927
+ if (!audit.available) {
13928
+ throw new McpToolError(
13929
+ "no_codeowners",
13930
+ "no CODEOWNERS file is available at HEAD: declared owners cannot be reported"
13931
+ );
13932
+ }
13933
+ const file = audit.files.find((candidate) => candidate.filePath === filePath);
13934
+ if (file === void 0) {
13935
+ throw new McpToolError(
13936
+ "path_not_tracked",
13937
+ `path "${filePath}" is not tracked at HEAD: declared owners cannot be reported`
13938
+ );
13939
+ }
13940
+ return jsonResult(toFileOwner(file, "HEAD", audit.warnings));
13941
+ };
13942
+ var getFileRisk = async (context, input) => {
13943
+ if (input.ref !== void 0 && input.ref !== "HEAD") {
13944
+ throw new McpToolError(
13945
+ "not_supported",
13946
+ 'risk analysis runs on the working tree; pass ref="HEAD" or omit it'
13947
+ );
13948
+ }
13949
+ const filePath = resolveRepositoryPath(context.root, input.path);
13950
+ const analysis = await context.cache.getAnalysis();
13951
+ const fileScore = analysis.risk.fileScores.find((candidate) => candidate.file === filePath);
13952
+ if (fileScore === void 0) {
13953
+ throw new McpToolError(
13954
+ "path_not_analyzed",
13955
+ `path "${filePath}" is not present in the risk analysis`
13956
+ );
13957
+ }
13958
+ const hotspotIndex = analysis.risk.hotspots.findIndex((hotspot) => hotspot.file === filePath);
13959
+ return jsonResult({
13960
+ path: filePath,
13961
+ ref: "HEAD",
13962
+ score: fileScore.score,
13963
+ normalizedScore: fileScore.normalizedScore,
13964
+ factors: fileScore.factors,
13965
+ hotspotRank: hotspotIndex === -1 ? null : hotspotIndex + 1,
13966
+ repositoryRiskScore: analysis.risk.riskScore
13967
+ });
13968
+ };
13969
+ var getReadingPath = async (context, input) => {
13970
+ try {
13971
+ const result = await runPathCommand(
13972
+ input.target,
13973
+ {
13974
+ ...input.maxSteps === void 0 ? {} : { maxSteps: input.maxSteps },
13975
+ format: "json"
13976
+ },
13977
+ context.logger
13978
+ );
13979
+ return jsonResult(toReadingPath(result.readingPath));
13980
+ } catch (error) {
13981
+ if (error instanceof PathConfigurationError) {
13982
+ throw new McpToolError("invalid_argument", error.message);
13983
+ }
13984
+ throw error;
13985
+ }
13986
+ };
13987
+ var getTrend = async (context, input) => {
13988
+ if (input.path !== void 0) {
13989
+ throw new McpToolError(
13990
+ "not_supported",
13991
+ "per-file trend series are not available: snapshots record repository-level metrics only"
13992
+ );
13993
+ }
13994
+ const snapshotsDir = process.env["CODESENTINEL_SNAPSHOTS_DIR"] ?? join15(context.root, ".codesentinel", "snapshots");
13995
+ const dayWindow = input.since !== void 0 && isDayWindow(input.since) ? input.since : null;
13996
+ let result;
13997
+ try {
13998
+ result = await readTrendSnapshots({
13999
+ from: snapshotsDir,
14000
+ ...dayWindow === null ? {} : { since: dayWindow }
14001
+ });
14002
+ } catch (error) {
14003
+ if (error instanceof TrendConfigurationError) {
14004
+ throw new McpToolError(
14005
+ "no_snapshots",
14006
+ `${error.message}; set CODESENTINEL_SNAPSHOTS_DIR to the directory or glob holding snapshot artifacts`
14007
+ );
14008
+ }
14009
+ throw error;
14010
+ }
14011
+ const isoSince = input.since !== void 0 && dayWindow === null ? input.since : void 0;
14012
+ const series = filterTrendByIsoDate(result.series, {
14013
+ ...isoSince === void 0 ? {} : { since: isoSince },
14014
+ ...input.until === void 0 ? {} : { until: input.until }
14015
+ }).map((point) => ({
14016
+ file: point.file,
14017
+ generatedAt: point.generatedAt,
14018
+ commit: point.commit,
14019
+ value: trendValue(point, input.metric)
14020
+ }));
14021
+ return jsonResult({
14022
+ metric: input.metric,
14023
+ series,
14024
+ snapshotCount: series.length,
14025
+ warnings: [...result.warnings]
14026
+ });
14027
+ };
14028
+ var listHotspots = async (context, input) => {
14029
+ const analysis = await context.cache.getAnalysis();
14030
+ const offset = decodeCursor(input.cursor);
14031
+ const { page, nextCursor } = paginate(analysis.risk.hotspots, offset, input.limit);
14032
+ return jsonResult({
14033
+ hotspots: toHotspots(page, offset),
14034
+ nextCursor,
14035
+ total: analysis.risk.hotspots.length
14036
+ });
14037
+ };
14038
+ var writeSnapshotFile = async (context, directory, baseName, contents) => {
14039
+ let suffix = 2;
14040
+ let candidate = join15(directory, `${baseName}.json`);
14041
+ for (; ; ) {
14042
+ assertPathInsideRoot(context.root, candidate);
14043
+ try {
14044
+ await writeFile12(candidate, contents, { encoding: "utf8", flag: "wx" });
14045
+ return candidate;
14046
+ } catch (error) {
14047
+ if (error.code !== "EEXIST") {
14048
+ throw error;
14049
+ }
14050
+ candidate = join15(directory, `${baseName}-${suffix}.json`);
14051
+ suffix += 1;
14052
+ }
14053
+ }
14054
+ };
14055
+ var runScan = async (context, input) => {
14056
+ const scanPath = input.path === void 0 ? context.root : resolve13(context.root, resolveRepositoryPath(context.root, input.path));
14057
+ assertPathInsideRoot(context.root, scanPath);
14058
+ const insideWorkTree = await context.git(["rev-parse", "--is-inside-work-tree"]);
14059
+ if (insideWorkTree.exitCode !== 0 || insideWorkTree.stdout.trim() !== "true") {
14060
+ throw new McpToolError(
14061
+ "not_a_git_repository",
14062
+ `run_scan requires a git work tree: ${context.root} is not inside one`
14063
+ );
14064
+ }
14065
+ const head = await context.git(["rev-parse", "HEAD"]);
14066
+ const commit = head.exitCode === 0 && head.stdout.trim().length > 0 ? head.stdout.trim() : null;
14067
+ const snapshot = await buildAnalysisSnapshot(
14068
+ scanPath,
14069
+ "likely_merge",
14070
+ {
14071
+ includeTrace: false,
14072
+ source: {
14073
+ ...commit === null ? {} : { commit },
14074
+ ref: "HEAD"
14075
+ }
14076
+ },
14077
+ context.logger
14078
+ );
14079
+ const snapshotDirectory = join15(context.root, ".codesentinel", "snapshots");
14080
+ await mkdir5(snapshotDirectory, { recursive: true });
14081
+ const generatedAt = snapshot.generatedAt;
14082
+ const baseName = `scan-${generatedAt.replace(/[:.Z]/g, "-")}-${shortCommit(commit) ?? "nocommit"}`;
14083
+ const snapshotPath = await writeSnapshotFile(
14084
+ context,
14085
+ snapshotDirectory,
14086
+ baseName,
14087
+ JSON.stringify(snapshot, null, 2)
14088
+ );
14089
+ const changedOnly = input.changedOnly === true;
14090
+ let changedFiles = [];
14091
+ if (changedOnly) {
14092
+ const diff = await context.git(["diff", "--name-only", "HEAD"]);
14093
+ changedFiles = changedFilesFromGitOutput(diff.stdout);
14094
+ }
14095
+ const changedHotspots = changedOnly ? snapshot.analysis.risk.hotspots.filter((hotspot) => changedFiles.includes(hotspot.file)).map((hotspot) => ({ file: hotspot.file, score: hotspot.score })) : [];
14096
+ return jsonResult({
14097
+ snapshotPath,
14098
+ generatedAt,
14099
+ commit,
14100
+ riskScore: snapshot.analysis.risk.riskScore,
14101
+ healthScore: snapshot.analysis.health.healthScore,
14102
+ hotspotCount: snapshot.analysis.risk.hotspots.length,
14103
+ scope: changedOnly ? "working_tree_changed" : "repository",
14104
+ changedFiles: [...changedFiles],
14105
+ changedHotspots
14106
+ });
14107
+ };
14108
+ var searchFindings = async (context, input) => {
14109
+ if (input.path !== void 0 && isAbsolute4(input.path)) {
14110
+ throw new McpToolError("path_outside_root", `path "${input.path}" must be repository-relative`);
14111
+ }
14112
+ const pathPrefix = input.path === void 0 ? "" : normalizePathPrefix(input.path);
14113
+ const audit = await context.cache.getOwnershipAudit("HEAD");
14114
+ if (!audit.available) {
14115
+ return jsonResult({
14116
+ findings: [],
14117
+ nextCursor: null,
14118
+ total: 0,
14119
+ warnings: ["no CODEOWNERS file is available at HEAD: no ownership findings"]
14120
+ });
14121
+ }
14122
+ const filters = {
14123
+ ...pathPrefix === "" ? {} : { path: pathPrefix },
14124
+ ...input.severity === void 0 ? {} : { severity: input.severity },
14125
+ ...input.rule === void 0 ? {} : { rule: input.rule },
14126
+ ...input.status === void 0 ? {} : { status: input.status }
14127
+ };
14128
+ const findings = filterFindings(toFindings(audit), filters);
14129
+ const offset = decodeCursor(input.cursor);
14130
+ const { page, nextCursor } = paginate(findings, offset, input.limit);
14131
+ return jsonResult({
14132
+ findings: page.map((finding) => ({ ...finding })),
14133
+ nextCursor,
14134
+ total: findings.length,
14135
+ warnings: [...audit.warnings]
14136
+ });
14137
+ };
14138
+ var registerCodeSentinelTools = (server, context) => {
14139
+ server.registerTool(
14140
+ "get_file_owner",
14141
+ {
14142
+ title: "Get file owner",
14143
+ description: "Report the declared CODEOWNERS owners, observed authorship and criticality of one tracked file.",
14144
+ inputSchema: z.object({
14145
+ path: z.string().min(1).describe("Repository-relative path of the file")
14146
+ }),
14147
+ outputSchema: fileOwnerOutputSchema,
14148
+ annotations: READ_ONLY_ANNOTATIONS
14149
+ },
14150
+ async (input) => {
14151
+ try {
14152
+ return await getFileOwner(context, input);
14153
+ } catch (error) {
14154
+ return toToolErrorResult(error);
14155
+ }
14156
+ }
14157
+ );
14158
+ server.registerTool(
14159
+ "get_file_risk",
14160
+ {
14161
+ title: "Get file risk",
14162
+ description: "Report the composed structural, evolution and external risk score of one analyzed file.",
14163
+ inputSchema: z.object({
14164
+ path: z.string().min(1).describe("Repository-relative path of the file"),
14165
+ ref: z.string().optional().describe('Git ref, only "HEAD" is supported')
14166
+ }),
14167
+ outputSchema: fileRiskOutputSchema,
14168
+ annotations: READ_ONLY_ANNOTATIONS
14169
+ },
14170
+ async (input) => {
14171
+ try {
14172
+ return await getFileRisk(context, input);
14173
+ } catch (error) {
14174
+ return toToolErrorResult(error);
14175
+ }
14176
+ }
14177
+ );
14178
+ server.registerTool(
14179
+ "get_reading_path",
14180
+ {
14181
+ title: "Get reading path",
14182
+ description: "Order the files to read first for a file or directory target, with ownership and activity evidence.",
14183
+ inputSchema: z.object({
14184
+ target: z.string().min(1).describe("Repository-relative file or directory target"),
14185
+ maxSteps: z.number().int().min(1).max(25).optional().describe("Maximum number of steps in the reading path")
14186
+ }),
14187
+ outputSchema: readingPathOutputSchema,
14188
+ annotations: READ_ONLY_ANNOTATIONS
14189
+ },
14190
+ async (input) => {
14191
+ try {
14192
+ return await getReadingPath(context, input);
14193
+ } catch (error) {
14194
+ return toToolErrorResult(error);
14195
+ }
14196
+ }
14197
+ );
14198
+ server.registerTool(
14199
+ "get_trend",
14200
+ {
14201
+ title: "Get trend",
14202
+ description: "Read repository-level metric history from snapshot artifacts, ordered oldest to newest.",
14203
+ inputSchema: z.object({
14204
+ metric: trendMetricEnum.describe("Repository metric to read"),
14205
+ path: z.string().optional().describe("Unsupported: snapshots record repository-level metrics only"),
14206
+ since: trendSinceSchema.optional().describe("ISO date or day window such as 90d"),
14207
+ until: trendUntilSchema.optional().describe("Inclusive ISO upper bound")
14208
+ }),
14209
+ outputSchema: trendOutputSchema,
14210
+ annotations: READ_ONLY_ANNOTATIONS
14211
+ },
14212
+ async (input) => {
14213
+ try {
14214
+ return await getTrend(context, input);
14215
+ } catch (error) {
14216
+ return toToolErrorResult(error);
14217
+ }
14218
+ }
14219
+ );
14220
+ server.registerTool(
14221
+ "list_hotspots",
14222
+ {
14223
+ title: "List hotspots",
14224
+ description: "List the repository risk hotspots in rank order, with cursor pagination.",
14225
+ inputSchema: z.object({
14226
+ limit: z.number().int().min(1).max(100).default(20).describe("Page size"),
14227
+ cursor: z.string().optional().describe("Opaque cursor from a previous page")
14228
+ }),
14229
+ outputSchema: hotspotsOutputSchema,
14230
+ annotations: READ_ONLY_ANNOTATIONS
14231
+ },
14232
+ async (input) => {
14233
+ try {
14234
+ return await listHotspots(context, input);
14235
+ } catch (error) {
14236
+ return toToolErrorResult(error);
14237
+ }
14238
+ }
14239
+ );
14240
+ server.registerTool(
14241
+ "run_scan",
14242
+ {
14243
+ title: "Run scan",
14244
+ description: "Analyze the repository (or a sub-path) and write a snapshot under .codesentinel/snapshots.",
14245
+ inputSchema: z.object({
14246
+ path: z.string().optional().describe("Sub-path of the repository root"),
14247
+ changedOnly: z.boolean().optional().describe("Also report hotspots touched by the working-tree diff against HEAD")
14248
+ }),
14249
+ outputSchema: runScanOutputSchema,
14250
+ annotations: WRITE_ANNOTATIONS
14251
+ },
14252
+ async (input) => {
14253
+ try {
14254
+ return await runScan(context, input);
14255
+ } catch (error) {
14256
+ return toToolErrorResult(error);
14257
+ }
14258
+ }
14259
+ );
14260
+ server.registerTool(
14261
+ "search_findings",
14262
+ {
14263
+ title: "Search findings",
14264
+ description: "Search declared-ownership findings by path, severity, rule or status, with cursor pagination.",
14265
+ inputSchema: z.object({
14266
+ path: z.string().optional().describe("File or directory path prefix"),
14267
+ severity: findingSeverityEnum.optional().describe("Finding severity"),
14268
+ rule: ownershipRuleEnum.optional().describe("SARIF ownership rule id"),
14269
+ status: ownershipStatusEnum.optional().describe("Ownership status"),
14270
+ cursor: z.string().optional().describe("Opaque cursor from a previous page"),
14271
+ limit: z.number().int().min(1).max(100).default(20).describe("Page size")
14272
+ }),
14273
+ outputSchema: findingsOutputSchema,
14274
+ annotations: READ_ONLY_ANNOTATIONS
14275
+ },
14276
+ async (input) => {
14277
+ try {
14278
+ return await searchFindings(context, input);
14279
+ } catch (error) {
14280
+ return toToolErrorResult(error);
14281
+ }
14282
+ }
14283
+ );
14284
+ };
14285
+
14286
+ // src/mcp/server.ts
14287
+ var MCP_SERVER_NAME = "codesentinel";
14288
+ var SERVER_INSTRUCTIONS = "CodeSentinel exposes repository ownership, risk, trend and reading-path data from local git history. All tools are read-only except run_scan, which analyzes the repository and writes a snapshot under .codesentinel/snapshots.";
14289
+ var setProcessRoot = (root) => {
14290
+ process.env["INIT_CWD"] = root;
14291
+ };
14292
+ var createCodeSentinelServer = (options) => {
14293
+ const root = options.root ?? resolveMcpRoot(process.env);
14294
+ setProcessRoot(root);
14295
+ const context = {
14296
+ root,
14297
+ version: options.version,
14298
+ logger: options.logger,
14299
+ cache: createAnalysisCache(root, options.logger),
14300
+ git: options.git ?? createGitRunner(root)
14301
+ };
14302
+ const server = new McpServer(
14303
+ { name: MCP_SERVER_NAME, version: options.version },
14304
+ { instructions: SERVER_INSTRUCTIONS }
14305
+ );
14306
+ registerCodeSentinelTools(server, context);
14307
+ return server;
14308
+ };
14309
+ var runMcpServer = async (options) => {
14310
+ const handle = serveStdio(
14311
+ () => createCodeSentinelServer({ version: options.version, logger: options.logger }),
14312
+ {
14313
+ onerror: (error) => options.logger.error(error.message)
14314
+ }
14315
+ );
14316
+ await new Promise((resolveClose) => {
14317
+ const close = () => {
14318
+ process.stdin.off("end", close);
14319
+ process.stdin.off("close", close);
14320
+ resolveClose();
14321
+ };
14322
+ process.stdin.once("end", close);
14323
+ process.stdin.once("close", close);
14324
+ });
14325
+ await handle.close();
14326
+ };
14327
+
13403
14328
  // src/index.ts
13404
14329
  var program = new Command();
13405
- var packageJsonPath = resolve12(dirname4(fileURLToPath2(import.meta.url)), "../package.json");
14330
+ var packageJsonPath = resolve14(dirname4(fileURLToPath2(import.meta.url)), "../package.json");
13406
14331
  var { version } = JSON.parse(readFileSync4(packageJsonPath, "utf8"));
13407
14332
  var parseRecentWindowDays = (value) => {
13408
14333
  const parsed = Number.parseInt(value, 10);
@@ -13542,6 +14467,23 @@ program.command("update").description("check for a newer CodeSentinel version an
13542
14467
  currentVersion: version
13543
14468
  });
13544
14469
  });
14470
+ program.command("mcp").exitOverride().description("serve CodeSentinel over the Model Context Protocol (stdio transport)").addHelpText(
14471
+ "after",
14472
+ `
14473
+ Transport: stdio only. JSON-RPC messages on stdin/stdout; every log goes to stderr.
14474
+ Tools: get_file_owner, get_file_risk, get_reading_path, get_trend, list_hotspots, run_scan, search_findings.
14475
+ No credentials are accepted as tool arguments; git and CI credentials come from the environment.
14476
+ Repository root: --root is not a flag; set CODESENTINEL_ROOT (defaults to the current directory).
14477
+ Register it with: claude mcp add codesentinel -- codesentinel mcp`
14478
+ ).addOption(
14479
+ new Option(
14480
+ "--log-level <level>",
14481
+ "log verbosity: silent, error, warn, info, debug (logs are written to stderr)"
14482
+ ).choices(["silent", "error", "warn", "info", "debug"]).default(parseLogLevel(process.env["CODESENTINEL_LOG_LEVEL"]))
14483
+ ).action(async (options) => {
14484
+ const logger = createStderrLogger(options.logLevel);
14485
+ await runMcpServer({ version, logger });
14486
+ });
13545
14487
  program.command("analyze").argument("[path]", "path to the project to analyze").addOption(scoringProfileOption()).addOption(
13546
14488
  new Option(
13547
14489
  "--author-identity <mode>",
@@ -13726,7 +14668,7 @@ program.command("run").argument("[path]", "path to the project to analyze").addO
13726
14668
  ...options.trace === true ? { trace: explain.trace } : {}
13727
14669
  });
13728
14670
  if (options.snapshot !== void 0) {
13729
- await writeFile12(options.snapshot, JSON.stringify(snapshot, null, 2), "utf8");
14671
+ await writeFile13(options.snapshot, JSON.stringify(snapshot, null, 2), "utf8");
13730
14672
  logger.info(`snapshot written: ${options.snapshot}`);
13731
14673
  }
13732
14674
  const report = options.compare === void 0 ? createReport(snapshot) : createReport(
@@ -14410,7 +15352,7 @@ if (argv.length <= 2) {
14410
15352
  program.outputHelp();
14411
15353
  process.exit(0);
14412
15354
  }
14413
- if (argv[2] !== "update") {
15355
+ if (argv[2] !== "update" && argv[2] !== "mcp") {
14414
15356
  await checkForCliUpdates({
14415
15357
  packageName: "@getcodesentinel/codesentinel",
14416
15358
  currentVersion: version,