@getchomp/mcp 0.2.44 → 0.2.46

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
@@ -13,6 +13,9 @@ import { applyActivePluginProjections, discoverPluginsInDir, listChompPlugins, l
13
13
  import "./plugins/index.js";
14
14
  import { SEMANTIC_OVERLAY_LAYER, classifySemanticOverlayMap, isEnrichmentTargetNode, } from "./enrichNodesPlugin.js";
15
15
  import { getConventionsReference } from "./conventionsReference.js";
16
+ import { diffDesignSystem } from "./designSystemPlugin.js";
17
+ import { resolveBaselinePath } from "./designSystem/baseline.js";
18
+ import { resolveDesignSystemConfig } from "./designSystem/config.js";
16
19
  export { auditGraphHealth, buildActiveViewUrl, checkGraphBoundaries, computeBlastRadius, filterNodesForMcp, findGraphRedundancies, formatEnrichNodesSummary, hydrateNodeOverlays, packageMatchesFilter, resolveViewNodeIds, resolveViewTargetAltitude, } from "./intelligence.js";
17
20
  export { PLUGINS_STATE_DIR_REL, PLUGIN_LAST_RUN_FILENAME, applyActivePluginProjections, buildOverlayEvidence, collectPluginRepoFiles, collectPluginStateFiles, computeFileOverlayHash, defineChompPlugin, discoverPluginsInDir, getChompPlugin, getPluginEnvStatus, getPluginLastRunPath, getPluginMcpToolSummaries, getPluginSettingsPath, getPluginStateDir, getPluginStateDirRel, getRegisteredPluginDefaultLayers, isPluginLayerEnabled, isRegisteredStructuralPluginOverlay, listChompPlugins, loadPluginSettings, readPluginLastRun, readRepoOverlayLayerToggles, registerChompPlugin, resolveActiveUiBaseUrl, resolvePluginSecret, resolveRepoGitBranch, resolveRepoName, runAllChompPlugins, runChompPlugin, savePluginSettings, unregisterChompPlugin, writePluginActiveView, writePluginLastRun, } from "./pluginRunner.js";
18
21
  export { BUILTIN_PLUGINS_DIR, discoverBuiltInPlugins } from "./plugins/index.js";
@@ -482,12 +485,24 @@ export async function computeGraphDeltaWithShims(repoPath, dbPath, repoId, stora
482
485
  overlayLayers,
483
486
  });
484
487
  const delta = compareGraphs(baseProjected, currentProjected);
488
+ const architecturalGate = computeArchitecturalDiffGate(baseProjected, currentProjected, {
489
+ repoPath,
490
+ isTargetOnDisk: true,
491
+ });
492
+ const designSystemGate = await maybeComputeCompactDesignSystemGate(repoPath, repoId, currentProjected);
493
+ const gateStatus = architecturalGate.gateStatus === "PASS" &&
494
+ (!designSystemGate || designSystemGate.gateStatus === "PASS")
495
+ ? "PASS"
496
+ : "WARN";
485
497
  return {
486
498
  ...delta,
487
499
  headCommitSha,
488
500
  baseExtractorVersion: baseRaw.extractorVersion,
489
501
  targetExtractorVersion: currentRaw.extractorVersion,
490
502
  baseStatus: "FRESH",
503
+ gateStatus,
504
+ architecturalGate,
505
+ ...(designSystemGate ? { designSystemGate } : {}),
491
506
  };
492
507
  }
493
508
  function resolveMcpGitCommitSha(repoPath, ref) {
@@ -644,6 +659,10 @@ export async function computeGitRefDeltaWithShims(repoPath, options) {
644
659
  readRepoFileOverride: (rel) => readGitBlobAtCommit(repoPath, targetSha, rel),
645
660
  });
646
661
  const delta = compareGraphs(baseProjected, targetProjected);
662
+ const architecturalGate = computeArchitecturalDiffGate(baseProjected, targetProjected, {
663
+ repoPath,
664
+ isTargetOnDisk: false,
665
+ });
647
666
  return {
648
667
  ...delta,
649
668
  baseCommitSha: baseSha,
@@ -655,6 +674,8 @@ export async function computeGitRefDeltaWithShims(repoPath, options) {
655
674
  baseRef,
656
675
  targetRef,
657
676
  isWorkingTreeSnapshot: false,
677
+ gateStatus: architecturalGate.gateStatus,
678
+ architecturalGate,
658
679
  };
659
680
  }
660
681
  const snapshotAt = new Date().toISOString();
@@ -664,6 +685,16 @@ export async function computeGitRefDeltaWithShims(repoPath, options) {
664
685
  overlayLayers,
665
686
  });
666
687
  const delta = compareGraphs(baseProjected, currentProjected);
688
+ const architecturalGate = computeArchitecturalDiffGate(baseProjected, currentProjected, {
689
+ repoPath,
690
+ isTargetOnDisk: true,
691
+ });
692
+ const repoIdForDs = resolveRepoName(repoPath).toLowerCase().replace(/[^a-z0-9_-]/g, "_");
693
+ const designSystemGate = await maybeComputeCompactDesignSystemGate(repoPath, repoIdForDs, currentProjected);
694
+ const gateStatus = architecturalGate.gateStatus === "PASS" &&
695
+ (!designSystemGate || designSystemGate.gateStatus === "PASS")
696
+ ? "PASS"
697
+ : "WARN";
667
698
  return {
668
699
  ...delta,
669
700
  baseCommitSha: baseSha,
@@ -675,6 +706,213 @@ export async function computeGitRefDeltaWithShims(repoPath, options) {
675
706
  targetRef: "WORKING_TREE",
676
707
  isWorkingTreeSnapshot: true,
677
708
  snapshotAt,
709
+ gateStatus,
710
+ architecturalGate,
711
+ ...(designSystemGate ? { designSystemGate } : {}),
712
+ };
713
+ }
714
+ async function maybeComputeCompactDesignSystemGate(repoPath, repoId, liveGraph) {
715
+ try {
716
+ const resolvedCfg = resolveDesignSystemConfig(repoPath);
717
+ const baselinePath = resolveBaselinePath(repoPath, resolvedCfg.config.baseline.path);
718
+ if (!existsSync(baselinePath))
719
+ return undefined;
720
+ const ds = await diffDesignSystem({
721
+ repoPath,
722
+ repoId,
723
+ graph: liveGraph,
724
+ });
725
+ if (!ds.hasBaseline || ds.gateStatus === "NO_BASELINE")
726
+ return undefined;
727
+ const gateStatus = ds.gateStatus === "PASS" ? "PASS" : "WARN";
728
+ const nonEmptyIssues = {};
729
+ if (gateStatus === "WARN" && ds.newIssues) {
730
+ for (const [k, arr] of Object.entries(ds.newIssues)) {
731
+ if (Array.isArray(arr) && arr.length > 0) {
732
+ nonEmptyIssues[k] = arr.slice(0, 5);
733
+ }
734
+ }
735
+ }
736
+ return {
737
+ gateStatus,
738
+ summary: {
739
+ newRawPrimitiveCount: ds.summary.newRawPrimitiveCount ?? 0,
740
+ newHardcodedLiteralCount: ds.summary.newHardcodedLiteralCount ?? 0,
741
+ newArbitraryTailwindCount: ds.summary.newArbitraryTailwindCount ?? 0,
742
+ newUndefinedTokenCount: ds.summary.newUndefinedTokenCount ?? 0,
743
+ newInvariantViolationCount: ds.summary.newInvariantViolationCount ?? 0,
744
+ newContrastFailureCount: ds.summary.newContrastFailureCount ?? 0,
745
+ },
746
+ ...(Object.keys(nonEmptyIssues).length > 0 ? { newIssues: nonEmptyIssues } : {}),
747
+ };
748
+ }
749
+ catch {
750
+ return undefined;
751
+ }
752
+ }
753
+ export function computeArchitecturalDiffGate(baseGraph, targetGraph, options) {
754
+ const baseRed = findGraphRedundancies(baseGraph, {
755
+ packageName: options?.packageName,
756
+ limit: 100,
757
+ });
758
+ const targetRed = findGraphRedundancies(targetGraph, {
759
+ packageName: options?.packageName,
760
+ limit: 100,
761
+ ...(options?.isTargetOnDisk !== false && options?.repoPath
762
+ ? { repoPath: options.repoPath }
763
+ : {}),
764
+ });
765
+ const baseNodeIds = new Set(baseGraph.nodes.map((n) => n.id));
766
+ const baseMiddlemenIds = new Set(baseRed.passThroughMiddlemen.map((m) => m.middleman.id));
767
+ const newPassThroughWrappers = targetRed.passThroughMiddlemen.filter((m) => {
768
+ if (baseMiddlemenIds.has(m.middleman.id))
769
+ return false;
770
+ // Do not penalize backward-compatible cross-package facade adapters (e.g. refactoring an
771
+ // existing @app/ui helper to delegate to a newly extracted @app/utils foundation package).
772
+ if (m.crossesPackageBoundary && baseNodeIds.has(m.middleman.id))
773
+ return false;
774
+ if (m.crossesPackageBoundary)
775
+ return false;
776
+ return true;
777
+ });
778
+ const baseSeqCallersBySig = new Map();
779
+ for (const seq of baseRed.duplicateStorySequences) {
780
+ const sig = seq.sharedTargets.map((t) => t.id).sort().join("::");
781
+ baseSeqCallersBySig.set(sig, new Set(seq.parallelCallers.map((c) => c.id)));
782
+ }
783
+ const newDuplicateFlows = targetRed.duplicateStorySequences.filter((seq) => {
784
+ const sig = seq.sharedTargets.map((t) => t.id).sort().join("::");
785
+ const baseCallers = baseSeqCallersBySig.get(sig);
786
+ if (!baseCallers)
787
+ return true;
788
+ return seq.parallelCallers.some((c) => !baseCallers.has(c.id));
789
+ });
790
+ const baseDupCountByName = new Map();
791
+ for (const dup of baseRed.duplicateSymbols) {
792
+ baseDupCountByName.set(dup.symbolName, dup.instanceCount);
793
+ }
794
+ const newDuplicateSymbols = targetRed.duplicateSymbols.filter((dup) => dup.instanceCount > (baseDupCountByName.get(dup.symbolName) ?? 0));
795
+ const baseBnd = checkGraphBoundaries(baseGraph, {
796
+ packageName: options?.packageName,
797
+ repoPath: options?.repoPath,
798
+ });
799
+ const targetBnd = checkGraphBoundaries(targetGraph, {
800
+ packageName: options?.packageName,
801
+ repoPath: options?.repoPath,
802
+ });
803
+ const violationKey = (v) => `${v.ruleId}::${v.sourcePackage}::${v.targetPackage}`;
804
+ const baseViolationKeys = new Set(baseBnd.boundaryViolations.map(violationKey));
805
+ const allNewBoundaryFindings = targetBnd.boundaryViolations.filter((v) => !baseViolationKeys.has(violationKey(v)));
806
+ const newBoundaryViolations = allNewBoundaryFindings.filter((v) => !v.severity || v.severity === "VIOLATION");
807
+ const newBoundaryAdvisories = allNewBoundaryFindings.filter((v) => v.severity === "ADVISORY");
808
+ const pkgCycleKey = (c) => Array.isArray(c?.packages)
809
+ ? [...c.packages].sort().join("::")
810
+ : JSON.stringify(c);
811
+ const basePkgCycles = new Set(baseBnd.circularDependencies.packageCycles.map(pkgCycleKey));
812
+ const newPkgCycles = targetBnd.circularDependencies.packageCycles.filter((c) => !basePkgCycles.has(pkgCycleKey(c)));
813
+ const contractCycleKey = (c) => Array.isArray(c?.nodes)
814
+ ? c.nodes.map((n) => n.id ?? n).sort().join("::")
815
+ : JSON.stringify(c);
816
+ const baseContractCycles = new Set(baseBnd.circularDependencies.contractCycles.map(contractCycleKey));
817
+ const newContractCycles = targetBnd.circularDependencies.contractCycles.filter((c) => !baseContractCycles.has(contractCycleKey(c)));
818
+ const cap = options?.limit ?? 25;
819
+ const totalNew = newPassThroughWrappers.length +
820
+ newDuplicateFlows.length +
821
+ newDuplicateSymbols.length +
822
+ newBoundaryViolations.length +
823
+ newPkgCycles.length +
824
+ newContractCycles.length;
825
+ return {
826
+ gateStatus: totalNew === 0 ? "PASS" : "WARN",
827
+ summary: {
828
+ newPassThroughWrapperCount: newPassThroughWrappers.length,
829
+ newDuplicateFlowCount: newDuplicateFlows.length,
830
+ newDuplicateSymbolCount: newDuplicateSymbols.length,
831
+ newBoundaryViolationCount: newBoundaryViolations.length,
832
+ ...(newBoundaryAdvisories.length > 0
833
+ ? { newBoundaryAdvisoryCount: newBoundaryAdvisories.length }
834
+ : {}),
835
+ newCycleCount: newPkgCycles.length + newContractCycles.length,
836
+ },
837
+ newPassThroughWrappers: newPassThroughWrappers.slice(0, cap),
838
+ newDuplicateFlows: newDuplicateFlows.slice(0, cap),
839
+ newDuplicateSymbols: newDuplicateSymbols.slice(0, cap),
840
+ newBoundaryViolations: newBoundaryViolations.slice(0, cap),
841
+ ...(newBoundaryAdvisories.length > 0
842
+ ? { newBoundaryAdvisories: newBoundaryAdvisories.slice(0, cap) }
843
+ : {}),
844
+ newCycles: {
845
+ packageCycles: newPkgCycles.slice(0, cap),
846
+ contractCycles: newContractCycles.slice(0, cap),
847
+ },
848
+ };
849
+ }
850
+ export async function resolveLiveAndBaseGraphsForMcp(repoPath, dbPath, repoId, options) {
851
+ const gitState = inspectMcpRepoGitBranches(repoPath);
852
+ const overlayLayers = readRepoOverlayLayerToggles(repoPath);
853
+ if (gitState.workingTreeDirty) {
854
+ const { headCommitSha } = readGitHeadState(repoPath);
855
+ const excludeWorkspaces = loadRepoExcludeWorkspaces(repoPath);
856
+ const liveRaw = extractLiveUserGraph(repoPath, headCommitSha, excludeWorkspaces);
857
+ const targetGraph = applyActivePluginProjections(liveRaw, {
858
+ repoPath,
859
+ overlayLayers,
860
+ });
861
+ let baseGraph = null;
862
+ if (options?.needBaseGraph) {
863
+ if (existsSync(dbPath)) {
864
+ const persistedRaw = await loadActiveGraphCached(dbPath, repoId);
865
+ const persistedSnap = persistedRaw
866
+ ? readBaseSnapshotIfMatching(dbPath, persistedRaw)
867
+ : null;
868
+ if (persistedRaw && !persistedSnap?.workingTreeDirty) {
869
+ baseGraph = hasGitCommit(repoPath, persistedRaw.commitSha)
870
+ ? applyActivePluginProjections(persistedRaw, {
871
+ repoPath,
872
+ overlayLayers,
873
+ readRepoFileOverride: (rel) => readGitBlobAtCommit(repoPath, persistedRaw.commitSha.trim(), rel),
874
+ })
875
+ : persistedRaw;
876
+ }
877
+ }
878
+ if (!baseGraph && headCommitSha) {
879
+ const baseRaw = extractMcpArchivedGraph(repoPath, headCommitSha, excludeWorkspaces, dbPath);
880
+ baseGraph = applyActivePluginProjections(baseRaw, {
881
+ repoPath,
882
+ overlayLayers,
883
+ readRepoFileOverride: (rel) => readGitBlobAtCommit(repoPath, headCommitSha, rel),
884
+ });
885
+ }
886
+ }
887
+ return { targetGraph, baseGraph, evaluatedSource: "WORKING_TREE" };
888
+ }
889
+ if (!existsSync(dbPath)) {
890
+ throw new Error(`Chomp database not found at ${dbPath}. Please run 'chomp analyze .' first.`);
891
+ }
892
+ const targetGraph = await loadActiveGraphWithShims(repoPath, dbPath, repoId);
893
+ if (!targetGraph) {
894
+ throw new Error(`Graph data for repository '${repoId}' not found in the database. Please run 'chomp analyze .' first.`);
895
+ }
896
+ let baseGraph = null;
897
+ if (options?.needBaseGraph &&
898
+ gitState.currentBranch !== "HEAD" &&
899
+ gitState.currentBranch !== gitState.defaultBaseBranch &&
900
+ gitState.hasDefaultBase) {
901
+ const baseSha = resolveMcpGitCommitSha(repoPath, gitState.defaultBaseBranch);
902
+ if (baseSha) {
903
+ const excludeWorkspaces = loadRepoExcludeWorkspaces(repoPath);
904
+ const baseRaw = extractMcpArchivedGraph(repoPath, baseSha, excludeWorkspaces, dbPath);
905
+ baseGraph = applyActivePluginProjections(baseRaw, {
906
+ repoPath,
907
+ overlayLayers,
908
+ readRepoFileOverride: (rel) => readGitBlobAtCommit(repoPath, baseSha, rel),
909
+ });
910
+ }
911
+ }
912
+ return {
913
+ targetGraph,
914
+ baseGraph: baseGraph ?? (options?.needBaseGraph ? targetGraph : null),
915
+ evaluatedSource: "COMMITTED_HEAD",
678
916
  };
679
917
  }
680
918
  /**
@@ -696,6 +934,372 @@ export function withMcpToolErrorBoundary(handler) {
696
934
  }
697
935
  };
698
936
  }
937
+ export function formatCompactMcpDiff(delta, options) {
938
+ const includeLexical = Boolean(options?.includeLexicalShift);
939
+ const includeUnchanged = Boolean(options?.includeUnchanged);
940
+ const verbose = Boolean(options?.verbose);
941
+ const maxNodes = options?.maxNodes ?? 60;
942
+ const maxEdges = options?.maxEdges ?? 60;
943
+ const isTestDiffPath = (loc) => {
944
+ if (!loc)
945
+ return false;
946
+ const clean = loc.split(":")[0].replace(/\\/g, "/");
947
+ return (/\.(test|spec)\.[cm]?[jt]sx?$/i.test(clean) ||
948
+ /(^|\/)(__tests__|__mocks__)\//i.test(clean));
949
+ };
950
+ const countStatuses = (record) => {
951
+ const counts = { ADDED: 0, MODIFIED: 0, REMOVED: 0, LEXICAL_SHIFT: 0, UNCHANGED: 0 };
952
+ for (const entry of Object.values(record)) {
953
+ if (entry.status in counts) {
954
+ counts[entry.status]++;
955
+ }
956
+ }
957
+ return counts;
958
+ };
959
+ const resolvedGateStatus = delta.gateStatus ??
960
+ (delta.architecturalGate
961
+ ? delta.architecturalGate.gateStatus === "PASS" &&
962
+ (!delta.designSystemGate || delta.designSystemGate.gateStatus === "PASS")
963
+ ? "PASS"
964
+ : "WARN"
965
+ : undefined);
966
+ const baseEnvelope = {
967
+ ...(resolvedGateStatus ? { gateStatus: resolvedGateStatus } : {}),
968
+ baseStatus: delta.baseStatus ?? "FRESH",
969
+ ...(delta.baseRef ? { baseRef: delta.baseRef } : {}),
970
+ baseCommitSha: delta.baseCommitSha,
971
+ ...(delta.targetRef ? { targetRef: delta.targetRef } : {}),
972
+ targetCommitSha: delta.targetCommitSha,
973
+ headCommitSha: delta.headCommitSha,
974
+ ...(delta.isWorkingTreeSnapshot !== undefined
975
+ ? { isWorkingTreeSnapshot: delta.isWorkingTreeSnapshot }
976
+ : {}),
977
+ ...(delta.snapshotAt ? { snapshotAt: delta.snapshotAt } : {}),
978
+ baseExtractorVersion: delta.baseExtractorVersion,
979
+ targetExtractorVersion: delta.targetExtractorVersion,
980
+ ...(delta.architecturalGate ? { architecturalGate: delta.architecturalGate } : {}),
981
+ ...(delta.designSystemGate ? { designSystemGate: delta.designSystemGate } : {}),
982
+ summary: {
983
+ nodes: countStatuses(delta.nodes),
984
+ edges: countStatuses(delta.edges),
985
+ },
986
+ };
987
+ if (verbose) {
988
+ const filterEntries = (record) => {
989
+ const out = {};
990
+ for (const [id, entry] of Object.entries(record)) {
991
+ if (entry.status === "UNCHANGED" && !includeUnchanged)
992
+ continue;
993
+ if (entry.status === "LEXICAL_SHIFT" && !includeLexical)
994
+ continue;
995
+ out[id] = entry;
996
+ }
997
+ return out;
998
+ };
999
+ return {
1000
+ ...baseEnvelope,
1001
+ nodes: filterEntries(delta.nodes),
1002
+ edges: filterEntries(delta.edges),
1003
+ };
1004
+ }
1005
+ const nodeById = new Map();
1006
+ for (const [id, entry] of Object.entries(delta.nodes)) {
1007
+ const n = entry.target ?? entry.base;
1008
+ if (n)
1009
+ nodeById.set(id, n);
1010
+ }
1011
+ const primaryLoc = (ev) => {
1012
+ const item = Array.isArray(ev) ? ev[0] : ev;
1013
+ if (!item?.filePath)
1014
+ return undefined;
1015
+ return typeof item.lineNumber === "number"
1016
+ ? `${item.filePath}:${item.lineNumber}`
1017
+ : String(item.filePath);
1018
+ };
1019
+ const formatSig = (n) => {
1020
+ if (!n?.metadata)
1021
+ return undefined;
1022
+ const ins = Array.isArray(n.metadata.inputTypes) ? n.metadata.inputTypes.join(", ") : "";
1023
+ const out = typeof n.metadata.outputType === "string" ? n.metadata.outputType : "";
1024
+ if (!ins && !out)
1025
+ return undefined;
1026
+ return `(${ins}) => ${out || "void"}`;
1027
+ };
1028
+ const omittedNoise = {
1029
+ modifiedDeploymentUnits: 0,
1030
+ modifiedExternalPackageImports: 0,
1031
+ modifiedSameEndpointEdges: 0,
1032
+ externalPackageCallEdges: 0,
1033
+ builtinOrDynamicEdges: 0,
1034
+ testFileNodes: 0,
1035
+ testFileEdges: 0,
1036
+ truncatedNodes: 0,
1037
+ truncatedEdges: 0,
1038
+ };
1039
+ const candidateNodes = [];
1040
+ for (const [id, entry] of Object.entries(delta.nodes)) {
1041
+ if (entry.status === "UNCHANGED" && !includeUnchanged)
1042
+ continue;
1043
+ if (entry.status === "LEXICAL_SHIFT" && !includeLexical)
1044
+ continue;
1045
+ const primary = entry.target ?? entry.base;
1046
+ if (!primary)
1047
+ continue;
1048
+ if (entry.status === "MODIFIED") {
1049
+ if (primary.entityType === "DEPLOYMENT_UNIT" &&
1050
+ entry.base?.name === entry.target?.name &&
1051
+ entry.base?.parentBoundaryId === entry.target?.parentBoundaryId) {
1052
+ omittedNoise.modifiedDeploymentUnits++;
1053
+ continue;
1054
+ }
1055
+ if (primary.entityType === "EXTERNAL_PACKAGE" &&
1056
+ entry.base?.name === entry.target?.name) {
1057
+ omittedNoise.modifiedExternalPackageImports++;
1058
+ continue;
1059
+ }
1060
+ }
1061
+ const loc = primaryLoc(primary.evidence);
1062
+ if (isTestDiffPath(loc)) {
1063
+ omittedNoise.testFileNodes++;
1064
+ continue;
1065
+ }
1066
+ const baseSig = entry.status === "MODIFIED" ? formatSig(entry.base) : undefined;
1067
+ const targetSig = entry.status === "MODIFIED" ? formatSig(entry.target) : undefined;
1068
+ const sigChanged = entry.status === "MODIFIED" && baseSig !== targetSig && Boolean(baseSig || targetSig);
1069
+ const nodePriority = primary.type === "CONTRACT" && primary.entityType !== "EXPORTED_TYPE"
1070
+ ? 0
1071
+ : primary.type === "BOUNDARY"
1072
+ ? 1
1073
+ : primary.entityType === "EXPORTED_TYPE"
1074
+ ? 2
1075
+ : 3;
1076
+ candidateNodes.push([
1077
+ id,
1078
+ {
1079
+ status: entry.status,
1080
+ name: primary.name,
1081
+ type: primary.type,
1082
+ entityType: primary.entityType,
1083
+ ...(loc ? { file: loc } : {}),
1084
+ ...(sigChanged
1085
+ ? { signatureChange: { from: baseSig ?? "unspecified", to: targetSig ?? "unspecified" } }
1086
+ : {}),
1087
+ },
1088
+ nodePriority,
1089
+ ]);
1090
+ }
1091
+ candidateNodes.sort((a, b) => a[2] - b[2]);
1092
+ const keptNodes = candidateNodes.slice(0, maxNodes);
1093
+ if (candidateNodes.length > maxNodes) {
1094
+ omittedNoise.truncatedNodes = candidateNodes.length - maxNodes;
1095
+ }
1096
+ const compactNodes = {};
1097
+ for (const [id, payload] of keptNodes) {
1098
+ compactNodes[id] = payload;
1099
+ }
1100
+ const candidateEdges = [];
1101
+ for (const [id, entry] of Object.entries(delta.edges)) {
1102
+ if (entry.status === "UNCHANGED" && !includeUnchanged)
1103
+ continue;
1104
+ if (entry.status === "LEXICAL_SHIFT" && !includeLexical)
1105
+ continue;
1106
+ const primary = entry.target ?? entry.base;
1107
+ if (!primary)
1108
+ continue;
1109
+ if (entry.status === "MODIFIED" &&
1110
+ entry.base?.sourceId === entry.target?.sourceId &&
1111
+ entry.base?.targetId === entry.target?.targetId &&
1112
+ entry.base?.entityType === entry.target?.entityType) {
1113
+ omittedNoise.modifiedSameEndpointEdges++;
1114
+ continue;
1115
+ }
1116
+ const tgtNode = primary.targetId ? nodeById.get(primary.targetId) : undefined;
1117
+ if (tgtNode?.entityType === "EXTERNAL_PACKAGE" || tgtNode?.entityType === "NODE_BUILTIN") {
1118
+ omittedNoise.externalPackageCallEdges++;
1119
+ continue;
1120
+ }
1121
+ const resClass = primary.metadata?.resolutionClass;
1122
+ if (!primary.targetId &&
1123
+ (resClass === "BUILTIN_OR_PLATFORM" || resClass === "DYNAMIC_BOUNDARY")) {
1124
+ omittedNoise.builtinOrDynamicEdges++;
1125
+ continue;
1126
+ }
1127
+ const loc = primaryLoc(primary.evidence);
1128
+ if (isTestDiffPath(loc)) {
1129
+ omittedNoise.testFileEdges++;
1130
+ continue;
1131
+ }
1132
+ const srcNode = nodeById.get(primary.sourceId);
1133
+ const priority = !primary.targetId ? 0 : entry.status === "ADDED" || entry.status === "REMOVED" ? 1 : 2;
1134
+ candidateEdges.push([
1135
+ id,
1136
+ {
1137
+ status: entry.status,
1138
+ entityType: primary.entityType,
1139
+ name: primary.name,
1140
+ sourceId: primary.sourceId,
1141
+ source: srcNode?.name ?? primary.sourceId,
1142
+ ...(primary.targetId
1143
+ ? {
1144
+ targetId: primary.targetId,
1145
+ target: tgtNode?.name ?? primary.targetId,
1146
+ }
1147
+ : { unresolved: true }),
1148
+ ...(loc ? { file: loc } : {}),
1149
+ },
1150
+ priority,
1151
+ ]);
1152
+ }
1153
+ candidateEdges.sort((a, b) => a[2] - b[2]);
1154
+ const keptEdges = candidateEdges.slice(0, maxEdges);
1155
+ if (candidateEdges.length > maxEdges) {
1156
+ omittedNoise.truncatedEdges = candidateEdges.length - maxEdges;
1157
+ }
1158
+ const compactEdges = {};
1159
+ for (const [id, payload] of keptEdges) {
1160
+ compactEdges[id] = payload;
1161
+ }
1162
+ return {
1163
+ ...baseEnvelope,
1164
+ summary: {
1165
+ ...baseEnvelope.summary,
1166
+ omittedNoise,
1167
+ },
1168
+ nodes: compactNodes,
1169
+ edges: compactEdges,
1170
+ };
1171
+ }
1172
+ export function formatCompactMcpNodes(nodes, options) {
1173
+ if (options?.verbose)
1174
+ return nodes;
1175
+ let candidateNodes = nodes;
1176
+ if (typeof options?.limit === "number" &&
1177
+ options.limit > 0 &&
1178
+ nodes.length > options.limit) {
1179
+ const nodePriority = (n) => {
1180
+ if (n.type === "CONTRACT" && n.entityType !== "EXPORTED_TYPE")
1181
+ return 0;
1182
+ if (n.type === "BOUNDARY")
1183
+ return 1;
1184
+ if (n.entityType === "EXPORTED_TYPE")
1185
+ return 2;
1186
+ return 3;
1187
+ };
1188
+ candidateNodes = nodes
1189
+ .map((n, idx) => ({ n, idx, pri: nodePriority(n) }))
1190
+ .sort((a, b) => a.pri - b.pri || a.idx - b.idx)
1191
+ .slice(0, options.limit)
1192
+ .map((item) => item.n);
1193
+ }
1194
+ const compactEvidence = (ev) => {
1195
+ if (!ev)
1196
+ return {};
1197
+ if (Array.isArray(ev)) {
1198
+ const cleaned = ev.slice(0, 3).map((r) => ({
1199
+ filePath: r.filePath,
1200
+ ...(typeof r.lineNumber === "number" ? { lineNumber: r.lineNumber } : {}),
1201
+ }));
1202
+ return {
1203
+ evidence: cleaned,
1204
+ ...(ev.length > 3 ? { evidenceCount: ev.length } : {}),
1205
+ };
1206
+ }
1207
+ return {
1208
+ evidence: {
1209
+ filePath: ev.filePath,
1210
+ ...(typeof ev.lineNumber === "number" ? { lineNumber: ev.lineNumber } : {}),
1211
+ },
1212
+ };
1213
+ };
1214
+ const compactMetadata = (rawMeta) => {
1215
+ if (!rawMeta || typeof rawMeta !== "object")
1216
+ return undefined;
1217
+ const { analyzedFiles, bodyHash: _bodyHash, portValves, unresolvedOutgoing, ...rest } = rawMeta;
1218
+ const out = { ...rest };
1219
+ if (Array.isArray(analyzedFiles)) {
1220
+ out.analyzedFileCount = analyzedFiles.length;
1221
+ }
1222
+ if (Array.isArray(unresolvedOutgoing) && unresolvedOutgoing.length > 0) {
1223
+ out.unresolvedCount = unresolvedOutgoing.length;
1224
+ }
1225
+ if (portValves && typeof portValves === "object") {
1226
+ const inputs = Array.isArray(portValves.inputs)
1227
+ ? portValves.inputs.map((inp) => `${inp.name ?? "arg"}${inp.optional ? "?" : ""}: ${inp.type ?? "unknown"}`)
1228
+ : undefined;
1229
+ const rawOut = portValves.output?.type ?? portValves.outputType ?? rawMeta.outputType;
1230
+ const output = rawOut && portValves.output?.async ? `Promise<${rawOut}>` : rawOut;
1231
+ if ((inputs && inputs.length > 0) || output) {
1232
+ out.signature = {
1233
+ ...(inputs && inputs.length > 0 ? { inputs } : {}),
1234
+ ...(output ? { output } : {}),
1235
+ };
1236
+ }
1237
+ }
1238
+ return Object.keys(out).length > 0 ? out : undefined;
1239
+ };
1240
+ return candidateNodes.map((n) => {
1241
+ const evPart = compactEvidence(n.evidence);
1242
+ const metaPart = compactMetadata(n.metadata);
1243
+ return {
1244
+ id: n.id,
1245
+ name: n.name,
1246
+ type: n.type,
1247
+ entityType: n.entityType,
1248
+ ...(n.parentBoundaryId ? { parentBoundaryId: n.parentBoundaryId } : {}),
1249
+ ...evPart,
1250
+ ...(metaPart ? { metadata: metaPart } : {}),
1251
+ ...(n.overlays !== undefined ? { overlays: n.overlays } : {}),
1252
+ };
1253
+ });
1254
+ }
1255
+ export function formatCompactMcpEdges(edges, options) {
1256
+ if (options?.verbose)
1257
+ return edges;
1258
+ const includeBuiltins = Boolean(options?.includeBuiltins);
1259
+ return edges
1260
+ .filter((e) => {
1261
+ if (includeBuiltins || e.targetId)
1262
+ return true;
1263
+ return e.metadata?.resolutionClass !== "BUILTIN_OR_PLATFORM";
1264
+ })
1265
+ .map((e) => {
1266
+ const ev = e.evidence;
1267
+ const compactEv = Array.isArray(ev)
1268
+ ? ev.slice(0, 3).map((r) => ({
1269
+ filePath: r.filePath,
1270
+ ...(typeof r.lineNumber === "number" ? { lineNumber: r.lineNumber } : {}),
1271
+ }))
1272
+ : ev
1273
+ ? {
1274
+ filePath: ev.filePath,
1275
+ ...(typeof ev.lineNumber === "number"
1276
+ ? { lineNumber: ev.lineNumber }
1277
+ : {}),
1278
+ }
1279
+ : undefined;
1280
+ const meta = e.metadata;
1281
+ const compactMeta = meta && typeof meta === "object"
1282
+ ? Object.fromEntries(Object.entries({
1283
+ resolutionClass: meta.resolutionClass,
1284
+ targetSymbol: meta.targetSymbol,
1285
+ viaHelper: meta.viaHelper,
1286
+ }).filter(([, v]) => v !== undefined))
1287
+ : undefined;
1288
+ return {
1289
+ id: e.id,
1290
+ name: e.name,
1291
+ entityType: e.entityType,
1292
+ ...(e.confidence ? { confidence: e.confidence } : {}),
1293
+ sourceId: e.sourceId,
1294
+ ...(e.targetId ? { targetId: e.targetId } : { unresolved: true }),
1295
+ ...(compactEv ? { evidence: compactEv } : {}),
1296
+ ...(Array.isArray(ev) && ev.length > 3 ? { evidenceCount: ev.length } : {}),
1297
+ ...(compactMeta && Object.keys(compactMeta).length > 0
1298
+ ? { metadata: compactMeta }
1299
+ : {}),
1300
+ };
1301
+ });
1302
+ }
699
1303
  export async function runMcpServer(targetPath = process.cwd()) {
700
1304
  const initialRepo = resolveActiveMcpRepo(targetPath);
701
1305
  const repoLocalPluginsDir = resolve(initialRepo.repoPath, ".chomp", "plugins");
@@ -706,9 +1310,11 @@ export async function runMcpServer(targetPath = process.cwd()) {
706
1310
  name: "chomp-mcp-server",
707
1311
  version: "0.1.0",
708
1312
  });
709
- server.tool("chomp_get_nodes", "MANDATORY FIRST STEP (MAP-FIRST NAVIGATION): Retrieves structural nodes from the persisted Chomp graph. Pass `search_term` and/or `packageName` BEFORE reading any files to resolve the exact node IDs of target Services, Routes, Components, and Functions. Only follow up with `chomp_create_view` when the user is asking an architectural question, querying how a flow works, or explicitly requesting a visual highlight/walkthrough (do NOT invoke `chomp_create_view` on routine coding or implementation prompts). Files and directories are not graph nodes: each node's source file and line live in its evidence records, and BOUNDARY nodes are only DEPLOYMENT_UNIT, CLASS, NAMESPACE or INIT_BLOCK.", {
1313
+ server.tool("chomp_get_nodes", "MANDATORY FIRST STEP (MAP-FIRST NAVIGATION): Retrieves structural nodes from the persisted Chomp graph. Batch multiple queries into a SINGLE call using `search_terms: [...]` (or `file_paths: [...]` / `packageName`) BEFORE reading any files to resolve the exact node IDs of target Services, Routes, Components, and Functions in one round-trip. Only follow up with `chomp_create_view` when the user is asking an architectural question, querying how a flow works, or explicitly requesting a visual highlight/walkthrough (do NOT invoke `chomp_create_view` on routine coding or implementation prompts). Files and directories are not graph nodes: each node's source file and line live in its evidence records, and BOUNDARY nodes are only DEPLOYMENT_UNIT, CLASS, NAMESPACE or INIT_BLOCK.", {
710
1314
  search_term: z.string().optional().describe("Fast-path case-insensitive search term matching node name, id, humanLabel, domain, summary, or evidence filePath (use this to quickly resolve target node IDs)"),
711
1315
  searchTerm: z.string().optional().describe("Alias for search_term (camelCase)"),
1316
+ search_terms: z.array(z.string()).optional().describe("Batched list of case-insensitive search terms matched with OR semantics in a single call, ranked by match count and symbol exactness (preferred over multiple single-term calls)"),
1317
+ searchTerms: z.array(z.string()).optional().describe("Alias for search_terms (camelCase)"),
712
1318
  packageName: z.string().optional().describe("Optional filter by owning package / DEPLOYMENT_UNIT name (e.g., 'mcp', '@getchomp/mcp', 'core', 'web', 'cli', 'db')"),
713
1319
  package_name: z.string().optional().describe("Alias for packageName (snake_case)"),
714
1320
  type: z.string().optional().describe("Optional filter by node type (e.g., BOUNDARY, CONTRACT, OPEN_CONNECTOR)"),
@@ -719,6 +1325,8 @@ export async function runMcpServer(targetPath = process.cwd()) {
719
1325
  name: z.string().optional().describe("Optional case-insensitive substring filter on node name (e.g., 'visitContract', 'SQLiteStorage', '/api/layout')"),
720
1326
  file_path: z.string().optional().describe("Optional case-insensitive substring filter on the node's evidence filePath (e.g., 'contractVisitor.ts', 'packages/core')"),
721
1327
  filePath: z.string().optional().describe("Alias for file_path (camelCase)"),
1328
+ file_paths: z.array(z.string()).optional().describe("Batched list of case-insensitive evidence filePath substrings matched in a single call"),
1329
+ filePaths: z.array(z.string()).optional().describe("Alias for file_paths (camelCase)"),
722
1330
  include_overlays: z.boolean().optional().describe("When true, attaches entity_overlays records onto each returned node. Defaults to false unless layers/layer is specified, keeping structural queries compact."),
723
1331
  includeOverlays: z.boolean().optional().describe("Alias for include_overlays (camelCase)"),
724
1332
  layers: z.array(z.string()).optional().describe("Optional list of overlay layers to hydrate on returned nodes (e.g. ['L1_SEMANTIC', 'L1_DESIGN_SYSTEM']). Implicitly enables overlay hydration for those layers."),
@@ -730,7 +1338,15 @@ export async function runMcpServer(targetPath = process.cwd()) {
730
1338
  enrichmentStatus: z
731
1339
  .enum(["enriched", "unenriched", "stale"])
732
1340
  .optional()
733
- .describe("Alias for enrichment_status (camelCase)")
1341
+ .describe("Alias for enrichment_status (camelCase)"),
1342
+ limit: z
1343
+ .number()
1344
+ .optional()
1345
+ .describe("Maximum nodes to return (default: 50, or up to 80 for batched search_terms)"),
1346
+ verbose: z
1347
+ .boolean()
1348
+ .optional()
1349
+ .describe("When true, returns full raw AST snippets, analyzedFiles, and expanded portValves field trees (default: false)")
734
1350
  }, withMcpToolErrorBoundary(async (args) => {
735
1351
  const { repoPath, repoId, dbPath } = resolveActiveMcpRepo(targetPath);
736
1352
  if (!existsSync(dbPath)) {
@@ -744,15 +1360,18 @@ export async function runMcpServer(targetPath = process.cwd()) {
744
1360
  .filter(Boolean);
745
1361
  const includeOverlays = args.include_overlays ?? args.includeOverlays ?? (requestedLayers.length > 0);
746
1362
  const searchTerm = args.search_term ?? args.searchTerm;
1363
+ const searchTerms = args.search_terms ?? args.searchTerms;
1364
+ const filePaths = args.file_paths ?? args.filePaths;
1365
+ const hasAnySearch = Boolean(searchTerm) || Boolean(searchTerms && searchTerms.length > 0);
747
1366
  const enrichmentStatus = args.enrichment_status ?? args.enrichmentStatus;
748
1367
  const needsSemanticFilter = Boolean(enrichmentStatus);
749
- const overlayLayerFilter = requestedLayers.length > 0 && !searchTerm && !needsSemanticFilter
1368
+ const overlayLayerFilter = requestedLayers.length > 0 && !hasAnySearch && !needsSemanticFilter
750
1369
  ? requestedLayers
751
- : needsSemanticFilter && !includeOverlays && !searchTerm
1370
+ : needsSemanticFilter && !includeOverlays && !hasAnySearch
752
1371
  ? [SEMANTIC_OVERLAY_LAYER]
753
1372
  : undefined;
754
1373
  const graph = await loadActiveGraphWithShims(repoPath, dbPath, repoId);
755
- const overlays = includeOverlays || Boolean(searchTerm) || needsSemanticFilter
1374
+ const overlays = includeOverlays || hasAnySearch || needsSemanticFilter
756
1375
  ? await withStorage(dbPath, (storage) => storage.getEntityOverlays(repoId, overlayLayerFilter ? { layers: overlayLayerFilter } : undefined))
757
1376
  : [];
758
1377
  if (!graph) {
@@ -773,7 +1392,9 @@ export async function runMcpServer(targetPath = process.cwd()) {
773
1392
  parentBoundaryId: args.parent_boundary_id ?? args.parentBoundaryId,
774
1393
  name: args.name,
775
1394
  filePath: args.file_path ?? args.filePath,
1395
+ filePaths,
776
1396
  searchTerm,
1397
+ searchTerms,
777
1398
  packageName: args.packageName ?? args.package_name,
778
1399
  overlaysByEntityId,
779
1400
  });
@@ -794,8 +1415,14 @@ export async function runMcpServer(targetPath = process.cwd()) {
794
1415
  includeOverlays,
795
1416
  layers: requestedLayers,
796
1417
  });
1418
+ const batchFactor = Math.max(searchTerms?.length ?? 1, filePaths?.length ?? 1);
1419
+ const defaultLimit = batchFactor > 1 ? Math.min(80, Math.max(50, batchFactor * 15)) : 50;
1420
+ const responseNodes = formatCompactMcpNodes(filteredNodes, {
1421
+ verbose: args.verbose,
1422
+ limit: args.limit ?? defaultLimit,
1423
+ });
797
1424
  return {
798
- content: [{ type: "text", text: JSON.stringify(filteredNodes, null, 2) }]
1425
+ content: [{ type: "text", text: JSON.stringify(responseNodes, null, 2) }]
799
1426
  };
800
1427
  }));
801
1428
  server.tool("chomp_get_edges", "Use this tool to trace execution paths. If you need to know what a function calls, or what calls a function, pass the node ID here instead of using global text search. Edges originate from contracts, classes, public methods, or INIT_BLOCKs (top-level code run on module load) — never from files or DEPLOYMENT_UNITs — and calls into imported packages target `Package: X` OPEN_CONNECTORs.", {
@@ -807,7 +1434,10 @@ export async function runMcpServer(targetPath = process.cwd()) {
807
1434
  resolved_only: z.boolean().optional().describe("When true, returns only edges with a resolved targetId, suppressing unresolved LOW-confidence platform method calls"),
808
1435
  resolvedOnly: z.boolean().optional().describe("Alias for resolved_only (camelCase)"),
809
1436
  min_confidence: z.enum(["LOW", "MEDIUM", "HIGH"]).optional().describe("Optional minimum confidence threshold (LOW, MEDIUM, or HIGH). DETERMINISTIC edges always count as HIGH."),
810
- minConfidence: z.enum(["LOW", "MEDIUM", "HIGH"]).optional().describe("Alias for min_confidence (camelCase)")
1437
+ minConfidence: z.enum(["LOW", "MEDIUM", "HIGH"]).optional().describe("Alias for min_confidence (camelCase)"),
1438
+ include_builtins: z.boolean().optional().describe("When true, includes unresolved BUILTIN_OR_PLATFORM calls (e.g. Array.map, String.trim; default: false)"),
1439
+ includeBuiltins: z.boolean().optional().describe("Alias for include_builtins (camelCase)"),
1440
+ verbose: z.boolean().optional().describe("When true, returns full raw AST edge snippets and metadata (default: false)")
811
1441
  }, withMcpToolErrorBoundary(async (args) => {
812
1442
  const { repoPath, repoId, dbPath } = resolveActiveMcpRepo(targetPath);
813
1443
  if (!existsSync(dbPath)) {
@@ -851,11 +1481,15 @@ export async function runMcpServer(targetPath = process.cwd()) {
851
1481
  return edgeRank >= minRank;
852
1482
  });
853
1483
  }
1484
+ const responseEdges = formatCompactMcpEdges(filteredEdges, {
1485
+ verbose: args.verbose,
1486
+ includeBuiltins: args.include_builtins ?? args.includeBuiltins,
1487
+ });
854
1488
  return {
855
- content: [{ type: "text", text: JSON.stringify(filteredEdges, null, 2) }]
1489
+ content: [{ type: "text", text: JSON.stringify(responseEdges, null, 2) }]
856
1490
  };
857
1491
  }));
858
- server.tool("chomp_get_diff", "Compares two git branches/commits (baseRef -> targetRef) or a point-in-time working-tree snapshot against the saved base graph in the Chomp SQLite database. Returns a structural delta summary and the ADDED, REMOVED, and MODIFIED entities (excluding UNCHANGED and LEXICAL_SHIFT noise by default).", {
1492
+ server.tool("chomp_get_diff", "UNIFIED POST-EDIT VERIFICATION GATE & STRUCTURAL DIFF: Compares two git branches/commits (baseRef -> targetRef) or the live dirty working tree against the saved base graph in .chomp/graph.db. Returns a top-level `gateStatus` ('PASS' | 'WARN'), inline `architecturalGate` (newly introduced pass-through middlemen, duplicate flows/symbols, upward boundary violations, and cycles), inline `designSystemGate` (when a design-system baseline exists), and compact ADDED/REMOVED/MODIFIED production entities. Call this ONCE after editing; if `gateStatus` is 'PASS', stop immediately without calling separate boundary/redundancy/design-system diff tools.", {
859
1493
  baseRef: z.string().optional().describe("Optional base git branch or commit SHA (e.g. 'main')"),
860
1494
  base_ref: z.string().optional().describe("Alias for baseRef (snake_case)"),
861
1495
  targetRef: z.string().optional().describe("Optional target git branch, commit SHA, or 'WORKING_TREE' (defaults to 'WORKING_TREE' when uncommitted edits exist, or current branch vs main when clean)"),
@@ -863,7 +1497,8 @@ export async function runMcpServer(targetPath = process.cwd()) {
863
1497
  include_lexical_shift: z.boolean().optional().describe("When true, includes LEXICAL_SHIFT entries (line-number-only shifts) in nodes/edges"),
864
1498
  includeLexicalShift: z.boolean().optional().describe("Alias for include_lexical_shift (camelCase)"),
865
1499
  include_unchanged: z.boolean().optional().describe("When true, includes UNCHANGED entries in nodes/edges"),
866
- includeUnchanged: z.boolean().optional().describe("Alias for include_unchanged (camelCase)")
1500
+ includeUnchanged: z.boolean().optional().describe("Alias for include_unchanged (camelCase)"),
1501
+ verbose: z.boolean().optional().describe("When true, returns full raw base/target AST node and edge records instead of compact summaries (default: false)")
867
1502
  }, withMcpToolErrorBoundary(async (args) => {
868
1503
  const { repoPath, repoId, dbPath } = resolveActiveMcpRepo(targetPath);
869
1504
  const requestedBase = args.baseRef ?? args.base_ref;
@@ -885,6 +1520,13 @@ export async function runMcpServer(targetPath = process.cwd()) {
885
1520
  }
886
1521
  else {
887
1522
  delta = await computeGraphDeltaWithShims(repoPath, dbPath, repoId);
1523
+ if (delta.baseStatus === "STALE" && resolveMcpGitCommitSha(repoPath, "HEAD")) {
1524
+ delta = await computeGitRefDeltaWithShims(repoPath, {
1525
+ baseRef: "HEAD",
1526
+ targetRef: "WORKING_TREE",
1527
+ dbPath,
1528
+ });
1529
+ }
888
1530
  }
889
1531
  if (delta.baseStatus === "STALE") {
890
1532
  return {
@@ -909,48 +1551,11 @@ export async function runMcpServer(targetPath = process.cwd()) {
909
1551
  ],
910
1552
  };
911
1553
  }
912
- const includeLexical = Boolean(args?.include_lexical_shift ?? args?.includeLexicalShift);
913
- const includeUnchanged = Boolean(args?.include_unchanged ?? args?.includeUnchanged);
914
- const countStatuses = (record) => {
915
- const counts = { ADDED: 0, MODIFIED: 0, REMOVED: 0, LEXICAL_SHIFT: 0, UNCHANGED: 0 };
916
- for (const entry of Object.values(record)) {
917
- if (entry.status in counts) {
918
- counts[entry.status]++;
919
- }
920
- }
921
- return counts;
922
- };
923
- const filterEntries = (record) => {
924
- const out = {};
925
- for (const [id, entry] of Object.entries(record)) {
926
- if (entry.status === "UNCHANGED" && !includeUnchanged)
927
- continue;
928
- if (entry.status === "LEXICAL_SHIFT" && !includeLexical)
929
- continue;
930
- out[id] = entry;
931
- }
932
- return out;
933
- };
934
- const compactDelta = {
935
- baseStatus: delta.baseStatus ?? "FRESH",
936
- ...(delta.baseRef ? { baseRef: delta.baseRef } : {}),
937
- baseCommitSha: delta.baseCommitSha,
938
- ...(delta.targetRef ? { targetRef: delta.targetRef } : {}),
939
- targetCommitSha: delta.targetCommitSha,
940
- headCommitSha: delta.headCommitSha,
941
- ...(delta.isWorkingTreeSnapshot !== undefined
942
- ? { isWorkingTreeSnapshot: delta.isWorkingTreeSnapshot }
943
- : {}),
944
- ...(delta.snapshotAt ? { snapshotAt: delta.snapshotAt } : {}),
945
- baseExtractorVersion: delta.baseExtractorVersion,
946
- targetExtractorVersion: delta.targetExtractorVersion,
947
- summary: {
948
- nodes: countStatuses(delta.nodes),
949
- edges: countStatuses(delta.edges),
950
- },
951
- nodes: filterEntries(delta.nodes),
952
- edges: filterEntries(delta.edges),
953
- };
1554
+ const compactDelta = formatCompactMcpDiff(delta, {
1555
+ includeLexicalShift: Boolean(args?.include_lexical_shift ?? args?.includeLexicalShift),
1556
+ includeUnchanged: Boolean(args?.include_unchanged ?? args?.includeUnchanged),
1557
+ verbose: Boolean(args?.verbose),
1558
+ });
954
1559
  return {
955
1560
  content: [{ type: "text", text: JSON.stringify(compactDelta, null, 2) }]
956
1561
  };
@@ -1094,45 +1699,122 @@ export async function runMcpServer(targetPath = process.cwd()) {
1094
1699
  content: [{ type: "text", text: JSON.stringify(report, null, 2) }]
1095
1700
  };
1096
1701
  }));
1097
- server.tool("chomp_find_redundancies", "ARCHITECTURAL REDUNDANCY & PATTERN ALIGNMENT DETECTOR: Scans the structural graph for (1) 1-to-1 pass-through wrapper functions that add indirection without branching or side effects, (2) parallel/duplicate call flows where multiple nodes invoke the exact same downstream target set, (3) duplicate symbol names across files/packages, and (4) outlier routes/endpoints that deviate from their package's dominant canonical wiring pattern.", {
1702
+ server.tool("chomp_find_redundancies", "ARCHITECTURAL REDUNDANCY & PATTERN ALIGNMENT DETECTOR: Scans the structural graph (automatically evaluating the live dirty working tree when uncommitted edits exist) for (1) 1-to-1 pass-through wrapper functions that add indirection without branching or side effects, (2) parallel/duplicate call flows where multiple nodes invoke the exact same downstream target set, (3) duplicate symbol names across files/packages, and (4) outlier routes/endpoints that deviate from their package's dominant canonical wiring pattern. Pass `only_new: true` (`diff_only: true`) during post-edit verification to report only newly introduced redundancies.", {
1098
1703
  packageName: z.string().optional().describe("Optional filter by package / DEPLOYMENT_UNIT name (e.g., 'core', 'cli', 'mcp', 'web', 'db')"),
1099
1704
  package_name: z.string().optional().describe("Alias for packageName (snake_case)"),
1100
- limit: z.number().optional().describe("Maximum entries per redundancy category (default: 25)")
1705
+ limit: z.number().optional().describe("Maximum entries per redundancy category (default: 25)"),
1706
+ only_new: z.boolean().optional().describe("When true, compares against the saved baseline graph and returns only newly introduced redundancies (default: false)"),
1707
+ onlyNew: z.boolean().optional().describe("Alias for only_new (camelCase)"),
1708
+ diff_only: z.boolean().optional().describe("Alias for only_new"),
1709
+ diffOnly: z.boolean().optional().describe("Alias for only_new (camelCase)")
1101
1710
  }, withMcpToolErrorBoundary(async (args) => {
1102
1711
  const { repoPath, repoId, dbPath } = resolveActiveMcpRepo(targetPath);
1103
- if (!existsSync(dbPath)) {
1104
- throw new Error(`Chomp database not found at ${dbPath}. Please run 'chomp analyze .' first.`);
1105
- }
1106
- const graph = await loadActiveGraphWithShims(repoPath, dbPath, repoId);
1107
- if (!graph) {
1108
- throw new Error(`Graph data for repository '${repoId}' not found in the database. Please run 'chomp analyze .' first.`);
1712
+ const onlyNew = Boolean(args.only_new ?? args.onlyNew ?? args.diff_only ?? args.diffOnly);
1713
+ const pkgFilter = args.packageName ?? args.package_name;
1714
+ const { targetGraph, baseGraph, evaluatedSource } = await resolveLiveAndBaseGraphsForMcp(repoPath, dbPath, repoId, {
1715
+ needBaseGraph: onlyNew,
1716
+ });
1717
+ if (onlyNew && baseGraph) {
1718
+ const gate = computeArchitecturalDiffGate(baseGraph, targetGraph, {
1719
+ repoPath,
1720
+ packageName: pkgFilter,
1721
+ limit: args.limit,
1722
+ });
1723
+ const deltaReport = {
1724
+ evaluatedSource,
1725
+ diffOnly: true,
1726
+ gateStatus: gate.summary.newPassThroughWrapperCount +
1727
+ gate.summary.newDuplicateFlowCount +
1728
+ gate.summary.newDuplicateSymbolCount ===
1729
+ 0
1730
+ ? "PASS"
1731
+ : "WARN",
1732
+ summary: {
1733
+ passThroughMiddlemenCount: gate.summary.newPassThroughWrapperCount,
1734
+ duplicateStorySequenceGroups: gate.summary.newDuplicateFlowCount,
1735
+ duplicateSymbolCount: gate.summary.newDuplicateSymbolCount,
1736
+ patternAlignmentOpportunityCount: 0,
1737
+ },
1738
+ passThroughMiddlemen: gate.newPassThroughWrappers,
1739
+ duplicateStorySequences: gate.newDuplicateFlows,
1740
+ duplicateSymbols: gate.newDuplicateSymbols,
1741
+ patternAlignmentOpportunities: [],
1742
+ };
1743
+ return {
1744
+ content: [{ type: "text", text: JSON.stringify(deltaReport, null, 2) }],
1745
+ };
1109
1746
  }
1110
- const report = findGraphRedundancies(graph, {
1111
- packageName: args.packageName ?? args.package_name,
1747
+ const report = findGraphRedundancies(targetGraph, {
1748
+ packageName: pkgFilter,
1112
1749
  limit: args.limit,
1750
+ repoPath,
1113
1751
  });
1114
1752
  return {
1115
- content: [{ type: "text", text: JSON.stringify(report, null, 2) }]
1753
+ content: [
1754
+ {
1755
+ type: "text",
1756
+ text: JSON.stringify({ evaluatedSource, ...report }, null, 2),
1757
+ },
1758
+ ],
1116
1759
  };
1117
1760
  }));
1118
- server.tool("chomp_check_boundaries", "BOUNDARY & TOPOLOGICAL LAYER CHECKER: Analyzes cross-package dependency topology, assigns each DEPLOYMENT_UNIT to an architectural tier (ENTRY_APPLICATION, SERVICE_ORCHESTRATOR, INFRASTRUCTURE_ADAPTER, FOUNDATION_CORE, ISOLATED_PACKAGE), detects package-level and node-level circular dependencies and self-loops, flags boundary isolation or upward layer violations, and surfaces cross-package seam & missing-link diagnostics (`ISOLATED_DEPLOYMENT_UNITS`, `UNSTITCHED_PROTOCOL_SEAM`, `INIT_BLOCK_CONNECTOR_LEAK`).", {
1761
+ server.tool("chomp_check_boundaries", "BOUNDARY & TOPOLOGICAL LAYER CHECKER: Analyzes cross-package dependency topology (automatically evaluating the live dirty working tree when uncommitted edits exist), assigns each DEPLOYMENT_UNIT to an architectural tier (ENTRY_APPLICATION, SERVICE_ORCHESTRATOR, INFRASTRUCTURE_ADAPTER, FOUNDATION_CORE, ISOLATED_PACKAGE), detects package-level and node-level circular dependencies and self-loops, flags boundary isolation or upward layer violations, and surfaces cross-package seam & missing-link diagnostics (`ISOLATED_DEPLOYMENT_UNITS`, `UNSTITCHED_PROTOCOL_SEAM`, `INIT_BLOCK_CONNECTOR_LEAK`). Pass `only_new: true` (`diff_only: true`) during post-edit verification to report only newly introduced boundary violations or cycles.", {
1119
1762
  packageName: z.string().optional().describe("Optional filter by package / DEPLOYMENT_UNIT name (e.g., 'core', 'cli', 'mcp', 'web', 'db')"),
1120
- package_name: z.string().optional().describe("Alias for packageName (snake_case)")
1763
+ package_name: z.string().optional().describe("Alias for packageName (snake_case)"),
1764
+ only_new: z.boolean().optional().describe("When true, compares against the saved baseline graph and returns only newly introduced boundary violations and cycles (default: false)"),
1765
+ onlyNew: z.boolean().optional().describe("Alias for only_new (camelCase)"),
1766
+ diff_only: z.boolean().optional().describe("Alias for only_new"),
1767
+ diffOnly: z.boolean().optional().describe("Alias for only_new (camelCase)")
1121
1768
  }, withMcpToolErrorBoundary(async (args) => {
1122
1769
  const { repoPath, repoId, dbPath } = resolveActiveMcpRepo(targetPath);
1123
- if (!existsSync(dbPath)) {
1124
- throw new Error(`Chomp database not found at ${dbPath}. Please run 'chomp analyze .' first.`);
1125
- }
1126
- const graph = await loadActiveGraphWithShims(repoPath, dbPath, repoId);
1127
- if (!graph) {
1128
- throw new Error(`Graph data for repository '${repoId}' not found in the database. Please run 'chomp analyze .' first.`);
1770
+ const onlyNew = Boolean(args.only_new ?? args.onlyNew ?? args.diff_only ?? args.diffOnly);
1771
+ const pkgFilter = args.packageName ?? args.package_name;
1772
+ const { targetGraph, baseGraph, evaluatedSource } = await resolveLiveAndBaseGraphsForMcp(repoPath, dbPath, repoId, {
1773
+ needBaseGraph: onlyNew,
1774
+ });
1775
+ if (onlyNew && baseGraph) {
1776
+ const gate = computeArchitecturalDiffGate(baseGraph, targetGraph, {
1777
+ repoPath,
1778
+ packageName: pkgFilter,
1779
+ isTargetOnDisk: true,
1780
+ });
1781
+ const hardCount = gate.newBoundaryViolations.length;
1782
+ const advCount = gate.newBoundaryAdvisories?.length ?? 0;
1783
+ const deltaReport = {
1784
+ evaluatedSource,
1785
+ diffOnly: true,
1786
+ status: hardCount > 0 || gate.newCycles.packageCycles.length > 0
1787
+ ? "VIOLATION"
1788
+ : advCount > 0 || gate.newCycles.contractCycles.length > 0
1789
+ ? "ADVISORY"
1790
+ : "CLEAN",
1791
+ summary: {
1792
+ packageCycleCount: gate.newCycles.packageCycles.length,
1793
+ contractCycleCount: gate.newCycles.contractCycles.length,
1794
+ boundaryViolationCount: hardCount,
1795
+ boundaryAdvisoryCount: advCount,
1796
+ },
1797
+ circularDependencies: gate.newCycles,
1798
+ boundaryViolations: [
1799
+ ...gate.newBoundaryViolations,
1800
+ ...(gate.newBoundaryAdvisories ?? []),
1801
+ ],
1802
+ };
1803
+ return {
1804
+ content: [{ type: "text", text: JSON.stringify(deltaReport, null, 2) }],
1805
+ };
1129
1806
  }
1130
- const report = checkGraphBoundaries(graph, {
1131
- packageName: args.packageName ?? args.package_name,
1807
+ const report = checkGraphBoundaries(targetGraph, {
1808
+ packageName: pkgFilter,
1132
1809
  repoPath,
1133
1810
  });
1134
1811
  return {
1135
- content: [{ type: "text", text: JSON.stringify(report, null, 2) }]
1812
+ content: [
1813
+ {
1814
+ type: "text",
1815
+ text: JSON.stringify({ evaluatedSource, ...report }, null, 2),
1816
+ },
1817
+ ],
1136
1818
  };
1137
1819
  }));
1138
1820
  server.tool("chomp_get_blast_radius", "MANDATORY PRE-EDIT IMPACT ANALYSIS: Call this tool BEFORE modifying or refactoring a function, class, route, or package boundary to compute its upstream dependent callers, downstream dependencies, external OPEN_CONNECTOR side effects, affected entry points, affected packages, and input/output type schemas. Leave `create_view: false` (default) during coding/refactoring tasks; pass `create_view: true` only when answering user questions about impact or blast radius.", {
@@ -1276,7 +1958,7 @@ export async function runMcpServer(targetPath = process.cwd()) {
1276
1958
  include_schema: z
1277
1959
  .boolean()
1278
1960
  .optional()
1279
- .describe("When true (default), includes the full NodeMatcher / EdgeMatcher / EmitTemplate schema reference and config templates; pass false for compact paved-road lookups."),
1961
+ .describe("When true, includes the full NodeMatcher / EdgeMatcher / EmitTemplate schema reference and config templates (default: false; pass true only when authoring chomp.config.json#conventions)."),
1280
1962
  includeSchema: z.boolean().optional().describe("Alias for include_schema (camelCase)"),
1281
1963
  }, withMcpToolErrorBoundary(async (args) => {
1282
1964
  const { repoPath } = resolveActiveMcpRepo(targetPath);
@@ -1287,7 +1969,7 @@ export async function runMcpServer(targetPath = process.cwd()) {
1287
1969
  signalKind: args.signal_kind ?? args.signalKind,
1288
1970
  shapeKey: args.shape_key ?? args.shapeKey,
1289
1971
  searchTerm: args.search_term ?? args.searchTerm,
1290
- includeSchema: args.include_schema ?? args.includeSchema ?? true,
1972
+ includeSchema: args.include_schema ?? args.includeSchema ?? false,
1291
1973
  });
1292
1974
  return {
1293
1975
  content: [{ type: "text", text: JSON.stringify(report, null, 2) }],